@pattern-stack/codegen 0.13.1 → 0.14.0

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 (153) hide show
  1. package/dist/{job-orchestrator.protocol-CHOEqBDk.d.ts → job-orchestrator.protocol-CARhMLCO.d.ts} +1 -1
  2. package/dist/runtime/subsystems/analytics/analytics.module.js +6 -2
  3. package/dist/runtime/subsystems/analytics/analytics.module.js.map +1 -1
  4. package/dist/runtime/subsystems/analytics/analytics.tokens.d.ts +0 -11
  5. package/dist/runtime/subsystems/analytics/analytics.tokens.js +6 -2
  6. package/dist/runtime/subsystems/analytics/analytics.tokens.js.map +1 -1
  7. package/dist/runtime/subsystems/analytics/cube-backend.js +6 -2
  8. package/dist/runtime/subsystems/analytics/cube-backend.js.map +1 -1
  9. package/dist/runtime/subsystems/analytics/index.js +6 -2
  10. package/dist/runtime/subsystems/analytics/index.js.map +1 -1
  11. package/dist/runtime/subsystems/auth/auth.module.js +12 -6
  12. package/dist/runtime/subsystems/auth/auth.module.js.map +1 -1
  13. package/dist/runtime/subsystems/auth/auth.tokens.d.ts +0 -28
  14. package/dist/runtime/subsystems/auth/auth.tokens.js +12 -8
  15. package/dist/runtime/subsystems/auth/auth.tokens.js.map +1 -1
  16. package/dist/runtime/subsystems/auth/controllers/auth.controller.js +12 -5
  17. package/dist/runtime/subsystems/auth/controllers/auth.controller.js.map +1 -1
  18. package/dist/runtime/subsystems/auth/index.js +12 -8
  19. package/dist/runtime/subsystems/auth/index.js.map +1 -1
  20. package/dist/runtime/subsystems/auth/middleware/requester-context.js +12 -1
  21. package/dist/runtime/subsystems/auth/middleware/requester-context.js.map +1 -1
  22. package/dist/runtime/subsystems/bridge/bridge-delivery-handler.d.ts +1 -1
  23. package/dist/runtime/subsystems/bridge/bridge-delivery-handler.js +10 -2
  24. package/dist/runtime/subsystems/bridge/bridge-delivery-handler.js.map +1 -1
  25. package/dist/runtime/subsystems/bridge/bridge-outbox-drain-hook.js +10 -2
  26. package/dist/runtime/subsystems/bridge/bridge-outbox-drain-hook.js.map +1 -1
  27. package/dist/runtime/subsystems/bridge/bridge.module.d.ts +1 -1
  28. package/dist/runtime/subsystems/bridge/bridge.module.js +14 -9
  29. package/dist/runtime/subsystems/bridge/bridge.module.js.map +1 -1
  30. package/dist/runtime/subsystems/bridge/bridge.protocol.d.ts +1 -1
  31. package/dist/runtime/subsystems/bridge/event-flow.service.d.ts +1 -1
  32. package/dist/runtime/subsystems/bridge/event-flow.service.js +9 -1
  33. package/dist/runtime/subsystems/bridge/event-flow.service.js.map +1 -1
  34. package/dist/runtime/subsystems/bridge/index.d.ts +1 -1
  35. package/dist/runtime/subsystems/bridge/index.js +14 -9
  36. package/dist/runtime/subsystems/bridge/index.js.map +1 -1
  37. package/dist/runtime/subsystems/cache/cache.drizzle-backend.js +6 -1
  38. package/dist/runtime/subsystems/cache/cache.drizzle-backend.js.map +1 -1
  39. package/dist/runtime/subsystems/cache/cache.memory-backend.js +6 -1
  40. package/dist/runtime/subsystems/cache/cache.memory-backend.js.map +1 -1
  41. package/dist/runtime/subsystems/cache/cache.module.js +6 -2
  42. package/dist/runtime/subsystems/cache/cache.module.js.map +1 -1
  43. package/dist/runtime/subsystems/cache/cache.tokens.d.ts +0 -10
  44. package/dist/runtime/subsystems/cache/cache.tokens.js +6 -2
  45. package/dist/runtime/subsystems/cache/cache.tokens.js.map +1 -1
  46. package/dist/runtime/subsystems/cache/index.js +6 -2
  47. package/dist/runtime/subsystems/cache/index.js.map +1 -1
  48. package/dist/runtime/subsystems/events/event-bus.drizzle-backend.js +5 -0
  49. package/dist/runtime/subsystems/events/event-bus.drizzle-backend.js.map +1 -1
  50. package/dist/runtime/subsystems/events/event-bus.memory-backend.js +5 -0
  51. package/dist/runtime/subsystems/events/event-bus.memory-backend.js.map +1 -1
  52. package/dist/runtime/subsystems/events/event-bus.redis-backend.js +5 -1
  53. package/dist/runtime/subsystems/events/event-bus.redis-backend.js.map +1 -1
  54. package/dist/runtime/subsystems/events/events.module.js +5 -1
  55. package/dist/runtime/subsystems/events/events.module.js.map +1 -1
  56. package/dist/runtime/subsystems/events/events.tokens.d.ts +5 -11
  57. package/dist/runtime/subsystems/events/events.tokens.js +5 -1
  58. package/dist/runtime/subsystems/events/events.tokens.js.map +1 -1
  59. package/dist/runtime/subsystems/events/generated/bus.js +5 -0
  60. package/dist/runtime/subsystems/events/generated/bus.js.map +1 -1
  61. package/dist/runtime/subsystems/events/generated/index.js +5 -0
  62. package/dist/runtime/subsystems/events/generated/index.js.map +1 -1
  63. package/dist/runtime/subsystems/events/index.js +5 -1
  64. package/dist/runtime/subsystems/events/index.js.map +1 -1
  65. package/dist/runtime/subsystems/index.d.ts +2 -2
  66. package/dist/runtime/subsystems/index.js +25 -20
  67. package/dist/runtime/subsystems/index.js.map +1 -1
  68. package/dist/runtime/subsystems/jobs/bullmq.config.d.ts +0 -9
  69. package/dist/runtime/subsystems/jobs/bullmq.config.js +6 -2
  70. package/dist/runtime/subsystems/jobs/bullmq.config.js.map +1 -1
  71. package/dist/runtime/subsystems/jobs/index.d.ts +1 -1
  72. package/dist/runtime/subsystems/jobs/index.js +13 -9
  73. package/dist/runtime/subsystems/jobs/index.js.map +1 -1
  74. package/dist/runtime/subsystems/jobs/job-handler.base.d.ts +1 -1
  75. package/dist/runtime/subsystems/jobs/job-handler.base.js +5 -1
  76. package/dist/runtime/subsystems/jobs/job-handler.base.js.map +1 -1
  77. package/dist/runtime/subsystems/jobs/job-orchestrator.bullmq-backend.d.ts +1 -1
  78. package/dist/runtime/subsystems/jobs/job-orchestrator.bullmq-backend.js +10 -3
  79. package/dist/runtime/subsystems/jobs/job-orchestrator.bullmq-backend.js.map +1 -1
  80. package/dist/runtime/subsystems/jobs/job-orchestrator.drizzle-backend.d.ts +1 -1
  81. package/dist/runtime/subsystems/jobs/job-orchestrator.drizzle-backend.js +8 -1
  82. package/dist/runtime/subsystems/jobs/job-orchestrator.drizzle-backend.js.map +1 -1
  83. package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.d.ts +1 -1
  84. package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.js +9 -1
  85. package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.js.map +1 -1
  86. package/dist/runtime/subsystems/jobs/job-orchestrator.protocol.d.ts +1 -1
  87. package/dist/runtime/subsystems/jobs/job-run-keyset-cursor.d.ts +1 -1
  88. package/dist/runtime/subsystems/jobs/job-run-service.drizzle-backend.d.ts +1 -1
  89. package/dist/runtime/subsystems/jobs/job-run-service.drizzle-backend.js +8 -2
  90. package/dist/runtime/subsystems/jobs/job-run-service.drizzle-backend.js.map +1 -1
  91. package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.d.ts +1 -1
  92. package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.js +8 -2
  93. package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.js.map +1 -1
  94. package/dist/runtime/subsystems/jobs/job-run-service.protocol.d.ts +1 -1
  95. package/dist/runtime/subsystems/jobs/job-worker.bullmq-backend.d.ts +1 -1
  96. package/dist/runtime/subsystems/jobs/job-worker.bullmq-backend.js +5 -0
  97. package/dist/runtime/subsystems/jobs/job-worker.bullmq-backend.js.map +1 -1
  98. package/dist/runtime/subsystems/jobs/job-worker.d.ts +1 -1
  99. package/dist/runtime/subsystems/jobs/job-worker.js +10 -4
  100. package/dist/runtime/subsystems/jobs/job-worker.js.map +1 -1
  101. package/dist/runtime/subsystems/jobs/job-worker.module.d.ts +5 -2
  102. package/dist/runtime/subsystems/jobs/job-worker.module.js +13 -8
  103. package/dist/runtime/subsystems/jobs/job-worker.module.js.map +1 -1
  104. package/dist/runtime/subsystems/jobs/jobs-domain.module.js +11 -6
  105. package/dist/runtime/subsystems/jobs/jobs-domain.module.js.map +1 -1
  106. package/dist/runtime/subsystems/jobs/jobs-domain.tokens.d.ts +0 -11
  107. package/dist/runtime/subsystems/jobs/jobs-domain.tokens.js +8 -4
  108. package/dist/runtime/subsystems/jobs/jobs-domain.tokens.js.map +1 -1
  109. package/dist/runtime/subsystems/jobs/jobs-errors.d.ts +1 -1
  110. package/dist/runtime/subsystems/observability/index.d.ts +1 -1
  111. package/dist/runtime/subsystems/observability/index.js +9 -1
  112. package/dist/runtime/subsystems/observability/index.js.map +1 -1
  113. package/dist/runtime/subsystems/observability/observability.module.js +9 -1
  114. package/dist/runtime/subsystems/observability/observability.module.js.map +1 -1
  115. package/dist/runtime/subsystems/observability/observability.protocol.d.ts +1 -1
  116. package/dist/runtime/subsystems/observability/observability.service.d.ts +1 -1
  117. package/dist/runtime/subsystems/observability/observability.service.js +9 -1
  118. package/dist/runtime/subsystems/observability/observability.service.js.map +1 -1
  119. package/dist/runtime/subsystems/observability/reporters/bridge-metrics.reporter.d.ts +1 -1
  120. package/dist/runtime/subsystems/observability/reporters/index.d.ts +1 -1
  121. package/dist/runtime/subsystems/storage/index.js +5 -1
  122. package/dist/runtime/subsystems/storage/index.js.map +1 -1
  123. package/dist/runtime/subsystems/storage/storage.module.js +5 -1
  124. package/dist/runtime/subsystems/storage/storage.module.js.map +1 -1
  125. package/dist/runtime/subsystems/storage/storage.tokens.d.ts +0 -8
  126. package/dist/runtime/subsystems/storage/storage.tokens.js +5 -1
  127. package/dist/runtime/subsystems/storage/storage.tokens.js.map +1 -1
  128. package/dist/runtime/subsystems/token-key.d.ts +7 -0
  129. package/dist/runtime/subsystems/token-key.js +8 -0
  130. package/dist/runtime/subsystems/token-key.js.map +1 -0
  131. package/dist/src/cli/index.js +349 -233
  132. package/dist/src/cli/index.js.map +1 -1
  133. package/package.json +5 -1
  134. package/runtime/subsystems/analytics/analytics.tokens.ts +6 -2
  135. package/runtime/subsystems/auth/auth.tokens.ts +15 -8
  136. package/runtime/subsystems/cache/cache.tokens.ts +7 -2
  137. package/runtime/subsystems/events/events.tokens.ts +8 -1
  138. package/runtime/subsystems/index.ts +5 -1
  139. package/runtime/subsystems/jobs/bullmq.config.ts +5 -2
  140. package/runtime/subsystems/jobs/job-handler.base.ts +6 -1
  141. package/runtime/subsystems/jobs/job-worker.module.ts +5 -1
  142. package/runtime/subsystems/jobs/job-worker.ts +4 -1
  143. package/runtime/subsystems/jobs/jobs-domain.tokens.ts +10 -7
  144. package/runtime/subsystems/storage/storage.tokens.ts +6 -1
  145. package/runtime/subsystems/token-key.ts +7 -0
  146. package/src/config/runtime-mode.mjs +82 -0
  147. package/templates/entity/new/backend/modules/core/integration-source.ejs.t +3 -2
  148. package/templates/entity/new/clean-lite-ps/controller.ejs.t +1 -1
  149. package/templates/entity/new/clean-lite-ps/module.ejs.t +1 -1
  150. package/templates/entity/new/clean-lite-ps/prompt-extension.js +8 -2
  151. package/templates/entity/new/clean-lite-ps/repository.ejs.t +4 -4
  152. package/templates/entity/new/clean-lite-ps/service.ejs.t +4 -4
  153. package/templates/entity/new/prompt.js +49 -10
@@ -20,15 +20,19 @@ var OAuthStateError = class extends Error {
20
20
  reason;
21
21
  };
22
22
 
23
+ // runtime/subsystems/token-key.ts
24
+ var PKG = "@pattern-stack/codegen";
25
+ var tokenKey = (area, name) => `${PKG}.${area}.${name}`;
26
+
23
27
  // runtime/subsystems/auth/auth.tokens.ts
24
- var ENCRYPTION_KEY = /* @__PURE__ */ Symbol("ENCRYPTION_KEY");
25
- var OAUTH_STATE_STORE = /* @__PURE__ */ Symbol("OAUTH_STATE_STORE");
26
- var AUTH_CONNECTION_READER = /* @__PURE__ */ Symbol("AUTH_CONNECTION_READER");
27
- var AUTH_CONNECTION_TOKEN_WRITER = /* @__PURE__ */ Symbol("AUTH_CONNECTION_TOKEN_WRITER");
28
- var AUTH_CONNECTION_GRANT_SINK = /* @__PURE__ */ Symbol("AUTH_CONNECTION_GRANT_SINK");
29
- var AUTH_USER_CONTEXT = /* @__PURE__ */ Symbol("AUTH_USER_CONTEXT");
30
- var STRATEGY_REGISTRY = /* @__PURE__ */ Symbol("STRATEGY_REGISTRY");
31
- var AUTH_OPTIONS = /* @__PURE__ */ Symbol("AUTH_OPTIONS");
28
+ var ENCRYPTION_KEY = Symbol.for(tokenKey("auth", "encryption-key"));
29
+ var OAUTH_STATE_STORE = Symbol.for(tokenKey("auth", "oauth-state-store"));
30
+ var AUTH_CONNECTION_READER = Symbol.for(tokenKey("auth", "connection-reader"));
31
+ var AUTH_CONNECTION_TOKEN_WRITER = Symbol.for(tokenKey("auth", "connection-token-writer"));
32
+ var AUTH_CONNECTION_GRANT_SINK = Symbol.for(tokenKey("auth", "connection-grant-sink"));
33
+ var AUTH_USER_CONTEXT = Symbol.for(tokenKey("auth", "user-context"));
34
+ var STRATEGY_REGISTRY = Symbol.for(tokenKey("auth", "strategy-registry"));
35
+ var AUTH_OPTIONS = Symbol.for(tokenKey("auth", "options"));
32
36
 
33
37
  // runtime/subsystems/auth/runtime/connection-broken.error.ts
34
38
  var ConnectionBrokenError = class extends Error {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../runtime/subsystems/auth/protocols/oauth-state-store.ts","../../../../runtime/subsystems/auth/auth.tokens.ts","../../../../runtime/subsystems/auth/runtime/connection-broken.error.ts","../../../../runtime/subsystems/auth/runtime/oauth2-refresh.strategy.ts","../../../../runtime/subsystems/auth/runtime/session-expired.error.ts","../../../../runtime/subsystems/auth/runtime/with-auth-retry.ts","../../../../runtime/subsystems/auth/auth-oauth-state.schema.ts","../../../../runtime/subsystems/auth/backends/encryption-key/env.ts","../../../../runtime/subsystems/auth/backends/state-store.memory-backend.ts","../../../../runtime/subsystems/auth/backends/state-store.drizzle-backend.ts","../../../../runtime/subsystems/auth/controllers/auth.controller.ts","../../../../runtime/base-classes/tenant-context.ts","../../../../runtime/subsystems/auth/middleware/requester-context.ts","../../../../runtime/subsystems/auth/auth.module.ts","../../../../runtime/constants/tokens.ts"],"sourcesContent":["/**\n * Auth subsystem — `IOAuthStateStore` port.\n *\n * CSRF protection for the OAuth2 authorize-code callback. Generic across\n * providers. The store mints opaque state tokens at /connect time and\n * single-use consumes them at /callback time, returning the original\n * record (userId + optional post-callback redirect path).\n *\n * Concrete backends live under `../backends/`:\n * - `state-store.memory-backend.ts` — in-process Map (tests/dev).\n * - `state-store.drizzle-backend.ts` — Postgres (prod).\n *\n * Semantics:\n * - `generate(record)` → returns an opaque state token; record is stored\n * under that token until consumed or until TTL expires.\n * - `consume(state)` → atomically deletes the entry and returns the\n * record. Throws on missing, expired, or replayed state. Never returns\n * null — a missing/expired state is a CSRF signal.\n */\nexport interface OAuthStateRecord {\n userId: string;\n /** Optional post-callback redirect path (relative URL). */\n redirect?: string;\n}\n\nexport interface IOAuthStateStore {\n /** Mint an opaque state token bound to `record`. Single-use. */\n generate(record: OAuthStateRecord): Promise<string>;\n /**\n * Atomically consume `state`, returning the bound record. Throws on\n * missing / expired / replayed state.\n */\n consume(state: string): Promise<OAuthStateRecord>;\n}\n\n/**\n * Thrown by `IOAuthStateStore.consume` when the state token is unknown,\n * expired, or has already been consumed (replay attempt).\n */\nexport class OAuthStateError extends Error {\n constructor(\n message: string,\n public readonly reason: 'missing' | 'expired',\n ) {\n super(message);\n this.name = 'OAuthStateError';\n }\n}\n","/**\n * Auth subsystem — injection tokens.\n *\n * Following ADR-008 guidance: `Symbol()` tokens for type safety and collision\n * avoidance. Consumers inject these via `@Inject(...)` against the matching\n * protocol interface.\n *\n * Usage:\n * ```typescript\n * constructor(\n * @Inject(ENCRYPTION_KEY) private readonly key: IEncryptionKey,\n * @Inject(OAUTH_STATE_STORE) private readonly states: IOAuthStateStore,\n * @Inject(AUTH_CONNECTION_READER) private readonly reader: IConnectionReader,\n * @Inject(AUTH_CONNECTION_TOKEN_WRITER) private readonly writer: IConnectionTokenWriter,\n * @Inject(AUTH_CONNECTION_GRANT_SINK) private readonly grants: IConnectionGrantSink,\n * @Inject(AUTH_USER_CONTEXT) private readonly userCtx: IUserContext,\n * @Inject(STRATEGY_REGISTRY) private readonly registry: ProviderStrategyRegistry,\n * ) {}\n * ```\n *\n * `IAuthStrategy` implementations are provider-specific and registered under\n * provider-specific tokens (e.g. `SALESFORCE_AUTH_STRATEGY`,\n * `HUBSPOT_AUTH_STRATEGY`) by each connection module — this subsystem does\n * not mandate a single `AUTH_STRATEGY` token because an app typically has\n * many concurrent strategies, one per provider. They are dispatched through\n * `STRATEGY_REGISTRY` (a `ReadonlyMap<slug, IProviderStrategy>`), populated\n * by per-provider modules via a `useFactory` provider.\n */\nexport const ENCRYPTION_KEY = Symbol('ENCRYPTION_KEY');\nexport const OAUTH_STATE_STORE = Symbol('OAUTH_STATE_STORE');\nexport const AUTH_CONNECTION_READER = Symbol('AUTH_CONNECTION_READER');\nexport const AUTH_CONNECTION_TOKEN_WRITER = Symbol('AUTH_CONNECTION_TOKEN_WRITER');\nexport const AUTH_CONNECTION_GRANT_SINK = Symbol('AUTH_CONNECTION_GRANT_SINK');\nexport const AUTH_USER_CONTEXT = Symbol('AUTH_USER_CONTEXT');\nexport const STRATEGY_REGISTRY = Symbol('STRATEGY_REGISTRY');\n/**\n * Holds the resolved `AuthModuleOptions` (used by `AuthController` to read\n * `redirectUriBase` for building per-provider callback URIs).\n */\nexport const AUTH_OPTIONS = Symbol('AUTH_OPTIONS');\n","/**\n * Thrown when an OAuth2 provider returns `400 invalid_grant`/`invalid_token`\n * on refresh — the refresh token itself is dead (user revoked, org\n * deactivated, token expired beyond the provider's rotation window). The\n * connection should be marked broken so background sync stops picking it\n * up; the user re-initiates OAuth.\n *\n * Shared across every OAuth2 strategy.\n */\nexport class ConnectionBrokenError extends Error {\n constructor(\n readonly connectionId: string,\n readonly errorCode: string,\n readonly errorDescription: string,\n ) {\n super(\n `Connection ${connectionId} broken: ${errorCode} - ${errorDescription}`,\n );\n this.name = 'ConnectionBrokenError';\n }\n}\n","/**\n * Abstract base class for OAuth2 refresh-token strategies.\n *\n * Template-method pattern: `resolve()` is concrete; four small hooks inject\n * provider specifics. Validated across two providers (Salesforce, HubSpot)\n * in the extraction-source app before being extracted here — see\n * `docs/gate-1-auth-extraction-findings.md` for the \"build first, extract\n * later\" evidence.\n *\n * Subclass contract:\n * - `provider` — slug matched against `connections.provider`\n * - `defaultExpiresInSec` — fallback when refresh response omits `expires_in`\n * - `tokenEndpoint()` — URL to POST the refresh grant\n * - `refreshBodyExtras()` — provider-specific body params\n * - `parseRefreshResponse()` — raw JSON → ParsedRefreshResponse\n * - `buildCredentials()` — stored or freshly-refreshed access token +\n * connection + optional raw refresh response\n * → provider credentials\n *\n * Base handles: expiry check w/ 5-min safety window, `forceRefresh` escape\n * hatch, POST form-urlencoded body, OAuth2 error mapping to\n * `ConnectionBrokenError`, refresh-token rotation persistence, fetch +\n * clock injection for tests.\n */\nimport type {\n AuthCredentials,\n AuthResolveOptions,\n IAuthStrategy,\n} from '../protocols/auth-strategy';\nimport type {\n DecryptedConnection,\n IConnectionReader,\n IConnectionTokenWriter,\n} from '../protocols/connection-store';\nimport { ConnectionBrokenError } from './connection-broken.error';\n\nexport type FetchLike = (\n input: string | URL | Request,\n init?: RequestInit,\n) => Promise<Response>;\n\n/** Safety window before expiry that triggers a refresh. */\nconst REFRESH_SAFETY_MS = 5 * 60 * 1000;\n\nexport interface OAuth2RefreshStrategyOptions {\n connectionReader: IConnectionReader;\n tokenWriter: IConnectionTokenWriter;\n /** Injectable fetch for tests. Defaults to the global `fetch`. */\n fetch?: FetchLike;\n /** Injectable clock for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\nexport interface ParsedRefreshResponse {\n accessToken: string;\n /**\n * New refresh token if the provider rotated it (HubSpot: always, Salesforce:\n * sometimes). Omit when the provider reused the old refresh token.\n */\n refreshToken?: string;\n /** Seconds from now. If omitted, subclass `defaultExpiresInSec` applies. */\n expiresInSec?: number;\n}\n\nexport abstract class OAuth2RefreshStrategy implements IAuthStrategy {\n protected abstract readonly provider: string;\n protected abstract readonly defaultExpiresInSec: number;\n\n protected readonly connectionReader: IConnectionReader;\n protected readonly tokenWriter: IConnectionTokenWriter;\n protected readonly fetchImpl: FetchLike;\n protected readonly now: () => number;\n\n constructor(opts: OAuth2RefreshStrategyOptions) {\n this.connectionReader = opts.connectionReader;\n this.tokenWriter = opts.tokenWriter;\n this.fetchImpl = opts.fetch ?? fetch;\n this.now = opts.now ?? Date.now;\n }\n\n async resolve(\n connectionId: string,\n opts: AuthResolveOptions = {},\n ): Promise<AuthCredentials> {\n const connection =\n await this.connectionReader.findByIdDecrypted(connectionId);\n if (!connection) {\n throw new Error(`Connection ${connectionId} not found`);\n }\n if (connection.provider !== this.provider) {\n throw new Error(\n `${this.constructor.name} called for non-${this.provider} connection ${connectionId} (provider=${connection.provider})`,\n );\n }\n\n const needsRefresh =\n opts.forceRefresh ||\n this.isExpiring(connection.expiresAt) ||\n !connection.accessToken;\n\n if (!needsRefresh) {\n return this.buildCredentials(connection.accessToken, connection);\n }\n\n if (!connection.refreshToken) {\n throw new ConnectionBrokenError(\n connectionId,\n 'no_refresh_token',\n 'Connection has no refresh token; user must reconnect',\n );\n }\n\n const { parsed, raw } = await this.executeRefresh(\n connectionId,\n connection.refreshToken,\n );\n const newExpiresAt = new Date(\n this.now() + (parsed.expiresInSec ?? this.defaultExpiresInSec) * 1000,\n );\n await this.tokenWriter.persistRefresh({\n connectionId,\n accessToken: parsed.accessToken,\n refreshToken: parsed.refreshToken ?? undefined,\n expiresAt: newExpiresAt,\n });\n\n return this.buildCredentials(parsed.accessToken, connection, raw);\n }\n\n protected abstract tokenEndpoint(): string;\n protected abstract refreshBodyExtras(): Record<string, string>;\n protected abstract parseRefreshResponse(raw: unknown): ParsedRefreshResponse;\n protected abstract buildCredentials(\n accessToken: string,\n connection: DecryptedConnection,\n refreshRaw?: unknown,\n ): AuthCredentials;\n\n private async executeRefresh(\n connectionId: string,\n refreshToken: string,\n ): Promise<{ parsed: ParsedRefreshResponse; raw: unknown }> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n ...this.refreshBodyExtras(),\n });\n const response = await this.fetchImpl(this.tokenEndpoint(), {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n if (!response.ok) {\n const err = (await safeJson(response)) as Partial<{\n error: string;\n error_description: string;\n message: string;\n }>;\n if (\n response.status === 400 &&\n (err.error === 'invalid_grant' || err.error === 'invalid_token')\n ) {\n throw new ConnectionBrokenError(\n connectionId,\n err.error ?? 'invalid_grant',\n err.error_description ?? err.message ?? 'refresh token rejected',\n );\n }\n throw new Error(\n `${this.provider} token refresh failed: ${response.status} ${err.error ?? ''} ${err.error_description ?? err.message ?? ''}`.trim(),\n );\n }\n const raw = await response.json();\n return { parsed: this.parseRefreshResponse(raw), raw };\n }\n\n private isExpiring(expiresAt: Date | null): boolean {\n if (!expiresAt) return true;\n return expiresAt.getTime() - this.now() < REFRESH_SAFETY_MS;\n }\n}\n\nasync function safeJson(response: Response): Promise<unknown> {\n try {\n return await response.clone().json();\n } catch {\n return {};\n }\n}\n","/**\n * Provider-agnostic marker for \"the access token was rejected; a forced\n * refresh may recover.\"\n *\n * Concrete provider error classes (e.g. SalesforceSessionExpiredError,\n * HubSpotUnauthorizedError) either extend `SessionExpiredError` directly or\n * set `isSessionExpired === true` on their instances. `withAuthRetry` uses\n * the `isSessionExpiredError` predicate to decide whether to force-refresh\n * and retry once.\n *\n * This discriminator replaces the SFDC-only `instanceof` check from the\n * extraction-source app's original `withAuthRetry`. See\n * `docs/gate-1-auth-extraction-findings.md` (recommendation 4).\n */\nexport class SessionExpiredError extends Error {\n /** Duck-type marker — works across package boundaries where `instanceof` fails. */\n readonly isSessionExpired = true as const;\n\n constructor(message = 'Access token rejected by provider') {\n super(message);\n this.name = 'SessionExpiredError';\n }\n}\n\n/**\n * Predicate used by `withAuthRetry` by default.\n *\n * Matches any error that either `instanceof SessionExpiredError` or carries\n * the `isSessionExpired === true` marker property. Provider adapters that\n * want their existing error classes to participate can simply add the\n * marker property without touching the class hierarchy.\n */\nexport function isSessionExpiredError(err: unknown): boolean {\n if (err instanceof SessionExpiredError) return true;\n if (err !== null && typeof err === 'object' && 'isSessionExpired' in err) {\n return (err as { isSessionExpired?: unknown }).isSessionExpired === true;\n }\n return false;\n}\n","/**\n * Run `op` with auth-aware retry-once on session-expired errors.\n *\n * Pattern: resolve creds → run op → if `isSessionExpired(e)` → resolve with\n * `forceRefresh: true` → retry → propagate. A second session-expired error\n * on the refreshed token propagates rather than looping, so transient\n * adapter bugs can't hang the caller.\n *\n * Generalisation over the extraction source's SFDC-specific original: the\n * session-expired classifier is injected. Providers mark their session-\n * expired errors (via `instanceof` of a marker class, or by setting a known\n * property) and pass a classifier matching that shape.\n *\n * Default classifier recognises the marker interface `SessionExpiredError`\n * shipped in `session-expired.error.ts` — concrete provider errors that\n * extend it (or set `isSessionExpired === true`) get retried without any\n * further wiring.\n */\nimport type {\n AuthCredentials,\n IAuthStrategy,\n} from '../protocols/auth-strategy';\nimport { isSessionExpiredError } from './session-expired.error';\n\nexport interface WithAuthRetryOptions {\n /**\n * Classifier that decides whether a thrown error is a session-expired\n * signal worth retrying once with a fresh token. Defaults to the marker-\n * interface check in `session-expired.error.ts`.\n */\n isSessionExpired?: (err: unknown) => boolean;\n}\n\nexport async function withAuthRetry<T>(\n authStrategy: IAuthStrategy,\n connectionId: string,\n op: (credentials: AuthCredentials) => Promise<T>,\n options: WithAuthRetryOptions = {},\n): Promise<T> {\n const classify = options.isSessionExpired ?? isSessionExpiredError;\n\n let creds = await authStrategy.resolve(connectionId);\n try {\n return await op(creds);\n } catch (e) {\n if (!classify(e)) throw e;\n creds = await authStrategy.resolve(connectionId, { forceRefresh: true });\n return op(creds);\n }\n}\n","/**\n * Drizzle schema for the `auth_oauth_state` table — backs the\n * `DrizzleOAuthStateStore` (`state-store.drizzle-backend.ts`).\n *\n * One row per outstanding /connect → /callback dance. Single-use; rows are\n * deleted on consume. A periodic sweep (or a `WHERE expires_at < now()`\n * filter on read) clears abandoned rows.\n *\n * Columns:\n * - `state` — opaque random token, primary key.\n * - `user_id` — text (matches the consumer-defined user-id shape;\n * the auth subsystem doesn't constrain this to UUID\n * because some apps key users by external id).\n * - `redirect` — optional post-callback redirect path.\n * - `expires_at` — TTL boundary; entries past this are treated as absent.\n *\n * Convention: schema files live at the root of the subsystem dir\n * (mirrors `cache.schema.ts`, `integration-audit.schema.ts`, `domain-events.schema.ts`).\n */\nimport { pgTable, text, timestamp } from 'drizzle-orm/pg-core';\nimport type { InferSelectModel } from 'drizzle-orm';\n\nexport const authOAuthState = pgTable('auth_oauth_state', {\n state: text('state').primaryKey(),\n userId: text('user_id').notNull(),\n redirect: text('redirect'),\n expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),\n});\n\nexport type AuthOAuthState = InferSelectModel<typeof authOAuthState>;\n","/**\n * Env-backed AES-256-GCM encryption.\n *\n * Framing: `base64( nonce(12B) || ciphertext || authTag(16B) )`. Random nonce\n * per call means two encryptions of the same plaintext produce different\n * ciphertexts — prevents replay-style inference. Auth tag enforces integrity;\n * any tampering throws on decrypt.\n *\n * Key source: `INTEGRATION_TOKEN_ENCRYPTION_KEY` env var, 32 bytes base64-encoded.\n * Generate via `openssl rand -base64 32`.\n *\n * Future backend: `kms.ts` (AWS/GCP KMS) for production deployments that\n * need key rotation + audit trails.\n */\nimport { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';\nimport type { IEncryptionKey } from '../../protocols/encryption-key';\n\nexport interface EnvEncryptionKeyOptions {\n /** Defaults to `process.env`. Tests inject a fixture. */\n env?: NodeJS.ProcessEnv;\n /** Defaults to `'INTEGRATION_TOKEN_ENCRYPTION_KEY'`. */\n envVar?: string;\n}\n\nconst ALGO = 'aes-256-gcm';\nconst NONCE_BYTES = 12;\nconst TAG_BYTES = 16;\nconst KEY_BYTES = 32;\n\nexport class EnvEncryptionKey implements IEncryptionKey {\n private readonly key: Buffer;\n\n constructor(opts: EnvEncryptionKeyOptions = {}) {\n const env = opts.env ?? process.env;\n const envVar = opts.envVar ?? 'INTEGRATION_TOKEN_ENCRYPTION_KEY';\n const raw = env[envVar];\n if (!raw) {\n throw new Error(\n `EnvEncryptionKey: ${envVar} is not set. Generate with: openssl rand -base64 32`,\n );\n }\n const decoded = Buffer.from(raw, 'base64');\n if (decoded.length !== KEY_BYTES) {\n throw new Error(\n `EnvEncryptionKey: ${envVar} must decode to ${KEY_BYTES} bytes (got ${decoded.length}). Use: openssl rand -base64 32`,\n );\n }\n this.key = decoded;\n }\n\n async encrypt(plaintext: string): Promise<string> {\n const nonce = randomBytes(NONCE_BYTES);\n const cipher = createCipheriv(ALGO, this.key, nonce);\n const ciphertext = Buffer.concat([\n cipher.update(plaintext, 'utf8'),\n cipher.final(),\n ]);\n const authTag = cipher.getAuthTag();\n return Buffer.concat([nonce, ciphertext, authTag]).toString('base64');\n }\n\n async decrypt(ciphertext: string): Promise<string> {\n const buf = Buffer.from(ciphertext, 'base64');\n if (buf.length < NONCE_BYTES + TAG_BYTES) {\n throw new Error('EnvEncryptionKey: ciphertext too short');\n }\n const nonce = buf.subarray(0, NONCE_BYTES);\n const authTag = buf.subarray(buf.length - TAG_BYTES);\n const body = buf.subarray(NONCE_BYTES, buf.length - TAG_BYTES);\n\n const decipher = createDecipheriv(ALGO, this.key, nonce);\n decipher.setAuthTag(authTag);\n const plain = Buffer.concat([decipher.update(body), decipher.final()]);\n return plain.toString('utf8');\n }\n}\n","/**\n * In-memory `IOAuthStateStore` backend.\n *\n * Single-process store — Map<state, { record, expiresAt }>. Suitable for\n * tests and single-worker dev. Production deployments select the drizzle\n * backend so state survives restarts and is shared across workers.\n *\n * Single-use semantics:\n * - `generate(record)` mints a 256-bit random token (base64url, opaque).\n * - `consume(state)` deletes the entry on read. A second call with the\n * same state throws `OAuthStateError('replay')`.\n * - Expired entries also throw (`'expired'`); the entry is deleted as a\n * side effect so a later replay still surfaces correctly.\n *\n * TTL defaults to 10 minutes — long enough for a user to complete the\n * provider's consent screen, short enough that abandoned states age out.\n */\nimport { randomBytes } from 'node:crypto';\nimport {\n type IOAuthStateStore,\n type OAuthStateRecord,\n OAuthStateError,\n} from '../protocols/oauth-state-store';\n\nexport interface MemoryOAuthStateStoreOptions {\n /** TTL in ms. Default 10 minutes. */\n ttlMs?: number;\n /** Injectable clock for tests. Default `Date.now`. */\n now?: () => number;\n /** Injectable token generator for tests. Default 32-byte base64url. */\n generateToken?: () => string;\n}\n\ninterface Slot {\n record: OAuthStateRecord;\n expiresAt: number;\n}\n\nexport class MemoryOAuthStateStore implements IOAuthStateStore {\n private readonly store = new Map<string, Slot>();\n private readonly ttlMs: number;\n private readonly now: () => number;\n private readonly generateToken: () => string;\n\n constructor(opts: MemoryOAuthStateStoreOptions = {}) {\n this.ttlMs = opts.ttlMs ?? 10 * 60 * 1000;\n this.now = opts.now ?? (() => Date.now());\n this.generateToken =\n opts.generateToken ?? (() => randomBytes(32).toString('base64url'));\n }\n\n async generate(record: OAuthStateRecord): Promise<string> {\n const state = this.generateToken();\n this.store.set(state, {\n record: { ...record },\n expiresAt: this.now() + this.ttlMs,\n });\n return state;\n }\n\n async consume(state: string): Promise<OAuthStateRecord> {\n const slot = this.store.get(state);\n if (!slot) {\n throw new OAuthStateError(\n `OAuth state token unknown or already consumed`,\n 'missing',\n );\n }\n // Delete first so a concurrent consume can't replay.\n this.store.delete(state);\n if (slot.expiresAt <= this.now()) {\n throw new OAuthStateError(`OAuth state token expired`, 'expired');\n }\n return slot.record;\n }\n}\n","/**\n * Drizzle-backed `IOAuthStateStore`.\n *\n * Uses the `auth_oauth_state` table (see `auth-oauth-state.schema.ts`).\n * Single-use semantics enforced via `DELETE ... RETURNING`: the consume\n * path atomically deletes and returns the row, so a concurrent /callback\n * with the same state cannot replay.\n *\n * Behaviour:\n * - `generate(record)` mints a 256-bit base64url token, INSERTs the row\n * with `expires_at = now() + ttlMs`.\n * - `consume(state)` runs `DELETE ... WHERE state = $1 RETURNING ...`\n * once. Throws `OAuthStateError('missing')` if no row was deleted\n * (unknown or already consumed) and `OAuthStateError('expired')` if\n * the deleted row was past its `expires_at`.\n */\nimport { randomBytes } from 'node:crypto';\nimport { eq } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../../types/drizzle';\nimport { authOAuthState } from '../auth-oauth-state.schema';\nimport {\n type IOAuthStateStore,\n type OAuthStateRecord,\n OAuthStateError,\n} from '../protocols/oauth-state-store';\n\nexport interface DrizzleOAuthStateStoreOptions {\n /** TTL in ms. Default 10 minutes. */\n ttlMs?: number;\n /** Injectable clock for tests. Default `Date.now`. */\n now?: () => number;\n /** Injectable token generator for tests. Default 32-byte base64url. */\n generateToken?: () => string;\n}\n\nexport class DrizzleOAuthStateStore implements IOAuthStateStore {\n private readonly ttlMs: number;\n private readonly now: () => number;\n private readonly generateToken: () => string;\n\n constructor(\n private readonly db: DrizzleClient,\n opts: DrizzleOAuthStateStoreOptions = {},\n ) {\n this.ttlMs = opts.ttlMs ?? 10 * 60 * 1000;\n this.now = opts.now ?? (() => Date.now());\n this.generateToken =\n opts.generateToken ?? (() => randomBytes(32).toString('base64url'));\n }\n\n async generate(record: OAuthStateRecord): Promise<string> {\n const state = this.generateToken();\n const expiresAt = new Date(this.now() + this.ttlMs);\n await this.db.insert(authOAuthState).values({\n state,\n userId: record.userId,\n redirect: record.redirect ?? null,\n expiresAt,\n });\n return state;\n }\n\n async consume(state: string): Promise<OAuthStateRecord> {\n const rows = await this.db\n .delete(authOAuthState)\n .where(eq(authOAuthState.state, state))\n .returning();\n const row = rows[0];\n if (!row) {\n throw new OAuthStateError(\n `OAuth state token unknown or already consumed`,\n 'missing',\n );\n }\n if (row.expiresAt.getTime() <= this.now()) {\n throw new OAuthStateError(`OAuth state token expired`, 'expired');\n }\n return {\n userId: row.userId,\n redirect: row.redirect ?? undefined,\n };\n }\n}\n","/**\n * AuthController — provider-agnostic OAuth2 connect/callback dance.\n *\n * Mounts two routes:\n * - `GET /auth/:provider/connect?redirect=...` — generates state, builds\n * the provider's authorize-url, 302-redirects the browser there.\n * - `GET /auth/:provider/callback?code=...&state=...` — consumes state,\n * exchanges the code for tokens, hands them to the grant sink, then\n * 302-redirects to the post-connect path.\n *\n * Hexagonal seams:\n * - `STRATEGY_REGISTRY` (ReadonlyMap<slug, IProviderStrategy>) — dispatch.\n * Concrete per-provider strategies live consumer-side and contribute\n * entries via a `useFactory` in the consumer's app module.\n * - `AUTH_USER_CONTEXT` (IUserContext) — resolves \"who is this request\"\n * from the consumer's session/JWT/etc.\n * - `OAUTH_STATE_STORE` (IOAuthStateStore) — CSRF state minting/consume.\n * - `AUTH_CONNECTION_GRANT_SINK` (IConnectionGrantSink) — persists the\n * freshly-minted grant. Adapter lives consumer-side (e.g. the\n * auth-integrations starter from #285).\n *\n * The controller never imports `ConnectionsService` or any other concrete\n * consumer type — it goes through ports only.\n */\nimport {\n Controller,\n Get,\n Inject,\n Param,\n Query,\n Req,\n Res,\n HttpException,\n HttpStatus,\n} from '@nestjs/common';\nimport {\n AUTH_CONNECTION_GRANT_SINK,\n AUTH_OPTIONS,\n AUTH_USER_CONTEXT,\n OAUTH_STATE_STORE,\n STRATEGY_REGISTRY,\n} from '../auth.tokens';\nimport type { AuthModuleOptions } from '../auth.module';\nimport type { IOAuthStateStore } from '../protocols/oauth-state-store';\nimport type { IUserContext } from '../protocols/user-context';\nimport type {\n IProviderStrategy,\n ProviderStrategyRegistry,\n} from '../protocols/provider-strategy';\nimport type { IConnectionGrantSink } from '../protocols/connection-store';\n\n/**\n * Minimal response surface used by the controller — typed loosely so we\n * don't pull a hard dep on `express` or `fastify`. Both popular HTTP\n * adapters expose `redirect(status, url)`.\n */\ninterface RedirectingResponse {\n redirect(statusCode: number, url: string): unknown;\n}\n\n@Controller('auth')\nexport class AuthController {\n constructor(\n @Inject(STRATEGY_REGISTRY)\n private readonly registry: ProviderStrategyRegistry,\n @Inject(AUTH_USER_CONTEXT)\n private readonly userContext: IUserContext,\n @Inject(OAUTH_STATE_STORE)\n private readonly stateStore: IOAuthStateStore,\n @Inject(AUTH_CONNECTION_GRANT_SINK)\n private readonly grantSink: IConnectionGrantSink,\n @Inject(AUTH_OPTIONS)\n private readonly options: AuthModuleOptions,\n ) {}\n\n @Get(':provider/connect')\n async connect(\n @Param('provider') slug: string,\n @Query('redirect') redirect: string | undefined,\n @Req() req: unknown,\n @Res() res: RedirectingResponse,\n ): Promise<unknown> {\n const strategy = this.requireStrategy(slug);\n const userId = await this.userContext.getCurrentUserId(req);\n const state = await this.stateStore.generate({ userId, redirect });\n const url = strategy.buildAuthorizeUrl({\n state,\n redirectUri: this.redirectUriFor(slug),\n });\n return res.redirect(HttpStatus.FOUND, url);\n }\n\n @Get(':provider/callback')\n async callback(\n @Param('provider') slug: string,\n @Query('code') code: string | undefined,\n @Query('state') state: string | undefined,\n @Res() res: RedirectingResponse,\n ): Promise<unknown> {\n const strategy = this.requireStrategy(slug);\n if (!code) {\n throw new HttpException(\n `Missing 'code' query param`,\n HttpStatus.BAD_REQUEST,\n );\n }\n if (!state) {\n throw new HttpException(\n `Missing 'state' query param`,\n HttpStatus.BAD_REQUEST,\n );\n }\n const { userId, redirect } = await this.stateStore.consume(state);\n const tokens = await strategy.exchangeCodeForTokens({\n code,\n redirectUri: this.redirectUriFor(slug),\n });\n await this.grantSink.createOrUpdateFromOAuthGrant({\n userId,\n provider: slug,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresAt,\n scope: tokens.scope,\n externalAccountId: tokens.externalAccountId,\n providerMetadata: tokens.providerMetadata,\n });\n return res.redirect(\n HttpStatus.FOUND,\n redirect ?? `/settings/connections?connected=${encodeURIComponent(slug)}`,\n );\n }\n\n private requireStrategy(slug: string): IProviderStrategy {\n const strategy = this.registry.get(slug);\n if (!strategy) {\n throw new HttpException(\n `Unknown provider '${slug}'`,\n HttpStatus.NOT_FOUND,\n );\n }\n return strategy;\n }\n\n private redirectUriFor(slug: string): string {\n const base = this.options.redirectUriBase;\n if (!base) {\n throw new Error(\n `AuthModule.forRoot: redirectUriBase is required when AuthController is enabled`,\n );\n }\n const trimmed = base.replace(/\\/+$/, '');\n return `${trimmed}/auth/${encodeURIComponent(slug)}/callback`;\n }\n}\n","/**\n * Ambient requester context — AsyncLocalStorage-backed tenant scope.\n *\n * The alternative to threading `userId`/`organizationId` through every\n * repository/service signature. Set ONCE at each boundary the generated app\n * owns, read implicitly inside `BaseRepository` (see `scopePredicate`).\n *\n * ## Where to set it (boundaries)\n *\n * - HTTP / tRPC handlers — from the authenticated `ctx.user`\n * - OAuth callback controllers — from the authenticated session\n * - Queue/worker `process()` — from the job's owning user after the\n * job's record is loaded\n *\n * Each boundary wraps the rest of the request in `withRequester({ userId,\n * organizationId }, () => ...)`. The context propagates through every `await`\n * to all downstream repo/service calls without being passed explicitly.\n *\n * ## Where to read it\n *\n * - `BaseRepository.scopePredicate()` reads it (via `tryGetRequester` in\n * lenient mode, `requireRequester` in strict mode) and filters every read\n * by the ambient scope when the repo declares `userTracking: true`.\n *\n * ## Why AsyncLocalStorage over an explicit parameter\n *\n * Threading `userId` (and later `organizationId`) through dozens of method\n * signatures is pure parameter pollution. Ambient context also lets a repo\n * make the \"I forgot to scope\" mistake impossible at runtime: in strict mode\n * `requireRequester()` throws when no context is active, surfacing a missing\n * boundary call loudly rather than silently leaking cross-tenant data.\n *\n * ## Not-found semantics\n *\n * When a row exists but belongs to a different requester, scoped reads return\n * `null`/`[]` — identical to \"truly doesn't exist\". No existence oracle;\n * callers throw NotFound uniformly. Standard security practice.\n *\n * ## Testing\n *\n * Tests that exercise scoped repos must wrap the call in `withRequester(...)`.\n * In strict mode an unwrapped call hitting `requireRequester()` throws — by\n * design. In lenient mode (the default) an unwrapped call is simply unscoped.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * Data-visibility scope. The auth layer decides which scope a request is\n * allowed to claim; the repo trusts whatever the ambient context says.\n *\n * - `'user'`: filter every read by `user_id = ctx.userId`. Default.\n * - `'org'`: filter every read by membership in the requester's org, resolved\n * via `user_id IN (ctx.orgUserIds)` rather than via a per-entity\n * `organization_id` column. Works for every user-owned table and keeps repos\n * single-table — the org member list is pre-resolved at the boundary.\n * - `'superuser'`: no scope filter. Engineering / internal-tools only.\n *\n * AUTHORIZATION (who is allowed to claim each scope) lives in boundary\n * middleware, not in the repo. The repo trusts the ambient context — same\n * trust model as a threaded `userId`.\n */\nexport type RequesterScope = 'user' | 'org' | 'superuser';\n\nexport interface RequesterContext {\n /**\n * The user making the request. Always present — even in `'org'` and\n * `'superuser'` scopes it is the audit-trail \"who actually did this\".\n */\n readonly userId: string;\n /**\n * The organization the requester belongs to. Required when\n * `scope === 'org'`; may be null for `'user'` (users with no org) and for\n * `'superuser'` (cross-org reads).\n */\n readonly organizationId: string | null;\n /**\n * Data-visibility scope. Defaults to `'user'` when omitted.\n */\n readonly scope?: RequesterScope;\n /**\n * For `scope === 'org'`: the list of user IDs in the requester's org,\n * pre-resolved by the boundary middleware that established the `'org'`\n * scope (one `SELECT users.id WHERE organization_id = X` at the trust\n * boundary). Repos use this as a literal `IN (...)` filter — they never\n * JOIN to `users` themselves. Required when `scope === 'org'`.\n */\n readonly orgUserIds?: readonly string[];\n}\n\nconst als = new AsyncLocalStorage<RequesterContext>();\n\n/**\n * Set the ambient requester context for the duration of `fn`. The context\n * propagates through `await` boundaries to all downstream calls. Nesting is\n * fine — an inner `withRequester` overrides the outer for its callback.\n */\nexport function withRequester<T>(\n ctx: RequesterContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return als.run(ctx, fn);\n}\n\n/**\n * Read the ambient requester context. Throws if no context is active — by\n * design. Used by repos in strict scope-enforcement mode; an unwrapped call\n * site is a missing boundary.\n */\nexport function requireRequester(): RequesterContext {\n const ctx = als.getStore();\n if (!ctx) {\n throw new Error(\n 'No requester context active. Wrap the entry point in ' +\n 'withRequester({ userId, organizationId }, fn). See tenant-context.ts.',\n );\n }\n return ctx;\n}\n\n/**\n * Read the ambient requester context without throwing. Returns `undefined`\n * when no context is active. Used by repos in lenient scope-enforcement mode\n * (the default) and by code paths that legitimately run outside a request.\n */\nexport function tryGetRequester(): RequesterContext | undefined {\n return als.getStore();\n}\n\n/**\n * Resolve the effective scope for the ambient context, defaulting to `'user'`.\n */\nexport function requireRequesterScope(): RequesterScope {\n return requireRequester().scope ?? 'user';\n}\n\n/**\n * Convenience helpers for setting scope explicitly. All three preserve\n * `userId` in the context (audit trail) regardless of scope.\n *\n * - `withUserScope`: regular end-user requests. Most call sites.\n * - `withOrgScope`: admin / org-shared resource access. The caller MUST verify\n * the requester's role permits `'org'` before calling — the helper does not\n * enforce authorization. `orgUserIds` is pre-resolved at the boundary.\n * - `withSuperuserScope`: engineering scripts / internal tools. `organizationId`\n * is null (cross-org is the point). Same authorization caveat applies.\n */\nexport function withUserScope<T>(\n userId: string,\n organizationId: string | null,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester({ userId, organizationId, scope: 'user' }, fn);\n}\n\nexport function withOrgScope<T>(\n userId: string,\n organizationId: string,\n orgUserIds: readonly string[],\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId, scope: 'org', orgUserIds },\n fn,\n );\n}\n\nexport function withSuperuserScope<T>(\n userId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId: null, scope: 'superuser' },\n fn,\n );\n}\n","/**\n * RequesterContext boundary install — bridges authentication to ambient\n * tenant scoping.\n *\n * This is the missing link that makes `BaseRepository`'s ambient scoping\n * (see `base-classes/tenant-context.ts`) actually engage on HTTP requests:\n * it reads the requester off each request (via the consumer-bound\n * `IUserContext`) and runs the rest of the request inside `withRequester(...)`,\n * so every downstream repository read/write is automatically scoped — no\n * threaded `userId`.\n *\n * ## Wiring (one line in your bootstrap)\n *\n * In `main.ts`, after `NestFactory.create`:\n *\n * ```ts\n * import { installRequesterContext } from './shared/subsystems/auth/middleware/requester-context';\n * const app = await NestFactory.create(AppModule);\n * installRequesterContext(app); // no-op + warn if AUTH_USER_CONTEXT is unbound\n * ```\n *\n * `installRequesterContext` resolves `AUTH_USER_CONTEXT` from the root DI\n * container (so it sees the binding the consumer provides in AppModule) and\n * registers a global Express middleware. Pairs with Swagger's `@ApiBearerAuth`\n * \"Authorize\" button: paste a token there and every request it sends now flows\n * through this boundary into a scoped repository call.\n *\n * ## Trust + failure model\n *\n * - The middleware TRUSTS whatever `IUserContext` returns — authentication and\n * authorization (validating the token, deciding which scope a requester may\n * claim) are the `IUserContext` implementation's job, exactly as for a\n * hand-threaded `userId`.\n * - When the requester cannot be resolved (no/invalid credentials — e.g. a\n * public route, or the OAuth callback itself), the request proceeds WITHOUT\n * an ambient context (`onUnresolved: 'unscoped'`, the default). A\n * `userTracking` repo in lenient mode then runs unscoped; in strict mode it\n * throws downstream — which is correct: unauthenticated callers must not\n * reach scoped data. Set `onUnresolved: 'reject'` to fail the request at the\n * boundary instead.\n */\nimport type { INestApplication } from '@nestjs/common';\nimport {\n withRequester,\n type RequesterContext,\n} from '../../../base-classes/tenant-context';\nimport { AUTH_USER_CONTEXT } from '../auth.tokens';\nimport type { IUserContext } from '../protocols/user-context';\n\n/** Minimal Express-style middleware signature (avoids an `express` dep). */\ntype NextFn = (err?: unknown) => void;\ntype RequestHandler = (req: unknown, res: unknown, next: NextFn) => void;\n\nexport interface RequesterContextOptions {\n /**\n * What to do when `IUserContext` cannot resolve a requester (throws, or\n * returns no `userId`).\n * - `'unscoped'` (default): proceed without a context — public routes work;\n * scoped repos run unscoped (lenient) or throw downstream (strict).\n * - `'reject'`: fail the request at the boundary (`next(error)`).\n */\n onUnresolved?: 'unscoped' | 'reject';\n}\n\n/**\n * Resolve the ambient context for a request: prefer the richer\n * `resolveRequester` (org/superuser), else derive plain `'user'` scope from\n * `getCurrentUserId`. Returns `undefined` when no requester can be determined.\n */\nexport async function resolveRequesterContext(\n userContext: IUserContext,\n req: unknown,\n): Promise<RequesterContext | undefined> {\n if (typeof userContext.resolveRequester === 'function') {\n const ctx = await userContext.resolveRequester(req);\n return ctx?.userId ? ctx : undefined;\n }\n const userId = await userContext.getCurrentUserId(req);\n return userId ? { userId, organizationId: null } : undefined;\n}\n\n/**\n * Build the global middleware. Runs the remainder of the request inside\n * `withRequester(...)` so the ambient context propagates through every `await`\n * to downstream repositories.\n */\nexport function makeRequesterContextMiddleware(\n userContext: IUserContext,\n options: RequesterContextOptions = {},\n): RequestHandler {\n const onUnresolved = options.onUnresolved ?? 'unscoped';\n return (req, _res, next) => {\n resolveRequesterContext(userContext, req).then(\n (ctx) => {\n if (!ctx) {\n next();\n return;\n }\n // als.run executes its callback synchronously; Express dispatches the\n // rest of the pipeline inside next(), so all downstream handlers (and\n // their awaits) inherit this context.\n withRequester(ctx, async () => {\n next();\n });\n },\n (err) => {\n if (onUnresolved === 'reject') {\n next(err);\n return;\n }\n next();\n },\n );\n };\n}\n\n/**\n * Register the requester-context boundary on a Nest app. Resolves\n * `AUTH_USER_CONTEXT` from the root container (so it sees the consumer's\n * AppModule binding) and installs the global middleware. No-ops with a warning\n * when `AUTH_USER_CONTEXT` is not bound, so calling it unconditionally in\n * bootstrap is safe.\n */\nexport function installRequesterContext(\n app: INestApplication,\n options: RequesterContextOptions = {},\n): void {\n const userContext = app.get<IUserContext>(AUTH_USER_CONTEXT, {\n strict: false,\n });\n if (!userContext) {\n // eslint-disable-next-line no-console\n console.warn(\n '[auth] installRequesterContext: AUTH_USER_CONTEXT is not bound — ' +\n 'request scoping NOT installed. Provide an IUserContext under ' +\n 'AUTH_USER_CONTEXT in your AppModule to enable ambient tenant scoping.',\n );\n return;\n }\n app.use(makeRequesterContextMiddleware(userContext, options));\n}\n","/**\n * AuthModule — DynamicModule factory for the auth subsystem.\n *\n * Wires the pluggable backends the subsystem ships with:\n * - `ENCRYPTION_KEY` → `EnvEncryptionKey` (AES-256-GCM from env)\n * - `OAUTH_STATE_STORE` → `MemoryOAuthStateStore` (dev/tests) or\n * `DrizzleOAuthStateStore` (prod, requires\n * DRIZZLE provider).\n * - `AUTH_OPTIONS` → resolved options bag (used by AuthController\n * for `redirectUriBase`).\n *\n * The connection-store ports (`AUTH_CONNECTION_READER`,\n * `AUTH_CONNECTION_TOKEN_WRITER`, `AUTH_CONNECTION_GRANT_SINK`),\n * `AUTH_USER_CONTEXT`, and `STRATEGY_REGISTRY` are deliberately **not**\n * wired here — they are always consumer-specific:\n * - connection-store ports adapt the consumer's `connections` storage;\n * - `IUserContext` adapts the app's session/JWT scheme;\n * - `STRATEGY_REGISTRY` is populated from the per-provider strategy\n * classes the consumer maintains.\n *\n * Consumers provide them in their app module (or by importing the\n * `auth-integrations` starter, which binds the three connection-store\n * ports off a single canonical entity).\n *\n * Usage in AppModule:\n * ```typescript\n * AuthModule.forRoot({\n * encryptionKey: 'env',\n * oauthStateStore: 'memory', // or 'drizzle'\n * enableController: true,\n * redirectUriBase: 'http://localhost:3000',\n * });\n * ```\n *\n * `global: true` means other modules don't need to re-import AuthModule to\n * inject the auth tokens.\n */\nimport { Module, type DynamicModule, type Provider } from '@nestjs/common';\nimport {\n AUTH_OPTIONS,\n ENCRYPTION_KEY,\n OAUTH_STATE_STORE,\n} from './auth.tokens';\nimport { EnvEncryptionKey } from './backends/encryption-key/env';\nimport { MemoryOAuthStateStore } from './backends/state-store.memory-backend';\nimport { DrizzleOAuthStateStore } from './backends/state-store.drizzle-backend';\nimport { AuthController } from './controllers/auth.controller';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type { DrizzleClient } from '../../types/drizzle';\n\ntype EncryptionKeyChoice =\n | 'env'\n | Omit<Provider, 'provide'>;\n\ntype OAuthStateStoreChoice =\n | 'memory'\n | 'drizzle'\n | Omit<Provider, 'provide'>;\n\nexport interface AuthModuleOptions {\n /** `'env'` (default) or a full provider definition (e.g. `{ useClass: MyKmsEncryptionKey }`). */\n encryptionKey?: EncryptionKeyChoice;\n /**\n * `'memory'` (default — tests/dev) or `'drizzle'` (prod, requires DRIZZLE\n * provider) or a full provider definition for a custom impl.\n */\n oauthStateStore?: OAuthStateStoreChoice;\n /**\n * Mount `AuthController` (`/auth/:provider/connect` + `/callback`).\n * Default `false` — apps that hand-roll connect/callback (rare) or that\n * use the subsystem only for the refresh path can opt out.\n */\n enableController?: boolean;\n /**\n * Public base URL of the API server. Used to construct per-provider\n * callback URIs as `${redirectUriBase}/auth/:provider/callback`.\n * Required when `enableController: true`.\n */\n redirectUriBase?: string;\n}\n\nfunction resolveEncryptionKeyProvider(choice: EncryptionKeyChoice): Provider {\n if (choice === 'env') {\n return { provide: ENCRYPTION_KEY, useClass: EnvEncryptionKey };\n }\n return { provide: ENCRYPTION_KEY, ...choice } as Provider;\n}\n\nfunction resolveOAuthStateStoreProvider(\n choice: OAuthStateStoreChoice,\n): Provider {\n if (choice === 'memory') {\n return { provide: OAUTH_STATE_STORE, useClass: MemoryOAuthStateStore };\n }\n if (choice === 'drizzle') {\n return {\n provide: OAUTH_STATE_STORE,\n useFactory: (db: DrizzleClient | null) => {\n if (!db) {\n throw new Error(\n \"AuthModule.forRoot: oauthStateStore: 'drizzle' selected but DRIZZLE provider is not available. \" +\n 'Ensure DatabaseModule (or another provider exposing DRIZZLE) is imported before AuthModule.forRoot.',\n );\n }\n return new DrizzleOAuthStateStore(db);\n },\n inject: [{ token: DRIZZLE, optional: true }],\n };\n }\n return { provide: OAUTH_STATE_STORE, ...choice } as Provider;\n}\n\n@Module({})\nexport class AuthModule {\n static forRoot(options: AuthModuleOptions = {}): DynamicModule {\n const resolved: AuthModuleOptions = {\n encryptionKey: options.encryptionKey ?? 'env',\n oauthStateStore: options.oauthStateStore ?? 'memory',\n enableController: options.enableController ?? false,\n redirectUriBase: options.redirectUriBase,\n };\n\n if (resolved.enableController && !resolved.redirectUriBase) {\n throw new Error(\n 'AuthModule.forRoot: redirectUriBase is required when enableController: true',\n );\n }\n\n const encryptionKeyProvider = resolveEncryptionKeyProvider(\n resolved.encryptionKey!,\n );\n const oauthStateStoreProvider = resolveOAuthStateStoreProvider(\n resolved.oauthStateStore!,\n );\n const optionsProvider: Provider = {\n provide: AUTH_OPTIONS,\n useValue: resolved,\n };\n\n return {\n module: AuthModule,\n global: true,\n providers: [encryptionKeyProvider, oauthStateStoreProvider, optionsProvider],\n controllers: resolved.enableController ? [AuthController] : [],\n exports: [ENCRYPTION_KEY, OAUTH_STATE_STORE, AUTH_OPTIONS],\n };\n }\n}\n","/**\n * NestJS injection tokens\n *\n * Used with @Inject() decorator in concrete repository constructors.\n */\n\n/**\n * Injection token for the Drizzle ORM database client.\n *\n * Usage in concrete repositories:\n * ```typescript\n * constructor(@Inject(DRIZZLE) db: DrizzleClient) { super(db); }\n * ```\n */\nexport const DRIZZLE = 'DRIZZLE' as const;\n\n/**\n * Injection token for the event bus (IEventBus).\n *\n * Optional — only resolved when EventsModule.forRoot() is registered.\n * BaseService uses this with @Optional() to emit lifecycle events\n * without requiring the events subsystem to be installed.\n *\n * Usage in services/use cases:\n * ```typescript\n * @Optional() @Inject(EVENT_BUS) eventBus?: IEventBus\n * ```\n */\nexport const EVENT_BUS = 'EVENT_BUS' as const;\n"],"mappings":";;;;;;;;;;;;;AAuCO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACgB,QAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EAJkB;AAKpB;;;ACnBO,IAAM,iBAAiB,uBAAO,gBAAgB;AAC9C,IAAM,oBAAoB,uBAAO,mBAAmB;AACpD,IAAM,yBAAyB,uBAAO,wBAAwB;AAC9D,IAAM,+BAA+B,uBAAO,8BAA8B;AAC1E,IAAM,6BAA6B,uBAAO,4BAA4B;AACtE,IAAM,oBAAoB,uBAAO,mBAAmB;AACpD,IAAM,oBAAoB,uBAAO,mBAAmB;AAKpD,IAAM,eAAe,uBAAO,cAAc;;;AC9B1C,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAC/C,YACW,cACA,WACA,kBACT;AACA;AAAA,MACE,cAAc,YAAY,YAAY,SAAS,MAAM,gBAAgB;AAAA,IACvE;AANS;AACA;AACA;AAKT,SAAK,OAAO;AAAA,EACd;AAAA,EARW;AAAA,EACA;AAAA,EACA;AAOb;;;ACsBA,IAAM,oBAAoB,IAAI,KAAK;AAsB5B,IAAe,wBAAf,MAA8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;AACA,UAAM,kBAA4B;AAAA,MAChC,SAAS;AAAA,MACT,UAAU;AAAA,IACZ;AAEA,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,WAAW,CAAC,uBAAuB,yBAAyB,eAAe;AAAA,MAC3E,aAAa,SAAS,mBAAmB,CAAC,cAAc,IAAI,CAAC;AAAA,MAC7D,SAAS,CAAC,gBAAgB,mBAAmB,YAAY;AAAA,IAC3D;AAAA,EACF;AACF;AAlCa,aAAN;AAAA,EADN,OAAO,CAAC,CAAC;AAAA,GACG;","names":["randomBytes","randomBytes","randomBytes","randomBytes"]}
1
+ {"version":3,"sources":["../../../../runtime/subsystems/auth/protocols/oauth-state-store.ts","../../../../runtime/subsystems/token-key.ts","../../../../runtime/subsystems/auth/auth.tokens.ts","../../../../runtime/subsystems/auth/runtime/connection-broken.error.ts","../../../../runtime/subsystems/auth/runtime/oauth2-refresh.strategy.ts","../../../../runtime/subsystems/auth/runtime/session-expired.error.ts","../../../../runtime/subsystems/auth/runtime/with-auth-retry.ts","../../../../runtime/subsystems/auth/auth-oauth-state.schema.ts","../../../../runtime/subsystems/auth/backends/encryption-key/env.ts","../../../../runtime/subsystems/auth/backends/state-store.memory-backend.ts","../../../../runtime/subsystems/auth/backends/state-store.drizzle-backend.ts","../../../../runtime/subsystems/auth/controllers/auth.controller.ts","../../../../runtime/base-classes/tenant-context.ts","../../../../runtime/subsystems/auth/middleware/requester-context.ts","../../../../runtime/subsystems/auth/auth.module.ts","../../../../runtime/constants/tokens.ts"],"sourcesContent":["/**\n * Auth subsystem — `IOAuthStateStore` port.\n *\n * CSRF protection for the OAuth2 authorize-code callback. Generic across\n * providers. The store mints opaque state tokens at /connect time and\n * single-use consumes them at /callback time, returning the original\n * record (userId + optional post-callback redirect path).\n *\n * Concrete backends live under `../backends/`:\n * - `state-store.memory-backend.ts` — in-process Map (tests/dev).\n * - `state-store.drizzle-backend.ts` — Postgres (prod).\n *\n * Semantics:\n * - `generate(record)` → returns an opaque state token; record is stored\n * under that token until consumed or until TTL expires.\n * - `consume(state)` → atomically deletes the entry and returns the\n * record. Throws on missing, expired, or replayed state. Never returns\n * null — a missing/expired state is a CSRF signal.\n */\nexport interface OAuthStateRecord {\n userId: string;\n /** Optional post-callback redirect path (relative URL). */\n redirect?: string;\n}\n\nexport interface IOAuthStateStore {\n /** Mint an opaque state token bound to `record`. Single-use. */\n generate(record: OAuthStateRecord): Promise<string>;\n /**\n * Atomically consume `state`, returning the bound record. Throws on\n * missing / expired / replayed state.\n */\n consume(state: string): Promise<OAuthStateRecord>;\n}\n\n/**\n * Thrown by `IOAuthStateStore.consume` when the state token is unknown,\n * expired, or has already been consumed (replay attempt).\n */\nexport class OAuthStateError extends Error {\n constructor(\n message: string,\n public readonly reason: 'missing' | 'expired',\n ) {\n super(message);\n this.name = 'OAuthStateError';\n }\n}\n","/** Canonical package namespace for cross-boundary DI token keys. MUST be a hardcoded\n * constant (NOT derived from package.json) so a vendored copy — which lives inside the\n * CONSUMER's package — produces the identical key and the two copies share the symbol. */\nexport const PKG = '@pattern-stack/codegen';\n// TODO(token-version): if/when a runtime contract version is adopted, inject it HERE only\n// (e.g. `${PKG}#${ABI}.${area}.${name}`) — this helper is the single chokepoint.\nexport const tokenKey = (area: string, name: string): string => `${PKG}.${area}.${name}`;\n","/**\n * Auth subsystem — injection tokens.\n *\n * Following ADR-008 guidance: `Symbol()` tokens for type safety and collision\n * avoidance. Consumers inject these via `@Inject(...)` against the matching\n * protocol interface.\n *\n * Usage:\n * ```typescript\n * constructor(\n * @Inject(ENCRYPTION_KEY) private readonly key: IEncryptionKey,\n * @Inject(OAUTH_STATE_STORE) private readonly states: IOAuthStateStore,\n * @Inject(AUTH_CONNECTION_READER) private readonly reader: IConnectionReader,\n * @Inject(AUTH_CONNECTION_TOKEN_WRITER) private readonly writer: IConnectionTokenWriter,\n * @Inject(AUTH_CONNECTION_GRANT_SINK) private readonly grants: IConnectionGrantSink,\n * @Inject(AUTH_USER_CONTEXT) private readonly userCtx: IUserContext,\n * @Inject(STRATEGY_REGISTRY) private readonly registry: ProviderStrategyRegistry,\n * ) {}\n * ```\n *\n * `IAuthStrategy` implementations are provider-specific and registered under\n * provider-specific tokens (e.g. `SALESFORCE_AUTH_STRATEGY`,\n * `HUBSPOT_AUTH_STRATEGY`) by each connection module — this subsystem does\n * not mandate a single `AUTH_STRATEGY` token because an app typically has\n * many concurrent strategies, one per provider. They are dispatched through\n * `STRATEGY_REGISTRY` (a `ReadonlyMap<slug, IProviderStrategy>`), populated\n * by per-provider modules via a `useFactory` provider.\n */\nimport { tokenKey } from '../token-key';\n\n// ADR-037: namespaced `Symbol.for(...)` keys so a token matches by VALUE across\n// import boundaries — the package copy and a (legacy) vendored copy resolve to\n// the SAME symbol, eliminating the dual-package DI-token identity hazard that\n// crashed boot once the emitter began emitting `STRATEGY_REGISTRY` as a runtime\n// value (RFC-0003 R5). Matches the convention surface packages already use.\nexport const ENCRYPTION_KEY = Symbol.for(tokenKey('auth', 'encryption-key'));\nexport const OAUTH_STATE_STORE = Symbol.for(tokenKey('auth', 'oauth-state-store'));\nexport const AUTH_CONNECTION_READER = Symbol.for(tokenKey('auth', 'connection-reader'));\nexport const AUTH_CONNECTION_TOKEN_WRITER = Symbol.for(tokenKey('auth', 'connection-token-writer'));\nexport const AUTH_CONNECTION_GRANT_SINK = Symbol.for(tokenKey('auth', 'connection-grant-sink'));\nexport const AUTH_USER_CONTEXT = Symbol.for(tokenKey('auth', 'user-context'));\nexport const STRATEGY_REGISTRY = Symbol.for(tokenKey('auth', 'strategy-registry'));\n/**\n * Holds the resolved `AuthModuleOptions` (used by `AuthController` to read\n * `redirectUriBase` for building per-provider callback URIs).\n */\nexport const AUTH_OPTIONS = Symbol.for(tokenKey('auth', 'options'));\n","/**\n * Thrown when an OAuth2 provider returns `400 invalid_grant`/`invalid_token`\n * on refresh — the refresh token itself is dead (user revoked, org\n * deactivated, token expired beyond the provider's rotation window). The\n * connection should be marked broken so background sync stops picking it\n * up; the user re-initiates OAuth.\n *\n * Shared across every OAuth2 strategy.\n */\nexport class ConnectionBrokenError extends Error {\n constructor(\n readonly connectionId: string,\n readonly errorCode: string,\n readonly errorDescription: string,\n ) {\n super(\n `Connection ${connectionId} broken: ${errorCode} - ${errorDescription}`,\n );\n this.name = 'ConnectionBrokenError';\n }\n}\n","/**\n * Abstract base class for OAuth2 refresh-token strategies.\n *\n * Template-method pattern: `resolve()` is concrete; four small hooks inject\n * provider specifics. Validated across two providers (Salesforce, HubSpot)\n * in the extraction-source app before being extracted here — see\n * `docs/gate-1-auth-extraction-findings.md` for the \"build first, extract\n * later\" evidence.\n *\n * Subclass contract:\n * - `provider` — slug matched against `connections.provider`\n * - `defaultExpiresInSec` — fallback when refresh response omits `expires_in`\n * - `tokenEndpoint()` — URL to POST the refresh grant\n * - `refreshBodyExtras()` — provider-specific body params\n * - `parseRefreshResponse()` — raw JSON → ParsedRefreshResponse\n * - `buildCredentials()` — stored or freshly-refreshed access token +\n * connection + optional raw refresh response\n * → provider credentials\n *\n * Base handles: expiry check w/ 5-min safety window, `forceRefresh` escape\n * hatch, POST form-urlencoded body, OAuth2 error mapping to\n * `ConnectionBrokenError`, refresh-token rotation persistence, fetch +\n * clock injection for tests.\n */\nimport type {\n AuthCredentials,\n AuthResolveOptions,\n IAuthStrategy,\n} from '../protocols/auth-strategy';\nimport type {\n DecryptedConnection,\n IConnectionReader,\n IConnectionTokenWriter,\n} from '../protocols/connection-store';\nimport { ConnectionBrokenError } from './connection-broken.error';\n\nexport type FetchLike = (\n input: string | URL | Request,\n init?: RequestInit,\n) => Promise<Response>;\n\n/** Safety window before expiry that triggers a refresh. */\nconst REFRESH_SAFETY_MS = 5 * 60 * 1000;\n\nexport interface OAuth2RefreshStrategyOptions {\n connectionReader: IConnectionReader;\n tokenWriter: IConnectionTokenWriter;\n /** Injectable fetch for tests. Defaults to the global `fetch`. */\n fetch?: FetchLike;\n /** Injectable clock for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\nexport interface ParsedRefreshResponse {\n accessToken: string;\n /**\n * New refresh token if the provider rotated it (HubSpot: always, Salesforce:\n * sometimes). Omit when the provider reused the old refresh token.\n */\n refreshToken?: string;\n /** Seconds from now. If omitted, subclass `defaultExpiresInSec` applies. */\n expiresInSec?: number;\n}\n\nexport abstract class OAuth2RefreshStrategy implements IAuthStrategy {\n protected abstract readonly provider: string;\n protected abstract readonly defaultExpiresInSec: number;\n\n protected readonly connectionReader: IConnectionReader;\n protected readonly tokenWriter: IConnectionTokenWriter;\n protected readonly fetchImpl: FetchLike;\n protected readonly now: () => number;\n\n constructor(opts: OAuth2RefreshStrategyOptions) {\n this.connectionReader = opts.connectionReader;\n this.tokenWriter = opts.tokenWriter;\n this.fetchImpl = opts.fetch ?? fetch;\n this.now = opts.now ?? Date.now;\n }\n\n async resolve(\n connectionId: string,\n opts: AuthResolveOptions = {},\n ): Promise<AuthCredentials> {\n const connection =\n await this.connectionReader.findByIdDecrypted(connectionId);\n if (!connection) {\n throw new Error(`Connection ${connectionId} not found`);\n }\n if (connection.provider !== this.provider) {\n throw new Error(\n `${this.constructor.name} called for non-${this.provider} connection ${connectionId} (provider=${connection.provider})`,\n );\n }\n\n const needsRefresh =\n opts.forceRefresh ||\n this.isExpiring(connection.expiresAt) ||\n !connection.accessToken;\n\n if (!needsRefresh) {\n return this.buildCredentials(connection.accessToken, connection);\n }\n\n if (!connection.refreshToken) {\n throw new ConnectionBrokenError(\n connectionId,\n 'no_refresh_token',\n 'Connection has no refresh token; user must reconnect',\n );\n }\n\n const { parsed, raw } = await this.executeRefresh(\n connectionId,\n connection.refreshToken,\n );\n const newExpiresAt = new Date(\n this.now() + (parsed.expiresInSec ?? this.defaultExpiresInSec) * 1000,\n );\n await this.tokenWriter.persistRefresh({\n connectionId,\n accessToken: parsed.accessToken,\n refreshToken: parsed.refreshToken ?? undefined,\n expiresAt: newExpiresAt,\n });\n\n return this.buildCredentials(parsed.accessToken, connection, raw);\n }\n\n protected abstract tokenEndpoint(): string;\n protected abstract refreshBodyExtras(): Record<string, string>;\n protected abstract parseRefreshResponse(raw: unknown): ParsedRefreshResponse;\n protected abstract buildCredentials(\n accessToken: string,\n connection: DecryptedConnection,\n refreshRaw?: unknown,\n ): AuthCredentials;\n\n private async executeRefresh(\n connectionId: string,\n refreshToken: string,\n ): Promise<{ parsed: ParsedRefreshResponse; raw: unknown }> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n ...this.refreshBodyExtras(),\n });\n const response = await this.fetchImpl(this.tokenEndpoint(), {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n if (!response.ok) {\n const err = (await safeJson(response)) as Partial<{\n error: string;\n error_description: string;\n message: string;\n }>;\n if (\n response.status === 400 &&\n (err.error === 'invalid_grant' || err.error === 'invalid_token')\n ) {\n throw new ConnectionBrokenError(\n connectionId,\n err.error ?? 'invalid_grant',\n err.error_description ?? err.message ?? 'refresh token rejected',\n );\n }\n throw new Error(\n `${this.provider} token refresh failed: ${response.status} ${err.error ?? ''} ${err.error_description ?? err.message ?? ''}`.trim(),\n );\n }\n const raw = await response.json();\n return { parsed: this.parseRefreshResponse(raw), raw };\n }\n\n private isExpiring(expiresAt: Date | null): boolean {\n if (!expiresAt) return true;\n return expiresAt.getTime() - this.now() < REFRESH_SAFETY_MS;\n }\n}\n\nasync function safeJson(response: Response): Promise<unknown> {\n try {\n return await response.clone().json();\n } catch {\n return {};\n }\n}\n","/**\n * Provider-agnostic marker for \"the access token was rejected; a forced\n * refresh may recover.\"\n *\n * Concrete provider error classes (e.g. SalesforceSessionExpiredError,\n * HubSpotUnauthorizedError) either extend `SessionExpiredError` directly or\n * set `isSessionExpired === true` on their instances. `withAuthRetry` uses\n * the `isSessionExpiredError` predicate to decide whether to force-refresh\n * and retry once.\n *\n * This discriminator replaces the SFDC-only `instanceof` check from the\n * extraction-source app's original `withAuthRetry`. See\n * `docs/gate-1-auth-extraction-findings.md` (recommendation 4).\n */\nexport class SessionExpiredError extends Error {\n /** Duck-type marker — works across package boundaries where `instanceof` fails. */\n readonly isSessionExpired = true as const;\n\n constructor(message = 'Access token rejected by provider') {\n super(message);\n this.name = 'SessionExpiredError';\n }\n}\n\n/**\n * Predicate used by `withAuthRetry` by default.\n *\n * Matches any error that either `instanceof SessionExpiredError` or carries\n * the `isSessionExpired === true` marker property. Provider adapters that\n * want their existing error classes to participate can simply add the\n * marker property without touching the class hierarchy.\n */\nexport function isSessionExpiredError(err: unknown): boolean {\n if (err instanceof SessionExpiredError) return true;\n if (err !== null && typeof err === 'object' && 'isSessionExpired' in err) {\n return (err as { isSessionExpired?: unknown }).isSessionExpired === true;\n }\n return false;\n}\n","/**\n * Run `op` with auth-aware retry-once on session-expired errors.\n *\n * Pattern: resolve creds → run op → if `isSessionExpired(e)` → resolve with\n * `forceRefresh: true` → retry → propagate. A second session-expired error\n * on the refreshed token propagates rather than looping, so transient\n * adapter bugs can't hang the caller.\n *\n * Generalisation over the extraction source's SFDC-specific original: the\n * session-expired classifier is injected. Providers mark their session-\n * expired errors (via `instanceof` of a marker class, or by setting a known\n * property) and pass a classifier matching that shape.\n *\n * Default classifier recognises the marker interface `SessionExpiredError`\n * shipped in `session-expired.error.ts` — concrete provider errors that\n * extend it (or set `isSessionExpired === true`) get retried without any\n * further wiring.\n */\nimport type {\n AuthCredentials,\n IAuthStrategy,\n} from '../protocols/auth-strategy';\nimport { isSessionExpiredError } from './session-expired.error';\n\nexport interface WithAuthRetryOptions {\n /**\n * Classifier that decides whether a thrown error is a session-expired\n * signal worth retrying once with a fresh token. Defaults to the marker-\n * interface check in `session-expired.error.ts`.\n */\n isSessionExpired?: (err: unknown) => boolean;\n}\n\nexport async function withAuthRetry<T>(\n authStrategy: IAuthStrategy,\n connectionId: string,\n op: (credentials: AuthCredentials) => Promise<T>,\n options: WithAuthRetryOptions = {},\n): Promise<T> {\n const classify = options.isSessionExpired ?? isSessionExpiredError;\n\n let creds = await authStrategy.resolve(connectionId);\n try {\n return await op(creds);\n } catch (e) {\n if (!classify(e)) throw e;\n creds = await authStrategy.resolve(connectionId, { forceRefresh: true });\n return op(creds);\n }\n}\n","/**\n * Drizzle schema for the `auth_oauth_state` table — backs the\n * `DrizzleOAuthStateStore` (`state-store.drizzle-backend.ts`).\n *\n * One row per outstanding /connect → /callback dance. Single-use; rows are\n * deleted on consume. A periodic sweep (or a `WHERE expires_at < now()`\n * filter on read) clears abandoned rows.\n *\n * Columns:\n * - `state` — opaque random token, primary key.\n * - `user_id` — text (matches the consumer-defined user-id shape;\n * the auth subsystem doesn't constrain this to UUID\n * because some apps key users by external id).\n * - `redirect` — optional post-callback redirect path.\n * - `expires_at` — TTL boundary; entries past this are treated as absent.\n *\n * Convention: schema files live at the root of the subsystem dir\n * (mirrors `cache.schema.ts`, `integration-audit.schema.ts`, `domain-events.schema.ts`).\n */\nimport { pgTable, text, timestamp } from 'drizzle-orm/pg-core';\nimport type { InferSelectModel } from 'drizzle-orm';\n\nexport const authOAuthState = pgTable('auth_oauth_state', {\n state: text('state').primaryKey(),\n userId: text('user_id').notNull(),\n redirect: text('redirect'),\n expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),\n});\n\nexport type AuthOAuthState = InferSelectModel<typeof authOAuthState>;\n","/**\n * Env-backed AES-256-GCM encryption.\n *\n * Framing: `base64( nonce(12B) || ciphertext || authTag(16B) )`. Random nonce\n * per call means two encryptions of the same plaintext produce different\n * ciphertexts — prevents replay-style inference. Auth tag enforces integrity;\n * any tampering throws on decrypt.\n *\n * Key source: `INTEGRATION_TOKEN_ENCRYPTION_KEY` env var, 32 bytes base64-encoded.\n * Generate via `openssl rand -base64 32`.\n *\n * Future backend: `kms.ts` (AWS/GCP KMS) for production deployments that\n * need key rotation + audit trails.\n */\nimport { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';\nimport type { IEncryptionKey } from '../../protocols/encryption-key';\n\nexport interface EnvEncryptionKeyOptions {\n /** Defaults to `process.env`. Tests inject a fixture. */\n env?: NodeJS.ProcessEnv;\n /** Defaults to `'INTEGRATION_TOKEN_ENCRYPTION_KEY'`. */\n envVar?: string;\n}\n\nconst ALGO = 'aes-256-gcm';\nconst NONCE_BYTES = 12;\nconst TAG_BYTES = 16;\nconst KEY_BYTES = 32;\n\nexport class EnvEncryptionKey implements IEncryptionKey {\n private readonly key: Buffer;\n\n constructor(opts: EnvEncryptionKeyOptions = {}) {\n const env = opts.env ?? process.env;\n const envVar = opts.envVar ?? 'INTEGRATION_TOKEN_ENCRYPTION_KEY';\n const raw = env[envVar];\n if (!raw) {\n throw new Error(\n `EnvEncryptionKey: ${envVar} is not set. Generate with: openssl rand -base64 32`,\n );\n }\n const decoded = Buffer.from(raw, 'base64');\n if (decoded.length !== KEY_BYTES) {\n throw new Error(\n `EnvEncryptionKey: ${envVar} must decode to ${KEY_BYTES} bytes (got ${decoded.length}). Use: openssl rand -base64 32`,\n );\n }\n this.key = decoded;\n }\n\n async encrypt(plaintext: string): Promise<string> {\n const nonce = randomBytes(NONCE_BYTES);\n const cipher = createCipheriv(ALGO, this.key, nonce);\n const ciphertext = Buffer.concat([\n cipher.update(plaintext, 'utf8'),\n cipher.final(),\n ]);\n const authTag = cipher.getAuthTag();\n return Buffer.concat([nonce, ciphertext, authTag]).toString('base64');\n }\n\n async decrypt(ciphertext: string): Promise<string> {\n const buf = Buffer.from(ciphertext, 'base64');\n if (buf.length < NONCE_BYTES + TAG_BYTES) {\n throw new Error('EnvEncryptionKey: ciphertext too short');\n }\n const nonce = buf.subarray(0, NONCE_BYTES);\n const authTag = buf.subarray(buf.length - TAG_BYTES);\n const body = buf.subarray(NONCE_BYTES, buf.length - TAG_BYTES);\n\n const decipher = createDecipheriv(ALGO, this.key, nonce);\n decipher.setAuthTag(authTag);\n const plain = Buffer.concat([decipher.update(body), decipher.final()]);\n return plain.toString('utf8');\n }\n}\n","/**\n * In-memory `IOAuthStateStore` backend.\n *\n * Single-process store — Map<state, { record, expiresAt }>. Suitable for\n * tests and single-worker dev. Production deployments select the drizzle\n * backend so state survives restarts and is shared across workers.\n *\n * Single-use semantics:\n * - `generate(record)` mints a 256-bit random token (base64url, opaque).\n * - `consume(state)` deletes the entry on read. A second call with the\n * same state throws `OAuthStateError('replay')`.\n * - Expired entries also throw (`'expired'`); the entry is deleted as a\n * side effect so a later replay still surfaces correctly.\n *\n * TTL defaults to 10 minutes — long enough for a user to complete the\n * provider's consent screen, short enough that abandoned states age out.\n */\nimport { randomBytes } from 'node:crypto';\nimport {\n type IOAuthStateStore,\n type OAuthStateRecord,\n OAuthStateError,\n} from '../protocols/oauth-state-store';\n\nexport interface MemoryOAuthStateStoreOptions {\n /** TTL in ms. Default 10 minutes. */\n ttlMs?: number;\n /** Injectable clock for tests. Default `Date.now`. */\n now?: () => number;\n /** Injectable token generator for tests. Default 32-byte base64url. */\n generateToken?: () => string;\n}\n\ninterface Slot {\n record: OAuthStateRecord;\n expiresAt: number;\n}\n\nexport class MemoryOAuthStateStore implements IOAuthStateStore {\n private readonly store = new Map<string, Slot>();\n private readonly ttlMs: number;\n private readonly now: () => number;\n private readonly generateToken: () => string;\n\n constructor(opts: MemoryOAuthStateStoreOptions = {}) {\n this.ttlMs = opts.ttlMs ?? 10 * 60 * 1000;\n this.now = opts.now ?? (() => Date.now());\n this.generateToken =\n opts.generateToken ?? (() => randomBytes(32).toString('base64url'));\n }\n\n async generate(record: OAuthStateRecord): Promise<string> {\n const state = this.generateToken();\n this.store.set(state, {\n record: { ...record },\n expiresAt: this.now() + this.ttlMs,\n });\n return state;\n }\n\n async consume(state: string): Promise<OAuthStateRecord> {\n const slot = this.store.get(state);\n if (!slot) {\n throw new OAuthStateError(\n `OAuth state token unknown or already consumed`,\n 'missing',\n );\n }\n // Delete first so a concurrent consume can't replay.\n this.store.delete(state);\n if (slot.expiresAt <= this.now()) {\n throw new OAuthStateError(`OAuth state token expired`, 'expired');\n }\n return slot.record;\n }\n}\n","/**\n * Drizzle-backed `IOAuthStateStore`.\n *\n * Uses the `auth_oauth_state` table (see `auth-oauth-state.schema.ts`).\n * Single-use semantics enforced via `DELETE ... RETURNING`: the consume\n * path atomically deletes and returns the row, so a concurrent /callback\n * with the same state cannot replay.\n *\n * Behaviour:\n * - `generate(record)` mints a 256-bit base64url token, INSERTs the row\n * with `expires_at = now() + ttlMs`.\n * - `consume(state)` runs `DELETE ... WHERE state = $1 RETURNING ...`\n * once. Throws `OAuthStateError('missing')` if no row was deleted\n * (unknown or already consumed) and `OAuthStateError('expired')` if\n * the deleted row was past its `expires_at`.\n */\nimport { randomBytes } from 'node:crypto';\nimport { eq } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../../types/drizzle';\nimport { authOAuthState } from '../auth-oauth-state.schema';\nimport {\n type IOAuthStateStore,\n type OAuthStateRecord,\n OAuthStateError,\n} from '../protocols/oauth-state-store';\n\nexport interface DrizzleOAuthStateStoreOptions {\n /** TTL in ms. Default 10 minutes. */\n ttlMs?: number;\n /** Injectable clock for tests. Default `Date.now`. */\n now?: () => number;\n /** Injectable token generator for tests. Default 32-byte base64url. */\n generateToken?: () => string;\n}\n\nexport class DrizzleOAuthStateStore implements IOAuthStateStore {\n private readonly ttlMs: number;\n private readonly now: () => number;\n private readonly generateToken: () => string;\n\n constructor(\n private readonly db: DrizzleClient,\n opts: DrizzleOAuthStateStoreOptions = {},\n ) {\n this.ttlMs = opts.ttlMs ?? 10 * 60 * 1000;\n this.now = opts.now ?? (() => Date.now());\n this.generateToken =\n opts.generateToken ?? (() => randomBytes(32).toString('base64url'));\n }\n\n async generate(record: OAuthStateRecord): Promise<string> {\n const state = this.generateToken();\n const expiresAt = new Date(this.now() + this.ttlMs);\n await this.db.insert(authOAuthState).values({\n state,\n userId: record.userId,\n redirect: record.redirect ?? null,\n expiresAt,\n });\n return state;\n }\n\n async consume(state: string): Promise<OAuthStateRecord> {\n const rows = await this.db\n .delete(authOAuthState)\n .where(eq(authOAuthState.state, state))\n .returning();\n const row = rows[0];\n if (!row) {\n throw new OAuthStateError(\n `OAuth state token unknown or already consumed`,\n 'missing',\n );\n }\n if (row.expiresAt.getTime() <= this.now()) {\n throw new OAuthStateError(`OAuth state token expired`, 'expired');\n }\n return {\n userId: row.userId,\n redirect: row.redirect ?? undefined,\n };\n }\n}\n","/**\n * AuthController — provider-agnostic OAuth2 connect/callback dance.\n *\n * Mounts two routes:\n * - `GET /auth/:provider/connect?redirect=...` — generates state, builds\n * the provider's authorize-url, 302-redirects the browser there.\n * - `GET /auth/:provider/callback?code=...&state=...` — consumes state,\n * exchanges the code for tokens, hands them to the grant sink, then\n * 302-redirects to the post-connect path.\n *\n * Hexagonal seams:\n * - `STRATEGY_REGISTRY` (ReadonlyMap<slug, IProviderStrategy>) — dispatch.\n * Concrete per-provider strategies live consumer-side and contribute\n * entries via a `useFactory` in the consumer's app module.\n * - `AUTH_USER_CONTEXT` (IUserContext) — resolves \"who is this request\"\n * from the consumer's session/JWT/etc.\n * - `OAUTH_STATE_STORE` (IOAuthStateStore) — CSRF state minting/consume.\n * - `AUTH_CONNECTION_GRANT_SINK` (IConnectionGrantSink) — persists the\n * freshly-minted grant. Adapter lives consumer-side (e.g. the\n * auth-integrations starter from #285).\n *\n * The controller never imports `ConnectionsService` or any other concrete\n * consumer type — it goes through ports only.\n */\nimport {\n Controller,\n Get,\n Inject,\n Param,\n Query,\n Req,\n Res,\n HttpException,\n HttpStatus,\n} from '@nestjs/common';\nimport {\n AUTH_CONNECTION_GRANT_SINK,\n AUTH_OPTIONS,\n AUTH_USER_CONTEXT,\n OAUTH_STATE_STORE,\n STRATEGY_REGISTRY,\n} from '../auth.tokens';\nimport type { AuthModuleOptions } from '../auth.module';\nimport type { IOAuthStateStore } from '../protocols/oauth-state-store';\nimport type { IUserContext } from '../protocols/user-context';\nimport type {\n IProviderStrategy,\n ProviderStrategyRegistry,\n} from '../protocols/provider-strategy';\nimport type { IConnectionGrantSink } from '../protocols/connection-store';\n\n/**\n * Minimal response surface used by the controller — typed loosely so we\n * don't pull a hard dep on `express` or `fastify`. Both popular HTTP\n * adapters expose `redirect(status, url)`.\n */\ninterface RedirectingResponse {\n redirect(statusCode: number, url: string): unknown;\n}\n\n@Controller('auth')\nexport class AuthController {\n constructor(\n @Inject(STRATEGY_REGISTRY)\n private readonly registry: ProviderStrategyRegistry,\n @Inject(AUTH_USER_CONTEXT)\n private readonly userContext: IUserContext,\n @Inject(OAUTH_STATE_STORE)\n private readonly stateStore: IOAuthStateStore,\n @Inject(AUTH_CONNECTION_GRANT_SINK)\n private readonly grantSink: IConnectionGrantSink,\n @Inject(AUTH_OPTIONS)\n private readonly options: AuthModuleOptions,\n ) {}\n\n @Get(':provider/connect')\n async connect(\n @Param('provider') slug: string,\n @Query('redirect') redirect: string | undefined,\n @Req() req: unknown,\n @Res() res: RedirectingResponse,\n ): Promise<unknown> {\n const strategy = this.requireStrategy(slug);\n const userId = await this.userContext.getCurrentUserId(req);\n const state = await this.stateStore.generate({ userId, redirect });\n const url = strategy.buildAuthorizeUrl({\n state,\n redirectUri: this.redirectUriFor(slug),\n });\n return res.redirect(HttpStatus.FOUND, url);\n }\n\n @Get(':provider/callback')\n async callback(\n @Param('provider') slug: string,\n @Query('code') code: string | undefined,\n @Query('state') state: string | undefined,\n @Res() res: RedirectingResponse,\n ): Promise<unknown> {\n const strategy = this.requireStrategy(slug);\n if (!code) {\n throw new HttpException(\n `Missing 'code' query param`,\n HttpStatus.BAD_REQUEST,\n );\n }\n if (!state) {\n throw new HttpException(\n `Missing 'state' query param`,\n HttpStatus.BAD_REQUEST,\n );\n }\n const { userId, redirect } = await this.stateStore.consume(state);\n const tokens = await strategy.exchangeCodeForTokens({\n code,\n redirectUri: this.redirectUriFor(slug),\n });\n await this.grantSink.createOrUpdateFromOAuthGrant({\n userId,\n provider: slug,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresAt,\n scope: tokens.scope,\n externalAccountId: tokens.externalAccountId,\n providerMetadata: tokens.providerMetadata,\n });\n return res.redirect(\n HttpStatus.FOUND,\n redirect ?? `/settings/connections?connected=${encodeURIComponent(slug)}`,\n );\n }\n\n private requireStrategy(slug: string): IProviderStrategy {\n const strategy = this.registry.get(slug);\n if (!strategy) {\n throw new HttpException(\n `Unknown provider '${slug}'`,\n HttpStatus.NOT_FOUND,\n );\n }\n return strategy;\n }\n\n private redirectUriFor(slug: string): string {\n const base = this.options.redirectUriBase;\n if (!base) {\n throw new Error(\n `AuthModule.forRoot: redirectUriBase is required when AuthController is enabled`,\n );\n }\n const trimmed = base.replace(/\\/+$/, '');\n return `${trimmed}/auth/${encodeURIComponent(slug)}/callback`;\n }\n}\n","/**\n * Ambient requester context — AsyncLocalStorage-backed tenant scope.\n *\n * The alternative to threading `userId`/`organizationId` through every\n * repository/service signature. Set ONCE at each boundary the generated app\n * owns, read implicitly inside `BaseRepository` (see `scopePredicate`).\n *\n * ## Where to set it (boundaries)\n *\n * - HTTP / tRPC handlers — from the authenticated `ctx.user`\n * - OAuth callback controllers — from the authenticated session\n * - Queue/worker `process()` — from the job's owning user after the\n * job's record is loaded\n *\n * Each boundary wraps the rest of the request in `withRequester({ userId,\n * organizationId }, () => ...)`. The context propagates through every `await`\n * to all downstream repo/service calls without being passed explicitly.\n *\n * ## Where to read it\n *\n * - `BaseRepository.scopePredicate()` reads it (via `tryGetRequester` in\n * lenient mode, `requireRequester` in strict mode) and filters every read\n * by the ambient scope when the repo declares `userTracking: true`.\n *\n * ## Why AsyncLocalStorage over an explicit parameter\n *\n * Threading `userId` (and later `organizationId`) through dozens of method\n * signatures is pure parameter pollution. Ambient context also lets a repo\n * make the \"I forgot to scope\" mistake impossible at runtime: in strict mode\n * `requireRequester()` throws when no context is active, surfacing a missing\n * boundary call loudly rather than silently leaking cross-tenant data.\n *\n * ## Not-found semantics\n *\n * When a row exists but belongs to a different requester, scoped reads return\n * `null`/`[]` — identical to \"truly doesn't exist\". No existence oracle;\n * callers throw NotFound uniformly. Standard security practice.\n *\n * ## Testing\n *\n * Tests that exercise scoped repos must wrap the call in `withRequester(...)`.\n * In strict mode an unwrapped call hitting `requireRequester()` throws — by\n * design. In lenient mode (the default) an unwrapped call is simply unscoped.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * Data-visibility scope. The auth layer decides which scope a request is\n * allowed to claim; the repo trusts whatever the ambient context says.\n *\n * - `'user'`: filter every read by `user_id = ctx.userId`. Default.\n * - `'org'`: filter every read by membership in the requester's org, resolved\n * via `user_id IN (ctx.orgUserIds)` rather than via a per-entity\n * `organization_id` column. Works for every user-owned table and keeps repos\n * single-table — the org member list is pre-resolved at the boundary.\n * - `'superuser'`: no scope filter. Engineering / internal-tools only.\n *\n * AUTHORIZATION (who is allowed to claim each scope) lives in boundary\n * middleware, not in the repo. The repo trusts the ambient context — same\n * trust model as a threaded `userId`.\n */\nexport type RequesterScope = 'user' | 'org' | 'superuser';\n\nexport interface RequesterContext {\n /**\n * The user making the request. Always present — even in `'org'` and\n * `'superuser'` scopes it is the audit-trail \"who actually did this\".\n */\n readonly userId: string;\n /**\n * The organization the requester belongs to. Required when\n * `scope === 'org'`; may be null for `'user'` (users with no org) and for\n * `'superuser'` (cross-org reads).\n */\n readonly organizationId: string | null;\n /**\n * Data-visibility scope. Defaults to `'user'` when omitted.\n */\n readonly scope?: RequesterScope;\n /**\n * For `scope === 'org'`: the list of user IDs in the requester's org,\n * pre-resolved by the boundary middleware that established the `'org'`\n * scope (one `SELECT users.id WHERE organization_id = X` at the trust\n * boundary). Repos use this as a literal `IN (...)` filter — they never\n * JOIN to `users` themselves. Required when `scope === 'org'`.\n */\n readonly orgUserIds?: readonly string[];\n}\n\nconst als = new AsyncLocalStorage<RequesterContext>();\n\n/**\n * Set the ambient requester context for the duration of `fn`. The context\n * propagates through `await` boundaries to all downstream calls. Nesting is\n * fine — an inner `withRequester` overrides the outer for its callback.\n */\nexport function withRequester<T>(\n ctx: RequesterContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return als.run(ctx, fn);\n}\n\n/**\n * Read the ambient requester context. Throws if no context is active — by\n * design. Used by repos in strict scope-enforcement mode; an unwrapped call\n * site is a missing boundary.\n */\nexport function requireRequester(): RequesterContext {\n const ctx = als.getStore();\n if (!ctx) {\n throw new Error(\n 'No requester context active. Wrap the entry point in ' +\n 'withRequester({ userId, organizationId }, fn). See tenant-context.ts.',\n );\n }\n return ctx;\n}\n\n/**\n * Read the ambient requester context without throwing. Returns `undefined`\n * when no context is active. Used by repos in lenient scope-enforcement mode\n * (the default) and by code paths that legitimately run outside a request.\n */\nexport function tryGetRequester(): RequesterContext | undefined {\n return als.getStore();\n}\n\n/**\n * Resolve the effective scope for the ambient context, defaulting to `'user'`.\n */\nexport function requireRequesterScope(): RequesterScope {\n return requireRequester().scope ?? 'user';\n}\n\n/**\n * Convenience helpers for setting scope explicitly. All three preserve\n * `userId` in the context (audit trail) regardless of scope.\n *\n * - `withUserScope`: regular end-user requests. Most call sites.\n * - `withOrgScope`: admin / org-shared resource access. The caller MUST verify\n * the requester's role permits `'org'` before calling — the helper does not\n * enforce authorization. `orgUserIds` is pre-resolved at the boundary.\n * - `withSuperuserScope`: engineering scripts / internal tools. `organizationId`\n * is null (cross-org is the point). Same authorization caveat applies.\n */\nexport function withUserScope<T>(\n userId: string,\n organizationId: string | null,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester({ userId, organizationId, scope: 'user' }, fn);\n}\n\nexport function withOrgScope<T>(\n userId: string,\n organizationId: string,\n orgUserIds: readonly string[],\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId, scope: 'org', orgUserIds },\n fn,\n );\n}\n\nexport function withSuperuserScope<T>(\n userId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId: null, scope: 'superuser' },\n fn,\n );\n}\n","/**\n * RequesterContext boundary install — bridges authentication to ambient\n * tenant scoping.\n *\n * This is the missing link that makes `BaseRepository`'s ambient scoping\n * (see `base-classes/tenant-context.ts`) actually engage on HTTP requests:\n * it reads the requester off each request (via the consumer-bound\n * `IUserContext`) and runs the rest of the request inside `withRequester(...)`,\n * so every downstream repository read/write is automatically scoped — no\n * threaded `userId`.\n *\n * ## Wiring (one line in your bootstrap)\n *\n * In `main.ts`, after `NestFactory.create`:\n *\n * ```ts\n * import { installRequesterContext } from './shared/subsystems/auth/middleware/requester-context';\n * const app = await NestFactory.create(AppModule);\n * installRequesterContext(app); // no-op + warn if AUTH_USER_CONTEXT is unbound\n * ```\n *\n * `installRequesterContext` resolves `AUTH_USER_CONTEXT` from the root DI\n * container (so it sees the binding the consumer provides in AppModule) and\n * registers a global Express middleware. Pairs with Swagger's `@ApiBearerAuth`\n * \"Authorize\" button: paste a token there and every request it sends now flows\n * through this boundary into a scoped repository call.\n *\n * ## Trust + failure model\n *\n * - The middleware TRUSTS whatever `IUserContext` returns — authentication and\n * authorization (validating the token, deciding which scope a requester may\n * claim) are the `IUserContext` implementation's job, exactly as for a\n * hand-threaded `userId`.\n * - When the requester cannot be resolved (no/invalid credentials — e.g. a\n * public route, or the OAuth callback itself), the request proceeds WITHOUT\n * an ambient context (`onUnresolved: 'unscoped'`, the default). A\n * `userTracking` repo in lenient mode then runs unscoped; in strict mode it\n * throws downstream — which is correct: unauthenticated callers must not\n * reach scoped data. Set `onUnresolved: 'reject'` to fail the request at the\n * boundary instead.\n */\nimport type { INestApplication } from '@nestjs/common';\nimport {\n withRequester,\n type RequesterContext,\n} from '../../../base-classes/tenant-context';\nimport { AUTH_USER_CONTEXT } from '../auth.tokens';\nimport type { IUserContext } from '../protocols/user-context';\n\n/** Minimal Express-style middleware signature (avoids an `express` dep). */\ntype NextFn = (err?: unknown) => void;\ntype RequestHandler = (req: unknown, res: unknown, next: NextFn) => void;\n\nexport interface RequesterContextOptions {\n /**\n * What to do when `IUserContext` cannot resolve a requester (throws, or\n * returns no `userId`).\n * - `'unscoped'` (default): proceed without a context — public routes work;\n * scoped repos run unscoped (lenient) or throw downstream (strict).\n * - `'reject'`: fail the request at the boundary (`next(error)`).\n */\n onUnresolved?: 'unscoped' | 'reject';\n}\n\n/**\n * Resolve the ambient context for a request: prefer the richer\n * `resolveRequester` (org/superuser), else derive plain `'user'` scope from\n * `getCurrentUserId`. Returns `undefined` when no requester can be determined.\n */\nexport async function resolveRequesterContext(\n userContext: IUserContext,\n req: unknown,\n): Promise<RequesterContext | undefined> {\n if (typeof userContext.resolveRequester === 'function') {\n const ctx = await userContext.resolveRequester(req);\n return ctx?.userId ? ctx : undefined;\n }\n const userId = await userContext.getCurrentUserId(req);\n return userId ? { userId, organizationId: null } : undefined;\n}\n\n/**\n * Build the global middleware. Runs the remainder of the request inside\n * `withRequester(...)` so the ambient context propagates through every `await`\n * to downstream repositories.\n */\nexport function makeRequesterContextMiddleware(\n userContext: IUserContext,\n options: RequesterContextOptions = {},\n): RequestHandler {\n const onUnresolved = options.onUnresolved ?? 'unscoped';\n return (req, _res, next) => {\n resolveRequesterContext(userContext, req).then(\n (ctx) => {\n if (!ctx) {\n next();\n return;\n }\n // als.run executes its callback synchronously; Express dispatches the\n // rest of the pipeline inside next(), so all downstream handlers (and\n // their awaits) inherit this context.\n withRequester(ctx, async () => {\n next();\n });\n },\n (err) => {\n if (onUnresolved === 'reject') {\n next(err);\n return;\n }\n next();\n },\n );\n };\n}\n\n/**\n * Register the requester-context boundary on a Nest app. Resolves\n * `AUTH_USER_CONTEXT` from the root container (so it sees the consumer's\n * AppModule binding) and installs the global middleware. No-ops with a warning\n * when `AUTH_USER_CONTEXT` is not bound, so calling it unconditionally in\n * bootstrap is safe.\n */\nexport function installRequesterContext(\n app: INestApplication,\n options: RequesterContextOptions = {},\n): void {\n const userContext = app.get<IUserContext>(AUTH_USER_CONTEXT, {\n strict: false,\n });\n if (!userContext) {\n // eslint-disable-next-line no-console\n console.warn(\n '[auth] installRequesterContext: AUTH_USER_CONTEXT is not bound — ' +\n 'request scoping NOT installed. Provide an IUserContext under ' +\n 'AUTH_USER_CONTEXT in your AppModule to enable ambient tenant scoping.',\n );\n return;\n }\n app.use(makeRequesterContextMiddleware(userContext, options));\n}\n","/**\n * AuthModule — DynamicModule factory for the auth subsystem.\n *\n * Wires the pluggable backends the subsystem ships with:\n * - `ENCRYPTION_KEY` → `EnvEncryptionKey` (AES-256-GCM from env)\n * - `OAUTH_STATE_STORE` → `MemoryOAuthStateStore` (dev/tests) or\n * `DrizzleOAuthStateStore` (prod, requires\n * DRIZZLE provider).\n * - `AUTH_OPTIONS` → resolved options bag (used by AuthController\n * for `redirectUriBase`).\n *\n * The connection-store ports (`AUTH_CONNECTION_READER`,\n * `AUTH_CONNECTION_TOKEN_WRITER`, `AUTH_CONNECTION_GRANT_SINK`),\n * `AUTH_USER_CONTEXT`, and `STRATEGY_REGISTRY` are deliberately **not**\n * wired here — they are always consumer-specific:\n * - connection-store ports adapt the consumer's `connections` storage;\n * - `IUserContext` adapts the app's session/JWT scheme;\n * - `STRATEGY_REGISTRY` is populated from the per-provider strategy\n * classes the consumer maintains.\n *\n * Consumers provide them in their app module (or by importing the\n * `auth-integrations` starter, which binds the three connection-store\n * ports off a single canonical entity).\n *\n * Usage in AppModule:\n * ```typescript\n * AuthModule.forRoot({\n * encryptionKey: 'env',\n * oauthStateStore: 'memory', // or 'drizzle'\n * enableController: true,\n * redirectUriBase: 'http://localhost:3000',\n * });\n * ```\n *\n * `global: true` means other modules don't need to re-import AuthModule to\n * inject the auth tokens.\n */\nimport { Module, type DynamicModule, type Provider } from '@nestjs/common';\nimport {\n AUTH_OPTIONS,\n ENCRYPTION_KEY,\n OAUTH_STATE_STORE,\n} from './auth.tokens';\nimport { EnvEncryptionKey } from './backends/encryption-key/env';\nimport { MemoryOAuthStateStore } from './backends/state-store.memory-backend';\nimport { DrizzleOAuthStateStore } from './backends/state-store.drizzle-backend';\nimport { AuthController } from './controllers/auth.controller';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type { DrizzleClient } from '../../types/drizzle';\n\ntype EncryptionKeyChoice =\n | 'env'\n | Omit<Provider, 'provide'>;\n\ntype OAuthStateStoreChoice =\n | 'memory'\n | 'drizzle'\n | Omit<Provider, 'provide'>;\n\nexport interface AuthModuleOptions {\n /** `'env'` (default) or a full provider definition (e.g. `{ useClass: MyKmsEncryptionKey }`). */\n encryptionKey?: EncryptionKeyChoice;\n /**\n * `'memory'` (default — tests/dev) or `'drizzle'` (prod, requires DRIZZLE\n * provider) or a full provider definition for a custom impl.\n */\n oauthStateStore?: OAuthStateStoreChoice;\n /**\n * Mount `AuthController` (`/auth/:provider/connect` + `/callback`).\n * Default `false` — apps that hand-roll connect/callback (rare) or that\n * use the subsystem only for the refresh path can opt out.\n */\n enableController?: boolean;\n /**\n * Public base URL of the API server. Used to construct per-provider\n * callback URIs as `${redirectUriBase}/auth/:provider/callback`.\n * Required when `enableController: true`.\n */\n redirectUriBase?: string;\n}\n\nfunction resolveEncryptionKeyProvider(choice: EncryptionKeyChoice): Provider {\n if (choice === 'env') {\n return { provide: ENCRYPTION_KEY, useClass: EnvEncryptionKey };\n }\n return { provide: ENCRYPTION_KEY, ...choice } as Provider;\n}\n\nfunction resolveOAuthStateStoreProvider(\n choice: OAuthStateStoreChoice,\n): Provider {\n if (choice === 'memory') {\n return { provide: OAUTH_STATE_STORE, useClass: MemoryOAuthStateStore };\n }\n if (choice === 'drizzle') {\n return {\n provide: OAUTH_STATE_STORE,\n useFactory: (db: DrizzleClient | null) => {\n if (!db) {\n throw new Error(\n \"AuthModule.forRoot: oauthStateStore: 'drizzle' selected but DRIZZLE provider is not available. \" +\n 'Ensure DatabaseModule (or another provider exposing DRIZZLE) is imported before AuthModule.forRoot.',\n );\n }\n return new DrizzleOAuthStateStore(db);\n },\n inject: [{ token: DRIZZLE, optional: true }],\n };\n }\n return { provide: OAUTH_STATE_STORE, ...choice } as Provider;\n}\n\n@Module({})\nexport class AuthModule {\n static forRoot(options: AuthModuleOptions = {}): DynamicModule {\n const resolved: AuthModuleOptions = {\n encryptionKey: options.encryptionKey ?? 'env',\n oauthStateStore: options.oauthStateStore ?? 'memory',\n enableController: options.enableController ?? false,\n redirectUriBase: options.redirectUriBase,\n };\n\n if (resolved.enableController && !resolved.redirectUriBase) {\n throw new Error(\n 'AuthModule.forRoot: redirectUriBase is required when enableController: true',\n );\n }\n\n const encryptionKeyProvider = resolveEncryptionKeyProvider(\n resolved.encryptionKey!,\n );\n const oauthStateStoreProvider = resolveOAuthStateStoreProvider(\n resolved.oauthStateStore!,\n );\n const optionsProvider: Provider = {\n provide: AUTH_OPTIONS,\n useValue: resolved,\n };\n\n return {\n module: AuthModule,\n global: true,\n providers: [encryptionKeyProvider, oauthStateStoreProvider, optionsProvider],\n controllers: resolved.enableController ? [AuthController] : [],\n exports: [ENCRYPTION_KEY, OAUTH_STATE_STORE, AUTH_OPTIONS],\n };\n }\n}\n","/**\n * NestJS injection tokens\n *\n * Used with @Inject() decorator in concrete repository constructors.\n */\n\n/**\n * Injection token for the Drizzle ORM database client.\n *\n * Usage in concrete repositories:\n * ```typescript\n * constructor(@Inject(DRIZZLE) db: DrizzleClient) { super(db); }\n * ```\n */\nexport const DRIZZLE = 'DRIZZLE' as const;\n\n/**\n * Injection token for the event bus (IEventBus).\n *\n * Optional — only resolved when EventsModule.forRoot() is registered.\n * BaseService uses this with @Optional() to emit lifecycle events\n * without requiring the events subsystem to be installed.\n *\n * Usage in services/use cases:\n * ```typescript\n * @Optional() @Inject(EVENT_BUS) eventBus?: IEventBus\n * ```\n */\nexport const EVENT_BUS = 'EVENT_BUS' as const;\n"],"mappings":";;;;;;;;;;;;;AAuCO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACgB,QAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EAJkB;AAKpB;;;AC5CO,IAAM,MAAM;AAGZ,IAAM,WAAW,CAAC,MAAc,SAAyB,GAAG,GAAG,IAAI,IAAI,IAAI,IAAI;;;AC6B/E,IAAM,iBAAiB,OAAO,IAAI,SAAS,QAAQ,gBAAgB,CAAC;A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,OAA6B;AACxC,YAAI,CAAC,IAAI;AACP,gBAAM,IAAI;AAAA,YACR;AAAA,UAEF;AAAA,QACF;AACA,eAAO,IAAI,uBAAuB,EAAE;AAAA,MACtC;AAAA,MACA,QAAQ,CAAC,EAAE,OAAO,SAAS,UAAU,KAAK,CAAC;AAAA,IAC7C;AAAA,EACF;AACA,SAAO,EAAE,SAAS,mBAAmB,GAAG,OAAO;AACjD;AAGO,IAAM,aAAN,MAAiB;AAAA,EACtB,OAAO,QAAQ,UAA6B,CAAC,GAAkB;AAC7D,UAAM,WAA8B;AAAA,MAClC,eAAe,QAAQ,iBAAiB;AAAA,MACxC,iBAAiB,QAAQ,mBAAmB;AAAA,MAC5C,kBAAkB,QAAQ,oBAAoB;AAAA,MAC9C,iBAAiB,QAAQ;AAAA,IAC3B;AAEA,QAAI,SAAS,oBAAoB,CAAC,SAAS,iBAAiB;AAC1D,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,wBAAwB;AAAA,MAC5B,SAAS;AAAA,IACX;AACA,UAAM,0BAA0B;AAAA,MAC9B,SAAS;AAAA,IACX;AACA,UAAM,kBAA4B;AAAA,MAChC,SAAS;AAAA,MACT,UAAU;AAAA,IACZ;AAEA,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,WAAW,CAAC,uBAAuB,yBAAyB,eAAe;AAAA,MAC3E,aAAa,SAAS,mBAAmB,CAAC,cAAc,IAAI,CAAC;AAAA,MAC7D,SAAS,CAAC,gBAAgB,mBAAmB,YAAY;AAAA,IAC3D;AAAA,EACF;AACF;AAlCa,aAAN;AAAA,EADN,OAAO,CAAC,CAAC;AAAA,GACG;","names":["randomBytes","randomBytes","randomBytes","randomBytes"]}
@@ -5,8 +5,19 @@ function withRequester(ctx, fn) {
5
5
  return als.run(ctx, fn);
6
6
  }
7
7
 
8
+ // runtime/subsystems/token-key.ts
9
+ var PKG = "@pattern-stack/codegen";
10
+ var tokenKey = (area, name) => `${PKG}.${area}.${name}`;
11
+
8
12
  // runtime/subsystems/auth/auth.tokens.ts
9
- var AUTH_USER_CONTEXT = /* @__PURE__ */ Symbol("AUTH_USER_CONTEXT");
13
+ var ENCRYPTION_KEY = Symbol.for(tokenKey("auth", "encryption-key"));
14
+ var OAUTH_STATE_STORE = Symbol.for(tokenKey("auth", "oauth-state-store"));
15
+ var AUTH_CONNECTION_READER = Symbol.for(tokenKey("auth", "connection-reader"));
16
+ var AUTH_CONNECTION_TOKEN_WRITER = Symbol.for(tokenKey("auth", "connection-token-writer"));
17
+ var AUTH_CONNECTION_GRANT_SINK = Symbol.for(tokenKey("auth", "connection-grant-sink"));
18
+ var AUTH_USER_CONTEXT = Symbol.for(tokenKey("auth", "user-context"));
19
+ var STRATEGY_REGISTRY = Symbol.for(tokenKey("auth", "strategy-registry"));
20
+ var AUTH_OPTIONS = Symbol.for(tokenKey("auth", "options"));
10
21
 
11
22
  // runtime/subsystems/auth/middleware/requester-context.ts
12
23
  async function resolveRequesterContext(userContext, req) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../runtime/base-classes/tenant-context.ts","../../../../../runtime/subsystems/auth/auth.tokens.ts","../../../../../runtime/subsystems/auth/middleware/requester-context.ts"],"sourcesContent":["/**\n * Ambient requester context — AsyncLocalStorage-backed tenant scope.\n *\n * The alternative to threading `userId`/`organizationId` through every\n * repository/service signature. Set ONCE at each boundary the generated app\n * owns, read implicitly inside `BaseRepository` (see `scopePredicate`).\n *\n * ## Where to set it (boundaries)\n *\n * - HTTP / tRPC handlers — from the authenticated `ctx.user`\n * - OAuth callback controllers — from the authenticated session\n * - Queue/worker `process()` — from the job's owning user after the\n * job's record is loaded\n *\n * Each boundary wraps the rest of the request in `withRequester({ userId,\n * organizationId }, () => ...)`. The context propagates through every `await`\n * to all downstream repo/service calls without being passed explicitly.\n *\n * ## Where to read it\n *\n * - `BaseRepository.scopePredicate()` reads it (via `tryGetRequester` in\n * lenient mode, `requireRequester` in strict mode) and filters every read\n * by the ambient scope when the repo declares `userTracking: true`.\n *\n * ## Why AsyncLocalStorage over an explicit parameter\n *\n * Threading `userId` (and later `organizationId`) through dozens of method\n * signatures is pure parameter pollution. Ambient context also lets a repo\n * make the \"I forgot to scope\" mistake impossible at runtime: in strict mode\n * `requireRequester()` throws when no context is active, surfacing a missing\n * boundary call loudly rather than silently leaking cross-tenant data.\n *\n * ## Not-found semantics\n *\n * When a row exists but belongs to a different requester, scoped reads return\n * `null`/`[]` — identical to \"truly doesn't exist\". No existence oracle;\n * callers throw NotFound uniformly. Standard security practice.\n *\n * ## Testing\n *\n * Tests that exercise scoped repos must wrap the call in `withRequester(...)`.\n * In strict mode an unwrapped call hitting `requireRequester()` throws — by\n * design. In lenient mode (the default) an unwrapped call is simply unscoped.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * Data-visibility scope. The auth layer decides which scope a request is\n * allowed to claim; the repo trusts whatever the ambient context says.\n *\n * - `'user'`: filter every read by `user_id = ctx.userId`. Default.\n * - `'org'`: filter every read by membership in the requester's org, resolved\n * via `user_id IN (ctx.orgUserIds)` rather than via a per-entity\n * `organization_id` column. Works for every user-owned table and keeps repos\n * single-table — the org member list is pre-resolved at the boundary.\n * - `'superuser'`: no scope filter. Engineering / internal-tools only.\n *\n * AUTHORIZATION (who is allowed to claim each scope) lives in boundary\n * middleware, not in the repo. The repo trusts the ambient context — same\n * trust model as a threaded `userId`.\n */\nexport type RequesterScope = 'user' | 'org' | 'superuser';\n\nexport interface RequesterContext {\n /**\n * The user making the request. Always present — even in `'org'` and\n * `'superuser'` scopes it is the audit-trail \"who actually did this\".\n */\n readonly userId: string;\n /**\n * The organization the requester belongs to. Required when\n * `scope === 'org'`; may be null for `'user'` (users with no org) and for\n * `'superuser'` (cross-org reads).\n */\n readonly organizationId: string | null;\n /**\n * Data-visibility scope. Defaults to `'user'` when omitted.\n */\n readonly scope?: RequesterScope;\n /**\n * For `scope === 'org'`: the list of user IDs in the requester's org,\n * pre-resolved by the boundary middleware that established the `'org'`\n * scope (one `SELECT users.id WHERE organization_id = X` at the trust\n * boundary). Repos use this as a literal `IN (...)` filter — they never\n * JOIN to `users` themselves. Required when `scope === 'org'`.\n */\n readonly orgUserIds?: readonly string[];\n}\n\nconst als = new AsyncLocalStorage<RequesterContext>();\n\n/**\n * Set the ambient requester context for the duration of `fn`. The context\n * propagates through `await` boundaries to all downstream calls. Nesting is\n * fine — an inner `withRequester` overrides the outer for its callback.\n */\nexport function withRequester<T>(\n ctx: RequesterContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return als.run(ctx, fn);\n}\n\n/**\n * Read the ambient requester context. Throws if no context is active — by\n * design. Used by repos in strict scope-enforcement mode; an unwrapped call\n * site is a missing boundary.\n */\nexport function requireRequester(): RequesterContext {\n const ctx = als.getStore();\n if (!ctx) {\n throw new Error(\n 'No requester context active. Wrap the entry point in ' +\n 'withRequester({ userId, organizationId }, fn). See tenant-context.ts.',\n );\n }\n return ctx;\n}\n\n/**\n * Read the ambient requester context without throwing. Returns `undefined`\n * when no context is active. Used by repos in lenient scope-enforcement mode\n * (the default) and by code paths that legitimately run outside a request.\n */\nexport function tryGetRequester(): RequesterContext | undefined {\n return als.getStore();\n}\n\n/**\n * Resolve the effective scope for the ambient context, defaulting to `'user'`.\n */\nexport function requireRequesterScope(): RequesterScope {\n return requireRequester().scope ?? 'user';\n}\n\n/**\n * Convenience helpers for setting scope explicitly. All three preserve\n * `userId` in the context (audit trail) regardless of scope.\n *\n * - `withUserScope`: regular end-user requests. Most call sites.\n * - `withOrgScope`: admin / org-shared resource access. The caller MUST verify\n * the requester's role permits `'org'` before calling — the helper does not\n * enforce authorization. `orgUserIds` is pre-resolved at the boundary.\n * - `withSuperuserScope`: engineering scripts / internal tools. `organizationId`\n * is null (cross-org is the point). Same authorization caveat applies.\n */\nexport function withUserScope<T>(\n userId: string,\n organizationId: string | null,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester({ userId, organizationId, scope: 'user' }, fn);\n}\n\nexport function withOrgScope<T>(\n userId: string,\n organizationId: string,\n orgUserIds: readonly string[],\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId, scope: 'org', orgUserIds },\n fn,\n );\n}\n\nexport function withSuperuserScope<T>(\n userId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId: null, scope: 'superuser' },\n fn,\n );\n}\n","/**\n * Auth subsystem — injection tokens.\n *\n * Following ADR-008 guidance: `Symbol()` tokens for type safety and collision\n * avoidance. Consumers inject these via `@Inject(...)` against the matching\n * protocol interface.\n *\n * Usage:\n * ```typescript\n * constructor(\n * @Inject(ENCRYPTION_KEY) private readonly key: IEncryptionKey,\n * @Inject(OAUTH_STATE_STORE) private readonly states: IOAuthStateStore,\n * @Inject(AUTH_CONNECTION_READER) private readonly reader: IConnectionReader,\n * @Inject(AUTH_CONNECTION_TOKEN_WRITER) private readonly writer: IConnectionTokenWriter,\n * @Inject(AUTH_CONNECTION_GRANT_SINK) private readonly grants: IConnectionGrantSink,\n * @Inject(AUTH_USER_CONTEXT) private readonly userCtx: IUserContext,\n * @Inject(STRATEGY_REGISTRY) private readonly registry: ProviderStrategyRegistry,\n * ) {}\n * ```\n *\n * `IAuthStrategy` implementations are provider-specific and registered under\n * provider-specific tokens (e.g. `SALESFORCE_AUTH_STRATEGY`,\n * `HUBSPOT_AUTH_STRATEGY`) by each connection module — this subsystem does\n * not mandate a single `AUTH_STRATEGY` token because an app typically has\n * many concurrent strategies, one per provider. They are dispatched through\n * `STRATEGY_REGISTRY` (a `ReadonlyMap<slug, IProviderStrategy>`), populated\n * by per-provider modules via a `useFactory` provider.\n */\nexport const ENCRYPTION_KEY = Symbol('ENCRYPTION_KEY');\nexport const OAUTH_STATE_STORE = Symbol('OAUTH_STATE_STORE');\nexport const AUTH_CONNECTION_READER = Symbol('AUTH_CONNECTION_READER');\nexport const AUTH_CONNECTION_TOKEN_WRITER = Symbol('AUTH_CONNECTION_TOKEN_WRITER');\nexport const AUTH_CONNECTION_GRANT_SINK = Symbol('AUTH_CONNECTION_GRANT_SINK');\nexport const AUTH_USER_CONTEXT = Symbol('AUTH_USER_CONTEXT');\nexport const STRATEGY_REGISTRY = Symbol('STRATEGY_REGISTRY');\n/**\n * Holds the resolved `AuthModuleOptions` (used by `AuthController` to read\n * `redirectUriBase` for building per-provider callback URIs).\n */\nexport const AUTH_OPTIONS = Symbol('AUTH_OPTIONS');\n","/**\n * RequesterContext boundary install — bridges authentication to ambient\n * tenant scoping.\n *\n * This is the missing link that makes `BaseRepository`'s ambient scoping\n * (see `base-classes/tenant-context.ts`) actually engage on HTTP requests:\n * it reads the requester off each request (via the consumer-bound\n * `IUserContext`) and runs the rest of the request inside `withRequester(...)`,\n * so every downstream repository read/write is automatically scoped — no\n * threaded `userId`.\n *\n * ## Wiring (one line in your bootstrap)\n *\n * In `main.ts`, after `NestFactory.create`:\n *\n * ```ts\n * import { installRequesterContext } from './shared/subsystems/auth/middleware/requester-context';\n * const app = await NestFactory.create(AppModule);\n * installRequesterContext(app); // no-op + warn if AUTH_USER_CONTEXT is unbound\n * ```\n *\n * `installRequesterContext` resolves `AUTH_USER_CONTEXT` from the root DI\n * container (so it sees the binding the consumer provides in AppModule) and\n * registers a global Express middleware. Pairs with Swagger's `@ApiBearerAuth`\n * \"Authorize\" button: paste a token there and every request it sends now flows\n * through this boundary into a scoped repository call.\n *\n * ## Trust + failure model\n *\n * - The middleware TRUSTS whatever `IUserContext` returns — authentication and\n * authorization (validating the token, deciding which scope a requester may\n * claim) are the `IUserContext` implementation's job, exactly as for a\n * hand-threaded `userId`.\n * - When the requester cannot be resolved (no/invalid credentials — e.g. a\n * public route, or the OAuth callback itself), the request proceeds WITHOUT\n * an ambient context (`onUnresolved: 'unscoped'`, the default). A\n * `userTracking` repo in lenient mode then runs unscoped; in strict mode it\n * throws downstream — which is correct: unauthenticated callers must not\n * reach scoped data. Set `onUnresolved: 'reject'` to fail the request at the\n * boundary instead.\n */\nimport type { INestApplication } from '@nestjs/common';\nimport {\n withRequester,\n type RequesterContext,\n} from '../../../base-classes/tenant-context';\nimport { AUTH_USER_CONTEXT } from '../auth.tokens';\nimport type { IUserContext } from '../protocols/user-context';\n\n/** Minimal Express-style middleware signature (avoids an `express` dep). */\ntype NextFn = (err?: unknown) => void;\ntype RequestHandler = (req: unknown, res: unknown, next: NextFn) => void;\n\nexport interface RequesterContextOptions {\n /**\n * What to do when `IUserContext` cannot resolve a requester (throws, or\n * returns no `userId`).\n * - `'unscoped'` (default): proceed without a context — public routes work;\n * scoped repos run unscoped (lenient) or throw downstream (strict).\n * - `'reject'`: fail the request at the boundary (`next(error)`).\n */\n onUnresolved?: 'unscoped' | 'reject';\n}\n\n/**\n * Resolve the ambient context for a request: prefer the richer\n * `resolveRequester` (org/superuser), else derive plain `'user'` scope from\n * `getCurrentUserId`. Returns `undefined` when no requester can be determined.\n */\nexport async function resolveRequesterContext(\n userContext: IUserContext,\n req: unknown,\n): Promise<RequesterContext | undefined> {\n if (typeof userContext.resolveRequester === 'function') {\n const ctx = await userContext.resolveRequester(req);\n return ctx?.userId ? ctx : undefined;\n }\n const userId = await userContext.getCurrentUserId(req);\n return userId ? { userId, organizationId: null } : undefined;\n}\n\n/**\n * Build the global middleware. Runs the remainder of the request inside\n * `withRequester(...)` so the ambient context propagates through every `await`\n * to downstream repositories.\n */\nexport function makeRequesterContextMiddleware(\n userContext: IUserContext,\n options: RequesterContextOptions = {},\n): RequestHandler {\n const onUnresolved = options.onUnresolved ?? 'unscoped';\n return (req, _res, next) => {\n resolveRequesterContext(userContext, req).then(\n (ctx) => {\n if (!ctx) {\n next();\n return;\n }\n // als.run executes its callback synchronously; Express dispatches the\n // rest of the pipeline inside next(), so all downstream handlers (and\n // their awaits) inherit this context.\n withRequester(ctx, async () => {\n next();\n });\n },\n (err) => {\n if (onUnresolved === 'reject') {\n next(err);\n return;\n }\n next();\n },\n );\n };\n}\n\n/**\n * Register the requester-context boundary on a Nest app. Resolves\n * `AUTH_USER_CONTEXT` from the root container (so it sees the consumer's\n * AppModule binding) and installs the global middleware. No-ops with a warning\n * when `AUTH_USER_CONTEXT` is not bound, so calling it unconditionally in\n * bootstrap is safe.\n */\nexport function installRequesterContext(\n app: INestApplication,\n options: RequesterContextOptions = {},\n): void {\n const userContext = app.get<IUserContext>(AUTH_USER_CONTEXT, {\n strict: false,\n });\n if (!userContext) {\n // eslint-disable-next-line no-console\n console.warn(\n '[auth] installRequesterContext: AUTH_USER_CONTEXT is not bound — ' +\n 'request scoping NOT installed. Provide an IUserContext under ' +\n 'AUTH_USER_CONTEXT in your AppModule to enable ambient tenant scoping.',\n );\n return;\n }\n app.use(makeRequesterContextMiddleware(userContext, options));\n}\n"],"mappings":";AA4CA,SAAS,yBAAyB;AA6ClC,IAAM,MAAM,IAAI,kBAAoC;AAO7C,SAAS,cACd,KACA,IACY;AACZ,SAAO,IAAI,IAAI,KAAK,EAAE;AACxB;;;ACpEO,IAAM,oBAAoB,uBAAO,mBAAmB;;;ACoC3D,eAAsB,wBACpB,aACA,KACuC;AACvC,MAAI,OAAO,YAAY,qBAAqB,YAAY;AACtD,UAAM,MAAM,MAAM,YAAY,iBAAiB,GAAG;AAClD,WAAO,KAAK,SAAS,MAAM;AAAA,EAC7B;AACA,QAAM,SAAS,MAAM,YAAY,iBAAiB,GAAG;AACrD,SAAO,SAAS,EAAE,QAAQ,gBAAgB,KAAK,IAAI;AACrD;AAOO,SAAS,+BACd,aACA,UAAmC,CAAC,GACpB;AAChB,QAAM,eAAe,QAAQ,gBAAgB;AAC7C,SAAO,CAAC,KAAK,MAAM,SAAS;AAC1B,4BAAwB,aAAa,GAAG,EAAE;AAAA,MACxC,CAAC,QAAQ;AACP,YAAI,CAAC,KAAK;AACR,eAAK;AACL;AAAA,QACF;AAIA,sBAAc,KAAK,YAAY;AAC7B,eAAK;AAAA,QACP,CAAC;AAAA,MACH;AAAA,MACA,CAAC,QAAQ;AACP,YAAI,iBAAiB,UAAU;AAC7B,eAAK,GAAG;AACR;AAAA,QACF;AACA,aAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACF;AASO,SAAS,wBACd,KACA,UAAmC,CAAC,GAC9B;AACN,QAAM,cAAc,IAAI,IAAkB,mBAAmB;AAAA,IAC3D,QAAQ;AAAA,EACV,CAAC;AACD,MAAI,CAAC,aAAa;AAEhB,YAAQ;AAAA,MACN;AAAA,IAGF;AACA;AAAA,EACF;AACA,MAAI,IAAI,+BAA+B,aAAa,OAAO,CAAC;AAC9D;","names":[]}
1
+ {"version":3,"sources":["../../../../../runtime/base-classes/tenant-context.ts","../../../../../runtime/subsystems/token-key.ts","../../../../../runtime/subsystems/auth/auth.tokens.ts","../../../../../runtime/subsystems/auth/middleware/requester-context.ts"],"sourcesContent":["/**\n * Ambient requester context — AsyncLocalStorage-backed tenant scope.\n *\n * The alternative to threading `userId`/`organizationId` through every\n * repository/service signature. Set ONCE at each boundary the generated app\n * owns, read implicitly inside `BaseRepository` (see `scopePredicate`).\n *\n * ## Where to set it (boundaries)\n *\n * - HTTP / tRPC handlers — from the authenticated `ctx.user`\n * - OAuth callback controllers — from the authenticated session\n * - Queue/worker `process()` — from the job's owning user after the\n * job's record is loaded\n *\n * Each boundary wraps the rest of the request in `withRequester({ userId,\n * organizationId }, () => ...)`. The context propagates through every `await`\n * to all downstream repo/service calls without being passed explicitly.\n *\n * ## Where to read it\n *\n * - `BaseRepository.scopePredicate()` reads it (via `tryGetRequester` in\n * lenient mode, `requireRequester` in strict mode) and filters every read\n * by the ambient scope when the repo declares `userTracking: true`.\n *\n * ## Why AsyncLocalStorage over an explicit parameter\n *\n * Threading `userId` (and later `organizationId`) through dozens of method\n * signatures is pure parameter pollution. Ambient context also lets a repo\n * make the \"I forgot to scope\" mistake impossible at runtime: in strict mode\n * `requireRequester()` throws when no context is active, surfacing a missing\n * boundary call loudly rather than silently leaking cross-tenant data.\n *\n * ## Not-found semantics\n *\n * When a row exists but belongs to a different requester, scoped reads return\n * `null`/`[]` — identical to \"truly doesn't exist\". No existence oracle;\n * callers throw NotFound uniformly. Standard security practice.\n *\n * ## Testing\n *\n * Tests that exercise scoped repos must wrap the call in `withRequester(...)`.\n * In strict mode an unwrapped call hitting `requireRequester()` throws — by\n * design. In lenient mode (the default) an unwrapped call is simply unscoped.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * Data-visibility scope. The auth layer decides which scope a request is\n * allowed to claim; the repo trusts whatever the ambient context says.\n *\n * - `'user'`: filter every read by `user_id = ctx.userId`. Default.\n * - `'org'`: filter every read by membership in the requester's org, resolved\n * via `user_id IN (ctx.orgUserIds)` rather than via a per-entity\n * `organization_id` column. Works for every user-owned table and keeps repos\n * single-table — the org member list is pre-resolved at the boundary.\n * - `'superuser'`: no scope filter. Engineering / internal-tools only.\n *\n * AUTHORIZATION (who is allowed to claim each scope) lives in boundary\n * middleware, not in the repo. The repo trusts the ambient context — same\n * trust model as a threaded `userId`.\n */\nexport type RequesterScope = 'user' | 'org' | 'superuser';\n\nexport interface RequesterContext {\n /**\n * The user making the request. Always present — even in `'org'` and\n * `'superuser'` scopes it is the audit-trail \"who actually did this\".\n */\n readonly userId: string;\n /**\n * The organization the requester belongs to. Required when\n * `scope === 'org'`; may be null for `'user'` (users with no org) and for\n * `'superuser'` (cross-org reads).\n */\n readonly organizationId: string | null;\n /**\n * Data-visibility scope. Defaults to `'user'` when omitted.\n */\n readonly scope?: RequesterScope;\n /**\n * For `scope === 'org'`: the list of user IDs in the requester's org,\n * pre-resolved by the boundary middleware that established the `'org'`\n * scope (one `SELECT users.id WHERE organization_id = X` at the trust\n * boundary). Repos use this as a literal `IN (...)` filter — they never\n * JOIN to `users` themselves. Required when `scope === 'org'`.\n */\n readonly orgUserIds?: readonly string[];\n}\n\nconst als = new AsyncLocalStorage<RequesterContext>();\n\n/**\n * Set the ambient requester context for the duration of `fn`. The context\n * propagates through `await` boundaries to all downstream calls. Nesting is\n * fine — an inner `withRequester` overrides the outer for its callback.\n */\nexport function withRequester<T>(\n ctx: RequesterContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return als.run(ctx, fn);\n}\n\n/**\n * Read the ambient requester context. Throws if no context is active — by\n * design. Used by repos in strict scope-enforcement mode; an unwrapped call\n * site is a missing boundary.\n */\nexport function requireRequester(): RequesterContext {\n const ctx = als.getStore();\n if (!ctx) {\n throw new Error(\n 'No requester context active. Wrap the entry point in ' +\n 'withRequester({ userId, organizationId }, fn). See tenant-context.ts.',\n );\n }\n return ctx;\n}\n\n/**\n * Read the ambient requester context without throwing. Returns `undefined`\n * when no context is active. Used by repos in lenient scope-enforcement mode\n * (the default) and by code paths that legitimately run outside a request.\n */\nexport function tryGetRequester(): RequesterContext | undefined {\n return als.getStore();\n}\n\n/**\n * Resolve the effective scope for the ambient context, defaulting to `'user'`.\n */\nexport function requireRequesterScope(): RequesterScope {\n return requireRequester().scope ?? 'user';\n}\n\n/**\n * Convenience helpers for setting scope explicitly. All three preserve\n * `userId` in the context (audit trail) regardless of scope.\n *\n * - `withUserScope`: regular end-user requests. Most call sites.\n * - `withOrgScope`: admin / org-shared resource access. The caller MUST verify\n * the requester's role permits `'org'` before calling — the helper does not\n * enforce authorization. `orgUserIds` is pre-resolved at the boundary.\n * - `withSuperuserScope`: engineering scripts / internal tools. `organizationId`\n * is null (cross-org is the point). Same authorization caveat applies.\n */\nexport function withUserScope<T>(\n userId: string,\n organizationId: string | null,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester({ userId, organizationId, scope: 'user' }, fn);\n}\n\nexport function withOrgScope<T>(\n userId: string,\n organizationId: string,\n orgUserIds: readonly string[],\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId, scope: 'org', orgUserIds },\n fn,\n );\n}\n\nexport function withSuperuserScope<T>(\n userId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId: null, scope: 'superuser' },\n fn,\n );\n}\n","/** Canonical package namespace for cross-boundary DI token keys. MUST be a hardcoded\n * constant (NOT derived from package.json) so a vendored copy — which lives inside the\n * CONSUMER's package — produces the identical key and the two copies share the symbol. */\nexport const PKG = '@pattern-stack/codegen';\n// TODO(token-version): if/when a runtime contract version is adopted, inject it HERE only\n// (e.g. `${PKG}#${ABI}.${area}.${name}`) — this helper is the single chokepoint.\nexport const tokenKey = (area: string, name: string): string => `${PKG}.${area}.${name}`;\n","/**\n * Auth subsystem — injection tokens.\n *\n * Following ADR-008 guidance: `Symbol()` tokens for type safety and collision\n * avoidance. Consumers inject these via `@Inject(...)` against the matching\n * protocol interface.\n *\n * Usage:\n * ```typescript\n * constructor(\n * @Inject(ENCRYPTION_KEY) private readonly key: IEncryptionKey,\n * @Inject(OAUTH_STATE_STORE) private readonly states: IOAuthStateStore,\n * @Inject(AUTH_CONNECTION_READER) private readonly reader: IConnectionReader,\n * @Inject(AUTH_CONNECTION_TOKEN_WRITER) private readonly writer: IConnectionTokenWriter,\n * @Inject(AUTH_CONNECTION_GRANT_SINK) private readonly grants: IConnectionGrantSink,\n * @Inject(AUTH_USER_CONTEXT) private readonly userCtx: IUserContext,\n * @Inject(STRATEGY_REGISTRY) private readonly registry: ProviderStrategyRegistry,\n * ) {}\n * ```\n *\n * `IAuthStrategy` implementations are provider-specific and registered under\n * provider-specific tokens (e.g. `SALESFORCE_AUTH_STRATEGY`,\n * `HUBSPOT_AUTH_STRATEGY`) by each connection module — this subsystem does\n * not mandate a single `AUTH_STRATEGY` token because an app typically has\n * many concurrent strategies, one per provider. They are dispatched through\n * `STRATEGY_REGISTRY` (a `ReadonlyMap<slug, IProviderStrategy>`), populated\n * by per-provider modules via a `useFactory` provider.\n */\nimport { tokenKey } from '../token-key';\n\n// ADR-037: namespaced `Symbol.for(...)` keys so a token matches by VALUE across\n// import boundaries — the package copy and a (legacy) vendored copy resolve to\n// the SAME symbol, eliminating the dual-package DI-token identity hazard that\n// crashed boot once the emitter began emitting `STRATEGY_REGISTRY` as a runtime\n// value (RFC-0003 R5). Matches the convention surface packages already use.\nexport const ENCRYPTION_KEY = Symbol.for(tokenKey('auth', 'encryption-key'));\nexport const OAUTH_STATE_STORE = Symbol.for(tokenKey('auth', 'oauth-state-store'));\nexport const AUTH_CONNECTION_READER = Symbol.for(tokenKey('auth', 'connection-reader'));\nexport const AUTH_CONNECTION_TOKEN_WRITER = Symbol.for(tokenKey('auth', 'connection-token-writer'));\nexport const AUTH_CONNECTION_GRANT_SINK = Symbol.for(tokenKey('auth', 'connection-grant-sink'));\nexport const AUTH_USER_CONTEXT = Symbol.for(tokenKey('auth', 'user-context'));\nexport const STRATEGY_REGISTRY = Symbol.for(tokenKey('auth', 'strategy-registry'));\n/**\n * Holds the resolved `AuthModuleOptions` (used by `AuthController` to read\n * `redirectUriBase` for building per-provider callback URIs).\n */\nexport const AUTH_OPTIONS = Symbol.for(tokenKey('auth', 'options'));\n","/**\n * RequesterContext boundary install — bridges authentication to ambient\n * tenant scoping.\n *\n * This is the missing link that makes `BaseRepository`'s ambient scoping\n * (see `base-classes/tenant-context.ts`) actually engage on HTTP requests:\n * it reads the requester off each request (via the consumer-bound\n * `IUserContext`) and runs the rest of the request inside `withRequester(...)`,\n * so every downstream repository read/write is automatically scoped — no\n * threaded `userId`.\n *\n * ## Wiring (one line in your bootstrap)\n *\n * In `main.ts`, after `NestFactory.create`:\n *\n * ```ts\n * import { installRequesterContext } from './shared/subsystems/auth/middleware/requester-context';\n * const app = await NestFactory.create(AppModule);\n * installRequesterContext(app); // no-op + warn if AUTH_USER_CONTEXT is unbound\n * ```\n *\n * `installRequesterContext` resolves `AUTH_USER_CONTEXT` from the root DI\n * container (so it sees the binding the consumer provides in AppModule) and\n * registers a global Express middleware. Pairs with Swagger's `@ApiBearerAuth`\n * \"Authorize\" button: paste a token there and every request it sends now flows\n * through this boundary into a scoped repository call.\n *\n * ## Trust + failure model\n *\n * - The middleware TRUSTS whatever `IUserContext` returns — authentication and\n * authorization (validating the token, deciding which scope a requester may\n * claim) are the `IUserContext` implementation's job, exactly as for a\n * hand-threaded `userId`.\n * - When the requester cannot be resolved (no/invalid credentials — e.g. a\n * public route, or the OAuth callback itself), the request proceeds WITHOUT\n * an ambient context (`onUnresolved: 'unscoped'`, the default). A\n * `userTracking` repo in lenient mode then runs unscoped; in strict mode it\n * throws downstream — which is correct: unauthenticated callers must not\n * reach scoped data. Set `onUnresolved: 'reject'` to fail the request at the\n * boundary instead.\n */\nimport type { INestApplication } from '@nestjs/common';\nimport {\n withRequester,\n type RequesterContext,\n} from '../../../base-classes/tenant-context';\nimport { AUTH_USER_CONTEXT } from '../auth.tokens';\nimport type { IUserContext } from '../protocols/user-context';\n\n/** Minimal Express-style middleware signature (avoids an `express` dep). */\ntype NextFn = (err?: unknown) => void;\ntype RequestHandler = (req: unknown, res: unknown, next: NextFn) => void;\n\nexport interface RequesterContextOptions {\n /**\n * What to do when `IUserContext` cannot resolve a requester (throws, or\n * returns no `userId`).\n * - `'unscoped'` (default): proceed without a context — public routes work;\n * scoped repos run unscoped (lenient) or throw downstream (strict).\n * - `'reject'`: fail the request at the boundary (`next(error)`).\n */\n onUnresolved?: 'unscoped' | 'reject';\n}\n\n/**\n * Resolve the ambient context for a request: prefer the richer\n * `resolveRequester` (org/superuser), else derive plain `'user'` scope from\n * `getCurrentUserId`. Returns `undefined` when no requester can be determined.\n */\nexport async function resolveRequesterContext(\n userContext: IUserContext,\n req: unknown,\n): Promise<RequesterContext | undefined> {\n if (typeof userContext.resolveRequester === 'function') {\n const ctx = await userContext.resolveRequester(req);\n return ctx?.userId ? ctx : undefined;\n }\n const userId = await userContext.getCurrentUserId(req);\n return userId ? { userId, organizationId: null } : undefined;\n}\n\n/**\n * Build the global middleware. Runs the remainder of the request inside\n * `withRequester(...)` so the ambient context propagates through every `await`\n * to downstream repositories.\n */\nexport function makeRequesterContextMiddleware(\n userContext: IUserContext,\n options: RequesterContextOptions = {},\n): RequestHandler {\n const onUnresolved = options.onUnresolved ?? 'unscoped';\n return (req, _res, next) => {\n resolveRequesterContext(userContext, req).then(\n (ctx) => {\n if (!ctx) {\n next();\n return;\n }\n // als.run executes its callback synchronously; Express dispatches the\n // rest of the pipeline inside next(), so all downstream handlers (and\n // their awaits) inherit this context.\n withRequester(ctx, async () => {\n next();\n });\n },\n (err) => {\n if (onUnresolved === 'reject') {\n next(err);\n return;\n }\n next();\n },\n );\n };\n}\n\n/**\n * Register the requester-context boundary on a Nest app. Resolves\n * `AUTH_USER_CONTEXT` from the root container (so it sees the consumer's\n * AppModule binding) and installs the global middleware. No-ops with a warning\n * when `AUTH_USER_CONTEXT` is not bound, so calling it unconditionally in\n * bootstrap is safe.\n */\nexport function installRequesterContext(\n app: INestApplication,\n options: RequesterContextOptions = {},\n): void {\n const userContext = app.get<IUserContext>(AUTH_USER_CONTEXT, {\n strict: false,\n });\n if (!userContext) {\n // eslint-disable-next-line no-console\n console.warn(\n '[auth] installRequesterContext: AUTH_USER_CONTEXT is not bound — ' +\n 'request scoping NOT installed. Provide an IUserContext under ' +\n 'AUTH_USER_CONTEXT in your AppModule to enable ambient tenant scoping.',\n );\n return;\n }\n app.use(makeRequesterContextMiddleware(userContext, options));\n}\n"],"mappings":";AA4CA,SAAS,yBAAyB;AA6ClC,IAAM,MAAM,IAAI,kBAAoC;AAO7C,SAAS,cACd,KACA,IACY;AACZ,SAAO,IAAI,IAAI,KAAK,EAAE;AACxB;;;AClGO,IAAM,MAAM;AAGZ,IAAM,WAAW,CAAC,MAAc,SAAyB,GAAG,GAAG,IAAI,IAAI,IAAI,IAAI;;;AC6B/E,IAAM,iBAAiB,OAAO,IAAI,SAAS,QAAQ,gBAAgB,CAAC;AACpE,IAAM,oBAAoB,OAAO,IAAI,SAAS,QAAQ,mBAAmB,CAAC;AAC1E,IAAM,yBAAyB,OAAO,IAAI,SAAS,QAAQ,mBAAmB,CAAC;AAC/E,IAAM,+BAA+B,OAAO,IAAI,SAAS,QAAQ,yBAAyB,CAAC;AAC3F,IAAM,6BAA6B,OAAO,IAAI,SAAS,QAAQ,uBAAuB,CAAC;AACvF,IAAM,oBAAoB,OAAO,IAAI,SAAS,QAAQ,cAAc,CAAC;AACrE,IAAM,oBAAoB,OAAO,IAAI,SAAS,QAAQ,mBAAmB,CAAC;AAK1E,IAAM,eAAe,OAAO,IAAI,SAAS,QAAQ,SAAS,CAAC;;;ACuBlE,eAAsB,wBACpB,aACA,KACuC;AACvC,MAAI,OAAO,YAAY,qBAAqB,YAAY;AACtD,UAAM,MAAM,MAAM,YAAY,iBAAiB,GAAG;AAClD,WAAO,KAAK,SAAS,MAAM;AAAA,EAC7B;AACA,QAAM,SAAS,MAAM,YAAY,iBAAiB,GAAG;AACrD,SAAO,SAAS,EAAE,QAAQ,gBAAgB,KAAK,IAAI;AACrD;AAOO,SAAS,+BACd,aACA,UAAmC,CAAC,GACpB;AAChB,QAAM,eAAe,QAAQ,gBAAgB;AAC7C,SAAO,CAAC,KAAK,MAAM,SAAS;AAC1B,4BAAwB,aAAa,GAAG,EAAE;AAAA,MACxC,CAAC,QAAQ;AACP,YAAI,CAAC,KAAK;AACR,eAAK;AACL;AAAA,QACF;AAIA,sBAAc,KAAK,YAAY;AAC7B,eAAK;AAAA,QACP,CAAC;AAAA,MACH;AAAA,MACA,CAAC,QAAQ;AACP,YAAI,iBAAiB,UAAU;AAC7B,eAAK,GAAG;AACR;AAAA,QACF;AACA,aAAK;AAAA,MACP;AAAA,IACF;AAAA,EACF;AACF;AASO,SAAS,wBACd,KACA,UAAmC,CAAC,GAC9B;AACN,QAAM,cAAc,IAAI,IAAkB,mBAAmB;AAAA,IAC3D,QAAQ;AAAA,EACV,CAAC;AACD,MAAI,CAAC,aAAa;AAEhB,YAAQ;AAAA,MACN;AAAA,IAGF;AACA;AAAA,EACF;AACA,MAAI,IAAI,+BAA+B,aAAa,OAAO,CAAC;AAC9D;","names":[]}
@@ -1,4 +1,4 @@
1
- import { f as JobHandlerBase, I as IJobOrchestrator, d as JobContext } from '../../../job-orchestrator.protocol-CHOEqBDk.js';
1
+ import { f as JobHandlerBase, I as IJobOrchestrator, d as JobContext } from '../../../job-orchestrator.protocol-CARhMLCO.js';
2
2
  import { IEventBus } from '../events/event-bus.protocol.js';
3
3
  import { IJobBridge, BridgeRegistry } from './bridge.protocol.js';
4
4
  import '../jobs/job-orchestration.schema.js';
@@ -13,14 +13,21 @@ var __decorateParam = (index, decorator) => (target, key) => decorator(target, k
13
13
  // runtime/subsystems/bridge/bridge-delivery-handler.ts
14
14
  import { Inject, Injectable, Logger, Optional } from "@nestjs/common";
15
15
 
16
+ // runtime/subsystems/token-key.ts
17
+ var PKG = "@pattern-stack/codegen";
18
+ var tokenKey = (area, name) => `${PKG}.${area}.${name}`;
19
+
16
20
  // runtime/subsystems/jobs/jobs-domain.tokens.ts
17
- var JOB_ORCHESTRATOR = /* @__PURE__ */ Symbol("JOB_ORCHESTRATOR");
21
+ var JOB_ORCHESTRATOR = Symbol.for(tokenKey("jobs", "orchestrator"));
22
+ var JOB_RUN_SERVICE = Symbol.for(tokenKey("jobs", "run-service"));
23
+ var JOB_STEP_SERVICE = Symbol.for(tokenKey("jobs", "step-service"));
24
+ var JOBS_MULTI_TENANT = Symbol.for(tokenKey("jobs", "multi-tenant"));
18
25
 
19
26
  // runtime/subsystems/jobs/job-handler.base.ts
20
27
  var JobHandlerBase = class {
21
28
  };
22
29
  var JOB_HANDLER_REGISTRY = /* @__PURE__ */ new Map();
23
- var JOB_HANDLER_METADATA_KEY = /* @__PURE__ */ Symbol("JobHandlerMeta");
30
+ var JOB_HANDLER_METADATA_KEY = Symbol.for(tokenKey("jobs", "handler-metadata"));
24
31
  function JobHandler(type, meta) {
25
32
  return (target) => {
26
33
  if (JOB_HANDLER_REGISTRY.has(type)) {
@@ -58,6 +65,7 @@ var HandlerRegistry;
58
65
 
59
66
  // runtime/subsystems/events/events.tokens.ts
60
67
  var EVENT_BUS = "EVENT_BUS";
68
+ var REDIS_URL = Symbol.for(tokenKey("events", "redis-url"));
61
69
 
62
70
  // runtime/subsystems/bridge/bridge.tokens.ts
63
71
  var BRIDGE_DELIVERY_REPO = "BRIDGE_DELIVERY_REPO";