@ipab/cli 0.1.0-rc.5 → 0.1.0-rc.7

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 (157) hide show
  1. package/README.md +128 -22
  2. package/dist/app-authoring.d.ts +5 -0
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +4 -1
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-templates.d.ts +0 -1
  7. package/dist/app-templates.d.ts.map +1 -1
  8. package/dist/app-templates.js +6 -45
  9. package/dist/app-templates.js.map +1 -1
  10. package/dist/builtins/skill.ipab.car +0 -0
  11. package/dist/builtins/template.bundle-viewer.car +0 -0
  12. package/dist/builtins/template.check.car +0 -0
  13. package/dist/builtins/template.node.car +0 -0
  14. package/dist/builtins/template.web-app.car +0 -0
  15. package/dist/builtins.d.ts.map +1 -1
  16. package/dist/builtins.js +1 -39
  17. package/dist/builtins.js.map +1 -1
  18. package/dist/cli.d.ts +4 -1
  19. package/dist/cli.d.ts.map +1 -1
  20. package/dist/cli.js +934 -336
  21. package/dist/cli.js.map +1 -1
  22. package/dist/content-provider.d.ts +1 -1
  23. package/dist/content-provider.d.ts.map +1 -1
  24. package/dist/content-provider.js +4 -3
  25. package/dist/content-provider.js.map +1 -1
  26. package/dist/context.d.ts +16 -1
  27. package/dist/context.d.ts.map +1 -1
  28. package/dist/context.js +20 -10
  29. package/dist/context.js.map +1 -1
  30. package/dist/doctor.d.ts +29 -0
  31. package/dist/doctor.d.ts.map +1 -0
  32. package/dist/doctor.js +576 -0
  33. package/dist/doctor.js.map +1 -0
  34. package/dist/identity.d.ts +1 -1
  35. package/dist/identity.d.ts.map +1 -1
  36. package/dist/identity.js +9 -9
  37. package/dist/identity.js.map +1 -1
  38. package/dist/ipc.d.ts +2 -2
  39. package/dist/ipc.d.ts.map +1 -1
  40. package/dist/ipc.js +44 -12
  41. package/dist/ipc.js.map +1 -1
  42. package/dist/kubo-install.d.ts +18 -1
  43. package/dist/kubo-install.d.ts.map +1 -1
  44. package/dist/kubo-install.js +424 -61
  45. package/dist/kubo-install.js.map +1 -1
  46. package/dist/kubo-release.d.ts +19 -0
  47. package/dist/kubo-release.d.ts.map +1 -1
  48. package/dist/kubo-release.js +164 -0
  49. package/dist/kubo-release.js.map +1 -1
  50. package/dist/kubo.d.ts +1 -0
  51. package/dist/kubo.d.ts.map +1 -1
  52. package/dist/kubo.js +102 -96
  53. package/dist/kubo.js.map +1 -1
  54. package/dist/pins.d.ts +15 -17
  55. package/dist/pins.d.ts.map +1 -1
  56. package/dist/pins.js +144 -106
  57. package/dist/pins.js.map +1 -1
  58. package/dist/publish-source.d.ts +3 -0
  59. package/dist/publish-source.d.ts.map +1 -0
  60. package/dist/publish-source.js +85 -0
  61. package/dist/publish-source.js.map +1 -0
  62. package/dist/runtime.d.ts.map +1 -1
  63. package/dist/runtime.js +6 -5
  64. package/dist/runtime.js.map +1 -1
  65. package/dist/skill-definition.d.ts +6 -0
  66. package/dist/skill-definition.d.ts.map +1 -0
  67. package/dist/skill-definition.js +38 -0
  68. package/dist/skill-definition.js.map +1 -0
  69. package/dist/skill-source.d.ts +5 -0
  70. package/dist/skill-source.d.ts.map +1 -0
  71. package/dist/skill-source.js +12 -0
  72. package/dist/skill-source.js.map +1 -0
  73. package/dist/skills.d.ts +84 -0
  74. package/dist/skills.d.ts.map +1 -0
  75. package/dist/skills.js +736 -0
  76. package/dist/skills.js.map +1 -0
  77. package/dist/space.d.ts +15 -2
  78. package/dist/space.d.ts.map +1 -1
  79. package/dist/space.js +153 -3
  80. package/dist/space.js.map +1 -1
  81. package/dist/state-storage-windows.js +1 -1
  82. package/dist/state-storage.d.ts +3 -1
  83. package/dist/state-storage.d.ts.map +1 -1
  84. package/dist/state-storage.js +38 -7
  85. package/dist/state-storage.js.map +1 -1
  86. package/dist/state.d.ts +40 -6
  87. package/dist/state.d.ts.map +1 -1
  88. package/dist/state.js +208 -82
  89. package/dist/state.js.map +1 -1
  90. package/dist/swarm-envelope.d.ts +1 -0
  91. package/dist/swarm-envelope.d.ts.map +1 -1
  92. package/dist/swarm-envelope.js +12 -0
  93. package/dist/swarm-envelope.js.map +1 -1
  94. package/dist/swarm-files.d.ts +1 -1
  95. package/dist/swarm-files.d.ts.map +1 -1
  96. package/dist/swarm-files.js +2 -2
  97. package/dist/swarm-files.js.map +1 -1
  98. package/dist/swarm-meta.d.ts +17 -0
  99. package/dist/swarm-meta.d.ts.map +1 -0
  100. package/dist/swarm-meta.js +96 -0
  101. package/dist/swarm-meta.js.map +1 -0
  102. package/dist/swarm.d.ts +117 -8
  103. package/dist/swarm.d.ts.map +1 -1
  104. package/dist/swarm.js +1275 -131
  105. package/dist/swarm.js.map +1 -1
  106. package/dist/template-paths.d.ts +7 -0
  107. package/dist/template-paths.d.ts.map +1 -0
  108. package/dist/template-paths.js +23 -0
  109. package/dist/template-paths.js.map +1 -0
  110. package/dist/template-presentation.d.ts +20 -0
  111. package/dist/template-presentation.d.ts.map +1 -0
  112. package/dist/template-presentation.js +133 -0
  113. package/dist/template-presentation.js.map +1 -0
  114. package/dist/template-source.d.ts +2 -1
  115. package/dist/template-source.d.ts.map +1 -1
  116. package/dist/template-source.js +7 -1
  117. package/dist/template-source.js.map +1 -1
  118. package/dist/templates.d.ts +11 -0
  119. package/dist/templates.d.ts.map +1 -0
  120. package/dist/templates.js +53 -0
  121. package/dist/templates.js.map +1 -0
  122. package/package.json +7 -6
  123. package/src/app-authoring.ts +18 -2
  124. package/src/app-templates.ts +8 -72
  125. package/src/builtins.ts +2 -48
  126. package/src/cli.ts +1154 -387
  127. package/src/content-provider.ts +4 -2
  128. package/src/context.ts +45 -10
  129. package/src/doctor.ts +902 -0
  130. package/src/identity.ts +10 -10
  131. package/src/ipc.ts +63 -10
  132. package/src/kubo-install.ts +562 -78
  133. package/src/kubo-release.ts +213 -0
  134. package/src/kubo.ts +134 -106
  135. package/src/pins.ts +188 -126
  136. package/src/publish-source.ts +103 -0
  137. package/src/runtime.ts +6 -5
  138. package/src/skill-definition.ts +53 -0
  139. package/src/skill-source.ts +15 -0
  140. package/src/skills.ts +1005 -0
  141. package/src/space.ts +214 -5
  142. package/src/state-storage-windows.ts +1 -1
  143. package/src/state-storage.ts +53 -7
  144. package/src/state.ts +357 -98
  145. package/src/swarm-envelope.ts +14 -0
  146. package/src/swarm-files.ts +2 -1
  147. package/src/swarm-meta.ts +109 -0
  148. package/src/swarm.ts +1877 -175
  149. package/src/template-paths.ts +43 -0
  150. package/src/template-presentation.ts +151 -0
  151. package/src/template-source.ts +9 -2
  152. package/src/templates.ts +77 -0
  153. package/dist/setup.d.ts +0 -8
  154. package/dist/setup.d.ts.map +0 -1
  155. package/dist/setup.js +0 -27
  156. package/dist/setup.js.map +0 -1
  157. package/src/setup.ts +0 -34
package/src/state.ts CHANGED
@@ -11,19 +11,43 @@ import {
11
11
  type ConfigValue,
12
12
  } from "./config.js";
13
13
  import { HostError, object, syntax } from "./errors.js";
14
- import { secureConfigurationStorage } from "./config-secret.js";
15
- import { prepareStateStorage } from "./state-storage.js";
14
+ import { openStateStorage } from "./state-storage.js";
16
15
 
17
16
  export interface Association {
18
17
  schemaCid: string;
19
18
  appCid: string;
20
19
  argv: string[];
21
20
  }
21
+ export function createAssociation(
22
+ schemaCid: string,
23
+ appCid: string,
24
+ argv: string[],
25
+ ): Association {
26
+ if (!argv.length || !argv.includes("%"))
27
+ syntax('Argument template must contain a whole "%" argument.');
28
+ return {
29
+ schemaCid: exactCid(schemaCid, true),
30
+ appCid: exactCid(appCid),
31
+ argv: [...argv],
32
+ };
33
+ }
22
34
  export interface RegisteredSwarm {
23
35
  // Keep the storage column name, but values are configuration URLs; old CID rows are rejected.
24
36
  cid: string;
25
37
  alias: string | null;
26
38
  }
39
+ export interface SwarmProjection {
40
+ account: string;
41
+ swarm: string;
42
+ stateCid: string;
43
+ root: string;
44
+ valueCid: string;
45
+ verifiedAt: number;
46
+ headId: string;
47
+ epoch: number;
48
+ membership: string;
49
+ }
50
+ const projectionVersion = 2;
27
51
  export function swarmAlias(value: string): void {
28
52
  pinName(value);
29
53
  }
@@ -65,15 +89,24 @@ export interface NamedPin {
65
89
  metadata: PinMetadata | null;
66
90
  builtin?: true;
67
91
  }
92
+ export interface ContentPin {
93
+ reference: string;
94
+ owner: string;
95
+ cid: string | null;
96
+ targetCid: string | null;
97
+ swarm: string | null;
98
+ name: string | null;
99
+ status: "pending" | "ready" | "deleting";
100
+ freshness: "current" | "stale" | "missing";
101
+ error: string | null;
102
+ }
68
103
  export function bundlePinMetadata(pin: NamedPin) {
69
104
  if (pin.status !== "ready" || !pin.metadata)
70
105
  throw new HostError(
71
- `Pin "${pin.name}" is ${pin.status}; retry pin add/delete before using it.`,
106
+ `Packaged reference "${pin.name}" is ${pin.status}; reinstall a verified CLI package before using it.`,
72
107
  );
73
108
  if (pin.metadata.kind !== "bundle")
74
- throw new HostError(
75
- `Pin "${pin.name}" is not a Bundle pin. Its retention is preserved; run ipab pin delete ${pin.name}, then wrap the content in a Bundle before adding a new pin.`,
76
- );
109
+ throw new HostError(`Packaged reference "${pin.name}" is not a Bundle.`);
77
110
  return pin.metadata;
78
111
  }
79
112
 
@@ -166,29 +199,94 @@ export class State {
166
199
  readonly db: DatabaseSync;
167
200
  readonly identity: string;
168
201
  readonly directory: string;
202
+ readonly legacyRegistrationCount: number;
203
+ readonly legacyPinCount: number;
169
204
  constructor(
170
205
  directory: string,
171
206
  private readonly builtins: readonly NamedPin[] = [],
172
207
  env: NodeJS.ProcessEnv = process.env,
173
208
  ) {
174
209
  this.directory = resolve(directory);
175
- this.db = new DatabaseSync(prepareStateStorage(this.directory, env));
210
+ this.db = new DatabaseSync(openStateStorage(this.directory, env));
176
211
  try {
177
212
  enableWal(this.db);
178
213
  this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA synchronous=FULL;
179
214
  CREATE TABLE IF NOT EXISTS identity (id TEXT NOT NULL);
180
215
  CREATE TABLE IF NOT EXISTS config (key TEXT PRIMARY KEY, value TEXT NOT NULL);
181
216
  DROP TABLE IF EXISTS aliases;
182
- CREATE TABLE IF NOT EXISTS named_pins (name TEXT PRIMARY KEY, owner TEXT UNIQUE NOT NULL, value TEXT NOT NULL);
183
- CREATE TABLE IF NOT EXISTS registrations (schema_cid TEXT PRIMARY KEY, value TEXT NOT NULL);
217
+ CREATE TABLE IF NOT EXISTS content_pins (reference TEXT PRIMARY KEY, owner TEXT UNIQUE NOT NULL, value TEXT NOT NULL);
184
218
  CREATE TABLE IF NOT EXISTS swarms (cid TEXT PRIMARY KEY, alias TEXT UNIQUE);
185
219
  CREATE TABLE IF NOT EXISTS swarm_headers (account TEXT NOT NULL, swarm TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (account,swarm));
220
+ CREATE TABLE IF NOT EXISTS swarm_projection_checkpoints (account TEXT NOT NULL, swarm TEXT NOT NULL, version INTEGER NOT NULL, state_cid TEXT NOT NULL, binding TEXT NOT NULL, PRIMARY KEY (account,swarm));
221
+ CREATE TABLE IF NOT EXISTS swarm_projection_names (account TEXT NOT NULL, swarm TEXT NOT NULL, version INTEGER NOT NULL, name TEXT NOT NULL, normalized TEXT NOT NULL, target_cid TEXT NOT NULL, PRIMARY KEY (account,swarm,name));
222
+ CREATE TABLE IF NOT EXISTS swarm_projection_registrations (account TEXT NOT NULL, swarm TEXT NOT NULL, version INTEGER NOT NULL, schema_cid TEXT NOT NULL, app_cid TEXT NOT NULL, argv TEXT NOT NULL, PRIMARY KEY (account,swarm,schema_cid));
186
223
  CREATE TABLE IF NOT EXISTS runs (id TEXT PRIMARY KEY, value TEXT NOT NULL);
187
224
  CREATE TABLE IF NOT EXISTS holds (owner TEXT PRIMARY KEY, value TEXT NOT NULL);`);
188
225
  this.transaction(() => {
226
+ if (
227
+ this.db
228
+ .prepare(
229
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='named_pins'",
230
+ )
231
+ .get()
232
+ ) {
233
+ if (
234
+ this.db
235
+ .prepare(
236
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='legacy_named_pins'",
237
+ )
238
+ .get()
239
+ )
240
+ throw new HostError(
241
+ "Both named_pins and legacy_named_pins exist; preserve both and resolve the archive conflict before retrying.",
242
+ );
243
+ this.db.exec("ALTER TABLE named_pins RENAME TO legacy_named_pins");
244
+ }
245
+ this.db.exec(
246
+ "CREATE TABLE IF NOT EXISTS legacy_named_pins (name TEXT PRIMARY KEY, owner TEXT UNIQUE NOT NULL, value TEXT NOT NULL)",
247
+ );
248
+ if (
249
+ this.db
250
+ .prepare(
251
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='registrations'",
252
+ )
253
+ .get()
254
+ ) {
255
+ if (
256
+ this.db
257
+ .prepare(
258
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='legacy_user_registrations'",
259
+ )
260
+ .get()
261
+ )
262
+ throw new HostError(
263
+ "Both registrations and legacy_user_registrations exist in the state database. Preserve both tables and resolve the archive conflict before retrying; no User registrations were uploaded or deleted.",
264
+ );
265
+ this.db.exec(
266
+ "ALTER TABLE registrations RENAME TO legacy_user_registrations",
267
+ );
268
+ }
189
269
  if (!this.db.prepare("SELECT id FROM identity").get())
190
270
  this.db.prepare("INSERT INTO identity VALUES (?)").run(randomUUID());
191
271
  });
272
+ this.legacyPinCount = Number(
273
+ this.db
274
+ .prepare("SELECT COUNT(*) AS count FROM legacy_named_pins")
275
+ .get()!.count,
276
+ );
277
+ this.legacyRegistrationCount = this.db
278
+ .prepare(
279
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='legacy_user_registrations'",
280
+ )
281
+ .get()
282
+ ? Number(
283
+ this.db
284
+ .prepare(
285
+ "SELECT COUNT(*) AS count FROM legacy_user_registrations",
286
+ )
287
+ .get()!.count,
288
+ )
289
+ : 0;
192
290
  this.identity = String(
193
291
  this.db.prepare("SELECT id FROM identity").get()!.id,
194
292
  );
@@ -217,20 +315,10 @@ export class State {
217
315
  const entries = this.db
218
316
  .prepare(
219
317
  includeSecrets
220
- ? "SELECT key, CASE WHEN key='pointers.apiKey' AND value!='null' THEN NULL ELSE value END AS value FROM config"
318
+ ? "SELECT key,value FROM config"
221
319
  : "SELECT key,value FROM config WHERE key != 'pointers.apiKey'",
222
320
  )
223
321
  .all();
224
- const secret = entries.find(
225
- (row) => row.key === "pointers.apiKey" && row.value === null,
226
- );
227
- if (secret) {
228
- secureConfigurationStorage(this.directory);
229
- secret.value =
230
- this.db
231
- .prepare("SELECT value FROM config WHERE key='pointers.apiKey'")
232
- .get()?.value ?? "null";
233
- }
234
322
  if (entries.some((row) => row.key === "store.rpc"))
235
323
  throw new HostError(
236
324
  "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.",
@@ -251,8 +339,6 @@ export class State {
251
339
  }
252
340
  }
253
341
  setConfig(key: ConfigKey, value: ConfigValue): void {
254
- if (key === "pointers.apiKey" && value !== null)
255
- secureConfigurationStorage(this.directory);
256
342
  this.db
257
343
  .prepare("INSERT OR REPLACE INTO config VALUES (?,?)")
258
344
  .run(key, JSON.stringify(value));
@@ -326,6 +412,7 @@ export class State {
326
412
  return this.transaction(() => {
327
413
  const entry = this.registeredSwarm(reference);
328
414
  this.db.prepare("DELETE FROM swarms WHERE cid=?").run(entry.cid);
415
+ this.deleteSwarmCache(entry.cid);
329
416
  if (this.config({ includeSecrets: false })["swarm.default"] === entry.cid)
330
417
  this.resetConfig("swarm.default");
331
418
  return entry.cid;
@@ -348,7 +435,185 @@ export class State {
348
435
  .run(account, swarm, JSON.stringify(value));
349
436
  }
350
437
  invalidateSwarmHeader(swarm: string): void {
438
+ this.transaction(() => {
439
+ this.deleteSwarmCache(swarm);
440
+ });
441
+ }
442
+ private deleteSwarmCache(swarm: string): void {
351
443
  this.db.prepare("DELETE FROM swarm_headers WHERE swarm=?").run(swarm);
444
+ for (const table of [
445
+ "swarm_projection_checkpoints",
446
+ "swarm_projection_names",
447
+ "swarm_projection_registrations",
448
+ ])
449
+ this.db.prepare(`DELETE FROM ${table} WHERE swarm=?`).run(swarm);
450
+ }
451
+ private checkProjectionHeader(binding: SwarmProjection): void {
452
+ const cached = this.swarmHeader(binding.account, binding.swarm) as
453
+ | {
454
+ head: { root: string; cid: string };
455
+ stateCid?: string;
456
+ verifiedAt: number;
457
+ headId: string;
458
+ epoch?: number;
459
+ }
460
+ | undefined;
461
+ if (
462
+ !cached ||
463
+ cached.head.root !== binding.root ||
464
+ cached.head.cid !== binding.valueCid ||
465
+ cached.verifiedAt !== binding.verifiedAt ||
466
+ cached.headId !== binding.headId ||
467
+ (cached.epoch !== undefined && cached.epoch !== binding.epoch) ||
468
+ (cached.stateCid !== undefined && cached.stateCid !== binding.stateCid)
469
+ )
470
+ throw new HostError("Swarm header changed; retry the verified read.");
471
+ }
472
+ projectSwarm(
473
+ binding: SwarmProjection,
474
+ names: Readonly<Record<string, CID>>,
475
+ registrations: () => readonly Association[],
476
+ ): void {
477
+ this.transaction(() => {
478
+ this.checkProjectionHeader(binding);
479
+ const cached = this.swarmHeader(binding.account, binding.swarm) as Record<
480
+ string,
481
+ unknown
482
+ >;
483
+ if (cached.stateCid === undefined)
484
+ this.saveSwarmHeader(binding.account, binding.swarm, {
485
+ ...cached,
486
+ stateCid: binding.stateCid,
487
+ });
488
+ const old = this.db
489
+ .prepare(
490
+ "SELECT version,state_cid,binding FROM swarm_projection_checkpoints WHERE account=? AND swarm=?",
491
+ )
492
+ .get(binding.account, binding.swarm);
493
+ const encoded = JSON.stringify(binding);
494
+ if (old?.version === projectionVersion && old.binding === encoded) return;
495
+ // A new Publication may reference the same State: only provenance changes.
496
+ if (
497
+ old?.version !== projectionVersion ||
498
+ old.state_cid !== binding.stateCid
499
+ ) {
500
+ for (const table of [
501
+ "swarm_projection_names",
502
+ "swarm_projection_registrations",
503
+ ])
504
+ this.db
505
+ .prepare(`DELETE FROM ${table} WHERE account=? AND swarm=?`)
506
+ .run(binding.account, binding.swarm);
507
+ const insertName = this.db.prepare(
508
+ "INSERT INTO swarm_projection_names VALUES (?,?,?,?,?,?)",
509
+ );
510
+ for (const [name, target] of Object.entries(names))
511
+ insertName.run(
512
+ binding.account,
513
+ binding.swarm,
514
+ projectionVersion,
515
+ name,
516
+ name.toLowerCase(),
517
+ target.toString(),
518
+ );
519
+ const insertRegistration = this.db.prepare(
520
+ "INSERT INTO swarm_projection_registrations VALUES (?,?,?,?,?,?)",
521
+ );
522
+ for (const item of registrations())
523
+ insertRegistration.run(
524
+ binding.account,
525
+ binding.swarm,
526
+ projectionVersion,
527
+ item.schemaCid,
528
+ item.appCid,
529
+ JSON.stringify(item.argv),
530
+ );
531
+ }
532
+ this.db
533
+ .prepare(
534
+ "INSERT OR REPLACE INTO swarm_projection_checkpoints VALUES (?,?,?,?,?)",
535
+ )
536
+ .run(
537
+ binding.account,
538
+ binding.swarm,
539
+ projectionVersion,
540
+ binding.stateCid,
541
+ encoded,
542
+ );
543
+ });
544
+ }
545
+ private checkProjection(binding: SwarmProjection): void {
546
+ this.checkProjectionHeader(binding);
547
+ if (
548
+ !this.db
549
+ .prepare(
550
+ "SELECT 1 FROM swarm_projection_checkpoints WHERE account=? AND swarm=? AND version=? AND binding=?",
551
+ )
552
+ .get(
553
+ binding.account,
554
+ binding.swarm,
555
+ projectionVersion,
556
+ JSON.stringify(binding),
557
+ )
558
+ )
559
+ throw new HostError("Swarm projection changed; retry the verified read.");
560
+ }
561
+ searchSwarmNames(
562
+ binding: SwarmProjection,
563
+ query: string,
564
+ ): { name: string; targetCid: string }[] {
565
+ return this.transaction(() => {
566
+ this.checkProjection(binding);
567
+ return this.db
568
+ .prepare(
569
+ "SELECT name,target_cid FROM swarm_projection_names WHERE account=? AND swarm=? AND version=? AND instr(normalized,?)>0",
570
+ )
571
+ .all(
572
+ binding.account,
573
+ binding.swarm,
574
+ projectionVersion,
575
+ query.toLowerCase(),
576
+ )
577
+ .map((row) => ({
578
+ name: String(row.name),
579
+ targetCid: String(row.target_cid),
580
+ }))
581
+ .sort((left, right) =>
582
+ left.name < right.name ? -1 : left.name > right.name ? 1 : 0,
583
+ );
584
+ });
585
+ }
586
+ projectedSwarmRegistrations(
587
+ binding: SwarmProjection,
588
+ schemaCid?: string,
589
+ ): Association[] {
590
+ return this.transaction(() => {
591
+ this.checkProjection(binding);
592
+ const rows =
593
+ schemaCid === undefined
594
+ ? this.db
595
+ .prepare(
596
+ "SELECT schema_cid,app_cid,argv FROM swarm_projection_registrations WHERE account=? AND swarm=? AND version=?",
597
+ )
598
+ .all(binding.account, binding.swarm, projectionVersion)
599
+ : this.db
600
+ .prepare(
601
+ "SELECT schema_cid,app_cid,argv FROM swarm_projection_registrations WHERE account=? AND swarm=? AND version=? AND schema_cid=?",
602
+ )
603
+ .all(
604
+ binding.account,
605
+ binding.swarm,
606
+ projectionVersion,
607
+ schemaCid,
608
+ );
609
+ return rows
610
+ .map((row) => ({
611
+ schemaCid: String(row.schema_cid),
612
+ appCid: String(row.app_cid),
613
+ argv: JSON.parse(String(row.argv)) as string[],
614
+ }))
615
+ .sort((left, right) => left.schemaCid.localeCompare(right.schemaCid));
616
+ });
352
617
  }
353
618
  resolve(value: string, schema = false): string {
354
619
  try {
@@ -357,43 +622,26 @@ export class State {
357
622
  try {
358
623
  CID.parse(value);
359
624
  } catch {
360
- const pin = this.pin(value);
625
+ const pin = value.startsWith("builtin:") ? this.pin(value) : undefined;
361
626
  if (pin) {
362
627
  const metadata = bundlePinMetadata(pin);
363
628
  if (schema) return metadata.schemaCid;
364
629
  return exactCid(pin.cid, schema);
365
630
  }
366
631
  throw new HostError(
367
- `Unknown CID or pin "${value}". Run ipab pin list.`,
632
+ `Unknown CID or packaged builtin reference "${value}". Local content aliases are unsupported; use an exact CID or a Swarm IPAB URI.`,
368
633
  );
369
634
  }
370
635
  throw error;
371
636
  }
372
637
  }
373
- resolvePin(name: string): string | undefined {
374
- const pin = this.pin(name);
375
- if (!pin) return undefined;
376
- bundlePinMetadata(pin);
377
- return exactCid(pin.cid);
378
- }
379
638
  pins(): NamedPin[] {
380
- const user = this.db
381
- .prepare("SELECT name,owner,value FROM named_pins ORDER BY name")
382
- .all()
383
- .map((row) =>
384
- this.readPin(String(row.name), String(row.owner), String(row.value)),
385
- );
386
- return [...user, ...this.builtins];
639
+ return [...this.builtins];
387
640
  }
388
641
  pin(name: string): NamedPin | undefined {
389
642
  const builtin = this.builtins.find((pin) => pin.name === name);
390
643
  if (builtin) return builtin;
391
- const row = this.db
392
- .prepare("SELECT owner,value FROM named_pins WHERE name=?")
393
- .get(name);
394
- return row
395
- ? this.readPin(name, String(row.owner), String(row.value))
396
- : undefined;
644
+ return undefined;
397
645
  }
398
646
  private readPin(name: string, owner: string, value: string): NamedPin {
399
647
  const data = object(JSON.parse(value) as unknown, "named pin");
@@ -438,73 +686,84 @@ export class State {
438
686
  metadata,
439
687
  };
440
688
  }
441
- savePin(pin: NamedPin): void {
442
- pinName(pin.name);
689
+ archivedPins(): NamedPin[] {
690
+ return this.db
691
+ .prepare("SELECT name,owner,value FROM legacy_named_pins ORDER BY name")
692
+ .all()
693
+ .map((row) =>
694
+ this.readPin(String(row.name), String(row.owner), String(row.value)),
695
+ );
696
+ }
697
+ contentPins(): ContentPin[] {
698
+ return this.db
699
+ .prepare(
700
+ "SELECT reference,owner,value FROM content_pins ORDER BY reference",
701
+ )
702
+ .all()
703
+ .map((row) => {
704
+ const pin = JSON.parse(String(row.value)) as ContentPin;
705
+ if (
706
+ pin.reference !== row.reference ||
707
+ pin.owner !== row.owner ||
708
+ !["pending", "ready", "deleting"].includes(pin.status) ||
709
+ !["current", "stale", "missing"].includes(pin.freshness) ||
710
+ (pin.error !== null && typeof pin.error !== "string") ||
711
+ (pin.cid !== null && typeof pin.cid !== "string") ||
712
+ (pin.targetCid !== null && typeof pin.targetCid !== "string") ||
713
+ (pin.swarm !== null && typeof pin.swarm !== "string") ||
714
+ (pin.name !== null && typeof pin.name !== "string")
715
+ )
716
+ throw new HostError(
717
+ "Invalid persisted content pin; recovery is blocked.",
718
+ );
719
+ if (pin.cid) exactCid(pin.cid);
720
+ if (pin.targetCid) exactCid(pin.targetCid);
721
+ if (pin.swarm) swarmUrl(pin.swarm);
722
+ if (
723
+ (pin.swarm === null) !== (pin.name === null) ||
724
+ (pin.swarm === null &&
725
+ (exactCid(pin.reference) !== pin.reference ||
726
+ (pin.cid !== null && pin.cid !== pin.reference))) ||
727
+ (pin.swarm !== null &&
728
+ (!pin.name || !pin.reference.startsWith("ipab://"))) ||
729
+ (pin.status === "ready" && (!pin.cid || !pin.targetCid))
730
+ )
731
+ throw new HostError(
732
+ "Invalid persisted pin reference/version binding; recovery is blocked.",
733
+ );
734
+ return pin;
735
+ });
736
+ }
737
+ contentPin(reference: string): ContentPin | undefined {
738
+ return this.contentPins().find((pin) => pin.reference === reference);
739
+ }
740
+ saveContentPin(pin: ContentPin): void {
443
741
  if (
444
742
  !this.db
445
743
  .prepare(
446
- "INSERT INTO named_pins VALUES (?,?,?) ON CONFLICT(name) DO UPDATE SET value=excluded.value WHERE owner=excluded.owner",
744
+ "INSERT INTO content_pins VALUES (?,?,?) ON CONFLICT(reference) DO UPDATE SET value=excluded.value WHERE owner=excluded.owner",
447
745
  )
448
- .run(pin.name, pin.owner, JSON.stringify(pin)).changes
746
+ .run(pin.reference, pin.owner, JSON.stringify(pin)).changes
449
747
  )
450
- throw new HostError(`Pin name "${pin.name}" is occupied.`);
748
+ throw new HostError("Content pin reference is occupied.");
749
+ }
750
+ deleteContentPin(reference: string): void {
751
+ this.db
752
+ .prepare("DELETE FROM content_pins WHERE reference=?")
753
+ .run(reference);
451
754
  }
452
755
  isPinOwner(owner: string): boolean {
453
756
  return Boolean(
454
- this.db.prepare("SELECT 1 FROM named_pins WHERE owner=?").get(owner),
757
+ this.db
758
+ .prepare(
759
+ "SELECT 1 FROM content_pins WHERE owner=? UNION ALL SELECT 1 FROM legacy_named_pins WHERE owner=?",
760
+ )
761
+ .get(owner, owner),
455
762
  );
456
763
  }
457
764
  deletePin(name: string): void {
458
765
  pinName(name);
459
- this.db.prepare("DELETE FROM named_pins WHERE name=?").run(name);
460
- }
461
- registrations(): Association[] {
462
- return this.db
463
- .prepare("SELECT value FROM registrations ORDER BY schema_cid")
464
- .all()
465
- .map((row) => JSON.parse(String(row.value)) as Association);
466
- }
467
- association(schemaCid: string): Association | undefined {
468
- const row = this.db
469
- .prepare("SELECT value FROM registrations WHERE schema_cid=?")
470
- .get(schemaCid);
471
- return row ? (JSON.parse(String(row.value)) as Association) : undefined;
472
- }
473
- setAssociation(
474
- schema: string,
475
- app: string,
476
- argv: string[],
477
- replace: boolean,
478
- ): Association {
479
- const value: Association = {
480
- schemaCid: this.resolve(schema, true),
481
- appCid: this.resolve(app),
482
- argv,
483
- };
484
- if (!argv.length || !argv.includes("%"))
485
- syntax('Argument template must contain a whole "%" argument.');
486
- this.transaction(() => {
487
- const old = this.association(value.schemaCid);
488
- if (old && JSON.stringify(old) !== JSON.stringify(value) && !replace)
489
- throw new HostError(
490
- "Schema has another association; use --replace before --.",
491
- );
492
- this.db
493
- .prepare("INSERT OR REPLACE INTO registrations VALUES (?,?)")
494
- .run(value.schemaCid, JSON.stringify(value));
495
- });
496
- return value;
497
- }
498
- removeAssociation(schema: string): string {
499
- const cid = this.resolve(schema, true);
500
- if (
501
- !this.db.prepare("DELETE FROM registrations WHERE schema_cid=?").run(cid)
502
- .changes
503
- )
504
- throw new HostError(
505
- "No association exists for this Schema. Run ipab register list.",
506
- );
507
- return cid;
766
+ this.db.prepare("DELETE FROM legacy_named_pins WHERE name=?").run(name);
508
767
  }
509
768
  runs(): RunRecord[] {
510
769
  return this.db
@@ -25,6 +25,20 @@ export interface EncryptionIdentity {
25
25
  publicKey: string;
26
26
  privateKey: string;
27
27
  }
28
+ export function validateEncryptionIdentity(value: EncryptionIdentity): void {
29
+ const privateKey = createPrivateKey({
30
+ key: Buffer.from(value.privateKey, "base64url"),
31
+ type: "pkcs8",
32
+ format: "der",
33
+ });
34
+ if (
35
+ privateKey.asymmetricKeyType !== "x25519" ||
36
+ createPublicKey(privateKey)
37
+ .export({ type: "spki", format: "der" })
38
+ .toString("base64url") !== value.publicKey
39
+ )
40
+ throw new HostError("Stored encryption identity is inconsistent.");
41
+ }
28
42
  export function encryptionIdentity(): EncryptionIdentity {
29
43
  const keys = generateKeyPairSync("x25519");
30
44
  return {
@@ -30,6 +30,7 @@ export async function readPrivate<T>(
30
30
  directory: string,
31
31
  name: string,
32
32
  additionalPaths: readonly ProtectedPath[] = [],
33
+ maximumBytes = 2 * 1024 * 1024,
33
34
  ): Promise<T | undefined> {
34
35
  const path = join(directory, name);
35
36
  if (additionalPaths.length) {
@@ -48,7 +49,7 @@ export async function readPrivate<T>(
48
49
  throw cause;
49
50
  }
50
51
  }
51
- if ((await lstat(path)).size > 2 * 1024 * 1024)
52
+ if ((await lstat(path)).size > maximumBytes)
52
53
  throw new HostError("Protected state is oversized.");
53
54
  return JSON.parse(await readFile(path, "utf8")) as T;
54
55
  }