@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.
- package/.env.example +159 -0
- package/CHANGELOG.md +58 -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 +48 -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 +777 -0
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { getState } from '../config/state.js';
|
|
3
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
4
|
+
import { OAUTH_CLIENT_STATUS, CLIENT_TYPES, CACHE_KEY_PREFIXES } from '../config/constants.js';
|
|
5
|
+
import { hashOpaqueToken, HASH_PURPOSES } from '../signing/token.service.js';
|
|
6
|
+
import { auditLog } from '../hooks/index.js';
|
|
7
|
+
import { currentSessionEpoch } from '../utils/session-family.js';
|
|
8
|
+
import { createLoginChallenge, redeemLoginChallenge } from './login-challenge.js';
|
|
9
|
+
|
|
10
|
+
function validateRedirectUri(client, redirectUri) {
|
|
11
|
+
if (!client.redirectUris?.includes(redirectUri)) {
|
|
12
|
+
throw new IdpError({ code: 'INVALID_REDIRECT_URI', httpStatus: 400, message: 'Invalid redirect_uri' });
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function validateScopes(client, requestedScopes) {
|
|
17
|
+
const allowed = new Set(client.allowedScopes || []);
|
|
18
|
+
const invalid = requestedScopes.filter((s) => !allowed.has(s));
|
|
19
|
+
if (invalid.length > 0) {
|
|
20
|
+
throw new IdpError({ code: 'INVALID_REQUEST', httpStatus: 400, message: `Requested scopes not allowed: ${invalid.join(', ')}` });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function loadActiveClient(state, clientId) {
|
|
25
|
+
const client = await state.storage.oauthClientRepository.findByClientId(clientId);
|
|
26
|
+
if (!client || client.status !== OAUTH_CLIENT_STATUS.ACTIVE) {
|
|
27
|
+
throw new IdpError({ code: 'OAUTH_CLIENT_NOT_FOUND', httpStatus: 400, message: 'Unknown or inactive client' });
|
|
28
|
+
}
|
|
29
|
+
return client;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* PKCE is required for public clients always (RFC 9700 §2.1.1), and for every client unless
|
|
34
|
+
* `config.oauth2.requirePkce` is `'public'`: without it a confidential client is still open to
|
|
35
|
+
* authorization-code injection.
|
|
36
|
+
*/
|
|
37
|
+
function assertPkce(state, client, codeChallenge) {
|
|
38
|
+
const required = client.clientType === CLIENT_TYPES.PUBLIC || state.config.oauth2.requirePkce !== 'public';
|
|
39
|
+
if (required && !codeChallenge) {
|
|
40
|
+
throw new IdpError({ code: 'INVALID_REQUEST', httpStatus: 400, message: 'code_challenge (PKCE, S256) is required' });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function issueAuthorizationCode(state, { clientId, userId, redirectUri, scopes, codeChallenge, nonce, authTime, sessionJti, consentVersion }) {
|
|
45
|
+
const code = crypto.randomBytes(32).toString('hex');
|
|
46
|
+
const sessionEpoch = await currentSessionEpoch(state, userId);
|
|
47
|
+
await state.storage.authorizationCodeRepository.create({
|
|
48
|
+
code: hashOpaqueToken(state, code, HASH_PURPOSES.AUTHORIZATION_CODE),
|
|
49
|
+
clientId,
|
|
50
|
+
userId,
|
|
51
|
+
redirectUri,
|
|
52
|
+
scopes,
|
|
53
|
+
codeChallenge: codeChallenge || null,
|
|
54
|
+
codeChallengeMethod: codeChallenge ? 'S256' : null,
|
|
55
|
+
nonce: nonce || null,
|
|
56
|
+
authTime: authTime ? new Date(authTime * 1000) : null,
|
|
57
|
+
// The session that authorized it — revoked before redemption (a sign-out landing while this
|
|
58
|
+
// request was in flight), the code is refused.
|
|
59
|
+
sessionJti: sessionJti ?? null,
|
|
60
|
+
// Redemption refuses the code if the user's sessions were revoked, or the consent changed, since.
|
|
61
|
+
sessionEpoch,
|
|
62
|
+
consentVersion: consentVersion ?? 0,
|
|
63
|
+
expiresAt: new Date(Date.now() + state.config.ttls.authCode * 1000),
|
|
64
|
+
used: false,
|
|
65
|
+
});
|
|
66
|
+
return code;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Redirects to the client with the response params plus `iss` (RFC 9207 — lets the client detect a mix-up between authorization servers). */
|
|
70
|
+
function redirectToClient(res, state, redirectUri, params) {
|
|
71
|
+
const url = new URL(redirectUri);
|
|
72
|
+
for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== null) url.searchParams.set(k, v);
|
|
73
|
+
url.searchParams.set('iss', state.config.issuer);
|
|
74
|
+
res.redirect(url.toString());
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const PROMPT_VALUES = new Set(['none', 'login', 'consent', 'select_account']);
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* `prompt` and `max_age` (OIDC Core §3.1.2.1). Unknown prompt values, or `none` with another, are
|
|
81
|
+
* refused. `select_account` is treated as `login` (there is no account chooser: signing in again is
|
|
82
|
+
* how the user picks an account). `max_age=0` means `prompt=login`.
|
|
83
|
+
*/
|
|
84
|
+
function resolvePrompt(q) {
|
|
85
|
+
const values = new Set(String(q.prompt ?? '').split(' ').filter(Boolean));
|
|
86
|
+
for (const v of values) {
|
|
87
|
+
if (!PROMPT_VALUES.has(v)) throw new IdpError({ code: 'INVALID_REQUEST', httpStatus: 400, message: `Unsupported prompt value: ${v}` });
|
|
88
|
+
}
|
|
89
|
+
if (values.has('none') && values.size > 1) throw new IdpError({ code: 'INVALID_REQUEST', httpStatus: 400, message: 'prompt=none cannot be combined with other values' });
|
|
90
|
+
const maxAge = q.max_age === undefined ? undefined : Number(q.max_age);
|
|
91
|
+
return {
|
|
92
|
+
none: values.has('none'),
|
|
93
|
+
login: values.has('login') || values.has('select_account') || maxAge === 0,
|
|
94
|
+
consent: values.has('consent'),
|
|
95
|
+
maxAge: maxAge === 0 ? undefined : maxAge,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Why the request needs a (new) login, or null: not signed in, or the login is older than prompt/max_age allow. */
|
|
100
|
+
function loginRequiredReason(req, prompt, challengeRedeemed) {
|
|
101
|
+
if (!req.auth?.userId) return 'unauthenticated';
|
|
102
|
+
// A login made for this very request (see login-challenge.js) satisfies prompt=login (and max_age=0);
|
|
103
|
+
// a positive max_age still holds it to its age, so the ID token's auth_time passes the client's check.
|
|
104
|
+
if (prompt.login && !challengeRedeemed) return 'prompt_login';
|
|
105
|
+
const authTime = req.auth.tokenMeta?.authTime;
|
|
106
|
+
const age = Number.isInteger(authTime) ? Math.floor(Date.now() / 1000) - authTime : Infinity;
|
|
107
|
+
if (prompt.maxAge !== undefined && !(age <= prompt.maxAge)) return 'max_age';
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The session behind the request's token — none for a sessionless token (the public issueAccessToken export). */
|
|
112
|
+
const sessionJtiOf = (req) => (req.auth?.tokenMeta?.sessionless ? null : req.auth?.tokenMeta?.jti ?? null);
|
|
113
|
+
|
|
114
|
+
const consentKey = (challenge) => `${CACHE_KEY_PREFIXES.OAUTH_CONSENT}:${challenge}`;
|
|
115
|
+
const INVALID_CONSENT = () => new IdpError({ code: 'INVALID_CONSENT_CHALLENGE', httpStatus: 400, message: 'Invalid or expired consent challenge — restart authorization' });
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* GET /oauth2/authorize
|
|
119
|
+
*
|
|
120
|
+
* Validates the request. When the user has already consented to every requested scope, issues the
|
|
121
|
+
* code straight away. Otherwise it answers `consent_required` with a `consent_challenge`: the whole
|
|
122
|
+
* validated request is stored server-side under that single-use, user-bound id, and confirm/deny
|
|
123
|
+
* act on exactly that request — never on parameters supplied again at confirm time. That's what
|
|
124
|
+
* stops a forged confirm (CSRF, or a script on a sibling origin) from granting an arbitrary client
|
|
125
|
+
* arbitrary scopes with a redirect of the attacker's choosing: it would need a challenge only the
|
|
126
|
+
* user's own consent page received.
|
|
127
|
+
*/
|
|
128
|
+
export async function authorizeHandler(req, res, next) {
|
|
129
|
+
try {
|
|
130
|
+
const state = getState();
|
|
131
|
+
const q = req.validatedQuery || req.query;
|
|
132
|
+
const { client_id, redirect_uri, scope, state: oauthState, nonce, code_challenge, response_type } = q;
|
|
133
|
+
|
|
134
|
+
if (response_type !== 'code') {
|
|
135
|
+
throw new IdpError({ code: 'INVALID_REQUEST', httpStatus: 400, message: 'Only response_type=code is supported' });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const client = await loadActiveClient(state, client_id);
|
|
139
|
+
validateRedirectUri(client, redirect_uri);
|
|
140
|
+
|
|
141
|
+
const requestedScopes = (scope || 'openid').split(' ').filter(Boolean);
|
|
142
|
+
if (requestedScopes.length === 0) throw new IdpError({ code: 'INVALID_REQUEST', httpStatus: 400, message: 'scope must name at least one scope' });
|
|
143
|
+
validateScopes(client, requestedScopes);
|
|
144
|
+
assertPkce(state, client, code_challenge);
|
|
145
|
+
|
|
146
|
+
const prompt = resolvePrompt(q);
|
|
147
|
+
const fresh = q.login_challenge ? await redeemLoginChallenge(state, req, q.login_challenge, client_id) : false;
|
|
148
|
+
const loginReason = loginRequiredReason(req, prompt, fresh);
|
|
149
|
+
if (loginReason) {
|
|
150
|
+
// prompt=none: the client asked for no UI, so the answer goes back to it (redirect_uri is validated).
|
|
151
|
+
if (prompt.none) return redirectToClient(res, state, redirect_uri, { error: 'login_required', state: oauthState });
|
|
152
|
+
// A login this request will accept must be made for it: hand out the challenge to bind it to.
|
|
153
|
+
const needsFreshLogin = prompt.login || prompt.maxAge !== undefined;
|
|
154
|
+
return res.status(401).json({
|
|
155
|
+
action: 'login_required', reason: loginReason,
|
|
156
|
+
...(needsFreshLogin ? { login_challenge: await createLoginChallenge(state, client_id) } : {}),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const pending = {
|
|
161
|
+
userId: req.auth.userId, clientId: client_id, redirectUri: redirect_uri, scopes: requestedScopes,
|
|
162
|
+
state: oauthState ?? null, nonce: nonce ?? null, codeChallenge: code_challenge ?? null,
|
|
163
|
+
authTime: req.auth.tokenMeta?.authTime ?? null,
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
const existingConsent = await state.storage.consentRepository.find(req.auth.userId, client_id);
|
|
167
|
+
const consentLive = existingConsent && !(existingConsent.expiresAt && new Date(existingConsent.expiresAt) <= new Date());
|
|
168
|
+
const consentedScopes = new Set(consentLive ? existingConsent.scopes || [] : []);
|
|
169
|
+
const missingScopes = requestedScopes.filter((s) => !consentedScopes.has(s));
|
|
170
|
+
|
|
171
|
+
if (missingScopes.length > 0 || prompt.consent) {
|
|
172
|
+
if (prompt.none) return redirectToClient(res, state, redirect_uri, { error: 'consent_required', state: oauthState });
|
|
173
|
+
const consentChallenge = crypto.randomBytes(32).toString('base64url');
|
|
174
|
+
await state.cache.set(consentKey(consentChallenge), pending, state.config.ttls.authCode);
|
|
175
|
+
res.set('Cache-Control', 'no-store');
|
|
176
|
+
return res.status(200).json({
|
|
177
|
+
action: 'consent_required',
|
|
178
|
+
consent_challenge: consentChallenge,
|
|
179
|
+
client: { name: client.name, logoUrl: client.logoUrl, websiteUrl: client.websiteUrl, privacyPolicyUrl: client.privacyPolicyUrl },
|
|
180
|
+
scopes: requestedScopes, missingScopes,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const code = await issueAuthorizationCode(state, { ...pending, sessionJti: sessionJtiOf(req), consentVersion: existingConsent?.version });
|
|
185
|
+
await auditLog(state.logger, state.hooks, 'OAUTH2_AUTHORIZE', { userId: req.auth.userId, clientId: client_id, scopes: requestedScopes });
|
|
186
|
+
redirectToClient(res, state, redirect_uri, { code, state: oauthState });
|
|
187
|
+
} catch (err) {
|
|
188
|
+
next(err);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Redeems a consent challenge — atomically, and only for the user it was issued to. */
|
|
193
|
+
async function takePendingAuthorization(state, req) {
|
|
194
|
+
const { consent_challenge: consentChallenge } = req.body;
|
|
195
|
+
if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
|
|
196
|
+
const pending = await state.cache.take(consentKey(consentChallenge));
|
|
197
|
+
if (!pending || String(pending.userId) !== String(req.auth.userId)) throw INVALID_CONSENT();
|
|
198
|
+
// The client may have been deactivated, or its redirect URIs changed, while the user decided.
|
|
199
|
+
const client = await loadActiveClient(state, pending.clientId);
|
|
200
|
+
validateRedirectUri(client, pending.redirectUri);
|
|
201
|
+
return pending;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** POST /oauth2/authorize/confirm — `{ consent_challenge }` from the authorize response. */
|
|
205
|
+
export async function confirmConsentHandler(req, res, next) {
|
|
206
|
+
try {
|
|
207
|
+
const state = getState();
|
|
208
|
+
const pending = await takePendingAuthorization(state, req);
|
|
209
|
+
|
|
210
|
+
const consent = await state.storage.consentRepository.upsert(req.auth.userId, pending.clientId, pending.scopes);
|
|
211
|
+
const code = await issueAuthorizationCode(state, { ...pending, sessionJti: sessionJtiOf(req), consentVersion: consent?.version });
|
|
212
|
+
|
|
213
|
+
await auditLog(state.logger, state.hooks, 'OAUTH2_CONSENT_GRANTED', { userId: req.auth.userId, clientId: pending.clientId, scopes: pending.scopes });
|
|
214
|
+
redirectToClient(res, state, pending.redirectUri, { code, state: pending.state });
|
|
215
|
+
} catch (err) {
|
|
216
|
+
next(err);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** POST /oauth2/authorize/deny — `{ consent_challenge }`; redirects back with `error=access_denied`. */
|
|
221
|
+
export async function denyConsentHandler(req, res, next) {
|
|
222
|
+
try {
|
|
223
|
+
const state = getState();
|
|
224
|
+
const pending = await takePendingAuthorization(state, req);
|
|
225
|
+
|
|
226
|
+
await auditLog(state.logger, state.hooks, 'OAUTH2_CONSENT_DENIED', { userId: req.auth.userId, clientId: pending.clientId });
|
|
227
|
+
redirectToClient(res, state, pending.redirectUri, { error: 'access_denied', error_description: 'The user denied access', state: pending.state });
|
|
228
|
+
} catch (err) {
|
|
229
|
+
next(err);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export { loadActiveClient, validateRedirectUri, validateScopes };
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
2
|
+
import { OAUTH_CLIENT_STATUS, CLIENT_TYPES } from '../config/constants.js';
|
|
3
|
+
import { verifyClientSecret, hashClientSecret } from '../utils/oauth-client-credentials.js';
|
|
4
|
+
import { tokenHashKeys, HASH_PURPOSES } from '../signing/token.service.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* One answer for every client-authentication failure — unknown client, inactive client, missing or
|
|
8
|
+
* wrong secret — so the token endpoint doesn't reveal which client ids exist (RFC 6749 §5.2
|
|
9
|
+
* `invalid_client`).
|
|
10
|
+
*/
|
|
11
|
+
export const INVALID_CLIENT = () => new IdpError({ code: 'INVALID_CLIENT', httpStatus: 401, message: 'Client authentication failed' });
|
|
12
|
+
|
|
13
|
+
/** `application/x-www-form-urlencoded` decoding, as RFC 6749 §2.3.1 requires for Basic credentials. */
|
|
14
|
+
function formDecode(s) {
|
|
15
|
+
return decodeURIComponent(s.replace(/\+/g, ' '));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The client credentials on a token-endpoint request: HTTP Basic (`client_secret_basic`) or the
|
|
20
|
+
* body (`client_secret_post`, or `client_id` alone for a public client). Using both Basic and a body
|
|
21
|
+
* secret is refused (RFC 6749 §2.3: one method per request), as is a body `client_id` that differs
|
|
22
|
+
* from the Basic one.
|
|
23
|
+
*/
|
|
24
|
+
export function readClientCredentials(req) {
|
|
25
|
+
const header = req.headers?.authorization;
|
|
26
|
+
const bodyId = req.body?.client_id;
|
|
27
|
+
const bodySecret = req.body?.client_secret;
|
|
28
|
+
|
|
29
|
+
if (typeof header === 'string' && /^Basic\s+/i.test(header)) {
|
|
30
|
+
let id;
|
|
31
|
+
let secret;
|
|
32
|
+
try {
|
|
33
|
+
const decoded = Buffer.from(header.replace(/^Basic\s+/i, '').trim(), 'base64').toString('utf8');
|
|
34
|
+
const sep = decoded.indexOf(':');
|
|
35
|
+
if (sep < 0) throw new Error('no separator');
|
|
36
|
+
id = formDecode(decoded.slice(0, sep));
|
|
37
|
+
secret = formDecode(decoded.slice(sep + 1));
|
|
38
|
+
} catch {
|
|
39
|
+
throw INVALID_CLIENT();
|
|
40
|
+
}
|
|
41
|
+
if (!id) throw INVALID_CLIENT();
|
|
42
|
+
if (bodySecret !== undefined) throw new IdpError({ code: 'INVALID_REQUEST', httpStatus: 400, message: 'Use one client authentication method per request' });
|
|
43
|
+
if (bodyId !== undefined && bodyId !== id) throw INVALID_CLIENT();
|
|
44
|
+
return { clientId: id, clientSecret: secret };
|
|
45
|
+
}
|
|
46
|
+
return { clientId: bodyId, clientSecret: bodySecret };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Authenticates the calling client. A confidential client must present its secret; a public client
|
|
51
|
+
* presents only its id (and is refused when `requireConfidential`). A secret still stored as a
|
|
52
|
+
* pre-0.4.0 bcrypt hash is re-stored as HMAC after it verifies.
|
|
53
|
+
*/
|
|
54
|
+
export async function authenticateClient(state, req, { requireConfidential = false } = {}) {
|
|
55
|
+
const { clientId, clientSecret } = readClientCredentials(req);
|
|
56
|
+
if (!clientId || typeof clientId !== 'string') throw INVALID_CLIENT();
|
|
57
|
+
|
|
58
|
+
const repo = state.storage.oauthClientRepository;
|
|
59
|
+
const client = await repo.findByClientId(clientId, { includeSecret: true });
|
|
60
|
+
if (!client || client.status !== OAUTH_CLIENT_STATUS.ACTIVE) throw INVALID_CLIENT();
|
|
61
|
+
|
|
62
|
+
if (client.clientType === CLIENT_TYPES.CONFIDENTIAL) {
|
|
63
|
+
const keys = tokenHashKeys(state, HASH_PURPOSES.OAUTH_CLIENT_SECRET);
|
|
64
|
+
const { valid, upgrade } = clientSecret ? await verifyClientSecret(clientSecret, client.clientSecretHash, keys) : { valid: false };
|
|
65
|
+
if (!valid) throw INVALID_CLIENT();
|
|
66
|
+
if (upgrade) {
|
|
67
|
+
try {
|
|
68
|
+
await repo.updateByClientId(clientId, { clientSecretHash: hashClientSecret(clientSecret, keys[0]) });
|
|
69
|
+
} catch (err) {
|
|
70
|
+
state.logger?.warn?.({ err, clientId }, 'Could not upgrade a legacy client-secret hash (non-fatal)');
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
} else if (requireConfidential) {
|
|
74
|
+
throw INVALID_CLIENT();
|
|
75
|
+
}
|
|
76
|
+
return client;
|
|
77
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { getState } from '../config/state.js';
|
|
2
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
3
|
+
import { OAUTH_CLIENT_STATUS, CLIENT_TYPES } from '../config/constants.js';
|
|
4
|
+
import { generateClientId, generateClientSecret, hashClientSecret } from '../utils/oauth-client-credentials.js';
|
|
5
|
+
import { auditLog } from '../hooks/index.js';
|
|
6
|
+
import { tokenHashKeys, HASH_PURPOSES } from '../signing/token.service.js';
|
|
7
|
+
import { revokeClientSessions } from './consent.controller.js';
|
|
8
|
+
|
|
9
|
+
/** POST /oauth2/clients — public self-registration; lands PENDING_APPROVAL until an operator approves it. */
|
|
10
|
+
export async function registerOAuthClientHandler(req, res, next) {
|
|
11
|
+
try {
|
|
12
|
+
const state = getState();
|
|
13
|
+
const { name, slug, clientType, redirectUris, postLogoutRedirectUris, allowedScopes, allowedGrants, metadata } = req.body;
|
|
14
|
+
|
|
15
|
+
const existing = await state.storage.oauthClientRepository.findBySlug(slug);
|
|
16
|
+
if (existing) throw new IdpError({ code: 'OAUTH_CLIENT_EXISTS', httpStatus: 409, message: 'A client with this slug already exists' });
|
|
17
|
+
|
|
18
|
+
const clientId = generateClientId();
|
|
19
|
+
const clientSecret = generateClientSecret();
|
|
20
|
+
const clientSecretHash = hashClientSecret(clientSecret, tokenHashKeys(state, HASH_PURPOSES.OAUTH_CLIENT_SECRET)[0]);
|
|
21
|
+
|
|
22
|
+
const client = await state.storage.oauthClientRepository.create({
|
|
23
|
+
name, slug, clientId, clientSecretHash,
|
|
24
|
+
clientType: clientType || CLIENT_TYPES.CONFIDENTIAL,
|
|
25
|
+
redirectUris,
|
|
26
|
+
postLogoutRedirectUris: postLogoutRedirectUris || [],
|
|
27
|
+
allowedScopes: allowedScopes || ['openid', 'email', 'profile'],
|
|
28
|
+
allowedGrants: allowedGrants || ['authorization_code', 'refresh_token'],
|
|
29
|
+
metadata: metadata || {},
|
|
30
|
+
status: OAUTH_CLIENT_STATUS.PENDING_APPROVAL,
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
await auditLog(state.logger, state.hooks, 'OAUTH_CLIENT_REGISTERED', { clientId, slug });
|
|
34
|
+
res.status(201).json({ id: client.id, name: client.name, slug: client.slug, clientId, clientSecret, status: client.status });
|
|
35
|
+
} catch (err) {
|
|
36
|
+
next(err);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function getOAuthClientHandler(req, res, next) {
|
|
41
|
+
try {
|
|
42
|
+
const state = getState();
|
|
43
|
+
const client = await state.storage.oauthClientRepository.findByClientId(req.params.clientId);
|
|
44
|
+
if (!client) throw new IdpError({ code: 'OAUTH_CLIENT_NOT_FOUND', httpStatus: 404, message: `Client ${req.params.clientId} not found` });
|
|
45
|
+
res.json(client);
|
|
46
|
+
} catch (err) {
|
|
47
|
+
next(err);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function listOAuthClientsHandler(req, res, next) {
|
|
52
|
+
try {
|
|
53
|
+
const state = getState();
|
|
54
|
+
const page = Math.max(1, parseInt(req.query.page) || 1);
|
|
55
|
+
const limit = Math.min(100, Math.max(1, parseInt(req.query.limit) || 20));
|
|
56
|
+
const [clients, total] = await Promise.all([
|
|
57
|
+
state.storage.oauthClientRepository.listMany({ skip: (page - 1) * limit, limit }),
|
|
58
|
+
state.storage.oauthClientRepository.countAll(),
|
|
59
|
+
]);
|
|
60
|
+
res.json({ clients, total, page, limit });
|
|
61
|
+
} catch (err) {
|
|
62
|
+
next(err);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function updateOAuthClientHandler(req, res, next) {
|
|
67
|
+
try {
|
|
68
|
+
const state = getState();
|
|
69
|
+
const client = await state.storage.oauthClientRepository.updateByClientId(req.params.clientId, req.body);
|
|
70
|
+
if (!client) throw new IdpError({ code: 'OAUTH_CLIENT_NOT_FOUND', httpStatus: 404, message: `Client ${req.params.clientId} not found` });
|
|
71
|
+
|
|
72
|
+
await auditLog(state.logger, state.hooks, 'OAUTH_CLIENT_UPDATED', { clientId: req.params.clientId });
|
|
73
|
+
res.json({ clientId: client.clientId, name: client.name, status: client.status });
|
|
74
|
+
} catch (err) {
|
|
75
|
+
next(err);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function rotateOAuthClientSecretHandler(req, res, next) {
|
|
80
|
+
try {
|
|
81
|
+
const state = getState();
|
|
82
|
+
const client = await state.storage.oauthClientRepository.findByClientId(req.params.clientId);
|
|
83
|
+
if (!client) throw new IdpError({ code: 'OAUTH_CLIENT_NOT_FOUND', httpStatus: 404, message: `Client ${req.params.clientId} not found` });
|
|
84
|
+
|
|
85
|
+
const newSecret = generateClientSecret();
|
|
86
|
+
await state.storage.oauthClientRepository.updateByClientId(req.params.clientId, { clientSecretHash: hashClientSecret(newSecret, tokenHashKeys(state, HASH_PURPOSES.OAUTH_CLIENT_SECRET)[0]) });
|
|
87
|
+
|
|
88
|
+
await auditLog(state.logger, state.hooks, 'OAUTH_CLIENT_SECRET_ROTATED', { clientId: req.params.clientId });
|
|
89
|
+
res.json({ clientId: req.params.clientId, clientSecret: newSecret });
|
|
90
|
+
} catch (err) {
|
|
91
|
+
next(err);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function deactivateOAuthClientHandler(req, res, next) {
|
|
96
|
+
try {
|
|
97
|
+
const state = getState();
|
|
98
|
+
const client = await state.storage.oauthClientRepository.updateByClientId(req.params.clientId, { status: OAUTH_CLIENT_STATUS.INACTIVE });
|
|
99
|
+
if (!client) throw new IdpError({ code: 'OAUTH_CLIENT_NOT_FOUND', httpStatus: 404, message: `Client ${req.params.clientId} not found` });
|
|
100
|
+
|
|
101
|
+
// A deactivated client keeps nothing it was issued: every user's refresh tokens (and the
|
|
102
|
+
// access tokens paired with them) are revoked.
|
|
103
|
+
const revokedSessions = await revokeClientSessions(state, req.params.clientId);
|
|
104
|
+
await auditLog(state.logger, state.hooks, 'OAUTH_CLIENT_DEACTIVATED', { clientId: req.params.clientId, revokedSessions });
|
|
105
|
+
res.json({ clientId: req.params.clientId, status: client.status });
|
|
106
|
+
} catch (err) {
|
|
107
|
+
next(err);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function approveOAuthClientHandler(req, res, next) {
|
|
112
|
+
try {
|
|
113
|
+
const state = getState();
|
|
114
|
+
const client = await state.storage.oauthClientRepository.updateByClientId(req.params.clientId, { status: OAUTH_CLIENT_STATUS.ACTIVE });
|
|
115
|
+
if (!client) throw new IdpError({ code: 'OAUTH_CLIENT_NOT_FOUND', httpStatus: 404, message: `Client ${req.params.clientId} not found` });
|
|
116
|
+
|
|
117
|
+
await auditLog(state.logger, state.hooks, 'OAUTH_CLIENT_APPROVED', { clientId: req.params.clientId });
|
|
118
|
+
res.json({ clientId: req.params.clientId, status: client.status });
|
|
119
|
+
} catch (err) {
|
|
120
|
+
next(err);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { getState } from '../config/state.js';
|
|
2
|
+
import { IdpError } from '../errors/idp-error.js';
|
|
3
|
+
import { auditLog } from '../hooks/index.js';
|
|
4
|
+
import { OAUTH_CLIENT_STATUS, CACHE_KEY_PREFIXES } from '../config/constants.js';
|
|
5
|
+
|
|
6
|
+
/** Revokes the client's live sessions (one user's, or everyone's) and marks their access tokens revoked in the cache too. */
|
|
7
|
+
export async function revokeClientSessions(state, clientId, { userId } = {}) {
|
|
8
|
+
if (typeof state.storage.sessionRepository.revokeForClient !== 'function') {
|
|
9
|
+
state.logger?.warn?.({ clientId }, 'Storage adapter has no sessionRepository.revokeForClient() — tokens issued to the client were NOT revoked');
|
|
10
|
+
return 0;
|
|
11
|
+
}
|
|
12
|
+
const { revokedCount, jtis } = await state.storage.sessionRepository.revokeForClient(clientId, { userId });
|
|
13
|
+
for (const jti of jtis || []) await state.cache.set(`${CACHE_KEY_PREFIXES.REVOKED_REFRESH_TOKEN}:${jti}`, '1', state.config.ttls.revocationCache);
|
|
14
|
+
return revokedCount;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** GET /oauth2/consent — pending-consent details for a client */
|
|
18
|
+
export async function getConsentHandler(req, res, next) {
|
|
19
|
+
try {
|
|
20
|
+
const state = getState();
|
|
21
|
+
const clientId = (req.validatedQuery || req.query).client_id;
|
|
22
|
+
if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
|
|
23
|
+
if (!clientId) throw new IdpError({ code: 'MISSING_REQUIRED_FIELDS', httpStatus: 400, message: 'client_id is required' });
|
|
24
|
+
|
|
25
|
+
const client = await state.storage.oauthClientRepository.findByClientId(clientId);
|
|
26
|
+
if (!client || client.status !== OAUTH_CLIENT_STATUS.ACTIVE) throw new IdpError({ code: 'OAUTH_CLIENT_NOT_FOUND', httpStatus: 400, message: 'Unknown client' });
|
|
27
|
+
|
|
28
|
+
const existingConsent = await state.storage.consentRepository.find(req.auth.userId, clientId);
|
|
29
|
+
res.json({
|
|
30
|
+
client: { name: client.name, clientId: client.clientId, logoUrl: client.logoUrl, websiteUrl: client.websiteUrl, privacyPolicyUrl: client.privacyPolicyUrl },
|
|
31
|
+
existingConsent: existingConsent ? { scopes: existingConsent.scopes, grantedAt: existingConsent.grantedAt } : null,
|
|
32
|
+
});
|
|
33
|
+
} catch (err) {
|
|
34
|
+
next(err);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function listConsentsHandler(req, res, next) {
|
|
39
|
+
try {
|
|
40
|
+
const state = getState();
|
|
41
|
+
if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
|
|
42
|
+
|
|
43
|
+
const consents = await state.storage.consentRepository.listForUser(req.auth.userId);
|
|
44
|
+
res.json(consents.map((c) => ({ clientId: c.clientId, scopes: c.scopes, grantedAt: c.grantedAt, expiresAt: c.expiresAt })));
|
|
45
|
+
} catch (err) {
|
|
46
|
+
next(err);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function revokeConsentHandler(req, res, next) {
|
|
51
|
+
try {
|
|
52
|
+
const state = getState();
|
|
53
|
+
if (!req.auth?.userId) throw new IdpError({ code: 'UNAUTHENTICATED', httpStatus: 401, message: 'Authentication required' });
|
|
54
|
+
|
|
55
|
+
await state.storage.consentRepository.revoke(req.auth.userId, req.params.clientId);
|
|
56
|
+
// Withdrawing consent also ends what it authorized: the client's tokens for this user.
|
|
57
|
+
const revokedSessions = await revokeClientSessions(state, req.params.clientId, { userId: req.auth.userId });
|
|
58
|
+
await auditLog(state.logger, state.hooks, 'CONSENT_REVOKED', { userId: req.auth.userId, clientId: req.params.clientId, revokedSessions });
|
|
59
|
+
res.json({ status: 'ok' });
|
|
60
|
+
} catch (err) {
|
|
61
|
+
next(err);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { familyOf } from '../utils/session-family.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Login challenges: what makes `prompt=login` and `max_age` mean "a login for THIS request".
|
|
7
|
+
*
|
|
8
|
+
* When /oauth2/authorize needs a (new) login, it answers with a single-use `login_challenge`. The IdP's
|
|
9
|
+
* frontend passes it to whichever sign-in it runs (password, magic link, passkey, SSO — and through
|
|
10
|
+
* the MFA step, inside the challenge token), and the session that sign-in creates is bound to it. The
|
|
11
|
+
* repeated authorize request presents the challenge, and is accepted only from exactly that session.
|
|
12
|
+
* No time window, no clock: an earlier login, however recent, doesn't satisfy it.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export const LOGIN_CHALLENGE_TTL_SECONDS = 15 * 60;
|
|
16
|
+
const key = (id) => `oauth2:login-challenge:${id}`;
|
|
17
|
+
|
|
18
|
+
/** The shape of a challenge id — for request schemas. */
|
|
19
|
+
export const loginChallengeSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/, 'login_challenge is malformed');
|
|
20
|
+
const isChallengeId = (v) => loginChallengeSchema.safeParse(v).success;
|
|
21
|
+
|
|
22
|
+
/** A new challenge for an authorization request of `clientId`. */
|
|
23
|
+
export async function createLoginChallenge(state, clientId) {
|
|
24
|
+
const id = crypto.randomBytes(32).toString('base64url');
|
|
25
|
+
await state.cache.set(key(id), { clientId, familyId: null }, LOGIN_CHALLENGE_TTL_SECONDS);
|
|
26
|
+
return id;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Called once a sign-in has created its session: binds the challenge (if any, and not yet bound) to it. */
|
|
30
|
+
export async function bindLoginChallenge(state, id, familyId) {
|
|
31
|
+
if (!id || !isChallengeId(id) || !familyId) return;
|
|
32
|
+
const entry = await state.cache.get(key(id));
|
|
33
|
+
if (!entry || entry.familyId) return; // unknown, expired, or already bound to another sign-in
|
|
34
|
+
await state.cache.set(key(id), { ...entry, familyId }, LOGIN_CHALLENGE_TTL_SECONDS);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Whether the request's session is the one bound to challenge `id` for `clientId` — consuming the
|
|
39
|
+
* challenge if so (single use).
|
|
40
|
+
*/
|
|
41
|
+
export async function redeemLoginChallenge(state, req, id, clientId) {
|
|
42
|
+
if (!id || !isChallengeId(id) || !req.auth?.userId || req.auth.tokenMeta?.sessionless) return false;
|
|
43
|
+
const entry = await state.cache.get(key(id));
|
|
44
|
+
if (!entry?.familyId || entry.clientId !== clientId) return false;
|
|
45
|
+
const sessions = state.storage.sessionRepository;
|
|
46
|
+
if (typeof sessions.findByJti !== 'function' || !req.auth.tokenMeta?.jti) return false;
|
|
47
|
+
const row = await sessions.findByJti(req.auth.tokenMeta.jti);
|
|
48
|
+
if (!row || row.revokedAt || String(row.user) !== String(req.auth.userId) || familyOf(row).familyId !== entry.familyId) return false;
|
|
49
|
+
return Boolean(await state.cache.take(key(id)));
|
|
50
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
2
|
+
// RFC 8252 §7.1 private-use URI scheme for native apps: reverse-DNS, so it contains a dot (com.example.app:/cb).
|
|
3
|
+
const PRIVATE_USE_SCHEME = /^[a-z][a-z0-9+-]*(\.[a-z0-9+-]+)+:$/;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Whether `uri` may be registered as a client redirect URI. The authorization code is sent there, so:
|
|
7
|
+
* - `https:` — always;
|
|
8
|
+
* - `http:` — only to a loopback host (native apps and local development, RFC 8252 §7.3);
|
|
9
|
+
* - a reverse-DNS private-use scheme (`com.example.app:/callback`) for native apps;
|
|
10
|
+
* - never a fragment (RFC 6749 §3.1.2), embedded credentials, or any other scheme (`javascript:`,
|
|
11
|
+
* `data:`, `file:` …).
|
|
12
|
+
*/
|
|
13
|
+
export function isAcceptableRedirectUri(uri) {
|
|
14
|
+
if (typeof uri !== 'string' || uri.length > 2048 || uri.includes('#')) return false;
|
|
15
|
+
let url;
|
|
16
|
+
try {
|
|
17
|
+
url = new URL(uri);
|
|
18
|
+
} catch {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
if (url.username || url.password) return false;
|
|
22
|
+
if (url.protocol === 'https:') return Boolean(url.hostname);
|
|
23
|
+
if (url.protocol === 'http:') return LOOPBACK_HOSTS.has(url.hostname);
|
|
24
|
+
return PRIVATE_USE_SCHEME.test(url.protocol);
|
|
25
|
+
}
|