create-strata 2.1.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2905,6 +2905,8 @@ function renderEnvExample(projectName, layers) {
2905
2905
  `APP_KEY_PREFIX=${projectName}`,
2906
2906
  "APP_ENV=local",
2907
2907
  "PORT=3000",
2908
+ "# Total graceful shutdown budget in milliseconds; keep deployment grace longer.",
2909
+ "SHUTDOWN_TIMEOUT_MS=30000",
2908
2910
  "APP_URL=http://localhost:3000",
2909
2911
  `DATABASE_URL=${defaultDatabaseUrl(layers, projectName)}`,
2910
2912
  ...postgresAppRoleEnvNotes(layers),
@@ -2922,10 +2924,14 @@ function renderEnvExample(projectName, layers) {
2922
2924
  `MAIL_DRIVER=${layers.mail}`,
2923
2925
  `AUTH_DEV_HEADERS=${envFlag(layers.auth === "headers")}`
2924
2926
  ];
2927
+ lines.push("# Scheduler coordination defaults to Redis in production, one process in development.");
2928
+ lines.push("# SCHEDULER_COORDINATION=redis");
2925
2929
  lines.push("APP_DEBUG=false");
2930
+ lines.push("TENANT_DEV_HEADERS=false");
2931
+ lines.push("# Development-only anonymous x-tenant-id selection; never enable in production.");
2926
2932
  lines.push("FEATURE_PUBLIC_READS=false");
2927
2933
  lines.push("# wrapWebPublicRead / wrapPublicRead require login when false (production-safe default).");
2928
- lines.push("# Local storefronts/catalogs may set true in .env. Production boot rejects FEATURE_PUBLIC_READS=true.");
2934
+ lines.push("# Public reads do not enable tenant headers. Production guest tenancy requires CORE_PUBLIC_TENANCY_TOKEN.");
2929
2935
  lines.push("FEATURE_SIEM_EXPORT=false");
2930
2936
  lines.push("# SIEM_EXPORT_URL=");
2931
2937
  lines.push("# SIEM_EXPORT_TOKEN=");
@@ -3191,9 +3197,9 @@ function renderPackageJson(projectName, options = {}) {
3191
3197
  "@getstrata/cli": "workspace:*",
3192
3198
  "@getstrata/core": "workspace:*"
3193
3199
  } : {
3194
- "@getstrata/bootstrap": "^2.1.0",
3195
- "@getstrata/cli": "^2.1.0",
3196
- "@getstrata/core": "^2.1.0"
3200
+ "@getstrata/bootstrap": "^2.2.1",
3201
+ "@getstrata/cli": "^2.2.1",
3202
+ "@getstrata/core": "^2.2.1"
3197
3203
  };
3198
3204
  coreDeps.eta = "^4.6.0";
3199
3205
  if (options.layers?.database === "mysql") {
@@ -3384,7 +3390,7 @@ function renderIntegrationsReadme(layers) {
3384
3390
  "",
3385
3391
  "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).",
3386
3392
  "",
3387
- "Wizard flags (any stack unless noted): `--oauth-github` and `--oidc` (cookie HTML), `--billing`, `--webhooks`. They emit modules, migrations, jobs, or listeners. `createApp` still calls `discoverListeners()` and `discoverJobs()`.",
3393
+ "Wizard flags (any stack unless noted): `--oauth-github` and `--oidc` (cookie HTML), `--billing`, `--webhooks`. They emit modules, migrations, jobs, or listeners. `createApp` still calls `await discoverListeners()` and `await discoverJobs()`.",
3388
3394
  ""
3389
3395
  ];
3390
3396
  if (enabled.length > 0) {
@@ -3473,6 +3479,8 @@ ${next.join(`
3473
3479
  Open http://localhost:3000. Health check: \`GET /health\`. Redis worker: \`bun run queue:work\` (requires \`REDIS_URL\`).
3474
3480
 
3475
3481
  ${renderSupportingToolsReadme(layers)}${layers.auth !== "headers" ? `
3482
+ For the first production admin, apply migrations and run \`bunx strata auth:provision-admin --email operator@example.test --name "Initial Operator" --password-stdin${layers.tenancy !== "none" ? " --tenant 1" : ""} < /run/secrets/initial_admin_password\` before admitting traffic. Supply your own private secret-manager-mounted file, not a demo password. Passwords require at least 16 characters and at most 72 UTF-8 bytes. Tenant-enabled applications require an existing tenant ID; this command does not create tenants. It refuses existing admins/accounts, records a transactional one-time claim, and does not mark email verified or enroll MFA. Additional admins and recovery remain explicit application administration. The command does not migrate or seed automatically.
3483
+
3476
3484
  Optional development demo accounts: run \`bun run db:seed:demo\` explicitly after migrations. This command refuses production and staging. It creates these accounts with password \`StrataDemo!ChangeMe\`:
3477
3485
 
3478
3486
  - \`demo@example.com\` (member)
@@ -3531,7 +3539,7 @@ The image sets \`APP_ENV=production\` and \`AUTH_DEV_HEADERS=false\`; everything
3531
3539
  - Replace every \`change-me\` placeholder in \`.env\`. The guard rejects the values this generator wrote, not just empty ones.
3532
3540
  - Set \`APP_URL\` to the public origin (for example \`https://app.example.com\`). Signed links and redirects are built from it; localhost is rejected.
3533
3541
  - Set \`AUTH_DEV_HEADERS=false\`.
3534
- - Set \`FEATURE_PUBLIC_READS=false\`. Generated \`.env.example\` already ships \`false\` so \`wrapWebPublicRead\` requires a login. Local storefronts may set \`true\` in \`.env\` for an anonymous catalog; \`assertProductionSecrets()\` rejects \`true\` in production. Do not ship a public-reads production boot.
3542
+ - Generated \`FEATURE_PUBLIC_READS=false\` makes \`wrapWebPublicRead\` / \`wrapPublicRead\` require login by default. Opt in per route with \`{ allowAnonymous: true }\`, or set \`FEATURE_PUBLIC_READS=true\` as their default policy. With tenancy enabled, production guests require an application-approved host resolver bound to \`CORE_PUBLIC_TENANCY_TOKEN\`; unknown hosts fail closed. Keep \`TENANT_DEV_HEADERS=false\` in production. See the framework TENANCY guide for proxy trust and rollout.
3535
3543
  - Add explicitly approved application headers with \`CORS_ADDITIONAL_ALLOWED_HEADERS=Idempotency-Key,X-Correlation-Id\`; this extends the defaults, validates header names and never reflects requested headers. OpenAPI metadata does not grant CORS access.
3536
3544
  - Cross-origin browser calls are off in production until you set \`CORS_ALLOWED_ORIGINS\` to explicit origins. A \`*\` entry is rejected. Non-browser clients are unaffected.
3537
3545
  - 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.
@@ -3541,6 +3549,87 @@ ${authUsesCookie(layers.auth) ? "- Set `SESSION_SECRET` to 32+ characters.\n" :
3541
3549
  `;
3542
3550
  }
3543
3551
 
3552
+ // ../strata-starter/src/renderInitialAdmin.ts
3553
+ function renderInitialAdminMigration(layers) {
3554
+ if (!authNeedsUsers(layers.auth))
3555
+ return null;
3556
+ const driver = layers.database === "postgres" ? "pgsql" : layers.database;
3557
+ return `import { Schema } from "@getstrata/core/database/schema";
3558
+ import type { Migration } from "@getstrata/core/database/migrations/types";
3559
+
3560
+ const migration: Migration = {
3561
+ name: "0004_initial_admin_provisioning",
3562
+ async up(db) {
3563
+ await Schema.run(db, "${driver}", schema => {
3564
+ schema.create("initial_admin_provisioning", table => {
3565
+ table.integer("id").primary();
3566
+ table.text("email");
3567
+ table.timestamp("provisioned_at").defaultRaw("CURRENT_TIMESTAMP");
3568
+ });
3569
+ });
3570
+ },
3571
+ async down(db) {
3572
+ if ((await db.unsafe("SELECT id FROM initial_admin_provisioning")).length) {
3573
+ throw new Error("Cannot discard a completed initial-admin provisioning claim.");
3574
+ }
3575
+ await Schema.run(db, "${driver}", schema => { schema.drop("initial_admin_provisioning"); });
3576
+ },
3577
+ };
3578
+ export default migration;
3579
+ `;
3580
+ }
3581
+ function renderInitialAdminCommand(layers) {
3582
+ if (!authNeedsUsers(layers.auth))
3583
+ return null;
3584
+ const tenant = usesTenantTable(layers.tenancy);
3585
+ const rls = layers.tenancy === "rls";
3586
+ const placeholder = layers.database === "postgres" ? "$1" : "?";
3587
+ const fields = ["name", "email", "password", "is_admin", ...tenant ? ["tenant_id"] : []];
3588
+ const placeholders = fields.map((_, index) => layers.database === "postgres" ? `$${index + 1}` : "?");
3589
+ return `import { runInitialAdminCommand } from "@getstrata/cli/initialAdmin";
3590
+ import { hashPassword } from "@getstrata/core/auth/password";
3591
+ import { runInTransaction } from "@getstrata/core/database/transaction";
3592
+ ${rls ? `import { runWithMigrationBypass } from "@getstrata/core/tenant/databaseTenantContext";
3593
+ import { isRlsTenancy } from "@getstrata/core/tenant/tenancyConfig";
3594
+ import { assertRlsLiveDatabaseRole } from "@getstrata/bootstrap/secretsGuard";
3595
+ ` : ""}import { getSql, closeDatabase } from "../bootstrap/database.ts";
3596
+
3597
+ export async function initialAdminCommand(...args: string[]): Promise<void> {
3598
+ await runInitialAdminCommand(args, {
3599
+ tenantRequired: ${tenant},
3600
+ async provision(input) {
3601
+ // Hash before acquiring the database claim; only the official auth helper owns crypto.
3602
+ const passwordHash = await hashPassword(input.password);
3603
+ try {
3604
+ getSql();
3605
+ ${rls ? ` if (!isRlsTenancy()) throw new Error("RLS configuration is required.");
3606
+ await assertRlsLiveDatabaseRole();
3607
+ ` : ""} const provision = () => runInTransaction(async db => {
3608
+ // The singleton primary key serializes bootstrap commands across all tenants/processes.
3609
+ await db.unsafe("INSERT INTO initial_admin_provisioning (id, email) VALUES (1, ${placeholder})", [input.email]);
3610
+ if ((await db.unsafe("SELECT id FROM users WHERE is_admin = ${layers.database === "postgres" ? "TRUE" : "1"} LIMIT 1")).length) {
3611
+ throw new Error("An admin already exists.");
3612
+ }
3613
+ if ((await db.unsafe("SELECT id FROM users WHERE LOWER(email) = ${placeholder}", [input.email])).length) {
3614
+ throw new Error("The account already exists; provisioning never promotes accounts.");
3615
+ }
3616
+ ${tenant ? ` if (!(await db.unsafe("SELECT id FROM tenant WHERE id = ${placeholder}", [input.tenantId])).length) {
3617
+ throw new Error("The tenant does not exist.");
3618
+ }
3619
+ ` : ""} await db.unsafe("INSERT INTO users (${fields.join(", ")}) VALUES (${placeholders.join(", ")})", [input.name, input.email, passwordHash, ${layers.database === "postgres" ? "true" : "1"}${tenant ? ", input.tenantId" : ""}]);
3620
+ // Verification and MFA stay unenrolled; normal application flows remain authoritative.
3621
+ });
3622
+ await ${rls ? "runWithMigrationBypass(provision)" : "provision()"};
3623
+ } finally {
3624
+ await closeDatabase();
3625
+ }
3626
+ },
3627
+ });
3628
+ console.log("Initial admin provisioned. Complete email verification and MFA through the application.");
3629
+ }
3630
+ `;
3631
+ }
3632
+
3544
3633
  // ../strata-starter/src/renderRuntime.ts
3545
3634
  function needsEnsure(layers) {
3546
3635
  return layers.database !== "sqlite";
@@ -3773,6 +3862,7 @@ function starterSchemaStatements(layers) {
3773
3862
  statements.push(`CREATE TABLE IF NOT EXISTS failed_job (
3774
3863
  id ${d.id},
3775
3864
  job_name ${d.keyText} NOT NULL,
3865
+ job_id ${d.text},
3776
3866
  payload ${payloadType},
3777
3867
  exception ${d.text} NOT NULL,
3778
3868
  failed_at ${d.timestamp}
@@ -3780,9 +3870,7 @@ function starterSchemaStatements(layers) {
3780
3870
  if (tenancyOn) {
3781
3871
  statements.push(`CREATE TABLE IF NOT EXISTS tenant (
3782
3872
  id ${d.id},
3783
- slug ${d.keyText} NOT NULL UNIQUE,
3784
- plan ${d.defaultText} NOT NULL DEFAULT 'free',
3785
- region ${d.defaultText} NOT NULL DEFAULT 'eu'
3873
+ slug ${d.keyText} NOT NULL UNIQUE
3786
3874
  )`);
3787
3875
  }
3788
3876
  const notesTenantColumn = tenancyOn ? `
@@ -3953,8 +4041,8 @@ function renderMigrateTs(layers) {
3953
4041
  );
3954
4042
  if (Number(tenantCount) === 0) {
3955
4043
  await sql.unsafe(
3956
- "INSERT INTO tenant (slug, plan, region) VALUES (${ph ? "$1, $2, $3" : "?, ?, ?"})",
3957
- ["default", "free", "eu"],
4044
+ "INSERT INTO tenant (slug) VALUES (${ph ? "$1" : "?"})",
4045
+ ["default"],
3958
4046
  );
3959
4047
  }` : "";
3960
4048
  const seedUsers = authNeedsUsers(layers.auth) ? `
@@ -4030,8 +4118,7 @@ function renderNoteModel(layers) {
4030
4118
  tenant_id: number;` : "";
4031
4119
  const tenantColumn = tenancyOn ? ', "tenant_id"' : "";
4032
4120
  const fillable = tenancyOn ? '["body", "tenant_id"]' : '["body"]';
4033
- return `import { BaseRepository } from "@getstrata/core/database/baseRepository";
4034
- import { Model, registerModelRepository } from "@getstrata/core/database/model";
4121
+ return `import { defineModel } from "@getstrata/core/database/model";
4035
4122
  import { defineTable } from "@getstrata/core/database/table";
4036
4123
 
4037
4124
  interface NoteRecord {
@@ -4047,15 +4134,13 @@ const notesTable = defineTable<NoteRecord, "id">({
4047
4134
  defaultOrderBy: { column: "id", direction: "ASC" },
4048
4135
  });
4049
4136
 
4050
- class Note extends Model<NoteRecord, "id"> {
4137
+ class Note extends defineModel(notesTable) {
4051
4138
  static $fillable = ${fillable} as const;
4052
4139
  // created_at uses the table default. Sending a JS Date from $timestamps
4053
4140
  // is rejected by SQLite bindings.
4054
4141
  static $timestamps = false;
4055
4142
  }
4056
4143
 
4057
- registerModelRepository(Note, new BaseRepository(notesTable));
4058
-
4059
4144
  export type { NoteRecord };
4060
4145
  export { Note };
4061
4146
  `;
@@ -4092,8 +4177,7 @@ function renderUserModel(layers) {
4092
4177
  const fillableLiteral = `[${fillable.map((column) => `"${column}"`).join(", ")}]`;
4093
4178
  const hiddenLiteral = `[${hidden.map((column) => `"${column}"`).join(", ")}]`;
4094
4179
  const columnsLiteral = columns.map((column) => `"${column}"`).join(", ");
4095
- return `import { BaseRepository } from "@getstrata/core/database/baseRepository";
4096
- import { Model, registerModelRepository } from "@getstrata/core/database/model";
4180
+ return `import { defineModel } from "@getstrata/core/database/model";
4097
4181
  import { defineTable } from "@getstrata/core/database/table";
4098
4182
 
4099
4183
  interface UserRecord {
@@ -4114,7 +4198,7 @@ const usersTable = defineTable<UserRecord, "id">({
4114
4198
  defaultOrderBy: { column: "id", direction: "ASC" },
4115
4199
  });
4116
4200
 
4117
- class User extends Model<UserRecord, "id"> {
4201
+ class User extends defineModel(usersTable) {
4118
4202
  static $fillable = ${fillableLiteral} as const;
4119
4203
  static $hidden = ${hiddenLiteral} as const;
4120
4204
  // created_at uses the table default. Sending a JS Date from $timestamps
@@ -4122,15 +4206,12 @@ class User extends Model<UserRecord, "id"> {
4122
4206
  static $timestamps = false;
4123
4207
  }
4124
4208
 
4125
- registerModelRepository(User, new BaseRepository(usersTable));
4126
-
4127
4209
  export type { UserRecord };
4128
4210
  export { User };
4129
4211
  `;
4130
4212
  }
4131
4213
  function renderApiTokenModel() {
4132
- return `import { BaseRepository } from "@getstrata/core/database/baseRepository";
4133
- import { Model, registerModelRepository } from "@getstrata/core/database/model";
4214
+ return `import { defineModel } from "@getstrata/core/database/model";
4134
4215
  import { defineTable } from "@getstrata/core/database/table";
4135
4216
 
4136
4217
  interface ApiTokenRecord {
@@ -4151,22 +4232,19 @@ const apiTokensTable = defineTable<ApiTokenRecord, "id">({
4151
4232
  defaultOrderBy: { column: "id", direction: "ASC" },
4152
4233
  });
4153
4234
 
4154
- class ApiToken extends Model<ApiTokenRecord, "id"> {
4235
+ class ApiToken extends defineModel(apiTokensTable) {
4155
4236
  static $fillable = ["user_id", "name", "token_hash", "abilities", "expires_at", "last_used_at"] as const;
4156
4237
  // created_at uses the table default. Sending a JS Date from $timestamps
4157
4238
  // is rejected by SQLite bindings.
4158
4239
  static $timestamps = false;
4159
4240
  }
4160
4241
 
4161
- registerModelRepository(ApiToken, new BaseRepository(apiTokensTable));
4162
-
4163
4242
  export type { ApiTokenRecord };
4164
4243
  export { ApiToken };
4165
4244
  `;
4166
4245
  }
4167
4246
  function renderAuthOneTimeTokenModel() {
4168
- return `import { BaseRepository } from "@getstrata/core/database/baseRepository";
4169
- import { Model, registerModelRepository } from "@getstrata/core/database/model";
4247
+ return `import { defineModel } from "@getstrata/core/database/model";
4170
4248
  import { defineTable } from "@getstrata/core/database/table";
4171
4249
 
4172
4250
  interface AuthOneTimeTokenRecord {
@@ -4185,37 +4263,20 @@ const authOneTimeTokensTable = defineTable<AuthOneTimeTokenRecord, "id">({
4185
4263
  defaultOrderBy: { column: "id", direction: "ASC" },
4186
4264
  });
4187
4265
 
4188
- class AuthOneTimeToken extends Model<AuthOneTimeTokenRecord, "id"> {
4266
+ class AuthOneTimeToken extends defineModel(authOneTimeTokensTable) {
4189
4267
  static $fillable = ["purpose", "user_id", "token_hash", "expires_at", "consumed_at"] as const;
4190
4268
  static $timestamps = false;
4191
4269
  }
4192
4270
 
4193
- registerModelRepository(AuthOneTimeToken, new BaseRepository(authOneTimeTokensTable));
4194
-
4195
4271
  export type { AuthOneTimeTokenRecord };
4196
4272
  export { AuthOneTimeToken };
4197
4273
  `;
4198
4274
  }
4199
- function renderModelsRegister(layers) {
4200
- const lines = [
4201
- "// Side-effect imports run registerModelRepository() in each model file.",
4202
- "// registerModelClass() is only for a string alias that is neither constructor.name nor $morphClass.",
4203
- 'import "./Note.ts";'
4204
- ];
4205
- if (authNeedsUsers(layers.auth)) {
4206
- lines.push('import "./User.ts";');
4207
- lines.push('import "./AuthOneTimeToken.ts";');
4208
- }
4209
- if (authUsesToken(layers.auth)) {
4210
- lines.push('import "./ApiToken.ts";');
4211
- }
4212
- lines.push("");
4213
- lines.push("// Optional alias when a relation uses belongsTo('CategoryAlias'):");
4214
- lines.push('// import { registerModelClass } from "@getstrata/core/database/model";');
4215
- lines.push('// registerModelClass("CategoryAlias", Category);');
4216
- lines.push("");
4217
- return `${lines.join(`
4218
- `)}
4275
+ function renderModelsRegister(_layers) {
4276
+ return `import { discoverModels } from "@getstrata/bootstrap/discoverModels";
4277
+
4278
+ // Discovery binds default repositories and registers every name before model boot.
4279
+ await discoverModels(import.meta.dir);
4219
4280
  `;
4220
4281
  }
4221
4282
  function dropTables(layers) {
@@ -4376,9 +4437,12 @@ function renderConfigProvider(layers) {
4376
4437
  return `import {
4377
4438
  APP_PORT_CONFIG_KEY,
4378
4439
  CORE_CONFIG_TOKEN,
4440
+ CORE_PUBLIC_TENANCY_TOKEN,
4379
4441
  DATABASE_URL_CONFIG_KEY,
4380
4442
  REDIS_URL_CONFIG_KEY,
4381
4443
  } from "@getstrata/bootstrap/config";
4444
+ import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
4445
+ import { normalizeTenantHostname } from "@getstrata/core/tenant/tenantMiddleware";
4382
4446
  import type { ServiceProvider } from "@getstrata/core/contracts/di";
4383
4447
  import { loadConfig } from "../config.ts";
4384
4448
 
@@ -4388,6 +4452,13 @@ const configProvider: ServiceProvider = {
4388
4452
  const appConfig = loadConfig();
4389
4453
 
4390
4454
  container.set(CORE_CONFIG_TOKEN, config);
4455
+ // One approved origin for the starter tenant. Multi-tenant apps replace this lookup.
4456
+ if (isProductionEnv()) {
4457
+ const publicHost = normalizeTenantHostname(new URL(appConfig.appUrl).host);
4458
+ container.set(CORE_PUBLIC_TENANCY_TOKEN, {
4459
+ resolveTenantId: async (hostname) => hostname === publicHost ? 1 : null,
4460
+ });
4461
+ }
4391
4462
  config.set(DATABASE_URL_CONFIG_KEY, appConfig.databaseUrl);
4392
4463
  config.set(APP_PORT_CONFIG_KEY, appConfig.port);
4393
4464
  config.set(REDIS_URL_CONFIG_KEY, process.env.REDIS_URL ?? "");
@@ -4415,17 +4486,15 @@ import {
4415
4486
 
4416
4487
  const queueProvider: ServiceProvider = {
4417
4488
  name: "starter.queue",
4418
- register({ container }) {
4489
+ async register({ container, onCleanup }) {
4419
4490
  const driver = (process.env.QUEUE_DRIVER ?? "sync") as "sync" | "async" | "redis";
4420
4491
  const failedJobs = createFailedJobService();
4421
4492
  container.set(FAILED_JOB_SERVICE_TOKEN, failedJobs);
4422
- container.set(
4423
- CORE_QUEUE_TOKEN,
4424
- createAppQueue(driver, process.env.REDIS_URL, failedJobs, () => {
4425
- registerDefaultJobs();
4426
- discoverJobs();
4427
- }),
4428
- );
4493
+ registerDefaultJobs();
4494
+ await discoverJobs();
4495
+ const queue = createAppQueue(driver, process.env.REDIS_URL, failedJobs);
4496
+ onCleanup(() => queue.close?.(), driver === "async" ? "drain" : "close");
4497
+ container.set(CORE_QUEUE_TOKEN, queue);
4429
4498
  },
4430
4499
  };
4431
4500
 
@@ -4529,7 +4598,8 @@ export default policyProvider;
4529
4598
  `;
4530
4599
  }
4531
4600
  function renderProvidersIndex() {
4532
- return `import { discoverListeners } from "@getstrata/bootstrap/discoverListeners";
4601
+ return `import { tracingProvider } from "@getstrata/bootstrap";
4602
+ import { discoverListeners } from "@getstrata/bootstrap/discoverListeners";
4533
4603
  import { registerInvalidateCacheOnModelWriteListeners } from "@getstrata/bootstrap/listeners/invalidateCacheOnModelWrite";
4534
4604
  import type { ServiceProvider } from "@getstrata/core/contracts/di";
4535
4605
  import authProvider from "./auth.ts";
@@ -4539,32 +4609,20 @@ import policyProvider from "./policy.ts";
4539
4609
  import queueProvider from "./queue.ts";
4540
4610
  import storageProvider from "./storage.ts";
4541
4611
 
4542
- const registeredListenerGroups = new Set<string>();
4543
-
4544
- function registerListenerGroup(name: string, register: () => void): void {
4545
- if (registeredListenerGroups.has(name)) {
4546
- return;
4547
- }
4548
-
4549
- registeredListenerGroups.add(name);
4550
- register();
4551
- }
4552
-
4553
4612
  const listenersProvider: ServiceProvider = {
4554
4613
  name: "starter.listeners",
4555
- boot() {
4556
- registerListenerGroup("cache.invalidate-on-model-write", () => {
4557
- registerInvalidateCacheOnModelWriteListeners();
4558
- });
4614
+ async boot({ onCleanup }) {
4615
+ onCleanup(registerInvalidateCacheOnModelWriteListeners());
4559
4616
 
4560
- for (const registerListener of discoverListeners()) {
4561
- registerListener();
4617
+ for (const registerListener of await discoverListeners()) {
4618
+ await registerListener();
4562
4619
  }
4563
4620
  },
4564
4621
  };
4565
4622
 
4566
4623
  const starterProviders: ServiceProvider[] = [
4567
4624
  configProvider,
4625
+ tracingProvider,
4568
4626
  cacheProvider,
4569
4627
  storageProvider,
4570
4628
  queueProvider,
@@ -4585,16 +4643,8 @@ function renderCreateAppTs(layers) {
4585
4643
  ...createMetricsRoutes(),` : "";
4586
4644
  return `import { join } from "node:path";
4587
4645
  import "./preload.ts";
4588
- import { runProviderPhase } from "@getstrata/bootstrap/context";
4589
- import {
4590
- type AppContext,
4591
- type AppRouteMap,
4592
- assertAppDependenciesComplete,
4593
- ConfigStore,
4594
- type MutableAppDependencies,
4595
- type ProviderContext,
4596
- ServiceContainer,
4597
- } from "@getstrata/bootstrap/contracts";
4646
+ import { createAppContext as createProviderAppContext, type InitializedAppContext } from "@getstrata/bootstrap/context";
4647
+ import type { AppRouteMap } from "@getstrata/bootstrap/contracts";
4598
4648
  import { mergeSpaRoutes } from "@getstrata/bootstrap/createSpaRoutes";
4599
4649
  import {
4600
4650
  configureModulesDirectory,
@@ -4604,13 +4654,13 @@ import {
4604
4654
  import { createHealthRoutes } from "@getstrata/bootstrap/health";
4605
4655
  ${metricsImport}import { assertProductionSecrets, assertRlsLiveDatabaseRole } from "@getstrata/bootstrap/secretsGuard";
4606
4656
  import { createWebServer } from "@getstrata/bootstrap/web/server";
4607
- import { setActiveApplicationContext } from "@getstrata/core/runtime/applicationRegistry";
4657
+ import type { LifecycleCoordinator } from "@getstrata/core/lifecycle/gracefulShutdown";
4608
4658
  import { isProductionEnv } from "@getstrata/core/runtime/appEnv";
4609
4659
  import { isRlsTenancy } from "@getstrata/core/tenant/tenancyConfig";
4610
4660
  import { migrate } from "../db/migrate.ts";
4611
4661
  import { buildRoutes } from "../routes.ts";
4612
4662
  import { loadConfig } from "./config.ts";
4613
- import { getSql } from "./database.ts";
4663
+ import { closeDatabase, getSql, pingDatabase } from "./database.ts";
4614
4664
  ${ensureLine}import { starterProviders } from "./providers/index.ts";
4615
4665
 
4616
4666
  export interface BootstrapOptions {
@@ -4618,73 +4668,71 @@ export interface BootstrapOptions {
4618
4668
  }
4619
4669
 
4620
4670
  export interface BootstrappedApp {
4621
- context: AppContext;
4671
+ context: InitializedAppContext;
4622
4672
  routes: AppRouteMap;
4623
4673
  config: ReturnType<typeof loadConfig>;
4624
4674
  }
4625
4675
 
4626
- function createAppContext(): AppContext {
4627
- const container = new ServiceContainer();
4628
- const config = new ConfigStore();
4629
- const dependencies: MutableAppDependencies = { container };
4630
- const context: ProviderContext = { container, config, dependencies };
4631
-
4632
- runProviderPhase(starterProviders, "register", context);
4633
- runProviderPhase(starterProviders, "boot", context);
4634
-
4676
+ async function createAppContext(): Promise<InitializedAppContext> {
4677
+ await ensureModulesLoaded();
4635
4678
  const moduleProviders = discoverModules().flatMap((module) => module.providers ?? []);
4636
- runProviderPhase(moduleProviders, "register", context);
4637
- runProviderPhase(moduleProviders, "boot", context);
4638
-
4639
- assertAppDependenciesComplete(dependencies);
4640
-
4641
- const appContext: AppContext = { container, config, dependencies };
4642
- setActiveApplicationContext(appContext);
4643
- return appContext;
4679
+ return createProviderAppContext([...starterProviders, ...moduleProviders]);
4644
4680
  }
4645
4681
 
4646
4682
  export async function bootstrapApp(options: BootstrapOptions = {}): Promise<BootstrappedApp> {
4647
- const isProduction = isProductionEnv();
4648
- // Dev boots migrate for convenience. Production must not mutate schema on
4649
- // start, so run \`strata migrate\` as an explicit deploy step instead.
4650
- const { migrate: runMigrate = !isProduction } = options;
4683
+ let context: InitializedAppContext | undefined;
4684
+ try {
4685
+ const isProduction = isProductionEnv();
4686
+ // Dev boots migrate for convenience. Production must not mutate schema on
4687
+ // start, so run \`strata migrate\` as an explicit deploy step instead.
4688
+ const { migrate: runMigrate = !isProduction } = options;
4651
4689
 
4652
- if (isProduction) {
4653
- assertProductionSecrets();
4654
- }
4690
+ if (isProduction) {
4691
+ assertProductionSecrets();
4692
+ }
4655
4693
 
4656
- ${needsEnsure(layers) ? ` await ensureAppDatabase();
4657
- ` : ""} const appConfig = loadConfig();
4658
- getSql();
4659
- if (isRlsTenancy()) {
4660
- await assertRlsLiveDatabaseRole();
4661
- }
4662
- configureModulesDirectory(join(import.meta.dir, "../modules"));
4663
- await ensureModulesLoaded();
4664
- const context = createAppContext();
4694
+ ${needsEnsure(layers) ? ` await ensureAppDatabase();
4695
+ ` : ""} const appConfig = loadConfig();
4696
+ getSql();
4697
+ if (!(await pingDatabase())) throw new Error("Database is not ready.");
4698
+ if (isRlsTenancy()) {
4699
+ await assertRlsLiveDatabaseRole();
4700
+ }
4701
+ configureModulesDirectory(join(import.meta.dir, "../modules"));
4702
+ await ensureModulesLoaded();
4703
+ context = await createAppContext();
4665
4704
 
4666
- if (runMigrate) {
4667
- await migrate();
4668
- }
4705
+ if (runMigrate) {
4706
+ await migrate();
4707
+ }
4669
4708
 
4670
- const routes = mergeSpaRoutes(context.dependencies, {
4671
- ...createHealthRoutes(context.dependencies),
4672
- ...buildRoutes(context.dependencies),${metricsSpread}
4673
- }, {
4674
- distDirectory: join(import.meta.dir, "../../frontend/dist"),
4675
- });
4709
+ const routes = mergeSpaRoutes(context.dependencies, {
4710
+ ...createHealthRoutes(context.dependencies),
4711
+ ...buildRoutes(context.dependencies),${metricsSpread}
4712
+ }, {
4713
+ distDirectory: join(import.meta.dir, "../../frontend/dist"),
4714
+ });
4676
4715
 
4677
- return { context, routes, config: appConfig };
4716
+ return { context, routes, config: appConfig };
4717
+ } catch (error) {
4718
+ const failures: unknown[] = [];
4719
+ for (const cleanup of [() => context?.dispose(), closeDatabase]) {
4720
+ try { await cleanup(); } catch (failure) { failures.push(failure); }
4721
+ }
4722
+ if (failures.length) throw new AggregateError([error, ...failures], "Application startup and cleanup failed.", { cause: error });
4723
+ throw error;
4724
+ }
4678
4725
  }
4679
4726
 
4680
4727
  export async function createApp(options: BootstrapOptions = {}) {
4681
4728
  return bootstrapApp({ migrate: false, ...options });
4682
4729
  }
4683
4730
 
4684
- export function createAppServer(routes: AppRouteMap, port = 0) {
4731
+ export function createAppServer(routes: AppRouteMap, port = 0, lifecycle?: LifecycleCoordinator) {
4685
4732
  return createWebServer({
4686
4733
  port,
4687
4734
  publicDir: "./public",
4735
+ lifecycle,
4688
4736
  routes,
4689
4737
  });
4690
4738
  }
@@ -4706,10 +4754,11 @@ export function buildRoutes(dependencies: AppDependencies): AppRouteMap {
4706
4754
  }
4707
4755
  `;
4708
4756
  }
4709
- function renderCliRegisterTs() {
4757
+ function renderCliRegisterTs(layers) {
4710
4758
  return `import type { StrataCommandMap } from "@getstrata/cli";
4711
4759
 
4712
- const commands: StrataCommandMap = {
4760
+ const commands: StrataCommandMap = {${layers && authNeedsUsers(layers.auth) ? `
4761
+ "auth:provision-admin": async () => (await import("./initialAdmin.ts")).initialAdminCommand,` : ""}
4713
4762
  "make:module": async () => (await import("@getstrata/cli/scaffold")).makeModuleCommand,
4714
4763
  "make:policy": async () => (await import("@getstrata/cli/scaffold")).makePolicyCommand,
4715
4764
  "make:job": async () => (await import("@getstrata/cli/scaffold")).makeJobCommand,
@@ -4740,9 +4789,20 @@ function renderCliQueueWorkTs() {
4740
4789
  const { bootstrapApp } = await import("../bootstrap/createApp.ts");
4741
4790
  const { closeDatabase } = await import("../bootstrap/database.ts");
4742
4791
 
4792
+ let app: Awaited<ReturnType<typeof bootstrapApp>> | undefined;
4743
4793
  await runQueueWorkerCommand({
4744
- boot: () => bootstrapApp({ migrate: false }),
4745
- close: closeDatabase,
4794
+ boot: async () => {
4795
+ app = await bootstrapApp({ migrate: false });
4796
+ },
4797
+ drain: () => app?.context.drain(),
4798
+ flush: () => app?.context.flush(),
4799
+ close: async () => {
4800
+ try {
4801
+ await app?.context.dispose();
4802
+ } finally {
4803
+ await closeDatabase();
4804
+ }
4805
+ },
4746
4806
  });
4747
4807
  }
4748
4808
 
@@ -4800,11 +4860,15 @@ export { openapiCheckCommand, openapiGenerateCommand, openapiValidateCommand };
4800
4860
  function renderCliScheduleRunTs() {
4801
4861
  return `async function scheduleRunCommand(): Promise<void> {
4802
4862
  const { createScheduleRunCommand } = await import("@getstrata/cli/schedule");
4863
+ const { bootstrapApp } = await import("../bootstrap/createApp.ts");
4864
+ const { closeDatabase } = await import("../bootstrap/database.ts");
4865
+ let app: Awaited<ReturnType<typeof bootstrapApp>> | undefined;
4803
4866
  await createScheduleRunCommand(async () => {
4804
- const { bootstrapApp } = await import("../bootstrap/createApp.ts");
4805
- await bootstrapApp({ migrate: false });
4867
+ app = await bootstrapApp({ migrate: false });
4806
4868
  await import("../bootstrap/schedule.ts");
4807
- })();
4869
+ }, async () => {
4870
+ try { await app?.context.dispose(); } finally { await closeDatabase(); }
4871
+ }, { drain: () => app?.context.drain(), flush: () => app?.context.flush() })();
4808
4872
  }
4809
4873
 
4810
4874
  export { scheduleRunCommand };
@@ -5186,6 +5250,7 @@ function renderScimModule(layers) {
5186
5250
  return null;
5187
5251
  }
5188
5252
  return `import { randomBytes } from "node:crypto";
5253
+ import type { HttpKernel } from "@getstrata/bootstrap/httpKernel";
5189
5254
  import type { AppModule } from "@getstrata/bootstrap/contracts";
5190
5255
  import { routeParams } from "@getstrata/bootstrap/web/routing";
5191
5256
  import { createScimAuthMiddleware } from "@getstrata/core/auth/scimAuthMiddleware";
@@ -5283,12 +5348,12 @@ function readName(body: Record<string, unknown>, fallback: string): string {
5283
5348
  return fallback;
5284
5349
  }
5285
5350
 
5286
- function wrapScim(handler: (request: Request) => Promise<Response>) {
5287
- const throttle = createScimThrottleMiddleware({
5351
+ function wrapScim(kernel: HttpKernel, handler: (request: Request) => Promise<Response>) {
5352
+ const throttle = kernel.ownThrottle(createScimThrottleMiddleware({
5288
5353
  redisUrl: process.env.REDIS_URL,
5289
5354
  maxAttempts: 120,
5290
5355
  decaySeconds: 60,
5291
- });
5356
+ }));
5292
5357
  return withMiddleware(throttle, createScimAuthMiddleware())(
5293
5358
  withErrorHandling(async (request) => {
5294
5359
  if (!scimEnabled()) {
@@ -5307,7 +5372,7 @@ const scimModule: AppModule = {
5307
5372
  "/scim/v2/ServiceProviderConfig": {
5308
5373
  GET: kernel.wrap(
5309
5374
  "api",
5310
- wrapScim(async () =>
5375
+ wrapScim(kernel, async () =>
5311
5376
  scimJson({
5312
5377
  schemas: [CONFIG_SCHEMA],
5313
5378
  patch: { supported: true },
@@ -5332,7 +5397,7 @@ const scimModule: AppModule = {
5332
5397
  "/scim/v2/Users": {
5333
5398
  GET: kernel.wrap(
5334
5399
  "api",
5335
- wrapScim(async (request) => {
5400
+ wrapScim(kernel, async (request) => {
5336
5401
  const url = new URL(request.url);
5337
5402
  const filter = url.searchParams.get("filter") ?? "";
5338
5403
  const match = /userName\\s+eq\\s+"([^"]+)"/i.exec(filter);
@@ -5364,7 +5429,7 @@ const scimModule: AppModule = {
5364
5429
  ),
5365
5430
  POST: kernel.wrap(
5366
5431
  "api",
5367
- wrapScim(async (request) => {
5432
+ wrapScim(kernel, async (request) => {
5368
5433
  const body = (await request.json()) as Record<string, unknown>;
5369
5434
  const email = readUserName(body);
5370
5435
  const name = readName(body, email.split("@")[0] ?? "User");
@@ -5387,7 +5452,7 @@ const scimModule: AppModule = {
5387
5452
  "/scim/v2/Users/:id": {
5388
5453
  GET: kernel.wrap(
5389
5454
  "api",
5390
- wrapScim(async (request) => {
5455
+ wrapScim(kernel, async (request) => {
5391
5456
  const id = readScimUserId(request);
5392
5457
  if (id instanceof Response) {
5393
5458
  return id;
@@ -5401,7 +5466,7 @@ const scimModule: AppModule = {
5401
5466
  ),
5402
5467
  PUT: kernel.wrap(
5403
5468
  "api",
5404
- wrapScim(async (request) => {
5469
+ wrapScim(kernel, async (request) => {
5405
5470
  const id = readScimUserId(request);
5406
5471
  if (id instanceof Response) {
5407
5472
  return id;
@@ -5422,7 +5487,7 @@ const scimModule: AppModule = {
5422
5487
  ),
5423
5488
  PATCH: kernel.wrap(
5424
5489
  "api",
5425
- wrapScim(async (request) => {
5490
+ wrapScim(kernel, async (request) => {
5426
5491
  const id = readScimUserId(request);
5427
5492
  if (id instanceof Response) {
5428
5493
  return id;
@@ -5463,7 +5528,7 @@ const scimModule: AppModule = {
5463
5528
  ),
5464
5529
  DELETE: kernel.wrap(
5465
5530
  "api",
5466
- wrapScim(async (request) => {
5531
+ wrapScim(kernel, async (request) => {
5467
5532
  const id = readScimUserId(request);
5468
5533
  if (id instanceof Response) {
5469
5534
  return id;
@@ -5578,7 +5643,16 @@ function writeGeneratedFiles(options) {
5578
5643
  }
5579
5644
  writeText(join2(src, "bootstrap/createApp.ts"), renderCreateAppTs(layers));
5580
5645
  writeText(join2(src, "bootstrap/schedule.ts"), renderScheduleTs());
5581
- writeText(join2(src, "cli/register.ts"), renderCliRegisterTs());
5646
+ writeText(join2(src, "cli/register.ts"), renderCliRegisterTs(layers));
5647
+ const initialAdminCommand = renderInitialAdminCommand(layers);
5648
+ const initialAdminMigration = renderInitialAdminMigration(layers);
5649
+ if (initialAdminCommand && initialAdminMigration) {
5650
+ writeText(join2(src, "cli/initialAdmin.ts"), initialAdminCommand);
5651
+ writeText(join2(src, "db/migrations/0004_initial_admin_provisioning.ts"), initialAdminMigration);
5652
+ } else {
5653
+ removeIfExists(join2(src, "cli/initialAdmin.ts"));
5654
+ removeIfExists(join2(src, "db/migrations/0004_initial_admin_provisioning.ts"));
5655
+ }
5582
5656
  writeText(join2(src, "cli/queueWork.ts"), renderCliQueueWorkTs());
5583
5657
  writeText(join2(src, "cli/queueFailed.ts"), renderCliQueueFailedTs());
5584
5658
  writeText(join2(src, "cli/openapi.ts"), renderCliOpenApiTs());
@@ -12,9 +12,9 @@
12
12
  "check": "tsc --noEmit"
13
13
  },
14
14
  "dependencies": {
15
- "@getstrata/bootstrap": "^2.1.0",
16
- "@getstrata/cli": "^2.1.0",
17
- "@getstrata/core": "^2.1.0",
15
+ "@getstrata/bootstrap": "^2.2.1",
16
+ "@getstrata/cli": "^2.2.1",
17
+ "@getstrata/core": "^2.2.1",
18
18
  "eta": "^4.6.0"
19
19
  },
20
20
  "devDependencies": {
@@ -5,13 +5,13 @@ import type { ServiceProvider } from "@getstrata/core/contracts/di";
5
5
 
6
6
  const cacheProvider: ServiceProvider = {
7
7
  name: "starter.cache",
8
- register({ container, config, dependencies }) {
8
+ register({ container, config, dependencies, onCleanup }) {
9
9
  container.singleton(CORE_CACHE_TOKEN, () => {
10
10
  const ttlMs = config.get<number>("cache.ttlMs") ?? 3_600_000;
11
11
  const maxEntries = config.get<number>("cache.maxEntries") ?? 100;
12
12
  const driver = config.get<"array" | "redis">("cache.driver") ?? "array";
13
13
 
14
- return new CacheRepository(
14
+ const cache = new CacheRepository(
15
15
  createCacheStore({
16
16
  driver,
17
17
  ttlMs,
@@ -19,6 +19,8 @@ const cacheProvider: ServiceProvider = {
19
19
  redisUrl: process.env.REDIS_URL,
20
20
  }),
21
21
  );
22
+ onCleanup(() => cache.close());
23
+ return cache;
22
24
  });
23
25
 
24
26
  Reflect.set(dependencies, "cache", container.resolve(CORE_CACHE_TOKEN));
@@ -1,25 +1,28 @@
1
1
  import "./preload.ts";
2
- import { ensureModulesLoaded } from "@getstrata/bootstrap/discoverModules";
2
+ import {
3
+ installGracefulShutdownSignals,
4
+ LifecycleCoordinator,
5
+ } from "@getstrata/core/lifecycle/gracefulShutdown";
3
6
  import { bootstrapApp, createAppServer } from "./createApp.ts";
4
- import { closeDatabase, pingDatabase } from "./database.ts";
7
+ import { closeDatabase } from "./database.ts";
5
8
 
6
- await ensureModulesLoaded();
7
-
8
- const { routes, config } = await bootstrapApp();
9
-
10
- const server = createAppServer(routes, config.port);
11
-
12
- console.log(`Listening on http://localhost:${server.port} (APP_URL ${config.appUrl})`);
13
-
14
- if (!(await pingDatabase())) {
15
- console.warn("Warning: database ping failed.");
16
- }
17
-
18
- async function shutdown() {
19
- await closeDatabase();
20
- server.stop();
21
- process.exit(0);
9
+ const { routes, config, context } = await bootstrapApp();
10
+ const lifecycle = new LifecycleCoordinator();
11
+ let server: ReturnType<typeof createAppServer>;
12
+ try {
13
+ server = createAppServer(routes, config.port, lifecycle);
14
+ } catch (error) {
15
+ try {
16
+ await context.dispose();
17
+ } finally {
18
+ await closeDatabase();
19
+ }
20
+ throw error;
22
21
  }
22
+ console.log(`Listening on http://localhost:${server.port} (APP_URL ${config.appUrl})`);
23
23
 
24
- process.on("SIGINT", shutdown);
25
- process.on("SIGTERM", shutdown);
24
+ lifecycle.register("providers:drain", () => context.drain(), "drain");
25
+ lifecycle.register("providers:flush", () => context.flush(), "flush");
26
+ lifecycle.register("providers:close", () => context.dispose(), "close");
27
+ lifecycle.register("database", closeDatabase, "close");
28
+ installGracefulShutdownSignals(undefined, lifecycle);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-strata",
3
- "version": "2.1.0",
3
+ "version": "2.2.1",
4
4
  "description": "Create a new Strata app. Interactive wizard; choose each layer; one database engine.",
5
5
  "type": "module",
6
6
  "license": "MIT",