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