@passport.lgbt/node 0.0.0-stage → 1.0.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/dist/client.js ADDED
@@ -0,0 +1,523 @@
1
+ import * as oauth from 'oauth4webapi';
2
+ import { ACR, ACR_VALUES, LOCALES, SCOPES } from './common.js';
3
+ import { discover, isSecureOrLoopback, parseIssuer } from './discovery.js';
4
+ import { DETAILS, PassportError, configError, fromAuthorizationError, sendRetryingOnce, throwIfRateLimited, toPassportError } from './errors.js';
5
+ import { RefreshQueue } from './refresh.js';
6
+ import { TRANSACTION_CLOCK_SKEW_MS, TRANSACTION_TTL_MS, buildAuthorizationUrl } from './transaction.js';
7
+ import { toUser } from './userinfo.js';
8
+ const OPTION_KEYS = new Set(['issuer', 'clientId', 'clientSecret', 'redirectUri', 'postLogoutRedirectUri', 'scopes', 'resource', 'fetch', 'onRefreshTokenRotated', 'onEvent']);
9
+ const SCOPE_TOKEN = /^[\x21\x23-\x5b\x5d-\x7e]+$/;
10
+ const REQUEST_TIMEOUT_MS = 10_000;
11
+ /** Tolérance d'horloge pour `max_age` (secondes). */
12
+ const MAX_AGE_TOLERANCE_S = 30;
13
+ function parseRedirect(value) {
14
+ if (typeof value !== 'string')
15
+ throw configError(DETAILS.redirectUri);
16
+ let u;
17
+ try {
18
+ u = new URL(value);
19
+ }
20
+ catch {
21
+ throw configError(DETAILS.redirectUri);
22
+ }
23
+ if (!isSecureOrLoopback(u) || u.hash || value.includes('#') || u.username || u.password)
24
+ throw configError(DETAILS.redirectUri);
25
+ return u;
26
+ }
27
+ function validate(o) {
28
+ if (!o || typeof o !== 'object')
29
+ throw configError();
30
+ for (const k of Object.keys(o))
31
+ if (!OPTION_KEYS.has(k))
32
+ throw configError(DETAILS.unknownOption);
33
+ parseIssuer(o.issuer);
34
+ if (typeof o.clientId !== 'string' || o.clientId.length === 0)
35
+ throw configError(DETAILS.clientId);
36
+ if (o.clientSecret !== undefined && (typeof o.clientSecret !== 'string' || o.clientSecret.length === 0))
37
+ throw configError(DETAILS.clientSecret);
38
+ if (!Array.isArray(o.scopes) || !o.scopes.every((s) => typeof s === 'string' && SCOPES.has(s)))
39
+ throw configError(DETAILS.scopes);
40
+ if (o.scopes.includes('offline_access') && o.clientSecret === undefined)
41
+ throw configError(DETAILS.offlinePublic);
42
+ if (o.fetch !== undefined && typeof o.fetch !== 'function')
43
+ throw configError(DETAILS.callback);
44
+ if (o.onEvent !== undefined && typeof o.onEvent !== 'function')
45
+ throw configError(DETAILS.callback);
46
+ if (o.onRefreshTokenRotated !== undefined && typeof o.onRefreshTokenRotated !== 'function')
47
+ throw configError(DETAILS.callback);
48
+ let resource;
49
+ if (o.resource !== undefined) {
50
+ const r = o.resource;
51
+ if (!r || typeof r !== 'object' || typeof r.indicator !== 'string' || !Array.isArray(r.scopes))
52
+ throw configError(DETAILS.resource);
53
+ let u;
54
+ try {
55
+ u = new URL(r.indicator);
56
+ }
57
+ catch {
58
+ throw configError(DETAILS.resource);
59
+ }
60
+ if (u.hash || r.indicator.includes('#'))
61
+ throw configError(DETAILS.resource);
62
+ const scopes = r.scopes;
63
+ if (!scopes.every((s) => typeof s === 'string' && SCOPE_TOKEN.test(s) && s !== 'openid' && s !== 'profile' && !SCOPES.has(s) && !s.startsWith('account:'))) {
64
+ throw configError(DETAILS.resource);
65
+ }
66
+ resource = { indicator: r.indicator, scopes: [...new Set(scopes)] };
67
+ }
68
+ const v = {
69
+ issuer: o.issuer,
70
+ clientId: o.clientId,
71
+ redirectUri: parseRedirect(o.redirectUri),
72
+ redirectUriRaw: o.redirectUri,
73
+ scopes: [...new Set(o.scopes)],
74
+ fetch: o.fetch ?? globalThis.fetch,
75
+ };
76
+ if (o.clientSecret !== undefined)
77
+ v.clientSecret = o.clientSecret;
78
+ if (o.postLogoutRedirectUri !== undefined) {
79
+ parseRedirect(o.postLogoutRedirectUri);
80
+ v.postLogoutRedirectUri = o.postLogoutRedirectUri;
81
+ }
82
+ if (resource)
83
+ v.resource = resource;
84
+ if (o.onEvent)
85
+ v.onEvent = o.onEvent;
86
+ if (o.onRefreshTokenRotated)
87
+ v.onRefreshTokenRotated = o.onRefreshTokenRotated;
88
+ return v;
89
+ }
90
+ /** Claims de l'ID token gardés : jamais un claim personnel. */
91
+ function idTokenClaims(c) {
92
+ if (typeof c.sub !== 'string' || c.sub.length === 0)
93
+ throw new PassportError('invalid_response');
94
+ const claims = { sub: c.sub, amr: Array.isArray(c.amr) ? c.amr.filter((x) => typeof x === 'string') : [] };
95
+ if (typeof c.acr === 'string')
96
+ claims.acr = c.acr;
97
+ if (typeof c.auth_time === 'number')
98
+ claims.authTime = c.auth_time;
99
+ if (typeof c.sid === 'string')
100
+ claims.sid = c.sid;
101
+ return claims;
102
+ }
103
+ const ACR_RANK = { [ACR.oneFactor]: 1, [ACR.twoFactors]: 2 };
104
+ /**
105
+ * `acr` obtenu contre chaque liste exigée (`requireAcr`, `acrValues` de la transaction) : un `acr` inconnu (dont
106
+ * `…/acr/recovery`) n'est jamais accepté ; absent, il ne passe que sans exigence ; sinon il doit valoir au moins le plus
107
+ * faible niveau demandé (deux facteurs satisfont une demande d'un facteur). Même règle que `@passport.lgbt/web`.
108
+ */
109
+ export function acrSatisfies(acr, ...required) {
110
+ const lists = required.filter((l) => l !== undefined && l.length > 0);
111
+ if (acr === undefined)
112
+ return lists.length === 0;
113
+ const rank = Object.hasOwn(ACR_RANK, acr) ? ACR_RANK[acr] : undefined;
114
+ if (rank === undefined)
115
+ return false;
116
+ return lists.every((list) => list.some((w) => Object.hasOwn(ACR_RANK, w) && rank >= (ACR_RANK[w] ?? Infinity)));
117
+ }
118
+ function checkAcr(acr, ...required) {
119
+ if (!acrSatisfies(acr, ...required))
120
+ throw new PassportError('acr_not_satisfied');
121
+ }
122
+ function isJwtAccessToken(token) {
123
+ const parts = token.split('.');
124
+ if (parts.length !== 3)
125
+ return false;
126
+ try {
127
+ const header = JSON.parse(Buffer.from(parts[0] ?? '', 'base64url').toString('utf8'));
128
+ return typeof header.typ === 'string' && header.typ.toLowerCase().replace(/^application\//, '') === 'at+jwt';
129
+ }
130
+ catch {
131
+ return false;
132
+ }
133
+ }
134
+ /** Audience du JWT (sans vérifier sa signature : jeton reçu en TLS direct du point /token) qui contient `aud`. */
135
+ function audienceIncludes(token, aud) {
136
+ try {
137
+ const p = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString('utf8'));
138
+ return p.aud === aud || (Array.isArray(p.aud) && p.aud.includes(aud));
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ }
144
+ /**
145
+ * Client OIDC serveur de passport.lgbt. La découverte est lue une fois, ici ; une erreur de configuration rejette avec
146
+ * `PassportError('config')`.
147
+ */
148
+ export function createPassportClient(options) {
149
+ return createClient(options, true);
150
+ }
151
+ /**
152
+ * `retryOnRateLimit` : une seule nouvelle tentative après le `Retry-After` d'un `429` (userinfo, refresh), jusqu'à 120 s
153
+ * d'attente. Le mode serveur la désactive : il ne dort jamais dans la requête de l'appli ni dans la section critique du
154
+ * renouvellement (délai de proxy, verrou de l'intégrateur qui expire, refresh token rejoué par un autre réplica) ; il
155
+ * répond tout de suite `429` + `Retry-After`.
156
+ */
157
+ export async function createClient(options, retryOnRateLimit) {
158
+ const cfg = validate(options);
159
+ const retrying = (send) => (retryOnRateLimit ? sendRetryingOnce(send) : send());
160
+ const signal = () => AbortSignal.timeout(REQUEST_TIMEOUT_MS);
161
+ const emit = (type, code) => {
162
+ if (!cfg.onEvent)
163
+ return;
164
+ try {
165
+ cfg.onEvent(code ? { type, code } : { type });
166
+ }
167
+ catch {
168
+ // le crochet de l'appli ne doit jamais casser le client
169
+ }
170
+ };
171
+ const fail = (e, o = {}) => {
172
+ const err = toPassportError(e, o);
173
+ emit('error', err.code);
174
+ throw err;
175
+ };
176
+ let as;
177
+ try {
178
+ as = await discover(cfg.issuer, { fetch: cfg.fetch, signal });
179
+ }
180
+ catch (e) {
181
+ return fail(e);
182
+ }
183
+ const client = { client_id: cfg.clientId, id_token_signed_response_alg: 'ES256' };
184
+ // Le secret ne vit que dans cette fermeture (oauth4webapi), jamais dans un objet exposé.
185
+ const auth = cfg.clientSecret !== undefined ? oauth.ClientSecretBasic(cfg.clientSecret) : oauth.None();
186
+ const insecure = new URL(cfg.issuer).protocol === 'http:';
187
+ // oauth4webapi appelle `customFetch(url, { method, headers, body, redirect, signal })`
188
+ const customFetch = (url, init) => cfg.fetch(url, init);
189
+ const http = (extra) => ({
190
+ [oauth.customFetch]: customFetch,
191
+ ...(insecure ? { [oauth.allowInsecureRequests]: true } : {}),
192
+ signal: signal(),
193
+ ...extra,
194
+ });
195
+ const scope = ['openid', ...cfg.scopes, ...(cfg.resource?.scopes ?? [])].join(' ');
196
+ const queue = new RefreshQueue();
197
+ /** Signale une rotation à l'appli, avant tout contrôle ; un crochet qui échoue rejette en `config`. */
198
+ async function keepRotated(previous, next) {
199
+ if (!cfg.onRefreshTokenRotated || next === previous)
200
+ return;
201
+ try {
202
+ await cfg.onRefreshTokenRotated({ previous, next });
203
+ }
204
+ catch {
205
+ throw configError(DETAILS.rotationHook);
206
+ }
207
+ }
208
+ /**
209
+ * Une requête de refresh (avec ou sans `resource`). Le refresh token rendu est lu sur la réponse brute et signalé
210
+ * (`rotated`, puis `onRefreshTokenRotated`) **avant** le traitement d'oauth4webapi et nos contrôles, qui peuvent rejeter.
211
+ */
212
+ async function refreshGrant(refreshToken, resource, rotated) {
213
+ const res = await retrying(() => oauth.refreshTokenGrantRequest(as, client, auth, refreshToken, http(resource ? { additionalParameters: { resource } } : {})));
214
+ throwIfRateLimited(res);
215
+ if (res.status === 200) {
216
+ const raw = await res
217
+ .clone()
218
+ .json()
219
+ .catch(() => undefined);
220
+ const next = raw && typeof raw === 'object' ? raw.refresh_token : undefined;
221
+ if (typeof next === 'string' && next.length > 0) {
222
+ rotated?.(next);
223
+ await keepRotated(refreshToken, next);
224
+ }
225
+ }
226
+ // horloge du serveur supposée fiable (NTP) : tolérance standard d'oauth4webapi, aucun décalage tiré de l'émetteur
227
+ const r = await oauth.processRefreshTokenResponse(as, client, res);
228
+ if (r.token_type.toLowerCase() !== 'bearer' || typeof r.expires_in !== 'number')
229
+ throw new PassportError('invalid_response');
230
+ return r;
231
+ }
232
+ /** Jeton de l'API par refresh avec `resource`, à appeler dans la file du refresh token. */
233
+ async function resourceToken(refreshToken, rotated) {
234
+ const indicator = cfg.resource?.indicator ?? '';
235
+ const r = await refreshGrant(refreshToken, indicator, rotated);
236
+ return { accessToken: r.access_token, expiresAt: Date.now() + (r.expires_in ?? 0) * 1000, refreshToken: r.refresh_token ?? refreshToken };
237
+ }
238
+ /**
239
+ * Jeton de l'API, sans jamais perdre un refresh token : si la requête avec `resource` échoue après la rotation du
240
+ * profil, le jeu du profil est rendu avec le refresh token **tourné** et sans jeton de ressource (l'appelant réessaiera
241
+ * au prochain refresh). Seul un `invalid_grant` (famille révoquée) rejette, en `session_ended`.
242
+ */
243
+ async function withResource(tokens, refreshToken) {
244
+ let latest = refreshToken;
245
+ try {
246
+ const got = await resourceToken(refreshToken, (next) => (latest = next));
247
+ return { ...tokens, refreshToken: got.refreshToken, resourceAccessToken: got.accessToken, resourceExpiresAt: got.expiresAt };
248
+ }
249
+ catch (e) {
250
+ const err = toPassportError(e, { grant: 'refresh' });
251
+ if (err.code === 'session_ended' || (err.code === 'config' && latest !== refreshToken))
252
+ throw err;
253
+ emit('resource_error', err.code);
254
+ // le refresh token a pu tourner avant l'échec (réponse reçue puis refusée) : on rend le dernier reçu
255
+ return { ...tokens, refreshToken: latest };
256
+ }
257
+ }
258
+ /** Transaction lisible et récente (10 min, marge d'horloge de 60 s), sinon `invalid_state`. */
259
+ function checkTransaction(transaction) {
260
+ if (!transaction || typeof transaction !== 'object' || typeof transaction.state !== 'string' || typeof transaction.nonce !== 'string' || typeof transaction.verifier !== 'string') {
261
+ throw new PassportError('invalid_state');
262
+ }
263
+ const age = Date.now() - transaction.at;
264
+ if (typeof transaction.at !== 'number' || !(age >= -TRANSACTION_CLOCK_SKEW_MS && age <= TRANSACTION_TTL_MS))
265
+ throw new PassportError('invalid_state');
266
+ }
267
+ /** `state` d'abord, avant tout appel à l'émetteur ; puis `iss` (RFC 9207), exigé même dans une réponse d'erreur. */
268
+ function checkResponse(url, transaction) {
269
+ let params;
270
+ try {
271
+ params = new URL(url).searchParams;
272
+ }
273
+ catch {
274
+ throw new PassportError('invalid_response');
275
+ }
276
+ if (params.getAll('state').length !== 1 || params.get('state') !== transaction.state)
277
+ throw new PassportError('invalid_state');
278
+ if (params.getAll('iss').length !== 1 || params.get('iss') !== as.issuer)
279
+ throw new PassportError('invalid_response');
280
+ const error = params.get('error');
281
+ if (error !== null)
282
+ throw fromAuthorizationError(error);
283
+ return oauth.validateAuthResponse(as, client, params, transaction.state);
284
+ }
285
+ function checkRequireAcr(o) {
286
+ if (o.requireAcr !== undefined && (!Array.isArray(o.requireAcr) || !o.requireAcr.every((a) => ACR_VALUES.has(a))))
287
+ throw configError(DETAILS.authorizationOptions);
288
+ }
289
+ function guardProfileToken(token) {
290
+ if (cfg.resource && isJwtAccessToken(token))
291
+ throw configError(DETAILS.resourceProfileToken);
292
+ }
293
+ const api = {
294
+ async authorizationUrl(o) {
295
+ return buildAuthorizationUrl({
296
+ as,
297
+ clientId: cfg.clientId,
298
+ redirectUri: cfg.redirectUri,
299
+ redirectUriRaw: cfg.redirectUriRaw,
300
+ scope,
301
+ offlineAccess: cfg.scopes.includes('offline_access'),
302
+ ...(cfg.resource ? { resource: cfg.resource.indicator } : {}),
303
+ }, o);
304
+ },
305
+ async callback(url, transaction, o = {}) {
306
+ try {
307
+ checkTransaction(transaction);
308
+ // un code du saut 2 ne s'échange que par `resourceCallback`
309
+ if (transaction.hop !== undefined)
310
+ throw new PassportError('invalid_state');
311
+ checkRequireAcr(o);
312
+ const validated = checkResponse(url, transaction);
313
+ const res = await oauth.authorizationCodeGrantRequest(as, client, auth, validated, cfg.redirectUriRaw, transaction.verifier, http());
314
+ throwIfRateLimited(res);
315
+ const r = await oauth.processAuthorizationCodeResponse(as, client, res, {
316
+ expectedNonce: transaction.nonce,
317
+ requireIdToken: true,
318
+ maxAge: oauth.skipAuthTimeCheck,
319
+ });
320
+ if (r.token_type.toLowerCase() !== 'bearer' || typeof r.expires_in !== 'number')
321
+ throw new PassportError('invalid_response');
322
+ const idToken = oauth.getValidatedIdTokenClaims(r);
323
+ if (!idToken)
324
+ throw new PassportError('token_error');
325
+ const claims = idTokenClaims(idToken);
326
+ checkAcr(claims.acr, o.requireAcr, transaction.acr);
327
+ if (transaction.maxAge !== undefined) {
328
+ const now = Math.floor(Date.now() / 1000);
329
+ if (claims.authTime === undefined || now - claims.authTime > transaction.maxAge + MAX_AGE_TOLERANCE_S)
330
+ throw new PassportError('max_age_exceeded');
331
+ }
332
+ guardProfileToken(r.access_token);
333
+ const tokens = { accessToken: r.access_token, expiresAt: Date.now() + r.expires_in * 1000, scope: r.scope ?? '', claims };
334
+ if (r.refresh_token)
335
+ tokens.refreshToken = r.refresh_token;
336
+ // sans refresh token, le jeton de l'API vient de la seconde autorisation silencieuse (resourceAuthorizationUrl)
337
+ if (cfg.resource && r.refresh_token) {
338
+ const first = r.refresh_token;
339
+ const rt = await queue.run(first, () => withResource(tokens, first));
340
+ emit('callback');
341
+ return rt;
342
+ }
343
+ emit('callback');
344
+ return tokens;
345
+ }
346
+ catch (e) {
347
+ return fail(e);
348
+ }
349
+ },
350
+ async resourceAuthorizationUrl(o) {
351
+ try {
352
+ if (!cfg.resource)
353
+ throw configError(DETAILS.resourceMissing);
354
+ if (!o || typeof o !== 'object' || typeof o.sub !== 'string' || o.sub.length === 0)
355
+ throw configError(DETAILS.authorizationOptions);
356
+ if (o.acr !== undefined && !ACR_VALUES.has(o.acr))
357
+ throw configError(DETAILS.authorizationOptions);
358
+ const { url, transaction } = await buildAuthorizationUrl({
359
+ as,
360
+ clientId: cfg.clientId,
361
+ redirectUri: cfg.redirectUri,
362
+ redirectUriRaw: cfg.redirectUriRaw,
363
+ scope: ['openid', ...cfg.resource.scopes].join(' '),
364
+ offlineAccess: false,
365
+ resource: cfg.resource.indicator,
366
+ }, {
367
+ prompt: 'none',
368
+ ...(o.returnTo !== undefined ? { returnTo: o.returnTo } : {}),
369
+ ...(o.acr !== undefined ? { acrValues: [o.acr] } : {}),
370
+ ...(o.locale !== undefined ? { locale: o.locale } : {}),
371
+ });
372
+ return { url, transaction: { ...transaction, hop: 'resource', sub: o.sub, resource: cfg.resource.indicator } };
373
+ }
374
+ catch (e) {
375
+ return fail(e);
376
+ }
377
+ },
378
+ async resourceCallback(url, transaction, o = {}) {
379
+ try {
380
+ checkTransaction(transaction);
381
+ if (transaction.hop !== 'resource' || typeof transaction.sub !== 'string' || transaction.sub.length === 0)
382
+ throw new PassportError('invalid_state');
383
+ if (!cfg.resource)
384
+ throw configError(DETAILS.resourceMissing);
385
+ // ressource changée entre le départ et le retour (déploiement) : la transaction n'est plus la nôtre
386
+ if (transaction.resource !== cfg.resource.indicator)
387
+ throw new PassportError('invalid_state');
388
+ checkRequireAcr(o);
389
+ const validated = checkResponse(url, transaction);
390
+ const res = await oauth.authorizationCodeGrantRequest(as, client, auth, validated, cfg.redirectUriRaw, transaction.verifier, http({ additionalParameters: { resource: cfg.resource.indicator } }));
391
+ throwIfRateLimited(res);
392
+ const r = await oauth.processAuthorizationCodeResponse(as, client, res, {
393
+ expectedNonce: transaction.nonce,
394
+ requireIdToken: true,
395
+ maxAge: oauth.skipAuthTimeCheck,
396
+ });
397
+ if (r.token_type.toLowerCase() !== 'bearer' || typeof r.expires_in !== 'number')
398
+ throw new PassportError('invalid_response');
399
+ const idToken = oauth.getValidatedIdTokenClaims(r);
400
+ if (!idToken)
401
+ throw new PassportError('token_error');
402
+ const claims = idTokenClaims(idToken);
403
+ if (claims.sub !== transaction.sub)
404
+ throw new PassportError('userinfo_mismatch');
405
+ checkAcr(claims.acr, o.requireAcr, transaction.acr);
406
+ if (!isJwtAccessToken(r.access_token) || !audienceIncludes(r.access_token, cfg.resource.indicator))
407
+ throw new PassportError('token_error');
408
+ // aucun scope de la ressource accordé (refusé au consentement, retiré par la console) : refus de la personne ou de
409
+ // l'émetteur, pas une panne ; le relancer à chaque navigation n'y changerait rien
410
+ const granted = typeof r.scope === 'string' ? r.scope.split(' ').filter(Boolean) : [];
411
+ if (!granted.some((x) => cfg.resource?.scopes.includes(x)))
412
+ throw new PassportError('access_denied');
413
+ // un refresh token éventuel est ignoré : le révoquer révoquerait tout le grant (revokeGrantPolicy), saut 1 compris
414
+ emit('resource_callback');
415
+ return { accessToken: r.access_token, expiresAt: Date.now() + r.expires_in * 1000, scope: granted.join(' '), claims };
416
+ }
417
+ catch (e) {
418
+ return fail(e);
419
+ }
420
+ },
421
+ async refresh(refreshToken) {
422
+ if (typeof refreshToken !== 'string' || refreshToken.length === 0)
423
+ return fail(configError(DETAILS.refreshToken));
424
+ try {
425
+ return await queue.run(refreshToken, async () => {
426
+ const r = await refreshGrant(refreshToken);
427
+ const idToken = oauth.getValidatedIdTokenClaims(r);
428
+ if (!idToken)
429
+ throw new PassportError('invalid_response');
430
+ const claims = idTokenClaims(idToken);
431
+ checkAcr(claims.acr);
432
+ guardProfileToken(r.access_token);
433
+ const tokens = { accessToken: r.access_token, expiresAt: Date.now() + (r.expires_in ?? 0) * 1000, scope: r.scope ?? '', claims };
434
+ const next = r.refresh_token ?? refreshToken;
435
+ tokens.refreshToken = next;
436
+ // même file : la requête avec `resource` part après celle du profil, avec le refresh token qui vient de tourner
437
+ const out = cfg.resource ? await withResource(tokens, next) : tokens;
438
+ emit('refresh');
439
+ return out;
440
+ });
441
+ }
442
+ catch (e) {
443
+ return fail(e, { grant: 'refresh' });
444
+ }
445
+ },
446
+ async userinfo(accessToken, expectedSub) {
447
+ if (typeof accessToken !== 'string' || accessToken.length === 0 || typeof expectedSub !== 'string' || expectedSub.length === 0)
448
+ return fail(configError(DETAILS.token));
449
+ try {
450
+ const res = await retrying(() => oauth.userInfoRequest(as, client, accessToken, http()));
451
+ throwIfRateLimited(res);
452
+ const info = await oauth.processUserInfoResponse(as, client, oauth.skipSubjectCheck, res);
453
+ if (info.sub !== expectedSub)
454
+ throw new PassportError('userinfo_mismatch');
455
+ return toUser(info.sub, info);
456
+ }
457
+ catch (e) {
458
+ return fail(e);
459
+ }
460
+ },
461
+ async revoke(token, hint) {
462
+ if (typeof token !== 'string' || token.length === 0)
463
+ return fail(configError(DETAILS.token));
464
+ if (!as.revocation_endpoint)
465
+ return fail(configError(DETAILS.endpoint));
466
+ try {
467
+ const res = await oauth.revocationRequest(as, client, auth, token, http(hint ? { additionalParameters: { token_type_hint: hint } } : {}));
468
+ await oauth.processRevocationResponse(res);
469
+ emit('revoke');
470
+ }
471
+ catch (e) {
472
+ return fail(e);
473
+ }
474
+ },
475
+ async introspect(token) {
476
+ if (typeof token !== 'string' || token.length === 0)
477
+ return fail(configError(DETAILS.token));
478
+ // l'introspection est réservée aux clients confidentiels (RFC 7662 §2.1) : sans secret, l'émetteur répondrait 401
479
+ if (cfg.clientSecret === undefined)
480
+ return fail(configError(DETAILS.introspectionSecret));
481
+ if (!as.introspection_endpoint)
482
+ return fail(configError(DETAILS.endpoint));
483
+ try {
484
+ const res = await oauth.introspectionRequest(as, client, auth, token, http());
485
+ const r = await oauth.processIntrospectionResponse(as, client, res);
486
+ if (r.active !== true)
487
+ return { active: false };
488
+ const out = { active: true };
489
+ if (typeof r.sub === 'string')
490
+ out.sub = r.sub;
491
+ if (typeof r.scope === 'string')
492
+ out.scope = r.scope;
493
+ if (typeof r.exp === 'number')
494
+ out.exp = r.exp;
495
+ if (typeof r.client_id === 'string')
496
+ out.clientId = r.client_id;
497
+ return out;
498
+ }
499
+ catch (e) {
500
+ return fail(e);
501
+ }
502
+ },
503
+ endSessionUrl(o = {}) {
504
+ if (!as.end_session_endpoint)
505
+ return fail(configError(DETAILS.endpoint));
506
+ if (o.state !== undefined && typeof o.state !== 'string')
507
+ return fail(configError(DETAILS.authorizationOptions));
508
+ if (o.locale !== undefined && !LOCALES.has(o.locale)) {
509
+ return fail(configError(DETAILS.authorizationOptions));
510
+ }
511
+ const u = new URL(as.end_session_endpoint);
512
+ u.searchParams.set('client_id', cfg.clientId);
513
+ if (cfg.postLogoutRedirectUri)
514
+ u.searchParams.set('post_logout_redirect_uri', cfg.postLogoutRedirectUri);
515
+ if (o.state)
516
+ u.searchParams.set('state', o.state);
517
+ if (o.locale)
518
+ u.searchParams.set('ui_locales', o.locale);
519
+ return u.href;
520
+ },
521
+ };
522
+ return Object.freeze(api);
523
+ }
@@ -0,0 +1,33 @@
1
+ /** Valeurs d'`acr` qu'une appli peut demander ou exiger. `…/acr/recovery` n'est jamais accepté par le SDK. */
2
+ export declare const ACR: {
3
+ readonly oneFactor: "https://passport.lgbt/acr/1";
4
+ readonly twoFactors: "https://passport.lgbt/acr/2";
5
+ };
6
+ export type Acr = (typeof ACR)[keyof typeof ACR];
7
+ export declare const ACR_VALUES: ReadonlySet<string>;
8
+ /** Scopes qu'une appli déclare ; `openid` est toujours ajouté par le SDK. Les scopes d'une API passent par `resource`. */
9
+ export type Scope = 'name' | 'avatar' | 'pronouns' | 'email' | 'phone' | 'offline_access';
10
+ export declare const SCOPES: ReadonlySet<string>;
11
+ export type Locale = 'fr' | 'en' | 'es' | 'de' | 'it' | 'pt-PT' | 'pt-BR' | 'nl' | 'ar' | 'ja' | 'zh-Hans' | 'zh-Hant';
12
+ export declare const LOCALES: ReadonlySet<string>;
13
+ export interface PassportUser {
14
+ /**
15
+ * Identifiant de la personne **pour cette appli (ou son équipe)** : il diffère d'une appli à l'autre. Ne le comparez pas
16
+ * entre applis et n'indexez jamais une personne par son adresse e-mail. Son format n'est pas garanti.
17
+ */
18
+ sub: string;
19
+ /** Scope `name` : le nom choisi, relu à chaque renouvellement. */
20
+ name?: string;
21
+ /** Scope `pronouns` : absent s'il n'est pas renseigné. */
22
+ pronouns?: string;
23
+ /** Scope `avatar` : URL de l'émetteur valable 1 h, relue à chaque renouvellement. */
24
+ picture?: string;
25
+ email?: string;
26
+ emailVerified?: boolean;
27
+ phoneNumber?: string;
28
+ phoneNumberVerified?: boolean;
29
+ /** De l'ID token (`TokenSet.claims`). */
30
+ acr?: string;
31
+ amr: readonly string[];
32
+ authTime?: number;
33
+ }
package/dist/common.js ADDED
@@ -0,0 +1,6 @@
1
+ // Types communs aux trois SDK (copiés, pas partagés : aucun paquet commun n'est publié).
2
+ /** Valeurs d'`acr` qu'une appli peut demander ou exiger. `…/acr/recovery` n'est jamais accepté par le SDK. */
3
+ export const ACR = { oneFactor: 'https://passport.lgbt/acr/1', twoFactors: 'https://passport.lgbt/acr/2' };
4
+ export const ACR_VALUES = new Set(Object.values(ACR));
5
+ export const SCOPES = new Set(['name', 'avatar', 'pronouns', 'email', 'phone', 'offline_access']);
6
+ export const LOCALES = new Set(['fr', 'en', 'es', 'de', 'it', 'pt-PT', 'pt-BR', 'nl', 'ar', 'ja', 'zh-Hans', 'zh-Hant']);
@@ -0,0 +1,15 @@
1
+ import type * as oauth from 'oauth4webapi';
2
+ /** `https:`, ou `http:` sur la boucle locale seulement (émetteur de test, appli en développement). */
3
+ export declare function isSecureOrLoopback(u: URL): boolean;
4
+ /** Émetteur configuré : URL absolue sans requête ni fragment, `https:` hors boucle locale. */
5
+ export declare function parseIssuer(issuer: unknown): URL;
6
+ export interface DiscoveryOptions {
7
+ fetch: typeof fetch;
8
+ signal: () => AbortSignal;
9
+ }
10
+ /**
11
+ * Lit la découverte une fois : son `issuer` doit être identique, caractère pour caractère, à l'émetteur configuré, et chaque
12
+ * point d'accès doit être sur l'origine de l'émetteur. Les métadonnées de sécurité sont imposées quoi que dise le document
13
+ * (`iss` exigé dans la réponse d'autorisation, PKCE S256, ID token ES256).
14
+ */
15
+ export declare function discover(issuer: string, o: DiscoveryOptions): Promise<oauth.AuthorizationServer>;
@@ -0,0 +1,90 @@
1
+ import { DETAILS, PassportError, configError } from './errors.js';
2
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);
3
+ /** `https:`, ou `http:` sur la boucle locale seulement (émetteur de test, appli en développement). */
4
+ export function isSecureOrLoopback(u) {
5
+ return u.protocol === 'https:' || (u.protocol === 'http:' && LOOPBACK.has(u.hostname));
6
+ }
7
+ /** Émetteur configuré : URL absolue sans requête ni fragment, `https:` hors boucle locale. */
8
+ export function parseIssuer(issuer) {
9
+ if (typeof issuer !== 'string')
10
+ throw configError(DETAILS.issuer);
11
+ let u;
12
+ try {
13
+ u = new URL(issuer);
14
+ }
15
+ catch {
16
+ throw configError(DETAILS.issuer);
17
+ }
18
+ if (!isSecureOrLoopback(u) || u.search || u.hash || issuer.includes('#') || issuer.includes('?') || u.username || u.password) {
19
+ throw configError(DETAILS.issuer);
20
+ }
21
+ return u;
22
+ }
23
+ const REQUIRED = ['authorization_endpoint', 'token_endpoint', 'jwks_uri', 'userinfo_endpoint'];
24
+ const OPTIONAL = ['revocation_endpoint', 'introspection_endpoint', 'end_session_endpoint'];
25
+ /**
26
+ * Lit la découverte une fois : son `issuer` doit être identique, caractère pour caractère, à l'émetteur configuré, et chaque
27
+ * point d'accès doit être sur l'origine de l'émetteur. Les métadonnées de sécurité sont imposées quoi que dise le document
28
+ * (`iss` exigé dans la réponse d'autorisation, PKCE S256, ID token ES256).
29
+ */
30
+ export async function discover(issuer, o) {
31
+ const base = parseIssuer(issuer);
32
+ const url = `${issuer.replace(/\/+$/, '')}/.well-known/openid-configuration`;
33
+ let res;
34
+ try {
35
+ res = await o.fetch(url, { method: 'GET', headers: { accept: 'application/json' }, redirect: 'manual', signal: o.signal() });
36
+ }
37
+ catch {
38
+ throw new PassportError('network');
39
+ }
40
+ if (res.status === 429)
41
+ throw new PassportError('rate_limited');
42
+ if (res.status !== 200)
43
+ throw new PassportError('invalid_response');
44
+ let doc;
45
+ try {
46
+ const json = await res.json();
47
+ if (!json || typeof json !== 'object' || Array.isArray(json))
48
+ throw new Error('not an object');
49
+ doc = json;
50
+ }
51
+ catch {
52
+ throw new PassportError('invalid_response');
53
+ }
54
+ if (doc.issuer !== issuer)
55
+ throw configError(DETAILS.discoveryIssuer);
56
+ const onIssuerOrigin = (v) => {
57
+ if (typeof v !== 'string')
58
+ return false;
59
+ try {
60
+ const u = new URL(v);
61
+ return u.origin === base.origin && !u.hash && !u.username && !u.password;
62
+ }
63
+ catch {
64
+ return false;
65
+ }
66
+ };
67
+ for (const k of REQUIRED)
68
+ if (!onIssuerOrigin(doc[k]))
69
+ throw configError(DETAILS.discoveryEndpoint);
70
+ for (const k of OPTIONAL)
71
+ if (doc[k] !== undefined && !onIssuerOrigin(doc[k]))
72
+ throw configError(DETAILS.discoveryEndpoint);
73
+ const as = {
74
+ issuer,
75
+ authorization_endpoint: doc.authorization_endpoint,
76
+ token_endpoint: doc.token_endpoint,
77
+ jwks_uri: doc.jwks_uri,
78
+ userinfo_endpoint: doc.userinfo_endpoint,
79
+ authorization_response_iss_parameter_supported: true,
80
+ code_challenge_methods_supported: ['S256'],
81
+ id_token_signing_alg_values_supported: ['ES256'],
82
+ };
83
+ for (const k of OPTIONAL)
84
+ if (typeof doc[k] === 'string')
85
+ as[k] = doc[k];
86
+ const dpopAlgs = doc.dpop_signing_alg_values_supported;
87
+ if (Array.isArray(dpopAlgs) && dpopAlgs.every((a) => typeof a === 'string'))
88
+ as.dpop_signing_alg_values_supported = [...dpopAlgs];
89
+ return as;
90
+ }