@nauth-toolkit/oidc-provider 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +158 -0
  3. package/dist/nestjs/index.d.ts +12 -0
  4. package/dist/nestjs/index.d.ts.map +1 -0
  5. package/dist/nestjs/index.js +23 -0
  6. package/dist/nestjs/index.js.map +1 -0
  7. package/dist/nestjs/mount.d.ts +38 -0
  8. package/dist/nestjs/mount.d.ts.map +1 -0
  9. package/dist/nestjs/mount.js +35 -0
  10. package/dist/nestjs/mount.js.map +1 -0
  11. package/dist/nestjs/oidc-interaction.controller.d.ts +40 -0
  12. package/dist/nestjs/oidc-interaction.controller.d.ts.map +1 -0
  13. package/dist/nestjs/oidc-interaction.controller.js +157 -0
  14. package/dist/nestjs/oidc-interaction.controller.js.map +1 -0
  15. package/dist/nestjs/oidc-provider.module.d.ts +70 -0
  16. package/dist/nestjs/oidc-provider.module.d.ts.map +1 -0
  17. package/dist/nestjs/oidc-provider.module.js +84 -0
  18. package/dist/nestjs/oidc-provider.module.js.map +1 -0
  19. package/dist/nestjs/tokens.d.ts +13 -0
  20. package/dist/nestjs/tokens.d.ts.map +1 -0
  21. package/dist/nestjs/tokens.js +16 -0
  22. package/dist/nestjs/tokens.js.map +1 -0
  23. package/dist/src/config.types.d.ts +102 -0
  24. package/dist/src/config.types.d.ts.map +1 -0
  25. package/dist/src/config.types.js +3 -0
  26. package/dist/src/config.types.js.map +1 -0
  27. package/dist/src/create-provider.d.ts +47 -0
  28. package/dist/src/create-provider.d.ts.map +1 -0
  29. package/dist/src/create-provider.js +159 -0
  30. package/dist/src/create-provider.js.map +1 -0
  31. package/dist/src/find-account.d.ts +33 -0
  32. package/dist/src/find-account.d.ts.map +1 -0
  33. package/dist/src/find-account.js +69 -0
  34. package/dist/src/find-account.js.map +1 -0
  35. package/dist/src/index.d.ts +41 -0
  36. package/dist/src/index.d.ts.map +1 -0
  37. package/dist/src/index.js +51 -0
  38. package/dist/src/index.js.map +1 -0
  39. package/dist/src/interaction-bridge.d.ts +147 -0
  40. package/dist/src/interaction-bridge.d.ts.map +1 -0
  41. package/dist/src/interaction-bridge.js +283 -0
  42. package/dist/src/interaction-bridge.js.map +1 -0
  43. package/dist/src/mount/express.d.ts +54 -0
  44. package/dist/src/mount/express.d.ts.map +1 -0
  45. package/dist/src/mount/express.js +56 -0
  46. package/dist/src/mount/express.js.map +1 -0
  47. package/dist/src/rate-limit.d.ts +61 -0
  48. package/dist/src/rate-limit.d.ts.map +1 -0
  49. package/dist/src/rate-limit.js +93 -0
  50. package/dist/src/rate-limit.js.map +1 -0
  51. package/dist/src/raw-http.d.ts +25 -0
  52. package/dist/src/raw-http.d.ts.map +1 -0
  53. package/dist/src/raw-http.js +33 -0
  54. package/dist/src/raw-http.js.map +1 -0
  55. package/dist/src/session-termination.d.ts +60 -0
  56. package/dist/src/session-termination.d.ts.map +1 -0
  57. package/dist/src/session-termination.js +70 -0
  58. package/dist/src/session-termination.js.map +1 -0
  59. package/dist/src/storage.adapter.d.ts +99 -0
  60. package/dist/src/storage.adapter.d.ts.map +1 -0
  61. package/dist/src/storage.adapter.js +197 -0
  62. package/dist/src/storage.adapter.js.map +1 -0
  63. package/dist/tsconfig.tsbuildinfo +1 -0
  64. package/package.json +95 -0
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ /**
3
+ * OpenID Connect provider for nauth-toolkit.
4
+ *
5
+ * Turns an nauth-backed application into an OAuth2 authorization server and OpenID
6
+ * Connect provider, so third parties can offer "Sign in with <your app>". The protocol
7
+ * itself is implemented by the OpenID Certified `oidc-provider` library; this package
8
+ * supplies the three things it needs from nauth — storage, accounts, and a login and
9
+ * consent flow — and nothing else.
10
+ *
11
+ * nauth remains the sole authority on identity: the whole challenge state machine
12
+ * (forced password change, email and phone verification, MFA setup and verification,
13
+ * adaptive risk) runs before the bridge ever reports a completed login.
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * import { createNAuthOIDCProvider, mountOIDCProviderExpress } from '@nauth-toolkit/oidc-provider';
18
+ *
19
+ * const provider = await createNAuthOIDCProvider({
20
+ * issuer: 'https://auth.example.com', // an origin, never a path
21
+ * interactionUrl: (uid) => `https://auth.example.com/interaction/${uid}`,
22
+ * storage: nauth.storage,
23
+ * userRepository,
24
+ * cookieKeys: [process.env.OIDC_COOKIE_SECRET!],
25
+ * });
26
+ *
27
+ * mountOIDCProviderExpress(app, provider); // before body parsers
28
+ * ```
29
+ */
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.createOIDCRateLimiter = exports.OIDCSessionTerminator = exports.toRawHttp = exports.isProviderPath = exports.mountOIDCProviderExpress = exports.OIDCInteractionBridge = exports.createFindAccount = exports.NAuthOIDCAdapter = exports.createOIDCStorageAdapter = exports.loadProviderCtor = exports.createNAuthOIDCProvider = void 0;
32
+ var create_provider_1 = require("./create-provider");
33
+ Object.defineProperty(exports, "createNAuthOIDCProvider", { enumerable: true, get: function () { return create_provider_1.createNAuthOIDCProvider; } });
34
+ Object.defineProperty(exports, "loadProviderCtor", { enumerable: true, get: function () { return create_provider_1.loadProviderCtor; } });
35
+ var storage_adapter_1 = require("./storage.adapter");
36
+ Object.defineProperty(exports, "createOIDCStorageAdapter", { enumerable: true, get: function () { return storage_adapter_1.createOIDCStorageAdapter; } });
37
+ Object.defineProperty(exports, "NAuthOIDCAdapter", { enumerable: true, get: function () { return storage_adapter_1.NAuthOIDCAdapter; } });
38
+ var find_account_1 = require("./find-account");
39
+ Object.defineProperty(exports, "createFindAccount", { enumerable: true, get: function () { return find_account_1.createFindAccount; } });
40
+ var interaction_bridge_1 = require("./interaction-bridge");
41
+ Object.defineProperty(exports, "OIDCInteractionBridge", { enumerable: true, get: function () { return interaction_bridge_1.OIDCInteractionBridge; } });
42
+ var express_1 = require("./mount/express");
43
+ Object.defineProperty(exports, "mountOIDCProviderExpress", { enumerable: true, get: function () { return express_1.mountOIDCProviderExpress; } });
44
+ Object.defineProperty(exports, "isProviderPath", { enumerable: true, get: function () { return express_1.isProviderPath; } });
45
+ var raw_http_1 = require("./raw-http");
46
+ Object.defineProperty(exports, "toRawHttp", { enumerable: true, get: function () { return raw_http_1.toRawHttp; } });
47
+ var session_termination_1 = require("./session-termination");
48
+ Object.defineProperty(exports, "OIDCSessionTerminator", { enumerable: true, get: function () { return session_termination_1.OIDCSessionTerminator; } });
49
+ var rate_limit_1 = require("./rate-limit");
50
+ Object.defineProperty(exports, "createOIDCRateLimiter", { enumerable: true, get: function () { return rate_limit_1.createOIDCRateLimiter; } });
51
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;;;AAEH,qDAA8E;AAArE,0HAAA,uBAAuB,OAAA;AAAE,mHAAA,gBAAgB,OAAA;AAClD,qDAA+E;AAAtE,2HAAA,wBAAwB,OAAA;AAAE,mHAAA,gBAAgB,OAAA;AACnD,+CAAmD;AAA1C,iHAAA,iBAAiB,OAAA;AAE1B,2DAA6D;AAApD,2HAAA,qBAAqB,OAAA;AAE9B,2CAA2E;AAAlE,mHAAA,wBAAwB,OAAA;AAAE,yGAAA,cAAc,OAAA;AACjD,uCAAuC;AAA9B,qGAAA,SAAS,OAAA;AAClB,6DAA8D;AAArD,4HAAA,qBAAqB,OAAA;AAC9B,2CAAqD;AAA5C,mHAAA,qBAAqB,OAAA"}
@@ -0,0 +1,147 @@
1
+ import type Provider from 'oidc-provider';
2
+ import type { AuthAuditService, IdpSessionGate } from '@nauth-toolkit/core/internal';
3
+ /** What the consent screen needs in order to ask the user. */
4
+ export interface InteractionStateDTO {
5
+ /** The pending interaction id. */
6
+ uid: string;
7
+ /** What the provider is asking for: a login, or consent for scopes. */
8
+ prompt: 'login' | 'consent' | string;
9
+ /** The client making the request, as the user should see it. */
10
+ client: {
11
+ clientId: string;
12
+ clientName?: string;
13
+ logoUri?: string;
14
+ clientUri?: string;
15
+ };
16
+ /** Scopes the client asked for. */
17
+ scopes: string[];
18
+ /** Scopes still needing consent — the rest are already granted. */
19
+ missingScopes: string[];
20
+ /** nauth's verdict on the current session. */
21
+ gate: 'authenticated' | 'login_required' | 'denied';
22
+ /** Why, when the gate is not `authenticated`. */
23
+ gateReason?: string;
24
+ /** External identifier of the signed-in user, when there is one. */
25
+ sub?: string;
26
+ }
27
+ /** Where to send the browser after a decision. */
28
+ export interface InteractionRedirectDTO {
29
+ /** Absolute URL to navigate to. */
30
+ redirectTo: string;
31
+ }
32
+ export declare class OIDCInteractionBridge {
33
+ private readonly provider;
34
+ private readonly sessionGate;
35
+ private readonly auditService?;
36
+ /**
37
+ * @param provider - The configured `oidc-provider` instance
38
+ * @param sessionGate - nauth's verdict on whether a request may be vouched for
39
+ * @param auditService - Optional. When supplied, every decision is written to nauth's
40
+ * audit trail with the relying party's identity attached. Omitted when audit logs
41
+ * are disabled, in which case nothing is recorded
42
+ */
43
+ constructor(provider: Provider, sessionGate: IdpSessionGate, auditService?: AuthAuditService | undefined);
44
+ /**
45
+ * Describe a pending interaction so the frontend can decide what to render.
46
+ *
47
+ * Callable anonymously: the answer for a signed-out user is precisely what tells the
48
+ * frontend to send them to login.
49
+ *
50
+ * @param req - The framework request
51
+ * @param res - The framework response
52
+ * @returns What the interaction needs, and whether nauth considers the caller signed in
53
+ * @throws {NAuthException} `OIDC_INTERACTION_NOT_FOUND` when there is no such pending request
54
+ */
55
+ getState(req: unknown, res: unknown): Promise<InteractionStateDTO>;
56
+ /**
57
+ * Complete the login step for the currently authenticated nauth user.
58
+ *
59
+ * The session gate runs again here, authoritatively. A valid access token only
60
+ * proves the challenge flow completed *when it was issued*; the gate re-reads the
61
+ * account so that a user disabled, locked, or newly required to change their
62
+ * password in the meantime cannot have an id_token minted for a third party.
63
+ *
64
+ * A denied account resolves the interaction with `access_denied` rather than
65
+ * throwing, so the relying party receives a proper protocol error instead of a dead
66
+ * browser tab.
67
+ *
68
+ * @param req - The framework request
69
+ * @param res - The framework response
70
+ * @returns Where to send the browser to resume the authorization request
71
+ * @throws {NAuthException} `OIDC_INTERACTION_NOT_FOUND` when the request has expired,
72
+ * or `OIDC_LOGIN_REQUIRED` when no completed nauth login stands behind it — the
73
+ * latter carrying `uid` so the frontend can resume after logging in
74
+ */
75
+ completeLogin(req: unknown, res: unknown): Promise<InteractionRedirectDTO>;
76
+ /**
77
+ * Record the user's consent decision.
78
+ *
79
+ * On approval this builds the provider's `Grant` — the durable record of what this
80
+ * user let this client see — and resolves the interaction with its id. On refusal it
81
+ * resolves with `access_denied`.
82
+ *
83
+ * @param req - The framework request
84
+ * @param res - The framework response
85
+ * @param decision - Whether the user approved, and optionally a narrowed scope set
86
+ * @returns Where to send the browser next
87
+ * @throws {NAuthException} `OIDC_INTERACTION_NOT_FOUND` when the request has expired,
88
+ * or `OIDC_LOGIN_REQUIRED` when the session lapsed while the consent screen was open
89
+ */
90
+ completeConsent(req: unknown, res: unknown, decision: {
91
+ approve: boolean;
92
+ scopes?: string[];
93
+ }): Promise<InteractionRedirectDTO>;
94
+ /**
95
+ * Abandon a pending interaction.
96
+ *
97
+ * Gives the relying party a clean `access_denied` instead of leaving it waiting on a
98
+ * browser tab the user closed.
99
+ *
100
+ * @param req - The framework request
101
+ * @param res - The framework response
102
+ * @returns Where to send the browser
103
+ */
104
+ abort(req: unknown, res: unknown): Promise<InteractionRedirectDTO>;
105
+ /**
106
+ * Write one decision to nauth's audit trail, with the relying party attached.
107
+ *
108
+ * The ordinary `LOGIN_SUCCESS` recorded when the user typed their password cannot
109
+ * carry this: at that point the authorization request is still parked and nauth has
110
+ * no idea a third party is waiting. Here it does.
111
+ *
112
+ * Fire-and-forget, and never allowed to fail the flow — an audit backend being down
113
+ * must not stop a user signing in. Client info (IP, geolocation, device, user agent)
114
+ * is filled in automatically by the audit service, because these are ordinary nauth
115
+ * routes running inside the request context.
116
+ *
117
+ * @param eventType - Which decision this was
118
+ * @param eventStatus - How it turned out
119
+ * @param details - The interaction the decision belongs to
120
+ * @param metadata - Anything to record beyond the client and scopes
121
+ * @param userId - Internal user id, when the gate has already resolved one
122
+ * @param sub - External identifier, for a refusal where no internal id was resolved
123
+ */
124
+ private audit;
125
+ /**
126
+ * Read the pending interaction, or say plainly that there isn't one.
127
+ *
128
+ * `interactionDetails` throws `SessionNotFound` for an interaction that has expired,
129
+ * been resolved already, or never existed — all of which are a 404 to the caller, not
130
+ * a server fault.
131
+ *
132
+ * @param raw - The unwrapped Node request and response
133
+ * @returns The provider's view of the pending interaction
134
+ * @throws {NAuthException} `OIDC_INTERACTION_NOT_FOUND` when there is no such interaction
135
+ */
136
+ private loadInteraction;
137
+ /**
138
+ * Resolve the interaction and report where the browser should go.
139
+ *
140
+ * @param raw - The unwrapped Node request and response
141
+ * @param result - What to resolve the interaction with
142
+ * @param mergeWithLastSubmission - Whether to merge into the previous submission
143
+ * @returns The provider's redirect target
144
+ */
145
+ private resolve;
146
+ }
147
+ //# sourceMappingURL=interaction-bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interaction-bridge.d.ts","sourceRoot":"","sources":["../../src/interaction-bridge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAC;AAG1C,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAGrF,8DAA8D;AAC9D,MAAM,WAAW,mBAAmB;IAClC,kCAAkC;IAClC,GAAG,EAAE,MAAM,CAAC;IACZ,uEAAuE;IACvE,MAAM,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,CAAC;IACrC,gEAAgE;IAChE,MAAM,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACx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;IACH,OAAO,CAAC,KAAK;IA2Cb;;;;;;;;;;OAUG;YACW,eAAe;IAY7B;;;;;;;OAOG;YACW,OAAO;CAWtB"}
@@ -0,0 +1,283 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OIDCInteractionBridge = void 0;
4
+ const core_1 = require("@nauth-toolkit/core");
5
+ const raw_http_1 = require("./raw-http");
6
+ /**
7
+ * The error a frontend acts on by sending the user back through login.
8
+ *
9
+ * Carries the interaction id so the caller can stash it before navigating away and
10
+ * return to exactly this request afterwards, and the gate's reason so it can explain
11
+ * itself. Recoverable, unlike `OIDC_ACCESS_DENIED`.
12
+ *
13
+ * @param uid - The pending interaction id
14
+ * @param reason - Why the session gate refused
15
+ * @returns An exception the HTTP layer maps to 401
16
+ */
17
+ function loginRequired(uid, reason) {
18
+ return new core_1.NAuthException(core_1.AuthErrorCode.OIDC_LOGIN_REQUIRED, 'A completed login is required to continue this authorization request', { uid, reason });
19
+ }
20
+ class OIDCInteractionBridge {
21
+ provider;
22
+ sessionGate;
23
+ auditService;
24
+ /**
25
+ * @param provider - The configured `oidc-provider` instance
26
+ * @param sessionGate - nauth's verdict on whether a request may be vouched for
27
+ * @param auditService - Optional. When supplied, every decision is written to nauth's
28
+ * audit trail with the relying party's identity attached. Omitted when audit logs
29
+ * are disabled, in which case nothing is recorded
30
+ */
31
+ constructor(provider, sessionGate, auditService) {
32
+ this.provider = provider;
33
+ this.sessionGate = sessionGate;
34
+ this.auditService = auditService;
35
+ }
36
+ /**
37
+ * Describe a pending interaction so the frontend can decide what to render.
38
+ *
39
+ * Callable anonymously: the answer for a signed-out user is precisely what tells the
40
+ * frontend to send them to login.
41
+ *
42
+ * @param req - The framework request
43
+ * @param res - The framework response
44
+ * @returns What the interaction needs, and whether nauth considers the caller signed in
45
+ * @throws {NAuthException} `OIDC_INTERACTION_NOT_FOUND` when there is no such pending request
46
+ */
47
+ async getState(req, res) {
48
+ const raw = (0, raw_http_1.toRawHttp)(req, res);
49
+ const details = await this.loadInteraction(raw);
50
+ const client = await this.provider.Client.find(details.params.client_id);
51
+ const gate = await this.sessionGate.evaluate();
52
+ const promptDetails = details.prompt.details;
53
+ const requested = String(details.params.scope ?? '')
54
+ .split(/\s+/)
55
+ .filter(Boolean);
56
+ return {
57
+ uid: details.uid,
58
+ prompt: details.prompt.name,
59
+ client: {
60
+ clientId: String(details.params.client_id),
61
+ clientName: client?.clientName,
62
+ logoUri: client?.logoUri,
63
+ clientUri: client?.clientUri,
64
+ },
65
+ scopes: requested,
66
+ missingScopes: promptDetails.missingOIDCScope ?? [],
67
+ gate: gate.status,
68
+ gateReason: gate.status === 'authenticated' ? undefined : gate.reason,
69
+ sub: gate.status === 'authenticated' ? gate.user.sub : undefined,
70
+ };
71
+ }
72
+ /**
73
+ * Complete the login step for the currently authenticated nauth user.
74
+ *
75
+ * The session gate runs again here, authoritatively. A valid access token only
76
+ * proves the challenge flow completed *when it was issued*; the gate re-reads the
77
+ * account so that a user disabled, locked, or newly required to change their
78
+ * password in the meantime cannot have an id_token minted for a third party.
79
+ *
80
+ * A denied account resolves the interaction with `access_denied` rather than
81
+ * throwing, so the relying party receives a proper protocol error instead of a dead
82
+ * browser tab.
83
+ *
84
+ * @param req - The framework request
85
+ * @param res - The framework response
86
+ * @returns Where to send the browser to resume the authorization request
87
+ * @throws {NAuthException} `OIDC_INTERACTION_NOT_FOUND` when the request has expired,
88
+ * or `OIDC_LOGIN_REQUIRED` when no completed nauth login stands behind it — the
89
+ * latter carrying `uid` so the frontend can resume after logging in
90
+ */
91
+ async completeLogin(req, res) {
92
+ const raw = (0, raw_http_1.toRawHttp)(req, res);
93
+ // Loaded before the gate is consulted, so an expired interaction is reported as
94
+ // such rather than as a login problem, and so `uid` is available to the error the
95
+ // frontend has to act on.
96
+ const details = await this.loadInteraction(raw);
97
+ const gate = await this.sessionGate.evaluate();
98
+ if (gate.status === 'denied') {
99
+ this.audit(core_1.AuthAuditEventType.OIDC_ACCESS_DENIED, 'FAILURE', details, { reason: gate.reason }, undefined, gate.sub);
100
+ return this.resolve(raw, {
101
+ error: 'access_denied',
102
+ error_description: `Account unavailable (${gate.reason})`,
103
+ });
104
+ }
105
+ if (gate.status !== 'authenticated') {
106
+ throw loginRequired(details.uid, gate.reason);
107
+ }
108
+ this.audit(core_1.AuthAuditEventType.OIDC_LOGIN_COMPLETED, 'SUCCESS', details, {}, gate.user.id);
109
+ return this.resolve(raw, { login: { accountId: gate.user.sub, remember: true } }, false);
110
+ }
111
+ /**
112
+ * Record the user's consent decision.
113
+ *
114
+ * On approval this builds the provider's `Grant` — the durable record of what this
115
+ * user let this client see — and resolves the interaction with its id. On refusal it
116
+ * resolves with `access_denied`.
117
+ *
118
+ * @param req - The framework request
119
+ * @param res - The framework response
120
+ * @param decision - Whether the user approved, and optionally a narrowed scope set
121
+ * @returns Where to send the browser next
122
+ * @throws {NAuthException} `OIDC_INTERACTION_NOT_FOUND` when the request has expired,
123
+ * or `OIDC_LOGIN_REQUIRED` when the session lapsed while the consent screen was open
124
+ */
125
+ async completeConsent(req, res, decision) {
126
+ const raw = (0, raw_http_1.toRawHttp)(req, res);
127
+ const details = await this.loadInteraction(raw);
128
+ if (!decision.approve) {
129
+ this.audit(core_1.AuthAuditEventType.OIDC_CONSENT_DENIED, 'INFO', details);
130
+ return this.resolve(raw, {
131
+ error: 'access_denied',
132
+ error_description: 'The user denied the request',
133
+ });
134
+ }
135
+ // The gate runs here for the same reason it runs on login: a consent screen is
136
+ // somewhere users linger, and the session behind it can lapse — or the account be
137
+ // disabled — between the screen rendering and the button being pressed.
138
+ const gate = await this.sessionGate.evaluate();
139
+ if (gate.status === 'denied') {
140
+ this.audit(core_1.AuthAuditEventType.OIDC_ACCESS_DENIED, 'FAILURE', details, { reason: gate.reason }, undefined, gate.sub);
141
+ return this.resolve(raw, {
142
+ error: 'access_denied',
143
+ error_description: `Account unavailable (${gate.reason})`,
144
+ });
145
+ }
146
+ if (gate.status !== 'authenticated') {
147
+ throw loginRequired(details.uid, gate.reason);
148
+ }
149
+ const accountId = details.session?.accountId;
150
+ if (!accountId) {
151
+ // The provider's own login record is gone even though nauth still has a session:
152
+ // the interaction has to be restarted from the login step.
153
+ throw loginRequired(details.uid, 'no_session');
154
+ }
155
+ const promptDetails = details.prompt.details;
156
+ const grant = details.grantId
157
+ ? await this.provider.Grant.find(details.grantId)
158
+ : new this.provider.Grant({ accountId, clientId: String(details.params.client_id) });
159
+ if (!grant) {
160
+ throw new core_1.NAuthException(core_1.AuthErrorCode.OIDC_INTERACTION_NOT_FOUND, 'The grant referenced by this authorization request no longer exists', { uid: details.uid });
161
+ }
162
+ const granting = decision.scopes ?? promptDetails.missingOIDCScope ?? [];
163
+ if (granting.length > 0) {
164
+ grant.addOIDCScope(granting.join(' '));
165
+ }
166
+ if (promptDetails.missingOIDCClaims?.length) {
167
+ grant.addOIDCClaims(promptDetails.missingOIDCClaims);
168
+ }
169
+ for (const [indicator, scopes] of Object.entries(promptDetails.missingResourceScopes ?? {})) {
170
+ grant.addResourceScope(indicator, scopes.join(' '));
171
+ }
172
+ const grantId = await grant.save();
173
+ this.audit(core_1.AuthAuditEventType.OIDC_CONSENT_GRANTED, 'SUCCESS', details, { grantedScopes: granting }, gate.user.id);
174
+ return this.resolve(raw, { consent: { grantId } }, Boolean(details.grantId));
175
+ }
176
+ /**
177
+ * Abandon a pending interaction.
178
+ *
179
+ * Gives the relying party a clean `access_denied` instead of leaving it waiting on a
180
+ * browser tab the user closed.
181
+ *
182
+ * @param req - The framework request
183
+ * @param res - The framework response
184
+ * @returns Where to send the browser
185
+ */
186
+ async abort(req, res) {
187
+ const raw = (0, raw_http_1.toRawHttp)(req, res);
188
+ // Loaded first so that aborting an interaction which has already expired answers
189
+ // 404 like every other route here, rather than surfacing as a server fault.
190
+ await this.loadInteraction(raw);
191
+ return this.resolve(raw, {
192
+ error: 'access_denied',
193
+ error_description: 'End-user aborted the interaction',
194
+ });
195
+ }
196
+ /**
197
+ * Write one decision to nauth's audit trail, with the relying party attached.
198
+ *
199
+ * The ordinary `LOGIN_SUCCESS` recorded when the user typed their password cannot
200
+ * carry this: at that point the authorization request is still parked and nauth has
201
+ * no idea a third party is waiting. Here it does.
202
+ *
203
+ * Fire-and-forget, and never allowed to fail the flow — an audit backend being down
204
+ * must not stop a user signing in. Client info (IP, geolocation, device, user agent)
205
+ * is filled in automatically by the audit service, because these are ordinary nauth
206
+ * routes running inside the request context.
207
+ *
208
+ * @param eventType - Which decision this was
209
+ * @param eventStatus - How it turned out
210
+ * @param details - The interaction the decision belongs to
211
+ * @param metadata - Anything to record beyond the client and scopes
212
+ * @param userId - Internal user id, when the gate has already resolved one
213
+ * @param sub - External identifier, for a refusal where no internal id was resolved
214
+ */
215
+ audit(eventType, eventStatus, details, metadata = {}, userId, sub) {
216
+ if (!this.auditService) {
217
+ return;
218
+ }
219
+ const clientId = details.params.client_id === undefined ? undefined : String(details.params.client_id);
220
+ // At the login step the provider has not recorded an account yet, so a refusal has
221
+ // to be attributed from the gate's own verdict instead.
222
+ const account = sub ?? details.session?.accountId;
223
+ // Without one of these the audit service cannot resolve a user, and would only log
224
+ // a warning per event.
225
+ if (userId === undefined && !account) {
226
+ return;
227
+ }
228
+ void this.auditService
229
+ .recordEvent({
230
+ ...(userId === undefined ? { sub: account } : { userId }),
231
+ eventType,
232
+ eventStatus,
233
+ authMethod: 'oidc',
234
+ metadata: {
235
+ clientId,
236
+ interactionUid: details.uid,
237
+ requestedScopes: String(details.params.scope ?? '')
238
+ .split(/\s+/)
239
+ .filter(Boolean),
240
+ ...metadata,
241
+ },
242
+ })
243
+ .catch(() => {
244
+ // Auditing must never break the authorization flow.
245
+ });
246
+ }
247
+ /**
248
+ * Read the pending interaction, or say plainly that there isn't one.
249
+ *
250
+ * `interactionDetails` throws `SessionNotFound` for an interaction that has expired,
251
+ * been resolved already, or never existed — all of which are a 404 to the caller, not
252
+ * a server fault.
253
+ *
254
+ * @param raw - The unwrapped Node request and response
255
+ * @returns The provider's view of the pending interaction
256
+ * @throws {NAuthException} `OIDC_INTERACTION_NOT_FOUND` when there is no such interaction
257
+ */
258
+ async loadInteraction(raw) {
259
+ try {
260
+ return await this.provider.interactionDetails(raw.req, raw.res);
261
+ }
262
+ catch (error) {
263
+ throw new core_1.NAuthException(core_1.AuthErrorCode.OIDC_INTERACTION_NOT_FOUND, 'This authorization request has expired or was already completed', { cause: error instanceof Error ? error.message : String(error) });
264
+ }
265
+ }
266
+ /**
267
+ * Resolve the interaction and report where the browser should go.
268
+ *
269
+ * @param raw - The unwrapped Node request and response
270
+ * @param result - What to resolve the interaction with
271
+ * @param mergeWithLastSubmission - Whether to merge into the previous submission
272
+ * @returns The provider's redirect target
273
+ */
274
+ async resolve(raw, result, mergeWithLastSubmission = true) {
275
+ return {
276
+ redirectTo: await this.provider.interactionResult(raw.req, raw.res, result, {
277
+ mergeWithLastSubmission,
278
+ }),
279
+ };
280
+ }
281
+ }
282
+ exports.OIDCInteractionBridge = OIDCInteractionBridge;
283
+ //# sourceMappingURL=interaction-bridge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interaction-bridge.js","sourceRoot":"","sources":["../../src/interaction-bridge.ts"],"names":[],"mappings":";;;AAEA,8CAAwF;AAExF,yCAAuC;AA+CvC;;;;;;;;;;GAUG;AACH,SAAS,aAAa,CAAC,GAAW,EAAE,MAAc;IAChD,OAAO,IAAI,qBAAc,CACvB,oBAAa,CAAC,mBAAmB,EACjC,sEAAsE,EACtE,EAAE,GAAG,EAAE,MAAM,EAAE,CAChB,CAAC;AACJ,CAAC;AAED,MAAa,qBAAqB;IASb;IACA;IACA;IAVnB;;;;;;OAMG;IACH,YACmB,QAAkB,EAClB,WAA2B,EAC3B,YAA+B;QAF/B,aAAQ,GAAR,QAAQ,CAAU;QAClB,gBAAW,GAAX,WAAW,CAAgB;QAC3B,iBAAY,GAAZ,YAAY,CAAmB;IAC/C,CAAC;IAEJ;;;;;;;;;;OAUG;IACH,KAAK,CAAC,QAAQ,CAA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iB,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE;gBAC1E,uBAAuB;aACxB,CAAC;SACH,CAAC;IACJ,CAAC;CACF;AAxUD,sDAwUC"}
@@ -0,0 +1,54 @@
1
+ import type Provider from 'oidc-provider';
2
+ /** Minimal shape of the Express-like app this helper mounts onto. */
3
+ interface MountableApp {
4
+ use(handler: (req: MountableRequest, res: unknown, next: () => void) => void): unknown;
5
+ }
6
+ /** Minimal shape of the request this helper inspects. */
7
+ interface MountableRequest {
8
+ url?: string;
9
+ path?: string;
10
+ }
11
+ /**
12
+ * Mount an `oidc-provider` instance onto an Express-style application.
13
+ *
14
+ * The provider is given the request **without any URL rewriting**. That is deliberate
15
+ * and load-bearing: its routes are configured with the path prefix already baked in,
16
+ * so it must see the full path. Mounting the conventional way, with
17
+ * `app.use('/oidc', provider.callback())`, strips the prefix and breaks every URL the
18
+ * provider generates.
19
+ *
20
+ * `provider.callback()` is Koa's — arity `(req, res)`, with no `next` — so it can
21
+ * never pass a request on. The gate below decides what reaches it and lets everything
22
+ * else continue to the rest of the application.
23
+ *
24
+ * Mount this **before** body-parsing middleware where you can. `oidc-provider` falls
25
+ * back to a pre-parsed `req.body` if the stream is already consumed, so it works
26
+ * either way, but mounting first avoids a startup warning and keeps the provider's own
27
+ * request size limit rather than deferring to the upstream parser's.
28
+ *
29
+ * @param app - The Express application
30
+ * @param provider - A configured provider
31
+ * @param options - The path prefix its routes were configured with
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * const app = express();
36
+ * mountOIDCProviderExpress(app, provider, { pathPrefix: '/oidc' });
37
+ * app.use(express.json());
38
+ * ```
39
+ */
40
+ export declare function mountOIDCProviderExpress(app: MountableApp, provider: Provider, options?: {
41
+ pathPrefix?: string;
42
+ }): void;
43
+ /**
44
+ * Whether a request belongs to the provider.
45
+ *
46
+ * Discovery lives at the origin root, not under the prefix, because the issuer is a
47
+ * bare origin — that is exactly where OpenID Connect Discovery says it belongs.
48
+ */
49
+ export declare function isProviderPath(req: {
50
+ url?: string;
51
+ path?: string;
52
+ }, prefix: string): boolean;
53
+ export {};
54
+ //# sourceMappingURL=express.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"express.d.ts","sourceRoot":"","sources":["../../../src/mount/express.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAC;AAE1C,qEAAqE;AACrE,UAAU,YAAY;IACpB,GAAG,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,gBAAgB,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,IAAI,KAAK,IAAI,GAAG,OAAO,CAAC;CACxF;AAED,yDAAyD;AACzD,UAAU,gBAAgB;IACxB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,wBAAwB,CACtC,GAAG,EAAE,YAAY,EACjB,QAAQ,EAAE,QAAQ,EAClB,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAA;CAAO,GACpC,IAAI,CAYN;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAG5F"}
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mountOIDCProviderExpress = mountOIDCProviderExpress;
4
+ exports.isProviderPath = isProviderPath;
5
+ /**
6
+ * Mount an `oidc-provider` instance onto an Express-style application.
7
+ *
8
+ * The provider is given the request **without any URL rewriting**. That is deliberate
9
+ * and load-bearing: its routes are configured with the path prefix already baked in,
10
+ * so it must see the full path. Mounting the conventional way, with
11
+ * `app.use('/oidc', provider.callback())`, strips the prefix and breaks every URL the
12
+ * provider generates.
13
+ *
14
+ * `provider.callback()` is Koa's — arity `(req, res)`, with no `next` — so it can
15
+ * never pass a request on. The gate below decides what reaches it and lets everything
16
+ * else continue to the rest of the application.
17
+ *
18
+ * Mount this **before** body-parsing middleware where you can. `oidc-provider` falls
19
+ * back to a pre-parsed `req.body` if the stream is already consumed, so it works
20
+ * either way, but mounting first avoids a startup warning and keeps the provider's own
21
+ * request size limit rather than deferring to the upstream parser's.
22
+ *
23
+ * @param app - The Express application
24
+ * @param provider - A configured provider
25
+ * @param options - The path prefix its routes were configured with
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * const app = express();
30
+ * mountOIDCProviderExpress(app, provider, { pathPrefix: '/oidc' });
31
+ * app.use(express.json());
32
+ * ```
33
+ */
34
+ function mountOIDCProviderExpress(app, provider, options = {}) {
35
+ const prefix = options.pathPrefix ?? '/oidc';
36
+ const callback = provider.callback();
37
+ app.use((req, res, next) => {
38
+ if (isProviderPath(req, prefix)) {
39
+ // Hand the raw Node objects straight over; the provider owns the response.
40
+ callback(req, res);
41
+ return;
42
+ }
43
+ next();
44
+ });
45
+ }
46
+ /**
47
+ * Whether a request belongs to the provider.
48
+ *
49
+ * Discovery lives at the origin root, not under the prefix, because the issuer is a
50
+ * bare origin — that is exactly where OpenID Connect Discovery says it belongs.
51
+ */
52
+ function isProviderPath(req, prefix) {
53
+ const path = (req.path ?? req.url ?? '').split('?')[0];
54
+ return path.startsWith(`${prefix}/`) || path === prefix || path.startsWith('/.well-known/');
55
+ }
56
+ //# sourceMappingURL=express.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"express.js","sourceRoot":"","sources":["../../../src/mount/express.ts"],"names":[],"mappings":";;AA0CA,4DAgBC;AAQD,wCAGC;AAxDD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,SAAgB,wBAAwB,CACtC,GAAiB,EACjB,QAAkB,EAClB,UAAmC,EAAE;IAErC,MAAM,MAAM,GAAG,OAAO,CAAC,UAAU,IAAI,OAAO,CAAC;IAC7C,MAAM,QAAQ,GAAG,QAAQ,CAAC,QAAQ,EAAE,CAAC;IAErC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAqB,EAAE,GAAY,EAAE,IAAgB,EAAE,EAAE;QAChE,IAAI,cAAc,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,CAAC;YAChC,2EAA2E;YAC1E,QAA0D,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;YACtE,OAAO;QACT,CAAC;QACD,IAAI,EAAE,CAAC;IACT,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,SAAgB,cAAc,CAAC,GAAoC,EAAE,MAAc;IACjF,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,GAAG,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,MAAM,GAAG,CAAC,IAAI,IAAI,KAAK,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC,eAAe,CAAC,CAAC;AAC9F,CAAC"}