@learncard/didkit-plugin 1.10.10 → 1.10.11

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.
@@ -0,0 +1,573 @@
1
+ /**
2
+ * Browser/Node fetch cache for did:web documents (`…/did.json`).
3
+ *
4
+ * DIDKit WASM resolves and verifies through `globalThis.fetch` with no in-flight
5
+ * dedupe (ssi did-web drops its TimedCache lock before the HTTP GET). Opening one
6
+ * credential can therefore stampede the same issuer document dozens of times.
7
+ *
8
+ * This module wraps `fetch` once so callers with *equivalent* resolver requests share:
9
+ * - in-flight promise dedupe keyed by normalized request semantics
10
+ * - a short TTL success cache (failures are never stored; Cache-Control honored)
11
+ *
12
+ * Equivalence follows platform `new Request(input, init)` rules (init.headers
13
+ * *replaces* Request headers, it does not merge). Semantics include method, URL,
14
+ * headers (so WASM's `Accept: application/json` is keyed, not bypassed), credentials,
15
+ * mode, cache, redirect, and referrer policy. Non-cacheable traffic (non-GET,
16
+ * non-did.json, integrity, no-store, etc.) is decided with cheap peeks and the
17
+ * original input/init are forwarded untouched — never `new Request` first, so
18
+ * body-bearing POSTs are not consumed. Only GET did.json paths normalize.
19
+ * Rebuilt Responses keep `url` (DIDKit parses it). Clear/invalidate bump a
20
+ * generation so stale in-flight work cannot join or repopulate after the body
21
+ * finishes streaming.
22
+ */
23
+
24
+ export const DEFAULT_DID_WEB_DOCUMENT_TTL_MS = 10_000;
25
+ /**
26
+ * LearnCard App wallet-boot TTL for did:web document GETs. Longer than
27
+ * {@link DEFAULT_DID_WEB_DOCUMENT_TTL_MS} so a credential detail modal that keeps
28
+ * re-resolving does not refetch every 10s (LC-2384: 4 identical demo-boi GETs at
29
+ * ~10s gaps). Apply only via {@link installWalletDidWebDocumentFetchCache} at app
30
+ * boot — never from {@link getDidKitPlugin}. Change this one constant to tune
31
+ * wallet lifetime; the public SDK factory keeps {@link DEFAULT_DID_WEB_DOCUMENT_TTL_MS}.
32
+ */
33
+ export const WALLET_DID_WEB_DOCUMENT_TTL_MS = 60_000;
34
+ export const DEFAULT_DID_WEB_DOCUMENT_CACHE_MAX_ENTRIES = 64;
35
+
36
+ const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
37
+
38
+ type StoredDocument = {
39
+ expiresAt: number;
40
+ status: number;
41
+ statusText: string;
42
+ headers: [string, string][];
43
+ body: ArrayBuffer | null;
44
+ /** Original response URL — required by DIDKit's wasm URL parser. */
45
+ url: string;
46
+ };
47
+
48
+ type RequestSemantics = {
49
+ method: string;
50
+ url: string;
51
+ headers: [string, string][];
52
+ credentials: RequestCredentials;
53
+ mode: RequestMode;
54
+ cache: RequestCache;
55
+ redirect: RequestRedirect;
56
+ referrerPolicy: ReferrerPolicy | '';
57
+ };
58
+
59
+ type InflightEntry = {
60
+ generation: number;
61
+ controller: AbortController;
62
+ promise: Promise<StoredDocument>;
63
+ waiters: number;
64
+ semanticsKey: string;
65
+ };
66
+
67
+ type FetchLike = typeof globalThis.fetch;
68
+
69
+ let installed = false;
70
+ let underlyingFetch: FetchLike | undefined;
71
+ let ttlMs = DEFAULT_DID_WEB_DOCUMENT_TTL_MS;
72
+ let maxEntries = DEFAULT_DID_WEB_DOCUMENT_CACHE_MAX_ENTRIES;
73
+ /** Bumped by clear so stale in-flight work cannot join or repopulate. */
74
+ let cacheGeneration = 0;
75
+
76
+ const successCache = new Map<string, StoredDocument>();
77
+ const inflight = new Map<string, InflightEntry>();
78
+ /** Per-URL generation; invalidate bumps this so old in-flight writes are ignored. */
79
+ const urlGeneration = new Map<string, number>();
80
+
81
+ export type DidWebDocumentCacheStats = {
82
+ installed: boolean;
83
+ ttlMs: number;
84
+ maxEntries: number;
85
+ successEntries: number;
86
+ inflightEntries: number;
87
+ cacheGeneration: number;
88
+ };
89
+
90
+ export type InstallDidWebDocumentFetchCacheOptions = {
91
+ /** Success-entry lifetime in ms. Defaults to {@link DEFAULT_DID_WEB_DOCUMENT_TTL_MS}. */
92
+ ttlMs?: number;
93
+ /** Max success entries (LRU). Defaults to {@link DEFAULT_DID_WEB_DOCUMENT_CACHE_MAX_ENTRIES}. */
94
+ maxEntries?: number;
95
+ /** Replace a previous install (tests). */
96
+ force?: boolean;
97
+ };
98
+
99
+ const normalizeAbsoluteUrl = (href: string): string => new URL(href).href;
100
+
101
+ const headersToSortedTuples = (headers: Headers): [string, string][] => {
102
+ const tuples: [string, string][] = [];
103
+ headers.forEach((value, key) => {
104
+ tuples.push([key.toLowerCase(), value]);
105
+ });
106
+ tuples.sort((a, b) =>
107
+ a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0
108
+ );
109
+ return tuples;
110
+ };
111
+
112
+ /**
113
+ * Normalize with the platform Request constructor so `init.headers` *replaces*
114
+ * (does not merge with) headers from an input Request — matching native fetch.
115
+ * Only call this after the cheap passthrough gate: GET did.json requests have no body.
116
+ */
117
+ const normalizeRequest = (input: RequestInfo | URL, init?: RequestInit): Request =>
118
+ new Request(input, init);
119
+
120
+ const describeSemanticsFromRequest = (request: Request): RequestSemantics => ({
121
+ method: request.method.toUpperCase(),
122
+ url: normalizeAbsoluteUrl(request.url),
123
+ headers: headersToSortedTuples(request.headers),
124
+ credentials: request.credentials,
125
+ mode: request.mode,
126
+ cache: request.cache,
127
+ redirect: request.redirect,
128
+ referrerPolicy: request.referrerPolicy,
129
+ });
130
+
131
+ const semanticsKey = (semantics: RequestSemantics): string =>
132
+ JSON.stringify([
133
+ semantics.method,
134
+ semantics.url,
135
+ semantics.headers,
136
+ semantics.credentials,
137
+ semantics.mode,
138
+ semantics.cache,
139
+ semantics.redirect,
140
+ semantics.referrerPolicy,
141
+ ]);
142
+
143
+ /** Shared network call: same semantics as the normalized Request, our AbortSignal. */
144
+ const sharedNetworkRequest = (normalized: Request, signal: AbortSignal): Request =>
145
+ new Request(normalized, { signal });
146
+
147
+ /** Cheap peeks — never construct Request / never touch body. */
148
+ const peekRequestUrl = (input: RequestInfo | URL): string => {
149
+ if (typeof input === 'string') return input;
150
+ if (input instanceof URL) return input.href;
151
+ return input.url;
152
+ };
153
+
154
+ const peekMethod = (input: RequestInfo | URL, init?: RequestInit): string => {
155
+ if (init?.method) return init.method.toUpperCase();
156
+ if (input instanceof Request) return input.method.toUpperCase();
157
+ return 'GET';
158
+ };
159
+
160
+ const peekHasIntegrity = (input: RequestInfo | URL, init?: RequestInit): boolean => {
161
+ if (typeof init?.integrity === 'string' && init.integrity.length > 0) return true;
162
+ if (input instanceof Request && input.integrity.length > 0) return true;
163
+ return false;
164
+ };
165
+
166
+ const peekCacheMode = (input: RequestInfo | URL, init?: RequestInit): RequestCache => {
167
+ if (init?.cache) return init.cache;
168
+ if (input instanceof Request) return input.cache;
169
+ return 'default';
170
+ };
171
+
172
+ /** did.json check without constructing Request or requiring absolute URL parse. */
173
+ const peekIsDidWebDocumentUrl = (url: string): boolean => {
174
+ try {
175
+ const pathname = new URL(url).pathname;
176
+ return pathname === '/did.json' || pathname.endsWith('/did.json');
177
+ } catch {
178
+ const path = url.split(/[?#]/, 1)[0] ?? url;
179
+ return path === 'did.json' || path.endsWith('/did.json');
180
+ }
181
+ };
182
+
183
+ /** True for did:web document URLs (`/did.json`), including `.well-known/did.json`. */
184
+ export const isDidWebDocumentUrl = (url: string): boolean => {
185
+ try {
186
+ const pathname = new URL(url).pathname;
187
+ return pathname === '/did.json' || pathname.endsWith('/did.json');
188
+ } catch {
189
+ return false;
190
+ }
191
+ };
192
+
193
+ /**
194
+ * Mirrors ssi `did_web_url`, then normalizes via the URL constructor (host case,
195
+ * default ports) so invalidate keys match fetch keys.
196
+ */
197
+ export const didWebToDocumentUrl = (did: string): string | undefined => {
198
+ if (!did.startsWith('did:web:')) return undefined;
199
+
200
+ const parts = did.slice('did:web:'.length).split(':');
201
+ const domainName = parts[0];
202
+ if (!domainName) return undefined;
203
+
204
+ const domain = domainName.replace(/%3A/gi, ':');
205
+ const path = parts.length > 1 ? parts.slice(1).join('/') : '.well-known';
206
+ const proto = domain.startsWith('localhost') ? 'http' : 'https';
207
+
208
+ try {
209
+ return normalizeAbsoluteUrl(`${proto}://${domain}/${path}/did.json`);
210
+ } catch {
211
+ return undefined;
212
+ }
213
+ };
214
+
215
+ const getUrlGeneration = (url: string): number => urlGeneration.get(url) ?? 0;
216
+
217
+ const bumpUrlGeneration = (url: string): void => {
218
+ urlGeneration.set(url, getUrlGeneration(url) + 1);
219
+ // Drop every in-flight join handle for this document URL (semantics key embeds URL).
220
+ for (const key of [...inflight.keys()]) {
221
+ try {
222
+ const parsed = JSON.parse(key) as unknown[];
223
+ if (parsed[1] === url) inflight.delete(key);
224
+ } catch {
225
+ /* ignore malformed keys */
226
+ }
227
+ }
228
+ };
229
+
230
+ const headersToTuples = (headers: Headers): [string, string][] => {
231
+ const tuples: [string, string][] = [];
232
+ headers.forEach((value, key) => {
233
+ tuples.push([key, value]);
234
+ });
235
+ return tuples;
236
+ };
237
+
238
+ const parseCacheControlMaxAgeMs = (headers: Headers): number | undefined => {
239
+ const raw = headers.get('cache-control');
240
+ if (!raw) return undefined;
241
+ const directives = raw
242
+ .toLowerCase()
243
+ .split(',')
244
+ .map(part => part.trim());
245
+ if (directives.some(d => d === 'no-store' || d === 'no-cache')) return 0;
246
+ for (const directive of directives) {
247
+ const match = /^max-age=(\d+)$/.exec(directive);
248
+ if (match) return Number(match[1]) * 1000;
249
+ }
250
+ return undefined;
251
+ };
252
+
253
+ const storedToResponse = (stored: StoredDocument): Response => {
254
+ const body =
255
+ stored.body === null || NULL_BODY_STATUSES.has(stored.status) ? null : stored.body.slice(0);
256
+ const response = new Response(body, {
257
+ status: stored.status,
258
+ statusText: stored.statusText,
259
+ headers: stored.headers,
260
+ });
261
+ // DIDKit WASM parses response.url; a rebuilt Response defaults to "".
262
+ try {
263
+ Object.defineProperty(response, 'url', {
264
+ value: stored.url,
265
+ writable: false,
266
+ enumerable: true,
267
+ configurable: true,
268
+ });
269
+ } catch {
270
+ /* some runtimes may refuse; clone-based paths still work for inflight */
271
+ }
272
+ return response;
273
+ };
274
+
275
+ const readResponse = async (
276
+ response: Response,
277
+ effectiveTtlMs: number,
278
+ fallbackUrl: string
279
+ ): Promise<StoredDocument> => {
280
+ const body = NULL_BODY_STATUSES.has(response.status) ? null : await response.arrayBuffer();
281
+ return {
282
+ expiresAt: Date.now() + effectiveTtlMs,
283
+ status: response.status,
284
+ statusText: response.statusText,
285
+ headers: headersToTuples(response.headers),
286
+ body,
287
+ url: response.url || fallbackUrl,
288
+ };
289
+ };
290
+
291
+ const sweepExpired = (now = Date.now()): void => {
292
+ for (const [key, entry] of successCache) {
293
+ if (entry.expiresAt <= now) successCache.delete(key);
294
+ }
295
+ };
296
+
297
+ const touchLru = (key: string, stored: StoredDocument): void => {
298
+ successCache.delete(key);
299
+ successCache.set(key, stored);
300
+ while (successCache.size > maxEntries) {
301
+ const oldest = successCache.keys().next().value;
302
+ if (oldest === undefined) break;
303
+ successCache.delete(oldest);
304
+ }
305
+ };
306
+
307
+ const getFreshSuccess = (key: string, now = Date.now()): StoredDocument | undefined => {
308
+ sweepExpired(now);
309
+ const hit = successCache.get(key);
310
+ if (!hit) return undefined;
311
+ if (hit.expiresAt <= now) {
312
+ successCache.delete(key);
313
+ return undefined;
314
+ }
315
+ touchLru(key, hit);
316
+ return hit;
317
+ };
318
+
319
+ const abortError = (): DOMException => {
320
+ if (typeof DOMException === 'function') {
321
+ return new DOMException('The operation was aborted.', 'AbortError');
322
+ }
323
+ const error = new Error('The operation was aborted.');
324
+ error.name = 'AbortError';
325
+ return error as DOMException;
326
+ };
327
+
328
+ const waitForAbort = (signal: AbortSignal): Promise<never> =>
329
+ new Promise((_, reject) => {
330
+ if (signal.aborted) {
331
+ reject(abortError());
332
+ return;
333
+ }
334
+ signal.addEventListener('abort', () => reject(abortError()), { once: true });
335
+ });
336
+
337
+ const releaseInflightWaiter = (key: string, entry: InflightEntry): void => {
338
+ entry.waiters -= 1;
339
+ if (entry.waiters > 0) return;
340
+ if (inflight.get(key) === entry) inflight.delete(key);
341
+ if (!entry.controller.signal.aborted) {
342
+ entry.controller.abort();
343
+ }
344
+ };
345
+
346
+ async function joinInflight(
347
+ key: string,
348
+ entry: InflightEntry,
349
+ callerSignal: AbortSignal | undefined
350
+ ): Promise<Response> {
351
+ entry.waiters += 1;
352
+ try {
353
+ if (callerSignal?.aborted) throw abortError();
354
+ const stored = callerSignal
355
+ ? await Promise.race([entry.promise, waitForAbort(callerSignal)])
356
+ : await entry.promise;
357
+ return storedToResponse(stored);
358
+ } finally {
359
+ releaseInflightWaiter(key, entry);
360
+ }
361
+ }
362
+
363
+ const shouldBypassRequestCacheMode = (cache: RequestCache): boolean =>
364
+ cache === 'no-store' || cache === 'reload' || cache === 'no-cache';
365
+
366
+ async function cachedFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
367
+ const fetchImpl = underlyingFetch;
368
+ if (!fetchImpl) {
369
+ if (typeof globalThis.fetch !== 'function') {
370
+ throw new TypeError('globalThis.fetch is not available');
371
+ }
372
+ return globalThis.fetch(input, init);
373
+ }
374
+
375
+ // Cheap passthrough decision — never `new Request` / never touch the body here.
376
+ // Body-bearing POST/PUT/PATCH Request inputs must reach native fetch unused.
377
+ if (peekHasIntegrity(input, init)) {
378
+ return fetchImpl(input, init);
379
+ }
380
+ if (peekMethod(input, init) !== 'GET') {
381
+ return fetchImpl(input, init);
382
+ }
383
+ if (!peekIsDidWebDocumentUrl(peekRequestUrl(input))) {
384
+ return fetchImpl(input, init);
385
+ }
386
+ if (shouldBypassRequestCacheMode(peekCacheMode(input, init))) {
387
+ return fetchImpl(input, init);
388
+ }
389
+
390
+ // Cacheable GET did.json only (no body). Safe to normalize for header-replace rules.
391
+ let normalized: Request;
392
+ try {
393
+ normalized = normalizeRequest(input, init);
394
+ } catch {
395
+ return fetchImpl(input, init);
396
+ }
397
+
398
+ const semantics = describeSemanticsFromRequest(normalized);
399
+
400
+ // Belt-and-suspenders after normalize (relative URL edge cases, etc.).
401
+ if (semantics.method !== 'GET' || !isDidWebDocumentUrl(semantics.url)) {
402
+ return fetchImpl(input, init);
403
+ }
404
+ if (shouldBypassRequestCacheMode(semantics.cache)) {
405
+ return fetchImpl(input, init);
406
+ }
407
+
408
+ const callerSignal = normalized.signal;
409
+ if (callerSignal.aborted) throw abortError();
410
+
411
+ const key = semanticsKey(semantics);
412
+
413
+ const cached = getFreshSuccess(key);
414
+ if (cached) return storedToResponse(cached);
415
+
416
+ const existing = inflight.get(key);
417
+ if (existing && existing.generation === cacheGeneration) {
418
+ return joinInflight(key, existing, callerSignal);
419
+ }
420
+
421
+ const generationAtStart = cacheGeneration;
422
+ const urlGenerationAtStart = getUrlGeneration(semantics.url);
423
+ const controller = new AbortController();
424
+ const networkRequest = sharedNetworkRequest(normalized, controller.signal);
425
+
426
+ const pending = (async (): Promise<StoredDocument> => {
427
+ const response = await fetchImpl(networkRequest);
428
+ const responseMaxAgeMs = parseCacheControlMaxAgeMs(response.headers);
429
+
430
+ const effectiveTtlMs =
431
+ responseMaxAgeMs === undefined ? ttlMs : Math.max(0, Math.min(ttlMs, responseMaxAgeMs));
432
+
433
+ // Await the body first — clear/invalidate during streaming must still be
434
+ // observed before we decide whether to insert.
435
+ const stored = await readResponse(response, effectiveTtlMs || ttlMs, semantics.url);
436
+
437
+ const stillCurrentGeneration =
438
+ generationAtStart === cacheGeneration &&
439
+ urlGenerationAtStart === getUrlGeneration(semantics.url);
440
+
441
+ const canStore =
442
+ response.ok && responseMaxAgeMs !== 0 && effectiveTtlMs > 0 && stillCurrentGeneration;
443
+
444
+ if (canStore) {
445
+ // Recheck generations immediately before insert (body may have taken a while).
446
+ if (
447
+ generationAtStart === cacheGeneration &&
448
+ urlGenerationAtStart === getUrlGeneration(semantics.url)
449
+ ) {
450
+ touchLru(key, stored);
451
+ }
452
+ }
453
+
454
+ return stored;
455
+ })();
456
+
457
+ const entry: InflightEntry = {
458
+ generation: generationAtStart,
459
+ controller,
460
+ promise: pending,
461
+ waiters: 0,
462
+ semanticsKey: key,
463
+ };
464
+ inflight.set(key, entry);
465
+
466
+ return joinInflight(key, entry, callerSignal);
467
+ }
468
+
469
+ /**
470
+ * Install (or no-op if already installed) the process-wide did:web document fetch cache.
471
+ *
472
+ * TTL / maxEntries semantics:
473
+ * - Omitting `ttlMs` / `maxEntries` never clobbers a value already configured (so a
474
+ * generic {@link getDidKitPlugin} install cannot raise a shorter preinstalled TTL).
475
+ * - Passing `ttlMs` / `maxEntries` is an intentional opt-in and updates the module
476
+ * globals even when the wrapper is already installed (no `force` required).
477
+ * - First install with no options uses {@link DEFAULT_DID_WEB_DOCUMENT_TTL_MS}.
478
+ */
479
+ export const installDidWebDocumentFetchCache = (
480
+ options: InstallDidWebDocumentFetchCacheOptions = {}
481
+ ): void => {
482
+ if (typeof globalThis.fetch !== 'function') {
483
+ throw new TypeError(
484
+ 'installDidWebDocumentFetchCache requires globalThis.fetch; none is available'
485
+ );
486
+ }
487
+
488
+ if (typeof options.ttlMs === 'number' && options.ttlMs > 0) {
489
+ ttlMs = options.ttlMs;
490
+ }
491
+ if (typeof options.maxEntries === 'number' && options.maxEntries > 0) {
492
+ maxEntries = options.maxEntries;
493
+ }
494
+
495
+ if (installed && !options.force) return;
496
+
497
+ if (installed && options.force && underlyingFetch) {
498
+ globalThis.fetch = underlyingFetch;
499
+ }
500
+
501
+ underlyingFetch = globalThis.fetch.bind(globalThis);
502
+ globalThis.fetch = cachedFetch as FetchLike;
503
+ installed = true;
504
+ };
505
+
506
+ /**
507
+ * LearnCard App / wallet boot opt-in: set did:web document TTL to
508
+ * {@link WALLET_DID_WEB_DOCUMENT_TTL_MS} (60s). Call before `initLearnCard` so the
509
+ * subsequent generic getDidKitPlugin install cannot clobber it. Not for generic
510
+ * SDK consumers (emptyLearnCard, scripts, etc.).
511
+ */
512
+ export const installWalletDidWebDocumentFetchCache = (): void => {
513
+ installDidWebDocumentFetchCache({ ttlMs: WALLET_DID_WEB_DOCUMENT_TTL_MS });
514
+ };
515
+
516
+ export const clearDidWebDocumentFetchCache = (): void => {
517
+ cacheGeneration += 1;
518
+ successCache.clear();
519
+ inflight.clear();
520
+ urlGeneration.clear();
521
+ };
522
+
523
+ export const invalidateDidWebDocument = (didOrUrl: string): void => {
524
+ const raw = didOrUrl.startsWith('did:')
525
+ ? didWebToDocumentUrl(didOrUrl)
526
+ : isDidWebDocumentUrl(didOrUrl)
527
+ ? didOrUrl
528
+ : undefined;
529
+ if (!raw) return;
530
+
531
+ let url: string;
532
+ try {
533
+ url = normalizeAbsoluteUrl(raw);
534
+ } catch {
535
+ return;
536
+ }
537
+
538
+ // Drop every success entry whose semantics URL matches.
539
+ for (const key of [...successCache.keys()]) {
540
+ try {
541
+ const parsed = JSON.parse(key) as unknown[];
542
+ if (parsed[1] === url) successCache.delete(key);
543
+ } catch {
544
+ /* ignore */
545
+ }
546
+ }
547
+
548
+ bumpUrlGeneration(url);
549
+ };
550
+
551
+ export const getDidWebDocumentFetchCacheStats = (): DidWebDocumentCacheStats => ({
552
+ installed,
553
+ ttlMs,
554
+ maxEntries,
555
+ successEntries: successCache.size,
556
+ inflightEntries: inflight.size,
557
+ cacheGeneration,
558
+ });
559
+
560
+ /** Test helper: restore `fetch` and empty caches. */
561
+ export const resetDidWebDocumentFetchCacheForTests = (): void => {
562
+ if (installed && underlyingFetch) {
563
+ globalThis.fetch = underlyingFetch;
564
+ }
565
+ installed = false;
566
+ underlyingFetch = undefined;
567
+ ttlMs = DEFAULT_DID_WEB_DOCUMENT_TTL_MS;
568
+ maxEntries = DEFAULT_DID_WEB_DOCUMENT_CACHE_MAX_ENTRIES;
569
+ cacheGeneration = 0;
570
+ successCache.clear();
571
+ inflight.clear();
572
+ urlGeneration.clear();
573
+ };
package/src/helpers.ts CHANGED
@@ -1,19 +1,27 @@
1
1
  import { LearnCard } from '@learncard/core';
2
2
 
3
- export const getContextURIs = (jsonld: Record<string, any>) => {
3
+ /**
4
+ * Collects every remote context URI (string `@context` entry) in a JSON-LD document,
5
+ * including scoped contexts nested inside term definitions.
6
+ *
7
+ * Inline context objects are skipped: they are already part of the document, so there
8
+ * is nothing to resolve. Forwarding them to the DIDKit WASM `contextLoader` (whose
9
+ * `url` parameter is a string) makes wasm-bindgen reallocate a dangling pointer, which
10
+ * traps inside the WASM allocator (LC-2380).
11
+ */
12
+ export const getContextURIs = (jsonld: unknown): string[] => {
4
13
  const contexts: string[] = [];
5
14
 
6
- const traverse = (obj: Record<string, any>) => {
15
+ const traverse = (obj: unknown) => {
7
16
  if (typeof obj !== 'object' || obj === null) return;
8
17
 
9
- if (obj['@context']) {
10
- if (Array.isArray(obj['@context'])) contexts.push(...obj['@context']);
11
- else contexts.push(obj['@context']);
18
+ const context = '@context' in obj ? obj['@context'] : undefined;
19
+
20
+ for (const entry of Array.isArray(context) ? context : [context]) {
21
+ if (typeof entry === 'string') contexts.push(entry);
12
22
  }
13
23
 
14
- Object.keys(obj).forEach(key => {
15
- traverse(obj[key]);
16
- });
24
+ Object.values(obj).forEach(traverse);
17
25
  };
18
26
 
19
27
  traverse(jsonld);
package/src/index.ts CHANGED
@@ -1,3 +1,15 @@
1
1
  export * from './types';
2
2
  export * from './plugin';
3
3
  export * from './helpers';
4
+ export {
5
+ clearDidWebDocumentFetchCache,
6
+ didWebToDocumentUrl,
7
+ getDidWebDocumentFetchCacheStats,
8
+ installDidWebDocumentFetchCache,
9
+ installWalletDidWebDocumentFetchCache,
10
+ invalidateDidWebDocument,
11
+ isDidWebDocumentUrl,
12
+ DEFAULT_DID_WEB_DOCUMENT_TTL_MS,
13
+ WALLET_DID_WEB_DOCUMENT_TTL_MS,
14
+ DEFAULT_DID_WEB_DOCUMENT_CACHE_MAX_ENTRIES,
15
+ } from './didWebDocumentCache';
package/src/plugin.ts CHANGED
@@ -19,6 +19,11 @@ import init, {
19
19
  clearCache,
20
20
  } from './didkit/index';
21
21
  import { getDocumentMap } from './helpers';
22
+ import {
23
+ clearDidWebDocumentFetchCache,
24
+ installDidWebDocumentFetchCache,
25
+ invalidateDidWebDocument,
26
+ } from './didWebDocumentCache';
22
27
 
23
28
  import { DIDKitPlugin, DidMethod } from './types';
24
29
 
@@ -30,6 +35,9 @@ export const getDidKitPlugin = async (
30
35
  input?: InitInput | Promise<InitInput>,
31
36
  allowRemoteContexts = false
32
37
  ): Promise<DIDKitPlugin> => {
38
+ // Deduplicate concurrent did:web document GETs (verify/resolve stampede) before WASM boots.
39
+ // Generic SDK default (10s). App wallet boot raises TTL via installWalletDidWebDocumentFetchCache.
40
+ installDidWebDocumentFetchCache();
33
41
  await init(input);
34
42
 
35
43
  const memoizedDids: Partial<Record<DidMethod, string>> = {};
@@ -41,6 +49,9 @@ export const getDidKitPlugin = async (
41
49
  'Provides an interface to DIDKit, which allows for the generation of key material, as well as signing and verifying credentials and presentations',
42
50
  context: {
43
51
  resolveStaticDocument: async (_learnCard, url) => {
52
+ // The WASM loader only accepts string URLs; anything else traps (LC-2380)
53
+ if (typeof url !== 'string') return undefined;
54
+
44
55
  try {
45
56
  return JSON.parse((await contextLoader(url)) ?? '') || undefined;
46
57
  } catch (error) {
@@ -127,6 +138,8 @@ export const getDidKitPlugin = async (
127
138
  },
128
139
 
129
140
  contextLoader: async (_learnCard, url) => {
141
+ if (typeof url !== 'string') return undefined;
142
+
130
143
  try {
131
144
  return JSON.parse((await contextLoader(url)) ?? '') || undefined;
132
145
  } catch (error) {
@@ -136,11 +149,15 @@ export const getDidKitPlugin = async (
136
149
  }
137
150
  },
138
151
 
139
- resolveDid: async (_learnCard, did, inputMetadata = {}) =>
140
- JSON.parse(await resolveDID(did, JSON.stringify(inputMetadata))),
152
+ resolveDid: async (_learnCard, did, inputMetadata = {}) => {
153
+ if (inputMetadata.noCache) invalidateDidWebDocument(did);
154
+ return JSON.parse(await resolveDID(did, JSON.stringify(inputMetadata)));
155
+ },
141
156
 
142
- didResolver: async (_learnCard, did, inputMetadata = {}) =>
143
- JSON.parse(await didResolver(did, JSON.stringify(inputMetadata))),
157
+ didResolver: async (_learnCard, did, inputMetadata = {}) => {
158
+ if (inputMetadata.noCache) invalidateDidWebDocument(did);
159
+ return JSON.parse(await didResolver(did, JSON.stringify(inputMetadata)));
160
+ },
144
161
 
145
162
  createJwe: async (_learnCard, cleartext, recipients) =>
146
163
  JSON.parse(await createJwe(cleartext, recipients)),
@@ -193,6 +210,7 @@ export const getDidKitPlugin = async (
193
210
  },
194
211
 
195
212
  clearDidWebCache: async () => {
213
+ clearDidWebDocumentFetchCache();
196
214
  await clearCache();
197
215
  },
198
216
  },