Initial commit: EduBox V2 platform

This commit is contained in:
root
2026-06-06 19:55:41 +00:00
commit 0a73a70820
69 changed files with 5634 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
DATABASE_URL=postgresql://edubox:CHANGE_ME@postgres:5432/edubox
POSTGRES_PASSWORD=CHANGE_ME
NEXTAUTH_SECRET=CHANGE_ME
NEXTAUTH_URL=http://localhost
SUPERADMIN_EMAIL=admin@edudeploy.fr
SUPERADMIN_PASSWORD=CHANGE_ME
HEADSCALE_URL=http://headscale:8080
HEADSCALE_AUTH_KEY=CHANGE_ME
GITEA_URL=http://gitea:3000
GITEA_TOKEN=CHANGE_ME
+15
View File
@@ -0,0 +1,15 @@
.env
node_modules/
.next/
*.log
edubox-data/
dist/
coverage/
*.exe
*.dll
*.so
*.dylib
agent/edubox-agent
agent/edubox-agent.exe
agent/edubox-agent-mac
agent/ui/*.go.html
+8
View File
@@ -0,0 +1,8 @@
{
auto_https off
}
:80 {
reverse_proxy /gitea* gitea:3000
reverse_proxy server:3000
}
+37
View File
@@ -0,0 +1,37 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
)
type Activation struct {
Activated bool `json:"activated"`
StudentName string `json:"studentName,omitempty"`
Code string `json:"code,omitempty"`
}
func activationFile(dataDir string) string {
return filepath.Join(dataDir, "activation.json")
}
func loadActivation(dataDir string) (*Activation, error) {
f := activationFile(dataDir)
data, err := os.ReadFile(f)
if err != nil {
return nil, err
}
var a Activation
err = json.Unmarshal(data, &a)
return &a, err
}
func saveActivation(dataDir string, a *Activation) error {
f := activationFile(dataDir)
data, err := json.MarshalIndent(a, "", " ")
if err != nil {
return err
}
return os.WriteFile(f, data, 0644)
}
+47
View File
@@ -0,0 +1,47 @@
package main
import (
"os"
"os/exec"
"path/filepath"
)
func instanceDir(dataDir, instanceID string) string {
return filepath.Join(dataDir, "instances", instanceID)
}
func writeCompose(dataDir, instanceID, compose string) error {
dir := instanceDir(dataDir, instanceID)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
f := filepath.Join(dir, "docker-compose.yml")
return os.WriteFile(f, []byte(compose), 0644)
}
func dockerComposeUp(dataDir, instanceID string) error {
dir := instanceDir(dataDir, instanceID)
cmd := exec.Command("docker", "compose", "-f", filepath.Join(dir, "docker-compose.yml"), "up", "-d")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func dockerComposeDown(dataDir, instanceID string) error {
dir := instanceDir(dataDir, instanceID)
cmd := exec.Command("docker", "compose", "-f", filepath.Join(dir, "docker-compose.yml"), "down")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func dockerComposeRm(dataDir, instanceID string) error {
dir := instanceDir(dataDir, instanceID)
cmd := exec.Command("docker", "compose", "-f", filepath.Join(dir, "docker-compose.yml"), "down", "-v")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
return os.RemoveAll(dir)
}
+54
View File
@@ -0,0 +1,54 @@
module edubox-agent
go 1.26.4
require (
github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674
tailscale.com v1.100.0
)
require (
filippo.io/edwards25519 v1.2.0 // indirect
github.com/akutz/memconn v0.1.0 // indirect
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa // indirect
github.com/coder/websocket v1.8.12 // indirect
github.com/creachadair/msync v0.7.1 // indirect
github.com/dblohm7/wingoes v0.0.0-20240119213807-a09d6be7affa // indirect
github.com/fxamacker/cbor/v2 v2.9.0 // indirect
github.com/gaissmai/bart v0.26.1 // indirect
github.com/go-json-experiment/json v0.0.0-20260214004413-d219187c3433 // indirect
github.com/godbus/dbus/v5 v5.1.1-0.20230522191255-76236955d466 // indirect
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/google/btree v1.1.3 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/hdevalence/ed25519consensus v0.2.0 // indirect
github.com/huin/goupnp v1.3.0 // indirect
github.com/jsimonetti/rtnetlink v1.4.0 // indirect
github.com/klauspost/compress v1.18.5 // indirect
github.com/mdlayher/netlink v1.7.3-0.20250113171957-fbb4dce95f42 // indirect
github.com/mdlayher/socket v0.5.0 // indirect
github.com/mitchellh/go-ps v1.0.0 // indirect
github.com/pires/go-proxyproto v0.8.1 // indirect
github.com/safchain/ethtool v0.3.0 // indirect
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d // indirect
github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55 // indirect
github.com/tailscale/hujson v0.0.0-20260302212456-ecc657c15afd // indirect
github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc // indirect
github.com/tailscale/web-client-prebuilt v0.0.0-20250124233751-d4cd19a26976 // indirect
github.com/tailscale/wireguard-go v0.0.0-20260527010701-b48af7099cad // indirect
github.com/x448/float16 v0.8.4 // indirect
go4.org/mem v0.0.0-20240501181205-ae6ca9944745 // indirect
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect
golang.org/x/crypto v0.52.0 // indirect
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
golang.org/x/net v0.55.0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/term v0.43.0 // indirect
golang.org/x/text v0.37.0 // indirect
golang.org/x/time v0.12.0 // indirect
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect
golang.zx2c4.com/wireguard/windows v0.5.3 // indirect
gvisor.dev/gvisor v0.0.0-20260224225140-573d5e7127a8 // indirect
)
+233
View File
@@ -0,0 +1,233 @@
9fans.net/go v0.0.8-0.20250307142834-96bdba94b63f h1:1C7nZuxUMNz7eiQALRfiqNOm04+m3edWlRff/BYHf0Q=
9fans.net/go v0.0.8-0.20250307142834-96bdba94b63f/go.mod h1:hHyrZRryGqVdqrknjq5OWDLGCTJ2NeEvtrpR96mjraM=
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
filippo.io/mkcert v1.4.4 h1:8eVbbwfVlaqUM7OwuftKc2nuYOoTDQWqsoXmzoXZdbc=
filippo.io/mkcert v1.4.4/go.mod h1:VyvOchVuAye3BoUsPUOOofKygVwLV2KQMVFJNRq+1dA=
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/akutz/memconn v0.1.0 h1:NawI0TORU4hcOMsMr11g7vwlCdkYeLKXBcxWu2W/P8A=
github.com/akutz/memconn v0.1.0/go.mod h1:Jo8rI7m0NieZyLI5e2CDlRdRqRRB4S7Xp77ukDjH+Fw=
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI=
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
github.com/aws/aws-sdk-go-v2 v1.41.0 h1:tNvqh1s+v0vFYdA1xq0aOJH+Y5cRyZ5upu6roPgPKd4=
github.com/aws/aws-sdk-go-v2 v1.41.0/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0=
github.com/aws/aws-sdk-go-v2/config v1.29.5 h1:4lS2IB+wwkj5J43Tq/AwvnscBerBJtQQ6YS7puzCI1k=
github.com/aws/aws-sdk-go-v2/config v1.29.5/go.mod h1:SNzldMlDVbN6nWxM7XsUiNXPSa1LWlqiXtvh/1PrJGg=
github.com/aws/aws-sdk-go-v2/credentials v1.17.58 h1:/d7FUpAPU8Lf2KUdjniQvfNdlMID0Sd9pS23FJ3SS9Y=
github.com/aws/aws-sdk-go-v2/credentials v1.17.58/go.mod h1:aVYW33Ow10CyMQGFgC0ptMRIqJWvJ4nxZb0sUiuQT/A=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.27 h1:7lOW8NUwE9UZekS1DYoiPdVAqZ6A+LheHWb+mHbNOq8=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.27/go.mod h1:w1BASFIPOPUae7AgaH4SbjNbfdkxuggLyGfNFTn8ITY=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16 h1:rgGwPzb82iBYSvHMHXc8h9mRoOUBZIGFgKb9qniaZZc=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.16/go.mod h1:L/UxsGeKpGoIj6DxfhOWHWQ/kGKcd4I1VncE4++IyKA=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16 h1:1jtGzuV7c82xnqOVfx2F0xmJcOw5374L7N6juGW6x6U=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.16/go.mod h1:M2E5OQf+XLe+SZGmmpaI2yy+J326aFf6/+54PoxSANc=
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.2 h1:Pg9URiobXy85kgFev3og2CuOZ8JZUBENF+dcgWBaYNk=
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.2/go.mod h1:FbtygfRFze9usAadmnGJNc8KsP346kEe+y2/oyhGAGc=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.16 h1:oHjJHeUy0ImIV0bsrX0X91GkV5nJAyv1l1CC9lnO0TI=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.16/go.mod h1:iRSNGgOYmiYwSCXxXaKb9HfOEj40+oTKn8pTxMlYkRM=
github.com/aws/aws-sdk-go-v2/service/ssm v1.44.7 h1:a8HvP/+ew3tKwSXqL3BCSjiuicr+XTU2eFYeogV9GJE=
github.com/aws/aws-sdk-go-v2/service/ssm v1.44.7/go.mod h1:Q7XIWsMo0JcMpI/6TGD6XXcXcV1DbTj6e9BKNntIMIM=
github.com/aws/aws-sdk-go-v2/service/sso v1.24.14 h1:c5WJ3iHz7rLIgArznb3JCSQT3uUMiz9DLZhIX+1G8ok=
github.com/aws/aws-sdk-go-v2/service/sso v1.24.14/go.mod h1:+JJQTxB6N4niArC14YNtxcQtwEqzS3o9Z32n7q33Rfs=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.13 h1:f1L/JtUkVODD+k1+IiSJUUv8A++2qVr+Xvb3xWXETMU=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.28.13/go.mod h1:tvqlFoja8/s0o+UruA1Nrezo/df0PzdunMDDurUfg6U=
github.com/aws/aws-sdk-go-v2/service/sts v1.41.5 h1:SciGFVNZ4mHdm7gpD1dgZYnCuVdX1s+lFTg4+4DOy70=
github.com/aws/aws-sdk-go-v2/service/sts v1.41.5/go.mod h1:iW40X4QBmUxdP+fZNOpfmkdMZqsovezbAeO+Ubiv2pk=
github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk=
github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=
github.com/axiomhq/hyperloglog v0.0.0-20240319100328-84253e514e02 h1:bXAPYSbdYbS5VTy92NIUbeDI1qyggi+JYh5op9IFlcQ=
github.com/axiomhq/hyperloglog v0.0.0-20240319100328-84253e514e02/go.mod h1:k08r+Yj1PRAmuayFiRK6MYuR5Ve4IuZtTfxErMIh0+c=
github.com/cilium/ebpf v0.16.0 h1:+BiEnHL6Z7lXnlGUsXQPPAE7+kenAd4ES8MQ5min0Ok=
github.com/cilium/ebpf v0.16.0/go.mod h1:L7u2Blt2jMM/vLAVgjxluxtBKlz3/GWjB0dMOEngfwE=
github.com/coder/websocket v1.8.12 h1:5bUXkEPPIbewrnkU8LTCLVaxi4N4J8ahufH2vlo4NAo=
github.com/coder/websocket v1.8.12/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
github.com/coreos/go-iptables v0.7.1-0.20240112124308-65c67c9f46e6 h1:8h5+bWd7R6AYUslN6c6iuZWTKsKxUFDlpnmilO6R2n0=
github.com/coreos/go-iptables v0.7.1-0.20240112124308-65c67c9f46e6/go.mod h1:Qe8Bv2Xik5FyTXwgIbLAnv2sWSBmvWdFETJConOQ//Q=
github.com/creachadair/mds v0.25.9 h1:080Hr8laN2h+l3NeVCGMBpXtIPnl9mz8e4HLraGPqtA=
github.com/creachadair/mds v0.25.9/go.mod h1:4hatI3hRM+qhzuAmqPRFvaBM8mONkS7nsLxkcuTYUIs=
github.com/creachadair/msync v0.7.1 h1:SeZmuEBXQPe5GqV/C94ER7QIZPwtvFbeQiykzt/7uho=
github.com/creachadair/msync v0.7.1/go.mod h1:8CcFlLsSujfHE5wWm19uUBLHIPDAUr6LXDwneVMO008=
github.com/creachadair/taskgroup v0.13.2 h1:3KyqakBuFsm3KkXi/9XIb0QcA8tEzLHLgaoidf0MdVc=
github.com/creachadair/taskgroup v0.13.2/go.mod h1:i3V1Zx7H8RjwljUEeUWYT30Lmb9poewSb2XI1yTwD0g=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/dblohm7/wingoes v0.0.0-20240119213807-a09d6be7affa h1:h8TfIT1xc8FWbwwpmHn1J5i43Y0uZP97GqasGCzSRJk=
github.com/dblohm7/wingoes v0.0.0-20240119213807-a09d6be7affa/go.mod h1:Nx87SkVqTKd8UtT+xu7sM/l+LgXs6c0aHrlKusR+2EQ=
github.com/dgryski/go-metro v0.0.0-20180109044635-280f6062b5bc h1:8WFBn63wegobsYAX0YjD+8suexZDga5CctH4CCTx2+8=
github.com/dgryski/go-metro v0.0.0-20180109044635-280f6062b5bc/go.mod h1:c9O8+fpSOX1DM8cPNSkX/qsBWdkD4yd2dpciOWQjpBw=
github.com/digitalocean/go-smbios v0.0.0-20180907143718-390a4f403a8e h1:vUmf0yezR0y7jJ5pceLHthLaYf4bA5T14B6q39S4q2Q=
github.com/digitalocean/go-smbios v0.0.0-20180907143718-390a4f403a8e/go.mod h1:YTIHhz/QFSYnu/EhlF2SpU2Uk+32abacUYA5ZPljz1A=
github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c=
github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM=
github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
github.com/gaissmai/bart v0.26.1 h1:+w4rnLGNlA2GDVn382Tfe3jOsK5vOr5n4KmigJ9lbTo=
github.com/gaissmai/bart v0.26.1/go.mod h1:GREWQfTLRWz/c5FTOsIw+KkscuFkIV5t8Rp7Nd1Td5c=
github.com/github/fakeca v0.1.0 h1:Km/MVOFvclqxPM9dZBC4+QE564nU4gz4iZ0D9pMw28I=
github.com/github/fakeca v0.1.0/go.mod h1:+bormgoGMMuamOscx7N91aOuUST7wdaJ2rNjeohylyo=
github.com/go-json-experiment/json v0.0.0-20260214004413-d219187c3433 h1:vymEbVwYFP/L05h5TKQxvkXoKxNvTpjxYKdF1Nlwuao=
github.com/go-json-experiment/json v0.0.0-20260214004413-d219187c3433/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/go4org/hashtriemap v0.0.0-20251130024219-545ba229f689 h1:0psnKZ+N2IP43/SZC8SKx6OpFJwLmQb9m9QyV9BC2f8=
github.com/go4org/hashtriemap v0.0.0-20251130024219-545ba229f689/go.mod h1:OGmRfY/9QEK2P5zCRtmqfbCF283xPkU2dvVA4MvbvpI=
github.com/go4org/plan9netshell v0.0.0-20250324183649-788daa080737 h1:cf60tHxREO3g1nroKr2osU3JWZsJzkfi7rEg+oAB0Lo=
github.com/go4org/plan9netshell v0.0.0-20250324183649-788daa080737/go.mod h1:MIS0jDzbU/vuM9MC4YnBITCv+RYuTRq8dJzmCrFsK9g=
github.com/godbus/dbus/v5 v5.1.1-0.20230522191255-76236955d466 h1:sQspH8M4niEijh3PFscJRLDnkL547IeP7kpPe3uUhEg=
github.com/godbus/dbus/v5 v5.1.1-0.20230522191255-76236955d466/go.mod h1:ZiQxhyQ+bbbfxUKVvjfO498oPYvtYhZzycal3G/NHmU=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=
github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=
github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/go-tpm v0.9.4 h1:awZRf9FwOeTunQmHoDYSHJps3ie6f1UlhS1fOdPEt1I=
github.com/google/go-tpm v0.9.4/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
github.com/google/nftables v0.2.1-0.20240414091927-5e242ec57806 h1:wG8RYIyctLhdFk6Vl1yPGtSRtwGpVkWyZww1OCil2MI=
github.com/google/nftables v0.2.1-0.20240414091927-5e242ec57806/go.mod h1:Beg6V6zZ3oEn0JuiUQ4wqwuyqqzasOltcoXPtgLbFp4=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo=
github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA=
github.com/hdevalence/ed25519consensus v0.2.0 h1:37ICyZqdyj0lAZ8P4D1d1id3HqbbG1N3iBb1Tb4rdcU=
github.com/hdevalence/ed25519consensus v0.2.0/go.mod h1:w3BHWjwJbFU29IRHL1Iqkw3sus+7FctEyM4RqDxYNzo=
github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc=
github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8=
github.com/illarion/gonotify/v3 v3.0.2 h1:O7S6vcopHexutmpObkeWsnzMJt/r1hONIEogeVNmJMk=
github.com/illarion/gonotify/v3 v3.0.2/go.mod h1:HWGPdPe817GfvY3w7cx6zkbzNZfi3QjcBm/wgVvEL1U=
github.com/insomniacslk/dhcp v0.0.0-20231206064809-8c70d406f6d2 h1:9K06NfxkBh25x56yVhWWlKFE8YpicaSfHwoV8SFbueA=
github.com/insomniacslk/dhcp v0.0.0-20231206064809-8c70d406f6d2/go.mod h1:3A9PQ1cunSDF/1rbTq99Ts4pVnycWg+vlPkfeD2NLFI=
github.com/jellydator/ttlcache/v3 v3.1.0 h1:0gPFG0IHHP6xyUyXq+JaD8fwkDCqgqwohXNJBcYE71g=
github.com/jellydator/ttlcache/v3 v3.1.0/go.mod h1:hi7MGFdMAwZna5n2tuvh63DvFLzVKySzCVW6+0gA2n4=
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
github.com/jsimonetti/rtnetlink v1.4.0 h1:Z1BF0fRgcETPEa0Kt0MRk3yV5+kF1FWTni6KUFKrq2I=
github.com/jsimonetti/rtnetlink v1.4.0/go.mod h1:5W1jDvWdnthFJ7fxYX1GMK07BUpI4oskfOqvPteYS6E=
github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE=
github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/kortschak/wol v0.0.0-20200729010619-da482cc4850a h1:+RR6SqnTkDLWyICxS1xpjCi/3dhyV+TgZwA6Ww3KncQ=
github.com/kortschak/wol v0.0.0-20200729010619-da482cc4850a/go.mod h1:YTtCCM3ryyfiu4F7t8HQ1mxvp1UBdWM2r6Xa+nGWvDk=
github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8=
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mdlayher/genetlink v1.3.2 h1:KdrNKe+CTu+IbZnm/GVUMXSqBBLqcGpRDa0xkQy56gw=
github.com/mdlayher/genetlink v1.3.2/go.mod h1:tcC3pkCrPUGIKKsCsp0B3AdaaKuHtaxoJRz3cc+528o=
github.com/mdlayher/netlink v1.7.3-0.20250113171957-fbb4dce95f42 h1:A1Cq6Ysb0GM0tpKMbdCXCIfBclan4oHk1Jb+Hrejirg=
github.com/mdlayher/netlink v1.7.3-0.20250113171957-fbb4dce95f42/go.mod h1:BB4YCPDOzfy7FniQ/lxuYQ3dgmM2cZumHbK8RpTjN2o=
github.com/mdlayher/sdnotify v1.0.0 h1:Ma9XeLVN/l0qpyx1tNeMSeTjCPH6NtuD6/N9XdTlQ3c=
github.com/mdlayher/sdnotify v1.0.0/go.mod h1:HQUmpM4XgYkhDLtd+Uad8ZFK1T9D5+pNxnXQjCeJlGE=
github.com/mdlayher/socket v0.5.0 h1:ilICZmJcQz70vrWVes1MFera4jGiWNocSkykwwoy3XI=
github.com/mdlayher/socket v0.5.0/go.mod h1:WkcBFfvyG8QENs5+hfQPl1X6Jpd2yeLIYgrGFmJiJxI=
github.com/miekg/dns v1.1.58 h1:ca2Hdkz+cDg/7eNF6V56jjzuZ4aCAE+DbVkILdQWG/4=
github.com/miekg/dns v1.1.58/go.mod h1:Ypv+3b/KadlvW9vJfXOTf300O4UqaHFzFCuHz+rPkBY=
github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc=
github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
github.com/pierrec/lz4/v4 v4.1.25 h1:kocOqRffaIbU5djlIBr7Wh+cx82C0vtFb0fOurZHqD0=
github.com/pierrec/lz4/v4 v4.1.25/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
github.com/pires/go-proxyproto v0.8.1 h1:9KEixbdJfhrbtjpz/ZwCdWDD2Xem0NZ38qMYaASJgp0=
github.com/pires/go-proxyproto v0.8.1/go.mod h1:ZKAAyp3cgy5Y5Mo4n9AlScrkCZwUy0g3Jf+slqQVcuU=
github.com/pkg/sftp v1.13.6 h1:JFZT4XbOU7l77xGSpOdW+pwIMqP044IyjXX6FGyEKFo=
github.com/pkg/sftp v1.13.6/go.mod h1:tz1ryNURKu77RL+GuCzmoJYxQczL3wLNNpPWagdg4Qk=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.65.0 h1:QDwzd+G1twt//Kwj/Ww6E9FQq1iVMmODnILtW1t2VzE=
github.com/prometheus/common v0.65.0/go.mod h1:0gZns+BLRQ3V6NdaerOhMbwwRbNh9hkGINtQAsP5GS8=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/safchain/ethtool v0.3.0 h1:gimQJpsI6sc1yIqP/y8GYgiXn/NjgvpM0RNoWLVVmP0=
github.com/safchain/ethtool v0.3.0/go.mod h1:SA9BwrgyAqNo7M+uaL6IYbxpm5wk3L7Mm6ocLW+CJUs=
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d h1:JcGKBZAL7ePLwOhUdN8qGQZlP5GueEiIZwY7R62pejE=
github.com/tailscale/certstore v0.1.1-0.20260409135935-3638fb84b77d/go.mod h1:XrBNfAFN+pwoWuksbFS9Ccxnopa15zJGgXRFN90l3K4=
github.com/tailscale/gliderssh v0.3.4-0.20260330083525-c1389c70ff89 h1:glgVc1ZYMjwN1Q/ITWeuSQyl029uayagaR2sjsifehc=
github.com/tailscale/gliderssh v0.3.4-0.20260330083525-c1389c70ff89/go.mod h1:wn16Km1EZOX4UEAyaZa3dBwfFGOJ7neck40NcwosJUw=
github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55 h1:Gzfnfk2TWrk8Jj4P4c1a3CtQyMaTVCznlkLZI++hok4=
github.com/tailscale/go-winio v0.0.0-20231025203758-c4f33415bf55/go.mod h1:4k4QO+dQ3R5FofL+SanAUZe+/QfeK0+OIuwDIRu2vSg=
github.com/tailscale/golang-x-crypto v0.0.0-20250404221719-a5573b049869 h1:SRL6irQkKGQKKLzvQP/ke/2ZuB7Py5+XuqtOgSj+iMM=
github.com/tailscale/golang-x-crypto v0.0.0-20250404221719-a5573b049869/go.mod h1:ikbF+YT089eInTp9f2vmvy4+ZVnW5hzX1q2WknxSprQ=
github.com/tailscale/hujson v0.0.0-20260302212456-ecc657c15afd h1:Rf9uhF1+VJ7ZHqxrG8pJ6YacmHvVCmByDmGbAWCc/gA=
github.com/tailscale/hujson v0.0.0-20260302212456-ecc657c15afd/go.mod h1:EbW0wDK/qEUYI0A5bqq0C2kF8JTQwWONmGDBbzsxxHo=
github.com/tailscale/netlink v1.1.1-0.20240822203006-4d49adab4de7 h1:uFsXVBE9Qr4ZoF094vE6iYTLDl0qCiKzYXlL6UeWObU=
github.com/tailscale/netlink v1.1.1-0.20240822203006-4d49adab4de7/go.mod h1:NzVQi3Mleb+qzq8VmcWpSkcSYxXIg0DkI6XDzpVkhJ0=
github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc h1:24heQPtnFR+yfntqhI3oAu9i27nEojcQ4NuBQOo5ZFA=
github.com/tailscale/peercred v0.0.0-20250107143737-35a0c7bd7edc/go.mod h1:f93CXfllFsO9ZQVq+Zocb1Gp4G5Fz0b0rXHLOzt/Djc=
github.com/tailscale/web-client-prebuilt v0.0.0-20250124233751-d4cd19a26976 h1:UBPHPtv8+nEAy2PD8RyAhOYvau1ek0HDJqLS/Pysi14=
github.com/tailscale/web-client-prebuilt v0.0.0-20250124233751-d4cd19a26976/go.mod h1:agQPE6y6ldqCOui2gkIh7ZMztTkIQKH049tv8siLuNQ=
github.com/tailscale/wf v0.0.0-20240214030419-6fbb0a674ee6 h1:l10Gi6w9jxvinoiq15g8OToDdASBni4CyJOdHY1Hr8M=
github.com/tailscale/wf v0.0.0-20240214030419-6fbb0a674ee6/go.mod h1:ZXRML051h7o4OcI0d3AaILDIad/Xw0IkXaHM17dic1Y=
github.com/tailscale/wireguard-go v0.0.0-20260527010701-b48af7099cad h1:Ky26FR5yZ5IKEB0xtm5A8xSTb06ImY7kxBFrvgOmJSg=
github.com/tailscale/wireguard-go v0.0.0-20260527010701-b48af7099cad/go.mod h1:6SerzcvHWQchKO2BfNdmquA77CHSECZuFl+D9fp4RnI=
github.com/tailscale/xnet v0.0.0-20240729143630-8497ac4dab2e h1:zOGKqN5D5hHhiYUp091JqK7DPCqSARyUfduhGUY8Bek=
github.com/tailscale/xnet v0.0.0-20240729143630-8497ac4dab2e/go.mod h1:orPd6JZXXRyuDusYilywte7k094d7dycXXU5YnWsrwg=
github.com/tc-hib/winres v0.2.1 h1:YDE0FiP0VmtRaDn7+aaChp1KiF4owBiJa5l964l5ujA=
github.com/tc-hib/winres v0.2.1/go.mod h1:C/JaNhH3KBvhNKVbvdlDWkbMDO9H4fKKDaN7/07SSuk=
github.com/u-root/u-root v0.14.0 h1:Ka4T10EEML7dQ5XDvO9c3MBN8z4nuSnGjcd1jmU2ivg=
github.com/u-root/u-root v0.14.0/go.mod h1:hAyZorapJe4qzbLWlAkmSVCJGbfoU9Pu4jpJ1WMluqE=
github.com/u-root/uio v0.0.0-20240224005618-d2acac8f3701 h1:pyC9PaHYZFgEKFdlp3G8RaCKgVpHZnecvArXvPXcFkM=
github.com/u-root/uio v0.0.0-20240224005618-d2acac8f3701/go.mod h1:P3a5rG4X7tI17Nn3aOIAYr5HbIMukwXG0urG0WuL8OA=
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
go4.org/mem v0.0.0-20240501181205-ae6ca9944745 h1:Tl++JLUCe4sxGu8cTpDzRLd3tN7US4hOxG5YpKCzkek=
go4.org/mem v0.0.0-20240501181205-ae6ca9944745/go.mod h1:reUoABIJ9ikfM5sgtSF3Wushcza7+WeD01VB9Lirh3g=
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBseWJUpBw5I82+2U4M=
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
golang.org/x/exp/typeparams v0.0.0-20240314144324-c7f7c6466f7f h1:phY1HzDcf18Aq9A8KkmRtY9WvOFIxN8wgfvy6Zm1DV8=
golang.org/x/exp/typeparams v0.0.0-20240314144324-c7f7c6466f7f/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=
golang.org/x/image v0.41.0 h1:8wS72eGJMJaBxK6okTzd4WaXumUlTVlb753MlsSvTCo=
golang.org/x/image v0.41.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20220817070843-5a390386f1f2/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg=
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
golang.zx2c4.com/wireguard/windows v0.5.3 h1:On6j2Rpn3OEMXqBq00QEDC7bWSZrPIHKIus8eIuExIE=
golang.zx2c4.com/wireguard/windows v0.5.3/go.mod h1:9TEe8TJmtwyQebdFwAkEWOPr3prrtqm+REGFifP60hI=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gvisor.dev/gvisor v0.0.0-20260224225140-573d5e7127a8 h1:Zy8IV/+FMLxy6j6p87vk/vQGKcdnbprwjTxc8UiUtsA=
gvisor.dev/gvisor v0.0.0-20260224225140-573d5e7127a8/go.mod h1:QkHjoMIBaYtpVufgwv3keYAbln78mBoCuShZrPrer1Q=
honnef.co/go/tools v0.7.0 h1:w6WUp1VbkqPEgLz4rkBzH/CSU6HkoqNLp6GstyTx3lU=
honnef.co/go/tools v0.7.0/go.mod h1:pm29oPxeP3P82ISxZDgIYeOaf9ta6Pi0EWvCFoLG2vc=
howett.net/plist v1.0.0 h1:7CrbWYbPPO/PyNy38b2EB/+gYbjCe2DXBxgtOOZbSQM=
howett.net/plist v1.0.0/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=
software.sslmate.com/src/go-pkcs12 v0.4.0 h1:H2g08FrTvSFKUj+D309j1DPfk5APnIdAQAB8aEykJ5k=
software.sslmate.com/src/go-pkcs12 v0.4.0/go.mod h1:Qiz0EyvDRJjjxGyUQa2cCNZn/wMyzrRJ/qcDXOQazLI=
tailscale.com v1.100.0 h1:nm/M/dEaW9RaRsGUjW2HsSDpsZ60Jwd9k4gNW9tTFiE=
tailscale.com v1.100.0/go.mod h1:DQ9YBy85DpNlSyeU2XRIWzbAu3RsGp/frv+Khg57meE=
+52
View File
@@ -0,0 +1,52 @@
package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
)
var (
serverAddr = flag.String("server", "ws://localhost:3001", "Adresse WebSocket du serveur")
nodeID = flag.String("node-id", defaultNodeID(), "ID du nœud (défaut: hostname)")
dataDir = flag.String("data-dir", "./edubox-data", "Répertoire de données")
uiEnabled = flag.Bool("ui", true, "Activer l'interface locale HTMX")
)
func defaultNodeID() string {
h, err := os.Hostname()
if err != nil {
return "unknown"
}
return h
}
func main() {
flag.Parse()
dd := *dataDir
if !filepath.IsAbs(dd) {
ex, err := os.Executable()
if err == nil {
dd = filepath.Join(filepath.Dir(ex), dd)
} else {
wd, _ := os.Getwd()
dd = filepath.Join(wd, dd)
}
}
*dataDir = dd
if err := os.MkdirAll(*dataDir, 0755); err != nil {
log.Fatalf("Cannot create data-dir: %v", err)
}
fmt.Printf("EduBox Agent - node: %s - data-dir: %s\n", *nodeID, *dataDir)
if *uiEnabled {
go startUI(*dataDir, *nodeID, *serverAddr)
}
startWebSocket(*serverAddr, *nodeID, *dataDir)
}
+28
View File
@@ -0,0 +1,28 @@
package main
import (
"fmt"
"log"
"net"
"tailscale.com/tsnet"
)
func startTailscale(dataDir string, nodeID string) (net.Listener, error) {
s := &tsnet.Server{
Hostname: nodeID,
Dir: dataDir,
Logf: log.Printf,
}
if err := s.Start(); err != nil {
return nil, fmt.Errorf("tailscale start: %w", err)
}
ln, err := s.Listen("tcp", ":0")
if err != nil {
return nil, fmt.Errorf("tailscale listen: %w", err)
}
return ln, nil
}
+104
View File
@@ -0,0 +1,104 @@
package main
import (
_ "embed"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"github.com/gorilla/websocket"
)
//go:embed ui/index.html
var uiHTML string
var upgrader = websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}
func startUI(dataDir, nodeID, serverAddr string) {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, uiHTML)
})
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("UI WS upgrade error: %v", err)
return
}
defer conn.Close()
for {
var msg map[string]interface{}
if err := conn.ReadJSON(&msg); err != nil {
break
}
action, _ := msg["action"].(string)
switch action {
case "check":
act, err := loadActivation(dataDir)
if err == nil && act.Activated {
conn.WriteJSON(map[string]interface{}{"action": "activated", "studentName": act.StudentName})
} else {
conn.WriteJSON(map[string]interface{}{"action": "not_activated"})
}
case "activate":
code, _ := msg["code"].(string)
// Forward to server WS
go func() {
forwardActivation(serverAddr, nodeID, code, conn)
}()
case "instances":
listInstances(dataDir, conn)
}
}
})
port := "7070"
log.Printf("UI starting on http://localhost:%s", port)
if err := http.ListenAndServe("127.0.0.1:"+port, nil); err != nil {
log.Fatalf("UI server error: %v", err)
}
}
func forwardActivation(serverAddr, nodeID, code string, uiConn *websocket.Conn) {
conn, _, err := websocket.DefaultDialer.Dial(serverAddr, nil)
if err != nil {
uiConn.WriteJSON(map[string]interface{}{"action": "activation_failed", "error": err.Error()})
return
}
defer conn.Close()
conn.WriteJSON(map[string]interface{}{"action": "register", "nodeId": nodeID})
conn.WriteJSON(map[string]interface{}{"action": "activate", "code": code, "nodeId": nodeID})
for {
var msg map[string]interface{}
if err := conn.ReadJSON(&msg); err != nil {
break
}
action, _ := msg["action"].(string)
if action == "activated" || action == "activation_failed" {
uiConn.WriteJSON(msg)
break
}
}
}
func listInstances(dataDir string, conn *websocket.Conn) {
dir := filepath.Join(dataDir, "instances")
entries, err := os.ReadDir(dir)
if err != nil {
conn.WriteJSON(map[string]interface{}{"action": "instances_list", "instances": []interface{}{}})
return
}
var instances []map[string]interface{}
for _, e := range entries {
if e.IsDir() {
instances = append(instances, map[string]interface{}{"id": e.Name()})
}
}
conn.WriteJSON(map[string]interface{}{"action": "instances_list", "instances": instances})
}
+77
View File
@@ -0,0 +1,77 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>EduBox Agent</title>
<script src="https://unpkg.com/htmx.org@1.9.12"></script>
<style>
body { font-family: system-ui, sans-serif; background: #f8fafc; margin: 0; padding: 2rem; }
.card { background: white; border-radius: 8px; padding: 1.5rem; max-width: 400px; margin: 2rem auto; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
h1 { font-size: 1.5rem; margin-bottom: 1rem; color: #1e293b; }
input { width: 100%; padding: 0.5rem; border: 1px solid #cbd5e1; border-radius: 4px; margin-bottom: 0.75rem; box-sizing: border-box; }
button { width: 100%; padding: 0.6rem; background: #2563eb; color: white; border: none; border-radius: 4px; cursor: pointer; font-weight: 500; }
button:hover { background: #1d4ed8; }
.status { margin-top: 1rem; font-size: 0.875rem; }
.success { color: #16a34a; }
.error { color: #dc2626; }
.instance-list { margin-top: 1rem; }
.instance-item { padding: 0.5rem; border: 1px solid #e2e8f0; border-radius: 4px; margin-bottom: 0.5rem; }
</style>
</head>
<body>
<div class="card">
<h1>EduBox Agent</h1>
<div id="main">
<p>Chargement...</p>
</div>
</div>
<script>
const ws = new WebSocket('ws://' + location.host + '/ws');
const main = document.getElementById('main');
ws.onopen = () => {
ws.send(JSON.stringify({action: 'check'}));
};
ws.onmessage = (ev) => {
const msg = JSON.parse(ev.data);
if (msg.action === 'not_activated') {
main.innerHTML = `
<p>Veuillez entrer votre code d'activation (6 caractères) :</p>
<input type="text" id="code" maxlength="6" placeholder="XXXXXX">
<button onclick="activate()">Activer</button>
<div id="status" class="status"></div>
`;
} else if (msg.action === 'activated') {
main.innerHTML = `
<p class="success">✅ Activé : <strong>${msg.studentName}</strong></p>
<div class="instance-list" id="instances"></div>
`;
ws.send(JSON.stringify({action: 'instances'}));
} else if (msg.action === 'activation_failed') {
document.getElementById('status').innerHTML = `<span class="error">❌ ${msg.error || 'Code invalide'}</span>`;
} else if (msg.action === 'instances_list') {
const container = document.getElementById('instances');
if (!container) return;
if (msg.instances.length === 0) {
container.innerHTML = '<p class="status">Aucune instance assignée.</p>';
} else {
container.innerHTML = '<p class="status"><strong>Instances :</strong></p>' +
msg.instances.map(i => `<div class="instance-item">${i.id}</div>`).join('');
}
}
};
function activate() {
const code = document.getElementById('code').value.trim().toUpperCase();
if (code.length !== 6) {
document.getElementById('status').innerHTML = '<span class="error">Le code doit faire 6 caractères.</span>';
return;
}
document.getElementById('status').innerHTML = 'Activation en cours...';
ws.send(JSON.stringify({action: 'activate', code}));
}
</script>
</body>
</html>
+125
View File
@@ -0,0 +1,125 @@
package main
import (
"log"
"time"
"github.com/gorilla/websocket"
)
type WSMessage struct {
Action string `json:"action"`
NodeID string `json:"nodeId,omitempty"`
Code string `json:"code,omitempty"`
InstanceID string `json:"instanceId,omitempty"`
Type string `json:"type,omitempty"`
Port int `json:"port,omitempty"`
ComposeConfig string `json:"composeConfig,omitempty"`
StudentName string `json:"studentName,omitempty"`
Error string `json:"error,omitempty"`
}
func startWebSocket(serverAddr, nodeID, dataDir string) {
for {
conn, _, err := websocket.DefaultDialer.Dial(serverAddr, nil)
if err != nil {
log.Printf("WS connect error: %v, retrying in 5s...", err)
time.Sleep(5 * time.Second)
continue
}
log.Printf("WS connected to %s", serverAddr)
// Register
if err := conn.WriteJSON(WSMessage{Action: "register", NodeID: nodeID}); err != nil {
log.Printf("WS register error: %v", err)
conn.Close()
continue
}
// Activation flow
act, err := loadActivation(dataDir)
if err != nil || !act.Activated {
log.Println("Waiting for activation...")
} else {
log.Printf("Already activated as %s", act.StudentName)
}
// Heartbeat goroutine
done := make(chan struct{})
go func() {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := conn.WriteJSON(WSMessage{Action: "heartbeat", NodeID: nodeID}); err != nil {
return
}
case <-done:
return
}
}
}()
// Read loop
for {
var msg WSMessage
if err := conn.ReadJSON(&msg); err != nil {
log.Printf("WS read error: %v", err)
break
}
handleMessage(conn, msg, dataDir, nodeID)
}
close(done)
conn.Close()
log.Println("WS disconnected, reconnecting in 5s...")
time.Sleep(5 * time.Second)
}
}
func handleMessage(conn *websocket.Conn, msg WSMessage, dataDir, nodeID string) {
switch msg.Action {
case "activate":
// handled by UI, but server can also push activation response
if msg.StudentName != "" {
act := &Activation{Activated: true, StudentName: msg.StudentName, Code: msg.Code}
saveActivation(dataDir, act)
log.Printf("Activated as %s", msg.StudentName)
}
case "start":
log.Printf("Start instance %s on port %d", msg.InstanceID, msg.Port)
if err := writeCompose(dataDir, msg.InstanceID, msg.ComposeConfig); err != nil {
log.Printf("writeCompose error: %v", err)
conn.WriteJSON(WSMessage{Action: "instance_error", InstanceID: msg.InstanceID, Error: err.Error()})
return
}
if err := dockerComposeUp(dataDir, msg.InstanceID); err != nil {
log.Printf("dockerComposeUp error: %v", err)
conn.WriteJSON(WSMessage{Action: "instance_error", InstanceID: msg.InstanceID, Error: err.Error()})
return
}
conn.WriteJSON(WSMessage{Action: "instance_started", InstanceID: msg.InstanceID, Port: msg.Port})
case "stop":
log.Printf("Stop instance %s", msg.InstanceID)
if err := dockerComposeDown(dataDir, msg.InstanceID); err != nil {
log.Printf("dockerComposeDown error: %v", err)
}
case "reset":
log.Printf("Reset instance %s", msg.InstanceID)
dockerComposeRm(dataDir, msg.InstanceID)
if err := writeCompose(dataDir, msg.InstanceID, msg.ComposeConfig); err != nil {
log.Printf("writeCompose error: %v", err)
return
}
if err := dockerComposeUp(dataDir, msg.InstanceID); err != nil {
log.Printf("dockerComposeUp error: %v", err)
conn.WriteJSON(WSMessage{Action: "instance_error", InstanceID: msg.InstanceID, Error: err.Error()})
return
}
conn.WriteJSON(WSMessage{Action: "instance_started", InstanceID: msg.InstanceID, Port: msg.Port})
default:
log.Printf("Unknown action: %s", msg.Action)
}
}
+93
View File
@@ -0,0 +1,93 @@
services:
postgres:
image: postgres:18-alpine
container_name: edubox-postgres
restart: unless-stopped
environment:
POSTGRES_USER: edubox
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: edubox
volumes:
- pg_data:/var/lib/postgresql
networks:
- edubox
healthcheck:
test: ["CMD-SHELL", "pg_isready -U edubox -d edubox"]
interval: 5s
timeout: 5s
retries: 5
server:
build:
context: ./server
dockerfile: Dockerfile
container_name: edubox-server
restart: unless-stopped
environment:
DATABASE_URL: ${DATABASE_URL}
NEXTAUTH_SECRET: ${NEXTAUTH_SECRET}
NEXTAUTH_URL: ${NEXTAUTH_URL}
SUPERADMIN_EMAIL: ${SUPERADMIN_EMAIL}
SUPERADMIN_PASSWORD: ${SUPERADMIN_PASSWORD}
HEADSCALE_URL: ${HEADSCALE_URL}
HEADSCALE_AUTH_KEY: ${HEADSCALE_AUTH_KEY}
GITEA_URL: ${GITEA_URL}
GITEA_TOKEN: ${GITEA_TOKEN}
depends_on:
postgres:
condition: service_healthy
networks:
- edubox
caddy:
image: caddy:2-alpine
container_name: edubox-caddy
restart: unless-stopped
ports:
- "80:80"
- "443:443"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy_data:/data
- caddy_config:/config
networks:
- edubox
headscale:
image: headscale/headscale:latest
container_name: edubox-headscale
restart: unless-stopped
command: serve
ports:
- "41641:41641/udp"
volumes:
- headscale_data:/etc/headscale
networks:
- edubox
gitea:
image: gitea/gitea:latest
container_name: edubox-gitea
restart: unless-stopped
ports:
- "3001:3000"
environment:
- USER_UID=1000
- USER_GID=1000
- GITEA__database__DB_TYPE=sqlite3
- GITEA__database__PATH=/data/gitea/gitea.db
volumes:
- gitea_data:/data
networks:
- edubox
volumes:
pg_data:
caddy_data:
caddy_config:
headscale_data:
gitea_data:
networks:
edubox:
driver: bridge
+9
View File
@@ -0,0 +1,9 @@
FROM node:24-alpine
WORKDIR /app
RUN apk add --no-cache openssl
COPY package.json package-lock.json* ./
COPY prisma ./prisma
RUN npm ci
COPY . .
RUN npm run build
CMD ["node_modules/.bin/next", "start"]
+46
View File
@@ -0,0 +1,46 @@
"use client";
import { useState } from "react";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
export default function LoginForm() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const router = useRouter();
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError("");
const res = await signIn("credentials", { email, password, redirect: false });
setLoading(false);
if (res?.error) {
setError("Email ou mot de passe invalide");
} else {
router.push("/dashboard");
router.refresh();
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4">
{error && <div className="text-sm text-destructive text-center">{error}</div>}
<div>
<label className="block text-sm font-medium mb-1">Email</label>
<Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
</div>
<div>
<label className="block text-sm font-medium mb-1">Mot de passe</label>
<Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? "Connexion..." : "Se connecter"}
</Button>
</form>
);
}
+15
View File
@@ -0,0 +1,15 @@
import LoginForm from "./LoginForm";
export const dynamic = "force-dynamic";
export default function LoginPage() {
return (
<div className="flex min-h-screen items-center justify-center bg-gray-50">
<div className="w-full max-w-md p-8 space-y-6 bg-white rounded-lg shadow-md">
<h1 className="text-2xl font-bold text-center text-gray-900">EduBox V2</h1>
<p className="text-center text-muted-foreground">Connexion à la plateforme</p>
<LoginForm />
</div>
</div>
);
}
@@ -0,0 +1,6 @@
import NextAuth from "next-auth";
import { authOptions } from "@/lib/auth-config";
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
+24
View File
@@ -0,0 +1,24 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const establishmentId = searchParams.get("establishmentId");
if (!establishmentId) return NextResponse.json({ error: "Missing establishmentId" }, { status: 400 });
const classes = await prisma.class.findMany({
where: { establishmentId },
include: { _count: { select: { students: true } } },
orderBy: { createdAt: "desc" },
});
return NextResponse.json(classes);
}
export async function POST(req: NextRequest) {
const body = await req.json();
const { establishmentId, name, level } = body;
const cls = await prisma.class.create({
data: { establishmentId, name, level },
});
return NextResponse.json(cls, { status: 201 });
}
+9
View File
@@ -0,0 +1,9 @@
import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({
windows: "/agent/edubox-agent.exe",
linux: "/agent/edubox-agent",
mac: "/agent/edubox-agent-mac",
});
}
+37
View File
@@ -0,0 +1,37 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { hashPassword } from "@/lib/auth";
export async function GET() {
const establishments = await prisma.establishment.findMany({
include: { subscription: true, _count: { select: { users: true, classes: true } } },
orderBy: { createdAt: "desc" },
});
return NextResponse.json(establishments);
}
export async function POST(req: NextRequest) {
const body = await req.json();
const { name, slug, adminEmail, adminPassword } = body;
const establishment = await prisma.establishment.create({
data: { name, slug },
});
await prisma.subscription.create({
data: { establishmentId: establishment.id, plan: "trial", status: "active" },
});
if (adminEmail && adminPassword) {
await prisma.user.create({
data: {
email: adminEmail,
password: await hashPassword(adminPassword),
role: "admin",
establishmentId: establishment.id,
},
});
}
return NextResponse.json(establishment, { status: 201 });
}
+86
View File
@@ -0,0 +1,86 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { sendToNode } from "@/lib/websocket";
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const nodeId = searchParams.get("nodeId");
const establishmentId = searchParams.get("establishmentId");
let where: any = {};
if (nodeId) where.nodeId = nodeId;
if (establishmentId) {
const classes = await prisma.class.findMany({ where: { establishmentId }, select: { id: true } });
const students = await prisma.student.findMany({ where: { classId: { in: classes.map((c) => c.id) } }, select: { id: true } });
const nodes = await prisma.node.findMany({ where: { studentId: { in: students.map((s) => s.id) } }, select: { id: true } });
where.nodeId = { in: nodes.map((n) => n.id) };
}
const instances = await prisma.instance.findMany({
where,
include: { node: { include: { student: { include: { class: true } } } }, template: true },
orderBy: { createdAt: "desc" },
});
return NextResponse.json(instances);
}
export async function POST(req: NextRequest) {
const body = await req.json();
const { nodeId, templateId, port } = body;
const template = await prisma.template.findUnique({ where: { id: templateId } });
if (!template) return NextResponse.json({ error: "Template not found" }, { status: 404 });
const instance = await prisma.instance.create({
data: { nodeId, templateId, port: port || 8080, status: "stopped" },
});
const sent = sendToNode(nodeId, {
action: "start",
instanceId: instance.id,
type: template.type,
port: instance.port,
composeConfig: template.composeConfig.replace(/{PORT}/g, String(instance.port)).replace(/{INSTANCE_ID}/g, instance.id),
});
if (!sent) {
await prisma.instance.update({ where: { id: instance.id }, data: { status: "error" } });
}
return NextResponse.json(instance, { status: 201 });
}
export async function PATCH(req: NextRequest) {
const body = await req.json();
const { id, action } = body;
const instance = await prisma.instance.findUnique({ where: { id }, include: { template: true } });
if (!instance) return NextResponse.json({ error: "Not found" }, { status: 404 });
if (action === "stop") {
sendToNode(instance.nodeId, { action: "stop", instanceId: instance.id });
await prisma.instance.update({ where: { id }, data: { status: "stopped" } });
} else if (action === "start") {
const sent = sendToNode(instance.nodeId, {
action: "start",
instanceId: instance.id,
type: instance.template.type,
port: instance.port,
composeConfig: instance.template.composeConfig.replace(/{PORT}/g, String(instance.port)).replace(/{INSTANCE_ID}/g, instance.id),
});
if (!sent) await prisma.instance.update({ where: { id }, data: { status: "error" } });
} else if (action === "reset") {
sendToNode(instance.nodeId, { action: "reset", instanceId: instance.id });
}
return NextResponse.json({ ok: true });
}
export async function DELETE(req: NextRequest) {
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
const instance = await prisma.instance.findUnique({ where: { id } });
if (instance) sendToNode(instance.nodeId, { action: "stop", instanceId: instance.id });
await prisma.instance.delete({ where: { id } });
return NextResponse.json({ ok: true });
}
+21
View File
@@ -0,0 +1,21 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const establishmentId = searchParams.get("establishmentId");
let where: any = {};
if (establishmentId) {
const classes = await prisma.class.findMany({ where: { establishmentId }, select: { id: true } });
const students = await prisma.student.findMany({ where: { classId: { in: classes.map((c) => c.id) } }, select: { id: true } });
where.studentId = { in: students.map((s) => s.id) };
}
const nodes = await prisma.node.findMany({
where,
include: { student: { include: { class: true } }, instances: true },
orderBy: { lastSeen: "desc" },
});
return NextResponse.json(nodes);
}
+44
View File
@@ -0,0 +1,44 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
function generateCode(length = 6) {
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let code = "";
for (let i = 0; i < length; i++) code += chars.charAt(Math.floor(Math.random() * chars.length));
return code;
}
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const classId = searchParams.get("classId");
const establishmentId = searchParams.get("establishmentId");
const where: any = {};
if (classId) where.classId = classId;
if (establishmentId) {
const classes = await prisma.class.findMany({ where: { establishmentId }, select: { id: true } });
where.classId = { in: classes.map((c) => c.id) };
}
const students = await prisma.student.findMany({
where,
include: { class: true, nodes: true },
orderBy: { createdAt: "desc" },
});
return NextResponse.json(students);
}
export async function POST(req: NextRequest) {
const body = await req.json();
const { classId, firstName, lastName, email } = body;
const student = await prisma.student.create({
data: {
classId,
firstName,
lastName,
email,
activationCode: generateCode(),
},
});
return NextResponse.json(student, { status: 201 });
}
+42
View File
@@ -0,0 +1,42 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const establishmentId = searchParams.get("establishmentId");
const templates = await prisma.template.findMany({
where: {
OR: [
{ isPublic: true },
...(establishmentId ? [{ establishmentId }] : []),
],
},
orderBy: { createdAt: "desc" },
});
return NextResponse.json(templates);
}
export async function POST(req: NextRequest) {
const body = await req.json();
const { name, type, dockerImage, composeConfig, isPublic, establishmentId, createdBy } = body;
const template = await prisma.template.create({
data: { name, type, dockerImage, composeConfig, isPublic, establishmentId, createdBy },
});
return NextResponse.json(template, { status: 201 });
}
export async function PUT(req: NextRequest) {
const body = await req.json();
const { id, ...data } = body;
const template = await prisma.template.update({ where: { id }, data });
return NextResponse.json(template);
}
export async function DELETE(req: NextRequest) {
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
await prisma.template.delete({ where: { id } });
return NextResponse.json({ ok: true });
}
+41
View File
@@ -0,0 +1,41 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { hashPassword } from "@/lib/auth";
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const establishmentId = searchParams.get("establishmentId");
const role = searchParams.get("role");
const where: any = {};
if (establishmentId) where.establishmentId = establishmentId;
if (role) where.role = role;
const users = await prisma.user.findMany({
where,
orderBy: { createdAt: "desc" },
});
return NextResponse.json(users);
}
export async function POST(req: NextRequest) {
const body = await req.json();
const { email, password, role, establishmentId } = body;
const user = await prisma.user.create({
data: {
email,
password: await hashPassword(password),
role,
establishmentId,
},
});
return NextResponse.json(user, { status: 201 });
}
export async function DELETE(req: NextRequest) {
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
if (!id) return NextResponse.json({ error: "Missing id" }, { status: 400 });
await prisma.user.delete({ where: { id } });
return NextResponse.json({ ok: true });
}
+17
View File
@@ -0,0 +1,17 @@
import { WebSocketServer } from "ws";
import { initWebSocketServer } from "@/lib/websocket";
const globalWss = globalThis as typeof globalThis & { __eduboxWss?: WebSocketServer };
if (!globalWss.__eduboxWss) {
try {
globalWss.__eduboxWss = new WebSocketServer({ port: 3001 });
initWebSocketServer(globalWss.__eduboxWss);
} catch {
// Port may be in use during build or hot reload
}
}
export async function GET() {
return new Response("WebSocket server running on port 3001", { status: 200 });
}
+72
View File
@@ -0,0 +1,72 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { signOut } from "next-auth/react";
import { cn } from "@/lib/utils";
const links = [
{ href: "/dashboard", label: "Accueil" },
{ href: "/dashboard/classes", label: "Classes" },
{ href: "/dashboard/students", label: "Étudiants" },
{ href: "/dashboard/nodes", label: "Nœuds" },
{ href: "/dashboard/instances", label: "Instances" },
{ href: "/dashboard/templates", label: "Templates" },
{ href: "/dashboard/download", label: "Téléchargements" },
];
const superadminLinks = [
{ href: "/superadmin", label: "Super Admin" },
{ href: "/superadmin/establishments", label: "Établissements" },
];
export default function DashboardNav({ role }: { role: string }) {
const pathname = usePathname();
return (
<nav className="w-64 bg-white border-r flex flex-col">
<div className="p-6 border-b">
<h2 className="text-xl font-bold text-primary">EduBox</h2>
</div>
<div className="flex-1 p-4 space-y-1">
{links.map((link) => (
<Link
key={link.href}
href={link.href}
className={cn(
"block px-3 py-2 rounded-md text-sm font-medium transition-colors",
pathname === link.href ? "bg-primary text-primary-foreground" : "text-gray-700 hover:bg-gray-100"
)}
>
{link.label}
</Link>
))}
{role === "superadmin" && (
<div className="pt-4 mt-4 border-t">
<p className="px-3 text-xs font-semibold text-muted-foreground uppercase mb-2">Super Admin</p>
{superadminLinks.map((link) => (
<Link
key={link.href}
href={link.href}
className={cn(
"block px-3 py-2 rounded-md text-sm font-medium transition-colors",
pathname === link.href ? "bg-primary text-primary-foreground" : "text-gray-700 hover:bg-gray-100"
)}
>
{link.label}
</Link>
))}
</div>
)}
</div>
<div className="p-4 border-t">
<button
onClick={() => signOut({ callbackUrl: "/login" })}
className="w-full text-left px-3 py-2 text-sm font-medium text-destructive hover:bg-destructive/10 rounded-md transition-colors"
>
Déconnexion
</button>
</div>
</nav>
);
}
+56
View File
@@ -0,0 +1,56 @@
import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect } from "next/navigation";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
export const dynamic = "force-dynamic";
export default async function ClassesPage() {
const session = await getServerSession(authOptions);
if (!session?.user) redirect("/login");
if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");
const establishmentId = session.user.establishmentId;
const classes = await prisma.class.findMany({
where: establishmentId ? { establishmentId } : {},
include: { _count: { select: { students: true } } },
orderBy: { createdAt: "desc" },
});
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold">Classes</h1>
<Card>
<CardContent className="pt-6">
<Table>
<TableHeader>
<TableRow>
<TableHead>Nom</TableHead>
<TableHead>Niveau</TableHead>
<TableHead>Étudiants</TableHead>
<TableHead>Créée le</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{classes.map((cls) => (
<TableRow key={cls.id}>
<TableCell className="font-medium">{cls.name}</TableCell>
<TableCell>{cls.level}</TableCell>
<TableCell>{cls._count.students}</TableCell>
<TableCell>{new Date(cls.createdAt).toLocaleDateString("fr-FR")}</TableCell>
</TableRow>
))}
{classes.length === 0 && (
<TableRow>
<TableCell colSpan={4} className="text-center text-muted-foreground">Aucune classe</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
);
}
+41
View File
@@ -0,0 +1,41 @@
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
export const dynamic = "force-dynamic";
export default function DownloadPage() {
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold">Téléchargements Agent</h1>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Card>
<CardHeader>
<CardTitle>Windows</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-4">Agent EduBox pour Windows (64 bits)</p>
<a href="/agent/edubox-agent.exe" download className="inline-flex items-center justify-center rounded-md text-sm font-medium bg-primary text-primary-foreground hover:bg-primary/90 h-10 px-4 py-2 w-full">Télécharger (.exe)</a>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Linux</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-4">Agent EduBox pour Linux (64 bits)</p>
<a href="/agent/edubox-agent" download className="inline-flex items-center justify-center rounded-md text-sm font-medium bg-primary text-primary-foreground hover:bg-primary/90 h-10 px-4 py-2 w-full">Télécharger</a>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>macOS</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-4">Agent EduBox pour macOS (Intel & Apple Silicon)</p>
<a href="/agent/edubox-agent-mac" download className="inline-flex items-center justify-center rounded-md text-sm font-medium bg-primary text-primary-foreground hover:bg-primary/90 h-10 px-4 py-2 w-full">Télécharger</a>
</CardContent>
</Card>
</div>
</div>
);
}
@@ -0,0 +1,37 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
export default function InstanceActions({ instanceId, status }: { instanceId: string; status: string }) {
const [loading, setLoading] = useState<string | null>(null);
async function action(type: string) {
setLoading(type);
await fetch("/api/instances", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: instanceId, action: type }),
});
setLoading(null);
window.location.reload();
}
return (
<div className="flex gap-2">
{status !== "running" && (
<Button size="sm" variant="outline" onClick={() => action("start")} disabled={!!loading}>
{loading === "start" ? "..." : "Démarrer"}
</Button>
)}
{status === "running" && (
<Button size="sm" variant="outline" onClick={() => action("stop")} disabled={!!loading}>
{loading === "stop" ? "..." : "Arrêter"}
</Button>
)}
<Button size="sm" variant="outline" onClick={() => action("reset")} disabled={!!loading}>
{loading === "reset" ? "..." : "Réinitialiser"}
</Button>
</div>
);
}
@@ -0,0 +1,60 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
export default function AssignForm({ templates, nodes }: { templates: any[]; nodes: any[] }) {
const [templateId, setTemplateId] = useState("");
const [nodeId, setNodeId] = useState("");
const [port, setPort] = useState("8080");
const [loading, setLoading] = useState(false);
const router = useRouter();
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
await fetch("/api/instances", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ templateId, nodeId, port: parseInt(port) }),
});
setLoading(false);
router.push("/dashboard/instances");
router.refresh();
}
return (
<form onSubmit={handleSubmit} className="space-y-4 bg-white p-6 rounded-lg border shadow-sm">
<div>
<label className="block text-sm font-medium mb-1">Template</label>
<Select value={templateId} onChange={(e) => setTemplateId(e.target.value)} required>
<option value="">Choisir un template</option>
{templates.map((t) => (
<option key={t.id} value={t.id}>{t.name}</option>
))}
</Select>
</div>
<div>
<label className="block text-sm font-medium mb-1">Nœud (étudiant)</label>
<Select value={nodeId} onChange={(e) => setNodeId(e.target.value)} required>
<option value="">Choisir un nœud</option>
{nodes.map((n) => (
<option key={n.id} value={n.id}>
{n.id} {n.student ? `- ${n.student.firstName} ${n.student.lastName}` : ""}
</option>
))}
</Select>
</div>
<div>
<label className="block text-sm font-medium mb-1">Port</label>
<Input type="number" value={port} onChange={(e) => setPort(e.target.value)} required />
</div>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? "Attribution..." : "Attribuer"}
</Button>
</form>
);
}
@@ -0,0 +1,34 @@
import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect } from "next/navigation";
import AssignForm from "./AssignForm";
export const dynamic = "force-dynamic";
export default async function AssignPage() {
const session = await getServerSession(authOptions);
if (!session?.user) redirect("/login");
if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");
const establishmentId = session.user.establishmentId;
const templates = await prisma.template.findMany({
where: { OR: [{ isPublic: true }, ...(establishmentId ? [{ establishmentId }] : [])] },
orderBy: { createdAt: "desc" },
});
const nodes = await prisma.node.findMany({
where: establishmentId
? { student: { class: { establishmentId } } }
: {},
include: { student: { include: { class: true } } },
orderBy: { createdAt: "desc" },
});
return (
<div className="space-y-6 max-w-xl">
<h1 className="text-3xl font-bold">Attribuer une instance</h1>
<AssignForm templates={templates} nodes={nodes} />
</div>
);
}
+77
View File
@@ -0,0 +1,77 @@
import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect } from "next/navigation";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import InstanceActions from "./InstanceActions";
import Link from "next/link";
import { Button } from "@/components/ui/button";
export const dynamic = "force-dynamic";
export default async function InstancesPage() {
const session = await getServerSession(authOptions);
if (!session?.user) redirect("/login");
if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");
const establishmentId = session.user.establishmentId;
const instances = await prisma.instance.findMany({
where: establishmentId
? { node: { student: { class: { establishmentId } } } }
: {},
include: { node: { include: { student: { include: { class: true } } } }, template: true },
orderBy: { createdAt: "desc" },
});
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-3xl font-bold">Instances</h1>
<Link href="/dashboard/instances/assign">
<Button>Attribuer une instance</Button>
</Link>
</div>
<Card>
<CardContent className="pt-6">
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Template</TableHead>
<TableHead>Nœud</TableHead>
<TableHead>Étudiant</TableHead>
<TableHead>Port</TableHead>
<TableHead>Statut</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{instances.map((inst) => (
<TableRow key={inst.id}>
<TableCell className="font-medium">{inst.id.slice(0, 8)}...</TableCell>
<TableCell>{inst.template.name}</TableCell>
<TableCell>{inst.node.id.slice(0, 8)}...</TableCell>
<TableCell>{inst.node.student ? `${inst.node.student.firstName} ${inst.node.student.lastName}` : "-"}</TableCell>
<TableCell>{inst.port}</TableCell>
<TableCell>
<Badge variant={inst.status === "running" ? "success" : inst.status === "error" ? "destructive" : "secondary"}>{inst.status}</Badge>
</TableCell>
<TableCell>
<InstanceActions instanceId={inst.id} status={inst.status} />
</TableCell>
</TableRow>
))}
{instances.length === 0 && (
<TableRow>
<TableCell colSpan={7} className="text-center text-muted-foreground">Aucune instance</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
);
}
+18
View File
@@ -0,0 +1,18 @@
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect } from "next/navigation";
import DashboardNav from "./DashboardNav";
export const dynamic = "force-dynamic";
export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
const session = await getServerSession(authOptions);
if (!session?.user) redirect("/login");
return (
<div className="flex min-h-screen bg-gray-50">
<DashboardNav role={session.user.role} />
<main className="flex-1 p-6 overflow-auto">{children}</main>
</div>
);
}
+65
View File
@@ -0,0 +1,65 @@
import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect } from "next/navigation";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
export const dynamic = "force-dynamic";
export default async function NodesPage() {
const session = await getServerSession(authOptions);
if (!session?.user) redirect("/login");
if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");
const establishmentId = session.user.establishmentId;
const nodes = await prisma.node.findMany({
where: establishmentId
? { student: { class: { establishmentId } } }
: {},
include: { student: { include: { class: true } }, instances: true },
orderBy: { lastSeen: "desc" },
});
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold">Nœuds</h1>
<Card>
<CardContent className="pt-6">
<Table>
<TableHeader>
<TableRow>
<TableHead>ID</TableHead>
<TableHead>Étudiant</TableHead>
<TableHead>IP Tailscale</TableHead>
<TableHead>Statut</TableHead>
<TableHead>Instances</TableHead>
<TableHead>Dernière vue</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{nodes.map((n) => (
<TableRow key={n.id}>
<TableCell className="font-medium">{n.id}</TableCell>
<TableCell>{n.student ? `${n.student.firstName} ${n.student.lastName}` : "-"}</TableCell>
<TableCell>{n.tailscaleIp || "-"}</TableCell>
<TableCell>
<Badge variant={n.status === "online" ? "success" : "secondary"}>{n.status}</Badge>
</TableCell>
<TableCell>{n.instances.length}</TableCell>
<TableCell>{n.lastSeen ? new Date(n.lastSeen).toLocaleString("fr-FR") : "-"}</TableCell>
</TableRow>
))}
{nodes.length === 0 && (
<TableRow>
<TableCell colSpan={6} className="text-center text-muted-foreground">Aucun nœud</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
);
}
+72
View File
@@ -0,0 +1,72 @@
import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect } from "next/navigation";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
export const dynamic = "force-dynamic";
export default async function DashboardPage() {
const session = await getServerSession(authOptions);
if (!session?.user) redirect("/login");
const isSuperadmin = session.user.role === "superadmin";
const establishmentId = session.user.establishmentId;
const where = isSuperadmin ? {} : { establishmentId };
const nodesCount = await prisma.node.count({
where: isSuperadmin ? {} : { student: { class: { establishmentId } } },
});
const onlineNodes = await prisma.node.count({
where: isSuperadmin ? { status: "online" } : { status: "online", student: { class: { establishmentId } } },
});
const instancesRunning = await prisma.instance.count({
where: isSuperadmin ? { status: "running" } : { status: "running", node: { student: { class: { establishmentId } } } },
});
const studentsCount = await prisma.student.count({
where: isSuperadmin ? {} : { class: { establishmentId } },
});
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold">Tableau de bord</h1>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Nœuds</CardTitle>
</CardHeader>
<CardContent>
<div className="text-3xl font-bold">{nodesCount}</div>
<Badge variant="success" className="mt-2">{onlineNodes} en ligne</Badge>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Instances actives</CardTitle>
</CardHeader>
<CardContent>
<div className="text-3xl font-bold">{instancesRunning}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Étudiants</CardTitle>
</CardHeader>
<CardContent>
<div className="text-3xl font-bold">{studentsCount}</div>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">Statut</CardTitle>
</CardHeader>
<CardContent>
<Badge variant="success">Opérationnel</Badge>
</CardContent>
</Card>
</div>
</div>
);
}
+68
View File
@@ -0,0 +1,68 @@
import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect } from "next/navigation";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
export const dynamic = "force-dynamic";
export default async function StudentsPage() {
const session = await getServerSession(authOptions);
if (!session?.user) redirect("/login");
if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");
const establishmentId = session.user.establishmentId;
const students = await prisma.student.findMany({
where: establishmentId ? { class: { establishmentId } } : {},
include: { class: true, nodes: true },
orderBy: { createdAt: "desc" },
});
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold">Étudiants</h1>
<Card>
<CardContent className="pt-6">
<Table>
<TableHeader>
<TableRow>
<TableHead>Nom</TableHead>
<TableHead>Classe</TableHead>
<TableHead>Email</TableHead>
<TableHead>Code activation</TableHead>
<TableHead>Nœud</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{students.map((s) => {
const node = s.nodes[0];
return (
<TableRow key={s.id}>
<TableCell className="font-medium">{s.firstName} {s.lastName}</TableCell>
<TableCell>{s.class.name}</TableCell>
<TableCell>{s.email}</TableCell>
<TableCell>{s.activationCode || "-"}</TableCell>
<TableCell>
{node ? (
<Badge variant={node.status === "online" ? "success" : "secondary"}>{node.status}</Badge>
) : (
<Badge variant="outline">Non lié</Badge>
)}
</TableCell>
</TableRow>
);
})}
{students.length === 0 && (
<TableRow>
<TableCell colSpan={5} className="text-center text-muted-foreground">Aucun étudiant</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
);
}
+61
View File
@@ -0,0 +1,61 @@
import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect } from "next/navigation";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
export const dynamic = "force-dynamic";
export default async function TemplatesPage() {
const session = await getServerSession(authOptions);
if (!session?.user) redirect("/login");
const establishmentId = session.user.establishmentId;
const templates = await prisma.template.findMany({
where: { OR: [{ isPublic: true }, ...(establishmentId ? [{ establishmentId }] : [])] },
orderBy: { createdAt: "desc" },
});
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold">Templates</h1>
<Card>
<CardContent className="pt-6">
<Table>
<TableHeader>
<TableRow>
<TableHead>Nom</TableHead>
<TableHead>Type</TableHead>
<TableHead>Image Docker</TableHead>
<TableHead>Visibilité</TableHead>
<TableHead>Créé par</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{templates.map((t) => (
<TableRow key={t.id}>
<TableCell className="font-medium">{t.name}</TableCell>
<TableCell>
<Badge variant="secondary">{t.type}</Badge>
</TableCell>
<TableCell>{t.dockerImage}</TableCell>
<TableCell>
<Badge variant={t.isPublic ? "success" : "outline"}>{t.isPublic ? "Public" : "Privé"}</Badge>
</TableCell>
<TableCell>{t.createdBy}</TableCell>
</TableRow>
))}
{templates.length === 0 && (
<TableRow>
<TableCell colSpan={5} className="text-center text-muted-foreground">Aucun template</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
);
}
+37
View File
@@ -0,0 +1,37 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--card: 0 0% 100%;
--card-foreground: 222.2 84% 4.9%;
--popover: 0 0% 100%;
--popover-foreground: 222.2 84% 4.9%;
--primary: 221.2 83.2% 53.3%;
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--secondary-foreground: 222.2 47.4% 11.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
--accent: 210 40% 96.1%;
--accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 210 40% 98%;
--border: 214.3 31.8% 91.4%;
--input: 214.3 31.8% 91.4%;
--ring: 221.2 83.2% 53.3%;
--radius: 0.5rem;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}
+22
View File
@@ -0,0 +1,22 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "EduBox V2",
description: "Plateforme de gestion d'instances pour l'enseignement BTS",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="fr">
<body className={inter.className}>{children}</body>
</html>
);
}
+5
View File
@@ -0,0 +1,5 @@
import { redirect } from 'next/navigation'
export default function Home() {
redirect('/dashboard')
}
@@ -0,0 +1,58 @@
import { prisma } from "@/lib/prisma";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
export const dynamic = "force-dynamic";
export default async function EstablishmentsPage() {
const establishments = await prisma.establishment.findMany({
include: { subscription: true, _count: { select: { users: true, classes: true } } },
orderBy: { createdAt: "desc" },
});
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold">Établissements</h1>
<Card>
<CardContent className="pt-6">
<Table>
<TableHeader>
<TableRow>
<TableHead>Nom</TableHead>
<TableHead>Slug</TableHead>
<TableHead>Plan</TableHead>
<TableHead>Statut</TableHead>
<TableHead>Utilisateurs</TableHead>
<TableHead>Classes</TableHead>
<TableHead>Expiration</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{establishments.map((e) => (
<TableRow key={e.id}>
<TableCell className="font-medium">{e.name}</TableCell>
<TableCell>{e.slug}</TableCell>
<TableCell>
<Badge variant="secondary">{e.subscription?.plan || "-"}</Badge>
</TableCell>
<TableCell>
<Badge variant={e.subscription?.status === "active" ? "success" : "destructive"}>{e.subscription?.status || "-"}</Badge>
</TableCell>
<TableCell>{e._count.users}</TableCell>
<TableCell>{e._count.classes}</TableCell>
<TableCell>{e.subscription?.expiresAt ? new Date(e.subscription.expiresAt).toLocaleDateString("fr-FR") : "-"}</TableCell>
</TableRow>
))}
{establishments.length === 0 && (
<TableRow>
<TableCell colSpan={7} className="text-center text-muted-foreground">Aucun établissement</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</CardContent>
</Card>
</div>
);
}
+11
View File
@@ -0,0 +1,11 @@
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect } from "next/navigation";
export const dynamic = "force-dynamic";
export default async function SuperAdminLayout({ children }: { children: React.ReactNode }) {
const session = await getServerSession(authOptions);
if (!session?.user || session.user.role !== "superadmin") redirect("/dashboard");
return <>{children}</>;
}
+46
View File
@@ -0,0 +1,46 @@
import { prisma } from "@/lib/prisma";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
export const dynamic = "force-dynamic";
export default async function SuperAdminPage() {
const establishments = await prisma.establishment.count();
const users = await prisma.user.count();
const students = await prisma.student.count();
const nodesOnline = await prisma.node.count({ where: { status: "online" } });
const instancesRunning = await prisma.instance.count({ where: { status: "running" } });
const activeSubs = await prisma.subscription.count({ where: { status: "active" } });
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold">Super Admin Vue globale</h1>
<div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-3 gap-4">
<Card>
<CardHeader className="pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">Établissements</CardTitle></CardHeader>
<CardContent><div className="text-3xl font-bold">{establishments}</div></CardContent>
</Card>
<Card>
<CardHeader className="pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">Utilisateurs</CardTitle></CardHeader>
<CardContent><div className="text-3xl font-bold">{users}</div></CardContent>
</Card>
<Card>
<CardHeader className="pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">Étudiants</CardTitle></CardHeader>
<CardContent><div className="text-3xl font-bold">{students}</div></CardContent>
</Card>
<Card>
<CardHeader className="pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">Nœuds en ligne</CardTitle></CardHeader>
<CardContent><div className="text-3xl font-bold">{nodesOnline}</div></CardContent>
</Card>
<Card>
<CardHeader className="pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">Instances running</CardTitle></CardHeader>
<CardContent><div className="text-3xl font-bold">{instancesRunning}</div></CardContent>
</Card>
<Card>
<CardHeader className="pb-2"><CardTitle className="text-sm font-medium text-muted-foreground">Abonnements actifs</CardTitle></CardHeader>
<CardContent><div className="text-3xl font-bold">{activeSubs}</div></CardContent>
</Card>
</div>
</div>
);
}
+25
View File
@@ -0,0 +1,25 @@
import * as React from "react";
import { cn } from "@/lib/utils";
interface BadgeProps extends React.HTMLAttributes<HTMLDivElement> {
variant?: "default" | "secondary" | "destructive" | "outline" | "success";
}
function Badge({ className, variant = "default", ...props }: BadgeProps) {
return (
<div
className={cn(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
variant === "default" && "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
variant === "secondary" && "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
variant === "destructive" && "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
variant === "outline" && "text-foreground",
variant === "success" && "border-transparent bg-green-100 text-green-800 hover:bg-green-200",
className
)}
{...props}
/>
);
}
export { Badge };
+36
View File
@@ -0,0 +1,36 @@
import * as React from "react";
import { cn } from "@/lib/utils";
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: "default" | "outline" | "ghost" | "destructive";
size?: "default" | "sm" | "lg";
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant = "default", size = "default", asChild = false, children, ...props }, ref) => {
const Comp = asChild ? "span" : "button";
return (
<Comp
className={cn(
"inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
variant === "default" && "bg-primary text-primary-foreground hover:bg-primary/90",
variant === "outline" && "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
variant === "ghost" && "hover:bg-accent hover:text-accent-foreground",
variant === "destructive" && "bg-destructive text-destructive-foreground hover:bg-destructive/90",
size === "default" && "h-10 px-4 py-2",
size === "sm" && "h-9 rounded-md px-3",
size === "lg" && "h-11 rounded-md px-8",
className
)}
ref={ref as any}
{...props as any}
>
{children}
</Comp>
);
}
);
Button.displayName = "Button";
export { Button };
+24
View File
@@ -0,0 +1,24 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("rounded-lg border bg-card text-card-foreground shadow-sm", className)} {...props} />
));
Card.displayName = "Card";
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
));
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(({ className, ...props }, ref) => (
<h3 ref={ref} className={cn("text-2xl font-semibold leading-none tracking-tight", className)} {...props} />
));
CardTitle.displayName = "CardTitle";
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
));
CardContent.displayName = "CardContent";
export { Card, CardHeader, CardTitle, CardContent };
+29
View File
@@ -0,0 +1,29 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Dialog = ({ open, onOpenChange, children }: { open?: boolean; onOpenChange?: (v: boolean) => void; children: React.ReactNode }) => {
if (!open) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={() => onOpenChange?.(false)}>
<div className={cn("relative z-50 grid w-full max-w-lg gap-4 border bg-background p-6 shadow-lg rounded-lg")} onClick={(e) => e.stopPropagation()}>
{children}
</div>
</div>
);
};
const DialogContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("grid gap-4", className)} {...props} />
));
DialogContent.displayName = "DialogContent";
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />
);
const DialogTitle = React.forwardRef<HTMLHeadingElement, React.HTMLAttributes<HTMLHeadingElement>>(({ className, ...props }, ref) => (
<h3 ref={ref} className={cn("text-lg font-semibold leading-none tracking-tight", className)} {...props} />
));
DialogTitle.displayName = "DialogTitle";
export { Dialog, DialogContent, DialogHeader, DialogTitle };
+21
View File
@@ -0,0 +1,21 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
);
}
);
Input.displayName = "Input";
export { Input };
+20
View File
@@ -0,0 +1,20 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Select = React.forwardRef<HTMLSelectElement, React.SelectHTMLAttributes<HTMLSelectElement>>(
({ className, ...props }, ref) => {
return (
<select
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
);
}
);
Select.displayName = "Select";
export { Select };
+36
View File
@@ -0,0 +1,36 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
</div>
));
Table.displayName = "Table";
const TableHeader = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
));
TableHeader.displayName = "TableHeader";
const TableBody = React.forwardRef<HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement>>(({ className, ...props }, ref) => (
<tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />
));
TableBody.displayName = "TableBody";
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(({ className, ...props }, ref) => (
<tr ref={ref} className={cn("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted", className)} {...props} />
));
TableRow.displayName = "TableRow";
const TableHead = React.forwardRef<HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement>>(({ className, ...props }, ref) => (
<th ref={ref} className={cn("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0", className)} {...props} />
));
TableHead.displayName = "TableHead";
const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement>>(({ className, ...props }, ref) => (
<td ref={ref} className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)} {...props} />
));
TableCell.displayName = "TableCell";
export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
+28
View File
@@ -0,0 +1,28 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Tabs = ({ children, className }: { children: React.ReactNode; className?: string }) => (
<div className={cn("w-full", className)}>{children}</div>
);
const TabsList = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground", className)} {...props} />
));
TabsList.displayName = "TabsList";
const TabsTrigger = React.forwardRef<HTMLButtonElement, React.ButtonHTMLAttributes<HTMLButtonElement> & { active?: boolean }>(
({ className, active, ...props }, ref) => (
<button
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
active && "bg-background text-foreground shadow-sm",
className
)}
{...props}
/>
)
);
TabsTrigger.displayName = "TabsTrigger";
export { Tabs, TabsList, TabsTrigger };
+45
View File
@@ -0,0 +1,45 @@
import CredentialsProvider from "next-auth/providers/credentials";
import { prisma } from "./prisma";
import { verifyPassword } from "./auth";
export const authOptions = {
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) return null;
const user = await prisma.user.findUnique({
where: { email: credentials.email },
});
if (!user) return null;
const valid = await verifyPassword(credentials.password, user.password);
if (!valid) return null;
return { id: user.id, email: user.email, role: user.role, establishmentId: user.establishmentId ?? undefined };
},
}),
],
callbacks: {
async jwt({ token, user }: any) {
if (user) {
token.role = user.role;
token.establishmentId = user.establishmentId;
}
return token;
},
async session({ session, token }: any) {
session.user.role = token.role;
session.user.establishmentId = token.establishmentId;
return session;
},
},
pages: {
signIn: "/login",
},
session: {
strategy: "jwt" as const,
},
};
+16
View File
@@ -0,0 +1,16 @@
import { prisma } from "./prisma";
import bcrypt from "bcryptjs";
export async function hashPassword(password: string): Promise<string> {
return bcrypt.hash(password, 12);
}
export async function verifyPassword(password: string, hashed: string): Promise<boolean> {
return bcrypt.compare(password, hashed);
}
export function requireRole(user: { role: string }, ...allowed: string[]) {
if (!allowed.includes(user.role)) {
throw new Error("Forbidden");
}
}
+7
View File
@@ -0,0 +1,7 @@
import { PrismaClient } from "@prisma/client";
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };
export const prisma = globalForPrisma.prisma || new PrismaClient();
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
+6
View File
@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+105
View File
@@ -0,0 +1,105 @@
import { WebSocketServer, WebSocket } from "ws";
import { prisma } from "./prisma";
interface NodeMessage {
action: string;
nodeId?: string;
code?: string;
instanceId?: string;
type?: string;
port?: number;
composeConfig?: string;
studentName?: string;
error?: string;
}
const nodes = new Map<string, WebSocket>();
export function initWebSocketServer(wss: WebSocketServer) {
wss.on("connection", (ws: WebSocket) => {
let nodeId: string | null = null;
ws.on("message", async (raw) => {
try {
const msg: NodeMessage = JSON.parse(raw.toString());
if (msg.action === "register" && msg.nodeId) {
nodeId = msg.nodeId;
nodes.set(nodeId, ws);
await prisma.node.upsert({
where: { id: nodeId },
update: { status: "online", lastSeen: new Date() },
create: { id: nodeId, status: "online", lastSeen: new Date() },
});
ws.send(JSON.stringify({ action: "registered" }));
return;
}
if (msg.action === "activate" && msg.code && msg.nodeId) {
nodeId = msg.nodeId;
const student = await prisma.student.findUnique({
where: { activationCode: msg.code },
});
if (!student) {
ws.send(JSON.stringify({ action: "activation_failed", error: "Invalid code" }));
return;
}
await prisma.node.upsert({
where: { id: nodeId },
update: { studentId: student.id, status: "online", lastSeen: new Date() },
create: { id: nodeId, studentId: student.id, status: "online", lastSeen: new Date() },
});
ws.send(JSON.stringify({ action: "activated", studentName: `${student.firstName} ${student.lastName}` }));
return;
}
if (msg.action === "heartbeat" && nodeId) {
await prisma.node.upsert({
where: { id: nodeId },
update: { lastSeen: new Date() },
create: { id: nodeId, status: "online", lastSeen: new Date() },
});
return;
}
if (msg.action === "instance_started" && msg.instanceId) {
await prisma.instance.update({
where: { id: msg.instanceId },
data: { status: "running" },
});
return;
}
if (msg.action === "instance_error" && msg.instanceId) {
await prisma.instance.update({
where: { id: msg.instanceId },
data: { status: "error" },
});
return;
}
} catch (err) {
console.error("WS error:", err);
}
});
ws.on("close", async () => {
if (nodeId) {
nodes.delete(nodeId);
await prisma.node.upsert({
where: { id: nodeId },
update: { status: "offline" },
create: { id: nodeId, status: "offline" },
});
}
});
});
}
export function sendToNode(nodeId: string, message: object) {
const ws = nodes.get(nodeId);
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(message));
return true;
}
return false;
}
+35
View File
@@ -0,0 +1,35 @@
import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";
export default withAuth(
function middleware(req) {
const { pathname } = req.nextUrl;
const role = req.nextauth.token?.role as string;
if (pathname.startsWith("/superadmin")) {
if (role !== "superadmin") {
return NextResponse.redirect(new URL("/dashboard", req.url));
}
}
if (pathname.startsWith("/dashboard")) {
if (!role || (role !== "admin" && role !== "teacher" && role !== "superadmin")) {
return NextResponse.redirect(new URL("/login", req.url));
}
}
return NextResponse.next();
},
{
callbacks: {
authorized({ req, token }) {
if (req.nextUrl.pathname.startsWith("/login")) return true;
return !!token;
},
},
}
);
export const config = {
matcher: ["/dashboard/:path*", "/superadmin/:path*", "/api/protected/:path*"],
};
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+4
View File
@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {}
module.exports = nextConfig
+2687
View File
File diff suppressed because it is too large Load Diff
+42
View File
@@ -0,0 +1,42 @@
{
"name": "edubox-server",
"version": "2.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"postinstall": "prisma generate"
},
"prisma": {
"seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"
},
"dependencies": {
"@prisma/client": "^5.0.0",
"bcryptjs": "^2.4.3",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"lucide-react": "^1.17.0",
"next": "^16.0.0",
"next-auth": "^4.24.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"tailwind-merge": "^2.2.0",
"ws": "^8.16.0"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
"@types/node": "^20.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@types/ws": "^8.5.10",
"autoprefixer": "^10.4.0",
"postcss": "^8.4.0",
"prisma": "^5.0.0",
"tailwindcss": "^3.4.0",
"tailwindcss-animate": "^1.0.7",
"ts-node": "^10.9.0",
"typescript": "^5.3.0"
}
}
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
+97
View File
@@ -0,0 +1,97 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Establishment {
id String @id @default(cuid())
name String
slug String @unique
createdAt DateTime @default(now())
subscription Subscription?
users User[]
classes Class[]
templates Template[]
}
model Subscription {
id String @id @default(cuid())
establishmentId String @unique
establishment Establishment @relation(fields: [establishmentId], references: [id], onDelete: Cascade)
plan String @default("trial")
status String @default("active")
expiresAt DateTime?
createdAt DateTime @default(now())
}
model User {
id String @id @default(cuid())
email String @unique
password String
role String
establishmentId String?
establishment Establishment? @relation(fields: [establishmentId], references: [id], onDelete: SetNull)
createdAt DateTime @default(now())
}
model Class {
id String @id @default(cuid())
establishmentId String
establishment Establishment @relation(fields: [establishmentId], references: [id], onDelete: Cascade)
name String
level String
createdAt DateTime @default(now())
students Student[]
}
model Student {
id String @id @default(cuid())
classId String
class Class @relation(fields: [classId], references: [id], onDelete: Cascade)
firstName String
lastName String
email String
activationCode String? @unique
createdAt DateTime @default(now())
nodes Node[]
}
model Node {
id String @id
studentId String?
student Student? @relation(fields: [studentId], references: [id], onDelete: SetNull)
tailscaleIp String?
status String @default("offline")
lastSeen DateTime?
createdAt DateTime @default(now())
instances Instance[]
}
model Instance {
id String @id @default(cuid())
nodeId String
node Node @relation(fields: [nodeId], references: [id], onDelete: Cascade)
templateId String
template Template @relation(fields: [templateId], references: [id], onDelete: Restrict)
status String @default("stopped")
port Int
createdAt DateTime @default(now())
}
model Template {
id String @id @default(cuid())
name String
type String
dockerImage String
composeConfig String
isPublic Boolean @default(true)
establishmentId String?
establishment Establishment? @relation(fields: [establishmentId], references: [id], onDelete: Cascade)
createdBy String
createdAt DateTime @default(now())
instances Instance[]
}
+66
View File
@@ -0,0 +1,66 @@
import { PrismaClient } from "@prisma/client";
import bcrypt from "bcryptjs";
const prisma = new PrismaClient();
async function main() {
const superadminEmail = process.env.SUPERADMIN_EMAIL || "admin@edudeploy.fr";
const superadminPassword = process.env.SUPERADMIN_PASSWORD || "CHANGE_ME";
const hashedPassword = await bcrypt.hash(superadminPassword, 12);
await prisma.user.upsert({
where: { email: superadminEmail },
update: {},
create: {
email: superadminEmail,
password: hashedPassword,
role: "superadmin",
},
});
const templates = [
{ name: "WordPress latest vierge", type: "wordpress", dockerImage: "wordpress:latest" },
{ name: "WordPress 6.7 vierge", type: "wordpress", dockerImage: "wordpress:6.7" },
{ name: "WordPress 6.4 vierge", type: "wordpress", dockerImage: "wordpress:6.4" },
{ name: "PrestaShop latest vierge", type: "prestashop", dockerImage: "prestashop/prestashop:latest" },
{ name: "PrestaShop 8.1 vierge", type: "prestashop", dockerImage: "prestashop/prestashop:8.1" },
];
for (const t of templates) {
const composeConfig = `services:
app:
image: ${t.dockerImage}
ports:
- "127.0.0.1:{PORT}:80"
environment:
INSTANCE_ID: {INSTANCE_ID}
restart: unless-stopped
`;
await prisma.template.upsert({
where: { id: `${t.type}-${t.dockerImage.replace(/[:\/]/g, "-")}` },
update: {},
create: {
id: `${t.type}-${t.dockerImage.replace(/[:\/]/g, "-")}`,
name: t.name,
type: t.type,
dockerImage: t.dockerImage,
composeConfig,
isPublic: true,
createdBy: "system",
},
});
}
console.log("Seed completed.");
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
+57
View File
@@ -0,0 +1,57 @@
import type { Config } from "tailwindcss";
const config: Config = {
darkMode: ["class"],
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
},
},
plugins: [require("tailwindcss-animate")],
};
export default config;
+41
View File
@@ -0,0 +1,41 @@
{
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./*"
]
},
"target": "ES2017"
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}
+26
View File
@@ -0,0 +1,26 @@
import "next-auth";
declare module "next-auth" {
interface Session {
user: {
id: string;
email: string;
role: string;
establishmentId?: string;
};
}
interface User {
id: string;
email: string;
role: string;
establishmentId?: string;
}
}
declare module "next-auth/jwt" {
interface JWT {
role?: string;
establishmentId?: string;
}
}
Executable
+49
View File
@@ -0,0 +1,49 @@
#!/bin/bash
set -e
echo "=== EduBox V2 Setup ==="
# Configure UFW
echo "Configuring firewall..."
if command -v ufw &> /dev/null; then
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 1586/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow 3001/tcp
ufw allow 41641/udp
echo "UFW configured."
else
echo "UFW not found, skipping firewall config."
fi
# Change SSH port
if [ -f /etc/ssh/sshd_config ]; then
echo "Changing SSH port to 1586..."
sed -i 's/^#\?Port .*/Port 1586/' /etc/ssh/sshd_config
systemctl restart sshd || true
echo "SSH port changed to 1586."
fi
# Generate .env if missing
if [ ! -f .env ]; then
echo "Generating .env from .env.example..."
cp .env.example .env
echo "Please edit .env with your secure values before running docker compose."
else
echo ".env already exists, skipping generation."
fi
# Build and start
echo "Building and starting services..."
docker compose up -d --build
echo ""
echo "=== Setup complete ==="
echo "Server: http://localhost"
echo "Gitea: http://localhost:3001"
echo "SSH port: 1586"
echo ""
echo "Don't forget to update .env with secure passwords!"