-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathread-api.test.ts
More file actions
676 lines (606 loc) · 24.3 KB
/
Copy pathread-api.test.ts
File metadata and controls
676 lines (606 loc) · 24.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
/**
* Read API integration tests.
*
* Each test seeds D1 directly with the columns the handlers read, then
* exercises the handler via `SELF.fetch` to a `/xrpc/...` URL — same path
* a real client would take. Asserts on the envelope shape (uri, cid, did,
* indexedAt, artifactCaches, labels) and on error mappings (404 NotFound, 400
* InvalidRequest).
*
* Cache descriptors are operational delivery metadata rather than signed
* release fields.
*/
import { NSID } from "@emdash-cms/registry-lexicons";
import { applyD1Migrations, env, SELF } from "cloudflare:test";
import { beforeAll, beforeEach, describe, expect, it } from "vitest";
interface TestEnv {
DB: D1Database;
TEST_MIGRATIONS: Parameters<typeof applyD1Migrations>[1];
}
const testEnv = env as unknown as TestEnv;
const DID_A = "did:plc:read000000000000000000aa";
const DID_B = "did:plc:read000000000000000000bb";
const NOW = new Date("2026-05-10T12:00:00.000Z");
beforeAll(async () => {
await applyD1Migrations(testEnv.DB, testEnv.TEST_MIGRATIONS);
});
beforeEach(async () => {
// Tables in dependency order: releases → packages (FK), then publishers
// + verifications.
await testEnv.DB.prepare("UPDATE public_projection_state SET active_generation = NULL").run();
await testEnv.DB.prepare("DELETE FROM public_releases").run();
await testEnv.DB.prepare("DELETE FROM public_packages").run();
await testEnv.DB.prepare("DELETE FROM public_projection_generations").run();
await testEnv.DB.prepare("DELETE FROM label_state").run();
await testEnv.DB.prepare("DELETE FROM labellers").run();
await testEnv.DB.prepare("DELETE FROM releases").run();
await testEnv.DB.prepare("DELETE FROM package_release_history").run();
await testEnv.DB.prepare("DELETE FROM packages").run();
await testEnv.DB.prepare("DELETE FROM package_profile_heads").run();
await testEnv.DB.prepare("DELETE FROM package_profile_revisions").run();
await testEnv.DB.prepare("DELETE FROM publishers").run();
await testEnv.DB.prepare("DELETE FROM publisher_verifications").run();
});
interface SeedPackageOpts {
did?: string;
slug?: string;
type?: string;
name?: string | null;
description?: string | null;
license?: string;
keywords?: string[] | null;
latestVersion?: string | null;
cid?: string;
indexedAt?: string;
verifiedAt?: string;
carBytes?: Uint8Array;
}
async function seedPackage(opts: SeedPackageOpts = {}): Promise<void> {
const did = opts.did ?? DID_A;
const slug = opts.slug ?? "demo";
const indexedAt = opts.indexedAt ?? NOW.toISOString();
await testEnv.DB.prepare(
`INSERT INTO packages
(did, slug, type, name, description, license, authors, security, keywords,
sections, last_updated, latest_version, capabilities, record_blob,
signature_metadata, verified_at, indexed_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.bind(
did,
slug,
opts.type ?? "emdash-plugin",
opts.name ?? "Demo Plugin",
opts.description ?? "A demo plugin",
opts.license ?? "MIT",
JSON.stringify([{ name: "Tester" }]),
JSON.stringify([{ email: "x@y.test" }]),
opts.keywords === null ? null : JSON.stringify(opts.keywords ?? ["demo"]),
null,
NOW.toISOString(),
opts.latestVersion ?? null,
null,
opts.carBytes ?? new Uint8Array([0xa1, 0xa2, 0xa3]),
JSON.stringify({ cid: opts.cid ?? "bafyseed" }),
opts.verifiedAt ?? NOW.toISOString(),
indexedAt,
)
.run();
}
interface SeedReleaseOpts {
did?: string;
package?: string;
version: string;
versionSort?: string;
tombstoned?: boolean;
cid?: string;
carBytes?: Uint8Array;
artifacts?: unknown;
}
async function seedRelease(opts: SeedReleaseOpts): Promise<void> {
const did = opts.did ?? DID_A;
const pkg = opts.package ?? "demo";
const rkey = `${pkg}:${opts.version}`;
await testEnv.DB.prepare(
`INSERT INTO releases
(did, package, version, rkey, version_sort, artifacts, requires, suggests,
emdash_extension, repo_url, cts, record_blob, signature_metadata,
verified_at, indexed_at, tombstoned_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.bind(
did,
pkg,
opts.version,
rkey,
opts.versionSort ?? defaultVersionSort(opts.version),
JSON.stringify(
opts.artifacts ?? {
package: { url: "https://x.test/d.tgz", checksum: "bsha256-abc" },
},
),
null,
null,
JSON.stringify({ declaredAccess: {} }),
null,
NOW.toISOString(),
opts.carBytes ?? new Uint8Array([0xb1, 0xb2, 0xb3]),
JSON.stringify({ cid: opts.cid ?? `bafrel-${opts.version}` }),
NOW.toISOString(),
NOW.toISOString(),
opts.tombstoned ? NOW.toISOString() : null,
)
.run();
}
async function seedReleaseHistory(complete: boolean): Promise<void> {
await testEnv.DB.prepare(
`INSERT INTO package_release_history
(did, package, release_history_complete, first_observed_at, first_observed_source)
VALUES (?, ?, ?, ?, ?)`,
)
.bind(DID_A, "demo", complete ? 1 : 0, NOW.toISOString(), complete ? "jetstream" : "backfill")
.run();
}
async function seedTakedown(uri: string, cid: string | null = null): Promise<void> {
await testEnv.DB.prepare(
`INSERT INTO labellers
(did, endpoint, signing_key, signing_key_id, trusted, added_at, last_resolved_at,
active, required_positive, accepted_state, redaction, policy_version)
VALUES ('did:web:labels.example', 'https://labels.example', 'key',
'did:web:labels.example#atproto_label', 1, ?, ?, 1, 0, 0, 1, 'test-v1')
ON CONFLICT(did) DO UPDATE SET active = 1, trusted = 1, redaction = 1`,
)
.bind(NOW.toISOString(), NOW.toISOString())
.run();
await testEnv.DB.prepare(
`INSERT INTO label_state
(src, uri, val, cid, neg, cts, exp, trusted, cts_epoch, cts_fraction, collision)
VALUES ('did:web:labels.example', ?, '!takedown', ?, 0, ?, NULL, 1, ?, ?, 1)`,
)
.bind(uri, cid, NOW.toISOString(), Math.floor(NOW.getTime() / 1_000), "0".repeat(32))
.run();
}
/** Naive 1.x.y zero-padded version_sort for the test fixtures. Real values
* come from the consumer's `computeVersionSort`; tests just need the
* relative ordering to be right. */
function defaultVersionSort(version: string): string {
const [major = "0", minor = "0", patch = "0"] = version.split(".");
const pad = (s: string) => s.padStart(10, "0");
return `${pad(major)}.${pad(minor)}.${pad(patch)}.~`;
}
describe("getPackage", () => {
it("returns the packageView envelope for an indexed package", async () => {
await seedPackage({ slug: "demo", latestVersion: "1.0.0" });
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorGetPackage}?did=${DID_A}&slug=demo`,
);
expect(res.status).toBe(200);
const body = (await res.json()) as Record<string, unknown>;
expect(body).toMatchObject({
uri: `at://${DID_A}/${NSID.packageProfile}/demo`,
cid: "bafyseed",
did: DID_A,
slug: "demo",
latestVersion: "1.0.0",
indexedAt: NOW.toISOString(),
labels: [],
});
// Artifact cache services apply to release blobs, not package profiles.
expect(body).not.toHaveProperty("artifactCaches");
const profile = body["profile"] as Record<string, unknown>;
expect(profile["$type"]).toBe(NSID.packageProfile);
expect(profile["id"]).toBe(`at://${DID_A}/${NSID.packageProfile}/demo`);
expect(profile["license"]).toBe("MIT");
expect(profile["slug"]).toBe("demo");
});
it("returns 404 NotFound when no row matches", async () => {
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorGetPackage}?did=${DID_A}&slug=missing`,
);
expect(res.status).toBe(404);
const body = (await res.json()) as { error: string };
expect(body.error).toBe("NotFound");
});
it("reports complete all-time release history including tombstones", async () => {
await seedPackage({ slug: "demo", latestVersion: "2.0.0" });
await seedRelease({ version: "1.0.0", tombstoned: true });
await seedRelease({ version: "2.0.0" });
await seedReleaseHistory(true);
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorGetPackage}?did=${DID_A}&slug=demo`,
);
expect(res.status).toBe(200);
await expect(res.json()).resolves.toMatchObject({
historicalReleaseCount: 2,
releaseHistoryComplete: true,
});
});
it("marks backfilled release history incomplete", async () => {
await seedPackage({ slug: "demo", latestVersion: "1.0.0" });
await seedRelease({ version: "1.0.0" });
await seedReleaseHistory(false);
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorGetPackage}?did=${DID_A}&slug=demo`,
);
expect(res.status).toBe(200);
await expect(res.json()).resolves.toMatchObject({
historicalReleaseCount: 1,
releaseHistoryComplete: false,
});
});
it("returns 400 InvalidRequest on missing required params", async () => {
const res = await SELF.fetch(`https://test/xrpc/${NSID.aggregatorGetPackage}?did=${DID_A}`);
expect(res.status).toBe(400);
});
it("sets Cache-Control: private, no-store on success", async () => {
await seedPackage({ slug: "demo" });
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorGetPackage}?did=${DID_A}&slug=demo`,
);
expect(res.headers.get("cache-control")).toBe("private, no-store");
});
it("omits latestVersion when no release has been written yet", async () => {
await seedPackage({ slug: "fresh", latestVersion: null });
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorGetPackage}?did=${DID_A}&slug=fresh`,
);
const body = (await res.json()) as Record<string, unknown>;
expect(body).not.toHaveProperty("latestVersion");
});
});
describe("listReleases", () => {
it("returns releases ordered by descending semver", async () => {
await seedPackage({ slug: "demo", latestVersion: "2.0.0" });
await seedRelease({ version: "1.0.0" });
await seedRelease({ version: "1.10.0" });
await seedRelease({ version: "2.0.0" });
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorListReleases}?did=${DID_A}&package=demo`,
);
expect(res.status).toBe(200);
const body = (await res.json()) as { releases: Array<{ version: string }>; cursor?: string };
expect(body.releases.map((r) => r.version)).toEqual(["2.0.0", "1.10.0", "1.0.0"]);
expect(body).not.toHaveProperty("cursor");
});
it("filters tombstoned releases", async () => {
await seedPackage({ slug: "demo" });
await seedRelease({ version: "1.0.0" });
await seedRelease({ version: "1.1.0", tombstoned: true });
await seedRelease({ version: "1.2.0" });
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorListReleases}?did=${DID_A}&package=demo`,
);
const body = (await res.json()) as { releases: Array<{ version: string }> };
expect(body.releases.map((r) => r.version)).toEqual(["1.2.0", "1.0.0"]);
});
it("paginates via cursor", async () => {
await seedPackage({ slug: "demo" });
for (let i = 1; i <= 5; i++) await seedRelease({ version: `1.${i}.0` });
const first = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorListReleases}?did=${DID_A}&package=demo&limit=2`,
);
const firstBody = (await first.json()) as {
releases: Array<{ version: string }>;
cursor: string;
};
expect(firstBody.releases.map((r) => r.version)).toEqual(["1.5.0", "1.4.0"]);
expect(firstBody.cursor).toBeTruthy();
const second = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorListReleases}?did=${DID_A}&package=demo&limit=2&cursor=${encodeURIComponent(firstBody.cursor)}`,
);
const secondBody = (await second.json()) as {
releases: Array<{ version: string }>;
cursor?: string;
};
expect(secondBody.releases.map((r) => r.version)).toEqual(["1.3.0", "1.2.0"]);
expect(secondBody.cursor).toBeTruthy();
});
it("returns 404 when the parent package is missing", async () => {
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorListReleases}?did=${DID_A}&package=missing`,
);
expect(res.status).toBe(404);
});
it("400s on a provided-but-malformed cursor", async () => {
await seedPackage({ slug: "demo" });
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorListReleases}?did=${DID_A}&package=demo&cursor=garbage!!!`,
);
expect(res.status).toBe(400);
});
});
describe("getLatestRelease", () => {
it("advertises the record-scoped Cumulus service for release blobs", async () => {
const cid = "bafkreia6n3lf256wgzhov3k2orn2lreyllrloag5qxl467ycpppsssrt7q";
await seedPackage({ slug: "demo", latestVersion: "1.0.0" });
await seedRelease({
version: "1.0.0",
artifacts: {
package: {
blob: {
$type: "blob",
ref: { $link: cid },
mimeType: "application/gzip",
size: 6,
},
checksum: "bciqb43wwlv35mnso5lwvu5c3uxcjqwxcw4an3boxz57qe667fffdh7a",
},
},
});
const response = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorGetLatestRelease}?did=${DID_A}&package=demo`,
);
const body = (await response.json()) as Record<string, unknown>;
expect(body["artifactCaches"]).toEqual([
{
$type: "com.emdashcms.experimental.aggregator.defs#recordScopedBlobCache",
serviceEndpoint: "https://cdn.em-da.sh",
},
]);
expect(body).not.toHaveProperty("mirrors");
});
it("does not represent the cache descriptor as admission for a gated blob", async () => {
await seedPackage({ slug: "demo", latestVersion: "1.0.0" });
await seedRelease({
version: "1.0.0",
artifacts: {
package: {
blob: {
$type: "blob",
ref: {
$link: "bafkreia6n3lf256wgzhov3k2orn2lreyllrloag5qxl467ycpppsssrt7q",
},
mimeType: "application/gzip",
size: 6,
},
requiresAuth: true,
checksum: "bciqb43wwlv35mnso5lwvu5c3uxcjqwxcw4an3boxz57qe667fffdh7a",
},
},
});
const response = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorGetLatestRelease}?did=${DID_A}&package=demo`,
);
const body = (await response.json()) as Record<string, unknown>;
expect(body["artifactCaches"]).toEqual([
{
$type: "com.emdashcms.experimental.aggregator.defs#recordScopedBlobCache",
serviceEndpoint: "https://cdn.em-da.sh",
},
]);
});
it("returns the release pointed to by packages.latest_version", async () => {
await seedPackage({ slug: "demo", latestVersion: "2.0.0" });
await seedRelease({ version: "1.0.0" });
await seedRelease({ version: "2.0.0" });
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorGetLatestRelease}?did=${DID_A}&package=demo`,
);
expect(res.status).toBe(200);
const body = (await res.json()) as Record<string, unknown>;
expect(body["version"]).toBe("2.0.0");
expect(body["uri"]).toBe(`at://${DID_A}/${NSID.packageRelease}/demo:2.0.0`);
});
it("returns 404 when ALL releases are tombstoned (or none exist)", async () => {
await seedPackage({ slug: "demo", latestVersion: "1.0.0" });
await seedRelease({ version: "1.0.0", tombstoned: true });
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorGetLatestRelease}?did=${DID_A}&package=demo`,
);
expect(res.status).toBe(404);
});
it("falls back to the next-best release when latest_version points at a tombstoned one", async () => {
// `latest_version` was set to 2.0.0, then 2.0.0 was tombstoned but
// `refreshPackageLatestStmt` hasn't run yet (or failed). The fast-path
// JOIN misses; the slow-path ORDER BY should still find 1.0.0 and
// return it instead of 404ing.
await seedPackage({ slug: "demo", latestVersion: "2.0.0" });
await seedRelease({ version: "1.0.0" });
await seedRelease({ version: "2.0.0", tombstoned: true });
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorGetLatestRelease}?did=${DID_A}&package=demo`,
);
expect(res.status).toBe(200);
const body = (await res.json()) as Record<string, unknown>;
expect(body["version"]).toBe("1.0.0");
});
it("returns 404 when no package row exists", async () => {
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorGetLatestRelease}?did=${DID_A}&package=missing`,
);
expect(res.status).toBe(404);
});
});
describe("searchPackages", () => {
it("returns FTS-matched packages", async () => {
await seedPackage({ slug: "gallery", name: "Gallery Plugin", description: "image gallery" });
await seedPackage({ slug: "form", name: "Form Plugin", description: "form builder" });
const res = await SELF.fetch(`https://test/xrpc/${NSID.aggregatorSearchPackages}?q=gallery`);
expect(res.status).toBe(200);
const body = (await res.json()) as { packages: Array<{ slug: string }> };
expect(body.packages.map((p) => p.slug)).toContain("gallery");
expect(body.packages.map((p) => p.slug)).not.toContain("form");
});
it("returns all packages ordered by last_updated DESC when q is empty", async () => {
await seedPackage({ slug: "alpha" });
await seedPackage({ slug: "beta" });
const res = await SELF.fetch(`https://test/xrpc/${NSID.aggregatorSearchPackages}`);
const body = (await res.json()) as { packages: Array<{ slug: string }> };
expect(body.packages.map((p) => p.slug).toSorted()).toEqual(["alpha", "beta"]);
});
it("excludes every package from a publisher with an active DID takedown", async () => {
await seedPackage({ slug: "gallery", name: "Gallery Plugin" });
await seedPackage({ did: DID_B, slug: "form", name: "Form Plugin" });
await seedTakedown(DID_A);
for (const query of ["", "?q=gallery"]) {
const res = await SELF.fetch(`https://test/xrpc/${NSID.aggregatorSearchPackages}${query}`);
expect(res.status).toBe(200);
const body = (await res.json()) as { packages: Array<{ did: string }> };
expect(body.packages.map((pkg) => pkg.did)).not.toContain(DID_A);
}
});
it("applies a profile takedown only to the exact CID", async () => {
await seedPackage({ slug: "gallery", name: "Gallery Plugin", cid: "bafycurrent" });
await seedTakedown(`at://${DID_A}/${NSID.packageProfile}/gallery`, "bafyprevious");
const res = await SELF.fetch(`https://test/xrpc/${NSID.aggregatorSearchPackages}?q=gallery`);
expect(res.status).toBe(200);
const body = (await res.json()) as { packages: Array<{ slug: string }> };
expect(body.packages.map((pkg) => pkg.slug)).toContain("gallery");
});
it("paginates via offset cursor", async () => {
for (let i = 0; i < 5; i++) await seedPackage({ slug: `pkg${i}` });
const first = await SELF.fetch(`https://test/xrpc/${NSID.aggregatorSearchPackages}?limit=2`);
const firstBody = (await first.json()) as {
packages: Array<{ slug: string }>;
cursor: string;
};
expect(firstBody.packages).toHaveLength(2);
expect(firstBody.cursor).toBeTruthy();
const second = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorSearchPackages}?limit=2&cursor=${encodeURIComponent(firstBody.cursor)}`,
);
const secondBody = (await second.json()) as { packages: Array<{ slug: string }> };
expect(secondBody.packages).toHaveLength(2);
// Distinct from page 1 — seeded slugs don't overlap.
const overlap = firstBody.packages
.map((p) => p.slug)
.filter((s) => secondBody.packages.some((p) => p.slug === s));
expect(overlap).toEqual([]);
});
it("doesn't blow up on FTS-unsafe query chars (defensive quoting)", async () => {
await seedPackage({ slug: "demo", name: "Demo" });
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorSearchPackages}?q=${encodeURIComponent('demo "*"(')}`,
);
// Either matches nothing or matches normally — but doesn't 500.
expect(res.status).toBe(200);
});
it("treats FTS operators as literal tokens (the escape actually works)", async () => {
await seedPackage({ slug: "alpha", name: "Alpha" });
await seedPackage({ slug: "beta", name: "Beta" });
// `alpha OR beta` would match both packages if `OR` were interpreted
// as the FTS5 operator. With proper escaping the whole string is one
// literal phrase that can't possibly appear in either record's
// indexed text → zero matches. A buggy escape that stripped the
// quotes would return *both* packages.
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorSearchPackages}?q=${encodeURIComponent("alpha OR beta")}`,
);
expect(res.status).toBe(200);
const body = (await res.json()) as { packages: Array<{ slug: string }> };
expect(body.packages).toEqual([]);
});
it("400s on a provided-but-malformed cursor (no silent restart)", async () => {
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorSearchPackages}?cursor=not-a-valid-cursor`,
);
expect(res.status).toBe(400);
});
it("400s on a forged cursor with an out-of-range offset", async () => {
// Encode {offset: 1_000_000} → over MAX_OFFSET → 400.
const forged = btoa(JSON.stringify({ offset: 1_000_000 }))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
const res = await SELF.fetch(
`https://test/xrpc/${NSID.aggregatorSearchPackages}?cursor=${forged}`,
);
expect(res.status).toBe(400);
});
});
describe("sync.getRecord", () => {
const PATH = "/xrpc/com.atproto.sync.getRecord";
it("returns CAR bytes for an indexed package profile", async () => {
await seedPackage({ slug: "demo", carBytes: new Uint8Array([0x11, 0x22, 0x33]) });
const res = await SELF.fetch(
`https://test${PATH}?did=${DID_A}&collection=${NSID.packageProfile}&rkey=demo`,
);
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toBe("application/vnd.ipld.car");
expect(res.headers.get("cache-control")).toBe("private, no-store");
const bytes = new Uint8Array(await res.arrayBuffer());
expect([...bytes]).toEqual([0x11, 0x22, 0x33]);
});
it("returns CAR bytes for an indexed release", async () => {
await seedPackage({ slug: "demo" });
await seedRelease({ version: "1.0.0", carBytes: new Uint8Array([0x44, 0x55]) });
const res = await SELF.fetch(
`https://test${PATH}?did=${DID_A}&collection=${NSID.packageRelease}&rkey=demo:1.0.0`,
);
expect(res.status).toBe(200);
const bytes = new Uint8Array(await res.arrayBuffer());
expect([...bytes]).toEqual([0x44, 0x55]);
});
it("returns 404 for a tombstoned release", async () => {
await seedPackage({ slug: "demo" });
await seedRelease({ version: "1.0.0", tombstoned: true });
const res = await SELF.fetch(
`https://test${PATH}?did=${DID_A}&collection=${NSID.packageRelease}&rkey=demo:1.0.0`,
);
expect(res.status).toBe(404);
});
it("returns 404 for an unknown rkey", async () => {
const res = await SELF.fetch(
`https://test${PATH}?did=${DID_A}&collection=${NSID.packageProfile}&rkey=does-not-exist`,
);
expect(res.status).toBe(404);
});
it("returns 400 InvalidRequest on missing query params", async () => {
const res = await SELF.fetch(`https://test${PATH}?did=${DID_A}`);
expect(res.status).toBe(400);
});
it("returns 400 on a malformed DID", async () => {
const res = await SELF.fetch(
`https://test${PATH}?did=not-a-did&collection=${NSID.packageProfile}&rkey=demo`,
);
expect(res.status).toBe(400);
});
it("returns HEAD with content-length but no body", async () => {
await seedPackage({ slug: "demo", carBytes: new Uint8Array([0x11, 0x22, 0x33]) });
const res = await SELF.fetch(
`https://test${PATH}?did=${DID_A}&collection=${NSID.packageProfile}&rkey=demo`,
{ method: "HEAD" },
);
expect(res.status).toBe(200);
expect(res.headers.get("content-length")).toBe("3");
const bytes = new Uint8Array(await res.arrayBuffer());
expect(bytes.byteLength).toBe(0);
});
it("rejects non-GET/HEAD methods with 405", async () => {
const res = await SELF.fetch(
`https://test${PATH}?did=${DID_A}&collection=${NSID.packageProfile}&rkey=demo`,
{ method: "POST" },
);
expect(res.status).toBe(405);
expect(res.headers.get("allow")).toBe("GET, HEAD");
});
it("only matches publisher.profile when rkey='self'", async () => {
// publisher.profile rkey is always 'self'; any other rkey returns 404
// even if the (did) row exists.
await testEnv.DB.prepare(
`INSERT INTO publishers
(did, display_name, record_blob, verified_at, indexed_at)
VALUES (?, ?, ?, ?, ?)`,
)
.bind(DID_B, "Pub", new Uint8Array([0x99]), NOW.toISOString(), NOW.toISOString())
.run();
const wrongRkey = await SELF.fetch(
`https://test${PATH}?did=${DID_B}&collection=${NSID.publisherProfile}&rkey=other`,
);
expect(wrongRkey.status).toBe(404);
const correctRkey = await SELF.fetch(
`https://test${PATH}?did=${DID_B}&collection=${NSID.publisherProfile}&rkey=self`,
);
expect(correctRkey.status).toBe(200);
});
});
describe("XRPC dispatcher", () => {
it("returns 404 on non-XRPC paths", async () => {
const res = await SELF.fetch("https://test/some/random/path");
expect(res.status).toBe(404);
});
it("returns 404 on unknown XRPC NSIDs", async () => {
const res = await SELF.fetch("https://test/xrpc/com.example.notARealEndpoint");
expect(res.status).toBe(404);
});
});