@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.
- package/CHANGELOG.md +22 -0
- package/README.md +2 -0
- package/dist/runtime/subsystems/auth/auth-oauth-state.schema.d.ts +81 -0
- package/dist/runtime/subsystems/auth/auth-oauth-state.schema.js +12 -0
- package/dist/runtime/subsystems/auth/auth-oauth-state.schema.js.map +1 -0
- package/dist/runtime/subsystems/auth/auth.module.d.ts +39 -24
- package/dist/runtime/subsystems/auth/auth.module.js +246 -13
- package/dist/runtime/subsystems/auth/auth.module.js.map +1 -1
- package/dist/runtime/subsystems/auth/auth.tokens.d.ts +15 -2
- package/dist/runtime/subsystems/auth/auth.tokens.js +9 -1
- package/dist/runtime/subsystems/auth/auth.tokens.js.map +1 -1
- package/dist/runtime/subsystems/auth/backends/state-store.drizzle-backend.d.ts +23 -0
- package/dist/runtime/subsystems/auth/backends/state-store.drizzle-backend.js +68 -0
- package/dist/runtime/subsystems/auth/backends/state-store.drizzle-backend.js.map +1 -0
- package/dist/runtime/subsystems/auth/backends/state-store.memory-backend.d.ts +21 -0
- package/dist/runtime/subsystems/auth/backends/state-store.memory-backend.js +51 -0
- package/dist/runtime/subsystems/auth/backends/state-store.memory-backend.js.map +1 -0
- package/dist/runtime/subsystems/auth/controllers/auth.controller.d.ts +31 -0
- package/dist/runtime/subsystems/auth/controllers/auth.controller.js +137 -0
- package/dist/runtime/subsystems/auth/controllers/auth.controller.js.map +1 -0
- package/dist/runtime/subsystems/auth/index.d.ts +13 -4
- package/dist/runtime/subsystems/auth/index.js +253 -14
- package/dist/runtime/subsystems/auth/index.js.map +1 -1
- package/dist/runtime/subsystems/auth/protocols/integration-store.d.ts +36 -1
- package/dist/runtime/subsystems/auth/protocols/oauth-state-store.d.ts +33 -7
- package/dist/runtime/subsystems/auth/protocols/oauth-state-store.js +12 -0
- package/dist/runtime/subsystems/auth/protocols/oauth-state-store.js.map +1 -1
- package/dist/runtime/subsystems/auth/protocols/provider-strategy.d.ts +47 -0
- package/dist/runtime/subsystems/auth/protocols/provider-strategy.js +1 -0
- package/dist/runtime/subsystems/auth/protocols/provider-strategy.js.map +1 -0
- package/dist/runtime/subsystems/auth/protocols/user-context.d.ts +24 -0
- package/dist/runtime/subsystems/auth/protocols/user-context.js +1 -0
- package/dist/runtime/subsystems/auth/protocols/user-context.js.map +1 -0
- package/dist/runtime/subsystems/index.d.ts +9 -4
- package/dist/runtime/subsystems/index.js +247 -14
- package/dist/runtime/subsystems/index.js.map +1 -1
- package/dist/src/cli/index.js +578 -143
- package/dist/src/cli/index.js.map +1 -1
- package/package.json +2 -1
- package/runtime/subsystems/auth/auth-oauth-state.schema.ts +30 -0
- package/runtime/subsystems/auth/auth.module.ts +89 -32
- package/runtime/subsystems/auth/auth.tokens.ts +14 -1
- package/runtime/subsystems/auth/backends/state-store.drizzle-backend.ts +83 -0
- package/runtime/subsystems/auth/backends/state-store.memory-backend.ts +76 -0
- package/runtime/subsystems/auth/controllers/auth.controller.ts +155 -0
- package/runtime/subsystems/auth/index.ts +43 -4
- package/runtime/subsystems/auth/protocols/integration-store.ts +37 -0
- package/runtime/subsystems/auth/protocols/oauth-state-store.ts +38 -6
- package/runtime/subsystems/auth/protocols/provider-strategy.ts +41 -0
- package/runtime/subsystems/auth/protocols/user-context.ts +22 -0
- package/runtime/subsystems/index.ts +17 -2
- package/templates/entity/new/backend/modules/core/sync-source.ejs.t +2 -2
- package/templates/entity/new/backend/modules/core/sync-source.providers.ejs.t +1 -1
- package/templates/entity/new/clean-lite-ps/prompt-extension.js +14 -0
- package/templates/entity/new/prompt.js +1 -0
- package/templates/subsystem/auth/app-module-hook.ejs.t +21 -0
- package/templates/subsystem/auth/auth-oauth-state.schema.ejs.t +35 -0
- package/templates/subsystem/auth/env-config.ejs.t +20 -0
- package/templates/subsystem/auth/prompt.js +46 -0
- package/templates/subsystem/auth-config/codegen-config-auth-block.ejs.t +20 -0
- package/templates/subsystem/auth-config/prompt.js +20 -0
- package/templates/subsystem/auth-integrations/app-module-hook.ejs.t +16 -0
- package/templates/subsystem/auth-integrations/prompt.js +23 -0
- package/dist/runtime/subsystems/auth/backends/oauth-state-store/in-memory.d.ts +0 -24
- package/dist/runtime/subsystems/auth/backends/oauth-state-store/in-memory.js +0 -24
- package/dist/runtime/subsystems/auth/backends/oauth-state-store/in-memory.js.map +0 -1
- package/runtime/subsystems/auth/backends/oauth-state-store/in-memory.ts +0 -42
|
@@ -12,6 +12,9 @@
|
|
|
12
12
|
* @Inject(OAUTH_STATE_STORE) private readonly states: IOAuthStateStore,
|
|
13
13
|
* @Inject(AUTH_INTEGRATION_READER) private readonly reader: IIntegrationReader,
|
|
14
14
|
* @Inject(AUTH_INTEGRATION_TOKEN_WRITER) private readonly writer: IIntegrationTokenWriter,
|
|
15
|
+
* @Inject(AUTH_INTEGRATION_GRANT_SINK) private readonly grants: IIntegrationGrantSink,
|
|
16
|
+
* @Inject(AUTH_USER_CONTEXT) private readonly userCtx: IUserContext,
|
|
17
|
+
* @Inject(STRATEGY_REGISTRY) private readonly registry: ProviderStrategyRegistry,
|
|
15
18
|
* ) {}
|
|
16
19
|
* ```
|
|
17
20
|
*
|
|
@@ -19,11 +22,21 @@
|
|
|
19
22
|
* provider-specific tokens (e.g. `SALESFORCE_AUTH_STRATEGY`,
|
|
20
23
|
* `HUBSPOT_AUTH_STRATEGY`) by each integration module — this subsystem does
|
|
21
24
|
* not mandate a single `AUTH_STRATEGY` token because an app typically has
|
|
22
|
-
* many concurrent strategies, one per provider.
|
|
25
|
+
* many concurrent strategies, one per provider. They are dispatched through
|
|
26
|
+
* `STRATEGY_REGISTRY` (a `ReadonlyMap<slug, ProviderStrategy>`), populated
|
|
27
|
+
* by per-provider modules via a `useFactory` provider.
|
|
23
28
|
*/
|
|
24
29
|
declare const ENCRYPTION_KEY: unique symbol;
|
|
25
30
|
declare const OAUTH_STATE_STORE: unique symbol;
|
|
26
31
|
declare const AUTH_INTEGRATION_READER: unique symbol;
|
|
27
32
|
declare const AUTH_INTEGRATION_TOKEN_WRITER: unique symbol;
|
|
33
|
+
declare const AUTH_INTEGRATION_GRANT_SINK: unique symbol;
|
|
34
|
+
declare const AUTH_USER_CONTEXT: unique symbol;
|
|
35
|
+
declare const STRATEGY_REGISTRY: unique symbol;
|
|
36
|
+
/**
|
|
37
|
+
* Holds the resolved `AuthModuleOptions` (used by `AuthController` to read
|
|
38
|
+
* `redirectUriBase` for building per-provider callback URIs).
|
|
39
|
+
*/
|
|
40
|
+
declare const AUTH_OPTIONS: unique symbol;
|
|
28
41
|
|
|
29
|
-
export { AUTH_INTEGRATION_READER, AUTH_INTEGRATION_TOKEN_WRITER, ENCRYPTION_KEY, OAUTH_STATE_STORE };
|
|
42
|
+
export { AUTH_INTEGRATION_GRANT_SINK, AUTH_INTEGRATION_READER, AUTH_INTEGRATION_TOKEN_WRITER, AUTH_OPTIONS, AUTH_USER_CONTEXT, ENCRYPTION_KEY, OAUTH_STATE_STORE, STRATEGY_REGISTRY };
|
|
@@ -3,10 +3,18 @@ var ENCRYPTION_KEY = /* @__PURE__ */ Symbol("ENCRYPTION_KEY");
|
|
|
3
3
|
var OAUTH_STATE_STORE = /* @__PURE__ */ Symbol("OAUTH_STATE_STORE");
|
|
4
4
|
var AUTH_INTEGRATION_READER = /* @__PURE__ */ Symbol("AUTH_INTEGRATION_READER");
|
|
5
5
|
var AUTH_INTEGRATION_TOKEN_WRITER = /* @__PURE__ */ Symbol("AUTH_INTEGRATION_TOKEN_WRITER");
|
|
6
|
+
var AUTH_INTEGRATION_GRANT_SINK = /* @__PURE__ */ Symbol("AUTH_INTEGRATION_GRANT_SINK");
|
|
7
|
+
var AUTH_USER_CONTEXT = /* @__PURE__ */ Symbol("AUTH_USER_CONTEXT");
|
|
8
|
+
var STRATEGY_REGISTRY = /* @__PURE__ */ Symbol("STRATEGY_REGISTRY");
|
|
9
|
+
var AUTH_OPTIONS = /* @__PURE__ */ Symbol("AUTH_OPTIONS");
|
|
6
10
|
export {
|
|
11
|
+
AUTH_INTEGRATION_GRANT_SINK,
|
|
7
12
|
AUTH_INTEGRATION_READER,
|
|
8
13
|
AUTH_INTEGRATION_TOKEN_WRITER,
|
|
14
|
+
AUTH_OPTIONS,
|
|
15
|
+
AUTH_USER_CONTEXT,
|
|
9
16
|
ENCRYPTION_KEY,
|
|
10
|
-
OAUTH_STATE_STORE
|
|
17
|
+
OAUTH_STATE_STORE,
|
|
18
|
+
STRATEGY_REGISTRY
|
|
11
19
|
};
|
|
12
20
|
//# sourceMappingURL=auth.tokens.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../runtime/subsystems/auth/auth.tokens.ts"],"sourcesContent":["/**\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"],"mappings":";
|
|
1
|
+
{"version":3,"sources":["../../../../runtime/subsystems/auth/auth.tokens.ts"],"sourcesContent":["/**\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"],"mappings":";AA4BO,IAAM,iBAAiB,uBAAO,gBAAgB;AAC9C,IAAM,oBAAoB,uBAAO,mBAAmB;AACpD,IAAM,0BAA0B,uBAAO,yBAAyB;AAChE,IAAM,gCAAgC,uBAAO,+BAA+B;AAC5E,IAAM,8BAA8B,uBAAO,6BAA6B;AACxE,IAAM,oBAAoB,uBAAO,mBAAmB;AACpD,IAAM,oBAAoB,uBAAO,mBAAmB;AAKpD,IAAM,eAAe,uBAAO,cAAc;","names":[]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { DrizzleClient } from '../../../types/drizzle.js';
|
|
2
|
+
import { IOAuthStateStore, OAuthStateRecord } from '../protocols/oauth-state-store.js';
|
|
3
|
+
import 'drizzle-orm/node-postgres';
|
|
4
|
+
|
|
5
|
+
interface DrizzleOAuthStateStoreOptions {
|
|
6
|
+
/** TTL in ms. Default 10 minutes. */
|
|
7
|
+
ttlMs?: number;
|
|
8
|
+
/** Injectable clock for tests. Default `Date.now`. */
|
|
9
|
+
now?: () => number;
|
|
10
|
+
/** Injectable token generator for tests. Default 32-byte base64url. */
|
|
11
|
+
generateToken?: () => string;
|
|
12
|
+
}
|
|
13
|
+
declare class DrizzleOAuthStateStore implements IOAuthStateStore {
|
|
14
|
+
private readonly db;
|
|
15
|
+
private readonly ttlMs;
|
|
16
|
+
private readonly now;
|
|
17
|
+
private readonly generateToken;
|
|
18
|
+
constructor(db: DrizzleClient, opts?: DrizzleOAuthStateStoreOptions);
|
|
19
|
+
generate(record: OAuthStateRecord): Promise<string>;
|
|
20
|
+
consume(state: string): Promise<OAuthStateRecord>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export { DrizzleOAuthStateStore, type DrizzleOAuthStateStoreOptions };
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// runtime/subsystems/auth/backends/state-store.drizzle-backend.ts
|
|
2
|
+
import { randomBytes } from "crypto";
|
|
3
|
+
import { eq } from "drizzle-orm";
|
|
4
|
+
|
|
5
|
+
// runtime/subsystems/auth/auth-oauth-state.schema.ts
|
|
6
|
+
import { pgTable, text, timestamp } from "drizzle-orm/pg-core";
|
|
7
|
+
var authOAuthState = pgTable("auth_oauth_state", {
|
|
8
|
+
state: text("state").primaryKey(),
|
|
9
|
+
userId: text("user_id").notNull(),
|
|
10
|
+
redirect: text("redirect"),
|
|
11
|
+
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull()
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
// runtime/subsystems/auth/protocols/oauth-state-store.ts
|
|
15
|
+
var OAuthStateError = class extends Error {
|
|
16
|
+
constructor(message, reason) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.reason = reason;
|
|
19
|
+
this.name = "OAuthStateError";
|
|
20
|
+
}
|
|
21
|
+
reason;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// runtime/subsystems/auth/backends/state-store.drizzle-backend.ts
|
|
25
|
+
var DrizzleOAuthStateStore = class {
|
|
26
|
+
constructor(db, opts = {}) {
|
|
27
|
+
this.db = db;
|
|
28
|
+
this.ttlMs = opts.ttlMs ?? 10 * 60 * 1e3;
|
|
29
|
+
this.now = opts.now ?? (() => Date.now());
|
|
30
|
+
this.generateToken = opts.generateToken ?? (() => randomBytes(32).toString("base64url"));
|
|
31
|
+
}
|
|
32
|
+
db;
|
|
33
|
+
ttlMs;
|
|
34
|
+
now;
|
|
35
|
+
generateToken;
|
|
36
|
+
async generate(record) {
|
|
37
|
+
const state = this.generateToken();
|
|
38
|
+
const expiresAt = new Date(this.now() + this.ttlMs);
|
|
39
|
+
await this.db.insert(authOAuthState).values({
|
|
40
|
+
state,
|
|
41
|
+
userId: record.userId,
|
|
42
|
+
redirect: record.redirect ?? null,
|
|
43
|
+
expiresAt
|
|
44
|
+
});
|
|
45
|
+
return state;
|
|
46
|
+
}
|
|
47
|
+
async consume(state) {
|
|
48
|
+
const rows = await this.db.delete(authOAuthState).where(eq(authOAuthState.state, state)).returning();
|
|
49
|
+
const row = rows[0];
|
|
50
|
+
if (!row) {
|
|
51
|
+
throw new OAuthStateError(
|
|
52
|
+
`OAuth state token unknown or already consumed`,
|
|
53
|
+
"missing"
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
if (row.expiresAt.getTime() <= this.now()) {
|
|
57
|
+
throw new OAuthStateError(`OAuth state token expired`, "expired");
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
userId: row.userId,
|
|
61
|
+
redirect: row.redirect ?? void 0
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
export {
|
|
66
|
+
DrizzleOAuthStateStore
|
|
67
|
+
};
|
|
68
|
+
//# sourceMappingURL=state-store.drizzle-backend.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../runtime/subsystems/auth/backends/state-store.drizzle-backend.ts","../../../../../runtime/subsystems/auth/auth-oauth-state.schema.ts","../../../../../runtime/subsystems/auth/protocols/oauth-state-store.ts"],"sourcesContent":["/**\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 * 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"],"mappings":";AAgBA,SAAS,mBAAmB;AAC5B,SAAS,UAAU;;;ACEnB,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;;;ACYM,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACgB,QAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EAJkB;AAKpB;;;AFZO,IAAM,yBAAN,MAAyD;AAAA,EAK9D,YACmB,IACjB,OAAsC,CAAC,GACvC;AAFiB;AAGjB,SAAK,QAAQ,KAAK,SAAS,KAAK,KAAK;AACrC,SAAK,MAAM,KAAK,QAAQ,MAAM,KAAK,IAAI;AACvC,SAAK,gBACH,KAAK,kBAAkB,MAAM,YAAY,EAAE,EAAE,SAAS,WAAW;AAAA,EACrE;AAAA,EAPmB;AAAA,EALF;AAAA,EACA;AAAA,EACA;AAAA,EAYjB,MAAM,SAAS,QAA2C;AACxD,UAAM,QAAQ,KAAK,cAAc;AACjC,UAAM,YAAY,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK;AAClD,UAAM,KAAK,GAAG,OAAO,cAAc,EAAE,OAAO;AAAA,MAC1C;AAAA,MACA,QAAQ,OAAO;AAAA,MACf,UAAU,OAAO,YAAY;AAAA,MAC7B;AAAA,IACF,CAAC;AACD,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,QAAQ,OAA0C;AACtD,UAAM,OAAO,MAAM,KAAK,GACrB,OAAO,cAAc,EACrB,MAAM,GAAG,eAAe,OAAO,KAAK,CAAC,EACrC,UAAU;AACb,UAAM,MAAM,KAAK,CAAC;AAClB,QAAI,CAAC,KAAK;AACR,YAAM,IAAI;AAAA,QACR;AAAA,QACA;AAAA,MACF;AAAA,IACF;AACA,QAAI,IAAI,UAAU,QAAQ,KAAK,KAAK,IAAI,GAAG;AACzC,YAAM,IAAI,gBAAgB,6BAA6B,SAAS;AAAA,IAClE;AACA,WAAO;AAAA,MACL,QAAQ,IAAI;AAAA,MACZ,UAAU,IAAI,YAAY;AAAA,IAC5B;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { IOAuthStateStore, OAuthStateRecord } from '../protocols/oauth-state-store.js';
|
|
2
|
+
|
|
3
|
+
interface MemoryOAuthStateStoreOptions {
|
|
4
|
+
/** TTL in ms. Default 10 minutes. */
|
|
5
|
+
ttlMs?: number;
|
|
6
|
+
/** Injectable clock for tests. Default `Date.now`. */
|
|
7
|
+
now?: () => number;
|
|
8
|
+
/** Injectable token generator for tests. Default 32-byte base64url. */
|
|
9
|
+
generateToken?: () => string;
|
|
10
|
+
}
|
|
11
|
+
declare class MemoryOAuthStateStore implements IOAuthStateStore {
|
|
12
|
+
private readonly store;
|
|
13
|
+
private readonly ttlMs;
|
|
14
|
+
private readonly now;
|
|
15
|
+
private readonly generateToken;
|
|
16
|
+
constructor(opts?: MemoryOAuthStateStoreOptions);
|
|
17
|
+
generate(record: OAuthStateRecord): Promise<string>;
|
|
18
|
+
consume(state: string): Promise<OAuthStateRecord>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export { MemoryOAuthStateStore, type MemoryOAuthStateStoreOptions };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// runtime/subsystems/auth/backends/state-store.memory-backend.ts
|
|
2
|
+
import { randomBytes } from "crypto";
|
|
3
|
+
|
|
4
|
+
// runtime/subsystems/auth/protocols/oauth-state-store.ts
|
|
5
|
+
var OAuthStateError = class extends Error {
|
|
6
|
+
constructor(message, reason) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.reason = reason;
|
|
9
|
+
this.name = "OAuthStateError";
|
|
10
|
+
}
|
|
11
|
+
reason;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
// runtime/subsystems/auth/backends/state-store.memory-backend.ts
|
|
15
|
+
var MemoryOAuthStateStore = class {
|
|
16
|
+
store = /* @__PURE__ */ new Map();
|
|
17
|
+
ttlMs;
|
|
18
|
+
now;
|
|
19
|
+
generateToken;
|
|
20
|
+
constructor(opts = {}) {
|
|
21
|
+
this.ttlMs = opts.ttlMs ?? 10 * 60 * 1e3;
|
|
22
|
+
this.now = opts.now ?? (() => Date.now());
|
|
23
|
+
this.generateToken = opts.generateToken ?? (() => randomBytes(32).toString("base64url"));
|
|
24
|
+
}
|
|
25
|
+
async generate(record) {
|
|
26
|
+
const state = this.generateToken();
|
|
27
|
+
this.store.set(state, {
|
|
28
|
+
record: { ...record },
|
|
29
|
+
expiresAt: this.now() + this.ttlMs
|
|
30
|
+
});
|
|
31
|
+
return state;
|
|
32
|
+
}
|
|
33
|
+
async consume(state) {
|
|
34
|
+
const slot = this.store.get(state);
|
|
35
|
+
if (!slot) {
|
|
36
|
+
throw new OAuthStateError(
|
|
37
|
+
`OAuth state token unknown or already consumed`,
|
|
38
|
+
"missing"
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
this.store.delete(state);
|
|
42
|
+
if (slot.expiresAt <= this.now()) {
|
|
43
|
+
throw new OAuthStateError(`OAuth state token expired`, "expired");
|
|
44
|
+
}
|
|
45
|
+
return slot.record;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
export {
|
|
49
|
+
MemoryOAuthStateStore
|
|
50
|
+
};
|
|
51
|
+
//# sourceMappingURL=state-store.memory-backend.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../runtime/subsystems/auth/backends/state-store.memory-backend.ts","../../../../../runtime/subsystems/auth/protocols/oauth-state-store.ts"],"sourcesContent":["/**\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"],"mappings":";AAiBA,SAAS,mBAAmB;;;ACsBrB,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACgB,QAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EAJkB;AAKpB;;;ADTO,IAAM,wBAAN,MAAwD;AAAA,EAC5C,QAAQ,oBAAI,IAAkB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,OAAqC,CAAC,GAAG;AACnD,SAAK,QAAQ,KAAK,SAAS,KAAK,KAAK;AACrC,SAAK,MAAM,KAAK,QAAQ,MAAM,KAAK,IAAI;AACvC,SAAK,gBACH,KAAK,kBAAkB,MAAM,YAAY,EAAE,EAAE,SAAS,WAAW;AAAA,EACrE;AAAA,EAEA,MAAM,SAAS,QAA2C;AACxD,UAAM,QAAQ,KAAK,cAAc;AACjC,SAAK,MAAM,IAAI,OAAO;AAAA,MACpB,QAAQ,EAAE,GAAG,OAAO;AAAA,MACpB,WAAW,KAAK,IAAI,IAAI,KAAK;AAAA,IAC/B,CAAC;AACD,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,QAAQ,OAA0C;AACtD,UAAM,OAAO,KAAK,MAAM,IAAI,KAAK;AACjC,QAAI,CAAC,MAAM;AACT,YAAM,IAAI;AAAA,QACR;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAEA,SAAK,MAAM,OAAO,KAAK;AACvB,QAAI,KAAK,aAAa,KAAK,IAAI,GAAG;AAChC,YAAM,IAAI,gBAAgB,6BAA6B,SAAS;AAAA,IAClE;AACA,WAAO,KAAK;AAAA,EACd;AACF;","names":[]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { AuthModuleOptions } from '../auth.module.js';
|
|
2
|
+
import { IOAuthStateStore } from '../protocols/oauth-state-store.js';
|
|
3
|
+
import { IUserContext } from '../protocols/user-context.js';
|
|
4
|
+
import { ProviderStrategyRegistry } from '../protocols/provider-strategy.js';
|
|
5
|
+
import { IIntegrationGrantSink } from '../protocols/integration-store.js';
|
|
6
|
+
import '@nestjs/common';
|
|
7
|
+
import '../runtime/oauth2-refresh.strategy.js';
|
|
8
|
+
import '../protocols/auth-strategy.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Minimal response surface used by the controller — typed loosely so we
|
|
12
|
+
* don't pull a hard dep on `express` or `fastify`. Both popular HTTP
|
|
13
|
+
* adapters expose `redirect(status, url)`.
|
|
14
|
+
*/
|
|
15
|
+
interface RedirectingResponse {
|
|
16
|
+
redirect(statusCode: number, url: string): unknown;
|
|
17
|
+
}
|
|
18
|
+
declare class AuthController {
|
|
19
|
+
private readonly registry;
|
|
20
|
+
private readonly userContext;
|
|
21
|
+
private readonly stateStore;
|
|
22
|
+
private readonly grantSink;
|
|
23
|
+
private readonly options;
|
|
24
|
+
constructor(registry: ProviderStrategyRegistry, userContext: IUserContext, stateStore: IOAuthStateStore, grantSink: IIntegrationGrantSink, options: AuthModuleOptions);
|
|
25
|
+
connect(slug: string, redirect: string | undefined, req: unknown, res: RedirectingResponse): Promise<unknown>;
|
|
26
|
+
callback(slug: string, code: string | undefined, state: string | undefined, res: RedirectingResponse): Promise<unknown>;
|
|
27
|
+
private requireStrategy;
|
|
28
|
+
private redirectUriFor;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export { AuthController };
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __decorateClass = (decorators, target, key, kind) => {
|
|
4
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
5
|
+
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
6
|
+
if (decorator = decorators[i])
|
|
7
|
+
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
8
|
+
if (kind && result) __defProp(target, key, result);
|
|
9
|
+
return result;
|
|
10
|
+
};
|
|
11
|
+
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
12
|
+
|
|
13
|
+
// runtime/subsystems/auth/controllers/auth.controller.ts
|
|
14
|
+
import {
|
|
15
|
+
Controller,
|
|
16
|
+
Get,
|
|
17
|
+
Inject,
|
|
18
|
+
Param,
|
|
19
|
+
Query,
|
|
20
|
+
Req,
|
|
21
|
+
Res,
|
|
22
|
+
HttpException,
|
|
23
|
+
HttpStatus
|
|
24
|
+
} from "@nestjs/common";
|
|
25
|
+
|
|
26
|
+
// runtime/subsystems/auth/auth.tokens.ts
|
|
27
|
+
var OAUTH_STATE_STORE = /* @__PURE__ */ Symbol("OAUTH_STATE_STORE");
|
|
28
|
+
var AUTH_INTEGRATION_GRANT_SINK = /* @__PURE__ */ Symbol("AUTH_INTEGRATION_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");
|
|
32
|
+
|
|
33
|
+
// runtime/subsystems/auth/controllers/auth.controller.ts
|
|
34
|
+
var AuthController = class {
|
|
35
|
+
constructor(registry, userContext, stateStore, grantSink, options) {
|
|
36
|
+
this.registry = registry;
|
|
37
|
+
this.userContext = userContext;
|
|
38
|
+
this.stateStore = stateStore;
|
|
39
|
+
this.grantSink = grantSink;
|
|
40
|
+
this.options = options;
|
|
41
|
+
}
|
|
42
|
+
registry;
|
|
43
|
+
userContext;
|
|
44
|
+
stateStore;
|
|
45
|
+
grantSink;
|
|
46
|
+
options;
|
|
47
|
+
async connect(slug, redirect, req, res) {
|
|
48
|
+
const strategy = this.requireStrategy(slug);
|
|
49
|
+
const userId = await this.userContext.getCurrentUserId(req);
|
|
50
|
+
const state = await this.stateStore.generate({ userId, redirect });
|
|
51
|
+
const url = strategy.buildAuthorizeUrl({
|
|
52
|
+
state,
|
|
53
|
+
redirectUri: this.redirectUriFor(slug)
|
|
54
|
+
});
|
|
55
|
+
return res.redirect(HttpStatus.FOUND, url);
|
|
56
|
+
}
|
|
57
|
+
async callback(slug, code, state, res) {
|
|
58
|
+
const strategy = this.requireStrategy(slug);
|
|
59
|
+
if (!code) {
|
|
60
|
+
throw new HttpException(
|
|
61
|
+
`Missing 'code' query param`,
|
|
62
|
+
HttpStatus.BAD_REQUEST
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
if (!state) {
|
|
66
|
+
throw new HttpException(
|
|
67
|
+
`Missing 'state' query param`,
|
|
68
|
+
HttpStatus.BAD_REQUEST
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
const { userId, redirect } = await this.stateStore.consume(state);
|
|
72
|
+
const tokens = await strategy.exchangeCodeForTokens({
|
|
73
|
+
code,
|
|
74
|
+
redirectUri: this.redirectUriFor(slug)
|
|
75
|
+
});
|
|
76
|
+
await this.grantSink.createOrUpdateFromOAuthGrant({
|
|
77
|
+
userId,
|
|
78
|
+
provider: slug,
|
|
79
|
+
accessToken: tokens.accessToken,
|
|
80
|
+
refreshToken: tokens.refreshToken,
|
|
81
|
+
expiresAt: tokens.expiresAt,
|
|
82
|
+
scope: tokens.scope,
|
|
83
|
+
externalAccountId: tokens.externalAccountId,
|
|
84
|
+
providerMetadata: tokens.providerMetadata
|
|
85
|
+
});
|
|
86
|
+
return res.redirect(
|
|
87
|
+
HttpStatus.FOUND,
|
|
88
|
+
redirect ?? `/settings/integrations?connected=${encodeURIComponent(slug)}`
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
requireStrategy(slug) {
|
|
92
|
+
const strategy = this.registry.get(slug);
|
|
93
|
+
if (!strategy) {
|
|
94
|
+
throw new HttpException(
|
|
95
|
+
`Unknown provider '${slug}'`,
|
|
96
|
+
HttpStatus.NOT_FOUND
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
return strategy;
|
|
100
|
+
}
|
|
101
|
+
redirectUriFor(slug) {
|
|
102
|
+
const base = this.options.redirectUriBase;
|
|
103
|
+
if (!base) {
|
|
104
|
+
throw new Error(
|
|
105
|
+
`AuthModule.forRoot: redirectUriBase is required when AuthController is enabled`
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
const trimmed = base.replace(/\/+$/, "");
|
|
109
|
+
return `${trimmed}/auth/${encodeURIComponent(slug)}/callback`;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
__decorateClass([
|
|
113
|
+
Get(":provider/connect"),
|
|
114
|
+
__decorateParam(0, Param("provider")),
|
|
115
|
+
__decorateParam(1, Query("redirect")),
|
|
116
|
+
__decorateParam(2, Req()),
|
|
117
|
+
__decorateParam(3, Res())
|
|
118
|
+
], AuthController.prototype, "connect", 1);
|
|
119
|
+
__decorateClass([
|
|
120
|
+
Get(":provider/callback"),
|
|
121
|
+
__decorateParam(0, Param("provider")),
|
|
122
|
+
__decorateParam(1, Query("code")),
|
|
123
|
+
__decorateParam(2, Query("state")),
|
|
124
|
+
__decorateParam(3, Res())
|
|
125
|
+
], AuthController.prototype, "callback", 1);
|
|
126
|
+
AuthController = __decorateClass([
|
|
127
|
+
Controller("auth"),
|
|
128
|
+
__decorateParam(0, Inject(STRATEGY_REGISTRY)),
|
|
129
|
+
__decorateParam(1, Inject(AUTH_USER_CONTEXT)),
|
|
130
|
+
__decorateParam(2, Inject(OAUTH_STATE_STORE)),
|
|
131
|
+
__decorateParam(3, Inject(AUTH_INTEGRATION_GRANT_SINK)),
|
|
132
|
+
__decorateParam(4, Inject(AUTH_OPTIONS))
|
|
133
|
+
], AuthController);
|
|
134
|
+
export {
|
|
135
|
+
AuthController
|
|
136
|
+
};
|
|
137
|
+
//# sourceMappingURL=auth.controller.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../runtime/subsystems/auth/controllers/auth.controller.ts","../../../../../runtime/subsystems/auth/auth.tokens.ts"],"sourcesContent":["/**\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 * 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"],"mappings":"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","names":[]}
|
|
@@ -1,13 +1,22 @@
|
|
|
1
1
|
export { AuthCredentials, AuthResolveOptions, IAuthStrategy } from './protocols/auth-strategy.js';
|
|
2
2
|
export { IEncryptionKey } from './protocols/encryption-key.js';
|
|
3
|
-
export { IOAuthStateStore,
|
|
4
|
-
export { DecryptedIntegration, IIntegrationReader, IIntegrationTokenWriter, IntegrationTokenUpdate } from './protocols/integration-store.js';
|
|
5
|
-
export {
|
|
3
|
+
export { IOAuthStateStore, OAuthStateError, OAuthStateRecord } from './protocols/oauth-state-store.js';
|
|
4
|
+
export { DecryptedIntegration, IIntegrationGrantSink, IIntegrationReader, IIntegrationTokenWriter, IntegrationGrantInput, IntegrationTokenUpdate } from './protocols/integration-store.js';
|
|
5
|
+
export { IUserContext } from './protocols/user-context.js';
|
|
6
|
+
export { ExchangedTokens, ProviderStrategy, ProviderStrategyRegistry } from './protocols/provider-strategy.js';
|
|
7
|
+
export { AUTH_INTEGRATION_GRANT_SINK, AUTH_INTEGRATION_READER, AUTH_INTEGRATION_TOKEN_WRITER, AUTH_OPTIONS, AUTH_USER_CONTEXT, ENCRYPTION_KEY, OAUTH_STATE_STORE, STRATEGY_REGISTRY } from './auth.tokens.js';
|
|
6
8
|
export { FetchLike, OAuth2RefreshStrategy, OAuth2RefreshStrategyOptions, ParsedRefreshResponse } from './runtime/oauth2-refresh.strategy.js';
|
|
7
9
|
export { WithAuthRetryOptions, withAuthRetry } from './runtime/with-auth-retry.js';
|
|
8
10
|
export { IntegrationBrokenError } from './runtime/integration-broken.error.js';
|
|
9
11
|
export { SessionExpiredError, isSessionExpiredError } from './runtime/session-expired.error.js';
|
|
12
|
+
export { AuthOAuthState, authOAuthState } from './auth-oauth-state.schema.js';
|
|
10
13
|
export { EnvEncryptionKey, EnvEncryptionKeyOptions } from './backends/encryption-key/env.js';
|
|
11
|
-
export {
|
|
14
|
+
export { MemoryOAuthStateStore, MemoryOAuthStateStoreOptions } from './backends/state-store.memory-backend.js';
|
|
15
|
+
export { DrizzleOAuthStateStore, DrizzleOAuthStateStoreOptions } from './backends/state-store.drizzle-backend.js';
|
|
16
|
+
export { AuthController } from './controllers/auth.controller.js';
|
|
12
17
|
export { AuthModule, AuthModuleOptions } from './auth.module.js';
|
|
18
|
+
import 'drizzle-orm/pg-core';
|
|
19
|
+
import 'drizzle-orm';
|
|
20
|
+
import '../../types/drizzle.js';
|
|
21
|
+
import 'drizzle-orm/node-postgres';
|
|
13
22
|
import '@nestjs/common';
|