create-strata 2.2.45 → 2.2.47

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/dist/cli.js CHANGED
@@ -2,9 +2,29 @@
2
2
  // @bun
3
3
 
4
4
  // ../strata-starter/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
  // ../strata-starter/src/copy.ts
9
29
  import {
10
30
  existsSync,
@@ -172,7 +192,7 @@ function selectedDockerServices(layers) {
172
192
  return selected;
173
193
  }
174
194
  function dockerComposeUpCommand(layers) {
175
- return selectedDockerServices(layers).includes("adminer") ? "docker compose --profile debug up -d" : "docker compose up -d";
195
+ return selectedDockerServices(layers).includes("adminer") ? "docker compose --profile debug up -d --wait --wait-timeout 180" : "docker compose up -d --wait --wait-timeout 180";
176
196
  }
177
197
  function reconcileDocker(layers) {
178
198
  const selected = selectedDockerServices(layers);
@@ -550,6 +570,7 @@ function applyFlagOverrides(base, flags) {
550
570
  console.warn(`Using --tenancy column: rls is Postgres-only (SET LOCAL app.tenant_id) and ${next.database} has no equivalent.`);
551
571
  next.tenancy = "column";
552
572
  }
573
+ next.spaPrefix = validateSpaPrefix(next.spaPrefix);
553
574
  dropInapplicableExtras(next, flags);
554
575
  return reconcileDocker(applyDockerFlags(next, flags));
555
576
  }
@@ -1175,7 +1196,7 @@ function renderAuthModule(layers) {
1175
1196
  const mfa = Boolean(layers.extras.mfa && cookie);
1176
1197
  const verify = Boolean(layers.extras.emailVerification);
1177
1198
  const bearerApi = authUsesToken(layers.auth) || authUsesJwt(layers.auth);
1178
- const jsonCookieAccounts = cookie && (layers.frontend === "api" || layers.frontend === "spa-react");
1199
+ const jsonCookieAccounts = cookie && (layers.frontend === "api" || layers.frontend === "spa-react" || layers.frontend === "hybrid");
1179
1200
  const jsonAccounts = bearerApi || jsonCookieAccounts;
1180
1201
  const tenantInsert = usesTenantTable(layers.tenancy);
1181
1202
  const tenantCreateField = tenantInsert ? `
@@ -2588,48 +2609,20 @@ ${tokenLookup}
2588
2609
  function renderAuthProvider(layers) {
2589
2610
  if (layers.auth === "headers") {
2590
2611
  return `import { CORE_AUTH_TOKEN } from "@getstrata/bootstrap/config";
2591
- import type { AuthUser } from "@getstrata/core/auth/authContext";
2592
- import { currentAuthUser } from "@getstrata/core/auth/authContext";
2612
+ import { createTokenAbilityChecker } from "@getstrata/core/auth/tokenAbilityChecker";
2613
+ import { CORE_ABILITY_CHECKER_TOKEN } from "@getstrata/core/contracts/serviceTokens";
2614
+ import { AuthManager, GuestGuard } from "@getstrata/core/auth/guard";
2593
2615
  import type { ServiceProvider } from "@getstrata/core/contracts/di";
2594
2616
  import { envFlagEnabled } from "@getstrata/core/runtime/appEnv";
2595
2617
 
2596
- class StarterAuthManager {
2597
- async resolveWithSource(request?: Request) {
2598
- const user = await this.resolve(request);
2599
- return { user, credentialSource: user ? "guest" as const : null };
2600
- }
2601
-
2602
- async resolve(request?: Request): Promise<AuthUser | null> {
2603
- if (!envFlagEnabled(process.env.AUTH_DEV_HEADERS)) {
2604
- return request ? null : currentAuthUser();
2605
- }
2606
- if (request) {
2607
- const userId = request.headers.get("x-authenticated-user-id");
2608
- if (!userId) {
2609
- return null;
2610
- }
2611
- const role = request.headers.get("x-authenticated-user-role");
2612
- return {
2613
- id: userId,
2614
- ...(role ? { role } : {}),
2615
- };
2616
- }
2617
- return currentAuthUser();
2618
- }
2619
-
2620
- user(request?: Request) {
2621
- return this.resolve(request);
2622
- }
2623
-
2624
- async check(request: Request) {
2625
- return (await this.user(request)) !== null;
2626
- }
2627
- }
2628
-
2629
2618
  const authProvider: ServiceProvider = {
2630
2619
  name: "starter.auth",
2631
2620
  register({ container }) {
2632
- container.set(CORE_AUTH_TOKEN, new StarterAuthManager());
2621
+ const guard = envFlagEnabled(process.env.AUTH_DEV_HEADERS)
2622
+ ? new GuestGuard()
2623
+ : { resolve: () => null };
2624
+ container.set(CORE_AUTH_TOKEN, new AuthManager(guard));
2625
+ container.set(CORE_ABILITY_CHECKER_TOKEN, createTokenAbilityChecker());
2633
2626
  },
2634
2627
  };
2635
2628
 
@@ -2654,7 +2647,7 @@ export default authProvider;
2654
2647
  auth.registerGuard("token", apiGuard);` : "";
2655
2648
  const jwtReg = authUsesJwt(layers.auth) ? ` auth.registerGuard("jwt", new JwtGuard(container));` : "";
2656
2649
  const basicReg = authUsesToken(layers.auth) || authUsesJwt(layers.auth) ? ` auth.registerGuard("basic", new BasicAuthGuard(container));` : "";
2657
- const ability = authUsesToken(layers.auth) ? ` container.set(CORE_ABILITY_CHECKER_TOKEN, createTokenAbilityChecker());` : "";
2650
+ const ability = ` container.set(CORE_ABILITY_CHECKER_TOKEN, createTokenAbilityChecker());`;
2658
2651
  const imports = [`import { CORE_AUTH_TOKEN } from "@getstrata/bootstrap/config";`];
2659
2652
  if (authUsesCookie(layers.auth)) {
2660
2653
  imports.push(`import { createCookieSessionAuthManager } from "@getstrata/bootstrap/web/session";`);
@@ -2672,14 +2665,9 @@ export default authProvider;
2672
2665
  if (authUsesJwt(layers.auth)) {
2673
2666
  imports.push(`import { JwtGuard } from "@getstrata/core/auth/jwtGuard";`);
2674
2667
  }
2675
- if (authUsesToken(layers.auth)) {
2676
- imports.push(`import { createTokenAbilityChecker } from "@getstrata/core/auth/tokenAbilityChecker";`);
2677
- }
2668
+ imports.push(`import { createTokenAbilityChecker } from "@getstrata/core/auth/tokenAbilityChecker";`);
2678
2669
  imports.push(`import type { ServiceProvider } from "@getstrata/core/contracts/di";`);
2679
- const tokenImports = ["CORE_AUTH_USER_DIRECTORY_TOKEN"];
2680
- if (authUsesToken(layers.auth)) {
2681
- tokenImports.unshift("CORE_ABILITY_CHECKER_TOKEN");
2682
- }
2670
+ const tokenImports = ["CORE_ABILITY_CHECKER_TOKEN", "CORE_AUTH_USER_DIRECTORY_TOKEN"];
2683
2671
  imports.push(`import {
2684
2672
  ${tokenImports.join(`,
2685
2673
  `)},
@@ -2934,6 +2922,10 @@ function renderEnvExample(projectName, layers) {
2934
2922
  `DATABASE_URL=${defaultDatabaseUrl(layers, projectName)}`,
2935
2923
  ...postgresAppRoleEnvNotes(layers),
2936
2924
  ...layers.database === "postgres" ? [`MIGRATION_DATABASE_URL=${defaultMigrationDatabaseUrl(layers, projectName)}`] : [],
2925
+ ...layers.database === "mysql" ? [
2926
+ "# Optional schema-administration URL for the same database; runtime may lack DDL.",
2927
+ "# MIGRATION_DATABASE_URL="
2928
+ ] : [],
2937
2929
  ...layers.database === "sqlite" ? [] : [
2938
2930
  "# Optional. Point runtime at a different database than DATABASE_URL.",
2939
2931
  "# APP_DATABASE_URL="
@@ -3083,6 +3075,14 @@ function renderEnvExample(projectName, layers) {
3083
3075
  `)}
3084
3076
  `;
3085
3077
  }
3078
+ function renderServiceHealthcheck(test) {
3079
+ return ` healthcheck:
3080
+ test: ${JSON.stringify(test)}
3081
+ interval: 2s
3082
+ timeout: 3s
3083
+ retries: 60
3084
+ start_period: 5s`;
3085
+ }
3086
3086
  function renderDockerCompose(projectName, layers) {
3087
3087
  const selected = selectedDockerServices(layers);
3088
3088
  if (selected.length === 0) {
@@ -3098,6 +3098,7 @@ function renderDockerCompose(projectName, layers) {
3098
3098
  POSTGRES_USER: postgres
3099
3099
  POSTGRES_PASSWORD: ${GENERATED_POSTGRES_SUPERUSER_PASSWORD}
3100
3100
  POSTGRES_DB: ${database}
3101
+ ${renderServiceHealthcheck(["CMD-SHELL", 'PGPASSWORD="$$POSTGRES_PASSWORD" psql -h 127.0.0.1 -U "$$POSTGRES_USER" -d "$$POSTGRES_DB" -tAc "SELECT 1" >/dev/null'])}
3101
3102
  ports:
3102
3103
  # Localhost only. Do not publish this port on a production host.
3103
3104
  - "127.0.0.1:5432:5432"
@@ -3112,6 +3113,7 @@ function renderDockerCompose(projectName, layers) {
3112
3113
  environment:
3113
3114
  MYSQL_ROOT_PASSWORD: ${GENERATED_MYSQL_ROOT_PASSWORD}
3114
3115
  MYSQL_DATABASE: ${database}
3116
+ ${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'])}
3115
3117
  ports:
3116
3118
  - "127.0.0.1:3306:3306"
3117
3119
  volumes:
@@ -3126,13 +3128,18 @@ function renderDockerCompose(projectName, layers) {
3126
3128
  environment:
3127
3129
  ADMINER_DEFAULT_SERVER: ${server}
3128
3130
  depends_on:
3129
- - ${server}
3131
+ ${server}:
3132
+ condition: service_healthy
3133
+ ${renderServiceHealthcheck(["CMD", "php", "-r", "exit(@file_get_contents('http://127.0.0.1:8080/') === false ? 1 : 0);"])}
3130
3134
  ports:
3131
3135
  - "127.0.0.1:8080:8080"`);
3132
3136
  }
3133
3137
  if (selectedSet.has("redis")) {
3134
3138
  services.push(` redis:
3135
3139
  image: redis:7-alpine
3140
+ environment:
3141
+ REDIS_PASSWORD: "\${REDIS_PASSWORD:-dev-redis-change-me}"
3142
+ ${renderServiceHealthcheck(["CMD-SHELL", 'REDISCLI_AUTH="$$REDIS_PASSWORD" redis-cli --no-auth-warning ping | grep -qx PONG'])}
3136
3143
  command: ["redis-server", "--requirepass", "\${REDIS_PASSWORD:-dev-redis-change-me}"]
3137
3144
  ports:
3138
3145
  - "127.0.0.1:6379:6379"`);
@@ -3140,6 +3147,7 @@ function renderDockerCompose(projectName, layers) {
3140
3147
  if (selectedSet.has("mailpit")) {
3141
3148
  services.push(` mailpit:
3142
3149
  image: axllent/mailpit:latest
3150
+ ${renderServiceHealthcheck(["CMD", "/mailpit", "readyz"])}
3143
3151
  ports:
3144
3152
  - "127.0.0.1:1025:1025"
3145
3153
  - "127.0.0.1:8025:8025"`);
@@ -3186,7 +3194,7 @@ function renderDockerfile(layers) {
3186
3194
  ""
3187
3195
  ];
3188
3196
  if (frontend) {
3189
- 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", "");
3197
+ 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", "");
3190
3198
  }
3191
3199
  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 . .");
3192
3200
  if (frontend) {
@@ -3228,9 +3236,9 @@ function renderPackageJson(projectName, options = {}) {
3228
3236
  "@getstrata/cli": "workspace:*",
3229
3237
  "@getstrata/core": "workspace:*"
3230
3238
  } : {
3231
- "@getstrata/bootstrap": "^2.2.45",
3232
- "@getstrata/cli": "^2.2.45",
3233
- "@getstrata/core": "^2.2.45"
3239
+ "@getstrata/bootstrap": "^2.2.47",
3240
+ "@getstrata/cli": "^2.2.47",
3241
+ "@getstrata/core": "^2.2.47"
3234
3242
  };
3235
3243
  coreDeps.eta = "^4.6.0";
3236
3244
  if (options.layers?.database === "mysql") {
@@ -3311,7 +3319,7 @@ function renderSupportingToolsReadme(projectName, layers) {
3311
3319
  const lines = ["## Supporting tools", ""];
3312
3320
  if (dockerOn.length > 0) {
3313
3321
  const names = dockerOn.map((name) => DOCKER_SERVICE_LABELS[name]).join(", ");
3314
- lines.push(`Docker Compose includes ${names}.`, "", "```bash", dockerComposeUpCommand(layers), "```", "");
3322
+ 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.", "");
3315
3323
  if (dockerSet.has("adminer")) {
3316
3324
  const mysql = layers.database === "mysql";
3317
3325
  const system = mysql ? "MySQL" : "PostgreSQL";
@@ -3548,7 +3556,7 @@ HTML auth kit (restyle \`views/\` and \`public/assets/site.css\`):
3548
3556
  - Reset password: signed \`/reset-password\` (mail log when \`MAIL_DRIVER=log\`)
3549
3557
  ${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" : ""}
3550
3558
  Cookie name is \`strata_session\`. Forms send CSRF as \`_token\`.
3551
- ` : ""}${authUsesCookie(layers.auth) && (layers.frontend === "api" || layers.frontend === "spa-react") ? `
3559
+ ` : ""}${authUsesCookie(layers.auth) && (layers.frontend === "api" || layers.frontend === "spa-react" || layers.frontend === "hybrid") ? `
3552
3560
  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 }\`.
3553
3561
  ${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" : ""}
3554
3562
  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.
@@ -3620,6 +3628,7 @@ The image sets \`APP_ENV=production\` and \`AUTH_DEV_HEADERS=false\`; everything
3620
3628
  - 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.
3621
3629
  ${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\`.
3622
3630
  ` : ""}
3631
+ ${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" : ""}
3623
3632
  \`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\`).
3624
3633
  `;
3625
3634
  }
@@ -3630,6 +3639,7 @@ function renderInitialAdminMigration(layers) {
3630
3639
  return null;
3631
3640
  const driver = layers.database === "postgres" ? "pgsql" : layers.database;
3632
3641
  return `import { Schema } from "@getstrata/core/database/schema";
3642
+ import { guardMigrationRollback } from "@getstrata/core/database/migrations";
3633
3643
  import type { Migration } from "@getstrata/core/database/migrations/types";
3634
3644
 
3635
3645
  const migration: Migration = {
@@ -3643,10 +3653,11 @@ const migration: Migration = {
3643
3653
  });
3644
3654
  });
3645
3655
  },
3646
- async down(db) {
3647
- if ((await db.unsafe("SELECT id FROM initial_admin_provisioning")).length) {
3648
- throw new Error("Cannot discard a completed initial-admin provisioning claim.");
3649
- }
3656
+ async down(db, context) {
3657
+ await guardMigrationRollback(context, {
3658
+ hasHistory: async () => (await db.unsafe("SELECT id FROM initial_admin_provisioning")).length > 0,
3659
+ message: "Cannot discard a completed initial-admin provisioning claim.",
3660
+ });
3650
3661
  await Schema.run(db, "${driver}", schema => { schema.drop("initial_admin_provisioning"); });
3651
3662
  },
3652
3663
  };
@@ -4082,6 +4093,33 @@ export async function withMigrationDatabase<T>(
4082
4093
  await admin.close?.();
4083
4094
  }
4084
4095
  }
4096
+ `;
4097
+ }
4098
+ if (layers.database === "mysql") {
4099
+ return `import { join } from "node:path";
4100
+ import { loadMigrationsFromDirectory } from "@getstrata/core/database/migrations";
4101
+ import type { MigrationDatabase } from "@getstrata/core/database/migrations/types";
4102
+ import { createMysqlConnection } from "@getstrata/core/database/mysqlConnection";
4103
+ import { runWithDatabaseConnection } from "@getstrata/core/database/connectionContext";
4104
+ import { getSql } from "../bootstrap/database.ts";
4105
+
4106
+ const MIGRATIONS_DIRECTORY = join(import.meta.dir, "migrations");
4107
+
4108
+ export async function loadStarterMigrations() {
4109
+ return loadMigrationsFromDirectory(MIGRATIONS_DIRECTORY);
4110
+ }
4111
+
4112
+ export async function withMigrationDatabase<T>(fn: (db: MigrationDatabase) => Promise<T>): Promise<T> {
4113
+ const runtime = getSql();
4114
+ const url = process.env.MIGRATION_DATABASE_URL?.trim();
4115
+ if (!url) return fn(runtime);
4116
+ const admin = createMysqlConnection(url);
4117
+ try {
4118
+ return await runWithDatabaseConnection(admin, () => fn(admin));
4119
+ } finally {
4120
+ await admin.close();
4121
+ }
4122
+ }
4085
4123
  `;
4086
4124
  }
4087
4125
  return `import { join } from "node:path";
@@ -4640,7 +4678,8 @@ export async function ensureAppDatabase(options: { provision?: boolean } = {}):
4640
4678
  }
4641
4679
  const name = safeDatabaseName(url);
4642
4680
 
4643
- const admin = new URL(url);
4681
+ // Explicit schema operations use the administrative connection when supplied.
4682
+ const admin = new URL(process.env.MIGRATION_DATABASE_URL?.trim() || url);
4644
4683
  admin.pathname = "/";
4645
4684
  const connection = await createConnection(admin.toString());
4646
4685
  try {
@@ -5096,12 +5135,20 @@ function billingMigrationName(layers) {
5096
5135
  }
5097
5136
  return layers.extras.webhooks ? "0003_billing_schema" : "0002_billing_schema";
5098
5137
  }
5099
- function renderFileMigration(name, upSql, downSql) {
5138
+ function renderFileMigration(name, upSql, downSql, columnCleanup) {
5100
5139
  const upCalls = upSql.map((sql) => ` await db.unsafe(${JSON.stringify(sql)});`).join(`
5101
5140
  `);
5102
5141
  const downCalls = downSql.map((sql) => ` await db.unsafe(${JSON.stringify(sql)});`).join(`
5103
5142
  `);
5104
- return `import type { Migration } from "@getstrata/core/database/migrations/types";
5143
+ const schemaImport = columnCleanup ? `import { Schema } from "@getstrata/core/database/schema";
5144
+ ` : "";
5145
+ const dropColumn = columnCleanup ? `
5146
+ await Schema.run(db, "${columnCleanup.database === "postgres" ? "pgsql" : columnCleanup.database}", schema => {
5147
+ schema.table(${JSON.stringify(columnCleanup.table)}, table => {
5148
+ table.dropColumn(${JSON.stringify(columnCleanup.column)});
5149
+ });
5150
+ });` : "";
5151
+ return `${schemaImport}import type { Migration } from "@getstrata/core/database/migrations/types";
5105
5152
 
5106
5153
  const migration: Migration = {
5107
5154
  name: ${JSON.stringify(name)},
@@ -5109,7 +5156,7 @@ const migration: Migration = {
5109
5156
  ${upCalls}
5110
5157
  },
5111
5158
  async down(db) {
5112
- ${downCalls}
5159
+ ${downCalls}${dropColumn}
5113
5160
  },
5114
5161
  };
5115
5162
 
@@ -5182,7 +5229,7 @@ function renderBillingMigration(layers) {
5182
5229
  `DROP TABLE IF EXISTS stripe_webhook_event${cascade}`,
5183
5230
  `DROP TABLE IF EXISTS subscription${cascade}`
5184
5231
  ];
5185
- return renderFileMigration(name, up, down);
5232
+ return renderFileMigration(name, up, down, tenancyOn ? { database: layers.database, table: "tenant", column: "stripe_customer_id" } : undefined);
5186
5233
  }
5187
5234
  function sqlParams(database, count) {
5188
5235
  return Array.from({ length: count }, (_, index) => database === "postgres" ? `$${index + 1}` : "?").join(", ");
@@ -5827,6 +5874,26 @@ function applyFrontendOverlays(overlayRoot, targetDir, layers) {
5827
5874
  function writeGeneratedFiles(options) {
5828
5875
  const { targetDir, projectName, layers } = options;
5829
5876
  const src = join2(targetDir, "src");
5877
+ if (needsFrontendBuild(layers.frontend)) {
5878
+ const transport = layers.auth.startsWith("cookie") ? "cookie" : layers.auth;
5879
+ const mfa = transport === "cookie" && layers.extras.mfa;
5880
+ writeText(join2(targetDir, "frontend/src/auth/config.ts"), `export type AuthTransport = "cookie" | "token" | "jwt" | "headers";
5881
+ export const AUTH_CONFIG: { transport: AuthTransport; mfa: boolean } = ${JSON.stringify({ transport, mfa })};
5882
+ `);
5883
+ writeText(join2(targetDir, "frontend/src/config.ts"), `import { validateSpaPrefix } from "@getstrata/core/runtime/frontendMode";
5884
+
5885
+ // Generated scripts supply only this public value before Bun starts.
5886
+ export const SPA_PREFIX = validateSpaPrefix(process.env.BUN_PUBLIC_SPA_PREFIX);
5887
+ export const TENANCY_ENABLED = ${usesTenantTable(layers.tenancy)};
5888
+ `);
5889
+ const manifestPath = join2(targetDir, "frontend/package.json");
5890
+ const manifest = JSON.parse(readFileSync2(manifestPath, "utf8"));
5891
+ const publicEnv = `BUN_PUBLIC_SPA_PREFIX="\${SPA_PREFIX:-${layers.spaPrefix}}"`;
5892
+ manifest.scripts.dev = `${publicEnv} bun --hot dev-server.ts`;
5893
+ manifest.scripts.build = `${publicEnv} bun run build.ts`;
5894
+ manifest.scripts.preview = `bun run build && ${publicEnv} bun dev-server.ts --preview`;
5895
+ writeText(manifestPath, JSON.stringify(manifest, null, 2));
5896
+ }
5830
5897
  writeText(join2(targetDir, ".bun-version"), `1.4.3
5831
5898
  `);
5832
5899
  writeText(join2(targetDir, ".env.example"), renderEnvExample(projectName, layers));
@@ -6041,6 +6108,7 @@ Next steps:`);
6041
6108
  }
6042
6109
  function generateProject(options) {
6043
6110
  assertProjectName(options.projectName);
6111
+ const layers = { ...options.layers, spaPrefix: validateSpaPrefix(options.layers.spaPrefix) };
6044
6112
  if (existsSync2(options.targetDir)) {
6045
6113
  if (!options.force) {
6046
6114
  throw new Error(`Directory already exists: ${options.targetDir}`);
@@ -6048,8 +6116,8 @@ function generateProject(options) {
6048
6116
  rmSync2(options.targetDir, { recursive: true, force: true });
6049
6117
  }
6050
6118
  copyTree(options.templateRoot, options.targetDir, options.projectName, new Set(["overlays"]));
6051
- applyFrontendOverlays(options.overlayRoot, options.targetDir, options.layers);
6052
- writeGeneratedFiles(options);
6119
+ applyFrontendOverlays(options.overlayRoot, options.targetDir, layers);
6120
+ writeGeneratedFiles({ ...options, layers });
6053
6121
  }
6054
6122
  async function runCreateStrata(argv, cwd = process.cwd()) {
6055
6123
  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.45",
16
- "@getstrata/cli": "^2.2.45",
17
- "@getstrata/core": "^2.2.45",
15
+ "@getstrata/bootstrap": "^2.2.47",
16
+ "@getstrata/cli": "^2.2.47",
17
+ "@getstrata/core": "^2.2.47",
18
18
  "eta": "^4.6.0"
19
19
  },
20
20
  "devDependencies": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-strata",
3
- "version": "2.2.45",
3
+ "version": "2.2.47",
4
4
  "description": "Create a new Strata app. Interactive wizard; choose each layer; one database engine.",
5
5
  "type": "module",
6
6
  "license": "MIT",