@ipab/cli 0.1.0-rc.3 → 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 (97) hide show
  1. package/README.md +21 -10
  2. package/dist/cli.d.ts +3 -1
  3. package/dist/cli.d.ts.map +1 -1
  4. package/dist/cli.js +188 -46
  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 +2 -1
  11. package/dist/config.d.ts.map +1 -1
  12. package/dist/config.js +23 -3
  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/identity.d.ts +5 -0
  23. package/dist/identity.d.ts.map +1 -1
  24. package/dist/identity.js +5 -0
  25. package/dist/identity.js.map +1 -1
  26. package/dist/ipc.d.ts +3 -1
  27. package/dist/ipc.d.ts.map +1 -1
  28. package/dist/ipc.js +34 -1
  29. package/dist/ipc.js.map +1 -1
  30. package/dist/kubo-install.d.ts +9 -0
  31. package/dist/kubo-install.d.ts.map +1 -0
  32. package/dist/kubo-install.js +361 -0
  33. package/dist/kubo-install.js.map +1 -0
  34. package/dist/kubo-peering.d.ts +11 -0
  35. package/dist/kubo-peering.d.ts.map +1 -0
  36. package/dist/kubo-peering.js +93 -0
  37. package/dist/kubo-peering.js.map +1 -0
  38. package/dist/kubo-peers.d.ts +12 -0
  39. package/dist/kubo-peers.d.ts.map +1 -0
  40. package/dist/kubo-peers.js +118 -0
  41. package/dist/kubo-peers.js.map +1 -0
  42. package/dist/kubo-release.d.ts +3 -0
  43. package/dist/kubo-release.d.ts.map +1 -0
  44. package/dist/kubo-release.js +12 -0
  45. package/dist/kubo-release.js.map +1 -0
  46. package/dist/kubo.d.ts +14 -5
  47. package/dist/kubo.d.ts.map +1 -1
  48. package/dist/kubo.js +186 -206
  49. package/dist/kubo.js.map +1 -1
  50. package/dist/runtime.d.ts +2 -0
  51. package/dist/runtime.d.ts.map +1 -1
  52. package/dist/runtime.js +6 -2
  53. package/dist/runtime.js.map +1 -1
  54. package/dist/setup.d.ts +2 -1
  55. package/dist/setup.d.ts.map +1 -1
  56. package/dist/setup.js +23 -18
  57. package/dist/setup.js.map +1 -1
  58. package/dist/state-storage-windows.d.ts +2 -0
  59. package/dist/state-storage-windows.d.ts.map +1 -0
  60. package/dist/state-storage-windows.js +114 -0
  61. package/dist/state-storage-windows.js.map +1 -0
  62. package/dist/state-storage.d.ts +3 -0
  63. package/dist/state-storage.d.ts.map +1 -0
  64. package/dist/state-storage.js +299 -0
  65. package/dist/state-storage.js.map +1 -0
  66. package/dist/state.d.ts +5 -3
  67. package/dist/state.d.ts.map +1 -1
  68. package/dist/state.js +64 -30
  69. package/dist/state.js.map +1 -1
  70. package/dist/swarm-files.d.ts +3 -2
  71. package/dist/swarm-files.d.ts.map +1 -1
  72. package/dist/swarm-files.js +25 -9
  73. package/dist/swarm-files.js.map +1 -1
  74. package/dist/swarm.d.ts +10 -5
  75. package/dist/swarm.d.ts.map +1 -1
  76. package/dist/swarm.js +225 -79
  77. package/dist/swarm.js.map +1 -1
  78. package/package.json +4 -4
  79. package/src/cli.ts +224 -60
  80. package/src/config-secret.ts +2 -84
  81. package/src/config.ts +25 -3
  82. package/src/context-types.ts +11 -0
  83. package/src/context.ts +40 -0
  84. package/src/identity.ts +13 -0
  85. package/src/ipc.ts +50 -1
  86. package/src/kubo-install.ts +452 -0
  87. package/src/kubo-peering.ts +126 -0
  88. package/src/kubo-peers.ts +145 -0
  89. package/src/kubo-release.ts +17 -0
  90. package/src/kubo.ts +254 -275
  91. package/src/runtime.ts +12 -1
  92. package/src/setup.ts +30 -17
  93. package/src/state-storage-windows.ts +134 -0
  94. package/src/state-storage.ts +329 -0
  95. package/src/state.ts +76 -35
  96. package/src/swarm-files.ts +26 -6
  97. package/src/swarm.ts +316 -97
package/src/runtime.ts CHANGED
@@ -10,6 +10,8 @@ import { ContextServer } from "./ipc.js";
10
10
  import { loadApp, OutputSpace } from "./space.js";
11
11
  import type { RunRecord, State } from "./state.js";
12
12
  import { ExecutionLogs } from "./logs.js";
13
+ import { verifyStateStorage } from "./state-storage.js";
14
+ import type { BundleInspection } from "./context.js";
13
15
 
14
16
  export interface Invocation {
15
17
  origin: "exec" | "open";
@@ -23,6 +25,11 @@ export interface ExecutionOptions {
23
25
  log?: boolean;
24
26
  signal?: AbortSignal;
25
27
  inputSchema?: string;
28
+ resolveBundleReference?: (
29
+ reference: string,
30
+ signal: AbortSignal,
31
+ swarm?: string,
32
+ ) => Promise<Pick<BundleInspection, "cid" | "targetCid" | "swarm">>;
26
33
  }
27
34
 
28
35
  export async function execute(
@@ -114,7 +121,10 @@ export async function execute(
114
121
  "validation",
115
122
  );
116
123
  phase = "startup";
117
- await mkdir(directory, { recursive: true });
124
+ const runtime = join(state.directory, "runtime");
125
+ verifyStateStorage(state.directory);
126
+ await mkdir(runtime, { recursive: true, mode: 0o700 });
127
+ await mkdir(directory, { mode: 0o700 });
118
128
  directoryCreated = true;
119
129
  await writeFile(entry, app.source, { flag: "wx", mode: 0o600 });
120
130
  entryCreated = true;
@@ -162,6 +172,7 @@ export async function execute(
162
172
  },
163
173
  invocation.appCid,
164
174
  (name) => state.resolvePin(name),
175
+ options.resolveBundleReference,
165
176
  );
166
177
  const result = await new Promise<{
167
178
  code: number | null;
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
+ }