@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,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef {Object} CacheAdapter
|
|
3
|
+
* @property {(key: string) => Promise<any|null>} get
|
|
4
|
+
* @property {(key: string, value: any, ttlSeconds?: number) => Promise<void>} set
|
|
5
|
+
* @property {(key: string) => Promise<void>} del
|
|
6
|
+
* @property {(key: string, ttlSeconds: number) => Promise<void>} expire
|
|
7
|
+
* @property {(key: string) => Promise<any|null>} take - ATOMIC get-and-delete: of two concurrent
|
|
8
|
+
* callers for one key, exactly one gets the value. The basis of every single-use value (WebAuthn
|
|
9
|
+
* challenges, SSO state).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Base class purely for documentation / instanceof checks — adapters are not
|
|
14
|
+
* required to extend it, only to satisfy the shape above.
|
|
15
|
+
*/
|
|
16
|
+
export class BaseCacheAdapter {
|
|
17
|
+
async get(_key) { throw new Error('CacheAdapter.get() not implemented'); }
|
|
18
|
+
async set(_key, _value, _ttlSeconds) { throw new Error('CacheAdapter.set() not implemented'); }
|
|
19
|
+
async del(_key) { throw new Error('CacheAdapter.del() not implemented'); }
|
|
20
|
+
async expire(_key, _ttlSeconds) { throw new Error('CacheAdapter.expire() not implemented'); }
|
|
21
|
+
async take(_key) { throw new Error('CacheAdapter.take() not implemented'); }
|
|
22
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { MemoryCacheAdapter } from './memory.adapter.js';
|
|
2
|
+
import { createRedisCacheAdapter } from './redis.adapter.js';
|
|
3
|
+
|
|
4
|
+
export { BaseCacheAdapter } from './cache-adapter.js';
|
|
5
|
+
export { MemoryCacheAdapter } from './memory.adapter.js';
|
|
6
|
+
export { RedisCacheAdapter, createRedisCacheAdapter } from './redis.adapter.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @param {object} [config]
|
|
10
|
+
* @param {'memory'|'redis'} [config.adapter='memory']
|
|
11
|
+
* @param {string} [config.keyPrefix='idp:']
|
|
12
|
+
* @param {object} [config.redis] - { host, port, password, db, keepAliveMs } — required if adapter === 'redis'
|
|
13
|
+
* @returns {Promise<import('./cache-adapter.js').CacheAdapter>}
|
|
14
|
+
*/
|
|
15
|
+
export async function createCacheAdapter(config = {}) {
|
|
16
|
+
const adapter = config.adapter || 'memory';
|
|
17
|
+
const prefix = config.keyPrefix ?? 'idp:';
|
|
18
|
+
|
|
19
|
+
let raw;
|
|
20
|
+
if (adapter === 'redis') {
|
|
21
|
+
raw = await createRedisCacheAdapter(config.redis || {});
|
|
22
|
+
} else if (adapter === 'memory') {
|
|
23
|
+
raw = new MemoryCacheAdapter();
|
|
24
|
+
} else {
|
|
25
|
+
throw new Error(`Unknown cache adapter "${adapter}" — expected "memory" or "redis"`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return prefixed(raw, prefix);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function prefixed(adapter, prefix) {
|
|
32
|
+
const k = (key) => `${prefix}${key}`;
|
|
33
|
+
return {
|
|
34
|
+
get: (key) => adapter.get(k(key)),
|
|
35
|
+
set: (key, value, ttlSeconds) => adapter.set(k(key), value, ttlSeconds),
|
|
36
|
+
del: (key) => adapter.del(k(key)),
|
|
37
|
+
expire: (key, ttlSeconds) => adapter.expire(k(key), ttlSeconds),
|
|
38
|
+
take: (key) => adapter.take(k(key)),
|
|
39
|
+
close: () => adapter.close?.(),
|
|
40
|
+
// Present only when the underlying adapter is Redis-backed — lets the
|
|
41
|
+
// rate limiter (and anything else that wants Redis) reuse this
|
|
42
|
+
// connection instead of opening a second one.
|
|
43
|
+
redisClient: adapter.client ?? null,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Fail-closed revocation lookup. A cache MISS (key not present) legitimately
|
|
49
|
+
* means "not revoked" and returns false. A cache ERROR (adapter threw —
|
|
50
|
+
* connection down, timeout, etc.) means we cannot determine revocation
|
|
51
|
+
* status, and this throws rather than returning false — the caller must
|
|
52
|
+
* reject the token instead of silently trusting it. This is a security
|
|
53
|
+
* invariant, independent of which adapter is configured.
|
|
54
|
+
*/
|
|
55
|
+
export async function isRevoked(cache, key) {
|
|
56
|
+
const { IdpError } = await import('../errors/idp-error.js');
|
|
57
|
+
try {
|
|
58
|
+
const value = await cache.get(key);
|
|
59
|
+
return !!value;
|
|
60
|
+
} catch (cause) {
|
|
61
|
+
throw new IdpError({
|
|
62
|
+
code: 'CACHE_UNAVAILABLE',
|
|
63
|
+
httpStatus: 503,
|
|
64
|
+
message: 'Unable to verify token revocation status',
|
|
65
|
+
cause,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { BaseCacheAdapter } from './cache-adapter.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Zero-config default cache adapter. Single-process, in-memory only — state
|
|
5
|
+
* is lost on restart and NOT shared across instances.
|
|
6
|
+
*
|
|
7
|
+
* This is fine for local development or a single-instance deployment. Any
|
|
8
|
+
* horizontally-scaled deployment (more than one process/pod) MUST configure
|
|
9
|
+
* the Redis adapter instead, or two invariants silently break:
|
|
10
|
+
* 1. Revocation checks (logout, refresh rotation) only apply on the
|
|
11
|
+
* instance that handled the revoking request.
|
|
12
|
+
* 2. SSO CSRF-state and the replay-nonce cache aren't shared, so a
|
|
13
|
+
* callback landing on a different instance than the one that issued
|
|
14
|
+
* the redirect will spuriously fail.
|
|
15
|
+
*/
|
|
16
|
+
export class MemoryCacheAdapter extends BaseCacheAdapter {
|
|
17
|
+
/**
|
|
18
|
+
* @param {{ sweepIntervalMs?: number, maxEntries?: number }} [opts] - `maxEntries` bounds memory: when
|
|
19
|
+
* full, expired entries are swept and then the oldest entries evicted. (Revocation is decided by the
|
|
20
|
+
* session store when `session.verifyOnEachRequest` is on, so an evicted marker costs a fast path,
|
|
21
|
+
* not a revocation.)
|
|
22
|
+
*/
|
|
23
|
+
constructor({ sweepIntervalMs = 60_000, maxEntries = 100_000 } = {}) {
|
|
24
|
+
super();
|
|
25
|
+
this._maxEntries = maxEntries;
|
|
26
|
+
this._store = new Map(); // key -> { value, expiresAt: number|null } — insertion order = age
|
|
27
|
+
this._sweepInterval = setInterval(() => this._sweep(), sweepIntervalMs);
|
|
28
|
+
this._sweepInterval.unref?.();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async get(key) {
|
|
32
|
+
const entry = this._store.get(key);
|
|
33
|
+
if (!entry) return null;
|
|
34
|
+
if (entry.expiresAt !== null && entry.expiresAt <= Date.now()) {
|
|
35
|
+
this._store.delete(key);
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
return entry.value;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async set(key, value, ttlSeconds) {
|
|
42
|
+
const expiresAt = ttlSeconds ? Date.now() + ttlSeconds * 1000 : null;
|
|
43
|
+
this._store.delete(key); // re-inserting moves the key to the "newest" end
|
|
44
|
+
if (this._store.size >= this._maxEntries) this._makeRoom();
|
|
45
|
+
this._store.set(key, { value, expiresAt });
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
_makeRoom() {
|
|
49
|
+
this._sweep();
|
|
50
|
+
while (this._store.size >= this._maxEntries) {
|
|
51
|
+
this._store.delete(this._store.keys().next().value);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async del(key) {
|
|
56
|
+
this._store.delete(key);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Get-and-delete with no `await` in between, so it is atomic on the single JS thread. */
|
|
60
|
+
async take(key) {
|
|
61
|
+
const entry = this._store.get(key);
|
|
62
|
+
if (!entry) return null;
|
|
63
|
+
this._store.delete(key);
|
|
64
|
+
if (entry.expiresAt !== null && entry.expiresAt <= Date.now()) return null;
|
|
65
|
+
return entry.value;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async expire(key, ttlSeconds) {
|
|
69
|
+
const entry = this._store.get(key);
|
|
70
|
+
if (!entry) return;
|
|
71
|
+
entry.expiresAt = Date.now() + ttlSeconds * 1000;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
_sweep() {
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
for (const [key, entry] of this._store) {
|
|
77
|
+
if (entry.expiresAt !== null && entry.expiresAt <= now) this._store.delete(key);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Stops the background sweep timer — call on graceful shutdown in tests/short-lived processes. */
|
|
82
|
+
close() {
|
|
83
|
+
clearInterval(this._sweepInterval);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { BaseCacheAdapter } from './cache-adapter.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Recommended for production / multi-instance deployments. `ioredis` is a
|
|
5
|
+
* peerDependency — it is only imported when this adapter is actually
|
|
6
|
+
* instantiated, so consumers who stick with the in-memory default never
|
|
7
|
+
* need to install it.
|
|
8
|
+
*/
|
|
9
|
+
export class RedisCacheAdapter extends BaseCacheAdapter {
|
|
10
|
+
constructor({ redis } = {}) {
|
|
11
|
+
super();
|
|
12
|
+
if (!redis) throw new Error('RedisCacheAdapter requires a connected ioredis client instance (pass via { redis })');
|
|
13
|
+
this._redis = redis;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The underlying ioredis client — exposed so other subsystems (e.g. the Redis rate limiter) can share this connection instead of opening a second one. */
|
|
17
|
+
get client() {
|
|
18
|
+
return this._redis;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async get(key) {
|
|
22
|
+
const raw = await this._redis.get(key);
|
|
23
|
+
if (raw === null || raw === undefined) return null;
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(raw);
|
|
26
|
+
} catch {
|
|
27
|
+
return raw;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async set(key, value, ttlSeconds) {
|
|
32
|
+
const payload = typeof value === 'string' ? value : JSON.stringify(value);
|
|
33
|
+
if (ttlSeconds) {
|
|
34
|
+
await this._redis.set(key, payload, 'EX', ttlSeconds);
|
|
35
|
+
} else {
|
|
36
|
+
await this._redis.set(key, payload);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async del(key) {
|
|
41
|
+
await this._redis.del(key);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** GET + DEL in one MULTI/EXEC transaction — atomic, and works on every Redis version (GETDEL needs 6.2). */
|
|
45
|
+
async take(key) {
|
|
46
|
+
const results = await this._redis.multi().get(key).del(key).exec();
|
|
47
|
+
const [err, raw] = results?.[0] ?? [];
|
|
48
|
+
if (err) throw err;
|
|
49
|
+
if (raw === null || raw === undefined) return null;
|
|
50
|
+
try {
|
|
51
|
+
return JSON.parse(raw);
|
|
52
|
+
} catch {
|
|
53
|
+
return raw;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async expire(key, ttlSeconds) {
|
|
58
|
+
await this._redis.expire(key, ttlSeconds);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Constructs an ioredis client and wraps it. Dynamically imports `ioredis`
|
|
64
|
+
* so it's never required unless this factory is actually called.
|
|
65
|
+
*/
|
|
66
|
+
export async function createRedisCacheAdapter({ host, port, username, password, db = 0, tls, keepAliveMs = 10_000 } = {}) {
|
|
67
|
+
if (!host) throw new Error('Cache adapter "redis" needs config.cache.redis.host');
|
|
68
|
+
let IORedis;
|
|
69
|
+
try {
|
|
70
|
+
({ default: IORedis } = await import('ioredis'));
|
|
71
|
+
} catch (err) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
'Cache adapter "redis" was configured but the "ioredis" peer dependency is not installed. ' +
|
|
74
|
+
'Run `npm install ioredis` or switch cache.adapter to "memory".'
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const redis = new IORedis({
|
|
79
|
+
host,
|
|
80
|
+
port,
|
|
81
|
+
username,
|
|
82
|
+
password,
|
|
83
|
+
db,
|
|
84
|
+
// Managed Redis (and anything off the local network) should be reached over TLS: pass
|
|
85
|
+
// `tls: true` or ioredis TLS options.
|
|
86
|
+
...(tls ? { tls: tls === true ? {} : tls } : {}),
|
|
87
|
+
lazyConnect: true,
|
|
88
|
+
maxRetriesPerRequest: 3,
|
|
89
|
+
keepAlive: keepAliveMs,
|
|
90
|
+
retryStrategy: (times) => Math.min(times * 500, 5000),
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
await redis.connect();
|
|
94
|
+
|
|
95
|
+
return new RedisCacheAdapter({ redis });
|
|
96
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Default logger — used when the consumer doesn't supply one. Mirrors the pino-style `{ info, warn, error, debug }(obj, msg)` call shape. */
|
|
2
|
+
export function createConsoleLogger() {
|
|
3
|
+
const format = (obj, msg) => (obj && Object.keys(obj).length ? [msg, obj] : [msg]);
|
|
4
|
+
return {
|
|
5
|
+
info: (obj, msg) => console.info(...format(obj, msg)),
|
|
6
|
+
warn: (obj, msg) => console.warn(...format(obj, msg)),
|
|
7
|
+
error: (obj, msg) => console.error(...format(obj, msg)),
|
|
8
|
+
debug: (obj, msg) => console.debug(...format(obj, msg)),
|
|
9
|
+
};
|
|
10
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// Generic constants inlined from the Okeav extraction audit (Phase 1 §3 / Phase 2 §4).
|
|
2
|
+
// None of these encode Okeav business taxonomy (accountType, role, capabilities) —
|
|
3
|
+
// those remain fully opaque to this package and live only inside `claims`.
|
|
4
|
+
|
|
5
|
+
export const IDENTITY_STATUS = Object.freeze({
|
|
6
|
+
ACTIVE: 'ACTIVE',
|
|
7
|
+
DISABLED: 'DISABLED',
|
|
8
|
+
INVITED: 'INVITED',
|
|
9
|
+
LOCKED: 'LOCKED',
|
|
10
|
+
PENDING_VERIFICATION: 'PENDING_VERIFICATION',
|
|
11
|
+
SUSPENDED: 'SUSPENDED',
|
|
12
|
+
DELETED: 'DELETED',
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
export const KEY_STATUS = Object.freeze({
|
|
16
|
+
ACTIVE: 'ACTIVE',
|
|
17
|
+
ROTATING: 'ROTATING',
|
|
18
|
+
RETIRED: 'RETIRED',
|
|
19
|
+
REVOKED: 'REVOKED',
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
export const COOKIE_NAMES = Object.freeze({
|
|
23
|
+
ACCESS_TOKEN: 'access_token',
|
|
24
|
+
REFRESH_TOKEN: 'refresh_token',
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
export const CACHE_KEY_PREFIXES = Object.freeze({
|
|
28
|
+
REFRESH_TOKEN: 'refresh-token',
|
|
29
|
+
REVOKED_REFRESH_TOKEN: 'revoked-refresh-token',
|
|
30
|
+
INTERNAL_AUTH_TOKEN: 'internal-auth-token',
|
|
31
|
+
CLIENT_NONCE: 'client-nonce',
|
|
32
|
+
SSO_STATE: 'sso-state',
|
|
33
|
+
PUBLIC_KEY: 'public-key',
|
|
34
|
+
WEBAUTHN_CHALLENGE: 'webauthn-challenge',
|
|
35
|
+
OAUTH_CONSENT: 'oauth-consent',
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
export const PASSWORD_POLICY_DEFAULTS = Object.freeze({
|
|
39
|
+
minLength: 8,
|
|
40
|
+
maxLength: 128,
|
|
41
|
+
uppercase: /[A-Z]/,
|
|
42
|
+
lowercase: /[a-z]/,
|
|
43
|
+
number: /[0-9]/,
|
|
44
|
+
special: /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/,
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
export const NAME_REGEX = /^[\p{L}\s'-]*$/u;
|
|
48
|
+
export const MAX_EMAIL_LENGTH = 255;
|
|
49
|
+
export const MAX_NAME_LENGTH = 50;
|
|
50
|
+
|
|
51
|
+
export const TOKEN_TYPES = Object.freeze({
|
|
52
|
+
ACCESS: 'access_token',
|
|
53
|
+
MFA_CHALLENGE: 'mfa_challenge',
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
/** See classifyAccessToken in signing/token.service.js. */
|
|
57
|
+
export const ACCESS_TOKEN_KINDS = Object.freeze({
|
|
58
|
+
FIRST_PARTY: 'first-party',
|
|
59
|
+
OAUTH2_USER: 'oauth2-user',
|
|
60
|
+
OAUTH2_CLIENT: 'oauth2-client',
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
/** What a session (refresh-token) row belongs to — a first-party login, or an OAuth2 client's grant. */
|
|
64
|
+
export const SESSION_KINDS = Object.freeze({
|
|
65
|
+
FIRST_PARTY: 'first_party',
|
|
66
|
+
OAUTH2: 'oauth2',
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
export const GRANT_TYPES = Object.freeze({
|
|
70
|
+
AUTHORIZATION_CODE: 'authorization_code',
|
|
71
|
+
CLIENT_CREDENTIALS: 'client_credentials',
|
|
72
|
+
REFRESH_TOKEN: 'refresh_token',
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
export const CLIENT_TYPES = Object.freeze({
|
|
76
|
+
CONFIDENTIAL: 'confidential',
|
|
77
|
+
PUBLIC: 'public',
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
export const OAUTH_CLIENT_STATUS = Object.freeze({
|
|
81
|
+
ACTIVE: 'ACTIVE',
|
|
82
|
+
INACTIVE: 'INACTIVE',
|
|
83
|
+
SUSPENDED: 'SUSPENDED',
|
|
84
|
+
PENDING_APPROVAL: 'PENDING_APPROVAL',
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
export const DEFAULT_TTL_SECONDS = Object.freeze({
|
|
88
|
+
accessToken: 60 * 60,
|
|
89
|
+
idToken: 60 * 60,
|
|
90
|
+
refreshToken: 30 * 24 * 60 * 60,
|
|
91
|
+
internalToken: 30,
|
|
92
|
+
authCode: 10 * 60,
|
|
93
|
+
revocationCache: 60 * 60,
|
|
94
|
+
refreshTokenCache: 60 * 60,
|
|
95
|
+
passwordReset: 15 * 60,
|
|
96
|
+
emailVerification: 24 * 60 * 60,
|
|
97
|
+
magicLink: 15 * 60,
|
|
98
|
+
mfaChallenge: 5 * 60,
|
|
99
|
+
ssoState: 10 * 60,
|
|
100
|
+
ssoExchange: 2 * 60,
|
|
101
|
+
discoveryCache: 60 * 60,
|
|
102
|
+
webauthnChallenge: 5 * 60,
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// Request-rate limiting — a distinct concern from `security.maxFailedLoginAttempts`
|
|
106
|
+
// (which locks an individual account after N wrong passwords, tracked forever
|
|
107
|
+
// on the user record). These limits throttle the *rate* of requests to an
|
|
108
|
+
// endpoint within a rolling window, tracked in the rate limiter's storage,
|
|
109
|
+
// and apply regardless of whether any individual request "succeeds."
|
|
110
|
+
export const DEFAULT_RATE_LIMITS = Object.freeze({
|
|
111
|
+
loginPerIp: { max: 10, windowSeconds: 15 * 60 },
|
|
112
|
+
loginPerEmail: { max: 5, windowSeconds: 15 * 60 },
|
|
113
|
+
passwordResetPerIp: { max: 3, windowSeconds: 60 * 60 },
|
|
114
|
+
passwordResetPerEmail: { max: 3, windowSeconds: 60 * 60 },
|
|
115
|
+
mfaChallengePerIp: { max: 5, windowSeconds: 15 * 60 },
|
|
116
|
+
refreshTokenPerIp: { max: 30, windowSeconds: 60 },
|
|
117
|
+
magicLinkPerIp: { max: 3, windowSeconds: 60 * 60 },
|
|
118
|
+
magicLinkPerEmail: { max: 3, windowSeconds: 60 * 60 },
|
|
119
|
+
registerPerIp: { max: 10, windowSeconds: 60 * 60 },
|
|
120
|
+
emailVerificationPerIp: { max: 20, windowSeconds: 15 * 60 },
|
|
121
|
+
// Every request that makes this IdP send a verification email to an address
|
|
122
|
+
// (registering it, re-registering a pending one, asking for a resend).
|
|
123
|
+
verificationEmailPerEmail: { max: 3, windowSeconds: 60 * 60 },
|
|
124
|
+
// Unauthenticated passkey login: options + verify both count (a login is 2 requests). Also
|
|
125
|
+
// bounds how many challenges one IP can park in the cache.
|
|
126
|
+
webauthnAuthenticationPerIp: { max: 60, windowSeconds: 5 * 60 },
|
|
127
|
+
// /oauth2/token, /token/revoke, /token/introspect — client authentication is attempted on each.
|
|
128
|
+
oauth2TokenPerIp: { max: 120, windowSeconds: 60 },
|
|
129
|
+
// GET /sso/:provider — each call parks a state entry in the cache for ssoState seconds.
|
|
130
|
+
ssoInitiatePerIp: { max: 30, windowSeconds: 5 * 60 },
|
|
131
|
+
// POST /internal/service-keys — guesses at the bootstrap secret.
|
|
132
|
+
serviceKeyRegistrationPerIp: { max: 20, windowSeconds: 15 * 60 },
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Wrong 6-digit email-verification codes: `maxFailedAttempts` per verification ticket, and as many
|
|
137
|
+
* again for attempts without one (per address), each for at least the code's lifetime; and at most
|
|
138
|
+
* `maxTotalFailedAttempts` per address in all (a year-long cap), after which only the link works.
|
|
139
|
+
*/
|
|
140
|
+
export const DEFAULT_VERIFICATION_CODE_LOCKOUT = Object.freeze({
|
|
141
|
+
maxFailedAttempts: 5,
|
|
142
|
+
// Wrong codes ever accepted for checking per address, all budgets together — then link only.
|
|
143
|
+
maxTotalFailedAttempts: 20,
|
|
144
|
+
windowSeconds: 24 * 60 * 60,
|
|
145
|
+
lockSeconds: 24 * 60 * 60,
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
// Per-ACCOUNT limit on wrong current passwords at /password/change. That endpoint is reached with a
|
|
149
|
+
// session, not a password, so without a limit anyone holding a stolen access token could guess the
|
|
150
|
+
// password there at bcrypt speed — no lockout, nothing to lose — and keep it after the token expires.
|
|
151
|
+
export const DEFAULT_PASSWORD_CHANGE_LOCKOUT = Object.freeze({
|
|
152
|
+
maxFailedAttempts: 5,
|
|
153
|
+
windowSeconds: 60 * 60,
|
|
154
|
+
lockSeconds: 60 * 60,
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
// Per-ACCOUNT limit on failed second-factor attempts (TOTP, recovery codes,
|
|
158
|
+
// WebAuthn-as-MFA, and the codes that confirm/disable MFA), counted in
|
|
159
|
+
// storage so it holds across instances. Distinct from the per-IP
|
|
160
|
+
// `mfaChallengePerIp` rate limit above, which an attacker with many IPs
|
|
161
|
+
// sidesteps. Independent of `rateLimiting.enabled`.
|
|
162
|
+
export const DEFAULT_MFA_LOCKOUT = Object.freeze({
|
|
163
|
+
maxFailedAttempts: 5,
|
|
164
|
+
windowSeconds: 15 * 60,
|
|
165
|
+
lockSeconds: 15 * 60,
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
// Outbound webhooks — additive to the in-process hooks, never a replacement.
|
|
169
|
+
// Delivery is fire-and-forget from the caller's perspective: nothing here is
|
|
170
|
+
// ever awaited by the request that triggered the event.
|
|
171
|
+
export const DEFAULT_WEBHOOK_CONFIG = Object.freeze({
|
|
172
|
+
endpoints: [],
|
|
173
|
+
maxAttempts: 5,
|
|
174
|
+
retryBaseDelayMs: 500,
|
|
175
|
+
timeoutMs: 5000,
|
|
176
|
+
// Deliveries (with their retries) running at once; beyond this, events are dropped with a warning.
|
|
177
|
+
maxInFlight: 100,
|
|
178
|
+
});
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { DEFAULT_TTL_SECONDS, DEFAULT_RATE_LIMITS, DEFAULT_WEBHOOK_CONFIG, DEFAULT_MFA_LOCKOUT, DEFAULT_VERIFICATION_CODE_LOCKOUT, DEFAULT_PASSWORD_CHANGE_LOCKOUT } from './constants.js';
|
|
2
|
+
|
|
3
|
+
export function withDefaults(config = {}) {
|
|
4
|
+
if (!config.issuer) throw new Error('config.issuer is required');
|
|
5
|
+
if (config.mongo) throw new Error('config.mongo is not used — @okeav/idp-pg stores everything in PostgreSQL (config.postgres)');
|
|
6
|
+
if (config.storage) throw new Error('config.storage is not used — @okeav/idp-pg configures its PostgreSQL store with config.postgres');
|
|
7
|
+
// Validated in full (before anything connects) by resolvePostgresOptions — see storage/postgres/index.js.
|
|
8
|
+
if (!config.postgres) throw new Error('config.postgres is required — { connectionString } or { pool }');
|
|
9
|
+
if (!config.signingKeys?.keys || Object.keys(config.signingKeys.keys).length === 0) {
|
|
10
|
+
throw new Error('config.signingKeys.keys is required (at least one ACTIVE signing key)');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
return {
|
|
14
|
+
...config,
|
|
15
|
+
cache: { adapter: 'memory', keyPrefix: 'idp:', ...config.cache },
|
|
16
|
+
// refreshTokenInBody: 'auto' — the refresh token is in JSON bodies only for non-browser clients.
|
|
17
|
+
cookies: { secure: process.env.NODE_ENV !== 'development', sameSite: 'lax', domain: undefined, refreshTokenInBody: 'auto', ...config.cookies },
|
|
18
|
+
// verifyOnEachRequest (default true since 0.3.0): authContextMiddleware
|
|
19
|
+
// checks the token's session row in storage on every request, so a
|
|
20
|
+
// logout-all / password reset takes effect on every instance at once.
|
|
21
|
+
// recentAuthMaxAgeSeconds: how recent a login must be for requireRecentAuth (passkey / MFA
|
|
22
|
+
// enrolment, account and passkey deletion).
|
|
23
|
+
session: { reresolveClaimsOnRefresh: true, verifyOnEachRequest: true, recentAuthMaxAgeSeconds: 15 * 60,
|
|
24
|
+
// A refresh-token family (one login) ends after this however actively it's refreshed.
|
|
25
|
+
absoluteLifetimeSeconds: 90 * 24 * 60 * 60,
|
|
26
|
+
// A rotated refresh token presented again within this window (two tabs refreshing at
|
|
27
|
+
// once) is just refused; after it, it revokes the whole family as a stolen-token signal.
|
|
28
|
+
refreshReuseGraceSeconds: 10,
|
|
29
|
+
...config.session },
|
|
30
|
+
ttls: { ...DEFAULT_TTL_SECONDS, ...config.ttls },
|
|
31
|
+
security: {
|
|
32
|
+
maxFailedLoginAttempts: 5,
|
|
33
|
+
accountLockDurationMs: 30 * 60 * 1000,
|
|
34
|
+
bcryptRounds: 12,
|
|
35
|
+
emailHashPepper: config.security?.emailHashPepper,
|
|
36
|
+
tokenHashSecret: config.security?.tokenHashSecret,
|
|
37
|
+
// Earlier tokenHashSecret values, newest first: what was hashed under them still verifies.
|
|
38
|
+
previousTokenHashSecrets: [],
|
|
39
|
+
...config.security,
|
|
40
|
+
verificationCodeLockout: { ...DEFAULT_VERIFICATION_CODE_LOCKOUT, ...config.security?.verificationCodeLockout },
|
|
41
|
+
passwordChangeLockout: { ...DEFAULT_PASSWORD_CHANGE_LOCKOUT, ...config.security?.passwordChangeLockout },
|
|
42
|
+
},
|
|
43
|
+
mfa: {
|
|
44
|
+
issuerLabel: 'App',
|
|
45
|
+
recoveryCodeCount: 10,
|
|
46
|
+
// TOTP MFA is on by default, which (since 0.3.0) means a key —
|
|
47
|
+
// encryptionKey or secretCipher — is required at startup. See mfa/secrets.js.
|
|
48
|
+
enabled: true,
|
|
49
|
+
allowPlaintext: false,
|
|
50
|
+
// requireEncrypted: left unset here — it defaults to true whenever a key or cipher is
|
|
51
|
+
// configured (see config/init.js), so a plain-text secret is refused rather than used.
|
|
52
|
+
previousEncryptionKeys: [],
|
|
53
|
+
...config.mfa,
|
|
54
|
+
lockout: { ...DEFAULT_MFA_LOCKOUT, ...config.mfa?.lockout },
|
|
55
|
+
},
|
|
56
|
+
magicLink: { allowSignupViaMagicLink: true, ...config.magicLink },
|
|
57
|
+
// No defaults for rpID/rpName/origin — they're deployment-specific
|
|
58
|
+
// (rpID in particular must be the *frontend's* registrable domain,
|
|
59
|
+
// not necessarily this API's own host) and WebAuthn is opt-in, so
|
|
60
|
+
// this is validated lazily at first handler call, not at startup.
|
|
61
|
+
webauthn: config.webauthn || {},
|
|
62
|
+
oauthProviders: config.oauthProviders || {},
|
|
63
|
+
sso: config.sso || {},
|
|
64
|
+
// endSessionConfirmationUrl: the IdP page that asks "sign out?" — see oidc/end-session.controller.js.
|
|
65
|
+
oidc: { endSessionConfirmationUrl: undefined, ...config.oidc },
|
|
66
|
+
// Bounds on this server's clock vs the database's — see security/clock-skew.js.
|
|
67
|
+
clock: { maxSkewSeconds: 30, warnSkewSeconds: 2, checkIntervalSeconds: 600, ...config.clock },
|
|
68
|
+
// requirePkce: 'all' (default) or 'public' — see oauth2/authorize.controller.js.
|
|
69
|
+
oauth2: { requirePkce: 'all', ...config.oauth2 },
|
|
70
|
+
// rotationGraceSeconds: how long a replaced (ROTATING) service key still verifies — see service-mesh/key-status.js.
|
|
71
|
+
serviceMesh: { tokenMode: 'token', rotationGraceSeconds: 60 * 60, ...config.serviceMesh },
|
|
72
|
+
rateLimiting: {
|
|
73
|
+
enabled: true,
|
|
74
|
+
adapter: 'memory',
|
|
75
|
+
keyPrefix: 'ratelimit:',
|
|
76
|
+
...config.rateLimiting,
|
|
77
|
+
login: { ...DEFAULT_RATE_LIMITS.loginPerIp, ...config.rateLimiting?.login },
|
|
78
|
+
loginByEmail: { ...DEFAULT_RATE_LIMITS.loginPerEmail, ...config.rateLimiting?.loginByEmail },
|
|
79
|
+
passwordReset: { ...DEFAULT_RATE_LIMITS.passwordResetPerIp, ...config.rateLimiting?.passwordReset },
|
|
80
|
+
passwordResetByEmail: { ...DEFAULT_RATE_LIMITS.passwordResetPerEmail, ...config.rateLimiting?.passwordResetByEmail },
|
|
81
|
+
mfaChallenge: { ...DEFAULT_RATE_LIMITS.mfaChallengePerIp, ...config.rateLimiting?.mfaChallenge },
|
|
82
|
+
refreshToken: { ...DEFAULT_RATE_LIMITS.refreshTokenPerIp, ...config.rateLimiting?.refreshToken },
|
|
83
|
+
magicLink: { ...DEFAULT_RATE_LIMITS.magicLinkPerIp, ...config.rateLimiting?.magicLink },
|
|
84
|
+
magicLinkByEmail: { ...DEFAULT_RATE_LIMITS.magicLinkPerEmail, ...config.rateLimiting?.magicLinkByEmail },
|
|
85
|
+
register: { ...DEFAULT_RATE_LIMITS.registerPerIp, ...config.rateLimiting?.register },
|
|
86
|
+
emailVerification: { ...DEFAULT_RATE_LIMITS.emailVerificationPerIp, ...config.rateLimiting?.emailVerification },
|
|
87
|
+
verificationEmailByEmail: { ...DEFAULT_RATE_LIMITS.verificationEmailPerEmail, ...config.rateLimiting?.verificationEmailByEmail },
|
|
88
|
+
webauthnAuthentication: { ...DEFAULT_RATE_LIMITS.webauthnAuthenticationPerIp, ...config.rateLimiting?.webauthnAuthentication },
|
|
89
|
+
oauth2Token: { ...DEFAULT_RATE_LIMITS.oauth2TokenPerIp, ...config.rateLimiting?.oauth2Token },
|
|
90
|
+
ssoInitiate: { ...DEFAULT_RATE_LIMITS.ssoInitiatePerIp, ...config.rateLimiting?.ssoInitiate },
|
|
91
|
+
serviceKeyRegistration: { ...DEFAULT_RATE_LIMITS.serviceKeyRegistrationPerIp, ...config.rateLimiting?.serviceKeyRegistration },
|
|
92
|
+
},
|
|
93
|
+
// acceptMetadata: persist the user-supplied `metadata` from POST /register (off by default).
|
|
94
|
+
registration: { acceptMetadata: false, ...config.registration },
|
|
95
|
+
hooks: config.hooks || {},
|
|
96
|
+
hookTimeoutMs: config.hookTimeoutMs ?? 10_000,
|
|
97
|
+
webhooks: { ...DEFAULT_WEBHOOK_CONFIG, ...config.webhooks },
|
|
98
|
+
postgres: config.postgres,
|
|
99
|
+
};
|
|
100
|
+
}
|