@ipab/cli 0.1.0-rc.0 → 0.1.0-rc.2

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 (101) hide show
  1. package/README.md +26 -4
  2. package/dist/app-authoring.d.ts +11 -2
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +135 -20
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-definition.d.ts +0 -6
  7. package/dist/app-definition.d.ts.map +1 -1
  8. package/dist/app-definition.js +1 -7
  9. package/dist/app-definition.js.map +1 -1
  10. package/dist/app-templates.d.ts.map +1 -1
  11. package/dist/app-templates.js +8 -0
  12. package/dist/app-templates.js.map +1 -1
  13. package/dist/assembly.d.ts +7 -0
  14. package/dist/assembly.d.ts.map +1 -0
  15. package/dist/assembly.js +131 -0
  16. package/dist/assembly.js.map +1 -0
  17. package/dist/authoring.d.ts +6 -15
  18. package/dist/authoring.d.ts.map +1 -1
  19. package/dist/authoring.js +13 -42
  20. package/dist/authoring.js.map +1 -1
  21. package/dist/builtins/template.node.car +0 -0
  22. package/dist/builtins/template.web-app.car +0 -0
  23. package/dist/builtins.d.ts.map +1 -1
  24. package/dist/builtins.js +5 -10
  25. package/dist/builtins.js.map +1 -1
  26. package/dist/cli.d.ts +1 -0
  27. package/dist/cli.d.ts.map +1 -1
  28. package/dist/cli.js +639 -147
  29. package/dist/cli.js.map +1 -1
  30. package/dist/config-secret.d.ts +3 -0
  31. package/dist/config-secret.d.ts.map +1 -0
  32. package/dist/config-secret.js +83 -0
  33. package/dist/config-secret.js.map +1 -0
  34. package/dist/config.d.ts +7 -4
  35. package/dist/config.d.ts.map +1 -1
  36. package/dist/config.js +118 -22
  37. package/dist/config.js.map +1 -1
  38. package/dist/content-provider.d.ts +9 -0
  39. package/dist/content-provider.d.ts.map +1 -0
  40. package/dist/content-provider.js +90 -0
  41. package/dist/content-provider.js.map +1 -0
  42. package/dist/context.d.ts +1 -0
  43. package/dist/context.d.ts.map +1 -1
  44. package/dist/context.js +10 -0
  45. package/dist/context.js.map +1 -1
  46. package/dist/get.d.ts +3 -0
  47. package/dist/get.d.ts.map +1 -0
  48. package/dist/get.js +61 -0
  49. package/dist/get.js.map +1 -0
  50. package/dist/identity.d.ts +9 -0
  51. package/dist/identity.d.ts.map +1 -0
  52. package/dist/identity.js +89 -0
  53. package/dist/identity.js.map +1 -0
  54. package/dist/ipc.d.ts +2 -1
  55. package/dist/ipc.d.ts.map +1 -1
  56. package/dist/ipc.js +10 -1
  57. package/dist/ipc.js.map +1 -1
  58. package/dist/pins.d.ts +9 -9
  59. package/dist/pins.d.ts.map +1 -1
  60. package/dist/pins.js +10 -28
  61. package/dist/pins.js.map +1 -1
  62. package/dist/runtime.d.ts.map +1 -1
  63. package/dist/runtime.js +1 -1
  64. package/dist/runtime.js.map +1 -1
  65. package/dist/source-bundle.d.ts +0 -1
  66. package/dist/source-bundle.d.ts.map +1 -1
  67. package/dist/source-bundle.js +1 -2
  68. package/dist/source-bundle.js.map +1 -1
  69. package/dist/state.d.ts +35 -10
  70. package/dist/state.d.ts.map +1 -1
  71. package/dist/state.js +124 -14
  72. package/dist/state.js.map +1 -1
  73. package/dist/swarm.d.ts +113 -0
  74. package/dist/swarm.d.ts.map +1 -0
  75. package/dist/swarm.js +760 -0
  76. package/dist/swarm.js.map +1 -0
  77. package/dist/template-definition.d.ts +0 -17
  78. package/dist/template-definition.d.ts.map +1 -1
  79. package/dist/template-definition.js +1 -10
  80. package/dist/template-definition.js.map +1 -1
  81. package/package.json +15 -10
  82. package/src/app-authoring.ts +203 -29
  83. package/src/app-definition.ts +1 -7
  84. package/src/app-templates.ts +13 -0
  85. package/src/assembly.ts +182 -0
  86. package/src/authoring.ts +32 -58
  87. package/src/builtins.ts +5 -11
  88. package/src/cli.ts +785 -167
  89. package/src/config-secret.ts +96 -0
  90. package/src/config.ts +161 -25
  91. package/src/content-provider.ts +123 -0
  92. package/src/context.ts +10 -0
  93. package/src/get.ts +68 -0
  94. package/src/identity.ts +133 -0
  95. package/src/ipc.ts +8 -0
  96. package/src/pins.ts +14 -28
  97. package/src/runtime.ts +1 -0
  98. package/src/source-bundle.ts +1 -2
  99. package/src/state.ts +149 -24
  100. package/src/swarm.ts +1186 -0
  101. package/src/template-definition.ts +1 -10
@@ -0,0 +1,96 @@
1
+ import { chmodSync, existsSync, lstatSync } from "node:fs";
2
+ import { execFileSync } from "node:child_process";
3
+ import { join } from "node:path";
4
+ import { HostError, syntax } from "./errors.js";
5
+
6
+ export async function readSecretStream(
7
+ input: AsyncIterable<string>,
8
+ ): Promise<string> {
9
+ let text = "";
10
+ for await (const chunk of input) {
11
+ if (Buffer.byteLength(text) + Buffer.byteLength(chunk) > 64)
12
+ syntax("API key input exceeds 64 bytes.");
13
+ text += chunk;
14
+ }
15
+ return text.trim();
16
+ }
17
+
18
+ function windowsAcl(paths: string[], protect: boolean): void {
19
+ const script = `
20
+ $ErrorActionPreference = 'Stop'
21
+ $sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
22
+ foreach ($path in (ConvertFrom-Json $env:IPAB_CONFIG_PATHS)) {
23
+ $acl = Get-Acl -LiteralPath $path
24
+ if ($env:IPAB_CONFIG_PROTECT -eq 'true') {
25
+ if ((Get-Item -LiteralPath $path).PSIsContainer) {
26
+ $acl = New-Object System.Security.AccessControl.DirectorySecurity
27
+ $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
28
+ } else {
29
+ $acl = New-Object System.Security.AccessControl.FileSecurity
30
+ $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'Allow')
31
+ }
32
+ $acl.SetAccessRuleProtection($true, $false)
33
+ $acl.AddAccessRule($rule)
34
+ if ((Get-Item -LiteralPath $path).PSIsContainer) {
35
+ [System.IO.Directory]::SetAccessControl($path, $acl)
36
+ } else {
37
+ [System.IO.File]::SetAccessControl($path, $acl)
38
+ }
39
+ } else {
40
+ foreach ($rule in $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) {
41
+ if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -ne $sid.Value) {
42
+ throw 'Configuration storage must be account-only'
43
+ }
44
+ }
45
+ }
46
+ }`;
47
+ execFileSync(
48
+ "powershell.exe",
49
+ [
50
+ "-NoProfile",
51
+ "-NonInteractive",
52
+ "-EncodedCommand",
53
+ Buffer.from(script, "utf16le").toString("base64"),
54
+ ],
55
+ {
56
+ env: {
57
+ ...Object.fromEntries(
58
+ Object.entries(process.env).filter(
59
+ ([key]) => key.toLowerCase() !== "psmodulepath",
60
+ ),
61
+ ),
62
+ IPAB_CONFIG_PATHS: JSON.stringify(paths),
63
+ IPAB_CONFIG_PROTECT: String(protect),
64
+ },
65
+ stdio: ["ignore", "pipe", "pipe"],
66
+ },
67
+ );
68
+ }
69
+ export function secureConfigurationStorage(
70
+ directory: string,
71
+ protect: boolean,
72
+ ): void {
73
+ try {
74
+ const paths = [
75
+ directory,
76
+ ...["state.sqlite", "state.sqlite-wal", "state.sqlite-shm"].map((file) =>
77
+ join(directory, file),
78
+ ),
79
+ ].filter((path) => existsSync(path));
80
+ for (const path of paths) {
81
+ const stat = lstatSync(path);
82
+ if (stat.isSymbolicLink() || (!stat.isFile() && !stat.isDirectory()))
83
+ throw new Error();
84
+ if (process.platform !== "win32") {
85
+ if (stat.uid !== process.getuid?.()) throw new Error();
86
+ if (protect) chmodSync(path, stat.isDirectory() ? 0o700 : 0o600);
87
+ else if ((stat.mode & 0o077) !== 0) throw new Error();
88
+ }
89
+ }
90
+ if (process.platform === "win32") windowsAcl(paths, protect);
91
+ } catch {
92
+ throw new HostError(
93
+ "Pointer API key configuration requires account-only state storage permissions.",
94
+ );
95
+ }
96
+ }
package/src/config.ts CHANGED
@@ -1,11 +1,19 @@
1
1
  import { homedir } from "node:os";
2
+ import { CID } from "multiformats/cid";
2
3
  import { join, resolve } from "node:path";
3
4
  import { readContentConfiguration } from "@ipab/ipfs-store/node";
4
5
  import type { StoreConfiguration } from "@ipab/ipfs-store";
5
6
  import { HostError, object, syntax } from "./errors.js";
6
7
 
7
8
  export type ConfigKey =
8
- | "store.rpc"
9
+ | "swarm.default"
10
+ | "swarm.service"
11
+ | "swarm.provider"
12
+ | "swarm.cacheTtl"
13
+ | "swarm.forceRefresh"
14
+ | "store.gateway"
15
+ | "pointers.service"
16
+ | "pointers.apiKey"
9
17
  | "history.enabled"
10
18
  | "history.limit"
11
19
  | "output.retention"
@@ -13,8 +21,9 @@ export type ConfigKey =
13
21
  export type ConfigValue = string | boolean | number | null;
14
22
  export type Source = "flag" | "env" | "user" | "default";
15
23
  export interface GlobalOptions {
24
+ swarm?: string;
16
25
  stateDir?: string;
17
- storeRpc?: string;
26
+ storeGateway?: string;
18
27
  json: boolean;
19
28
  }
20
29
  export interface ConfigItem {
@@ -23,14 +32,27 @@ export interface ConfigItem {
23
32
  source: Source;
24
33
  }
25
34
  export const defaults: Record<ConfigKey, ConfigValue> = {
26
- "store.rpc": null,
35
+ "swarm.default": null,
36
+ "swarm.service": null,
37
+ "swarm.provider": "http://127.0.0.1:5001",
38
+ "swarm.cacheTtl": 300,
39
+ "swarm.forceRefresh": false,
40
+ "store.gateway": null,
41
+ "pointers.service": null,
42
+ "pointers.apiKey": null,
27
43
  "history.enabled": true,
28
44
  "history.limit": 20,
29
45
  "output.retention": "history",
30
46
  "bundle.outputDir": "dist",
31
47
  };
32
- const environments: Record<ConfigKey, string> = {
33
- "store.rpc": "IPAB_STORE_RPC",
48
+ const environments: Partial<Record<ConfigKey, string>> = {
49
+ "swarm.service": "IPAB_SWARM_SERVICE",
50
+ "swarm.provider": "IPAB_SWARM_PROVIDER",
51
+ "swarm.cacheTtl": "IPAB_SWARM_CACHE_TTL",
52
+ "swarm.forceRefresh": "IPAB_SWARM_FORCE_REFRESH",
53
+ "store.gateway": "IPAB_STORE_GATEWAY",
54
+ "pointers.service": "IPAB_POINTERS_SERVICE",
55
+ "pointers.apiKey": "IPAB_POINTERS_API_KEY",
34
56
  "history.enabled": "IPAB_HISTORY_ENABLED",
35
57
  "history.limit": "IPAB_HISTORY_LIMIT",
36
58
  "output.retention": "IPAB_OUTPUT_RETENTION",
@@ -65,21 +87,115 @@ export function publicUrl(value: string): string {
65
87
  return url.toString();
66
88
  }
67
89
 
90
+ export function pointerService(value: string): string {
91
+ let url: URL;
92
+ try {
93
+ url = new URL(value);
94
+ } catch {
95
+ syntax(
96
+ "Pointer service must be a canonical HTTPS origin (HTTP loopback allowed).",
97
+ );
98
+ }
99
+ if (
100
+ url.username ||
101
+ url.password ||
102
+ url.search ||
103
+ url.hash ||
104
+ url.pathname !== "/" ||
105
+ (url.protocol !== "https:" &&
106
+ !(
107
+ url.protocol === "http:" &&
108
+ ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)
109
+ )) ||
110
+ value !== url.origin
111
+ )
112
+ syntax(
113
+ "Pointer service must be a canonical HTTPS origin (HTTP loopback allowed).",
114
+ );
115
+ return url.origin;
116
+ }
117
+
118
+ export function visibleConfig(item: ConfigItem): ConfigItem {
119
+ return item.key === "pointers.apiKey" && item.value !== null
120
+ ? { ...item, value: "<redacted>" }
121
+ : item;
122
+ }
123
+
68
124
  export function parseValue(
69
125
  key: ConfigKey,
70
126
  value: unknown,
71
127
  text = false,
72
128
  ): ConfigValue {
73
129
  if (text && typeof value === "string") {
74
- if (key === "history.enabled") {
130
+ if (key.startsWith("swarm.") && value === "default")
131
+ return key === "swarm.cacheTtl" || key === "swarm.forceRefresh"
132
+ ? defaults[key]
133
+ : null;
134
+ if (key === "history.enabled" || key === "swarm.forceRefresh") {
75
135
  if (value === "true") return true;
76
136
  if (value === "false") return false;
77
137
  }
78
138
  if (key === "history.limit" && /^[1-9]\d*$/.test(value))
79
139
  value = Number(value);
80
- if (key === "store.rpc" && value === "default") return null;
140
+ if (
141
+ key === "swarm.cacheTtl" &&
142
+ typeof value === "string" &&
143
+ /^(0|[1-9]\d*)$/.test(value)
144
+ )
145
+ value = Number(value);
146
+ if (
147
+ ["store.gateway", "pointers.service", "pointers.apiKey"].includes(key) &&
148
+ value === "default"
149
+ )
150
+ return null;
81
151
  }
82
- if (key === "store.rpc" && value === null) return null;
152
+ if (key === "pointers.service" || key === "pointers.apiKey") {
153
+ if (value === null) return null;
154
+ if (key === "pointers.service" && typeof value === "string")
155
+ return pointerService(value);
156
+ if (
157
+ key === "pointers.apiKey" &&
158
+ typeof value === "string" &&
159
+ /^[A-Za-z0-9_-]{43}$/.test(value) &&
160
+ Buffer.from(value, "base64url").toString("base64url") === value
161
+ )
162
+ return value;
163
+ syntax(
164
+ key === "pointers.apiKey"
165
+ ? "Invalid pointers.apiKey; expected a canonical base64url encoding of 32 bytes."
166
+ : "Invalid pointers.service; expected a canonical HTTPS origin or default.",
167
+ );
168
+ }
169
+ if (key === "swarm.cacheTtl") {
170
+ if (
171
+ Number.isSafeInteger(value) &&
172
+ typeof value === "number" &&
173
+ value >= 0 &&
174
+ value <= 86400
175
+ )
176
+ return value;
177
+ syntax(
178
+ "swarm.cacheTtl requires an integer number of seconds from 0 to 86400.",
179
+ );
180
+ }
181
+ if (key === "swarm.forceRefresh") {
182
+ if (typeof value === "boolean") return value;
183
+ syntax("swarm.forceRefresh requires true or false.");
184
+ }
185
+ if (key.startsWith("swarm.") && value === null) return null;
186
+ if (key === "swarm.default" && typeof value === "string") {
187
+ try {
188
+ return CID.parse(value).toV1().toString();
189
+ } catch {
190
+ syntax("swarm.default requires an exact Swarm Bundle CID.");
191
+ }
192
+ }
193
+ if (
194
+ (key === "swarm.service" || key === "swarm.provider") &&
195
+ typeof value === "string"
196
+ )
197
+ return publicUrl(value);
198
+ if (key === "store.gateway" && value === null) return null;
83
199
  if (
84
200
  key === "bundle.outputDir" &&
85
201
  typeof value === "string" &&
@@ -87,7 +203,8 @@ export function parseValue(
87
203
  !value.includes("\0")
88
204
  )
89
205
  return value;
90
- if (key === "store.rpc" && typeof value === "string") return publicUrl(value);
206
+ if (key === "store.gateway" && typeof value === "string")
207
+ return publicUrl(value);
91
208
  if (key === "history.enabled" && typeof value === "boolean") return value;
92
209
  if (
93
210
  key === "history.limit" &&
@@ -162,19 +279,42 @@ export function effectiveConfig(
162
279
  user: Partial<Record<ConfigKey, ConfigValue>>,
163
280
  flags: GlobalOptions,
164
281
  env: NodeJS.ProcessEnv = process.env,
282
+ resolveSwarm?: (reference: string) => string,
165
283
  ): ConfigItem[] {
284
+ if (env.IPAB_SWARM !== undefined)
285
+ syntax(
286
+ "IPAB_SWARM is no longer supported. Remove it and use --swarm CID_OR_ALIAS or ipab swarm use CID_OR_ALIAS.",
287
+ );
288
+ if (env.IPAB_STORE_RPC !== undefined)
289
+ syntax(
290
+ "IPAB_STORE_RPC is no longer supported. Remove it and use IPAB_STORE_GATEWAY with an HTTP gateway URL.",
291
+ );
166
292
  const result = (Object.keys(defaults) as ConfigKey[]).map(
167
293
  (key): ConfigItem => {
168
- const variable = env[environments[key]];
169
- const flag = key === "store.rpc" ? flags.storeRpc : undefined;
294
+ const environment = environments[key];
295
+ const variable = environment === undefined ? undefined : env[environment];
296
+ const flag =
297
+ key === "store.gateway"
298
+ ? flags.storeGateway
299
+ : key === "swarm.default"
300
+ ? flags.swarm
301
+ : undefined;
170
302
  // Invalid lower layers are not hidden by a higher-priority override.
303
+ const parse = (value: string) =>
304
+ parseValue(
305
+ key,
306
+ key === "swarm.default" && value !== "default" && resolveSwarm
307
+ ? resolveSwarm(value)
308
+ : value,
309
+ true,
310
+ );
171
311
  const environmental =
172
- variable === undefined ? undefined : parseValue(key, variable, true);
312
+ variable === undefined ? undefined : parse(variable);
173
313
  return {
174
314
  key,
175
315
  value:
176
316
  flag !== undefined
177
- ? parseValue(key, flag, true)
317
+ ? parse(flag)
178
318
  : variable !== undefined
179
319
  ? environmental!
180
320
  : Object.hasOwn(user, key)
@@ -201,20 +341,16 @@ export function effectiveConfig(
201
341
  }
202
342
 
203
343
  export async function storeConfiguration(
204
- rpc: ConfigValue,
344
+ gateway: ConfigValue,
205
345
  ): Promise<StoreConfiguration> {
206
- const config =
207
- rpc === null
208
- ? await readContentConfiguration()
209
- : { backend: "kubo" as const, apiUrl: publicUrl(String(rpc)) };
210
- const urls =
211
- config.backend === "kubo"
212
- ? [config.apiUrl]
346
+ const config = await readContentConfiguration(
347
+ gateway === null ? {} : { gateway: publicUrl(String(gateway)) },
348
+ );
349
+ const urls = config.gateway
350
+ ? typeof config.gateway === "string"
351
+ ? [config.gateway]
213
352
  : config.gateway
214
- ? typeof config.gateway === "string"
215
- ? [config.gateway]
216
- : config.gateway
217
- : [];
353
+ : [];
218
354
  for (const url of urls) publicUrl(url);
219
355
  return config;
220
356
  }
@@ -0,0 +1,123 @@
1
+ import {
2
+ createWriter,
3
+ headerLength,
4
+ blockLength,
5
+ } from "@ipld/car/buffer-writer";
6
+ import * as dagPb from "@ipld/dag-pb";
7
+ import * as dagCbor from "@ipld/dag-cbor";
8
+ import { CID } from "multiformats/cid";
9
+ import type { IpfsStore } from "@ipab/ipfs-store";
10
+ import { bundleLimits, openBundle } from "@ipab/bundle";
11
+ import { bytes } from "./space.js";
12
+ import { HostError } from "./errors.js";
13
+ import { publicUrl } from "./config.js";
14
+
15
+ export async function contentCar(
16
+ store: IpfsStore,
17
+ roots: readonly string[],
18
+ ): Promise<Uint8Array> {
19
+ const blocks = new Map<string, { cid: CID; bytes: Uint8Array }>();
20
+ let total = 0;
21
+ const visit = async (cid: CID, depth: number): Promise<void> => {
22
+ const key = cid.toV1().toString();
23
+ if (blocks.has(key)) return;
24
+ if (depth > bundleLimits.depth || blocks.size >= bundleLimits.blocks)
25
+ throw new HostError("Publication DAG exceeds limits.");
26
+ const value = await store.block.get(key);
27
+ total += value.length;
28
+ if (total > bundleLimits.bytes)
29
+ throw new HostError("Publication exceeds byte budget.");
30
+ blocks.set(key, { cid, bytes: value });
31
+ if (cid.code === dagPb.code)
32
+ for (const link of dagPb.decode(value).Links)
33
+ await visit(link.Hash, depth + 1);
34
+ else if (cid.code === dagCbor.code) {
35
+ const scan = async (value: unknown): Promise<void> => {
36
+ const link = CID.asCID(value);
37
+ if (link) await visit(link, depth + 1);
38
+ else if (Array.isArray(value))
39
+ for (const item of value) await scan(item);
40
+ else if (value && typeof value === "object")
41
+ for (const item of Object.values(value)) await scan(item);
42
+ };
43
+ await scan(dagCbor.decode(value));
44
+ }
45
+ };
46
+ const cids = [...new Set(roots)].map((root) => CID.parse(root));
47
+ for (const cid of cids) await visit(cid, 0);
48
+ const size =
49
+ headerLength({ roots: cids }) +
50
+ [...blocks.values()].reduce((sum, block) => sum + blockLength(block), 0);
51
+ const writer = createWriter(new ArrayBuffer(size), { roots: cids });
52
+ for (const block of blocks.values()) writer.write(block);
53
+ return writer.close();
54
+ }
55
+
56
+ /** Explicit upload bridge, not a Store backend or daemon lifecycle controller. */
57
+ export async function provideContent(
58
+ store: IpfsStore,
59
+ roots: readonly string[],
60
+ endpoint: string,
61
+ fetcher: typeof fetch = fetch,
62
+ ): Promise<void> {
63
+ const url = new URL(publicUrl(endpoint));
64
+ if (
65
+ url.protocol !== "https:" &&
66
+ !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)
67
+ )
68
+ throw new HostError(
69
+ "Kubo provider must use HTTPS or account-local loopback HTTP.",
70
+ );
71
+ const car = await contentCar(store, roots);
72
+ const owner = `publication:${roots[0]!}`;
73
+ store.registerOwner(owner, roots);
74
+ await store.retain(owner, roots);
75
+ const data = new FormData();
76
+ data.append("file", new Blob([Uint8Array.from(car)]), "content.car");
77
+ const response = await fetcher(
78
+ `${url.toString().replace(/\/$/, "")}/api/v0/dag/import?pin-roots=true`,
79
+ {
80
+ method: "POST",
81
+ body: data,
82
+ redirect: "error",
83
+ signal: AbortSignal.timeout(30_000),
84
+ },
85
+ );
86
+ if (!response.ok || !response.body)
87
+ throw new HostError(
88
+ `Content provider import failed (HTTP ${response.status}); HEAD was not changed.`,
89
+ );
90
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(
91
+ await bytes(response.body, 256 * 1024),
92
+ );
93
+ const accepted = new Set<string>();
94
+ for (const line of text.trim().split(/\r?\n/)) {
95
+ const item = JSON.parse(line) as {
96
+ Root?: { Cid?: { "/"?: string }; PinErrorMsg?: string };
97
+ ErrMsg?: string;
98
+ };
99
+ if (item.ErrMsg || item.Root?.PinErrorMsg)
100
+ throw new HostError("Content provider failed to pin imported roots.");
101
+ if (item.Root?.Cid?.["/"])
102
+ accepted.add(CID.parse(item.Root.Cid["/"]).toV1().toString());
103
+ }
104
+ if (roots.some((root) => !accepted.has(CID.parse(root).toV1().toString())))
105
+ throw new HostError(
106
+ "Content provider did not confirm every imported/pinned root; HEAD was not changed.",
107
+ );
108
+ }
109
+
110
+ export async function bundleJson(store: IpfsStore, root: string) {
111
+ const bundle = await openBundle(CID.parse(root), {
112
+ resolveCid: (cid) => store.block.get(cid.toString()),
113
+ });
114
+ const value: unknown = JSON.parse(
115
+ new TextDecoder("utf-8", { fatal: true }).decode(
116
+ await bytes(
117
+ await bundle.readFile(bundle.manifest.entry.path),
118
+ 1024 * 1024,
119
+ ),
120
+ ),
121
+ );
122
+ return { bundle, value };
123
+ }
package/src/context.ts CHANGED
@@ -3,6 +3,7 @@ import { CHUNK_BYTES, relativePath } from "./space.js";
3
3
 
4
4
  export interface AppContext {
5
5
  readonly appCid: string;
6
+ resolvePin(name: string): Promise<string | undefined>;
6
7
  readFile(
7
8
  rootCid: string,
8
9
  path: string,
@@ -126,6 +127,15 @@ export function createContext(port: Port): {
126
127
  }
127
128
  };
128
129
  const context: AppContext = {
130
+ async resolvePin(name) {
131
+ if (!name || name.length > 256)
132
+ throw new HostError("Pin name must contain 1..256 characters.");
133
+ const result = await rpc("resolvePin", name);
134
+ if (result === null) return undefined;
135
+ if (typeof result !== "string")
136
+ throw new HostError("Invalid pin lookup response.");
137
+ return result;
138
+ },
129
139
  get appCid() {
130
140
  if (!appCid)
131
141
  throw new HostError("IPAB context identity is not initialized.");
package/src/get.ts ADDED
@@ -0,0 +1,68 @@
1
+ import { dirname, resolve } from "node:path";
2
+ import { lstat } from "node:fs/promises";
3
+ import { openBundle, bundleLimits } from "@ipab/bundle";
4
+ import { CID } from "multiformats/cid";
5
+ import type { IpfsStore } from "@ipab/ipfs-store";
6
+ import { scaffoldFiles, nodeError } from "./authoring.js";
7
+ import { relativePath } from "./space.js";
8
+ import { HostError } from "./errors.js";
9
+
10
+ export async function getBundle(
11
+ store: IpfsStore,
12
+ cid: string,
13
+ output = cid,
14
+ ): Promise<string> {
15
+ await openBundle(CID.parse(cid), {
16
+ resolveCid: (cid) => store.block.get(cid.toString()),
17
+ });
18
+ const files = new Map<string, Uint8Array>();
19
+ let total = 0;
20
+ const visit = async (
21
+ root: CID,
22
+ path: string,
23
+ depth: number,
24
+ ): Promise<void> => {
25
+ if (depth > bundleLimits.depth || files.size > bundleLimits.files)
26
+ throw new HostError("Download tree exceeds Bundle limits.");
27
+ const node = await store.read(root);
28
+ if (node.type === "directory") {
29
+ for await (const item of node.entries()) {
30
+ const target = path ? `${path}/${item.name}` : item.name;
31
+ relativePath(target);
32
+ await visit(item.cid, target, depth + 1);
33
+ }
34
+ } else {
35
+ const chunks: Uint8Array[] = [];
36
+ let size = 0;
37
+ for await (const chunk of node.content()) {
38
+ total += chunk.length;
39
+ size += chunk.length;
40
+ if (total > bundleLimits.bytes)
41
+ throw new HostError("Download exceeds byte budget.");
42
+ chunks.push(chunk);
43
+ }
44
+ const value = new Uint8Array(size);
45
+ let offset = 0;
46
+ for (const chunk of chunks) {
47
+ value.set(chunk, offset);
48
+ offset += chunk.length;
49
+ }
50
+ files.set(path, value);
51
+ }
52
+ };
53
+ await visit(CID.parse(cid), "", 0);
54
+ const directory = resolve(output);
55
+ for (let current = directory; ; current = dirname(current)) {
56
+ try {
57
+ const stat = await lstat(current);
58
+ if (stat.isSymbolicLink() || !stat.isDirectory())
59
+ throw new HostError(
60
+ "Download destination must not cross a symlink or file.",
61
+ );
62
+ } catch (cause) {
63
+ if (!nodeError(cause, "ENOENT")) throw cause;
64
+ }
65
+ if (dirname(current) === current) break;
66
+ }
67
+ return scaffoldFiles(directory, files);
68
+ }