@okeav/idp-pg 0.0.0-stage → 0.2.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 +63 -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 +61 -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 +783 -0
@@ -0,0 +1,138 @@
1
+ import { newId, isUuid, columnFor, deleteInBatches } from '../db.js';
2
+
3
+ const COLUMNS = {
4
+ tokenHash: 'token_hash',
5
+ verificationCode: 'verification_code',
6
+ passwordHash: 'password_hash',
7
+ expiresAt: 'expires_at',
8
+ usedAt: 'used_at',
9
+ };
10
+
11
+ /** The kinds with at most one live token per user (a partial unique index backs replaceForUser). */
12
+ const ONE_PER_USER = new Set(['password_reset', 'magic_link']);
13
+ /** Single-use by deletion: a clicked verification / magic link is gone afterwards. */
14
+ const DELETED_ON_USE = new Set(['email_verification', 'magic_link']);
15
+
16
+ /** @implements {import('../../interfaces.js').VerificationTokenRepository} */
17
+ export class PgVerificationTokenRepository {
18
+ constructor(pool) {
19
+ this.pool = pool;
20
+ }
21
+
22
+ async create(kind, input) {
23
+ const { user, ...rest } = input;
24
+ if (!isUuid(user)) throw new Error('@okeav/idp-pg: a verification token needs a user id');
25
+ const columns = ['id', 'kind', 'user_id'];
26
+ const values = [newId(), kind, user];
27
+ for (const [key, value] of Object.entries(rest)) {
28
+ if (value === undefined) continue;
29
+ columns.push(columnFor(COLUMNS, key, 'idp_verification_tokens'));
30
+ values.push(value);
31
+ }
32
+ await this.pool.query(
33
+ `INSERT INTO idp_verification_tokens (${columns.join(', ')}) VALUES (${columns.map((_, i) => `$${i + 1}`).join(', ')})`,
34
+ values,
35
+ );
36
+ }
37
+
38
+ /** Atomic consume by token hash; `userId`, when given, scopes it to the claimed identity. */
39
+ async consumeByHash(kind, hash, userId) {
40
+ if (!hash || (userId != null && !isUuid(userId))) return null;
41
+ const params = [kind, hash, new Date()];
42
+ let where = 'kind = $1 AND token_hash = $2 AND used_at IS NULL AND expires_at > $3';
43
+ if (userId != null) {
44
+ params.push(userId);
45
+ where += ` AND user_id = $${params.length}`;
46
+ }
47
+ return this._consumeOne(where, params, DELETED_ON_USE.has(kind));
48
+ }
49
+
50
+ /** Atomic consume by (hashed) code, for one user. A null code never matches. */
51
+ async consumeByCode(kind, code, userId) {
52
+ if (!code || !isUuid(userId)) return null;
53
+ return this._consumeOne('kind = $1 AND verification_code = $2 AND user_id = $3 AND expires_at > $4', [kind, code, userId, new Date()], true);
54
+ }
55
+
56
+ /**
57
+ * Takes ONE matching row — deleting it, or marking it used — and resolves it (null if none). The row
58
+ * lock makes concurrent consumers of one token see it once.
59
+ */
60
+ async _consumeOne(where, params, deleteRow) {
61
+ const target = `SELECT id FROM idp_verification_tokens WHERE ${where} ORDER BY created_at, id LIMIT 1 FOR UPDATE`;
62
+ const sql = deleteRow
63
+ ? `WITH target AS (${target}) DELETE FROM idp_verification_tokens t USING target WHERE t.id = target.id RETURNING t.*`
64
+ : `WITH target AS (${target}) UPDATE idp_verification_tokens t SET used_at = now(), updated_at = now()
65
+ FROM target WHERE t.id = target.id AND t.used_at IS NULL RETURNING t.*`;
66
+ const { rows: [row] } = await this.pool.query(sql, params);
67
+ return mapToken(row);
68
+ }
69
+
70
+ /** A live (unused, unexpired) token by its hash or code hash, WITHOUT consuming it. */
71
+ async findActive(kind, { tokenHash, verificationCode } = {}, userId) {
72
+ if (!isUuid(userId)) return null;
73
+ const by = tokenHash ? ['token_hash', tokenHash] : verificationCode ? ['verification_code', verificationCode] : null;
74
+ if (!by) return null;
75
+ const { rows: [row] } = await this.pool.query(
76
+ `SELECT * FROM idp_verification_tokens
77
+ WHERE kind = $1 AND user_id = $2 AND used_at IS NULL AND expires_at > $3 AND ${by[0]} = $4
78
+ ORDER BY created_at, id LIMIT 1`,
79
+ [kind, userId, new Date(), by[1]],
80
+ );
81
+ return mapToken(row);
82
+ }
83
+
84
+ /** Nulls the guessable codes of every outstanding row (the links keep working). */
85
+ async clearCodes(kind, userId) {
86
+ if (!isUuid(userId)) return;
87
+ await this.pool.query(
88
+ 'UPDATE idp_verification_tokens SET verification_code = NULL, updated_at = now() WHERE kind = $1 AND user_id = $2 AND verification_code IS NOT NULL',
89
+ [kind, userId],
90
+ );
91
+ }
92
+
93
+ /** The single live token of this kind for the user, replaced atomically (one statement, a unique index). */
94
+ async replaceForUser(kind, userId, input) {
95
+ if (!ONE_PER_USER.has(kind)) throw new Error(`@okeav/idp-pg: replaceForUser supports ${[...ONE_PER_USER].join(', ')} (got ${kind})`);
96
+ if (!isUuid(userId)) throw new Error('@okeav/idp-pg: a verification token needs a user id');
97
+ const columns = ['id', 'kind', 'user_id', 'used_at'];
98
+ const values = [newId(), kind, userId, null];
99
+ const updates = ['used_at = NULL', 'updated_at = now()'];
100
+ for (const [key, value] of Object.entries(input)) {
101
+ if (value === undefined || key === 'usedAt' || key === 'user' || key === 'kind') continue;
102
+ const column = columnFor(COLUMNS, key, 'idp_verification_tokens');
103
+ columns.push(column);
104
+ values.push(value);
105
+ updates.push(`${column} = EXCLUDED.${column}`);
106
+ }
107
+ await this.pool.query(
108
+ `INSERT INTO idp_verification_tokens (${columns.join(', ')}) VALUES (${columns.map((_, i) => `$${i + 1}`).join(', ')})
109
+ ON CONFLICT (kind, user_id) WHERE kind IN ('password_reset', 'magic_link') DO UPDATE SET ${updates.join(', ')}`,
110
+ values,
111
+ );
112
+ }
113
+
114
+ async deleteAllForUser(kind, userId) {
115
+ if (!isUuid(userId)) return;
116
+ await this.pool.query('DELETE FROM idp_verification_tokens WHERE kind = $1 AND user_id = $2', [kind, userId]);
117
+ }
118
+
119
+ async pruneExpired() {
120
+ return deleteInBatches(this.pool, 'idp_verification_tokens', 'expires_at < $1', [new Date()]);
121
+ }
122
+ }
123
+
124
+ export function mapToken(row) {
125
+ if (!row) return null;
126
+ return {
127
+ id: row.id,
128
+ kind: row.kind,
129
+ user: row.user_id,
130
+ tokenHash: row.token_hash,
131
+ verificationCode: row.verification_code,
132
+ passwordHash: row.password_hash,
133
+ expiresAt: row.expires_at,
134
+ usedAt: row.used_at,
135
+ createdAt: row.created_at,
136
+ updatedAt: row.updated_at,
137
+ };
138
+ }
@@ -0,0 +1,22 @@
1
+ import pg from 'pg';
2
+ import { runMigrations as runMigrationsOnPool } from './migrations/run-migrations.js';
3
+
4
+ /**
5
+ * Applies this version's schema migrations — at deploy time, or at startup with
6
+ * `postgres.migrations: 'apply'`. Safe to run from several instances at once.
7
+ *
8
+ * @param {import('pg').Pool | { connectionString: string } | string} target - a pg.Pool (left open), or a
9
+ * connection string / pool config (a pool is opened and closed for the run)
10
+ * @returns {Promise<string[]>} the migrations applied by this call
11
+ */
12
+ export async function runMigrations(target) {
13
+ if (target && typeof target.query === 'function' && typeof target.connect === 'function') return runMigrationsOnPool(target);
14
+ const config = typeof target === 'string' ? { connectionString: target } : target;
15
+ if (!config?.connectionString && !config?.host) throw new Error('@okeav/idp-pg: runMigrations needs a pg.Pool or a connection string');
16
+ const pool = new pg.Pool({ application_name: 'idp-pg-migrate', max: 1, ...config });
17
+ try {
18
+ return await runMigrationsOnPool(pool);
19
+ } finally {
20
+ await pool.end();
21
+ }
22
+ }
@@ -0,0 +1,26 @@
1
+ import { IDENTITY_STATUS } from '../config/constants.js';
2
+
3
+ /**
4
+ * The failed-password lockout is a property of PASSWORD login (`lockUntil`), not an account status.
5
+ * As a status it locked the owner out of every other method too — magic link, passkey, SSO, MFA,
6
+ * refresh, OAuth2 — so five anonymous wrong passwords were a denial of service against any account,
7
+ * and a passwordless account (which never makes a password login to lift it) stayed locked for good.
8
+ *
9
+ * Rows locked before 0.4.0 carry `status: LOCKED` together with a `lockUntil`: that is the automatic
10
+ * lockout, and counts as ACTIVE here. A LOCKED status with no `lockUntil` is an administrative lock
11
+ * and still blocks every method.
12
+ */
13
+ export function effectiveStatus(user) {
14
+ if (user?.status === IDENTITY_STATUS.LOCKED && user.lockUntil) return IDENTITY_STATUS.ACTIVE;
15
+ return user?.status;
16
+ }
17
+
18
+ /** Whether the account may sign in / keep its sessions (any method). */
19
+ export function isActiveAccount(user) {
20
+ return Boolean(user) && effectiveStatus(user) === IDENTITY_STATUS.ACTIVE;
21
+ }
22
+
23
+ /** Whether password login is currently locked by failed attempts. */
24
+ export function isPasswordLocked(user) {
25
+ return Boolean(user?.lockUntil) && new Date(user.lockUntil) > new Date();
26
+ }
@@ -0,0 +1,129 @@
1
+ import { IdpError } from '../errors/idp-error.js';
2
+ import { hashOpaqueToken, opaqueTokenHashes, HASH_PURPOSES } from '../signing/token.service.js';
3
+
4
+ /** Whether cookies are `Secure` (config.cookies.secure; default: everywhere but NODE_ENV=development). */
5
+ export function cookiesAreSecure(state) {
6
+ return state.config.cookies?.secure ?? process.env.NODE_ENV !== 'development';
7
+ }
8
+
9
+ /**
10
+ * The real name of a session cookie (`access_token`, `refresh_token`).
11
+ *
12
+ * Cookie tossing: a sibling subdomain (or a script on one) can set a cookie for the parent domain with
13
+ * the same name and a longer path; the browser then sends both, the planted one first, and the server
14
+ * reads the attacker's session — signing the victim into the attacker's account (and an OAuth2 client
15
+ * into the attacker's identity). A `__Host-` cookie can only be set by this exact host, over HTTPS,
16
+ * with Path=/ and no Domain, so it can't be planted. With `cookies.domain` (cookies shared across
17
+ * subdomains by choice) `__Host-` is impossible; `__Secure-` is used and a request carrying the cookie
18
+ * twice is refused (readSessionCookie). Without Secure (development over http) no prefix is allowed.
19
+ */
20
+ export function sessionCookieName(state, base) {
21
+ if (!cookiesAreSecure(state)) return base;
22
+ return state.config.cookies?.domain ? `__Secure-${base}` : `__Host-${base}`;
23
+ }
24
+
25
+ /** A host-only cookie name for the IdP's own short-lived cookies (SSO binding): `__Host-` whenever Secure. */
26
+ export function hostCookieName(secure, base) {
27
+ return secure ? `__Host-${base}` : base;
28
+ }
29
+
30
+ const COOKIE_CONFLICT = () => new IdpError({
31
+ code: 'COOKIE_CONFLICT',
32
+ httpStatus: 400,
33
+ message: 'Conflicting session cookies — sign in again',
34
+ });
35
+
36
+ /**
37
+ * How many times a cookie name occurs in the raw Cookie header. cookie-parser keeps the first of two
38
+ * same-named cookies, and the browser lists a planted longer-path cookie first — so a duplicate is
39
+ * refused rather than resolved.
40
+ */
41
+ function occurrences(req, name) {
42
+ const raw = req.headers?.cookie;
43
+ if (typeof raw !== 'string') return 0;
44
+ // Compared the way the parser reads names — trimmed, up to the first "=" — so a variant such as
45
+ // `name =value` (which the parser also treats as `name`) counts as a second occurrence.
46
+ return raw.split(';').filter((part) => {
47
+ const eq = part.indexOf('=');
48
+ return eq !== -1 && part.slice(0, eq).trim() === name;
49
+ }).length;
50
+ }
51
+
52
+ /** The value of a cookie the IdP set; undefined when absent or not a string; throws if it occurs twice. */
53
+ export function readCookie(req, name) {
54
+ if (occurrences(req, name) > 1) throw COOKIE_CONFLICT();
55
+ const value = req.cookies?.[name];
56
+ return typeof value === 'string' ? value : undefined;
57
+ }
58
+
59
+ /** The value of a session cookie (see sessionCookieName). */
60
+ export function readSessionCookie(state, req, base) {
61
+ return readCookie(req, sessionCookieName(state, base));
62
+ }
63
+
64
+ /**
65
+ * The refresh-token cookie is scoped to the session endpoints (`<mount path>/session`), so the
66
+ * long-lived token is sent nowhere else. A path-scoped cookie can't carry the `__Host-` prefix — the
67
+ * one thing a sibling subdomain can't plant — so it is `__Secure-`, and comes with a host-only
68
+ * BINDING cookie (`__Host-refresh_binding`, `Path=/`) holding a keyed hash of the token. A refresh
69
+ * cookie is only accepted with its binding: a planted one (whose binding the planter can't set) is
70
+ * refused. The binding alone is useless — it is not the token. With `cookies.domain` (cookies shared
71
+ * across subdomains by choice) both are domain cookies, as before.
72
+ */
73
+ export function refreshCookieNames(state) {
74
+ if (!cookiesAreSecure(state)) return { token: 'refresh_token', binding: 'refresh_binding' };
75
+ return { token: '__Secure-refresh_token', binding: state.config.cookies?.domain ? '__Secure-refresh_binding' : '__Host-refresh_binding' };
76
+ }
77
+
78
+ /**
79
+ * The path the refresh cookie is scoped to: `cookies.sessionPath` when configured, otherwise the session
80
+ * endpoints under wherever the router is mounted (as the request spelled it).
81
+ */
82
+ export const sessionCookiePath = (state, req) => state.config.cookies?.sessionPath ?? `${req.baseUrl ?? ''}/session`;
83
+
84
+ export const refreshCookieBinding = (state, token) => hashOpaqueToken(state, token, HASH_PURPOSES.REFRESH_COOKIE_BINDING);
85
+
86
+ /** Every value of cookie `name` in the raw Cookie header, decoded the way the cookie parser decodes them. */
87
+ function allCookieValues(req, name) {
88
+ const raw = req.headers?.cookie;
89
+ if (typeof raw !== 'string') return [];
90
+ const values = [];
91
+ for (const part of raw.split(';')) {
92
+ const eq = part.indexOf('=');
93
+ if (eq === -1 || part.slice(0, eq).trim() !== name) continue;
94
+ let value = part.slice(eq + 1).trim();
95
+ if (value.length > 1 && value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
96
+ try {
97
+ value = decodeURIComponent(value);
98
+ } catch {
99
+ // left as sent, like the parser does
100
+ }
101
+ values.push(value);
102
+ }
103
+ return values;
104
+ }
105
+
106
+ /**
107
+ * The refresh token from its cookie: the one value whose keyed hash its binding cookie holds. Values
108
+ * without a matching binding (planted — the binding is host-only) are ignored, so a planted cookie
109
+ * can neither be used nor block the real one. undefined when none matches; COOKIE_CONFLICT only when
110
+ * two different tokens each come with a matching binding — possible only with `cookies.domain`, where
111
+ * the binding is a domain cookie too.
112
+ */
113
+ export function readRefreshCookie(state, req) {
114
+ const names = refreshCookieNames(state);
115
+ const bindings = new Set(allCookieValues(req, names.binding));
116
+ // A browser holds one host-only binding; several can only be forged (or, with cookies.domain, planted).
117
+ if (bindings.size === 0 || (bindings.size > MAX_BINDINGS(state))) return undefined;
118
+ // Every token value is considered — planted ones listed first must not crowd out the real one. The
119
+ // header-size limit bounds the count, and each costs one keyed hash per key.
120
+ const tokens = [...new Set(allCookieValues(req, names.token))];
121
+ // One keyed hash per token and key, looked up in the set (linear; both values come from the client,
122
+ // so a constant-time comparison protects nothing here).
123
+ const bound = tokens.filter((token) => opaqueTokenHashes(state, token, HASH_PURPOSES.REFRESH_COOKIE_BINDING).some((h) => bindings.has(h)));
124
+ if (bound.length > 1) throw COOKIE_CONFLICT();
125
+ return bound[0];
126
+ }
127
+
128
+ /** Bindings accepted at all: one host-only cookie (a browser holds one); a few with cookies.domain, where siblings can add theirs. */
129
+ const MAX_BINDINGS = (state) => (state.config.cookies?.domain ? 8 : 1);
@@ -0,0 +1,58 @@
1
+ import crypto from 'crypto';
2
+ import { safeInvokeHook } from '../hooks/index.js';
3
+
4
+ /**
5
+ * Reduces a raw user-agent string to a stable "browser-family + os-family"
6
+ * fingerprint so a browser/OS auto-update doesn't trigger a false
7
+ * new-device alert on every login. Narrower than full device identity —
8
+ * switching browsers on the same machine is treated as a new device, which
9
+ * is the conservative/correct choice.
10
+ */
11
+ export function normalizeUserAgent(ua) {
12
+ if (!ua || typeof ua !== 'string') return '';
13
+ const lower = ua.toLowerCase().trim();
14
+
15
+ const browser =
16
+ /edg\//.test(lower) ? 'edge' :
17
+ /opr\/|opera/.test(lower) ? 'opera' :
18
+ /chrome\//.test(lower) ? 'chrome' :
19
+ /firefox\//.test(lower) ? 'firefox' :
20
+ /safari\//.test(lower) ? 'safari' :
21
+ /msie |trident\//.test(lower) ? 'ie' :
22
+ null;
23
+
24
+ const os =
25
+ /windows nt/.test(lower) ? 'windows' :
26
+ /mac os x|macintosh/.test(lower) ? 'macos' :
27
+ /android/.test(lower) ? 'android' :
28
+ /iphone|ipad|ios/.test(lower) ? 'ios' :
29
+ /linux/.test(lower) ? 'linux' :
30
+ null;
31
+
32
+ if (browser && os) return `${browser}|${os}`;
33
+ return lower;
34
+ }
35
+
36
+ export function buildDeviceFingerprint(rawUserAgent) {
37
+ const normalized = normalizeUserAgent(rawUserAgent);
38
+ if (!normalized) return null;
39
+ return crypto.createHash('sha256').update(normalized).digest('hex');
40
+ }
41
+
42
+ /**
43
+ * Fires `onNewDeviceLogin`. Whether the device is new is decided by the caller BEFORE the login's own
44
+ * session row is written (see issueSession) — checking afterwards always finds that row, which is
45
+ * why the alert never fired before 0.4.0.
46
+ */
47
+ export async function notifyNewDevice({ hooks, logger, req, user }) {
48
+ await safeInvokeHook(logger, hooks, 'onNewDeviceLogin', {
49
+ userId: String(user.id),
50
+ email: user.email,
51
+ firstName: user.profile?.firstName || '',
52
+ lastName: user.profile?.lastName || '',
53
+ locale: user.profile?.locale || 'en',
54
+ when: new Date().toISOString(),
55
+ deviceInfo: req.headers?.['user-agent'] || '',
56
+ ipAddress: req.ip || '',
57
+ });
58
+ }
@@ -0,0 +1,23 @@
1
+ import crypto from 'crypto';
2
+
3
+ /**
4
+ * Blind index for email lookups. IdentityUser stores the plaintext email
5
+ * (display, OIDC claims, outbound mail) but every lookup goes through an
6
+ * HMAC-SHA-256 of the normalized email keyed by a server-side pepper — so a
7
+ * leaked database without the pepper can't be brute-forced for common
8
+ * addresses, and only this IDP instance can compute the lookup hash.
9
+ *
10
+ * Rotating the pepper invalidates every existing hash — treat it as a
11
+ * non-rotating, well-backed-up secret.
12
+ */
13
+ export function normalizeEmail(email) {
14
+ return String(email ?? '').trim().toLowerCase();
15
+ }
16
+
17
+ export function makeHashEmail(pepper) {
18
+ if (!pepper) throw new Error('config.security.emailHashPepper is required');
19
+ return function hashEmail(email) {
20
+ if (!email) return null;
21
+ return crypto.createHmac('sha256', pepper).update(normalizeEmail(email)).digest('hex');
22
+ };
23
+ }
@@ -0,0 +1,51 @@
1
+ import crypto from 'crypto';
2
+ import bcrypt from 'bcrypt';
3
+
4
+ /**
5
+ * Client secrets are 256-bit random values, so a slow password hash adds nothing — there is no
6
+ * dictionary to search — while bcrypt's ~250 ms per check let anyone with a (public) client_id tie
7
+ * up the libuv thread pool (and with it every login) from a handful of connections. New secrets are
8
+ * stored as `hmac-sha256:<hex>` under the client-secret key derived from `security.tokenHashSecret`
9
+ * (see tokenHashKeys). Hashes made under a previous secret, and bcrypt hashes from before 0.4.0
10
+ * (`$2…`), still verify, and are re-stored under the current key on their next successful use.
11
+ */
12
+ const HMAC_PREFIX = 'hmac-sha256:';
13
+
14
+ export function generateClientId() {
15
+ return crypto.randomBytes(16).toString('hex');
16
+ }
17
+
18
+ export function generateClientSecret() {
19
+ return crypto.randomBytes(32).toString('hex');
20
+ }
21
+
22
+ export function hashClientSecret(clientSecret, hmacKey) {
23
+ if (!hmacKey) throw new Error('hashClientSecret: hmacKey (the derived client-secret key) is required');
24
+ return HMAC_PREFIX + crypto.createHmac('sha256', hmacKey).update(String(clientSecret)).digest('hex');
25
+ }
26
+
27
+ /** True when the stored hash should be replaced by the current format after a successful verify. */
28
+ export const isLegacyClientSecretHash = (hash) => typeof hash === 'string' && hash.startsWith('$2');
29
+
30
+ /**
31
+ * Checks `clientSecret` against the stored `hash`. `hmacKeys`: the current key first, then previous
32
+ * ones. Resolves `{ valid, upgrade }` — `upgrade`: it verified, but not under the current key (a
33
+ * previous key, or bcrypt), so the caller should re-store it.
34
+ */
35
+ export async function verifyClientSecret(clientSecret, hash, hmacKeys) {
36
+ const keys = Array.isArray(hmacKeys) ? hmacKeys : [hmacKeys];
37
+ if (typeof clientSecret !== 'string' || typeof hash !== 'string') return { valid: false, upgrade: false };
38
+ if (hash.startsWith(HMAC_PREFIX)) {
39
+ const expected = Buffer.from(hash);
40
+ for (const [i, key] of keys.entries()) {
41
+ const actual = Buffer.from(hashClientSecret(clientSecret, key));
42
+ if (expected.length === actual.length && crypto.timingSafeEqual(expected, actual)) return { valid: true, upgrade: i > 0 };
43
+ }
44
+ return { valid: false, upgrade: false };
45
+ }
46
+ if (isLegacyClientSecretHash(hash)) {
47
+ const valid = await bcrypt.compare(clientSecret, hash);
48
+ return { valid, upgrade: valid };
49
+ }
50
+ return { valid: false, upgrade: false };
51
+ }
@@ -0,0 +1,40 @@
1
+ import crypto from 'crypto';
2
+ import bcrypt from 'bcrypt';
3
+
4
+ // A real hash at the configured cost (set by prepareDummyHash at init). A fixed cost-12 constant made
5
+ // "no such account" slower or faster than a real compare whenever bcryptRounds wasn't 12 — a timing
6
+ // oracle for which emails exist, and which accounts have no password.
7
+ let dummyHash = null;
8
+
9
+ /** The cost of the current dummy hash (tests). */
10
+ export function dummyHashRounds() {
11
+ return dummyHash ? bcrypt.getRounds(dummyHash) : null;
12
+ }
13
+
14
+ /** Called by initIdentityProvider with `security.bcryptRounds`. */
15
+ export async function prepareDummyHash(rounds) {
16
+ dummyHash = await bcrypt.hash(crypto.randomBytes(16).toString('hex'), rounds);
17
+ }
18
+
19
+ export async function hashPassword(password, rounds) {
20
+ return bcrypt.hash(password, rounds);
21
+ }
22
+
23
+ /**
24
+ * False — never a throw — for an account with no password (SSO-only, magic-link-only, or one whose
25
+ * pre-verification password was discarded): bcrypt throws on a missing hash, which surfaced as a 500
26
+ * that told an attacker exactly which accounts are passwordless. The dummy compare keeps the timing.
27
+ */
28
+ export async function verifyPassword(password, hash) {
29
+ if (typeof hash !== 'string' || hash.length === 0) {
30
+ await compareDummyPassword(password);
31
+ return false;
32
+ }
33
+ return bcrypt.compare(password, hash);
34
+ }
35
+
36
+ /** Spends roughly the same wall-clock as a real verify, so a login attempt against a nonexistent email doesn't respond faster than one against a real (wrong-password) account. */
37
+ export async function compareDummyPassword(password) {
38
+ if (!dummyHash) await prepareDummyHash(12);
39
+ return bcrypt.compare(password, dummyHash);
40
+ }
@@ -0,0 +1,12 @@
1
+ import crypto from 'crypto';
2
+
3
+ /**
4
+ * Constant-time comparison of two secrets of any length: both are hashed first, so neither the
5
+ * content nor the length of the expected secret leaks through timing.
6
+ */
7
+ export function safeEqualSecret(presented, expected) {
8
+ if (typeof presented !== 'string' || typeof expected !== 'string' || expected.length === 0) return false;
9
+ const a = crypto.createHash('sha256').update(presented).digest();
10
+ const b = crypto.createHash('sha256').update(expected).digest();
11
+ return crypto.timingSafeEqual(a, b);
12
+ }
@@ -0,0 +1,158 @@
1
+ import crypto from 'crypto';
2
+ import { IdpError } from '../errors/idp-error.js';
3
+ import { CACHE_KEY_PREFIXES } from '../config/constants.js';
4
+ import { auditLog } from '../hooks/index.js';
5
+ import { HASH_PURPOSES, hashOpaqueToken, lookupByTokenHash } from '../signing/token.service.js';
6
+
7
+ /**
8
+ * Refresh-token families (RFC 9700 §4.14.2). A login — or an OAuth2 authorization code — starts a
9
+ * family; each rotation adds a row to it. Rows record why they were revoked, so presenting a refresh
10
+ * token that was already *rotated* is recognisable: someone holds a copy. The legitimate client and
11
+ * the thief each have a token of the same family, and only one of them can be the rightful one —
12
+ * so the whole family is revoked and both must log in again.
13
+ */
14
+
15
+ export const newFamilyId = () => crypto.randomUUID();
16
+
17
+ /** The family a row belongs to. Rows from before 0.4.0 have none: each starts its own from here on. */
18
+ export function familyOf(session) {
19
+ return {
20
+ familyId: session.familyId ?? `legacy:${session.id ?? session._id}`,
21
+ familyCreatedAt: session.familyCreatedAt ?? session.authTime ?? session.createdAt ?? new Date(),
22
+ };
23
+ }
24
+
25
+ /** When a family must end regardless of activity (`session.absoluteLifetimeSeconds`). */
26
+ export function familyEndsAt(state, familyCreatedAt) {
27
+ return new Date(new Date(familyCreatedAt).getTime() + state.config.session.absoluteLifetimeSeconds * 1000);
28
+ }
29
+
30
+ /** A refresh row's expiry: the usual sliding TTL, but never past the family's absolute end. */
31
+ export function cappedExpiry(state, familyCreatedAt, ttlSeconds) {
32
+ const sliding = new Date(Date.now() + ttlSeconds * 1000);
33
+ const end = familyEndsAt(state, familyCreatedAt);
34
+ return sliding < end ? sliding : end;
35
+ }
36
+
37
+ async function markRevokedInCache(state, jtis) {
38
+ for (const jti of jtis || []) {
39
+ await state.cache.set(`${CACHE_KEY_PREFIXES.REVOKED_REFRESH_TOKEN}:${jti}`, '1', state.config.ttls.revocationCache);
40
+ }
41
+ }
42
+
43
+ /**
44
+ * The hash a refresh token's row is stored under: the current key's, or — after
45
+ * `security.tokenHashSecret` was rotated — a previous key's. Everything after uses that one hash.
46
+ */
47
+ export async function resolveRefreshTokenHash(state, rawToken) {
48
+ if (!state.config.security.previousTokenHashSecrets?.length) return hashOpaqueToken(state, rawToken, HASH_PURPOSES.REFRESH_TOKEN);
49
+ const sessions = state.storage.sessionRepository;
50
+ return (await lookupByTokenHash(state, rawToken, HASH_PURPOSES.REFRESH_TOKEN, (hash) => sessions.findByRefreshTokenHash(hash))).hash;
51
+ }
52
+
53
+ /**
54
+ * The live (unrevoked, unexpired) row for a refresh token, read WITHOUT consuming it — so a refresh
55
+ * can run every check before it commits. The consume that follows is still the atomic gate.
56
+ */
57
+ export async function peekRefreshRow(state, tokenHash) {
58
+ const row = await state.storage.sessionRepository.findByRefreshTokenHash(tokenHash);
59
+ if (!row || row.revokedAt || !(new Date(row.expiresAt) > new Date())) return null;
60
+ return row;
61
+ }
62
+
63
+ /**
64
+ * Called when a refresh token didn't redeem. If it is one that was already rotated — and not within
65
+ * the short `session.refreshReuseGraceSeconds` (two tabs refreshing at once) — revokes its family.
66
+ */
67
+ export async function handleRefreshReuse(state, tokenHash) {
68
+ const sessions = state.storage.sessionRepository;
69
+ if (typeof sessions.revokeFamily !== 'function') return;
70
+ const row = await sessions.findByRefreshTokenHash(tokenHash);
71
+ if (!row?.revokedAt || row.revokeReason !== 'rotated') return;
72
+ // Measured by the database alone (the rotation and this check may run on servers whose clocks differ).
73
+ if (await sessions.rotatedWithin(tokenHash, state.config.session.refreshReuseGraceSeconds)) return;
74
+
75
+ const { familyId } = familyOf(row);
76
+ const { revokedCount, jtis } = await sessions.revokeFamily(familyId, { reason: 'reuse_detected' });
77
+ await markRevokedInCache(state, jtis);
78
+ await auditLog(state.logger, state.hooks, 'REFRESH_TOKEN_REUSE_DETECTED', {
79
+ userId: String(row.user), clientId: row.claims?.clientId ?? null, revokedSessions: revokedCount,
80
+ });
81
+ }
82
+
83
+ /** Revokes a family outright (e.g. every token produced from a reused authorization code). */
84
+ export async function revokeFamily(state, familyId, reason) {
85
+ const sessions = state.storage.sessionRepository;
86
+ if (typeof sessions.revokeFamily !== 'function') return 0;
87
+ const { revokedCount, jtis } = await sessions.revokeFamily(familyId, { reason });
88
+ await markRevokedInCache(state, jtis);
89
+ return revokedCount;
90
+ }
91
+
92
+ /** The user's current session epoch (see identity-user.model.js) — 0 for a user that never had one bumped. */
93
+ export async function currentSessionEpoch(state, userId) {
94
+ const user = await state.storage.userRepository.findById(userId, { select: 'sessionEpoch' });
95
+ return user?.sessionEpoch ?? 0;
96
+ }
97
+
98
+ /**
99
+ * "Revoke all of this user's sessions" (logout-all, password reset/change, account deletion). The
100
+ * user's `sessionEpoch` is bumped FIRST, then the rows are revoked: a refresh that consumed its row
101
+ * just before and inserts its successor just after would otherwise leave that successor alive.
102
+ * `assertChainNotRevoked` is the refresh-side half of that.
103
+ */
104
+ export async function revokeAllUserSessions(state, userId, opts) {
105
+ await state.storage.userRepository.bumpSessionEpoch(userId);
106
+ return state.storage.sessionRepository.revokeAllForUser(userId, opts);
107
+ }
108
+
109
+ /**
110
+ * "Sign out every OTHER session" (MFA enrolment): the same watermark as revokeAllUserSessions, with the
111
+ * current session's family exempt — so a refresh of another session that was already in flight is
112
+ * still caught by assertChainNotRevoked, while the current session carries on.
113
+ */
114
+ export async function revokeOtherUserSessions(state, userId, { exceptJti }) {
115
+ const current = exceptJti && typeof state.storage.sessionRepository.findByJti === 'function'
116
+ ? await state.storage.sessionRepository.findByJti(exceptJti)
117
+ : null;
118
+ const exceptFamily = current ? familyOf(current).familyId : null;
119
+ const epoch = await state.storage.userRepository.bumpSessionEpoch(userId, { exceptFamily });
120
+ const result = await state.storage.sessionRepository.revokeAllForUser(userId, { exceptJti });
121
+ // The current session carries on into the new epoch (so a later revocation that exempts it again
122
+ // still recognises it).
123
+ if (exceptFamily && epoch !== null) await state.storage.sessionRepository.raiseFamilyEpoch(exceptFamily, epoch);
124
+ return result;
125
+ }
126
+
127
+ /**
128
+ * After a session row has been written (login, refresh, code redemption): if the user's sessions were
129
+ * revoked since `sinceEpoch` — the epoch the chain was authenticated in (read before the credentials
130
+ * were checked) — the new row belongs to a revoked chain: revoke it and refuse. `familyId` is spared
131
+ * only when the one revocation since was revokeOtherUserSessions exempting that family.
132
+ */
133
+ export async function assertChainNotRevoked(state, userId, sinceEpoch, newTokenHash, familyId) {
134
+ const user = await state.storage.userRepository.findById(userId, { select: 'sessionEpoch sessionsRevokedExceptFamily' });
135
+ // Without a readable epoch there is no telling whether the chain was revoked: refuse (an adapter
136
+ // that doesn't persist the field would otherwise turn this check off silently).
137
+ if (user && !Number.isInteger(user.sessionEpoch)) state.logger?.error?.({ userId: String(userId) }, 'Storage adapter returned a user without an integer sessionEpoch — session refused (see storage/interfaces.js)');
138
+ const current = Number.isInteger(user?.sessionEpoch) ? user.sessionEpoch : Infinity;
139
+ const since = sinceEpoch ?? 0;
140
+ if (current <= since) return;
141
+ if (familyId && current === since + 1 && user.sessionsRevokedExceptFamily === familyId) {
142
+ await state.storage.sessionRepository.raiseFamilyEpoch(familyId, current);
143
+ return;
144
+ }
145
+ await state.storage.sessionRepository.revokeByRefreshTokenHash(newTokenHash, { onlyIfActive: false });
146
+ throw new IdpError({ code: 'TOKEN_REVOKED', httpStatus: 401, message: 'Session has been revoked' });
147
+ }
148
+
149
+ /**
150
+ * After a refresh has written its successor: if reuse detection revoked the family meanwhile (it ran
151
+ * while this refresh was between consuming its token and inserting the successor, so it couldn't see
152
+ * the successor), revoke the successor and refuse.
153
+ */
154
+ export async function assertFamilyNotRevoked(state, familyId, newTokenHash) {
155
+ if (!(await state.storage.sessionRepository.isFamilyRevoked(familyId))) return;
156
+ await state.storage.sessionRepository.revokeByRefreshTokenHash(newTokenHash, { onlyIfActive: false });
157
+ throw new IdpError({ code: 'TOKEN_REVOKED', httpStatus: 401, message: 'Session has been revoked' });
158
+ }