@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,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
+ }
package/src/ipc.ts CHANGED
@@ -75,6 +75,9 @@ export class ContextServer {
75
75
  readonly output: OutputSpace,
76
76
  readonly fatal: (error: Error) => void,
77
77
  readonly appCid: string,
78
+ readonly resolvePin: (name: string) => string | undefined = () => {
79
+ throw new HostError("Pin lookup is unavailable in this context.");
80
+ },
78
81
  ) {
79
82
  child.on("message", this.receive);
80
83
  }
@@ -153,6 +156,11 @@ export class ContextServer {
153
156
  ): Promise<unknown> {
154
157
  signal.throwIfAborted();
155
158
  if (operation === "identity") return this.appCid;
159
+ if (operation === "resolvePin") {
160
+ if (typeof args !== "string" || !args || args.length > 256)
161
+ throw new HostError("Pin name must contain 1..256 characters.");
162
+ return this.resolvePin(args) ?? null;
163
+ }
156
164
  if (operation === "read") {
157
165
  if (this.reads.size + this.writes.size + this.openingReads >= 32)
158
166
  throw new HostError("Context stream capacity exceeded.");
package/src/pins.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { CID } from "multiformats/cid";
3
3
  import { IpfsStore } from "@ipab/ipfs-store";
4
- import { declaresBundleSchema, openBundle, openSchema } from "@ipab/bundle";
4
+ import { openBundle } from "@ipab/bundle";
5
5
  import { HostError, message } from "./errors.js";
6
6
  import { alive, type StoreFactory } from "./history.js";
7
7
  import {
8
8
  exactCid,
9
9
  pinName,
10
+ bundlePinMetadata,
10
11
  type NamedPin,
11
12
  type PinMetadata,
12
13
  type State,
@@ -20,7 +21,7 @@ export function pinDetails(pin: NamedPin) {
20
21
  return {
21
22
  name: pin.name,
22
23
  cid: pin.cid,
23
- ...pin.metadata,
24
+ ...bundlePinMetadata(pin),
24
25
  ...(pin.builtin ? { builtin: true as const } : {}),
25
26
  };
26
27
  }
@@ -46,34 +47,19 @@ function idleHold(state: State, pin: NamedPin) {
46
47
  return hold;
47
48
  }
48
49
 
49
- async function classify(cid: string, store: IpfsStore): Promise<PinMetadata> {
50
+ async function classify(
51
+ cid: string,
52
+ store: IpfsStore,
53
+ ): Promise<Extract<PinMetadata, { kind: "bundle" }>> {
50
54
  const root = CID.parse(cid);
51
55
  const resolveCid = (cid: CID, options: { signal?: AbortSignal }) =>
52
56
  store.block.get(cid.toString(), options);
53
- if (root.code === 0x71 && declaresBundleSchema(await store.block.get(cid))) {
54
- const schema = await openSchema(root, { resolveCid });
55
- return {
56
- kind: "schema",
57
- typeName: schema.manifest.name,
58
- schemaCid: schema.cid.toString(),
59
- };
60
- }
61
- if (root.code === 0x70) {
62
- const node = await store.read(root);
63
- if (node.type === "directory") {
64
- for await (const entry of node.entries()) {
65
- if (entry.name === ".bundle.yaml") {
66
- const bundle = await openBundle(root, { resolveCid });
67
- return {
68
- kind: "bundle",
69
- typeName: bundle.manifest.name,
70
- schemaCid: bundle.schemaKey,
71
- };
72
- }
73
- }
74
- }
75
- }
76
- return { kind: "content", typeName: null, schemaCid: null };
57
+ const bundle = await openBundle(root, { resolveCid });
58
+ return {
59
+ kind: "bundle",
60
+ typeName: bundle.manifest.name,
61
+ schemaCid: bundle.schemaKey,
62
+ };
77
63
  }
78
64
 
79
65
  export async function addPin(
@@ -121,8 +107,8 @@ export async function addPin(
121
107
  try {
122
108
  store = factory(state.hold(pin.owner)!.backend);
123
109
  await store.recoverOwner(pin.owner, () => state.hold(pin.owner)!.roots);
124
- await store.retain(pin.owner, [cid]);
125
110
  const metadata = await classify(cid, store);
111
+ await store.retain(pin.owner, [cid]);
126
112
  state.transaction(() => {
127
113
  state.savePin({ ...pin, metadata });
128
114
  state.saveHold({ ...state.hold(pin.owner)!, roots: [cid] });
package/src/runtime.ts CHANGED
@@ -161,6 +161,7 @@ export async function execute(
161
161
  stop(error);
162
162
  },
163
163
  invocation.appCid,
164
+ (name) => state.resolvePin(name),
164
165
  );
165
166
  const result = await new Promise<{
166
167
  code: number | null;
@@ -16,7 +16,6 @@ export const sourceSchema = {
16
16
  path: "package.json",
17
17
  contentType: "application/json",
18
18
  schema: { type: "object" },
19
- defaultValue: {},
20
19
  },
21
20
  } as const;
22
21
 
@@ -42,7 +41,7 @@ export async function captureSource(
42
41
  if (
43
42
  normalized
44
43
  .split("/")
45
- .some((part) => [".git", "node_modules"].includes(part)) ||
44
+ .some((part) => [".git", ".ipab", "node_modules"].includes(part)) ||
46
45
  normalized === ".bundle-ignore" ||
47
46
  normalized === "dist" ||
48
47
  normalized.startsWith("dist/") ||
package/src/state.ts CHANGED
@@ -10,12 +10,20 @@ import {
10
10
  type ConfigValue,
11
11
  } from "./config.js";
12
12
  import { HostError, object, syntax } from "./errors.js";
13
+ import { secureConfigurationStorage } from "./config-secret.js";
13
14
 
14
15
  export interface Association {
15
16
  schemaCid: string;
16
17
  appCid: string;
17
18
  argv: string[];
18
19
  }
20
+ export interface RegisteredSwarm {
21
+ cid: string;
22
+ alias: string | null;
23
+ }
24
+ export function swarmAlias(value: string): void {
25
+ pinName(value);
26
+ }
19
27
  export interface RunRecord {
20
28
  id: string;
21
29
  origin: "exec" | "open";
@@ -42,11 +50,10 @@ export interface Hold {
42
50
  session: string | null;
43
51
  recordId: string | null;
44
52
  }
45
- export interface PinMetadata {
46
- kind: "bundle" | "schema" | "content";
47
- typeName: string | null;
48
- schemaCid: string | null;
49
- }
53
+ export type PinMetadata =
54
+ | { kind: "bundle"; typeName: string; schemaCid: string }
55
+ | { kind: "schema"; typeName: string; schemaCid: string }
56
+ | { kind: "content"; typeName: null; schemaCid: null };
50
57
  export interface NamedPin {
51
58
  name: string;
52
59
  cid: string;
@@ -55,6 +62,17 @@ export interface NamedPin {
55
62
  metadata: PinMetadata | null;
56
63
  builtin?: true;
57
64
  }
65
+ export function bundlePinMetadata(pin: NamedPin) {
66
+ if (pin.status !== "ready" || !pin.metadata)
67
+ throw new HostError(
68
+ `Pin "${pin.name}" is ${pin.status}; retry pin add/delete before using it.`,
69
+ );
70
+ if (pin.metadata.kind !== "bundle")
71
+ throw new HostError(
72
+ `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.`,
73
+ );
74
+ return pin.metadata;
75
+ }
58
76
 
59
77
  export function exactCid(value: string, schema = false): string {
60
78
  let cid: CID;
@@ -88,7 +106,13 @@ export function pinName(value: string, builtin = false): void {
88
106
  function persistedHold(value: string, owner: string): Hold {
89
107
  try {
90
108
  const data = object(JSON.parse(value) as unknown, "retention metadata");
91
- object(data.backend, "original Store configuration");
109
+ const backend = object(data.backend, "original Store configuration");
110
+ if (backend.backend === "kubo")
111
+ throw new HostError(
112
+ "This retention record belongs to the removed Kubo RPC Store. It is not migrated or released. Create a new local pin and manage the old daemon pin independently.",
113
+ 1,
114
+ "LEGACY_STORE",
115
+ );
92
116
  if (
93
117
  data.owner !== owner ||
94
118
  !Array.isArray(data.roots) ||
@@ -101,7 +125,9 @@ function persistedHold(value: string, owner: string): Hold {
101
125
  throw new Error("Invalid retention fields.");
102
126
  for (const root of data.roots as string[]) exactCid(root);
103
127
  return data as unknown as Hold;
104
- } catch {
128
+ } catch (error) {
129
+ if (error instanceof HostError && error.code === "LEGACY_STORE")
130
+ throw error;
105
131
  throw new HostError(
106
132
  "Invalid persisted retention metadata; cleanup is blocked.",
107
133
  1,
@@ -117,15 +143,17 @@ export class State {
117
143
  readonly directory: string,
118
144
  private readonly builtins: readonly NamedPin[] = [],
119
145
  ) {
120
- mkdirSync(directory, { recursive: true });
146
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
121
147
  this.db = new DatabaseSync(join(directory, "state.sqlite"));
122
148
  this.db
123
149
  .exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
124
150
  CREATE TABLE IF NOT EXISTS identity (id TEXT NOT NULL);
125
151
  CREATE TABLE IF NOT EXISTS config (key TEXT PRIMARY KEY, value TEXT NOT NULL);
126
- CREATE TABLE IF NOT EXISTS aliases (name TEXT PRIMARY KEY, cid TEXT NOT NULL);
152
+ DROP TABLE IF EXISTS aliases;
127
153
  CREATE TABLE IF NOT EXISTS named_pins (name TEXT PRIMARY KEY, owner TEXT UNIQUE NOT NULL, value TEXT NOT NULL);
128
154
  CREATE TABLE IF NOT EXISTS registrations (schema_cid TEXT PRIMARY KEY, value TEXT NOT NULL);
155
+ CREATE TABLE IF NOT EXISTS swarms (cid TEXT PRIMARY KEY, alias TEXT UNIQUE);
156
+ CREATE TABLE IF NOT EXISTS swarm_headers (account TEXT NOT NULL, swarm TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (account,swarm));
129
157
  CREATE TABLE IF NOT EXISTS runs (id TEXT PRIMARY KEY, value TEXT NOT NULL);
130
158
  CREATE TABLE IF NOT EXISTS holds (owner TEXT PRIMARY KEY, value TEXT NOT NULL);`);
131
159
  this.transaction(() => {
@@ -152,6 +180,16 @@ export class State {
152
180
  }
153
181
  config(): Partial<Record<ConfigKey, ConfigValue>> {
154
182
  const entries = this.db.prepare("SELECT key,value FROM config").all();
183
+ if (
184
+ entries.some(
185
+ (row) => row.key === "pointers.apiKey" && row.value !== "null",
186
+ )
187
+ )
188
+ secureConfigurationStorage(this.directory, false);
189
+ if (entries.some((row) => row.key === "store.rpc"))
190
+ throw new HostError(
191
+ "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.",
192
+ );
155
193
  try {
156
194
  return validateUserConfig(
157
195
  Object.fromEntries(
@@ -168,21 +206,107 @@ export class State {
168
206
  }
169
207
  }
170
208
  setConfig(key: ConfigKey, value: ConfigValue): void {
209
+ if (key === "pointers.apiKey" && value !== null)
210
+ secureConfigurationStorage(this.directory, true);
171
211
  this.db
172
212
  .prepare("INSERT OR REPLACE INTO config VALUES (?,?)")
173
213
  .run(key, JSON.stringify(value));
174
214
  }
175
- resetConfig(key: ConfigKey): void {
215
+ resetConfig(key: ConfigKey | "store.rpc"): void {
176
216
  this.db.prepare("DELETE FROM config WHERE key=?").run(key);
177
217
  }
178
- aliases(): { name: string; cid: string }[] {
218
+ swarms(): RegisteredSwarm[] {
179
219
  return this.db
180
- .prepare("SELECT name,cid FROM aliases ORDER BY name")
220
+ .prepare("SELECT cid,alias FROM swarms ORDER BY cid")
181
221
  .all()
182
- .map((row) => ({
183
- name: String(row.name),
184
- cid: exactCid(String(row.cid)),
185
- }));
222
+ .map((row) => {
223
+ if (
224
+ typeof row.cid !== "string" ||
225
+ (row.alias !== null && typeof row.alias !== "string")
226
+ )
227
+ throw new HostError("Invalid persisted swarm registration.");
228
+ const cid = exactCid(row.cid);
229
+ if (row.alias !== null) swarmAlias(row.alias);
230
+ return { cid, alias: row.alias };
231
+ });
232
+ }
233
+ resolveSwarm(reference: string): string {
234
+ try {
235
+ return CID.parse(reference).toV1().toString();
236
+ } catch {
237
+ const entry = this.swarms().find((entry) => entry.alias === reference);
238
+ if (entry) return entry.cid;
239
+ throw new HostError(
240
+ `Unknown swarm alias "${reference}". Run ipab swarm list.`,
241
+ );
242
+ }
243
+ }
244
+ registeredSwarm(reference: string): RegisteredSwarm {
245
+ const cid = this.resolveSwarm(reference);
246
+ const entry = this.swarms().find((entry) => entry.cid === cid);
247
+ if (!entry)
248
+ throw new HostError(
249
+ `Swarm "${reference}" is not registered. Run ipab swarm add ${cid}.`,
250
+ );
251
+ return entry;
252
+ }
253
+ checkSwarmAlias(alias: string, cid?: string): void {
254
+ swarmAlias(alias);
255
+ if (
256
+ this.swarms().some((entry) => entry.alias === alias && entry.cid !== cid)
257
+ )
258
+ throw new HostError(
259
+ `Swarm alias "${alias}" is already assigned. Choose another alias.`,
260
+ );
261
+ }
262
+ registerSwarm(cid: string, alias?: string): RegisteredSwarm {
263
+ cid = exactCid(cid);
264
+ return this.transaction(() => {
265
+ if (alias !== undefined) this.checkSwarmAlias(alias, cid);
266
+ const previous = this.swarms().find((entry) => entry.cid === cid);
267
+ const entry = { cid, alias: alias ?? previous?.alias ?? null };
268
+ this.db
269
+ .prepare("INSERT OR REPLACE INTO swarms VALUES (?,?)")
270
+ .run(cid, entry.alias);
271
+ if (this.config()["swarm.default"] == null)
272
+ this.setConfig("swarm.default", cid);
273
+ return entry;
274
+ });
275
+ }
276
+ useSwarm(reference: string): string {
277
+ return this.transaction(() => {
278
+ const entry = this.registeredSwarm(reference);
279
+ this.setConfig("swarm.default", entry.cid);
280
+ return entry.cid;
281
+ });
282
+ }
283
+ removeSwarm(reference: string): string {
284
+ return this.transaction(() => {
285
+ const entry = this.registeredSwarm(reference);
286
+ this.db.prepare("DELETE FROM swarms WHERE cid=?").run(entry.cid);
287
+ if (this.config()["swarm.default"] === entry.cid)
288
+ this.resetConfig("swarm.default");
289
+ return entry.cid;
290
+ });
291
+ }
292
+ swarmHeader(account: string, swarm: string): unknown {
293
+ const row = this.db
294
+ .prepare("SELECT value FROM swarm_headers WHERE account=? AND swarm=?")
295
+ .get(account, swarm);
296
+ if (!row) return undefined;
297
+ try {
298
+ return JSON.parse(String(row.value)) as unknown;
299
+ } catch {
300
+ throw new HostError("Malformed persisted swarm header cache.");
301
+ }
302
+ }
303
+ saveSwarmHeader(account: string, swarm: string, value: unknown): void {
304
+ this.db
305
+ .prepare("INSERT OR REPLACE INTO swarm_headers VALUES (?,?,?)")
306
+ .run(account, swarm, JSON.stringify(value));
307
+ }
308
+ invalidateSwarmHeader(swarm: string): void {
309
+ this.db.prepare("DELETE FROM swarm_headers WHERE swarm=?").run(swarm);
186
310
  }
187
311
  resolve(value: string, schema = false): string {
188
312
  try {
@@ -193,16 +317,10 @@ export class State {
193
317
  } catch {
194
318
  const pin = this.pin(value);
195
319
  if (pin) {
196
- if (pin.status !== "ready")
197
- throw new HostError(
198
- `Pin "${value}" is ${pin.status}; retry pin add/delete before using it.`,
199
- );
320
+ const metadata = bundlePinMetadata(pin);
321
+ if (schema) return metadata.schemaCid;
200
322
  return exactCid(pin.cid, schema);
201
323
  }
202
- if (this.db.prepare("SELECT 1 FROM aliases WHERE name=?").get(value))
203
- throw new HostError(
204
- `Legacy Alias "${value}" is not a pin. Read its CID from the preserved aliases table and run ipab pin add NAME CID to verify and retain it.`,
205
- );
206
324
  throw new HostError(
207
325
  `Unknown CID or pin "${value}". Run ipab pin list.`,
208
326
  );
@@ -210,6 +328,12 @@ export class State {
210
328
  throw error;
211
329
  }
212
330
  }
331
+ resolvePin(name: string): string | undefined {
332
+ const pin = this.pin(name);
333
+ if (!pin) return undefined;
334
+ bundlePinMetadata(pin);
335
+ return exactCid(pin.cid);
336
+ }
213
337
  pins(): NamedPin[] {
214
338
  const user = this.db
215
339
  .prepare("SELECT name,owner,value FROM named_pins ORDER BY name")
@@ -252,6 +376,7 @@ export class State {
252
376
  if (
253
377
  (value.kind !== "bundle" && value.kind !== "schema") ||
254
378
  typeof value.typeName !== "string" ||
379
+ !value.typeName.trim() ||
255
380
  typeof value.schemaCid !== "string"
256
381
  )
257
382
  throw new HostError("Invalid persisted pin type metadata.");