@okeav/idp-pg 0.0.0-stage → 0.1.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 (111) hide show
  1. package/.env.example +159 -0
  2. package/CHANGELOG.md +58 -0
  3. package/LICENSE +21 -0
  4. package/README.md +275 -3
  5. package/package.json +78 -6
  6. package/src/cache/cache-adapter.js +22 -0
  7. package/src/cache/index.js +68 -0
  8. package/src/cache/memory.adapter.js +85 -0
  9. package/src/cache/redis.adapter.js +96 -0
  10. package/src/config/console-logger.js +10 -0
  11. package/src/config/constants.js +178 -0
  12. package/src/config/defaults.js +100 -0
  13. package/src/config/from-env.js +150 -0
  14. package/src/config/init.js +286 -0
  15. package/src/config/state.js +22 -0
  16. package/src/errors/error-codes.js +97 -0
  17. package/src/errors/idp-error.js +75 -0
  18. package/src/hooks/index.js +85 -0
  19. package/src/index.js +167 -0
  20. package/src/magic-link/controller.js +129 -0
  21. package/src/magic-link/schemas.js +12 -0
  22. package/src/mfa/attempt-guard.js +48 -0
  23. package/src/mfa/controller.js +309 -0
  24. package/src/mfa/factor-store.js +37 -0
  25. package/src/mfa/memory-attempt-counter.js +58 -0
  26. package/src/mfa/schemas.js +11 -0
  27. package/src/mfa/secret-cipher.js +133 -0
  28. package/src/mfa/secrets.js +156 -0
  29. package/src/middleware/auth-context.middleware.js +149 -0
  30. package/src/middleware/cookie-parser.js +4 -0
  31. package/src/middleware/csrf.js +48 -0
  32. package/src/middleware/require-recent-auth.middleware.js +30 -0
  33. package/src/middleware/require-service-caller.middleware.js +32 -0
  34. package/src/middleware/service-context.middleware.js +70 -0
  35. package/src/middleware/validate-body.js +16 -0
  36. package/src/middleware/validate-query.js +22 -0
  37. package/src/oauth2/authorize.controller.js +233 -0
  38. package/src/oauth2/client-auth.js +77 -0
  39. package/src/oauth2/client.controller.js +122 -0
  40. package/src/oauth2/consent.controller.js +63 -0
  41. package/src/oauth2/login-challenge.js +50 -0
  42. package/src/oauth2/redirect-uri.js +25 -0
  43. package/src/oauth2/schemas.js +103 -0
  44. package/src/oauth2/token.controller.js +370 -0
  45. package/src/oidc/discovery.controller.js +36 -0
  46. package/src/oidc/end-session.controller.js +137 -0
  47. package/src/oidc/userinfo.controller.js +49 -0
  48. package/src/password-auth/controllers.js +927 -0
  49. package/src/password-auth/schemas.js +76 -0
  50. package/src/rate-limit/enforce.js +35 -0
  51. package/src/rate-limit/index.js +48 -0
  52. package/src/rate-limit/keys.js +36 -0
  53. package/src/rate-limit/memory.adapter.js +75 -0
  54. package/src/rate-limit/noop.adapter.js +14 -0
  55. package/src/rate-limit/rate-limiter.js +18 -0
  56. package/src/rate-limit/redis.adapter.js +71 -0
  57. package/src/routes/build-router.js +238 -0
  58. package/src/security/attempt-budget.js +47 -0
  59. package/src/security/clock-skew.js +63 -0
  60. package/src/service-mesh/key-status.js +22 -0
  61. package/src/service-mesh/local-key-lookup.js +12 -0
  62. package/src/service-mesh/remote-jwks-key-lookup.js +74 -0
  63. package/src/service-mesh/s2s-bootstrap.middleware.js +41 -0
  64. package/src/service-mesh/service-identity.client.js +89 -0
  65. package/src/service-mesh/service-key.controller.js +170 -0
  66. package/src/service-mesh/verify-service-token.js +75 -0
  67. package/src/signing/jwks.controller.js +30 -0
  68. package/src/signing/jwks.js +24 -0
  69. package/src/signing/key-registry.js +97 -0
  70. package/src/signing/token.service.js +336 -0
  71. package/src/sso/binding.js +30 -0
  72. package/src/sso/callback.controller.js +186 -0
  73. package/src/sso/initiate.controller.js +92 -0
  74. package/src/sso/providers.js +237 -0
  75. package/src/sso/schemas.js +7 -0
  76. package/src/storage/interfaces.js +178 -0
  77. package/src/storage/postgres/db.js +68 -0
  78. package/src/storage/postgres/index.js +160 -0
  79. package/src/storage/postgres/migrations/run-migrations.js +122 -0
  80. package/src/storage/postgres/migrations/sql/0001_init.sql +253 -0
  81. package/src/storage/postgres/repositories/attempt-counter.repository.js +65 -0
  82. package/src/storage/postgres/repositories/authorization-code.repository.js +104 -0
  83. package/src/storage/postgres/repositories/consent.repository.js +68 -0
  84. package/src/storage/postgres/repositories/credential.repository.js +75 -0
  85. package/src/storage/postgres/repositories/oauth-client.repository.js +122 -0
  86. package/src/storage/postgres/repositories/service-key.repository.js +76 -0
  87. package/src/storage/postgres/repositories/session.repository.js +290 -0
  88. package/src/storage/postgres/repositories/user.repository.js +328 -0
  89. package/src/storage/postgres/repositories/verification-token.repository.js +138 -0
  90. package/src/storage/postgres/run.js +22 -0
  91. package/src/utils/account-status.js +26 -0
  92. package/src/utils/cookies.js +129 -0
  93. package/src/utils/device-fingerprint.js +58 -0
  94. package/src/utils/email-hash.js +23 -0
  95. package/src/utils/oauth-client-credentials.js +51 -0
  96. package/src/utils/password.js +40 -0
  97. package/src/utils/safe-equal.js +12 -0
  98. package/src/utils/session-family.js +158 -0
  99. package/src/utils/session-kind.js +15 -0
  100. package/src/utils/url.js +17 -0
  101. package/src/webauthn/authentication.controller.js +126 -0
  102. package/src/webauthn/challenge-store.js +17 -0
  103. package/src/webauthn/config.js +25 -0
  104. package/src/webauthn/mfa.controller.js +119 -0
  105. package/src/webauthn/registration.controller.js +128 -0
  106. package/src/webauthn/schemas.js +41 -0
  107. package/src/webauthn/shared.js +63 -0
  108. package/src/webhooks/dispatcher.js +135 -0
  109. package/src/webhooks/sign.js +55 -0
  110. package/src/webhooks/wrap-hooks.js +51 -0
  111. package/types/index.d.ts +777 -0
@@ -0,0 +1,97 @@
1
+ import crypto from 'crypto';
2
+ import { KEY_STATUS } from '../config/constants.js';
3
+
4
+ /**
5
+ * Normalizes a key-material value into a PEM string. Accepts either a raw
6
+ * PEM (detected by the `-----BEGIN` header) or a base64-encoded PEM (the
7
+ * convention the audited Okeav services used, since PEM newlines don't
8
+ * survive some secret-store transports unscathed).
9
+ */
10
+ export function resolveKeyMaterial(value) {
11
+ if (!value) return null;
12
+ if (value.includes('-----BEGIN')) return value;
13
+ return Buffer.from(value, 'base64').toString('utf8');
14
+ }
15
+
16
+ /**
17
+ * @param {Record<string, {privateKey?: string, publicKey: string, status: string}>} keysConfig
18
+ * @returns {Record<string, {privateKeyPem: string|null, publicKeyPem: string, status: string}>}
19
+ */
20
+ export function buildKeyRegistry(keysConfig = {}) {
21
+ const registry = {};
22
+ for (const [kid, entry] of Object.entries(keysConfig)) {
23
+ registry[kid] = {
24
+ privateKeyPem: entry.privateKey ? resolveKeyMaterial(entry.privateKey) : null,
25
+ publicKeyPem: resolveKeyMaterial(entry.publicKey),
26
+ status: entry.status || KEY_STATUS.ACTIVE,
27
+ };
28
+ assertUsableKey(kid, registry[kid]);
29
+ }
30
+ return registry;
31
+ }
32
+
33
+ /** Startup check: the IdP must be able to sign — at least one ACTIVE (or ROTATING) key with its private key. */
34
+ export function assertCanSign(registry) {
35
+ if (!Object.values(registry).some((k) => k.privateKeyPem && [KEY_STATUS.ACTIVE, KEY_STATUS.ROTATING].includes(k.status))) {
36
+ throw new Error('config.signingKeys: at least one ACTIVE (or ROTATING) key needs a privateKey to sign with');
37
+ }
38
+ }
39
+
40
+ const MIN_RSA_BITS = 2048;
41
+
42
+ /**
43
+ * Fails at startup — not at the first login — on a signing key that can't work or isn't safe: an
44
+ * unparseable PEM, a non-RSA key (tokens are RS256), one under 2048 bits, an unknown status, or a
45
+ * private key that doesn't belong to its public key.
46
+ */
47
+ function assertUsableKey(kid, { privateKeyPem, publicKeyPem, status }) {
48
+ const where = `config.signingKeys.keys["${kid}"]`;
49
+ if (!Object.values(KEY_STATUS).includes(status)) throw new Error(`${where}.status must be one of ${Object.values(KEY_STATUS).join(', ')}`);
50
+ let publicKey;
51
+ try {
52
+ publicKey = crypto.createPublicKey(publicKeyPem);
53
+ } catch {
54
+ throw new Error(`${where}.publicKey is not a valid public key (PEM, or base64-encoded PEM)`);
55
+ }
56
+ if (publicKey.asymmetricKeyType !== 'rsa') throw new Error(`${where} must be an RSA key (tokens are signed RS256)`);
57
+ if ((publicKey.asymmetricKeyDetails?.modulusLength ?? 0) < MIN_RSA_BITS) throw new Error(`${where} must be at least ${MIN_RSA_BITS} bits`);
58
+ if (!privateKeyPem) return;
59
+ let privateKey;
60
+ try {
61
+ privateKey = crypto.createPrivateKey(privateKeyPem);
62
+ } catch {
63
+ throw new Error(`${where}.privateKey is not a valid private key (PEM, or base64-encoded PEM)`);
64
+ }
65
+ const probe = Buffer.from(`idp-key-check:${kid}`);
66
+ const signature = crypto.sign('sha256', probe, privateKey);
67
+ if (!crypto.verify('sha256', probe, publicKey, signature)) throw new Error(`${where}: privateKey and publicKey are not a pair`);
68
+ }
69
+
70
+ const PUBLISHABLE_STATUSES = [KEY_STATUS.ACTIVE, KEY_STATUS.ROTATING];
71
+
72
+ /** Returns [kid, entry] for the current signing key — ACTIVE preferred, ROTATING as fallback. */
73
+ export function getActiveSigningKey(registry) {
74
+ const active = Object.entries(registry).find(([, k]) => k.status === KEY_STATUS.ACTIVE);
75
+ if (active) return active;
76
+ const rotating = Object.entries(registry).find(([, k]) => k.status === KEY_STATUS.ROTATING);
77
+ if (rotating) return rotating;
78
+ throw new Error('No ACTIVE or ROTATING signing key configured — set config.signingKeys.keys');
79
+ }
80
+
81
+ /** Every key eligible for verification (ACTIVE + ROTATING), most recently active first. */
82
+ export function getVerifiableKeys(registry) {
83
+ return Object.entries(registry).filter(([, k]) => PUBLISHABLE_STATUSES.includes(k.status));
84
+ }
85
+
86
+ /**
87
+ * Looks up a key for verification purposes by `kid`. A REVOKED key never
88
+ * verifies, regardless of `kid` match — this is the one status that must
89
+ * actually invalidate previously-issued tokens, not just stop being
90
+ * published/used for new signing. ACTIVE/ROTATING/RETIRED all still verify,
91
+ * matching the set `/keys/:kid` allows.
92
+ */
93
+ export function getPublicKeyByKid(registry, kid) {
94
+ const entry = registry[kid];
95
+ if (!entry || entry.status === KEY_STATUS.REVOKED) return null;
96
+ return entry.publicKeyPem;
97
+ }
@@ -0,0 +1,336 @@
1
+ import crypto from 'crypto';
2
+ import jwt from 'jsonwebtoken';
3
+ import { getActiveSigningKey, getVerifiableKeys, getPublicKeyByKid } from './key-registry.js';
4
+ import { IdpError } from '../errors/idp-error.js';
5
+ import { TOKEN_TYPES, ACCESS_TOKEN_KINDS, GRANT_TYPES } from '../config/constants.js';
6
+
7
+ const ALGORITHM = 'RS256';
8
+
9
+ /**
10
+ * @param {object} state - the initialized IDP state (see config/state.js)
11
+ * @param {{ sub: string, email?: string, claims?: Record<string, unknown> }} input
12
+ * @param {{ ttlSeconds?: number, audience?: string, sessionless?: boolean, authTime?: number }} [opts] - `sessionless: true`
13
+ * marks a token that has no session row behind it, so authContextMiddleware's per-request session
14
+ * check (`session.verifyOnEachRequest`) skips it instead of refusing it. Internal session-backed
15
+ * issuance (login, refresh) never sets it.
16
+ */
17
+ export async function issueAccessToken(state, input, opts = {}) {
18
+ const { sub, email, claims = {} } = input;
19
+ if (!sub) throw new IdpError({ code: 'MISSING_REQUIRED_FIELDS', httpStatus: 400, message: 'sub is required to issue an access token' });
20
+
21
+ const issuedAt = Math.floor(Date.now() / 1000);
22
+ const ttl = opts.ttlSeconds ?? state.config.ttls.accessToken;
23
+ const expiresAt = issuedAt + ttl;
24
+ const [kid, key] = getActiveSigningKey(state.signingKeys);
25
+
26
+ const payload = {
27
+ sub,
28
+ email,
29
+ claims,
30
+ type: TOKEN_TYPES.ACCESS,
31
+ iss: state.config.issuer,
32
+ aud: opts.audience ?? state.config.issuer,
33
+ jti: crypto.randomUUID(),
34
+ iat: issuedAt,
35
+ exp: expiresAt,
36
+ // When the user last actually authenticated (seconds) — carried unchanged across refreshes,
37
+ // so requireRecentAuth can demand a fresh login before sensitive changes.
38
+ ...(Number.isInteger(opts.authTime) ? { auth_time: opts.authTime } : {}),
39
+ ...(opts.sessionless ? { sessionless: true } : {}),
40
+ };
41
+
42
+ const token = jwt.sign(payload, key.privateKeyPem, { algorithm: ALGORITHM, keyid: kid });
43
+ return { token, expiresAt: new Date(expiresAt * 1000), kid, jti: payload.jti };
44
+ }
45
+
46
+ /**
47
+ * Which party an access token was issued to:
48
+ * - `first-party` — this IdP's own login/refresh (and the public `issueAccessToken()` export). No `client_id`.
49
+ * - `oauth2-user` — issued to an OAuth2 client on behalf of a user (authorization_code / refresh_token grants).
50
+ * - `oauth2-client` — a client_credentials machine token; the client itself is the subject, there is no user.
51
+ */
52
+ /** Upper bounds for a client's own token lifetimes (also enforced at registration; this covers older rows). */
53
+ export const MAX_CLIENT_TTL_SECONDS = Object.freeze({ accessTokenTTL: 24 * 60 * 60, idTokenTTL: 24 * 60 * 60, refreshTokenTTL: 365 * 24 * 60 * 60 });
54
+
55
+ /** A client's configured lifetime for `key`, or `fallback` — never above MAX_CLIENT_TTL_SECONDS. */
56
+ export function clientTtl(client, key, fallback) {
57
+ const value = Number.isInteger(client?.[key]) && client[key] > 0 ? client[key] : fallback;
58
+ return value === undefined ? undefined : Math.min(value, MAX_CLIENT_TTL_SECONDS[key]);
59
+ }
60
+
61
+ export function classifyAccessToken(payload) {
62
+ if (!payload?.client_id) return ACCESS_TOKEN_KINDS.FIRST_PARTY;
63
+ if (payload.gty === GRANT_TYPES.CLIENT_CREDENTIALS || payload.sub === payload.client_id) return ACCESS_TOKEN_KINDS.OAUTH2_CLIENT;
64
+ return ACCESS_TOKEN_KINDS.OAUTH2_USER;
65
+ }
66
+
67
+ const INVALID_AUDIENCE = (message) => new IdpError({ code: 'INVALID_TOKEN', httpStatus: 401, message });
68
+
69
+ /**
70
+ * Verifies signature, issuer, expiry, `type: access_token`, AND which party the token was issued to.
71
+ *
72
+ * @param {{ issuer?: string, audience?: string | string[], accept?: Array<'first-party'|'oauth2-user'|'oauth2-client'> }} [opts]
73
+ * `accept` defaults to `['first-party']`: an access token minted for a third-party OAuth2 client
74
+ * (aud = that client) is NOT a credential for this IdP's own routes — otherwise any relying party a
75
+ * user authorized could act as that user here. `audience` is the `aud` a first-party token must carry
76
+ * (default: the issuer). OAuth2 tokens must carry `aud === client_id`.
77
+ */
78
+ export async function verifyAccessToken(state, token, opts = {}) {
79
+ const payload = await verifyWithAnyKey(state, token, { issuer: opts.issuer ?? state.config.issuer });
80
+ if (payload.type !== TOKEN_TYPES.ACCESS) {
81
+ throw new IdpError({ code: 'INVALID_TOKEN', httpStatus: 401, message: 'Token is not an access token' });
82
+ }
83
+
84
+ const accept = opts.accept ?? [ACCESS_TOKEN_KINDS.FIRST_PARTY];
85
+ const kind = classifyAccessToken(payload);
86
+ if (!accept.includes(kind)) {
87
+ throw INVALID_AUDIENCE(`Token kind "${kind}" is not accepted here`);
88
+ }
89
+
90
+ const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
91
+ if (kind === ACCESS_TOKEN_KINDS.FIRST_PARTY) {
92
+ const expected = [].concat(opts.audience ?? state.config.issuer);
93
+ if (!audiences.some((a) => expected.includes(a))) throw INVALID_AUDIENCE('Token audience is not accepted here');
94
+ } else if (!audiences.includes(payload.client_id)) {
95
+ throw INVALID_AUDIENCE('Token audience does not match its client');
96
+ }
97
+ return payload;
98
+ }
99
+
100
+ /**
101
+ * @param {{ scopes?: string[], authTime?: number, ttlSeconds?: number }} [opts] - `scopes` decide
102
+ * which user claims are released (OIDC Core §5.4: `email` → email + email_verified, `profile` →
103
+ * name, picture, locale …). Default: openid email profile (the pre-0.4.0 behaviour, kept for the
104
+ * public export). `authTime` (seconds) becomes `auth_time`.
105
+ */
106
+ export async function issueIdToken(state, user, audience, nonce, opts = {}) {
107
+ const now = Math.floor(Date.now() / 1000);
108
+ const expiresAt = now + (opts.ttlSeconds ?? state.config.ttls.idToken);
109
+ const [kid, key] = getActiveSigningKey(state.signingKeys);
110
+ const scopes = new Set(opts.scopes ?? ['openid', 'email', 'profile']);
111
+
112
+ const claims = {
113
+ sub: String(user.id),
114
+ ...(scopes.has('email') ? { email: user.email, email_verified: user.status !== 'PENDING_VERIFICATION' } : {}),
115
+ ...(scopes.has('profile') ? {
116
+ name: user.profile?.displayName || [user.profile?.firstName, user.profile?.lastName].filter(Boolean).join(' ') || undefined,
117
+ given_name: user.profile?.firstName || undefined,
118
+ family_name: user.profile?.lastName || undefined,
119
+ picture: user.profile?.avatarUrl || undefined,
120
+ locale: user.profile?.locale || undefined,
121
+ zoneinfo: user.profile?.zoneinfo || undefined,
122
+ } : {}),
123
+ aud: audience,
124
+ azp: audience,
125
+ iss: state.config.issuer,
126
+ jti: crypto.randomUUID(),
127
+ iat: now,
128
+ exp: expiresAt,
129
+ ...(Number.isInteger(opts.authTime) ? { auth_time: opts.authTime } : {}),
130
+ ...(nonce ? { nonce } : {}),
131
+ };
132
+ Object.keys(claims).forEach((k) => claims[k] === undefined && delete claims[k]);
133
+
134
+ const token = jwt.sign(claims, key.privateKeyPem, { algorithm: ALGORITHM, keyid: kid });
135
+ return { token, expiresAt: new Date(expiresAt * 1000), kid, jti: claims.jti };
136
+ }
137
+
138
+ export async function issueOAuth2AccessToken(state, subject, client, scopes, { sessionless = false, grantType } = {}) {
139
+ const now = Math.floor(Date.now() / 1000);
140
+ const ttl = clientTtl(client, 'accessTokenTTL', state.config.ttls.accessToken);
141
+ const expiresAt = now + ttl;
142
+ const [kid, key] = getActiveSigningKey(state.signingKeys);
143
+
144
+ const claims = {
145
+ sub: String(subject.id),
146
+ // Top-level `scope`/`client_id` per OAuth2/OIDC convention (RFC 6749,
147
+ // RFC 7519) for resource servers that read raw JWT claims directly —
148
+ // also nested under `claims` so this token verifies through the same
149
+ // `verifyAccessToken`/`authContextMiddleware` path as password- and
150
+ // SSO-issued tokens (both require `type: 'access_token'`, which a
151
+ // flat OAuth2-only claim set would otherwise lack).
152
+ scope: scopes.join(' '),
153
+ client_id: client.clientId,
154
+ claims: { scope: scopes.join(' '), clientId: client.clientId },
155
+ type: TOKEN_TYPES.ACCESS,
156
+ aud: client.clientId,
157
+ iss: state.config.issuer,
158
+ jti: crypto.randomUUID(),
159
+ iat: now,
160
+ exp: expiresAt,
161
+ // Marks a machine token (no user) so it can never pass as a user identity — see classifyAccessToken.
162
+ ...(grantType === GRANT_TYPES.CLIENT_CREDENTIALS ? { gty: GRANT_TYPES.CLIENT_CREDENTIALS } : {}),
163
+ ...(sessionless ? { sessionless: true } : {}),
164
+ };
165
+
166
+ const token = jwt.sign(claims, key.privateKeyPem, { algorithm: ALGORITHM, keyid: kid });
167
+ return { token, expiresAt: new Date(expiresAt * 1000), kid, jti: claims.jti };
168
+ }
169
+
170
+ /**
171
+ * `opts.sessionEpoch`: the user's sessionEpoch as read BEFORE the first factor was checked. The
172
+ * challenge is refused at /mfa/verify if the user's sessions were revoked since (password reset,
173
+ * logout-all), and the session it completes belongs to that epoch.
174
+ */
175
+ export async function issueMfaChallengeToken(state, subjectId, { sessionEpoch, loginChallenge } = {}) {
176
+ const now = Math.floor(Date.now() / 1000);
177
+ const expiresAt = now + state.config.ttls.mfaChallenge;
178
+ const [kid, key] = getActiveSigningKey(state.signingKeys);
179
+
180
+ const claims = {
181
+ sub: String(subjectId),
182
+ type: TOKEN_TYPES.MFA_CHALLENGE,
183
+ iss: state.config.issuer,
184
+ aud: mfaChallengeAudience(state),
185
+ jti: crypto.randomUUID(),
186
+ iat: now,
187
+ exp: expiresAt,
188
+ ...(Number.isInteger(sessionEpoch) ? { sep: sessionEpoch } : {}),
189
+ // An /oauth2/authorize login challenge this sign-in was started for — bound once MFA completes.
190
+ ...(typeof loginChallenge === 'string' ? { lch: loginChallenge } : {}),
191
+ };
192
+
193
+ return jwt.sign(claims, key.privateKeyPem, { algorithm: ALGORITHM, keyid: kid });
194
+ }
195
+
196
+ const mfaChallengeAudience = (state) => `${state.config.issuer}#mfa-challenge`;
197
+
198
+ export function verifyMfaChallengeToken(state, token) {
199
+ for (const [, key] of getVerifiableKeys(state.signingKeys)) {
200
+ try {
201
+ // Issuer and audience pinned: a challenge from another environment sharing a signing key
202
+ // (or any other token type) is not one of ours.
203
+ const decoded = jwt.verify(token, key.publicKeyPem, { algorithms: [ALGORITHM], issuer: state.config.issuer, audience: mfaChallengeAudience(state) });
204
+ if (decoded.type !== TOKEN_TYPES.MFA_CHALLENGE) continue;
205
+ return decoded;
206
+ } catch {
207
+ // try next key
208
+ }
209
+ }
210
+ throw new IdpError({ code: 'INVALID_MFA_CHALLENGE_TOKEN', httpStatus: 401, message: 'Invalid or expired MFA challenge token' });
211
+ }
212
+
213
+ /** Generic "did we issue this" verification — returns null instead of throwing. Used by end-session's id_token_hint. */
214
+ export function verifyIssuedToken(state, token, opts = {}) {
215
+ if (!token || typeof token !== 'string') return null;
216
+ for (const [, key] of getVerifiableKeys(state.signingKeys)) {
217
+ try {
218
+ return jwt.verify(token, key.publicKeyPem, {
219
+ algorithms: [ALGORITHM],
220
+ ...(opts.issuer ? { issuer: opts.issuer } : {}),
221
+ ...(opts.ignoreExpiration ? { ignoreExpiration: true } : {}),
222
+ });
223
+ } catch {
224
+ // try next key
225
+ }
226
+ }
227
+ return null;
228
+ }
229
+
230
+ /**
231
+ * True for an ID token this IdP issued (verify the signature first): no `type` (access and MFA
232
+ * challenge tokens have one), no `client_id` (OAuth2 access tokens have one), and an audience that
233
+ * is a client — never the IdP itself.
234
+ */
235
+ export function isIdTokenPayload(state, payload) {
236
+ return Boolean(payload) && payload.type === undefined && payload.client_id === undefined
237
+ && typeof payload.aud === 'string' && payload.aud !== state.config.issuer && typeof payload.sub === 'string';
238
+ }
239
+
240
+ async function verifyWithAnyKey(state, token, { issuer } = {}) {
241
+ const decoded = jwt.decode(token, { complete: true });
242
+ const kid = decoded?.header?.kid;
243
+ const publicKeyPem = kid ? getPublicKeyByKid(state.signingKeys, kid) : null;
244
+
245
+ const tryVerify = (pem) => jwt.verify(token, pem, { algorithms: [ALGORITHM], clockTolerance: 30, ...(issuer ? { issuer } : {}) });
246
+
247
+ try {
248
+ if (publicKeyPem) return tryVerify(publicKeyPem);
249
+ // Unknown/missing kid — fall through to trying every verifiable key.
250
+ for (const [, key] of getVerifiableKeys(state.signingKeys)) {
251
+ try { return tryVerify(key.publicKeyPem); } catch { /* try next */ }
252
+ }
253
+ throw new Error('no matching key');
254
+ } catch (err) {
255
+ if (err?.name === 'TokenExpiredError') {
256
+ throw new IdpError({ code: 'TOKEN_EXPIRED', httpStatus: 401, message: 'Token expired' });
257
+ }
258
+ throw new IdpError({ code: 'INVALID_TOKEN', httpStatus: 401, message: 'Invalid token', cause: err });
259
+ }
260
+ }
261
+
262
+ // ── Opaque-token hashing (refresh tokens, codes, links, recovery codes, client secrets) ──
263
+
264
+ /**
265
+ * What a keyed hash is for. Each purpose gets its own key, derived from `security.tokenHashSecret`
266
+ * (HKDF-SHA256, the purpose as `info`): a hash made for one purpose never verifies as another, and
267
+ * no stored hash is keyed by the secret itself.
268
+ */
269
+ export const HASH_PURPOSES = Object.freeze({
270
+ REFRESH_TOKEN: 'refresh-token',
271
+ AUTHORIZATION_CODE: 'authorization-code',
272
+ EMAIL_VERIFICATION_LINK: 'email-verification-link',
273
+ EMAIL_VERIFICATION_CODE: 'email-verification-code',
274
+ EMAIL_VERIFICATION_TICKET: 'email-verification-ticket',
275
+ REFRESH_COOKIE_BINDING: 'refresh-cookie-binding',
276
+ PASSWORD_RESET: 'password-reset',
277
+ MAGIC_LINK: 'magic-link',
278
+ MFA_RECOVERY_CODE: 'mfa-recovery-code',
279
+ OAUTH_CLIENT_SECRET: 'oauth-client-secret',
280
+ ACCESS_TOKEN_AUDIT: 'access-token-audit',
281
+ WEBAUTHN_DECOY: 'webauthn-decoy',
282
+ });
283
+ const PURPOSES = new Set(Object.values(HASH_PURPOSES));
284
+ const HKDF_SALT = 'okeav/idp-core token-hash v1';
285
+ const derivedKeys = new Map();
286
+
287
+ function derivedKey(secret, purpose) {
288
+ const id = `${purpose}\u0000${secret}`;
289
+ let key = derivedKeys.get(id);
290
+ if (!key) {
291
+ key = Buffer.from(crypto.hkdfSync('sha256', secret, HKDF_SALT, purpose, 32));
292
+ derivedKeys.set(id, key);
293
+ }
294
+ return key;
295
+ }
296
+
297
+ /**
298
+ * The keys for `purpose`: the current one (from `security.tokenHashSecret`) first, then one per
299
+ * `security.previousTokenHashSecrets` — so the secret can be rotated: new hashes use the current key,
300
+ * while everything stored under a previous one still verifies until it expires or is replaced.
301
+ */
302
+ export function tokenHashKeys(state, purpose) {
303
+ if (!PURPOSES.has(purpose)) throw new Error(`Unknown token-hash purpose: ${purpose}`);
304
+ const { tokenHashSecret, previousTokenHashSecrets = [] } = state.config.security;
305
+ return [tokenHashSecret, ...previousTokenHashSecrets].map((secret) => derivedKey(secret, purpose));
306
+ }
307
+
308
+ const hmacHex = (key, value) => crypto.createHmac('sha256', key).update(String(value)).digest('hex');
309
+
310
+ /** The hash to STORE for `rawToken` — always under the current key. */
311
+ export function hashOpaqueToken(state, rawToken, purpose) {
312
+ return hmacHex(tokenHashKeys(state, purpose)[0], rawToken);
313
+ }
314
+
315
+ /** Every hash `rawToken` may be stored under: the current key's first, then each previous key's. */
316
+ export function opaqueTokenHashes(state, rawToken, purpose) {
317
+ return tokenHashKeys(state, purpose).map((key) => hmacHex(key, rawToken));
318
+ }
319
+
320
+ /**
321
+ * Looks `rawToken` up under each of its candidate hashes (opaqueTokenHashes), in order, until
322
+ * `lookup(hash)` returns something. Resolves `{ result, hash }` — the hash that matched, or (no match)
323
+ * the current one with a null result. With no previous secrets this is a single lookup.
324
+ */
325
+ export async function lookupByTokenHash(state, rawToken, purpose, lookup) {
326
+ const hashes = opaqueTokenHashes(state, rawToken, purpose);
327
+ for (const hash of hashes) {
328
+ const result = await lookup(hash);
329
+ if (result) return { result, hash };
330
+ }
331
+ return { result: null, hash: hashes[0] };
332
+ }
333
+
334
+ export function generateOpaqueToken(byteLength = 64) {
335
+ return crypto.randomBytes(byteLength).toString('hex');
336
+ }
@@ -0,0 +1,30 @@
1
+ import { cookiesAreSecure, hostCookieName } from '../utils/cookies.js';
2
+
3
+ /**
4
+ * The cookie that ties an SSO login to the browser that started it (see initiate.controller.js).
5
+ * One cookie per attempt — named after the state — so two logins in two tabs don't overwrite each
6
+ * other. httpOnly, scoped to the attempt's lifetime. SameSite=Lax is sent on the provider's
7
+ * top-level GET redirect back; Apple returns with a cross-site form POST, which only carries a
8
+ * SameSite=None (hence Secure) cookie.
9
+ */
10
+ export function ssoBindingCookie(state, csrfState, providerConfig) {
11
+ const crossSitePost = providerConfig?.responseMode === 'form_post';
12
+ const secure = crossSitePost ? true : cookiesAreSecure(state);
13
+ return {
14
+ // Host-only and `__Host-` (when Secure): it only has to come back to the IdP itself, and a
15
+ // binding cookie planted from a sibling subdomain would bind the victim's browser to the
16
+ // ATTACKER's login attempt — exactly the login CSRF it exists to stop.
17
+ name: hostCookieName(secure, ssoBindingCookieName(csrfState)),
18
+ options: {
19
+ httpOnly: true,
20
+ secure,
21
+ sameSite: crossSitePost ? 'none' : 'lax',
22
+ path: '/',
23
+ maxAge: state.config.ttls.ssoState * 1000,
24
+ },
25
+ };
26
+ }
27
+
28
+ export function ssoBindingCookieName(csrfState) {
29
+ return `idp_sso_${String(csrfState).slice(0, 16)}`;
30
+ }
@@ -0,0 +1,186 @@
1
+ import crypto from 'crypto';
2
+ import { getState } from '../config/state.js';
3
+ import { IdpError } from '../errors/idp-error.js';
4
+ import { IDENTITY_STATUS, CACHE_KEY_PREFIXES } from '../config/constants.js';
5
+ import { isActiveAccount } from '../utils/account-status.js';
6
+ import { buildSsoProviders, normalizeUserInfo, exchangeCode, fetchUserInfo, assertAppleIdToken, decodeJwtPayload } from './providers.js';
7
+ import { ssoBindingCookie } from './binding.js';
8
+ import { readCookie } from '../utils/cookies.js';
9
+ import { auditLog } from '../hooks/index.js';
10
+ import { issueSession, setSessionCookies, resolveClaims, mfaChallengeResponse } from '../password-auth/controllers.js';
11
+
12
+ /**
13
+ * GET/POST /sso/:provider/callback
14
+ *
15
+ * Collapsed to a single step (Phase 2 decision): the audited source issued a
16
+ * short-lived exchange token here and made a second service redeem it for an
17
+ * enriched session. That split existed only because Okeav's account-service
18
+ * (not auth-service) resolved role/scopes/accountId — it wasn't a redirect-
19
+ * URI or CSRF security requirement (the CSRF-relevant `state` check happens
20
+ * entirely above, before any token is minted). This version calls
21
+ * `hooks.resolveAuthContext` synchronously and mints the full session
22
+ * directly. A consumer who wants Okeav's two-service split can still get it
23
+ * by having `resolveAuthContext` itself return a pointer and complete
24
+ * enrichment out-of-band — that's a hook implementation choice now, not
25
+ * something the package hardcodes.
26
+ */
27
+ export async function ssoCallbackHandler(req, res, next) {
28
+ try {
29
+ const state = getState();
30
+ const { provider } = req.params;
31
+
32
+ const param = (name) => {
33
+ const v = req.query[name] ?? req.body?.[name];
34
+ return typeof v === 'string' ? v : undefined;
35
+ };
36
+ const code = param('code');
37
+ const csrfState = param('state');
38
+
39
+ // The state is checked (and consumed, atomically) before anything else — including a provider
40
+ // error — so nothing on this endpoint answers a request that this browser didn't start.
41
+ const INVALID_STATE = () => new IdpError({ code: 'INVALID_SSO_STATE', httpStatus: 400, message: 'Invalid or expired SSO state' });
42
+ if (!csrfState) throw INVALID_STATE();
43
+ const stateData = await state.cache.take(`${CACHE_KEY_PREFIXES.SSO_STATE}:${csrfState}`);
44
+ if (!stateData || stateData.provider !== provider) throw INVALID_STATE();
45
+
46
+ const providers = buildSsoProviders(state.config);
47
+ const providerConfig = providers[provider];
48
+ if (!providerConfig) throw new IdpError({ code: 'INVALID_SSO_PROVIDER', httpStatus: 400, message: `Unknown SSO provider: ${provider}` });
49
+
50
+ const cookie = ssoBindingCookie(state, csrfState, providerConfig);
51
+ const binding = readCookie(req, cookie.name);
52
+ res.clearCookie(cookie.name, { ...cookie.options, maxAge: undefined });
53
+ if (typeof binding !== 'string' || !stateData.bindingHash || !safeEqual(sha256b64url(binding), stateData.bindingHash)) {
54
+ state.logger?.warn?.({ provider }, 'SSO callback refused — not completed in the browser that started it');
55
+ throw INVALID_STATE();
56
+ }
57
+
58
+ const { redirect_uri, extra } = stateData;
59
+ const providerError = param('error');
60
+ if (providerError) {
61
+ // Only a sanitized error code travels back — never the provider's free-text description.
62
+ return res.redirect(withParams(redirect_uri, { error: 'provider_error', provider_error: providerError.replace(/[^a-z_]/gi, '').slice(0, 64) }));
63
+ }
64
+ if (!code) return res.redirect(withParams(redirect_uri, { error: 'provider_error' }));
65
+
66
+ const providerTokens = await exchangeCode(state.config, providerConfig, code, { codeVerifier: stateData.codeVerifier ?? undefined });
67
+
68
+ let rawUserInfo;
69
+ if (provider === 'apple') {
70
+ let appleUser = null;
71
+ const userParam = param('user');
72
+ if (userParam) {
73
+ try { appleUser = JSON.parse(userParam); } catch { /* name only sent on first authorization */ }
74
+ }
75
+ try {
76
+ assertAppleIdToken(providerConfig, decodeJwtPayload(providerTokens.id_token), stateData.nonce);
77
+ } catch (cause) {
78
+ throw new IdpError({ code: 'SSO_PROVIDER_ERROR', httpStatus: 400, message: 'Apple id_token was not issued for this login', cause });
79
+ }
80
+ rawUserInfo = { id_token: providerTokens.id_token, appleUser };
81
+ } else {
82
+ rawUserInfo = await fetchUserInfo(state.config, providerConfig, providerTokens.access_token);
83
+ }
84
+
85
+ const userInfo = normalizeUserInfo(provider, rawUserInfo, providerConfig);
86
+ if (!userInfo.email) {
87
+ state.logger?.warn?.({ provider }, 'SSO provider did not return an email address');
88
+ return res.redirect(withParams(redirect_uri, { error: 'email_required' }));
89
+ }
90
+
91
+ const users = state.storage.userRepository;
92
+ let user = await users.findByExternalProvider(provider, userInfo.providerId);
93
+ let isNewUser = false;
94
+ let isNewLink = false;
95
+
96
+ if (!user) {
97
+ // Matching by email links this provider identity to whoever owns the address here — so the
98
+ // provider must vouch that the address is verified. Otherwise anyone who can put an
99
+ // arbitrary email on a provider account (e.g. a Microsoft tenant admin) logs in as its owner.
100
+ if (!userInfo.emailVerified) {
101
+ state.logger?.warn?.({ provider }, 'SSO login refused — provider did not assert a verified email');
102
+ return res.redirect(withParams(redirect_uri, { error: 'email_not_verified' }));
103
+ }
104
+
105
+ const link = { provider, providerId: userInfo.providerId, email: userInfo.email, connectedAt: new Date() };
106
+ const existing = await users.findByEmail(userInfo.email);
107
+ if (isActiveAccount(existing)) {
108
+ await users.linkExternalProvider(existing.id, link);
109
+ user = await users.findById(existing.id);
110
+ isNewLink = true;
111
+ } else if (existing?.status === IDENTITY_STATUS.PENDING_VERIFICATION) {
112
+ // The provider just proved ownership of an address someone registered here but never
113
+ // verified. Whatever password that registration set is not the owner's (it may be an
114
+ // attacker's pre-registration), so it is discarded as the owner claims the account.
115
+ // Conditional on still being pending (an activation since the read must not be wiped);
116
+ // either way the address is now owned by the provider-verified user and is linked below.
117
+ const claimed = await users.updateByIdIfStatus(existing.id, IDENTITY_STATUS.PENDING_VERIFICATION, {
118
+ status: IDENTITY_STATUS.ACTIVE, failedLoginAttempts: 0, lockUntil: null,
119
+ passwordHash: null, registrationContested: false, mfaEnabled: false, mfaSecret: null, mfaTempSecret: null, mfaRecoveryCodes: [],
120
+ });
121
+ if (claimed) await state.storage.verificationTokenRepository.deleteAllForUser('email_verification', existing.id);
122
+ await users.linkExternalProvider(existing.id, link);
123
+ user = await users.findById(existing.id);
124
+ isNewLink = true;
125
+ await auditLog(state.logger, state.hooks, 'SSO_PENDING_ACCOUNT_CLAIMED', { userId: String(user.id), provider });
126
+ } else if (existing) {
127
+ // Locked, suspended, deleted …: never attach a new login method to it.
128
+ state.logger?.warn?.({ userId: existing.id, provider, status: existing.status }, 'SSO login blocked — account not active');
129
+ return res.redirect(withParams(redirect_uri, { error: 'account_inactive' }));
130
+ } else {
131
+ user = await users.create({
132
+ email: userInfo.email.toLowerCase(),
133
+ status: IDENTITY_STATUS.ACTIVE, // the provider verified the address
134
+ profile: { firstName: userInfo.firstName, lastName: userInfo.lastName, displayName: userInfo.name, avatarUrl: userInfo.avatarUrl },
135
+ externalProviders: [link],
136
+ });
137
+ isNewUser = true;
138
+ }
139
+ }
140
+
141
+ if (!isActiveAccount(user)) {
142
+ state.logger?.warn?.({ userId: user.id, provider, status: user.status }, 'SSO login blocked — account not active');
143
+ return res.redirect(withParams(redirect_uri, { error: 'account_inactive' }));
144
+ }
145
+
146
+ if (isNewUser) await auditLog(state.logger, state.hooks, 'SSO_REGISTERED', { userId: String(user.id), provider });
147
+ if (isNewLink) await auditLog(state.logger, state.hooks, 'SSO_PROVIDER_LINKED', { userId: String(user.id), provider });
148
+
149
+ // SSO is one factor. An account with MFA still has to present it: hand back a challenge (in
150
+ // the URL fragment, which never reaches a server log or a Referer header) instead of a session.
151
+ if (user.mfaEnabled) {
152
+ await auditLog(state.logger, state.hooks, 'SSO_MFA_REQUIRED', { userId: String(user.id), provider });
153
+ const { mfaChallengeToken, expiresIn } = await mfaChallengeResponse(state, user, { loginChallenge: stateData.loginChallenge ?? undefined });
154
+ return res.redirect(withParams(redirect_uri, { mfa_required: '1', mfa_challenge_token: mfaChallengeToken, expires_in: String(expiresIn) }, { fragment: true }));
155
+ }
156
+
157
+ await auditLog(state.logger, state.hooks, 'SSO_LOGIN', { userId: String(user.id), provider });
158
+
159
+ const claims = await resolveClaims(state, user, { isNewUser, isNewLink, provider, extra });
160
+ const session = await issueSession(state, { user, claims, req, loginChallenge: stateData.loginChallenge ?? undefined });
161
+
162
+ setSessionCookies(req, res, state, session);
163
+ res.redirect(withParams(redirect_uri, { ssoLogin: 'success' }));
164
+ } catch (err) {
165
+ next(err);
166
+ }
167
+ }
168
+
169
+ const sha256b64url = (s) => crypto.createHash('sha256').update(s).digest('base64url');
170
+
171
+ function safeEqual(a, b) {
172
+ const x = Buffer.from(String(a));
173
+ const y = Buffer.from(String(b));
174
+ return x.length === y.length && crypto.timingSafeEqual(x, y);
175
+ }
176
+
177
+ /** Adds params to a URL that may already carry a query string (or, with `fragment`, to its fragment). */
178
+ function withParams(uri, params, { fragment = false } = {}) {
179
+ const url = new URL(uri);
180
+ if (fragment) {
181
+ url.hash = new URLSearchParams(params).toString();
182
+ } else {
183
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
184
+ }
185
+ return url.toString();
186
+ }