@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,103 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { isAcceptableRedirectUri } from './redirect-uri.js';
|
|
3
|
+
import { loginChallengeSchema } from './login-challenge.js';
|
|
4
|
+
|
|
5
|
+
const httpsUrl = (field) => z.string().max(2048).refine((v) => { try { return new URL(v).protocol === 'https:'; } catch { return false; } }, `${field} must be an https URL`);
|
|
6
|
+
|
|
7
|
+
// PKCE (RFC 7636): only S256. A challenge is the base64url SHA-256 of the verifier (always 43
|
|
8
|
+
// chars); a verifier is 43–128 unreserved characters. `plain` is refused — it protects nothing
|
|
9
|
+
// once the authorization request is observed (RFC 9700 §2.1.1).
|
|
10
|
+
const codeChallenge = z.string().regex(/^[A-Za-z0-9_-]{43}$/, 'code_challenge must be a base64url-encoded SHA-256 (S256) value');
|
|
11
|
+
const codeVerifier = z.string().regex(/^[A-Za-z0-9\-._~]{43,128}$/, 'code_verifier must be 43-128 unreserved characters');
|
|
12
|
+
const pkceFields = {
|
|
13
|
+
code_challenge: codeChallenge.optional(),
|
|
14
|
+
code_challenge_method: z.literal('S256').optional(),
|
|
15
|
+
};
|
|
16
|
+
// RFC 7636 §4.3: an omitted method means "plain" — so a challenge without `S256` is refused, not assumed.
|
|
17
|
+
const pkceMethodRequired = (v) => !v.code_challenge || v.code_challenge_method === 'S256';
|
|
18
|
+
const pkceMethodMessage = { message: 'code_challenge_method=S256 is required with a code_challenge', path: ['code_challenge_method'] };
|
|
19
|
+
|
|
20
|
+
const redirectUri = z.string().refine(isAcceptableRedirectUri, { message: 'redirect_uri must be https (http only for loopback), or a reverse-DNS private-use scheme, with no fragment' });
|
|
21
|
+
const nonce = z.string().min(1).max(512);
|
|
22
|
+
|
|
23
|
+
export const authorizeQuerySchema = z.object({
|
|
24
|
+
client_id: z.string().min(1),
|
|
25
|
+
redirect_uri: z.string().url(),
|
|
26
|
+
response_type: z.string(),
|
|
27
|
+
scope: z.string().optional(),
|
|
28
|
+
state: z.string().max(2048).optional(),
|
|
29
|
+
nonce: nonce.optional(),
|
|
30
|
+
// OIDC Core §3.1.2.1 — see authorize.controller.js (resolvePrompt).
|
|
31
|
+
prompt: z.string().max(100).optional(),
|
|
32
|
+
max_age: z.string().regex(/^\d{1,10}$/, 'max_age must be a non-negative integer of seconds').optional(),
|
|
33
|
+
// Returned with a login_required answer; presented again once the user signed in for it (login-challenge.js).
|
|
34
|
+
login_challenge: loginChallengeSchema.optional(),
|
|
35
|
+
...pkceFields,
|
|
36
|
+
}).refine(pkceMethodRequired, pkceMethodMessage);
|
|
37
|
+
|
|
38
|
+
// Confirm/deny act on the request stored under the consent_challenge that /oauth2/authorize
|
|
39
|
+
// returned — the client, scopes, redirect_uri, state, nonce and PKCE challenge are NOT taken from
|
|
40
|
+
// this body (see authorize.controller.js).
|
|
41
|
+
const consentChallenge = z.string().regex(/^[A-Za-z0-9_-]{20,100}$/, 'consent_challenge is malformed');
|
|
42
|
+
export const confirmAuthorizeSchema = z.object({ consent_challenge: consentChallenge }).strict();
|
|
43
|
+
export const denyAuthorizeSchema = z.object({ consent_challenge: consentChallenge }).strict();
|
|
44
|
+
|
|
45
|
+
// client_id / client_secret may instead arrive as HTTP Basic credentials (client_secret_basic).
|
|
46
|
+
export const tokenSchema = z.object({
|
|
47
|
+
grant_type: z.enum(['authorization_code', 'refresh_token', 'client_credentials']),
|
|
48
|
+
code: z.string().optional(),
|
|
49
|
+
redirect_uri: z.string().optional(),
|
|
50
|
+
client_id: z.string().min(1).optional(),
|
|
51
|
+
client_secret: z.string().optional(),
|
|
52
|
+
code_verifier: codeVerifier.optional(),
|
|
53
|
+
refresh_token: z.string().optional(),
|
|
54
|
+
scope: z.string().optional(),
|
|
55
|
+
}).passthrough();
|
|
56
|
+
|
|
57
|
+
export const revokeTokenSchema = z.object({
|
|
58
|
+
token: z.string().min(1),
|
|
59
|
+
token_type_hint: z.string().optional(),
|
|
60
|
+
client_id: z.string().min(1).optional(),
|
|
61
|
+
client_secret: z.string().optional(),
|
|
62
|
+
}).strict();
|
|
63
|
+
|
|
64
|
+
export const introspectTokenSchema = z.object({
|
|
65
|
+
token: z.string().min(1),
|
|
66
|
+
token_type_hint: z.string().optional(),
|
|
67
|
+
client_id: z.string().min(1).optional(),
|
|
68
|
+
client_secret: z.string().optional(),
|
|
69
|
+
}).strict();
|
|
70
|
+
|
|
71
|
+
export const consentQuerySchema = z.object({ client_id: z.string().min(1) }).strict();
|
|
72
|
+
|
|
73
|
+
export const registerOAuthClientSchema = z.object({
|
|
74
|
+
name: z.string().trim().min(1),
|
|
75
|
+
slug: z.string().trim().min(1).toLowerCase(),
|
|
76
|
+
clientType: z.enum(['confidential', 'public']).optional(),
|
|
77
|
+
redirectUris: z.array(redirectUri).min(1),
|
|
78
|
+
postLogoutRedirectUris: z.array(redirectUri).optional(),
|
|
79
|
+
allowedScopes: z.array(z.string()).optional(),
|
|
80
|
+
allowedGrants: z.array(z.enum(['authorization_code', 'client_credentials', 'refresh_token'])).optional(),
|
|
81
|
+
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
82
|
+
}).strict();
|
|
83
|
+
|
|
84
|
+
export const updateOAuthClientSchema = z.object({
|
|
85
|
+
name: z.string().trim().min(1).optional(),
|
|
86
|
+
redirectUris: z.array(redirectUri).optional(),
|
|
87
|
+
postLogoutRedirectUris: z.array(redirectUri).optional(),
|
|
88
|
+
allowedScopes: z.array(z.string()).optional(),
|
|
89
|
+
allowedGrants: z.array(z.enum(['authorization_code', 'client_credentials', 'refresh_token'])).optional(),
|
|
90
|
+
clientType: z.enum(['confidential', 'public']).optional(),
|
|
91
|
+
// Bounded: an access token can't be revoked once issued (client_credentials tokens have no session),
|
|
92
|
+
// so a ten-year lifetime is a ten-year credential.
|
|
93
|
+
accessTokenTTL: z.number().int().positive().max(24 * 60 * 60).optional(),
|
|
94
|
+
refreshTokenTTL: z.number().int().positive().max(365 * 24 * 60 * 60).optional(),
|
|
95
|
+
idTokenTTL: z.number().int().positive().max(24 * 60 * 60).optional(),
|
|
96
|
+
// Shown as links on the consent screen: https only (a `javascript:` URL there runs in the IdP's origin).
|
|
97
|
+
logoUrl: httpsUrl('logoUrl').optional(),
|
|
98
|
+
websiteUrl: httpsUrl('websiteUrl').optional(),
|
|
99
|
+
privacyPolicyUrl: httpsUrl('privacyPolicyUrl').optional(),
|
|
100
|
+
termsOfServiceUrl: httpsUrl('termsOfServiceUrl').optional(),
|
|
101
|
+
supportEmail: z.string().email().optional(),
|
|
102
|
+
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
103
|
+
}).strict();
|
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { getState } from '../config/state.js';
|
|
3
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
4
|
+
import { GRANT_TYPES, CACHE_KEY_PREFIXES, SESSION_KINDS, ACCESS_TOKEN_KINDS } from '../config/constants.js';
|
|
5
|
+
import { isActiveAccount } from '../utils/account-status.js';
|
|
6
|
+
import { issueOAuth2AccessToken, issueIdToken, hashOpaqueToken, generateOpaqueToken, verifyAccessToken, clientTtl, lookupByTokenHash, opaqueTokenHashes, HASH_PURPOSES } from '../signing/token.service.js';
|
|
7
|
+
import { sessionKindOf } from '../utils/session-kind.js';
|
|
8
|
+
import { authenticateClient } from './client-auth.js';
|
|
9
|
+
import { auditLog } from '../hooks/index.js';
|
|
10
|
+
import { enforceRateLimit } from '../rate-limit/enforce.js';
|
|
11
|
+
import { ipKey } from '../rate-limit/keys.js';
|
|
12
|
+
import { familyOf, familyEndsAt, cappedExpiry, handleRefreshReuse, revokeFamily, assertChainNotRevoked, assertFamilyNotRevoked, peekRefreshRow, resolveRefreshTokenHash } from '../utils/session-family.js';
|
|
13
|
+
|
|
14
|
+
const INVALID_GRANT = (message) => new IdpError({ code: 'INVALID_GRANT', httpStatus: 400, message });
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* RFC 7636 with S256 only. A code issued with a challenge needs the matching verifier; a code issued
|
|
18
|
+
* WITHOUT one must not be redeemed with a verifier either (RFC 9700 §4.8.2) — that combination is a
|
|
19
|
+
* PKCE downgrade: an attacker injecting a challenge-less code into a client that uses PKCE.
|
|
20
|
+
*/
|
|
21
|
+
function verifyPkce(codeVerifier, authCode) {
|
|
22
|
+
if (!authCode.codeChallenge) {
|
|
23
|
+
if (codeVerifier) throw INVALID_GRANT('code_verifier sent for a code issued without code_challenge');
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
if (authCode.codeChallengeMethod !== 'S256') throw INVALID_GRANT('Unsupported code_challenge_method');
|
|
27
|
+
if (!codeVerifier) throw INVALID_GRANT('code_verifier is required');
|
|
28
|
+
const computed = Buffer.from(crypto.createHash('sha256').update(codeVerifier).digest('base64url'));
|
|
29
|
+
const stored = Buffer.from(authCode.codeChallenge);
|
|
30
|
+
if (computed.length !== stored.length || !crypto.timingSafeEqual(computed, stored)) throw INVALID_GRANT('PKCE verification failed');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const codeFamilyId = (authCode) => `code:${authCode.id ?? authCode._id}`;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A code that doesn't redeem may be one that already did (RFC 6749 §4.1.2): someone else holds it.
|
|
37
|
+
* Everything issued from its first redemption is revoked.
|
|
38
|
+
*/
|
|
39
|
+
async function handleCodeReuse(state, codeHash) {
|
|
40
|
+
const repo = state.storage.authorizationCodeRepository;
|
|
41
|
+
if (typeof repo.findUsedByCodeHash !== 'function') return;
|
|
42
|
+
const used = await repo.findUsedByCodeHash(codeHash);
|
|
43
|
+
if (!used) return;
|
|
44
|
+
// Flag first: a redemption still in flight checks it after creating its session (assertCodeNotReused).
|
|
45
|
+
if (typeof repo.markReused === 'function') await repo.markReused(codeHash);
|
|
46
|
+
const revokedSessions = await revokeFamily(state, codeFamilyId(used), 'code_reuse_detected');
|
|
47
|
+
await auditLog(state.logger, state.hooks, 'OAUTH2_CODE_REUSE_DETECTED', { userId: String(used.userId), clientId: used.clientId, revokedSessions });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* An unredeemed code is a session waiting to happen, so whatever ended the user's sessions or
|
|
52
|
+
* withdrew the grant since it was issued must end it too: a code issued before "sign out everywhere"
|
|
53
|
+
* (logout-all, password reset/change, account deletion), or before the user's consent to this client
|
|
54
|
+
* was revoked — or revoked and granted again — is refused. Otherwise a code minted with a stolen token
|
|
55
|
+
* shortly before the victim reset their password still turns into a fresh, long-lived session.
|
|
56
|
+
*/
|
|
57
|
+
async function assertCodeStillAuthorized(state, user, authCode) {
|
|
58
|
+
// The session that authorized the code must still be live — it may have been signed out while the
|
|
59
|
+
// authorize request was in flight, after the code's other checks could see it.
|
|
60
|
+
const sessions = state.storage.sessionRepository;
|
|
61
|
+
if (authCode.sessionJti && typeof sessions.findByJti === 'function') {
|
|
62
|
+
const authorizing = await sessions.findByJti(authCode.sessionJti);
|
|
63
|
+
// A row retired by a normal refresh is fine as long as its session carries on (a live row in
|
|
64
|
+
// the same family); revoked any other way — logout, sign-out-everywhere, reuse — it is not.
|
|
65
|
+
const rotatedButLive = authorizing?.revokedAt && authorizing.revokeReason === 'rotated'
|
|
66
|
+
&& await sessions.isFamilyLive(familyOf(authorizing).familyId);
|
|
67
|
+
if (!authorizing || (authorizing.revokedAt && !rotatedButLive)) throw INVALID_GRANT('Authorization code was revoked');
|
|
68
|
+
}
|
|
69
|
+
// Counters, not timestamps: the code may have been issued on another server than this one.
|
|
70
|
+
// A missing epoch or version (an adapter that doesn't persist them) refuses rather than passes.
|
|
71
|
+
if (!Number.isInteger(user.sessionEpoch) || user.sessionEpoch > (authCode.sessionEpoch ?? 0)) throw INVALID_GRANT('Authorization code was revoked');
|
|
72
|
+
|
|
73
|
+
const consent = await state.storage.consentRepository.find(user.id, authCode.clientId);
|
|
74
|
+
const live = consent && !(consent.expiresAt && new Date(consent.expiresAt) <= new Date());
|
|
75
|
+
const covered = live && (authCode.scopes || []).every((s) => (consent.scopes || []).includes(s));
|
|
76
|
+
if (!covered || !Number.isInteger(consent.version) || consent.version !== authCode.consentVersion) throw INVALID_GRANT('Authorization code was revoked');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* After the code's session row exists: a replay of the same code that raced this redemption flags the
|
|
81
|
+
* code (handleCodeReuse) and revokes its family — possibly before this row was inserted, so it must be
|
|
82
|
+
* checked here too.
|
|
83
|
+
*/
|
|
84
|
+
async function assertCodeNotReused(state, codeHash, familyId, newTokenHash) {
|
|
85
|
+
const repo = state.storage.authorizationCodeRepository;
|
|
86
|
+
const flagged = typeof repo.findUsedByCodeHash === 'function' && (await repo.findUsedByCodeHash(codeHash))?.reuseDetectedAt;
|
|
87
|
+
if (flagged || await state.storage.sessionRepository.isFamilyRevoked(familyId)) {
|
|
88
|
+
await state.storage.sessionRepository.revokeByRefreshTokenHash(newTokenHash, { onlyIfActive: false });
|
|
89
|
+
throw INVALID_GRANT('Authorization code was already used');
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A client must be explicitly registered for the grant it's trying to use — `allowedGrants` isn't decorative. */
|
|
94
|
+
function assertGrantAllowed(client, grantType) {
|
|
95
|
+
if (!client.allowedGrants?.includes(grantType)) {
|
|
96
|
+
throw new IdpError({ code: 'UNAUTHORIZED_CLIENT', httpStatus: 400, message: `Client is not authorized to use grant_type "${grantType}"` });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** RFC 6749 §5.1: token responses MUST NOT be cached. Also applied to revoke/introspect. */
|
|
101
|
+
function noStore(res) {
|
|
102
|
+
res.set('Cache-Control', 'no-store');
|
|
103
|
+
res.set('Pragma', 'no-cache');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function limitTokenEndpoint(state, req) {
|
|
107
|
+
await enforceRateLimit(state, `oauth2-token:ip:${ipKey(req.ip)}`, state.config.rateLimiting.oauth2Token, { failMode: 'closed' });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** POST /oauth2/token */
|
|
111
|
+
export async function tokenHandler(req, res, next) {
|
|
112
|
+
try {
|
|
113
|
+
noStore(res);
|
|
114
|
+
const state = getState();
|
|
115
|
+
await limitTokenEndpoint(state, req);
|
|
116
|
+
const { grant_type } = req.body;
|
|
117
|
+
// `await` matters: without it a rejected grant escapes this try/catch, and on Express 4
|
|
118
|
+
// (which ignores returned promises) becomes an unhandledRejection that kills the process.
|
|
119
|
+
if (grant_type === 'authorization_code') return await handleAuthorizationCodeGrant(req, res, next);
|
|
120
|
+
if (grant_type === 'refresh_token') return await handleRefreshTokenGrant(req, res, next);
|
|
121
|
+
if (grant_type === 'client_credentials') return await handleClientCredentialsGrant(req, res, next);
|
|
122
|
+
throw new IdpError({ code: 'UNSUPPORTED_GRANT_TYPE', httpStatus: 400, message: `Unsupported grant_type: ${grant_type}` });
|
|
123
|
+
} catch (err) {
|
|
124
|
+
next(err);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function handleAuthorizationCodeGrant(req, res) {
|
|
129
|
+
const state = getState();
|
|
130
|
+
const { code, redirect_uri, code_verifier } = req.body;
|
|
131
|
+
if (!code || !redirect_uri) throw new IdpError({ code: 'MISSING_REQUIRED_FIELDS', httpStatus: 400, message: 'code and redirect_uri are required' });
|
|
132
|
+
|
|
133
|
+
const client = await authenticateClient(state, req);
|
|
134
|
+
assertGrantAllowed(client, GRANT_TYPES.AUTHORIZATION_CODE);
|
|
135
|
+
const { result: authCode, hash: codeHash } = await lookupByTokenHash(state, code, HASH_PURPOSES.AUTHORIZATION_CODE, (hash) => state.storage.authorizationCodeRepository.consumeByCodeHash(hash));
|
|
136
|
+
if (!authCode) {
|
|
137
|
+
for (const hash of opaqueTokenHashes(state, code, HASH_PURPOSES.AUTHORIZATION_CODE)) await handleCodeReuse(state, hash);
|
|
138
|
+
throw INVALID_GRANT('Invalid or expired authorization code');
|
|
139
|
+
}
|
|
140
|
+
if (authCode.clientId !== client.clientId) throw INVALID_GRANT('Authorization code was issued to another client');
|
|
141
|
+
if (authCode.redirectUri !== redirect_uri) throw INVALID_GRANT('redirect_uri mismatch');
|
|
142
|
+
verifyPkce(code_verifier, authCode);
|
|
143
|
+
|
|
144
|
+
const user = await state.storage.userRepository.findById(authCode.userId);
|
|
145
|
+
if (!isActiveAccount(user)) throw INVALID_GRANT('User account is not active');
|
|
146
|
+
await assertCodeStillAuthorized(state, user, authCode);
|
|
147
|
+
|
|
148
|
+
const scopes = authCode.scopes || [];
|
|
149
|
+
const accessTokenResult = await issueOAuth2AccessToken(state, user, client, scopes);
|
|
150
|
+
const refreshTokenValue = generateOpaqueToken();
|
|
151
|
+
const familyCreatedAt = new Date();
|
|
152
|
+
const refreshExpiresAt = cappedExpiry(state, familyCreatedAt, clientTtl(client, 'refreshTokenTTL', state.config.ttls.refreshToken));
|
|
153
|
+
|
|
154
|
+
const refreshTokenHash = hashOpaqueToken(state, refreshTokenValue, HASH_PURPOSES.REFRESH_TOKEN);
|
|
155
|
+
await state.storage.sessionRepository.createSession({
|
|
156
|
+
user: user.id, tokenHash: refreshTokenHash, expiresAt: refreshExpiresAt,
|
|
157
|
+
kid: accessTokenResult.kid, jti: accessTokenResult.jti, ipAddress: req.ip, deviceInfo: req.headers['user-agent'],
|
|
158
|
+
kind: SESSION_KINDS.OAUTH2, claims: { clientId: client.clientId, scopes },
|
|
159
|
+
// The code is the family root: if it is ever presented again, everything it produced is revoked.
|
|
160
|
+
familyId: codeFamilyId(authCode), familyCreatedAt, sessionEpoch: authCode.sessionEpoch ?? 0,
|
|
161
|
+
});
|
|
162
|
+
await assertCodeNotReused(state, codeHash, codeFamilyId(authCode), refreshTokenHash);
|
|
163
|
+
// A sign-out-everywhere that landed while this redemption was running ends it too.
|
|
164
|
+
await assertChainNotRevoked(state, user.id, authCode.sessionEpoch ?? 0, refreshTokenHash, codeFamilyId(authCode));
|
|
165
|
+
|
|
166
|
+
const idToken = scopes.includes('openid')
|
|
167
|
+
? await issueIdToken(state, user, client.clientId, authCode.nonce || undefined, {
|
|
168
|
+
scopes,
|
|
169
|
+
authTime: authCode.authTime ? Math.floor(new Date(authCode.authTime).getTime() / 1000) : undefined,
|
|
170
|
+
ttlSeconds: clientTtl(client, 'idTokenTTL', undefined),
|
|
171
|
+
})
|
|
172
|
+
: null;
|
|
173
|
+
|
|
174
|
+
await auditLog(state.logger, state.hooks, 'OAUTH2_TOKEN_ISSUED', { userId: String(user.id), clientId: client.clientId, grantType: 'authorization_code', scopes });
|
|
175
|
+
|
|
176
|
+
res.json({
|
|
177
|
+
access_token: accessTokenResult.token,
|
|
178
|
+
refresh_token: refreshTokenValue,
|
|
179
|
+
...(idToken ? { id_token: idToken.token } : {}),
|
|
180
|
+
token_type: 'Bearer',
|
|
181
|
+
expires_in: clientTtl(client, 'accessTokenTTL', state.config.ttls.accessToken),
|
|
182
|
+
scope: scopes.join(' '),
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function handleRefreshTokenGrant(req, res) {
|
|
187
|
+
const state = getState();
|
|
188
|
+
const { refresh_token } = req.body;
|
|
189
|
+
if (!refresh_token) throw new IdpError({ code: 'MISSING_REQUIRED_FIELDS', httpStatus: 400, message: 'refresh_token is required' });
|
|
190
|
+
|
|
191
|
+
const client = await authenticateClient(state, req);
|
|
192
|
+
assertGrantAllowed(client, GRANT_TYPES.REFRESH_TOKEN);
|
|
193
|
+
const tokenHash = await resolveRefreshTokenHash(state, refresh_token);
|
|
194
|
+
// Every check runs before the token is consumed, so a refusal doesn't burn it (see /refresh).
|
|
195
|
+
const row = await peekRefreshRow(state, tokenHash);
|
|
196
|
+
if (!row) {
|
|
197
|
+
await handleRefreshReuse(state, tokenHash);
|
|
198
|
+
throw INVALID_GRANT('Invalid or expired refresh token');
|
|
199
|
+
}
|
|
200
|
+
// RFC 6749 §6: a refresh token is bound to the client it was issued to. A first-party login's
|
|
201
|
+
// refresh token, or another client's, is refused — and revoked, since presenting it here means
|
|
202
|
+
// it leaked.
|
|
203
|
+
if (sessionKindOf(row) !== SESSION_KINDS.OAUTH2 || row.claims?.clientId !== client.clientId) {
|
|
204
|
+
await state.storage.sessionRepository.revokeByRefreshTokenHash(tokenHash, { reason: 'misused' });
|
|
205
|
+
state.logger?.warn?.({ clientId: client.clientId }, 'Refresh token presented by a client it was not issued to — refused and revoked');
|
|
206
|
+
throw INVALID_GRANT('Invalid or expired refresh token');
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const user = await state.storage.userRepository.findById(row.user);
|
|
210
|
+
if (!isActiveAccount(user)) throw INVALID_GRANT('User account is not active');
|
|
211
|
+
|
|
212
|
+
// Refreshing must never grant more than the user originally consented to — narrow the
|
|
213
|
+
// originally-granted scopes to whatever the client is still allowed, don't recompute from scratch.
|
|
214
|
+
const grantedScopes = row.claims?.scopes || [];
|
|
215
|
+
const allowedScopes = new Set(client.allowedScopes || []);
|
|
216
|
+
const scopes = grantedScopes.filter((s) => allowedScopes.has(s));
|
|
217
|
+
const { familyId, familyCreatedAt } = familyOf(row);
|
|
218
|
+
if (familyEndsAt(state, familyCreatedAt) <= new Date()) throw INVALID_GRANT('Refresh token has reached its maximum lifetime');
|
|
219
|
+
|
|
220
|
+
const existing = await state.storage.sessionRepository.revokeByRefreshTokenHash(tokenHash, { reason: 'rotated' });
|
|
221
|
+
if (!existing) {
|
|
222
|
+
await handleRefreshReuse(state, tokenHash);
|
|
223
|
+
throw INVALID_GRANT('Invalid or expired refresh token');
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const accessTokenResult = await issueOAuth2AccessToken(state, user, client, scopes);
|
|
227
|
+
const newRefreshTokenValue = generateOpaqueToken();
|
|
228
|
+
const newTokenHash = hashOpaqueToken(state, newRefreshTokenValue, HASH_PURPOSES.REFRESH_TOKEN);
|
|
229
|
+
const refreshExpiresAt = cappedExpiry(state, familyCreatedAt, clientTtl(client, 'refreshTokenTTL', state.config.ttls.refreshToken));
|
|
230
|
+
|
|
231
|
+
await state.storage.sessionRepository.createSession({
|
|
232
|
+
user: user.id, tokenHash: newTokenHash, expiresAt: refreshExpiresAt,
|
|
233
|
+
kid: accessTokenResult.kid, jti: accessTokenResult.jti, ipAddress: req.ip, deviceInfo: req.headers['user-agent'],
|
|
234
|
+
kind: SESSION_KINDS.OAUTH2, claims: { clientId: client.clientId, scopes }, familyId, familyCreatedAt,
|
|
235
|
+
sessionEpoch: existing.sessionEpoch ?? 0,
|
|
236
|
+
});
|
|
237
|
+
await assertChainNotRevoked(state, user.id, existing.sessionEpoch ?? 0, newTokenHash, familyId);
|
|
238
|
+
await assertFamilyNotRevoked(state, familyId, newTokenHash);
|
|
239
|
+
|
|
240
|
+
if (existing.jti) await state.cache.set(`${CACHE_KEY_PREFIXES.REVOKED_REFRESH_TOKEN}:${existing.jti}`, '1', state.config.ttls.revocationCache);
|
|
241
|
+
|
|
242
|
+
await auditLog(state.logger, state.hooks, 'OAUTH2_TOKEN_ISSUED', { userId: String(user.id), clientId: client.clientId, grantType: 'refresh_token' });
|
|
243
|
+
|
|
244
|
+
res.json({
|
|
245
|
+
access_token: accessTokenResult.token, refresh_token: newRefreshTokenValue, token_type: 'Bearer',
|
|
246
|
+
expires_in: clientTtl(client, 'accessTokenTTL', state.config.ttls.accessToken), scope: scopes.join(' '),
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* RFC 6749 §4.4 — machine-to-machine grant, no end user involved. The
|
|
252
|
+
* client authenticates as itself and gets a token representing itself, not
|
|
253
|
+
* a resource owner. Confidential clients only (a public client can't prove
|
|
254
|
+
* its own identity without a secret, and there's no PKCE equivalent for
|
|
255
|
+
* this grant). No refresh token is issued, per spec — the client just
|
|
256
|
+
* re-authenticates with its credentials whenever it needs a new one.
|
|
257
|
+
*/
|
|
258
|
+
async function handleClientCredentialsGrant(req, res) {
|
|
259
|
+
const state = getState();
|
|
260
|
+
const { scope } = req.body;
|
|
261
|
+
|
|
262
|
+
const client = await authenticateClient(state, req, { requireConfidential: true });
|
|
263
|
+
assertGrantAllowed(client, GRANT_TYPES.CLIENT_CREDENTIALS);
|
|
264
|
+
|
|
265
|
+
const allowed = new Set(client.allowedScopes || []);
|
|
266
|
+
const requestedScopes = scope ? scope.split(' ').filter(Boolean) : [...allowed];
|
|
267
|
+
const invalidScopes = requestedScopes.filter((s) => !allowed.has(s));
|
|
268
|
+
if (invalidScopes.length > 0) {
|
|
269
|
+
throw new IdpError({ code: 'INVALID_SCOPE', httpStatus: 400, message: `Requested scopes not allowed: ${invalidScopes.join(', ')}` });
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// No user, no refresh token, no session row — marked sessionless so the
|
|
273
|
+
// per-request session check doesn't refuse it.
|
|
274
|
+
const accessTokenResult = await issueOAuth2AccessToken(state, { id: client.clientId }, client, requestedScopes, { sessionless: true, grantType: GRANT_TYPES.CLIENT_CREDENTIALS });
|
|
275
|
+
|
|
276
|
+
await auditLog(state.logger, state.hooks, 'OAUTH2_TOKEN_ISSUED', { clientId: client.clientId, grantType: 'client_credentials', scopes: requestedScopes });
|
|
277
|
+
|
|
278
|
+
res.json({
|
|
279
|
+
access_token: accessTokenResult.token,
|
|
280
|
+
token_type: 'Bearer',
|
|
281
|
+
expires_in: clientTtl(client, 'accessTokenTTL', state.config.ttls.accessToken),
|
|
282
|
+
scope: requestedScopes.join(' '),
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const looksLikeJwt = (token) => /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token);
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Resolves a token presented to revoke/introspect to its OAuth2 session row — but only a token issued
|
|
290
|
+
* to `client`. First-party tokens and other clients' tokens resolve to nothing.
|
|
291
|
+
*/
|
|
292
|
+
async function findClientSession(state, client, token) {
|
|
293
|
+
const sessions = state.storage.sessionRepository;
|
|
294
|
+
if (looksLikeJwt(token)) {
|
|
295
|
+
let payload;
|
|
296
|
+
try {
|
|
297
|
+
payload = await verifyAccessToken(state, token, { accept: [ACCESS_TOKEN_KINDS.OAUTH2_USER, ACCESS_TOKEN_KINDS.OAUTH2_CLIENT] });
|
|
298
|
+
} catch {
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
if (payload.client_id !== client.clientId) return null;
|
|
302
|
+
if (payload.sessionless) return { payload, session: null };
|
|
303
|
+
if (typeof sessions.findByJti !== 'function') return null;
|
|
304
|
+
const session = await sessions.findByJti(payload.jti);
|
|
305
|
+
return session ? { payload, session } : null;
|
|
306
|
+
}
|
|
307
|
+
const { result: session } = await lookupByTokenHash(state, token, HASH_PURPOSES.REFRESH_TOKEN, (hash) => sessions.findByRefreshTokenHash(hash));
|
|
308
|
+
if (!session || sessionKindOf(session) !== SESSION_KINDS.OAUTH2 || session.claims?.clientId !== client.clientId) return null;
|
|
309
|
+
return { payload: null, session };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* POST /oauth2/token/revoke — RFC 7009. The client must authenticate (a public client by its id),
|
|
314
|
+
* and only tokens issued to it are revoked; anything else is silently ignored. Always 200.
|
|
315
|
+
*/
|
|
316
|
+
export async function revokeTokenHandler(req, res, next) {
|
|
317
|
+
try {
|
|
318
|
+
noStore(res);
|
|
319
|
+
const state = getState();
|
|
320
|
+
await limitTokenEndpoint(state, req);
|
|
321
|
+
const client = await authenticateClient(state, req);
|
|
322
|
+
|
|
323
|
+
const found = await findClientSession(state, client, req.body.token);
|
|
324
|
+
if (found?.session && !found.session.revokedAt) {
|
|
325
|
+
const sessions = state.storage.sessionRepository;
|
|
326
|
+
if (found.payload) await sessions.revokeById(found.session.id, found.session.user);
|
|
327
|
+
else await sessions.revokeByRefreshTokenHash(await resolveRefreshTokenHash(state, req.body.token), { onlyIfActive: false });
|
|
328
|
+
if (found.session.jti) await state.cache.set(`${CACHE_KEY_PREFIXES.REVOKED_REFRESH_TOKEN}:${found.session.jti}`, '1', state.config.ttls.revocationCache);
|
|
329
|
+
await auditLog(state.logger, state.hooks, 'OAUTH2_TOKEN_REVOKED', { clientId: client.clientId, userId: String(found.session.user) });
|
|
330
|
+
}
|
|
331
|
+
res.status(200).json({ status: 'ok' });
|
|
332
|
+
} catch (err) {
|
|
333
|
+
next(err);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* POST /oauth2/token/introspect — RFC 7662. Callable only by an authenticated confidential client
|
|
339
|
+
* (a resource server registered as a client), and it describes only tokens issued to that client;
|
|
340
|
+
* anything else is `{ active: false }`. Handles both access tokens (JWT) and refresh tokens.
|
|
341
|
+
*/
|
|
342
|
+
export async function introspectTokenHandler(req, res, next) {
|
|
343
|
+
try {
|
|
344
|
+
noStore(res);
|
|
345
|
+
const state = getState();
|
|
346
|
+
await limitTokenEndpoint(state, req);
|
|
347
|
+
const client = await authenticateClient(state, req, { requireConfidential: true });
|
|
348
|
+
|
|
349
|
+
const found = await findClientSession(state, client, req.body.token);
|
|
350
|
+
const session = found?.session;
|
|
351
|
+
const live = session ? !session.revokedAt && new Date(session.expiresAt) > new Date() : Boolean(found?.payload);
|
|
352
|
+
if (!found || !live) return res.json({ active: false });
|
|
353
|
+
|
|
354
|
+
if (found.payload) {
|
|
355
|
+
const p = found.payload;
|
|
356
|
+
return res.json({ active: true, token_type: 'access_token', client_id: p.client_id, sub: p.sub, scope: p.scope, exp: p.exp, iat: p.iat, iss: p.iss, aud: p.aud, jti: p.jti });
|
|
357
|
+
}
|
|
358
|
+
res.json({
|
|
359
|
+
active: true,
|
|
360
|
+
token_type: 'refresh_token',
|
|
361
|
+
client_id: client.clientId,
|
|
362
|
+
sub: String(session.user),
|
|
363
|
+
scope: (session.claims?.scopes || []).join(' '),
|
|
364
|
+
exp: Math.floor(new Date(session.expiresAt).getTime() / 1000),
|
|
365
|
+
iat: Math.floor(new Date(session.createdAt).getTime() / 1000),
|
|
366
|
+
});
|
|
367
|
+
} catch (err) {
|
|
368
|
+
next(err);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { getState } from '../config/state.js';
|
|
2
|
+
|
|
3
|
+
/** GET /.well-known/openid-configuration */
|
|
4
|
+
export function openidConfigurationHandler(req, res) {
|
|
5
|
+
const state = getState();
|
|
6
|
+
const issuer = state.config.issuer;
|
|
7
|
+
|
|
8
|
+
res.set('Cache-Control', `public, max-age=${state.config.ttls.discoveryCache}`).json({
|
|
9
|
+
issuer,
|
|
10
|
+
authorization_endpoint: `${issuer}/oauth2/authorize`,
|
|
11
|
+
token_endpoint: `${issuer}/oauth2/token`,
|
|
12
|
+
userinfo_endpoint: `${issuer}/userinfo`,
|
|
13
|
+
jwks_uri: `${issuer}/.well-known/jwks.json`,
|
|
14
|
+
end_session_endpoint: `${issuer}/session/end`,
|
|
15
|
+
revocation_endpoint: `${issuer}/oauth2/token/revoke`,
|
|
16
|
+
introspection_endpoint: `${issuer}/oauth2/token/introspect`,
|
|
17
|
+
response_types_supported: ['code'],
|
|
18
|
+
grant_types_supported: ['authorization_code', 'refresh_token', 'client_credentials'],
|
|
19
|
+
subject_types_supported: ['public'],
|
|
20
|
+
id_token_signing_alg_values_supported: ['RS256'],
|
|
21
|
+
token_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post', 'none'],
|
|
22
|
+
revocation_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post', 'none'],
|
|
23
|
+
introspection_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post'],
|
|
24
|
+
scopes_supported: ['openid', 'email', 'profile'],
|
|
25
|
+
claims_supported: [
|
|
26
|
+
'sub', 'iss', 'aud', 'azp', 'exp', 'iat', 'jti', 'nonce', 'auth_time',
|
|
27
|
+
'email', 'email_verified',
|
|
28
|
+
'name', 'given_name', 'family_name', 'picture', 'locale', 'zoneinfo', 'updated_at',
|
|
29
|
+
],
|
|
30
|
+
code_challenge_methods_supported: ['S256'],
|
|
31
|
+
prompt_values_supported: ['none', 'login', 'consent', 'select_account'],
|
|
32
|
+
authorization_response_iss_parameter_supported: true,
|
|
33
|
+
request_parameter_supported: false,
|
|
34
|
+
claims_parameter_supported: false,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { getState } from '../config/state.js';
|
|
2
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
3
|
+
import { verifyIssuedToken, isIdTokenPayload } from '../signing/token.service.js';
|
|
4
|
+
import { OAUTH_CLIENT_STATUS, CACHE_KEY_PREFIXES, SESSION_KINDS } from '../config/constants.js';
|
|
5
|
+
import { auditLog } from '../hooks/index.js';
|
|
6
|
+
import { clearSessionCookies } from '../password-auth/controllers.js';
|
|
7
|
+
import { assertTrustedOrigin } from '../middleware/csrf.js';
|
|
8
|
+
import { readRefreshCookie } from '../utils/cookies.js';
|
|
9
|
+
import { sessionKindOf } from '../utils/session-kind.js';
|
|
10
|
+
import { familyOf, peekRefreshRow, resolveRefreshTokenHash, revokeFamily } from '../utils/session-family.js';
|
|
11
|
+
|
|
12
|
+
/** What a GET needing confirmation forwards to oidc.endSessionConfirmationUrl. */
|
|
13
|
+
const CONFIRMATION_PARAMS = ['client_id', 'state', 'ui_locales', 'logout_hint'];
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The browser's own first-party session row: the one behind its access token (`req.auth`) — or, once
|
|
17
|
+
* that short-lived cookie has expired, the one behind its refresh cookie. Null when there is none.
|
|
18
|
+
*/
|
|
19
|
+
async function ownSessionRow(state, req) {
|
|
20
|
+
const sessions = state.storage.sessionRepository;
|
|
21
|
+
if (req.auth?.userId && req.auth.tokenMeta?.jti && !req.auth.tokenMeta.sessionless && typeof sessions.findByJti === 'function') {
|
|
22
|
+
const row = await sessions.findByJti(req.auth.tokenMeta.jti);
|
|
23
|
+
if (row && !row.revokedAt && String(row.user) === String(req.auth.userId)) return row;
|
|
24
|
+
}
|
|
25
|
+
const raw = readRefreshCookie(state, req);
|
|
26
|
+
if (!raw) return null;
|
|
27
|
+
const row = await peekRefreshRow(state, await resolveRefreshTokenHash(state, raw));
|
|
28
|
+
return row && sessionKindOf(row) === SESSION_KINDS.FIRST_PARTY ? row : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* GET|POST /session/end — RP-initiated logout (OIDC RP-Initiated Logout 1.0).
|
|
33
|
+
*
|
|
34
|
+
* What it ends is deliberately narrow, because a GET is something any site can trigger:
|
|
35
|
+
* - the browser's own IdP session (the first-party session whose cookie came with the request) —
|
|
36
|
+
* on a GET only with an `id_token_hint` for that same user (the relying party the user signed in
|
|
37
|
+
* to asked for it). Without one, a GET ends nothing and answers
|
|
38
|
+
* `{ action: 'logout_confirmation_required' }`: the IdP's frontend asks the user, then POSTs the
|
|
39
|
+
* same parameters (JSON or form) from a trusted origin (`cookies.trustedOrigins`) to end it;
|
|
40
|
+
* - with an `id_token_hint` AND the browser signed in as that same user, the hinted relying party's
|
|
41
|
+
* sessions for that user. A hint alone ends nothing: ID tokens travel through URLs and logs, and
|
|
42
|
+
* whoever holds one must not be able to sign its user out of the relying party.
|
|
43
|
+
* It never signs the user out of every device: an ID token is handed to every relying party, so
|
|
44
|
+
* possessing one — or tricking a browser into this URL — must not be a kill switch for all of the
|
|
45
|
+
* user's sessions. "Log out everywhere" remains `POST /session/logout/all`.
|
|
46
|
+
*
|
|
47
|
+
* `id_token_hint` must be an ID token this IdP issued (an access or MFA-challenge token is refused);
|
|
48
|
+
* an expired one is accepted, as the spec recommends. `post_logout_redirect_uri` must be registered
|
|
49
|
+
* to the hinted client.
|
|
50
|
+
*/
|
|
51
|
+
export async function endSessionHandler(req, res, next) {
|
|
52
|
+
try {
|
|
53
|
+
const state = getState();
|
|
54
|
+
const confirmed = req.method === 'POST';
|
|
55
|
+
// A POST is the confirmation: it must come from the IdP's own pages (or a trusted frontend).
|
|
56
|
+
if (confirmed) assertTrustedOrigin(state, req);
|
|
57
|
+
const q = (confirmed ? req.body : req.query) ?? {};
|
|
58
|
+
const idTokenHint = typeof q.id_token_hint === 'string' ? q.id_token_hint : undefined;
|
|
59
|
+
const postLogoutRedirectUri = typeof q.post_logout_redirect_uri === 'string' ? q.post_logout_redirect_uri : undefined;
|
|
60
|
+
const oidcState = typeof q.state === 'string' ? q.state : undefined;
|
|
61
|
+
|
|
62
|
+
const own = await ownSessionRow(state, req);
|
|
63
|
+
const signedInUserId = req.auth?.userId ?? (own ? String(own.user) : undefined);
|
|
64
|
+
|
|
65
|
+
let hint = null;
|
|
66
|
+
if (idTokenHint) {
|
|
67
|
+
hint = verifyIssuedToken(state, idTokenHint, { issuer: state.config.issuer, ignoreExpiration: true });
|
|
68
|
+
if (!isIdTokenPayload(state, hint)) throw new IdpError({ code: 'INVALID_REQUEST', httpStatus: 400, message: 'Invalid id_token_hint' });
|
|
69
|
+
if (signedInUserId && String(signedInUserId) !== String(hint.sub)) {
|
|
70
|
+
throw new IdpError({ code: 'INVALID_REQUEST', httpStatus: 400, message: 'id_token_hint does not belong to the signed-in user' });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (postLogoutRedirectUri) {
|
|
75
|
+
if (!hint) {
|
|
76
|
+
throw new IdpError({ code: 'INVALID_REQUEST', httpStatus: 400, message: 'id_token_hint is required when post_logout_redirect_uri is supplied' });
|
|
77
|
+
}
|
|
78
|
+
const client = await state.storage.oauthClientRepository.findByClientId(hint.aud);
|
|
79
|
+
if (!client || client.status !== OAUTH_CLIENT_STATUS.ACTIVE) {
|
|
80
|
+
throw new IdpError({ code: 'OAUTH_CLIENT_NOT_FOUND', httpStatus: 400, message: 'Unknown or inactive client' });
|
|
81
|
+
}
|
|
82
|
+
const allowed = client.postLogoutRedirectUris?.length ? client.postLogoutRedirectUris : client.redirectUris;
|
|
83
|
+
if (!allowed?.includes(postLogoutRedirectUri)) {
|
|
84
|
+
throw new IdpError({ code: 'INVALID_REDIRECT_URI', httpStatus: 400, message: 'post_logout_redirect_uri is not registered for this client' });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Signed in, and nothing shows the user asked for this: ask them first — on the IdP's
|
|
89
|
+
// confirmation page when one is configured (the browser was sent here by a relying party), with
|
|
90
|
+
// the request's parameters so the page can POST them back.
|
|
91
|
+
if (signedInUserId && !hint && !confirmed) {
|
|
92
|
+
res.set('Cache-Control', 'no-store');
|
|
93
|
+
const page = state.config.oidc?.endSessionConfirmationUrl;
|
|
94
|
+
if (page) {
|
|
95
|
+
// Only the RP-initiated-logout parameters the page needs to POST back, never overriding
|
|
96
|
+
// ones the configured URL already has.
|
|
97
|
+
const url = new URL(page);
|
|
98
|
+
for (const k of CONFIRMATION_PARAMS) {
|
|
99
|
+
if (typeof q[k] === 'string' && !url.searchParams.has(k)) url.searchParams.set(k, q[k]);
|
|
100
|
+
}
|
|
101
|
+
return res.redirect(url.toString());
|
|
102
|
+
}
|
|
103
|
+
return res.status(200).json({ action: 'logout_confirmation_required' });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const sessions = state.storage.sessionRepository;
|
|
107
|
+
const revokedJtis = [];
|
|
108
|
+
|
|
109
|
+
// The browser's own IdP session — its whole refresh family, so no rotated sibling carries on.
|
|
110
|
+
if (own) {
|
|
111
|
+
const revoked = await revokeFamily(state, familyOf(own).familyId, 'end_session');
|
|
112
|
+
if (!revoked && (await sessions.revokeById(own.id, own.user)) && own.jti) revokedJtis.push(own.jti);
|
|
113
|
+
}
|
|
114
|
+
if (signedInUserId) clearSessionCookies(req, res, state);
|
|
115
|
+
// The hinted relying party's sessions for this user — only on the user's own browser session.
|
|
116
|
+
if (hint && signedInUserId && typeof sessions.revokeForClient === 'function') {
|
|
117
|
+
const { jtis } = await sessions.revokeForClient(hint.aud, { userId: hint.sub });
|
|
118
|
+
revokedJtis.push(...jtis);
|
|
119
|
+
}
|
|
120
|
+
for (const jti of revokedJtis) {
|
|
121
|
+
await state.cache.set(`${CACHE_KEY_PREFIXES.REVOKED_REFRESH_TOKEN}:${jti}`, '1', state.config.ttls.revocationCache);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const userId = signedInUserId ?? hint?.sub;
|
|
125
|
+
if (userId) await auditLog(state.logger, state.hooks, 'END_SESSION', { userId: String(userId), clientId: hint?.aud ?? null, revokedSessions: revokedJtis.length });
|
|
126
|
+
|
|
127
|
+
if (postLogoutRedirectUri) {
|
|
128
|
+
const redirectUrl = new URL(postLogoutRedirectUri);
|
|
129
|
+
if (oidcState) redirectUrl.searchParams.set('state', oidcState);
|
|
130
|
+
return res.redirect(redirectUrl.toString());
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
res.json({ status: 'ok' });
|
|
134
|
+
} catch (err) {
|
|
135
|
+
next(err);
|
|
136
|
+
}
|
|
137
|
+
}
|