@ipab/cli 0.1.0-rc.1 → 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 (62) hide show
  1. package/README.md +21 -5
  2. package/dist/app-authoring.d.ts +10 -0
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +127 -11
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/assembly.d.ts +7 -0
  7. package/dist/assembly.d.ts.map +1 -0
  8. package/dist/assembly.js +131 -0
  9. package/dist/assembly.js.map +1 -0
  10. package/dist/authoring.d.ts +1 -1
  11. package/dist/authoring.d.ts.map +1 -1
  12. package/dist/authoring.js +3 -3
  13. package/dist/authoring.js.map +1 -1
  14. package/dist/builtins/template.node.car +0 -0
  15. package/dist/builtins/template.web-app.car +0 -0
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.d.ts.map +1 -1
  18. package/dist/cli.js +520 -66
  19. package/dist/cli.js.map +1 -1
  20. package/dist/config-secret.d.ts +3 -0
  21. package/dist/config-secret.d.ts.map +1 -0
  22. package/dist/config-secret.js +83 -0
  23. package/dist/config-secret.js.map +1 -0
  24. package/dist/config.d.ts +5 -2
  25. package/dist/config.d.ts.map +1 -1
  26. package/dist/config.js +105 -7
  27. package/dist/config.js.map +1 -1
  28. package/dist/content-provider.d.ts +9 -0
  29. package/dist/content-provider.d.ts.map +1 -0
  30. package/dist/content-provider.js +90 -0
  31. package/dist/content-provider.js.map +1 -0
  32. package/dist/get.d.ts +3 -0
  33. package/dist/get.d.ts.map +1 -0
  34. package/dist/get.js +61 -0
  35. package/dist/get.js.map +1 -0
  36. package/dist/identity.d.ts +9 -0
  37. package/dist/identity.d.ts.map +1 -0
  38. package/dist/identity.js +89 -0
  39. package/dist/identity.js.map +1 -0
  40. package/dist/source-bundle.js +1 -1
  41. package/dist/source-bundle.js.map +1 -1
  42. package/dist/state.d.ts +15 -0
  43. package/dist/state.d.ts.map +1 -1
  44. package/dist/state.js +100 -1
  45. package/dist/state.js.map +1 -1
  46. package/dist/swarm.d.ts +113 -0
  47. package/dist/swarm.d.ts.map +1 -0
  48. package/dist/swarm.js +760 -0
  49. package/dist/swarm.js.map +1 -0
  50. package/package.json +10 -5
  51. package/src/app-authoring.ts +188 -16
  52. package/src/assembly.ts +182 -0
  53. package/src/authoring.ts +10 -3
  54. package/src/cli.ts +641 -68
  55. package/src/config-secret.ts +96 -0
  56. package/src/config.ts +142 -7
  57. package/src/content-provider.ts +123 -0
  58. package/src/get.ts +68 -0
  59. package/src/identity.ts +133 -0
  60. package/src/source-bundle.ts +1 -1
  61. package/src/state.ts +112 -1
  62. package/src/swarm.ts +1186 -0
@@ -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 =
9
+ | "swarm.default"
10
+ | "swarm.service"
11
+ | "swarm.provider"
12
+ | "swarm.cacheTtl"
13
+ | "swarm.forceRefresh"
8
14
  | "store.gateway"
15
+ | "pointers.service"
16
+ | "pointers.apiKey"
9
17
  | "history.enabled"
10
18
  | "history.limit"
11
19
  | "output.retention"
@@ -13,6 +21,7 @@ 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
26
  storeGateway?: string;
18
27
  json: boolean;
@@ -23,14 +32,27 @@ export interface ConfigItem {
23
32
  source: Source;
24
33
  }
25
34
  export const defaults: Record<ConfigKey, ConfigValue> = {
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,
26
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> = {
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",
33
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,20 +87,114 @@ 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.gateway" && 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;
151
+ }
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
+ );
81
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);
82
198
  if (key === "store.gateway" && value === null) return null;
83
199
  if (
84
200
  key === "bundle.outputDir" &&
@@ -163,23 +279,42 @@ export function effectiveConfig(
163
279
  user: Partial<Record<ConfigKey, ConfigValue>>,
164
280
  flags: GlobalOptions,
165
281
  env: NodeJS.ProcessEnv = process.env,
282
+ resolveSwarm?: (reference: string) => string,
166
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
+ );
167
288
  if (env.IPAB_STORE_RPC !== undefined)
168
289
  syntax(
169
290
  "IPAB_STORE_RPC is no longer supported. Remove it and use IPAB_STORE_GATEWAY with an HTTP gateway URL.",
170
291
  );
171
292
  const result = (Object.keys(defaults) as ConfigKey[]).map(
172
293
  (key): ConfigItem => {
173
- const variable = env[environments[key]];
174
- const flag = key === "store.gateway" ? flags.storeGateway : 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;
175
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
+ );
176
311
  const environmental =
177
- variable === undefined ? undefined : parseValue(key, variable, true);
312
+ variable === undefined ? undefined : parse(variable);
178
313
  return {
179
314
  key,
180
315
  value:
181
316
  flag !== undefined
182
- ? parseValue(key, flag, true)
317
+ ? parse(flag)
183
318
  : variable !== undefined
184
319
  ? environmental!
185
320
  : Object.hasOwn(user, key)
@@ -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/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
+ }
@@ -0,0 +1,133 @@
1
+ import { lstat, mkdir, open, readFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import {
5
+ protectAccountOnly,
6
+ requireAccountOnly,
7
+ requireAccountOnlyMany,
8
+ } from "@ipab/bundle/pointer/protected-files";
9
+ import {
10
+ generateKeyPair,
11
+ importPrivateKeyPkcs8,
12
+ importPublicKeyRaw,
13
+ signEd25519,
14
+ verifyEd25519,
15
+ } from "@ipab/bundle/pointer/crypto";
16
+ import { HostError, object } from "./errors.js";
17
+ import { nodeError } from "./authoring.js";
18
+
19
+ export interface Identity {
20
+ publicKey: string;
21
+ privateKey: string;
22
+ }
23
+
24
+ export async function protectedPath(
25
+ path: string,
26
+ directory = false,
27
+ ): Promise<void> {
28
+ await regularPath(path, directory);
29
+ await requireAccountOnly(path);
30
+ }
31
+
32
+ async function regularPath(path: string, directory: boolean): Promise<void> {
33
+ const stat = await lstat(path);
34
+ if (
35
+ stat.isSymbolicLink() ||
36
+ (directory ? !stat.isDirectory() : !stat.isFile())
37
+ )
38
+ throw new HostError(
39
+ "Credential path is not a regular account-owned file/directory.",
40
+ );
41
+ }
42
+
43
+ export async function secureNew(
44
+ path: string,
45
+ directory = false,
46
+ ): Promise<void> {
47
+ await regularPath(path, directory);
48
+ await protectAccountOnly(path);
49
+ }
50
+
51
+ export async function readIdentityFile(path: string): Promise<Identity> {
52
+ await protectedPath(path);
53
+ return decodeIdentityFile(path);
54
+ }
55
+ async function decodeIdentityFile(path: string): Promise<Identity> {
56
+ let value: Record<string, unknown>;
57
+ try {
58
+ const stat = await lstat(path);
59
+ if (stat.size > 16 * 1024) throw new Error("oversized");
60
+ value = object(
61
+ JSON.parse(await readFile(path, "utf8")) as unknown,
62
+ "identity",
63
+ );
64
+ } catch {
65
+ throw new HostError(
66
+ "Invalid credential encoding. Restore the existing protected key file.",
67
+ );
68
+ }
69
+ if (
70
+ typeof value.publicKey !== "string" ||
71
+ typeof value.privateKey !== "string"
72
+ )
73
+ throw new HostError(
74
+ "Invalid identity. Restore the existing key; do not initialize a replacement.",
75
+ );
76
+ const key = await importPrivateKeyPkcs8(value.privateKey);
77
+ const proof = await signEd25519(key, "IPAB identity consistency");
78
+ if (
79
+ !(await verifyEd25519(
80
+ await importPublicKeyRaw(value.publicKey),
81
+ proof,
82
+ "IPAB identity consistency",
83
+ ))
84
+ )
85
+ throw new HostError("Identity public and private keys do not match.");
86
+ return { publicKey: value.publicKey, privateKey: value.privateKey };
87
+ }
88
+
89
+ export async function accountIdentity(
90
+ env: NodeJS.ProcessEnv,
91
+ initialize = false,
92
+ ): Promise<Identity> {
93
+ const home = resolve(env.HOME ?? env.USERPROFILE ?? homedir());
94
+ const parent = join(home, ".ipab");
95
+ const directory = join(parent, "identity");
96
+ try {
97
+ await lstat(directory);
98
+ } catch (cause) {
99
+ if (!nodeError(cause, "ENOENT")) throw cause;
100
+ if (!initialize)
101
+ throw new HostError(
102
+ "No account identity. Start with swarm create or swarm request.",
103
+ );
104
+ const created = await mkdir(parent, { recursive: true, mode: 0o700 });
105
+ if (created) await secureNew(parent, true);
106
+ else await protectedPath(parent, true);
107
+ if ((await lstat(parent)).isSymbolicLink())
108
+ throw new HostError("Identity parent must not be a symbolic link.");
109
+ await mkdir(directory, { mode: 0o700 });
110
+ await secureNew(directory, true);
111
+ const pair = await generateKeyPair();
112
+ const file = join(directory, "key.json");
113
+ const handle = await open(file, "wx", 0o600);
114
+ try {
115
+ await handle.writeFile(
116
+ JSON.stringify({
117
+ publicKey: pair.publicRaw,
118
+ privateKey: pair.privatePkcs8,
119
+ }),
120
+ );
121
+ await handle.sync();
122
+ } finally {
123
+ await handle.close();
124
+ }
125
+ await secureNew(file);
126
+ }
127
+ const file = join(directory, "key.json");
128
+ await regularPath(parent, true);
129
+ await regularPath(directory, true);
130
+ await regularPath(file, false);
131
+ await requireAccountOnlyMany([parent, directory, file]);
132
+ return decodeIdentityFile(file);
133
+ }
@@ -41,7 +41,7 @@ export async function captureSource(
41
41
  if (
42
42
  normalized
43
43
  .split("/")
44
- .some((part) => [".git", "node_modules"].includes(part)) ||
44
+ .some((part) => [".git", ".ipab", "node_modules"].includes(part)) ||
45
45
  normalized === ".bundle-ignore" ||
46
46
  normalized === "dist" ||
47
47
  normalized.startsWith("dist/") ||