create-strata 2.2.45 → 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/dist/cli.js +127 -57
- package/dist/templates/overlays/spa-react/frontend/build.ts +4 -1
- package/dist/templates/overlays/spa-react/frontend/bunfig.toml +2 -0
- package/dist/templates/overlays/spa-react/frontend/dev-server.ts +19 -8
- package/dist/templates/overlays/spa-react/frontend/src/App.tsx +14 -2
- package/dist/templates/overlays/spa-react/frontend/src/api/client.ts +118 -75
- package/dist/templates/overlays/spa-react/frontend/src/auth/AuthContext.tsx +31 -48
- package/dist/templates/overlays/spa-react/frontend/src/auth/config.ts +6 -0
- package/dist/templates/overlays/spa-react/frontend/src/config.ts +7 -0
- package/dist/templates/overlays/spa-react/frontend/src/examples/notes.ts +25 -0
- package/dist/templates/overlays/spa-react/frontend/src/main.tsx +2 -1
- package/dist/templates/overlays/spa-react/frontend/src/pages/HomePage.tsx +18 -34
- package/dist/templates/overlays/spa-react/frontend/src/pages/LoginPage.tsx +82 -41
- package/dist/templates/package.json +3 -3
- package/package.json +1 -1
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,17 @@ ${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
|
|
2592
|
-
import { currentAuthUser } from "@getstrata/core/auth/authContext";
|
|
2612
|
+
import { AuthManager, GuestGuard } from "@getstrata/core/auth/guard";
|
|
2593
2613
|
import type { ServiceProvider } from "@getstrata/core/contracts/di";
|
|
2594
2614
|
import { envFlagEnabled } from "@getstrata/core/runtime/appEnv";
|
|
2595
2615
|
|
|
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
2616
|
const authProvider: ServiceProvider = {
|
|
2630
2617
|
name: "starter.auth",
|
|
2631
2618
|
register({ container }) {
|
|
2632
|
-
|
|
2619
|
+
const guard = envFlagEnabled(process.env.AUTH_DEV_HEADERS)
|
|
2620
|
+
? new GuestGuard()
|
|
2621
|
+
: { resolve: () => null };
|
|
2622
|
+
container.set(CORE_AUTH_TOKEN, new AuthManager(guard));
|
|
2633
2623
|
},
|
|
2634
2624
|
};
|
|
2635
2625
|
|
|
@@ -2934,6 +2924,10 @@ function renderEnvExample(projectName, layers) {
|
|
|
2934
2924
|
`DATABASE_URL=${defaultDatabaseUrl(layers, projectName)}`,
|
|
2935
2925
|
...postgresAppRoleEnvNotes(layers),
|
|
2936
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
|
+
] : [],
|
|
2937
2931
|
...layers.database === "sqlite" ? [] : [
|
|
2938
2932
|
"# Optional. Point runtime at a different database than DATABASE_URL.",
|
|
2939
2933
|
"# APP_DATABASE_URL="
|
|
@@ -3083,6 +3077,14 @@ function renderEnvExample(projectName, layers) {
|
|
|
3083
3077
|
`)}
|
|
3084
3078
|
`;
|
|
3085
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
|
+
}
|
|
3086
3088
|
function renderDockerCompose(projectName, layers) {
|
|
3087
3089
|
const selected = selectedDockerServices(layers);
|
|
3088
3090
|
if (selected.length === 0) {
|
|
@@ -3098,6 +3100,7 @@ function renderDockerCompose(projectName, layers) {
|
|
|
3098
3100
|
POSTGRES_USER: postgres
|
|
3099
3101
|
POSTGRES_PASSWORD: ${GENERATED_POSTGRES_SUPERUSER_PASSWORD}
|
|
3100
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'])}
|
|
3101
3104
|
ports:
|
|
3102
3105
|
# Localhost only. Do not publish this port on a production host.
|
|
3103
3106
|
- "127.0.0.1:5432:5432"
|
|
@@ -3112,6 +3115,7 @@ function renderDockerCompose(projectName, layers) {
|
|
|
3112
3115
|
environment:
|
|
3113
3116
|
MYSQL_ROOT_PASSWORD: ${GENERATED_MYSQL_ROOT_PASSWORD}
|
|
3114
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'])}
|
|
3115
3119
|
ports:
|
|
3116
3120
|
- "127.0.0.1:3306:3306"
|
|
3117
3121
|
volumes:
|
|
@@ -3126,13 +3130,18 @@ function renderDockerCompose(projectName, layers) {
|
|
|
3126
3130
|
environment:
|
|
3127
3131
|
ADMINER_DEFAULT_SERVER: ${server}
|
|
3128
3132
|
depends_on:
|
|
3129
|
-
|
|
3133
|
+
${server}:
|
|
3134
|
+
condition: service_healthy
|
|
3135
|
+
${renderServiceHealthcheck(["CMD", "php", "-r", "exit(@file_get_contents('http://127.0.0.1:8080/') === false ? 1 : 0);"])}
|
|
3130
3136
|
ports:
|
|
3131
3137
|
- "127.0.0.1:8080:8080"`);
|
|
3132
3138
|
}
|
|
3133
3139
|
if (selectedSet.has("redis")) {
|
|
3134
3140
|
services.push(` redis:
|
|
3135
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'])}
|
|
3136
3145
|
command: ["redis-server", "--requirepass", "\${REDIS_PASSWORD:-dev-redis-change-me}"]
|
|
3137
3146
|
ports:
|
|
3138
3147
|
- "127.0.0.1:6379:6379"`);
|
|
@@ -3140,6 +3149,7 @@ function renderDockerCompose(projectName, layers) {
|
|
|
3140
3149
|
if (selectedSet.has("mailpit")) {
|
|
3141
3150
|
services.push(` mailpit:
|
|
3142
3151
|
image: axllent/mailpit:latest
|
|
3152
|
+
${renderServiceHealthcheck(["CMD", "/mailpit", "readyz"])}
|
|
3143
3153
|
ports:
|
|
3144
3154
|
- "127.0.0.1:1025:1025"
|
|
3145
3155
|
- "127.0.0.1:8025:8025"`);
|
|
@@ -3186,7 +3196,7 @@ function renderDockerfile(layers) {
|
|
|
3186
3196
|
""
|
|
3187
3197
|
];
|
|
3188
3198
|
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", "");
|
|
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", "");
|
|
3190
3200
|
}
|
|
3191
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 . .");
|
|
3192
3202
|
if (frontend) {
|
|
@@ -3228,9 +3238,9 @@ function renderPackageJson(projectName, options = {}) {
|
|
|
3228
3238
|
"@getstrata/cli": "workspace:*",
|
|
3229
3239
|
"@getstrata/core": "workspace:*"
|
|
3230
3240
|
} : {
|
|
3231
|
-
"@getstrata/bootstrap": "^2.2.
|
|
3232
|
-
"@getstrata/cli": "^2.2.
|
|
3233
|
-
"@getstrata/core": "^2.2.
|
|
3241
|
+
"@getstrata/bootstrap": "^2.2.46",
|
|
3242
|
+
"@getstrata/cli": "^2.2.46",
|
|
3243
|
+
"@getstrata/core": "^2.2.46"
|
|
3234
3244
|
};
|
|
3235
3245
|
coreDeps.eta = "^4.6.0";
|
|
3236
3246
|
if (options.layers?.database === "mysql") {
|
|
@@ -3311,7 +3321,7 @@ function renderSupportingToolsReadme(projectName, layers) {
|
|
|
3311
3321
|
const lines = ["## Supporting tools", ""];
|
|
3312
3322
|
if (dockerOn.length > 0) {
|
|
3313
3323
|
const names = dockerOn.map((name) => DOCKER_SERVICE_LABELS[name]).join(", ");
|
|
3314
|
-
lines.push(`Docker Compose includes ${names}.`, "", "```bash", dockerComposeUpCommand(layers), "```", "");
|
|
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.", "");
|
|
3315
3325
|
if (dockerSet.has("adminer")) {
|
|
3316
3326
|
const mysql = layers.database === "mysql";
|
|
3317
3327
|
const system = mysql ? "MySQL" : "PostgreSQL";
|
|
@@ -3548,7 +3558,7 @@ HTML auth kit (restyle \`views/\` and \`public/assets/site.css\`):
|
|
|
3548
3558
|
- Reset password: signed \`/reset-password\` (mail log when \`MAIL_DRIVER=log\`)
|
|
3549
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" : ""}
|
|
3550
3560
|
Cookie name is \`strata_session\`. Forms send CSRF as \`_token\`.
|
|
3551
|
-
` : ""}${authUsesCookie(layers.auth) && (layers.frontend === "api" || layers.frontend === "spa-react") ? `
|
|
3561
|
+
` : ""}${authUsesCookie(layers.auth) && (layers.frontend === "api" || layers.frontend === "spa-react" || layers.frontend === "hybrid") ? `
|
|
3552
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 }\`.
|
|
3553
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" : ""}
|
|
3554
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.
|
|
@@ -3620,6 +3630,7 @@ The image sets \`APP_ENV=production\` and \`AUTH_DEV_HEADERS=false\`; everything
|
|
|
3620
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.
|
|
3621
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\`.
|
|
3622
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" : ""}
|
|
3623
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\`).
|
|
3624
3635
|
`;
|
|
3625
3636
|
}
|
|
@@ -3630,6 +3641,7 @@ function renderInitialAdminMigration(layers) {
|
|
|
3630
3641
|
return null;
|
|
3631
3642
|
const driver = layers.database === "postgres" ? "pgsql" : layers.database;
|
|
3632
3643
|
return `import { Schema } from "@getstrata/core/database/schema";
|
|
3644
|
+
import { guardMigrationRollback } from "@getstrata/core/database/migrations";
|
|
3633
3645
|
import type { Migration } from "@getstrata/core/database/migrations/types";
|
|
3634
3646
|
|
|
3635
3647
|
const migration: Migration = {
|
|
@@ -3643,10 +3655,11 @@ const migration: Migration = {
|
|
|
3643
3655
|
});
|
|
3644
3656
|
});
|
|
3645
3657
|
},
|
|
3646
|
-
async down(db) {
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
|
|
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
|
+
});
|
|
3650
3663
|
await Schema.run(db, "${driver}", schema => { schema.drop("initial_admin_provisioning"); });
|
|
3651
3664
|
},
|
|
3652
3665
|
};
|
|
@@ -4082,6 +4095,33 @@ export async function withMigrationDatabase<T>(
|
|
|
4082
4095
|
await admin.close?.();
|
|
4083
4096
|
}
|
|
4084
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
|
+
}
|
|
4085
4125
|
`;
|
|
4086
4126
|
}
|
|
4087
4127
|
return `import { join } from "node:path";
|
|
@@ -4640,7 +4680,8 @@ export async function ensureAppDatabase(options: { provision?: boolean } = {}):
|
|
|
4640
4680
|
}
|
|
4641
4681
|
const name = safeDatabaseName(url);
|
|
4642
4682
|
|
|
4643
|
-
|
|
4683
|
+
// Explicit schema operations use the administrative connection when supplied.
|
|
4684
|
+
const admin = new URL(process.env.MIGRATION_DATABASE_URL?.trim() || url);
|
|
4644
4685
|
admin.pathname = "/";
|
|
4645
4686
|
const connection = await createConnection(admin.toString());
|
|
4646
4687
|
try {
|
|
@@ -5096,12 +5137,20 @@ function billingMigrationName(layers) {
|
|
|
5096
5137
|
}
|
|
5097
5138
|
return layers.extras.webhooks ? "0003_billing_schema" : "0002_billing_schema";
|
|
5098
5139
|
}
|
|
5099
|
-
function renderFileMigration(name, upSql, downSql) {
|
|
5140
|
+
function renderFileMigration(name, upSql, downSql, columnCleanup) {
|
|
5100
5141
|
const upCalls = upSql.map((sql) => ` await db.unsafe(${JSON.stringify(sql)});`).join(`
|
|
5101
5142
|
`);
|
|
5102
5143
|
const downCalls = downSql.map((sql) => ` await db.unsafe(${JSON.stringify(sql)});`).join(`
|
|
5103
5144
|
`);
|
|
5104
|
-
|
|
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";
|
|
5105
5154
|
|
|
5106
5155
|
const migration: Migration = {
|
|
5107
5156
|
name: ${JSON.stringify(name)},
|
|
@@ -5109,7 +5158,7 @@ const migration: Migration = {
|
|
|
5109
5158
|
${upCalls}
|
|
5110
5159
|
},
|
|
5111
5160
|
async down(db) {
|
|
5112
|
-
${downCalls}
|
|
5161
|
+
${downCalls}${dropColumn}
|
|
5113
5162
|
},
|
|
5114
5163
|
};
|
|
5115
5164
|
|
|
@@ -5182,7 +5231,7 @@ function renderBillingMigration(layers) {
|
|
|
5182
5231
|
`DROP TABLE IF EXISTS stripe_webhook_event${cascade}`,
|
|
5183
5232
|
`DROP TABLE IF EXISTS subscription${cascade}`
|
|
5184
5233
|
];
|
|
5185
|
-
return renderFileMigration(name, up, down);
|
|
5234
|
+
return renderFileMigration(name, up, down, tenancyOn ? { database: layers.database, table: "tenant", column: "stripe_customer_id" } : undefined);
|
|
5186
5235
|
}
|
|
5187
5236
|
function sqlParams(database, count) {
|
|
5188
5237
|
return Array.from({ length: count }, (_, index) => database === "postgres" ? `$${index + 1}` : "?").join(", ");
|
|
@@ -5827,6 +5876,26 @@ function applyFrontendOverlays(overlayRoot, targetDir, layers) {
|
|
|
5827
5876
|
function writeGeneratedFiles(options) {
|
|
5828
5877
|
const { targetDir, projectName, layers } = options;
|
|
5829
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
|
+
}
|
|
5830
5899
|
writeText(join2(targetDir, ".bun-version"), `1.4.3
|
|
5831
5900
|
`);
|
|
5832
5901
|
writeText(join2(targetDir, ".env.example"), renderEnvExample(projectName, layers));
|
|
@@ -6041,6 +6110,7 @@ Next steps:`);
|
|
|
6041
6110
|
}
|
|
6042
6111
|
function generateProject(options) {
|
|
6043
6112
|
assertProjectName(options.projectName);
|
|
6113
|
+
const layers = { ...options.layers, spaPrefix: validateSpaPrefix(options.layers.spaPrefix) };
|
|
6044
6114
|
if (existsSync2(options.targetDir)) {
|
|
6045
6115
|
if (!options.force) {
|
|
6046
6116
|
throw new Error(`Directory already exists: ${options.targetDir}`);
|
|
@@ -6048,8 +6118,8 @@ function generateProject(options) {
|
|
|
6048
6118
|
rmSync2(options.targetDir, { recursive: true, force: true });
|
|
6049
6119
|
}
|
|
6050
6120
|
copyTree(options.templateRoot, options.targetDir, options.projectName, new Set(["overlays"]));
|
|
6051
|
-
applyFrontendOverlays(options.overlayRoot, options.targetDir,
|
|
6052
|
-
writeGeneratedFiles(options);
|
|
6121
|
+
applyFrontendOverlays(options.overlayRoot, options.targetDir, layers);
|
|
6122
|
+
writeGeneratedFiles({ ...options, layers });
|
|
6053
6123
|
}
|
|
6054
6124
|
async function runCreateStrata(argv, cwd = process.cwd()) {
|
|
6055
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:
|
|
8
|
+
publicPath: `${SPA_PREFIX}/`,
|
|
9
|
+
env: "BUN_PUBLIC_*",
|
|
7
10
|
});
|
|
8
11
|
|
|
9
12
|
if (!result.success) {
|
|
@@ -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
|
-
|
|
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 =
|
|
27
|
-
|
|
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
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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}
|
|
65
|
-
: `SPA dev server on ${server.url}
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
94
|
-
|
|
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 {
|
|
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 {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
-
|
|
54
|
-
|
|
55
|
-
|
|
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
|
|
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
|
-
|
|
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,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=
|
|
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
|
-
|
|
11
|
-
|
|
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
|
|
38
|
-
|
|
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>{
|
|
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
|
-
|
|
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 : "
|
|
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">
|
|
37
|
-
|
|
38
|
-
|
|
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
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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.
|
|
16
|
-
"@getstrata/cli": "^2.2.
|
|
17
|
-
"@getstrata/core": "^2.2.
|
|
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": {
|