@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,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-key limit on attempts at a secret (a code, a password, an assertion),
|
|
3
|
+
* counted in `state.attemptCounters` so it holds across instances.
|
|
4
|
+
*
|
|
5
|
+
* The attempt is counted BEFORE the secret is checked, not after a failure.
|
|
6
|
+
* Counting after is a check-then-act race: N concurrent requests all read
|
|
7
|
+
* "not locked", all get their guess checked, and only then are N failures
|
|
8
|
+
* recorded — a burst gets as many guesses as it has requests. Counting first
|
|
9
|
+
* makes the counter's atomic increment the gate: each concurrent request sees
|
|
10
|
+
* a distinct count, and only the first `maxFailedAttempts` within a window get
|
|
11
|
+
* checked. A success resets the counter, so the reservation it made costs
|
|
12
|
+
* nothing. (An attempt that errors for another reason — an expired challenge,
|
|
13
|
+
* say — keeps its reservation: when in doubt, it counts.)
|
|
14
|
+
*
|
|
15
|
+
* The failed attempt that uses up the budget answers with `lockedError` (not
|
|
16
|
+
* its own error) and runs `onLocked` once; every later attempt is refused with
|
|
17
|
+
* the identical `lockedError` before its secret is looked at, whatever it was.
|
|
18
|
+
*
|
|
19
|
+
* A counter backend error propagates, so this fails closed.
|
|
20
|
+
*
|
|
21
|
+
* @param {object} state
|
|
22
|
+
* @param {string} key
|
|
23
|
+
* @param {{ maxFailedAttempts: number, windowSeconds: number, lockSeconds: number }} limits
|
|
24
|
+
* @param {{ lockedError: () => Error, onLocked?: (entry) => Promise<void>, isFailure?: (err) => boolean }} opts
|
|
25
|
+
* `isFailure` decides whether an error from `verify` was a wrong guess (default: any error).
|
|
26
|
+
* @param {() => Promise<T>} verify - throws on a wrong secret.
|
|
27
|
+
* @returns {Promise<T>}
|
|
28
|
+
* @template T
|
|
29
|
+
*/
|
|
30
|
+
export async function withAttemptBudget(state, key, limits, { lockedError, onLocked, isFailure = () => true }, verify) {
|
|
31
|
+
const { maxFailedAttempts: max, windowSeconds, lockSeconds } = limits;
|
|
32
|
+
const entry = await state.attemptCounters.recordFailure(key, { max, windowSeconds, lockSeconds });
|
|
33
|
+
if (entry.count > max) throw lockedError();
|
|
34
|
+
|
|
35
|
+
let result;
|
|
36
|
+
try {
|
|
37
|
+
result = await verify();
|
|
38
|
+
} catch (err) {
|
|
39
|
+
if (entry.count === max && isFailure(err)) {
|
|
40
|
+
if (onLocked) await onLocked(entry);
|
|
41
|
+
throw lockedError();
|
|
42
|
+
}
|
|
43
|
+
throw err;
|
|
44
|
+
}
|
|
45
|
+
await state.attemptCounters.reset(key);
|
|
46
|
+
return result;
|
|
47
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Clock skew between this app server and the database.
|
|
3
|
+
*
|
|
4
|
+
* Revocation ordering doesn't use clocks (it uses counters and the database's own clock), but expiry
|
|
5
|
+
* does: token `exp`, code and link lifetimes and lockout windows are compared against the clock of the
|
|
6
|
+
* server checking them. Servers whose clocks disagree would let something live longer — or die sooner —
|
|
7
|
+
* than configured. So, as Kerberos does, the skew is bounded: each server measures its clock against
|
|
8
|
+
* the database's at startup (refusing to start past `clock.maxSkewSeconds`) and again every
|
|
9
|
+
* `clock.checkIntervalSeconds` (logging an error past it). Every server measured against the same
|
|
10
|
+
* clock is then within 2 × maxSkewSeconds of every other.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* This server's clock minus the database's, in ms (the database's reading is taken as the midpoint
|
|
15
|
+
* of the round trip). Null when the storage adapter can't tell the time (`storage.databaseTime`).
|
|
16
|
+
*/
|
|
17
|
+
export async function measureClockSkew(storage) {
|
|
18
|
+
if (typeof storage?.databaseTime !== 'function') return null;
|
|
19
|
+
const sent = Date.now();
|
|
20
|
+
const { time } = await storage.databaseTime();
|
|
21
|
+
const received = Date.now();
|
|
22
|
+
const dbTime = new Date(time).getTime();
|
|
23
|
+
if (!Number.isFinite(dbTime)) throw new Error('storage.databaseTime() did not return a valid time');
|
|
24
|
+
return Math.round((sent + received) / 2 - dbTime);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** `{ skewMs, ok, level }` for the current skew — `level`: 'ok', 'warn' (past warnSkewSeconds) or 'error' (past maxSkewSeconds). */
|
|
28
|
+
export async function checkSkew(storage, clockConfig) {
|
|
29
|
+
const skewMs = await measureClockSkew(storage);
|
|
30
|
+
if (skewMs === null) return { skewMs: null, ok: true, level: 'unknown' };
|
|
31
|
+
const abs = Math.abs(skewMs);
|
|
32
|
+
const level = abs > clockConfig.maxSkewSeconds * 1000 ? 'error' : abs > clockConfig.warnSkewSeconds * 1000 ? 'warn' : 'ok';
|
|
33
|
+
return { skewMs, ok: level !== 'error', level };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const message = (skewMs, clock) => `This server's clock is ${(Math.abs(skewMs) / 1000).toFixed(1)}s ${skewMs > 0 ? 'ahead of' : 'behind'} the database's `
|
|
37
|
+
+ `(limit ${clock.maxSkewSeconds}s) — token and code lifetimes would be wrong. Sync the clock (NTP).`;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Startup: refuses (throws) past maxSkewSeconds, warns past warnSkewSeconds, then re-checks every
|
|
41
|
+
* checkIntervalSeconds. Resolves a `stop()` for the periodic check.
|
|
42
|
+
*/
|
|
43
|
+
export async function startClockSkewGuard(storage, clock, logger) {
|
|
44
|
+
if (typeof storage?.databaseTime !== 'function') {
|
|
45
|
+
logger?.warn?.({}, '@okeav/idp-pg: the storage has no databaseTime() — clock skew between servers is not checked. Upgrade the adapter.');
|
|
46
|
+
return () => {};
|
|
47
|
+
}
|
|
48
|
+
const first = await checkSkew(storage, clock);
|
|
49
|
+
if (first.level === 'error') throw new Error(message(first.skewMs, clock));
|
|
50
|
+
if (first.level === 'warn') logger?.warn?.({ skewMs: first.skewMs }, message(first.skewMs, clock));
|
|
51
|
+
|
|
52
|
+
const timer = setInterval(async () => {
|
|
53
|
+
try {
|
|
54
|
+
const { skewMs, level } = await checkSkew(storage, clock);
|
|
55
|
+
if (level === 'error') logger?.error?.({ skewMs }, message(skewMs, clock));
|
|
56
|
+
else if (level === 'warn') logger?.warn?.({ skewMs }, message(skewMs, clock));
|
|
57
|
+
} catch (err) {
|
|
58
|
+
logger?.warn?.({ err: { name: err?.name, message: err?.message } }, 'Clock skew check failed');
|
|
59
|
+
}
|
|
60
|
+
}, clock.checkIntervalSeconds * 1000);
|
|
61
|
+
timer.unref?.();
|
|
62
|
+
return () => clearInterval(timer);
|
|
63
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { KEY_STATUS } from '../config/constants.js';
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_ROTATION_GRACE_SECONDS = 60 * 60;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Whether a stored service key may verify tokens (and be published in the services JWKS).
|
|
7
|
+
*
|
|
8
|
+
* ACTIVE keys may. A ROTATING key — one its service replaced with a newer key — may only for
|
|
9
|
+
* `serviceMesh.rotationGraceSeconds` after it was replaced: long enough for in-flight tokens and for
|
|
10
|
+
* instances still running the old key during a rolling deploy, but not indefinitely. A service
|
|
11
|
+
* rotates precisely when a key is suspected compromised, and an unbounded "rotating" state would keep
|
|
12
|
+
* honouring the compromised key until some later rotation happened to retire it.
|
|
13
|
+
*
|
|
14
|
+
* `statusChangedAt` is written on every status change since 0.4.0; an older row falls back to its
|
|
15
|
+
* `updatedAt`, which the status change also bumped.
|
|
16
|
+
*/
|
|
17
|
+
export function isKeyPublishable(doc, graceSeconds = DEFAULT_ROTATION_GRACE_SECONDS, now = Date.now()) {
|
|
18
|
+
if (doc?.status === KEY_STATUS.ACTIVE) return true;
|
|
19
|
+
if (doc?.status !== KEY_STATUS.ROTATING) return false;
|
|
20
|
+
const since = doc.statusChangedAt ?? doc.updatedAt ?? doc.lastSeenAt;
|
|
21
|
+
return Boolean(since) && new Date(since).getTime() + graceSeconds * 1000 > now;
|
|
22
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { isKeyPublishable, DEFAULT_ROTATION_GRACE_SECONDS } from './key-status.js';
|
|
2
|
+
|
|
3
|
+
/** In-process key lookup — used when the verifier is the IDP itself, which has direct storage access. */
|
|
4
|
+
export function localKeyLookup(serviceKeyRepository, { rotationGraceSeconds = DEFAULT_ROTATION_GRACE_SECONDS } = {}) {
|
|
5
|
+
return async (kid) => {
|
|
6
|
+
const match = typeof serviceKeyRepository.findPublishableByKid === 'function'
|
|
7
|
+
? await serviceKeyRepository.findPublishableByKid(kid)
|
|
8
|
+
: (await serviceKeyRepository.listPublishable()).find((k) => k.kid === kid);
|
|
9
|
+
if (!match || !isKeyPublishable(match, rotationGraceSeconds)) return null;
|
|
10
|
+
return { publicKeyPem: Buffer.from(match.publicKey, 'base64').toString('utf8'), service: match.name };
|
|
11
|
+
};
|
|
12
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
3
|
+
import { isSecureUrl } from '../utils/url.js';
|
|
4
|
+
|
|
5
|
+
const CACHE_TTL_MS = 5 * 60 * 1000;
|
|
6
|
+
// A forced refresh (unknown kid) happens at most this often: otherwise every request carrying a junk
|
|
7
|
+
// kid — no credentials needed — makes this service fetch the IdP's JWKS.
|
|
8
|
+
const MIN_FORCED_REFRESH_INTERVAL_MS = 30 * 1000;
|
|
9
|
+
const FETCH_TIMEOUT_MS = 5000;
|
|
10
|
+
// After a failed fetch, wait this long before trying again (the IdP may be down — don't hammer it).
|
|
11
|
+
const FAILURE_BACKOFF_MS = 30 * 1000;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* HTTP-based key lookup for a downstream service that verifies inbound S2S
|
|
15
|
+
* calls from peers but doesn't run the IDP itself (no direct DB access).
|
|
16
|
+
* Fetches `${idpBaseUrl}/.well-known/services-jwks.json` with a short
|
|
17
|
+
* in-memory cache, force-refreshing on a kid miss (peer rotated) — rate
|
|
18
|
+
* limited, with a timeout, and keeping the last good keys if a refresh fails.
|
|
19
|
+
*/
|
|
20
|
+
export function remoteJwksKeyLookup(idpBaseUrl, { timeoutMs = FETCH_TIMEOUT_MS } = {}) {
|
|
21
|
+
// Over plain http anyone on the path could substitute the key set — and so every service's identity.
|
|
22
|
+
if (!isSecureUrl(idpBaseUrl)) throw new Error('remoteJwksKeyLookup: idpBaseUrl must be https (http only for localhost)');
|
|
23
|
+
const jwksUrl = `${idpBaseUrl.replace(/\/$/, '')}/.well-known/services-jwks.json`;
|
|
24
|
+
let cache = new Map();
|
|
25
|
+
let fetchedAt = 0;
|
|
26
|
+
let lastForcedAt = 0;
|
|
27
|
+
let retryAfter = 0;
|
|
28
|
+
let inflight = null;
|
|
29
|
+
|
|
30
|
+
async function refresh() {
|
|
31
|
+
if (inflight) return inflight;
|
|
32
|
+
inflight = (async () => {
|
|
33
|
+
const res = await fetch(jwksUrl, { redirect: 'error', signal: AbortSignal.timeout(timeoutMs) });
|
|
34
|
+
if (!res.ok) throw new Error(`JWKS fetch failed: ${res.status}`);
|
|
35
|
+
const body = await res.json();
|
|
36
|
+
const fresh = new Map();
|
|
37
|
+
for (const jwk of body.keys ?? []) {
|
|
38
|
+
if (!jwk.kid || jwk.kty !== 'RSA') continue;
|
|
39
|
+
try {
|
|
40
|
+
const pem = crypto.createPublicKey({ key: jwk, format: 'jwk' }).export({ format: 'pem', type: 'spki' }).toString('utf8');
|
|
41
|
+
fresh.set(jwk.kid, { publicKeyPem: pem, service: jwk.service });
|
|
42
|
+
} catch {
|
|
43
|
+
// skip an unreadable key rather than failing the whole set
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
cache = fresh;
|
|
47
|
+
fetchedAt = Date.now();
|
|
48
|
+
})();
|
|
49
|
+
try {
|
|
50
|
+
await inflight;
|
|
51
|
+
} finally {
|
|
52
|
+
inflight = null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return async (kid, { forceRefresh = false } = {}) => {
|
|
57
|
+
const now = Date.now();
|
|
58
|
+
const stale = !fetchedAt || now - fetchedAt > CACHE_TTL_MS;
|
|
59
|
+
const mayForce = forceRefresh && now - lastForcedAt >= MIN_FORCED_REFRESH_INTERVAL_MS;
|
|
60
|
+
if ((stale || mayForce) && now >= retryAfter) {
|
|
61
|
+
if (mayForce) lastForcedAt = now;
|
|
62
|
+
try {
|
|
63
|
+
await refresh();
|
|
64
|
+
} catch (cause) {
|
|
65
|
+
retryAfter = Date.now() + FAILURE_BACKOFF_MS;
|
|
66
|
+
// Keep serving the keys we have; with none at all there is nothing to verify against.
|
|
67
|
+
if (!fetchedAt) throw new IdpError({ code: 'SERVICE_UNAVAILABLE', httpStatus: 503, message: 'Service keys are unavailable', cause });
|
|
68
|
+
}
|
|
69
|
+
} else if (!fetchedAt) {
|
|
70
|
+
throw new IdpError({ code: 'SERVICE_UNAVAILABLE', httpStatus: 503, message: 'Service keys are unavailable' });
|
|
71
|
+
}
|
|
72
|
+
return cache.get(kid) ?? null;
|
|
73
|
+
};
|
|
74
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { getState } from '../config/state.js';
|
|
2
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
3
|
+
import { safeEqualSecret } from '../utils/safe-equal.js';
|
|
4
|
+
import { enforceRateLimit } from '../rate-limit/enforce.js';
|
|
5
|
+
import { ipKey } from '../rate-limit/keys.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Bootstrap gate for `registerServiceKeyHandler`. A service can't mint an S2S JWT before its key is
|
|
9
|
+
* registered, so registration is gated on a bootstrap secret in the `x-s2s-bootstrap-secret` header.
|
|
10
|
+
*
|
|
11
|
+
* Preferred: `config.serviceMesh.bootstrapSecrets = { <serviceName>: <secret> }` — one credential per
|
|
12
|
+
* service, so the secret proves WHICH service is registering (`req.s2sBootstrap.serviceName`). The
|
|
13
|
+
* single shared `config.serviceMesh.bootstrapSecret` is still accepted, but proves only "some
|
|
14
|
+
* participating service": the handler then refuses to change the key of a name that already has one.
|
|
15
|
+
*/
|
|
16
|
+
export async function s2sBootstrapMiddleware(req, _res, next) {
|
|
17
|
+
try {
|
|
18
|
+
const state = getState();
|
|
19
|
+
await enforceRateLimit(state, `s2s-bootstrap:ip:${ipKey(req.ip)}`, state.config.rateLimiting.serviceKeyRegistration, { failMode: 'closed' });
|
|
20
|
+
|
|
21
|
+
const presented = req.headers['x-s2s-bootstrap-secret'];
|
|
22
|
+
const name = req.body?.name;
|
|
23
|
+
const perService = state.config.serviceMesh?.bootstrapSecrets;
|
|
24
|
+
const shared = state.config.serviceMesh?.bootstrapSecret;
|
|
25
|
+
const DENIED = () => new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Invalid bootstrap secret' });
|
|
26
|
+
|
|
27
|
+
if (typeof presented !== 'string' || presented.length === 0) return next(DENIED());
|
|
28
|
+
|
|
29
|
+
if (perService && typeof name === 'string' && Object.hasOwn(perService, name) && safeEqualSecret(presented, perService[name])) {
|
|
30
|
+
req.s2sBootstrap = { serviceName: name, shared: false };
|
|
31
|
+
return next();
|
|
32
|
+
}
|
|
33
|
+
if (shared && safeEqualSecret(presented, shared)) {
|
|
34
|
+
req.s2sBootstrap = { serviceName: null, shared: true };
|
|
35
|
+
return next();
|
|
36
|
+
}
|
|
37
|
+
next(DENIED());
|
|
38
|
+
} catch (err) {
|
|
39
|
+
next(err);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import jwt from 'jsonwebtoken';
|
|
3
|
+
import { deriveKid, verifyServiceTokenWith } from './verify-service-token.js';
|
|
4
|
+
import { remoteJwksKeyLookup } from './remote-jwks-key-lookup.js';
|
|
5
|
+
import { isSecureUrl } from '../utils/url.js';
|
|
6
|
+
|
|
7
|
+
const TOKEN_TTL_SECONDS = 60;
|
|
8
|
+
|
|
9
|
+
let _identity = { serviceName: null, region: 'global', kid: null, privateKeyPem: null, publicKeyPem: null };
|
|
10
|
+
let _remoteLookup = null;
|
|
11
|
+
// One cached lookup per IdP URL: verifyServiceTokenRemote({ idpBaseUrl }) used to build a new one —
|
|
12
|
+
// and so fetch the JWKS — on every call.
|
|
13
|
+
const _lookupsByUrl = new Map();
|
|
14
|
+
function lookupFor(idpBaseUrl) {
|
|
15
|
+
if (!_lookupsByUrl.has(idpBaseUrl)) _lookupsByUrl.set(idpBaseUrl, remoteJwksKeyLookup(idpBaseUrl));
|
|
16
|
+
return _lookupsByUrl.get(idpBaseUrl);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Registers this process's own S2S keypair with an IDP instance (this one,
|
|
21
|
+
* or a separately-deployed one) so other services can verify tokens it
|
|
22
|
+
* mints. Call once at startup. Idempotent — re-running with the same key is
|
|
23
|
+
* a no-op server-side (upsert by kid).
|
|
24
|
+
*
|
|
25
|
+
* @param {{ serviceName: string, privateKeyPem: string, region?: string, idpBaseUrl: string, bootstrapSecret: string }} opts
|
|
26
|
+
*/
|
|
27
|
+
export async function initServiceIdentity(opts = {}) {
|
|
28
|
+
const { serviceName, privateKeyPem, region = 'global', idpBaseUrl, bootstrapSecret } = opts;
|
|
29
|
+
if (!serviceName) throw new Error('initServiceIdentity: serviceName is required');
|
|
30
|
+
if (!privateKeyPem) throw new Error('initServiceIdentity: privateKeyPem is required');
|
|
31
|
+
if (!idpBaseUrl) throw new Error('initServiceIdentity: idpBaseUrl is required');
|
|
32
|
+
if (!bootstrapSecret) throw new Error('initServiceIdentity: bootstrapSecret is required');
|
|
33
|
+
// The bootstrap secret is sent to it, and its key set decides whose tokens are trusted.
|
|
34
|
+
if (!isSecureUrl(idpBaseUrl)) throw new Error('initServiceIdentity: idpBaseUrl must be https (http only for localhost)');
|
|
35
|
+
|
|
36
|
+
const publicKeyPem = crypto.createPublicKey(privateKeyPem).export({ format: 'pem', type: 'spki' }).toString('utf8');
|
|
37
|
+
const kid = deriveKid(serviceName, publicKeyPem);
|
|
38
|
+
|
|
39
|
+
_identity = { serviceName, region, kid, privateKeyPem, publicKeyPem };
|
|
40
|
+
_remoteLookup = lookupFor(idpBaseUrl);
|
|
41
|
+
|
|
42
|
+
const registerUrl = `${idpBaseUrl.replace(/\/$/, '')}/internal/service-keys`;
|
|
43
|
+
const res = await fetch(registerUrl, {
|
|
44
|
+
method: 'POST',
|
|
45
|
+
headers: { 'Content-Type': 'application/json', 'x-s2s-bootstrap-secret': bootstrapSecret },
|
|
46
|
+
body: JSON.stringify({ name: serviceName, publicKey: Buffer.from(publicKeyPem, 'utf8').toString('base64'), region }),
|
|
47
|
+
});
|
|
48
|
+
if (!res.ok) {
|
|
49
|
+
const body = await res.text().catch(() => '');
|
|
50
|
+
throw new Error(`Failed to register service key with IDP (${res.status}): ${body}`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return { kid };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function getServiceIdentity() {
|
|
57
|
+
if (!_identity.kid) throw new Error('Service identity not initialized — call initServiceIdentity() at startup');
|
|
58
|
+
return { serviceName: _identity.serviceName, kid: _identity.kid, region: _identity.region };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function mintServiceToken(targetService, { scopes = [] } = {}) {
|
|
62
|
+
if (!_identity.privateKeyPem) throw new Error('mintServiceToken: identity not initialized — call initServiceIdentity() first');
|
|
63
|
+
if (!targetService) throw new Error('mintServiceToken: targetService is required');
|
|
64
|
+
|
|
65
|
+
const now = Math.floor(Date.now() / 1000);
|
|
66
|
+
const payload = {
|
|
67
|
+
iss: _identity.serviceName,
|
|
68
|
+
aud: targetService,
|
|
69
|
+
iat: now,
|
|
70
|
+
exp: now + TOKEN_TTL_SECONDS,
|
|
71
|
+
jti: crypto.randomUUID(),
|
|
72
|
+
region: _identity.region,
|
|
73
|
+
...(scopes.length ? { scope: scopes.join(' ') } : {}),
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
return jwt.sign(payload, _identity.privateKeyPem, { algorithm: 'RS256', keyid: _identity.kid });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Verifies an inbound S2S JWT against a remote IDP's public services-JWKS
|
|
81
|
+
* endpoint. Use this in a downstream service that does NOT itself run
|
|
82
|
+
* `@okeav/idp-pg` — a service that does should use
|
|
83
|
+
* `serviceContextMiddleware` instead, which looks keys up in-process.
|
|
84
|
+
*/
|
|
85
|
+
export async function verifyServiceTokenRemote(token, { expectedAud, expectedIss, idpBaseUrl } = {}) {
|
|
86
|
+
const lookup = idpBaseUrl ? lookupFor(idpBaseUrl) : _remoteLookup;
|
|
87
|
+
if (!lookup) throw new Error('verifyServiceTokenRemote: pass idpBaseUrl, or call initServiceIdentity() first');
|
|
88
|
+
return verifyServiceTokenWith(token, { expectedAud, expectedIss }, lookup);
|
|
89
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { getState } from '../config/state.js';
|
|
3
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
4
|
+
import { KEY_STATUS } from '../config/constants.js';
|
|
5
|
+
import { deriveKid } from './verify-service-token.js';
|
|
6
|
+
import { auditLog } from '../hooks/index.js';
|
|
7
|
+
import { isKeyPublishable } from './key-status.js';
|
|
8
|
+
|
|
9
|
+
export const SERVICE_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;
|
|
10
|
+
const MIN_RSA_BITS = 2048;
|
|
11
|
+
|
|
12
|
+
const invalid = (message) => new IdpError({ code: 'INVALID_REQUEST', httpStatus: 400, message });
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Parses a registration's public key. Only an RSA PUBLIC key of at least 2048 bits: tokens are
|
|
16
|
+
* verified as RS256, a weak key can be factored, and a private key PEM (which `createPublicKey`
|
|
17
|
+
* happily accepts) must never be stored or served. Returns the normalized SPKI PEM.
|
|
18
|
+
*/
|
|
19
|
+
function parsePublicKey(publicKeyB64) {
|
|
20
|
+
let pem;
|
|
21
|
+
try {
|
|
22
|
+
pem = Buffer.from(publicKeyB64, 'base64').toString('utf8');
|
|
23
|
+
} catch {
|
|
24
|
+
throw invalid('publicKey must be a base64-encoded PEM');
|
|
25
|
+
}
|
|
26
|
+
let isPrivate = false;
|
|
27
|
+
try {
|
|
28
|
+
crypto.createPrivateKey(pem);
|
|
29
|
+
isPrivate = true;
|
|
30
|
+
} catch {
|
|
31
|
+
// not a private key — expected
|
|
32
|
+
}
|
|
33
|
+
if (isPrivate) throw invalid('publicKey is a PRIVATE key — send only the public key (and rotate this one: it has left the service)');
|
|
34
|
+
|
|
35
|
+
let key;
|
|
36
|
+
try {
|
|
37
|
+
key = crypto.createPublicKey(pem);
|
|
38
|
+
} catch {
|
|
39
|
+
throw invalid('publicKey is not a valid public key PEM');
|
|
40
|
+
}
|
|
41
|
+
if (key.asymmetricKeyType !== 'rsa') throw invalid('publicKey must be an RSA key (tokens are RS256)');
|
|
42
|
+
if ((key.asymmetricKeyDetails?.modulusLength ?? 0) < MIN_RSA_BITS) throw invalid(`publicKey must be at least ${MIN_RSA_BITS} bits`);
|
|
43
|
+
return key.export({ format: 'pem', type: 'spki' }).toString('utf8');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* POST /internal/service-keys — a service publishes its S2S public key. Gate with
|
|
48
|
+
* `s2sBootstrapMiddleware`.
|
|
49
|
+
*
|
|
50
|
+
* - Re-registering the same key (same kid) is idempotent.
|
|
51
|
+
* - A per-service bootstrap secret (`serviceMesh.bootstrapSecrets`) authorizes exactly its own name,
|
|
52
|
+
* and may register a new key for it (rotation): the previous keys move to ROTATING (still
|
|
53
|
+
* verifiable, so in-flight tokens keep working) and are retired on the next rotation.
|
|
54
|
+
* - The shared `serviceMesh.bootstrapSecret` may only register a name that has no live key, and never
|
|
55
|
+
* a name that has its own per-service secret: it proves "some participating service", not which
|
|
56
|
+
* one, so it must not be able to replace another service's key and impersonate it. (A shared-secret
|
|
57
|
+
* name whose keys were all revoked can be registered again by a shared-secret holder — that is how
|
|
58
|
+
* such a service recovers; give a service its own secret to rule that out.)
|
|
59
|
+
* - A revoked key is never accepted again (409 SERVICE_KEY_REVOKED): the service must generate a new one.
|
|
60
|
+
* - A rotated-away (ROTATING) key keeps verifying for `serviceMesh.rotationGraceSeconds` only.
|
|
61
|
+
* - `serviceMesh.allowedServiceNames`, when set, limits which names can register at all.
|
|
62
|
+
*/
|
|
63
|
+
export async function registerServiceKeyHandler(req, res, next) {
|
|
64
|
+
try {
|
|
65
|
+
const state = getState();
|
|
66
|
+
const { name, publicKey: publicKeyB64, region } = req.body ?? {};
|
|
67
|
+
|
|
68
|
+
if (typeof name !== 'string' || !SERVICE_NAME_PATTERN.test(name)) throw invalid('name must match /^[a-z0-9][a-z0-9-]{0,62}$/');
|
|
69
|
+
if (region !== undefined && (typeof region !== 'string' || !/^[A-Za-z0-9_-]{1,32}$/.test(region))) throw invalid('region must be 1-32 characters [A-Za-z0-9_-]');
|
|
70
|
+
if (!publicKeyB64 || typeof publicKeyB64 !== 'string' || publicKeyB64.length > 8192) throw invalid('publicKey (base64 PEM) is required');
|
|
71
|
+
|
|
72
|
+
const allowedNames = state.config.serviceMesh?.allowedServiceNames;
|
|
73
|
+
if (Array.isArray(allowedNames) && !allowedNames.includes(name)) {
|
|
74
|
+
throw new IdpError({ code: 'FORBIDDEN', httpStatus: 403, message: `Service name '${name}' is not allowed to register` });
|
|
75
|
+
}
|
|
76
|
+
const auth = req.s2sBootstrap;
|
|
77
|
+
if (!auth || (!auth.shared && auth.serviceName !== name)) {
|
|
78
|
+
throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Bootstrap credential does not cover this service name' });
|
|
79
|
+
}
|
|
80
|
+
const perService = state.config.serviceMesh?.bootstrapSecrets;
|
|
81
|
+
if (auth.shared && perService && Object.hasOwn(perService, name)) {
|
|
82
|
+
await auditLog(state.logger, state.hooks, 'SERVICE_KEY_REGISTRATION_REFUSED', { name, reason: 'name_has_own_secret' });
|
|
83
|
+
throw new IdpError({ code: 'FORBIDDEN', httpStatus: 403, message: `Service '${name}' registers with its own bootstrap secret, not the shared one` });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const publicKeyPem = parsePublicKey(publicKeyB64);
|
|
87
|
+
const kid = deriveKid(name, publicKeyPem);
|
|
88
|
+
const repo = state.storage.serviceKeyRepository;
|
|
89
|
+
const revoked = () => new IdpError({ code: 'SERVICE_KEY_REVOKED', httpStatus: 409, message: 'This key was revoked — generate a new key pair' });
|
|
90
|
+
// Checked before a rotation demotes the current key (upsertByKid refuses it again, atomically).
|
|
91
|
+
if (typeof repo.findByKid === 'function' && (await repo.findByKid(kid))?.status === KEY_STATUS.REVOKED) {
|
|
92
|
+
await auditLog(state.logger, state.hooks, 'SERVICE_KEY_REGISTRATION_REFUSED', { name, kid, reason: 'key_revoked' });
|
|
93
|
+
throw revoked();
|
|
94
|
+
}
|
|
95
|
+
const existing = (await repo.listPublishable()).filter((k) => k.name === name);
|
|
96
|
+
const sameKey = existing.some((k) => k.kid === kid);
|
|
97
|
+
|
|
98
|
+
const nameTaken = async () => {
|
|
99
|
+
await auditLog(state.logger, state.hooks, 'SERVICE_KEY_REGISTRATION_REFUSED', { name, kid, reason: 'name_taken' });
|
|
100
|
+
return new IdpError({ code: 'SERVICE_NAME_TAKEN', httpStatus: 409, message: `Service '${name}' already has a key; rotating it needs that service's own bootstrap secret` });
|
|
101
|
+
};
|
|
102
|
+
if (existing.length > 0 && !sameKey && auth.shared) throw await nameTaken();
|
|
103
|
+
|
|
104
|
+
// The new key goes in first: a registration refused here (a revoked kid) must not have demoted
|
|
105
|
+
// the service's current key already.
|
|
106
|
+
const saved = await repo.upsertByKid({ kid, name, publicKey: Buffer.from(publicKeyPem, 'utf8').toString('base64'), region });
|
|
107
|
+
if (!saved) throw revoked();
|
|
108
|
+
|
|
109
|
+
if (existing.length > 0 && !sameKey) {
|
|
110
|
+
// Per-service rotation: retire keys already rotating, demote the active ones — each only from
|
|
111
|
+
// the status just read, so a key revoked meanwhile stays revoked.
|
|
112
|
+
for (const k of existing) {
|
|
113
|
+
await repo.setStatusByKid(k.kid, k.status === KEY_STATUS.ROTATING ? KEY_STATUS.RETIRED : KEY_STATUS.ROTATING, { expectedStatus: k.status });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (auth.shared && existing.length === 0) {
|
|
117
|
+
// Concurrent first registrations of one new name with the shared secret all saw "no key yet".
|
|
118
|
+
// Exactly one keeps it — the earliest registered (then lowest kid); the others revoke their own.
|
|
119
|
+
const rivals = (await repo.listPublishable()).filter((k) => k.name === name && k.status === KEY_STATUS.ACTIVE);
|
|
120
|
+
const winner = rivals.sort((a, b) => (new Date(a.registeredAt) - new Date(b.registeredAt)) || String(a.kid).localeCompare(String(b.kid)))[0];
|
|
121
|
+
if (winner && winner.kid !== kid) {
|
|
122
|
+
await repo.setStatusByKid(kid, KEY_STATUS.REVOKED);
|
|
123
|
+
throw await nameTaken();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
await auditLog(state.logger, state.hooks, 'SERVICE_KEY_REGISTERED', { name, kid: saved.kid, rotated: existing.length > 0 && !sameKey });
|
|
128
|
+
res.status(201).json({ kid: saved.kid, name: saved.name });
|
|
129
|
+
} catch (err) {
|
|
130
|
+
next(err);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Revokes a service key by kid (programmatic, for your admin tooling): it is no longer published or
|
|
136
|
+
* accepted. The name can then be registered again with a new key.
|
|
137
|
+
*/
|
|
138
|
+
export async function revokeServiceKey(kid) {
|
|
139
|
+
const state = getState();
|
|
140
|
+
const updated = await state.storage.serviceKeyRepository.setStatusByKid(kid, KEY_STATUS.REVOKED);
|
|
141
|
+
if (updated) await auditLog(state.logger, state.hooks, 'SERVICE_KEY_REVOKED', { kid });
|
|
142
|
+
return Boolean(updated);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* GET /.well-known/services-jwks.json — union JWKS for every ACTIVE/ROTATING
|
|
147
|
+
* service key. Public — keys are public by definition, no auth required.
|
|
148
|
+
*/
|
|
149
|
+
export async function getServicesJwksHandler(req, res, next) {
|
|
150
|
+
try {
|
|
151
|
+
const state = getState();
|
|
152
|
+
const docs = await state.storage.serviceKeyRepository.listPublishable();
|
|
153
|
+
const grace = state.config.serviceMesh?.rotationGraceSeconds;
|
|
154
|
+
const keys = [];
|
|
155
|
+
for (const doc of docs.filter((d) => isKeyPublishable(d, grace))) {
|
|
156
|
+
try {
|
|
157
|
+
const key = crypto.createPublicKey(Buffer.from(doc.publicKey, 'base64').toString('utf8'));
|
|
158
|
+
// Never publish anything but an RSA public key (rows written before 0.4.0 weren't validated).
|
|
159
|
+
if (key.asymmetricKeyType !== 'rsa') continue;
|
|
160
|
+
keys.push({ ...key.export({ format: 'jwk' }), use: 'sig', alg: 'RS256', kid: doc.kid, service: doc.name, status: doc.status });
|
|
161
|
+
} catch {
|
|
162
|
+
state.logger?.warn?.({ kid: doc.kid }, 'Skipping an unreadable service key');
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
res.set('Cache-Control', 'public, max-age=60');
|
|
166
|
+
res.json({ keys });
|
|
167
|
+
} catch (err) {
|
|
168
|
+
next(err);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import jwt from 'jsonwebtoken';
|
|
2
|
+
import crypto from 'crypto';
|
|
3
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
4
|
+
|
|
5
|
+
// Service tokens are minted per call with a 60 s lifetime (see service-identity.client.js). Anything
|
|
6
|
+
// claiming to live longer — or with no expiry at all — wasn't minted by a well-behaved peer, and a
|
|
7
|
+
// token that never expires can't be cut off by revoking its key's future signatures.
|
|
8
|
+
export const SERVICE_TOKEN_MAX_AGE_SECONDS = 5 * 60;
|
|
9
|
+
const CLOCK_TOLERANCE_SECONDS = 30;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Core S2S-JWT verification, parameterized over a `lookupKey(kid)` function
|
|
13
|
+
* so it works both for the IDP verifying inbound calls against its own
|
|
14
|
+
* in-process ServiceKeyRepository, and for a downstream service verifying
|
|
15
|
+
* against a remote JWKS fetched over HTTP (see remote-jwks-key-lookup.js).
|
|
16
|
+
*
|
|
17
|
+
* Requires RS256, `aud` = the expected service, `exp` and `iat` (issued no more than
|
|
18
|
+
* SERVICE_TOKEN_MAX_AGE_SECONDS ago and not in the future), and `iss` = the key's owner.
|
|
19
|
+
*
|
|
20
|
+
* @param {string} token
|
|
21
|
+
* @param {{ expectedAud: string, expectedIss?: string }} opts
|
|
22
|
+
* @param {(kid: string, opts: {forceRefresh?: boolean}) => Promise<{publicKeyPem: string, service?: string}|null>} lookupKey
|
|
23
|
+
*/
|
|
24
|
+
export async function verifyServiceTokenWith(token, opts, lookupKey) {
|
|
25
|
+
const { expectedAud, expectedIss } = opts;
|
|
26
|
+
if (!expectedAud) {
|
|
27
|
+
throw new IdpError({ code: 'SERVICE_NOT_CONFIGURED', httpStatus: 500, message: 'verifyServiceToken: expectedAud (this service\'s own name) is required' });
|
|
28
|
+
}
|
|
29
|
+
if (!token) throw badToken('Missing service token');
|
|
30
|
+
|
|
31
|
+
const decoded = jwt.decode(token, { complete: true });
|
|
32
|
+
if (!decoded?.header?.kid) throw badToken('Service token missing kid');
|
|
33
|
+
|
|
34
|
+
let entry = await lookupKey(decoded.header.kid, {});
|
|
35
|
+
if (!entry) entry = await lookupKey(decoded.header.kid, { forceRefresh: true }); // peer may have just rotated
|
|
36
|
+
if (!entry) throw badToken(`Unknown service key kid: ${decoded.header.kid}`);
|
|
37
|
+
|
|
38
|
+
let payload;
|
|
39
|
+
try {
|
|
40
|
+
payload = jwt.verify(token, entry.publicKeyPem, {
|
|
41
|
+
algorithms: ['RS256'],
|
|
42
|
+
audience: expectedAud,
|
|
43
|
+
clockTolerance: CLOCK_TOLERANCE_SECONDS,
|
|
44
|
+
maxAge: SERVICE_TOKEN_MAX_AGE_SECONDS,
|
|
45
|
+
...(expectedIss ? { issuer: expectedIss } : {}),
|
|
46
|
+
});
|
|
47
|
+
} catch (err) {
|
|
48
|
+
if (err?.name === 'TokenExpiredError') {
|
|
49
|
+
throw new IdpError({ code: 'TOKEN_EXPIRED', httpStatus: 401, message: 'Service token expired' });
|
|
50
|
+
}
|
|
51
|
+
throw badToken(err.message);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const now = Math.floor(Date.now() / 1000);
|
|
55
|
+
if (typeof payload.exp !== 'number') throw badToken('Service token has no expiry');
|
|
56
|
+
if (typeof payload.iat !== 'number' || payload.iat > now + CLOCK_TOLERANCE_SECONDS) throw badToken('Service token iat is missing or in the future');
|
|
57
|
+
if (payload.exp - payload.iat > SERVICE_TOKEN_MAX_AGE_SECONDS) throw badToken('Service token lifetime is too long');
|
|
58
|
+
|
|
59
|
+
if (entry.service && payload.iss !== entry.service) {
|
|
60
|
+
throw badToken(`Service token iss=${payload.iss} doesn't match key owner ${entry.service}`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return payload;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function badToken(message) {
|
|
67
|
+
return new IdpError({ code: 'SERVICE_TOKEN_INVALID', httpStatus: 401, message });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function deriveKid(serviceName, publicKeyPem) {
|
|
71
|
+
const jwk = crypto.createPublicKey(publicKeyPem).export({ format: 'jwk' });
|
|
72
|
+
const canonical = JSON.stringify({ e: jwk.e, kty: jwk.kty, n: jwk.n });
|
|
73
|
+
const digest = crypto.createHash('sha256').update(canonical).digest('hex');
|
|
74
|
+
return `${serviceName}:${digest.slice(0, 16)}`;
|
|
75
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { getState } from '../config/state.js';
|
|
2
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
3
|
+
import { buildUserTokenJwks } from './jwks.js';
|
|
4
|
+
import { KEY_STATUS } from '../config/constants.js';
|
|
5
|
+
|
|
6
|
+
// Public keys are public: relying parties may cache them, briefly, so a rotation propagates quickly.
|
|
7
|
+
const PUBLIC_KEY_CACHE = 'public, max-age=300';
|
|
8
|
+
|
|
9
|
+
/** GET /.well-known/jwks.json — RFC 7517 JWK Set for this IDP's user-token signing keys. */
|
|
10
|
+
export function jwksHandler(_req, res) {
|
|
11
|
+
res.set('Cache-Control', PUBLIC_KEY_CACHE);
|
|
12
|
+
res.json(buildUserTokenJwks(getState()));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** GET /keys/:kid — raw base64 PEM for a single key. Internal use (e.g. resource servers that want the PEM directly instead of JWK). */
|
|
16
|
+
export function authPublicKeyHandler(req, res, next) {
|
|
17
|
+
try {
|
|
18
|
+
const state = getState();
|
|
19
|
+
const { kid } = req.params;
|
|
20
|
+
const entry = state.signingKeys[kid];
|
|
21
|
+
if (!entry) throw new IdpError({ code: 'UNKNOWN_KID', httpStatus: 404, message: 'Unknown key ID' });
|
|
22
|
+
if (![KEY_STATUS.ACTIVE, KEY_STATUS.ROTATING, KEY_STATUS.RETIRED].includes(entry.status)) {
|
|
23
|
+
throw new IdpError({ code: 'KEY_NOT_ALLOWED', httpStatus: 403, message: 'Key not allowed' });
|
|
24
|
+
}
|
|
25
|
+
res.set('Cache-Control', PUBLIC_KEY_CACHE);
|
|
26
|
+
res.json({ publicKey: Buffer.from(entry.publicKeyPem, 'utf8').toString('base64') });
|
|
27
|
+
} catch (err) {
|
|
28
|
+
next(err);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { getVerifiableKeys } from './key-registry.js';
|
|
3
|
+
|
|
4
|
+
/** RFC 7517 JWK Set for this IDP's own user-token signing keys (access/ID/OAuth2 tokens). */
|
|
5
|
+
export function buildUserTokenJwks(state) {
|
|
6
|
+
const keys = getVerifiableKeys(state.signingKeys).map(([kid, key]) => {
|
|
7
|
+
const jwk = crypto.createPublicKey(key.publicKeyPem).export({ format: 'jwk' });
|
|
8
|
+
return { ...jwk, use: 'sig', alg: 'RS256', kid };
|
|
9
|
+
});
|
|
10
|
+
return { keys };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** JWK SHA-256 thumbprint per RFC 7638, used to derive stable service kids. */
|
|
14
|
+
export function deriveKidFromPublicKey(name, publicKeyPem) {
|
|
15
|
+
const jwk = crypto.createPublicKey(publicKeyPem).export({ format: 'jwk' });
|
|
16
|
+
const canonical = JSON.stringify({ e: jwk.e, kty: jwk.kty, n: jwk.n });
|
|
17
|
+
const digest = crypto.createHash('sha256').update(canonical).digest('hex');
|
|
18
|
+
return `${name}:${digest.slice(0, 16)}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function pemToJwk(publicKeyPem, extra = {}) {
|
|
22
|
+
const jwk = crypto.createPublicKey(publicKeyPem).export({ format: 'jwk' });
|
|
23
|
+
return { ...jwk, ...extra };
|
|
24
|
+
}
|