@getstrata/starter 2.2.44 → 2.2.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,7 +28,7 @@ The wizard asks for each layer. In a terminal, lists use up/down and Enter, or a
28
28
 
29
29
  Layer flags: `--frontend`, `--database`, `--auth`, `--tenancy`, `--cache`, `--queue`, `--mail`, `--spa-prefix`, plus extras (`--mfa`, `--email-verification`, `--scim`, `--metrics`) and their `--no-` forms.
30
30
 
31
- Pick one database engine. Docker Compose is optional (`--docker`, `--no-docker`, `--docker-services=postgres,redis`) and only includes services for the tools you selected. `--docker` with Postgres or MySQL also writes Adminer on port 8080.
31
+ Pick one database engine. Docker Compose is optional (`--docker`, `--no-docker`, `--docker-services=postgres,redis`) and only includes services for the tools you selected. The wizard offers optional Adminer in both Docker and Mix modes when the database is in Compose. `--docker` alone includes required services only; add Adminer explicitly with `--docker-services=mysql,mailpit,adminer` (or `postgres`). When selected, start its debug profile with `docker compose --profile debug up -d --wait --wait-timeout 180`; open http://localhost:8080.
32
32
 
33
33
  ## What you get
34
34
 
package/dist/cli.js CHANGED
@@ -2,9 +2,29 @@
2
2
  // @bun
3
3
 
4
4
  // src/generate.ts
5
- import { copyFileSync, existsSync as existsSync2, mkdirSync as mkdirSync2, rmSync as rmSync2 } from "fs";
5
+ import { copyFileSync, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, rmSync as rmSync2 } from "fs";
6
6
  import { basename, join as join2, resolve } from "path";
7
7
 
8
+ // ../../src/core/runtime/frontendMode.ts
9
+ var FRONTEND_MODES = ["api", "server-htmx", "spa-react", "hybrid"];
10
+ var DEFAULT_SPA_PREFIX = "/app";
11
+ var FRONTEND_MODE_PATTERN = new RegExp(`^(${FRONTEND_MODES.join("|")})$`);
12
+ function normalizeSpaPrefix(value) {
13
+ const raw = (value ?? DEFAULT_SPA_PREFIX).trim() || DEFAULT_SPA_PREFIX;
14
+ const withSlash = raw.startsWith("/") ? raw : `/${raw}`;
15
+ const trimmed = withSlash.replace(/\/+$/, "");
16
+ if (trimmed.length === 0 || trimmed === "/") {
17
+ return DEFAULT_SPA_PREFIX;
18
+ }
19
+ return trimmed;
20
+ }
21
+ function validateSpaPrefix(value) {
22
+ const prefix = normalizeSpaPrefix(value);
23
+ if (!/^\/[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*$/.test(prefix) || prefix.split("/").some((part) => part === "." || part === "..") || prefix === "/api" || prefix.startsWith("/api/") || prefix === "/assets" || prefix.startsWith("/assets/") || ["/health", "/ready", "/metrics"].includes(prefix))
24
+ throw new Error("SPA_PREFIX must be a dedicated URL path outside API, assets and health/metrics routes.");
25
+ return prefix;
26
+ }
27
+
8
28
  // src/copy.ts
9
29
  import {
10
30
  existsSync,
@@ -171,6 +191,9 @@ function selectedDockerServices(layers) {
171
191
  }
172
192
  return selected;
173
193
  }
194
+ function dockerComposeUpCommand(layers) {
195
+ return selectedDockerServices(layers).includes("adminer") ? "docker compose --profile debug up -d --wait --wait-timeout 180" : "docker compose up -d --wait --wait-timeout 180";
196
+ }
174
197
  function reconcileDocker(layers) {
175
198
  const selected = selectedDockerServices(layers);
176
199
  return {
@@ -547,6 +570,7 @@ function applyFlagOverrides(base, flags) {
547
570
  console.warn(`Using --tenancy column: rls is Postgres-only (SET LOCAL app.tenant_id) and ${next.database} has no equivalent.`);
548
571
  next.tenancy = "column";
549
572
  }
573
+ next.spaPrefix = validateSpaPrefix(next.spaPrefix);
550
574
  dropInapplicableExtras(next, flags);
551
575
  return reconcileDocker(applyDockerFlags(next, flags));
552
576
  }
@@ -1110,12 +1134,11 @@ async function promptDockerLayer(prompter, layers) {
1110
1134
  if (mode === "local") {
1111
1135
  return dockerLayerForNeeded(layers, false);
1112
1136
  }
1113
- if (mode === "docker") {
1114
- return dockerLayerForNeeded(layers, true);
1115
- }
1116
- const services = emptyDockerServices();
1117
- for (const name of needed) {
1118
- services[name] = await prompter.confirm(`Docker Compose for ${DOCKER_SERVICE_LABELS[name]}?`, true);
1137
+ const services = mode === "docker" ? dockerLayerForNeeded(layers, true).services : emptyDockerServices();
1138
+ if (mode === "mix") {
1139
+ for (const name of needed) {
1140
+ services[name] = await prompter.confirm(`Docker Compose for ${DOCKER_SERVICE_LABELS[name]}?`, true);
1141
+ }
1119
1142
  }
1120
1143
  const databaseService = dockerDatabaseService(layers.database);
1121
1144
  if (databaseService && services[databaseService]) {
@@ -1173,7 +1196,7 @@ function renderAuthModule(layers) {
1173
1196
  const mfa = Boolean(layers.extras.mfa && cookie);
1174
1197
  const verify = Boolean(layers.extras.emailVerification);
1175
1198
  const bearerApi = authUsesToken(layers.auth) || authUsesJwt(layers.auth);
1176
- const jsonCookieAccounts = cookie && (layers.frontend === "api" || layers.frontend === "spa-react");
1199
+ const jsonCookieAccounts = cookie && (layers.frontend === "api" || layers.frontend === "spa-react" || layers.frontend === "hybrid");
1177
1200
  const jsonAccounts = bearerApi || jsonCookieAccounts;
1178
1201
  const tenantInsert = usesTenantTable(layers.tenancy);
1179
1202
  const tenantCreateField = tenantInsert ? `
@@ -2586,48 +2609,17 @@ ${tokenLookup}
2586
2609
  function renderAuthProvider(layers) {
2587
2610
  if (layers.auth === "headers") {
2588
2611
  return `import { CORE_AUTH_TOKEN } from "@getstrata/bootstrap/config";
2589
- import type { AuthUser } from "@getstrata/core/auth/authContext";
2590
- import { currentAuthUser } from "@getstrata/core/auth/authContext";
2612
+ import { AuthManager, GuestGuard } from "@getstrata/core/auth/guard";
2591
2613
  import type { ServiceProvider } from "@getstrata/core/contracts/di";
2592
2614
  import { envFlagEnabled } from "@getstrata/core/runtime/appEnv";
2593
2615
 
2594
- class StarterAuthManager {
2595
- async resolveWithSource(request?: Request) {
2596
- const user = await this.resolve(request);
2597
- return { user, credentialSource: user ? "guest" as const : null };
2598
- }
2599
-
2600
- async resolve(request?: Request): Promise<AuthUser | null> {
2601
- if (!envFlagEnabled(process.env.AUTH_DEV_HEADERS)) {
2602
- return request ? null : currentAuthUser();
2603
- }
2604
- if (request) {
2605
- const userId = request.headers.get("x-authenticated-user-id");
2606
- if (!userId) {
2607
- return null;
2608
- }
2609
- const role = request.headers.get("x-authenticated-user-role");
2610
- return {
2611
- id: userId,
2612
- ...(role ? { role } : {}),
2613
- };
2614
- }
2615
- return currentAuthUser();
2616
- }
2617
-
2618
- user(request?: Request) {
2619
- return this.resolve(request);
2620
- }
2621
-
2622
- async check(request: Request) {
2623
- return (await this.user(request)) !== null;
2624
- }
2625
- }
2626
-
2627
2616
  const authProvider: ServiceProvider = {
2628
2617
  name: "starter.auth",
2629
2618
  register({ container }) {
2630
- container.set(CORE_AUTH_TOKEN, new StarterAuthManager());
2619
+ const guard = envFlagEnabled(process.env.AUTH_DEV_HEADERS)
2620
+ ? new GuestGuard()
2621
+ : { resolve: () => null };
2622
+ container.set(CORE_AUTH_TOKEN, new AuthManager(guard));
2631
2623
  },
2632
2624
  };
2633
2625
 
@@ -2932,6 +2924,10 @@ function renderEnvExample(projectName, layers) {
2932
2924
  `DATABASE_URL=${defaultDatabaseUrl(layers, projectName)}`,
2933
2925
  ...postgresAppRoleEnvNotes(layers),
2934
2926
  ...layers.database === "postgres" ? [`MIGRATION_DATABASE_URL=${defaultMigrationDatabaseUrl(layers, projectName)}`] : [],
2927
+ ...layers.database === "mysql" ? [
2928
+ "# Optional schema-administration URL for the same database; runtime may lack DDL.",
2929
+ "# MIGRATION_DATABASE_URL="
2930
+ ] : [],
2935
2931
  ...layers.database === "sqlite" ? [] : [
2936
2932
  "# Optional. Point runtime at a different database than DATABASE_URL.",
2937
2933
  "# APP_DATABASE_URL="
@@ -3081,6 +3077,14 @@ function renderEnvExample(projectName, layers) {
3081
3077
  `)}
3082
3078
  `;
3083
3079
  }
3080
+ function renderServiceHealthcheck(test) {
3081
+ return ` healthcheck:
3082
+ test: ${JSON.stringify(test)}
3083
+ interval: 2s
3084
+ timeout: 3s
3085
+ retries: 60
3086
+ start_period: 5s`;
3087
+ }
3084
3088
  function renderDockerCompose(projectName, layers) {
3085
3089
  const selected = selectedDockerServices(layers);
3086
3090
  if (selected.length === 0) {
@@ -3096,6 +3100,7 @@ function renderDockerCompose(projectName, layers) {
3096
3100
  POSTGRES_USER: postgres
3097
3101
  POSTGRES_PASSWORD: ${GENERATED_POSTGRES_SUPERUSER_PASSWORD}
3098
3102
  POSTGRES_DB: ${database}
3103
+ ${renderServiceHealthcheck(["CMD-SHELL", 'PGPASSWORD="$$POSTGRES_PASSWORD" psql -h 127.0.0.1 -U "$$POSTGRES_USER" -d "$$POSTGRES_DB" -tAc "SELECT 1" >/dev/null'])}
3099
3104
  ports:
3100
3105
  # Localhost only. Do not publish this port on a production host.
3101
3106
  - "127.0.0.1:5432:5432"
@@ -3110,6 +3115,7 @@ function renderDockerCompose(projectName, layers) {
3110
3115
  environment:
3111
3116
  MYSQL_ROOT_PASSWORD: ${GENERATED_MYSQL_ROOT_PASSWORD}
3112
3117
  MYSQL_DATABASE: ${database}
3118
+ ${renderServiceHealthcheck(["CMD-SHELL", 'MYSQL_PWD="$$MYSQL_ROOT_PASSWORD" mysql --protocol=tcp -h 127.0.0.1 -u root -D "$$MYSQL_DATABASE" -N -e "SELECT 1" >/dev/null'])}
3113
3119
  ports:
3114
3120
  - "127.0.0.1:3306:3306"
3115
3121
  volumes:
@@ -3124,13 +3130,18 @@ function renderDockerCompose(projectName, layers) {
3124
3130
  environment:
3125
3131
  ADMINER_DEFAULT_SERVER: ${server}
3126
3132
  depends_on:
3127
- - ${server}
3133
+ ${server}:
3134
+ condition: service_healthy
3135
+ ${renderServiceHealthcheck(["CMD", "php", "-r", "exit(@file_get_contents('http://127.0.0.1:8080/') === false ? 1 : 0);"])}
3128
3136
  ports:
3129
3137
  - "127.0.0.1:8080:8080"`);
3130
3138
  }
3131
3139
  if (selectedSet.has("redis")) {
3132
3140
  services.push(` redis:
3133
3141
  image: redis:7-alpine
3142
+ environment:
3143
+ REDIS_PASSWORD: "\${REDIS_PASSWORD:-dev-redis-change-me}"
3144
+ ${renderServiceHealthcheck(["CMD-SHELL", 'REDISCLI_AUTH="$$REDIS_PASSWORD" redis-cli --no-auth-warning ping | grep -qx PONG'])}
3134
3145
  command: ["redis-server", "--requirepass", "\${REDIS_PASSWORD:-dev-redis-change-me}"]
3135
3146
  ports:
3136
3147
  - "127.0.0.1:6379:6379"`);
@@ -3138,6 +3149,7 @@ function renderDockerCompose(projectName, layers) {
3138
3149
  if (selectedSet.has("mailpit")) {
3139
3150
  services.push(` mailpit:
3140
3151
  image: axllent/mailpit:latest
3152
+ ${renderServiceHealthcheck(["CMD", "/mailpit", "readyz"])}
3141
3153
  ports:
3142
3154
  - "127.0.0.1:1025:1025"
3143
3155
  - "127.0.0.1:8025:8025"`);
@@ -3184,7 +3196,7 @@ function renderDockerfile(layers) {
3184
3196
  ""
3185
3197
  ];
3186
3198
  if (frontend) {
3187
- lines.push("FROM oven/bun:1.4.3 AS frontend", "WORKDIR /app/frontend", "COPY frontend/package.json frontend/bun.lock ./", "RUN bun install --frozen-lockfile", "COPY frontend/ ./", "RUN bun run build", "");
3199
+ lines.push("FROM oven/bun:1.4.3 AS frontend", "WORKDIR /app/frontend", "COPY --from=deps /app/node_modules /app/node_modules", "ARG SPA_PREFIX", "ENV SPA_PREFIX=$SPA_PREFIX", "COPY frontend/package.json frontend/bun.lock ./", "RUN bun install --frozen-lockfile", "COPY frontend/ ./", "RUN bun run build", "");
3188
3200
  }
3189
3201
  lines.push("FROM oven/bun:1.4.3-slim AS runtime", "WORKDIR /app", "ENV APP_ENV=production", "ENV AUTH_DEV_HEADERS=false", "ENV PORT=3000", "COPY --from=deps /app/node_modules ./node_modules", "COPY . .");
3190
3202
  if (frontend) {
@@ -3226,9 +3238,9 @@ function renderPackageJson(projectName, options = {}) {
3226
3238
  "@getstrata/cli": "workspace:*",
3227
3239
  "@getstrata/core": "workspace:*"
3228
3240
  } : {
3229
- "@getstrata/bootstrap": "^2.2.44",
3230
- "@getstrata/cli": "^2.2.44",
3231
- "@getstrata/core": "^2.2.44"
3241
+ "@getstrata/bootstrap": "^2.2.46",
3242
+ "@getstrata/cli": "^2.2.46",
3243
+ "@getstrata/core": "^2.2.46"
3232
3244
  };
3233
3245
  coreDeps.eta = "^4.6.0";
3234
3246
  if (options.layers?.database === "mysql") {
@@ -3298,7 +3310,7 @@ function localEnvVars(services) {
3298
3310
  }
3299
3311
  return [...new Set(vars)];
3300
3312
  }
3301
- function renderSupportingToolsReadme(layers) {
3313
+ function renderSupportingToolsReadme(projectName, layers) {
3302
3314
  const needed = neededDockerServices(layers);
3303
3315
  if (needed.length === 0) {
3304
3316
  return "";
@@ -3309,14 +3321,14 @@ function renderSupportingToolsReadme(layers) {
3309
3321
  const lines = ["## Supporting tools", ""];
3310
3322
  if (dockerOn.length > 0) {
3311
3323
  const names = dockerOn.map((name) => DOCKER_SERVICE_LABELS[name]).join(", ");
3312
- lines.push(`Docker Compose includes ${names}.`, "", "```bash", "docker compose up -d", "```", "");
3324
+ lines.push(`Docker Compose includes ${names}.`, "", "```bash", dockerComposeUpCommand(layers), "```", "", "Wait for this command to succeed before migrating. It waits up to 180 seconds for selected services to be healthy; inspect `docker compose ps` and `docker compose logs` if it fails. Increasing `--wait-timeout` can accommodate a slow first initialization. These checks do not run application migrations.", "");
3313
3325
  if (dockerSet.has("adminer")) {
3314
3326
  const mysql = layers.database === "mysql";
3315
3327
  const system = mysql ? "MySQL" : "PostgreSQL";
3316
3328
  const server = mysql ? "mysql" : "postgres";
3317
3329
  const username = mysql ? "root" : "postgres";
3318
3330
  const password = mysql ? GENERATED_MYSQL_ROOT_PASSWORD : GENERATED_POSTGRES_SUPERUSER_PASSWORD;
3319
- lines.push(`Adminer: http://localhost:8080 (${system}, server \`${server}\`, username \`${username}\`, password \`${password}\`).`, "");
3331
+ lines.push(`Adminer: http://localhost:8080 (${system}, server \`${server}\`, username \`${username}\`, password \`${password}\`, database \`${appDatabaseName(projectName)}\`).`, "", "Adminer is optional development tooling in the `debug` profile; plain `docker compose up -d` does not start Adminer. Use the profile command above to start it with the database.", "");
3320
3332
  if (!mysql) {
3321
3333
  lines.push("Adminer uses the Compose `postgres` superuser, which skips FORCE RLS. Application traffic should use `strata_app`.", "");
3322
3334
  }
@@ -3484,7 +3496,7 @@ function renderReadme(projectName, layers, options = {}) {
3484
3496
  const docker = renderDockerCompose(projectName, layers);
3485
3497
  const next = [`cd ${projectName}`, "cp .env.example .env"];
3486
3498
  if (docker) {
3487
- next.push("docker compose up -d");
3499
+ next.push(dockerComposeUpCommand(layers));
3488
3500
  }
3489
3501
  next.push("bun install");
3490
3502
  if (needsFrontendBuild(layers.frontend)) {
@@ -3527,7 +3539,7 @@ ${layers.queue === "redis" ? "Redis jobs need `bun run queue:work` in another te
3527
3539
 
3528
3540
  `}For durable events, add listeners in \`src/outbox/registry.ts\`, apply \`bun run db:migrate\`, then run \`bun run outbox:work\` in another terminal. Apps that do not publish durable events do not need this worker. Durable cache invalidation also needs the outbox worker when explicitly configured. Use the same application environment, database, Redis URL and \`APP_KEY_PREFIX\` for HTTP and its workers. An idle worker is normal; startup output confirms entry into polling, not dependency health. Stop HTTP and workers before resetting the development database.
3529
3541
 
3530
- ${renderSupportingToolsReadme(layers)}${layers.auth !== "headers" ? `
3542
+ ${renderSupportingToolsReadme(projectName, layers)}${layers.auth !== "headers" ? `
3531
3543
  For the first production admin, apply migrations and run \`bunx strata auth:provision-admin --email operator@example.test --name "Initial Operator" --password-stdin${layers.tenancy !== "none" ? " --tenant 1" : ""} < /run/secrets/initial_admin_password\` before admitting traffic. Supply your own private secret-manager-mounted file, not a demo password. Passwords require at least 16 characters and at most 72 UTF-8 bytes. Tenant-enabled applications require an existing tenant ID; this command does not create tenants. It refuses existing admins/accounts, records a transactional one-time claim, and does not mark email verified or enroll MFA. Additional admins and recovery remain explicit application administration. The command does not migrate or seed automatically.
3532
3544
 
3533
3545
  Optional development demo accounts: run \`bun run db:seed:demo\` explicitly after migrations. This command refuses production and staging. It creates these accounts with password \`StrataDemo!ChangeMe\`:
@@ -3546,7 +3558,7 @@ HTML auth kit (restyle \`views/\` and \`public/assets/site.css\`):
3546
3558
  - Reset password: signed \`/reset-password\` (mail log when \`MAIL_DRIVER=log\`)
3547
3559
  ${layers.extras.emailVerification ? "- Verify email: `/email/verify`\n" : ""}${layers.extras.mfa ? "- MFA challenge: `/login/mfa` and setup: `/account/mfa`\n" : ""}${layers.extras.oauthGithub ? "- GitHub: `/auth/github` (needs `FEATURE_OAUTH=true`). Failures on the callback are JSON, not the login page. State is the signed query value from `createOAuthState()`, not `createOAuthStateCookie()`.\n" : ""}${layers.extras.oidc ? "- OIDC: `/auth/oidc` (needs `FEATURE_OAUTH=true` plus `OIDC_CLIENT_ID` and `OIDC_CLIENT_SECRET`; otherwise the login link stays hidden and the route is 404). PKCE cookie `oidc_pkce`. Callback failures are JSON, not the login page.\n" : ""}
3548
3560
  Cookie name is \`strata_session\`. Forms send CSRF as \`_token\`.
3549
- ` : ""}${authUsesCookie(layers.auth) && (layers.frontend === "api" || layers.frontend === "spa-react") ? `
3561
+ ` : ""}${authUsesCookie(layers.auth) && (layers.frontend === "api" || layers.frontend === "spa-react" || layers.frontend === "hybrid") ? `
3550
3562
  JSON cookie account flows: fetch \`GET /api/v1/auth/csrf\`, retain the cookie and send \`X-CSRF-Token\` on writes (browser clients use credentials). Register through \`POST /api/v1/auth/register\` (neutral 201), login through \`POST /api/v1/auth/login\` (session cookie), and read \`GET /api/v1/auth/me\`. Reset through \`POST /api/v1/auth/forgot-password\` then signed \`POST /api/v1/auth/reset-password\` with \`{ password }\`.
3551
3563
  ${layers.extras.emailVerification ? "Verify through signed `POST /api/v1/auth/verify-email`; authenticated unverified owners resend through `POST /api/v1/auth/verification-notification`.\n" : ""}${layers.extras.mfa ? "MFA setup: `GET /api/v1/auth/mfa`, confirm the current password through `POST /api/v1/auth/confirm-password`, then submit `{ secret, code }` to `POST /api/v1/auth/mfa`. Store the returned recovery codes safely; enrollment revokes credentials. Login again with `{ email, password, mfa_code }` using a TOTP or one-use recovery code. Missing code returns JSON 401 `mfa_required`.\n" : ""}
3552
3564
  These routes return JSON, not account pages. The client owns account forms and handling the signed mail URL: submit to its unchanged path/query, with CSRF; opening the URL with GET does not consume a token. No HTML registration/reset page or automatic login is generated for these modes. All auth JSON is private/no-store. API docs list routes; the SPA scaffold is an example client, not a complete account-management UI.
@@ -3618,6 +3630,7 @@ The image sets \`APP_ENV=production\` and \`AUTH_DEV_HEADERS=false\`; everything
3618
3630
  - Behind a reverse proxy or load balancer, set \`TRUST_FORWARDED_FOR=true\` so throttles and session records see the client address instead of the proxy. Only the rightmost public hop of \`X-Forwarded-For\` is trusted.
3619
3631
  ${authUsesCookie(layers.auth) ? "- Set `SESSION_SECRET` to 32+ characters.\n" : ""}${authUsesToken(layers.auth) ? "- Set `TOKEN_HASH_PEPPER`.\n" : ""}${layers.extras.scim ? "- Set `SCIM_BEARER_TOKEN`.\n" : ""}${layers.extras.metrics ? "- Set `METRICS_TOKEN`.\n" : ""}${layers.extras.oauthGithub ? "- Set `OAUTH_STATE_SECRET` and `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`.\n" : ""}${layers.extras.oidc ? "- Set `OAUTH_STATE_SECRET`, `OIDC_ISSUER`, `OIDC_CLIENT_ID`, and `OIDC_CLIENT_SECRET`. Loopback issuers work outside production; set `OIDC_ALLOW_PRIVATE=true` for other private IdPs.\n" : ""}${layers.extras.billing ? "- Set `STRIPE_WEBHOOK_SECRET` when `FEATURE_BILLING=true`.\n" : ""}${layers.tenancy === "rls" ? `- \`DATABASE_URL\` must be a \`NOBYPASSRLS\` role, not the \`postgres\` superuser. Generated apps create \`${GENERATED_POSTGRES_APP_ROLE}\` via \`db/ensure-postgres-app-role.sql\` (and Compose init on first empty volume). \`MIGRATION_DATABASE_URL\` and an explicit non-development \`STRATA_APP_PASSWORD\` belong only to the migrate/provisioning process. HTTP/workers connect to the existing role without admin credentials or role/password writes. Production boot rejects username \`postgres\` or \`root\`, then inspects \`pg_roles\` for \`rolsuper\` / \`rolbypassrls\`.
3620
3632
  ` : ""}
3633
+ ${layers.database === "mysql" ? "- Keep the MySQL runtime account limited to application reads/writes. Set `MIGRATION_DATABASE_URL` for the same database only in the administrative migration process; provisioning and migration callbacks use that connection and close it afterward. If unset, explicit migration commands require DDL privileges on the configured account.\n" : ""}
3621
3634
  \`strata start\` does not migrate when \`APP_ENV=production\`. Run \`bun run db:migrate\` as a deploy step. \`GET /health\` is 200 when \`notes\` is readable (including zero rows) and configured dependencies are available; it returns only \`ok\` or \`degraded\` without authentication or tenant selection, and 503 when a dependency or schema check fails. Use it for readiness, not process liveness. Redis jobs need a worker: \`bun run queue:work\` (requires \`REDIS_URL\`).
3622
3635
  `;
3623
3636
  }
@@ -3628,6 +3641,7 @@ function renderInitialAdminMigration(layers) {
3628
3641
  return null;
3629
3642
  const driver = layers.database === "postgres" ? "pgsql" : layers.database;
3630
3643
  return `import { Schema } from "@getstrata/core/database/schema";
3644
+ import { guardMigrationRollback } from "@getstrata/core/database/migrations";
3631
3645
  import type { Migration } from "@getstrata/core/database/migrations/types";
3632
3646
 
3633
3647
  const migration: Migration = {
@@ -3641,10 +3655,11 @@ const migration: Migration = {
3641
3655
  });
3642
3656
  });
3643
3657
  },
3644
- async down(db) {
3645
- if ((await db.unsafe("SELECT id FROM initial_admin_provisioning")).length) {
3646
- throw new Error("Cannot discard a completed initial-admin provisioning claim.");
3647
- }
3658
+ async down(db, context) {
3659
+ await guardMigrationRollback(context, {
3660
+ hasHistory: async () => (await db.unsafe("SELECT id FROM initial_admin_provisioning")).length > 0,
3661
+ message: "Cannot discard a completed initial-admin provisioning claim.",
3662
+ });
3648
3663
  await Schema.run(db, "${driver}", schema => { schema.drop("initial_admin_provisioning"); });
3649
3664
  },
3650
3665
  };
@@ -4080,6 +4095,33 @@ export async function withMigrationDatabase<T>(
4080
4095
  await admin.close?.();
4081
4096
  }
4082
4097
  }
4098
+ `;
4099
+ }
4100
+ if (layers.database === "mysql") {
4101
+ return `import { join } from "node:path";
4102
+ import { loadMigrationsFromDirectory } from "@getstrata/core/database/migrations";
4103
+ import type { MigrationDatabase } from "@getstrata/core/database/migrations/types";
4104
+ import { createMysqlConnection } from "@getstrata/core/database/mysqlConnection";
4105
+ import { runWithDatabaseConnection } from "@getstrata/core/database/connectionContext";
4106
+ import { getSql } from "../bootstrap/database.ts";
4107
+
4108
+ const MIGRATIONS_DIRECTORY = join(import.meta.dir, "migrations");
4109
+
4110
+ export async function loadStarterMigrations() {
4111
+ return loadMigrationsFromDirectory(MIGRATIONS_DIRECTORY);
4112
+ }
4113
+
4114
+ export async function withMigrationDatabase<T>(fn: (db: MigrationDatabase) => Promise<T>): Promise<T> {
4115
+ const runtime = getSql();
4116
+ const url = process.env.MIGRATION_DATABASE_URL?.trim();
4117
+ if (!url) return fn(runtime);
4118
+ const admin = createMysqlConnection(url);
4119
+ try {
4120
+ return await runWithDatabaseConnection(admin, () => fn(admin));
4121
+ } finally {
4122
+ await admin.close();
4123
+ }
4124
+ }
4083
4125
  `;
4084
4126
  }
4085
4127
  return `import { join } from "node:path";
@@ -4638,7 +4680,8 @@ export async function ensureAppDatabase(options: { provision?: boolean } = {}):
4638
4680
  }
4639
4681
  const name = safeDatabaseName(url);
4640
4682
 
4641
- const admin = new URL(url);
4683
+ // Explicit schema operations use the administrative connection when supplied.
4684
+ const admin = new URL(process.env.MIGRATION_DATABASE_URL?.trim() || url);
4642
4685
  admin.pathname = "/";
4643
4686
  const connection = await createConnection(admin.toString());
4644
4687
  try {
@@ -5094,12 +5137,20 @@ function billingMigrationName(layers) {
5094
5137
  }
5095
5138
  return layers.extras.webhooks ? "0003_billing_schema" : "0002_billing_schema";
5096
5139
  }
5097
- function renderFileMigration(name, upSql, downSql) {
5140
+ function renderFileMigration(name, upSql, downSql, columnCleanup) {
5098
5141
  const upCalls = upSql.map((sql) => ` await db.unsafe(${JSON.stringify(sql)});`).join(`
5099
5142
  `);
5100
5143
  const downCalls = downSql.map((sql) => ` await db.unsafe(${JSON.stringify(sql)});`).join(`
5101
5144
  `);
5102
- return `import type { Migration } from "@getstrata/core/database/migrations/types";
5145
+ const schemaImport = columnCleanup ? `import { Schema } from "@getstrata/core/database/schema";
5146
+ ` : "";
5147
+ const dropColumn = columnCleanup ? `
5148
+ await Schema.run(db, "${columnCleanup.database === "postgres" ? "pgsql" : columnCleanup.database}", schema => {
5149
+ schema.table(${JSON.stringify(columnCleanup.table)}, table => {
5150
+ table.dropColumn(${JSON.stringify(columnCleanup.column)});
5151
+ });
5152
+ });` : "";
5153
+ return `${schemaImport}import type { Migration } from "@getstrata/core/database/migrations/types";
5103
5154
 
5104
5155
  const migration: Migration = {
5105
5156
  name: ${JSON.stringify(name)},
@@ -5107,7 +5158,7 @@ const migration: Migration = {
5107
5158
  ${upCalls}
5108
5159
  },
5109
5160
  async down(db) {
5110
- ${downCalls}
5161
+ ${downCalls}${dropColumn}
5111
5162
  },
5112
5163
  };
5113
5164
 
@@ -5180,7 +5231,7 @@ function renderBillingMigration(layers) {
5180
5231
  `DROP TABLE IF EXISTS stripe_webhook_event${cascade}`,
5181
5232
  `DROP TABLE IF EXISTS subscription${cascade}`
5182
5233
  ];
5183
- return renderFileMigration(name, up, down);
5234
+ return renderFileMigration(name, up, down, tenancyOn ? { database: layers.database, table: "tenant", column: "stripe_customer_id" } : undefined);
5184
5235
  }
5185
5236
  function sqlParams(database, count) {
5186
5237
  return Array.from({ length: count }, (_, index) => database === "postgres" ? `$${index + 1}` : "?").join(", ");
@@ -5825,6 +5876,26 @@ function applyFrontendOverlays(overlayRoot, targetDir, layers) {
5825
5876
  function writeGeneratedFiles(options) {
5826
5877
  const { targetDir, projectName, layers } = options;
5827
5878
  const src = join2(targetDir, "src");
5879
+ if (needsFrontendBuild(layers.frontend)) {
5880
+ const transport = layers.auth.startsWith("cookie") ? "cookie" : layers.auth;
5881
+ const mfa = transport === "cookie" && layers.extras.mfa;
5882
+ writeText(join2(targetDir, "frontend/src/auth/config.ts"), `export type AuthTransport = "cookie" | "token" | "jwt" | "headers";
5883
+ export const AUTH_CONFIG: { transport: AuthTransport; mfa: boolean } = ${JSON.stringify({ transport, mfa })};
5884
+ `);
5885
+ writeText(join2(targetDir, "frontend/src/config.ts"), `import { validateSpaPrefix } from "@getstrata/core/runtime/frontendMode";
5886
+
5887
+ // Generated scripts supply only this public value before Bun starts.
5888
+ export const SPA_PREFIX = validateSpaPrefix(process.env.BUN_PUBLIC_SPA_PREFIX);
5889
+ export const TENANCY_ENABLED = ${usesTenantTable(layers.tenancy)};
5890
+ `);
5891
+ const manifestPath = join2(targetDir, "frontend/package.json");
5892
+ const manifest = JSON.parse(readFileSync2(manifestPath, "utf8"));
5893
+ const publicEnv = `BUN_PUBLIC_SPA_PREFIX="\${SPA_PREFIX:-${layers.spaPrefix}}"`;
5894
+ manifest.scripts.dev = `${publicEnv} bun --hot dev-server.ts`;
5895
+ manifest.scripts.build = `${publicEnv} bun run build.ts`;
5896
+ manifest.scripts.preview = `bun run build && ${publicEnv} bun dev-server.ts --preview`;
5897
+ writeText(manifestPath, JSON.stringify(manifest, null, 2));
5898
+ }
5828
5899
  writeText(join2(targetDir, ".bun-version"), `1.4.3
5829
5900
  `);
5830
5901
  writeText(join2(targetDir, ".env.example"), renderEnvExample(projectName, layers));
@@ -6017,7 +6088,7 @@ Next steps:`);
6017
6088
  console.log(` cd ${cdTarget}`);
6018
6089
  console.log(" cp .env.example .env");
6019
6090
  if (compose) {
6020
- console.log(" docker compose up -d");
6091
+ console.log(` ${dockerComposeUpCommand(layers)}`);
6021
6092
  }
6022
6093
  if (dockerOn.includes("adminer")) {
6023
6094
  console.log(" Adminer: http://localhost:8080");
@@ -6039,6 +6110,7 @@ Next steps:`);
6039
6110
  }
6040
6111
  function generateProject(options) {
6041
6112
  assertProjectName(options.projectName);
6113
+ const layers = { ...options.layers, spaPrefix: validateSpaPrefix(options.layers.spaPrefix) };
6042
6114
  if (existsSync2(options.targetDir)) {
6043
6115
  if (!options.force) {
6044
6116
  throw new Error(`Directory already exists: ${options.targetDir}`);
@@ -6046,8 +6118,8 @@ function generateProject(options) {
6046
6118
  rmSync2(options.targetDir, { recursive: true, force: true });
6047
6119
  }
6048
6120
  copyTree(options.templateRoot, options.targetDir, options.projectName, new Set(["overlays"]));
6049
- applyFrontendOverlays(options.overlayRoot, options.targetDir, options.layers);
6050
- writeGeneratedFiles(options);
6121
+ applyFrontendOverlays(options.overlayRoot, options.targetDir, layers);
6122
+ writeGeneratedFiles({ ...options, layers });
6051
6123
  }
6052
6124
  async function runCreateStrata(argv, cwd = process.cwd()) {
6053
6125
  let flags;
@@ -1,9 +1,12 @@
1
+ import { SPA_PREFIX } from "./src/config.ts";
2
+
1
3
  const result = await Bun.build({
2
4
  entrypoints: ["./index.html"],
3
5
  outdir: "./dist",
4
6
  target: "browser",
5
7
  minify: true,
6
- publicPath: "/app/",
8
+ publicPath: `${SPA_PREFIX}/`,
9
+ env: "BUN_PUBLIC_*",
7
10
  });
8
11
 
9
12
  if (!result.success) {
@@ -0,0 +1,2 @@
1
+ [serve.static]
2
+ env = "BUN_PUBLIC_*"
@@ -1,5 +1,7 @@
1
1
  import { join } from "node:path";
2
+ import { assertPathUnderRoot } from "@getstrata/core/security/safePath";
2
3
  import index from "./index.html";
4
+ import { SPA_PREFIX } from "./src/config.ts";
3
5
 
4
6
  const API_ORIGIN = process.env.API_ORIGIN ?? "http://localhost:3000";
5
7
  const PORT = Number(process.env.FRONTEND_PORT ?? "5173");
@@ -10,7 +12,8 @@ async function proxyToApi(request: Request): Promise<Response> {
10
12
  const incoming = new URL(request.url);
11
13
  const target = new URL(`${incoming.pathname}${incoming.search}`, API_ORIGIN);
12
14
  const headers = new Headers(request.headers);
13
- headers.delete("host");
15
+ // Preserve the browser-facing host so Request URL and Origin remain consistent.
16
+ // The upstream network target still comes exclusively from API_ORIGIN.
14
17
 
15
18
  return fetch(target, {
16
19
  method: request.method,
@@ -23,8 +26,16 @@ async function proxyToApi(request: Request): Promise<Response> {
23
26
 
24
27
  async function servePreview(request: Request): Promise<Response> {
25
28
  const pathname = new URL(request.url).pathname;
26
- const relativePath = pathname.replace(/^\/app\/?/, "");
27
- const asset = Bun.file(join(DIST_DIRECTORY, relativePath));
29
+ const relativePath =
30
+ pathname === SPA_PREFIX || pathname === `${SPA_PREFIX}/`
31
+ ? ""
32
+ : pathname.slice(SPA_PREFIX.length + 1);
33
+ let asset: ReturnType<typeof Bun.file>;
34
+ try {
35
+ asset = Bun.file(assertPathUnderRoot(DIST_DIRECTORY, relativePath || "index.html"));
36
+ } catch {
37
+ return new Response("Not found", { status: 404 });
38
+ }
28
39
 
29
40
  if (relativePath.length > 0 && (await asset.exists())) {
30
41
  return new Response(asset);
@@ -53,14 +64,14 @@ const server = Bun.serve({
53
64
  "/api/*": proxyToApi,
54
65
  "/health": proxyToApi,
55
66
  "/ready": proxyToApi,
56
- "/app": PREVIEW ? servePreview : index,
57
- "/app/": PREVIEW ? servePreview : index,
58
- "/app/*": PREVIEW ? servePreview : index,
67
+ [SPA_PREFIX]: PREVIEW ? servePreview : index,
68
+ [`${SPA_PREFIX}/`]: PREVIEW ? servePreview : index,
69
+ [`${SPA_PREFIX}/*`]: PREVIEW ? servePreview : index,
59
70
  },
60
71
  });
61
72
 
62
73
  console.log(
63
74
  PREVIEW
64
- ? `SPA preview on ${server.url}app/ (proxy ${API_ORIGIN})`
65
- : `SPA dev server on ${server.url}app/ (proxy ${API_ORIGIN})`,
75
+ ? `SPA preview on ${new URL(`${SPA_PREFIX}/`, server.url)} (proxy ${API_ORIGIN})`
76
+ : `SPA dev server on ${new URL(`${SPA_PREFIX}/`, server.url)} (proxy ${API_ORIGIN})`,
66
77
  );
@@ -1,3 +1,4 @@
1
+ import { useState } from "react";
1
2
  import { Link, Navigate, Route, Routes } from "react-router-dom";
2
3
  import { useAuth } from "./auth/AuthContext";
3
4
  import HomePage from "./pages/HomePage";
@@ -20,6 +21,7 @@ function ProtectedRoute({ children }: { children: React.ReactNode }) {
20
21
 
21
22
  function AppShell() {
22
23
  const { user, logout } = useAuth();
24
+ const [logoutError, setLogoutError] = useState<string | null>(null);
23
25
 
24
26
  return (
25
27
  <div className="app-shell">
@@ -29,8 +31,17 @@ function AppShell() {
29
31
  <Link to="/">Home</Link>
30
32
  {user ? (
31
33
  <>
32
- <span className="hint">{user.email}</span>
33
- <button type="button" className="secondary" onClick={logout}>
34
+ <span className="hint">{user.email ?? `User ${user.id}`}</span>
35
+ <button
36
+ type="button"
37
+ className="secondary"
38
+ onClick={() => {
39
+ setLogoutError(null);
40
+ void logout().catch(() =>
41
+ setLogoutError("Sign-out could not complete. Try again."),
42
+ );
43
+ }}
44
+ >
34
45
  Sign out
35
46
  </button>
36
47
  </>
@@ -38,6 +49,7 @@ function AppShell() {
38
49
  </nav>
39
50
  </header>
40
51
 
52
+ {logoutError ? <p role="alert">{logoutError}</p> : null}
41
53
  <Routes>
42
54
  <Route path="/login" element={<LoginPage />} />
43
55
  <Route
@@ -1,10 +1,10 @@
1
- const API_PREFIX = "/api/v1";
1
+ import { AUTH_CONFIG } from "../auth/config";
2
2
 
3
+ const API_PREFIX = "/api/v1";
3
4
  interface ApiErrorBody {
4
5
  error?: string;
5
6
  details?: Record<string, string[]>;
6
7
  }
7
-
8
8
  class ApiError extends Error {
9
9
  constructor(
10
10
  readonly status: number,
@@ -15,97 +15,140 @@ class ApiError extends Error {
15
15
  this.name = "ApiError";
16
16
  }
17
17
  }
18
-
19
18
  interface ApiFetchOptions extends RequestInit {
20
19
  etag?: string | null;
21
20
  }
22
-
21
+ interface AuthUser {
22
+ id: number | string;
23
+ name?: string;
24
+ email?: string;
25
+ role: string;
26
+ }
23
27
  let csrfToken: string | null = null;
24
-
25
- async function resolveCsrfToken(): Promise<string> {
26
- if (csrfToken) {
27
- return csrfToken;
28
- }
29
-
30
- const response = await fetch(`${API_PREFIX}/auth/csrf`, {
31
- credentials: "include",
32
- });
33
- if (!response.ok) {
34
- throw new ApiError(response.status, "Could not load a CSRF token.");
28
+ let bearer: string | null = null;
29
+ let developmentIdentity: AuthUser | null = null;
30
+ const invalidationListeners = new Set<() => void>();
31
+ function onAuthInvalidated(listener: () => void) {
32
+ invalidationListeners.add(listener);
33
+ return () => {
34
+ invalidationListeners.delete(listener);
35
+ };
36
+ }
37
+ function clearAuthentication() {
38
+ bearer = null;
39
+ developmentIdentity = null;
40
+ csrfToken = null;
41
+ for (const listener of invalidationListeners) listener();
42
+ }
43
+ function authHeaders(headers: Headers) {
44
+ if (bearer) headers.set("authorization", `Bearer ${bearer}`);
45
+ if (AUTH_CONFIG.transport === "headers" && developmentIdentity) {
46
+ headers.set("x-authenticated-user-id", String(developmentIdentity.id));
47
+ headers.set("x-authenticated-user-role", developmentIdentity.role);
35
48
  }
36
-
49
+ }
50
+ async function resolveCsrfToken(): Promise<string> {
51
+ if (csrfToken) return csrfToken;
52
+ const response = await fetch(`${API_PREFIX}/auth/csrf`, { credentials: "include" });
53
+ if (!response.ok) throw new ApiError(response.status, "Could not load a CSRF token.");
37
54
  const body = (await response.json()) as { token?: string };
38
- csrfToken = body.token ?? "";
55
+ if (!body.token) throw new ApiError(502, "The CSRF response did not include a token.");
56
+ csrfToken = body.token;
39
57
  return csrfToken;
40
58
  }
41
-
42
- async function apiFetch<T>(path: string, options: ApiFetchOptions = {}): Promise<T> {
59
+ async function request(path: string, options: ApiFetchOptions = {}): Promise<Response> {
43
60
  const headers = new Headers(options.headers);
44
61
  const method = (options.method ?? "GET").toUpperCase();
45
-
46
- if (options.etag) {
47
- headers.set("if-match", options.etag);
48
- }
49
-
50
- if (options.body && !headers.has("content-type")) {
51
- headers.set("content-type", "application/json");
52
- }
53
-
54
- if (method !== "GET" && method !== "HEAD") {
62
+ authHeaders(headers);
63
+ if (options.etag) headers.set("if-match", options.etag);
64
+ if (options.body && !headers.has("content-type")) headers.set("content-type", "application/json");
65
+ if (AUTH_CONFIG.transport !== "headers" && method !== "GET" && method !== "HEAD")
55
66
  headers.set("x-csrf-token", await resolveCsrfToken());
67
+ const response = await fetch(path, { ...options, credentials: "include", headers });
68
+ const next = response.headers.get("x-csrf-token");
69
+ if (next) csrfToken = next;
70
+ if (response.status === 401) clearAuthentication();
71
+ return response;
72
+ }
73
+ async function requestJson<T>(path: string, options: ApiFetchOptions = {}): Promise<T> {
74
+ const response = await request(path, options);
75
+ if (response.status === 204) return undefined as T;
76
+ if (!(response.headers.get("content-type") ?? "").includes("application/json")) {
77
+ throw new ApiError(response.status, `Expected JSON from ${path}; received ${response.status}.`);
56
78
  }
57
-
58
- const response = await fetch(`${API_PREFIX}${path}`, {
59
- ...options,
60
- credentials: "include",
61
- headers,
62
- });
63
-
64
- const nextCsrf = response.headers.get("x-csrf-token");
65
- if (nextCsrf) {
66
- csrfToken = nextCsrf;
67
- }
68
-
69
- if (response.status === 204) {
70
- return undefined as T;
71
- }
72
-
73
- const contentType = response.headers.get("content-type") ?? "";
74
-
75
- if (!contentType.includes("application/json")) {
76
- if (!response.ok) {
77
- throw new ApiError(response.status, `Request failed with ${response.status}`);
78
- }
79
-
80
- return undefined as T;
81
- }
82
-
83
79
  const body = (await response.json()) as T & ApiErrorBody;
84
-
85
- if (!response.ok) {
80
+ if (!response.ok)
86
81
  throw new ApiError(response.status, body.error ?? "Request failed", body.details);
87
- }
88
-
89
82
  return body;
90
83
  }
91
-
84
+ async function apiFetch<T>(path: string, options: ApiFetchOptions = {}): Promise<T> {
85
+ return requestJson<T>(`${API_PREFIX}${path}`, options);
86
+ }
92
87
  async function fetchResourceEtag(path: string): Promise<string> {
93
- const response = await fetch(`${API_PREFIX}${path}`, {
94
- credentials: "include",
95
- });
96
-
97
- if (!response.ok) {
98
- throw new ApiError(response.status, `Failed to load ETag for ${path}`);
99
- }
100
-
88
+ const response = await request(`${API_PREFIX}${path}`);
89
+ if (!response.ok) throw new ApiError(response.status, `Failed to load ETag for ${path}`);
101
90
  const etag = response.headers.get("etag");
102
-
103
- if (!etag) {
104
- throw new ApiError(412, `Missing ETag for ${path}`);
105
- }
106
-
91
+ if (!etag) throw new ApiError(412, `Missing ETag for ${path}`);
107
92
  return etag;
108
93
  }
94
+ async function loadProfile(): Promise<AuthUser | null> {
95
+ if (AUTH_CONFIG.transport === "headers") return developmentIdentity;
96
+ if ((AUTH_CONFIG.transport === "token" || AUTH_CONFIG.transport === "jwt") && !bearer)
97
+ return null;
98
+ return requestJson<AuthUser>(
99
+ AUTH_CONFIG.transport === "jwt" ? "/api/user" : `${API_PREFIX}/auth/me`,
100
+ );
101
+ }
102
+ async function signIn(email: string, password: string, mfaCode?: string): Promise<AuthUser> {
103
+ if (AUTH_CONFIG.transport === "headers")
104
+ throw new ApiError(400, "Use a development identity instead.");
105
+ const payload = await requestJson<{ token?: string }>(
106
+ AUTH_CONFIG.transport === "jwt" ? "/api/auth/token" : `${API_PREFIX}/auth/login`,
107
+ {
108
+ method: "POST",
109
+ body: JSON.stringify({ email, password, ...(mfaCode ? { mfa_code: mfaCode } : {}) }),
110
+ },
111
+ );
112
+ if (AUTH_CONFIG.transport === "token" || AUTH_CONFIG.transport === "jwt") {
113
+ if (!payload.token)
114
+ throw new ApiError(502, "Login did not return the selected bearer credential.");
115
+ bearer = payload.token;
116
+ }
117
+ try {
118
+ const profile = await loadProfile();
119
+ if (!profile) throw new ApiError(401, "Login did not establish an identity.");
120
+ return profile;
121
+ } catch (error) {
122
+ clearAuthentication();
123
+ throw error;
124
+ }
125
+ }
126
+ function selectDevelopmentIdentity(id: string, role: string): AuthUser {
127
+ if (
128
+ AUTH_CONFIG.transport !== "headers" ||
129
+ !/^\d+$/.test(id) ||
130
+ Number(id) <= 0 ||
131
+ !["member", "admin"].includes(role)
132
+ )
133
+ throw new ApiError(422, "Choose a positive user ID and a supported role.");
134
+ developmentIdentity = { id, role };
135
+ return developmentIdentity;
136
+ }
137
+ async function signOut(): Promise<void> {
138
+ // Bearer logout drops this browser's memory; server revocation remains the account API's contract.
139
+ if (AUTH_CONFIG.transport === "cookie") await apiFetch("/auth/logout", { method: "POST" });
140
+ clearAuthentication();
141
+ }
109
142
 
110
- export type { ApiErrorBody };
111
- export { API_PREFIX, ApiError, apiFetch, fetchResourceEtag };
143
+ export type { ApiErrorBody, AuthUser };
144
+ export {
145
+ API_PREFIX,
146
+ ApiError,
147
+ apiFetch,
148
+ fetchResourceEtag,
149
+ loadProfile,
150
+ onAuthInvalidated,
151
+ selectDevelopmentIdentity,
152
+ signIn,
153
+ signOut,
154
+ };
@@ -7,79 +7,62 @@ import {
7
7
  useMemo,
8
8
  useState,
9
9
  } from "react";
10
- import { apiFetch } from "../api/client";
11
-
12
- interface AuthUser {
13
- id: number;
14
- name: string;
15
- email: string;
16
- role: string;
17
- }
10
+ import {
11
+ type AuthUser,
12
+ loadProfile,
13
+ onAuthInvalidated,
14
+ selectDevelopmentIdentity,
15
+ signIn,
16
+ signOut,
17
+ } from "../api/client";
18
18
 
19
19
  interface AuthContextValue {
20
20
  user: AuthUser | null;
21
21
  loading: boolean;
22
- login: (email: string, password: string) => Promise<void>;
22
+ login: (email: string, password: string, mfaCode?: string) => Promise<void>;
23
23
  logout: () => Promise<void>;
24
+ chooseIdentity: (id: string, role: string) => void;
24
25
  }
25
-
26
26
  const AuthContext = createContext<AuthContextValue | null>(null);
27
-
28
27
  function AuthProvider({ children }: { children: ReactNode }) {
29
28
  const [user, setUser] = useState<AuthUser | null>(null);
30
29
  const [loading, setLoading] = useState(true);
31
-
32
- const loadProfile = useCallback(async () => {
33
- const profile = await apiFetch<AuthUser>("/auth/me");
34
- setUser(profile);
35
- }, []);
36
-
30
+ useEffect(() => onAuthInvalidated(() => setUser(null)), []);
37
31
  useEffect(() => {
32
+ let active = true;
38
33
  loadProfile()
34
+ .then((profile) => {
35
+ if (active) setUser(profile);
36
+ })
39
37
  .catch(() => {
40
- setUser(null);
38
+ if (active) setUser(null);
41
39
  })
42
40
  .finally(() => {
43
- setLoading(false);
44
- });
45
- }, [loadProfile]);
46
-
47
- const login = useCallback(
48
- async (email: string, password: string) => {
49
- await apiFetch("/auth/login", {
50
- method: "POST",
51
- body: JSON.stringify({ email, password }),
41
+ if (active) setLoading(false);
52
42
  });
53
- await loadProfile();
54
- },
55
- [loadProfile],
56
- );
57
-
43
+ return () => {
44
+ active = false;
45
+ };
46
+ }, []);
47
+ const login = useCallback(async (email: string, password: string, mfaCode?: string) => {
48
+ setUser(await signIn(email, password, mfaCode));
49
+ }, []);
58
50
  const logout = useCallback(async () => {
59
- await apiFetch("/auth/logout", { method: "POST" }).catch(() => undefined);
51
+ await signOut();
60
52
  setUser(null);
61
53
  }, []);
62
-
54
+ const chooseIdentity = useCallback((id: string, role: string) => {
55
+ setUser(selectDevelopmentIdentity(id, role));
56
+ }, []);
63
57
  const value = useMemo(
64
- () => ({
65
- user,
66
- loading,
67
- login,
68
- logout,
69
- }),
70
- [loading, login, logout, user],
58
+ () => ({ user, loading, login, logout, chooseIdentity }),
59
+ [user, loading, login, logout, chooseIdentity],
71
60
  );
72
-
73
61
  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
74
62
  }
75
-
76
63
  function useAuth(): AuthContextValue {
77
64
  const context = useContext(AuthContext);
78
-
79
- if (!context) {
80
- throw new Error("useAuth must be used within AuthProvider");
81
- }
82
-
65
+ if (!context) throw new Error("useAuth must be used within AuthProvider");
83
66
  return context;
84
67
  }
85
68
 
@@ -0,0 +1,6 @@
1
+ export type AuthTransport = "cookie" | "token" | "jwt" | "headers";
2
+ // The generator replaces these public capabilities for the chosen auth stack.
3
+ export const AUTH_CONFIG: { transport: AuthTransport; mfa: boolean } = {
4
+ transport: "cookie",
5
+ mfa: false,
6
+ };
@@ -0,0 +1,7 @@
1
+ import { validateSpaPrefix } from "@getstrata/core/runtime/frontendMode";
2
+
3
+ // The generated scripts supply only this public value before Bun starts.
4
+ export const SPA_PREFIX = validateSpaPrefix(process.env.BUN_PUBLIC_SPA_PREFIX);
5
+
6
+ // Public schema capability selected by the generator, not an authorization decision.
7
+ export const TENANCY_ENABLED = false;
@@ -0,0 +1,25 @@
1
+ /** Displayed source only; business handlers execute after the developer adds this module. */
2
+ export function notesModuleExample(tenancy: boolean): string {
3
+ const tenantImport = tenancy
4
+ ? 'import { currentTenantId } from "@getstrata/core/tenant/tenantContext";\n'
5
+ : "";
6
+ const scope = tenancy ? ".where({ tenant_id: currentTenantId() })" : "";
7
+ return `// src/modules/notes/index.ts
8
+ import type { AppModule } from "@getstrata/bootstrap/contracts";
9
+ import { jsonResponse } from "@getstrata/core/http/response";
10
+ ${tenantImport}import { Note } from "../../models/Note.ts";
11
+
12
+ export default {
13
+ name: "notes",
14
+ routes({ kernel }) {
15
+ return {
16
+ "/api/v1/notes": {
17
+ GET: kernel.wrapApi(async () => {
18
+ const rows = await Note.query()${scope}.orderBy({ column: "id", direction: "DESC" }).limit(100).get();
19
+ return jsonResponse({ data: rows.map(row => row.toObject()) });
20
+ }),
21
+ },
22
+ };
23
+ },
24
+ } satisfies AppModule;`;
25
+ }
@@ -3,6 +3,7 @@ import { createRoot } from "react-dom/client";
3
3
  import { BrowserRouter } from "react-router-dom";
4
4
  import App from "./App";
5
5
  import { AuthProvider } from "./auth/AuthContext";
6
+ import { SPA_PREFIX } from "./config";
6
7
  import "./app.css";
7
8
 
8
9
  const rootElement = document.getElementById("root");
@@ -13,7 +14,7 @@ if (!rootElement) {
13
14
 
14
15
  createRoot(rootElement).render(
15
16
  <StrictMode>
16
- <BrowserRouter basename="/app">
17
+ <BrowserRouter basename={SPA_PREFIX}>
17
18
  <AuthProvider>
18
19
  <App />
19
20
  </AuthProvider>
@@ -1,19 +1,26 @@
1
1
  import { useAuth } from "../auth/AuthContext";
2
-
2
+ import { AUTH_CONFIG } from "../auth/config";
3
+ import { TENANCY_ENABLED } from "../config";
4
+ import { notesModuleExample } from "../examples/notes";
3
5
  export default function HomePage() {
4
6
  const { user } = useAuth();
5
-
6
7
  return (
7
8
  <section>
8
- <h1>Signed in</h1>
9
+ <h1>{AUTH_CONFIG.transport === "headers" ? "Development identity selected" : "Signed in"}</h1>
9
10
  <p className="hint">
10
- This page reads <code>GET /api/v1/auth/me</code> with the HttpOnly session cookie. It is the
11
- only resource the generated backend serves, so it is the only one this page shows.
11
+ {AUTH_CONFIG.transport === "headers"
12
+ ? "Request identity headers are enabled only for local development. There is no account profile endpoint in this mode."
13
+ : AUTH_CONFIG.transport === "jwt"
14
+ ? "This page reads GET /api/user with a memory-only JWT. Reloading requires sign-in again."
15
+ : `This page reads GET /api/v1/auth/me with ${AUTH_CONFIG.transport === "cookie" ? "the HttpOnly session cookie" : "a memory-only API token"}.`}
12
16
  </p>
13
-
14
17
  <div className="card">
15
18
  <table>
16
19
  <tbody>
20
+ <tr>
21
+ <th>ID</th>
22
+ <td>{user?.id ?? "—"}</td>
23
+ </tr>
17
24
  <tr>
18
25
  <th>Name</th>
19
26
  <td>{user?.name ?? "—"}</td>
@@ -31,41 +38,18 @@ export default function HomePage() {
31
38
  </tbody>
32
39
  </table>
33
40
  </div>
34
-
35
41
  <h2>Starter-only example</h2>
36
42
  <p>
37
- This empty app already serves <code>GET /api/v1/auth/me</code>. It does not serve{" "}
38
- <code>GET /api/v1/notes</code>. The module below is an example you add yourself. Create it
39
- under <code>src/modules/</code> and the kernel picks it up on the next boot.
43
+ This app has no notes API yet. Add an explicit module under <code>src/modules/</code> to
44
+ expose your own application resources through the ORM.
40
45
  </p>
41
-
42
46
  <pre className="card">
43
- <code>{`// src/modules/notes/index.ts
44
- import type { AppModule } from "@getstrata/bootstrap/contracts";
45
- import { jsonResponse } from "@getstrata/core/http/response";
46
- import { getSql } from "../../bootstrap/database.ts";
47
-
48
- const notesModule: AppModule = {
49
- name: "notes",
50
- order: 2,
51
- routes({ kernel }) {
52
- return {
53
- "/api/v1/notes": kernel.wrap("api", async () => {
54
- const rows = await getSql().unsafe<{ id: number; body: string }>(
55
- "SELECT id, body FROM notes ORDER BY id DESC",
56
- );
57
- return jsonResponse({ data: rows });
58
- }),
59
- };
60
- },
61
- };
62
-
63
- export default notesModule;`}</code>
47
+ <code>{notesModuleExample(TENANCY_ENABLED)}</code>
64
48
  </pre>
65
-
66
49
  <p className="hint">
67
50
  Then fetch it here with <code>apiFetch("/notes")</code>. The <code>notes</code> table
68
- already exists after <code>bun run db:migrate</code>.
51
+ already exists after <code>bun run db:migrate</code>. Application authorization and tenant
52
+ scope remain required for real business data.
69
53
  </p>
70
54
  </section>
71
55
  );
@@ -2,68 +2,109 @@ import { type FormEvent, useState } from "react";
2
2
  import { Navigate, useNavigate } from "react-router-dom";
3
3
  import { ApiError } from "../api/client";
4
4
  import { useAuth } from "../auth/AuthContext";
5
-
5
+ import { AUTH_CONFIG } from "../auth/config";
6
6
  export default function LoginPage() {
7
- const { login, user } = useAuth();
7
+ const { login, user, chooseIdentity } = useAuth();
8
8
  const navigate = useNavigate();
9
9
  const [email, setEmail] = useState("");
10
10
  const [password, setPassword] = useState("");
11
+ const [mfaCode, setMfaCode] = useState("");
12
+ const [id, setId] = useState("");
13
+ const [role, setRole] = useState("member");
11
14
  const [error, setError] = useState<string | null>(null);
12
15
  const [submitting, setSubmitting] = useState(false);
13
-
14
- if (user) {
15
- return <Navigate to="/" replace />;
16
- }
17
-
16
+ if (user) return <Navigate to="/" replace />;
18
17
  async function onSubmit(event: FormEvent<HTMLFormElement>) {
19
18
  event.preventDefault();
20
19
  setSubmitting(true);
21
20
  setError(null);
22
-
23
21
  try {
24
- await login(email, password);
22
+ if (AUTH_CONFIG.transport === "headers") chooseIdentity(id, role);
23
+ else await login(email, password, mfaCode);
25
24
  navigate("/");
26
25
  } catch (cause) {
27
- setError(cause instanceof ApiError ? cause.message : "Login failed");
26
+ setError(cause instanceof ApiError ? cause.message : "Sign-in failed");
28
27
  } finally {
29
28
  setSubmitting(false);
30
29
  }
31
30
  }
32
-
31
+ const development = AUTH_CONFIG.transport === "headers";
33
32
  return (
34
33
  <section className="card">
35
- <h1>Sign in</h1>
36
- <p className="hint">Enter your account email and password.</p>
37
-
38
- {error ? <p className="error">{error}</p> : null}
39
-
34
+ <h1>{development ? "Development identity" : "Sign in"}</h1>
35
+ <p className="hint">
36
+ {development
37
+ ? "Development only. Select request headers for local testing; this is not a persisted account or production sign-in. The backend must allow AUTH_DEV_HEADERS in a local environment."
38
+ : AUTH_CONFIG.transport === "cookie"
39
+ ? "Enter your account email and password."
40
+ : "Enter your account email and password. The bearer credential stays in memory; reloading requires sign-in again."}
41
+ </p>
42
+ {error ? (
43
+ <p className="error" role="alert">
44
+ {error}
45
+ </p>
46
+ ) : null}
40
47
  <form className="stack-form" onSubmit={onSubmit}>
41
- <label>
42
- Email
43
- <input
44
- type="email"
45
- name="email"
46
- autoComplete="username"
47
- value={email}
48
- onChange={(event) => setEmail(event.target.value)}
49
- required
50
- />
51
- </label>
52
-
53
- <label>
54
- Password
55
- <input
56
- type="password"
57
- name="password"
58
- autoComplete="current-password"
59
- value={password}
60
- onChange={(event) => setPassword(event.target.value)}
61
- required
62
- />
63
- </label>
64
-
48
+ {development ? (
49
+ <>
50
+ <label>
51
+ User ID
52
+ <input
53
+ name="userId"
54
+ inputMode="numeric"
55
+ pattern="[0-9]+"
56
+ value={id}
57
+ onChange={(e) => setId(e.target.value)}
58
+ required
59
+ />
60
+ </label>
61
+ <label>
62
+ Role
63
+ <select value={role} onChange={(e) => setRole(e.target.value)}>
64
+ <option value="member">Member</option>
65
+ <option value="admin">Admin</option>
66
+ </select>
67
+ </label>
68
+ </>
69
+ ) : (
70
+ <>
71
+ <label>
72
+ Email
73
+ <input
74
+ type="email"
75
+ name="email"
76
+ autoComplete="username"
77
+ value={email}
78
+ onChange={(e) => setEmail(e.target.value)}
79
+ required
80
+ />
81
+ </label>
82
+ <label>
83
+ Password
84
+ <input
85
+ type="password"
86
+ name="password"
87
+ autoComplete="current-password"
88
+ value={password}
89
+ onChange={(e) => setPassword(e.target.value)}
90
+ required
91
+ />
92
+ </label>
93
+ {AUTH_CONFIG.mfa ? (
94
+ <label>
95
+ Authenticator or recovery code
96
+ <input
97
+ name="mfa_code"
98
+ autoComplete="one-time-code"
99
+ value={mfaCode}
100
+ onChange={(e) => setMfaCode(e.target.value)}
101
+ />
102
+ </label>
103
+ ) : null}
104
+ </>
105
+ )}
65
106
  <button type="submit" disabled={submitting}>
66
- {submitting ? "Signing in…" : "Sign in"}
107
+ {submitting ? "Signing in…" : development ? "Use development identity" : "Sign in"}
67
108
  </button>
68
109
  </form>
69
110
  </section>
@@ -12,9 +12,9 @@
12
12
  "check": "tsc --noEmit"
13
13
  },
14
14
  "dependencies": {
15
- "@getstrata/bootstrap": "^2.2.44",
16
- "@getstrata/cli": "^2.2.44",
17
- "@getstrata/core": "^2.2.44",
15
+ "@getstrata/bootstrap": "^2.2.46",
16
+ "@getstrata/cli": "^2.2.46",
17
+ "@getstrata/core": "^2.2.46",
18
18
  "eta": "^4.6.0"
19
19
  },
20
20
  "devDependencies": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getstrata/starter",
3
- "version": "2.2.44",
3
+ "version": "2.2.46",
4
4
  "description": "Interactive create-strata wizard. Choose each layer; one database engine.",
5
5
  "type": "module",
6
6
  "license": "MIT",