@pattern-stack/codegen 0.6.3 → 0.6.5

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 (67) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +2 -0
  3. package/dist/runtime/subsystems/auth/auth-oauth-state.schema.d.ts +81 -0
  4. package/dist/runtime/subsystems/auth/auth-oauth-state.schema.js +12 -0
  5. package/dist/runtime/subsystems/auth/auth-oauth-state.schema.js.map +1 -0
  6. package/dist/runtime/subsystems/auth/auth.module.d.ts +39 -24
  7. package/dist/runtime/subsystems/auth/auth.module.js +246 -13
  8. package/dist/runtime/subsystems/auth/auth.module.js.map +1 -1
  9. package/dist/runtime/subsystems/auth/auth.tokens.d.ts +15 -2
  10. package/dist/runtime/subsystems/auth/auth.tokens.js +9 -1
  11. package/dist/runtime/subsystems/auth/auth.tokens.js.map +1 -1
  12. package/dist/runtime/subsystems/auth/backends/state-store.drizzle-backend.d.ts +23 -0
  13. package/dist/runtime/subsystems/auth/backends/state-store.drizzle-backend.js +68 -0
  14. package/dist/runtime/subsystems/auth/backends/state-store.drizzle-backend.js.map +1 -0
  15. package/dist/runtime/subsystems/auth/backends/state-store.memory-backend.d.ts +21 -0
  16. package/dist/runtime/subsystems/auth/backends/state-store.memory-backend.js +51 -0
  17. package/dist/runtime/subsystems/auth/backends/state-store.memory-backend.js.map +1 -0
  18. package/dist/runtime/subsystems/auth/controllers/auth.controller.d.ts +31 -0
  19. package/dist/runtime/subsystems/auth/controllers/auth.controller.js +137 -0
  20. package/dist/runtime/subsystems/auth/controllers/auth.controller.js.map +1 -0
  21. package/dist/runtime/subsystems/auth/index.d.ts +13 -4
  22. package/dist/runtime/subsystems/auth/index.js +253 -14
  23. package/dist/runtime/subsystems/auth/index.js.map +1 -1
  24. package/dist/runtime/subsystems/auth/protocols/integration-store.d.ts +36 -1
  25. package/dist/runtime/subsystems/auth/protocols/oauth-state-store.d.ts +33 -7
  26. package/dist/runtime/subsystems/auth/protocols/oauth-state-store.js +12 -0
  27. package/dist/runtime/subsystems/auth/protocols/oauth-state-store.js.map +1 -1
  28. package/dist/runtime/subsystems/auth/protocols/provider-strategy.d.ts +47 -0
  29. package/dist/runtime/subsystems/auth/protocols/provider-strategy.js +1 -0
  30. package/dist/runtime/subsystems/auth/protocols/provider-strategy.js.map +1 -0
  31. package/dist/runtime/subsystems/auth/protocols/user-context.d.ts +24 -0
  32. package/dist/runtime/subsystems/auth/protocols/user-context.js +1 -0
  33. package/dist/runtime/subsystems/auth/protocols/user-context.js.map +1 -0
  34. package/dist/runtime/subsystems/index.d.ts +9 -4
  35. package/dist/runtime/subsystems/index.js +247 -14
  36. package/dist/runtime/subsystems/index.js.map +1 -1
  37. package/dist/src/cli/index.js +578 -143
  38. package/dist/src/cli/index.js.map +1 -1
  39. package/package.json +2 -1
  40. package/runtime/subsystems/auth/auth-oauth-state.schema.ts +30 -0
  41. package/runtime/subsystems/auth/auth.module.ts +89 -32
  42. package/runtime/subsystems/auth/auth.tokens.ts +14 -1
  43. package/runtime/subsystems/auth/backends/state-store.drizzle-backend.ts +83 -0
  44. package/runtime/subsystems/auth/backends/state-store.memory-backend.ts +76 -0
  45. package/runtime/subsystems/auth/controllers/auth.controller.ts +155 -0
  46. package/runtime/subsystems/auth/index.ts +43 -4
  47. package/runtime/subsystems/auth/protocols/integration-store.ts +37 -0
  48. package/runtime/subsystems/auth/protocols/oauth-state-store.ts +38 -6
  49. package/runtime/subsystems/auth/protocols/provider-strategy.ts +41 -0
  50. package/runtime/subsystems/auth/protocols/user-context.ts +22 -0
  51. package/runtime/subsystems/index.ts +17 -2
  52. package/templates/entity/new/backend/modules/core/sync-source.ejs.t +2 -2
  53. package/templates/entity/new/backend/modules/core/sync-source.providers.ejs.t +1 -1
  54. package/templates/entity/new/clean-lite-ps/prompt-extension.js +14 -0
  55. package/templates/entity/new/prompt.js +1 -0
  56. package/templates/subsystem/auth/app-module-hook.ejs.t +21 -0
  57. package/templates/subsystem/auth/auth-oauth-state.schema.ejs.t +35 -0
  58. package/templates/subsystem/auth/env-config.ejs.t +20 -0
  59. package/templates/subsystem/auth/prompt.js +46 -0
  60. package/templates/subsystem/auth-config/codegen-config-auth-block.ejs.t +20 -0
  61. package/templates/subsystem/auth-config/prompt.js +20 -0
  62. package/templates/subsystem/auth-integrations/app-module-hook.ejs.t +16 -0
  63. package/templates/subsystem/auth-integrations/prompt.js +23 -0
  64. package/dist/runtime/subsystems/auth/backends/oauth-state-store/in-memory.d.ts +0 -24
  65. package/dist/runtime/subsystems/auth/backends/oauth-state-store/in-memory.js +0 -24
  66. package/dist/runtime/subsystems/auth/backends/oauth-state-store/in-memory.js.map +0 -1
  67. package/runtime/subsystems/auth/backends/oauth-state-store/in-memory.ts +0 -42
package/CHANGELOG.md CHANGED
@@ -4,6 +4,28 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.6.5] — 2026-04-27
8
+
9
+ Auth subsystem reaches consumers. `runtime/subsystems/auth/`, the `auth-integrations` starter, and the `cdp subsystem install auth` + `auth-integrations` templates were all merged on `main` (PRs #289, #290, #292, #293, #294, #295) but the published artifact was still pinned at `0.6.4`. This release ships them.
10
+
11
+ ### Added
12
+
13
+ - **`feat(auth)` #289** — provider-agnostic `AuthController` mounting `GET /auth/:provider/connect` and `GET /auth/:provider/callback`, plus the `IUserContext` / `IOAuthStateStore` / `IIntegrationGrantSink` ports and memory + drizzle state-store backends. `OAuth2RefreshStrategy` extracted as a template-method base class. See `runtime/subsystems/auth/`.
14
+ - **`feat(examples)` #290** — `examples/auth-integrations/` starter: canonical `integration.yaml` entity + adapters that satisfy the three `AUTH_INTEGRATION_*` ports + `IntegrationsService` facade.
15
+ - **`feat(cdp)` #293** — `cdp subsystem install auth` and `cdp subsystem install auth-integrations` templates. The auth template emits `auth_oauth_state` drizzle schema, appends `TOKEN_ENCRYPTION_KEY` + `AUTH_REDIRECT_URI_BASE` to `.env.config`, and drops a TODO into `app.module.ts`. `auth-integrations` vendors the starter under `apps/api/src/shared/integrations/`.
16
+
17
+ ## [0.6.4] — 2026-04-27
18
+
19
+ Two consumer-DX fixes surfaced by a fresh `cdp project init` run.
20
+
21
+ ### Fixed
22
+
23
+ - **`fix(init)` #277** — typed the empty `GENERATED_MODULES` barrel emitted by `cdp project init`. The scaffold previously emitted `export const GENERATED_MODULES: unknown[] = []`, which fails `tsc --noEmit` against the scaffolded `app.module.ts` (`...GENERATED_MODULES` spread doesn't satisfy NestJS's `imports:` type) on day one of any new consumer project. Now typed as `Array<Type | DynamicModule | Promise<DynamicModule> | ForwardReference>`. Entity-populated barrels remain unaffected — class refs already satisfy `Type`.
24
+
25
+ ### Changed
26
+
27
+ - **`fix(bin)` #277** — added `codegen` as the primary bin name in `package.json`. The previous bin name `cdp` collides with an unrelated published npm package, so `bunx cdp ...` (without a local install) silently fetches and runs the wrong package. The CLI banner, README, and downstream docs all already refer to the binary as `codegen`. `cdp` is preserved as an alias for backwards compatibility.
28
+
7
29
  ## [0.6.3] — 2026-04-26
8
30
 
9
31
  ### Fixed
package/README.md CHANGED
@@ -97,6 +97,8 @@ codegen subsystem install storage # file storage (local filesystem)
97
97
  codegen subsystem install sync # external-system sync engine (IChangeSource + orchestrator + audit log)
98
98
  codegen subsystem install bridge # event-to-job bridge (durable async fanout via @JobHandler.triggers)
99
99
  codegen subsystem install openapi-config # OpenAPI/Swagger — Zod DTOs as /docs-json + Swagger UI. See docs/CONSUMER-SETUP.md §OpenAPI
100
+ codegen subsystem install auth # OAuth integration auth (AuthModule + ports + state store + AuthController)
101
+ codegen subsystem install auth-integrations # vendored integrations entity + adapters (consumes auth subsystem)
100
102
  codegen subsystem list # show installed + available
101
103
 
102
104
  codegen events consumers <type> # list all Tier 1/2/3 consumers of an event type
@@ -0,0 +1,81 @@
1
+ import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
2
+ import { InferSelectModel } from 'drizzle-orm';
3
+
4
+ declare const authOAuthState: drizzle_orm_pg_core.PgTableWithColumns<{
5
+ name: "auth_oauth_state";
6
+ schema: undefined;
7
+ columns: {
8
+ state: drizzle_orm_pg_core.PgColumn<{
9
+ name: "state";
10
+ tableName: "auth_oauth_state";
11
+ dataType: "string";
12
+ columnType: "PgText";
13
+ data: string;
14
+ driverParam: string;
15
+ notNull: true;
16
+ hasDefault: false;
17
+ isPrimaryKey: true;
18
+ isAutoincrement: false;
19
+ hasRuntimeDefault: false;
20
+ enumValues: [string, ...string[]];
21
+ baseColumn: never;
22
+ identity: undefined;
23
+ generated: undefined;
24
+ }, {}, {}>;
25
+ userId: drizzle_orm_pg_core.PgColumn<{
26
+ name: "user_id";
27
+ tableName: "auth_oauth_state";
28
+ dataType: "string";
29
+ columnType: "PgText";
30
+ data: string;
31
+ driverParam: string;
32
+ notNull: true;
33
+ hasDefault: false;
34
+ isPrimaryKey: false;
35
+ isAutoincrement: false;
36
+ hasRuntimeDefault: false;
37
+ enumValues: [string, ...string[]];
38
+ baseColumn: never;
39
+ identity: undefined;
40
+ generated: undefined;
41
+ }, {}, {}>;
42
+ redirect: drizzle_orm_pg_core.PgColumn<{
43
+ name: "redirect";
44
+ tableName: "auth_oauth_state";
45
+ dataType: "string";
46
+ columnType: "PgText";
47
+ data: string;
48
+ driverParam: string;
49
+ notNull: false;
50
+ hasDefault: false;
51
+ isPrimaryKey: false;
52
+ isAutoincrement: false;
53
+ hasRuntimeDefault: false;
54
+ enumValues: [string, ...string[]];
55
+ baseColumn: never;
56
+ identity: undefined;
57
+ generated: undefined;
58
+ }, {}, {}>;
59
+ expiresAt: drizzle_orm_pg_core.PgColumn<{
60
+ name: "expires_at";
61
+ tableName: "auth_oauth_state";
62
+ dataType: "date";
63
+ columnType: "PgTimestamp";
64
+ data: Date;
65
+ driverParam: string;
66
+ notNull: true;
67
+ hasDefault: false;
68
+ isPrimaryKey: false;
69
+ isAutoincrement: false;
70
+ hasRuntimeDefault: false;
71
+ enumValues: undefined;
72
+ baseColumn: never;
73
+ identity: undefined;
74
+ generated: undefined;
75
+ }, {}, {}>;
76
+ };
77
+ dialect: "pg";
78
+ }>;
79
+ type AuthOAuthState = InferSelectModel<typeof authOAuthState>;
80
+
81
+ export { type AuthOAuthState, authOAuthState };
@@ -0,0 +1,12 @@
1
+ // runtime/subsystems/auth/auth-oauth-state.schema.ts
2
+ import { pgTable, text, timestamp } from "drizzle-orm/pg-core";
3
+ var authOAuthState = pgTable("auth_oauth_state", {
4
+ state: text("state").primaryKey(),
5
+ userId: text("user_id").notNull(),
6
+ redirect: text("redirect"),
7
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull()
8
+ });
9
+ export {
10
+ authOAuthState
11
+ };
12
+ //# sourceMappingURL=auth-oauth-state.schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../runtime/subsystems/auth/auth-oauth-state.schema.ts"],"sourcesContent":["/**\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`, `sync-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"],"mappings":";AAmBA,SAAS,SAAS,MAAM,iBAAiB;AAGlC,IAAM,iBAAiB,QAAQ,oBAAoB;AAAA,EACxD,OAAO,KAAK,OAAO,EAAE,WAAW;AAAA,EAChC,QAAQ,KAAK,SAAS,EAAE,QAAQ;AAAA,EAChC,UAAU,KAAK,UAAU;AAAA,EACzB,WAAW,UAAU,cAAc,EAAE,cAAc,KAAK,CAAC,EAAE,QAAQ;AACrE,CAAC;","names":[]}
@@ -3,48 +3,63 @@ import { Provider, DynamicModule } from '@nestjs/common';
3
3
  /**
4
4
  * AuthModule — DynamicModule factory for the auth subsystem.
5
5
  *
6
- * Wires the two pluggable backends the subsystem ships with:
7
- * - `ENCRYPTION_KEY` → `EnvEncryptionKey` (AES-256-GCM from env)
8
- * - `OAUTH_STATE_STORE` → `InMemoryOAuthStateStore` (dev) / custom Redis impl (prod)
6
+ * Wires the pluggable backends the subsystem ships with:
7
+ * - `ENCRYPTION_KEY` → `EnvEncryptionKey` (AES-256-GCM from env)
8
+ * - `OAUTH_STATE_STORE` → `MemoryOAuthStateStore` (dev/tests) or
9
+ * `DrizzleOAuthStateStore` (prod, requires
10
+ * DRIZZLE provider).
11
+ * - `AUTH_OPTIONS` → resolved options bag (used by AuthController
12
+ * for `redirectUriBase`).
9
13
  *
10
- * The two integration-store ports (`AUTH_INTEGRATION_READER`,
11
- * `AUTH_INTEGRATION_TOKEN_WRITER`) are deliberately **not** wired by this
12
- * module they are always consumer-specific (adapters over the app's own
13
- * integrations entity/service). Consumers provide them in the module that
14
- * owns the integrations domain, not here.
14
+ * The integration-store ports (`AUTH_INTEGRATION_READER`,
15
+ * `AUTH_INTEGRATION_TOKEN_WRITER`, `AUTH_INTEGRATION_GRANT_SINK`),
16
+ * `AUTH_USER_CONTEXT`, and `STRATEGY_REGISTRY` are deliberately **not**
17
+ * wired here they are always consumer-specific:
18
+ * - integration-store ports adapt the consumer's `integrations` storage;
19
+ * - `IUserContext` adapts the app's session/JWT scheme;
20
+ * - `STRATEGY_REGISTRY` is populated from the per-provider strategy
21
+ * classes the consumer maintains.
15
22
  *
16
- * `IAuthStrategy` implementations are also per-provider and live in the
17
- * integration module that uses them (`SalesforceModule`, `HubSpotModule`, …).
18
- * The subsystem provides the abstract base class
19
- * (`OAuth2RefreshStrategy`) — binding concrete strategies is an app concern.
23
+ * Consumers provide them in their app module (or by importing the
24
+ * `auth-integrations` starter, which binds the three integration-store
25
+ * ports off a single canonical entity).
20
26
  *
21
27
  * Usage in AppModule:
22
28
  * ```typescript
23
29
  * AuthModule.forRoot({
24
30
  * encryptionKey: 'env',
25
- * oauthStateStore: 'in-memory',
26
- * });
27
- * ```
28
- *
29
- * Or inject custom providers directly:
30
- * ```typescript
31
- * AuthModule.forRoot({
32
- * encryptionKey: { useClass: MyKmsEncryptionKey },
33
- * oauthStateStore: { useClass: RedisOAuthStateStore },
31
+ * oauthStateStore: 'memory', // or 'drizzle'
32
+ * enableController: true,
33
+ * redirectUriBase: 'http://localhost:3000',
34
34
  * });
35
35
  * ```
36
36
  *
37
37
  * `global: true` means other modules don't need to re-import AuthModule to
38
- * inject `ENCRYPTION_KEY` / `OAUTH_STATE_STORE`.
38
+ * inject the auth tokens.
39
39
  */
40
40
 
41
41
  type EncryptionKeyChoice = 'env' | Omit<Provider, 'provide'>;
42
- type OAuthStateStoreChoice = 'in-memory' | Omit<Provider, 'provide'>;
42
+ type OAuthStateStoreChoice = 'memory' | 'drizzle' | Omit<Provider, 'provide'>;
43
43
  interface AuthModuleOptions {
44
44
  /** `'env'` (default) or a full provider definition (e.g. `{ useClass: MyKmsEncryptionKey }`). */
45
45
  encryptionKey?: EncryptionKeyChoice;
46
- /** `'in-memory'` (default) or a full provider definition for a Redis/DB impl. */
46
+ /**
47
+ * `'memory'` (default — tests/dev) or `'drizzle'` (prod, requires DRIZZLE
48
+ * provider) or a full provider definition for a custom impl.
49
+ */
47
50
  oauthStateStore?: OAuthStateStoreChoice;
51
+ /**
52
+ * Mount `AuthController` (`/auth/:provider/connect` + `/callback`).
53
+ * Default `false` — apps that hand-roll connect/callback (rare) or that
54
+ * use the subsystem only for the refresh path can opt out.
55
+ */
56
+ enableController?: boolean;
57
+ /**
58
+ * Public base URL of the API server. Used to construct per-provider
59
+ * callback URIs as `${redirectUriBase}/auth/:provider/callback`.
60
+ * Required when `enableController: true`.
61
+ */
62
+ redirectUriBase?: string;
48
63
  }
49
64
  declare class AuthModule {
50
65
  static forRoot(options?: AuthModuleOptions): DynamicModule;
@@ -8,6 +8,7 @@ var __decorateClass = (decorators, target, key, kind) => {
8
8
  if (kind && result) __defProp(target, key, result);
9
9
  return result;
10
10
  };
11
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
11
12
 
12
13
  // runtime/subsystems/auth/auth.module.ts
13
14
  import { Module } from "@nestjs/common";
@@ -15,6 +16,10 @@ import { Module } from "@nestjs/common";
15
16
  // runtime/subsystems/auth/auth.tokens.ts
16
17
  var ENCRYPTION_KEY = /* @__PURE__ */ Symbol("ENCRYPTION_KEY");
17
18
  var OAUTH_STATE_STORE = /* @__PURE__ */ Symbol("OAUTH_STATE_STORE");
19
+ var AUTH_INTEGRATION_GRANT_SINK = /* @__PURE__ */ Symbol("AUTH_INTEGRATION_GRANT_SINK");
20
+ var AUTH_USER_CONTEXT = /* @__PURE__ */ Symbol("AUTH_USER_CONTEXT");
21
+ var STRATEGY_REGISTRY = /* @__PURE__ */ Symbol("STRATEGY_REGISTRY");
22
+ var AUTH_OPTIONS = /* @__PURE__ */ Symbol("AUTH_OPTIONS");
18
23
 
19
24
  // runtime/subsystems/auth/backends/encryption-key/env.ts
20
25
  import { createCipheriv, createDecipheriv, randomBytes } from "crypto";
@@ -66,26 +71,224 @@ var EnvEncryptionKey = class {
66
71
  }
67
72
  };
68
73
 
69
- // runtime/subsystems/auth/backends/oauth-state-store/in-memory.ts
70
- var InMemoryOAuthStateStore = class {
74
+ // runtime/subsystems/auth/backends/state-store.memory-backend.ts
75
+ import { randomBytes as randomBytes2 } from "crypto";
76
+
77
+ // runtime/subsystems/auth/protocols/oauth-state-store.ts
78
+ var OAuthStateError = class extends Error {
79
+ constructor(message, reason) {
80
+ super(message);
81
+ this.reason = reason;
82
+ this.name = "OAuthStateError";
83
+ }
84
+ reason;
85
+ };
86
+
87
+ // runtime/subsystems/auth/backends/state-store.memory-backend.ts
88
+ var MemoryOAuthStateStore = class {
71
89
  store = /* @__PURE__ */ new Map();
72
90
  ttlMs;
73
91
  now;
92
+ generateToken;
74
93
  constructor(opts = {}) {
75
94
  this.ttlMs = opts.ttlMs ?? 10 * 60 * 1e3;
76
95
  this.now = opts.now ?? (() => Date.now());
96
+ this.generateToken = opts.generateToken ?? (() => randomBytes2(32).toString("base64url"));
77
97
  }
78
- async put(state, entry) {
79
- this.store.set(state, { entry, expiresAt: this.now() + this.ttlMs });
98
+ async generate(record) {
99
+ const state = this.generateToken();
100
+ this.store.set(state, {
101
+ record: { ...record },
102
+ expiresAt: this.now() + this.ttlMs
103
+ });
104
+ return state;
80
105
  }
81
106
  async consume(state) {
82
107
  const slot = this.store.get(state);
83
- if (!slot) return null;
108
+ if (!slot) {
109
+ throw new OAuthStateError(
110
+ `OAuth state token unknown or already consumed`,
111
+ "missing"
112
+ );
113
+ }
84
114
  this.store.delete(state);
85
- if (slot.expiresAt <= this.now()) return null;
86
- return slot.entry;
115
+ if (slot.expiresAt <= this.now()) {
116
+ throw new OAuthStateError(`OAuth state token expired`, "expired");
117
+ }
118
+ return slot.record;
119
+ }
120
+ };
121
+
122
+ // runtime/subsystems/auth/backends/state-store.drizzle-backend.ts
123
+ import { randomBytes as randomBytes3 } from "crypto";
124
+ import { eq } from "drizzle-orm";
125
+
126
+ // runtime/subsystems/auth/auth-oauth-state.schema.ts
127
+ import { pgTable, text, timestamp } from "drizzle-orm/pg-core";
128
+ var authOAuthState = pgTable("auth_oauth_state", {
129
+ state: text("state").primaryKey(),
130
+ userId: text("user_id").notNull(),
131
+ redirect: text("redirect"),
132
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull()
133
+ });
134
+
135
+ // runtime/subsystems/auth/backends/state-store.drizzle-backend.ts
136
+ var DrizzleOAuthStateStore = class {
137
+ constructor(db, opts = {}) {
138
+ this.db = db;
139
+ this.ttlMs = opts.ttlMs ?? 10 * 60 * 1e3;
140
+ this.now = opts.now ?? (() => Date.now());
141
+ this.generateToken = opts.generateToken ?? (() => randomBytes3(32).toString("base64url"));
142
+ }
143
+ db;
144
+ ttlMs;
145
+ now;
146
+ generateToken;
147
+ async generate(record) {
148
+ const state = this.generateToken();
149
+ const expiresAt = new Date(this.now() + this.ttlMs);
150
+ await this.db.insert(authOAuthState).values({
151
+ state,
152
+ userId: record.userId,
153
+ redirect: record.redirect ?? null,
154
+ expiresAt
155
+ });
156
+ return state;
157
+ }
158
+ async consume(state) {
159
+ const rows = await this.db.delete(authOAuthState).where(eq(authOAuthState.state, state)).returning();
160
+ const row = rows[0];
161
+ if (!row) {
162
+ throw new OAuthStateError(
163
+ `OAuth state token unknown or already consumed`,
164
+ "missing"
165
+ );
166
+ }
167
+ if (row.expiresAt.getTime() <= this.now()) {
168
+ throw new OAuthStateError(`OAuth state token expired`, "expired");
169
+ }
170
+ return {
171
+ userId: row.userId,
172
+ redirect: row.redirect ?? void 0
173
+ };
174
+ }
175
+ };
176
+
177
+ // runtime/subsystems/auth/controllers/auth.controller.ts
178
+ import {
179
+ Controller,
180
+ Get,
181
+ Inject,
182
+ Param,
183
+ Query,
184
+ Req,
185
+ Res,
186
+ HttpException,
187
+ HttpStatus
188
+ } from "@nestjs/common";
189
+ var AuthController = class {
190
+ constructor(registry, userContext, stateStore, grantSink, options) {
191
+ this.registry = registry;
192
+ this.userContext = userContext;
193
+ this.stateStore = stateStore;
194
+ this.grantSink = grantSink;
195
+ this.options = options;
196
+ }
197
+ registry;
198
+ userContext;
199
+ stateStore;
200
+ grantSink;
201
+ options;
202
+ async connect(slug, redirect, req, res) {
203
+ const strategy = this.requireStrategy(slug);
204
+ const userId = await this.userContext.getCurrentUserId(req);
205
+ const state = await this.stateStore.generate({ userId, redirect });
206
+ const url = strategy.buildAuthorizeUrl({
207
+ state,
208
+ redirectUri: this.redirectUriFor(slug)
209
+ });
210
+ return res.redirect(HttpStatus.FOUND, url);
211
+ }
212
+ async callback(slug, code, state, res) {
213
+ const strategy = this.requireStrategy(slug);
214
+ if (!code) {
215
+ throw new HttpException(
216
+ `Missing 'code' query param`,
217
+ HttpStatus.BAD_REQUEST
218
+ );
219
+ }
220
+ if (!state) {
221
+ throw new HttpException(
222
+ `Missing 'state' query param`,
223
+ HttpStatus.BAD_REQUEST
224
+ );
225
+ }
226
+ const { userId, redirect } = await this.stateStore.consume(state);
227
+ const tokens = await strategy.exchangeCodeForTokens({
228
+ code,
229
+ redirectUri: this.redirectUriFor(slug)
230
+ });
231
+ await this.grantSink.createOrUpdateFromOAuthGrant({
232
+ userId,
233
+ provider: slug,
234
+ accessToken: tokens.accessToken,
235
+ refreshToken: tokens.refreshToken,
236
+ expiresAt: tokens.expiresAt,
237
+ scope: tokens.scope,
238
+ externalAccountId: tokens.externalAccountId,
239
+ providerMetadata: tokens.providerMetadata
240
+ });
241
+ return res.redirect(
242
+ HttpStatus.FOUND,
243
+ redirect ?? `/settings/integrations?connected=${encodeURIComponent(slug)}`
244
+ );
245
+ }
246
+ requireStrategy(slug) {
247
+ const strategy = this.registry.get(slug);
248
+ if (!strategy) {
249
+ throw new HttpException(
250
+ `Unknown provider '${slug}'`,
251
+ HttpStatus.NOT_FOUND
252
+ );
253
+ }
254
+ return strategy;
255
+ }
256
+ redirectUriFor(slug) {
257
+ const base = this.options.redirectUriBase;
258
+ if (!base) {
259
+ throw new Error(
260
+ `AuthModule.forRoot: redirectUriBase is required when AuthController is enabled`
261
+ );
262
+ }
263
+ const trimmed = base.replace(/\/+$/, "");
264
+ return `${trimmed}/auth/${encodeURIComponent(slug)}/callback`;
87
265
  }
88
266
  };
267
+ __decorateClass([
268
+ Get(":provider/connect"),
269
+ __decorateParam(0, Param("provider")),
270
+ __decorateParam(1, Query("redirect")),
271
+ __decorateParam(2, Req()),
272
+ __decorateParam(3, Res())
273
+ ], AuthController.prototype, "connect", 1);
274
+ __decorateClass([
275
+ Get(":provider/callback"),
276
+ __decorateParam(0, Param("provider")),
277
+ __decorateParam(1, Query("code")),
278
+ __decorateParam(2, Query("state")),
279
+ __decorateParam(3, Res())
280
+ ], AuthController.prototype, "callback", 1);
281
+ AuthController = __decorateClass([
282
+ Controller("auth"),
283
+ __decorateParam(0, Inject(STRATEGY_REGISTRY)),
284
+ __decorateParam(1, Inject(AUTH_USER_CONTEXT)),
285
+ __decorateParam(2, Inject(OAUTH_STATE_STORE)),
286
+ __decorateParam(3, Inject(AUTH_INTEGRATION_GRANT_SINK)),
287
+ __decorateParam(4, Inject(AUTH_OPTIONS))
288
+ ], AuthController);
289
+
290
+ // runtime/constants/tokens.ts
291
+ var DRIZZLE = "DRIZZLE";
89
292
 
90
293
  // runtime/subsystems/auth/auth.module.ts
91
294
  function resolveEncryptionKeyProvider(choice) {
@@ -95,24 +298,54 @@ function resolveEncryptionKeyProvider(choice) {
95
298
  return { provide: ENCRYPTION_KEY, ...choice };
96
299
  }
97
300
  function resolveOAuthStateStoreProvider(choice) {
98
- if (choice === "in-memory") {
99
- return { provide: OAUTH_STATE_STORE, useClass: InMemoryOAuthStateStore };
301
+ if (choice === "memory") {
302
+ return { provide: OAUTH_STATE_STORE, useClass: MemoryOAuthStateStore };
303
+ }
304
+ if (choice === "drizzle") {
305
+ return {
306
+ provide: OAUTH_STATE_STORE,
307
+ useFactory: (db) => {
308
+ if (!db) {
309
+ throw new Error(
310
+ "AuthModule.forRoot: oauthStateStore: 'drizzle' selected but DRIZZLE provider is not available. Ensure DatabaseModule (or another provider exposing DRIZZLE) is imported before AuthModule.forRoot."
311
+ );
312
+ }
313
+ return new DrizzleOAuthStateStore(db);
314
+ },
315
+ inject: [{ token: DRIZZLE, optional: true }]
316
+ };
100
317
  }
101
318
  return { provide: OAUTH_STATE_STORE, ...choice };
102
319
  }
103
320
  var AuthModule = class {
104
321
  static forRoot(options = {}) {
322
+ const resolved = {
323
+ encryptionKey: options.encryptionKey ?? "env",
324
+ oauthStateStore: options.oauthStateStore ?? "memory",
325
+ enableController: options.enableController ?? false,
326
+ redirectUriBase: options.redirectUriBase
327
+ };
328
+ if (resolved.enableController && !resolved.redirectUriBase) {
329
+ throw new Error(
330
+ "AuthModule.forRoot: redirectUriBase is required when enableController: true"
331
+ );
332
+ }
105
333
  const encryptionKeyProvider = resolveEncryptionKeyProvider(
106
- options.encryptionKey ?? "env"
334
+ resolved.encryptionKey
107
335
  );
108
336
  const oauthStateStoreProvider = resolveOAuthStateStoreProvider(
109
- options.oauthStateStore ?? "in-memory"
337
+ resolved.oauthStateStore
110
338
  );
339
+ const optionsProvider = {
340
+ provide: AUTH_OPTIONS,
341
+ useValue: resolved
342
+ };
111
343
  return {
112
344
  module: AuthModule,
113
345
  global: true,
114
- providers: [encryptionKeyProvider, oauthStateStoreProvider],
115
- exports: [ENCRYPTION_KEY, OAUTH_STATE_STORE]
346
+ providers: [encryptionKeyProvider, oauthStateStoreProvider, optionsProvider],
347
+ controllers: resolved.enableController ? [AuthController] : [],
348
+ exports: [ENCRYPTION_KEY, OAUTH_STATE_STORE, AUTH_OPTIONS]
116
349
  };
117
350
  }
118
351
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../runtime/subsystems/auth/auth.module.ts","../../../../runtime/subsystems/auth/auth.tokens.ts","../../../../runtime/subsystems/auth/backends/encryption-key/env.ts","../../../../runtime/subsystems/auth/backends/oauth-state-store/in-memory.ts"],"sourcesContent":["/**\n * AuthModule — DynamicModule factory for the auth subsystem.\n *\n * Wires the two pluggable backends the subsystem ships with:\n * - `ENCRYPTION_KEY` → `EnvEncryptionKey` (AES-256-GCM from env)\n * - `OAUTH_STATE_STORE` → `InMemoryOAuthStateStore` (dev) / custom Redis impl (prod)\n *\n * The two integration-store ports (`AUTH_INTEGRATION_READER`,\n * `AUTH_INTEGRATION_TOKEN_WRITER`) are deliberately **not** wired by this\n * module — they are always consumer-specific (adapters over the app's own\n * integrations entity/service). Consumers provide them in the module that\n * owns the integrations domain, not here.\n *\n * `IAuthStrategy` implementations are also per-provider and live in the\n * integration module that uses them (`SalesforceModule`, `HubSpotModule`, …).\n * The subsystem provides the abstract base class\n * (`OAuth2RefreshStrategy`) — binding concrete strategies is an app concern.\n *\n * Usage in AppModule:\n * ```typescript\n * AuthModule.forRoot({\n * encryptionKey: 'env',\n * oauthStateStore: 'in-memory',\n * });\n * ```\n *\n * Or inject custom providers directly:\n * ```typescript\n * AuthModule.forRoot({\n * encryptionKey: { useClass: MyKmsEncryptionKey },\n * oauthStateStore: { useClass: RedisOAuthStateStore },\n * });\n * ```\n *\n * `global: true` means other modules don't need to re-import AuthModule to\n * inject `ENCRYPTION_KEY` / `OAUTH_STATE_STORE`.\n */\nimport { Module, type DynamicModule, type Provider } from '@nestjs/common';\nimport { ENCRYPTION_KEY, OAUTH_STATE_STORE } from './auth.tokens';\nimport { EnvEncryptionKey } from './backends/encryption-key/env';\nimport { InMemoryOAuthStateStore } from './backends/oauth-state-store/in-memory';\n\ntype EncryptionKeyChoice =\n | 'env'\n | Omit<Provider, 'provide'>;\n\ntype OAuthStateStoreChoice =\n | 'in-memory'\n | Omit<Provider, 'provide'>;\n\nexport interface AuthModuleOptions {\n /** `'env'` (default) or a full provider definition (e.g. `{ useClass: MyKmsEncryptionKey }`). */\n encryptionKey?: EncryptionKeyChoice;\n /** `'in-memory'` (default) or a full provider definition for a Redis/DB impl. */\n oauthStateStore?: OAuthStateStoreChoice;\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 === 'in-memory') {\n return { provide: OAUTH_STATE_STORE, useClass: InMemoryOAuthStateStore };\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 encryptionKeyProvider = resolveEncryptionKeyProvider(\n options.encryptionKey ?? 'env',\n );\n const oauthStateStoreProvider = resolveOAuthStateStoreProvider(\n options.oauthStateStore ?? 'in-memory',\n );\n\n return {\n module: AuthModule,\n global: true,\n providers: [encryptionKeyProvider, oauthStateStoreProvider],\n exports: [ENCRYPTION_KEY, OAUTH_STATE_STORE],\n };\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_INTEGRATION_READER) private readonly reader: IIntegrationReader,\n * @Inject(AUTH_INTEGRATION_TOKEN_WRITER) private readonly writer: IIntegrationTokenWriter,\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 integration module — this subsystem does\n * not mandate a single `AUTH_STRATEGY` token because an app typically has\n * many concurrent strategies, one per provider.\n */\nexport const ENCRYPTION_KEY = Symbol('ENCRYPTION_KEY');\nexport const OAUTH_STATE_STORE = Symbol('OAUTH_STATE_STORE');\nexport const AUTH_INTEGRATION_READER = Symbol('AUTH_INTEGRATION_READER');\nexport const AUTH_INTEGRATION_TOKEN_WRITER = Symbol('AUTH_INTEGRATION_TOKEN_WRITER');\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: `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 `'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 ?? '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 OAuth state store.\n *\n * Single-process dev store. Production deployments need a Redis-backed impl\n * (follow-up) so state survives restarts + is shared across workers.\n */\nimport type {\n IOAuthStateStore,\n OAuthStateEntry,\n} from '../../protocols/oauth-state-store';\n\nexport interface InMemoryOAuthStateStoreOptions {\n /** TTL in ms. Entries older than this are treated as absent. Default 10min. */\n ttlMs?: number;\n now?: () => number;\n}\n\nexport class InMemoryOAuthStateStore implements IOAuthStateStore {\n private readonly store = new Map<\n string,\n { entry: OAuthStateEntry; expiresAt: number }\n >();\n private readonly ttlMs: number;\n private readonly now: () => number;\n\n constructor(opts: InMemoryOAuthStateStoreOptions = {}) {\n this.ttlMs = opts.ttlMs ?? 10 * 60 * 1000;\n this.now = opts.now ?? (() => Date.now());\n }\n\n async put(state: string, entry: OAuthStateEntry): Promise<void> {\n this.store.set(state, { entry, expiresAt: this.now() + this.ttlMs });\n }\n\n async consume(state: string): Promise<OAuthStateEntry | null> {\n const slot = this.store.get(state);\n if (!slot) return null;\n this.store.delete(state);\n if (slot.expiresAt <= this.now()) return null;\n return slot.entry;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAqCA,SAAS,cAAiD;;;ACdnD,IAAM,iBAAiB,uBAAO,gBAAgB;AAC9C,IAAM,oBAAoB,uBAAO,mBAAmB;;;ACV3D,SAAS,gBAAgB,kBAAkB,mBAAmB;AAU9D,IAAM,OAAO;AACb,IAAM,cAAc;AACpB,IAAM,YAAY;AAClB,IAAM,YAAY;AAEX,IAAM,mBAAN,MAAiD;AAAA,EACrC;AAAA,EAEjB,YAAY,OAAgC,CAAC,GAAG;A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AAiB;AAAA,IAC7C;AAAA,EACF;AACF;AAhBa,aAAN;AAAA,EADN,OAAO,CAAC,CAAC;AAAA,GACG;","names":[]}
1
+ {"version":3,"sources":["../../../../runtime/subsystems/auth/auth.module.ts","../../../../runtime/subsystems/auth/auth.tokens.ts","../../../../runtime/subsystems/auth/backends/encryption-key/env.ts","../../../../runtime/subsystems/auth/backends/state-store.memory-backend.ts","../../../../runtime/subsystems/auth/protocols/oauth-state-store.ts","../../../../runtime/subsystems/auth/backends/state-store.drizzle-backend.ts","../../../../runtime/subsystems/auth/auth-oauth-state.schema.ts","../../../../runtime/subsystems/auth/controllers/auth.controller.ts","../../../../runtime/constants/tokens.ts"],"sourcesContent":["/**\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 integration-store ports (`AUTH_INTEGRATION_READER`,\n * `AUTH_INTEGRATION_TOKEN_WRITER`, `AUTH_INTEGRATION_GRANT_SINK`),\n * `AUTH_USER_CONTEXT`, and `STRATEGY_REGISTRY` are deliberately **not**\n * wired here — they are always consumer-specific:\n * - integration-store ports adapt the consumer's `integrations` 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 integration-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 * 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_INTEGRATION_READER) private readonly reader: IIntegrationReader,\n * @Inject(AUTH_INTEGRATION_TOKEN_WRITER) private readonly writer: IIntegrationTokenWriter,\n * @Inject(AUTH_INTEGRATION_GRANT_SINK) private readonly grants: IIntegrationGrantSink,\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 integration 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, ProviderStrategy>`), 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_INTEGRATION_READER = Symbol('AUTH_INTEGRATION_READER');\nexport const AUTH_INTEGRATION_TOKEN_WRITER = Symbol('AUTH_INTEGRATION_TOKEN_WRITER');\nexport const AUTH_INTEGRATION_GRANT_SINK = Symbol('AUTH_INTEGRATION_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 * 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: `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 `'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 ?? '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 * 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 * 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 * 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`, `sync-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 * 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, ProviderStrategy>) — 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_INTEGRATION_GRANT_SINK` (IIntegrationGrantSink) — 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 `IntegrationsService` 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_INTEGRATION_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 ProviderStrategy,\n ProviderStrategyRegistry,\n} from '../protocols/provider-strategy';\nimport type { IIntegrationGrantSink } from '../protocols/integration-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_INTEGRATION_GRANT_SINK)\n private readonly grantSink: IIntegrationGrantSink,\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/integrations?connected=${encodeURIComponent(slug)}`,\n );\n }\n\n private requireStrategy(slug: string): ProviderStrategy {\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 * 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":";;;;;;;;;;;;;AAqCA,SAAS,cAAiD;;;ACTnD,IAA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