@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,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional convenience — builds an IdpConfig object from `process.env`
|
|
3
|
+
* variables matching `.env.example`. This package never reads `process.env`
|
|
4
|
+
* on its own initiative; using this helper (or not) is entirely your
|
|
5
|
+
* choice — hand `initIdentityProvider()` a plain object built any way you
|
|
6
|
+
* like (including from Infisical, AWS Secrets Manager, etc.).
|
|
7
|
+
*
|
|
8
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
9
|
+
*/
|
|
10
|
+
const TRUE_VALUES = new Set(['true', '1', 'yes', 'on']);
|
|
11
|
+
const FALSE_VALUES = new Set(['false', '0', 'no', 'off']);
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Strict parsing: an unset or blank variable means "use the default"; anything else must be a
|
|
15
|
+
* recognisable value or startup fails. Before 0.4.0 only the exact string "true" was true, so
|
|
16
|
+
* `IDP_COOKIE_SECURE=1` (or a blank `IDP_COOKIE_SECURE=`) silently turned secure cookies OFF, and a
|
|
17
|
+
* non-numeric `IDP_MAX_FAILED_LOGIN_ATTEMPTS` became NaN, disabling account lockout.
|
|
18
|
+
*/
|
|
19
|
+
function parseBool(env, name, fallback) {
|
|
20
|
+
const raw = env[name];
|
|
21
|
+
if (raw === undefined || raw.trim() === '') return fallback;
|
|
22
|
+
const v = raw.trim().toLowerCase();
|
|
23
|
+
if (TRUE_VALUES.has(v)) return true;
|
|
24
|
+
if (FALSE_VALUES.has(v)) return false;
|
|
25
|
+
throw new Error(`${name} must be true/false (or 1/0, yes/no, on/off) — got "${raw}"`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function parseInteger(env, name, fallback, { min = 0 } = {}) {
|
|
29
|
+
const raw = env[name];
|
|
30
|
+
if (raw === undefined || raw.trim() === '') return fallback;
|
|
31
|
+
const n = Number(raw.trim());
|
|
32
|
+
if (!Number.isInteger(n) || n < min) throw new Error(`${name} must be an integer >= ${min} — got "${raw}"`);
|
|
33
|
+
return n;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const list = (raw) => (raw || '').split(',').map((x) => x.trim()).filter(Boolean);
|
|
37
|
+
|
|
38
|
+
export function configFromEnv(env = process.env) {
|
|
39
|
+
const bool = (name, fallback) => parseBool(env, name, fallback);
|
|
40
|
+
const int = (name, fallback, opts) => parseInteger(env, name, fallback, opts);
|
|
41
|
+
|
|
42
|
+
const signingKeys = { keys: {} };
|
|
43
|
+
if (env.IDP_SIGNING_KEY_CURRENT_KID) {
|
|
44
|
+
signingKeys.keys[env.IDP_SIGNING_KEY_CURRENT_KID] = {
|
|
45
|
+
privateKey: env.IDP_SIGNING_KEY_CURRENT_PRIVATE_B64,
|
|
46
|
+
publicKey: env.IDP_SIGNING_KEY_CURRENT_PUBLIC_B64,
|
|
47
|
+
status: 'ACTIVE',
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
if (env.IDP_SIGNING_KEY_PREVIOUS_KID) {
|
|
51
|
+
signingKeys.keys[env.IDP_SIGNING_KEY_PREVIOUS_KID] = {
|
|
52
|
+
privateKey: env.IDP_SIGNING_KEY_PREVIOUS_PRIVATE_B64,
|
|
53
|
+
publicKey: env.IDP_SIGNING_KEY_PREVIOUS_PUBLIC_B64,
|
|
54
|
+
status: 'ROTATING',
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
issuer: env.IDP_ISSUER,
|
|
60
|
+
postgres: {
|
|
61
|
+
connectionString: env.IDP_DATABASE_URL || env.DATABASE_URL,
|
|
62
|
+
migrations: env.IDP_PG_MIGRATIONS || 'verify',
|
|
63
|
+
pruneIntervalSeconds: int('IDP_PG_PRUNE_INTERVAL_SECONDS', 3600),
|
|
64
|
+
...(env.IDP_PG_POOL_MAX ? { poolConfig: { max: int('IDP_PG_POOL_MAX', 10, { min: 1 }) } } : {}),
|
|
65
|
+
},
|
|
66
|
+
cache: {
|
|
67
|
+
adapter: env.IDP_CACHE_ADAPTER || 'memory',
|
|
68
|
+
keyPrefix: env.IDP_CACHE_KEY_PREFIX || 'idp:',
|
|
69
|
+
redis: { host: env.IDP_REDIS_HOST, port: int('IDP_REDIS_PORT', 6379, { min: 1 }), username: env.IDP_REDIS_USERNAME || undefined, password: env.IDP_REDIS_PASSWORD || undefined, tls: bool('IDP_REDIS_TLS', false) },
|
|
70
|
+
},
|
|
71
|
+
signingKeys,
|
|
72
|
+
cookies: {
|
|
73
|
+
secure: bool('IDP_COOKIE_SECURE', env.NODE_ENV !== 'development'),
|
|
74
|
+
sameSite: env.IDP_COOKIE_SAME_SITE || 'lax',
|
|
75
|
+
domain: env.IDP_COOKIE_DOMAIN || undefined,
|
|
76
|
+
trustedOrigins: list(env.IDP_COOKIE_TRUSTED_ORIGINS),
|
|
77
|
+
refreshTokenInBody: (env.IDP_COOKIE_REFRESH_TOKEN_IN_BODY ?? '').trim().toLowerCase() === 'auto' ? 'auto' : bool('IDP_COOKIE_REFRESH_TOKEN_IN_BODY', 'auto'),
|
|
78
|
+
},
|
|
79
|
+
security: {
|
|
80
|
+
maxFailedLoginAttempts: int('IDP_MAX_FAILED_LOGIN_ATTEMPTS', 5, { min: 1 }),
|
|
81
|
+
accountLockDurationMs: int('IDP_ACCOUNT_LOCK_DURATION_MS', 30 * 60 * 1000, { min: 1000 }),
|
|
82
|
+
bcryptRounds: int('IDP_BCRYPT_ROUNDS', 12, { min: 10 }),
|
|
83
|
+
emailHashPepper: env.IDP_EMAIL_HASH_PEPPER,
|
|
84
|
+
tokenHashSecret: env.IDP_TOKEN_HASH_SECRET,
|
|
85
|
+
previousTokenHashSecrets: list(env.IDP_PREVIOUS_TOKEN_HASH_SECRETS),
|
|
86
|
+
},
|
|
87
|
+
mfa: {
|
|
88
|
+
issuerLabel: env.IDP_MFA_ISSUER_LABEL || 'App',
|
|
89
|
+
recoveryCodeCount: int('IDP_MFA_RECOVERY_CODE_COUNT', 10, { min: 1 }),
|
|
90
|
+
enabled: bool('IDP_MFA_ENABLED', true),
|
|
91
|
+
encryptionKey: env.IDP_MFA_ENCRYPTION_KEY || undefined,
|
|
92
|
+
previousEncryptionKeys: (env.IDP_MFA_PREVIOUS_ENCRYPTION_KEYS || '').split(',').map((k) => k.trim()).filter(Boolean),
|
|
93
|
+
requireEncrypted: bool('IDP_MFA_REQUIRE_ENCRYPTED', undefined),
|
|
94
|
+
allowPlaintext: bool('IDP_MFA_ALLOW_PLAINTEXT', false),
|
|
95
|
+
},
|
|
96
|
+
session: {
|
|
97
|
+
verifyOnEachRequest: bool('IDP_SESSION_VERIFY_ON_EACH_REQUEST', true),
|
|
98
|
+
},
|
|
99
|
+
oidc: {
|
|
100
|
+
endSessionConfirmationUrl: env.IDP_OIDC_END_SESSION_CONFIRMATION_URL || undefined,
|
|
101
|
+
},
|
|
102
|
+
clock: {
|
|
103
|
+
maxSkewSeconds: int('IDP_CLOCK_MAX_SKEW_SECONDS', 30, { min: 1 }),
|
|
104
|
+
warnSkewSeconds: int('IDP_CLOCK_WARN_SKEW_SECONDS', 2, { min: 0 }),
|
|
105
|
+
checkIntervalSeconds: int('IDP_CLOCK_CHECK_INTERVAL_SECONDS', 600, { min: 10 }),
|
|
106
|
+
},
|
|
107
|
+
oauthProviders: {
|
|
108
|
+
google: env.IDP_SSO_GOOGLE_CLIENT_ID ? { clientId: env.IDP_SSO_GOOGLE_CLIENT_ID, clientSecret: env.IDP_SSO_GOOGLE_CLIENT_SECRET } : undefined,
|
|
109
|
+
microsoft: env.IDP_SSO_MICROSOFT_CLIENT_ID ? { clientId: env.IDP_SSO_MICROSOFT_CLIENT_ID, clientSecret: env.IDP_SSO_MICROSOFT_CLIENT_SECRET, tenant: env.IDP_SSO_MICROSOFT_TENANT || 'common', trustEmail: bool('IDP_SSO_MICROSOFT_TRUST_EMAIL', false) } : undefined,
|
|
110
|
+
github: env.IDP_SSO_GITHUB_CLIENT_ID ? { clientId: env.IDP_SSO_GITHUB_CLIENT_ID, clientSecret: env.IDP_SSO_GITHUB_CLIENT_SECRET } : undefined,
|
|
111
|
+
apple: env.IDP_SSO_APPLE_CLIENT_ID ? { clientId: env.IDP_SSO_APPLE_CLIENT_ID, teamId: env.IDP_SSO_APPLE_TEAM_ID, keyId: env.IDP_SSO_APPLE_KEY_ID, privateKeyPem: env.IDP_SSO_APPLE_PRIVATE_KEY_B64 ? Buffer.from(env.IDP_SSO_APPLE_PRIVATE_KEY_B64, 'base64').toString('utf8') : undefined } : undefined,
|
|
112
|
+
linkedin: env.IDP_SSO_LINKEDIN_CLIENT_ID ? { clientId: env.IDP_SSO_LINKEDIN_CLIENT_ID, clientSecret: env.IDP_SSO_LINKEDIN_CLIENT_SECRET } : undefined,
|
|
113
|
+
},
|
|
114
|
+
sso: {
|
|
115
|
+
baseCallbackUrl: env.IDP_SSO_BASE_CALLBACK_URL || undefined,
|
|
116
|
+
allowedRedirectOrigins: list(env.IDP_SSO_ALLOWED_REDIRECT_ORIGINS),
|
|
117
|
+
},
|
|
118
|
+
serviceMesh: {
|
|
119
|
+
bootstrapSecret: env.IDP_S2S_BOOTSTRAP_SECRET || undefined,
|
|
120
|
+
// "billing=secret1,orders=secret2"
|
|
121
|
+
bootstrapSecrets: env.IDP_S2S_BOOTSTRAP_SECRETS
|
|
122
|
+
? Object.fromEntries(list(env.IDP_S2S_BOOTSTRAP_SECRETS).map((pair) => {
|
|
123
|
+
const i = pair.indexOf('=');
|
|
124
|
+
if (i < 1) throw new Error('IDP_S2S_BOOTSTRAP_SECRETS must be name=secret pairs, comma-separated');
|
|
125
|
+
return [pair.slice(0, i), pair.slice(i + 1)];
|
|
126
|
+
}))
|
|
127
|
+
: undefined,
|
|
128
|
+
tokenMode: env.IDP_S2S_TOKEN_MODE || 'token',
|
|
129
|
+
ownServiceName: env.IDP_S2S_OWN_SERVICE_NAME || undefined,
|
|
130
|
+
},
|
|
131
|
+
rateLimiting: {
|
|
132
|
+
enabled: bool('IDP_RATE_LIMIT_ENABLED', true),
|
|
133
|
+
adapter: env.IDP_RATE_LIMIT_ADAPTER || 'memory',
|
|
134
|
+
},
|
|
135
|
+
magicLink: {
|
|
136
|
+
allowSignupViaMagicLink: bool('IDP_MAGIC_LINK_ALLOW_SIGNUP', true),
|
|
137
|
+
},
|
|
138
|
+
// Only wired if IDP_WEBAUTHN_RP_ID is set — WebAuthn is fully opt-in
|
|
139
|
+
// and deployment-specific (rpID must be the frontend's registrable
|
|
140
|
+
// domain), so there's no sensible default to fall back to.
|
|
141
|
+
webauthn: env.IDP_WEBAUTHN_RP_ID
|
|
142
|
+
? { rpID: env.IDP_WEBAUTHN_RP_ID, rpName: env.IDP_WEBAUTHN_RP_NAME || 'App', origin: env.IDP_WEBAUTHN_ORIGIN }
|
|
143
|
+
: {},
|
|
144
|
+
// Only supports a single endpoint via env vars (the common case) —
|
|
145
|
+
// configure config.webhooks.endpoints directly for multiple.
|
|
146
|
+
webhooks: env.IDP_WEBHOOK_URL
|
|
147
|
+
? { endpoints: [{ url: env.IDP_WEBHOOK_URL, secret: env.IDP_WEBHOOK_SECRET }] }
|
|
148
|
+
: {},
|
|
149
|
+
};
|
|
150
|
+
}
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import { withDefaults } from './defaults.js';
|
|
2
|
+
import { setState } from './state.js';
|
|
3
|
+
import { createConsoleLogger } from './console-logger.js';
|
|
4
|
+
import { mergeHooks, setHookTimeout } from '../hooks/index.js';
|
|
5
|
+
import { createCacheAdapter } from '../cache/index.js';
|
|
6
|
+
import { createRateLimiter } from '../rate-limit/index.js';
|
|
7
|
+
import { WebhookDispatcher } from '../webhooks/dispatcher.js';
|
|
8
|
+
import { wrapHooksWithWebhooks } from '../webhooks/wrap-hooks.js';
|
|
9
|
+
import { buildKeyRegistry, assertCanSign } from '../signing/key-registry.js';
|
|
10
|
+
import { createPostgresStorage, resolvePostgresOptions } from '../storage/postgres/index.js';
|
|
11
|
+
import { makeHashEmail, normalizeEmail } from '../utils/email-hash.js';
|
|
12
|
+
import { createMfaSecretCipher, assertMfaSecretConfig } from '../mfa/secrets.js';
|
|
13
|
+
import { assertStorageContract } from '../storage/interfaces.js';
|
|
14
|
+
import { startClockSkewGuard } from '../security/clock-skew.js';
|
|
15
|
+
import { MemoryAttemptCounterRepository } from '../mfa/memory-attempt-counter.js';
|
|
16
|
+
import { prepareDummyHash } from '../utils/password.js';
|
|
17
|
+
import { isSecureUrl, isLoopbackHost } from '../utils/url.js';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Wires storage, cache, signing keys, hooks, and logger, and stores the
|
|
21
|
+
* result in this module's singleton state. Call once at startup, before
|
|
22
|
+
* mounting any handler/middleware this package exports.
|
|
23
|
+
*
|
|
24
|
+
* @param {import('../../types/index.d.ts').IdpConfig} config
|
|
25
|
+
* @returns {Promise<{ config: object, logger: object, storage: object, cache: object }>}
|
|
26
|
+
* A read-only-ish view of the wired state, for consumers who want direct
|
|
27
|
+
* access (e.g. to close the database pool in tests). Every handler
|
|
28
|
+
* export reads the same underlying state internally — you do not need to
|
|
29
|
+
* thread this return value through your routes.
|
|
30
|
+
*/
|
|
31
|
+
export async function initIdentityProvider(config) {
|
|
32
|
+
const resolved = withDefaults(config);
|
|
33
|
+
resolvePostgresOptions(resolved.postgres); // a bad database config fails before anything starts
|
|
34
|
+
|
|
35
|
+
assertSecurityConfig(resolved.security);
|
|
36
|
+
await prepareDummyHash(resolved.security.bcryptRounds);
|
|
37
|
+
assertRateLimitRules(resolved.rateLimiting);
|
|
38
|
+
|
|
39
|
+
const logger = config.logger || createConsoleLogger();
|
|
40
|
+
|
|
41
|
+
// MFA secret encryption is validated before anything connects, so a
|
|
42
|
+
// missing key fails the boot rather than the first enrolment.
|
|
43
|
+
const mfaCipher = createMfaSecretCipher(resolved.mfa);
|
|
44
|
+
// With a key, a plain-text secret (from <= 0.2.x, or written straight into the database) is refused
|
|
45
|
+
// unless the app explicitly opts back in — run migrateMfaSecrets() to encrypt old ones.
|
|
46
|
+
if (resolved.mfa.requireEncrypted === undefined) resolved.mfa.requireEncrypted = Boolean(mfaCipher);
|
|
47
|
+
assertMfaSecretConfig(resolved.mfa, mfaCipher, logger);
|
|
48
|
+
assertLockoutConfig('mfa.lockout', resolved.mfa.lockout);
|
|
49
|
+
assertLockoutConfig('security.verificationCodeLockout', resolved.security.verificationCodeLockout);
|
|
50
|
+
const totalCap = resolved.security.verificationCodeLockout.maxTotalFailedAttempts;
|
|
51
|
+
if (!Number.isInteger(totalCap) || totalCap < 1) throw new Error(`config.security.verificationCodeLockout.maxTotalFailedAttempts must be a positive integer (got ${totalCap})`);
|
|
52
|
+
assertLockoutConfig('security.passwordChangeLockout', resolved.security.passwordChangeLockout);
|
|
53
|
+
assertSsoConfig(resolved);
|
|
54
|
+
if (!Number.isInteger(resolved.hookTimeoutMs) || resolved.hookTimeoutMs < 1) throw new Error(`config.hookTimeoutMs must be a positive integer (got ${resolved.hookTimeoutMs})`);
|
|
55
|
+
setHookTimeout(resolved.hookTimeoutMs);
|
|
56
|
+
if (!['all', 'public'].includes(resolved.oauth2.requirePkce)) {
|
|
57
|
+
throw new Error("config.oauth2.requirePkce must be 'all' or 'public'");
|
|
58
|
+
}
|
|
59
|
+
assertCookieConfig(resolved.cookies);
|
|
60
|
+
assertIssuerAndTtls(resolved, logger);
|
|
61
|
+
assertOidcConfig(resolved);
|
|
62
|
+
assertClockConfig(resolved.clock);
|
|
63
|
+
assertServiceMeshSecrets(resolved.serviceMesh);
|
|
64
|
+
const grace = resolved.serviceMesh.rotationGraceSeconds;
|
|
65
|
+
if (!Number.isInteger(grace) || grace < 0) throw new Error(`config.serviceMesh.rotationGraceSeconds must be an integer >= 0 (got ${grace})`);
|
|
66
|
+
for (const [name, min] of [['recentAuthMaxAgeSeconds', 1], ['absoluteLifetimeSeconds', 1], ['refreshReuseGraceSeconds', 0]]) {
|
|
67
|
+
const value = resolved.session[name];
|
|
68
|
+
if (!Number.isInteger(value) || value < min) throw new Error(`config.session.${name} must be an integer >= ${min} (got ${value})`);
|
|
69
|
+
}
|
|
70
|
+
const webhookDispatcher = new WebhookDispatcher(resolved.webhooks, logger);
|
|
71
|
+
const hooks = wrapHooksWithWebhooks(mergeHooks(resolved.hooks), webhookDispatcher);
|
|
72
|
+
const cache = await createCacheAdapter(resolved.cache);
|
|
73
|
+
const rateLimiter = await createRateLimiter(resolved.rateLimiting, cache.redisClient);
|
|
74
|
+
const signingKeys = buildKeyRegistry(resolved.signingKeys.keys);
|
|
75
|
+
assertCanSign(signingKeys);
|
|
76
|
+
const hashEmail = makeHashEmail(resolved.security.emailHashPepper);
|
|
77
|
+
|
|
78
|
+
// The PostgreSQL store: connects, checks the server version and the schema (config.postgres.migrations).
|
|
79
|
+
const storage = await createPostgresStorage(resolved.postgres, { hashEmail, normalizeEmail }, { logger });
|
|
80
|
+
|
|
81
|
+
let stopClockGuard;
|
|
82
|
+
try {
|
|
83
|
+
assertStorageContract(storage);
|
|
84
|
+
stopClockGuard = await startClockSkewGuard(storage, resolved.clock, logger);
|
|
85
|
+
} catch (err) {
|
|
86
|
+
await storage?.close?.().catch(() => {});
|
|
87
|
+
throw err;
|
|
88
|
+
}
|
|
89
|
+
// Closing the storage also ends the periodic clock check.
|
|
90
|
+
const closeStorage = storage.close.bind(storage);
|
|
91
|
+
storage.close = async () => {
|
|
92
|
+
stopClockGuard();
|
|
93
|
+
return closeStorage();
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
// Adapters that predate 0.3.0 (or haven't caught up yet) keep working:
|
|
97
|
+
// the MFA lockout falls back to an in-process counter, and per-request
|
|
98
|
+
// session verification falls back to the per-process revocation cache.
|
|
99
|
+
// Both are weaker on a multi-instance deployment, so say so loudly.
|
|
100
|
+
let attemptCounters = storage.attemptCounterRepository;
|
|
101
|
+
if (!attemptCounters) {
|
|
102
|
+
attemptCounters = new MemoryAttemptCounterRepository();
|
|
103
|
+
logger.warn({}, '@okeav/idp-pg: storage has no attemptCounterRepository — the per-account MFA lockout is counted in-process only (not shared across instances). Upgrade the adapter.');
|
|
104
|
+
}
|
|
105
|
+
const missingAtomic = ['claimTotpStep', 'consumeRecoveryCode'].filter((m) => typeof storage.userRepository?.[m] !== 'function');
|
|
106
|
+
if (missingAtomic.length > 0) {
|
|
107
|
+
logger.warn({}, `@okeav/idp-pg: storage's userRepository has no ${missingAtomic.join('/')}() — TOTP replay and recovery-code reuse are checked with a non-atomic read-then-write, which concurrent requests can race. Upgrade the adapter.`);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const state = { config: resolved, logger, hooks, cache, rateLimiter, webhookDispatcher, signingKeys, storage, hashEmail, normalizeEmail, mfaCipher, attemptCounters };
|
|
111
|
+
setState(state);
|
|
112
|
+
|
|
113
|
+
logger.info({ issuer: resolved.issuer }, '@okeav/idp-pg initialized');
|
|
114
|
+
|
|
115
|
+
return state;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* With any SSO provider configured, the redirect allowlist and the absolute callback base URL are
|
|
120
|
+
* required: SSO without an allowlist is an open redirect at the end of a real provider login, and
|
|
121
|
+
* without baseCallbackUrl the provider is handed a relative redirect_uri it will reject.
|
|
122
|
+
*/
|
|
123
|
+
function assertSsoConfig(resolved) {
|
|
124
|
+
const configured = Object.entries(resolved.oauthProviders || {}).filter(([, v]) => v?.clientId).map(([k]) => k);
|
|
125
|
+
if (configured.length === 0) return;
|
|
126
|
+
const origins = resolved.sso?.allowedRedirectOrigins;
|
|
127
|
+
if (!Array.isArray(origins) || origins.length === 0) {
|
|
128
|
+
throw new Error(`config.sso.allowedRedirectOrigins is required when SSO providers are configured (${configured.join(', ')}) — list the origins SSO may redirect back to`);
|
|
129
|
+
}
|
|
130
|
+
for (const origin of origins) {
|
|
131
|
+
let url;
|
|
132
|
+
try { url = new URL(origin); } catch { url = null; }
|
|
133
|
+
if (!url || url.origin !== origin) throw new Error(`config.sso.allowedRedirectOrigins: "${origin}" is not an origin (scheme://host[:port], no path)`);
|
|
134
|
+
}
|
|
135
|
+
let base;
|
|
136
|
+
try { base = new URL(resolved.sso?.baseCallbackUrl); } catch { base = null; }
|
|
137
|
+
if (!base || !['https:', 'http:'].includes(base.protocol)) {
|
|
138
|
+
throw new Error('config.sso.baseCallbackUrl must be an absolute URL when SSO providers are configured');
|
|
139
|
+
}
|
|
140
|
+
if (!isSecureUrl(resolved.sso.baseCallbackUrl)) {
|
|
141
|
+
throw new Error('config.sso.baseCallbackUrl must be https (http only for localhost) — provider codes are returned to it');
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const MIN_SECRET_LENGTH = 32;
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The secrets behind every token hash and the email blind index must be real secrets (a short one
|
|
149
|
+
* can be brute-forced offline from a database dump), and the password-hash cost and lockout numbers
|
|
150
|
+
* must be numbers — a NaN lockout threshold (e.g. from a mistyped env var) silently disables lockout.
|
|
151
|
+
*/
|
|
152
|
+
function assertSecurityConfig(security) {
|
|
153
|
+
for (const name of ['emailHashPepper', 'tokenHashSecret']) {
|
|
154
|
+
const value = security[name];
|
|
155
|
+
if (!value) throw new Error(`config.security.${name} is required`);
|
|
156
|
+
if (typeof value !== 'string' || value.length < MIN_SECRET_LENGTH) {
|
|
157
|
+
throw new Error(`config.security.${name} must be a random string of at least ${MIN_SECRET_LENGTH} characters`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const previous = security.previousTokenHashSecrets ?? [];
|
|
161
|
+
if (!Array.isArray(previous)) throw new Error('config.security.previousTokenHashSecrets must be an array of strings');
|
|
162
|
+
for (const [i, value] of previous.entries()) {
|
|
163
|
+
if (typeof value !== 'string' || value.length < MIN_SECRET_LENGTH) {
|
|
164
|
+
throw new Error(`config.security.previousTokenHashSecrets[${i}] must be a string of at least ${MIN_SECRET_LENGTH} characters`);
|
|
165
|
+
}
|
|
166
|
+
if (value === security.tokenHashSecret) throw new Error(`config.security.previousTokenHashSecrets[${i}] is the current tokenHashSecret`);
|
|
167
|
+
if (value === security.emailHashPepper) throw new Error(`config.security.previousTokenHashSecrets[${i}] must not be the emailHashPepper`);
|
|
168
|
+
}
|
|
169
|
+
if (new Set(previous).size !== previous.length) throw new Error('config.security.previousTokenHashSecrets has duplicates');
|
|
170
|
+
const minRounds = security.allowWeakBcryptRounds === true ? 4 : 10;
|
|
171
|
+
if (!Number.isInteger(security.bcryptRounds) || security.bcryptRounds < minRounds || security.bcryptRounds > 15) {
|
|
172
|
+
throw new Error(`config.security.bcryptRounds must be an integer from ${minRounds} to 15 (got ${security.bcryptRounds})`);
|
|
173
|
+
}
|
|
174
|
+
if (!Number.isInteger(security.maxFailedLoginAttempts) || security.maxFailedLoginAttempts < 1) {
|
|
175
|
+
throw new Error(`config.security.maxFailedLoginAttempts must be a positive integer (got ${security.maxFailedLoginAttempts})`);
|
|
176
|
+
}
|
|
177
|
+
if (!Number.isInteger(security.accountLockDurationMs) || security.accountLockDurationMs < 1000) {
|
|
178
|
+
throw new Error(`config.security.accountLockDurationMs must be an integer of at least 1000 (got ${security.accountLockDurationMs})`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Every rate-limit rule needs positive integers — a fractional window can leave Redis keys without a TTL. */
|
|
183
|
+
function assertRateLimitRules(rateLimiting) {
|
|
184
|
+
for (const [name, rule] of Object.entries(rateLimiting)) {
|
|
185
|
+
if (!rule || typeof rule !== 'object' || Array.isArray(rule) || !('max' in rule || 'windowSeconds' in rule)) continue;
|
|
186
|
+
if (!Number.isInteger(rule.max) || rule.max < 1 || !Number.isInteger(rule.windowSeconds) || rule.windowSeconds < 1) {
|
|
187
|
+
throw new Error(`config.rateLimiting.${name} needs positive integer max and windowSeconds (got ${JSON.stringify(rule)})`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Service-mesh secrets gate who may register a service key (and so mint tokens as that service), or —
|
|
194
|
+
* in tokenMode 'secret'/'both' — who may call as a service: as strong as the token secrets.
|
|
195
|
+
*/
|
|
196
|
+
function assertServiceMeshSecrets(mesh = {}) {
|
|
197
|
+
const MIN = 32;
|
|
198
|
+
const weak = (v) => typeof v !== 'string' || v.length < MIN;
|
|
199
|
+
for (const key of ['bootstrapSecret', 'sharedSecret']) {
|
|
200
|
+
if (mesh[key] !== undefined && weak(mesh[key])) throw new Error(`config.serviceMesh.${key} must be at least ${MIN} characters`);
|
|
201
|
+
}
|
|
202
|
+
for (const [name, secret] of Object.entries(mesh.bootstrapSecrets ?? {})) {
|
|
203
|
+
if (weak(secret)) throw new Error(`config.serviceMesh.bootstrapSecrets.${name} must be at least ${MIN} characters`);
|
|
204
|
+
if (secret === mesh.bootstrapSecret) throw new Error(`config.serviceMesh.bootstrapSecrets.${name} must differ from the shared bootstrapSecret`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The issuer is every token's `iss` and the default trusted origin for the CSRF check (a non-URL issuer
|
|
211
|
+
* silently contributed none). Lifetimes must be positive whole seconds, and the two keyed-hash secrets
|
|
212
|
+
* distinct. In cache-only revocation mode (`session.verifyOnEachRequest: false`) a revocation marker
|
|
213
|
+
* must outlive the access token it revokes, or the token comes back to life.
|
|
214
|
+
*/
|
|
215
|
+
function assertIssuerAndTtls(resolved, logger) {
|
|
216
|
+
if (!isSecureUrl(resolved.issuer)) throw new Error(`config.issuer must be an https URL (http only for localhost) — got ${JSON.stringify(resolved.issuer)}`);
|
|
217
|
+
for (const [name, value] of Object.entries(resolved.ttls ?? {})) {
|
|
218
|
+
if (!Number.isInteger(value) || value < 1) throw new Error(`config.ttls.${name} must be a positive integer of seconds (got ${value})`);
|
|
219
|
+
}
|
|
220
|
+
const { tokenHashSecret, emailHashPepper } = resolved.security;
|
|
221
|
+
if (tokenHashSecret && tokenHashSecret === emailHashPepper) throw new Error('config.security.tokenHashSecret and emailHashPepper must be different secrets');
|
|
222
|
+
if (resolved.session?.verifyOnEachRequest === false && resolved.ttls.revocationCache < resolved.ttls.accessToken) {
|
|
223
|
+
throw new Error('config.ttls.revocationCache must be at least ttls.accessToken when session.verifyOnEachRequest is false (revocation would expire before the token)');
|
|
224
|
+
}
|
|
225
|
+
for (const [what, cfg] of [['cache', resolved.cache], ['rateLimiting', resolved.rateLimiting]]) {
|
|
226
|
+
const redis = cfg?.redis;
|
|
227
|
+
if (cfg?.adapter === 'redis' && redis?.host && !isLoopbackHost(redis.host) && !redis.tls) {
|
|
228
|
+
logger?.warn?.({ host: redis.host }, `config.${what}: Redis at a remote host without TLS — revocation markers, challenges and limits travel in clear`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** A typo in sameSite used to surface as a 500 on every login; SameSite=None without Secure is dropped by browsers. */
|
|
234
|
+
function assertCookieConfig(cookies = {}) {
|
|
235
|
+
// Normalised in place: 'Lax' (e.g. from IDP_COOKIE_SAME_SITE) means 'lax'; an origin's host is case-insensitive.
|
|
236
|
+
if (typeof cookies.sameSite === 'string') cookies.sameSite = cookies.sameSite.toLowerCase();
|
|
237
|
+
if (Array.isArray(cookies.trustedOrigins)) cookies.trustedOrigins = cookies.trustedOrigins.map((o) => (typeof o === 'string' && safeOrigin(o) && safeOrigin(o).toLowerCase() === o.toLowerCase() ? safeOrigin(o) : o));
|
|
238
|
+
if (cookies.sameSite !== undefined && !['lax', 'strict', 'none'].includes(cookies.sameSite)) {
|
|
239
|
+
throw new Error(`config.cookies.sameSite must be 'lax', 'strict' or 'none' (got ${JSON.stringify(cookies.sameSite)})`);
|
|
240
|
+
}
|
|
241
|
+
if (cookies.refreshTokenInBody !== undefined && ![true, false, 'auto'].includes(cookies.refreshTokenInBody)) {
|
|
242
|
+
throw new Error(`config.cookies.refreshTokenInBody must be true, false or 'auto' (got ${JSON.stringify(cookies.refreshTokenInBody)})`);
|
|
243
|
+
}
|
|
244
|
+
if (cookies.sessionPath !== undefined && (typeof cookies.sessionPath !== 'string' || !/^\/[\x21-\x3a\x3c-\x7e]*$/.test(cookies.sessionPath))) {
|
|
245
|
+
throw new Error('config.cookies.sessionPath must be an absolute path (e.g. /auth/session) — the path the session routes are served under');
|
|
246
|
+
}
|
|
247
|
+
if (cookies.sameSite === 'none' && cookies.secure === false) throw new Error("config.cookies.sameSite 'none' requires secure cookies (browsers drop SameSite=None without Secure)");
|
|
248
|
+
if (cookies.trustedOrigins !== undefined && (!Array.isArray(cookies.trustedOrigins) || cookies.trustedOrigins.some((o) => typeof o !== 'string' || o !== safeOrigin(o)))) {
|
|
249
|
+
throw new Error('config.cookies.trustedOrigins must be an array of exact origins, e.g. https://app.example.com (no path, no trailing slash)');
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* The end-session confirmation page POSTs back to /session/end, which only accepts that from a
|
|
255
|
+
* trusted origin — so the page must be on one (and https, like every other URL the IdP sends users to).
|
|
256
|
+
*/
|
|
257
|
+
function assertClockConfig(clock) {
|
|
258
|
+
for (const [name, min] of [['maxSkewSeconds', 1], ['warnSkewSeconds', 0], ['checkIntervalSeconds', 10]]) {
|
|
259
|
+
if (!Number.isInteger(clock[name]) || clock[name] < min) throw new Error(`config.clock.${name} must be an integer >= ${min} (got ${clock[name]})`);
|
|
260
|
+
}
|
|
261
|
+
if (clock.warnSkewSeconds > clock.maxSkewSeconds) throw new Error('config.clock.warnSkewSeconds must not exceed maxSkewSeconds');
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function assertOidcConfig(resolved) {
|
|
265
|
+
const url = resolved.oidc?.endSessionConfirmationUrl;
|
|
266
|
+
if (url === undefined) return;
|
|
267
|
+
if (typeof url !== 'string' || !isSecureUrl(url)) throw new Error('config.oidc.endSessionConfirmationUrl must be an https URL (http only for localhost)');
|
|
268
|
+
const trusted = new Set([safeOrigin(resolved.issuer), ...(resolved.cookies?.trustedOrigins ?? [])]);
|
|
269
|
+
if (!trusted.has(safeOrigin(url))) {
|
|
270
|
+
throw new Error('config.oidc.endSessionConfirmationUrl must be on the issuer\'s origin or one of cookies.trustedOrigins (its confirmation POST is refused from anywhere else)');
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function safeOrigin(value) {
|
|
275
|
+
try {
|
|
276
|
+
return new URL(value).origin;
|
|
277
|
+
} catch {
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function assertLockoutConfig(path, { maxFailedAttempts, windowSeconds, lockSeconds }) {
|
|
283
|
+
for (const [name, value] of Object.entries({ maxFailedAttempts, windowSeconds, lockSeconds })) {
|
|
284
|
+
if (!Number.isInteger(value) || value < 1) throw new Error(`config.${path}.${name} must be a positive integer (got ${value})`);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Module-level singleton holding everything `initIdentityProvider()` wires up
|
|
2
|
+
// (storage, cache, signing keys, hooks, logger, resolved config). Every
|
|
3
|
+
// handler/middleware reads it via `getState()` at call time — this is what
|
|
4
|
+
// makes flat named exports (`import { loginHandler } from '...'`) work
|
|
5
|
+
// without threading config through every import.
|
|
6
|
+
let state = null;
|
|
7
|
+
|
|
8
|
+
export function setState(s) {
|
|
9
|
+
state = s;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function getState() {
|
|
13
|
+
if (!state) {
|
|
14
|
+
throw new Error('initIdentityProvider(config) must be called once before using any @okeav/idp-pg export');
|
|
15
|
+
}
|
|
16
|
+
return state;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Test/teardown helper — not part of the public surface. */
|
|
20
|
+
export function resetState() {
|
|
21
|
+
state = null;
|
|
22
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Central catalogue of `IdpError.code` values this package throws.
|
|
2
|
+
// Not exhaustive-enforced — a stable reference for consumers writing their
|
|
3
|
+
// error-handling middleware.
|
|
4
|
+
export const ERROR_CODES = Object.freeze({
|
|
5
|
+
// Generic
|
|
6
|
+
INTERNAL_ERROR: 'INTERNAL_ERROR',
|
|
7
|
+
INVALID_REQUEST: 'INVALID_REQUEST',
|
|
8
|
+
MISSING_REQUIRED_FIELDS: 'MISSING_REQUIRED_FIELDS',
|
|
9
|
+
VALIDATION_ERROR: 'VALIDATION_ERROR',
|
|
10
|
+
SERVICE_UNAVAILABLE: 'SERVICE_UNAVAILABLE',
|
|
11
|
+
NOT_FOUND: 'NOT_FOUND',
|
|
12
|
+
RATE_LIMIT_EXCEEDED: 'RATE_LIMIT_EXCEEDED',
|
|
13
|
+
RATE_LIMITER_UNAVAILABLE: 'RATE_LIMITER_UNAVAILABLE',
|
|
14
|
+
FEATURE_DISABLED: 'FEATURE_DISABLED',
|
|
15
|
+
CSRF_ORIGIN_REJECTED: 'CSRF_ORIGIN_REJECTED',
|
|
16
|
+
PAYLOAD_TOO_LARGE: 'PAYLOAD_TOO_LARGE',
|
|
17
|
+
COOKIE_CONFLICT: 'COOKIE_CONFLICT',
|
|
18
|
+
REGISTRATION_PASSWORD_REQUIRED: 'REGISTRATION_PASSWORD_REQUIRED',
|
|
19
|
+
PASSWORD_CHANGE_LOCKED: 'PASSWORD_CHANGE_LOCKED',
|
|
20
|
+
SERVICE_KEY_REVOKED: 'SERVICE_KEY_REVOKED',
|
|
21
|
+
|
|
22
|
+
// AuthN
|
|
23
|
+
AUTH_REQUIRED: 'AUTH_REQUIRED',
|
|
24
|
+
UNAUTHENTICATED: 'UNAUTHENTICATED',
|
|
25
|
+
FORBIDDEN: 'FORBIDDEN',
|
|
26
|
+
INVALID_TOKEN: 'INVALID_TOKEN',
|
|
27
|
+
TOKEN_EXPIRED: 'TOKEN_EXPIRED',
|
|
28
|
+
TOKEN_REVOKED: 'TOKEN_REVOKED',
|
|
29
|
+
REAUTHENTICATION_REQUIRED: 'REAUTHENTICATION_REQUIRED',
|
|
30
|
+
CACHE_UNAVAILABLE: 'CACHE_UNAVAILABLE',
|
|
31
|
+
SESSION_STORE_UNAVAILABLE: 'SESSION_STORE_UNAVAILABLE',
|
|
32
|
+
|
|
33
|
+
// Credentials / account lifecycle
|
|
34
|
+
INVALID_CREDENTIALS: 'INVALID_CREDENTIALS',
|
|
35
|
+
EMAIL_AND_PASSWORD_REQUIRED: 'EMAIL_AND_PASSWORD_REQUIRED',
|
|
36
|
+
EMAIL_REQUIRED: 'EMAIL_REQUIRED',
|
|
37
|
+
USER_NOT_FOUND: 'USER_NOT_FOUND',
|
|
38
|
+
USER_ALREADY_EXISTS: 'USER_ALREADY_EXISTS',
|
|
39
|
+
USER_NOT_ACTIVE: 'USER_NOT_ACTIVE',
|
|
40
|
+
ACCOUNT_LOCKED: 'ACCOUNT_LOCKED',
|
|
41
|
+
ACCOUNT_SUSPENDED: 'ACCOUNT_SUSPENDED',
|
|
42
|
+
PENDING_VERIFICATION: 'PENDING_VERIFICATION',
|
|
43
|
+
CANNOT_DELETE_USER: 'CANNOT_DELETE_USER',
|
|
44
|
+
EMAIL_ALREADY_VERIFIED: 'EMAIL_ALREADY_VERIFIED',
|
|
45
|
+
INVALID_OR_EXPIRED_TOKEN: 'INVALID_OR_EXPIRED_TOKEN',
|
|
46
|
+
VERIFICATION_LOCKED: 'VERIFICATION_LOCKED',
|
|
47
|
+
CURRENT_PASSWORD_INCORRECT: 'CURRENT_PASSWORD_INCORRECT',
|
|
48
|
+
|
|
49
|
+
// Refresh / session
|
|
50
|
+
REFRESH_TOKEN_REQUIRED: 'REFRESH_TOKEN_REQUIRED',
|
|
51
|
+
INVALID_REFRESH_TOKEN: 'INVALID_REFRESH_TOKEN',
|
|
52
|
+
REFRESH_TOKEN_NOT_FOUND: 'REFRESH_TOKEN_NOT_FOUND',
|
|
53
|
+
|
|
54
|
+
// MFA
|
|
55
|
+
MFA_ALREADY_ENABLED: 'MFA_ALREADY_ENABLED',
|
|
56
|
+
MFA_NOT_ENABLED: 'MFA_NOT_ENABLED',
|
|
57
|
+
MFA_SETUP_REQUIRED: 'MFA_SETUP_REQUIRED',
|
|
58
|
+
INVALID_MFA_CODE: 'INVALID_MFA_CODE',
|
|
59
|
+
INVALID_MFA_CHALLENGE_TOKEN: 'INVALID_MFA_CHALLENGE_TOKEN',
|
|
60
|
+
MFA_LOCKED: 'MFA_LOCKED',
|
|
61
|
+
MFA_ENCRYPTION_NOT_CONFIGURED: 'MFA_ENCRYPTION_NOT_CONFIGURED',
|
|
62
|
+
MFA_SECRET_NOT_ENCRYPTED: 'MFA_SECRET_NOT_ENCRYPTED',
|
|
63
|
+
MFA_SECRET_UNREADABLE: 'MFA_SECRET_UNREADABLE',
|
|
64
|
+
|
|
65
|
+
// OAuth2 / OIDC / JWKS
|
|
66
|
+
UNKNOWN_KID: 'UNKNOWN_KID',
|
|
67
|
+
KEY_NOT_ALLOWED: 'KEY_NOT_ALLOWED',
|
|
68
|
+
INVALID_REDIRECT_URI: 'INVALID_REDIRECT_URI',
|
|
69
|
+
INVALID_CLIENT: 'INVALID_CLIENT',
|
|
70
|
+
INVALID_GRANT: 'INVALID_GRANT',
|
|
71
|
+
INVALID_SCOPE: 'INVALID_SCOPE',
|
|
72
|
+
UNAUTHORIZED_CLIENT: 'UNAUTHORIZED_CLIENT',
|
|
73
|
+
UNSUPPORTED_GRANT_TYPE: 'UNSUPPORTED_GRANT_TYPE',
|
|
74
|
+
INVALID_CONSENT_CHALLENGE: 'INVALID_CONSENT_CHALLENGE',
|
|
75
|
+
|
|
76
|
+
// SSO
|
|
77
|
+
SSO_PROVIDER_ERROR: 'SSO_PROVIDER_ERROR',
|
|
78
|
+
INVALID_SSO_PROVIDER: 'INVALID_SSO_PROVIDER',
|
|
79
|
+
SSO_PROVIDER_NOT_CONFIGURED: 'SSO_PROVIDER_NOT_CONFIGURED',
|
|
80
|
+
INVALID_SSO_STATE: 'INVALID_SSO_STATE',
|
|
81
|
+
|
|
82
|
+
// OAuth clients / tenants
|
|
83
|
+
OAUTH_CLIENT_EXISTS: 'OAUTH_CLIENT_EXISTS',
|
|
84
|
+
OAUTH_CLIENT_NOT_FOUND: 'OAUTH_CLIENT_NOT_FOUND',
|
|
85
|
+
|
|
86
|
+
// Service mesh
|
|
87
|
+
SERVICE_TOKEN_INVALID: 'SERVICE_TOKEN_INVALID',
|
|
88
|
+
SERVICE_AUTH_FAILED: 'SERVICE_AUTH_FAILED',
|
|
89
|
+
SERVICE_NOT_CONFIGURED: 'SERVICE_NOT_CONFIGURED',
|
|
90
|
+
SERVICE_NAME_TAKEN: 'SERVICE_NAME_TAKEN',
|
|
91
|
+
|
|
92
|
+
// WebAuthn / passkeys
|
|
93
|
+
WEBAUTHN_NOT_CONFIGURED: 'WEBAUTHN_NOT_CONFIGURED',
|
|
94
|
+
WEBAUTHN_CHALLENGE_EXPIRED: 'WEBAUTHN_CHALLENGE_EXPIRED',
|
|
95
|
+
WEBAUTHN_VERIFICATION_FAILED: 'WEBAUTHN_VERIFICATION_FAILED',
|
|
96
|
+
CREDENTIAL_NOT_FOUND: 'CREDENTIAL_NOT_FOUND',
|
|
97
|
+
});
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { getState } from '../config/state.js';
|
|
2
|
+
/**
|
|
3
|
+
* The package's only error type. Handlers throw this (or let it propagate
|
|
4
|
+
* from `next(err)` in middleware) and never shape an HTTP response body
|
|
5
|
+
* themselves — the consumer's own Express error-handling middleware maps
|
|
6
|
+
* `{ code, httpStatus, message }` to whatever envelope their API uses (or
|
|
7
|
+
* mounts `idpErrorHandler()`, which does it safely).
|
|
8
|
+
*
|
|
9
|
+
* `status` / `statusCode` mirror `httpStatus` so Express's default error
|
|
10
|
+
* handler (and other frameworks' conventions) answer with the right status
|
|
11
|
+
* instead of turning every 401/429 into a 500.
|
|
12
|
+
*/
|
|
13
|
+
export class IdpError extends Error {
|
|
14
|
+
constructor({ code, httpStatus = 500, message, cause } = {}) {
|
|
15
|
+
super(message || code || 'IdpError');
|
|
16
|
+
this.name = 'IdpError';
|
|
17
|
+
this.code = code || 'INTERNAL_ERROR';
|
|
18
|
+
this.httpStatus = httpStatus;
|
|
19
|
+
this.status = httpStatus;
|
|
20
|
+
this.statusCode = httpStatus;
|
|
21
|
+
// Our messages are written for clients; only show them for client errors.
|
|
22
|
+
this.expose = httpStatus < 500;
|
|
23
|
+
if (cause !== undefined) this.cause = cause;
|
|
24
|
+
Error.captureStackTrace?.(this, IdpError);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function isIdpError(err) {
|
|
29
|
+
return err instanceof IdpError;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* An Express error handler that is safe to expose to the internet: mount it after the router.
|
|
34
|
+
*
|
|
35
|
+
* - An `IdpError` below 500 answers `{ error: code, message }`.
|
|
36
|
+
* - Body-parser errors (malformed JSON, payload too large) answer 400/413 with a fixed message —
|
|
37
|
+
* never the parser's text, which echoes the request body.
|
|
38
|
+
* - Anything else — an IdpError of 500+, a database error, a bug — answers 500
|
|
39
|
+
* `{ error: 'INTERNAL_ERROR' }` with no message, stack or driver detail (those name collections,
|
|
40
|
+
* indexes and values), and is logged.
|
|
41
|
+
*
|
|
42
|
+
* @param {{ logger?: { error?: Function } }} [opts]
|
|
43
|
+
*/
|
|
44
|
+
/**
|
|
45
|
+
* `logger`: where unexpected (5xx) errors are logged — by default the logger given to
|
|
46
|
+
* initIdentityProvider, so they are never silently dropped.
|
|
47
|
+
*/
|
|
48
|
+
export function idpErrorHandler({ logger } = {}) {
|
|
49
|
+
// eslint-disable-next-line no-unused-vars
|
|
50
|
+
return function (err, req, res, _next) {
|
|
51
|
+
if (res.headersSent) return res.end();
|
|
52
|
+
if (isIdpError(err) && err.httpStatus < 500) {
|
|
53
|
+
return res.status(err.httpStatus).json({ error: err.code, message: err.message });
|
|
54
|
+
}
|
|
55
|
+
if (err?.type === 'entity.too.large' || err?.status === 413) {
|
|
56
|
+
return res.status(413).json({ error: 'PAYLOAD_TOO_LARGE', message: 'Request body is too large' });
|
|
57
|
+
}
|
|
58
|
+
if (err?.type === 'entity.parse.failed' || (err instanceof SyntaxError && err?.status === 400)) {
|
|
59
|
+
return res.status(400).json({ error: 'INVALID_REQUEST', message: 'Malformed request body' });
|
|
60
|
+
}
|
|
61
|
+
// The path only — a query string can carry tokens (end-session's id_token_hint, an SSO code).
|
|
62
|
+
(logger ?? stateLogger())?.error?.({ err, path: req?.path }, 'Unhandled error');
|
|
63
|
+
const status = isIdpError(err) ? err.httpStatus : 500;
|
|
64
|
+
res.status(status).json({ error: isIdpError(err) ? err.code : 'INTERNAL_ERROR' });
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The configured logger, if the IdP is initialized (the error handler may run before init). */
|
|
69
|
+
function stateLogger() {
|
|
70
|
+
try {
|
|
71
|
+
return getState().logger;
|
|
72
|
+
} catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
}
|