@getstrata/starter 3.1.0 → 3.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @getstrata/starter
|
|
2
2
|
|
|
3
|
-
The application generator for [Strata](https://github.com/EyK-26/strata/blob/main/README.md). Requires Bun >=1.4.4; tested on Bun 1.4.4.
|
|
3
|
+
The application generator for [Strata](https://github.com/EyK-26/strata/blob/main/README.md), a Laravel-inspired Bun and TypeScript framework. Requires Bun >=1.4.4; tested on Bun 1.4.4.
|
|
4
4
|
|
|
5
5
|
Use the short package name:
|
|
6
6
|
|
|
@@ -27,3 +27,5 @@ Generated apps contain model classes in `src/models`, named controllers in `src/
|
|
|
27
27
|
Follow the generated README to configure the environment, start selected services, install dependencies, migrate, and run the app. Choices are recorded in `strata.layers.json`; the generated file inventory is in `.strata/generator.json`.
|
|
28
28
|
|
|
29
29
|
See the [project README](https://github.com/EyK-26/strata/blob/main/README.md), [starter and layer options](https://github.com/EyK-26/strata/blob/main/docs/STARTER.md), [authentication](https://github.com/EyK-26/strata/blob/main/docs/AUTH.md), [integrations](https://github.com/EyK-26/strata/blob/main/docs/INTEGRATIONS.md), and [production](https://github.com/EyK-26/strata/blob/main/docs/PRODUCTION.md).
|
|
30
|
+
|
|
31
|
+
Generated apps include an `AGENTS.md` tailored to their selected stack, with application feature workflows and validation guidance for AI coding agents.
|
package/dist/cli.js
CHANGED
|
@@ -388,17 +388,17 @@ function compileStarterFeatures(input, reference) {
|
|
|
388
388
|
browserTransport: cookie ? "cookie" : layers.auth
|
|
389
389
|
});
|
|
390
390
|
const artifacts = [
|
|
391
|
+
"AGENTS.md",
|
|
391
392
|
"package.json",
|
|
392
393
|
"src/bootstrap/createApp.ts",
|
|
393
394
|
"src/routes/api.ts",
|
|
394
395
|
"src/routes/web.ts",
|
|
395
396
|
"src/routes/index.ts",
|
|
396
|
-
"src/models/Note.ts",
|
|
397
397
|
"src/models/register.ts",
|
|
398
398
|
"src/db/migrations/0001_starter_schema.ts"
|
|
399
399
|
];
|
|
400
400
|
if (decisions.users)
|
|
401
|
-
artifacts.push("src/http/controllers/AuthController.ts", "src/http/auth/account.ts", "src/models/User.ts", "src/models/AuthOneTimeToken.ts", "src/db/migrations/0006_account_state.ts");
|
|
401
|
+
artifacts.push("src/http/controllers/AuthController.ts", "src/http/auth/account.ts", "src/models/User.ts", "src/db/factories/UserFactory.ts", "src/models/AuthOneTimeToken.ts", "src/db/migrations/0006_account_state.ts");
|
|
402
402
|
if (decisions.cookie)
|
|
403
403
|
artifacts.push("src/http/controllers/AuthWebController.ts");
|
|
404
404
|
if (decisions.serverViews)
|
|
@@ -418,7 +418,7 @@ function compileStarterFeatures(input, reference) {
|
|
|
418
418
|
if (layers.extras.billing)
|
|
419
419
|
artifacts.push("src/billing/applyStripeWebhook.ts", "src/http/controllers/BillingController.ts");
|
|
420
420
|
if (layers.extras.webhooks)
|
|
421
|
-
artifacts.push("src/jobs/dispatchOutboundWebhookJob.ts", "src/
|
|
421
|
+
artifacts.push("src/jobs/dispatchOutboundWebhookJob.ts", "src/webhooks/dispatchWebhook.ts");
|
|
422
422
|
if (decisions.workTracker)
|
|
423
423
|
artifacts.push("docs/WORK_TRACKER.md", "src/domain/workTracker.ts", "src/models/workTracker.ts", "src/http/controllers/WorkTrackerController.ts", "src/http/requests/WorkRequest.ts", "src/db/migrations/0007_work_tracker.ts");
|
|
424
424
|
return Object.freeze({
|
|
@@ -1171,7 +1171,7 @@ var EXTRA_CHOICES = [
|
|
|
1171
1171
|
{ value: "oauthGithub", label: "oauth-github: GitHub cookie login at /auth/github" },
|
|
1172
1172
|
{ value: "oidc", label: "oidc: OIDC cookie login at /auth/oidc (PKCE cookie)" },
|
|
1173
1173
|
{ value: "billing", label: "billing: Stripe webhook stub + GET /api/v1/billing/subscription" },
|
|
1174
|
-
{ value: "webhooks", label: "webhooks: outbound
|
|
1174
|
+
{ value: "webhooks", label: "webhooks: outbound event delivery (webhook.dispatch)" }
|
|
1175
1175
|
];
|
|
1176
1176
|
function isInteractive(flags) {
|
|
1177
1177
|
if (flags.yes || flags.noInteractive) {
|
|
@@ -1397,6 +1397,135 @@ async function resolveStarterPlan(flags, injected) {
|
|
|
1397
1397
|
}
|
|
1398
1398
|
}
|
|
1399
1399
|
|
|
1400
|
+
// src/renderAgentInstructions.ts
|
|
1401
|
+
function renderAgentInstructions(projectName, plan) {
|
|
1402
|
+
const { layers, decisions, services } = plan;
|
|
1403
|
+
const extras = Object.entries(layers.extras).filter(([, enabled]) => enabled).map(([name]) => name).sort();
|
|
1404
|
+
return `# Building ${projectName}
|
|
1405
|
+
|
|
1406
|
+
This is an application built with Strata, TypeScript and Bun. Build product features
|
|
1407
|
+
in this app using the installed public APIs; do not recreate framework internals or
|
|
1408
|
+
edit node_modules. Follow Laravel-style organization where it fits TypeScript.
|
|
1409
|
+
|
|
1410
|
+
## Start here
|
|
1411
|
+
|
|
1412
|
+
Read README.md, package.json and the files involved in the feature. Installed package
|
|
1413
|
+
versions and current application code take precedence over generic examples. Runtime
|
|
1414
|
+
choices live in src/config/app.ts and environment configuration. strata.layers.json
|
|
1415
|
+
records generation choices; editing it does not reconfigure the application.
|
|
1416
|
+
Update this guide when the app's structure or stack changes. Do not print secrets
|
|
1417
|
+
from .env or commit credentials.
|
|
1418
|
+
|
|
1419
|
+
Starting stack: frontend=${layers.frontend}; database=${layers.database}; auth=${layers.auth};
|
|
1420
|
+
tenancy=${layers.tenancy}; cache=${layers.cache}; queue=${layers.queue}; mail=${layers.mail}.
|
|
1421
|
+
Selected extras: ${extras.join(", ") || "none"}.
|
|
1422
|
+
|
|
1423
|
+
## Where features belong
|
|
1424
|
+
|
|
1425
|
+
- src/routes/api.ts and src/routes/web.ts: endpoints and their middleware.
|
|
1426
|
+
- src/http/controllers/: named actions; create a controller when needed.
|
|
1427
|
+
- src/http/requests/: input validation and request authorization when needed.
|
|
1428
|
+
- src/policies/: resource access rules when needed.
|
|
1429
|
+
- src/models/: model classes; add new classes to src/models/register.ts.
|
|
1430
|
+
- src/db/migrations/: explicit schema changes, separate from model declarations.
|
|
1431
|
+
${decisions.users ? `- src/db/factories/UserFactory.ts: user test data with explicit credentials and invocation-owned persistence.
|
|
1432
|
+
` : ""}- src/db/seed.ts: explicit development-only seed entrypoint.
|
|
1433
|
+
- src/config/app.ts and src/bootstrap/: configuration and dependency composition.
|
|
1434
|
+
${decisions.serverViews || decisions.mfaViews ? `- views/: Eta templates; use the existing view rendering and escaping helpers.
|
|
1435
|
+
` : ""}${decisions.frontendBuild ? `- frontend/: React UI built by Bun; preserve the configured SPA prefix (${layers.spaPrefix}).
|
|
1436
|
+
` : ""}
|
|
1437
|
+
Optional folders need not exist until their first feature is added. Larger domains
|
|
1438
|
+
may use modules; ordinary CRUD needs no module, forwarding service or repository layer.
|
|
1439
|
+
|
|
1440
|
+
## Add a feature
|
|
1441
|
+
|
|
1442
|
+
Use the local CLI from this directory; inspect each command's help before guessing flags:
|
|
1443
|
+
|
|
1444
|
+
\`\`\`sh
|
|
1445
|
+
bunx strata make:model Product
|
|
1446
|
+
bunx strata make:migration create_products
|
|
1447
|
+
bunx strata make:controller ProductController
|
|
1448
|
+
bunx strata make:request StoreProductRequest
|
|
1449
|
+
bunx strata make:policy ProductPolicy
|
|
1450
|
+
\`\`\`
|
|
1451
|
+
|
|
1452
|
+
1. Declare model fields once with defineModel and field from
|
|
1453
|
+
@getstrata/core/database/model. Infer row types with ModelAttributes when needed.
|
|
1454
|
+
Put relationships on the model class, for example
|
|
1455
|
+
category() { return this.belongsTo(Category, "category_id"); }.
|
|
1456
|
+
Register both model classes. Ordinary models need no separate XxxRepository.
|
|
1457
|
+
2. Implement a new migration for the actual table/columns/indexes. Model declarations
|
|
1458
|
+
do not change the database. Keep applied migrations intact.
|
|
1459
|
+
3. Validate input in a request and authorize the operation/resource. A fillable list
|
|
1460
|
+
is not authorization. Derive identity/ownership values from trusted context.
|
|
1461
|
+
4. Put application behavior in the controller or a service that adds real domain
|
|
1462
|
+
behavior. Register routes through the existing kernel/middleware composition.
|
|
1463
|
+
5. Query through database.model(Product), or transaction.model(Product) inside its
|
|
1464
|
+
transaction. Never cache a request session, identity or bound model in a singleton.
|
|
1465
|
+
Keep after-commit effects inside the existing transaction-aware workflow.
|
|
1466
|
+
6. Add focused tests for successful, denied and invalid operations. Check persisted
|
|
1467
|
+
outcomes and rollback when a feature changes data.
|
|
1468
|
+
|
|
1469
|
+
Use @getstrata/core/... and @getstrata/bootstrap/... public subpaths. Inspect installed
|
|
1470
|
+
types and neighboring app code before inventing an API. Pass narrow dependencies to
|
|
1471
|
+
controllers; do not pass the whole container. Prefer native Bun HTTP, SQL, streaming
|
|
1472
|
+
and image capabilities through Strata's APIs instead of adding duplicate frameworks.
|
|
1473
|
+
|
|
1474
|
+
## Access and the selected stack
|
|
1475
|
+
|
|
1476
|
+
${layers.auth === "headers" ? `Development header auth is selected. It is not a production login mechanism; adopt an appropriate real guard before exposing private data.
|
|
1477
|
+
` : `Keep the generated authentication and account-state checks. Authentication, abilities and resource policies are separate checks; do not bypass them in a new endpoint.
|
|
1478
|
+
`}${decisions.cookie ? `Preserve the existing cookie/CSRF handshake and server-side session handling. Do not store session credentials in browser storage or mint cookies in controllers.
|
|
1479
|
+
` : ""}${decisions.token || decisions.jwt ? `Preserve bearer-token/JWT verification and expiry. Do not persist bearer credentials in localStorage or sessionStorage, or treat unverified claims as identity.
|
|
1480
|
+
` : ""}${decisions.rls ? `PostgreSQL RLS is selected. Keep runtime access on the restricted app role and tenant policy inside the owned transaction; administrative migration credentials never belong in request handlers.
|
|
1481
|
+
` : decisions.tenantTable ? `Column tenancy is selected. Explicitly filter tenant-owned reads and writes using the trusted current tenant; a tenant_id column alone does not isolate records.
|
|
1482
|
+
` : `No tenancy is selected. Do not invent tenant fields or middleware without adding the corresponding schema and application policy.
|
|
1483
|
+
`}${layers.database === "sqlite" ? `SQLite is selected. Use its configured file and portable schema/query APIs; do not assume PostgreSQL RLS or full-text operators are available.
|
|
1484
|
+
` : ""}${decisions.redisQueue ? `Redis queued work needs a separate bun run queue:work process. Make job effects idempotent and preserve retry/cancellation semantics.
|
|
1485
|
+
` : `The queue is synchronous; HTTP startup does not create a background queue worker.
|
|
1486
|
+
`}Only run bun run outbox:work when this application uses SQL durable listeners.
|
|
1487
|
+
${layers.mail === "log" ? `Mail is logged locally; configure an actual mail transport before relying on delivered account emails.
|
|
1488
|
+
` : `SMTP is selected; use the configured transport and preserve failure/retry handling without logging credentials.
|
|
1489
|
+
`}
|
|
1490
|
+
## Commands and validation
|
|
1491
|
+
|
|
1492
|
+
Use the Bun version in .bun-version. Follow README.md for environment setup and
|
|
1493
|
+
${services.docker.length ? `selected Docker services (${services.docker.join(", ")}).` : services.local.length ? `local services (${services.local.join(", ")}).` : "local startup; this selection needs no supporting service containers."}
|
|
1494
|
+
|
|
1495
|
+
\`\`\`sh
|
|
1496
|
+
bun install
|
|
1497
|
+
bun run check
|
|
1498
|
+
bun run db:migrate
|
|
1499
|
+
bun run dev
|
|
1500
|
+
${decisions.frontendBuild ? `bun run frontend:install
|
|
1501
|
+
bun run frontend:build
|
|
1502
|
+
` : ""}\`\`\`
|
|
1503
|
+
|
|
1504
|
+
Run migrations against the intended development database after reviewing the changes.
|
|
1505
|
+
db:fresh is destructive; never use it on shared or production data. Demo seeds are
|
|
1506
|
+
development-only. Use disposable test data. Run existing focused tests with bun test
|
|
1507
|
+
when present; do not assume this app defines test, lint or framework-monorepo scripts.
|
|
1508
|
+
Inspect package.json for additional commands and add application tests where needed.
|
|
1509
|
+
|
|
1510
|
+
Keep changes small and inspect the diff. Avoid reading unrelated files or repeatedly
|
|
1511
|
+
running full suites. Recheck affected behavior after edits; report what ran and what
|
|
1512
|
+
remains unverified. Do not replace a failed check with a weaker assertion. Keep new
|
|
1513
|
+
dependencies, public APIs and infrastructure proportional to the product requirement.
|
|
1514
|
+
|
|
1515
|
+
## Framework reference
|
|
1516
|
+
|
|
1517
|
+
- [Application workflow](https://github.com/EyK-26/strata/blob/main/docs/BUILDING-APPS.md)
|
|
1518
|
+
- [Models and migrations](https://github.com/EyK-26/strata/blob/main/docs/DATABASE.md)
|
|
1519
|
+
- [Authentication](https://github.com/EyK-26/strata/blob/main/docs/AUTH.md)
|
|
1520
|
+
- [Tenancy](https://github.com/EyK-26/strata/blob/main/docs/TENANCY.md)
|
|
1521
|
+
- [Uploads and images](https://github.com/EyK-26/strata/blob/main/docs/MEDIA.md)
|
|
1522
|
+
|
|
1523
|
+
Documentation on main may be newer than the installed release. Keep this app's
|
|
1524
|
+
versions and public type contracts authoritative. Adding a feature should not require
|
|
1525
|
+
studying Strata's contributor workspace or changing framework package versions.
|
|
1526
|
+
`;
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1400
1529
|
// src/controllerActions.ts
|
|
1401
1530
|
class ControllerActions {
|
|
1402
1531
|
className;
|
|
@@ -1423,8 +1552,9 @@ class ControllerActions {
|
|
|
1423
1552
|
const indentation = Math.min(...lines.filter((line) => line.trim()).map((line) => line.match(/^\s*/)?.[0].length ?? 0));
|
|
1424
1553
|
const formatted = lines.map((line) => line.trim() ? ` ${line.slice(indentation)}` : "").join(`
|
|
1425
1554
|
`);
|
|
1426
|
-
|
|
1427
|
-
|
|
1555
|
+
const usedScope = scope.filter((binding) => new RegExp(`\\b${binding}\\b`).test(handler));
|
|
1556
|
+
return ` ${name}: BusinessRouteHandler = ${signature} => {${usedScope.length ? `
|
|
1557
|
+
const { ${usedScope.join(", ")} } = this;` : ""}
|
|
1428
1558
|
${formatted}
|
|
1429
1559
|
};`;
|
|
1430
1560
|
});
|
|
@@ -1811,7 +1941,7 @@ ${renderMfaChallengeRoutes(actions)}
|
|
|
1811
1941
|
}`)}),
|
|
1812
1942
|
},
|
|
1813
1943
|
"/api/v1/auth/logout": {
|
|
1814
|
-
POST: kernel.wrap("api", ${cookie ? "kernel.wrapIdentity(" : ""}${renderAction(actions, "logoutBearer", `async (request, _ports) => {
|
|
1944
|
+
POST: kernel.wrap("api", ${cookie ? "kernel.wrapIdentity(" : ""}${renderAction(actions, "logoutBearer", `async (${cookie ? "request" : "_request"}, _ports) => {
|
|
1815
1945
|
const payload = privateJsonResponse({ ok: true });
|
|
1816
1946
|
${cookie ? `const sessionAuth = authServices.session(_ports);
|
|
1817
1947
|
const { setCookie } = await sessionAuth.signOut(request);
|
|
@@ -2174,6 +2304,95 @@ function renderAuthImports({
|
|
|
2174
2304
|
return imports;
|
|
2175
2305
|
}
|
|
2176
2306
|
|
|
2307
|
+
// src/auth/renderHttpImports.ts
|
|
2308
|
+
function renderAuthHttpImports(context, target) {
|
|
2309
|
+
const { plan, cookie, mfa, verify, github, oidc, jsonAccounts, jsonCookieAccounts } = context;
|
|
2310
|
+
const apiMfa = jsonCookieAccounts && mfa;
|
|
2311
|
+
const browserMfa = plan.decisions.mfaViews;
|
|
2312
|
+
const names = new Set(["StarterAuthServices"]);
|
|
2313
|
+
const add = (...values) => {
|
|
2314
|
+
for (const value of values)
|
|
2315
|
+
names.add(value);
|
|
2316
|
+
};
|
|
2317
|
+
if (target === "account") {
|
|
2318
|
+
add("prepareAccountMail", "registerAccount", "completeAccountToken", "authenticatePasswordAccount", "withLoginAccount", "BusinessRequestPorts", "SelectedSession", "isUniqueConstraintError", "hashPassword", "AUTH_ONE_TIME_PURPOSES", "consumeOneTimeToken", "generateOneTimeToken", "hashOneTimeToken", "revokeStoredUserSessions", "persistConsumedRecoveryHash", "absoluteTemporarySignedUrl", "createStarterAuthDirectory", "withAuthIdentifier", "runWithLockedAuthUser", "StarterAuthUserRecord", "User", "AuthOneTimeToken");
|
|
2319
|
+
if (cookie)
|
|
2320
|
+
add("randomBytes", "privateJsonResponse");
|
|
2321
|
+
if (mfa)
|
|
2322
|
+
add("ConflictError", "generateRecoveryCodes", "hashRecoveryCode");
|
|
2323
|
+
} else {
|
|
2324
|
+
add("parseLoginCredentials");
|
|
2325
|
+
if (target === "web" || jsonAccounts)
|
|
2326
|
+
add("parseRegisterCredentials", "parseForgotPasswordEmail", "hashPassword", "AUTH_ONE_TIME_PURPOSES");
|
|
2327
|
+
if (target === "web") {
|
|
2328
|
+
add("parseFormBody", "flashResponse");
|
|
2329
|
+
if (mfa)
|
|
2330
|
+
add("verifyPassword", "completePasswordLogin", "createPasswordConfirmCookie", "sanitizeInternalPath", "buildOtpauthUrl", "generateTotpSecret", "verifyTotp");
|
|
2331
|
+
if (verify)
|
|
2332
|
+
add("assertValidSignature");
|
|
2333
|
+
} else {
|
|
2334
|
+
add("parseJsonBody", "privateJsonResponse", "resolveCsrfTokenForRequest");
|
|
2335
|
+
if (plan.decisions.token)
|
|
2336
|
+
add("randomBytes", "hashApiToken", "ApiToken");
|
|
2337
|
+
if (plan.decisions.jwt)
|
|
2338
|
+
add("signJwt");
|
|
2339
|
+
if (cookie)
|
|
2340
|
+
add("createSamlStateCookie", "verifySamlState", "clearSamlStateCookie");
|
|
2341
|
+
if (github)
|
|
2342
|
+
add("GitHubOAuthProvider", "createOAuthStateCookie", "clearOAuthStateCookie", "verifyOAuthState");
|
|
2343
|
+
if (oidc)
|
|
2344
|
+
add("OidcProvider", "createOAuthState", "verifySignedOAuthStateValue", "clearOidcPkceCookie", "readOidcPkceCookie", "sealOidcPkceCookie");
|
|
2345
|
+
if (browserMfa)
|
|
2346
|
+
add("parseFormBody", "completePasswordLogin");
|
|
2347
|
+
if (jsonCookieAccounts && (mfa || verify))
|
|
2348
|
+
add("ConflictError");
|
|
2349
|
+
if (apiMfa)
|
|
2350
|
+
add("verifyPassword", "createPasswordConfirmCookie", "required", "stringRule", "validateObject", "buildOtpauthUrl", "generateTotpSecret", "verifyTotp");
|
|
2351
|
+
}
|
|
2352
|
+
}
|
|
2353
|
+
const imports = renderAuthImports(context).flatMap((line) => {
|
|
2354
|
+
const match = /^(import (?:type )?\{ )(.+)( \} from .+;)$/.exec(line);
|
|
2355
|
+
if (!match)
|
|
2356
|
+
throw new Error(`Unsupported auth import declaration: ${line}`);
|
|
2357
|
+
const bindings = (match[2] ?? "").split(", ").filter((binding) => names.has(binding.split(" as ").at(-1)?.replace(/^type /, "") ?? ""));
|
|
2358
|
+
return bindings.length ? [`${match[1]}${bindings.join(", ")}${match[3]}`] : [];
|
|
2359
|
+
});
|
|
2360
|
+
if (target !== "account") {
|
|
2361
|
+
imports.push('import type { BusinessRouteHandler } from "@getstrata/bootstrap/persistenceContracts";');
|
|
2362
|
+
if (target === "web" || browserMfa)
|
|
2363
|
+
imports.push('import type { NamespacedViewRenderer } from "@getstrata/core/view";');
|
|
2364
|
+
const helpers = ["authenticatePasswordUser", "runWithLoginUser"];
|
|
2365
|
+
if (target === "web" || jsonAccounts)
|
|
2366
|
+
helpers.push("issueSignedAuthMail", "createRegistration", "completeSignedPasswordReset");
|
|
2367
|
+
if (target === "web") {
|
|
2368
|
+
helpers.push("redirectTo", "sessionUser");
|
|
2369
|
+
if (mfa)
|
|
2370
|
+
helpers.push("runWithLockedAccount", "persistAuthRecovery", "enrollMfa");
|
|
2371
|
+
if (verify)
|
|
2372
|
+
helpers.push("deferAuthEffect", "completeSignedEmailVerification");
|
|
2373
|
+
} else {
|
|
2374
|
+
if (plan.decisions.token)
|
|
2375
|
+
helpers.push("authTimestamp", "runAuthWrite");
|
|
2376
|
+
if (cookie)
|
|
2377
|
+
helpers.push("sessionUser", "completeBrowserSsoLogin");
|
|
2378
|
+
if (plan.decisions.jsonVerification)
|
|
2379
|
+
helpers.push("completeSignedEmailVerification");
|
|
2380
|
+
if (jsonAccounts && verify)
|
|
2381
|
+
helpers.push("deferAuthEffect");
|
|
2382
|
+
if (apiMfa || browserMfa || jsonCookieAccounts && verify)
|
|
2383
|
+
helpers.push("runWithLockedAccount");
|
|
2384
|
+
if (browserMfa)
|
|
2385
|
+
helpers.push("persistAuthRecovery", "redirectTo");
|
|
2386
|
+
if (apiMfa)
|
|
2387
|
+
helpers.push("enrollMfa");
|
|
2388
|
+
}
|
|
2389
|
+
imports.push(`import { ${helpers.join(", ")} } from "../auth/account.ts";`);
|
|
2390
|
+
}
|
|
2391
|
+
return `${imports.join(`
|
|
2392
|
+
`)}
|
|
2393
|
+
`;
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2177
2396
|
// src/auth/renderingContext.ts
|
|
2178
2397
|
function createAuthRenderingContext(plan) {
|
|
2179
2398
|
const { cookie, github, oidc, mfa, bearerApi, jsonCookieAccounts, jsonAccounts } = plan.decisions;
|
|
@@ -2258,7 +2477,7 @@ async function issueSignedAuthMail(ports: BusinessRequestPorts, services: Starte
|
|
|
2258
2477
|
await deferAuthEffect(ports, () => services.mail.send(message));
|
|
2259
2478
|
}
|
|
2260
2479
|
|
|
2261
|
-
async function createRegistration(ports: BusinessRequestPorts, services: StarterAuthServices, credentials: { name: string; email: string; password: string }${verify ? ", verificationPath: string" : ""}) {
|
|
2480
|
+
async function createRegistration(ports: BusinessRequestPorts, ${verify ? "services" : "_services"}: StarterAuthServices, credentials: { name: string; email: string; password: string }${verify ? ", verificationPath: string" : ""}) {
|
|
2262
2481
|
const { email } = credentials;
|
|
2263
2482
|
return registerAccount(ports, email, {
|
|
2264
2483
|
write: runAuthWrite, transaction: runAuthTransaction,
|
|
@@ -2282,11 +2501,11 @@ async function consumeSignedAuthToken(ports: BusinessRequestPorts, request: Requ
|
|
|
2282
2501
|
return await runAuthWrite(ports, hashOneTimeToken(token), async (ports) => consumeOneTimeToken(ports.database, purpose, token));
|
|
2283
2502
|
}
|
|
2284
2503
|
|
|
2285
|
-
async function revokeUserSessions(ports: BusinessRequestPorts, userId: number) {
|
|
2504
|
+
${mfa ? `async function revokeUserSessions(ports: BusinessRequestPorts, userId: number) {
|
|
2286
2505
|
await runAuthWrite(ports, userId, async (ports) => {
|
|
2287
2506
|
await revokeStoredUserSessions(ports.database, userId, { incrementAuthVersion: true });
|
|
2288
2507
|
});
|
|
2289
|
-
}
|
|
2508
|
+
}` : ""}
|
|
2290
2509
|
|
|
2291
2510
|
${verify ? `
|
|
2292
2511
|
async function completeSignedEmailVerification(ports: BusinessRequestPorts, request: Request): Promise<boolean> {
|
|
@@ -2434,8 +2653,7 @@ function renderAuthHttp(plan) {
|
|
|
2434
2653
|
if (!plan.decisions.users)
|
|
2435
2654
|
return null;
|
|
2436
2655
|
const context = createAuthRenderingContext(plan);
|
|
2437
|
-
const imports =
|
|
2438
|
-
`);
|
|
2656
|
+
const imports = renderAuthHttpImports(context, "account");
|
|
2439
2657
|
const helperNames = [
|
|
2440
2658
|
"runWithLockedAccount",
|
|
2441
2659
|
"authTimestamp",
|
|
@@ -2455,14 +2673,6 @@ function renderAuthHttp(plan) {
|
|
|
2455
2673
|
${renderAuthHelpers(context)}
|
|
2456
2674
|
${renderMfaEnrollment(context.mfa)}
|
|
2457
2675
|
export { ${helperNames.join(", ")} };
|
|
2458
|
-
`;
|
|
2459
|
-
const controllerDependencies = renderAuthImports(context).filter((line) => !line.includes("AppModule") && !line.includes("CORE_VIEW_RENDERER_TOKEN") && !line.includes("wrapWebLogin")).map((line) => line.includes("STARTER_AUTH_SERVICES") ? 'import type { StarterAuthServices } from "../../bootstrap/auth.ts";' : line).join(`
|
|
2460
|
-
`);
|
|
2461
|
-
const controllerImports = `${controllerDependencies}
|
|
2462
|
-
${context.cookie ? `import type { NamespacedViewRenderer } from "@getstrata/core/view";
|
|
2463
|
-
` : ""}
|
|
2464
|
-
import type { BusinessRouteHandler } from "@getstrata/bootstrap/persistenceContracts";
|
|
2465
|
-
import { ${helperNames.join(", ")} } from "../auth/account.ts";
|
|
2466
2676
|
`;
|
|
2467
2677
|
const apiActions = new ControllerActions("AuthController");
|
|
2468
2678
|
const api = renderApiAuthRoutes(context, apiActions);
|
|
@@ -2470,12 +2680,12 @@ import { ${helperNames.join(", ")} } from "../auth/account.ts";
|
|
|
2470
2680
|
const construction = (views) => ` constructor(private readonly authServices: StarterAuthServices${views ? ", private readonly views: NamespacedViewRenderer" : ""}) {}`;
|
|
2471
2681
|
const files = {
|
|
2472
2682
|
"http/auth/account.ts": helpers,
|
|
2473
|
-
"http/controllers/AuthController.ts":
|
|
2683
|
+
"http/controllers/AuthController.ts": renderAuthHttpImports(context, "api") + apiActions.render(construction(plan.decisions.mfaViews), apiScope)
|
|
2474
2684
|
};
|
|
2475
2685
|
const webActions = new ControllerActions("AuthWebController");
|
|
2476
2686
|
const web = renderBrowserAuthRoutes(context, webActions);
|
|
2477
2687
|
if (web)
|
|
2478
|
-
files["http/controllers/AuthWebController.ts"] =
|
|
2688
|
+
files["http/controllers/AuthWebController.ts"] = renderAuthHttpImports(context, "web") + webActions.render(construction(true), ["authServices", "views"]);
|
|
2479
2689
|
return {
|
|
2480
2690
|
files,
|
|
2481
2691
|
api: { name: "authApiRoutes", source: api },
|
|
@@ -3078,7 +3288,6 @@ import { databaseOptions } from "./database.ts";
|
|
|
3078
3288
|
import { createStarterAuthServices, STARTER_AUTH_SERVICES } from "./auth.ts";
|
|
3079
3289
|
import { modelDefinitions${plan.decisions.workTracker ? ", repositoryDefinitions" : ""} } from "../models/register.ts";
|
|
3080
3290
|
import { applicationRoutes } from "../routes/index.ts";
|
|
3081
|
-
import { Note } from "../models/Note.ts";
|
|
3082
3291
|
import { migrate } from "../db/migrate.ts";
|
|
3083
3292
|
import { listeners } from "../outbox/registry.ts";
|
|
3084
3293
|
${plan.decisions.ensureDatabase ? `import { ensureAppDatabase } from "./ensureDatabase.ts";
|
|
@@ -3096,7 +3305,10 @@ const { bootstrapApp, createApp, createAppServer } = defineApp({
|
|
|
3096
3305
|
migrate,${plan.decisions.ensureDatabase ? `
|
|
3097
3306
|
ensureDatabase: ensureAppDatabase,` : ""}
|
|
3098
3307
|
outbox: { listeners${plan.decisions.workTracker ? ", token: WORK_TRACKER_OUTBOX" : ""} },
|
|
3099
|
-
health: async database => {
|
|
3308
|
+
health: async database => {
|
|
3309
|
+
const applied = await database.execute({ text: "SELECT name FROM framework_migrations WHERE name = '0001_starter_schema'", params: [] });
|
|
3310
|
+
return applied.length === 1;
|
|
3311
|
+
},
|
|
3100
3312
|
});
|
|
3101
3313
|
export { bootstrapApp, createApp, createAppServer };
|
|
3102
3314
|
export type { BootstrappedApp, BootstrapOptions };
|
|
@@ -3398,7 +3610,7 @@ function renderSupportingToolsReadme(projectName, plan) {
|
|
|
3398
3610
|
function renderApiDocs(projectName, plan) {
|
|
3399
3611
|
const layers = plan.layers;
|
|
3400
3612
|
const rows = ["| Method | Path | Notes |", "| --- | --- | --- |"];
|
|
3401
|
-
rows.push("| `GET` | `/health` | Plain text `ok` (200) when configured database/Redis checks succeed and
|
|
3613
|
+
rows.push("| `GET` | `/health` | Plain text `ok` (200) when configured database/Redis checks succeed and the starter schema migration is recorded in `framework_migrations`. This infrastructure probe runs outside API auth/tenancy admission, never selects a tenant or bypasses RLS, and returns no rows. `degraded` (503) when a dependency or schema check fails. Docker HEALTHCHECK uses this path. |", '| `GET` | `/ready` | JSON from the framework: `{"status":"ready","checks":{"database":"ok","redis":"skipped"}}` (200) or `not_ready` (503). `redis` is `ok` or `error` when `REDIS_URL` is set and `skipped` otherwise. It does not check the schema, so use `/health` as the deploy gate. |');
|
|
3402
3614
|
if (plan.decisions.token) {
|
|
3403
3615
|
rows.push("| `POST` | `/api/v1/auth/login` | `{ email, password }` returns `{ token }`. Requires `GET /api/v1/auth/csrf` then `X-CSRF-Token`. |", "| `GET` | `/api/v1/auth/me` | Requires `Authorization: Bearer <token>`. |");
|
|
3404
3616
|
}
|
|
@@ -3447,7 +3659,7 @@ function renderApiDocs(projectName, plan) {
|
|
|
3447
3659
|
${rows.join(`
|
|
3448
3660
|
`)}
|
|
3449
3661
|
|
|
3450
|
-
|
|
3662
|
+
Add application resources with the CLI commands below. The starter contains only the models required by your selected features.
|
|
3451
3663
|
|
|
3452
3664
|
## Auth
|
|
3453
3665
|
|
|
@@ -3457,26 +3669,14 @@ ${authNote}
|
|
|
3457
3669
|
|
|
3458
3670
|
Put HTTP actions in \`src/http/controllers/\` and register their paths and middleware in \`src/routes/api.ts\` or \`src/routes/web.ts\`. The bootstrap loads these route files once. Controller methods receive Bun's native \`Request\` and explicit request ports.
|
|
3459
3671
|
|
|
3460
|
-
\`\`\`
|
|
3461
|
-
|
|
3462
|
-
|
|
3463
|
-
|
|
3464
|
-
|
|
3465
|
-
export class NoteController {
|
|
3466
|
-
index: BusinessRouteHandler = async (_request, { database }) => {
|
|
3467
|
-
const notes = await database.model(Note).query().orderBy({ id: "desc" }).get();
|
|
3468
|
-
return Response.json({ data: notes.map(note => note.toJSON()) });
|
|
3469
|
-
};
|
|
3470
|
-
}
|
|
3471
|
-
\`\`\`
|
|
3472
|
-
|
|
3473
|
-
In \`src/routes/api.ts\`, import \`NoteController\` from \`../http/controllers/NoteController.ts\`, construct it in \`apiRoutes(context)\`, and add this map to that function's \`composeRouteMaps(...)\` arguments:
|
|
3474
|
-
|
|
3475
|
-
\`\`\`typescript
|
|
3476
|
-
{ "/api/v1/notes": { GET: context.kernel.wrapApi(notes.index) } }
|
|
3672
|
+
\`\`\`sh
|
|
3673
|
+
bun run strata make:model Product
|
|
3674
|
+
bun run strata make:controller ProductController
|
|
3675
|
+
bun run strata make:request StoreProductRequest
|
|
3676
|
+
bun run strata make:migration create_products
|
|
3477
3677
|
\`\`\`
|
|
3478
3678
|
|
|
3479
|
-
|
|
3679
|
+
Add model fields and fillable attributes, register the model in \`src/models/register.ts\`, and define its table in the migration. Register controller actions through \`context.kernel.wrapApi(...)\` in the API route map. This preserves authentication and the selected tenant policy. Use the handler's \`database\` port to bind your model to the current request. Account credential validation and workflows are provided by the framework.
|
|
3480
3680
|
|
|
3481
3681
|
Optional modules in \`src/modules/\` remain available for feature composition. They use the same kernel and execution ports.
|
|
3482
3682
|
|
|
@@ -3493,14 +3693,14 @@ function renderIntegrationsReadme(plan) {
|
|
|
3493
3693
|
layers.extras.oauthGithub ? "GitHub OAuth cookie login (`/auth/github`)" : null,
|
|
3494
3694
|
layers.extras.oidc ? "OIDC cookie login (`/auth/oidc`, PKCE in `oidc_pkce`)" : null,
|
|
3495
3695
|
layers.extras.billing ? "Stripe billing stub (`POST /billing/webhooks/stripe`, `GET /api/v1/billing/subscription`)" : null,
|
|
3496
|
-
layers.extras.webhooks ? "Outbound webhooks (
|
|
3696
|
+
layers.extras.webhooks ? "Outbound webhooks (explicit event dispatcher + `webhook.dispatch` job)" : null
|
|
3497
3697
|
].filter((row) => row !== null);
|
|
3498
3698
|
const lines = [
|
|
3499
3699
|
"## Integrations",
|
|
3500
3700
|
"",
|
|
3501
3701
|
"OAuth, billing, outbound webhooks, SIEM, and SAML are **off by default**. Commented placeholders live in `.env.example`. Framework map: [INTEGRATIONS.md](https://github.com/EyK-26/strata/blob/main/docs/INTEGRATIONS.md).",
|
|
3502
3702
|
"",
|
|
3503
|
-
"Wizard flags (any stack unless noted): `--oauth-github` and `--oidc` (cookie HTML), `--billing`, `--webhooks`. They emit controllers, routes, migrations, jobs, or listeners.
|
|
3703
|
+
"Wizard flags (any stack unless noted): `--oauth-github` and `--oidc` (cookie HTML), `--billing`, `--webhooks`. They emit controllers, routes, migrations, jobs, or listeners. Startup discovers the application\u2019s declared listeners and jobs.",
|
|
3504
3704
|
""
|
|
3505
3705
|
];
|
|
3506
3706
|
if (enabled.length > 0) {
|
|
@@ -3508,6 +3708,8 @@ function renderIntegrationsReadme(plan) {
|
|
|
3508
3708
|
} else {
|
|
3509
3709
|
lines.push("This app did not pass those flags. Turn a flag on and re-run `create-strata`, or copy the commented env block and add the integration controller and routes yourself.", "");
|
|
3510
3710
|
}
|
|
3711
|
+
if (layers.extras.webhooks)
|
|
3712
|
+
lines.push("Call `dispatchWebhook({ database, queue, options }, event, data)` from `src/webhooks/dispatchWebhook.ts` after your domain transaction commits. Supply an explicit public payload; never send account credentials. Compose the queue and options using `APPLICATION_QUEUE` and `APPLICATION_WEBHOOKS`. The dispatcher delivers to active subscriptions matching the event name or `*`; use a commit-aware model listener or outbox handler for transactional changes.", "");
|
|
3511
3713
|
return `${lines.join(`
|
|
3512
3714
|
`)}
|
|
3513
3715
|
`;
|
|
@@ -3562,6 +3764,9 @@ function renderReadme(projectName, plan, options = {}) {
|
|
|
3562
3764
|
const neededTools = plan.services.required;
|
|
3563
3765
|
const dockerLabel = neededTools.length === 0 ? "not needed" : dockerServices.length > 0 ? dockerServices.join(", ") : "off (local installs)";
|
|
3564
3766
|
return `${renderReadmeIntro(projectName, options)}
|
|
3767
|
+
AI coding agents: read [AGENTS.md](AGENTS.md) for this application's structure,
|
|
3768
|
+
selected stack, feature workflow and validation commands. Keep it current as the app evolves.
|
|
3769
|
+
|
|
3565
3770
|
## Layers
|
|
3566
3771
|
|
|
3567
3772
|
| Layer | Choice |
|
|
@@ -3702,7 +3907,7 @@ The image sets \`APP_ENV=production\` and \`AUTH_DEV_HEADERS=false\`; everything
|
|
|
3702
3907
|
${plan.decisions.dedicatedSigningSecret ? "- Set `SIGNED_URL_SECRET` to 32+ characters.\n" : ""}${plan.decisions.cookie ? "- Set `SESSION_SECRET` to 32+ characters.\n" : ""}${plan.decisions.token ? "- 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" : ""}${plan.decisions.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\`.
|
|
3703
3908
|
` : ""}
|
|
3704
3909
|
${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" : ""}
|
|
3705
|
-
\`strata start\` does not migrate when \`APP_ENV=production\`. Run \`bun run db:migrate\` as a deploy step. \`GET /health\` is 200 when
|
|
3910
|
+
\`strata start\` does not migrate when \`APP_ENV=production\`. Run \`bun run db:migrate\` as a deploy step. \`GET /health\` is 200 when the starter schema migration is recorded in \`framework_migrations\` 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\`).
|
|
3706
3911
|
`;
|
|
3707
3912
|
}
|
|
3708
3913
|
// ../../src/core/runtime/appEnv.ts
|
|
@@ -4090,9 +4295,9 @@ function renderPackageJson(projectName, options = {}) {
|
|
|
4090
4295
|
"@getstrata/cli": "workspace:*",
|
|
4091
4296
|
"@getstrata/core": "workspace:*"
|
|
4092
4297
|
} : {
|
|
4093
|
-
"@getstrata/bootstrap": "^3.1.
|
|
4094
|
-
"@getstrata/cli": "^3.1.
|
|
4095
|
-
"@getstrata/core": "^3.1.
|
|
4298
|
+
"@getstrata/bootstrap": "^3.1.4",
|
|
4299
|
+
"@getstrata/cli": "^3.1.4",
|
|
4300
|
+
"@getstrata/core": "^3.1.4"
|
|
4096
4301
|
};
|
|
4097
4302
|
if (!options.plan || options.plan.decisions.serverViews || options.plan.decisions.mfaViews)
|
|
4098
4303
|
coreDeps.eta = "^4.6.0";
|
|
@@ -4197,7 +4402,6 @@ function starterSchemaStatements(plan) {
|
|
|
4197
4402
|
const layers = plan.layers;
|
|
4198
4403
|
const d = dialectFragments(layers.database);
|
|
4199
4404
|
const statements = [];
|
|
4200
|
-
const tenancyOn = plan.decisions.tenantTable;
|
|
4201
4405
|
const mfaOn = plan.decisions.mfa;
|
|
4202
4406
|
const payloadType = layers.database === "postgres" ? "JSONB NOT NULL" : `${d.text} NOT NULL`;
|
|
4203
4407
|
statements.push(`CREATE TABLE IF NOT EXISTS failed_job (
|
|
@@ -4215,13 +4419,6 @@ function starterSchemaStatements(plan) {
|
|
|
4215
4419
|
slug ${d.keyText} NOT NULL UNIQUE
|
|
4216
4420
|
)`);
|
|
4217
4421
|
}
|
|
4218
|
-
const notesTenantColumn = tenancyOn ? `
|
|
4219
|
-
tenant_id INTEGER NOT NULL DEFAULT 1,` : "";
|
|
4220
|
-
statements.push(`CREATE TABLE IF NOT EXISTS notes (
|
|
4221
|
-
id ${d.id},
|
|
4222
|
-
body ${d.text} NOT NULL,${notesTenantColumn}
|
|
4223
|
-
created_at ${d.timestamp}
|
|
4224
|
-
)`);
|
|
4225
4422
|
if (plan.decisions.users) {
|
|
4226
4423
|
const tenantColumn = plan.decisions.schemaTenants ? `
|
|
4227
4424
|
tenant_id INTEGER NOT NULL DEFAULT 1,` : "";
|
|
@@ -4280,7 +4477,7 @@ function starterSchemaStatements(plan) {
|
|
|
4280
4477
|
}
|
|
4281
4478
|
const rlsOn = plan.decisions.rls;
|
|
4282
4479
|
if (rlsOn) {
|
|
4283
|
-
const rlsTables = plan.decisions.users ? ["
|
|
4480
|
+
const rlsTables = plan.decisions.users ? ["users"] : [];
|
|
4284
4481
|
const userOwnedTables = [];
|
|
4285
4482
|
if (plan.decisions.users) {
|
|
4286
4483
|
userOwnedTables.push("auth_one_time_tokens");
|
|
@@ -4336,11 +4533,10 @@ export function withMigrationDatabase<T>(operation: (db: MigrationDatabase) => P
|
|
|
4336
4533
|
`;
|
|
4337
4534
|
}
|
|
4338
4535
|
function renderMigrateTs(plan) {
|
|
4339
|
-
const tenancyOn = plan.decisions.tenantTable;
|
|
4340
4536
|
const usersOn = plan.decisions.users;
|
|
4341
4537
|
const verifyOn = plan.decisions.emailVerification;
|
|
4342
4538
|
const rlsOn = plan.decisions.rls;
|
|
4343
|
-
const imports = usersOn ? `import {
|
|
4539
|
+
const imports = usersOn ? `import { createUserFactory } from "./factories/UserFactory.ts";
|
|
4344
4540
|
import { User } from "../models/User.ts";
|
|
4345
4541
|
` : "";
|
|
4346
4542
|
const tenant = plan.decisions.schemaTenants ? `
|
|
@@ -4349,9 +4545,9 @@ import { User } from "../models/User.ts";
|
|
|
4349
4545
|
const users = usersOn ? `
|
|
4350
4546
|
const users = selected.model(User);
|
|
4351
4547
|
if ((await users.query().value("id")) === null) {
|
|
4352
|
-
const
|
|
4353
|
-
await
|
|
4354
|
-
await
|
|
4548
|
+
const factory = await createUserFactory("StrataDemo!ChangeMe", ${plan.decisions.schemaTenants ? "1, " : ""}async values => (await users.create(values)).toObject());
|
|
4549
|
+
await factory.create({name:"Demo User",email:"demo@example.com",is_admin:false${verifyOn ? ",email_verified_at:selected.dialect.timestampValue(new Date())" : ""}});
|
|
4550
|
+
await factory.create({name:"Admin User",email:"admin@example.test",is_admin:true${verifyOn ? ",email_verified_at:selected.dialect.timestampValue(new Date())" : ""}});
|
|
4355
4551
|
}` : "";
|
|
4356
4552
|
const run = rlsOn ? `policy.run(database, {kind:"bypass"}, writeSeed)` : `database.transaction(writeSeed)`;
|
|
4357
4553
|
return `${imports}${ensureImport(plan)}import { createApplication } from "@getstrata/core/runtime/application";
|
|
@@ -4361,7 +4557,6 @@ import { createPersistenceInvocation } from "@getstrata/bootstrap/persistenceInv
|
|
|
4361
4557
|
import { migrateDatabase } from "@getstrata/core/database/migrations";
|
|
4362
4558
|
import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
|
|
4363
4559
|
import { databaseOptions, databaseEnvironment } from "../bootstrap/database.ts";
|
|
4364
|
-
import { Note } from "../models/Note.ts";
|
|
4365
4560
|
import { loadStarterMigrations, withMigrationDatabase } from "./migrationRuntime.ts";
|
|
4366
4561
|
|
|
4367
4562
|
/** An explicit development-only command owns its own canonical Application. */
|
|
@@ -4369,14 +4564,12 @@ export async function seed(input: Readonly<Record<string, string | undefined>> =
|
|
|
4369
4564
|
const environment = databaseEnvironment(input);
|
|
4370
4565
|
if (isProductionEnv(environment)) throw new Error("Demo seeding is disabled in production and staging.");
|
|
4371
4566
|
${ensureCall(plan)} const connection = databaseOptions(environment);
|
|
4372
|
-
const application = createApplication({providers:[],services:createDatabaseBindings({default:"main",connections:{main:connection},models:[
|
|
4567
|
+
const application = createApplication({providers:[],services:createDatabaseBindings({default:"main",connections:{main:connection},models:[${usersOn ? "User" : ""}]})});
|
|
4373
4568
|
await application.start();
|
|
4374
4569
|
try {
|
|
4375
4570
|
const invoke = createPersistenceInvocation(application, "main");
|
|
4376
4571
|
await invoke({kind:"command",actor:{kind:"system",policy:"starter-demo-seed"}}, ({database${rlsOn ? ",policy" : ""}}) => {
|
|
4377
|
-
const writeSeed = async (selected: DatabaseSession | TransactionSession) => {${tenant}
|
|
4378
|
-
const notes = selected.model(Note);
|
|
4379
|
-
if ((await notes.query().value("id")) === null) await notes.create({body:"Welcome to Strata!"${tenancyOn ? ",tenant_id:1" : ""}});${users}
|
|
4572
|
+
const writeSeed = async (${usersOn || plan.decisions.schemaTenants ? "selected" : "_selected"}: DatabaseSession | TransactionSession) => {${tenant}${users}
|
|
4380
4573
|
};
|
|
4381
4574
|
return ${run};
|
|
4382
4575
|
});
|
|
@@ -4411,7 +4604,6 @@ function dropTables(plan) {
|
|
|
4411
4604
|
ordered.push("auth_one_time_tokens");
|
|
4412
4605
|
ordered.push("users");
|
|
4413
4606
|
}
|
|
4414
|
-
ordered.push("notes");
|
|
4415
4607
|
if (plan.decisions.schemaTenants) {
|
|
4416
4608
|
ordered.push("tenant");
|
|
4417
4609
|
}
|
|
@@ -4712,51 +4904,41 @@ export default DispatchOutboundWebhookJob;
|
|
|
4712
4904
|
export type { DispatchOutboundWebhookPayload };
|
|
4713
4905
|
`;
|
|
4714
4906
|
}
|
|
4715
|
-
function
|
|
4716
|
-
return `import type {
|
|
4717
|
-
import {
|
|
4718
|
-
import { createServiceToken } from "@getstrata/core/contracts/token";
|
|
4719
|
-
import { modelEffects, type AfterCommitRepositoryListener } from "@getstrata/core/database/definitions";
|
|
4720
|
-
import { APPLICATION_QUEUE as STARTER_QUEUE_TOKEN, APPLICATION_WEBHOOKS as STARTER_WEBHOOK_OPTIONS_TOKEN } from "@getstrata/bootstrap/application";
|
|
4721
|
-
import { Note, type NoteRecord } from "../models/Note.ts";
|
|
4907
|
+
function renderDispatchWebhook() {
|
|
4908
|
+
return `import type { DatabaseSession, TransactionSession } from "@getstrata/core/database/session";
|
|
4909
|
+
import type { QueueDispatcher } from "@getstrata/core/queue";
|
|
4722
4910
|
import DispatchOutboundWebhookJob from "../jobs/dispatchOutboundWebhookJob.ts";
|
|
4723
4911
|
|
|
4724
|
-
|
|
4725
|
-
|
|
4726
|
-
|
|
4727
|
-
|
|
4728
|
-
|
|
4729
|
-
|
|
4730
|
-
|
|
4731
|
-
|
|
4732
|
-
|
|
4733
|
-
|
|
4734
|
-
|
|
4735
|
-
|
|
4736
|
-
|
|
4737
|
-
|
|
4738
|
-
|
|
4739
|
-
|
|
4740
|
-
|
|
4741
|
-
|
|
4742
|
-
|
|
4743
|
-
|
|
4744
|
-
|
|
4745
|
-
|
|
4746
|
-
|
|
4747
|
-
|
|
4748
|
-
|
|
4749
|
-
|
|
4750
|
-
|
|
4751
|
-
|
|
4752
|
-
|
|
4753
|
-
|
|
4754
|
-
repositoryEffects: Object.freeze([modelEffects(Note, [
|
|
4755
|
-
{action: "created", afterCommit: noteCreated},
|
|
4756
|
-
])]),
|
|
4757
|
-
});
|
|
4758
|
-
|
|
4759
|
-
export default declarations;
|
|
4912
|
+
interface WebhookPorts {
|
|
4913
|
+
database: DatabaseSession | TransactionSession;
|
|
4914
|
+
queue: QueueDispatcher;
|
|
4915
|
+
options: Readonly<{ allowPrivate: boolean; signatureHeader: string }>;
|
|
4916
|
+
}
|
|
4917
|
+
|
|
4918
|
+
/** Call after commit; choose a public payload explicitly, excluding account credentials. */
|
|
4919
|
+
export async function dispatchWebhook({ database, queue, options }: WebhookPorts, event: string, data: unknown): Promise<void> {
|
|
4920
|
+
if (!event.trim()) throw new Error("A webhook event name is required.");
|
|
4921
|
+
const body = JSON.stringify({ event, data });
|
|
4922
|
+
const hooks = await database.execute<{
|
|
4923
|
+
id: number;
|
|
4924
|
+
url: string;
|
|
4925
|
+
secret: string;
|
|
4926
|
+
active: number | boolean;
|
|
4927
|
+
events: string;
|
|
4928
|
+
}>({ text: "SELECT id, url, secret, active, events FROM webhooks", params: [] });
|
|
4929
|
+
for (const hook of hooks) {
|
|
4930
|
+
if (!hook.active || (hook.events !== "*" && hook.events !== event)) continue;
|
|
4931
|
+
await queue.dispatch(new DispatchOutboundWebhookJob(), {
|
|
4932
|
+
webhookId: hook.id,
|
|
4933
|
+
event,
|
|
4934
|
+
url: hook.url,
|
|
4935
|
+
secret: hook.secret,
|
|
4936
|
+
body,
|
|
4937
|
+
allowPrivate: options.allowPrivate,
|
|
4938
|
+
signatureHeader: options.signatureHeader,
|
|
4939
|
+
});
|
|
4940
|
+
}
|
|
4941
|
+
}
|
|
4760
4942
|
`;
|
|
4761
4943
|
}
|
|
4762
4944
|
function renderApplyStripeWebhook() {
|
|
@@ -5655,7 +5837,7 @@ ${imports[kind].join(`
|
|
|
5655
5837
|
${routes.map((route) => route.source).join(`
|
|
5656
5838
|
`)}
|
|
5657
5839
|
/** Register ${kind === "api" ? "API" : "browser"} endpoints and their middleware here. */
|
|
5658
|
-
export function ${kind}Routes(context: ModuleRouteContext): AppRouteMap {
|
|
5840
|
+
export function ${kind}Routes(${routes.length ? "context" : "_context"}: ModuleRouteContext): AppRouteMap {
|
|
5659
5841
|
return composeRouteMaps(${routes.map((route) => `${route.name}(context)`).join(", ")});
|
|
5660
5842
|
}
|
|
5661
5843
|
`;
|
|
@@ -5783,15 +5965,6 @@ export type { ${name}Record };
|
|
|
5783
5965
|
export { ${name} };
|
|
5784
5966
|
`;
|
|
5785
5967
|
}
|
|
5786
|
-
function renderNoteModel(plan) {
|
|
5787
|
-
const tenant = plan.decisions.tenantTable;
|
|
5788
|
-
return renderModel("Note", "notes", {
|
|
5789
|
-
id: "field.number()",
|
|
5790
|
-
body: "field.string()",
|
|
5791
|
-
...tenant ? { tenant_id: "field.number()" } : {},
|
|
5792
|
-
created_at: "field.timestamp()"
|
|
5793
|
-
}, ["body", ...tenant ? ["tenant_id"] : []]);
|
|
5794
|
-
}
|
|
5795
5968
|
function renderUserModel(plan) {
|
|
5796
5969
|
const tenant = plan.decisions.schemaTenants;
|
|
5797
5970
|
const mfa = plan.layers.extras.mfa;
|
|
@@ -5824,6 +5997,36 @@ function renderUserModel(plan) {
|
|
|
5824
5997
|
"email_verified_at"
|
|
5825
5998
|
], ["password", ...mfa ? ["mfa_secret", "mfa_recovery_codes"] : []]);
|
|
5826
5999
|
}
|
|
6000
|
+
function renderUserFactory(plan) {
|
|
6001
|
+
return `import { hashPassword } from "@getstrata/core/auth/password";
|
|
6002
|
+
import { createFactory, type FactoryPersist } from "@getstrata/core/database/factory";
|
|
6003
|
+
import type { UserRecord } from "../../models/User.ts";
|
|
6004
|
+
|
|
6005
|
+
/** Explicit credentials and persistence keep test data local to its invocation. */
|
|
6006
|
+
export async function createUserFactory(password: string, ${plan.decisions.schemaTenants ? "tenantId: number, " : ""}persist?: FactoryPersist<UserRecord>) {
|
|
6007
|
+
const hashedPassword = await hashPassword(password);
|
|
6008
|
+
return createFactory<UserRecord>({
|
|
6009
|
+
definition: () => ({
|
|
6010
|
+
id: 0,
|
|
6011
|
+
name: "Test User",
|
|
6012
|
+
email: \`user-\${crypto.randomUUID()}@example.test\`,
|
|
6013
|
+
password: hashedPassword,
|
|
6014
|
+
is_admin: false,
|
|
6015
|
+
is_active: true,
|
|
6016
|
+
auth_version: 0,
|
|
6017
|
+
${plan.decisions.schemaTenants ? ` tenant_id: tenantId,
|
|
6018
|
+
` : ""}${plan.decisions.mfa ? ` mfa_secret: null,
|
|
6019
|
+
mfa_enabled: false,
|
|
6020
|
+
mfa_recovery_codes: null,
|
|
6021
|
+
` : ""} session_valid_after: null,
|
|
6022
|
+
email_verified_at: null,
|
|
6023
|
+
created_at: new Date().toISOString(),
|
|
6024
|
+
}),
|
|
6025
|
+
persist,
|
|
6026
|
+
});
|
|
6027
|
+
}
|
|
6028
|
+
`;
|
|
6029
|
+
}
|
|
5827
6030
|
function renderApiTokenModel() {
|
|
5828
6031
|
return renderModel("ApiToken", "api_tokens", {
|
|
5829
6032
|
id: "field.number()",
|
|
@@ -5847,7 +6050,7 @@ function renderAuthOneTimeTokenModel() {
|
|
|
5847
6050
|
}, ["purpose", "user_id", "token_hash", "expires_at", "consumed_at"]);
|
|
5848
6051
|
}
|
|
5849
6052
|
function renderModelsRegister(plan) {
|
|
5850
|
-
const names = [
|
|
6053
|
+
const names = [];
|
|
5851
6054
|
if (plan.decisions.users)
|
|
5852
6055
|
names.push("User", "AuthOneTimeToken");
|
|
5853
6056
|
if (plan.decisions.token)
|
|
@@ -5934,6 +6137,7 @@ export const TENANCY_ENABLED = ${decisions.tenantTable};
|
|
|
5934
6137
|
}
|
|
5935
6138
|
writeText(join2(targetDir, ".bun-version"), `1.4.4
|
|
5936
6139
|
`);
|
|
6140
|
+
writeText(join2(targetDir, "AGENTS.md"), renderAgentInstructions(projectName, plan));
|
|
5937
6141
|
writeText(join2(targetDir, ".env.example"), renderEnvExample(projectName, plan));
|
|
5938
6142
|
writeText(join2(targetDir, ".gitignore"), renderGitignore());
|
|
5939
6143
|
writeText(join2(targetDir, "package.json"), renderPackageJson(projectName, { ...options, plan }));
|
|
@@ -5991,12 +6195,13 @@ export const TENANCY_ENABLED = ${decisions.tenantTable};
|
|
|
5991
6195
|
}
|
|
5992
6196
|
writeText(join2(src, "outbox/registry.ts"), renderOutboxRegistryTs(plan));
|
|
5993
6197
|
writeText(join2(src, "bootstrap/auth.ts"), renderAuthProvider(plan));
|
|
5994
|
-
writeText(join2(src, "models/Note.ts"), renderNoteModel(plan));
|
|
5995
6198
|
if (decisions.users) {
|
|
5996
6199
|
writeText(join2(src, "models/User.ts"), renderUserModel(plan));
|
|
6200
|
+
writeText(join2(src, "db/factories/UserFactory.ts"), renderUserFactory(plan));
|
|
5997
6201
|
writeText(join2(src, "models/AuthOneTimeToken.ts"), renderAuthOneTimeTokenModel());
|
|
5998
6202
|
} else {
|
|
5999
6203
|
removeIfExists(join2(src, "models/User.ts"));
|
|
6204
|
+
removeIfExists(join2(src, "db/factories/UserFactory.ts"));
|
|
6000
6205
|
removeIfExists(join2(src, "models/AuthOneTimeToken.ts"));
|
|
6001
6206
|
}
|
|
6002
6207
|
if (decisions.token) {
|
|
@@ -6045,10 +6250,10 @@ export const TENANCY_ENABLED = ${decisions.tenantTable};
|
|
|
6045
6250
|
}
|
|
6046
6251
|
if (layers.extras.webhooks) {
|
|
6047
6252
|
writeText(join2(src, "jobs/dispatchOutboundWebhookJob.ts"), renderDispatchOutboundWebhookJob(plan));
|
|
6048
|
-
writeText(join2(src, "
|
|
6253
|
+
writeText(join2(src, "webhooks/dispatchWebhook.ts"), renderDispatchWebhook());
|
|
6049
6254
|
} else {
|
|
6050
6255
|
removeIfExists(join2(src, "jobs/dispatchOutboundWebhookJob.ts"));
|
|
6051
|
-
removeIfExists(join2(src, "
|
|
6256
|
+
removeIfExists(join2(src, "webhooks/dispatchWebhook.ts"));
|
|
6052
6257
|
}
|
|
6053
6258
|
if (decisions.pendingMfa) {
|
|
6054
6259
|
writeText(join2(src, "bootstrap/pendingMfa.ts"), renderPendingMfaTs());
|
|
@@ -1,50 +1,5 @@
|
|
|
1
|
-
# API
|
|
1
|
+
# API routes
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The generated `docs/API.md` describes the routes and authentication for your selected starter options.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
- `GET /health` returns plain text `ok`, or `degraded` (503) until the database ping succeeds and the migrated `notes` table exists. Docker HEALTHCHECK uses `/health`.
|
|
8
|
-
- `GET /ready` returns JSON `{"status":"ready","checks":{"database":"ok","redis":"skipped"}}` (200) or `not_ready` (503). `redis` is `ok` or `error` when `REDIS_URL` is set and `skipped` otherwise. It does not check the schema, so `/health` is the deploy gate.
|
|
9
|
-
- `GET /` returns the welcome page.
|
|
10
|
-
- A `notes` table, with no routes on it yet.
|
|
11
|
-
|
|
12
|
-
Login endpoints depend on the auth layer you chose. Token auth adds `POST /api/v1/auth/login` and `GET /api/v1/auth/me`; JWT auth adds `POST /api/auth/token`; header auth adds none and expects `x-authenticated-user-id` for local work only.
|
|
13
|
-
|
|
14
|
-
There is no CRUD endpoint for `notes`. Adding your own routes is the first thing you do.
|
|
15
|
-
|
|
16
|
-
## Adding a route
|
|
17
|
-
|
|
18
|
-
```typescript
|
|
19
|
-
// src/modules/notes/index.ts
|
|
20
|
-
import type { AppModule } from "@getstrata/bootstrap/contracts";
|
|
21
|
-
import { jsonResponse } from "@getstrata/core/http/response";
|
|
22
|
-
import { getSql } from "../../bootstrap/database.ts";
|
|
23
|
-
|
|
24
|
-
const notesModule: AppModule = {
|
|
25
|
-
name: "notes",
|
|
26
|
-
order: 2,
|
|
27
|
-
routes({ kernel }) {
|
|
28
|
-
return {
|
|
29
|
-
"/api/v1/notes": kernel.wrap("api", async () => {
|
|
30
|
-
const rows = await getSql().unsafe<{ id: number; body: string }>(
|
|
31
|
-
"SELECT id, body FROM notes ORDER BY id DESC",
|
|
32
|
-
);
|
|
33
|
-
return jsonResponse({ data: rows });
|
|
34
|
-
}),
|
|
35
|
-
};
|
|
36
|
-
},
|
|
37
|
-
};
|
|
38
|
-
|
|
39
|
-
export default notesModule;
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
Import from `@getstrata/core/...` subpaths rather than the package root, so singleton state such as the database pool stays shared.
|
|
43
|
-
|
|
44
|
-
## Generating an app instead
|
|
45
|
-
|
|
46
|
-
```bash
|
|
47
|
-
bunx create-strata my-app --frontend api --yes
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
A generated app writes its own `docs/API.md` listing only the routes its layers actually serve.
|
|
5
|
+
Add application actions in `src/http/controllers/`, validation in `src/http/requests/`, and routes in `src/routes/api.ts`. Use `bun run strata make:controller ProductController` to begin. Register routes through the kernel to preserve authentication and tenant policies.
|
|
@@ -1,7 +1,5 @@
|
|
|
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";
|
|
5
3
|
export default function HomePage() {
|
|
6
4
|
const { user } = useAuth();
|
|
7
5
|
return (
|
|
@@ -38,19 +36,6 @@ export default function HomePage() {
|
|
|
38
36
|
</tbody>
|
|
39
37
|
</table>
|
|
40
38
|
</div>
|
|
41
|
-
<h2>Starter-only example</h2>
|
|
42
|
-
<p>
|
|
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.
|
|
45
|
-
</p>
|
|
46
|
-
<pre className="card">
|
|
47
|
-
<code>{notesModuleExample(TENANCY_ENABLED)}</code>
|
|
48
|
-
</pre>
|
|
49
|
-
<p className="hint">
|
|
50
|
-
Then fetch it here with <code>apiFetch("/notes")</code>. The <code>notes</code> table
|
|
51
|
-
already exists after <code>bun run db:migrate</code>. Application authorization and tenant
|
|
52
|
-
scope remain required for real business data.
|
|
53
|
-
</p>
|
|
54
39
|
</section>
|
|
55
40
|
);
|
|
56
41
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@getstrata/starter",
|
|
3
|
-
"version": "3.1.
|
|
4
|
-
"description": "Interactive
|
|
3
|
+
"version": "3.1.4",
|
|
4
|
+
"description": "Interactive application generator for Strata, a Laravel-inspired Bun and TypeScript framework.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
/** Displayed source only; business handlers execute after the developer adds this module. */
|
|
2
|
-
export function notesModuleExample(tenancy: boolean): string {
|
|
3
|
-
const scope = tenancy ? ".where({ tenant_id: ports.established.tenant.id })" : "";
|
|
4
|
-
return `// src/modules/notes/index.ts
|
|
5
|
-
import type { AppModule } from "@getstrata/bootstrap/contracts";
|
|
6
|
-
import { jsonResponse } from "@getstrata/core/http/response";
|
|
7
|
-
import { Note } from "../../models/Note.ts";
|
|
8
|
-
|
|
9
|
-
export default {
|
|
10
|
-
name: "notes",
|
|
11
|
-
routes({ kernel }) {
|
|
12
|
-
return {
|
|
13
|
-
"/api/v1/notes": {
|
|
14
|
-
GET: kernel.wrapApi(async (_request, ports) => {
|
|
15
|
-
const rows = await ports.database.model(Note).query()${scope}.orderBy({ column: "id", direction: "DESC" }).limit(100).get();
|
|
16
|
-
return jsonResponse({ data: rows.map(row => row.toObject()) });
|
|
17
|
-
}),
|
|
18
|
-
},
|
|
19
|
-
};
|
|
20
|
-
},
|
|
21
|
-
} satisfies AppModule;`;
|
|
22
|
-
}
|