~james/core

core/web/src/lib/api/strings.test.ts -rw-r--r-- 9.0 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
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
import { describe, expect, it, vi } from "vitest";
import type { OAuthUserAgent } from "@atcute/oauth-browser-client";
import type { BobbinContext } from "#lib/api/client.ts";

const agent = { sub: "did:plc:alice" } as unknown as OAuthUserAgent;

const BLOB = {
	$type: "blob" as const,
	ref: { $link: "bafkreifqrrwn3ioqkrquhibb3csu6i3kogd76uk6ktptc7s5exim6rfu6u" },
	mimeType: "text/plain",
	size: 12
};

const load = async () => {
	vi.resetModules();
	const writes: Record<string, unknown>[] = [];
	const waits: Record<string, unknown>[] = [];
	vi.doMock("$app/env", () => ({ browser: true }));
	vi.doMock("#lib/auth/agent.ts", () => ({
		createClient: () => ({
			call: async (_schema: unknown, options: { input: Record<string, unknown> }) => {
				writes.push(options.input);
				return {
					ok: true,
					data: {
						uri: "at://did:plc:alice/org.tangled.snippet.string/3l7abc",
						cid: "bafyreicu44j74asmgef6cyxrpe5ege6cmovaqx6dzckgtawb7m2odv24gu"
					}
				};
			}
		})
	}));
	const strings = await import("./strings");
	const graph = await import("./graph");
	const records = await import("./records");
	const bobbin = {
		xrpc: {
			call: async (_schema: unknown, options: { params: Record<string, unknown> }) => {
				waits.push(options.params);
				return {
					ok: true,
					data: options.params.cid
						? { status: "indexed", cid: options.params.cid }
						: { status: "deleted" }
				};
			}
		}
	} as unknown as BobbinContext;
	return { strings, graph, records, writes, waits, bobbin };
};

describe("strings api", () => {
	it("puts a string record into org.tangled.snippet.string collection with optional swapRecord", async () => {
		const { strings, writes, waits, bobbin } = await load();
		await strings.putString(
			agent,
			bobbin,
			"3l7abc",
			{
				$type: "org.tangled.snippet.string",
				snippet: {
					$type: "org.tangled.snippet.string#textFile",
					name: "main.rs",
					content: BLOB
				},
				description: "test snippet",
				createdAt: "2026-05-01T00:00:00Z"
			},
			"bafyreigrjynfxx5cdjylqloavwwdjsx3sfdssjqoeohh72jetcrnpgg6cy"
		);

		expect(writes).toHaveLength(1);
		expect(writes[0]).toMatchObject({
			repo: "did:plc:alice",
			collection: "org.tangled.snippet.string",
			rkey: "3l7abc",
			swapRecord: "bafyreigrjynfxx5cdjylqloavwwdjsx3sfdssjqoeohh72jetcrnpgg6cy",
			record: {
				$type: "org.tangled.snippet.string",
				snippet: { name: "main.rs", content: BLOB }
			}
		});
		expect(waits).toEqual([
			{
				uri: "at://did:plc:alice/org.tangled.snippet.string/3l7abc",
				cid: "bafyreicu44j74asmgef6cyxrpe5ege6cmovaqx6dzckgtawb7m2odv24gu"
			}
		]);
	});

	it("surfaces a write the appview did not index", async () => {
		const { strings, bobbin } = await load();
		(bobbin as unknown as { xrpc: { call: unknown } }).xrpc.call = async () => ({
			ok: true,
			data: { status: "rejected", detail: "unknown collection" }
		});

		await expect(
			strings.putString(agent, bobbin, "3l7abc", {
				$type: "org.tangled.snippet.string",
				snippet: {
					$type: "org.tangled.snippet.string#textFile",
					name: "main.rs",
					content: BLOB
				},
				createdAt: "2026-05-01T00:00:00Z"
			})
		).rejects.toThrow("unknown collection");
	});

	it("deletes a string record from org.tangled.snippet.string collection with optional swapRecord", async () => {
		const { strings, writes, waits, bobbin } = await load();
		await strings.deleteString(
			agent,
			bobbin,
			"at://did:plc:alice/org.tangled.snippet.string/3l7abc",
			"bafyreigrjynfxx5cdjylqloavwwdjsx3sfdssjqoeohh72jetcrnpgg6cy"
		);

		expect(writes).toHaveLength(1);
		expect(writes[0]).toMatchObject({
			repo: "did:plc:alice",
			collection: "org.tangled.snippet.string",
			rkey: "3l7abc",
			swapRecord: "bafyreigrjynfxx5cdjylqloavwwdjsx3sfdssjqoeohh72jetcrnpgg6cy"
		});
		expect(waits).toEqual([{ uri: "at://did:plc:alice/org.tangled.snippet.string/3l7abc" }]);
	});

	it("reports an unconfirmed delete instead of failing the delete", async () => {
		vi.useFakeTimers();
		try {
			const { strings, bobbin } = await load();
			(bobbin as unknown as { xrpc: { call: unknown } }).xrpc.call = async () => ({
				ok: true,
				data: { status: "indexed", cid: "bafytest" }
			});

			const deleted = strings.deleteString(
				agent,
				bobbin,
				"at://did:plc:alice/org.tangled.snippet.string/3l7abc"
			);
			await vi.advanceTimersByTimeAsync(6000);
			await expect(deleted).resolves.toBe(false);
		} finally {
			vi.useRealTimers();
		}
	});

	it("confirms a delete once the remembered write stops answering", async () => {
		const { strings, bobbin } = await load();
		let asks = 0;
		(bobbin as unknown as { xrpc: { call: unknown } }).xrpc.call = async () => {
			asks += 1;
			return asks === 1
				? { ok: true, data: { status: "indexed", cid: "bafytest" } }
				: { ok: true, data: { status: "deleted" } };
		};

		await expect(
			strings.deleteString(
				agent,
				bobbin,
				"at://did:plc:alice/org.tangled.snippet.string/3l7abc"
			)
		).resolves.toBe(true);
		expect(asks).toBe(2);
	});

	it("stops asking after the budget when bobbin keeps answering with the write", async () => {
		const { bobbin } = await load();
		let asks = 0;
		(bobbin as unknown as { xrpc: { call: unknown } }).xrpc.call = async () => {
			asks += 1;
			return { ok: true, data: { status: "indexed", cid: "bafytest" } };
		};

		const { awaitDeletedRecord } = await import("./awaitRecord");
		await expect(
			awaitDeletedRecord(bobbin, "at://did:plc:alice/org.tangled.snippet.string/3l7abc", {
				budgetMs: 5,
				pollMs: 1
			})
		).resolves.toBe(false);
		expect(asks).toBeGreaterThan(1);
	});

	it("creates a star on a string AT-URI", async () => {
		const { graph, writes } = await load();
		const { rkey } = await graph.createStar(agent, {
			kind: "string",
			uri: "at://did:plc:bob/org.tangled.snippet.string/3l7xyz",
			cid: "bafyreiasfuctyrni66wjjvcrvckwcjsheir3a56bx2y5j7ietypnsfd7gy"
		});

		expect(writes).toHaveLength(1);
		expect(writes[0]).toMatchObject({
			repo: "did:plc:alice",
			collection: "org.tangled.feed.star",
			record: {
				$type: "org.tangled.feed.star",
				subject: {
					$type: "org.tangled.feed.star#record",
					record: {
						uri: "at://did:plc:bob/org.tangled.snippet.string/3l7xyz",
						cid: "bafyreiasfuctyrni66wjjvcrvckwcjsheir3a56bx2y5j7ietypnsfd7gy"
					}
				}
			}
		});
		expect(rkey).toBe("3l7abc");
	});

	it("fetches a string via getString", async () => {
		const { records } = await load();
		const mockFetch = vi.fn().mockResolvedValue({
			ok: true,
			json: async () => ({
				uri: "at://did:plc:alice/org.tangled.snippet.string/3l7abc",
				cid: "bafyreicu44j74asmgef6cyxrpe5ege6cmovaqx6dzckgtawb7m2odv24gu",
				value: {
					$type: "org.tangled.snippet.string",
					snippet: {
						$type: "org.tangled.snippet.string#textFile",
						name: "main.rs",
						content: BLOB
					},
					description: "test snippet",
					createdAt: "2026-05-01T00:00:00Z"
				}
			})
		});
		const ctx: BobbinContext = {
			serviceUrl: "https://bobbin.tangled.local",
			fetch: mockFetch,
			xrpc: {} as unknown as BobbinContext["xrpc"]
		};

		const result = await records.getString(
			ctx,
			"at://did:plc:alice/org.tangled.snippet.string/3l7abc"
		);
		expect(mockFetch).toHaveBeenCalledTimes(1);
		const url = new URL(mockFetch.mock.calls[0][0]);
		expect(url.pathname).toBe("/xrpc/org.tangled.string.getString");
		expect(url.searchParams.get("uri")).toBe(
			"at://did:plc:alice/org.tangled.snippet.string/3l7abc"
		);
		expect(result.value.snippet.name).toBe("main.rs");
	});
});

describe("fetchStringContents", () => {
	const subject = (pds: string) =>
		({
			did: "did:plc:alice",
			handle: "alice.test",
			pds,
			uri: "at://did:plc:alice/org.tangled.snippet.string/3l7abc",
			record: { value: { snippet: { name: "a.txt", content: BLOB } } }
		}) as never;

	const load = async () => {
		vi.resetModules();
		vi.doMock("$app/env", () => ({ browser: false, dev: false }));
		return import("#lib/api/strings.ts");
	};

	it("reads the blob from a public pds", async () => {
		const { fetchStringContents } = await load();
		const fetch = vi.fn(async () => new Response("hello"));
		expect(await fetchStringContents(fetch, subject("https://pds.example.com"))).toBe("hello");
	});

	it("never fetches from a pds in the private network", async () => {
		const { fetchStringContents } = await load();
		const fetch = vi.fn(async () => new Response("secret"));
		for (const pds of [
			"http://169.254.169.254",
			"https://localhost:2583",
			"http://bobbin:8090"
		])
			await expect(fetchStringContents(fetch, subject(pds))).rejects.toMatchObject({
				status: 502
			});
		expect(fetch).not.toHaveBeenCalled();
	});

	it("doesn't follow a public pds's redirect into the private network", async () => {
		const { fetchStringContents } = await load();
		const fetch = vi.fn(
			async () =>
				new Response(null, {
					status: 302,
					headers: { location: "http://169.254.169.254/latest/meta-data" }
				})
		);
		await expect(
			fetchStringContents(fetch, subject("https://evil.example.com"))
		).rejects.toMatchObject({ status: 502 });
		expect(fetch).toHaveBeenCalledTimes(1);
	});
});