From e182c0615c3415cf123dc0173e1fcf4f526fd719 Mon Sep 17 00:00:00 2001 From: Amen <2668333+amenophis1er@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:38:46 -0500 Subject: [PATCH] fix: scaffolded projects ship no known secret and get generated ones trokky create no longer writes a JWT secret fallback, a default admin password, or placeholder keys that switch Google sign-in, Resend mail or a captcha on with fake values. It writes a gitignored .env with generated TROKKY_JWT_SECRET and TROKKY_CLAIM_SECRET; without ADMIN_PASSWORD the first administrator claims the site (in the Studio, or POST /api/auth/claim for api-only). --- cmd/create.go | 9 ++- internal/scaffold/scaffold.go | 21 +++++++ internal/scaffold/scaffold_test.go | 98 ++++++++++++++++++++++++++++++ internal/scaffold/templates.go | 72 ++++++++++++++++------ 4 files changed, 179 insertions(+), 21 deletions(-) diff --git a/cmd/create.go b/cmd/create.go index 89a895f..e7670b6 100644 --- a/cmd/create.go +++ b/cmd/create.go @@ -141,10 +141,17 @@ Examples: fmt.Println(" Next steps:") fmt.Println() fmt.Printf(" cd %s\n", name) - fmt.Println(" cp .env.example .env # Configure your environment") fmt.Println(" npm install # Install dependencies") fmt.Println(" npm run dev # Start development server") fmt.Println() + fmt.Println(" .env holds freshly generated secrets and is not committed. On a server, set") + fmt.Println(" TROKKY_JWT_SECRET and TROKKY_CLAIM_SECRET to values of your own.") + if cfg.Studio == scaffold.StudioNone { + fmt.Println(" Claim the site with POST /api/auth/claim, using TROKKY_CLAIM_SECRET from .env.") + } else { + fmt.Println(" Open the Studio and claim the site, using TROKKY_CLAIM_SECRET from .env.") + } + fmt.Println() return nil }, diff --git a/internal/scaffold/scaffold.go b/internal/scaffold/scaffold.go index ea2dd63..3a68413 100644 --- a/internal/scaffold/scaffold.go +++ b/internal/scaffold/scaffold.go @@ -1,7 +1,11 @@ package scaffold import ( + "crypto/rand" + "encoding/base64" + "errors" "fmt" + "io/fs" "os" "path/filepath" ) @@ -62,5 +66,22 @@ func Scaffold(cfg ProjectConfig, targetDir string) error { } } + // A .env with generated secrets (gitignored), unless one is already there + envPath := filepath.Join(targetDir, ".env") + if _, err := os.Stat(envPath); errors.Is(err, fs.ErrNotExist) { + if err := os.WriteFile(envPath, []byte(GenerateEnv(cfg, newSecret)), 0600); err != nil { + return fmt.Errorf("failed to write %s: %w", envPath, err) + } + } + return nil } + +// newSecret is 48 random bytes, base64: what `openssl rand -base64 48` prints +func newSecret() string { + b := make([]byte, 48) + if _, err := rand.Read(b); err != nil { + panic(fmt.Sprintf("no randomness for a secret: %v", err)) + } + return base64.StdEncoding.EncodeToString(b) +} diff --git a/internal/scaffold/scaffold_test.go b/internal/scaffold/scaffold_test.go index ef6078b..06d3c10 100644 --- a/internal/scaffold/scaffold_test.go +++ b/internal/scaffold/scaffold_test.go @@ -261,3 +261,101 @@ func TestValidateRejectsRemovedAdapters(t *testing.T) { } } } + +// A scaffolded project must not carry a secret anyone who has read this code knows: a fallback +// JWT key lets them sign tokens, a default admin password lets them sign in. +func TestScaffoldShipsNoKnownSecrets(t *testing.T) { + for name, cfg := range testConfigs() { + t.Run(name, func(t *testing.T) { + config := GenerateTrokkyConfig(cfg) + env := GenerateEnvExample(cfg) + for _, known := range []string{"change-me", "change-in-production", "your-secret", "admin123"} { + if strings.Contains(config, known) || strings.Contains(env, known) { + t.Errorf("generated project contains the known value %q", known) + } + } + if !strings.Contains(config, "jwtSecret: process.env.TROKKY_JWT_SECRET,") { + t.Errorf("jwtSecret should read TROKKY_JWT_SECRET with no fallback:\n%s", config) + } + if !strings.Contains(config, "adminUser: process.env.ADMIN_PASSWORD ? {") { + t.Errorf("the admin user should only be created when ADMIN_PASSWORD is set:\n%s", config) + } + for _, line := range []string{"TROKKY_JWT_SECRET=\n", "TROKKY_CLAIM_SECRET=\n", "ADMIN_PASSWORD=\n"} { + if !strings.Contains(env, line) { + t.Errorf(".env.example should leave %q empty, to be generated:\n%s", strings.TrimSpace(line), env) + } + } + }) + } +} + +func TestScaffoldWritesADotEnvWithGeneratedSecrets(t *testing.T) { + for name, cfg := range testConfigs() { + t.Run(name, func(t *testing.T) { + dir := filepath.Join(t.TempDir(), "site") + if err := Scaffold(cfg, dir); err != nil { + t.Fatal(err) + } + env, err := os.ReadFile(filepath.Join(dir, ".env")) + if err != nil { + t.Fatalf(".env was not written: %v", err) + } + secrets := map[string]string{} + for _, line := range strings.Split(string(env), "\n") { + for _, key := range []string{"TROKKY_JWT_SECRET", "TROKKY_CLAIM_SECRET"} { + if strings.HasPrefix(line, key+"=") { + secrets[key] = strings.TrimPrefix(line, key+"=") + } + } + } + for _, key := range []string{"TROKKY_JWT_SECRET", "TROKKY_CLAIM_SECRET"} { + if len(secrets[key]) < 60 { + t.Errorf("%s = %q, want a generated value", key, secrets[key]) + } + } + if secrets["TROKKY_JWT_SECRET"] == secrets["TROKKY_CLAIM_SECRET"] { + t.Error("the two secrets must differ") + } + info, _ := os.Stat(filepath.Join(dir, ".env")) + if info.Mode().Perm() != 0o600 { + t.Errorf(".env mode = %v, want 0600", info.Mode().Perm()) + } + example, _ := os.ReadFile(filepath.Join(dir, ".env.example")) + if !strings.Contains(string(example), "\nTROKKY_JWT_SECRET=\n") { + t.Error(".env.example must keep the secret empty") + } + }) + } +} + +func TestScaffoldKeepsAnExistingDotEnv(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, ".env"), []byte("MINE=1\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := Scaffold(TemplateDefaults[TemplateMinimal], dir); err != nil { + t.Fatal(err) + } + if env, _ := os.ReadFile(filepath.Join(dir, ".env")); string(env) != "MINE=1\n" { + t.Errorf(".env was overwritten: %q", env) + } +} + +func TestScaffoldShipsNoPlaceholderThatSwitchesAFeatureOn(t *testing.T) { + cfg := TemplateDefaults[TemplateFull] + env := GenerateEnvExample(cfg) + for _, placeholder := range []string{"your-client-id", "your-client-secret", "re_xxxxx", "your-site-key"} { + if strings.Contains(env, placeholder) { + t.Errorf(".env.example contains the placeholder %q", placeholder) + } + } +} + +func TestClaimInstructionsMatchTheTemplate(t *testing.T) { + if got := claimWhere(TemplateDefaults[TemplateAPIOnly]); !strings.Contains(got, "POST /api/auth/claim") { + t.Errorf("api-only: %q", got) + } + if got := claimWhere(TemplateDefaults[TemplateMinimal]); !strings.Contains(got, "Studio") { + t.Errorf("minimal: %q", got) + } +} diff --git a/internal/scaffold/templates.go b/internal/scaffold/templates.go index 2e7259c..922514d 100644 --- a/internal/scaffold/templates.go +++ b/internal/scaffold/templates.go @@ -347,14 +347,19 @@ export default { security: { enabled: true, - jwtSecret: process.env.JWT_SECRET || 'change-me-in-production', - adminUser: { + // No fallback: a fallback is a key anyone who has read this file can sign tokens with. + // trokky create generated one into .env; set your own on the server. + jwtSecret: process.env.TROKKY_JWT_SECRET, + // Created on first start when ADMIN_PASSWORD is set. Without it nobody is created, and the + // first person to claim the site (%s) becomes its administrator: keep + // TROKKY_CLAIM_SECRET set so only someone who has it can. + adminUser: process.env.ADMIN_PASSWORD ? { username: process.env.ADMIN_USERNAME || 'admin', email: process.env.ADMIN_EMAIL || 'admin@example.com', - password: process.env.ADMIN_PASSWORD || 'admin123', + password: process.env.ADMIN_PASSWORD, firstName: 'Admin', lastName: 'User', - }, + } : undefined, passkey: process.env.PASSKEY_RP_ID ? { enabled: true, rpId: process.env.PASSKEY_RP_ID, @@ -380,24 +385,48 @@ export default { },%s%s%s%s%s } `, schemaImports, mailImport, structureImport, mailConsts, schemas, - dataConfig, mediaConfig, cfg.Name, + dataConfig, mediaConfig, claimWhere(cfg), cfg.Name, oauthConfig, mailConfig, captchaConfig, studioConfig, i18nConfig) } +// claimWhere says where a project's first administrator claims the site. +func claimWhere(cfg ProjectConfig) string { + if cfg.Studio == StudioNone { + return "POST /api/auth/claim, there is no Studio" + } + return "in the Studio, on first visit" +} + +// GenerateEnv is .env.example with fresh secrets filled in: the file trokky create writes as +// .env, so development keeps its sign-ins across restarts without anyone inventing a key. +func GenerateEnv(cfg ProjectConfig, secret func() string) string { + env := GenerateEnvExample(cfg) + for _, name := range []string{"TROKKY_JWT_SECRET", "TROKKY_CLAIM_SECRET"} { + env = strings.Replace(env, "\n"+name+"=\n", "\n"+name+"="+secret()+"\n", 1) + } + return env +} + // GenerateEnvExample generates the .env.example file. func GenerateEnvExample(cfg ProjectConfig) string { lines := []string{ - "# Server", + "# Server (set NODE_ENV=production on the server: it turns on the production checks)", "PORT=3000", "NODE_ENV=development", "", - "# Security", - "JWT_SECRET=your-secret-key-change-in-production", + "# Security. Generate each value, do not invent it: openssl rand -base64 48", + "# (trokky create wrote generated ones into .env.)", + "# Signs sessions and tokens. It must stay the same across restarts and deploys, or", + "# every sign-in ends. Without it, newer Trokky versions refuse to start in production.", + "TROKKY_JWT_SECRET=", + "# Asked for by the first-boot claim (below), so only someone who has it can claim the site.", + "TROKKY_CLAIM_SECRET=", "", - "# Admin User", + "# Admin user, created on first start when ADMIN_PASSWORD is set. Leave it empty to", + fmt.Sprintf("# claim the site instead (%s).", claimWhere(cfg)), "ADMIN_USERNAME=admin", "ADMIN_EMAIL=admin@example.com", - "ADMIN_PASSWORD=admin123", + "ADMIN_PASSWORD=", } if cfg.Studio != StudioNone { @@ -414,27 +443,30 @@ func GenerateEnvExample(cfg ProjectConfig) string { "TROKKY_MAIL_ENABLED=true", fmt.Sprintf("TROKKY_MAIL_PROVIDER=%s", cfg.Mail)) if cfg.Mail == MailResend { - lines = append(lines, "RESEND_API_KEY=re_xxxxx") + // Empty, not a placeholder: with no key the console adapter prints mail instead + lines = append(lines, "# From the Resend dashboard; mail is printed to the console until set", "RESEND_API_KEY=") } lines = append(lines, "EMAIL_FROM=noreply@example.com", "EMAIL_FROM_NAME=My App") } if cfg.Auth == AuthOAuth { - lines = append(lines, "", "# OAuth (Google)", - "GOOGLE_CLIENT_ID=your-client-id", - "GOOGLE_CLIENT_SECRET=your-client-secret", + // Empty, not a placeholder: a set client id shows a Google button that cannot work + lines = append(lines, "", "# OAuth (Google; from the Google Cloud console, sign-in with Google is off until set)", + "GOOGLE_CLIENT_ID=", + "GOOGLE_CLIENT_SECRET=", "GOOGLE_REDIRECT_URI=http://localhost:3000/api/auth/google/callback") } if cfg.Captcha == CaptchaTurnstile { - lines = append(lines, "", "# Cloudflare Turnstile", - "TURNSTILE_SITE_KEY=your-site-key", - "TURNSTILE_SECRET_KEY=your-secret-key") + // Empty, not a placeholder: a set secret key turns the captcha on, and a made-up one fails every form + lines = append(lines, "", "# Cloudflare Turnstile (keys from the Cloudflare dashboard; captcha is off until set)", + "TURNSTILE_SITE_KEY=", + "TURNSTILE_SECRET_KEY=") } if cfg.Captcha == CaptchaRecaptcha { - lines = append(lines, "", "# Google reCAPTCHA", - "RECAPTCHA_SITE_KEY=your-site-key", - "RECAPTCHA_SECRET_KEY=your-secret-key") + lines = append(lines, "", "# Google reCAPTCHA (keys from the reCAPTCHA admin console; captcha is off until set)", + "RECAPTCHA_SITE_KEY=", + "RECAPTCHA_SECRET_KEY=") } lines = append(lines, "",