@amedia/user 1.5.1 → 1.6.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/user.node.js CHANGED
@@ -97,17 +97,38 @@ const SiteAccessSchema = v.object({
97
97
  site_domain: v.string(),
98
98
  access_features: v.array(v.string()),
99
99
  });
100
+ const PhoneSchema = v.object({
101
+ country_code: v.string(),
102
+ national_number: v.string(),
103
+ });
104
+ /**
105
+ * Every attribute is optional: what comes back is decided by the filter asked
106
+ * for and the scopes behind the credential, and aID omits what it may not read
107
+ * exactly as it omits what the reader does not have.
108
+ *
109
+ * An attribute missing from this schema is dropped in silence — valibot strips
110
+ * what it does not declare — so a field absent here reads as an attribute the
111
+ * reader has not got. For a `*_verified_at` that means every reader looks
112
+ * unverified, which is why all four are listed rather than only the one a
113
+ * browser session can reach.
114
+ */
100
115
  const ServiceUserSchema = v.partial(v.object({
101
116
  uuid: v.string(),
102
117
  name: v.string(),
103
118
  name_verified_at: v.nullish(v.string()),
119
+ birth_date: v.nullish(v.string()),
120
+ birth_date_verified_at: v.nullish(v.string()),
121
+ email: v.nullish(v.string()),
122
+ email_verified_at: v.nullish(v.string()),
123
+ phone: v.nullish(PhoneSchema),
124
+ phone_verified_at: v.nullish(v.string()),
104
125
  tracking_key: v.string(),
105
126
  avatar: v.string(),
106
127
  access: v.array(SiteAccessSchema),
107
128
  privacy_preferences: PrivacyPreferencesSchema,
108
129
  session_tracking_key: v.string(),
109
130
  }));
110
- v.partial(v.object({
131
+ const SessionSchema = v.partial(v.object({
111
132
  user_uuid: v.string(),
112
133
  user_agent: v.string(),
113
134
  session_tracking_key: v.string(),
@@ -130,6 +151,33 @@ var LoginStatus;
130
151
  const LoginStatusResponseSchema = v.object({
131
152
  status: v.enum(LoginStatus),
132
153
  });
154
+ /**
155
+ * One provider as a chooser needs it: what to call it, what it proves, what it
156
+ * looks like. `icon_svg` is the registry's own artwork, and is serialised even
157
+ * when empty — an absent logo is a provider without one, not an older response.
158
+ *
159
+ * `acr_values` is deliberately absent from the public projection: naming the
160
+ * assurance level invites a caller to ask for a weaker one.
161
+ */
162
+ const VerificationProviderSchema = v.object({
163
+ id: v.string(),
164
+ label: v.string(),
165
+ source: v.string(),
166
+ attributes: v.array(v.string()),
167
+ /**
168
+ * The provider's logo, as SVG markup.
169
+ *
170
+ * Markup from the network, so it goes in as an image rather than as nodes:
171
+ * `<img src="data:image/svg+xml;base64,…">` draws it with scripts inert,
172
+ * while `innerHTML = icon_svg` would run anything it carried. aID writes this
173
+ * and the trust is internal, which is why this is a rendering instruction and
174
+ * not a warning — but the safe rendering costs nothing.
175
+ */
176
+ icon_svg: v.string(),
177
+ });
178
+ const VerificationProvidersSchema = v.object({
179
+ providers: v.array(VerificationProviderSchema),
180
+ });
133
181
 
134
182
  var AffiliationType;
135
183
  (function (AffiliationType) {
@@ -212,7 +260,264 @@ const coreFetcher = (url, options) => fetch(url, options)
212
260
  */
213
261
  const coreSchemaVerifiedFetch = (schema, url, options) => coreFetcher(url, options).then((json) => v.parse(schema, json));
214
262
 
263
+ const VERIFIABLE_ATTRIBUTES = [
264
+ 'name',
265
+ 'birth_date',
266
+ 'email',
267
+ 'phone',
268
+ ];
269
+ const VERIFICATION_SOURCES = ['eid', 'otp'];
270
+ const VERIFICATION_ERRORS = [
271
+ 'invalid_request',
272
+ 'requirement_not_met',
273
+ 'state_mismatch',
274
+ 'provider_error',
275
+ 'login_required',
276
+ 'unknown_outcome',
277
+ ];
278
+ const VERIFICATION_PARAM = 'verification';
279
+ const VERIFICATION_ERROR_PARAM = 'verification_error';
280
+ const MAX_AGE_CEILING_SECONDS = 365 * 24 * 60 * 60;
281
+ const DURATION_UNIT_SECONDS = {
282
+ s: 1,
283
+ m: 60,
284
+ h: 60 * 60,
285
+ d: 24 * 60 * 60,
286
+ };
287
+ /**
288
+ * What kind of source a provider name is, as quirinus classifies it.
289
+ *
290
+ * Vesta writes only names quirinus knows — `bankid`, `otp`, and `eid` for the
291
+ * dummy provider, chosen so a role-holding test account classifies rather than
292
+ * falling through (`VerificationProvider::STAMP_SOURCES`). Its own table matches
293
+ * `eid` by substring where quirinus requires equality; this follows quirinus,
294
+ * because classifying a name quirinus leaves unclassified is what would report a
295
+ * requirement met that aID considers unmet.
296
+ */
297
+ const verificationSourceOf = (provider) => {
298
+ const name = (provider ?? '').toLowerCase();
299
+ if (name.includes('bankid') || name.includes('mitid') || name === 'eid') {
300
+ return 'eid';
301
+ }
302
+ if (name.includes('otp') || name.includes('sms') || name.includes('code')) {
303
+ return 'otp';
304
+ }
305
+ return null;
306
+ };
307
+ /**
308
+ * What can prove an attribute, and therefore what proved it. Mirrors quirinus
309
+ * `ImpliedVerificationSource`.
310
+ */
311
+ const impliedSourceOf = (attribute) => attribute === 'email' || attribute === 'phone' ? 'otp' : 'eid';
312
+ /**
313
+ * Zero is a value, not an omission: it is OIDC `max_age=0`, "prove it now",
314
+ * which quirinus resolves against the moment the reader left the page.
315
+ */
316
+ const toSeconds = (maxAge) => {
317
+ const invalid = () => new ValidationError('verification_invalid_max_age', `maxAge must be a whole number of seconds (0 or more) or a duration such as "30m" (got ${JSON.stringify(maxAge)})`);
318
+ if (typeof maxAge === 'number') {
319
+ if (!Number.isInteger(maxAge) || maxAge < 0) {
320
+ throw invalid();
321
+ }
322
+ return maxAge;
323
+ }
324
+ const match = /^(\d+)([smhd])?$/.exec(maxAge.trim());
325
+ if (!match) {
326
+ throw invalid();
327
+ }
328
+ return Number(match[1]) * (match[2] ? DURATION_UNIT_SECONDS[match[2]] : 1);
329
+ };
330
+ const toMaxAgeSeconds = (maxAge) => {
331
+ const seconds = toSeconds(maxAge);
332
+ if (seconds > MAX_AGE_CEILING_SECONDS) {
333
+ throw new ValidationError('verification_max_age_too_large', `maxAge must be at most ${MAX_AGE_CEILING_SECONDS} seconds (a year), was ${seconds}.`);
334
+ }
335
+ return seconds;
336
+ };
337
+ /**
338
+ * Where the reader lands afterwards, refused unless it is a path on the site
339
+ * they are already on.
340
+ *
341
+ * Not a redirect guard -- eris keeps only the path of `requested_url`, so an
342
+ * absolute URL cannot send anyone off-site. What it does instead is lose them:
343
+ * `https://example.no/artikkel/` arrives as `/`, and the reader finishes
344
+ * verifying on the front page rather than where they started. A server taking
345
+ * this from `?returnTo=` would never hear about it.
346
+ *
347
+ * `//` and `/\` are refused with the rest: a browser reads both as the start
348
+ * of a host, so they are not the same-site paths they resemble.
349
+ */
350
+ const assertRequestedUrl = (requestedUrl) => {
351
+ if (!requestedUrl.startsWith('/') ||
352
+ requestedUrl.startsWith('//') ||
353
+ requestedUrl.startsWith('/\\')) {
354
+ throw new ValidationError('verification_invalid_requested_url', `requestedUrl must be a path on your own site, starting with a single "/", was ${JSON.stringify(requestedUrl)}`);
355
+ }
356
+ return requestedUrl;
357
+ };
358
+ /**
359
+ * Checks the requirement and fills in what was left out. Throws rather than
360
+ * navigating for anything aID would refuse anyway, so a caller bug costs no
361
+ * round trip.
362
+ *
363
+ * `fallbackRequestedUrl` is where the reader returns when the requirement does
364
+ * not say — the current page in a browser, and a caller's own choice on a
365
+ * server, which has no current page.
366
+ */
367
+ const normalizeVerificationRequirement = (requirement, fallbackRequestedUrl) => {
368
+ const attributes = requirement.attributes ?? [];
369
+ const sources = requirement.sources ?? [];
370
+ const unknownAttribute = attributes.find((attribute) => !VERIFIABLE_ATTRIBUTES.includes(attribute));
371
+ if (unknownAttribute) {
372
+ throw new ValidationError('verification_unknown_attribute', `Unknown attribute "${unknownAttribute}". Verifiable attributes are ${VERIFIABLE_ATTRIBUTES.join(', ')}.`);
373
+ }
374
+ const unknownSource = sources.find((source) => !VERIFICATION_SOURCES.includes(source));
375
+ if (unknownSource) {
376
+ throw new ValidationError('verification_unknown_source', `Unknown source "${unknownSource}". Sources are ${VERIFICATION_SOURCES.join(', ')} — provider names are not part of the public API.`);
377
+ }
378
+ const verifiedSession = requirement.verifiedSession === true;
379
+ if (attributes.length === 0 && !verifiedSession) {
380
+ throw new ValidationError('verification_requirement_empty', 'A verification requirement must name at least one attribute or require a verified session.');
381
+ }
382
+ // What proves an attribute is decided by the attribute, so a sources param
383
+ // excluding it can never be met. quirinus refuses this up front; catching it
384
+ // here saves the reader a round trip to hear the same thing.
385
+ if (sources.length > 0) {
386
+ const excluded = attributes.find((attribute) => !sources.includes(impliedSourceOf(attribute)));
387
+ if (excluded) {
388
+ throw new ValidationError('verification_sources_exclude_attribute', `Attribute "${excluded}" can only be proven by source "${impliedSourceOf(excluded)}", which is not among the requested sources ${sources.join(',')}.`);
389
+ }
390
+ }
391
+ return {
392
+ attributes,
393
+ verifiedSession,
394
+ sources,
395
+ maxAgeSeconds: requirement.maxAge === undefined
396
+ ? undefined
397
+ : toMaxAgeSeconds(requirement.maxAge),
398
+ requestedUrl: assertRequestedUrl(requirement.requestedUrl ?? fallbackRequestedUrl),
399
+ context: requirement.context ?? 'require_verification',
400
+ };
401
+ };
402
+ /**
403
+ * A bare host, and nothing that could make it name a different one.
404
+ *
405
+ * Interpolated straight into a URL, `www.avisnavn.no@evil.example` parses as
406
+ * userinfo on `evil.example` and `evil.example/#` buries the path in a
407
+ * fragment — either sends the reader, and the `requested_url` they come back
408
+ * to, somewhere else entirely. A server's natural source for this is the
409
+ * request it is answering, so it is caller input.
410
+ */
411
+ const assertSiteDomain = (siteDomain) => {
412
+ const invalid = () => new ValidationError('verification_invalid_site_domain', `siteDomain must be a bare host, was ${JSON.stringify(siteDomain)}`);
413
+ let parsed;
414
+ try {
415
+ parsed = new URL(`https://${siteDomain}`);
416
+ }
417
+ catch {
418
+ throw invalid();
419
+ }
420
+ if (parsed.username ||
421
+ parsed.password ||
422
+ parsed.search ||
423
+ parsed.hash ||
424
+ parsed.pathname !== '/') {
425
+ throw invalid();
426
+ }
427
+ // The host has to be the whole of what was given. Compared as a parsed host
428
+ // rather than by blacklisting characters, which is what catches a backslash
429
+ // -- browsers read it as a slash -- and what lets an IDN through, since it
430
+ // survives its own punycoding where the raw input would not.
431
+ if (new URL(`https://${parsed.host}`).href !== parsed.href) {
432
+ throw invalid();
433
+ }
434
+ return parsed.host;
435
+ };
436
+ /**
437
+ * What must be true, as aID reads it. One spelling, so the verify hand-off and
438
+ * the provider registry can be asked the same question with the same params.
439
+ *
440
+ * `context` is not among them: it is tracking rather than requirement, and each
441
+ * caller puts it where its own URL has always put it.
442
+ */
443
+ const verificationRequirementParams = (requirement) => {
444
+ const params = new URLSearchParams();
445
+ if (requirement.attributes.length > 0) {
446
+ params.set('attributes', requirement.attributes.join(','));
447
+ }
448
+ if (requirement.verifiedSession) {
449
+ params.set('verified_session', 'true');
450
+ }
451
+ if (requirement.sources.length > 0) {
452
+ params.set('sources', requirement.sources.join(','));
453
+ }
454
+ if (requirement.maxAgeSeconds !== undefined) {
455
+ params.set('max_age', String(requirement.maxAgeSeconds));
456
+ }
457
+ return params;
458
+ };
459
+ /** `/aid/verify` on the site's own domain, carrying the requirement. */
460
+ const verificationUrlFor = (siteDomain, requirement) => {
461
+ const url = new URL('/aid/verify', `https://${assertSiteDomain(siteDomain)}`);
462
+ verificationRequirementParams(requirement).forEach((value, key) => {
463
+ url.searchParams.set(key, value);
464
+ });
465
+ url.searchParams.set('requested_url', requirement.requestedUrl);
466
+ url.searchParams.set('context', requirement.context);
467
+ return url;
468
+ };
469
+ /**
470
+ * eris normalises anything outside its five known errors to `provider_error`
471
+ * before it reaches the address bar, so a value that is not in the union was
472
+ * not written by eris. Normalising the same way keeps the union closed without
473
+ * inventing an error where the param was simply absent.
474
+ */
475
+ const asVerificationError = (error) => {
476
+ if (error === null) {
477
+ return null;
478
+ }
479
+ return (VERIFICATION_ERRORS.find((known) => known === error) ?? 'provider_error');
480
+ };
481
+ const isVerificationStatus = (status) => status === 'completed' || status === 'cancelled' || status === 'failed';
482
+ /**
483
+ * Reads the outcome aID appended to the URL it returned the reader to. `null`
484
+ * on a URL carrying none, which is an ordinary page load.
485
+ *
486
+ * Pure: it neither reads nor writes the address bar, so a server can call it on
487
+ * the request URL. A status this version does not recognise reads as a failure
488
+ * rather than as nothing — the reader did go somewhere.
489
+ *
490
+ * The outcome is a hint for what to tell the reader, never authority. Gate on
491
+ * the session, on the attribute's own timestamp, or on the action's response.
492
+ */
493
+ /** Stands in for an origin that is never read. */
494
+ const RELATIVE_URL_BASE = 'https://relative.invalid';
495
+ const readVerificationOutcome = (url) => {
496
+ // A base, so a path parses as readily as a whole URL: on the server the value
497
+ // at hand is `req.url`, which in node:http and Express is `/side?verification=`
498
+ // and nothing more. Only the query is read, so the base is never seen -- and an
499
+ // absolute URL ignores it.
500
+ const { searchParams } = url instanceof URL ? url : new URL(url, RELATIVE_URL_BASE);
501
+ const status = searchParams.get(VERIFICATION_PARAM);
502
+ if (status === null) {
503
+ return null;
504
+ }
505
+ const error = asVerificationError(searchParams.get(VERIFICATION_ERROR_PARAM));
506
+ if (!isVerificationStatus(status)) {
507
+ return { status: 'failed', error: error ?? 'unknown_outcome' };
508
+ }
509
+ // Only a failure carries a reason, the way aID reads the same two params. A
510
+ // stale verification_error survives a back-button, and `if (outcome.error)`
511
+ // would then report a failure for a verification that completed.
512
+ return status === 'failed' && error !== null ? { status, error } : { status };
513
+ };
514
+
215
515
  const DEFAULT_CLIENT_ID = 'default';
516
+ /** The half of `RequestInit` these reads carry, in one place. */
517
+ const initFrom = (opts) => ({
518
+ headers: opts.headers,
519
+ signal: opts.signal,
520
+ });
216
521
  const buildUrl$1 = (path, baseUrl) => baseUrl ? `${baseUrl.replace(/\/$/, '')}${path}` : path;
217
522
  const resolveSchemaVerifiedFetch = (opts) => opts.schemaVerifiedFetch ?? coreSchemaVerifiedFetch;
218
523
  /**
@@ -232,16 +537,50 @@ const fetchSelf = (filter = [
232
537
  }
233
538
  }
234
539
  const filterQuery = filter.length > 0 ? `?filter=(${filter.join(',')})` : '';
235
- return resolveSchemaVerifiedFetch(opts)(ServiceUserSchema, buildUrl$1(`/aid/api/users/self${filterQuery}`, opts.baseUrl), { headers: opts.headers });
540
+ return resolveSchemaVerifiedFetch(opts)(ServiceUserSchema, buildUrl$1(`/aid/api/users/self${filterQuery}`, opts.baseUrl), initFrom(opts));
236
541
  };
542
+ /**
543
+ * GET /aid/api/session — the current browser session, including the
544
+ * verification stamp (`verified_at` / `verification_source`) it carries.
545
+ */
546
+ const fetchSession = (opts = {}) => resolveSchemaVerifiedFetch(opts)(SessionSchema, buildUrl$1('/aid/api/session', opts.baseUrl), initFrom(opts));
237
547
  /**
238
548
  * GET /aid/api/access — returns string[] of access features for a site.
239
549
  */
240
- const fetchAccessFeatures = (siteDomain, opts = {}) => resolveSchemaVerifiedFetch(opts)(v.array(v.string()), buildUrl$1(`/aid/api/access?${new URLSearchParams({ site_domain: siteDomain })}`, opts.baseUrl), { headers: opts.headers });
550
+ const fetchAccessFeatures = (siteDomain, opts = {}) => resolveSchemaVerifiedFetch(opts)(v.array(v.string()), buildUrl$1(`/aid/api/access?${new URLSearchParams({ site_domain: siteDomain })}`, opts.baseUrl), initFrom(opts));
241
551
  /**
242
552
  * GET /aid/login/status — login flow status enum.
243
553
  */
244
- const fetchLoginStatus = (opts = {}) => resolveSchemaVerifiedFetch(opts)(LoginStatusResponseSchema, buildUrl$1(`/aid/login/status`, opts.baseUrl), { headers: opts.headers }).then((d) => d.status);
554
+ const fetchLoginStatus = (opts = {}) => resolveSchemaVerifiedFetch(opts)(LoginStatusResponseSchema, buildUrl$1(`/aid/login/status`, opts.baseUrl), initFrom(opts)).then((d) => d.status);
555
+ /**
556
+ * GET /api/aid/verification/providers — the providers a site may offer a reader,
557
+ * in the order aID offers them, so a caller can name one, or draw its logo,
558
+ * before sending anyone anywhere.
559
+ *
560
+ * Narrowed by the same requirement the verify hand-off takes, when one is given.
561
+ * Omit it and the answer is the whole catalogue: aID refuses an empty
562
+ * requirement, so a requirement that says nothing must be sent as no params at
563
+ * all rather than as empty ones.
564
+ *
565
+ * A row's `attributes` is the provider's whole capability list rather than the
566
+ * subset asked for — it describes the provider, so narrowing to `birth_date`
567
+ * still shows BankID advertising `name`.
568
+ *
569
+ * This one lives on aID's own origin, not the site's, and is the one read here
570
+ * that needs no credential: it knows no reader.
571
+ */
572
+ const fetchVerificationProviders$1 = (requirement, opts = {}) => {
573
+ let params = new URLSearchParams();
574
+ if (requirement) {
575
+ // requestedUrl is the verify hand-off's business; the registry has no reader
576
+ // to send anywhere, so anything is a safe fill-in for a param never sent.
577
+ const normalized = normalizeVerificationRequirement(requirement, '/');
578
+ params = verificationRequirementParams(normalized);
579
+ params.set('context', normalized.context);
580
+ }
581
+ const query = params.toString();
582
+ return resolveSchemaVerifiedFetch(opts)(VerificationProvidersSchema, buildUrl$1(`/api/aid/verification/providers${query ? `?${query}` : ''}`, opts.baseUrl), initFrom(opts)).then((answer) => answer.providers);
583
+ };
245
584
 
246
585
  const buildUrl = (path, baseUrl) => baseUrl ? `${baseUrl.replace(/\/$/, '')}${path}` : path;
247
586
  /**
@@ -254,6 +593,112 @@ const fetchPrimarySite = (accessFeatures, opts = {}) => {
254
593
  })}`, opts.baseUrl), { method: 'GET', headers: opts.headers });
255
594
  };
256
595
 
596
+ /**
597
+ * The problem types aID answers with, named rather than matched by substring.
598
+ *
599
+ * A caller testing `type.includes('session/not-found')` stops matching the day
600
+ * a type is renamed, and does so silently — the branch simply never runs again.
601
+ */
602
+ const AidProblem = {
603
+ SESSION_NOT_FOUND: '/api/problem/aid/session/not-found',
604
+ SESSION_NOT_SPECIFIED: '/api/problem/aid/session/not-specified',
605
+ SESSION_IDENTIFIER_INVALID: '/api/problem/aid/session/identifier-invalid',
606
+ SESSION_NOT_VERIFIED: '/api/problem/aid/session/not-verified',
607
+ SESSION_ALREADY_ACTIVATED: '/api/problem/aid/session/already-activated',
608
+ SESSION_TOO_MANY_ACTIVATED: '/api/problem/aid/session/too-many-activated',
609
+ USER_DEACTIVATED: '/api/problem/aid/user/deactivated',
610
+ BIRTH_DATE_NOT_VERIFIED: '/api/problem/aid/user/birthdate-not-verified',
611
+ BIRTH_DATE_VERIFIED_TOO_LONG_AGO: '/api/problem/aid/user/birthdate-verified-too-long-ago',
612
+ AGREEMENT_NOT_FOUND: '/api/problem/aid/agreement/not-found',
613
+ AGREEMENT_DUPLICATE: '/api/problem/aid/agreement/duplicate',
614
+ ACTIVATION_NOT_FOUND: '/api/problem/aid/activation/not-found',
615
+ /** The request named no reader: with an m2m credential, a session with no user. */
616
+ MISSING_PARAMETER: '/api/problem/request/param/missing',
617
+ INVALID_PARAMETER: '/api/problem/request/param/invalid',
618
+ INVALID_CLIENT_CREDENTIAL: '/api/problem/request/auth/invalid-client-credential',
619
+ ACCESS_DENIED: '/api/problem/request/auth/access-denied',
620
+ INSUFFICIENT_SCOPE: '/api/problem/request/auth/oauth-insufficient-scope',
621
+ UNKNOWN_SITE: '/api/problem/onsite/unknown-site',
622
+ SITE_NOT_AID_ENABLED: '/api/problem/onsite/site-not-aid-enabled',
623
+ UNKNOWN_SERVICE_PROVIDER: '/api/problem/onsite/unknown-service-provider',
624
+ NO_BACKEND_FOR_SERVICE_PROVIDER: '/api/problem/onsite/no-backend-for-service-provider',
625
+ BACKEND_UNREACHABLE: '/api/problem/onsite/backend-unreachable',
626
+ SITE_CONFIG_UNAVAILABLE: '/api/problem/onsite/site-config-unavailable',
627
+ };
628
+ /** Some deployments answer an absolute type; the path is the part that names it. */
629
+ const pathOf = (type) => {
630
+ try {
631
+ return new URL(type).pathname;
632
+ }
633
+ catch {
634
+ return type;
635
+ }
636
+ };
637
+ /**
638
+ * The problem inside whatever the caller has to hand: the thrown error, an
639
+ * error carrying one, or a problem on its own. Taking all three is what lets a
640
+ * catch block ask its question in one line instead of unwrapping first.
641
+ */
642
+ const problemOf = (value) => {
643
+ if (value instanceof ProblemJsonError) {
644
+ return value.problem;
645
+ }
646
+ if (!value || typeof value !== 'object') {
647
+ return null;
648
+ }
649
+ // Duck-typed, not instanceof: what a catch block holds is usually somebody
650
+ // else's error carrying a plain JSON.parse result, which is a class instance
651
+ // of nothing.
652
+ const candidate = value;
653
+ if (candidate.problem && typeof candidate.problem.type === 'string') {
654
+ return candidate.problem;
655
+ }
656
+ return typeof candidate.type === 'string' ? value : null;
657
+ };
658
+ const isAidProblem = (value, ...types) => {
659
+ const problem = problemOf(value);
660
+ return (!!problem?.type && types.includes(pathOf(problem.type)));
661
+ };
662
+ /**
663
+ * Nobody is signed in. Render a login link rather than an error — this is a
664
+ * state, not a failure.
665
+ */
666
+ const LOGGED_OUT_PROBLEMS = [
667
+ AidProblem.SESSION_NOT_FOUND,
668
+ AidProblem.SESSION_NOT_SPECIFIED,
669
+ AidProblem.SESSION_IDENTIFIER_INVALID,
670
+ AidProblem.USER_DEACTIVATED,
671
+ ];
672
+ const isLoggedOut = (value) => isAidProblem(value, ...LOGGED_OUT_PROBLEMS);
673
+ /**
674
+ * No reader to answer about: signed out, or an anonymous session, which names
675
+ * no user for an m2m credential to act for.
676
+ *
677
+ * Takes the error straight from a catch block:
678
+ *
679
+ * ```ts
680
+ * try {
681
+ * return await aid.getSelf(sessionId);
682
+ * } catch (error) {
683
+ * if (namesNoReader(error)) return null;
684
+ * throw error;
685
+ * }
686
+ * ```
687
+ *
688
+ * Deliberately distinct from every 4xx. An unapproved audience or a missing
689
+ * scope is a configuration fault, and reading it as a signed-out reader hides
690
+ * it behind a page that looks like it is working.
691
+ *
692
+ * `MISSING_PARAMETER` is in the list on eris' behaviour rather than on its name:
693
+ * both places that answer this problem type mean "the request named no reader"
694
+ * — an m2m credential with no session, and a session identifying no user. An
695
+ * ordinary missing parameter answers in eris' older JSON:API shape, which
696
+ * carries no `type` at all and so cannot reach here. That is a convention, not
697
+ * a guarantee the type name makes, so a third place answering it for a real
698
+ * missing parameter would widen this helper silently (amedia-user-js#1299).
699
+ */
700
+ const namesNoReader = (value) => isLoggedOut(value) || isAidProblem(value, AidProblem.MISSING_PARAMETER);
701
+
257
702
  /**
258
703
  * Reject URLs that are not absolute http(s) — protects against SSRF via
259
704
  * `file:`, `gopher:`, missing scheme (empty → relative), or malformed input
@@ -317,6 +762,85 @@ const createAidClient = (options) => {
317
762
  };
318
763
  };
319
764
 
765
+ /** The router reads this; `Host` cannot be set from `fetch`. */
766
+ const SITE_HEADER = 'X-Aid-Site';
767
+ const SESSION_HEADER = 'X-Aid-Session';
768
+ /**
769
+ * The site's own origin unless another was named. Derived from the same
770
+ * `siteDomain` rather than passed beside it, so the common case cannot point at
771
+ * one site while naming another — naming a different origin stays possible,
772
+ * because crossing environments is the reason to.
773
+ */
774
+ const baseUrlOf = (options) => options.apiOrigin ?? `https://${options.siteDomain}`;
775
+ const DEFAULT_TIMEOUT_MS = 3000;
776
+ /**
777
+ * The caller's own signal and the timeout, whichever fires first. `AbortSignal`
778
+ * has `any` for exactly this, and a timeout of its own needs no clearing.
779
+ */
780
+ const abortSignalFor = (options) => {
781
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
782
+ return options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
783
+ };
784
+ const requestOptions = async (options, sessionId) => {
785
+ const headers = {
786
+ ...options.headers,
787
+ // Already a host that round-tripped through `new URL`, so unlike the two
788
+ // below it cannot carry CR, LF or NUL and needs no check of its own.
789
+ [SITE_HEADER]: options.siteDomain,
790
+ [SESSION_HEADER]: assertHeaderSafe(sessionId, 'sessionId'),
791
+ };
792
+ if (options.token) {
793
+ const token = typeof options.token === 'function'
794
+ ? await options.token()
795
+ : options.token;
796
+ headers.Authorization = `Bearer ${assertHeaderSafe(token, 'token')}`;
797
+ }
798
+ return {
799
+ baseUrl: baseUrlOf(options),
800
+ headers,
801
+ signal: abortSignalFor(options),
802
+ };
803
+ };
804
+ /**
805
+ * A server-side client for the aID On-Site API.
806
+ *
807
+ * Two credentials, two jobs: `X-Aid-Session` says which reader the call is
808
+ * about, and the m2m token says what may be read about them. Together they
809
+ * reach data the reader's own browser session is not granted, about a reader
810
+ * the session proves is still signed in.
811
+ *
812
+ * The site travels in `X-Aid-Site` rather than `Host`, which is a forbidden
813
+ * header name — `fetch` drops it without a word, and the router would resolve
814
+ * its own address instead. It is sent on both roads: going direct, the URL
815
+ * already names the site and eris reads it off `Host`, so the header is spare
816
+ * rather than wrong, and one request shape serves both.
817
+ *
818
+ * Holds nothing: three closures over these options, no cache and no pool, about
819
+ * a microsecond to build. So a server juggling many sites makes one per request
820
+ * from the site it is answering for, rather than keeping a map of them — the
821
+ * token provider is the thing worth keeping, and it lives outside.
822
+ *
823
+ * @see https://www.aid.no/aid/docs/developer/aid-on-site-api
824
+ */
825
+ const createOnSiteClient = (options) => {
826
+ // Normalised once and used for everything after. `new URL` punycodes the
827
+ // host it builds while `Headers` would send the raw one, so an IDN site left
828
+ // unnormalised has the URL and X-Aid-Site naming different sites -- the thing
829
+ // deriving both from one `siteDomain` was meant to make impossible.
830
+ const site = {
831
+ ...options,
832
+ siteDomain: assertSiteDomain(options.siteDomain),
833
+ };
834
+ assertHttpUrl(baseUrlOf(site), 'apiOrigin');
835
+ return {
836
+ getSelf: async (sessionId, filter) => fetchSelf(filter, await requestOptions(site, sessionId)),
837
+ getSession: async (sessionId) => fetchSession(await requestOptions(site, sessionId)),
838
+ getAccessFeatures: async (sessionId, siteDomain) => fetchAccessFeatures(siteDomain === undefined
839
+ ? site.siteDomain
840
+ : assertSiteDomain(siteDomain), await requestOptions(site, sessionId)),
841
+ };
842
+ };
843
+
320
844
  const optsWith = (c) => ({
321
845
  baseUrl: c.baseUrl,
322
846
  // Caller headers spread FIRST so they cannot override the Authorization
@@ -333,6 +857,42 @@ const createShamoClient = (options) => {
333
857
  };
334
858
  };
335
859
 
860
+ /**
861
+ * The `/aid/verify` link for a requirement, ready to put in an `href`.
862
+ *
863
+ * Built on the server so the link is in the first render rather than after a
864
+ * script has loaded. Throws for a requirement aID would refuse anyway — an
865
+ * unknown attribute, a `sources` that excludes one, nothing required at all —
866
+ * so a caller bug costs no round trip.
867
+ *
868
+ * @see https://www.aid.no/aid/docs/developer/aid-on-site-verification
869
+ */
870
+ const buildVerificationUrl = ({ siteDomain, ...requirement }) => verificationUrlFor(siteDomain, normalizeVerificationRequirement(requirement, requirement.requestedUrl));
871
+ /** Where aID answers in production. */
872
+ const AID_ORIGIN = 'https://www.aid.no';
873
+ /**
874
+ * The providers aID may offer a reader, in aID's own order — what to call each
875
+ * one and what it looks like, so a server-rendered page can draw the logo it is
876
+ * about to send the reader to.
877
+ *
878
+ * Narrowed by a requirement when given; omit it for the whole catalogue.
879
+ *
880
+ * Unlike everything else here this one lives on aID's own origin rather than
881
+ * the site's, and needs no credential: the registry knows no reader. That
882
+ * origin is filled in, because in a browser a relative URL would have resolved
883
+ * against the page and here there is no page — `fetch('/api/aid/...')` simply
884
+ * throws. Name another `baseUrl` to reach another environment.
885
+ *
886
+ * `icon_svg` is markup from the network. Rendering it through `innerHTML` runs
887
+ * whatever it contains; `<img src="data:image/svg+xml;base64,…">` does not.
888
+ *
889
+ * @see https://www.aid.no/aid/docs/developer/aid-on-site-verification
890
+ */
891
+ const fetchVerificationProviders = (requirement, opts = {}) => fetchVerificationProviders$1(requirement, {
892
+ baseUrl: AID_ORIGIN,
893
+ ...opts,
894
+ });
895
+
336
896
  /**
337
897
  * Cache of JWKS resolvers keyed by URL. `createRemoteJWKSet` already caches
338
898
  * the fetched JWKS in memory — we just avoid constructing multiple resolvers
@@ -437,5 +997,5 @@ function mapJoseError(err) {
437
997
  return new ValidationError('validation_failed', String(err));
438
998
  }
439
999
 
440
- export { AffiliationType, DEFAULT_CLIENT_ID, FetchTimeoutError, IgnoredNetworkError, LoginStatus, ProblemJsonError, ResponseError, ServerError, ValidationError, clearJwksCache, createAidClient, createShamoClient, validateToken };
1000
+ export { AffiliationType, AidProblem, DEFAULT_CLIENT_ID, FetchTimeoutError, IgnoredNetworkError, LOGGED_OUT_PROBLEMS, LoginStatus, MAX_AGE_CEILING_SECONDS, ProblemJsonError, ResponseError, SESSION_HEADER, SITE_HEADER, ServerError, VERIFIABLE_ATTRIBUTES, VERIFICATION_SOURCES, ValidationError, buildVerificationUrl, clearJwksCache, createAidClient, createOnSiteClient, createShamoClient, fetchVerificationProviders, isAidProblem, isLoggedOut, namesNoReader, normalizeVerificationRequirement, readVerificationOutcome, validateToken, verificationSourceOf, verificationUrlFor };
441
1001
  //# sourceMappingURL=user.node.js.map