@ipab/ipfs-store 0.0.0 → 0.1.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +244 -1
  3. package/dist/configuration.d.ts +21 -0
  4. package/dist/configuration.d.ts.map +1 -0
  5. package/dist/configuration.js +62 -0
  6. package/dist/configuration.js.map +1 -0
  7. package/dist/dag.d.ts +49 -0
  8. package/dist/dag.d.ts.map +1 -0
  9. package/dist/dag.js +216 -0
  10. package/dist/dag.js.map +1 -0
  11. package/dist/errors.d.ts +6 -0
  12. package/dist/errors.d.ts.map +1 -0
  13. package/dist/errors.js +15 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/index.d.ts +57 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +417 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/kubo.d.ts +38 -0
  20. package/dist/kubo.d.ts.map +1 -0
  21. package/dist/kubo.js +189 -0
  22. package/dist/kubo.js.map +1 -0
  23. package/dist/node.d.ts +11 -0
  24. package/dist/node.d.ts.map +1 -0
  25. package/dist/node.js +60 -0
  26. package/dist/node.js.map +1 -0
  27. package/dist/retention.d.ts +44 -0
  28. package/dist/retention.d.ts.map +1 -0
  29. package/dist/retention.js +328 -0
  30. package/dist/retention.js.map +1 -0
  31. package/dist/storage.d.ts +28 -0
  32. package/dist/storage.d.ts.map +1 -0
  33. package/dist/storage.js +161 -0
  34. package/dist/storage.js.map +1 -0
  35. package/dist/store.d.ts +71 -0
  36. package/dist/store.d.ts.map +1 -0
  37. package/dist/store.js +412 -0
  38. package/dist/store.js.map +1 -0
  39. package/package.json +67 -5
  40. package/src/configuration.ts +93 -0
  41. package/src/dag.ts +281 -0
  42. package/src/errors.ts +25 -0
  43. package/src/index.ts +520 -0
  44. package/src/kubo.ts +293 -0
  45. package/src/node.ts +78 -0
  46. package/src/retention.ts +398 -0
  47. package/src/storage.ts +181 -0
  48. package/src/store.ts +577 -0
package/src/kubo.ts ADDED
@@ -0,0 +1,293 @@
1
+ import { CID } from "multiformats/cid";
2
+ import { verifyBlock } from "./dag.js";
3
+ import { ContentError } from "./errors.js";
4
+
5
+ export interface PinRecord {
6
+ Type: string;
7
+ Name?: string;
8
+ }
9
+ export class KuboContent {
10
+ private readonly lifetime = new AbortController();
11
+ private readonly pending = new Set<Promise<unknown>>();
12
+ constructor(
13
+ private readonly apiUrl: string,
14
+ private readonly blockBytes: number,
15
+ private readonly timeoutMs = 30_000,
16
+ ) {}
17
+ private request(
18
+ command: string,
19
+ args: Record<string, string>,
20
+ maxBytes: number,
21
+ options: { signal?: AbortSignal } = {},
22
+ body?: FormData,
23
+ ): Promise<Uint8Array> {
24
+ const operation = this.fetch(command, args, maxBytes, options, body);
25
+ this.pending.add(operation);
26
+ void operation
27
+ .finally(() => this.pending.delete(operation))
28
+ .catch(() => {});
29
+ return operation;
30
+ }
31
+ private async fetch(
32
+ command: string,
33
+ args: Record<string, string>,
34
+ maxBytes: number,
35
+ options: { signal?: AbortSignal },
36
+ body?: FormData,
37
+ ): Promise<Uint8Array> {
38
+ const signal = AbortSignal.any([
39
+ this.lifetime.signal,
40
+ AbortSignal.timeout(this.timeoutMs),
41
+ ...(options.signal ? [options.signal] : []),
42
+ ]);
43
+ signal.throwIfAborted();
44
+ const url = new URL(this.apiUrl);
45
+ url.pathname = `${url.pathname.replace(/\/(?:api\/v0\/?)?$/, "")}/api/v0/${command}`;
46
+ const headers: Record<string, string> = {};
47
+ if (url.username || url.password) {
48
+ headers.Authorization = `Basic ${Buffer.from(
49
+ `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`,
50
+ ).toString("base64")}`;
51
+ url.username = "";
52
+ url.password = "";
53
+ }
54
+ for (const [key, value] of Object.entries(args))
55
+ url.searchParams.set(key, value);
56
+ let response: Response;
57
+ try {
58
+ response = await fetch(url, {
59
+ method: "POST",
60
+ ...(body ? { body } : {}),
61
+ headers,
62
+ signal,
63
+ redirect: "error",
64
+ });
65
+ } catch {
66
+ signal.throwIfAborted();
67
+ throw new ContentError(
68
+ "rpc_unavailable",
69
+ `Kubo ${command} RPC is unavailable.`,
70
+ );
71
+ }
72
+ const bound = response.ok ? maxBytes : Math.min(maxBytes, 8192);
73
+ const reader = response.body?.getReader();
74
+ const parts: Uint8Array[] = [];
75
+ let size = 0;
76
+ try {
77
+ if (reader)
78
+ for (;;) {
79
+ const item = await reader.read();
80
+ if (item.done) break;
81
+ const chunk: unknown = item.value;
82
+ if (!(chunk instanceof Uint8Array))
83
+ throw new ContentError("rpc_failed", "Kubo RPC must return bytes.");
84
+ size += chunk.byteLength;
85
+ if (size > bound)
86
+ throw new ContentError(
87
+ "capacity_exceeded",
88
+ "Kubo RPC response capacity exceeded.",
89
+ );
90
+ parts.push(chunk);
91
+ }
92
+ } catch (error) {
93
+ signal.throwIfAborted();
94
+ if (error instanceof ContentError) throw error;
95
+ throw new ContentError(
96
+ "rpc_unavailable",
97
+ `Kubo ${command} response was interrupted.`,
98
+ );
99
+ } finally {
100
+ await reader?.cancel().catch(() => {});
101
+ reader?.releaseLock();
102
+ }
103
+ signal.throwIfAborted();
104
+ if (!response.ok) {
105
+ if (
106
+ command === "pin/ls" &&
107
+ response.status === 500 &&
108
+ /is not pinned/i.test(Buffer.concat(parts, size).toString())
109
+ )
110
+ return Buffer.from('{"Keys":{}}');
111
+ const body = Buffer.concat(parts, size).toString();
112
+ const missing =
113
+ command === "block/get" &&
114
+ /(?:not found|could not find|blockservice: key not found|block not found|no such block)/i.test(
115
+ body,
116
+ );
117
+ throw new ContentError(
118
+ response.status === 404 || missing ? "missing_block" : "rpc_failed",
119
+ missing
120
+ ? "Kubo block is missing."
121
+ : `Kubo ${command} RPC failed (HTTP ${response.status}); operation outcome may be unknown.`,
122
+ );
123
+ }
124
+ return Buffer.concat(parts, size);
125
+ }
126
+ private async json(
127
+ command: string,
128
+ args: Record<string, string>,
129
+ options: { signal?: AbortSignal },
130
+ body?: FormData,
131
+ ): Promise<unknown> {
132
+ const bytes = await this.request(command, args, 1024 * 1024, options, body);
133
+ try {
134
+ return JSON.parse(
135
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes),
136
+ );
137
+ } catch {
138
+ throw new ContentError("rpc_failed", `Invalid Kubo ${command} response.`);
139
+ }
140
+ }
141
+ readonly block = {
142
+ get: (value: string, options: { signal?: AbortSignal } = {}) =>
143
+ this.readBlock(value, options),
144
+ };
145
+ async readBlock(
146
+ value: string,
147
+ options: { signal?: AbortSignal } = {},
148
+ ): Promise<Uint8Array> {
149
+ const cid = CID.parse(value);
150
+ if (cid.multihash.code !== 0x12)
151
+ throw new Error("Unsupported content hash.");
152
+ const bytes = await this.request(
153
+ "block/get",
154
+ { arg: value },
155
+ this.blockBytes,
156
+ options,
157
+ );
158
+ await verifyBlock(cid, bytes);
159
+ return bytes;
160
+ }
161
+ async put(
162
+ cid: CID,
163
+ bytes: Uint8Array,
164
+ options: { signal?: AbortSignal } = {},
165
+ staged = false,
166
+ ): Promise<void> {
167
+ if (bytes.byteLength > this.blockBytes)
168
+ throw new ContentError(
169
+ "capacity_exceeded",
170
+ "Content block capacity exceeded.",
171
+ );
172
+ const snapshot = Uint8Array.from(bytes);
173
+ await verifyBlock(cid, snapshot);
174
+ const format = new Map([
175
+ [0x55, "raw"],
176
+ [0x70, "dag-pb"],
177
+ [0x71, "dag-cbor"],
178
+ ]).get(cid.code);
179
+ if (!format)
180
+ throw new ContentError(
181
+ "unsupported_content",
182
+ "Unsupported Kubo block codec.",
183
+ );
184
+ const body = new FormData();
185
+ body.append("file", new Blob([snapshot]), "block");
186
+ const result = (await this.json(
187
+ "block/put",
188
+ {
189
+ "cid-codec": format,
190
+ mhtype: "sha2-256",
191
+ mhlen: "32",
192
+ pin: String(staged),
193
+ },
194
+ options,
195
+ body,
196
+ )) as { Key?: string };
197
+ if (!result.Key || !CID.parse(result.Key).toV1().equals(cid.toV1()))
198
+ throw new ContentError(
199
+ "rpc_failed",
200
+ "Kubo returned a different block CID.",
201
+ );
202
+ }
203
+ async pinStatus(
204
+ cid: string,
205
+ options: { signal?: AbortSignal } = {},
206
+ ): Promise<PinRecord | undefined> {
207
+ const result = await this.json(
208
+ "pin/ls",
209
+ { arg: cid, type: "all", names: "true" },
210
+ options,
211
+ );
212
+ if (
213
+ !result ||
214
+ typeof result !== "object" ||
215
+ !("Keys" in result) ||
216
+ !result.Keys ||
217
+ typeof result.Keys !== "object" ||
218
+ Array.isArray(result.Keys)
219
+ )
220
+ throw new ContentError("rpc_failed", "Invalid Kubo pin listing.");
221
+ const status: unknown = Object.entries(result.Keys).find(([key]) =>
222
+ CID.parse(key).toV1().equals(CID.parse(cid).toV1()),
223
+ )?.[1];
224
+ if (status === undefined) return undefined;
225
+ if (!status || typeof status !== "object")
226
+ throw new ContentError("rpc_failed", "Invalid Kubo pin status.");
227
+ let type = "Type" in status ? status.Type : undefined;
228
+ const name = "Name" in status ? status.Name : undefined;
229
+ if (typeof type === "string" && type.startsWith("indirect through ")) {
230
+ try {
231
+ CID.parse(type.slice("indirect through ".length));
232
+ } catch {
233
+ throw new ContentError("rpc_failed", "Invalid Kubo pin status.");
234
+ }
235
+ type = "indirect";
236
+ }
237
+ if (
238
+ typeof type !== "string" ||
239
+ !["recursive", "direct", "indirect"].includes(type) ||
240
+ (name !== undefined && typeof name !== "string")
241
+ )
242
+ throw new ContentError("rpc_failed", "Invalid Kubo pin status.");
243
+ return { Type: type, ...(name === undefined ? {} : { Name: name }) };
244
+ }
245
+ async pin(
246
+ cid: string,
247
+ name: string,
248
+ options: { signal?: AbortSignal } = {},
249
+ recursive = true,
250
+ ): Promise<void> {
251
+ const result = (await this.json(
252
+ "pin/add",
253
+ { arg: cid, recursive: String(recursive), name },
254
+ options,
255
+ )) as { Pins?: string[] };
256
+ if (
257
+ !Array.isArray(result.Pins) ||
258
+ !result.Pins.some((value) =>
259
+ CID.parse(value).toV1().equals(CID.parse(cid).toV1()),
260
+ )
261
+ )
262
+ throw new ContentError(
263
+ "rpc_failed",
264
+ "Kubo pin confirmation did not include the requested CID.",
265
+ );
266
+ }
267
+ async unpin(
268
+ cid: string,
269
+ options: { signal?: AbortSignal } = {},
270
+ ): Promise<void> {
271
+ const result = (await this.json(
272
+ "pin/rm",
273
+ { arg: cid, recursive: "true" },
274
+ options,
275
+ )) as {
276
+ Pins?: string[];
277
+ };
278
+ if (
279
+ !Array.isArray(result.Pins) ||
280
+ !result.Pins.some((value) =>
281
+ CID.parse(value).toV1().equals(CID.parse(cid).toV1()),
282
+ )
283
+ )
284
+ throw new ContentError(
285
+ "rpc_failed",
286
+ "Kubo unpin confirmation did not include the requested CID.",
287
+ );
288
+ }
289
+ async close(): Promise<void> {
290
+ this.lifetime.abort(new Error("Kubo content store is closed."));
291
+ await Promise.allSettled([...this.pending]);
292
+ }
293
+ }
package/src/node.ts ADDED
@@ -0,0 +1,78 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { IpfsStore } from "./store.js";
5
+ import {
6
+ validateConfiguration,
7
+ type StoreConfiguration,
8
+ } from "./configuration.js";
9
+
10
+ export { SharedContent } from "./storage.js";
11
+ export type ContentConfiguration = StoreConfiguration;
12
+ export function contentConfigPath(): string {
13
+ return (
14
+ process.env.TASK_CONTENT_CONFIG ??
15
+ (process.platform === "win32"
16
+ ? join(
17
+ process.env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"),
18
+ "TaskContent",
19
+ "config.json",
20
+ )
21
+ : join(homedir(), ".config", "task-content", "config.json"))
22
+ );
23
+ }
24
+ export async function readContentConfiguration(
25
+ overrides: Partial<ContentConfiguration> = {},
26
+ path = contentConfigPath(),
27
+ ): Promise<ContentConfiguration> {
28
+ let value: unknown = {};
29
+ try {
30
+ value = JSON.parse(await readFile(path, "utf8"));
31
+ } catch (error) {
32
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
33
+ }
34
+ if (!value || typeof value !== "object" || Array.isArray(value))
35
+ throw new Error(`Invalid public content configuration: ${path}`);
36
+ const record = value as Record<string, unknown>;
37
+ const backend =
38
+ record.backend ??
39
+ (Object.keys(record).length === 0
40
+ ? (overrides.backend ?? "local")
41
+ : "local");
42
+ const defaults =
43
+ backend === "local"
44
+ ? { dataDir: join(homedir(), ".silvermoon.work", "content") }
45
+ : {};
46
+ // Validate both the file and merged value: overrides cannot hide malformed file fields.
47
+ try {
48
+ if (Object.keys(record).length)
49
+ validateConfiguration({ ...defaults, ...record });
50
+ const config = validateConfiguration({
51
+ ...defaults,
52
+ ...record,
53
+ ...overrides,
54
+ });
55
+ if (Object.keys(record).length && config.backend !== backend)
56
+ throw new Error(
57
+ "Backend overrides must replace the configuration file explicitly.",
58
+ );
59
+ if (config.coordinationDir)
60
+ config.coordinationDir = resolve(dirname(path), config.coordinationDir);
61
+ if (config.backend === "local")
62
+ config.dataDir = isAbsolute(config.dataDir)
63
+ ? resolve(config.dataDir)
64
+ : resolve(dirname(path), config.dataDir);
65
+ return config;
66
+ } catch {
67
+ throw new Error(
68
+ `Invalid public content configuration: ${path}; check backend-specific fields.`,
69
+ );
70
+ }
71
+ }
72
+ /** Explicit host helper; never called as a library import side effect. */
73
+ export async function createConfiguredContent(
74
+ overrides: Partial<ContentConfiguration> = {},
75
+ ): Promise<IpfsStore & { configuration: ContentConfiguration }> {
76
+ const configuration = await readContentConfiguration(overrides);
77
+ return new IpfsStore(configuration);
78
+ }