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

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 (92) hide show
  1. package/README.md +12 -7
  2. package/dist/cli.d.ts +3 -1
  3. package/dist/cli.d.ts.map +1 -1
  4. package/dist/cli.js +114 -25
  5. package/dist/cli.js.map +1 -1
  6. package/dist/config-secret.d.ts +1 -1
  7. package/dist/config-secret.d.ts.map +1 -1
  8. package/dist/config-secret.js +2 -73
  9. package/dist/config-secret.js.map +1 -1
  10. package/dist/config.d.ts +1 -0
  11. package/dist/config.d.ts.map +1 -1
  12. package/dist/config.js +12 -1
  13. package/dist/config.js.map +1 -1
  14. package/dist/context-types.d.ts +12 -0
  15. package/dist/context-types.d.ts.map +1 -0
  16. package/dist/context-types.js +2 -0
  17. package/dist/context-types.js.map +1 -0
  18. package/dist/context.d.ts +6 -0
  19. package/dist/context.d.ts.map +1 -1
  20. package/dist/context.js +25 -0
  21. package/dist/context.js.map +1 -1
  22. package/dist/ipc.d.ts +3 -1
  23. package/dist/ipc.d.ts.map +1 -1
  24. package/dist/ipc.js +34 -1
  25. package/dist/ipc.js.map +1 -1
  26. package/dist/kubo-install.d.ts +9 -0
  27. package/dist/kubo-install.d.ts.map +1 -0
  28. package/dist/kubo-install.js +361 -0
  29. package/dist/kubo-install.js.map +1 -0
  30. package/dist/kubo-peering.d.ts +11 -0
  31. package/dist/kubo-peering.d.ts.map +1 -0
  32. package/dist/kubo-peering.js +93 -0
  33. package/dist/kubo-peering.js.map +1 -0
  34. package/dist/kubo-peers.d.ts +12 -0
  35. package/dist/kubo-peers.d.ts.map +1 -0
  36. package/dist/kubo-peers.js +118 -0
  37. package/dist/kubo-peers.js.map +1 -0
  38. package/dist/kubo-release.d.ts +3 -0
  39. package/dist/kubo-release.d.ts.map +1 -0
  40. package/dist/kubo-release.js +12 -0
  41. package/dist/kubo-release.js.map +1 -0
  42. package/dist/kubo.d.ts +11 -4
  43. package/dist/kubo.d.ts.map +1 -1
  44. package/dist/kubo.js +150 -197
  45. package/dist/kubo.js.map +1 -1
  46. package/dist/runtime.d.ts +2 -0
  47. package/dist/runtime.d.ts.map +1 -1
  48. package/dist/runtime.js +6 -2
  49. package/dist/runtime.js.map +1 -1
  50. package/dist/setup.d.ts +2 -1
  51. package/dist/setup.d.ts.map +1 -1
  52. package/dist/setup.js +23 -18
  53. package/dist/setup.js.map +1 -1
  54. package/dist/state-storage-windows.d.ts +2 -0
  55. package/dist/state-storage-windows.d.ts.map +1 -0
  56. package/dist/state-storage-windows.js +114 -0
  57. package/dist/state-storage-windows.js.map +1 -0
  58. package/dist/state-storage.d.ts +3 -0
  59. package/dist/state-storage.d.ts.map +1 -0
  60. package/dist/state-storage.js +299 -0
  61. package/dist/state-storage.js.map +1 -0
  62. package/dist/state.d.ts +2 -2
  63. package/dist/state.d.ts.map +1 -1
  64. package/dist/state.js +59 -29
  65. package/dist/state.js.map +1 -1
  66. package/dist/swarm-files.d.ts +1 -1
  67. package/dist/swarm-files.d.ts.map +1 -1
  68. package/dist/swarm-files.js +4 -1
  69. package/dist/swarm-files.js.map +1 -1
  70. package/dist/swarm.d.ts +6 -3
  71. package/dist/swarm.d.ts.map +1 -1
  72. package/dist/swarm.js +184 -70
  73. package/dist/swarm.js.map +1 -1
  74. package/package.json +4 -4
  75. package/src/cli.ts +146 -39
  76. package/src/config-secret.ts +2 -84
  77. package/src/config.ts +14 -1
  78. package/src/context-types.ts +11 -0
  79. package/src/context.ts +40 -0
  80. package/src/ipc.ts +50 -1
  81. package/src/kubo-install.ts +452 -0
  82. package/src/kubo-peering.ts +126 -0
  83. package/src/kubo-peers.ts +145 -0
  84. package/src/kubo-release.ts +17 -0
  85. package/src/kubo.ts +207 -269
  86. package/src/runtime.ts +12 -1
  87. package/src/setup.ts +30 -17
  88. package/src/state-storage-windows.ts +134 -0
  89. package/src/state-storage.ts +329 -0
  90. package/src/state.ts +68 -35
  91. package/src/swarm-files.ts +4 -0
  92. package/src/swarm.ts +256 -90
package/src/setup.ts CHANGED
@@ -1,21 +1,34 @@
1
- import { lstat, mkdir } from "node:fs/promises";
2
- import { accountIdentity, secureNew } from "./identity.js";
1
+ import { accountIdentity } from "./identity.js";
3
2
  import { kuboBinary, KUBO_VERSION } from "./kubo.js";
4
3
  import { keyId } from "@ipab/bundle/pointer/crypto";
5
- import { HostError } from "./errors.js";
4
+ import { prepareStateStorage } from "./state-storage.js";
5
+ import { setupFailure, type InstallOptions } from "./kubo-install.js";
6
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
- };
7
+ export async function setupDevice(
8
+ stateDir: string,
9
+ env: NodeJS.ProcessEnv,
10
+ options: InstallOptions = {},
11
+ ) {
12
+ options.signal?.throwIfAborted();
13
+ prepareStateStorage(stateDir, env);
14
+ const binary = await kuboBinary(stateDir, options);
15
+ try {
16
+ options.signal?.throwIfAborted();
17
+ options.diagnostic?.("Preparing the protected HOME account identity...");
18
+ const identity = await accountIdentity(env, true);
19
+ options.signal?.throwIfAborted();
20
+ return {
21
+ kuboVersion: KUBO_VERSION,
22
+ binary,
23
+ publicKey: identity.publicKey,
24
+ fingerprint: await keyId(identity.publicKey),
25
+ };
26
+ } catch (cause) {
27
+ options.signal?.throwIfAborted();
28
+ throw setupFailure(
29
+ "identity preparation",
30
+ "protected account identity",
31
+ cause,
32
+ );
33
+ }
21
34
  }
@@ -0,0 +1,134 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { join } from "node:path";
3
+
4
+ // One process per preflight, not one per path or SQL statement. Use framework
5
+ // APIs directly: loading PowerShell's filesystem/ACL cmdlets dominates startup.
6
+ const script = `
7
+ $ErrorActionPreference = 'Stop'
8
+ $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User
9
+ $sidType = [Security.Principal.SecurityIdentifier]
10
+ $root = $env:IPAB_STATE_ROOT
11
+ $repair = $env:IPAB_STATE_ACTION -eq 'prepare'
12
+ $managed = $env:IPAB_STATE_MANAGED -eq '1'
13
+ function New-PrivateAcl($dir) {
14
+ if ($dir) {
15
+ $a = [Security.AccessControl.DirectorySecurity]::new()
16
+ $r = [Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow')
17
+ } else {
18
+ $a = [Security.AccessControl.FileSecurity]::new()
19
+ $r = [Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','Allow')
20
+ }
21
+ $a.SetAccessRuleProtection($true,$false)
22
+ $a.AddAccessRule($r)
23
+ return $a
24
+ }
25
+ if ($repair -and ![IO.Directory]::Exists($root)) {
26
+ $new = New-PrivateAcl $true
27
+ $new.SetOwner($sid)
28
+ [void][IO.Directory]::CreateDirectory($root,$new)
29
+ }
30
+ $changes = @()
31
+ $paths = @($root)
32
+ foreach ($name in ([string]$env:IPAB_STATE_ENTRIES).Split('|',[StringSplitOptions]::RemoveEmptyEntries)) {
33
+ $paths += [IO.Path]::Combine($root,$name)
34
+ }
35
+ function Check-Path($path) {
36
+ try {
37
+ $attrs = [IO.File]::GetAttributes($path)
38
+ if ($attrs -band [IO.FileAttributes]::ReparsePoint) { throw 'Invalid state path' }
39
+ $dir = [bool]($attrs -band [IO.FileAttributes]::Directory)
40
+ $isDir = $path -eq $root -or [IO.Path]::GetFileName($path) -in 'runtime','logs','kubo-bin','swarm-nodes','swarm-credentials'
41
+ if ($dir -ne $isDir) { throw 'Invalid state type' }
42
+ if ($dir) { $acl = [IO.Directory]::GetAccessControl($path) }
43
+ else { $acl = [IO.File]::GetAccessControl($path) }
44
+ }
45
+ catch [IO.FileNotFoundException] {
46
+ if ($path -match 'state\\.sqlite-(wal|shm|journal)$') { return }
47
+ throw
48
+ }
49
+ if ($acl.GetOwner($sidType).Value -ne $sid.Value) { throw 'Invalid owner' }
50
+ if ($env:IPAB_STATE_ACTION -eq 'owners') { return }
51
+ if ($dir -and $path -ne $root -and [IO.Path]::GetFileName($path) -notin 'runtime','logs') { return }
52
+ $private = $false
53
+ $raw = [Security.AccessControl.RawSecurityDescriptor]::new($acl.GetSecurityDescriptorBinaryForm(),0)
54
+ foreach ($ace in $raw.DiscretionaryAcl) {
55
+ if ($ace.AceType -ne 'AccessAllowed' -or $ace.SecurityIdentifier.Value -ne $sid.Value) { $private = $false; break }
56
+ $flags = [int]$ace.AceFlags
57
+ if ($ace.AccessMask -eq [int][Security.AccessControl.FileSystemRights]::FullControl -and !($flags -band 8) -and (!$dir -or ($flags -band 15) -eq 3)) { $private = $true }
58
+ }
59
+ if (!$private -or ($path -eq $root -and !$acl.AreAccessRulesProtected)) {
60
+ if (!$repair -or (!$managed -and !$private)) { throw 'Not account-only' }
61
+ return @{path=$path; dir=$dir}
62
+ }
63
+ }
64
+ foreach ($path in $paths) { $change = Check-Path $path; if ($change) { $changes += $change } }
65
+ foreach ($c in $changes) {
66
+ $acl = New-PrivateAcl $c.dir
67
+ if ($c.dir) {
68
+ # SetKernelObjectSecurity only updates this directory; SetAccessControl
69
+ # would propagate inheritable ACEs through existing, uninspected children.
70
+ if (!('IpabDirectoryAcl' -as [type])) {
71
+ Add-Type -TypeDefinition @'
72
+ using System;
73
+ using System.Runtime.InteropServices;
74
+ using Microsoft.Win32.SafeHandles;
75
+ public static class IpabDirectoryAcl {
76
+ [DllImport("kernel32", CharSet=CharSet.Unicode, SetLastError=true)]
77
+ static extern SafeFileHandle CreateFile(string p, uint a, uint s, IntPtr sa, uint d, uint f, IntPtr t);
78
+ [DllImport("advapi32", SetLastError=true)]
79
+ static extern bool SetKernelObjectSecurity(SafeFileHandle h, uint i, byte[] sd);
80
+ public static void Set(string p, byte[] sd) {
81
+ using (var h = CreateFile(p, 0x40000, 3, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero)) {
82
+ if (h.IsInvalid || !SetKernelObjectSecurity(h, 0x80000004, sd)) throw new System.ComponentModel.Win32Exception();
83
+ }
84
+ }
85
+ }
86
+ '@
87
+ }
88
+ [IpabDirectoryAcl]::Set($c.path,$acl.GetSecurityDescriptorBinaryForm())
89
+ } else { [IO.File]::SetAccessControl($c.path,$acl) }
90
+ if (Check-Path $c.path) { throw 'ACL did not persist' }
91
+ if ($c.path -eq $root) { 'sealed'; break }
92
+ }
93
+ `;
94
+
95
+ export function windowsStateAccess(
96
+ root: string,
97
+ entries: string[],
98
+ action: "owners" | "prepare" | "verify",
99
+ managed: boolean,
100
+ ): boolean {
101
+ const result = execFileSync(
102
+ join(
103
+ process.env.SystemRoot!,
104
+ "System32",
105
+ "WindowsPowerShell",
106
+ "v1.0",
107
+ "powershell.exe",
108
+ ),
109
+ [
110
+ "-NoLogo",
111
+ "-NoProfile",
112
+ "-NonInteractive",
113
+ "-EncodedCommand",
114
+ Buffer.from(script, "utf16le").toString("base64"),
115
+ ],
116
+ {
117
+ windowsHide: true,
118
+ encoding: "utf8",
119
+ env: {
120
+ ...Object.fromEntries(
121
+ Object.entries(process.env).filter(
122
+ ([key]) => key.toLowerCase() !== "psmodulepath",
123
+ ),
124
+ ),
125
+ IPAB_STATE_ROOT: root,
126
+ IPAB_STATE_ENTRIES: entries.join("|"),
127
+ IPAB_STATE_ACTION: action,
128
+ IPAB_STATE_MANAGED: managed ? "1" : "0",
129
+ },
130
+ stdio: ["ignore", "pipe", "pipe"],
131
+ },
132
+ );
133
+ return result.trim() === "sealed";
134
+ }
@@ -0,0 +1,329 @@
1
+ import {
2
+ closeSync,
3
+ constants,
4
+ fchmodSync,
5
+ fstatSync,
6
+ lstatSync,
7
+ mkdirSync,
8
+ openSync,
9
+ readdirSync,
10
+ realpathSync,
11
+ readSync,
12
+ type Stats,
13
+ } from "node:fs";
14
+ import { homedir, tmpdir } from "node:os";
15
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
16
+ import { HostError } from "./errors.js";
17
+ import { windowsStateAccess } from "./state-storage-windows.js";
18
+
19
+ // Written only after the existing layout/owner checks, before the first DB
20
+ // open. A competing first opener need not guess whether an empty DB is ours.
21
+ const marker = ".ipab-state-v1";
22
+ const database = "state.sqlite";
23
+ const files = [
24
+ marker,
25
+ database,
26
+ `${database}-journal`,
27
+ `${database}-wal`,
28
+ `${database}-shm`,
29
+ ];
30
+ const directories = [
31
+ "runtime",
32
+ "logs",
33
+ "kubo-bin",
34
+ "swarm-nodes",
35
+ "swarm-credentials",
36
+ ];
37
+ const windows = () => process.platform === "win32";
38
+ function unsafe(): never {
39
+ throw new HostError(
40
+ "State storage requires a dedicated, account-only regular directory and files. Stop IPAB processes, back up your state, and migrate only known IPAB files to a new private --state-dir; do not change permissions on a shared directory.",
41
+ );
42
+ }
43
+
44
+ function inspect(stat: Stats, directory: boolean): void {
45
+ if (
46
+ (directory ? !stat.isDirectory() : !stat.isFile() || stat.nlink !== 1) ||
47
+ (!windows() && stat.uid !== process.geteuid?.())
48
+ )
49
+ unsafe();
50
+ }
51
+
52
+ function checkLocation(directory: string, env: NodeJS.ProcessEnv): void {
53
+ if (dirname(directory) === directory) unsafe();
54
+ if (
55
+ windows() &&
56
+ (!/^[A-Za-z]:\\/.test(directory) ||
57
+ directory
58
+ .slice(3)
59
+ .split("\\")
60
+ .some((part) => /[. ]$|:/.test(part)))
61
+ )
62
+ unsafe();
63
+ for (const reserved of [
64
+ homedir(),
65
+ env.HOME,
66
+ env.USERPROFILE,
67
+ env.LOCALAPPDATA,
68
+ env.XDG_DATA_HOME,
69
+ tmpdir(),
70
+ process.cwd(),
71
+ ]) {
72
+ if (!reserved) continue;
73
+ const tail = relative(directory, reserved);
74
+ if (!isAbsolute(tail) && !tail.startsWith(`..${sep}`) && tail !== "..")
75
+ unsafe();
76
+ }
77
+ // Never create a child through a junction/symlink, or below a replaceable
78
+ // POSIX ancestor. A sticky, system-owned temporary directory is OK.
79
+ let parent = dirname(directory);
80
+ let canonical = !windows();
81
+ if (!canonical && lstatSync(directory, { throwIfNoEntry: false })) {
82
+ if (relative(directory, realpathSync.native(directory))) unsafe();
83
+ canonical = true;
84
+ }
85
+ for (;;) {
86
+ const info = lstatSync(parent, { throwIfNoEntry: false });
87
+ if (info && !canonical) {
88
+ if (relative(parent, realpathSync.native(parent))) unsafe();
89
+ canonical = true;
90
+ }
91
+ if (
92
+ info &&
93
+ (!info.isDirectory() ||
94
+ (!windows() &&
95
+ ((info.uid !== 0 && info.uid !== process.geteuid?.()) ||
96
+ ((info.mode & 0o022) !== 0 && !(info.mode & 0o1000)))))
97
+ )
98
+ unsafe();
99
+ const next = dirname(parent);
100
+ if (parent === next) break;
101
+ parent = next;
102
+ }
103
+ }
104
+
105
+ function openChecked(path: string, directory: boolean): number {
106
+ const fd = openSync(
107
+ path,
108
+ constants.O_RDONLY |
109
+ (windows()
110
+ ? 0
111
+ : constants.O_NOFOLLOW |
112
+ constants.O_NONBLOCK |
113
+ (directory ? constants.O_DIRECTORY : 0)),
114
+ );
115
+ try {
116
+ inspect(fstatSync(fd), directory);
117
+ return fd;
118
+ } catch (error) {
119
+ closeSync(fd);
120
+ throw error;
121
+ }
122
+ }
123
+
124
+ function schemaPage(page: Buffer): boolean {
125
+ if (page.toString("latin1", 0, 16) !== "SQLite format 3\0") return false;
126
+ const schema = page.toString("latin1", 100);
127
+ return [
128
+ "CREATE TABLE identity (id TEXT NOT NULL)",
129
+ "CREATE TABLE holds (owner TEXT PRIMARY KEY, value TEXT NOT NULL)",
130
+ ].every((sql) => schema.includes(sql));
131
+ }
132
+
133
+ // Older versions have no marker. Recognize their first schema page without
134
+ // opening SQLite (even a read-only WAL connection can write SHM). Before the
135
+ // first checkpoint this page is in the WAL rather than in the main database.
136
+ function legacyDatabase(path: string, hasWal: boolean): boolean {
137
+ const fd = openChecked(path, false);
138
+ let length: number;
139
+ try {
140
+ const header = Buffer.alloc(100);
141
+ if (
142
+ readSync(fd, header, 0, 100, 0) !== 100 ||
143
+ header.toString("latin1", 0, 16) !== "SQLite format 3\0"
144
+ )
145
+ return false;
146
+ length = header.readUInt16BE(16);
147
+ if (length === 1) length = 65536;
148
+ if (length < 512 || (length & (length - 1)) !== 0) return false;
149
+ const page = Buffer.alloc(length);
150
+ if (readSync(fd, page, 0, length, 0) !== length) return false;
151
+ if (schemaPage(page)) return true;
152
+ if (
153
+ header.readUInt32BE(28) !== 1 ||
154
+ header.readUInt32BE(40) !== 0 ||
155
+ page[100] !== 13 ||
156
+ page.readUInt16BE(103) !== 0
157
+ )
158
+ return false;
159
+ } finally {
160
+ closeSync(fd);
161
+ }
162
+ if (!hasWal) return false;
163
+ const wal = openChecked(`${path}-wal`, false);
164
+ try {
165
+ const header = Buffer.alloc(32),
166
+ frame = Buffer.alloc(24),
167
+ page = Buffer.alloc(length);
168
+ if (
169
+ readSync(wal, header, 0, 32, 0) !== 32 ||
170
+ ![0x377f0682, 0x377f0683].includes(header.readUInt32BE()) ||
171
+ header.readUInt32BE(8) !== length
172
+ )
173
+ return false;
174
+ const salt = header.subarray(16, 24);
175
+ for (let i = 0; i < 128; i++) {
176
+ const offset = 32 + i * (24 + length);
177
+ if (
178
+ readSync(wal, frame, 0, 24, offset) !== 24 ||
179
+ !salt.equals(frame.subarray(8, 16))
180
+ )
181
+ return false;
182
+ if (
183
+ frame.readUInt32BE() === 1 &&
184
+ readSync(wal, page, 0, length, offset + 24) === length &&
185
+ schemaPage(page)
186
+ )
187
+ return true;
188
+ }
189
+ return false;
190
+ } finally {
191
+ closeSync(wal);
192
+ }
193
+ }
194
+
195
+ function createFile(path: string): void {
196
+ try {
197
+ const fd = openSync(path, "wx", 0o600);
198
+ try {
199
+ if (!windows() && (fstatSync(fd).mode & 0o7777) !== 0o600) {
200
+ fchmodSync(fd, 0o600);
201
+ if ((fstatSync(fd).mode & 0o7777) !== 0o600) unsafe();
202
+ }
203
+ } finally {
204
+ closeSync(fd);
205
+ }
206
+ } catch (error) {
207
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
208
+ }
209
+ inspect(lstatSync(path), false);
210
+ }
211
+
212
+ interface Entry {
213
+ name: string;
214
+ directory: boolean;
215
+ info: Stats;
216
+ }
217
+
218
+ function access(directory: string, initialize: boolean, sealed = false): void {
219
+ const root = lstatSync(directory, { throwIfNoEntry: false });
220
+ if (root) inspect(root, true);
221
+ else if (!initialize) unsafe();
222
+ const entries: Entry[] = [];
223
+ for (const name of root ? readdirSync(directory) : []) {
224
+ const dir = directories.includes(name);
225
+ if (!dir && !files.includes(name)) unsafe();
226
+ const info = lstatSync(join(directory, name), { throwIfNoEntry: false });
227
+ // SQLite may unlink a transient sidecar as another connection closes.
228
+ if (!info) {
229
+ if (name.startsWith(`${database}-`)) continue;
230
+ unsafe();
231
+ }
232
+ inspect(info, dir);
233
+ entries.push({ name, directory: dir, info });
234
+ }
235
+ const markerInfo = lstatSync(join(directory, marker), {
236
+ throwIfNoEntry: false,
237
+ });
238
+ if (markerInfo) {
239
+ inspect(markerInfo, false);
240
+ if (markerInfo.size !== 0) unsafe();
241
+ if (!entries.some((e) => e.name === marker))
242
+ entries.push({ name: marker, directory: false, info: markerInfo });
243
+ }
244
+ const marked = !!markerInfo;
245
+ const hasDb = entries.some((e) => e.name === database);
246
+ if (!initialize && (!marked || !hasDb)) unsafe();
247
+ const names = entries.map((e) => e.name);
248
+ if (windows() && !marked && hasDb) {
249
+ windowsStateAccess(directory, names, "owners", false);
250
+ }
251
+ const managed =
252
+ marked ||
253
+ (hasDb &&
254
+ legacyDatabase(
255
+ join(directory, database),
256
+ names.includes(`${database}-wal`),
257
+ ));
258
+ if (!managed && entries.some((e) => e.name !== "kubo-bin")) unsafe();
259
+
260
+ if (windows()) {
261
+ if (
262
+ windowsStateAccess(
263
+ directory,
264
+ names,
265
+ initialize ? "prepare" : "verify",
266
+ managed,
267
+ )
268
+ ) {
269
+ if (sealed) unsafe();
270
+ access(directory, initialize, true);
271
+ }
272
+ } else {
273
+ if (!root || (!managed && (root.mode & 0o077) !== 0)) unsafe();
274
+ for (const entry of [
275
+ { name: "", directory: true, info: root },
276
+ ...entries,
277
+ ]) {
278
+ if (entry.directory && !["", "runtime", "logs"].includes(entry.name))
279
+ continue;
280
+ const mode = entry.directory ? 0o700 : 0o600;
281
+ if ((entry.info.mode & 0o7777) === mode) continue;
282
+ if (!initialize) unsafe();
283
+ const fd = openChecked(join(directory, entry.name), entry.directory);
284
+ try {
285
+ fchmodSync(fd, mode);
286
+ if ((fstatSync(fd).mode & 0o7777) !== mode) unsafe();
287
+ } finally {
288
+ closeSync(fd);
289
+ }
290
+ if (!entry.name) {
291
+ // Children might have changed while the old directory was writable.
292
+ // Re-inspect its contents now before touching any existing child.
293
+ if (sealed) unsafe();
294
+ access(directory, initialize, true);
295
+ return;
296
+ }
297
+ }
298
+ }
299
+ }
300
+
301
+ export function prepareStateStorage(
302
+ directory: string,
303
+ env: NodeJS.ProcessEnv = process.env,
304
+ ): string {
305
+ try {
306
+ directory = resolve(directory);
307
+ checkLocation(directory, env);
308
+ mkdirSync(windows() ? dirname(directory) : directory, {
309
+ recursive: true,
310
+ mode: 0o700,
311
+ });
312
+ access(directory, true);
313
+ createFile(join(directory, marker));
314
+ const path = join(directory, database);
315
+ createFile(path);
316
+ return path;
317
+ } catch {
318
+ unsafe();
319
+ }
320
+ }
321
+
322
+ export function verifyStateStorage(directory: string): void {
323
+ try {
324
+ checkLocation(resolve(directory), process.env);
325
+ access(directory, false);
326
+ } catch {
327
+ unsafe();
328
+ }
329
+ }
package/src/state.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { mkdirSync } from "node:fs";
2
1
  import { randomUUID } from "node:crypto";
3
- import { join } from "node:path";
2
+ import { resolve } from "node:path";
4
3
  import { DatabaseSync } from "node:sqlite";
5
4
  import { CID } from "multiformats/cid";
6
5
  import type { StoreConfiguration } from "@ipab/ipfs-store";
7
6
  import {
7
+ rejectLegacySwarmCid,
8
8
  validateUserConfig,
9
9
  swarmUrl,
10
10
  type ConfigKey,
@@ -12,6 +12,7 @@ import {
12
12
  } from "./config.js";
13
13
  import { HostError, object, syntax } from "./errors.js";
14
14
  import { secureConfigurationStorage } from "./config-secret.js";
15
+ import { prepareStateStorage } from "./state-storage.js";
15
16
 
16
17
  export interface Association {
17
18
  schemaCid: string;
@@ -138,17 +139,43 @@ function persistedHold(value: string, owner: string): Hold {
138
139
  }
139
140
  }
140
141
 
142
+ // SQLite can report BUSY immediately when concurrent first opens both try to
143
+ // upgrade their read lock to switch journal mode, even with a busy timeout.
144
+ function enableWal(db: DatabaseSync): void {
145
+ const until = performance.now() + 5000;
146
+ for (;;) {
147
+ try {
148
+ db.exec("PRAGMA journal_mode=WAL");
149
+ if (db.prepare("PRAGMA journal_mode").get()?.journal_mode !== "wal")
150
+ throw new HostError(
151
+ "Cannot enable WAL for the private state database.",
152
+ );
153
+ return;
154
+ } catch (error) {
155
+ if (
156
+ (((error as { errcode?: number }).errcode ?? 0) & 0xff) !== 5 ||
157
+ performance.now() >= until
158
+ )
159
+ throw error;
160
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
161
+ }
162
+ }
163
+ }
164
+
141
165
  export class State {
142
166
  readonly db: DatabaseSync;
143
167
  readonly identity: string;
168
+ readonly directory: string;
144
169
  constructor(
145
- readonly directory: string,
170
+ directory: string,
146
171
  private readonly builtins: readonly NamedPin[] = [],
172
+ env: NodeJS.ProcessEnv = process.env,
147
173
  ) {
148
- mkdirSync(directory, { recursive: true, mode: 0o700 });
149
- this.db = new DatabaseSync(join(directory, "state.sqlite"));
150
- this.db
151
- .exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
174
+ this.directory = resolve(directory);
175
+ this.db = new DatabaseSync(prepareStateStorage(this.directory, env));
176
+ try {
177
+ enableWal(this.db);
178
+ this.db.exec(`PRAGMA busy_timeout=5000; PRAGMA synchronous=FULL;
152
179
  CREATE TABLE IF NOT EXISTS identity (id TEXT NOT NULL);
153
180
  CREATE TABLE IF NOT EXISTS config (key TEXT PRIMARY KEY, value TEXT NOT NULL);
154
181
  DROP TABLE IF EXISTS aliases;
@@ -158,13 +185,17 @@ export class State {
158
185
  CREATE TABLE IF NOT EXISTS swarm_headers (account TEXT NOT NULL, swarm TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (account,swarm));
159
186
  CREATE TABLE IF NOT EXISTS runs (id TEXT PRIMARY KEY, value TEXT NOT NULL);
160
187
  CREATE TABLE IF NOT EXISTS holds (owner TEXT PRIMARY KEY, value TEXT NOT NULL);`);
161
- this.transaction(() => {
162
- if (!this.db.prepare("SELECT id FROM identity").get())
163
- this.db.prepare("INSERT INTO identity VALUES (?)").run(randomUUID());
164
- });
165
- this.identity = String(
166
- this.db.prepare("SELECT id FROM identity").get()!.id,
167
- );
188
+ this.transaction(() => {
189
+ if (!this.db.prepare("SELECT id FROM identity").get())
190
+ this.db.prepare("INSERT INTO identity VALUES (?)").run(randomUUID());
191
+ });
192
+ this.identity = String(
193
+ this.db.prepare("SELECT id FROM identity").get()!.id,
194
+ );
195
+ } catch (error) {
196
+ this.db.close();
197
+ throw error;
198
+ }
168
199
  }
169
200
  close(): void {
170
201
  this.db.close();
@@ -186,16 +217,20 @@ export class State {
186
217
  const entries = this.db
187
218
  .prepare(
188
219
  includeSecrets
189
- ? "SELECT key,value FROM config"
220
+ ? "SELECT key, CASE WHEN key='pointers.apiKey' AND value!='null' THEN NULL ELSE value END AS value FROM config"
190
221
  : "SELECT key,value FROM config WHERE key != 'pointers.apiKey'",
191
222
  )
192
223
  .all();
193
- if (
194
- entries.some(
195
- (row) => row.key === "pointers.apiKey" && row.value !== "null",
196
- )
197
- )
198
- secureConfigurationStorage(this.directory, false);
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
+ }
199
234
  if (entries.some((row) => row.key === "store.rpc"))
200
235
  throw new HostError(
201
236
  "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.",
@@ -217,7 +252,7 @@ export class State {
217
252
  }
218
253
  setConfig(key: ConfigKey, value: ConfigValue): void {
219
254
  if (key === "pointers.apiKey" && value !== null)
220
- secureConfigurationStorage(this.directory, true);
255
+ secureConfigurationStorage(this.directory);
221
256
  this.db
222
257
  .prepare("INSERT OR REPLACE INTO config VALUES (?,?)")
223
258
  .run(key, JSON.stringify(value));
@@ -242,13 +277,12 @@ export class State {
242
277
  }
243
278
  resolveSwarm(reference: string): string {
244
279
  if (/^https?:/.test(reference)) return swarmUrl(reference);
245
- {
246
- const entry = this.swarms().find((entry) => entry.alias === reference);
247
- if (entry) return entry.cid;
248
- throw new HostError(
249
- `Unknown swarm alias "${reference}". Run ipab swarm list.`,
250
- );
251
- }
280
+ const entry = this.swarms().find((entry) => entry.alias === reference);
281
+ if (entry) return entry.cid;
282
+ rejectLegacySwarmCid(reference);
283
+ throw new HostError(
284
+ `Unknown swarm alias "${reference}". Run ipab swarm list.`,
285
+ );
252
286
  }
253
287
  registeredSwarm(reference: string): RegisteredSwarm {
254
288
  const cid = this.resolveSwarm(reference);
@@ -261,11 +295,10 @@ export class State {
261
295
  }
262
296
  checkSwarmAlias(alias: string, cid?: string): void {
263
297
  swarmAlias(alias);
264
- if (
265
- this.swarms().some((entry) => entry.alias === alias && entry.cid !== cid)
266
- )
298
+ const existing = this.swarms().find((entry) => entry.alias === alias);
299
+ if (existing && existing.cid !== cid)
267
300
  throw new HostError(
268
- `Swarm alias "${alias}" is already assigned. Choose another alias.`,
301
+ `Swarm alias "${alias}" is already assigned to "${existing.cid}". To keep both Swarms, retry with a different --alias. To replace only this local registration, run ipab swarm remove ${alias} and retry. Removal clears a matching default but preserves credentials and remote membership.`,
269
302
  );
270
303
  }
271
304
  registerSwarm(cid: string, alias?: string): RegisteredSwarm {
@@ -277,7 +310,7 @@ export class State {
277
310
  this.db
278
311
  .prepare("INSERT OR REPLACE INTO swarms VALUES (?,?)")
279
312
  .run(cid, entry.alias);
280
- if (this.config()["swarm.default"] == null)
313
+ if (this.config({ includeSecrets: false })["swarm.default"] == null)
281
314
  this.setConfig("swarm.default", cid);
282
315
  return entry;
283
316
  });
@@ -293,7 +326,7 @@ export class State {
293
326
  return this.transaction(() => {
294
327
  const entry = this.registeredSwarm(reference);
295
328
  this.db.prepare("DELETE FROM swarms WHERE cid=?").run(entry.cid);
296
- if (this.config()["swarm.default"] === entry.cid)
329
+ if (this.config({ includeSecrets: false })["swarm.default"] === entry.cid)
297
330
  this.resetConfig("swarm.default");
298
331
  return entry.cid;
299
332
  });