@learncard/didkit-plugin 1.10.10 → 1.10.12

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,732 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
6
+
7
+ import {
8
+ clearDidWebDocumentFetchCache,
9
+ DEFAULT_DID_WEB_DOCUMENT_TTL_MS,
10
+ didWebToDocumentUrl,
11
+ getDidWebDocumentFetchCacheStats,
12
+ installDidWebDocumentFetchCache,
13
+ installWalletDidWebDocumentFetchCache,
14
+ invalidateDidWebDocument,
15
+ isDidWebDocumentUrl,
16
+ resetDidWebDocumentFetchCacheForTests,
17
+ WALLET_DID_WEB_DOCUMENT_TTL_MS,
18
+ } from './didWebDocumentCache';
19
+ import { getDidKitPlugin } from './plugin';
20
+
21
+ const DOC_URL = 'https://network.learncard.com/users/playwright-test-demo-boi/did.json';
22
+ const DOC_BODY = JSON.stringify({
23
+ '@context': 'https://www.w3.org/ns/did/v1',
24
+ id: 'did:web:network.learncard.com:users:playwright-test-demo-boi',
25
+ verificationMethod: [],
26
+ });
27
+ const AUTH_BODY = JSON.stringify({
28
+ '@context': 'https://www.w3.org/ns/did/v1',
29
+ id: 'did:web:network.learncard.com:users:playwright-test-demo-boi',
30
+ verificationMethod: [{ id: 'authed' }],
31
+ });
32
+
33
+ const wasmPath = join(
34
+ dirname(fileURLToPath(import.meta.url)),
35
+ 'didkit',
36
+ 'pkg',
37
+ 'didkit_wasm_bg.wasm'
38
+ );
39
+
40
+ describe('didWebDocumentCache', () => {
41
+ const originalFetch = globalThis.fetch;
42
+ let fetchMock: ReturnType<typeof vi.fn>;
43
+
44
+ beforeEach(() => {
45
+ resetDidWebDocumentFetchCacheForTests();
46
+ fetchMock = vi.fn(
47
+ async () =>
48
+ new Response(DOC_BODY, {
49
+ status: 200,
50
+ headers: { 'content-type': 'application/json' },
51
+ })
52
+ );
53
+ // Give mocked responses a URL when possible (undici/Response may ignore).
54
+ fetchMock.mockImplementation(async (input: RequestInfo | URL) => {
55
+ const url =
56
+ typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
57
+ const response = new Response(DOC_BODY, {
58
+ status: 200,
59
+ headers: { 'content-type': 'application/json' },
60
+ });
61
+ try {
62
+ Object.defineProperty(response, 'url', { value: url, configurable: true });
63
+ } catch {
64
+ /* ignore */
65
+ }
66
+ return response;
67
+ });
68
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
69
+ installDidWebDocumentFetchCache({ ttlMs: 50, maxEntries: 3, force: true });
70
+ });
71
+
72
+ afterEach(() => {
73
+ resetDidWebDocumentFetchCacheForTests();
74
+ globalThis.fetch = originalFetch;
75
+ });
76
+
77
+ it('maps did:web DIDs to document URLs the same way as ssi did-web', () => {
78
+ expect(didWebToDocumentUrl('did:web:example.com')).toBe(
79
+ 'https://example.com/.well-known/did.json'
80
+ );
81
+ expect(didWebToDocumentUrl('did:web:example.com:u:bob')).toBe(
82
+ 'https://example.com/u/bob/did.json'
83
+ );
84
+ expect(
85
+ didWebToDocumentUrl('did:web:network.learncard.com:users:playwright-test-demo-boi')
86
+ ).toBe(DOC_URL);
87
+ expect(isDidWebDocumentUrl(DOC_URL)).toBe(true);
88
+ expect(isDidWebDocumentUrl('https://example.com/api')).toBe(false);
89
+ });
90
+
91
+ it('dedupes concurrent GETs for the same did.json URL to a single network fetch', async () => {
92
+ let release!: (value: Response) => void;
93
+ const gate = new Promise<Response>(resolve => {
94
+ release = resolve;
95
+ });
96
+ fetchMock.mockImplementationOnce((input: RequestInfo | URL) => {
97
+ expect(input).toBeInstanceOf(Request);
98
+ expect((input as Request).signal).toBeInstanceOf(AbortSignal);
99
+ return gate;
100
+ });
101
+
102
+ const requests = Array.from({ length: 25 }, () => fetch(DOC_URL));
103
+ await Promise.resolve();
104
+ expect(getDidWebDocumentFetchCacheStats().inflightEntries).toBe(1);
105
+
106
+ const gated = new Response(DOC_BODY, { status: 200 });
107
+ Object.defineProperty(gated, 'url', { value: DOC_URL, configurable: true });
108
+ release!(gated);
109
+ const responses = await Promise.all(requests);
110
+
111
+ expect(fetchMock).toHaveBeenCalledTimes(1);
112
+ expect(responses).toHaveLength(25);
113
+ for (const response of responses) {
114
+ expect(response.status).toBe(200);
115
+ expect(response.url).toBe(DOC_URL);
116
+ expect(await response.json()).toEqual(JSON.parse(DOC_BODY));
117
+ }
118
+ });
119
+
120
+ it('serves TTL cache hits without refetching, then refetches after expiry', async () => {
121
+ const first = await fetch(DOC_URL);
122
+ expect(await first.json()).toEqual(JSON.parse(DOC_BODY));
123
+ expect(fetchMock).toHaveBeenCalledTimes(1);
124
+
125
+ const second = await fetch(DOC_URL);
126
+ expect(await second.json()).toEqual(JSON.parse(DOC_BODY));
127
+ expect(fetchMock).toHaveBeenCalledTimes(1);
128
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(1);
129
+
130
+ await new Promise(resolve => setTimeout(resolve, 60));
131
+
132
+ const third = await fetch(DOC_URL);
133
+ expect(await third.json()).toEqual(JSON.parse(DOC_BODY));
134
+ expect(fetchMock).toHaveBeenCalledTimes(2);
135
+ });
136
+
137
+ it('does not cache failed resolutions', async () => {
138
+ fetchMock.mockResolvedValueOnce(new Response('missing', { status: 404 }));
139
+
140
+ const failed = await fetch(DOC_URL);
141
+ expect(failed.status).toBe(404);
142
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(0);
143
+
144
+ const recovered = await fetch(DOC_URL);
145
+ expect(recovered.status).toBe(200);
146
+ expect(fetchMock).toHaveBeenCalledTimes(2);
147
+ });
148
+
149
+ it('does not cache thrown network errors; the next call retries', async () => {
150
+ fetchMock.mockRejectedValueOnce(new Error('network down'));
151
+
152
+ await expect(fetch(DOC_URL)).rejects.toThrow('network down');
153
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(0);
154
+ expect(getDidWebDocumentFetchCacheStats().inflightEntries).toBe(0);
155
+
156
+ const recovered = await fetch(DOC_URL);
157
+ expect(recovered.status).toBe(200);
158
+ expect(fetchMock).toHaveBeenCalledTimes(2);
159
+ });
160
+
161
+ it('invalidates a DID document so noCache-style callers refetch', async () => {
162
+ await fetch(DOC_URL);
163
+ expect(fetchMock).toHaveBeenCalledTimes(1);
164
+
165
+ invalidateDidWebDocument('did:web:network.learncard.com:users:playwright-test-demo-boi');
166
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(0);
167
+
168
+ await fetch(DOC_URL);
169
+ expect(fetchMock).toHaveBeenCalledTimes(2);
170
+ });
171
+
172
+ it('clearDidWebDocumentFetchCache drops success entries', async () => {
173
+ await fetch(DOC_URL);
174
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(1);
175
+ clearDidWebDocumentFetchCache();
176
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(0);
177
+
178
+ await fetch(DOC_URL);
179
+ expect(fetchMock).toHaveBeenCalledTimes(2);
180
+ });
181
+
182
+ it('leaves non-did.json traffic untouched', async () => {
183
+ await fetch('https://network.learncard.com/api/health');
184
+ expect(fetchMock).toHaveBeenCalledTimes(1);
185
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(0);
186
+ });
187
+
188
+ it('bypasses the success cache for cache: "no-store" requests', async () => {
189
+ await fetch(DOC_URL);
190
+ expect(fetchMock).toHaveBeenCalledTimes(1);
191
+
192
+ await fetch(DOC_URL, { cache: 'no-store' });
193
+ expect(fetchMock).toHaveBeenCalledTimes(2);
194
+ });
195
+
196
+ it('keys Authorization separately so unauthenticated GETs do not reuse authed bodies', async () => {
197
+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
198
+ const req = input instanceof Request ? input : new Request(input, init);
199
+ const headers = new Headers(req.headers);
200
+ const body = headers.get('authorization') ? AUTH_BODY : DOC_BODY;
201
+ const response = new Response(body, { status: 200 });
202
+ Object.defineProperty(response, 'url', { value: DOC_URL, configurable: true });
203
+ return response;
204
+ });
205
+
206
+ const authed = await fetch(DOC_URL, { headers: { Authorization: 'Bearer secret' } });
207
+ expect(await authed.json()).toEqual(JSON.parse(AUTH_BODY));
208
+ expect(fetchMock).toHaveBeenCalledTimes(1);
209
+
210
+ const anon = await fetch(DOC_URL);
211
+ expect(await anon.json()).toEqual(JSON.parse(DOC_BODY));
212
+ expect(fetchMock).toHaveBeenCalledTimes(2);
213
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(2);
214
+ });
215
+
216
+ it('caches WASM-style Accept: application/json requests instead of bypassing them', async () => {
217
+ const wasmHeaders = { Accept: 'application/json', 'User-Agent': 'did-web/0.2.0' };
218
+ await fetch(DOC_URL, { headers: wasmHeaders });
219
+ await fetch(DOC_URL, { headers: wasmHeaders });
220
+ expect(fetchMock).toHaveBeenCalledTimes(1);
221
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(1);
222
+ });
223
+
224
+ it('preserves credentials and mode on the shared network call', async () => {
225
+ await fetch(DOC_URL, { credentials: 'omit', mode: 'cors' });
226
+ expect(fetchMock).toHaveBeenCalledTimes(1);
227
+ const req1 = fetchMock.mock.calls[0]![0] as Request;
228
+ expect(req1).toBeInstanceOf(Request);
229
+ expect(req1.credentials).toBe('omit');
230
+ expect(req1.mode).toBe('cors');
231
+
232
+ // Different credentials => different key => new fetch.
233
+ await fetch(DOC_URL, { credentials: 'include', mode: 'cors' });
234
+ expect(fetchMock).toHaveBeenCalledTimes(2);
235
+ const req2 = fetchMock.mock.calls[1]![0] as Request;
236
+ expect(req2.credentials).toBe('include');
237
+ });
238
+
239
+ it('preserves response.url on rebuilt/cached responses', async () => {
240
+ const response = await fetch(DOC_URL);
241
+ expect(response.url).toBe(DOC_URL);
242
+ const cached = await fetch(DOC_URL);
243
+ expect(cached.url).toBe(DOC_URL);
244
+ expect(fetchMock).toHaveBeenCalledTimes(1);
245
+ });
246
+
247
+ it('honors response Cache-Control: no-store and max-age', async () => {
248
+ fetchMock.mockResolvedValueOnce(
249
+ new Response(DOC_BODY, {
250
+ status: 200,
251
+ headers: { 'cache-control': 'no-store' },
252
+ })
253
+ );
254
+ await fetch(DOC_URL);
255
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(0);
256
+
257
+ fetchMock.mockImplementationOnce(async () => {
258
+ const response = new Response(DOC_BODY, {
259
+ status: 200,
260
+ headers: { 'cache-control': 'max-age=1' },
261
+ });
262
+ Object.defineProperty(response, 'url', { value: DOC_URL, configurable: true });
263
+ return response;
264
+ });
265
+ await fetch(DOC_URL);
266
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(1);
267
+ await fetch(DOC_URL);
268
+ expect(fetchMock).toHaveBeenCalledTimes(2);
269
+
270
+ await new Promise(resolve => setTimeout(resolve, 1100));
271
+ await fetch(DOC_URL);
272
+ expect(fetchMock).toHaveBeenCalledTimes(3);
273
+ });
274
+
275
+ it('does not join or repopulate from in-flight work after clear/invalidate', async () => {
276
+ let release!: (value: Response) => void;
277
+ const gate = new Promise<Response>(resolve => {
278
+ release = resolve;
279
+ });
280
+ fetchMock.mockImplementationOnce(() => gate);
281
+
282
+ const stale = fetch(DOC_URL);
283
+ await Promise.resolve();
284
+ expect(getDidWebDocumentFetchCacheStats().inflightEntries).toBe(1);
285
+
286
+ clearDidWebDocumentFetchCache();
287
+ expect(getDidWebDocumentFetchCacheStats().inflightEntries).toBe(0);
288
+ expect(getDidWebDocumentFetchCacheStats().cacheGeneration).toBe(1);
289
+
290
+ fetchMock.mockImplementationOnce(async () => {
291
+ const response = new Response(AUTH_BODY, { status: 200 });
292
+ Object.defineProperty(response, 'url', { value: DOC_URL, configurable: true });
293
+ return response;
294
+ });
295
+ const fresh = await fetch(DOC_URL);
296
+ expect(await fresh.json()).toEqual(JSON.parse(AUTH_BODY));
297
+ expect(fetchMock).toHaveBeenCalledTimes(2);
298
+
299
+ const gated = new Response(DOC_BODY, { status: 200 });
300
+ Object.defineProperty(gated, 'url', { value: DOC_URL, configurable: true });
301
+ release!(gated);
302
+ await expect(stale).resolves.toMatchObject({ status: 200 });
303
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(1);
304
+ const stillFresh = await fetch(DOC_URL);
305
+ expect(await stillFresh.json()).toEqual(JSON.parse(AUTH_BODY));
306
+ expect(fetchMock).toHaveBeenCalledTimes(2);
307
+ });
308
+
309
+ it('rechecks generations after body streaming before insert (canStore race)', async () => {
310
+ let releaseBody!: () => void;
311
+ const bodyGate = new Promise<void>(resolve => {
312
+ releaseBody = resolve;
313
+ });
314
+
315
+ fetchMock.mockImplementationOnce(async () => {
316
+ const stream = new ReadableStream<Uint8Array>({
317
+ async start(controller) {
318
+ await bodyGate;
319
+ controller.enqueue(new TextEncoder().encode(DOC_BODY));
320
+ controller.close();
321
+ },
322
+ });
323
+ const response = new Response(stream, {
324
+ status: 200,
325
+ headers: { 'content-type': 'application/json' },
326
+ });
327
+ Object.defineProperty(response, 'url', { value: DOC_URL, configurable: true });
328
+ return response;
329
+ });
330
+
331
+ const stale = fetch(DOC_URL);
332
+ await Promise.resolve();
333
+ await Promise.resolve();
334
+
335
+ // Newer document lands while the stale body is still gated.
336
+ clearDidWebDocumentFetchCache();
337
+ fetchMock.mockImplementationOnce(async () => {
338
+ const response = new Response(AUTH_BODY, { status: 200 });
339
+ Object.defineProperty(response, 'url', { value: DOC_URL, configurable: true });
340
+ return response;
341
+ });
342
+ const fresh = await fetch(DOC_URL);
343
+ expect(await fresh.json()).toEqual(JSON.parse(AUTH_BODY));
344
+
345
+ releaseBody!();
346
+ await stale;
347
+
348
+ const stillFresh = await fetch(DOC_URL);
349
+ expect(await stillFresh.json()).toEqual(JSON.parse(AUTH_BODY));
350
+ expect(fetchMock).toHaveBeenCalledTimes(2);
351
+ });
352
+
353
+ it('normalize invalidate keys like toAbsoluteUrl (host case / default port)', async () => {
354
+ const mixedCaseUrl = 'https://EXAMPLE.com:443/.well-known/did.json';
355
+ await fetch(mixedCaseUrl);
356
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(1);
357
+
358
+ invalidateDidWebDocument('did:web:EXAMPLE.com%3A443');
359
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(0);
360
+
361
+ await fetch('https://example.com/.well-known/did.json');
362
+ expect(fetchMock).toHaveBeenCalledTimes(2);
363
+ });
364
+
365
+ it('lets joiners cancel independently without aborting peers', async () => {
366
+ let release!: (value: Response) => void;
367
+ const gate = new Promise<Response>(resolve => {
368
+ release = resolve;
369
+ });
370
+ fetchMock.mockImplementationOnce(() => gate);
371
+
372
+ const a = new AbortController();
373
+ const b = new AbortController();
374
+ const pA = fetch(DOC_URL, { signal: a.signal });
375
+ const pB = fetch(DOC_URL, { signal: b.signal });
376
+ await Promise.resolve();
377
+ expect(fetchMock).toHaveBeenCalledTimes(1);
378
+
379
+ a.abort();
380
+ await expect(pA).rejects.toMatchObject({ name: 'AbortError' });
381
+
382
+ const gated = new Response(DOC_BODY, { status: 200 });
383
+ Object.defineProperty(gated, 'url', { value: DOC_URL, configurable: true });
384
+ release!(gated);
385
+ const responseB = await pB;
386
+ expect(responseB.status).toBe(200);
387
+ expect(await responseB.json()).toEqual(JSON.parse(DOC_BODY));
388
+ });
389
+
390
+ it('evicts expired and over-capacity entries', async () => {
391
+ installDidWebDocumentFetchCache({ ttlMs: 50, maxEntries: 2, force: true });
392
+
393
+ const urls = [
394
+ 'https://a.example.com/.well-known/did.json',
395
+ 'https://b.example.com/.well-known/did.json',
396
+ 'https://c.example.com/.well-known/did.json',
397
+ ];
398
+ for (const url of urls) {
399
+ await fetch(url);
400
+ }
401
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(2);
402
+
403
+ await fetch(urls[0]!);
404
+ expect(fetchMock).toHaveBeenCalledTimes(4);
405
+
406
+ await new Promise(resolve => setTimeout(resolve, 60));
407
+ await fetch(urls[1]!);
408
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(1);
409
+ });
410
+
411
+ it('rebuilds null-body statuses without throwing', async () => {
412
+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 }));
413
+ const response = await fetch(DOC_URL);
414
+ expect(response.status).toBe(204);
415
+ expect(await response.text()).toBe('');
416
+ });
417
+
418
+ it('replaces Request headers when init.headers is supplied (does not merge Authorization)', async () => {
419
+ const seen: Headers[] = [];
420
+ fetchMock.mockImplementation(async (input: RequestInfo | URL) => {
421
+ const req = input instanceof Request ? input : new Request(input);
422
+ seen.push(new Headers(req.headers));
423
+ const response = new Response(DOC_BODY, { status: 200 });
424
+ Object.defineProperty(response, 'url', { value: DOC_URL, configurable: true });
425
+ return response;
426
+ });
427
+
428
+ // Populate an authenticated cache entry first.
429
+ await fetch(DOC_URL, { headers: { Authorization: 'Bearer secret' } });
430
+ expect(seen[0]!.get('authorization')).toBe('Bearer secret');
431
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(1);
432
+
433
+ // Platform rule: init.headers replaces the input Request's headers entirely.
434
+ const authedRequest = new Request(DOC_URL, {
435
+ headers: { Authorization: 'Bearer secret' },
436
+ });
437
+ await fetch(authedRequest, { headers: { Accept: 'application/json' } });
438
+ expect(fetchMock).toHaveBeenCalledTimes(2);
439
+ expect(seen[1]!.get('authorization')).toBeNull();
440
+ expect(seen[1]!.get('accept')).toBe('application/json');
441
+ });
442
+
443
+ it('empty init.headers replaces and strips Authorization from the input Request', async () => {
444
+ const seen: Headers[] = [];
445
+ fetchMock.mockImplementation(async (input: RequestInfo | URL) => {
446
+ const req = input instanceof Request ? input : new Request(input);
447
+ seen.push(new Headers(req.headers));
448
+ const response = new Response(DOC_BODY, { status: 200 });
449
+ Object.defineProperty(response, 'url', { value: DOC_URL, configurable: true });
450
+ return response;
451
+ });
452
+
453
+ await fetch(DOC_URL, { headers: { Authorization: 'Bearer secret' } });
454
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(1);
455
+
456
+ const authedRequest = new Request(DOC_URL, {
457
+ headers: { Authorization: 'Bearer secret' },
458
+ });
459
+ await fetch(authedRequest, { headers: {} });
460
+ expect(fetchMock).toHaveBeenCalledTimes(2);
461
+ expect(seen[1]!.get('authorization')).toBeNull();
462
+ });
463
+
464
+ it('passes integrity-bearing requests through to native fetch (cold cache)', async () => {
465
+ fetchMock.mockImplementation(async (_input: RequestInfo | URL, init?: RequestInit) => {
466
+ const integrity =
467
+ init?.integrity || (_input instanceof Request ? _input.integrity : undefined);
468
+ if (integrity) {
469
+ throw new TypeError('Failed to fetch (integrity mismatch)');
470
+ }
471
+ const response = new Response(DOC_BODY, { status: 200 });
472
+ Object.defineProperty(response, 'url', { value: DOC_URL, configurable: true });
473
+ return response;
474
+ });
475
+
476
+ await expect(
477
+ fetch(DOC_URL, {
478
+ integrity: 'sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',
479
+ })
480
+ ).rejects.toThrow(/integrity mismatch/);
481
+ expect(fetchMock).toHaveBeenCalledTimes(1);
482
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(0);
483
+ });
484
+
485
+ it('does not serve warm cache hits for integrity-bearing requests', async () => {
486
+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
487
+ const integrity =
488
+ init?.integrity || (input instanceof Request ? input.integrity : undefined);
489
+ if (integrity) {
490
+ throw new TypeError('Failed to fetch (integrity mismatch)');
491
+ }
492
+ const response = new Response(DOC_BODY, { status: 200 });
493
+ Object.defineProperty(response, 'url', { value: DOC_URL, configurable: true });
494
+ return response;
495
+ });
496
+
497
+ await fetch(DOC_URL);
498
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(1);
499
+ expect(fetchMock).toHaveBeenCalledTimes(1);
500
+
501
+ await expect(
502
+ fetch(DOC_URL, {
503
+ integrity: 'sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',
504
+ })
505
+ ).rejects.toThrow(/integrity mismatch/);
506
+ // Must not be satisfied from the warm cache — underlying fetch runs again.
507
+ expect(fetchMock).toHaveBeenCalledTimes(2);
508
+ });
509
+
510
+ it('does not consume body-bearing non-did.json Request inputs (POST/PUT/PATCH)', async () => {
511
+ const received: { method: string; body: string }[] = [];
512
+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
513
+ // Must be able to construct from the original — proves it was not already used.
514
+ const req =
515
+ input instanceof Request ? new Request(input, init) : new Request(input, init);
516
+ received.push({ method: req.method.toUpperCase(), body: await req.text() });
517
+ return new Response('ok', { status: 200 });
518
+ });
519
+
520
+ for (const method of ['POST', 'PUT', 'PATCH'] as const) {
521
+ const req = new Request('https://example.com/api', { method, body: `hello-${method}` });
522
+ await fetch(req);
523
+ }
524
+
525
+ expect(received).toEqual([
526
+ { method: 'POST', body: 'hello-POST' },
527
+ { method: 'PUT', body: 'hello-PUT' },
528
+ { method: 'PATCH', body: 'hello-PATCH' },
529
+ ]);
530
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBe(0);
531
+ });
532
+
533
+ it('forwards Request+init body overrides without consuming the original early', async () => {
534
+ let receivedBody = '';
535
+ let receivedMethod = '';
536
+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
537
+ const req =
538
+ input instanceof Request ? new Request(input, init) : new Request(input, init);
539
+ receivedMethod = req.method.toUpperCase();
540
+ receivedBody = await req.text();
541
+ return new Response('ok', { status: 200 });
542
+ });
543
+
544
+ const original = new Request('https://example.com/api', {
545
+ method: 'POST',
546
+ body: 'from-request',
547
+ });
548
+ await fetch(original, { method: 'PUT', body: 'from-init' });
549
+ expect(receivedMethod).toBe('PUT');
550
+ expect(receivedBody).toBe('from-init');
551
+ });
552
+
553
+ it('does not consume a ReadableStream request body before passthrough', async () => {
554
+ let receivedBody = '';
555
+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
556
+ const req =
557
+ input instanceof Request ? new Request(input, init) : new Request(input, init);
558
+ receivedBody = await req.text();
559
+ return new Response('ok', { status: 200 });
560
+ });
561
+
562
+ const stream = new ReadableStream<Uint8Array>({
563
+ start(controller) {
564
+ controller.enqueue(new TextEncoder().encode('stream-hello'));
565
+ controller.close();
566
+ },
567
+ });
568
+ const req = new Request('https://example.com/api', {
569
+ method: 'POST',
570
+ body: stream,
571
+ // Node/undici requires duplex when body is a stream.
572
+ duplex: 'half',
573
+ } as RequestInit);
574
+ await fetch(req);
575
+ expect(receivedBody).toBe('stream-hello');
576
+ });
577
+
578
+ it('throws when install is called without globalThis.fetch', () => {
579
+ resetDidWebDocumentFetchCacheForTests();
580
+ const previous = globalThis.fetch;
581
+ // @ts-expect-error intentional
582
+ delete globalThis.fetch;
583
+ try {
584
+ expect(() => installDidWebDocumentFetchCache({ force: true })).toThrow(
585
+ /globalThis\.fetch/
586
+ );
587
+ } finally {
588
+ globalThis.fetch = previous;
589
+ }
590
+ });
591
+ });
592
+
593
+ describe('didWebDocumentCache + getDidKitPlugin TTL policy', () => {
594
+ const originalFetch = globalThis.fetch;
595
+ let fetchMock: ReturnType<typeof vi.fn>;
596
+
597
+ beforeEach(() => {
598
+ resetDidWebDocumentFetchCacheForTests();
599
+ fetchMock = vi.fn(async (input: RequestInfo | URL) => {
600
+ const url =
601
+ typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
602
+ const response = new Response(DOC_BODY, {
603
+ status: 200,
604
+ headers: { 'content-type': 'application/json' },
605
+ });
606
+ try {
607
+ Object.defineProperty(response, 'url', { value: url, configurable: true });
608
+ } catch {
609
+ /* ignore */
610
+ }
611
+ return response;
612
+ });
613
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
614
+ });
615
+
616
+ afterEach(() => {
617
+ resetDidWebDocumentFetchCacheForTests();
618
+ globalThis.fetch = originalFetch;
619
+ vi.useRealTimers();
620
+ });
621
+
622
+ it('keeps the generic 10s TTL when getDidKitPlugin installs', async () => {
623
+ const wasmBytes = readFileSync(wasmPath);
624
+ await getDidKitPlugin(wasmBytes);
625
+ expect(getDidWebDocumentFetchCacheStats().ttlMs).toBe(DEFAULT_DID_WEB_DOCUMENT_TTL_MS);
626
+ expect(getDidWebDocumentFetchCacheStats().installed).toBe(true);
627
+ }, 60_000);
628
+
629
+ it('does not raise a preinstalled shorter TTL when getDidKitPlugin inits', async () => {
630
+ vi.useFakeTimers();
631
+ installDidWebDocumentFetchCache({ ttlMs: 1_000, force: true });
632
+ expect(getDidWebDocumentFetchCacheStats().ttlMs).toBe(1_000);
633
+
634
+ const wasmBytes = readFileSync(wasmPath);
635
+ // Advance fake timers during WASM init so wall-clock waits do not hang.
636
+ const pluginPromise = getDidKitPlugin(wasmBytes);
637
+ await vi.runAllTimersAsync();
638
+ await pluginPromise;
639
+
640
+ expect(getDidWebDocumentFetchCacheStats().ttlMs).toBe(1_000);
641
+
642
+ await fetch(DOC_URL);
643
+ expect(fetchMock).toHaveBeenCalledTimes(1);
644
+
645
+ await vi.advanceTimersByTimeAsync(2_000);
646
+ await fetch(DOC_URL);
647
+ expect(fetchMock).toHaveBeenCalledTimes(2);
648
+ }, 60_000);
649
+
650
+ it('app wallet opt-in gets 60s TTL with no second GET at 30s', async () => {
651
+ vi.useFakeTimers();
652
+ // Order matches learn-card-base wallet boot: wallet opt-in, then getDidKitPlugin.
653
+ installWalletDidWebDocumentFetchCache();
654
+ const wasmBytes = readFileSync(wasmPath);
655
+ const pluginPromise = getDidKitPlugin(wasmBytes);
656
+ await vi.runAllTimersAsync();
657
+ await pluginPromise;
658
+
659
+ expect(getDidWebDocumentFetchCacheStats().ttlMs).toBe(WALLET_DID_WEB_DOCUMENT_TTL_MS);
660
+
661
+ await fetch(DOC_URL);
662
+ expect(fetchMock).toHaveBeenCalledTimes(1);
663
+
664
+ await vi.advanceTimersByTimeAsync(30_000);
665
+ await fetch(DOC_URL);
666
+ expect(fetchMock).toHaveBeenCalledTimes(1);
667
+ }, 60_000);
668
+ });
669
+
670
+ describe('didWebDocumentCache + DIDKit WASM resolveDid', () => {
671
+ const originalFetch = globalThis.fetch;
672
+ let fetchCount = 0;
673
+
674
+ afterEach(() => {
675
+ resetDidWebDocumentFetchCacheForTests();
676
+ globalThis.fetch = originalFetch;
677
+ });
678
+
679
+ it('dedupes 25 concurrent WASM did:web resolutions to one did.json fetch', async () => {
680
+ const did = 'did:web:network.learncard.com:users:playwright-test-demo-boi';
681
+ const docUrl = didWebToDocumentUrl(did)!;
682
+ const didDocument = {
683
+ '@context': 'https://www.w3.org/ns/did/v1',
684
+ id: did,
685
+ verificationMethod: [
686
+ {
687
+ id: `${did}#key-0`,
688
+ type: 'Ed25519VerificationKey2018',
689
+ controller: did,
690
+ publicKeyBase58: 'H3C2AVvLMv6gmMNam3uVAjZpfkcJCwDwnZn6z3wXmqPV',
691
+ },
692
+ ],
693
+ assertionMethod: [`${did}#key-0`],
694
+ };
695
+
696
+ fetchCount = 0;
697
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
698
+ const req = input instanceof Request ? input : new Request(input, init);
699
+ const url = req.url;
700
+ if (url.includes('/did.json')) {
701
+ fetchCount += 1;
702
+ // Real WASM sends Accept: application/json (and usually a User-Agent).
703
+ expect(req.headers.get('accept')?.toLowerCase()).toContain('application/json');
704
+ await new Promise(r => setTimeout(r, 30));
705
+ const response = new Response(JSON.stringify(didDocument), {
706
+ status: 200,
707
+ headers: { 'content-type': 'application/json' },
708
+ });
709
+ Object.defineProperty(response, 'url', { value: url, configurable: true });
710
+ return response;
711
+ }
712
+ return originalFetch(input, init);
713
+ }) as typeof fetch;
714
+
715
+ // Plugin install wraps fetch; pass local wasm bytes so we do not hit the CDN.
716
+ const wasmBytes = readFileSync(wasmPath);
717
+ const plugin = await getDidKitPlugin(wasmBytes);
718
+
719
+ const results = await Promise.all(
720
+ Array.from({ length: 25 }, () => plugin.methods.resolveDid({} as never, did))
721
+ );
722
+
723
+ expect(results).toHaveLength(25);
724
+ for (const doc of results) {
725
+ expect(doc.id).toBe(did);
726
+ }
727
+ // Measured through the real WASM resolveDid path (not a bare fetch harness).
728
+ expect(fetchCount).toBe(1);
729
+ expect(getDidWebDocumentFetchCacheStats().successEntries).toBeGreaterThanOrEqual(1);
730
+ expect(docUrl).toBe(DOC_URL);
731
+ }, 60_000);
732
+ });