@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.
- package/.env.example +159 -0
- package/CHANGELOG.md +63 -0
- package/LICENSE +21 -0
- package/README.md +275 -3
- package/package.json +78 -6
- package/src/cache/cache-adapter.js +22 -0
- package/src/cache/index.js +68 -0
- package/src/cache/memory.adapter.js +85 -0
- package/src/cache/redis.adapter.js +96 -0
- package/src/config/console-logger.js +10 -0
- package/src/config/constants.js +178 -0
- package/src/config/defaults.js +100 -0
- package/src/config/from-env.js +150 -0
- package/src/config/init.js +286 -0
- package/src/config/state.js +22 -0
- package/src/errors/error-codes.js +97 -0
- package/src/errors/idp-error.js +75 -0
- package/src/hooks/index.js +85 -0
- package/src/index.js +167 -0
- package/src/magic-link/controller.js +129 -0
- package/src/magic-link/schemas.js +12 -0
- package/src/mfa/attempt-guard.js +48 -0
- package/src/mfa/controller.js +309 -0
- package/src/mfa/factor-store.js +37 -0
- package/src/mfa/memory-attempt-counter.js +58 -0
- package/src/mfa/schemas.js +11 -0
- package/src/mfa/secret-cipher.js +133 -0
- package/src/mfa/secrets.js +156 -0
- package/src/middleware/auth-context.middleware.js +149 -0
- package/src/middleware/cookie-parser.js +4 -0
- package/src/middleware/csrf.js +48 -0
- package/src/middleware/require-recent-auth.middleware.js +30 -0
- package/src/middleware/require-service-caller.middleware.js +32 -0
- package/src/middleware/service-context.middleware.js +70 -0
- package/src/middleware/validate-body.js +16 -0
- package/src/middleware/validate-query.js +22 -0
- package/src/oauth2/authorize.controller.js +233 -0
- package/src/oauth2/client-auth.js +77 -0
- package/src/oauth2/client.controller.js +122 -0
- package/src/oauth2/consent.controller.js +63 -0
- package/src/oauth2/login-challenge.js +50 -0
- package/src/oauth2/redirect-uri.js +25 -0
- package/src/oauth2/schemas.js +103 -0
- package/src/oauth2/token.controller.js +370 -0
- package/src/oidc/discovery.controller.js +36 -0
- package/src/oidc/end-session.controller.js +137 -0
- package/src/oidc/userinfo.controller.js +49 -0
- package/src/password-auth/controllers.js +927 -0
- package/src/password-auth/schemas.js +76 -0
- package/src/rate-limit/enforce.js +35 -0
- package/src/rate-limit/index.js +61 -0
- package/src/rate-limit/keys.js +36 -0
- package/src/rate-limit/memory.adapter.js +75 -0
- package/src/rate-limit/noop.adapter.js +14 -0
- package/src/rate-limit/rate-limiter.js +18 -0
- package/src/rate-limit/redis.adapter.js +71 -0
- package/src/routes/build-router.js +238 -0
- package/src/security/attempt-budget.js +47 -0
- package/src/security/clock-skew.js +63 -0
- package/src/service-mesh/key-status.js +22 -0
- package/src/service-mesh/local-key-lookup.js +12 -0
- package/src/service-mesh/remote-jwks-key-lookup.js +74 -0
- package/src/service-mesh/s2s-bootstrap.middleware.js +41 -0
- package/src/service-mesh/service-identity.client.js +89 -0
- package/src/service-mesh/service-key.controller.js +170 -0
- package/src/service-mesh/verify-service-token.js +75 -0
- package/src/signing/jwks.controller.js +30 -0
- package/src/signing/jwks.js +24 -0
- package/src/signing/key-registry.js +97 -0
- package/src/signing/token.service.js +336 -0
- package/src/sso/binding.js +30 -0
- package/src/sso/callback.controller.js +186 -0
- package/src/sso/initiate.controller.js +92 -0
- package/src/sso/providers.js +237 -0
- package/src/sso/schemas.js +7 -0
- package/src/storage/interfaces.js +178 -0
- package/src/storage/postgres/db.js +68 -0
- package/src/storage/postgres/index.js +160 -0
- package/src/storage/postgres/migrations/run-migrations.js +122 -0
- package/src/storage/postgres/migrations/sql/0001_init.sql +253 -0
- package/src/storage/postgres/repositories/attempt-counter.repository.js +65 -0
- package/src/storage/postgres/repositories/authorization-code.repository.js +104 -0
- package/src/storage/postgres/repositories/consent.repository.js +68 -0
- package/src/storage/postgres/repositories/credential.repository.js +75 -0
- package/src/storage/postgres/repositories/oauth-client.repository.js +122 -0
- package/src/storage/postgres/repositories/service-key.repository.js +76 -0
- package/src/storage/postgres/repositories/session.repository.js +290 -0
- package/src/storage/postgres/repositories/user.repository.js +328 -0
- package/src/storage/postgres/repositories/verification-token.repository.js +138 -0
- package/src/storage/postgres/run.js +22 -0
- package/src/utils/account-status.js +26 -0
- package/src/utils/cookies.js +129 -0
- package/src/utils/device-fingerprint.js +58 -0
- package/src/utils/email-hash.js +23 -0
- package/src/utils/oauth-client-credentials.js +51 -0
- package/src/utils/password.js +40 -0
- package/src/utils/safe-equal.js +12 -0
- package/src/utils/session-family.js +158 -0
- package/src/utils/session-kind.js +15 -0
- package/src/utils/url.js +17 -0
- package/src/webauthn/authentication.controller.js +126 -0
- package/src/webauthn/challenge-store.js +17 -0
- package/src/webauthn/config.js +25 -0
- package/src/webauthn/mfa.controller.js +119 -0
- package/src/webauthn/registration.controller.js +128 -0
- package/src/webauthn/schemas.js +41 -0
- package/src/webauthn/shared.js +63 -0
- package/src/webhooks/dispatcher.js +135 -0
- package/src/webhooks/sign.js +55 -0
- package/src/webhooks/wrap-hooks.js +51 -0
- package/types/index.d.ts +783 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { getState } from '../config/state.js';
|
|
3
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
4
|
+
import { CACHE_KEY_PREFIXES } from '../config/constants.js';
|
|
5
|
+
import { buildSsoProviders, isAllowedRedirectUri } from './providers.js';
|
|
6
|
+
import { auditLog } from '../hooks/index.js';
|
|
7
|
+
import { enforceRateLimit } from '../rate-limit/enforce.js';
|
|
8
|
+
import { ipKey } from '../rate-limit/keys.js';
|
|
9
|
+
import { ssoBindingCookie } from './binding.js';
|
|
10
|
+
|
|
11
|
+
const RESERVED_QUERY_KEYS = new Set(['redirect_uri', 'login_challenge']);
|
|
12
|
+
const MAX_EXTRA_KEYS = 10;
|
|
13
|
+
const MAX_EXTRA_KEY_LENGTH = 64;
|
|
14
|
+
const MAX_EXTRA_VALUE_LENGTH = 256;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Extra query params beyond `redirect_uri` are opaque, consumer-defined context (e.g. an intended-role
|
|
18
|
+
* hint) handed to `resolveAuthContext` at callback time. They come from whoever built the link, so
|
|
19
|
+
* they are UNTRUSTED input — and they sit in the cache for the whole login. Only short string values
|
|
20
|
+
* are kept (at most 10); anything else (nested objects from Express 4's qs parser, long values) is
|
|
21
|
+
* dropped.
|
|
22
|
+
*/
|
|
23
|
+
function sanitizeExtra(query) {
|
|
24
|
+
const extra = {};
|
|
25
|
+
for (const [k, v] of Object.entries(query)) {
|
|
26
|
+
if (RESERVED_QUERY_KEYS.has(k) || Object.keys(extra).length >= MAX_EXTRA_KEYS) continue;
|
|
27
|
+
if (k.length > MAX_EXTRA_KEY_LENGTH || typeof v !== 'string' || v.length > MAX_EXTRA_VALUE_LENGTH) continue;
|
|
28
|
+
extra[k] = v;
|
|
29
|
+
}
|
|
30
|
+
return extra;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const sha256b64url = (s) => crypto.createHash('sha256').update(s).digest('base64url');
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* GET /sso/:provider
|
|
37
|
+
*
|
|
38
|
+
* Starts a provider login. Alongside the random `state`, it sets a cookie (one per attempt) holding a
|
|
39
|
+
* random binding value whose hash is stored with the state: the callback only completes in the
|
|
40
|
+
* browser that started the login. Without that, an attacker could start a login with their own
|
|
41
|
+
* provider account and get a victim's browser to finish it — signing the victim into the
|
|
42
|
+
* attacker's account (login CSRF). With providers that support it, the code exchange is also bound
|
|
43
|
+
* by PKCE; Apple (id_token-based) is bound by a nonce.
|
|
44
|
+
*/
|
|
45
|
+
export async function initiateSsoHandler(req, res, next) {
|
|
46
|
+
try {
|
|
47
|
+
const state = getState();
|
|
48
|
+
await enforceRateLimit(state, `sso-initiate:ip:${ipKey(req.ip)}`, state.config.rateLimiting.ssoInitiate, { failMode: 'closed' });
|
|
49
|
+
|
|
50
|
+
const { provider } = req.params;
|
|
51
|
+
const q = req.validatedQuery || req.query;
|
|
52
|
+
const { redirect_uri } = q;
|
|
53
|
+
|
|
54
|
+
if (!redirect_uri || !isAllowedRedirectUri(state.config, redirect_uri)) {
|
|
55
|
+
throw new IdpError({ code: 'INVALID_REDIRECT_URI', httpStatus: 400, message: 'redirect_uri is missing or not on an allowed origin' });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const providers = buildSsoProviders(state.config);
|
|
59
|
+
const providerConfig = providers[provider];
|
|
60
|
+
if (!providerConfig) throw new IdpError({ code: 'INVALID_SSO_PROVIDER', httpStatus: 400, message: `Unknown or unconfigured SSO provider: ${provider}` });
|
|
61
|
+
|
|
62
|
+
const csrfState = crypto.randomBytes(32).toString('base64url');
|
|
63
|
+
const binding = crypto.randomBytes(32).toString('base64url');
|
|
64
|
+
const codeVerifier = providerConfig.pkce ? crypto.randomBytes(32).toString('base64url') : null;
|
|
65
|
+
const nonce = providerConfig.nonce ? crypto.randomBytes(16).toString('base64url') : null;
|
|
66
|
+
|
|
67
|
+
await state.cache.set(`${CACHE_KEY_PREFIXES.SSO_STATE}:${csrfState}`, {
|
|
68
|
+
provider, redirect_uri, extra: sanitizeExtra(q), bindingHash: sha256b64url(binding), codeVerifier, nonce,
|
|
69
|
+
loginChallenge: typeof q.login_challenge === 'string' ? q.login_challenge : null,
|
|
70
|
+
}, state.config.ttls.ssoState);
|
|
71
|
+
|
|
72
|
+
const cookie = ssoBindingCookie(state, csrfState, providerConfig);
|
|
73
|
+
res.cookie(cookie.name, binding, cookie.options);
|
|
74
|
+
|
|
75
|
+
const params = new URLSearchParams({
|
|
76
|
+
response_type: 'code',
|
|
77
|
+
client_id: providerConfig.clientId,
|
|
78
|
+
redirect_uri: providerConfig.redirectUri,
|
|
79
|
+
scope: providerConfig.scopes.join(' '),
|
|
80
|
+
state: csrfState,
|
|
81
|
+
...(codeVerifier ? { code_challenge: sha256b64url(codeVerifier), code_challenge_method: 'S256' } : {}),
|
|
82
|
+
...(nonce ? { nonce } : {}),
|
|
83
|
+
...(providerConfig.name === 'apple' ? { response_mode: 'form_post' } : {}),
|
|
84
|
+
...(providerConfig.name === 'google' ? { access_type: 'online', prompt: 'select_account' } : {}),
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
await auditLog(state.logger, state.hooks, 'SSO_INITIATED', { provider });
|
|
88
|
+
res.redirect(`${providerConfig.authorizationUrl}?${params.toString()}`);
|
|
89
|
+
} catch (err) {
|
|
90
|
+
next(err);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Apple requires a short-lived ES256-signed JWT as the OAuth client_secret,
|
|
5
|
+
* regenerated before every token exchange. This is Apple's own requirement
|
|
6
|
+
* for its client-assertion format — unrelated to (and independent of) this
|
|
7
|
+
* package's own RS256 user-token signing keys.
|
|
8
|
+
*/
|
|
9
|
+
function generateAppleClientSecret(appleConfig) {
|
|
10
|
+
const { teamId, keyId, clientId, privateKeyPem } = appleConfig;
|
|
11
|
+
if (!teamId || !keyId || !clientId || !privateKeyPem) {
|
|
12
|
+
throw new Error('Apple SSO is not fully configured (teamId, keyId, clientId, privateKeyPem required)');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const now = Math.floor(Date.now() / 1000);
|
|
16
|
+
const header = Buffer.from(JSON.stringify({ alg: 'ES256', kid: keyId })).toString('base64url');
|
|
17
|
+
// Minted per exchange, so it only needs to outlive one request: 5 minutes, not Apple's 6-month
|
|
18
|
+
// maximum — a secret that leaks from a log is then useless almost immediately.
|
|
19
|
+
const payload = Buffer.from(JSON.stringify({ iss: teamId, iat: now, exp: now + 300, aud: APPLE_ISSUER, sub: clientId })).toString('base64url');
|
|
20
|
+
const signingInput = `${header}.${payload}`;
|
|
21
|
+
const sign = crypto.createSign('SHA256');
|
|
22
|
+
sign.update(signingInput);
|
|
23
|
+
sign.end();
|
|
24
|
+
const signature = sign.sign({ key: privateKeyPem, dsaEncoding: 'ieee-p1363' }).toString('base64url');
|
|
25
|
+
return `${signingInput}.${signature}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const MULTI_TENANT_AUTHORITIES = new Set(['common', 'organizations', 'consumers']);
|
|
29
|
+
const APPLE_ISSUER = 'https://appleid.apple.com';
|
|
30
|
+
const DEFAULT_PROVIDER_TIMEOUT_MS = 10_000;
|
|
31
|
+
|
|
32
|
+
/** Builds the provider table from `config.oauthProviders` + `config.sso.baseCallbackUrl`. Providers with no clientId configured are omitted. */
|
|
33
|
+
export function buildSsoProviders(config) {
|
|
34
|
+
const p = config.oauthProviders || {};
|
|
35
|
+
const callbackFor = (provider) => `${config.sso?.baseCallbackUrl?.replace(/\/$/, '') || ''}/sso/${provider}/callback`;
|
|
36
|
+
|
|
37
|
+
const providers = {};
|
|
38
|
+
|
|
39
|
+
if (p.google?.clientId) {
|
|
40
|
+
providers.google = {
|
|
41
|
+
name: 'google',
|
|
42
|
+
authorizationUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
|
|
43
|
+
tokenUrl: 'https://oauth2.googleapis.com/token',
|
|
44
|
+
userInfoUrl: 'https://www.googleapis.com/oauth2/v3/userinfo',
|
|
45
|
+
clientId: p.google.clientId, clientSecret: p.google.clientSecret,
|
|
46
|
+
scopes: ['openid', 'email', 'profile'],
|
|
47
|
+
redirectUri: callbackFor('google'),
|
|
48
|
+
pkce: true,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (p.github?.clientId) {
|
|
53
|
+
providers.github = {
|
|
54
|
+
name: 'github',
|
|
55
|
+
authorizationUrl: 'https://github.com/login/oauth/authorize',
|
|
56
|
+
tokenUrl: 'https://github.com/login/oauth/access_token',
|
|
57
|
+
userInfoUrl: 'https://api.github.com/user',
|
|
58
|
+
userEmailsUrl: 'https://api.github.com/user/emails',
|
|
59
|
+
clientId: p.github.clientId, clientSecret: p.github.clientSecret,
|
|
60
|
+
scopes: ['read:user', 'user:email'],
|
|
61
|
+
redirectUri: callbackFor('github'),
|
|
62
|
+
pkce: true,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (p.microsoft?.clientId) {
|
|
67
|
+
// `tenant` defaults to "common" — multitenant work/school + personal
|
|
68
|
+
// Microsoft accounts. This is the one piece of the audited source
|
|
69
|
+
// that was already fully generic (a hardcoded literal, not an
|
|
70
|
+
// Okeav-specific value) — kept as-is, just made configurable.
|
|
71
|
+
const tenant = p.microsoft.tenant || 'common';
|
|
72
|
+
providers.microsoft = {
|
|
73
|
+
name: 'microsoft',
|
|
74
|
+
// Graph's `mail` / `userPrincipalName` are set by whichever tenant's admin owns the account,
|
|
75
|
+
// and Microsoft does not verify them — with a multi-tenant authority, anyone can create a
|
|
76
|
+
// tenant and give a user `mail = victim@yourcompany.com` ("nOAuth"). The address is only
|
|
77
|
+
// trusted when the authority is pinned to one tenant (yours), or explicitly via `trustEmail`.
|
|
78
|
+
emailTrusted: p.microsoft.trustEmail === true || !MULTI_TENANT_AUTHORITIES.has(String(tenant).toLowerCase()),
|
|
79
|
+
authorizationUrl: `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/authorize`,
|
|
80
|
+
tokenUrl: `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/token`,
|
|
81
|
+
userInfoUrl: 'https://graph.microsoft.com/v1.0/me',
|
|
82
|
+
clientId: p.microsoft.clientId, clientSecret: p.microsoft.clientSecret,
|
|
83
|
+
scopes: ['openid', 'email', 'profile', 'User.Read'],
|
|
84
|
+
redirectUri: callbackFor('microsoft'),
|
|
85
|
+
pkce: true,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (p.apple?.clientId) {
|
|
90
|
+
providers.apple = {
|
|
91
|
+
name: 'apple',
|
|
92
|
+
authorizationUrl: 'https://appleid.apple.com/auth/authorize',
|
|
93
|
+
tokenUrl: 'https://appleid.apple.com/auth/token',
|
|
94
|
+
clientId: p.apple.clientId,
|
|
95
|
+
scopes: ['openid', 'email', 'name'],
|
|
96
|
+
redirectUri: callbackFor('apple'),
|
|
97
|
+
responseMode: 'form_post',
|
|
98
|
+
// The identity comes from Apple's id_token, so it is bound to this login with a nonce.
|
|
99
|
+
nonce: true,
|
|
100
|
+
getClientSecret: () => generateAppleClientSecret(p.apple),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (p.linkedin?.clientId) {
|
|
105
|
+
providers.linkedin = {
|
|
106
|
+
name: 'linkedin',
|
|
107
|
+
authorizationUrl: 'https://www.linkedin.com/oauth/v2/authorization',
|
|
108
|
+
tokenUrl: 'https://www.linkedin.com/oauth/v2/accessToken',
|
|
109
|
+
userInfoUrl: 'https://api.linkedin.com/v2/userinfo',
|
|
110
|
+
clientId: p.linkedin.clientId, clientSecret: p.linkedin.clientSecret,
|
|
111
|
+
scopes: ['openid', 'profile', 'email'],
|
|
112
|
+
redirectUri: callbackFor('linkedin'),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return providers;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Whether SSO may send the browser back to `uri`. Fails closed: without a non-empty
|
|
121
|
+
* `config.sso.allowedRedirectOrigins` nothing is allowed (initIdentityProvider refuses to start with
|
|
122
|
+
* SSO providers but no allowlist) — an open redirect at the end of a real provider login is a
|
|
123
|
+
* convincing phishing step. Only https (or http to localhost) origins on the list pass.
|
|
124
|
+
*/
|
|
125
|
+
export function isAllowedRedirectUri(config, uri) {
|
|
126
|
+
const allowed = config.sso?.allowedRedirectOrigins;
|
|
127
|
+
if (!Array.isArray(allowed) || allowed.length === 0) return false;
|
|
128
|
+
let url;
|
|
129
|
+
try {
|
|
130
|
+
url = new URL(uri);
|
|
131
|
+
} catch {
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
const schemeOk = url.protocol === 'https:' || (url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname));
|
|
135
|
+
return schemeOk && !url.username && !url.password && allowed.includes(url.origin);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Checks Apple's id_token. It arrives over TLS straight from Apple's token endpoint in exchange for
|
|
140
|
+
* our client-authenticated code request, which OIDC Core §3.1.3.7 accepts in place of a signature
|
|
141
|
+
* check — but the claims must still be ours: issuer, audience (our client id), expiry, and the
|
|
142
|
+
* nonce this login sent.
|
|
143
|
+
*/
|
|
144
|
+
export function assertAppleIdToken(providerConfig, idTokenPayload, expectedNonce) {
|
|
145
|
+
const now = Math.floor(Date.now() / 1000);
|
|
146
|
+
const aud = Array.isArray(idTokenPayload?.aud) ? idTokenPayload.aud : [idTokenPayload?.aud];
|
|
147
|
+
if (idTokenPayload?.iss !== APPLE_ISSUER) throw new Error('Apple id_token: unexpected issuer');
|
|
148
|
+
if (!aud.includes(providerConfig.clientId)) throw new Error('Apple id_token: unexpected audience');
|
|
149
|
+
if (!(typeof idTokenPayload.exp === 'number' && idTokenPayload.exp > now - 60)) throw new Error('Apple id_token: expired');
|
|
150
|
+
if (!expectedNonce || idTokenPayload.nonce !== expectedNonce) throw new Error('Apple id_token: nonce mismatch');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function decodeJwtPayload(token) {
|
|
154
|
+
const [, payload] = String(token).split('.');
|
|
155
|
+
return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function providerFetch(config, url, init) {
|
|
159
|
+
return fetch(url, { ...init, redirect: 'error', signal: AbortSignal.timeout(config.sso?.providerTimeoutMs ?? DEFAULT_PROVIDER_TIMEOUT_MS) });
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Apple sends email_verified as the string "true"; the others as a boolean.
|
|
163
|
+
const isTrue = (v) => v === true || v === 'true';
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Normalizes each provider's raw profile response into a consistent shape. `emailVerified` is true
|
|
167
|
+
* only when the provider itself asserts it verified the address — it decides whether this identity
|
|
168
|
+
* may be linked to (or create) a local account by email. `providerConfig` is needed for Microsoft.
|
|
169
|
+
*/
|
|
170
|
+
export function normalizeUserInfo(provider, raw, providerConfig = {}) {
|
|
171
|
+
switch (provider) {
|
|
172
|
+
case 'google':
|
|
173
|
+
return { providerId: raw.sub, email: raw.email, emailVerified: isTrue(raw.email_verified), firstName: raw.given_name || null, lastName: raw.family_name || null, name: raw.name, avatarUrl: raw.picture };
|
|
174
|
+
case 'github':
|
|
175
|
+
return {
|
|
176
|
+
// fetchUserInfo replaces `email` with the account's primary *verified* address (or null).
|
|
177
|
+
providerId: String(raw.id), email: raw.email, emailVerified: isTrue(raw.email_verified),
|
|
178
|
+
firstName: raw.name?.split(' ')[0] || null,
|
|
179
|
+
lastName: raw.name?.split(' ').slice(1).join(' ') || null,
|
|
180
|
+
name: raw.name || raw.login, avatarUrl: raw.avatar_url,
|
|
181
|
+
};
|
|
182
|
+
case 'microsoft':
|
|
183
|
+
return { providerId: raw.id, email: raw.mail || raw.userPrincipalName, emailVerified: providerConfig.emailTrusted === true, firstName: raw.givenName || null, lastName: raw.surname || null, name: raw.displayName, avatarUrl: null };
|
|
184
|
+
case 'apple': {
|
|
185
|
+
const payload = decodeJwtPayload(raw.id_token);
|
|
186
|
+
const appleUser = raw.appleUser;
|
|
187
|
+
return {
|
|
188
|
+
providerId: payload.sub, email: payload.email || null, emailVerified: isTrue(payload.email_verified),
|
|
189
|
+
firstName: appleUser?.name?.firstName || null, lastName: appleUser?.name?.lastName || null,
|
|
190
|
+
name: [appleUser?.name?.firstName, appleUser?.name?.lastName].filter(Boolean).join(' ') || payload.sub,
|
|
191
|
+
avatarUrl: null,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
case 'linkedin':
|
|
195
|
+
return { providerId: raw.sub, email: raw.email, emailVerified: isTrue(raw.email_verified), firstName: raw.given_name || null, lastName: raw.family_name || null, name: raw.name || [raw.given_name, raw.family_name].filter(Boolean).join(' '), avatarUrl: raw.picture || null };
|
|
196
|
+
default:
|
|
197
|
+
throw new Error(`Unknown provider: ${provider}`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export async function exchangeCode(config, providerConfig, code, { codeVerifier } = {}) {
|
|
202
|
+
const clientSecret = providerConfig.getClientSecret ? providerConfig.getClientSecret() : providerConfig.clientSecret;
|
|
203
|
+
const params = new URLSearchParams({
|
|
204
|
+
grant_type: 'authorization_code', code, redirect_uri: providerConfig.redirectUri, client_id: providerConfig.clientId, client_secret: clientSecret,
|
|
205
|
+
...(codeVerifier ? { code_verifier: codeVerifier } : {}),
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
const response = await providerFetch(config, providerConfig.tokenUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }, body: params.toString() });
|
|
209
|
+
if (!response.ok) {
|
|
210
|
+
throw new Error(`SSO provider ${providerConfig.name} returned ${response.status} during code exchange`);
|
|
211
|
+
}
|
|
212
|
+
return response.json();
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export async function fetchUserInfo(config, providerConfig, accessToken) {
|
|
216
|
+
const response = await providerFetch(config, providerConfig.userInfoUrl, { headers: { Authorization: `Bearer ${accessToken}`, Accept: 'application/json' } });
|
|
217
|
+
if (!response.ok) throw new Error(`SSO provider ${providerConfig.name} returned ${response.status} fetching user info`);
|
|
218
|
+
const info = await response.json();
|
|
219
|
+
|
|
220
|
+
// GitHub's profile `email` is whatever public address the user chose to show, and carries no
|
|
221
|
+
// verification status — only the emails endpoint says which address is verified. Always use the
|
|
222
|
+
// primary verified one; without it there is no trustworthy email at all.
|
|
223
|
+
if (providerConfig.name === 'github' && providerConfig.userEmailsUrl) {
|
|
224
|
+
info.email = null;
|
|
225
|
+
info.email_verified = false;
|
|
226
|
+
const emailRes = await providerFetch(config, providerConfig.userEmailsUrl, { headers: { Authorization: `Bearer ${accessToken}`, Accept: 'application/json' } });
|
|
227
|
+
if (emailRes.ok) {
|
|
228
|
+
const emails = await emailRes.json();
|
|
229
|
+
const primary = Array.isArray(emails) ? emails.find((e) => e.primary && e.verified) : null;
|
|
230
|
+
if (primary) {
|
|
231
|
+
info.email = primary.email;
|
|
232
|
+
info.email_verified = true;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return info;
|
|
237
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { loginChallengeSchema } from '../oauth2/login-challenge.js';
|
|
3
|
+
|
|
4
|
+
export const ssoInitiateQuerySchema = z.object({
|
|
5
|
+
redirect_uri: z.string().url(),
|
|
6
|
+
login_challenge: loginChallengeSchema.optional(),
|
|
7
|
+
}).passthrough(); // extra opaque query params are forwarded to resolveAuthContext — see initiate.controller.js
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Storage interfaces — documentation only (JS has no runtime interface
|
|
3
|
+
* checks). See types/index.d.ts for the enforced TypeScript shapes.
|
|
4
|
+
*
|
|
5
|
+
* The contract the IdP code holds the store to: every repository in
|
|
6
|
+
* storage/postgres/repositories implements one of these, and createPostgresStorage()
|
|
7
|
+
* (storage/postgres/index.js) returns them together with close(), databaseTime() and
|
|
8
|
+
* pruneExpired(). The semantics below (atomicity, which clock, what to persist) are what
|
|
9
|
+
* the security behaviour rests on — a change to a repository must keep them.
|
|
10
|
+
*
|
|
11
|
+
* @typedef {Object} UserRepository
|
|
12
|
+
* @property {(data: object) => Promise<object>} create
|
|
13
|
+
* @property {(id: string, opts?: {select?: string}) => Promise<object|null>} findById
|
|
14
|
+
* @property {(email: string, opts?: {select?: string}) => Promise<object|null>} findByEmail
|
|
15
|
+
* @property {(provider: string, providerId: string) => Promise<object|null>} findByExternalProvider
|
|
16
|
+
* @property {(id: string, patch: object, opts?: object) => Promise<object|null>} updateById
|
|
17
|
+
* @property {(id: string, status: string, patch: object) => Promise<object|null>} updateByIdIfStatus - ATOMIC: apply
|
|
18
|
+
* `patch` only while the user's status is still `status`; null if it changed (registration/activation races)
|
|
19
|
+
* @property {(id: string, opts?: {exceptFamily?: string|null}) => Promise<number|null>} bumpSessionEpoch - ATOMIC:
|
|
20
|
+
* increment the user's `sessionEpoch` (a number, default 0, returned on every user read) and record
|
|
21
|
+
* `sessionsRevokedExceptFamily = exceptFamily` and `sessionsRevokedAt`; resolve the new epoch. "Revoke all sessions"
|
|
22
|
+
* is ordered by this counter, never by comparing app-server clocks. A user read that lacks an integer
|
|
23
|
+
* `sessionEpoch` makes sign-in and code redemption fail (closed), with an error log.
|
|
24
|
+
* @property {(id: string) => Promise<object|null>} [incrementFailedLoginAttempts] - unused since 0.4.0 (the password
|
|
25
|
+
* lockout lives in the attempt counters, key `password-login:<userId>`); kept for older callers
|
|
26
|
+
* @property {(id: string, step: number) => Promise<boolean>} [claimTotpStep] - ATOMIC: set `mfaLastTotpStep = step`
|
|
27
|
+
* only if it is unset or lower; resolve whether this call set it. Keeps a TOTP code from being accepted twice.
|
|
28
|
+
* Optional for now (a non-atomic fallback is used, with a startup warning).
|
|
29
|
+
* @property {(id: string, codeHash: string) => Promise<boolean>} [consumeRecoveryCode] - ATOMIC: set `usedAt` on the
|
|
30
|
+
* one unused recovery code with this hash; resolve whether one was. Optional for now, as above.
|
|
31
|
+
* @property {(id: string, link: {provider, providerId, email, connectedAt}) => Promise<object>} linkExternalProvider
|
|
32
|
+
* @property {(id: string) => Promise<void>} deleteById
|
|
33
|
+
* @property {() => Promise<number>} countAll
|
|
34
|
+
* @property {(opts: {skip?: number, limit?: number}) => Promise<object[]>} findMany
|
|
35
|
+
*
|
|
36
|
+
* @typedef {Object} SessionRepository
|
|
37
|
+
* @property {(input: object) => Promise<object>} createSession
|
|
38
|
+
* @property {(hash: string) => Promise<object|null>} findByRefreshTokenHash
|
|
39
|
+
* @property {(jti: string) => Promise<{id, user, expiresAt: Date, revokedAt: Date|null, revokeReason?: string, familyId?: string, createdAt?: Date}|null>} findByJti - the
|
|
40
|
+
* session whose `jti` matches an access token's `jti`. Called once per authenticated request when
|
|
41
|
+
* `config.session.verifyOnEachRequest` is on (the default), so it must be an indexed lookup. Also used
|
|
42
|
+
* to bind authorization codes to their session, to exempt the enrolling session at MFA enrolment, to
|
|
43
|
+
* redeem login challenges (prompt=login / max_age) and to find the browser's session at end-session.
|
|
44
|
+
* Required (and must return `familyId`).
|
|
45
|
+
* @property {(hash: string, opts?: {onlyIfActive?: boolean, reason?: string}) => Promise<object|null>} revokeByRefreshTokenHash -
|
|
46
|
+
* ATOMIC consume; resolves the row as it was BEFORE revocation. Must persist `reason` as `revokeReason`
|
|
47
|
+
* ('rotated' on refresh) — that is how a replayed rotated token is recognised.
|
|
48
|
+
* @property {(hash: string, seconds: number) => Promise<boolean>} rotatedWithin - whether the row was revoked with
|
|
49
|
+
* reason 'rotated' less than `seconds` ago, measured by ONE clock — the database's (so `revokeByRefreshTokenHash`
|
|
50
|
+
* must write `revokedAt` from that same clock)
|
|
51
|
+
* @property {(familyId: string, epoch: number) => Promise<void>} raiseFamilyEpoch - set `sessionEpoch` to at least
|
|
52
|
+
* `epoch` on every row of the family. Rows also persist `sessionEpoch` as given on create.
|
|
53
|
+
* @property {(familyId: string) => Promise<boolean>} isFamilyLive - whether the family has a live (unrevoked,
|
|
54
|
+
* unexpired) row
|
|
55
|
+
* @property {(familyId: string) => Promise<boolean>} isFamilyRevoked - whether revokeFamily ran for this family
|
|
56
|
+
* (it must tombstone every row of the family, `familyRevokedAt`, not only revoke the live ones)
|
|
57
|
+
* @property {(familyId: string, opts?: {reason?: string}) => Promise<{revokedCount: number, jtis: string[]}>} revokeFamily -
|
|
58
|
+
* revokes every live row with this `familyId` (refresh-token reuse / authorization-code reuse). Optional for now:
|
|
59
|
+
* without it, reuse is only refused, not punished.
|
|
60
|
+
* @property {(clientId: string, opts?: {userId?: string}) => Promise<{revokedCount: number, jtis: string[]}>} [revokeForClient] -
|
|
61
|
+
* revokes a client's live OAuth2 rows (one user's, or all). Used by consent revocation, client deactivation, end-session.
|
|
62
|
+
* Session rows also carry `kind`, `authTime`, `familyId`, `familyCreatedAt` — persist them as given.
|
|
63
|
+
* @property {(id: string, userId: string) => Promise<object|null>} revokeById
|
|
64
|
+
* @property {(userId: string, opts?: {exceptTokenHash?: string}) => Promise<{revokedCount: number}>} revokeAllForUser
|
|
65
|
+
* @property {(userId: string) => Promise<object[]>} listActiveForUser
|
|
66
|
+
* @property {(userId: string, opts?: {limit?: number}) => Promise<object[]>} listHistoryForUser
|
|
67
|
+
* @property {(userId: string, fingerprint: string|null, rawDeviceInfo: string) => Promise<boolean>} existsForDevice
|
|
68
|
+
* @property {(entry: object) => Promise<void>} [recordIssuedAccessToken] - optional, write-only audit
|
|
69
|
+
* @property {(input: object) => Promise<object>} createSessionForLogin - atomic composite write, see §2.1
|
|
70
|
+
* @property {() => Promise<{deletedCount: number}>} [pruneExpired] - optional, for adapters without native TTL
|
|
71
|
+
*
|
|
72
|
+
* @typedef {Object} AuthorizationCodeRepository
|
|
73
|
+
* Codes also carry `sessionEpoch` and `consentVersion` (numbers) — persist them as given.
|
|
74
|
+
* @property {(input: object) => Promise<void>} create
|
|
75
|
+
* @property {(hash: string) => Promise<object|null>} consumeByCodeHash
|
|
76
|
+
* @property {(hash: string) => Promise<object|null>} [findUsedByCodeHash] - an already-redeemed code (for reuse
|
|
77
|
+
* detection: its first redemption's tokens are revoked). Codes also carry `nonce` and `authTime`.
|
|
78
|
+
* @property {() => Promise<{deletedCount: number}>} [pruneExpired]
|
|
79
|
+
*
|
|
80
|
+
* @typedef {Object} ConsentRepository
|
|
81
|
+
* Every consent has a `version` (number, default 0) that `upsert` and `revoke` both increment atomically. A consent
|
|
82
|
+
* read without an integer `version` refuses code redemption (fail closed).
|
|
83
|
+
* @property {(userId: string, clientId: string, scopes: string[]) => Promise<object>} upsert - resolves the consent
|
|
84
|
+
* AFTER the write (with its new `version`)
|
|
85
|
+
* @property {(userId: string, clientId: string) => Promise<object|null>} find
|
|
86
|
+
* @property {(userId: string) => Promise<object[]>} listForUser
|
|
87
|
+
* @property {(userId: string, clientId: string) => Promise<void>} revoke
|
|
88
|
+
*
|
|
89
|
+
* @typedef {Object} OAuthClientRepository
|
|
90
|
+
* @property {(input: object) => Promise<object>} create
|
|
91
|
+
* @property {(clientId: string, opts?: {includeSecret?: boolean}) => Promise<object|null>} findByClientId
|
|
92
|
+
* @property {(slug: string) => Promise<object|null>} findBySlug
|
|
93
|
+
* @property {(clientId: string, patch: object) => Promise<object>} updateByClientId
|
|
94
|
+
* @property {(opts: {skip?: number, limit?: number}) => Promise<object[]>} listMany
|
|
95
|
+
* @property {() => Promise<number>} countAll
|
|
96
|
+
*
|
|
97
|
+
* @typedef {Object} VerificationTokenRepository
|
|
98
|
+
* @property {(kind: 'password_reset'|'email_verification'|'magic_link', input: object) => Promise<void>} create
|
|
99
|
+
* @property {(kind: string, hash: string, userId?: string) => Promise<object|null>} consumeByHash
|
|
100
|
+
* @property {(kind: string, code: string, userId: string) => Promise<object|null>} consumeByCode
|
|
101
|
+
* @property {(kind: string, by: {tokenHash?: string, verificationCode?: string}, userId: string) => Promise<object|null>} findActive -
|
|
102
|
+
* a live (unused, unexpired) token WITHOUT consuming it
|
|
103
|
+
* @property {(kind: string, userId: string) => Promise<void>} [clearCodes] - null the `verificationCode` of every row
|
|
104
|
+
* (kills guessable codes, keeps unguessable links). No longer called by idp-core; optional.
|
|
105
|
+
* @property {(kind: string, userId: string, input: object) => Promise<void>} replaceForUser - ATOMIC: the one live
|
|
106
|
+
* token of `kind` for the user (password_reset, magic_link), even under concurrent requests
|
|
107
|
+
* @property {(kind: string, userId: string) => Promise<void>} deleteAllForUser
|
|
108
|
+
* @property {() => Promise<{deletedCount: number}>} [pruneExpired]
|
|
109
|
+
*
|
|
110
|
+
* @typedef {Object} ServiceKeyRepository
|
|
111
|
+
* @property {(input: {kid, name, publicKey, region}) => Promise<object|null>} upsertByKid - must return null
|
|
112
|
+
* (and change nothing) for a kid that is REVOKED — a revoked key is never re-activated
|
|
113
|
+
* @property {(kid: string) => Promise<object|null>} [findByKid] - a key by kid whatever its status (lets a
|
|
114
|
+
* rotation refuse a revoked key before demoting the current one)
|
|
115
|
+
* @property {() => Promise<object[]>} listPublishable
|
|
116
|
+
* @property {(kid: string) => Promise<object|null>} [findPublishableByKid] - indexed single-key read (verification)
|
|
117
|
+
* @property {(kid: string, status: string, opts?: {expectedStatus?: string}) => Promise<object|null>} setStatusByKid - ROTATING / RETIRED / REVOKED;
|
|
118
|
+
* with `expectedStatus`, ATOMICALLY only from that status;
|
|
119
|
+
* should record `statusChangedAt` (a ROTATING key verifies for `serviceMesh.rotationGraceSeconds` after it)
|
|
120
|
+
*
|
|
121
|
+
* @typedef {Object} CredentialRepository
|
|
122
|
+
* WebAuthn/passkey credentials — one document per registered authenticator.
|
|
123
|
+
* `credentialId` is the base64url credential ID from the browser (globally
|
|
124
|
+
* unique per WebAuthn spec) and is the natural lookup key during both the
|
|
125
|
+
* primary-passwordless and MFA-second-factor authentication ceremonies.
|
|
126
|
+
* @property {(input: {userId, credentialId, publicKey, counter, transports?, deviceType?, backedUp?, name?}) => Promise<object>} create
|
|
127
|
+
* @property {(credentialId: string) => Promise<object|null>} findByCredentialId
|
|
128
|
+
* @property {(userId: string) => Promise<object[]>} findByUserId
|
|
129
|
+
* @property {(credentialId: string, newCounter: number) => Promise<void>} updateCounter
|
|
130
|
+
* @property {(credentialId: string, userId: string) => Promise<void>} deleteByCredentialId - scoped to the claimed owner
|
|
131
|
+
* @property {(userId: string) => Promise<number>} countForUser
|
|
132
|
+
*
|
|
133
|
+
* @typedef {Object} AttemptCounterRepository
|
|
134
|
+
* Optional. Fixed-window failure counters with a lock, keyed by an opaque
|
|
135
|
+
* string (`mfa:<userId>`, `password-login:<userId>`, `password-change:<userId>`,
|
|
136
|
+
* `email-verification:<email key>`).
|
|
137
|
+
* Lives in storage rather than the rate limiter so every app instance sees
|
|
138
|
+
* the same count whatever cache/rate-limiter adapter is configured. An
|
|
139
|
+
* adapter that doesn't provide it gets an in-process fallback
|
|
140
|
+
* (src/mfa/memory-attempt-counter.js) and a startup warning.
|
|
141
|
+
* @property {(key: string) => Promise<{count: number, windowExpiresAt: Date, lockedUntil: Date|null}|null>} get
|
|
142
|
+
* @property {(key: string, opts: {max: number, windowSeconds: number, lockSeconds: number}) => Promise<{count: number, windowExpiresAt: Date, lockedUntil: Date|null}>} recordFailure -
|
|
143
|
+
* ATOMIC: if there's no record, or (with no lock still active) its window has passed or its lock has
|
|
144
|
+
* expired, start over at count 1 with a new window; otherwise count + 1. When the count reaches `max` and no lock is set, set
|
|
145
|
+
* `lockedUntil = now + lockSeconds`. Returns the post-update record. Concurrent callers must each see a
|
|
146
|
+
* distinct count (exactly one sees `count === max`).
|
|
147
|
+
* @property {(key: string) => Promise<void>} reset
|
|
148
|
+
* @property {() => Promise<{deletedCount: number}>} [pruneExpired]
|
|
149
|
+
*/
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* The methods idp-core calls without checking for them first — an adapter missing one is refused at
|
|
153
|
+
* startup (initIdentityProvider) instead of failing in the middle of a login. Everything else in the
|
|
154
|
+
* typedefs above marked optional (`[name]`) is feature-detected.
|
|
155
|
+
*/
|
|
156
|
+
export const REQUIRED_STORAGE_METHODS = Object.freeze({
|
|
157
|
+
userRepository: ['create', 'findById', 'findByEmail', 'findByExternalProvider', 'updateById', 'updateByIdIfStatus', 'bumpSessionEpoch', 'linkExternalProvider', 'countAll', 'findMany'],
|
|
158
|
+
sessionRepository: ['createSession', 'createSessionForLogin', 'findByRefreshTokenHash', 'revokeByRefreshTokenHash', 'findByJti', 'rotatedWithin', 'raiseFamilyEpoch', 'isFamilyLive', 'isFamilyRevoked', 'revokeById', 'revokeAllForUser', 'listActiveForUser', 'existsForDevice'],
|
|
159
|
+
authorizationCodeRepository: ['create', 'consumeByCodeHash'],
|
|
160
|
+
consentRepository: ['upsert', 'find', 'listForUser', 'revoke'],
|
|
161
|
+
oauthClientRepository: ['create', 'findByClientId', 'findBySlug', 'updateByClientId', 'listMany', 'countAll'],
|
|
162
|
+
verificationTokenRepository: ['create', 'consumeByHash', 'consumeByCode', 'findActive', 'replaceForUser', 'deleteAllForUser'],
|
|
163
|
+
serviceKeyRepository: ['upsertByKid', 'listPublishable', 'setStatusByKid'],
|
|
164
|
+
credentialRepository: ['create', 'findByCredentialId', 'findByUserId', 'updateCounter', 'deleteByCredentialId'],
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
/** Throws naming every required method the adapter's `storage` object lacks. */
|
|
168
|
+
export function assertStorageContract(storage) {
|
|
169
|
+
const missing = [];
|
|
170
|
+
for (const [repo, methods] of Object.entries(REQUIRED_STORAGE_METHODS)) {
|
|
171
|
+
for (const m of methods) if (typeof storage?.[repo]?.[m] !== 'function') missing.push(`${repo}.${m}`);
|
|
172
|
+
}
|
|
173
|
+
if (typeof storage?.close !== 'function') missing.push('close');
|
|
174
|
+
if (storage?.attemptCounterRepository) {
|
|
175
|
+
for (const m of ['get', 'recordFailure', 'reset']) if (typeof storage.attemptCounterRepository[m] !== 'function') missing.push(`attemptCounterRepository.${m}`);
|
|
176
|
+
}
|
|
177
|
+
if (missing.length) throw new Error(`Storage adapter is missing required methods: ${missing.join(', ')} — see src/storage/interfaces.js`);
|
|
178
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export const newId = () => crypto.randomUUID();
|
|
4
|
+
|
|
5
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Whether `value` can be a row id here. Ids reach the repositories from tokens and URLs; one that
|
|
9
|
+
* can't be a UUID finds nothing — it must not become a 500 (Postgres refuses to cast it).
|
|
10
|
+
*/
|
|
11
|
+
export const isUuid = (value) => typeof value === 'string' && UUID.test(value);
|
|
12
|
+
|
|
13
|
+
/** Runs `fn(client)` in one transaction on one connection; rolls back on any error. */
|
|
14
|
+
export async function withTransaction(pool, fn) {
|
|
15
|
+
const client = await pool.connect();
|
|
16
|
+
let broken;
|
|
17
|
+
try {
|
|
18
|
+
await client.query('BEGIN');
|
|
19
|
+
const result = await fn(client);
|
|
20
|
+
await client.query('COMMIT');
|
|
21
|
+
return result;
|
|
22
|
+
} catch (err) {
|
|
23
|
+
await client.query('ROLLBACK').catch((rollbackErr) => { broken = rollbackErr; });
|
|
24
|
+
throw err;
|
|
25
|
+
} finally {
|
|
26
|
+
// A connection whose ROLLBACK failed is in an unknown state: destroy it rather than reuse it.
|
|
27
|
+
client.release(broken);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The column a patch key maps to — or a thrown error. A patch key this store doesn't know must never be
|
|
33
|
+
* dropped silently (a security-relevant field quietly not written is worse than a failed request).
|
|
34
|
+
*/
|
|
35
|
+
export function columnFor(columns, key, table) {
|
|
36
|
+
// Own properties only: `constructor`, `toString` … must not resolve to something.
|
|
37
|
+
const column = Object.hasOwn(columns, key) ? columns[key] : undefined;
|
|
38
|
+
if (!column) throw new Error(`@okeav/idp-pg: ${table} has no field '${key}' — a bug: the store and the IdP code are out of step`);
|
|
39
|
+
return column;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** `SET` clauses and values for a patch, numbering placeholders from `offset + 1`. */
|
|
43
|
+
export function setClauses(patch, columns, table, offset, encode = (_k, v) => v) {
|
|
44
|
+
const sets = [];
|
|
45
|
+
const values = [];
|
|
46
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
47
|
+
if (value === undefined) continue;
|
|
48
|
+
values.push(encode(key, value));
|
|
49
|
+
sets.push(`${columnFor(columns, key, table)} = $${offset + values.length}`);
|
|
50
|
+
}
|
|
51
|
+
return { sets, values };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Rows deleted per statement by pruning: short statements, short locks. */
|
|
55
|
+
export const PRUNE_BATCH = 5000;
|
|
56
|
+
|
|
57
|
+
/** Deletes rows matching `where` in batches; resolves the total deleted. */
|
|
58
|
+
export async function deleteInBatches(pool, table, where, params = []) {
|
|
59
|
+
let deletedCount = 0;
|
|
60
|
+
for (;;) {
|
|
61
|
+
const { rowCount } = await pool.query(
|
|
62
|
+
`DELETE FROM ${table} WHERE ctid IN (SELECT ctid FROM ${table} WHERE ${where} LIMIT ${PRUNE_BATCH})`,
|
|
63
|
+
params,
|
|
64
|
+
);
|
|
65
|
+
deletedCount += rowCount;
|
|
66
|
+
if (rowCount < PRUNE_BATCH) return { deletedCount };
|
|
67
|
+
}
|
|
68
|
+
}
|