@sirosfoundation/wmp-js 0.6.0 → 0.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.
@@ -43,11 +43,21 @@ export declare class CompletionResultError extends Error {
43
43
  * - a decrypt_credential_response result has credential_count (1 to 256) or
44
44
  * transaction_id, never both, and carries no credentials or
45
45
  * credential_metadata; interval only accompanies transaction_id;
46
+ * - a vp_token, when present, is a presentation form {@link validVpToken} allows;
47
+ * presentation_submission is an object and response_code a string (Section 3.2.4);
46
48
  * - a response_jwe is a compact JWE of five base64url segments (only the
47
49
  * encrypted key may be empty), at most {@link MAX_RESPONSE_JWE_LEN} long, and
48
50
  * never accompanies a vp_token.
49
51
  */
50
52
  export declare function validateCompletionResult(result: unknown, secretMembers?: readonly string[]): void;
53
+ /**
54
+ * A vp_token the profile allows (table in profile 3.2.5, DCQL form in 7.x): a
55
+ * non-empty string, a non-empty array of non-empty strings, or an object mapping
56
+ * query ids to non-empty arrays of non-empty strings. Anything else (booleans,
57
+ * numbers, null, empty or mixed values) is not a presentation. The predicate
58
+ * form of {@link validateVpToken} — the same rule, exposed for the flows.
59
+ */
60
+ export declare function validVpToken(v: unknown): boolean;
51
61
  /**
52
62
  * Checks the `result` of a wmp.flow.complete for a flow of type match
53
63
  * (Section 3.3.2). The result is a closed set: nothing but satisfiable,
@@ -41,7 +41,7 @@ function isObj(v) {
41
41
  return typeof v === "object" && v !== null && !Array.isArray(v);
42
42
  }
43
43
  function has(o, k) {
44
- return Object.prototype.hasOwnProperty.call(o, k);
44
+ return Object.hasOwn(o, k);
45
45
  }
46
46
  function fail(msg) {
47
47
  throw new CompletionResultError(msg);
@@ -61,6 +61,8 @@ function fail(msg) {
61
61
  * - a decrypt_credential_response result has credential_count (1 to 256) or
62
62
  * transaction_id, never both, and carries no credentials or
63
63
  * credential_metadata; interval only accompanies transaction_id;
64
+ * - a vp_token, when present, is a presentation form {@link validVpToken} allows;
65
+ * presentation_submission is an object and response_code a string (Section 3.2.4);
64
66
  * - a response_jwe is a compact JWE of five base64url segments (only the
65
67
  * encrypted key may be empty), at most {@link MAX_RESPONSE_JWE_LEN} long, and
66
68
  * never accompanies a vp_token.
@@ -76,6 +78,7 @@ export function validateCompletionResult(result, secretMembers = DEFAULT_SECRET_
76
78
  validateDecryptResult(result);
77
79
  validateResponseJWE(result);
78
80
  validateVpToken(result);
81
+ validatePresentationMembers(result);
79
82
  }
80
83
  // OpenID4x §3.2.4: a sign result's vp_token is a non-empty string, a non-empty
81
84
  // array of non-empty strings, or a non-empty object of non-empty arrays of
@@ -118,6 +121,33 @@ function validateVpToken(m) {
118
121
  }
119
122
  fail("vp_token is not a string, array, or object");
120
123
  }
124
+ /** The result members of an oid4vp completion (Section 3.2.4): each, when present, has its type.
125
+ * The vp_token form itself is {@link validateVpToken}'s (the same check, landed with it). */
126
+ function validatePresentationMembers(m) {
127
+ if (has(m, "presentation_submission") && !isObj(m.presentation_submission)) {
128
+ fail("presentation_submission is not an object");
129
+ }
130
+ if (has(m, "response_code") && typeof m.response_code !== "string") {
131
+ fail("response_code is not a string");
132
+ }
133
+ }
134
+ /**
135
+ * A vp_token the profile allows (table in profile 3.2.5, DCQL form in 7.x): a
136
+ * non-empty string, a non-empty array of non-empty strings, or an object mapping
137
+ * query ids to non-empty arrays of non-empty strings. Anything else (booleans,
138
+ * numbers, null, empty or mixed values) is not a presentation. The predicate
139
+ * form of {@link validateVpToken} — the same rule, exposed for the flows.
140
+ */
141
+ export function validVpToken(v) {
142
+ const str = (x) => typeof x === "string" && x !== "";
143
+ const strs = (x) => Array.isArray(x) && x.length > 0 && x.every(str);
144
+ if (str(v) || strs(v))
145
+ return true;
146
+ if (typeof v !== "object" || v === null || Array.isArray(v))
147
+ return false;
148
+ const vals = Object.values(v);
149
+ return vals.length > 0 && vals.every(strs);
150
+ }
121
151
  function validateEncryptedFlag(m) {
122
152
  if (!has(m, "credential_response_encrypted"))
123
153
  return false;
@@ -235,8 +265,8 @@ function validateResponseJWE(m) {
235
265
  // ---------------------------------------------------------------------------
236
266
  // match flow result (Section 3.3)
237
267
  // ---------------------------------------------------------------------------
238
- const MATCH_MEMBERS = ["satisfiable", "satisfiable_query_ids", "selection_handle", "code"];
239
- const MATCH_CODES = ["no_match", "insufficient", "error"];
268
+ const MATCH_MEMBERS = new Set(["satisfiable", "satisfiable_query_ids", "selection_handle", "code"]);
269
+ const MATCH_CODES = new Set(["no_match", "insufficient", "error"]);
240
270
  // 22 or more base64url characters, no padding, canonical length (4n, 4n+2, 4n+3).
241
271
  const MATCH_HANDLE = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;
242
272
  /**
@@ -254,38 +284,41 @@ export function validateMatchResult(result, queryIds) {
254
284
  if (!isObj(result))
255
285
  fail("match result is not an object");
256
286
  for (const k of Object.keys(result)) {
257
- if (!MATCH_MEMBERS.includes(k))
287
+ if (!MATCH_MEMBERS.has(k))
258
288
  fail("match result carries a member outside the closed set");
259
289
  }
290
+ validateMatchSatisfiable(result);
291
+ validateMatchIds(result, queryIds);
292
+ if (has(result, "selection_handle")) {
293
+ const h = result.selection_handle;
294
+ if (typeof h !== "string" || h.length < 22 || !MATCH_HANDLE.test(h))
295
+ fail("selection_handle is not a base64url string of at least 22 characters");
296
+ }
297
+ }
298
+ function validateMatchSatisfiable(result) {
260
299
  if (typeof result.satisfiable !== "boolean")
261
300
  fail("satisfiable is not a boolean");
262
- if (result.satisfiable) {
263
- if (has(result, "code"))
264
- fail("code present although satisfiable is true");
265
- }
266
- else if (!has(result, "code")) {
301
+ if (result.satisfiable && has(result, "code"))
302
+ fail("code present although satisfiable is true");
303
+ if (!result.satisfiable && !has(result, "code"))
267
304
  fail("code absent although satisfiable is false");
268
- }
269
- if (has(result, "code") && !MATCH_CODES.includes(result.code)) {
305
+ if (has(result, "code") && !MATCH_CODES.has(result.code)) {
270
306
  fail("code is not one of no_match, insufficient, error");
271
307
  }
272
- if (has(result, "satisfiable_query_ids")) {
273
- const ids = result.satisfiable_query_ids;
274
- if (!Array.isArray(ids) || ids.some((x) => typeof x !== "string"))
275
- fail("satisfiable_query_ids is not an array of strings");
276
- const seen = new Set();
277
- for (const id of ids) {
278
- if (seen.has(id))
279
- fail("satisfiable_query_ids repeats an element");
280
- seen.add(id);
281
- if (queryIds && !queryIds.includes(id))
282
- fail("satisfiable_query_ids has an element that is not an id of the query");
283
- }
284
- }
285
- if (has(result, "selection_handle")) {
286
- const h = result.selection_handle;
287
- if (typeof h !== "string" || h.length < 22 || !MATCH_HANDLE.test(h))
288
- fail("selection_handle is not a base64url string of at least 22 characters");
308
+ }
309
+ function validateMatchIds(result, queryIds) {
310
+ if (!has(result, "satisfiable_query_ids"))
311
+ return;
312
+ const ids = result.satisfiable_query_ids;
313
+ if (!Array.isArray(ids) || ids.some((x) => typeof x !== "string"))
314
+ fail("satisfiable_query_ids is not an array of strings");
315
+ const seen = new Set();
316
+ for (const id of ids) {
317
+ if (seen.has(id))
318
+ fail("satisfiable_query_ids repeats an element");
319
+ seen.add(id);
320
+ if (queryIds && !queryIds.includes(id))
321
+ fail("satisfiable_query_ids has an element that is not an id of the query");
289
322
  }
290
323
  }
291
324
  /** The `id` of each credential query of a DCQL query (for {@link validateMatchResult}). */
@@ -331,13 +364,7 @@ export function splitReplaySecrets(data) {
331
364
  const rawMethod = env.get("method");
332
365
  if (rawMethod === undefined)
333
366
  return { ok: true, replay: text }; // a response carries no completion
334
- let method;
335
- try {
336
- method = JSON.parse(rawMethod);
337
- }
338
- catch {
339
- return REFUSED;
340
- }
367
+ const method = parseJson(rawMethod);
341
368
  if (typeof method !== "string")
342
369
  return REFUSED;
343
370
  if (method !== METHOD_FLOW_COMPLETE)
@@ -367,6 +394,15 @@ export function splitReplaySecrets(data) {
367
394
  env.set("params", assemble(params));
368
395
  return { ok: true, replay: assemble(env), live: text };
369
396
  }
397
+ /** JSON.parse that yields undefined for text that is not JSON (undefined is no JSON value). */
398
+ function parseJson(text) {
399
+ try {
400
+ return JSON.parse(text);
401
+ }
402
+ catch {
403
+ return undefined;
404
+ }
405
+ }
370
406
  const REFUSED = { ok: false, replay: "" };
371
407
  function assemble(m) {
372
408
  return "{" + [...m].map(([k, v]) => `${JSON.stringify(k)}:${v}`).join(",") + "}";
@@ -381,13 +417,13 @@ function assemble(m) {
381
417
  function mayNeedRedaction(text) {
382
418
  const lower = text.toLowerCase();
383
419
  // eslint-disable-next-line no-control-regex
384
- if (/[^\u0000-\u007f]/.test(text) || lower.includes("\\u") || lower.includes(`"${REDACTED_MEMBERS_KEY}"`)) {
420
+ if (/[^\u0000-\u007f]/.test(text) || lower.includes(String.raw `\u`) || lower.includes(`"${REDACTED_MEMBERS_KEY}"`)) {
385
421
  return true;
386
422
  }
387
423
  return REPLAY_SECRET_MEMBERS.some((k) => lower.includes(`"${k}"`));
388
424
  }
389
425
  function foldCase(s) {
390
- return s.replace(/ſ/g, "s").replace(/K/g, "k").toLowerCase();
426
+ return s.replaceAll("\u017f", "s").replaceAll("\u212a", "k").toLowerCase();
391
427
  }
392
428
  /**
393
429
  * Splits a JSON text that is exactly one object into its members, in order,
@@ -396,118 +432,113 @@ function foldCase(s) {
396
432
  * decoding, or that has a name equal to one of `exact` only up to letter case.
397
433
  */
398
434
  function scanObject(text, exact) {
399
- let i = 0;
400
435
  const n = text.length;
401
- const ws = () => {
402
- while (i < n && (text[i] === " " || text[i] === "\t" || text[i] === "\n" || text[i] === "\r"))
403
- i++;
404
- };
405
- // Returns the end index (exclusive) of the string literal starting at i.
406
- const stringEnd = (start) => {
407
- let j = start + 1;
408
- while (j < n) {
409
- const c = text[j];
410
- if (c === "\\")
411
- j += 2;
412
- else if (c === '"')
413
- return j + 1;
414
- else
415
- j++;
416
- }
417
- return -1;
418
- };
419
- // Returns the end index of the JSON value starting at i, or -1.
420
- const valueEnd = (start) => {
421
- const c = text[start];
422
- if (c === '"')
423
- return stringEnd(start);
424
- if (c === "{" || c === "[") {
425
- let depth = 0;
426
- let j = start;
427
- while (j < n) {
428
- const d = text[j];
429
- if (d === '"') {
430
- const e = stringEnd(j);
431
- if (e < 0)
432
- return -1;
433
- j = e;
434
- continue;
435
- }
436
- if (d === "{" || d === "[")
437
- depth++;
438
- else if (d === "}" || d === "]") {
439
- depth--;
440
- if (depth === 0)
441
- return j + 1;
442
- }
443
- j++;
444
- }
445
- return -1;
446
- }
447
- let j = start;
448
- while (j < n && !/[,}\]\s]/.test(text[j]))
449
- j++;
450
- return j > start ? j : -1;
451
- };
452
- ws();
436
+ let i = skipWs(text, 0);
453
437
  if (text[i] !== "{")
454
438
  return undefined;
455
- i++;
439
+ i = skipWs(text, i + 1);
456
440
  const members = new Map();
457
- ws();
458
- if (text[i] === "}") {
459
- i++;
460
- }
461
- else {
462
- for (;;) {
463
- ws();
464
- if (text[i] !== '"')
465
- return undefined;
466
- const ke = stringEnd(i);
467
- if (ke < 0)
468
- return undefined;
469
- let key;
470
- try {
471
- key = JSON.parse(text.slice(i, ke));
472
- }
473
- catch {
474
- return undefined;
475
- }
476
- i = ke;
477
- ws();
478
- if (text[i] !== ":")
479
- return undefined;
441
+ if (text[i] === "}")
442
+ return skipWs(text, i + 1) === n ? members : undefined;
443
+ for (;;) {
444
+ const next = scanMember(text, skipWs(text, i), members, exact);
445
+ if (next < 0)
446
+ return undefined;
447
+ i = skipWs(text, next);
448
+ if (text[i] === ",") {
480
449
  i++;
481
- ws();
482
- const ve = valueEnd(i);
483
- if (ve < 0)
484
- return undefined;
485
- const raw = text.slice(i, ve);
486
- try {
487
- JSON.parse(raw); // the value must itself be well-formed JSON
488
- }
489
- catch {
490
- return undefined;
491
- }
492
- if (members.has(key))
493
- return undefined;
494
- const folded = foldCase(key);
495
- if (exact.some((e) => key !== e && folded === e))
496
- return undefined;
497
- members.set(key, raw);
498
- i = ve;
499
- ws();
500
- if (text[i] === ",") {
501
- i++;
502
- continue;
503
- }
504
- if (text[i] === "}") {
505
- i++;
506
- break;
507
- }
450
+ continue;
451
+ }
452
+ if (text[i] !== "}")
508
453
  return undefined;
454
+ return skipWs(text, i + 1) === n ? members : undefined;
455
+ }
456
+ }
457
+ function skipWs(text, from) {
458
+ let i = from;
459
+ while (i < text.length && (text[i] === " " || text[i] === "\t" || text[i] === "\n" || text[i] === "\r"))
460
+ i++;
461
+ return i;
462
+ }
463
+ /** Returns the end index (exclusive) of the string literal starting at `start`, or -1. */
464
+ function stringEnd(text, start) {
465
+ let j = start + 1;
466
+ while (j < text.length) {
467
+ const c = text[j];
468
+ if (c === "\\")
469
+ j += 2;
470
+ else if (c === '"')
471
+ return j + 1;
472
+ else
473
+ j++;
474
+ }
475
+ return -1;
476
+ }
477
+ /** Returns the end index of the bracketed value (object or array) starting at `start`, or -1. */
478
+ function bracketedEnd(text, start) {
479
+ let depth = 0;
480
+ let j = start;
481
+ while (j < text.length) {
482
+ const d = text[j];
483
+ if (d === '"') {
484
+ const e = stringEnd(text, j);
485
+ if (e < 0)
486
+ return -1;
487
+ j = e;
488
+ continue;
509
489
  }
490
+ if (d === "{" || d === "[")
491
+ depth++;
492
+ else if (d === "}" || d === "]") {
493
+ depth--;
494
+ if (depth === 0)
495
+ return j + 1;
496
+ }
497
+ j++;
510
498
  }
511
- ws();
512
- return i === n ? members : undefined;
499
+ return -1;
500
+ }
501
+ /** Returns the end index of the JSON value starting at `start`, or -1. */
502
+ function valueEnd(text, start) {
503
+ const c = text[start];
504
+ if (c === '"')
505
+ return stringEnd(text, start);
506
+ if (c === "{" || c === "[")
507
+ return bracketedEnd(text, start);
508
+ let j = start;
509
+ while (j < text.length && !/[,}\]\s]/.test(text[j]))
510
+ j++;
511
+ return j > start ? j : -1;
512
+ }
513
+ /**
514
+ * Scans one `"name": value` member starting at `start` and records it in
515
+ * `members`. Returns the index after the value, or -1 when the member is
516
+ * malformed, repeated, or its name equals one of `exact` only up to letter case.
517
+ */
518
+ function scanMember(text, start, members, exact) {
519
+ if (text[start] !== '"')
520
+ return -1;
521
+ const ke = stringEnd(text, start);
522
+ if (ke < 0)
523
+ return -1;
524
+ const key = parseJson(text.slice(start, ke));
525
+ if (typeof key !== "string")
526
+ return -1;
527
+ const colon = skipWs(text, ke);
528
+ if (text[colon] !== ":")
529
+ return -1;
530
+ const vs = skipWs(text, colon + 1);
531
+ const ve = valueEnd(text, vs);
532
+ if (ve < 0)
533
+ return -1;
534
+ const raw = text.slice(vs, ve);
535
+ if (parseJson(raw) === undefined)
536
+ return -1; // the value must itself be well-formed JSON
537
+ if (members.has(key))
538
+ return -1;
539
+ const folded = foldCase(key);
540
+ if (exact.some((e) => key !== e && folded === e))
541
+ return -1;
542
+ members.set(key, raw);
543
+ return ve;
513
544
  }
package/dist/consent.js CHANGED
@@ -56,8 +56,8 @@ export function newSelectionHandle() {
56
56
  const bytes = getRandomValues(16);
57
57
  let bin = "";
58
58
  for (const b of bytes)
59
- bin += String.fromCharCode(b);
60
- return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
59
+ bin += String.fromCodePoint(b);
60
+ return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
61
61
  }
62
62
  function isObj(v) {
63
63
  return typeof v === "object" && v !== null && !Array.isArray(v);
@@ -1,8 +1,16 @@
1
1
  /**
2
2
  * WMP endpoint discovery — mirrors go-wmp/pkg/wmp/discovery.go.
3
3
  */
4
- /** Well-known WMP configuration as served at /.well-known/wmp-configuration. */
4
+ /**
5
+ * Well-known WMP configuration as served at /.well-known/wmp-configuration,
6
+ * or below it for a tenant.
7
+ */
5
8
  export interface WellKnownConfig {
9
+ /**
10
+ * The discovery base the document describes:
11
+ * `https://<host><tenant-path>`. Required for a tenant path.
12
+ */
13
+ discovery_base?: string;
6
14
  supported_versions: string[];
7
15
  endpoints: Record<string, string>;
8
16
  security_modes: string[];
@@ -38,14 +46,46 @@ export interface RecipientMetadata {
38
46
  */
39
47
  export declare function extractDomain(identifier: string): string;
40
48
  /**
41
- * Fetch the well-known WMP configuration for any WMP identifier.
49
+ * Where the well-known configuration of a domain-based identifier is found
50
+ * (WMP Core 7.5.1): a host and, for a tenant of a host that serves several
51
+ * providers, the tenant's path.
52
+ */
53
+ export interface DiscoveryBase {
54
+ /** The host, with its port when the identifier names one. */
55
+ host: string;
56
+ /** Empty for the whole host; otherwise starts with "/", no trailing "/". */
57
+ tenantPath: string;
58
+ }
59
+ /**
60
+ * Derive the discovery base of an identifier, or `null` when it has none.
61
+ *
62
+ * x509:san:dns:example.com -> example.com
63
+ * https://example.com/tenant1 -> example.com, /tenant1
64
+ * x509:san:uri:https://example.com/tenant -> example.com, /tenant
65
+ * did:web:example.com -> example.com
66
+ *
67
+ * A did:web identifier with a path has none: the did:web method resolves it
68
+ * through its DID Document, whose WMPMessaging service names the endpoint
69
+ * (WMP Core 7.5.4). An identifier with a query, a fragment, userinfo or a
70
+ * "." or ".." path segment has none either.
71
+ */
72
+ export declare function discoveryBase(identifier: string): DiscoveryBase | null;
73
+ /**
74
+ * The URL of a base's configuration: the well-known segment inserted between
75
+ * the host and the tenant path, as RFC 8414 Section 3.1 does.
76
+ */
77
+ export declare function wellKnownUrl(base: DiscoveryBase): string;
78
+ /**
79
+ * Fetch the well-known WMP configuration for a domain-based WMP identifier.
42
80
  *
43
- * For a full URL (e.g. `https://host/wmp-engine/wmp`), tries the well-known
44
- * at the URL's own path prefix FIRST (`https://host/wmp-engine/.well-known/
45
- * wmp-configuration`) — path-prefixed deployments (a reverse proxy's
46
- * location) serve it there — and falls back to the domain root.
47
- * For bare identifiers (domains, DIDs), fetches the domain root.
81
+ * The configuration is fetched at exactly the URL of the identifier's
82
+ * discovery base ({@link discoveryBase}, {@link wellKnownUrl}):
83
+ * `https://host/tenant1` resolves at
84
+ * `https://host/.well-known/wmp-configuration/tenant1`. A tenant never gets
85
+ * its host's configuration, and the document's `discovery_base` must name
86
+ * the base: required for a tenant, checked when present for a whole host.
48
87
  *
49
- * Throws if no domain can be extracted or every fetch fails.
88
+ * Throws if the identifier has no discovery base, the fetch fails, or the
89
+ * document is for another base.
50
90
  */
51
91
  export declare function discoverEndpoint(identifier: string, fetchFn?: typeof globalThis.fetch): Promise<WellKnownConfig>;
package/dist/discovery.js CHANGED
@@ -48,54 +48,135 @@ export function extractDomain(identifier) {
48
48
  }
49
49
  return "";
50
50
  }
51
+ const HOST_RE = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*(:\d{1,5})?$/i;
52
+ const IPV6_HOST_RE = /^\[[0-9a-f:.]+\](:\d{1,5})?$/i;
53
+ function hostBase(host) {
54
+ if (host.length > 259 || !(HOST_RE.test(host) || IPV6_HOST_RE.test(host))) {
55
+ return null;
56
+ }
57
+ return { host, tenantPath: "" };
58
+ }
51
59
  /**
52
- * Fetch the well-known WMP configuration for any WMP identifier.
53
- *
54
- * For a full URL (e.g. `https://host/wmp-engine/wmp`), tries the well-known
55
- * at the URL's own path prefix FIRST (`https://host/wmp-engine/.well-known/
56
- * wmp-configuration`) — path-prefixed deployments (a reverse proxy's
57
- * location) serve it there — and falls back to the domain root.
58
- * For bare identifiers (domains, DIDs), fetches the domain root.
59
- *
60
- * Throws if no domain can be extracted or every fetch fails.
60
+ * The base of an https URL, read from the string as written: `URL` would
61
+ * resolve dot segments and drop an empty query, and the identifier is what
62
+ * the tenant path is compared with.
61
63
  */
62
- export async function discoverEndpoint(identifier, fetchFn = globalThis.fetch.bind(globalThis)) {
63
- const domain = extractDomain(identifier);
64
- if (!domain) {
65
- throw new Error(`Cannot extract domain from identifier "${identifier}": use session parameters or a profile resolver`);
64
+ function urlBase(raw) {
65
+ if (!raw.startsWith("https://") || /[?#\\\s]/.test(raw)) {
66
+ return null;
66
67
  }
67
- // The candidate well-known URLs, first-wins: the URL's own path prefix
68
- // (a reverse-proxied deployment), then the domain root.
69
- const candidates = [];
70
- if (identifier.startsWith("https://")) {
68
+ const rest = raw.slice("https://".length);
69
+ const slash = rest.indexOf("/");
70
+ const base = hostBase(slash < 0 ? rest : rest.slice(0, slash));
71
+ if (!base) {
72
+ return null;
73
+ }
74
+ let end = rest.length;
75
+ while (slash >= 0 && end > slash && rest[end - 1] === "/") {
76
+ end--;
77
+ }
78
+ const tenantPath = slash < 0 ? "" : rest.slice(slash, end);
79
+ for (const segment of tenantPath.split("/")) {
80
+ let decoded;
71
81
  try {
72
- const url = new URL(identifier);
73
- const path = url.pathname.replace(/\/+$/, "").replace(/\/wmp$/, "");
74
- if (path && path !== "/") {
75
- candidates.push(`${url.origin}${path}/.well-known/wmp-configuration`);
76
- }
82
+ decoded = decodeURIComponent(segment);
77
83
  }
78
84
  catch {
79
- // fall through to the domain root
85
+ return null;
86
+ }
87
+ if (decoded === "." || decoded === "..") {
88
+ return null;
80
89
  }
81
90
  }
82
- candidates.push(`https://${domain}/.well-known/wmp-configuration`);
83
- let lastError;
84
- for (const url of candidates) {
91
+ return { host: base.host, tenantPath };
92
+ }
93
+ /**
94
+ * Derive the discovery base of an identifier, or `null` when it has none.
95
+ *
96
+ * x509:san:dns:example.com -> example.com
97
+ * https://example.com/tenant1 -> example.com, /tenant1
98
+ * x509:san:uri:https://example.com/tenant -> example.com, /tenant
99
+ * did:web:example.com -> example.com
100
+ *
101
+ * A did:web identifier with a path has none: the did:web method resolves it
102
+ * through its DID Document, whose WMPMessaging service names the endpoint
103
+ * (WMP Core 7.5.4). An identifier with a query, a fragment, userinfo or a
104
+ * "." or ".." path segment has none either.
105
+ */
106
+ export function discoveryBase(identifier) {
107
+ if (identifier.startsWith("x509:san:dns:")) {
108
+ return hostBase(identifier.slice("x509:san:dns:".length));
109
+ }
110
+ if (identifier.startsWith("x509:san:uri:")) {
111
+ return urlBase(identifier.slice("x509:san:uri:".length));
112
+ }
113
+ if (identifier.startsWith("https://")) {
114
+ return urlBase(identifier);
115
+ }
116
+ if (identifier.startsWith("did:web:")) {
117
+ const parts = identifier.slice("did:web:".length).split(":");
118
+ if (parts.length !== 1) {
119
+ return null;
120
+ }
85
121
  try {
86
- const resp = await fetchFn(url, {
87
- headers: { Accept: "application/json" },
88
- });
89
- if (resp.ok) {
90
- return (await resp.json());
91
- }
92
- lastError = new Error(`WMP discovery failed for ${url}: HTTP ${resp.status}`);
122
+ return hostBase(decodeURIComponent(parts[0]));
93
123
  }
94
- catch (err) {
95
- lastError = err;
124
+ catch {
125
+ return null;
96
126
  }
97
127
  }
98
- throw lastError instanceof Error
99
- ? lastError
100
- : new Error(`WMP discovery failed for ${identifier}`);
128
+ return null;
129
+ }
130
+ /**
131
+ * The URL of a base's configuration: the well-known segment inserted between
132
+ * the host and the tenant path, as RFC 8414 Section 3.1 does.
133
+ */
134
+ export function wellKnownUrl(base) {
135
+ return `https://${base.host}/.well-known/wmp-configuration${base.tenantPath}`;
136
+ }
137
+ /** Whether a configuration describes the base it was fetched for. */
138
+ function describesBase(config, base) {
139
+ if (config.discovery_base === undefined || config.discovery_base === "") {
140
+ return base.tenantPath === "";
141
+ }
142
+ // The declared base is compared as written: a trailing "/" is not the
143
+ // base, only an identifier's path is trimmed.
144
+ if (typeof config.discovery_base !== "string" ||
145
+ config.discovery_base.endsWith("/")) {
146
+ return false;
147
+ }
148
+ // The scheme compares case-insensitively, like the host.
149
+ const got = urlBase(config.discovery_base.replace(/^https:/i, "https:"));
150
+ return (got !== null &&
151
+ got.host.toLowerCase() === base.host.toLowerCase() &&
152
+ got.tenantPath === base.tenantPath);
153
+ }
154
+ /**
155
+ * Fetch the well-known WMP configuration for a domain-based WMP identifier.
156
+ *
157
+ * The configuration is fetched at exactly the URL of the identifier's
158
+ * discovery base ({@link discoveryBase}, {@link wellKnownUrl}):
159
+ * `https://host/tenant1` resolves at
160
+ * `https://host/.well-known/wmp-configuration/tenant1`. A tenant never gets
161
+ * its host's configuration, and the document's `discovery_base` must name
162
+ * the base: required for a tenant, checked when present for a whole host.
163
+ *
164
+ * Throws if the identifier has no discovery base, the fetch fails, or the
165
+ * document is for another base.
166
+ */
167
+ export async function discoverEndpoint(identifier, fetchFn = globalThis.fetch.bind(globalThis)) {
168
+ const base = discoveryBase(identifier);
169
+ if (!base) {
170
+ throw new Error(`Identifier "${identifier}" has no discovery base: use session parameters or a profile resolver`);
171
+ }
172
+ const url = wellKnownUrl(base);
173
+ const resp = await fetchFn(url, { headers: { Accept: "application/json" } });
174
+ if (!resp.ok) {
175
+ throw new Error(`WMP discovery failed for ${url}: HTTP ${resp.status}`);
176
+ }
177
+ const config = (await resp.json());
178
+ if (config === null || typeof config !== "object" || !describesBase(config, base)) {
179
+ throw new Error(`WMP discovery failed for ${url}: the configuration is not for https://${base.host}${base.tenantPath}`);
180
+ }
181
+ return config;
101
182
  }
package/dist/index.d.ts CHANGED
@@ -31,8 +31,8 @@ export { Relay } from "./relay.js";
31
31
  export type { RelayConfig, QueuedMessage } from "./relay.js";
32
32
  export { MemorySessionStore, SessionStoreError, isSessionExpired, sessionOwnedBy, tokensEqual, } from "./session-store.js";
33
33
  export type { Session, SessionStore, SessionStoreErrorCode, TokenRotator, SessionCreator, SessionUpdater, ExpiredSessionLister, } from "./session-store.js";
34
- export { extractDomain, discoverEndpoint } from "./discovery.js";
35
- export type { WellKnownConfig } from "./discovery.js";
34
+ export { extractDomain, discoverEndpoint, discoveryBase, wellKnownUrl, } from "./discovery.js";
35
+ export type { WellKnownConfig, DiscoveryBase } from "./discovery.js";
36
36
  export type { ErdsMetadata, RecipientMetadata } from "./discovery.js";
37
37
  export { InvitationPurpose, createInvitation, invitationSigningPayload, invitationToURI, invitationToHTTPSURI, parseInvitationURI, parseInvitationJSON, isInvitationExpired, generateNonce, MemoryInvitationStore, validateInvitationNonce, } from "./invitation.js";
38
38
  export type { Invitation, CreateInvitationOptions, InvitationStore, } from "./invitation.js";
package/dist/index.js CHANGED
@@ -32,6 +32,6 @@ export { Relay } from "./relay.js";
32
32
  // Session store (server-side)
33
33
  export { MemorySessionStore, SessionStoreError, isSessionExpired, sessionOwnedBy, tokensEqual, } from "./session-store.js";
34
34
  // Discovery
35
- export { extractDomain, discoverEndpoint } from "./discovery.js";
35
+ export { extractDomain, discoverEndpoint, discoveryBase, wellKnownUrl, } from "./discovery.js";
36
36
  // Invitation
37
37
  export { InvitationPurpose, createInvitation, invitationSigningPayload, invitationToURI, invitationToHTTPSURI, parseInvitationURI, parseInvitationJSON, isInvitationExpired, generateNonce, MemoryInvitationStore, validateInvitationNonce, } from "./invitation.js";
package/dist/peer.d.ts CHANGED
@@ -79,11 +79,11 @@ export declare class Peer implements PeerContext {
79
79
  private negotiatedVersion?;
80
80
  private resumptionToken?;
81
81
  private closed;
82
- private validator?;
83
- private authorize?;
82
+ private validator;
83
+ private authorize;
84
84
  private validateCompletions;
85
- private onRefusedCompletion?;
86
- private onSessionLost?;
85
+ private onRefusedCompletion;
86
+ private onSessionLost;
87
87
  private supportedVersions;
88
88
  /**
89
89
  * Capabilities negotiated for a session, bound to that session's ID; undefined
package/dist/peer.js CHANGED
@@ -112,7 +112,7 @@ export class Peer {
112
112
  resumeNegotiated(sessionId, capabilities, rev, source = "remote") {
113
113
  const id = Peer.usableId(sessionId);
114
114
  const n = this.negotiated;
115
- if (n && n.sessionId !== undefined && n.sessionId === id) {
115
+ if (n?.sessionId !== undefined && n.sessionId === id) {
116
116
  if (capabilities !== undefined)
117
117
  this.applySnapshot(n, rev, capabilities, source);
118
118
  return;
@@ -134,7 +134,7 @@ export class Peer {
134
134
  return;
135
135
  }
136
136
  const have = Object.keys(n.capabilities);
137
- const same = have.length === Object.keys(snapshot).length && have.every((k) => Object.prototype.hasOwnProperty.call(snapshot, k));
137
+ const same = have.length === Object.keys(snapshot).length && have.every((k) => Object.hasOwn(snapshot, k));
138
138
  // A stale snapshot that names exactly what is cached changes nothing: no
139
139
  // revision bump and no refresh (which would otherwise ping-pong between peers
140
140
  // whose grants never change).
@@ -146,7 +146,7 @@ export class Peer {
146
146
  source = "remote";
147
147
  const kept = {};
148
148
  for (const k of have) {
149
- if (Object.prototype.hasOwnProperty.call(snapshot, k))
149
+ if (Object.hasOwn(snapshot, k))
150
150
  kept[k] = n.capabilities[k];
151
151
  }
152
152
  n.capabilities = kept;
@@ -198,7 +198,11 @@ export class Peer {
198
198
  // Only the refresh that is still the current one clears the marker and drains.
199
199
  if (this.grantRefresh === mine) {
200
200
  this.grantRefresh = undefined;
201
- const next = this.grantRefreshPending.remote ? "remote" : this.grantRefreshPending.local ? "local" : undefined;
201
+ let next;
202
+ if (this.grantRefreshPending.remote)
203
+ next = "remote";
204
+ else if (this.grantRefreshPending.local)
205
+ next = "local";
202
206
  if (next) {
203
207
  this.grantRefreshPending[next] = false;
204
208
  this.scheduleGrantRefresh(next); // respects the session held NOW; the other source drains after it
@@ -234,7 +238,7 @@ export class Peer {
234
238
  // of the wrong type or content is not "no id".
235
239
  if (requestSession !== undefined && requestSession !== n.sessionId)
236
240
  return false;
237
- return Object.prototype.hasOwnProperty.call(n.capabilities, capability);
241
+ return Object.hasOwn(n.capabilities, capability);
238
242
  }
239
243
  /** The highest supported version (what a client offers). */
240
244
  offeredVersion() {
@@ -1054,7 +1058,7 @@ export class Peer {
1054
1058
  // processed shares its outcome, even if the flow completed meanwhile. A
1055
1059
  // replacement flow under the same id is a different generation.
1056
1060
  const pending = this.cancelling.get(flowId);
1057
- if (pending && pending.epoch === epoch && pending.gen === gen)
1061
+ if (pending?.epoch === epoch && pending.gen === gen)
1058
1062
  return pending.run;
1059
1063
  const entry = { epoch, gen, run: undefined };
1060
1064
  this.cancelCount.set(flowId, (this.cancelCount.get(flowId) ?? 0) + 1);
@@ -85,7 +85,7 @@ export interface ExpiredSessionLister {
85
85
  * In-memory SessionStore — suitable for development and testing.
86
86
  */
87
87
  export declare class MemorySessionStore implements SessionStore, TokenRotator, SessionCreator, SessionUpdater, ExpiredSessionLister {
88
- private sessions;
88
+ private readonly sessions;
89
89
  create(session: Session): Promise<void>;
90
90
  get(id: string): Promise<Session | undefined>;
91
91
  update(session: Session): Promise<void>;
@@ -41,7 +41,7 @@ export function tokensEqual(a, b) {
41
41
  let diff = a.length ^ b.length;
42
42
  const n = Math.max(a.length, b.length);
43
43
  for (let i = 0; i < n; i++) {
44
- diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);
44
+ diff |= (a.codePointAt(i) ?? 0) ^ (b.codePointAt(i) ?? 0);
45
45
  }
46
46
  return diff === 0;
47
47
  }
@@ -69,7 +69,7 @@ export class MemorySessionStore {
69
69
  const now = Date.now();
70
70
  const out = [];
71
71
  for (const s of this.sessions.values()) {
72
- if (s.metadata && s.metadata[key] === value && !isSessionExpired(s, now))
72
+ if (s.metadata?.[key] === value && !isSessionExpired(s, now))
73
73
  out.push(s);
74
74
  }
75
75
  return out;
package/dist/signflow.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * orchestrator-side FlowContext.RequestSign / RequestMatch.
5
5
  */
6
6
  import { sha256, sha384, sha512 } from "@noble/hashes/sha2.js";
7
- import { CompletionResultError, validateCompletionResult } from "./completion.js";
7
+ import { CompletionResultError, validVpToken, validateCompletionResult } from "./completion.js";
8
8
  import { isSelectionHandle } from "./consent.js";
9
9
  import { unsupportedError } from "./errors.js";
10
10
  import { WMPError } from "./jsonrpc.js";
@@ -25,7 +25,7 @@ export const TRANSACTION_DATA_VERSION_1 = 1;
25
25
  * which would read as support the peer never claimed.
26
26
  */
27
27
  export function offersTransactionData(caps, version = TRANSACTION_DATA_VERSION_1) {
28
- const raw = caps !== undefined && Object.prototype.hasOwnProperty.call(caps, CAPABILITY_TRANSACTION_DATA) ? caps[CAPABILITY_TRANSACTION_DATA] : undefined;
28
+ const raw = caps !== undefined && Object.hasOwn(caps, CAPABILITY_TRANSACTION_DATA) ? caps[CAPABILITY_TRANSACTION_DATA] : undefined;
29
29
  // A malformed descriptor is not an offer: fail closed on every member we know.
30
30
  if (typeof raw !== "object" || raw === null || Array.isArray(raw))
31
31
  return false;
@@ -62,8 +62,8 @@ export const TRANSACTION_DATA_HASH_ALGS = [...HASHES.keys()];
62
62
  function toBase64Url(bytes) {
63
63
  let bin = "";
64
64
  for (const b of bytes)
65
- bin += String.fromCharCode(b);
66
- return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
65
+ bin += String.fromCodePoint(b);
66
+ return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
67
67
  }
68
68
  function fromBase64Url(s) {
69
69
  if (!/^[A-Za-z0-9_-]+$/.test(s))
@@ -71,8 +71,8 @@ function fromBase64Url(s) {
71
71
  const pad = (4 - (s.length % 4)) % 4;
72
72
  if (pad === 3)
73
73
  throw new Error("impossible base64url length");
74
- const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat(pad));
75
- return Uint8Array.from(bin, (c) => c.charCodeAt(0));
74
+ const bin = atob(s.replaceAll("-", "+").replaceAll("_", "/") + "=".repeat(pad));
75
+ return Uint8Array.from(bin, (c) => c.codePointAt(0) ?? 0);
76
76
  }
77
77
  /**
78
78
  * `transaction_data_hashes` element for an entry: base64url (no padding) of the
@@ -91,7 +91,7 @@ export function transactionDataHash(raw, alg = "sha-256") {
91
91
  throw new Error("transaction_data raw is not ASCII");
92
92
  const bytes = new Uint8Array(raw.length);
93
93
  for (let i = 0; i < raw.length; i++)
94
- bytes[i] = raw.charCodeAt(i);
94
+ bytes[i] = raw.codePointAt(i) ?? 0;
95
95
  return toBase64Url(h(bytes));
96
96
  }
97
97
  function deepEqual(a, b) {
@@ -105,7 +105,7 @@ function deepEqual(a, b) {
105
105
  const kb = Object.keys(b);
106
106
  if (ka.length !== kb.length)
107
107
  return false;
108
- return ka.every((k) => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k]));
108
+ return ka.every((k) => Object.hasOwn(b, k) && deepEqual(a[k], b[k]));
109
109
  }
110
110
  /**
111
111
  * A transaction_data_hashes_alg as a list for comparison: a bare string becomes a
@@ -332,26 +332,10 @@ function present(v) {
332
332
  // and numbers are not a presentation or an error report.
333
333
  return typeof v === "object" && v !== null && Object.keys(v).length > 0;
334
334
  }
335
- /**
336
- * A vp_token the profile allows (table in profile 3.2.5, DCQL form in 7.x): a
337
- * non-empty string, a non-empty array of non-empty strings, or an object mapping
338
- * query ids to non-empty arrays of non-empty strings. Anything else (booleans,
339
- * numbers, null, empty or mixed values) is not a presentation.
340
- */
341
- function validVpToken(v) {
342
- const str = (x) => typeof x === "string" && x !== "";
343
- const strs = (x) => Array.isArray(x) && x.length > 0 && x.every(str);
344
- if (str(v) || strs(v))
345
- return true;
346
- if (typeof v !== "object" || v === null || Array.isArray(v))
347
- return false;
348
- const vals = Object.values(v);
349
- return vals.length > 0 && vals.every(strs);
350
- }
351
335
  /** Response modes in which the wallet encrypts the response (profile 7.7). */
352
- const ENCRYPTED_RESPONSE_MODES = ["direct_post.jwt", "dc_api.jwt"];
336
+ const ENCRYPTED_RESPONSE_MODES = new Set(["direct_post.jwt", "dc_api.jwt"]);
353
337
  /** The members a decrypt_credential_response result may carry: control members only. */
354
- const DECRYPT_RESULT_MEMBERS = ["credential_count", "transaction_id", "interval", "error"];
338
+ const DECRYPT_RESULT_MEMBERS = new Set(["credential_count", "transaction_id", "interval", "error"]);
355
339
  /**
356
340
  * Checks the result of a sign sub-flow before it is sent: the completion rules
357
341
  * and, per action, what must never reach the orchestrator. A
@@ -364,12 +348,16 @@ const DECRYPT_RESULT_MEMBERS = ["credential_count", "transaction_id", "interval"
364
348
  export function validateSignResult(action, result, responseMode) {
365
349
  validateCompletionResult(result);
366
350
  const r = result;
351
+ // A proof is a compact JWS: a missing, empty or non-string proof_jwt must not be sent as one.
352
+ if (action === "generate_proof" && "proof_jwt" in r && (typeof r.proof_jwt !== "string" || r.proof_jwt === "")) {
353
+ throw new CompletionResultError("proof_jwt is not a non-empty string");
354
+ }
367
355
  if (action === "sign_presentation") {
368
356
  // An encrypted response mode: the wallet builds and encrypts the response
369
357
  // itself and answers with response_jwe; a plaintext vp_token would reach the
370
358
  // orchestrator unprotected and no later refusal can undo that (profile 7.7).
371
359
  // A plaintext mode has no use for a JWE the orchestrator cannot read.
372
- const encrypted = responseMode !== undefined && ENCRYPTED_RESPONSE_MODES.includes(responseMode);
360
+ const encrypted = responseMode !== undefined && ENCRYPTED_RESPONSE_MODES.has(responseMode);
373
361
  if ("error" in r) {
374
362
  // An error result carries no presentation in any mode, and no response_jwe
375
363
  // (profile 7.7): it reports a refusal, there is nothing to encrypt. The
@@ -399,7 +387,7 @@ export function validateSignResult(action, result, responseMode) {
399
387
  if (action !== "decrypt_credential_response")
400
388
  return;
401
389
  for (const k of Object.keys(r)) {
402
- if (!DECRYPT_RESULT_MEMBERS.includes(k))
390
+ if (!DECRYPT_RESULT_MEMBERS.has(k))
403
391
  throw new CompletionResultError("decryption result carries a member outside the control set");
404
392
  }
405
393
  if (!("credential_count" in r) && !("transaction_id" in r) && !("error" in r)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sirosfoundation/wmp-js",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Wallet Messaging Protocol (WMP) client library — JSON-RPC 2.0 over WebSocket and HTTP+SSE",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",