@okeav/idp-pg 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/.env.example +159 -0
  2. package/CHANGELOG.md +58 -0
  3. package/LICENSE +21 -0
  4. package/README.md +275 -3
  5. package/package.json +78 -6
  6. package/src/cache/cache-adapter.js +22 -0
  7. package/src/cache/index.js +68 -0
  8. package/src/cache/memory.adapter.js +85 -0
  9. package/src/cache/redis.adapter.js +96 -0
  10. package/src/config/console-logger.js +10 -0
  11. package/src/config/constants.js +178 -0
  12. package/src/config/defaults.js +100 -0
  13. package/src/config/from-env.js +150 -0
  14. package/src/config/init.js +286 -0
  15. package/src/config/state.js +22 -0
  16. package/src/errors/error-codes.js +97 -0
  17. package/src/errors/idp-error.js +75 -0
  18. package/src/hooks/index.js +85 -0
  19. package/src/index.js +167 -0
  20. package/src/magic-link/controller.js +129 -0
  21. package/src/magic-link/schemas.js +12 -0
  22. package/src/mfa/attempt-guard.js +48 -0
  23. package/src/mfa/controller.js +309 -0
  24. package/src/mfa/factor-store.js +37 -0
  25. package/src/mfa/memory-attempt-counter.js +58 -0
  26. package/src/mfa/schemas.js +11 -0
  27. package/src/mfa/secret-cipher.js +133 -0
  28. package/src/mfa/secrets.js +156 -0
  29. package/src/middleware/auth-context.middleware.js +149 -0
  30. package/src/middleware/cookie-parser.js +4 -0
  31. package/src/middleware/csrf.js +48 -0
  32. package/src/middleware/require-recent-auth.middleware.js +30 -0
  33. package/src/middleware/require-service-caller.middleware.js +32 -0
  34. package/src/middleware/service-context.middleware.js +70 -0
  35. package/src/middleware/validate-body.js +16 -0
  36. package/src/middleware/validate-query.js +22 -0
  37. package/src/oauth2/authorize.controller.js +233 -0
  38. package/src/oauth2/client-auth.js +77 -0
  39. package/src/oauth2/client.controller.js +122 -0
  40. package/src/oauth2/consent.controller.js +63 -0
  41. package/src/oauth2/login-challenge.js +50 -0
  42. package/src/oauth2/redirect-uri.js +25 -0
  43. package/src/oauth2/schemas.js +103 -0
  44. package/src/oauth2/token.controller.js +370 -0
  45. package/src/oidc/discovery.controller.js +36 -0
  46. package/src/oidc/end-session.controller.js +137 -0
  47. package/src/oidc/userinfo.controller.js +49 -0
  48. package/src/password-auth/controllers.js +927 -0
  49. package/src/password-auth/schemas.js +76 -0
  50. package/src/rate-limit/enforce.js +35 -0
  51. package/src/rate-limit/index.js +48 -0
  52. package/src/rate-limit/keys.js +36 -0
  53. package/src/rate-limit/memory.adapter.js +75 -0
  54. package/src/rate-limit/noop.adapter.js +14 -0
  55. package/src/rate-limit/rate-limiter.js +18 -0
  56. package/src/rate-limit/redis.adapter.js +71 -0
  57. package/src/routes/build-router.js +238 -0
  58. package/src/security/attempt-budget.js +47 -0
  59. package/src/security/clock-skew.js +63 -0
  60. package/src/service-mesh/key-status.js +22 -0
  61. package/src/service-mesh/local-key-lookup.js +12 -0
  62. package/src/service-mesh/remote-jwks-key-lookup.js +74 -0
  63. package/src/service-mesh/s2s-bootstrap.middleware.js +41 -0
  64. package/src/service-mesh/service-identity.client.js +89 -0
  65. package/src/service-mesh/service-key.controller.js +170 -0
  66. package/src/service-mesh/verify-service-token.js +75 -0
  67. package/src/signing/jwks.controller.js +30 -0
  68. package/src/signing/jwks.js +24 -0
  69. package/src/signing/key-registry.js +97 -0
  70. package/src/signing/token.service.js +336 -0
  71. package/src/sso/binding.js +30 -0
  72. package/src/sso/callback.controller.js +186 -0
  73. package/src/sso/initiate.controller.js +92 -0
  74. package/src/sso/providers.js +237 -0
  75. package/src/sso/schemas.js +7 -0
  76. package/src/storage/interfaces.js +178 -0
  77. package/src/storage/postgres/db.js +68 -0
  78. package/src/storage/postgres/index.js +160 -0
  79. package/src/storage/postgres/migrations/run-migrations.js +122 -0
  80. package/src/storage/postgres/migrations/sql/0001_init.sql +253 -0
  81. package/src/storage/postgres/repositories/attempt-counter.repository.js +65 -0
  82. package/src/storage/postgres/repositories/authorization-code.repository.js +104 -0
  83. package/src/storage/postgres/repositories/consent.repository.js +68 -0
  84. package/src/storage/postgres/repositories/credential.repository.js +75 -0
  85. package/src/storage/postgres/repositories/oauth-client.repository.js +122 -0
  86. package/src/storage/postgres/repositories/service-key.repository.js +76 -0
  87. package/src/storage/postgres/repositories/session.repository.js +290 -0
  88. package/src/storage/postgres/repositories/user.repository.js +328 -0
  89. package/src/storage/postgres/repositories/verification-token.repository.js +138 -0
  90. package/src/storage/postgres/run.js +22 -0
  91. package/src/utils/account-status.js +26 -0
  92. package/src/utils/cookies.js +129 -0
  93. package/src/utils/device-fingerprint.js +58 -0
  94. package/src/utils/email-hash.js +23 -0
  95. package/src/utils/oauth-client-credentials.js +51 -0
  96. package/src/utils/password.js +40 -0
  97. package/src/utils/safe-equal.js +12 -0
  98. package/src/utils/session-family.js +158 -0
  99. package/src/utils/session-kind.js +15 -0
  100. package/src/utils/url.js +17 -0
  101. package/src/webauthn/authentication.controller.js +126 -0
  102. package/src/webauthn/challenge-store.js +17 -0
  103. package/src/webauthn/config.js +25 -0
  104. package/src/webauthn/mfa.controller.js +119 -0
  105. package/src/webauthn/registration.controller.js +128 -0
  106. package/src/webauthn/schemas.js +41 -0
  107. package/src/webauthn/shared.js +63 -0
  108. package/src/webhooks/dispatcher.js +135 -0
  109. package/src/webhooks/sign.js +55 -0
  110. package/src/webhooks/wrap-hooks.js +51 -0
  111. package/types/index.d.ts +777 -0
@@ -0,0 +1,135 @@
1
+ import crypto from 'crypto';
2
+ import { buildSignatureHeader } from './sign.js';
3
+
4
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
5
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
6
+ const MIN_SECRET_LENGTH = 16;
7
+
8
+ /** A URL safe to put in a log line: no credentials, no query string. */
9
+ function redactUrl(url) {
10
+ try {
11
+ const u = new URL(url);
12
+ return `${u.origin}${u.pathname}`;
13
+ } catch {
14
+ return '<invalid url>';
15
+ }
16
+ }
17
+
18
+ /**
19
+ * Validates one configured endpoint (at startup): https only (http only to a loopback host), a
20
+ * signing secret of at least 16 characters, and an optional `events` allowlist.
21
+ */
22
+ function validateEndpoint(endpoint, i) {
23
+ const where = `config.webhooks.endpoints[${i}]`;
24
+ let url;
25
+ try {
26
+ url = new URL(endpoint?.url);
27
+ } catch {
28
+ throw new Error(`${where}.url is not a valid URL`);
29
+ }
30
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))) {
31
+ throw new Error(`${where}.url must be https (http only for localhost) — deliveries carry account data`);
32
+ }
33
+ if (typeof endpoint.secret !== 'string' || endpoint.secret.length < MIN_SECRET_LENGTH) {
34
+ throw new Error(`${where}.secret must be a string of at least ${MIN_SECRET_LENGTH} characters`);
35
+ }
36
+ if (endpoint.events !== undefined && !(Array.isArray(endpoint.events) && endpoint.events.every((e) => typeof e === 'string'))) {
37
+ throw new Error(`${where}.events must be an array of event names`);
38
+ }
39
+ return { url: endpoint.url, secret: endpoint.secret, events: endpoint.events ? new Set(endpoint.events) : null, includeCredentials: endpoint.includeCredentials === true };
40
+ }
41
+
42
+ /**
43
+ * Delivers signed event payloads to consumer-configured HTTP endpoints,
44
+ * additive to the in-process hooks (never a replacement for them). Every
45
+ * public method is fire-and-forget: `dispatch()` never returns a promise the
46
+ * caller is expected to await, and delivery failures — including a
47
+ * permanently unreachable endpoint after all retries — only ever get logged,
48
+ * never thrown back into the auth operation that triggered the event.
49
+ *
50
+ * Per endpoint: `events` limits which events it receives; credential fields (reset tokens,
51
+ * magic-link tokens, verification codes) are stripped unless `includeCredentials: true` — a
52
+ * receiver that only analyses events must never be able to take over accounts. At most
53
+ * `maxInFlight` deliveries (including their retries) run at once; beyond that, events are dropped
54
+ * with a warning rather than queued without bound. Redirects are not followed.
55
+ */
56
+ export class WebhookDispatcher {
57
+ constructor({ endpoints = [], maxAttempts = 5, retryBaseDelayMs = 500, timeoutMs = 5000, maxInFlight = 100 } = {}, logger) {
58
+ this.endpoints = endpoints.map(validateEndpoint);
59
+ this.maxAttempts = maxAttempts;
60
+ this.retryBaseDelayMs = retryBaseDelayMs;
61
+ this.timeoutMs = timeoutMs;
62
+ this.maxInFlight = maxInFlight;
63
+ this.inFlight = 0;
64
+ this.logger = logger;
65
+ }
66
+
67
+ get isNoop() {
68
+ return this.endpoints.length === 0;
69
+ }
70
+
71
+ /**
72
+ * Fire-and-forget. Never throws, never returns a promise callers need to await.
73
+ * @param {{ credentialFields?: string[] }} [opts] - payload fields that are credentials.
74
+ */
75
+ dispatch(event, payload, { credentialFields = [] } = {}) {
76
+ if (this.isNoop) return;
77
+ for (const endpoint of this.endpoints) {
78
+ if (endpoint.events && !endpoint.events.has(event)) continue;
79
+ if (this.inFlight >= this.maxInFlight) {
80
+ this.logger?.warn?.({ event, url: redactUrl(endpoint.url), maxInFlight: this.maxInFlight }, 'Webhook backlog full — event dropped');
81
+ continue;
82
+ }
83
+
84
+ let body = payload;
85
+ if (credentialFields.length > 0 && !endpoint.includeCredentials && payload && typeof payload === 'object') {
86
+ body = { ...payload };
87
+ for (const field of credentialFields) delete body[field];
88
+ }
89
+ // The delivery id is part of the signed body, so a receiver can de-duplicate on it and a
90
+ // replayed delivery can't be passed off as a new one by changing a header.
91
+ const id = crypto.randomUUID();
92
+ const rawBody = JSON.stringify({ id, event, payload: body, timestamp: new Date().toISOString() });
93
+
94
+ this.inFlight += 1;
95
+ this._deliverWithRetry(endpoint, event, id, rawBody)
96
+ .catch((err) => {
97
+ this.logger?.warn?.({ err: err?.message, event, url: redactUrl(endpoint.url) }, 'Webhook delivery failed after all retries — ignoring');
98
+ })
99
+ .finally(() => {
100
+ this.inFlight -= 1;
101
+ });
102
+ }
103
+ }
104
+
105
+ async _deliverWithRetry(endpoint, event, deliveryId, rawBody) {
106
+ for (let attempt = 1; attempt <= this.maxAttempts; attempt += 1) {
107
+ try {
108
+ await this._send(endpoint, rawBody, event, deliveryId);
109
+ return;
110
+ } catch (err) {
111
+ if (attempt >= this.maxAttempts) throw err;
112
+ await sleep(this.retryBaseDelayMs * 2 ** (attempt - 1));
113
+ }
114
+ }
115
+ }
116
+
117
+ async _send(endpoint, rawBody, event, deliveryId) {
118
+ const timestamp = Math.floor(Date.now() / 1000);
119
+ const signature = buildSignatureHeader(endpoint.secret, timestamp, rawBody);
120
+
121
+ const res = await fetch(endpoint.url, {
122
+ method: 'POST',
123
+ headers: {
124
+ 'Content-Type': 'application/json',
125
+ 'X-Idp-Event': event,
126
+ 'X-Idp-Delivery': deliveryId,
127
+ 'X-Idp-Signature': signature,
128
+ },
129
+ body: rawBody,
130
+ redirect: 'manual', // a 3xx is a failure — never re-send a signed body to wherever it points
131
+ signal: AbortSignal.timeout(this.timeoutMs),
132
+ });
133
+ if (!res.ok) throw new Error(`webhook endpoint ${redactUrl(endpoint.url)} responded with status ${res.status}`);
134
+ }
135
+ }
@@ -0,0 +1,55 @@
1
+ import crypto from 'crypto';
2
+
3
+ /**
4
+ * Stripe-style webhook signing: sign `${timestamp}.${rawBody}` with
5
+ * HMAC-SHA256 so a receiving consumer can verify both authenticity and that
6
+ * the delivery isn't a stale replay, without ever needing to parse the body
7
+ * before verifying it.
8
+ */
9
+ export function signWebhookPayload(secret, timestamp, rawBody) {
10
+ return crypto.createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex');
11
+ }
12
+
13
+ export function buildSignatureHeader(secret, timestamp, rawBody) {
14
+ return `t=${timestamp},v1=${signWebhookPayload(secret, timestamp, rawBody)}`;
15
+ }
16
+
17
+ /**
18
+ * For consumers receiving webhook deliveries from this package. Verifies the
19
+ * `X-Idp-Signature` header (`t=<unix seconds>,v1=<hex hmac>[,v1=…]`) against the raw
20
+ * request body, rejecting stale deliveries via `toleranceSeconds`.
21
+ *
22
+ * Rotation: pass an array of secrets (current and previous) to accept either, and the header may
23
+ * carry several `v1` signatures — any one matching suffices. After verifying, de-duplicate on the
24
+ * body's `id` (signed, unlike the `X-Idp-Delivery` header) to reject a replay within the tolerance.
25
+ *
26
+ * @param {string | string[]} secret - the shared secret(s) configured for this endpoint
27
+ * @param {string} rawBody - the exact, unparsed request body bytes/string
28
+ * @param {string} signatureHeader - the `X-Idp-Signature` header value
29
+ * @param {{ toleranceSeconds?: number }} [opts]
30
+ * @returns {boolean}
31
+ */
32
+ export function verifyWebhookSignature(secret, rawBody, signatureHeader, opts = {}) {
33
+ const toleranceSeconds = opts.toleranceSeconds ?? 5 * 60;
34
+ if (typeof signatureHeader !== 'string' || typeof rawBody !== 'string') return false;
35
+ const secrets = (Array.isArray(secret) ? secret : [secret]).filter((s) => typeof s === 'string' && s.length > 0);
36
+ if (secrets.length === 0) return false;
37
+
38
+ let timestamp = NaN;
39
+ const provided = [];
40
+ for (const part of signatureHeader.split(',')) {
41
+ const idx = part.indexOf('=');
42
+ if (idx < 0) continue;
43
+ const key = part.slice(0, idx).trim();
44
+ const value = part.slice(idx + 1).trim();
45
+ if (key === 't') timestamp = Number(value);
46
+ else if (key === 'v1' && /^[0-9a-f]{64}$/i.test(value)) provided.push(Buffer.from(value, 'hex'));
47
+ }
48
+ if (!Number.isFinite(timestamp) || timestamp <= 0 || provided.length === 0) return false;
49
+ if (Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return false;
50
+
51
+ return secrets.some((s) => {
52
+ const expected = Buffer.from(signWebhookPayload(s, timestamp, rawBody), 'hex');
53
+ return provided.some((p) => p.length === expected.length && crypto.timingSafeEqual(p, expected));
54
+ });
55
+ }
@@ -0,0 +1,51 @@
1
+ // `resolveAuthContext` is the one hook whose return value the caller actually
2
+ // uses (it builds `claims`) — it's a data-returning callback, not a one-way
3
+ // event notification, so it's never wrapped for webhook dispatch.
4
+ const EXCLUDED_HOOKS = new Set(['resolveAuthContext']);
5
+
6
+ /**
7
+ * Payload fields that are credentials: whoever holds one can reset a password, log in, or verify an
8
+ * address. They are stripped from webhook deliveries unless the endpoint sets `includeCredentials`
9
+ * (e.g. the endpoint that actually sends your emails).
10
+ */
11
+ export const CREDENTIAL_FIELDS = Object.freeze({
12
+ onPasswordResetRequested: ['resetToken'],
13
+ onMagicLinkRequested: ['magicLinkToken'],
14
+ onVerificationEmailRequested: ['verificationToken', 'verificationCode'],
15
+ });
16
+
17
+ /**
18
+ * Wraps every one-way notification hook so that, in addition to invoking the
19
+ * consumer's in-process hook (unchanged), it also fires an outbound webhook
20
+ * delivery via `dispatcher`. Purely additive — if no webhook endpoints are
21
+ * configured, `dispatcher.isNoop` is true and the original `hooks` object is
22
+ * returned untouched.
23
+ *
24
+ * `onAuditLog` payloads carry their own `action` (e.g. "login", "password.changed"),
25
+ * which is a more useful event name for a consumer filtering deliveries than
26
+ * the literal string "onAuditLog", so that one case uses `payload.action` as
27
+ * the dispatched event name instead of the hook name.
28
+ *
29
+ * The webhook is dispatched even when the in-process hook throws: one failing consumer
30
+ * callback must not silently drop the event for every webhook receiver.
31
+ */
32
+ export function wrapHooksWithWebhooks(hooks, dispatcher) {
33
+ if (!dispatcher || dispatcher.isNoop) return hooks;
34
+
35
+ const wrapped = {};
36
+ for (const [name, fn] of Object.entries(hooks)) {
37
+ if (EXCLUDED_HOOKS.has(name) || typeof fn !== 'function') {
38
+ wrapped[name] = fn;
39
+ continue;
40
+ }
41
+ wrapped[name] = async (payload) => {
42
+ try {
43
+ return await fn(payload);
44
+ } finally {
45
+ const event = name === 'onAuditLog' && payload?.action ? payload.action : name;
46
+ dispatcher.dispatch(event, payload, { credentialFields: CREDENTIAL_FIELDS[name] ?? [] });
47
+ }
48
+ };
49
+ }
50
+ return wrapped;
51
+ }