@ipab/cli 0.1.0-rc.1 → 0.1.0-rc.3

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 (116) hide show
  1. package/README.md +43 -6
  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 +138 -13
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-definition.d.ts +52 -57
  7. package/dist/app-definition.d.ts.map +1 -1
  8. package/dist/app-definition.js +33 -38
  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 +2 -1
  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 +130 -0
  16. package/dist/assembly.js.map +1 -0
  17. package/dist/authoring.d.ts +4 -8
  18. package/dist/authoring.d.ts.map +1 -1
  19. package/dist/authoring.js +25 -15
  20. package/dist/authoring.js.map +1 -1
  21. package/dist/builtins/skill.ipab.car +0 -0
  22. package/dist/builtins/template.node.car +0 -0
  23. package/dist/builtins/template.web-app.car +0 -0
  24. package/dist/builtins.d.ts.map +1 -1
  25. package/dist/builtins.js +18 -2
  26. package/dist/builtins.js.map +1 -1
  27. package/dist/cli.d.ts +1 -0
  28. package/dist/cli.d.ts.map +1 -1
  29. package/dist/cli.js +720 -76
  30. package/dist/cli.js.map +1 -1
  31. package/dist/config-secret.d.ts +3 -0
  32. package/dist/config-secret.d.ts.map +1 -0
  33. package/dist/config-secret.js +83 -0
  34. package/dist/config-secret.js.map +1 -0
  35. package/dist/config.d.ts +6 -2
  36. package/dist/config.d.ts.map +1 -1
  37. package/dist/config.js +109 -7
  38. package/dist/config.js.map +1 -1
  39. package/dist/content-provider.d.ts +9 -0
  40. package/dist/content-provider.d.ts.map +1 -0
  41. package/dist/content-provider.js +93 -0
  42. package/dist/content-provider.js.map +1 -0
  43. package/dist/get.d.ts +3 -0
  44. package/dist/get.d.ts.map +1 -0
  45. package/dist/get.js +80 -0
  46. package/dist/get.js.map +1 -0
  47. package/dist/identity.d.ts +9 -0
  48. package/dist/identity.d.ts.map +1 -0
  49. package/dist/identity.js +89 -0
  50. package/dist/identity.js.map +1 -0
  51. package/dist/kubo.d.ts +38 -0
  52. package/dist/kubo.d.ts.map +1 -0
  53. package/dist/kubo.js +528 -0
  54. package/dist/kubo.js.map +1 -0
  55. package/dist/pins.d.ts +3 -3
  56. package/dist/pins.js +1 -1
  57. package/dist/pins.js.map +1 -1
  58. package/dist/setup.d.ts +7 -0
  59. package/dist/setup.d.ts.map +1 -0
  60. package/dist/setup.js +22 -0
  61. package/dist/setup.js.map +1 -0
  62. package/dist/source-bundle.d.ts +3 -8
  63. package/dist/source-bundle.d.ts.map +1 -1
  64. package/dist/source-bundle.js +17 -12
  65. package/dist/source-bundle.js.map +1 -1
  66. package/dist/space.d.ts.map +1 -1
  67. package/dist/space.js +2 -2
  68. package/dist/space.js.map +1 -1
  69. package/dist/state.d.ts +19 -4
  70. package/dist/state.d.ts.map +1 -1
  71. package/dist/state.js +105 -7
  72. package/dist/state.js.map +1 -1
  73. package/dist/swarm-envelope.d.ts +36 -0
  74. package/dist/swarm-envelope.d.ts.map +1 -0
  75. package/dist/swarm-envelope.js +145 -0
  76. package/dist/swarm-envelope.js.map +1 -0
  77. package/dist/swarm-files.d.ts +5 -0
  78. package/dist/swarm-files.d.ts.map +1 -0
  79. package/dist/swarm-files.js +94 -0
  80. package/dist/swarm-files.js.map +1 -0
  81. package/dist/swarm.d.ts +173 -0
  82. package/dist/swarm.d.ts.map +1 -0
  83. package/dist/swarm.js +1245 -0
  84. package/dist/swarm.js.map +1 -0
  85. package/dist/template-definition.d.ts +47 -52
  86. package/dist/template-definition.d.ts.map +1 -1
  87. package/dist/template-definition.js +36 -41
  88. package/dist/template-definition.js.map +1 -1
  89. package/dist/template-source.d.ts +2 -0
  90. package/dist/template-source.d.ts.map +1 -1
  91. package/dist/template-source.js +4 -3
  92. package/dist/template-source.js.map +1 -1
  93. package/package.json +10 -5
  94. package/src/app-authoring.ts +210 -21
  95. package/src/app-definition.ts +33 -39
  96. package/src/app-templates.ts +9 -1
  97. package/src/assembly.ts +185 -0
  98. package/src/authoring.ts +41 -17
  99. package/src/builtins.ts +23 -2
  100. package/src/cli.ts +875 -79
  101. package/src/config-secret.ts +96 -0
  102. package/src/config.ts +146 -7
  103. package/src/content-provider.ts +124 -0
  104. package/src/get.ts +90 -0
  105. package/src/identity.ts +133 -0
  106. package/src/kubo.ts +691 -0
  107. package/src/pins.ts +1 -1
  108. package/src/setup.ts +21 -0
  109. package/src/source-bundle.ts +26 -13
  110. package/src/space.ts +2 -5
  111. package/src/state.ts +121 -9
  112. package/src/swarm-envelope.ts +255 -0
  113. package/src/swarm-files.ts +100 -0
  114. package/src/swarm.ts +2025 -0
  115. package/src/template-definition.ts +36 -41
  116. package/src/template-source.ts +10 -3
package/src/setup.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { lstat, mkdir } from "node:fs/promises";
2
+ import { accountIdentity, secureNew } from "./identity.js";
3
+ import { kuboBinary, KUBO_VERSION } from "./kubo.js";
4
+ import { keyId } from "@ipab/bundle/pointer/crypto";
5
+ import { HostError } from "./errors.js";
6
+
7
+ export async function setupDevice(stateDir: string, env: NodeJS.ProcessEnv) {
8
+ const created = await mkdir(stateDir, { recursive: true, mode: 0o700 });
9
+ if (created) await secureNew(stateDir, true);
10
+ const directory = await lstat(stateDir);
11
+ if (!directory.isDirectory() || directory.isSymbolicLink())
12
+ throw new HostError("Setup state directory must be a regular directory.");
13
+ const binary = await kuboBinary(stateDir);
14
+ const identity = await accountIdentity(env, true);
15
+ return {
16
+ kuboVersion: KUBO_VERSION,
17
+ binary,
18
+ publicKey: identity.publicKey,
19
+ fingerprint: await keyId(identity.publicKey),
20
+ };
21
+ }
@@ -2,21 +2,15 @@ import { relative, isAbsolute, sep } from "node:path";
2
2
  import { createHash } from "node:crypto";
3
3
  import ignore from "ignore";
4
4
  import { stringify } from "yaml";
5
- import { bundleLimits } from "@ipab/bundle";
5
+ import { bundleLimits, parseBundleManifest } from "@ipab/bundle";
6
6
  import { listTree, readBytes } from "@ipab/bundle-builder";
7
7
  import { filesystemTree } from "@ipab/bundle-builder/node";
8
8
  import { nodeError, type AuthoringOptions } from "./authoring.js";
9
9
  import { HostError } from "./errors.js";
10
10
 
11
11
  export const sourceSchema = {
12
- name: "IPAB App Source",
13
- description:
14
- "App project source snapshot; build inputs are ordinary resources.",
15
- entry: {
16
- path: "package.json",
17
- contentType: "application/json",
18
- schema: { type: "object" },
19
- },
12
+ contentType: "application/json",
13
+ schema: { type: "object" },
20
14
  } as const;
21
15
 
22
16
  export async function captureSource(
@@ -41,7 +35,7 @@ export async function captureSource(
41
35
  if (
42
36
  normalized
43
37
  .split("/")
44
- .some((part) => [".git", "node_modules"].includes(part)) ||
38
+ .some((part) => [".git", ".ipab", "node_modules"].includes(part)) ||
45
39
  normalized === ".bundle-ignore" ||
46
40
  normalized === "dist" ||
47
41
  normalized.startsWith("dist/") ||
@@ -113,11 +107,30 @@ export async function captureSource(
113
107
  throw new HostError("Source .bundle.yaml is excluded by .gitignore.");
114
108
  files.set(
115
109
  ".bundle.yaml",
116
- new TextEncoder().encode(stringify(sourceSchema)),
110
+ new TextEncoder().encode(
111
+ stringify({
112
+ title: "IPAB App Source",
113
+ entry: "package.json",
114
+ type: ".bundle-type.yaml",
115
+ }),
116
+ ),
117
117
  );
118
+ if (excluded(".bundle-type.yaml", false))
119
+ throw new HostError(
120
+ "Source .bundle-type.yaml is excluded by .gitignore.",
121
+ );
122
+ if (!files.has(".bundle-type.yaml"))
123
+ files.set(
124
+ ".bundle-type.yaml",
125
+ new TextEncoder().encode(stringify(sourceSchema)),
126
+ );
118
127
  }
119
- if (!files.has("package.json"))
120
- throw new HostError("Source package.json is excluded by .gitignore.");
128
+ const manifest = parseBundleManifest(files.get(".bundle.yaml")!);
129
+ for (const required of [manifest.entry, manifest.type])
130
+ if (!files.has(required))
131
+ throw new HostError(
132
+ `Source required file is excluded or missing: ${required}.`,
133
+ );
121
134
  return files;
122
135
  }
123
136
 
package/src/space.ts CHANGED
@@ -106,7 +106,7 @@ export async function loadApp(
106
106
  const bundle = await validatedBundle(root, store, owner, signal);
107
107
  if (
108
108
  bundle.schemaKey !== appSchemaCid.toString() ||
109
- bundle.manifest.entry.contentType !== "application/json"
109
+ bundle.schema.type.contentType !== "application/json"
110
110
  )
111
111
  throw new HostError(
112
112
  "App must use the documented exact builtin Node App type CID.",
@@ -117,10 +117,7 @@ export async function loadApp(
117
117
  const description = appDescription(
118
118
  JSON.parse(
119
119
  new TextDecoder("utf-8", { fatal: true }).decode(
120
- await bytes(
121
- await bundle.readFile(bundle.manifest.entry.path),
122
- 64 * 1024,
123
- ),
120
+ await bytes(await bundle.readFile(bundle.manifest.entry), 64 * 1024),
124
121
  ),
125
122
  ) as unknown,
126
123
  );
package/src/state.ts CHANGED
@@ -6,16 +6,26 @@ import { CID } from "multiformats/cid";
6
6
  import type { StoreConfiguration } from "@ipab/ipfs-store";
7
7
  import {
8
8
  validateUserConfig,
9
+ swarmUrl,
9
10
  type ConfigKey,
10
11
  type ConfigValue,
11
12
  } from "./config.js";
12
13
  import { HostError, object, syntax } from "./errors.js";
14
+ import { secureConfigurationStorage } from "./config-secret.js";
13
15
 
14
16
  export interface Association {
15
17
  schemaCid: string;
16
18
  appCid: string;
17
19
  argv: string[];
18
20
  }
21
+ export interface RegisteredSwarm {
22
+ // Keep the storage column name, but values are configuration URLs; old CID rows are rejected.
23
+ cid: string;
24
+ alias: string | null;
25
+ }
26
+ export function swarmAlias(value: string): void {
27
+ pinName(value);
28
+ }
19
29
  export interface RunRecord {
20
30
  id: string;
21
31
  origin: "exec" | "open";
@@ -43,9 +53,9 @@ export interface Hold {
43
53
  recordId: string | null;
44
54
  }
45
55
  export type PinMetadata =
46
- | { kind: "bundle"; typeName: string; schemaCid: string }
47
- | { kind: "schema"; typeName: string; schemaCid: string }
48
- | { kind: "content"; typeName: null; schemaCid: null };
56
+ | { kind: "bundle"; title: string; schemaCid: string }
57
+ | { kind: "schema"; title: string; schemaCid: string }
58
+ | { kind: "content"; title: null; schemaCid: null };
49
59
  export interface NamedPin {
50
60
  name: string;
51
61
  cid: string;
@@ -135,7 +145,7 @@ export class State {
135
145
  readonly directory: string,
136
146
  private readonly builtins: readonly NamedPin[] = [],
137
147
  ) {
138
- mkdirSync(directory, { recursive: true });
148
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
139
149
  this.db = new DatabaseSync(join(directory, "state.sqlite"));
140
150
  this.db
141
151
  .exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
@@ -144,6 +154,8 @@ export class State {
144
154
  DROP TABLE IF EXISTS aliases;
145
155
  CREATE TABLE IF NOT EXISTS named_pins (name TEXT PRIMARY KEY, owner TEXT UNIQUE NOT NULL, value TEXT NOT NULL);
146
156
  CREATE TABLE IF NOT EXISTS registrations (schema_cid TEXT PRIMARY KEY, value TEXT NOT NULL);
157
+ CREATE TABLE IF NOT EXISTS swarms (cid TEXT PRIMARY KEY, alias TEXT UNIQUE);
158
+ CREATE TABLE IF NOT EXISTS swarm_headers (account TEXT NOT NULL, swarm TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (account,swarm));
147
159
  CREATE TABLE IF NOT EXISTS runs (id TEXT PRIMARY KEY, value TEXT NOT NULL);
148
160
  CREATE TABLE IF NOT EXISTS holds (owner TEXT PRIMARY KEY, value TEXT NOT NULL);`);
149
161
  this.transaction(() => {
@@ -170,6 +182,12 @@ export class State {
170
182
  }
171
183
  config(): Partial<Record<ConfigKey, ConfigValue>> {
172
184
  const entries = this.db.prepare("SELECT key,value FROM config").all();
185
+ if (
186
+ entries.some(
187
+ (row) => row.key === "pointers.apiKey" && row.value !== "null",
188
+ )
189
+ )
190
+ secureConfigurationStorage(this.directory, false);
173
191
  if (entries.some((row) => row.key === "store.rpc"))
174
192
  throw new HostError(
175
193
  "store.rpc is no longer supported. Run ipab config reset store.rpc, then configure store.gateway with an HTTP gateway URL. Existing Kubo pins are not migrated or released.",
@@ -190,6 +208,8 @@ export class State {
190
208
  }
191
209
  }
192
210
  setConfig(key: ConfigKey, value: ConfigValue): void {
211
+ if (key === "pointers.apiKey" && value !== null)
212
+ secureConfigurationStorage(this.directory, true);
193
213
  this.db
194
214
  .prepare("INSERT OR REPLACE INTO config VALUES (?,?)")
195
215
  .run(key, JSON.stringify(value));
@@ -197,6 +217,98 @@ export class State {
197
217
  resetConfig(key: ConfigKey | "store.rpc"): void {
198
218
  this.db.prepare("DELETE FROM config WHERE key=?").run(key);
199
219
  }
220
+ swarms(): RegisteredSwarm[] {
221
+ return this.db
222
+ .prepare("SELECT cid,alias FROM swarms ORDER BY cid")
223
+ .all()
224
+ .map((row) => {
225
+ if (
226
+ typeof row.cid !== "string" ||
227
+ (row.alias !== null && typeof row.alias !== "string")
228
+ )
229
+ throw new HostError("Invalid persisted swarm registration.");
230
+ const cid = swarmUrl(row.cid);
231
+ if (row.alias !== null) swarmAlias(row.alias);
232
+ return { cid, alias: row.alias };
233
+ });
234
+ }
235
+ resolveSwarm(reference: string): string {
236
+ if (/^https?:/.test(reference)) return swarmUrl(reference);
237
+ {
238
+ const entry = this.swarms().find((entry) => entry.alias === reference);
239
+ if (entry) return entry.cid;
240
+ throw new HostError(
241
+ `Unknown swarm alias "${reference}". Run ipab swarm list.`,
242
+ );
243
+ }
244
+ }
245
+ registeredSwarm(reference: string): RegisteredSwarm {
246
+ const cid = this.resolveSwarm(reference);
247
+ const entry = this.swarms().find((entry) => entry.cid === cid);
248
+ if (!entry)
249
+ throw new HostError(
250
+ `Swarm "${reference}" is not registered. Run ipab swarm add ${cid}.`,
251
+ );
252
+ return entry;
253
+ }
254
+ checkSwarmAlias(alias: string, cid?: string): void {
255
+ swarmAlias(alias);
256
+ if (
257
+ this.swarms().some((entry) => entry.alias === alias && entry.cid !== cid)
258
+ )
259
+ throw new HostError(
260
+ `Swarm alias "${alias}" is already assigned. Choose another alias.`,
261
+ );
262
+ }
263
+ registerSwarm(cid: string, alias?: string): RegisteredSwarm {
264
+ cid = swarmUrl(cid);
265
+ return this.transaction(() => {
266
+ if (alias !== undefined) this.checkSwarmAlias(alias, cid);
267
+ const previous = this.swarms().find((entry) => entry.cid === cid);
268
+ const entry = { cid, alias: alias ?? previous?.alias ?? null };
269
+ this.db
270
+ .prepare("INSERT OR REPLACE INTO swarms VALUES (?,?)")
271
+ .run(cid, entry.alias);
272
+ if (this.config()["swarm.default"] == null)
273
+ this.setConfig("swarm.default", cid);
274
+ return entry;
275
+ });
276
+ }
277
+ useSwarm(reference: string): string {
278
+ return this.transaction(() => {
279
+ const entry = this.registeredSwarm(reference);
280
+ this.setConfig("swarm.default", entry.cid);
281
+ return entry.cid;
282
+ });
283
+ }
284
+ removeSwarm(reference: string): string {
285
+ return this.transaction(() => {
286
+ const entry = this.registeredSwarm(reference);
287
+ this.db.prepare("DELETE FROM swarms WHERE cid=?").run(entry.cid);
288
+ if (this.config()["swarm.default"] === entry.cid)
289
+ this.resetConfig("swarm.default");
290
+ return entry.cid;
291
+ });
292
+ }
293
+ swarmHeader(account: string, swarm: string): unknown {
294
+ const row = this.db
295
+ .prepare("SELECT value FROM swarm_headers WHERE account=? AND swarm=?")
296
+ .get(account, swarm);
297
+ if (!row) return undefined;
298
+ try {
299
+ return JSON.parse(String(row.value)) as unknown;
300
+ } catch {
301
+ throw new HostError("Malformed persisted swarm header cache.");
302
+ }
303
+ }
304
+ saveSwarmHeader(account: string, swarm: string, value: unknown): void {
305
+ this.db
306
+ .prepare("INSERT OR REPLACE INTO swarm_headers VALUES (?,?,?)")
307
+ .run(account, swarm, JSON.stringify(value));
308
+ }
309
+ invalidateSwarmHeader(swarm: string): void {
310
+ this.db.prepare("DELETE FROM swarm_headers WHERE swarm=?").run(swarm);
311
+ }
200
312
  resolve(value: string, schema = false): string {
201
313
  try {
202
314
  return exactCid(value, schema);
@@ -258,20 +370,20 @@ export class State {
258
370
  if (data.metadata !== null) {
259
371
  const value = object(data.metadata, "pin type metadata");
260
372
  if (value.kind === "content") {
261
- if (value.typeName !== null || value.schemaCid !== null)
373
+ if (value.title !== null || value.schemaCid !== null)
262
374
  throw new HostError("Invalid persisted pin type metadata.");
263
- metadata = { kind: "content", typeName: null, schemaCid: null };
375
+ metadata = { kind: "content", title: null, schemaCid: null };
264
376
  } else {
265
377
  if (
266
378
  (value.kind !== "bundle" && value.kind !== "schema") ||
267
- typeof value.typeName !== "string" ||
268
- !value.typeName.trim() ||
379
+ typeof value.title !== "string" ||
380
+ !value.title.trim() ||
269
381
  typeof value.schemaCid !== "string"
270
382
  )
271
383
  throw new HostError("Invalid persisted pin type metadata.");
272
384
  metadata = {
273
385
  kind: value.kind,
274
- typeName: value.typeName,
386
+ title: value.title,
275
387
  schemaCid: exactCid(value.schemaCid, true),
276
388
  };
277
389
  }
@@ -0,0 +1,255 @@
1
+ import {
2
+ createCipheriv,
3
+ createDecipheriv,
4
+ createPrivateKey,
5
+ createPublicKey,
6
+ diffieHellman,
7
+ generateKeyPairSync,
8
+ hkdfSync,
9
+ randomBytes,
10
+ } from "node:crypto";
11
+ import {
12
+ importPrivateKeyPkcs8,
13
+ importPublicKeyRaw,
14
+ signEd25519,
15
+ verifyEd25519,
16
+ } from "@ipab/bundle/pointer/crypto";
17
+ import {
18
+ parseScopeCertificate,
19
+ type ScopeCertificate,
20
+ } from "@ipab/bundle/pointer/scope";
21
+ import { HostError, object } from "./errors.js";
22
+ import type { Identity } from "./identity.js";
23
+
24
+ export interface EncryptionIdentity {
25
+ publicKey: string;
26
+ privateKey: string;
27
+ }
28
+ export function encryptionIdentity(): EncryptionIdentity {
29
+ const keys = generateKeyPairSync("x25519");
30
+ return {
31
+ publicKey: keys.publicKey
32
+ .export({ format: "der", type: "spki" })
33
+ .toString("base64url"),
34
+ privateKey: keys.privateKey
35
+ .export({ format: "der", type: "pkcs8" })
36
+ .toString("base64url"),
37
+ };
38
+ }
39
+ export interface EnvelopeBinding {
40
+ configUrl: string;
41
+ scopeId: string;
42
+ owner: string;
43
+ member: string;
44
+ requestId: string;
45
+ peerId: string;
46
+ profileId: string;
47
+ headId: string;
48
+ epoch: number;
49
+ encryptionKey: string;
50
+ }
51
+ export interface MembershipSecret {
52
+ certificate: ScopeCertificate;
53
+ swarmKey: string;
54
+ }
55
+ export interface Envelope {
56
+ binding: EnvelopeBinding;
57
+ ephemeral: string;
58
+ salt: string;
59
+ iv: string;
60
+ ciphertext: string;
61
+ tag: string;
62
+ signature: string;
63
+ }
64
+ export function parseEnvelope(value: unknown): Envelope {
65
+ const envelope = object(value, "approval envelope");
66
+ if (
67
+ Object.keys(envelope).sort().join() !==
68
+ "binding,ciphertext,ephemeral,iv,salt,signature,tag"
69
+ )
70
+ throw new HostError("Invalid approval envelope encoding.");
71
+ const fields = object(envelope.binding, "approval binding");
72
+ if (
73
+ Object.keys(fields).sort().join() !==
74
+ "configUrl,encryptionKey,epoch,headId,member,owner,peerId,profileId,requestId,scopeId"
75
+ )
76
+ throw new HostError("Invalid approval binding.");
77
+ const text = (record: Record<string, unknown>, key: string): string => {
78
+ const field = record[key];
79
+ if (typeof field !== "string")
80
+ throw new HostError("Invalid approval field.");
81
+ return field;
82
+ };
83
+ const epoch = fields.epoch;
84
+ if (typeof epoch !== "number" || !Number.isSafeInteger(epoch) || epoch < 1)
85
+ throw new HostError("Invalid approval epoch.");
86
+ const binding: EnvelopeBinding = {
87
+ configUrl: text(fields, "configUrl"),
88
+ scopeId: text(fields, "scopeId"),
89
+ owner: text(fields, "owner"),
90
+ member: text(fields, "member"),
91
+ requestId: text(fields, "requestId"),
92
+ peerId: text(fields, "peerId"),
93
+ profileId: text(fields, "profileId"),
94
+ headId: text(fields, "headId"),
95
+ epoch,
96
+ encryptionKey: text(fields, "encryptionKey"),
97
+ };
98
+ const result: Envelope = {
99
+ binding,
100
+ ephemeral: text(envelope, "ephemeral"),
101
+ salt: text(envelope, "salt"),
102
+ iv: text(envelope, "iv"),
103
+ ciphertext: text(envelope, "ciphertext"),
104
+ tag: text(envelope, "tag"),
105
+ signature: text(envelope, "signature"),
106
+ };
107
+ if (
108
+ ![
109
+ result.ephemeral,
110
+ result.salt,
111
+ result.iv,
112
+ result.ciphertext,
113
+ result.tag,
114
+ result.signature,
115
+ ].every((field) => /^[A-Za-z0-9_-]+$/.test(field)) ||
116
+ result.salt.length !== 43 ||
117
+ result.iv.length !== 16 ||
118
+ result.tag.length !== 22 ||
119
+ result.signature.length !== 86 ||
120
+ result.ciphertext.length > 8192
121
+ )
122
+ throw new HostError("Invalid approval envelope encoding.");
123
+ return result;
124
+ }
125
+ const message = (e: Omit<Envelope, "signature">) =>
126
+ JSON.stringify([
127
+ "IPAB-APPROVAL/1",
128
+ e.binding,
129
+ e.ephemeral,
130
+ e.salt,
131
+ e.iv,
132
+ e.ciphertext,
133
+ e.tag,
134
+ ]);
135
+ function encryptionKey(
136
+ privateKey: string,
137
+ publicKey: string,
138
+ salt: Buffer,
139
+ binding: EnvelopeBinding,
140
+ ): Buffer {
141
+ const privateObject = createPrivateKey({
142
+ key: Buffer.from(privateKey, "base64url"),
143
+ type: "pkcs8",
144
+ format: "der",
145
+ });
146
+ const publicObject = createPublicKey({
147
+ key: Buffer.from(publicKey, "base64url"),
148
+ type: "spki",
149
+ format: "der",
150
+ });
151
+ if (
152
+ privateObject.asymmetricKeyType !== "x25519" ||
153
+ publicObject.asymmetricKeyType !== "x25519"
154
+ )
155
+ throw new HostError("Approval requires X25519 encryption keys.");
156
+ return Buffer.from(
157
+ hkdfSync(
158
+ "sha256",
159
+ diffieHellman({ privateKey: privateObject, publicKey: publicObject }),
160
+ salt,
161
+ Buffer.from(JSON.stringify(["IPAB-ENVELOPE/1", binding])),
162
+ 32,
163
+ ),
164
+ );
165
+ }
166
+ export async function sealApproval(
167
+ binding: EnvelopeBinding,
168
+ secret: MembershipSecret,
169
+ owner: Identity,
170
+ ): Promise<Envelope> {
171
+ const ephemeral = encryptionIdentity();
172
+ const salt = randomBytes(32),
173
+ iv = randomBytes(12);
174
+ const cipher = createCipheriv(
175
+ "aes-256-gcm",
176
+ encryptionKey(ephemeral.privateKey, binding.encryptionKey, salt, binding),
177
+ iv,
178
+ );
179
+ cipher.setAAD(Buffer.from(JSON.stringify(binding)));
180
+ const ciphertext = Buffer.concat([
181
+ cipher.update(JSON.stringify(secret), "utf8"),
182
+ cipher.final(),
183
+ ]);
184
+ const envelope = {
185
+ binding,
186
+ ephemeral: ephemeral.publicKey,
187
+ salt: salt.toString("base64url"),
188
+ iv: iv.toString("base64url"),
189
+ ciphertext: ciphertext.toString("base64url"),
190
+ tag: cipher.getAuthTag().toString("base64url"),
191
+ };
192
+ return {
193
+ ...envelope,
194
+ signature: await signEd25519(
195
+ await importPrivateKeyPkcs8(owner.privateKey),
196
+ message(envelope),
197
+ ),
198
+ };
199
+ }
200
+ export async function openApproval(
201
+ value: unknown,
202
+ expected: EnvelopeBinding,
203
+ identity: EncryptionIdentity,
204
+ ): Promise<MembershipSecret> {
205
+ const envelope = parseEnvelope(value);
206
+ if (
207
+ JSON.stringify(envelope.binding) !== JSON.stringify(expected) ||
208
+ expected.encryptionKey !== identity.publicKey ||
209
+ !(await verifyEd25519(
210
+ await importPublicKeyRaw(expected.owner),
211
+ envelope.signature,
212
+ message(envelope),
213
+ ))
214
+ )
215
+ throw new HostError(
216
+ "Approval signature or exact request/resource/identity binding is invalid.",
217
+ );
218
+ try {
219
+ const decipher = createDecipheriv(
220
+ "aes-256-gcm",
221
+ encryptionKey(
222
+ identity.privateKey,
223
+ envelope.ephemeral,
224
+ Buffer.from(envelope.salt, "base64url"),
225
+ expected,
226
+ ),
227
+ Buffer.from(envelope.iv, "base64url"),
228
+ );
229
+ decipher.setAAD(Buffer.from(JSON.stringify(expected)));
230
+ decipher.setAuthTag(Buffer.from(envelope.tag, "base64url"));
231
+ const secret = object(
232
+ JSON.parse(
233
+ Buffer.concat([
234
+ decipher.update(Buffer.from(envelope.ciphertext, "base64url")),
235
+ decipher.final(),
236
+ ]).toString("utf8"),
237
+ ) as unknown,
238
+ "membership secret",
239
+ );
240
+ if (
241
+ Object.keys(secret).sort().join() !== "certificate,swarmKey" ||
242
+ typeof secret.swarmKey !== "string" ||
243
+ !/^[a-f0-9]{64}$/.test(secret.swarmKey)
244
+ )
245
+ throw new HostError("Invalid membership secret.");
246
+ return {
247
+ certificate: parseScopeCertificate(secret.certificate),
248
+ swarmKey: secret.swarmKey,
249
+ };
250
+ } catch {
251
+ throw new HostError(
252
+ "Could not decrypt the approved package; preserve the original local Request identity.",
253
+ );
254
+ }
255
+ }
@@ -0,0 +1,100 @@
1
+ import { lstat, mkdir, open, readFile, rename, unlink } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { DatabaseSync } from "node:sqlite";
5
+ import { protectedPath, secureNew } from "./identity.js";
6
+ import { nodeError } from "./authoring.js";
7
+ import { HostError } from "./errors.js";
8
+
9
+ export async function privateDirectory(
10
+ parent: string,
11
+ name: string,
12
+ ): Promise<string> {
13
+ const path = join(parent, name);
14
+ try {
15
+ await lstat(path);
16
+ } catch (cause) {
17
+ if (!nodeError(cause, "ENOENT")) throw cause;
18
+ await mkdir(path, { mode: 0o700 });
19
+ await secureNew(path, true);
20
+ }
21
+ await protectedPath(path, true);
22
+ return path;
23
+ }
24
+ export async function readPrivate<T>(
25
+ directory: string,
26
+ name: string,
27
+ ): Promise<T | undefined> {
28
+ const path = join(directory, name);
29
+ try {
30
+ await protectedPath(path);
31
+ } catch (cause) {
32
+ if (nodeError(cause, "ENOENT")) return undefined;
33
+ throw cause;
34
+ }
35
+ if ((await lstat(path)).size > 2 * 1024 * 1024)
36
+ throw new HostError("Protected state is oversized.");
37
+ return JSON.parse(await readFile(path, "utf8")) as T;
38
+ }
39
+ export async function writePrivate(
40
+ directory: string,
41
+ name: string,
42
+ value: unknown,
43
+ ): Promise<void> {
44
+ const target = join(directory, name);
45
+ const temporary = join(directory, `.write-${randomUUID()}`);
46
+ const file = await open(temporary, "wx", 0o600);
47
+ try {
48
+ await secureNew(temporary);
49
+ await file.writeFile(JSON.stringify(value));
50
+ await file.sync();
51
+ await file.close();
52
+ await rename(temporary, target);
53
+ } finally {
54
+ await file.close();
55
+ await unlink(temporary).catch((cause: unknown) => {
56
+ if (!nodeError(cause, "ENOENT")) throw cause;
57
+ });
58
+ }
59
+ }
60
+ export async function withPrivateLock<T>(
61
+ directory: string,
62
+ operation: () => Promise<T>,
63
+ ): Promise<T> {
64
+ const path = join(directory, "operation.sqlite");
65
+ try {
66
+ const handle = await open(path, "wx", 0o600);
67
+ await handle.close();
68
+ await secureNew(path);
69
+ } catch (cause) {
70
+ if (!nodeError(cause, "EEXIST")) throw cause;
71
+ }
72
+ await protectedPath(path);
73
+ const db = new DatabaseSync(path);
74
+ let locked = false;
75
+ try {
76
+ db.exec("PRAGMA busy_timeout=0");
77
+ for (let attempt = 0; attempt < 300; attempt++) {
78
+ try {
79
+ db.exec("BEGIN IMMEDIATE");
80
+ locked = true;
81
+ break;
82
+ } catch (cause) {
83
+ if (
84
+ !(cause instanceof Error) ||
85
+ !cause.message.includes("database is locked")
86
+ )
87
+ throw cause;
88
+ await new Promise((resolve) => setTimeout(resolve, 100));
89
+ }
90
+ }
91
+ if (!locked)
92
+ throw new HostError(
93
+ "Another local Swarm operation is still running; retry later.",
94
+ );
95
+ return await operation();
96
+ } finally {
97
+ if (locked) db.exec("ROLLBACK");
98
+ db.close();
99
+ }
100
+ }