@getstrata/bootstrap 3.0.5 → 3.0.8

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.
Files changed (43) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +11 -8
  3. package/dist/bootstrap/application/config.d.ts +7 -0
  4. package/dist/bootstrap/application/services.d.ts +28 -0
  5. package/dist/bootstrap/application.d.ts +115 -0
  6. package/dist/bootstrap/auth/accountWorkflows.d.ts +68 -0
  7. package/dist/bootstrap/auth/runtimeConfig.d.ts +66 -0
  8. package/dist/bootstrap/config.d.ts +1 -1
  9. package/dist/bootstrap/contracts.d.ts +1 -0
  10. package/dist/bootstrap/createSpaRoutes.d.ts +2 -0
  11. package/dist/bootstrap/databaseCommands.d.ts +26 -0
  12. package/dist/bootstrap/discoverJobs.d.ts +1 -2
  13. package/dist/bootstrap/discoverListeners.d.ts +4 -0
  14. package/dist/bootstrap/httpKernel.d.ts +0 -1
  15. package/dist/bootstrap/httpResponseComposition.d.ts +32 -0
  16. package/dist/bootstrap/jobDiscoveryState.d.ts +12 -0
  17. package/dist/bootstrap/providers/events.d.ts +2 -2
  18. package/dist/bootstrap/public-api.d.ts +3 -2
  19. package/dist/bootstrap/testing.d.ts +4 -0
  20. package/dist/entries/application.js +1 -0
  21. package/dist/entries/auth/accountWorkflows.js +98 -0
  22. package/dist/entries/auth/runtimeConfig.js +79 -0
  23. package/dist/entries/buildModuleRoutes.js +114 -94
  24. package/dist/entries/buildWebModuleRoutes.js +114 -94
  25. package/dist/entries/config.js +2 -0
  26. package/dist/entries/context.js +12 -18
  27. package/dist/entries/createSpaRoutes.js +2 -2
  28. package/dist/entries/createWebRoutes.js +114 -94
  29. package/dist/entries/databaseCommands.js +103 -0
  30. package/dist/entries/dependencies.js +12 -18
  31. package/dist/entries/discoverJobs.js +2 -15
  32. package/dist/entries/discoverListeners.js +34 -0
  33. package/dist/entries/health.js +1 -0
  34. package/dist/entries/httpKernel.js +114 -94
  35. package/dist/entries/providers/auth.js +1 -0
  36. package/dist/entries/providers/events.js +1 -0
  37. package/dist/entries/providers.js +6 -15
  38. package/dist/entries/testing.js +10 -0
  39. package/dist/entries/web/routing.js +114 -94
  40. package/dist/entries/web/server.js +2 -1
  41. package/dist/index.js +3222 -2272
  42. package/dist/internal/jobDiscoveryState.js +14 -0
  43. package/package.json +35 -6
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # @getstrata/bootstrap changelog
2
2
 
3
+ ## 3.0.8
4
+
5
+ Synchronize the Strata packages for the published starter template-discovery fix. Both generator entrypoints now locate their bundled templates after the source-template cleanup, and CI verifies generation from installed tarballs. See docs/releases/3.0.8.md.
6
+
7
+ ## 3.0.7
8
+
9
+ Carry forward the 3.0.6 application-authoring and correctness changes after its release stopped before publication. Correct SAML release acceptance to require browser-bound state while preserving assertion validation, successful login and MFA. See docs/releases/3.0.7.md for upgrade notes.
10
+
11
+ ## 3.0.6
12
+
13
+ - Add packaged `defineApp` and `serveApplication` composition, shared account workflows, database provisioning/migration helpers and concise model/event listener declarations.
14
+ - Validate and freeze configuration before provisioning or migration. Carry the same snapshot through auth, workers, migrations and seeding; resolve relative storage/SQLite paths from the application root.
15
+ - Run canonical provider setup and boot in the correct phases, retain application-owned resource cleanup, and reject missing worker configuration before schema side effects.
16
+ - Keep composition tokens identical across the package root and application entrypoint. Fix separately bundled event listeners using a different token from application event bindings.
17
+ - Narrow consumer queue/event/policy capabilities and expose bootstrap test controls only through `@getstrata/bootstrap/testing`.
18
+ - Integrate core shutdown and authentication fixes, including browser-bound OAuth/SAML state, purpose-bound password confirmation and compatible positive JWT lifetimes.
19
+
20
+ **Upgrade:** Existing applications should adopt the small `defineApp` declaration and current generated composition instead of copying framework lifecycle code. Model/repository registration and account mapping remain explicit. Update removed test-control imports. Package upgrades do not rewrite existing auth modules: apply the current GitHub/SAML route changes, use HTTPS for SAML, and expect one fresh password confirmation. See [the release notes](../../docs/releases/3.0.6.md).
21
+
3
22
  ## 3.0.5
4
23
 
5
24
  - Fixed SQLite queries returning no rows when SQL begins with comments, including VALUES, PRAGMA, EXPLAIN, and compact RETURNING statements.
package/README.md CHANGED
@@ -14,15 +14,18 @@ bunx create-strata my-app
14
14
  bun add @getstrata/bootstrap @getstrata/core
15
15
  ```
16
16
 
17
- ## HttpKernel and providers
17
+ ## Application startup
18
18
 
19
- ```typescript
20
- import { coreProviders, createAppContext, createHttpKernel } from "@getstrata/bootstrap";
21
- ```
22
-
23
- `createAppContext()` does not call `assertProductionSecrets`. Call that yourself when `isProductionEnv()` is true (`APP_ENV` or `NODE_ENV` production, `APP_ENV=staging`, or an unrecognized `APP_ENV`); it is feature-gated, so an HTML app with API tokens off is not asked for token secrets. It rejects empty secrets, short `SESSION_SECRET` values, wildcard `CORS_ALLOWED_ORIGINS`, `AUTH_DEV_HEADERS` other than `false`, `FEATURE_PUBLIC_READS=true`, and any secret still holding a generated `change-me` placeholder.
19
+ Generated apps use `defineApp` from `@getstrata/bootstrap/application` with a small
20
+ application definition. The package supplies `bootstrapApp`, `createApp` and
21
+ `createAppServer`; application choices belong in that definition. The application
22
+ owns startup validation, discovery, providers, native Bun HTTP and resource cleanup.
23
+ Keep the returned owner and stop it through its application lifecycle handle.
24
24
 
25
- Build routes with `buildWebModuleRoutes` and `buildModuleRoutes`.
25
+ Advanced integrations can still compose `createHttpKernel`, module route builders
26
+ and explicit providers. Low-level application contexts require an application
27
+ definition and selected connection; they are not ownerless startup shortcuts.
28
+ Test seams belong on `@getstrata/bootstrap/testing`.
26
29
 
27
30
  ## Web utilities
28
31
 
@@ -48,7 +51,7 @@ HTML apps should bind `createCookieSessionAuthManager` from `@getstrata/bootstra
48
51
 
49
52
  ## Queue
50
53
 
51
- `registerDefaultJobs()` registers `cache.invalidate-tags` and `audit.export` only. Outbound model webhooks are not a core job. Put a class with `static jobName` in `src/jobs/` (generated `--webhooks` uses `webhook.dispatch`) and call `await discoverJobs()` on boot. `queue:work` already does that. There is no `registerWebhookJobs()` export.
54
+ `registerDefaultJobs()` registers `cache.invalidate-tags` and `audit.export` only. Outbound model webhooks are not a core job. Put a class with `static jobName` in `src/jobs/` (generated `--webhooks` uses `webhook.dispatch`) and discover it into the owned job registry on boot. `queue:work` already does that. There is no `registerWebhookJobs()` export.
52
55
 
53
56
  ## Not a starter API
54
57
 
@@ -0,0 +1,7 @@
1
+ export interface ApplicationConfig {
2
+ readonly port: number;
3
+ readonly hostname?: string;
4
+ readonly appUrl: string;
5
+ readonly databaseUrl: string;
6
+ }
7
+ export declare function loadApplicationConfig(env: Readonly<Record<string, string | undefined>>): ApplicationConfig;
@@ -0,0 +1,28 @@
1
+ import { CacheRepository } from "@getstrata/core/cache/repository";
2
+ import type { ServiceProvider } from "@getstrata/core/contracts/di";
3
+ import { type ServiceDeclaration } from "@getstrata/core/contracts/services";
4
+ import type { Queue } from "@getstrata/core/queue";
5
+ import { type QueueServices } from "@getstrata/core/queue/createAppQueue";
6
+ import { JobRegistry } from "@getstrata/core/queue/jobRegistry";
7
+ import { StorageManager } from "@getstrata/core/storage/storage";
8
+ import type { AppDefinition, ApplicationAuthServices } from "../application";
9
+ import { loadApplicationConfig } from "./config";
10
+ export declare const APPLICATION_STORAGE: import("@getstrata/core/contracts/token").ServiceToken<StorageManager>;
11
+ export declare const APPLICATION_CACHE: import("@getstrata/core/contracts/token").ServiceToken<CacheRepository>;
12
+ export declare const APPLICATION_QUEUE: import("@getstrata/core/contracts/token").ServiceToken<Queue>;
13
+ export declare const APPLICATION_QUEUE_SERVICES: import("@getstrata/core/contracts/token").ServiceToken<QueueServices>;
14
+ export declare const APPLICATION_AUDIT_EXPORT: import("@getstrata/core/contracts/token").ServiceToken<() => Promise<number>>;
15
+ export declare const APPLICATION_BILLING: import("@getstrata/core/contracts/token").ServiceToken<Readonly<{
16
+ enabled: boolean;
17
+ stripeSecret: string;
18
+ }>>;
19
+ export declare const APPLICATION_WEBHOOKS: import("@getstrata/core/contracts/token").ServiceToken<Readonly<{
20
+ allowPrivate: boolean;
21
+ signatureHeader: string;
22
+ }>>;
23
+ export declare function createApplicationServices(env: Readonly<Record<string, string | undefined>>, invoke: import("@getstrata/core/contracts/persistence").PersistenceInvocation, root: string): readonly ServiceDeclaration[];
24
+ export declare function createApplicationProviders<A extends ApplicationAuthServices>(definition: AppDefinition<A>, env: Readonly<Record<string, string | undefined>>, auth: A, cache: CacheRepository, queue: Queue, queueServices: QueueServices, events: import("@getstrata/core/events").EventBus, billing: Readonly<{
25
+ enabled: boolean;
26
+ stripeSecret: string;
27
+ }>, storage: StorageManager, registry: JobRegistry, appConfig?: ReturnType<typeof loadApplicationConfig>): readonly ServiceProvider[];
28
+ export declare function createConfigProvider(appConfig: ReturnType<typeof loadApplicationConfig>, env: Readonly<Record<string, string | undefined>>): ServiceProvider;
@@ -0,0 +1,115 @@
1
+ import { type InitializedAppContext } from "@getstrata/bootstrap/context";
2
+ import { type AppRouteMap } from "@getstrata/bootstrap/contracts";
3
+ import { type MetricsRuntimeOptions } from "@getstrata/bootstrap/metricsRoutes";
4
+ import { type NativeServerOptions } from "@getstrata/bootstrap/web/server";
5
+ import type { Application, ProviderDefinition } from "@getstrata/core/contracts/application";
6
+ import type { PersistenceInvocation } from "@getstrata/core/contracts/persistence";
7
+ import type { ServiceToken } from "@getstrata/core/contracts/token";
8
+ import type { DatabaseDefinition } from "@getstrata/core/database/bindings";
9
+ import type { DatabaseConnectionOptions } from "@getstrata/core/database/session";
10
+ import type { DurableListener } from "@getstrata/core/events/outbox";
11
+ import { createOutboxWorkerTransport, type SqlOutbox } from "@getstrata/core/events/outbox";
12
+ import { type JobRegistry } from "@getstrata/core/queue/jobRegistry";
13
+ import { createQueueWorkerTransport } from "@getstrata/core/queue/queueWorkerTransport";
14
+ import { type FrontendMode } from "@getstrata/core/runtime/frontendMode";
15
+ import type { Server } from "bun";
16
+ import { loadApplicationConfig } from "./application/config";
17
+ import type { AppModule } from "./contracts";
18
+ import type { HttpPersistenceOptions } from "./persistenceContracts";
19
+ import type { MetadataAuthOptions } from "./providers/auth";
20
+ export interface BootstrapOptions {
21
+ migrate?: boolean;
22
+ transports?: readonly import("@getstrata/core/contracts/application").TransportDefinition[];
23
+ providers?: readonly ProviderDefinition[];
24
+ services?: readonly import("@getstrata/core/contracts/services").ServiceDeclaration[];
25
+ persistence?: Pick<import("@getstrata/core/database/bindings").DatabaseDefinition, "repositories" | "models" | "repositoryEffects">;
26
+ mode?: "http" | "command" | "worker" | "outbox-worker";
27
+ server?: {
28
+ port?: number;
29
+ native?: NativeServerOptions;
30
+ };
31
+ onConstructed?: (application: Application) => undefined;
32
+ runtimeMetrics?: Omit<MetricsRuntimeOptions, "failedJobs" | "outbox"> & {
33
+ failedJobs?: Omit<NonNullable<MetricsRuntimeOptions["failedJobs"]>, "observeReadOnly">;
34
+ outbox?: Omit<NonNullable<MetricsRuntimeOptions["outbox"]>, "observeReadOnly">;
35
+ };
36
+ }
37
+ export interface BootstrappedApp {
38
+ application: Application;
39
+ auditExport: () => Promise<number>;
40
+ invoke: PersistenceInvocation;
41
+ readonly outbox: Readonly<Pick<SqlOutbox, "publish">>;
42
+ context: InitializedAppContext;
43
+ routes: AppRouteMap;
44
+ config: ReturnType<typeof loadApplicationConfig>;
45
+ queue: import("@getstrata/core/queue").QueueDispatcher;
46
+ queueServices: import("@getstrata/core/queue/createAppQueue").QueueServices;
47
+ registry: JobRegistry;
48
+ server?: Server<unknown>;
49
+ worker?: ReturnType<typeof createQueueWorkerTransport>;
50
+ outboxWorker?: ReturnType<typeof createOutboxWorkerTransport>;
51
+ }
52
+ /** Application-owned choices. Pools, transports and lifecycle assembly stay in the package. */
53
+ export interface ApplicationAuthServices {
54
+ readonly metadata: HttpPersistenceOptions["metadata"];
55
+ readonly config: {
56
+ readonly signatureSecret: string;
57
+ readonly sessionCookie: {
58
+ readonly cookieName: string;
59
+ readonly production: boolean;
60
+ };
61
+ readonly passwordConfirmation: NonNullable<HttpPersistenceOptions["passwordConfirmation"]>;
62
+ };
63
+ }
64
+ export type ApplicationAuthOptions = Omit<MetadataAuthOptions, "mechanisms" | "sessionGuard" | "mfaSecrets"> & {
65
+ readonly environment: Readonly<Record<string, string | undefined>>;
66
+ readonly sessionSecret?: string;
67
+ readonly signatureSecret?: string;
68
+ };
69
+ export interface AppDefinition<A extends ApplicationAuthServices> {
70
+ readonly root: string;
71
+ readonly database: (env: Readonly<Record<string, string | undefined>>) => DatabaseConnectionOptions;
72
+ readonly auth: {
73
+ readonly create: (options: ApplicationAuthOptions) => A;
74
+ readonly token: ServiceToken<A>;
75
+ };
76
+ readonly models: NonNullable<DatabaseDefinition["models"]>;
77
+ readonly repositories: NonNullable<DatabaseDefinition["repositories"]>;
78
+ readonly migrate: (environment?: Readonly<Record<string, string | undefined>>) => Promise<void>;
79
+ readonly ensureDatabase?: (options: {
80
+ provision: boolean;
81
+ environment?: Readonly<Record<string, string | undefined>>;
82
+ }) => Promise<unknown>;
83
+ readonly routes?: (dependencies: import("./contracts").AppDependencies, modules: readonly AppModule[], options: {
84
+ frontend: FrontendMode;
85
+ }) => AppRouteMap;
86
+ readonly outbox: {
87
+ readonly listeners: readonly DurableListener[];
88
+ readonly token?: ServiceToken<Readonly<Pick<SqlOutbox, "publish">>>;
89
+ };
90
+ readonly tenancy: "none" | "column" | "rls";
91
+ readonly frontend: "api" | "spa-react" | "server-htmx" | "hybrid";
92
+ readonly views?: boolean;
93
+ readonly scim?: boolean;
94
+ readonly metrics?: boolean;
95
+ readonly health?: (database: import("@getstrata/core/database/session").DatabaseSession) => Promise<boolean>;
96
+ readonly modulesDirectory?: string;
97
+ readonly defaults?: Readonly<Record<string, string | undefined>>;
98
+ readonly providers?: readonly ProviderDefinition[];
99
+ }
100
+ export declare function defineApp<A extends ApplicationAuthServices>(input: AppDefinition<A>): Readonly<{
101
+ bootstrapApp: {
102
+ (options: BootstrapOptions & {
103
+ mode: "outbox-worker";
104
+ }): Promise<BootstrappedApp & {
105
+ outboxWorker: ReturnType<typeof createOutboxWorkerTransport>;
106
+ }>;
107
+ (options?: BootstrapOptions): Promise<BootstrappedApp>;
108
+ };
109
+ createApp: (options?: BootstrapOptions) => Promise<BootstrappedApp>;
110
+ createAppServer: (options?: Omit<BootstrapOptions, "mode">) => Promise<BootstrappedApp>;
111
+ }>;
112
+ /** The executable entrypoint owns signal wiring; applications declare only their server. */
113
+ export declare function serveApplication(start: () => Promise<BootstrappedApp>): Promise<BootstrappedApp>;
114
+ export { CORE_QUEUE_TOKEN as APPLICATION_QUEUE } from "@getstrata/core/contracts/serviceTokens";
115
+ export { APPLICATION_BILLING, APPLICATION_WEBHOOKS, } from "./application/services";
@@ -0,0 +1,68 @@
1
+ import { type PasswordLoginResult } from "@getstrata/core/auth/passwordLogin";
2
+ import type { AuthUserRecord } from "@getstrata/core/contracts/authUserDirectory";
3
+ import type { MfaSecretCodec } from "@getstrata/core/crypto/mfaSecret";
4
+ export declare function parseLoginCredentials(payload: unknown): {
5
+ email: string;
6
+ password: string;
7
+ mfa_code: string | undefined;
8
+ };
9
+ export declare function parseRegisterCredentials(payload: unknown): {
10
+ name: string;
11
+ email: string;
12
+ password: string;
13
+ };
14
+ export declare function parseForgotPasswordEmail(payload: unknown): string;
15
+ /** Directory and locking callbacks retain the application's established tenant and cancellation scope. */
16
+ export declare function withLoginAccount<Ports, Record extends {
17
+ id: number;
18
+ email?: string | null;
19
+ }, Result>(ports: Ports, email: string, directory: (ports: Ports) => {
20
+ findByEmail(email: string): Promise<Record | null>;
21
+ }, lock: (ports: Ports, id: number, work: (record: Record | null, child: Ports) => Promise<Result>) => Promise<Result>, operation: (record: Record | null, child: Ports) => Promise<Result>): Promise<Result>;
22
+ export type PasswordAccountResult<User> = {
23
+ ok: false;
24
+ error: "invalid_credentials";
25
+ } | (PasswordLoginResult & {
26
+ user: User;
27
+ });
28
+ export declare function authenticatePasswordAccount<User extends Pick<AuthUserRecord, "is_active" | "mfa_enabled" | "mfa_secret" | "mfa_recovery_codes"> & {
29
+ password?: string | null;
30
+ }>(user: User | null, password: string, mfaCode: string | undefined, secrets: MfaSecretCodec, persistRecovery: (user: User, consumedHash: string | undefined) => Promise<void>): Promise<PasswordAccountResult<User>>;
31
+ /** A uniqueness race is neutral only after rollback and a scoped account readback. */
32
+ export declare function registerAccount<Ports, Result>(ports: Ports, email: string, options: {
33
+ write: <T>(ports: Ports, identifier: string, work: (child: Ports) => Promise<T>) => Promise<T>;
34
+ transaction: <T>(ports: Ports, work: (child: Ports) => Promise<T>) => Promise<T>;
35
+ create: (child: Ports) => Promise<Result>;
36
+ isUniqueViolation: (error: unknown) => boolean;
37
+ accountExists: (ports: Ports, email: string) => Promise<boolean>;
38
+ }): Promise<Result | undefined>;
39
+ /** Consume and mutate atomically so failed account changes leave the token usable. */
40
+ export declare function completeAccountToken<Ports>(ports: Ports, request: Request, purpose: string, options: {
41
+ transaction: <T>(ports: Ports, work: (child: Ports) => Promise<T>) => Promise<T>;
42
+ consume: (child: Ports, request: Request, purpose: string) => Promise<number | null>;
43
+ update: (child: Ports, userId: number) => Promise<void>;
44
+ }): Promise<boolean>;
45
+ export declare function prepareAccountMail<Ports>(ports: Ports, message: {
46
+ to: string;
47
+ subject: string;
48
+ path: string;
49
+ purpose: string;
50
+ userId: number;
51
+ extra?: Record<string, string>;
52
+ }, options: {
53
+ issue: () => {
54
+ plain: string;
55
+ hash: string;
56
+ };
57
+ store: (ports: Ports, token: {
58
+ purpose: string;
59
+ userId: number;
60
+ hash: string;
61
+ expiresAt: Date;
62
+ }) => Promise<void>;
63
+ sign: (path: string, ttl: number, parameters: Record<string, string>) => string;
64
+ }): Promise<{
65
+ to: string;
66
+ subject: string;
67
+ body: string;
68
+ }>;
@@ -0,0 +1,66 @@
1
+ import { type PasswordConfirmWriteOptions } from "@getstrata/core/auth/passwordConfirmCookie";
2
+ export interface AuthRuntimeOptions {
3
+ readonly environment: Readonly<Record<string, string | undefined>>;
4
+ readonly production: boolean;
5
+ readonly jwtSecret: string;
6
+ readonly sessionSecret?: string;
7
+ readonly signatureSecret?: string;
8
+ readonly oauthStateSecret?: string;
9
+ readonly passwordConfirmation?: PasswordConfirmWriteOptions;
10
+ }
11
+ export interface AuthRuntimeFeatures {
12
+ readonly users: boolean;
13
+ readonly cookie: boolean;
14
+ readonly token: boolean;
15
+ readonly jwt: boolean;
16
+ readonly signedUrls: boolean;
17
+ }
18
+ /** Resolve security options once at composition, before any request can observe them. */
19
+ export declare function createAuthRuntimeConfig(options: AuthRuntimeOptions, features: AuthRuntimeFeatures): Readonly<{
20
+ sessionCookie: Readonly<{
21
+ cookieName: string;
22
+ production: boolean;
23
+ }>;
24
+ registrationEnabled: boolean;
25
+ scimEnabled: boolean;
26
+ redisUrl: string | undefined;
27
+ samlEnabled: boolean;
28
+ oauthEnabled: boolean;
29
+ appName: string;
30
+ appUrl: string;
31
+ saml: Readonly<import("@getstrata/core/auth/saml/samlServiceProvider").SamlServiceProviderConfig> | undefined;
32
+ github: Readonly<{
33
+ clientId: string;
34
+ clientSecret: string;
35
+ redirectUri: string;
36
+ production: boolean;
37
+ userAgent: string;
38
+ }>;
39
+ oidc: Readonly<{
40
+ issuer: string;
41
+ clientId: string;
42
+ clientSecret: string;
43
+ redirectUri: string;
44
+ networkPolicy: Readonly<{
45
+ production: boolean;
46
+ allowPrivate: boolean;
47
+ }>;
48
+ }>;
49
+ throttleNamespace: string;
50
+ trustForwardedFor: boolean;
51
+ scimTenantForToken: (token: string) => number | null;
52
+ tokenExpiryDays: number | null;
53
+ jwtTtlSeconds: number;
54
+ jwtSecret: string;
55
+ signatureSecret: string;
56
+ oauth: Readonly<{
57
+ secret: string;
58
+ production: boolean;
59
+ }>;
60
+ passwordConfirmation: Readonly<{
61
+ secret: string;
62
+ cookieName: string;
63
+ ttlSeconds: number;
64
+ production: boolean;
65
+ }>;
66
+ }>;
@@ -5,7 +5,7 @@ declare const CACHE_DRIVER_CONFIG_KEY = "cache.driver";
5
5
  declare const REDIS_URL_CONFIG_KEY = "cache.redisUrl";
6
6
  declare const DATABASE_URL_CONFIG_KEY = "database.url";
7
7
  declare const CSRF_TARGET_ORIGIN_CONFIG_KEY = "http.csrf.targetOrigin";
8
- export { CORE_ABILITY_CHECKER_TOKEN, CORE_AUTH_TOKEN, CORE_AUTH_USER_DIRECTORY_TOKEN, CORE_CACHE_TOKEN, CORE_CONFIG_TOKEN, CORE_EVENT_BUS_TOKEN, CORE_HTTP_CLEANUP_TOKEN, CORE_POLICY_GATE_TOKEN, CORE_PUBLIC_TENANCY_TOKEN, CORE_QUEUE_TOKEN, CORE_TENANT_RESOLVER_TOKEN, CORE_THROTTLE_QUOTA_POLICY_TOKEN, } from "@getstrata/core/contracts/serviceTokens";
8
+ export { CORE_ABILITY_CHECKER_TOKEN, CORE_AUTH_TOKEN, CORE_AUTH_USER_DIRECTORY_TOKEN, CORE_CACHE_TOKEN, CORE_CONFIG_TOKEN, CORE_EVENT_BUS_TOKEN, CORE_HTTP_CLEANUP_TOKEN, CORE_POLICY_GATE_TOKEN, CORE_POLICY_REGISTRY_TOKEN, CORE_PUBLIC_TENANCY_TOKEN, CORE_QUEUE_TOKEN, CORE_TENANT_RESOLVER_TOKEN, CORE_THROTTLE_QUOTA_POLICY_TOKEN, } from "@getstrata/core/contracts/serviceTokens";
9
9
  declare const AUTH_DEV_HEADERS_CONFIG_KEY = "auth.allowDevHeaders";
10
10
  declare const DEFAULT_APP_PORT = 3000;
11
11
  declare const DEFAULT_CACHE_TTL_MS = 3600000;
@@ -18,6 +18,7 @@ interface AppModule {
18
18
  cacheTags?: readonly string[];
19
19
  cacheDeleteExtraTags?: readonly string[];
20
20
  providers?: ServiceProvider[];
21
+ policies?: Readonly<Record<string, import("@getstrata/core/auth/policy").Policy>>;
21
22
  routes?(context: ModuleRouteContext): AppRouteMap;
22
23
  webRoutes?(context: ModuleRouteContext): AppRouteMap;
23
24
  }
@@ -2,6 +2,8 @@ import type { RouteHandler } from "@getstrata/core/http/middleware";
2
2
  import type { AppDependencies, AppRouteMap } from "./contracts";
3
3
  declare const SPA_DIST_DIRECTORY: string;
4
4
  type SpaRouteOptions = {
5
+ enabled?: boolean;
6
+ viewsEnabled?: boolean;
5
7
  prefix?: string;
6
8
  distDirectory?: string;
7
9
  wrap?: (handler: RouteHandler) => RouteHandler;
@@ -0,0 +1,26 @@
1
+ import type { MigrationDatabase } from "@getstrata/core/database/migrations/types";
2
+ import type { DatabaseConnectionOptions } from "@getstrata/core/database/session";
3
+ type Environment = Readonly<Record<string, string | undefined>>;
4
+ type Driver = DatabaseConnectionOptions["driver"];
5
+ /** Resolve a configuration snapshot without opening a connection or mutating the environment. */
6
+ export declare function resolveDatabaseOptions(environment: Environment, defaults: {
7
+ driver: Driver;
8
+ defaultUrl?: string;
9
+ root?: string;
10
+ }): DatabaseConnectionOptions;
11
+ interface ProvisionDatabaseOptions {
12
+ readonly driver: "pgsql" | "mysql";
13
+ readonly runtimeUrl: string;
14
+ readonly migrationUrl?: string;
15
+ readonly password?: string;
16
+ readonly production: boolean;
17
+ readonly provision?: boolean;
18
+ }
19
+ /** Provision only when explicitly selected, with production defaulting to resolution only. */
20
+ export declare function ensureDatabase(options: ProvisionDatabaseOptions): Promise<string>;
21
+ /** Schema commands own one connection, including dialect selection, grants and cleanup. */
22
+ export declare function withMigrationDatabase<T>(options: DatabaseConnectionOptions, operation: (database: MigrationDatabase) => Promise<T>, controls?: {
23
+ readonly environment?: Environment;
24
+ readonly grantRuntimePrivileges?: boolean;
25
+ }): Promise<T>;
26
+ export {};
@@ -12,6 +12,5 @@ interface DiscoverJobsOptions extends InfrastructureDiscoveryOptions {
12
12
  manifest?: readonly JobManifestEntry[];
13
13
  }
14
14
  declare function discoverJobs(registry: JobRegistry, options?: DiscoverJobsOptions): Promise<string[]>;
15
- declare function resetDiscoverJobsForTests(registry: JobRegistry): void;
16
15
  export type { DiscoveredJobClass, DiscoverJobsOptions, JobManifestEntry };
17
- export { discoverJobs, resetDiscoverJobsForTests };
16
+ export { discoverJobs };
@@ -10,3 +10,7 @@ export interface DiscoverListenersOptions extends InfrastructureDiscoveryOptions
10
10
  readonly manifest?: readonly ListenerDeclarations[];
11
11
  }
12
12
  export declare function discoverListeners(options?: DiscoverListenersOptions): Promise<readonly ListenerDeclarations[]>;
13
+ /** Declare an after-commit listener; its lifetime belongs to the application graph. */
14
+ export declare function defineModelListener<R extends object, K extends keyof R & string, T extends import("@getstrata/core/database/baseRepository").BaseRepository<R, K>>(repository: import("@getstrata/core/database/definitions").RepositoryDefinition<R, K, T>, action: import("@getstrata/core/database/definitions").RepositoryAction, handler: import("@getstrata/core/database/definitions").AfterCommitRepositoryListener<R>): ListenerDeclarations;
15
+ /** Subscribe when the application opens and unsubscribe when it stops. */
16
+ export declare function defineEventListener(event: string, handler: Parameters<import("@getstrata/core/events").EventBus["listen"]>[1]): ListenerDeclarations;
@@ -35,7 +35,6 @@ declare class HttpKernel {
35
35
  wrapPasswordConfirm<TRequest extends Request>(handler: BusinessRouteHandler<TRequest>): ComposedRouteHandler<TRequest>;
36
36
  wrapRouteMap(routes: Record<string, unknown>, middleware: readonly Middleware[]): Record<string, unknown>;
37
37
  wrapScim<TRequest extends Request>(handler: BusinessRouteHandler<TRequest>, before?: readonly Middleware[]): ComposedRouteHandler<TRequest>;
38
- private responseMiddleware;
39
38
  /** Public application documents still own response policy and observation. */
40
39
  wrapPublicDocument<TRequest extends Request = Request>(handler: RouteHandler<TRequest>): RouteHandler<TRequest>;
41
40
  group(name: MiddlewareGroupName): Middleware[];
@@ -0,0 +1,32 @@
1
+ import type { Middleware } from "@getstrata/core/http/middleware";
2
+ import type { AppDependencies } from "./contracts";
3
+ import type { HttpPersistenceOptions } from "./persistenceContracts";
4
+ /** Snapshot response configuration once, independently of route wrapping and persistence. */
5
+ declare function resolveHttpResponseSettings(dependencies: AppDependencies, http: HttpPersistenceOptions | undefined): {
6
+ emailVerificationRequired: boolean;
7
+ viewsEnabled: boolean;
8
+ publicReadsEnabled: boolean;
9
+ etagEnabled: boolean;
10
+ responsePolicy: Readonly<{
11
+ cors: {
12
+ allowedOrigins: string[];
13
+ additionalAllowedHeaders: string[];
14
+ } | undefined;
15
+ securityHeaders: import("@getstrata/core/http/securityHeadersMiddleware").ContentSecurityPolicyOptions;
16
+ maxBodyBytes: number;
17
+ rateLimitPerMinute: number;
18
+ namespace: string;
19
+ trustForwardedFor: boolean;
20
+ loginRateLimit: Readonly<{
21
+ maxAttempts: number;
22
+ decaySeconds: number;
23
+ }>;
24
+ registerRateLimit: Readonly<{
25
+ maxAttempts: number;
26
+ decaySeconds: number;
27
+ }>;
28
+ }>;
29
+ configuredCsrfMiddleware: Middleware;
30
+ };
31
+ declare function createHttpResponseMiddleware(dependencies: AppDependencies, settings: ReturnType<typeof resolveHttpResponseSettings>, errorFormat: "json" | "web"): Middleware[];
32
+ export { createHttpResponseMiddleware, resolveHttpResponseSettings };
@@ -0,0 +1,12 @@
1
+ import type { JobRegistry } from "@getstrata/core/queue/jobRegistry";
2
+ import type { JobManifestEntry } from "./discoverJobs";
3
+ /** Package-private registry-owned discovery cache, shared by all package entries. */
4
+ interface DiscoverJobsState {
5
+ registered: Map<string, {
6
+ identity: unknown;
7
+ location: string;
8
+ }>;
9
+ loads: Map<string | readonly JobManifestEntry[], Promise<string[]>>;
10
+ }
11
+ declare function jobDiscoveryState(registry: JobRegistry): DiscoverJobsState;
12
+ export { jobDiscoveryState };
@@ -1,8 +1,8 @@
1
- import { EventBus } from "@getstrata/core/events";
1
+ import { EventBus, type EventDispatcher } from "@getstrata/core/events";
2
2
  import { CORE_EVENT_BUS_TOKEN } from "../config";
3
3
  import type { ServiceProvider } from "../contracts";
4
4
  export declare const APPLICATION_EVENT_BUS_TOKEN: import("@getstrata/core/contracts/token").ServiceToken<EventBus>;
5
5
  /** Non-ORM custom events keep one explicit app-owned dispatcher. */
6
6
  export declare function createEventBindings(): readonly import("@getstrata/core/contracts/services").ValueServiceDeclaration[];
7
- export declare function createEventsProvider(bus: EventBus): ServiceProvider;
7
+ export declare function createEventsProvider(bus: EventDispatcher): ServiceProvider;
8
8
  export { CORE_EVENT_BUS_TOKEN };
@@ -1,3 +1,4 @@
1
+ export { APPLICATION_BILLING, APPLICATION_QUEUE, APPLICATION_WEBHOOKS, type AppDefinition, type ApplicationAuthOptions, type ApplicationAuthServices, type BootstrapOptions, type BootstrappedApp, defineApp, serveApplication, } from "./application";
1
2
  /**
2
3
  * @getstrata/bootstrap: application shell for Strata apps.
3
4
  */
@@ -9,7 +10,7 @@ export type { BuildWebModuleRoutesOptions } from "./buildWebModuleRoutes.ts";
9
10
  export { buildWebModuleRoutes } from "./buildWebModuleRoutes.ts";
10
11
  export { cacheTagsForModelWrite, discoverModelTableNames } from "./cache/modelCacheTags.ts";
11
12
  export { createCachedJson } from "./cachedJson.ts";
12
- export { APP_PORT_CONFIG_KEY, CORE_ABILITY_CHECKER_TOKEN, CORE_AUTH_TOKEN, CORE_AUTH_USER_DIRECTORY_TOKEN, CORE_CACHE_TOKEN, CORE_CONFIG_TOKEN, CORE_EVENT_BUS_TOKEN, CORE_POLICY_GATE_TOKEN, CORE_QUEUE_TOKEN, CSRF_TARGET_ORIGIN_CONFIG_KEY, DATABASE_URL_CONFIG_KEY, DEFAULT_APP_PORT, REDIS_URL_CONFIG_KEY, } from "./config.ts";
13
+ export { APP_PORT_CONFIG_KEY, CORE_ABILITY_CHECKER_TOKEN, CORE_AUTH_TOKEN, CORE_AUTH_USER_DIRECTORY_TOKEN, CORE_CACHE_TOKEN, CORE_CONFIG_TOKEN, CORE_EVENT_BUS_TOKEN, CORE_POLICY_GATE_TOKEN, CORE_POLICY_REGISTRY_TOKEN, CORE_QUEUE_TOKEN, CSRF_TARGET_ORIGIN_CONFIG_KEY, DATABASE_URL_CONFIG_KEY, DEFAULT_APP_PORT, REDIS_URL_CONFIG_KEY, } from "./config.ts";
13
14
  export type { InitializedAppContext } from "./context.ts";
14
15
  export { collectProviders, createAppContext, runProviderPhase } from "./context.ts";
15
16
  export type { AppContext, AppDependencies, AppModule, AppRouteMap, CachedJson, ConfigStore, ModuleRouteContext, MutableAppDependencies, ProviderContext, ServiceFactory, ServiceProvider, } from "./contracts.ts";
@@ -18,7 +19,7 @@ export type { CreateWebRoutesOptions } from "./createWebRoutes.ts";
18
19
  export { createWebRoutes, mergeWebRoutes } from "./createWebRoutes.ts";
19
20
  export { createAppDependencies } from "./dependencies.ts";
20
21
  export type { DiscoveredJobClass, DiscoverJobsOptions, JobManifestEntry } from "./discoverJobs.ts";
21
- export { discoverJobs, resetDiscoverJobsForTests } from "./discoverJobs.ts";
22
+ export { discoverJobs } from "./discoverJobs.ts";
22
23
  export type { DiscoverModelsOptions } from "./discoverModels.ts";
23
24
  export { discoverModels } from "./discoverModels.ts";
24
25
  export type { DiscoverModulesOptions } from "./discoverModules.ts";
@@ -0,0 +1,4 @@
1
+ import type { JobRegistry } from "@getstrata/core/queue/jobRegistry";
2
+ /** Forget discovery caches for this registry between isolated tests. */
3
+ declare function resetDiscoverJobsForTests(registry: JobRegistry): void;
4
+ export { resetDiscoverJobsForTests };
@@ -0,0 +1 @@
1
+ export { defineApp, serveApplication, APPLICATION_BILLING, APPLICATION_WEBHOOKS, APPLICATION_QUEUE } from "../index.js";
@@ -0,0 +1,98 @@
1
+ // @bun
2
+ // ../../src/bootstrap/auth/accountWorkflows.ts
3
+ import { verifyPassword } from "@getstrata/core/auth/password";
4
+ import {
5
+ completePasswordLogin
6
+ } from "@getstrata/core/auth/passwordLogin";
7
+ import {
8
+ emailRule,
9
+ minLength,
10
+ required,
11
+ stringRule,
12
+ validateObject
13
+ } from "@getstrata/core/validation/rules";
14
+ function parseLoginCredentials(payload) {
15
+ const body = validateObject(payload, {
16
+ email: [required(), stringRule(), emailRule()],
17
+ password: [required(), stringRule()],
18
+ mfa_code: [stringRule()]
19
+ });
20
+ return {
21
+ email: String(body.email).toLowerCase(),
22
+ password: String(body.password ?? ""),
23
+ mfa_code: typeof body.mfa_code === "string" ? body.mfa_code : undefined
24
+ };
25
+ }
26
+ function parseRegisterCredentials(payload) {
27
+ const body = validateObject(payload, {
28
+ name: [required(), stringRule()],
29
+ email: [required(), stringRule(), emailRule()],
30
+ password: [required(), stringRule(), minLength(8)]
31
+ });
32
+ return {
33
+ name: String(body.name ?? ""),
34
+ email: String(body.email).toLowerCase(),
35
+ password: String(body.password ?? "")
36
+ };
37
+ }
38
+ function parseForgotPasswordEmail(payload) {
39
+ const body = validateObject(payload, { email: [required(), stringRule(), emailRule()] });
40
+ return String(body.email).toLowerCase();
41
+ }
42
+ async function withLoginAccount(ports, email, directory, lock, operation) {
43
+ const candidate = await directory(ports).findByEmail(email);
44
+ if (!candidate)
45
+ return operation(null, ports);
46
+ return lock(ports, candidate.id, (record, child) => operation(record?.email === email.trim().toLowerCase() ? record : null, child));
47
+ }
48
+ async function authenticatePasswordAccount(user, password, mfaCode, secrets, persistRecovery) {
49
+ if (!user?.password || !await verifyPassword(password, user.password))
50
+ return { ok: false, error: "invalid_credentials" };
51
+ const result = completePasswordLogin(user, { mfaCode }, secrets);
52
+ if (!result.ok)
53
+ return { ...result, user };
54
+ await persistRecovery(user, result.consumedRecoveryHash);
55
+ return { ...result, user };
56
+ }
57
+ async function registerAccount(ports, email, options) {
58
+ try {
59
+ return await options.write(ports, email, (child) => options.transaction(child, options.create));
60
+ } catch (error) {
61
+ if (!options.isUniqueViolation(error) || !await options.accountExists(ports, email))
62
+ throw error;
63
+ return;
64
+ }
65
+ }
66
+ async function completeAccountToken(ports, request, purpose, options) {
67
+ return options.transaction(ports, async (child) => {
68
+ const userId = await options.consume(child, request, purpose);
69
+ if (!userId)
70
+ return false;
71
+ await options.update(child, userId);
72
+ return true;
73
+ });
74
+ }
75
+ async function prepareAccountMail(ports, message, options) {
76
+ const issued = options.issue();
77
+ await options.store(ports, {
78
+ purpose: message.purpose,
79
+ userId: message.userId,
80
+ hash: issued.hash,
81
+ expiresAt: new Date(Date.now() + 3600 * 1000)
82
+ });
83
+ const link = options.sign(message.path, 3600, { ...message.extra, token: issued.plain });
84
+ return { to: message.to, subject: message.subject, body: `${message.subject}
85
+
86
+ ${link}
87
+ ` };
88
+ }
89
+ export {
90
+ authenticatePasswordAccount,
91
+ completeAccountToken,
92
+ parseForgotPasswordEmail,
93
+ parseLoginCredentials,
94
+ parseRegisterCredentials,
95
+ prepareAccountMail,
96
+ registerAccount,
97
+ withLoginAccount
98
+ };