@codelia/storage 0.1.86 → 0.1.89
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.
- package/dist/index.cjs +3118 -568
- package/dist/index.d.cts +449 -4
- package/dist/index.d.ts +449 -4
- package/dist/index.js +3048 -548
- package/package.json +8 -4
package/dist/index.js
CHANGED
|
@@ -1,8 +1,42 @@
|
|
|
1
|
+
// src/atomic-file.ts
|
|
2
|
+
import { randomUUID } from "crypto";
|
|
3
|
+
import { promises as fs } from "fs";
|
|
4
|
+
import path from "path";
|
|
5
|
+
var writeFileAtomic = async (targetPath, data, options = {}) => {
|
|
6
|
+
const mode = options.mode ?? 384;
|
|
7
|
+
const dir = path.dirname(targetPath);
|
|
8
|
+
const base = path.basename(targetPath);
|
|
9
|
+
const temporary = path.join(dir, `.${base}.${randomUUID()}.tmp`);
|
|
10
|
+
let handle;
|
|
11
|
+
try {
|
|
12
|
+
handle = await fs.open(temporary, "wx", mode);
|
|
13
|
+
await handle.writeFile(data, "utf8");
|
|
14
|
+
await handle.sync();
|
|
15
|
+
await handle.close();
|
|
16
|
+
handle = void 0;
|
|
17
|
+
try {
|
|
18
|
+
await fs.chmod(temporary, mode);
|
|
19
|
+
} catch {
|
|
20
|
+
}
|
|
21
|
+
await fs.rename(temporary, targetPath);
|
|
22
|
+
try {
|
|
23
|
+
await fs.chmod(targetPath, mode);
|
|
24
|
+
} catch {
|
|
25
|
+
}
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if (handle) {
|
|
28
|
+
await handle.close().catch(() => void 0);
|
|
29
|
+
}
|
|
30
|
+
await fs.unlink(temporary).catch(() => void 0);
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
1
35
|
// src/attachments.ts
|
|
2
|
-
import { createHash as createHash2, randomUUID } from "crypto";
|
|
36
|
+
import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
|
|
3
37
|
import { constants as constants2 } from "fs";
|
|
4
38
|
import { lstat, mkdir, open as open2, rename, rm, writeFile } from "fs/promises";
|
|
5
|
-
import
|
|
39
|
+
import path2 from "path";
|
|
6
40
|
|
|
7
41
|
// src/image-files.ts
|
|
8
42
|
import { createHash } from "crypto";
|
|
@@ -44,189 +78,2306 @@ var SHA256 = /^[0-9a-f]{64}$/;
|
|
|
44
78
|
var MAX_BYTES = 32 * 1024 * 1024;
|
|
45
79
|
var BLOCK_BYTES = 64 * 1024;
|
|
46
80
|
var digest = (bytes) => createHash2("sha256").update(bytes).digest("hex");
|
|
47
|
-
var createAttachmentId = () => `codelia-attachment-${
|
|
81
|
+
var createAttachmentId = () => `codelia-attachment-${randomUUID2()}`;
|
|
48
82
|
var isAttachmentId = (id2) => ID.test(id2);
|
|
49
83
|
var FileAttachmentStore = class {
|
|
50
84
|
constructor(root, images) {
|
|
51
85
|
this.root = root;
|
|
52
86
|
this.images = images;
|
|
53
87
|
}
|
|
54
|
-
root;
|
|
55
|
-
images;
|
|
56
|
-
resolveImage = (ref) => this.images.resolve(ref);
|
|
57
|
-
async commit(sessionId, entries2) {
|
|
58
|
-
if (!entries2.length) return;
|
|
59
|
-
const batch =
|
|
60
|
-
const marker =
|
|
61
|
-
await mkdir(
|
|
62
|
-
recursive: true,
|
|
63
|
-
mode: 448
|
|
88
|
+
root;
|
|
89
|
+
images;
|
|
90
|
+
resolveImage = (ref) => this.images.resolve(ref);
|
|
91
|
+
async commit(sessionId, entries2) {
|
|
92
|
+
if (!entries2.length) return;
|
|
93
|
+
const batch = randomUUID2();
|
|
94
|
+
const marker = path2.join(this.root, "committed", batch);
|
|
95
|
+
await mkdir(path2.join(this.root, "committed"), {
|
|
96
|
+
recursive: true,
|
|
97
|
+
mode: 448
|
|
98
|
+
});
|
|
99
|
+
const created = [];
|
|
100
|
+
const createdImages = [];
|
|
101
|
+
try {
|
|
102
|
+
for (const { record: record2, bytes } of entries2) {
|
|
103
|
+
const { ref, imageRef } = record2;
|
|
104
|
+
if (!isAttachmentId(ref.attachment_id) || bytes.length !== ref.byte_size || bytes.length > MAX_BYTES || digest(bytes) !== ref.sha256) {
|
|
105
|
+
throw new Error("Invalid attachment original");
|
|
106
|
+
}
|
|
107
|
+
const dir = path2.join(this.root, ref.attachment_id);
|
|
108
|
+
await mkdir(dir, { mode: 448 });
|
|
109
|
+
created.push(dir);
|
|
110
|
+
const metadata = { ...record2, sessionId, batch };
|
|
111
|
+
if (imageRef) {
|
|
112
|
+
await this.images.saveAttachment(bytes, imageRef.media_type, {
|
|
113
|
+
artifactId: imageRef.artifact_id,
|
|
114
|
+
ownerSessionId: sessionId
|
|
115
|
+
});
|
|
116
|
+
createdImages.push(imageRef);
|
|
117
|
+
} else {
|
|
118
|
+
metadata.blocks = [];
|
|
119
|
+
for (let offset = 0; offset < bytes.length; offset += BLOCK_BYTES) {
|
|
120
|
+
metadata.blocks.push(
|
|
121
|
+
digest(bytes.subarray(offset, offset + BLOCK_BYTES))
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
await writeFile(path2.join(dir, "original"), bytes, {
|
|
125
|
+
flag: "wx",
|
|
126
|
+
mode: 384
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
await writeFile(
|
|
130
|
+
path2.join(dir, "metadata.json"),
|
|
131
|
+
JSON.stringify(metadata),
|
|
132
|
+
{ flag: "wx", mode: 384 }
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
await writeFile(`${marker}.pending`, "", { flag: "wx", mode: 384 });
|
|
136
|
+
await rename(`${marker}.pending`, marker);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
await Promise.allSettled([
|
|
139
|
+
...created.map((dir) => rm(dir, { force: true, recursive: true })),
|
|
140
|
+
...createdImages.map(
|
|
141
|
+
(ref) => this.images.discardUnpublishedAttachment(ref, sessionId)
|
|
142
|
+
),
|
|
143
|
+
rm(`${marker}.pending`, { force: true })
|
|
144
|
+
]);
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
async lookup(attachmentId, sessionId) {
|
|
149
|
+
const metadata = await this.metadata(attachmentId, sessionId);
|
|
150
|
+
if (!metadata) return null;
|
|
151
|
+
const { ref, imageRef } = metadata;
|
|
152
|
+
if (imageRef) {
|
|
153
|
+
await this.readImage(metadata);
|
|
154
|
+
} else {
|
|
155
|
+
const bytes = await readImageFileBounded(
|
|
156
|
+
path2.join(this.root, attachmentId, "original"),
|
|
157
|
+
ref.byte_size
|
|
158
|
+
);
|
|
159
|
+
if (bytes.length !== ref.byte_size || digest(bytes) !== ref.sha256)
|
|
160
|
+
throw new Error("Attachment original is corrupt");
|
|
161
|
+
}
|
|
162
|
+
return { ref, ...imageRef ? { imageRef } : {} };
|
|
163
|
+
}
|
|
164
|
+
async read(attachmentId, sessionId, offset, length) {
|
|
165
|
+
const metadata = await this.metadata(attachmentId, sessionId);
|
|
166
|
+
if (!metadata) throw new Error("Attachment unavailable in this session");
|
|
167
|
+
if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || length > 256 * 1024)
|
|
168
|
+
throw new Error("Invalid attachment byte range");
|
|
169
|
+
const end = Math.min(offset + length, metadata.ref.byte_size);
|
|
170
|
+
if (metadata.imageRef)
|
|
171
|
+
return (await this.readImage(metadata)).subarray(offset, end);
|
|
172
|
+
const file = await open2(
|
|
173
|
+
path2.join(this.root, attachmentId, "original"),
|
|
174
|
+
constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0) | (constants2.O_NONBLOCK ?? 0)
|
|
175
|
+
);
|
|
176
|
+
try {
|
|
177
|
+
const stat = await file.stat();
|
|
178
|
+
if (!stat.isFile() || stat.size !== metadata.ref.byte_size)
|
|
179
|
+
throw new Error("Attachment original is corrupt");
|
|
180
|
+
if (offset >= end) return Buffer.alloc(0);
|
|
181
|
+
const firstBlock = Math.floor(offset / BLOCK_BYTES);
|
|
182
|
+
const lastBlock = Math.ceil(end / BLOCK_BYTES);
|
|
183
|
+
const start = firstBlock * BLOCK_BYTES;
|
|
184
|
+
const bytes = Buffer.alloc(
|
|
185
|
+
Math.min(lastBlock * BLOCK_BYTES, stat.size) - start
|
|
186
|
+
);
|
|
187
|
+
let count = 0;
|
|
188
|
+
while (count < bytes.length) {
|
|
189
|
+
const result = await file.read(
|
|
190
|
+
bytes,
|
|
191
|
+
count,
|
|
192
|
+
bytes.length - count,
|
|
193
|
+
start + count
|
|
194
|
+
);
|
|
195
|
+
if (!result.bytesRead)
|
|
196
|
+
throw new Error("Attachment original is corrupt");
|
|
197
|
+
count += result.bytesRead;
|
|
198
|
+
}
|
|
199
|
+
for (let block = firstBlock; block < lastBlock; block++) {
|
|
200
|
+
const beg = (block - firstBlock) * BLOCK_BYTES;
|
|
201
|
+
if (metadata.blocks?.[block] !== digest(bytes.subarray(beg, beg + BLOCK_BYTES))) {
|
|
202
|
+
throw new Error("Attachment original is corrupt");
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return bytes.subarray(offset - start, end - start);
|
|
206
|
+
} finally {
|
|
207
|
+
await file.close();
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
async metadata(attachmentId, sessionId) {
|
|
211
|
+
if (!isAttachmentId(attachmentId)) return null;
|
|
212
|
+
const dir = path2.join(this.root, attachmentId);
|
|
213
|
+
try {
|
|
214
|
+
if (!(await lstat(dir)).isDirectory()) return null;
|
|
215
|
+
const metadata = JSON.parse(
|
|
216
|
+
(await readImageFileBounded(path2.join(dir, "metadata.json"), 64 * 1024)).toString()
|
|
217
|
+
);
|
|
218
|
+
const { ref, imageRef, blocks } = metadata;
|
|
219
|
+
if (metadata.sessionId !== sessionId || !UUID.test(metadata.batch) || ref?.attachment_id !== attachmentId)
|
|
220
|
+
return null;
|
|
221
|
+
if (!Number.isSafeInteger(ref.byte_size) || ref.byte_size < 0 || ref.byte_size > MAX_BYTES || !SHA256.test(ref.sha256) || typeof ref.media_type !== "string" || typeof ref.display_name !== "string")
|
|
222
|
+
throw new Error("Invalid attachment metadata");
|
|
223
|
+
if (!imageRef && (!Array.isArray(blocks) || blocks.length !== Math.ceil(ref.byte_size / BLOCK_BYTES)))
|
|
224
|
+
throw new Error("Invalid attachment block index");
|
|
225
|
+
const marker = path2.join(this.root, "committed", metadata.batch);
|
|
226
|
+
return (await lstat(marker)).isFile() ? metadata : null;
|
|
227
|
+
} catch (error) {
|
|
228
|
+
if (error.code === "ENOENT") return null;
|
|
229
|
+
throw error;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
async readImage({
|
|
233
|
+
ref,
|
|
234
|
+
imageRef,
|
|
235
|
+
sessionId
|
|
236
|
+
}) {
|
|
237
|
+
if (!imageRef || imageRef.sha256 !== ref.sha256 || imageRef.byte_size !== ref.byte_size || imageRef.media_type !== ref.media_type || imageRef.width !== ref.width || imageRef.height !== ref.height)
|
|
238
|
+
throw new Error("Invalid image attachment reference");
|
|
239
|
+
const { metadata, bytes } = await this.images.read(
|
|
240
|
+
imageRef.artifact_id,
|
|
241
|
+
sessionId
|
|
242
|
+
);
|
|
243
|
+
if (metadata.kind !== "attachment" || metadata.sha256 !== ref.sha256 || metadata.byte_size !== ref.byte_size || metadata.media_type !== ref.media_type || metadata.width !== ref.width || metadata.height !== ref.height)
|
|
244
|
+
throw new Error("Image attachment original is corrupt");
|
|
245
|
+
return bytes;
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
// src/auth-lock.ts
|
|
250
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
251
|
+
import { promises as fs3 } from "fs";
|
|
252
|
+
import path4 from "path";
|
|
253
|
+
import { setTimeout as delay } from "timers/promises";
|
|
254
|
+
|
|
255
|
+
// src/sqlite.ts
|
|
256
|
+
var openSqlite = async (filename) => {
|
|
257
|
+
if (process.versions.bun) {
|
|
258
|
+
const bunSqliteSpecifier = "bun:sqlite";
|
|
259
|
+
const { Database } = await import(bunSqliteSpecifier);
|
|
260
|
+
const db2 = new Database(filename, { create: true });
|
|
261
|
+
return {
|
|
262
|
+
close: () => db2.close(),
|
|
263
|
+
exec: (sql) => {
|
|
264
|
+
db2.exec(sql);
|
|
265
|
+
},
|
|
266
|
+
run: (sql, params = []) => {
|
|
267
|
+
db2.query(sql).run(...params);
|
|
268
|
+
},
|
|
269
|
+
get: (sql, params = []) => {
|
|
270
|
+
const row = db2.query(sql).get(...params);
|
|
271
|
+
return row ?? void 0;
|
|
272
|
+
},
|
|
273
|
+
all: (sql, params = []) => db2.query(sql).all(...params)
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
const betterSqliteSpecifier = "better-sqlite3";
|
|
277
|
+
const betterSqliteModule = await import(betterSqliteSpecifier);
|
|
278
|
+
const BetterSqlite3 = betterSqliteModule.default ?? betterSqliteModule;
|
|
279
|
+
const db = new BetterSqlite3(filename);
|
|
280
|
+
return {
|
|
281
|
+
close: () => db.close(),
|
|
282
|
+
exec: (sql) => {
|
|
283
|
+
db.exec(sql);
|
|
284
|
+
},
|
|
285
|
+
run: (sql, params = []) => {
|
|
286
|
+
db.prepare(sql).run(...params);
|
|
287
|
+
},
|
|
288
|
+
get: (sql, params = []) => {
|
|
289
|
+
const row = db.prepare(sql).get(...params);
|
|
290
|
+
return row ?? void 0;
|
|
291
|
+
},
|
|
292
|
+
all: (sql, params = []) => db.prepare(sql).all(...params)
|
|
293
|
+
};
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
// src/windows-acl.ts
|
|
297
|
+
import { execFile, execFileSync } from "child_process";
|
|
298
|
+
import { promises as fs2, lstatSync } from "fs";
|
|
299
|
+
import path3 from "path";
|
|
300
|
+
import { promisify } from "util";
|
|
301
|
+
var execFileAsync = promisify(execFile);
|
|
302
|
+
var resolveWindowsSystem32Dir = (env = process.env) => {
|
|
303
|
+
const root = (env.SystemRoot ?? env.WINDIR ?? "").trim() || "C:\\Windows";
|
|
304
|
+
if (!/^[A-Za-z]:\\/u.test(root) || root.includes("..")) {
|
|
305
|
+
throw new Error("unsafe_windows_credentials_acl: invalid_system_root");
|
|
306
|
+
}
|
|
307
|
+
return path3.win32.join(root, "System32");
|
|
308
|
+
};
|
|
309
|
+
var execOptions = {
|
|
310
|
+
windowsHide: true,
|
|
311
|
+
timeout: 5e3,
|
|
312
|
+
maxBuffer: 32 * 1024
|
|
313
|
+
};
|
|
314
|
+
var defaultRunner = async (exe, args, options) => execFileAsync(exe, [...args], { ...options, ...execOptions });
|
|
315
|
+
var aclScript = `
|
|
316
|
+
$ErrorActionPreference = 'Stop'
|
|
317
|
+
$target = $env:CODELIA_ACL_TARGET
|
|
318
|
+
$operation = $env:CODELIA_ACL_OPERATION
|
|
319
|
+
$legacy = $operation -eq 'legacy_file'
|
|
320
|
+
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
|
|
321
|
+
$system = [System.Security.Principal.SecurityIdentifier]::new('S-1-5-18')
|
|
322
|
+
$administrators = 'S-1-5-32-544'
|
|
323
|
+
$sections = [System.Security.AccessControl.AccessControlSections]'Owner, Access'
|
|
324
|
+
$inherit = [System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'
|
|
325
|
+
$inheritAces = [System.Security.AccessControl.AceFlags]'ContainerInherit, ObjectInherit'
|
|
326
|
+
$full = [System.Security.AccessControl.FileSystemRights]::FullControl
|
|
327
|
+
# Include generic read and execute if Windows left the generic bits unmapped.
|
|
328
|
+
$legacyReadMask = (
|
|
329
|
+
[int][System.Security.AccessControl.FileSystemRights]::ReadAndExecute -bor
|
|
330
|
+
[int][System.Security.AccessControl.FileSystemRights]::Synchronize -bor
|
|
331
|
+
[int]::MinValue -bor 0x20000000
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
function Get-TargetType([string]$file, [bool]$directory) {
|
|
335
|
+
try {
|
|
336
|
+
$attributes = [System.IO.File]::GetAttributes($file)
|
|
337
|
+
} catch [System.IO.FileNotFoundException], [System.IO.DirectoryNotFoundException] {
|
|
338
|
+
return 'missing'
|
|
339
|
+
}
|
|
340
|
+
if ($attributes -band [System.IO.FileAttributes]::ReparsePoint) { return 'reparse_point' }
|
|
341
|
+
if ([bool]($attributes -band [System.IO.FileAttributes]::Directory) -ne $directory) {
|
|
342
|
+
return 'unexpected_target_type'
|
|
343
|
+
}
|
|
344
|
+
return 'ok'
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function Test-CredentialAcl($acl, [bool]$directory) {
|
|
348
|
+
$descriptor = [System.Security.AccessControl.RawSecurityDescriptor]::new(
|
|
349
|
+
$acl.GetSecurityDescriptorBinaryForm(), 0)
|
|
350
|
+
if ($descriptor.Owner.Value -ne $user.Value) { return 'owner_mismatch' }
|
|
351
|
+
if ($null -eq $descriptor.DiscretionaryAcl) { return 'null_dacl' }
|
|
352
|
+
if ($directory -and -not $acl.AreAccessRulesProtected) { return 'unprotected_dacl' }
|
|
353
|
+
$hasUser = $false
|
|
354
|
+
foreach ($ace in $descriptor.DiscretionaryAcl) {
|
|
355
|
+
if ($legacy -and ($ace.AceType -eq [System.Security.AccessControl.AceType]::AccessDenied -or
|
|
356
|
+
$ace.AceFlags.HasFlag([System.Security.AccessControl.AceFlags]::InheritOnly))) { continue }
|
|
357
|
+
if ($ace.AceType -ne [System.Security.AccessControl.AceType]::AccessAllowed) {
|
|
358
|
+
return 'unexpected_ace_type'
|
|
359
|
+
}
|
|
360
|
+
$sid = $ace.SecurityIdentifier.Value
|
|
361
|
+
if ($legacy) {
|
|
362
|
+
# The old config root may have inherited Administrators and read grants.
|
|
363
|
+
if ($sid -ne $user.Value -and $sid -ne $system.Value -and $sid -ne $administrators -and
|
|
364
|
+
($ace.AccessMask -band (-bnot $legacyReadMask))) { return 'legacy_write_grant' }
|
|
365
|
+
continue
|
|
366
|
+
}
|
|
367
|
+
if ($sid -ne $user.Value -and $sid -ne $system.Value) { return 'unexpected_principals' }
|
|
368
|
+
if ($directory -and ($ace.AccessMask -ne [int]$full -or $ace.AceFlags -ne $inheritAces)) {
|
|
369
|
+
return 'unexpected_directory_ace'
|
|
370
|
+
}
|
|
371
|
+
if ($sid -eq $user.Value) { $hasUser = $true }
|
|
372
|
+
}
|
|
373
|
+
if (-not $legacy -and -not $hasUser) { return 'missing_user_grant' }
|
|
374
|
+
return 'ok'
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
if ($operation -eq 'ensure_directory') {
|
|
378
|
+
$targetType = Get-TargetType $target $true
|
|
379
|
+
if ($targetType -ne 'ok') { $targetType; exit }
|
|
380
|
+
$acl = [System.IO.Directory]::GetAccessControl($target, $sections)
|
|
381
|
+
$result = Test-CredentialAcl $acl $true
|
|
382
|
+
if ($result -eq 'ok' -or $result -eq 'owner_mismatch') { $result; exit }
|
|
383
|
+
|
|
384
|
+
$privateAcl = [System.Security.AccessControl.DirectorySecurity]::new()
|
|
385
|
+
$privateAcl.SetAccessRuleProtection($true, $false)
|
|
386
|
+
$propagate = [System.Security.AccessControl.PropagationFlags]::None
|
|
387
|
+
$allow = [System.Security.AccessControl.AccessControlType]::Allow
|
|
388
|
+
$privateAcl.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new(
|
|
389
|
+
$user, $full, $inherit, $propagate, $allow))
|
|
390
|
+
if ($user.Value -ne $system.Value) {
|
|
391
|
+
$privateAcl.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new(
|
|
392
|
+
$system, $full, $inherit, $propagate, $allow))
|
|
393
|
+
}
|
|
394
|
+
[System.IO.Directory]::SetAccessControl($target, $privateAcl)
|
|
395
|
+
$targetType = Get-TargetType $target $true
|
|
396
|
+
if ($targetType -ne 'ok') { $targetType; exit }
|
|
397
|
+
Test-CredentialAcl ([System.IO.Directory]::GetAccessControl($target, $sections)) $true
|
|
398
|
+
exit
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
if ($operation -eq 'file') {
|
|
402
|
+
$parent = [System.IO.Path]::GetDirectoryName($target)
|
|
403
|
+
$parentType = Get-TargetType $parent $true
|
|
404
|
+
if ($parentType -ne 'ok') { $parentType; exit }
|
|
405
|
+
$parentAcl = Test-CredentialAcl ([System.IO.Directory]::GetAccessControl($parent, $sections)) $true
|
|
406
|
+
if ($parentAcl -ne 'ok') { $parentAcl; exit }
|
|
407
|
+
}
|
|
408
|
+
try {
|
|
409
|
+
$targetType = Get-TargetType $target $false
|
|
410
|
+
if ($targetType -ne 'ok') { $targetType; exit }
|
|
411
|
+
Test-CredentialAcl ([System.IO.File]::GetAccessControl($target, $sections)) $false
|
|
412
|
+
} catch [System.IO.FileNotFoundException], [System.IO.DirectoryNotFoundException] {
|
|
413
|
+
'missing'
|
|
414
|
+
}
|
|
415
|
+
`;
|
|
416
|
+
var encodedAclScript = Buffer.from(aclScript, "utf16le").toString("base64");
|
|
417
|
+
function aclCommand(target, operation, env) {
|
|
418
|
+
const system32 = resolveWindowsSystem32Dir(env);
|
|
419
|
+
return {
|
|
420
|
+
exe: path3.win32.join(
|
|
421
|
+
system32,
|
|
422
|
+
"WindowsPowerShell",
|
|
423
|
+
"v1.0",
|
|
424
|
+
"powershell.exe"
|
|
425
|
+
),
|
|
426
|
+
args: [
|
|
427
|
+
"-NoProfile",
|
|
428
|
+
"-NonInteractive",
|
|
429
|
+
"-EncodedCommand",
|
|
430
|
+
encodedAclScript
|
|
431
|
+
],
|
|
432
|
+
options: {
|
|
433
|
+
cwd: system32,
|
|
434
|
+
env: {
|
|
435
|
+
...env,
|
|
436
|
+
CODELIA_ACL_TARGET: path3.win32.resolve(target),
|
|
437
|
+
CODELIA_ACL_OPERATION: operation
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
var aclFailures = /* @__PURE__ */ new Set([
|
|
443
|
+
"missing",
|
|
444
|
+
"owner_mismatch",
|
|
445
|
+
"reparse_point",
|
|
446
|
+
"unexpected_target_type",
|
|
447
|
+
"null_dacl",
|
|
448
|
+
"unprotected_dacl",
|
|
449
|
+
"unexpected_ace_type",
|
|
450
|
+
"unexpected_principals",
|
|
451
|
+
"legacy_write_grant",
|
|
452
|
+
"unexpected_directory_ace",
|
|
453
|
+
"missing_user_grant"
|
|
454
|
+
]);
|
|
455
|
+
function verifyAclResult(stdout, operation) {
|
|
456
|
+
const result = stdout.trim();
|
|
457
|
+
if (result === "ok") return true;
|
|
458
|
+
if (operation !== "ensure_directory" && result === "missing") return false;
|
|
459
|
+
const reason = aclFailures.has(result) ? result : "invalid_probe_result";
|
|
460
|
+
throw new Error(`unsafe_windows_credentials_acl: ${reason}`);
|
|
461
|
+
}
|
|
462
|
+
async function runAclCommand(target, operation, runner, env) {
|
|
463
|
+
const { exe, args, options } = aclCommand(target, operation, env);
|
|
464
|
+
let stdout;
|
|
465
|
+
try {
|
|
466
|
+
({ stdout } = await runner(exe, args, options));
|
|
467
|
+
} catch {
|
|
468
|
+
throw new Error("unsafe_windows_credentials_acl: acl_probe_failed");
|
|
469
|
+
}
|
|
470
|
+
return verifyAclResult(stdout, operation);
|
|
471
|
+
}
|
|
472
|
+
var enforceWindowsOwnerOnlyDacl = async (dirPath, runner = defaultRunner, env = process.env) => {
|
|
473
|
+
await runAclCommand(dirPath, "ensure_directory", runner, env);
|
|
474
|
+
};
|
|
475
|
+
var isMissing = (error) => error?.code === "ENOENT";
|
|
476
|
+
var verifyWindowsCredentialFileAcl = async (filePath, legacy = false) => {
|
|
477
|
+
if (process.platform !== "win32") return true;
|
|
478
|
+
try {
|
|
479
|
+
await fs2.lstat(filePath);
|
|
480
|
+
} catch (error) {
|
|
481
|
+
if (isMissing(error)) return false;
|
|
482
|
+
throw error;
|
|
483
|
+
}
|
|
484
|
+
return runAclCommand(
|
|
485
|
+
filePath,
|
|
486
|
+
legacy ? "legacy_file" : "file",
|
|
487
|
+
defaultRunner,
|
|
488
|
+
process.env
|
|
489
|
+
);
|
|
490
|
+
};
|
|
491
|
+
var verifyWindowsCredentialFileAclSync = (filePath, legacy = false) => {
|
|
492
|
+
if (process.platform !== "win32") return true;
|
|
493
|
+
try {
|
|
494
|
+
lstatSync(filePath);
|
|
495
|
+
} catch (error) {
|
|
496
|
+
if (isMissing(error)) return false;
|
|
497
|
+
throw error;
|
|
498
|
+
}
|
|
499
|
+
const operation = legacy ? "legacy_file" : "file";
|
|
500
|
+
const { exe, args, options } = aclCommand(filePath, operation, process.env);
|
|
501
|
+
let stdout;
|
|
502
|
+
try {
|
|
503
|
+
stdout = execFileSync(exe, args, {
|
|
504
|
+
...options,
|
|
505
|
+
...execOptions,
|
|
506
|
+
encoding: "utf8",
|
|
507
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
508
|
+
});
|
|
509
|
+
} catch {
|
|
510
|
+
throw new Error("unsafe_windows_credentials_acl: acl_probe_failed");
|
|
511
|
+
}
|
|
512
|
+
return verifyAclResult(stdout, operation);
|
|
513
|
+
};
|
|
514
|
+
var ensureCredentialsDirectory = async (credentialsDir, options) => {
|
|
515
|
+
const platform = options?.platform ?? process.platform;
|
|
516
|
+
await fs2.mkdir(credentialsDir, { recursive: true, mode: 448 });
|
|
517
|
+
if (platform === "win32") {
|
|
518
|
+
await enforceWindowsOwnerOnlyDacl(credentialsDir, options?.windowsRunner);
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
const info = await fs2.lstat(credentialsDir);
|
|
522
|
+
if (!info.isDirectory() || info.uid !== process.geteuid?.()) {
|
|
523
|
+
throw new Error("unsafe_credentials_directory");
|
|
524
|
+
}
|
|
525
|
+
if ((info.mode & 511) !== 448) await fs2.chmod(credentialsDir, 448);
|
|
526
|
+
};
|
|
527
|
+
|
|
528
|
+
// src/auth-lock.ts
|
|
529
|
+
var DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 3e4;
|
|
530
|
+
var DEFAULT_AUTH_LOCK_TIMEOUT_MS = 35e3;
|
|
531
|
+
var DEFAULT_POLL_MS = 25;
|
|
532
|
+
var inProcessQueues = /* @__PURE__ */ new Map();
|
|
533
|
+
var authLockPathFor = (dir) => path4.join(dir, ".auth-store-lock.sqlite");
|
|
534
|
+
var isMissing2 = (error) => error?.code === "ENOENT";
|
|
535
|
+
var lstatIfPresent = (file) => fs3.lstat(file).catch((error) => {
|
|
536
|
+
if (!isMissing2(error)) throw error;
|
|
537
|
+
return void 0;
|
|
538
|
+
});
|
|
539
|
+
var verifyLockFile = async (file) => {
|
|
540
|
+
const info = await lstatIfPresent(file);
|
|
541
|
+
if (!info) return;
|
|
542
|
+
const uid = process.geteuid?.();
|
|
543
|
+
if (!info.isFile() || info.size === 0 || uid !== void 0 && (info.uid !== uid || (info.mode & 18) !== 0)) {
|
|
544
|
+
throw new Error("unsafe_auth_store_lock");
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
var initializeLockFile = async (lockPath) => {
|
|
548
|
+
if (await lstatIfPresent(lockPath)) return;
|
|
549
|
+
const temporary = `${lockPath}.${randomUUID3()}.tmp`;
|
|
550
|
+
try {
|
|
551
|
+
const file = await fs3.open(temporary, "wx", 384);
|
|
552
|
+
await file.close();
|
|
553
|
+
const db = await openSqlite(temporary);
|
|
554
|
+
try {
|
|
555
|
+
db.exec("PRAGMA user_version = 1");
|
|
556
|
+
} finally {
|
|
557
|
+
db.close();
|
|
558
|
+
}
|
|
559
|
+
try {
|
|
560
|
+
await fs3.link(temporary, lockPath);
|
|
561
|
+
} catch (error) {
|
|
562
|
+
if (error.code !== "EEXIST") throw error;
|
|
563
|
+
}
|
|
564
|
+
} finally {
|
|
565
|
+
await fs3.unlink(temporary).catch(() => void 0);
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
var isSqliteBusy = (error) => {
|
|
569
|
+
const code = error?.code;
|
|
570
|
+
if (code === "SQLITE_BUSY" || code === "SQLITE_LOCKED") return true;
|
|
571
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
572
|
+
return /database is locked|SQLITE_BUSY/i.test(message);
|
|
573
|
+
};
|
|
574
|
+
var openAuthLock = async (lockPath, timeoutMs, pollMs) => {
|
|
575
|
+
await ensureCredentialsDirectory(path4.dirname(lockPath));
|
|
576
|
+
await initializeLockFile(lockPath);
|
|
577
|
+
await verifyLockFile(lockPath);
|
|
578
|
+
if (process.platform === "win32") {
|
|
579
|
+
if (!await verifyWindowsCredentialFileAcl(lockPath)) {
|
|
580
|
+
throw new Error("unsafe_auth_store_lock");
|
|
581
|
+
}
|
|
582
|
+
await Promise.all(
|
|
583
|
+
["-journal", "-wal", "-shm"].map(
|
|
584
|
+
(suffix) => verifyWindowsCredentialFileAcl(lockPath + suffix)
|
|
585
|
+
)
|
|
586
|
+
);
|
|
587
|
+
}
|
|
588
|
+
const db = await openSqlite(lockPath);
|
|
589
|
+
const deadline = performance.now() + timeoutMs;
|
|
590
|
+
try {
|
|
591
|
+
db.exec("PRAGMA busy_timeout = 0");
|
|
592
|
+
for (; ; ) {
|
|
593
|
+
try {
|
|
594
|
+
db.exec("BEGIN IMMEDIATE");
|
|
595
|
+
return db;
|
|
596
|
+
} catch (error) {
|
|
597
|
+
if (!isSqliteBusy(error) || performance.now() >= deadline) {
|
|
598
|
+
throw error;
|
|
599
|
+
}
|
|
600
|
+
await delay(pollMs);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
} catch (error) {
|
|
604
|
+
db.close();
|
|
605
|
+
throw error;
|
|
606
|
+
}
|
|
607
|
+
};
|
|
608
|
+
var enqueueInProcess = async (key, fn) => {
|
|
609
|
+
const previous = inProcessQueues.get(key) ?? Promise.resolve();
|
|
610
|
+
const next = previous.then(fn, fn);
|
|
611
|
+
const settled = next.then(
|
|
612
|
+
() => void 0,
|
|
613
|
+
() => void 0
|
|
614
|
+
);
|
|
615
|
+
inProcessQueues.set(key, settled);
|
|
616
|
+
try {
|
|
617
|
+
return await next;
|
|
618
|
+
} finally {
|
|
619
|
+
if (inProcessQueues.get(key) === settled) inProcessQueues.delete(key);
|
|
620
|
+
}
|
|
621
|
+
};
|
|
622
|
+
var withAuthStoreLock = (lockPath, fn, options = {}) => {
|
|
623
|
+
const resolved = path4.resolve(lockPath);
|
|
624
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_AUTH_LOCK_TIMEOUT_MS;
|
|
625
|
+
const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
|
|
626
|
+
return enqueueInProcess(resolved, async () => {
|
|
627
|
+
const db = await openAuthLock(resolved, timeoutMs, pollMs);
|
|
628
|
+
try {
|
|
629
|
+
return await fn();
|
|
630
|
+
} finally {
|
|
631
|
+
try {
|
|
632
|
+
db.exec("ROLLBACK");
|
|
633
|
+
} catch {
|
|
634
|
+
}
|
|
635
|
+
db.close();
|
|
636
|
+
}
|
|
637
|
+
});
|
|
638
|
+
};
|
|
639
|
+
|
|
640
|
+
// src/macos-keychain.ts
|
|
641
|
+
import { execFile as execFile2, execFileSync as execFileSync2, spawn } from "child_process";
|
|
642
|
+
import { createHash as createHash3 } from "crypto";
|
|
643
|
+
import { accessSync, constants as constants3, realpathSync } from "fs";
|
|
644
|
+
import os from "os";
|
|
645
|
+
import path5 from "path";
|
|
646
|
+
var CODELIA_AUTH_KEYCHAIN_SERVICE = "codelia.auth";
|
|
647
|
+
var CODELIA_MCP_AUTH_KEYCHAIN_SERVICE = "codelia.mcp-auth";
|
|
648
|
+
var DEFAULT_SECURITY_PATH = "/usr/bin/security";
|
|
649
|
+
var DEFAULT_ASYNC_TIMEOUT_MS = 5e3;
|
|
650
|
+
var DEFAULT_SYNC_TIMEOUT_MS = 2e3;
|
|
651
|
+
var AUTHORIZATION_TIMEOUT_MS = 12e4;
|
|
652
|
+
var MAX_SECURITY_BUFFER = 8 * 1024 * 1024;
|
|
653
|
+
var SECURITY_INTERACTIVE_MAX_LINE_BYTES = 4096;
|
|
654
|
+
var MAX_STDERR_CAPTURE_BYTES = 16384;
|
|
655
|
+
var MAX_CHUNKS = 64;
|
|
656
|
+
var SWEEP_CONSECUTIVE_MISS_LIMIT = 2;
|
|
657
|
+
var MAX_SNAPSHOT_ATTEMPTS = 3;
|
|
658
|
+
var CHUNK_RAW_BYTES = 1800;
|
|
659
|
+
var MAX_KEYCHAIN_PAYLOAD_BYTES = MAX_CHUNKS * CHUNK_RAW_BYTES;
|
|
660
|
+
var CHUNK_PREFIX = "cb1:";
|
|
661
|
+
var GEN_POINTER_PREFIX = "cb2:";
|
|
662
|
+
var SAFE_TOKEN_RE = /^[A-Za-z0-9._:#-]+$/;
|
|
663
|
+
var KeychainError = class extends Error {
|
|
664
|
+
code;
|
|
665
|
+
constructor(code, message) {
|
|
666
|
+
super(message);
|
|
667
|
+
this.name = "KeychainError";
|
|
668
|
+
this.code = code;
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
var canonicalDirForHash = (configDir) => {
|
|
672
|
+
const resolved = path5.resolve(configDir);
|
|
673
|
+
try {
|
|
674
|
+
return realpathSync(resolved);
|
|
675
|
+
} catch {
|
|
676
|
+
return resolved;
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
var keychainAccountForConfigDir = (configDir) => {
|
|
680
|
+
const digest2 = createHash3("sha256").update(canonicalDirForHash(configDir)).digest("hex").slice(0, 16);
|
|
681
|
+
return `codelia-${digest2}`;
|
|
682
|
+
};
|
|
683
|
+
var validateKeychainToken = (label2, value) => {
|
|
684
|
+
if (!value || !SAFE_TOKEN_RE.test(value)) {
|
|
685
|
+
throw new KeychainError(
|
|
686
|
+
"keychain_error",
|
|
687
|
+
`Invalid Keychain ${label2} identifier`
|
|
688
|
+
);
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
var chunkServiceName = (service, index) => index === 0 ? service : `${service}#${index}`;
|
|
692
|
+
var genChunkServiceName = (service, gen, index) => `${service}#g:${gen}:${index}`;
|
|
693
|
+
var encodePayloadChunks = (value) => {
|
|
694
|
+
const raw = Buffer.from(value, "utf8");
|
|
695
|
+
const total = Math.max(1, Math.ceil(raw.length / CHUNK_RAW_BYTES));
|
|
696
|
+
if (total > MAX_CHUNKS) {
|
|
697
|
+
throw new KeychainError(
|
|
698
|
+
"keychain_error",
|
|
699
|
+
`Keychain payload exceeds maximum size (${MAX_KEYCHAIN_PAYLOAD_BYTES} bytes)`
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
const chunks = [];
|
|
703
|
+
for (let i = 0; i < total; i += 1) {
|
|
704
|
+
const slice = raw.subarray(
|
|
705
|
+
i * CHUNK_RAW_BYTES,
|
|
706
|
+
Math.min(raw.length, (i + 1) * CHUNK_RAW_BYTES)
|
|
707
|
+
);
|
|
708
|
+
chunks.push(`${CHUNK_PREFIX}${total}:${slice.toString("base64")}`);
|
|
709
|
+
}
|
|
710
|
+
return chunks;
|
|
711
|
+
};
|
|
712
|
+
var FIXED_GEN_SLOTS = ["a", "b"];
|
|
713
|
+
var parseGenPointer = (raw) => {
|
|
714
|
+
if (!raw.startsWith(GEN_POINTER_PREFIX)) return null;
|
|
715
|
+
const parts = raw.slice(GEN_POINTER_PREFIX.length).split(":");
|
|
716
|
+
if (parts.length !== 2) {
|
|
717
|
+
throw new KeychainError(
|
|
718
|
+
"keychain_error",
|
|
719
|
+
"Corrupt Keychain generation pointer"
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
const [gen, totalStr] = parts;
|
|
723
|
+
const countAndDigest = /^([1-9][0-9]*)(?:\.([a-f0-9]{64}))?$/.exec(totalStr);
|
|
724
|
+
const total = Number(countAndDigest?.[1]);
|
|
725
|
+
if (!/^(?:a|b|[0-9a-f]{8,16})$/.test(gen) || !Number.isInteger(total) || total < 1 || total > MAX_CHUNKS) {
|
|
726
|
+
throw new KeychainError(
|
|
727
|
+
"keychain_error",
|
|
728
|
+
"Corrupt Keychain generation pointer metadata"
|
|
729
|
+
);
|
|
730
|
+
}
|
|
731
|
+
return { gen, total, digest: countAndDigest?.[2] };
|
|
732
|
+
};
|
|
733
|
+
var parseChunkEnvelope = (raw) => {
|
|
734
|
+
if (!raw.startsWith(CHUNK_PREFIX)) return null;
|
|
735
|
+
const rest = raw.slice(CHUNK_PREFIX.length);
|
|
736
|
+
const sep = rest.indexOf(":");
|
|
737
|
+
if (sep <= 0) {
|
|
738
|
+
throw new KeychainError(
|
|
739
|
+
"keychain_error",
|
|
740
|
+
"Corrupt Keychain chunk envelope"
|
|
741
|
+
);
|
|
742
|
+
}
|
|
743
|
+
const total = Number.parseInt(rest.slice(0, sep), 10);
|
|
744
|
+
const base64 = rest.slice(sep + 1);
|
|
745
|
+
if (!Number.isInteger(total) || total < 1 || total > MAX_CHUNKS || !/^[A-Za-z0-9+/=]*$/.test(base64)) {
|
|
746
|
+
throw new KeychainError(
|
|
747
|
+
"keychain_error",
|
|
748
|
+
"Corrupt Keychain chunk metadata"
|
|
749
|
+
);
|
|
750
|
+
}
|
|
751
|
+
return { total, base64 };
|
|
752
|
+
};
|
|
753
|
+
var extractValidatedChunkBase64 = (rawChunk, expectedTotal, index, service) => {
|
|
754
|
+
if (rawChunk === null) {
|
|
755
|
+
throw new KeychainError(
|
|
756
|
+
"keychain_error",
|
|
757
|
+
`Missing Keychain chunk ${index + 1}/${expectedTotal} for ${service}`
|
|
758
|
+
);
|
|
759
|
+
}
|
|
760
|
+
const parsed = parseChunkEnvelope(rawChunk);
|
|
761
|
+
if (!parsed || parsed.total !== expectedTotal) {
|
|
762
|
+
throw new KeychainError(
|
|
763
|
+
"keychain_error",
|
|
764
|
+
`Inconsistent Keychain chunk ${index + 1}/${expectedTotal} for ${service}`
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
return parsed.base64;
|
|
768
|
+
};
|
|
769
|
+
var decodeBase64Chunks = (parts) => Buffer.from(parts.join(""), "base64").toString("utf8");
|
|
770
|
+
var payloadDigest = (value) => createHash3("sha256").update(value, "utf8").digest("hex");
|
|
771
|
+
var decodeLegacyOrSingleValue = (trimmed) => {
|
|
772
|
+
if (trimmed.startsWith("{")) return trimmed;
|
|
773
|
+
if (/^[0-9a-fA-F]+$/.test(trimmed) && trimmed.length % 2 === 0) {
|
|
774
|
+
const decoded = Buffer.from(trimmed, "hex").toString("utf8");
|
|
775
|
+
if (decoded.startsWith("{")) return decoded;
|
|
776
|
+
}
|
|
777
|
+
throw new KeychainError(
|
|
778
|
+
"keychain_error",
|
|
779
|
+
"Keychain item contains unrecognized credential format"
|
|
780
|
+
);
|
|
781
|
+
};
|
|
782
|
+
function* readChunkedSnapshot(service, root) {
|
|
783
|
+
if (root === null) return { value: null };
|
|
784
|
+
const pointer = parseGenPointer(root);
|
|
785
|
+
const first = pointer ? null : parseChunkEnvelope(root);
|
|
786
|
+
if (!pointer && !first) return { value: decodeLegacyOrSingleValue(root) };
|
|
787
|
+
if (first?.total === 1) return { value: decodeBase64Chunks([first.base64]) };
|
|
788
|
+
const total = pointer?.total ?? first?.total ?? 0;
|
|
789
|
+
const parts = first ? [first.base64] : [];
|
|
790
|
+
let result;
|
|
791
|
+
try {
|
|
792
|
+
for (let i = parts.length; i < total; i += 1) {
|
|
793
|
+
const rawChunk = yield pointer ? genChunkServiceName(service, pointer.gen, i) : chunkServiceName(service, i);
|
|
794
|
+
parts.push(extractValidatedChunkBase64(rawChunk, total, i, service));
|
|
795
|
+
}
|
|
796
|
+
const value = decodeBase64Chunks(parts);
|
|
797
|
+
if (pointer?.digest && pointer.digest !== payloadDigest(value)) {
|
|
798
|
+
throw new KeychainError(
|
|
799
|
+
"keychain_error",
|
|
800
|
+
"Inconsistent Keychain payload"
|
|
801
|
+
);
|
|
802
|
+
}
|
|
803
|
+
result = { value };
|
|
804
|
+
} catch (error) {
|
|
805
|
+
result = { error };
|
|
806
|
+
}
|
|
807
|
+
const currentRoot = yield service;
|
|
808
|
+
if (currentRoot !== root) return { nextRoot: currentRoot };
|
|
809
|
+
if ("error" in result) throw result.error;
|
|
810
|
+
return result;
|
|
811
|
+
}
|
|
812
|
+
var isNotFoundOutput = (code, stderr) => code === 44 || /could not be found in the keychain|SecKeychainSearchCopyNext: The specified item could not be found/i.test(
|
|
813
|
+
stderr
|
|
814
|
+
);
|
|
815
|
+
var classifySecurityFailure = (code, stderr, timedOut = false) => {
|
|
816
|
+
if (timedOut) {
|
|
817
|
+
return new KeychainError(
|
|
818
|
+
"keychain_error",
|
|
819
|
+
"macOS Keychain operation timed out. Run `codelia auth authorize-keychain` from a local terminal, then retry."
|
|
820
|
+
);
|
|
821
|
+
}
|
|
822
|
+
if (code === 36 || /User interaction is not allowed|errSecInteractionNotAllowed|keychain is locked/i.test(
|
|
823
|
+
stderr
|
|
824
|
+
)) {
|
|
825
|
+
return new KeychainError(
|
|
826
|
+
"keychain_locked",
|
|
827
|
+
"macOS login Keychain is locked; run `security unlock-keychain ~/Library/Keychains/login.keychain-db`"
|
|
828
|
+
);
|
|
829
|
+
}
|
|
830
|
+
if (code === 128 || /User canceled the operation|errSecUserCanceled|errSecAuthFailed|The user name or passphrase you entered is not correct/i.test(
|
|
831
|
+
stderr
|
|
832
|
+
)) {
|
|
833
|
+
return new KeychainError(
|
|
834
|
+
"keychain_access_denied",
|
|
835
|
+
"macOS Keychain denied access; run `codelia auth authorize-keychain` from a local terminal"
|
|
836
|
+
);
|
|
837
|
+
}
|
|
838
|
+
return new KeychainError("keychain_error", "macOS Keychain operation failed");
|
|
839
|
+
};
|
|
840
|
+
var securityEnv = () => ({
|
|
841
|
+
HOME: os.homedir(),
|
|
842
|
+
PATH: "/usr/bin:/bin",
|
|
843
|
+
...process.env.USER ? { USER: process.env.USER } : {},
|
|
844
|
+
...process.env.LOGNAME ? { LOGNAME: process.env.LOGNAME } : {}
|
|
845
|
+
});
|
|
846
|
+
var MacOsKeychainClient = class {
|
|
847
|
+
securityBinary;
|
|
848
|
+
hasCustomBinary;
|
|
849
|
+
constructor(options) {
|
|
850
|
+
const custom = options?.securityPath ?? options?.helperPath;
|
|
851
|
+
this.securityBinary = custom ?? DEFAULT_SECURITY_PATH;
|
|
852
|
+
this.hasCustomBinary = Boolean(custom);
|
|
853
|
+
}
|
|
854
|
+
resolveBinary() {
|
|
855
|
+
if (!this.hasCustomBinary && process.platform !== "darwin") {
|
|
856
|
+
return null;
|
|
857
|
+
}
|
|
858
|
+
if (!this.hasCustomBinary && process.env.CODELIA_TEST_KEYCHAIN_DISABLED === "1") {
|
|
859
|
+
throw new KeychainError(
|
|
860
|
+
"keychain_unavailable",
|
|
861
|
+
"macOS Keychain is disabled for tests"
|
|
862
|
+
);
|
|
863
|
+
}
|
|
864
|
+
try {
|
|
865
|
+
accessSync(this.securityBinary, constants3.X_OK);
|
|
866
|
+
return this.securityBinary;
|
|
867
|
+
} catch {
|
|
868
|
+
return null;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
requireBinary() {
|
|
872
|
+
const binary = this.resolveBinary();
|
|
873
|
+
if (!binary) {
|
|
874
|
+
throw new KeychainError(
|
|
875
|
+
"keychain_unavailable",
|
|
876
|
+
process.platform !== "darwin" ? "unsupported_platform" : "macOS /usr/bin/security is unavailable"
|
|
877
|
+
);
|
|
878
|
+
}
|
|
879
|
+
return binary;
|
|
880
|
+
}
|
|
881
|
+
runArgsAsync(args, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
|
|
882
|
+
const binary = this.requireBinary();
|
|
883
|
+
return new Promise((resolve, reject) => {
|
|
884
|
+
execFile2(
|
|
885
|
+
binary,
|
|
886
|
+
[...args],
|
|
887
|
+
{
|
|
888
|
+
cwd: "/",
|
|
889
|
+
env: securityEnv(),
|
|
890
|
+
timeout: timeoutMs,
|
|
891
|
+
killSignal: "SIGKILL",
|
|
892
|
+
maxBuffer: MAX_SECURITY_BUFFER,
|
|
893
|
+
encoding: "utf8"
|
|
894
|
+
},
|
|
895
|
+
(error, stdout, stderr) => {
|
|
896
|
+
if (!error) {
|
|
897
|
+
resolve({ code: 0, stdout, stderr });
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
const timedOut = Boolean(error.killed && error.code === null);
|
|
901
|
+
const exitCode = typeof error.code === "number" ? error.code : null;
|
|
902
|
+
if (timedOut) {
|
|
903
|
+
reject(classifySecurityFailure(exitCode, stderr ?? "", true));
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
resolve({
|
|
907
|
+
code: exitCode ?? 1,
|
|
908
|
+
stdout: stdout ?? "",
|
|
909
|
+
stderr: stderr ?? error.message
|
|
910
|
+
});
|
|
911
|
+
}
|
|
912
|
+
);
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
runInteractiveBatchAsync(commands, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
|
|
916
|
+
const binary = this.requireBinary();
|
|
917
|
+
const payload = `${commands.join("\n")}
|
|
918
|
+
`;
|
|
919
|
+
for (const line of commands) {
|
|
920
|
+
if (Buffer.byteLength(line, "utf8") + 1 >= SECURITY_INTERACTIVE_MAX_LINE_BYTES) {
|
|
921
|
+
throw new KeychainError(
|
|
922
|
+
"keychain_error",
|
|
923
|
+
"Keychain batch command exceeds 4096-byte security -i line limit"
|
|
924
|
+
);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
return new Promise((resolve, reject) => {
|
|
928
|
+
const child = spawn(binary, ["-i"], {
|
|
929
|
+
cwd: "/",
|
|
930
|
+
env: securityEnv(),
|
|
931
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
932
|
+
});
|
|
933
|
+
let stderr = "";
|
|
934
|
+
let timedOut = false;
|
|
935
|
+
const timer = setTimeout(() => {
|
|
936
|
+
timedOut = true;
|
|
937
|
+
child.kill("SIGKILL");
|
|
938
|
+
}, timeoutMs);
|
|
939
|
+
child.stdout.on("data", () => void 0);
|
|
940
|
+
child.stderr.on("data", (chunk) => {
|
|
941
|
+
if (stderr.length < MAX_STDERR_CAPTURE_BYTES) {
|
|
942
|
+
stderr += chunk.toString("utf8");
|
|
943
|
+
}
|
|
944
|
+
});
|
|
945
|
+
child.once("error", () => {
|
|
946
|
+
clearTimeout(timer);
|
|
947
|
+
reject(
|
|
948
|
+
new KeychainError(
|
|
949
|
+
"keychain_unavailable",
|
|
950
|
+
"Failed to launch macOS /usr/bin/security"
|
|
951
|
+
)
|
|
952
|
+
);
|
|
953
|
+
});
|
|
954
|
+
child.once("close", (code) => {
|
|
955
|
+
clearTimeout(timer);
|
|
956
|
+
if (timedOut) {
|
|
957
|
+
reject(classifySecurityFailure(code, stderr, true));
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
if (code !== 0) {
|
|
961
|
+
reject(classifySecurityFailure(code, stderr, false));
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
resolve();
|
|
965
|
+
});
|
|
966
|
+
child.stdin.on("error", () => void 0);
|
|
967
|
+
child.stdin.end(payload);
|
|
968
|
+
});
|
|
969
|
+
}
|
|
970
|
+
findRawAsync(service, account, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
|
|
971
|
+
validateKeychainToken("service", service);
|
|
972
|
+
validateKeychainToken("account", account);
|
|
973
|
+
return this.runArgsAsync(
|
|
974
|
+
["find-generic-password", "-w", "-a", account, "-s", service],
|
|
975
|
+
timeoutMs
|
|
976
|
+
).then(({ code, stdout, stderr }) => {
|
|
977
|
+
if (code === 0) return stdout.replace(/\r?\n$/, "");
|
|
978
|
+
if (isNotFoundOutput(code, stderr)) return null;
|
|
979
|
+
throw classifySecurityFailure(code, stderr);
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
findRawSync(service, account, timeoutMs = DEFAULT_SYNC_TIMEOUT_MS) {
|
|
983
|
+
validateKeychainToken("service", service);
|
|
984
|
+
validateKeychainToken("account", account);
|
|
985
|
+
const binary = this.requireBinary();
|
|
986
|
+
try {
|
|
987
|
+
const stdout = execFileSync2(
|
|
988
|
+
binary,
|
|
989
|
+
["find-generic-password", "-w", "-a", account, "-s", service],
|
|
990
|
+
{
|
|
991
|
+
cwd: "/",
|
|
992
|
+
env: securityEnv(),
|
|
993
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
994
|
+
timeout: timeoutMs,
|
|
995
|
+
killSignal: "SIGKILL",
|
|
996
|
+
maxBuffer: MAX_SECURITY_BUFFER,
|
|
997
|
+
encoding: "utf8"
|
|
998
|
+
}
|
|
999
|
+
);
|
|
1000
|
+
return stdout.replace(/\r?\n$/, "");
|
|
1001
|
+
} catch (error) {
|
|
1002
|
+
const err = error;
|
|
1003
|
+
const status = typeof err.status === "number" ? err.status : null;
|
|
1004
|
+
const stderr = typeof err.stderr === "string" ? err.stderr : Buffer.isBuffer(err.stderr) ? err.stderr.toString("utf8") : "";
|
|
1005
|
+
const timedOut = err.code === "ETIMEDOUT" || status === null && Boolean(err.signal);
|
|
1006
|
+
if (!timedOut && isNotFoundOutput(status, stderr)) {
|
|
1007
|
+
return null;
|
|
1008
|
+
}
|
|
1009
|
+
throw classifySecurityFailure(status, stderr, timedOut);
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
async probe() {
|
|
1013
|
+
if (!this.hasCustomBinary && process.platform !== "darwin") {
|
|
1014
|
+
return {
|
|
1015
|
+
available: false,
|
|
1016
|
+
reason: "unsupported_platform",
|
|
1017
|
+
message: "OS Keychain backend is currently supported on macOS only"
|
|
1018
|
+
};
|
|
1019
|
+
}
|
|
1020
|
+
try {
|
|
1021
|
+
const binary = this.resolveBinary();
|
|
1022
|
+
if (!binary) {
|
|
1023
|
+
return {
|
|
1024
|
+
available: false,
|
|
1025
|
+
reason: "keychain_unavailable",
|
|
1026
|
+
message: "macOS /usr/bin/security is unavailable"
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
const { code, stderr } = await this.runArgsAsync(["show-keychain-info"]);
|
|
1030
|
+
if (code === 0) return { available: true };
|
|
1031
|
+
const classified = classifySecurityFailure(code, stderr);
|
|
1032
|
+
return {
|
|
1033
|
+
available: false,
|
|
1034
|
+
reason: classified.code === "keychain_locked" ? "keychain_locked" : "keychain_unavailable",
|
|
1035
|
+
message: classified.message
|
|
1036
|
+
};
|
|
1037
|
+
} catch (error) {
|
|
1038
|
+
const isLocked = error instanceof KeychainError && error.code === "keychain_locked";
|
|
1039
|
+
return {
|
|
1040
|
+
available: false,
|
|
1041
|
+
reason: isLocked ? "keychain_locked" : "keychain_unavailable",
|
|
1042
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1043
|
+
};
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
async readFullAsync(service, account, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
|
|
1047
|
+
const find = (name) => this.findRawAsync(name, account, timeoutMs);
|
|
1048
|
+
let root = await find(service);
|
|
1049
|
+
for (let attempt = 0; attempt < MAX_SNAPSHOT_ATTEMPTS; attempt += 1) {
|
|
1050
|
+
const snapshot = readChunkedSnapshot(service, root);
|
|
1051
|
+
let step = snapshot.next();
|
|
1052
|
+
while (!step.done) step = snapshot.next(await find(step.value));
|
|
1053
|
+
if ("value" in step.value) return step.value.value;
|
|
1054
|
+
root = step.value.nextRoot;
|
|
1055
|
+
}
|
|
1056
|
+
throw new KeychainError(
|
|
1057
|
+
"keychain_error",
|
|
1058
|
+
"Keychain changed during read; retry"
|
|
1059
|
+
);
|
|
1060
|
+
}
|
|
1061
|
+
async get(service, account) {
|
|
1062
|
+
return this.readFullAsync(service, account, DEFAULT_ASYNC_TIMEOUT_MS);
|
|
1063
|
+
}
|
|
1064
|
+
getSync(service, account, timeoutMs = DEFAULT_SYNC_TIMEOUT_MS) {
|
|
1065
|
+
const deadline = performance.now() + timeoutMs;
|
|
1066
|
+
const find = (name) => {
|
|
1067
|
+
const remaining = Math.ceil(deadline - performance.now());
|
|
1068
|
+
if (remaining <= 0) throw classifySecurityFailure(null, "", true);
|
|
1069
|
+
return this.findRawSync(name, account, remaining);
|
|
1070
|
+
};
|
|
1071
|
+
let root = find(service);
|
|
1072
|
+
for (let attempt = 0; attempt < MAX_SNAPSHOT_ATTEMPTS; attempt += 1) {
|
|
1073
|
+
const snapshot = readChunkedSnapshot(service, root);
|
|
1074
|
+
let step = snapshot.next();
|
|
1075
|
+
while (!step.done) step = snapshot.next(find(step.value));
|
|
1076
|
+
if ("value" in step.value) return step.value.value;
|
|
1077
|
+
root = step.value.nextRoot;
|
|
1078
|
+
}
|
|
1079
|
+
throw new KeychainError(
|
|
1080
|
+
"keychain_error",
|
|
1081
|
+
"Keychain changed during read; retry"
|
|
1082
|
+
);
|
|
1083
|
+
}
|
|
1084
|
+
async sweepGenSlotBestEffort(service, account, gen, startIndex = 0) {
|
|
1085
|
+
let consecutiveMisses = 0;
|
|
1086
|
+
for (let i = startIndex; i < MAX_CHUNKS; i += 1) {
|
|
1087
|
+
const deleted = await this.deleteSingleItem(
|
|
1088
|
+
genChunkServiceName(service, gen, i),
|
|
1089
|
+
account
|
|
1090
|
+
).catch(() => false);
|
|
1091
|
+
if (deleted) {
|
|
1092
|
+
consecutiveMisses = 0;
|
|
1093
|
+
} else {
|
|
1094
|
+
consecutiveMisses += 1;
|
|
1095
|
+
if (consecutiveMisses >= SWEEP_CONSECUTIVE_MISS_LIMIT) break;
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* Exhaustively delete every possible chunk index (`0..MAX_CHUNKS-1`) in a
|
|
1101
|
+
* fixed generation slot and propagate any non-not-found delete error.
|
|
1102
|
+
*/
|
|
1103
|
+
async deleteAllSlotChunksStrict(service, account, gen) {
|
|
1104
|
+
let deletedAny = false;
|
|
1105
|
+
for (let i = 0; i < MAX_CHUNKS; i += 1) {
|
|
1106
|
+
const deleted = await this.deleteSingleItem(
|
|
1107
|
+
genChunkServiceName(service, gen, i),
|
|
1108
|
+
account
|
|
1109
|
+
);
|
|
1110
|
+
if (deleted) deletedAny = true;
|
|
1111
|
+
}
|
|
1112
|
+
return deletedAny;
|
|
1113
|
+
}
|
|
1114
|
+
async cleanupOldChunks(service, account, previousRoot, keepGen) {
|
|
1115
|
+
try {
|
|
1116
|
+
if (previousRoot) {
|
|
1117
|
+
let prevPtr = null;
|
|
1118
|
+
try {
|
|
1119
|
+
prevPtr = parseGenPointer(previousRoot);
|
|
1120
|
+
} catch {
|
|
1121
|
+
prevPtr = null;
|
|
1122
|
+
}
|
|
1123
|
+
if (prevPtr && prevPtr.gen !== keepGen) {
|
|
1124
|
+
for (let i = 0; i < prevPtr.total; i += 1) {
|
|
1125
|
+
await this.deleteSingleItem(
|
|
1126
|
+
genChunkServiceName(service, prevPtr.gen, i),
|
|
1127
|
+
account
|
|
1128
|
+
).catch(() => false);
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
let prevCb1 = null;
|
|
1132
|
+
try {
|
|
1133
|
+
prevCb1 = parseChunkEnvelope(previousRoot);
|
|
1134
|
+
} catch {
|
|
1135
|
+
prevCb1 = null;
|
|
1136
|
+
}
|
|
1137
|
+
if (prevCb1 && prevCb1.total > 1) {
|
|
1138
|
+
for (let i = 1; i < prevCb1.total; i += 1) {
|
|
1139
|
+
await this.deleteSingleItem(
|
|
1140
|
+
chunkServiceName(service, i),
|
|
1141
|
+
account
|
|
1142
|
+
).catch(() => false);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
for (const slot of FIXED_GEN_SLOTS) {
|
|
1147
|
+
if (slot !== keepGen) {
|
|
1148
|
+
await this.sweepGenSlotBestEffort(service, account, slot, 0);
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
} catch {
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
async writeSingleChunk(service, account, encoded, previousRoot) {
|
|
1155
|
+
await this.runInteractiveBatchAsync([
|
|
1156
|
+
`add-generic-password -U -a ${account} -s ${service} -w ${encoded}`
|
|
1157
|
+
]);
|
|
1158
|
+
const verified = await this.findRawAsync(service, account);
|
|
1159
|
+
if (verified !== encoded) {
|
|
1160
|
+
throw new KeychainError(
|
|
1161
|
+
"keychain_error",
|
|
1162
|
+
"macOS Keychain write verification failed"
|
|
1163
|
+
);
|
|
1164
|
+
}
|
|
1165
|
+
await this.cleanupOldChunks(service, account, previousRoot);
|
|
1166
|
+
}
|
|
1167
|
+
/**
|
|
1168
|
+
* Multi-chunk write: alternates between fixed A/B slots (`a` and `b`) so
|
|
1169
|
+
* existing credentials stay untouched until every staged chunk verifies via
|
|
1170
|
+
* read-back AND crashed writes remain deterministically discoverable on logout.
|
|
1171
|
+
*/
|
|
1172
|
+
async writeMultiChunk(service, account, chunks, previousRoot, digest2) {
|
|
1173
|
+
const activeGen = previousRoot ? parseGenPointer(previousRoot)?.gen : void 0;
|
|
1174
|
+
const gen = activeGen === "a" ? "b" : "a";
|
|
1175
|
+
const stageCommands = chunks.map(
|
|
1176
|
+
(encoded, index) => `add-generic-password -U -a ${account} -s ${genChunkServiceName(service, gen, index)} -w ${encoded}`
|
|
1177
|
+
);
|
|
1178
|
+
const rollbackStaged = async () => {
|
|
1179
|
+
for (let i = 0; i < chunks.length; i += 1) {
|
|
1180
|
+
await this.deleteSingleItem(
|
|
1181
|
+
genChunkServiceName(service, gen, i),
|
|
1182
|
+
account
|
|
1183
|
+
).catch(() => false);
|
|
1184
|
+
}
|
|
1185
|
+
};
|
|
1186
|
+
try {
|
|
1187
|
+
await this.runInteractiveBatchAsync(stageCommands);
|
|
1188
|
+
for (let i = 0; i < chunks.length; i += 1) {
|
|
1189
|
+
const verified = await this.findRawAsync(
|
|
1190
|
+
genChunkServiceName(service, gen, i),
|
|
1191
|
+
account
|
|
1192
|
+
);
|
|
1193
|
+
if (verified !== chunks[i]) {
|
|
1194
|
+
throw new KeychainError(
|
|
1195
|
+
"keychain_error",
|
|
1196
|
+
`macOS Keychain staged chunk ${i + 1}/${chunks.length} failed verification`
|
|
1197
|
+
);
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
} catch (error) {
|
|
1201
|
+
await rollbackStaged();
|
|
1202
|
+
throw error;
|
|
1203
|
+
}
|
|
1204
|
+
const pointerValue = `${GEN_POINTER_PREFIX}${gen}:${chunks.length}.${digest2}`;
|
|
1205
|
+
await this.runInteractiveBatchAsync([
|
|
1206
|
+
`add-generic-password -U -a ${account} -s ${service} -w ${pointerValue}`
|
|
1207
|
+
]);
|
|
1208
|
+
const verifiedPointer = await this.findRawAsync(service, account);
|
|
1209
|
+
if (verifiedPointer !== pointerValue) {
|
|
1210
|
+
await rollbackStaged();
|
|
1211
|
+
throw new KeychainError(
|
|
1212
|
+
"keychain_error",
|
|
1213
|
+
"macOS Keychain pointer verification failed"
|
|
1214
|
+
);
|
|
1215
|
+
}
|
|
1216
|
+
await this.sweepGenSlotBestEffort(service, account, gen, chunks.length);
|
|
1217
|
+
await this.cleanupOldChunks(service, account, previousRoot, gen);
|
|
1218
|
+
}
|
|
1219
|
+
async set(service, account, value) {
|
|
1220
|
+
validateKeychainToken("service", service);
|
|
1221
|
+
validateKeychainToken("account", account);
|
|
1222
|
+
const chunks = encodePayloadChunks(value);
|
|
1223
|
+
const previousRoot = await this.findRawAsync(service, account);
|
|
1224
|
+
if (chunks.length === 1) {
|
|
1225
|
+
await this.writeSingleChunk(service, account, chunks[0], previousRoot);
|
|
1226
|
+
return;
|
|
1227
|
+
}
|
|
1228
|
+
await this.writeMultiChunk(
|
|
1229
|
+
service,
|
|
1230
|
+
account,
|
|
1231
|
+
chunks,
|
|
1232
|
+
previousRoot,
|
|
1233
|
+
payloadDigest(value)
|
|
1234
|
+
);
|
|
1235
|
+
}
|
|
1236
|
+
async deleteSingleItem(service, account) {
|
|
1237
|
+
validateKeychainToken("service", service);
|
|
1238
|
+
validateKeychainToken("account", account);
|
|
1239
|
+
const { code, stderr } = await this.runArgsAsync([
|
|
1240
|
+
"delete-generic-password",
|
|
1241
|
+
"-a",
|
|
1242
|
+
account,
|
|
1243
|
+
"-s",
|
|
1244
|
+
service
|
|
1245
|
+
]);
|
|
1246
|
+
if (code === 0) return true;
|
|
1247
|
+
if (isNotFoundOutput(code, stderr)) return false;
|
|
1248
|
+
throw classifySecurityFailure(code, stderr);
|
|
1249
|
+
}
|
|
1250
|
+
async delete(service, account) {
|
|
1251
|
+
validateKeychainToken("service", service);
|
|
1252
|
+
validateKeychainToken("account", account);
|
|
1253
|
+
const existing = await this.findRawAsync(service, account);
|
|
1254
|
+
let deletedAny = false;
|
|
1255
|
+
if (existing) {
|
|
1256
|
+
let prevCb1 = null;
|
|
1257
|
+
try {
|
|
1258
|
+
prevCb1 = parseChunkEnvelope(existing);
|
|
1259
|
+
} catch {
|
|
1260
|
+
prevCb1 = null;
|
|
1261
|
+
}
|
|
1262
|
+
if (prevCb1 && prevCb1.total > 1) {
|
|
1263
|
+
for (let i = 1; i < prevCb1.total; i += 1) {
|
|
1264
|
+
if (await this.deleteSingleItem(chunkServiceName(service, i), account)) {
|
|
1265
|
+
deletedAny = true;
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
let prevPtr = null;
|
|
1270
|
+
try {
|
|
1271
|
+
prevPtr = parseGenPointer(existing);
|
|
1272
|
+
} catch {
|
|
1273
|
+
prevPtr = null;
|
|
1274
|
+
}
|
|
1275
|
+
if (prevPtr && !FIXED_GEN_SLOTS.includes(
|
|
1276
|
+
prevPtr.gen
|
|
1277
|
+
)) {
|
|
1278
|
+
for (let i = 0; i < prevPtr.total; i += 1) {
|
|
1279
|
+
if (await this.deleteSingleItem(
|
|
1280
|
+
genChunkServiceName(service, prevPtr.gen, i),
|
|
1281
|
+
account
|
|
1282
|
+
)) {
|
|
1283
|
+
deletedAny = true;
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
const deletedPrimary = await this.deleteSingleItem(service, account);
|
|
1289
|
+
if (deletedPrimary) deletedAny = true;
|
|
1290
|
+
for (const slot of FIXED_GEN_SLOTS) {
|
|
1291
|
+
if (await this.deleteAllSlotChunksStrict(service, account, slot)) {
|
|
1292
|
+
deletedAny = true;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
return deletedAny;
|
|
1296
|
+
}
|
|
1297
|
+
/** Let macOS prompt the user to authorize reading each existing item. */
|
|
1298
|
+
async authorize(service, account) {
|
|
1299
|
+
const fullValue = await this.readFullAsync(
|
|
1300
|
+
service,
|
|
1301
|
+
account,
|
|
1302
|
+
AUTHORIZATION_TIMEOUT_MS
|
|
1303
|
+
);
|
|
1304
|
+
return fullValue !== null;
|
|
1305
|
+
}
|
|
1306
|
+
};
|
|
1307
|
+
|
|
1308
|
+
// src/auth-schema.ts
|
|
1309
|
+
var AUTH_VERSION_V1 = 1;
|
|
1310
|
+
var AUTH_VERSION_V2 = 2;
|
|
1311
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1312
|
+
var normalizeApiKey = (value) => {
|
|
1313
|
+
if (!isRecord(value) || typeof value.api_key !== "string") return null;
|
|
1314
|
+
return {
|
|
1315
|
+
api_key: value.api_key,
|
|
1316
|
+
...typeof value.api_base === "string" && value.api_base.length > 0 ? { api_base: value.api_base } : {}
|
|
1317
|
+
};
|
|
1318
|
+
};
|
|
1319
|
+
var normalizeOAuth = (value) => {
|
|
1320
|
+
if (!isRecord(value) || typeof value.access_token !== "string" || typeof value.refresh_token !== "string" || typeof value.expires_at !== "number" || !Number.isFinite(value.expires_at)) {
|
|
1321
|
+
return null;
|
|
1322
|
+
}
|
|
1323
|
+
return {
|
|
1324
|
+
access_token: value.access_token,
|
|
1325
|
+
refresh_token: value.refresh_token,
|
|
1326
|
+
expires_at: value.expires_at,
|
|
1327
|
+
...typeof value.account_id === "string" && value.account_id.length > 0 ? { account_id: value.account_id } : {}
|
|
1328
|
+
};
|
|
1329
|
+
};
|
|
1330
|
+
var normalizeProviderEntryV1 = (value) => {
|
|
1331
|
+
if (!isRecord(value)) {
|
|
1332
|
+
throw new Error("auth.json contains invalid provider entry");
|
|
1333
|
+
}
|
|
1334
|
+
if (value.method === "api_key") {
|
|
1335
|
+
const apiKey = normalizeApiKey(value);
|
|
1336
|
+
if (!apiKey) {
|
|
1337
|
+
throw new Error("auth.json contains invalid api_key entry");
|
|
1338
|
+
}
|
|
1339
|
+
return {
|
|
1340
|
+
chat_method: "api_key",
|
|
1341
|
+
credentials: { api_key: apiKey }
|
|
1342
|
+
};
|
|
1343
|
+
}
|
|
1344
|
+
if (value.method === "oauth") {
|
|
1345
|
+
const oauth = normalizeOAuth(value.oauth);
|
|
1346
|
+
if (!oauth) {
|
|
1347
|
+
throw new Error("auth.json contains invalid oauth entry");
|
|
1348
|
+
}
|
|
1349
|
+
return {
|
|
1350
|
+
chat_method: "oauth",
|
|
1351
|
+
credentials: { oauth }
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
throw new Error("auth.json contains unsupported auth method");
|
|
1355
|
+
};
|
|
1356
|
+
var normalizeProviderEntryV2 = (value) => {
|
|
1357
|
+
if (!isRecord(value) || !isRecord(value.credentials)) {
|
|
1358
|
+
throw new Error("auth.json v2 contains invalid provider entry");
|
|
1359
|
+
}
|
|
1360
|
+
const chatMethod = value.chat_method;
|
|
1361
|
+
if (chatMethod !== void 0 && chatMethod !== "api_key" && chatMethod !== "oauth") {
|
|
1362
|
+
throw new Error("auth.json v2 contains invalid chat_method");
|
|
1363
|
+
}
|
|
1364
|
+
const credentials = {};
|
|
1365
|
+
if (value.credentials.api_key !== void 0) {
|
|
1366
|
+
const apiKey = normalizeApiKey(value.credentials.api_key);
|
|
1367
|
+
if (!apiKey) {
|
|
1368
|
+
throw new Error("auth.json v2 contains invalid api_key credential");
|
|
1369
|
+
}
|
|
1370
|
+
credentials.api_key = apiKey;
|
|
1371
|
+
}
|
|
1372
|
+
if (value.credentials.oauth !== void 0) {
|
|
1373
|
+
const oauth = normalizeOAuth(value.credentials.oauth);
|
|
1374
|
+
if (!oauth) {
|
|
1375
|
+
throw new Error("auth.json v2 contains invalid oauth credential");
|
|
1376
|
+
}
|
|
1377
|
+
credentials.oauth = oauth;
|
|
1378
|
+
}
|
|
1379
|
+
return {
|
|
1380
|
+
...chatMethod ? { chat_method: chatMethod } : {},
|
|
1381
|
+
credentials
|
|
1382
|
+
};
|
|
1383
|
+
};
|
|
1384
|
+
var parseAuthDocument = (text) => {
|
|
1385
|
+
const parsed = JSON.parse(text);
|
|
1386
|
+
if (!isRecord(parsed)) {
|
|
1387
|
+
throw new Error("auth.json has unsupported format");
|
|
1388
|
+
}
|
|
1389
|
+
if (parsed.version === AUTH_VERSION_V1) {
|
|
1390
|
+
const rawProviders = isRecord(parsed.providers) ? parsed.providers : {};
|
|
1391
|
+
const providers = {};
|
|
1392
|
+
for (const [name, entry] of Object.entries(rawProviders)) {
|
|
1393
|
+
providers[name] = normalizeProviderEntryV1(entry);
|
|
1394
|
+
}
|
|
1395
|
+
return {
|
|
1396
|
+
normalized: { version: AUTH_VERSION_V2, providers },
|
|
1397
|
+
sourceVersion: 1
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
if (parsed.version === AUTH_VERSION_V2) {
|
|
1401
|
+
const rawProviders = isRecord(parsed.providers) ? parsed.providers : {};
|
|
1402
|
+
const providers = {};
|
|
1403
|
+
for (const [name, entry] of Object.entries(rawProviders)) {
|
|
1404
|
+
providers[name] = normalizeProviderEntryV2(entry);
|
|
1405
|
+
}
|
|
1406
|
+
return {
|
|
1407
|
+
normalized: { version: AUTH_VERSION_V2, providers },
|
|
1408
|
+
sourceVersion: 2
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
throw new Error("auth.json has unsupported version");
|
|
1412
|
+
};
|
|
1413
|
+
var providerAuthStoreAdapter = {
|
|
1414
|
+
name: "auth",
|
|
1415
|
+
service: CODELIA_AUTH_KEYCHAIN_SERVICE,
|
|
1416
|
+
filePath: (paths) => paths.authFile,
|
|
1417
|
+
legacyFilePath: (paths) => paths.legacyAuthFile,
|
|
1418
|
+
empty: () => ({ version: AUTH_VERSION_V2, providers: {} }),
|
|
1419
|
+
isNonEmpty: (doc) => Object.keys(doc.providers).length > 0,
|
|
1420
|
+
parse: (text) => parseAuthDocument(text)
|
|
1421
|
+
};
|
|
1422
|
+
|
|
1423
|
+
// src/credential-backend.ts
|
|
1424
|
+
import { promises as fs5, readFileSync as readFileSync2 } from "fs";
|
|
1425
|
+
import path7 from "path";
|
|
1426
|
+
|
|
1427
|
+
// src/credential-migration.ts
|
|
1428
|
+
import { promises as fs4, readFileSync } from "fs";
|
|
1429
|
+
var CredentialConflictError = class extends Error {
|
|
1430
|
+
code = "credential_storage_conflict";
|
|
1431
|
+
store;
|
|
1432
|
+
constructor(store, detail) {
|
|
1433
|
+
super(
|
|
1434
|
+
detail ?? `Credential storage conflict detected for '${store}': both source and destination contain different credentials. Resolve the conflict before continuing.`
|
|
1435
|
+
);
|
|
1436
|
+
this.name = "CredentialConflictError";
|
|
1437
|
+
this.store = store;
|
|
1438
|
+
}
|
|
1439
|
+
};
|
|
1440
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1441
|
+
var canonicalizeValue = (value) => {
|
|
1442
|
+
if (Array.isArray(value)) {
|
|
1443
|
+
return value.map(canonicalizeValue);
|
|
1444
|
+
}
|
|
1445
|
+
if (isRecord2(value)) {
|
|
1446
|
+
const sorted = {};
|
|
1447
|
+
for (const key of Object.keys(value).sort()) {
|
|
1448
|
+
const entry = value[key];
|
|
1449
|
+
if (entry !== void 0) {
|
|
1450
|
+
sorted[key] = canonicalizeValue(entry);
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
return sorted;
|
|
1454
|
+
}
|
|
1455
|
+
return value;
|
|
1456
|
+
};
|
|
1457
|
+
var canonicalJsonStringify = (value) => JSON.stringify(canonicalizeValue(value));
|
|
1458
|
+
var canonicalJsonEqual = (left, right) => canonicalJsonStringify(left) === canonicalJsonStringify(right);
|
|
1459
|
+
var parseAuthStorageState = (text) => {
|
|
1460
|
+
const parsed = JSON.parse(text);
|
|
1461
|
+
if (!isRecord2(parsed) || parsed.version !== 1) {
|
|
1462
|
+
throw new Error("storage-state.json has unsupported version");
|
|
1463
|
+
}
|
|
1464
|
+
const active = parsed.active_backend;
|
|
1465
|
+
if (active !== "file" && active !== "keyring") {
|
|
1466
|
+
throw new Error("storage-state.json has invalid active_backend");
|
|
1467
|
+
}
|
|
1468
|
+
if (parsed.mcp_reauth_required !== void 0 && (!Array.isArray(parsed.mcp_reauth_required) || !parsed.mcp_reauth_required.every((item) => typeof item === "string"))) {
|
|
1469
|
+
throw new Error("storage-state.json has invalid mcp_reauth_required");
|
|
1470
|
+
}
|
|
1471
|
+
const mcpReauth = parsed.mcp_reauth_required;
|
|
1472
|
+
if (parsed.status === "steady") {
|
|
1473
|
+
return {
|
|
1474
|
+
version: 1,
|
|
1475
|
+
status: "steady",
|
|
1476
|
+
active_backend: active,
|
|
1477
|
+
...mcpReauth?.length ? { mcp_reauth_required: mcpReauth } : {}
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
if (parsed.status === "migrating") {
|
|
1481
|
+
const target = parsed.target_backend;
|
|
1482
|
+
const stores = isRecord2(parsed.stores) ? parsed.stores : null;
|
|
1483
|
+
const authStatus = stores?.auth;
|
|
1484
|
+
const mcpStatus = stores?.mcp_auth;
|
|
1485
|
+
if (target !== "file" && target !== "keyring" || authStatus !== "pending" && authStatus !== "verified" || mcpStatus !== "pending" && mcpStatus !== "verified") {
|
|
1486
|
+
throw new Error("storage-state.json has invalid migrating state");
|
|
1487
|
+
}
|
|
1488
|
+
let cleanupPending;
|
|
1489
|
+
if (parsed.cleanup_pending !== void 0) {
|
|
1490
|
+
if (!isRecord2(parsed.cleanup_pending)) {
|
|
1491
|
+
throw new Error("storage-state.json has invalid cleanup_pending");
|
|
1492
|
+
}
|
|
1493
|
+
const sourceBackend = parsed.cleanup_pending.source_backend;
|
|
1494
|
+
const authFlag = parsed.cleanup_pending.auth;
|
|
1495
|
+
const mcpFlag = parsed.cleanup_pending.mcp_auth;
|
|
1496
|
+
if (sourceBackend !== "file" && sourceBackend !== "legacy_file" && sourceBackend !== "keyring" || typeof authFlag !== "boolean" || typeof mcpFlag !== "boolean") {
|
|
1497
|
+
throw new Error("storage-state.json has invalid cleanup_pending");
|
|
1498
|
+
}
|
|
1499
|
+
cleanupPending = {
|
|
1500
|
+
source_backend: sourceBackend,
|
|
1501
|
+
auth: authFlag,
|
|
1502
|
+
mcp_auth: mcpFlag
|
|
1503
|
+
};
|
|
1504
|
+
}
|
|
1505
|
+
return {
|
|
1506
|
+
version: 1,
|
|
1507
|
+
status: "migrating",
|
|
1508
|
+
active_backend: active,
|
|
1509
|
+
target_backend: target,
|
|
1510
|
+
stores: { auth: authStatus, mcp_auth: mcpStatus },
|
|
1511
|
+
...cleanupPending ? { cleanup_pending: cleanupPending } : {},
|
|
1512
|
+
...mcpReauth?.length ? { mcp_reauth_required: mcpReauth } : {}
|
|
1513
|
+
};
|
|
1514
|
+
}
|
|
1515
|
+
throw new Error("storage-state.json has invalid status");
|
|
1516
|
+
};
|
|
1517
|
+
var readAuthStorageState = async (stateFile) => {
|
|
1518
|
+
if (!await verifyWindowsCredentialFileAcl(stateFile)) return null;
|
|
1519
|
+
let text;
|
|
1520
|
+
try {
|
|
1521
|
+
text = await fs4.readFile(stateFile, "utf8");
|
|
1522
|
+
} catch (error) {
|
|
1523
|
+
if (error?.code === "ENOENT") return null;
|
|
1524
|
+
throw error;
|
|
1525
|
+
}
|
|
1526
|
+
return parseAuthStorageState(text);
|
|
1527
|
+
};
|
|
1528
|
+
var readAuthStorageStateSync = (stateFile) => {
|
|
1529
|
+
if (!verifyWindowsCredentialFileAclSync(stateFile)) return null;
|
|
1530
|
+
let text;
|
|
1531
|
+
try {
|
|
1532
|
+
text = readFileSync(stateFile, "utf8");
|
|
1533
|
+
} catch (error) {
|
|
1534
|
+
if (error?.code === "ENOENT") return null;
|
|
1535
|
+
throw error;
|
|
1536
|
+
}
|
|
1537
|
+
return parseAuthStorageState(text);
|
|
1538
|
+
};
|
|
1539
|
+
var writeAuthStorageState = async (stateFile, state) => {
|
|
1540
|
+
await writeFileAtomic(stateFile, JSON.stringify(state, null, 2), {
|
|
1541
|
+
mode: 384
|
|
1542
|
+
});
|
|
1543
|
+
};
|
|
1544
|
+
var runTwoPhaseMigration = async (options) => {
|
|
1545
|
+
const [authSrc, authDst, mcpSrc, mcpDst] = await Promise.all([
|
|
1546
|
+
options.authSlot.readSource(),
|
|
1547
|
+
options.authSlot.readDest(),
|
|
1548
|
+
options.mcpSlot.readSource(),
|
|
1549
|
+
options.mcpSlot.readDest()
|
|
1550
|
+
]);
|
|
1551
|
+
const evaluate = (name, src, dst) => {
|
|
1552
|
+
if (!src.present) return "none";
|
|
1553
|
+
if (src.nonEmpty && dst.nonEmpty) {
|
|
1554
|
+
if (canonicalJsonEqual(src.normalized, dst.normalized)) {
|
|
1555
|
+
return "recover";
|
|
1556
|
+
}
|
|
1557
|
+
throw new CredentialConflictError(name);
|
|
1558
|
+
}
|
|
1559
|
+
if (!src.nonEmpty && dst.nonEmpty) {
|
|
1560
|
+
return "recover";
|
|
1561
|
+
}
|
|
1562
|
+
if (dst.present && canonicalJsonEqual(src.normalized, dst.normalized)) {
|
|
1563
|
+
return "recover";
|
|
1564
|
+
}
|
|
1565
|
+
return "copy";
|
|
1566
|
+
};
|
|
1567
|
+
const authAction = evaluate("auth", authSrc, authDst);
|
|
1568
|
+
const mcpAction = evaluate("mcp_auth", mcpSrc, mcpDst);
|
|
1569
|
+
const mcpReauthSet = /* @__PURE__ */ new Set([
|
|
1570
|
+
...options.existingMcpReauth ?? [],
|
|
1571
|
+
...mcpSrc.extraWarnings ?? []
|
|
1572
|
+
]);
|
|
1573
|
+
const mcpReauthRequired = [...mcpReauthSet].sort();
|
|
1574
|
+
if (authAction === "none" && mcpAction === "none") {
|
|
1575
|
+
if (options.fromBackend !== options.toBackend || options.commitSteadyIfEmpty) {
|
|
1576
|
+
await writeAuthStorageState(options.stateFile, {
|
|
1577
|
+
version: 1,
|
|
1578
|
+
status: "steady",
|
|
1579
|
+
active_backend: options.toBackend,
|
|
1580
|
+
...mcpReauthRequired.length ? { mcp_reauth_required: mcpReauthRequired } : {}
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
return { migrated: false, mcpReauthRequired };
|
|
1584
|
+
}
|
|
1585
|
+
const migratingState = {
|
|
1586
|
+
version: 1,
|
|
1587
|
+
status: "migrating",
|
|
1588
|
+
active_backend: options.fromBackend,
|
|
1589
|
+
target_backend: options.toBackend,
|
|
1590
|
+
stores: {
|
|
1591
|
+
auth: authAction === "copy" ? "pending" : "verified",
|
|
1592
|
+
mcp_auth: mcpAction === "copy" ? "pending" : "verified"
|
|
1593
|
+
},
|
|
1594
|
+
...mcpReauthRequired.length ? { mcp_reauth_required: mcpReauthRequired } : {}
|
|
1595
|
+
};
|
|
1596
|
+
await writeAuthStorageState(options.stateFile, migratingState);
|
|
1597
|
+
if (authAction === "copy") {
|
|
1598
|
+
await options.authSlot.writeDest(authSrc.normalized);
|
|
1599
|
+
const verified = await options.authSlot.verifyDest(authSrc.normalized);
|
|
1600
|
+
if (!verified) {
|
|
1601
|
+
throw new Error("auth migration read-back verification failed");
|
|
1602
|
+
}
|
|
1603
|
+
migratingState.stores.auth = "verified";
|
|
1604
|
+
await writeAuthStorageState(options.stateFile, migratingState);
|
|
1605
|
+
}
|
|
1606
|
+
if (mcpAction === "copy") {
|
|
1607
|
+
await options.mcpSlot.writeDest(mcpSrc.normalized);
|
|
1608
|
+
const verified = await options.mcpSlot.verifyDest(mcpSrc.normalized);
|
|
1609
|
+
if (!verified) {
|
|
1610
|
+
throw new Error("mcp-auth migration read-back verification failed");
|
|
1611
|
+
}
|
|
1612
|
+
migratingState.stores.mcp_auth = "verified";
|
|
1613
|
+
await writeAuthStorageState(options.stateFile, migratingState);
|
|
1614
|
+
}
|
|
1615
|
+
if (authSrc.present || mcpSrc.present) {
|
|
1616
|
+
migratingState.cleanup_pending = {
|
|
1617
|
+
source_backend: options.cleanupSourceKind ?? options.fromBackend,
|
|
1618
|
+
auth: authSrc.present,
|
|
1619
|
+
mcp_auth: mcpSrc.present
|
|
1620
|
+
};
|
|
1621
|
+
await writeAuthStorageState(options.stateFile, migratingState);
|
|
1622
|
+
}
|
|
1623
|
+
if (authSrc.present) {
|
|
1624
|
+
await options.authSlot.cleanupSource();
|
|
1625
|
+
}
|
|
1626
|
+
if (mcpSrc.present) {
|
|
1627
|
+
await options.mcpSlot.cleanupSource();
|
|
1628
|
+
}
|
|
1629
|
+
await writeAuthStorageState(options.stateFile, {
|
|
1630
|
+
version: 1,
|
|
1631
|
+
status: "steady",
|
|
1632
|
+
active_backend: options.toBackend,
|
|
1633
|
+
...mcpReauthRequired.length ? { mcp_reauth_required: mcpReauthRequired } : {}
|
|
1634
|
+
});
|
|
1635
|
+
return { migrated: true, mcpReauthRequired };
|
|
1636
|
+
};
|
|
1637
|
+
|
|
1638
|
+
// src/paths.ts
|
|
1639
|
+
import { mkdir as mkdir2 } from "fs/promises";
|
|
1640
|
+
import os2 from "os";
|
|
1641
|
+
import path6 from "path";
|
|
1642
|
+
var DEFAULT_ROOT_DIR = ".codelia";
|
|
1643
|
+
var LAYOUT_ENV = "CODELIA_LAYOUT";
|
|
1644
|
+
var XDG_DIR_NAME = "codelia";
|
|
1645
|
+
var CONFIG_FILENAME = "config.json";
|
|
1646
|
+
var CREDENTIALS_DIRNAME = "credentials";
|
|
1647
|
+
var AUTH_FILENAME = "auth.json";
|
|
1648
|
+
var MCP_AUTH_FILENAME = "mcp-auth.json";
|
|
1649
|
+
var AUTH_STATE_FILENAME = "storage-state.json";
|
|
1650
|
+
var PROJECTS_FILENAME = "projects.json";
|
|
1651
|
+
var CACHE_DIRNAME = "cache";
|
|
1652
|
+
var TOOL_OUTPUT_CACHE_DIRNAME = "tool-output";
|
|
1653
|
+
var SESSIONS_DIRNAME = "sessions";
|
|
1654
|
+
var LOGS_DIRNAME = "logs";
|
|
1655
|
+
function resolveStoragePaths(options = {}) {
|
|
1656
|
+
if (options.rootOverride) {
|
|
1657
|
+
return buildHomeLayout(options.rootOverride);
|
|
1658
|
+
}
|
|
1659
|
+
const layoutValue = options.layout ?? process.env[LAYOUT_ENV];
|
|
1660
|
+
const layout = normalizeLayout(layoutValue);
|
|
1661
|
+
if (layout === "xdg") {
|
|
1662
|
+
return buildXdgLayout();
|
|
1663
|
+
}
|
|
1664
|
+
return buildHomeLayout(defaultHomeRoot());
|
|
1665
|
+
}
|
|
1666
|
+
async function ensureStorageDirs(paths) {
|
|
1667
|
+
await Promise.all([
|
|
1668
|
+
mkdir2(paths.configDir, { recursive: true }),
|
|
1669
|
+
mkdir2(paths.cacheDir, { recursive: true }),
|
|
1670
|
+
mkdir2(paths.toolOutputCacheDir, { recursive: true }),
|
|
1671
|
+
mkdir2(paths.sessionsDir, { recursive: true }),
|
|
1672
|
+
mkdir2(paths.logsDir, { recursive: true })
|
|
1673
|
+
]);
|
|
1674
|
+
}
|
|
1675
|
+
function resolveDefaultHomeConfigDir(home = os2.homedir(), layoutValue = process.env[LAYOUT_ENV]) {
|
|
1676
|
+
const layout = normalizeLayout(layoutValue);
|
|
1677
|
+
return layout === "xdg" ? path6.join(home, ".config", XDG_DIR_NAME) : path6.join(home, DEFAULT_ROOT_DIR);
|
|
1678
|
+
}
|
|
1679
|
+
function normalizeLayout(value) {
|
|
1680
|
+
if (value && value.toLowerCase() === "xdg") return "xdg";
|
|
1681
|
+
return "home";
|
|
1682
|
+
}
|
|
1683
|
+
function defaultHomeRoot() {
|
|
1684
|
+
return path6.join(os2.homedir(), DEFAULT_ROOT_DIR);
|
|
1685
|
+
}
|
|
1686
|
+
function buildHomeLayout(root) {
|
|
1687
|
+
const configDir = root;
|
|
1688
|
+
const credentialsDir = path6.join(configDir, CREDENTIALS_DIRNAME);
|
|
1689
|
+
return {
|
|
1690
|
+
root,
|
|
1691
|
+
configDir,
|
|
1692
|
+
configFile: path6.join(configDir, CONFIG_FILENAME),
|
|
1693
|
+
credentialsDir,
|
|
1694
|
+
authFile: path6.join(credentialsDir, AUTH_FILENAME),
|
|
1695
|
+
mcpAuthFile: path6.join(credentialsDir, MCP_AUTH_FILENAME),
|
|
1696
|
+
legacyAuthFile: path6.join(configDir, AUTH_FILENAME),
|
|
1697
|
+
legacyMcpAuthFile: path6.join(configDir, MCP_AUTH_FILENAME),
|
|
1698
|
+
authStateFile: path6.join(credentialsDir, AUTH_STATE_FILENAME),
|
|
1699
|
+
projectsFile: path6.join(configDir, PROJECTS_FILENAME),
|
|
1700
|
+
cacheDir: path6.join(root, CACHE_DIRNAME),
|
|
1701
|
+
toolOutputCacheDir: path6.join(
|
|
1702
|
+
root,
|
|
1703
|
+
CACHE_DIRNAME,
|
|
1704
|
+
TOOL_OUTPUT_CACHE_DIRNAME
|
|
1705
|
+
),
|
|
1706
|
+
sessionsDir: path6.join(root, SESSIONS_DIRNAME),
|
|
1707
|
+
logsDir: path6.join(root, LOGS_DIRNAME)
|
|
1708
|
+
};
|
|
1709
|
+
}
|
|
1710
|
+
function buildXdgLayout() {
|
|
1711
|
+
const home = os2.homedir();
|
|
1712
|
+
const configRoot = process.env.XDG_CONFIG_HOME ?? path6.join(home, ".config");
|
|
1713
|
+
const cacheRoot = process.env.XDG_CACHE_HOME ?? path6.join(home, ".cache");
|
|
1714
|
+
const stateRoot = process.env.XDG_STATE_HOME ?? path6.join(home, ".local", "state");
|
|
1715
|
+
const configDir = path6.join(configRoot, XDG_DIR_NAME);
|
|
1716
|
+
const credentialsDir = path6.join(configDir, CREDENTIALS_DIRNAME);
|
|
1717
|
+
const cacheDir = path6.join(cacheRoot, XDG_DIR_NAME);
|
|
1718
|
+
const stateDir = path6.join(stateRoot, XDG_DIR_NAME);
|
|
1719
|
+
return {
|
|
1720
|
+
root: stateDir,
|
|
1721
|
+
configDir,
|
|
1722
|
+
configFile: path6.join(configDir, CONFIG_FILENAME),
|
|
1723
|
+
credentialsDir,
|
|
1724
|
+
authFile: path6.join(credentialsDir, AUTH_FILENAME),
|
|
1725
|
+
mcpAuthFile: path6.join(credentialsDir, MCP_AUTH_FILENAME),
|
|
1726
|
+
legacyAuthFile: path6.join(configDir, AUTH_FILENAME),
|
|
1727
|
+
legacyMcpAuthFile: path6.join(configDir, MCP_AUTH_FILENAME),
|
|
1728
|
+
authStateFile: path6.join(credentialsDir, AUTH_STATE_FILENAME),
|
|
1729
|
+
projectsFile: path6.join(configDir, PROJECTS_FILENAME),
|
|
1730
|
+
cacheDir,
|
|
1731
|
+
toolOutputCacheDir: path6.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
|
|
1732
|
+
sessionsDir: path6.join(stateDir, SESSIONS_DIRNAME),
|
|
1733
|
+
logsDir: path6.join(stateDir, LOGS_DIRNAME)
|
|
1734
|
+
};
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
// src/credential-backend.ts
|
|
1738
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1739
|
+
var probeUnavailableError = (probe, message = probe.message) => new KeychainError(
|
|
1740
|
+
probe.reason === "keychain_locked" ? "keychain_locked" : "keychain_unavailable",
|
|
1741
|
+
message
|
|
1742
|
+
);
|
|
1743
|
+
var buildSteadyState = (activeBackend, mcpReauthRequired) => ({
|
|
1744
|
+
version: 1,
|
|
1745
|
+
status: "steady",
|
|
1746
|
+
active_backend: activeBackend,
|
|
1747
|
+
...mcpReauthRequired?.length ? { mcp_reauth_required: [...mcpReauthRequired] } : {}
|
|
1748
|
+
});
|
|
1749
|
+
var isKeyringOwnedOrTargeting = (state) => state?.active_backend === "keyring" || state?.status === "migrating" && state.target_backend === "keyring";
|
|
1750
|
+
var isKeyringInvolved = (state) => isKeyringOwnedOrTargeting(state) || state?.status === "migrating" && state.cleanup_pending?.source_backend === "keyring";
|
|
1751
|
+
var parseStorageModeValue = (value) => {
|
|
1752
|
+
if (value === "auto" || value === "keyring" || value === "file") {
|
|
1753
|
+
return value;
|
|
1754
|
+
}
|
|
1755
|
+
return void 0;
|
|
1756
|
+
};
|
|
1757
|
+
var resolveConfiguredAuthStorageMode = (paths, overrideMode) => {
|
|
1758
|
+
if (overrideMode) return overrideMode;
|
|
1759
|
+
const envRaw = process.env.CODELIA_AUTH_STORAGE?.trim();
|
|
1760
|
+
if (envRaw) {
|
|
1761
|
+
const parsed = parseStorageModeValue(envRaw);
|
|
1762
|
+
if (!parsed) {
|
|
1763
|
+
throw new Error(
|
|
1764
|
+
`Invalid CODELIA_AUTH_STORAGE="${envRaw}" (expected "auto", "keyring", or "file")`
|
|
1765
|
+
);
|
|
1766
|
+
}
|
|
1767
|
+
return parsed;
|
|
1768
|
+
}
|
|
1769
|
+
const globalConfigPath = process.env.CODELIA_CONFIG_PATH?.trim() ? path7.resolve(process.env.CODELIA_CONFIG_PATH.trim()) : paths.configFile;
|
|
1770
|
+
try {
|
|
1771
|
+
const raw = readFileSync2(globalConfigPath, "utf8");
|
|
1772
|
+
const parsed = JSON.parse(raw);
|
|
1773
|
+
if (isRecord3(parsed) && isRecord3(parsed.auth)) {
|
|
1774
|
+
const mode = parsed.auth.storage;
|
|
1775
|
+
if (mode !== void 0) {
|
|
1776
|
+
const valid = parseStorageModeValue(mode);
|
|
1777
|
+
if (!valid) {
|
|
1778
|
+
throw new Error(
|
|
1779
|
+
`Invalid global auth.storage="${String(mode)}" (expected "auto", "keyring", or "file")`
|
|
1780
|
+
);
|
|
1781
|
+
}
|
|
1782
|
+
return valid;
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
} catch (error) {
|
|
1786
|
+
if (error?.code !== "ENOENT") {
|
|
1787
|
+
if (error instanceof Error && error.message.startsWith("Invalid global auth.storage")) {
|
|
1788
|
+
throw error;
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
return "auto";
|
|
1793
|
+
};
|
|
1794
|
+
var readTextIfPresent = async (filePath, legacy = false) => {
|
|
1795
|
+
if (!await verifyWindowsCredentialFileAcl(filePath, legacy)) return null;
|
|
1796
|
+
try {
|
|
1797
|
+
return await fs5.readFile(filePath, "utf8");
|
|
1798
|
+
} catch (error) {
|
|
1799
|
+
if (error?.code === "ENOENT") return null;
|
|
1800
|
+
throw error;
|
|
1801
|
+
}
|
|
1802
|
+
};
|
|
1803
|
+
var readFileSlot = async (filePath, adapter, legacy = false) => {
|
|
1804
|
+
const text = await readTextIfPresent(filePath, legacy);
|
|
1805
|
+
if (text === null) {
|
|
1806
|
+
return { present: false, normalized: adapter.empty(), nonEmpty: false };
|
|
1807
|
+
}
|
|
1808
|
+
const parsed = adapter.parse(text);
|
|
1809
|
+
return {
|
|
1810
|
+
present: true,
|
|
1811
|
+
normalized: parsed.normalized,
|
|
1812
|
+
nonEmpty: adapter.isNonEmpty(parsed.normalized),
|
|
1813
|
+
sourceVersion: parsed.sourceVersion,
|
|
1814
|
+
extraWarnings: parsed.extraWarnings
|
|
1815
|
+
};
|
|
1816
|
+
};
|
|
1817
|
+
var readKeychainSlot = async (keychain, service, account, adapter) => {
|
|
1818
|
+
const text = await keychain.get(service, account);
|
|
1819
|
+
if (text === null) {
|
|
1820
|
+
return { present: false, normalized: adapter.empty(), nonEmpty: false };
|
|
1821
|
+
}
|
|
1822
|
+
const parsed = adapter.parse(text);
|
|
1823
|
+
return {
|
|
1824
|
+
present: true,
|
|
1825
|
+
normalized: parsed.normalized,
|
|
1826
|
+
nonEmpty: adapter.isNonEmpty(parsed.normalized)
|
|
1827
|
+
};
|
|
1828
|
+
};
|
|
1829
|
+
var unlinkIfPresent = async (filePath) => {
|
|
1830
|
+
try {
|
|
1831
|
+
await fs5.unlink(filePath);
|
|
1832
|
+
} catch (error) {
|
|
1833
|
+
if (error?.code === "ENOENT") return;
|
|
1834
|
+
throw error;
|
|
1835
|
+
}
|
|
1836
|
+
};
|
|
1837
|
+
var makeKeychainTargetSlot = (keychain, account, adapter, sourcePath) => ({
|
|
1838
|
+
name: adapter.name,
|
|
1839
|
+
readSource: () => readFileSlot(sourcePath, adapter),
|
|
1840
|
+
readDest: () => readKeychainSlot(keychain, adapter.service, account, adapter),
|
|
1841
|
+
writeDest: async (normalized) => {
|
|
1842
|
+
await keychain.set(adapter.service, account, JSON.stringify(normalized));
|
|
1843
|
+
},
|
|
1844
|
+
verifyDest: async (expected) => {
|
|
1845
|
+
const back = await readKeychainSlot(
|
|
1846
|
+
keychain,
|
|
1847
|
+
adapter.service,
|
|
1848
|
+
account,
|
|
1849
|
+
adapter
|
|
1850
|
+
);
|
|
1851
|
+
return back.present && canonicalJsonEqual(back.normalized, expected);
|
|
1852
|
+
},
|
|
1853
|
+
cleanupSource: () => unlinkIfPresent(sourcePath)
|
|
1854
|
+
});
|
|
1855
|
+
var makeFileDestHandlers = (paths, adapter) => {
|
|
1856
|
+
const destPath = adapter.filePath(paths);
|
|
1857
|
+
return {
|
|
1858
|
+
readDest: () => readFileSlot(destPath, adapter),
|
|
1859
|
+
writeDest: async (normalized) => {
|
|
1860
|
+
await ensureStorageDirs(paths);
|
|
1861
|
+
await writeFileAtomic(destPath, JSON.stringify(normalized, null, 2), {
|
|
1862
|
+
mode: 384
|
|
1863
|
+
});
|
|
1864
|
+
},
|
|
1865
|
+
verifyDest: async (expected) => {
|
|
1866
|
+
const back = await readFileSlot(destPath, adapter);
|
|
1867
|
+
return back.present && canonicalJsonEqual(back.normalized, expected);
|
|
1868
|
+
}
|
|
1869
|
+
};
|
|
1870
|
+
};
|
|
1871
|
+
var makeFileFromKeychainSlot = (paths, keychain, account, adapter) => ({
|
|
1872
|
+
name: adapter.name,
|
|
1873
|
+
readSource: () => readKeychainSlot(keychain, adapter.service, account, adapter),
|
|
1874
|
+
...makeFileDestHandlers(paths, adapter),
|
|
1875
|
+
cleanupSource: async () => {
|
|
1876
|
+
await keychain.delete(adapter.service, account);
|
|
1877
|
+
}
|
|
1878
|
+
});
|
|
1879
|
+
var makeFileFromLegacySlot = (paths, adapter) => {
|
|
1880
|
+
const sourcePath = adapter.legacyFilePath(paths);
|
|
1881
|
+
return {
|
|
1882
|
+
name: adapter.name,
|
|
1883
|
+
readSource: () => readFileSlot(sourcePath, adapter, true),
|
|
1884
|
+
...makeFileDestHandlers(paths, adapter),
|
|
1885
|
+
cleanupSource: () => unlinkIfPresent(sourcePath)
|
|
1886
|
+
};
|
|
1887
|
+
};
|
|
1888
|
+
var completePendingCleanupUnlocked = async (options) => {
|
|
1889
|
+
const pending = options.state.cleanup_pending;
|
|
1890
|
+
if (!pending) return options.state;
|
|
1891
|
+
if (pending.source_backend === "keyring" && options.state.target_backend === "file") {
|
|
1892
|
+
const probe = await options.keychain.probe();
|
|
1893
|
+
if (!probe.available) {
|
|
1894
|
+
throw probeUnavailableError(
|
|
1895
|
+
probe,
|
|
1896
|
+
`Cannot finish cleanup of previous Keychain credentials after migration while Keychain is unavailable (${probe.reason}): ${probe.message}`
|
|
1897
|
+
);
|
|
1898
|
+
}
|
|
1899
|
+
if (pending.auth) {
|
|
1900
|
+
await options.keychain.delete(
|
|
1901
|
+
options.authAdapter.service,
|
|
1902
|
+
options.account
|
|
1903
|
+
);
|
|
1904
|
+
}
|
|
1905
|
+
if (pending.mcp_auth) {
|
|
1906
|
+
await options.keychain.delete(
|
|
1907
|
+
options.mcpAdapter.service,
|
|
1908
|
+
options.account
|
|
1909
|
+
);
|
|
1910
|
+
}
|
|
1911
|
+
} else if (pending.source_backend === "legacy_file") {
|
|
1912
|
+
if (pending.auth) {
|
|
1913
|
+
await unlinkIfPresent(options.authAdapter.legacyFilePath(options.paths));
|
|
1914
|
+
}
|
|
1915
|
+
if (pending.mcp_auth) {
|
|
1916
|
+
await unlinkIfPresent(options.mcpAdapter.legacyFilePath(options.paths));
|
|
1917
|
+
}
|
|
1918
|
+
} else {
|
|
1919
|
+
const isLegacyCleanup = options.state.target_backend !== "keyring";
|
|
1920
|
+
const cleanupAuthPath = isLegacyCleanup ? options.authAdapter.legacyFilePath(options.paths) : options.authAdapter.filePath(options.paths);
|
|
1921
|
+
const cleanupMcpPath = isLegacyCleanup ? options.mcpAdapter.legacyFilePath(options.paths) : options.mcpAdapter.filePath(options.paths);
|
|
1922
|
+
if (pending.auth) {
|
|
1923
|
+
await unlinkIfPresent(cleanupAuthPath);
|
|
1924
|
+
}
|
|
1925
|
+
if (pending.mcp_auth) {
|
|
1926
|
+
await unlinkIfPresent(cleanupMcpPath);
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
const committed = buildSteadyState(
|
|
1930
|
+
options.state.target_backend,
|
|
1931
|
+
options.state.mcp_reauth_required
|
|
1932
|
+
);
|
|
1933
|
+
await writeAuthStorageState(options.paths.authStateFile, committed);
|
|
1934
|
+
return committed;
|
|
1935
|
+
};
|
|
1936
|
+
var coordinateCredentialBackendUnlocked = async (options) => {
|
|
1937
|
+
const { paths, authAdapter, mcpAdapter } = options;
|
|
1938
|
+
const keychain = options.keychain ?? new MacOsKeychainClient({ credentialsDir: paths.credentialsDir });
|
|
1939
|
+
const configured = resolveConfiguredAuthStorageMode(
|
|
1940
|
+
paths,
|
|
1941
|
+
options.storageMode
|
|
1942
|
+
);
|
|
1943
|
+
const account = keychainAccountForConfigDir(paths.configDir);
|
|
1944
|
+
await ensureStorageDirs(paths);
|
|
1945
|
+
let state = await readAuthStorageState(
|
|
1946
|
+
paths.authStateFile
|
|
1947
|
+
);
|
|
1948
|
+
if (state?.status === "migrating" && state.cleanup_pending) {
|
|
1949
|
+
state = await completePendingCleanupUnlocked({
|
|
1950
|
+
paths,
|
|
1951
|
+
state,
|
|
1952
|
+
keychain,
|
|
1953
|
+
account,
|
|
1954
|
+
authAdapter,
|
|
1955
|
+
mcpAdapter
|
|
64
1956
|
});
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
mode: 384
|
|
93
|
-
});
|
|
94
|
-
}
|
|
95
|
-
await writeFile(
|
|
96
|
-
path.join(dir, "metadata.json"),
|
|
97
|
-
JSON.stringify(metadata),
|
|
98
|
-
{ flag: "wx", mode: 384 }
|
|
1957
|
+
}
|
|
1958
|
+
const migrateLegacyToCredentials = async () => {
|
|
1959
|
+
const [legacyAuth, legacyMcp] = await Promise.all([
|
|
1960
|
+
readTextIfPresent(authAdapter.legacyFilePath(paths), true),
|
|
1961
|
+
readTextIfPresent(mcpAdapter.legacyFilePath(paths), true)
|
|
1962
|
+
]);
|
|
1963
|
+
if (legacyAuth === null && legacyMcp === null) return;
|
|
1964
|
+
await runTwoPhaseMigration({
|
|
1965
|
+
stateFile: paths.authStateFile,
|
|
1966
|
+
fromBackend: state?.active_backend ?? "file",
|
|
1967
|
+
toBackend: state?.active_backend ?? "file",
|
|
1968
|
+
cleanupSourceKind: "legacy_file",
|
|
1969
|
+
authSlot: makeFileFromLegacySlot(paths, authAdapter),
|
|
1970
|
+
mcpSlot: makeFileFromLegacySlot(paths, mcpAdapter),
|
|
1971
|
+
existingMcpReauth: state?.mcp_reauth_required
|
|
1972
|
+
});
|
|
1973
|
+
state = await readAuthStorageState(paths.authStateFile);
|
|
1974
|
+
};
|
|
1975
|
+
const keyringOwnedOrInFlight = isKeyringOwnedOrTargeting(state);
|
|
1976
|
+
if (configured === "file") {
|
|
1977
|
+
await migrateLegacyToCredentials();
|
|
1978
|
+
if (keyringOwnedOrInFlight) {
|
|
1979
|
+
const probe2 = await keychain.probe();
|
|
1980
|
+
if (!probe2.available) {
|
|
1981
|
+
throw probeUnavailableError(
|
|
1982
|
+
probe2,
|
|
1983
|
+
`Cannot switch auth.storage to "file" while Keychain is unavailable: ${probe2.message}`
|
|
99
1984
|
);
|
|
100
1985
|
}
|
|
101
|
-
await
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
1986
|
+
await runTwoPhaseMigration({
|
|
1987
|
+
stateFile: paths.authStateFile,
|
|
1988
|
+
fromBackend: "keyring",
|
|
1989
|
+
toBackend: "file",
|
|
1990
|
+
authSlot: makeFileFromKeychainSlot(
|
|
1991
|
+
paths,
|
|
1992
|
+
keychain,
|
|
1993
|
+
account,
|
|
1994
|
+
authAdapter
|
|
108
1995
|
),
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
1996
|
+
mcpSlot: makeFileFromKeychainSlot(paths, keychain, account, mcpAdapter),
|
|
1997
|
+
existingMcpReauth: state?.mcp_reauth_required,
|
|
1998
|
+
commitSteadyIfEmpty: true
|
|
1999
|
+
});
|
|
2000
|
+
state = await readAuthStorageState(paths.authStateFile);
|
|
2001
|
+
} else if (!state || state.status === "migrating") {
|
|
2002
|
+
await writeAuthStorageState(
|
|
2003
|
+
paths.authStateFile,
|
|
2004
|
+
buildSteadyState("file", state?.mcp_reauth_required)
|
|
2005
|
+
);
|
|
112
2006
|
}
|
|
2007
|
+
return {
|
|
2008
|
+
configured,
|
|
2009
|
+
active: "file",
|
|
2010
|
+
state: "steady"
|
|
2011
|
+
};
|
|
113
2012
|
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
if (
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
ref.byte_size
|
|
2013
|
+
const probe = await keychain.probe();
|
|
2014
|
+
if (!probe.available) {
|
|
2015
|
+
if (configured === "keyring") {
|
|
2016
|
+
throw probeUnavailableError(probe);
|
|
2017
|
+
}
|
|
2018
|
+
if (keyringOwnedOrInFlight) {
|
|
2019
|
+
throw probeUnavailableError(
|
|
2020
|
+
probe,
|
|
2021
|
+
`Credentials are managed in macOS Keychain. ${probe.message}`
|
|
124
2022
|
);
|
|
125
|
-
if (bytes.length !== ref.byte_size || digest(bytes) !== ref.sha256)
|
|
126
|
-
throw new Error("Attachment original is corrupt");
|
|
127
2023
|
}
|
|
128
|
-
|
|
2024
|
+
await migrateLegacyToCredentials();
|
|
2025
|
+
return {
|
|
2026
|
+
configured,
|
|
2027
|
+
active: "file",
|
|
2028
|
+
state: "steady",
|
|
2029
|
+
fallbackReason: probe.reason
|
|
2030
|
+
};
|
|
129
2031
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
2032
|
+
await migrateLegacyToCredentials();
|
|
2033
|
+
const [credAuthText, credMcpText] = await Promise.all([
|
|
2034
|
+
readTextIfPresent(authAdapter.filePath(paths)),
|
|
2035
|
+
readTextIfPresent(mcpAdapter.filePath(paths))
|
|
2036
|
+
]);
|
|
2037
|
+
if (credAuthText !== null || credMcpText !== null || state?.status === "migrating") {
|
|
2038
|
+
await runTwoPhaseMigration({
|
|
2039
|
+
stateFile: paths.authStateFile,
|
|
2040
|
+
fromBackend: "file",
|
|
2041
|
+
toBackend: "keyring",
|
|
2042
|
+
authSlot: makeKeychainTargetSlot(
|
|
2043
|
+
keychain,
|
|
2044
|
+
account,
|
|
2045
|
+
authAdapter,
|
|
2046
|
+
authAdapter.filePath(paths)
|
|
2047
|
+
),
|
|
2048
|
+
mcpSlot: makeKeychainTargetSlot(
|
|
2049
|
+
keychain,
|
|
2050
|
+
account,
|
|
2051
|
+
mcpAdapter,
|
|
2052
|
+
mcpAdapter.filePath(paths)
|
|
2053
|
+
),
|
|
2054
|
+
existingMcpReauth: state?.mcp_reauth_required,
|
|
2055
|
+
commitSteadyIfEmpty: true
|
|
2056
|
+
});
|
|
2057
|
+
state = await readAuthStorageState(paths.authStateFile);
|
|
2058
|
+
} else if (state?.active_backend !== "keyring") {
|
|
2059
|
+
await writeAuthStorageState(
|
|
2060
|
+
paths.authStateFile,
|
|
2061
|
+
buildSteadyState("keyring", state?.mcp_reauth_required)
|
|
141
2062
|
);
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
2063
|
+
}
|
|
2064
|
+
return {
|
|
2065
|
+
configured,
|
|
2066
|
+
active: "keyring",
|
|
2067
|
+
state: "steady"
|
|
2068
|
+
};
|
|
2069
|
+
};
|
|
2070
|
+
var coordinateCredentialBackend = (options) => {
|
|
2071
|
+
const paths = options.paths ?? resolveStoragePaths();
|
|
2072
|
+
return withAuthStoreLock(
|
|
2073
|
+
authLockPathFor(paths.credentialsDir),
|
|
2074
|
+
() => coordinateCredentialBackendUnlocked({
|
|
2075
|
+
...options,
|
|
2076
|
+
paths
|
|
2077
|
+
}),
|
|
2078
|
+
options.lock
|
|
2079
|
+
);
|
|
2080
|
+
};
|
|
2081
|
+
var clearStoreAcrossAllLocationsUnlocked = async (options) => {
|
|
2082
|
+
const { paths, adapter } = options;
|
|
2083
|
+
const keychain = options.keychain ?? new MacOsKeychainClient({ credentialsDir: paths.credentialsDir });
|
|
2084
|
+
const account = keychainAccountForConfigDir(paths.configDir);
|
|
2085
|
+
await ensureStorageDirs(paths);
|
|
2086
|
+
await unlinkIfPresent(adapter.filePath(paths));
|
|
2087
|
+
await unlinkIfPresent(adapter.legacyFilePath(paths));
|
|
2088
|
+
const probe = await keychain.probe();
|
|
2089
|
+
if (probe.available) {
|
|
2090
|
+
await keychain.delete(adapter.service, account);
|
|
2091
|
+
} else {
|
|
2092
|
+
const storedState = await readAuthStorageState(paths.authStateFile).catch(
|
|
2093
|
+
() => null
|
|
2094
|
+
);
|
|
2095
|
+
if (isKeyringInvolved(storedState)) {
|
|
2096
|
+
throw probeUnavailableError(
|
|
2097
|
+
probe,
|
|
2098
|
+
`Cannot clear Keychain credentials while Keychain is unavailable (${probe.reason}): ${probe.message}`
|
|
152
2099
|
);
|
|
153
|
-
let count = 0;
|
|
154
|
-
while (count < bytes.length) {
|
|
155
|
-
const result = await file.read(
|
|
156
|
-
bytes,
|
|
157
|
-
count,
|
|
158
|
-
bytes.length - count,
|
|
159
|
-
start + count
|
|
160
|
-
);
|
|
161
|
-
if (!result.bytesRead)
|
|
162
|
-
throw new Error("Attachment original is corrupt");
|
|
163
|
-
count += result.bytesRead;
|
|
164
|
-
}
|
|
165
|
-
for (let block = firstBlock; block < lastBlock; block++) {
|
|
166
|
-
const beg = (block - firstBlock) * BLOCK_BYTES;
|
|
167
|
-
if (metadata.blocks?.[block] !== digest(bytes.subarray(beg, beg + BLOCK_BYTES))) {
|
|
168
|
-
throw new Error("Attachment original is corrupt");
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
return bytes.subarray(offset - start, end - start);
|
|
172
|
-
} finally {
|
|
173
|
-
await file.close();
|
|
174
2100
|
}
|
|
175
2101
|
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
2102
|
+
};
|
|
2103
|
+
var resolveDefaultTargetBackend = async (configured, keychain) => {
|
|
2104
|
+
if (configured === "file") return "file";
|
|
2105
|
+
if (configured === "keyring") return "keyring";
|
|
2106
|
+
return (await keychain.probe()).available ? "keyring" : "file";
|
|
2107
|
+
};
|
|
2108
|
+
var resolveKeepKeyringStore = async (ctx, adapter) => {
|
|
2109
|
+
const probe = await ctx.keychain.probe();
|
|
2110
|
+
if (!probe.available) {
|
|
2111
|
+
throw probeUnavailableError(
|
|
2112
|
+
probe,
|
|
2113
|
+
`Cannot keep Keychain credentials while Keychain is unavailable: ${probe.message}`
|
|
2114
|
+
);
|
|
2115
|
+
}
|
|
2116
|
+
const slot = await readKeychainSlot(
|
|
2117
|
+
ctx.keychain,
|
|
2118
|
+
adapter.service,
|
|
2119
|
+
ctx.account,
|
|
2120
|
+
adapter
|
|
2121
|
+
);
|
|
2122
|
+
const fileSlot = await readFileSlot(
|
|
2123
|
+
adapter.filePath(ctx.paths),
|
|
2124
|
+
adapter
|
|
2125
|
+
).catch(() => ({ present: true, nonEmpty: true }));
|
|
2126
|
+
const legacySlot = await readFileSlot(
|
|
2127
|
+
adapter.legacyFilePath(ctx.paths),
|
|
2128
|
+
adapter,
|
|
2129
|
+
true
|
|
2130
|
+
).catch(() => ({ present: true, nonEmpty: true }));
|
|
2131
|
+
if (!slot.present && !fileSlot.present && !legacySlot.present) {
|
|
2132
|
+
return;
|
|
2133
|
+
}
|
|
2134
|
+
if (!slot.present || !slot.nonEmpty && (fileSlot.nonEmpty || legacySlot.nonEmpty)) {
|
|
2135
|
+
throw new Error(
|
|
2136
|
+
`Cannot keep Keychain store for '${adapter.name}': Keychain has no saved credentials`
|
|
2137
|
+
);
|
|
2138
|
+
}
|
|
2139
|
+
await unlinkIfPresent(adapter.filePath(ctx.paths));
|
|
2140
|
+
await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
|
|
2141
|
+
};
|
|
2142
|
+
var resolveKeepFileStore = async (ctx, adapter) => {
|
|
2143
|
+
const slot = await readFileSlot(adapter.filePath(ctx.paths), adapter);
|
|
2144
|
+
if (!slot.present) {
|
|
2145
|
+
throw new Error(
|
|
2146
|
+
`Cannot keep file store for '${adapter.name}': ${adapter.filePath(ctx.paths)} does not exist`
|
|
2147
|
+
);
|
|
2148
|
+
}
|
|
2149
|
+
await writeFileAtomic(
|
|
2150
|
+
adapter.filePath(ctx.paths),
|
|
2151
|
+
JSON.stringify(slot.normalized, null, 2),
|
|
2152
|
+
{ mode: 384 }
|
|
2153
|
+
);
|
|
2154
|
+
await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
|
|
2155
|
+
const probe = await ctx.keychain.probe();
|
|
2156
|
+
if (probe.available) {
|
|
2157
|
+
await ctx.keychain.delete(adapter.service, ctx.account);
|
|
2158
|
+
} else if (ctx.existingState?.active_backend === "keyring") {
|
|
2159
|
+
throw probeUnavailableError(
|
|
2160
|
+
probe,
|
|
2161
|
+
`Cannot remove superseded Keychain entry while Keychain is unavailable: ${probe.message}`
|
|
2162
|
+
);
|
|
2163
|
+
}
|
|
2164
|
+
};
|
|
2165
|
+
var resolveKeepLegacyStore = async (ctx, adapter) => {
|
|
2166
|
+
const legacy = await readFileSlot(
|
|
2167
|
+
adapter.legacyFilePath(ctx.paths),
|
|
2168
|
+
adapter,
|
|
2169
|
+
true
|
|
2170
|
+
);
|
|
2171
|
+
if (!legacy.present) {
|
|
2172
|
+
throw new Error(
|
|
2173
|
+
`Cannot keep legacy store for '${adapter.name}': ${adapter.legacyFilePath(ctx.paths)} does not exist`
|
|
2174
|
+
);
|
|
2175
|
+
}
|
|
2176
|
+
const targetBackend = await resolveDefaultTargetBackend(
|
|
2177
|
+
ctx.configured,
|
|
2178
|
+
ctx.keychain
|
|
2179
|
+
);
|
|
2180
|
+
if (targetBackend === "keyring") {
|
|
2181
|
+
const probe2 = await ctx.keychain.probe();
|
|
2182
|
+
if (!probe2.available) {
|
|
2183
|
+
throw probeUnavailableError(
|
|
2184
|
+
probe2,
|
|
2185
|
+
`Cannot promote legacy store to Keychain while Keychain is unavailable: ${probe2.message}`
|
|
183
2186
|
);
|
|
184
|
-
const { ref, imageRef, blocks } = metadata;
|
|
185
|
-
if (metadata.sessionId !== sessionId || !UUID.test(metadata.batch) || ref?.attachment_id !== attachmentId)
|
|
186
|
-
return null;
|
|
187
|
-
if (!Number.isSafeInteger(ref.byte_size) || ref.byte_size < 0 || ref.byte_size > MAX_BYTES || !SHA256.test(ref.sha256) || typeof ref.media_type !== "string" || typeof ref.display_name !== "string")
|
|
188
|
-
throw new Error("Invalid attachment metadata");
|
|
189
|
-
if (!imageRef && (!Array.isArray(blocks) || blocks.length !== Math.ceil(ref.byte_size / BLOCK_BYTES)))
|
|
190
|
-
throw new Error("Invalid attachment block index");
|
|
191
|
-
const marker = path.join(this.root, "committed", metadata.batch);
|
|
192
|
-
return (await lstat(marker)).isFile() ? metadata : null;
|
|
193
|
-
} catch (error) {
|
|
194
|
-
if (error.code === "ENOENT") return null;
|
|
195
|
-
throw error;
|
|
196
2187
|
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
sessionId
|
|
202
|
-
}) {
|
|
203
|
-
if (!imageRef || imageRef.sha256 !== ref.sha256 || imageRef.byte_size !== ref.byte_size || imageRef.media_type !== ref.media_type || imageRef.width !== ref.width || imageRef.height !== ref.height)
|
|
204
|
-
throw new Error("Invalid image attachment reference");
|
|
205
|
-
const { metadata, bytes } = await this.images.read(
|
|
206
|
-
imageRef.artifact_id,
|
|
207
|
-
sessionId
|
|
2188
|
+
await ctx.keychain.set(
|
|
2189
|
+
adapter.service,
|
|
2190
|
+
ctx.account,
|
|
2191
|
+
JSON.stringify(legacy.normalized)
|
|
208
2192
|
);
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
2193
|
+
const verify = await readKeychainSlot(
|
|
2194
|
+
ctx.keychain,
|
|
2195
|
+
adapter.service,
|
|
2196
|
+
ctx.account,
|
|
2197
|
+
adapter
|
|
2198
|
+
);
|
|
2199
|
+
if (!verify.present || !canonicalJsonEqual(verify.normalized, legacy.normalized)) {
|
|
2200
|
+
throw new Error(
|
|
2201
|
+
`Failed to verify promoted '${adapter.name}' in Keychain`
|
|
2202
|
+
);
|
|
2203
|
+
}
|
|
2204
|
+
await unlinkIfPresent(adapter.filePath(ctx.paths));
|
|
2205
|
+
await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
|
|
2206
|
+
return;
|
|
2207
|
+
}
|
|
2208
|
+
await writeFileAtomic(
|
|
2209
|
+
adapter.filePath(ctx.paths),
|
|
2210
|
+
JSON.stringify(legacy.normalized, null, 2),
|
|
2211
|
+
{ mode: 384 }
|
|
2212
|
+
);
|
|
2213
|
+
await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
|
|
2214
|
+
const probe = await ctx.keychain.probe();
|
|
2215
|
+
if (probe.available) {
|
|
2216
|
+
await ctx.keychain.delete(adapter.service, ctx.account);
|
|
2217
|
+
}
|
|
2218
|
+
};
|
|
2219
|
+
var resolveCredentialConflict = async (options) => {
|
|
2220
|
+
const paths = options.paths ?? resolveStoragePaths();
|
|
2221
|
+
const keychain = options.keychain ?? new MacOsKeychainClient({ credentialsDir: paths.credentialsDir });
|
|
2222
|
+
const account = keychainAccountForConfigDir(paths.configDir);
|
|
2223
|
+
const targets = options.stores?.length ? [...new Set(options.stores)] : ["auth", "mcp_auth"];
|
|
2224
|
+
return withAuthStoreLock(
|
|
2225
|
+
authLockPathFor(paths.credentialsDir),
|
|
2226
|
+
async () => {
|
|
2227
|
+
await ensureStorageDirs(paths);
|
|
2228
|
+
const configured = resolveConfiguredAuthStorageMode(
|
|
2229
|
+
paths,
|
|
2230
|
+
options.storageMode
|
|
2231
|
+
);
|
|
2232
|
+
const existingState = await readAuthStorageState(
|
|
2233
|
+
paths.authStateFile
|
|
2234
|
+
).catch(() => null);
|
|
2235
|
+
const ctx = {
|
|
2236
|
+
paths,
|
|
2237
|
+
keychain,
|
|
2238
|
+
account,
|
|
2239
|
+
configured,
|
|
2240
|
+
existingState
|
|
2241
|
+
};
|
|
2242
|
+
const resolveOne = async (adapter) => {
|
|
2243
|
+
switch (options.strategy) {
|
|
2244
|
+
case "clear_all":
|
|
2245
|
+
await clearStoreAcrossAllLocationsUnlocked({
|
|
2246
|
+
paths,
|
|
2247
|
+
adapter,
|
|
2248
|
+
keychain
|
|
2249
|
+
});
|
|
2250
|
+
return;
|
|
2251
|
+
case "keep_keyring":
|
|
2252
|
+
await resolveKeepKeyringStore(ctx, adapter);
|
|
2253
|
+
return;
|
|
2254
|
+
case "keep_file":
|
|
2255
|
+
await resolveKeepFileStore(ctx, adapter);
|
|
2256
|
+
return;
|
|
2257
|
+
case "keep_legacy":
|
|
2258
|
+
await resolveKeepLegacyStore(ctx, adapter);
|
|
2259
|
+
return;
|
|
2260
|
+
}
|
|
2261
|
+
};
|
|
2262
|
+
for (const storeName of targets) {
|
|
2263
|
+
if (storeName === "auth") {
|
|
2264
|
+
await resolveOne(options.authAdapter);
|
|
2265
|
+
} else {
|
|
2266
|
+
await resolveOne(options.mcpAdapter);
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
const targetActive = options.strategy === "keep_keyring" ? "keyring" : options.strategy === "keep_file" ? "file" : await resolveDefaultTargetBackend(configured, keychain);
|
|
2270
|
+
await writeAuthStorageState(
|
|
2271
|
+
paths.authStateFile,
|
|
2272
|
+
buildSteadyState(targetActive, existingState?.mcp_reauth_required)
|
|
2273
|
+
);
|
|
2274
|
+
return { active: targetActive, resolvedStores: targets };
|
|
2275
|
+
},
|
|
2276
|
+
options.lock
|
|
2277
|
+
);
|
|
2278
|
+
};
|
|
2279
|
+
var inspectCredentialStorageStatus = async (options) => {
|
|
2280
|
+
const paths = options.paths ?? resolveStoragePaths();
|
|
2281
|
+
const keychain = options.keychain ?? new MacOsKeychainClient({
|
|
2282
|
+
credentialsDir: paths.credentialsDir
|
|
2283
|
+
});
|
|
2284
|
+
const configured = resolveConfiguredAuthStorageMode(
|
|
2285
|
+
paths,
|
|
2286
|
+
options.storageMode
|
|
2287
|
+
);
|
|
2288
|
+
const account = keychainAccountForConfigDir(paths.configDir);
|
|
2289
|
+
let stateCorrupt = false;
|
|
2290
|
+
let storedState = null;
|
|
2291
|
+
try {
|
|
2292
|
+
storedState = await readAuthStorageState(paths.authStateFile);
|
|
2293
|
+
} catch {
|
|
2294
|
+
stateCorrupt = true;
|
|
2295
|
+
}
|
|
2296
|
+
const mcpReauthRequired = storedState?.mcp_reauth_required ?? [];
|
|
2297
|
+
const keyringOwned = isKeyringInvolved(storedState);
|
|
2298
|
+
const shouldProbeKeychain = configured !== "file" || keyringOwned;
|
|
2299
|
+
const probe = shouldProbeKeychain ? await keychain.probe() : {
|
|
2300
|
+
available: false,
|
|
2301
|
+
reason: "keychain_unavailable",
|
|
2302
|
+
message: "file mode selected"
|
|
2303
|
+
};
|
|
2304
|
+
const inspectStore = async (adapter) => {
|
|
2305
|
+
let issue;
|
|
2306
|
+
const inspectKeychain = async () => {
|
|
2307
|
+
if (!probe.available) {
|
|
2308
|
+
if (keyringOwned || configured === "keyring") {
|
|
2309
|
+
issue = probe.reason === "keychain_locked" ? "keychain_locked" : "keychain_unavailable";
|
|
2310
|
+
}
|
|
2311
|
+
return null;
|
|
2312
|
+
}
|
|
2313
|
+
try {
|
|
2314
|
+
return await readKeychainSlot(
|
|
2315
|
+
keychain,
|
|
2316
|
+
adapter.service,
|
|
2317
|
+
account,
|
|
2318
|
+
adapter
|
|
2319
|
+
);
|
|
2320
|
+
} catch (error) {
|
|
2321
|
+
if (!(error instanceof KeychainError)) throw error;
|
|
2322
|
+
issue = error.code === "keychain_locked" || error.code === "keychain_access_denied" ? error.code : "keychain_unavailable";
|
|
2323
|
+
return null;
|
|
2324
|
+
}
|
|
2325
|
+
};
|
|
2326
|
+
const [current, legacy, native] = await Promise.all([
|
|
2327
|
+
readFileSlot(adapter.filePath(paths), adapter),
|
|
2328
|
+
readFileSlot(adapter.legacyFilePath(paths), adapter, true),
|
|
2329
|
+
inspectKeychain()
|
|
2330
|
+
]);
|
|
2331
|
+
const file = current.nonEmpty ? current : legacy;
|
|
2332
|
+
const conflict = current.nonEmpty && legacy.nonEmpty && !canonicalJsonEqual(current.normalized, legacy.normalized) || file.nonEmpty && native?.nonEmpty && !canonicalJsonEqual(file.normalized, native.normalized);
|
|
2333
|
+
return { file, native, conflict, issue };
|
|
2334
|
+
};
|
|
2335
|
+
const [auth, mcp] = await Promise.all([
|
|
2336
|
+
inspectStore(options.authAdapter).catch(() => null),
|
|
2337
|
+
inspectStore(options.mcpAdapter).catch(() => null)
|
|
2338
|
+
]);
|
|
2339
|
+
const keychainIssue = auth?.issue ?? mcp?.issue;
|
|
2340
|
+
const unreadableStores = [];
|
|
2341
|
+
if (!auth) unreadableStores.push("auth");
|
|
2342
|
+
if (!mcp) unreadableStores.push("mcp_auth");
|
|
2343
|
+
if (stateCorrupt) unreadableStores.push("storage_state");
|
|
2344
|
+
const conflictStores = [];
|
|
2345
|
+
if (auth?.conflict) conflictStores.push("auth");
|
|
2346
|
+
if (mcp?.conflict) conflictStores.push("mcp_auth");
|
|
2347
|
+
const state = stateCorrupt || conflictStores.length > 0 ? "conflict" : storedState?.status ?? "steady";
|
|
2348
|
+
const active = storedState?.active_backend ?? (auth?.file.nonEmpty || mcp?.file.nonEmpty ? "file" : probe.available || configured === "keyring" ? "keyring" : "file");
|
|
2349
|
+
const fallbackReason = configured === "auto" && active === "file" && !probe.available ? probe.reason : void 0;
|
|
2350
|
+
if (state === "steady" && auth && !auth.issue) {
|
|
2351
|
+
const snapshot = active === "file" ? auth.file : auth.native;
|
|
2352
|
+
if (snapshot?.nonEmpty) options.onReadableAuth?.(snapshot.normalized);
|
|
212
2353
|
}
|
|
2354
|
+
return {
|
|
2355
|
+
configured,
|
|
2356
|
+
active,
|
|
2357
|
+
state,
|
|
2358
|
+
...fallbackReason ? { fallbackReason } : {},
|
|
2359
|
+
mcpReauthRequired,
|
|
2360
|
+
conflictStores,
|
|
2361
|
+
unreadableStores,
|
|
2362
|
+
...keychainIssue ? { keychainIssue } : {}
|
|
2363
|
+
};
|
|
213
2364
|
};
|
|
214
2365
|
|
|
215
2366
|
// src/image-artifacts.ts
|
|
216
|
-
import { randomUUID as
|
|
217
|
-
import { lstat as lstat3, mkdir as
|
|
218
|
-
import
|
|
2367
|
+
import { randomUUID as randomUUID5 } from "crypto";
|
|
2368
|
+
import { lstat as lstat3, mkdir as mkdir4, rename as rename3, rm as rm3, writeFile as writeFile3 } from "fs/promises";
|
|
2369
|
+
import path9 from "path";
|
|
219
2370
|
|
|
220
2371
|
// src/image-attachment.ts
|
|
221
2372
|
import { imageSize } from "image-size";
|
|
222
2373
|
|
|
223
2374
|
// src/image-png.ts
|
|
224
|
-
import { promisify } from "util";
|
|
2375
|
+
import { promisify as promisify2 } from "util";
|
|
225
2376
|
import { inflate } from "zlib";
|
|
226
2377
|
var IMAGE_MAX_BYTES = 32 * 1024 * 1024;
|
|
227
2378
|
var IMAGE_MAX_SIDE = 12288;
|
|
228
2379
|
var IMAGE_MAX_PIXELS = 2e7;
|
|
229
|
-
var inflateAsync =
|
|
2380
|
+
var inflateAsync = promisify2(inflate);
|
|
230
2381
|
var crcTable = Uint32Array.from({ length: 256 }, (_, n) => {
|
|
231
2382
|
let c = n;
|
|
232
2383
|
for (let i = 0; i < 8; i++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
@@ -398,15 +2549,15 @@ function parseImageMetadata(value) {
|
|
|
398
2549
|
}
|
|
399
2550
|
|
|
400
2551
|
// src/image-model-view.ts
|
|
401
|
-
import { randomUUID as
|
|
402
|
-
import { lstat as lstat2, mkdir as
|
|
403
|
-
import
|
|
2552
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
2553
|
+
import { lstat as lstat2, mkdir as mkdir3, rename as rename2, rm as rm2, writeFile as writeFile2 } from "fs/promises";
|
|
2554
|
+
import path8 from "path";
|
|
404
2555
|
import {
|
|
405
2556
|
isImageModelView
|
|
406
2557
|
} from "@codelia/shared-types";
|
|
407
2558
|
import { imageSize as imageSize2 } from "image-size";
|
|
408
2559
|
var VERSION = "jpeg-q90-444-v1";
|
|
409
|
-
var directory = (root) =>
|
|
2560
|
+
var directory = (root) => path8.join(root, VERSION);
|
|
410
2561
|
var errorCode = (error) => error && typeof error === "object" && "code" in error ? error.code : void 0;
|
|
411
2562
|
async function readModelView(root, original, expected) {
|
|
412
2563
|
if (expected !== void 0 && !isImageModelView(expected))
|
|
@@ -415,7 +2566,7 @@ async function readModelView(root, original, expected) {
|
|
|
415
2566
|
if (!(await lstat2(dir)).isDirectory())
|
|
416
2567
|
throw new Error("Invalid model view directory");
|
|
417
2568
|
const record2 = JSON.parse(
|
|
418
|
-
(await readImageFileBounded(
|
|
2569
|
+
(await readImageFileBounded(path8.join(dir, "metadata.json"), 4096)).toString()
|
|
419
2570
|
);
|
|
420
2571
|
if (!record2 || record2.original_sha256 !== original.sha256 || !isImageModelView(record2.view))
|
|
421
2572
|
throw new Error("Invalid model view metadata");
|
|
@@ -423,7 +2574,7 @@ async function readModelView(root, original, expected) {
|
|
|
423
2574
|
if (expected && (view.sha256 !== expected.sha256 || view.byte_size !== expected.byte_size))
|
|
424
2575
|
throw new Error("Image model view reference mismatch");
|
|
425
2576
|
const bytes = await readImageFileBounded(
|
|
426
|
-
|
|
2577
|
+
path8.join(dir, "view.jpg"),
|
|
427
2578
|
32 * 1024 * 1024
|
|
428
2579
|
);
|
|
429
2580
|
const dims = imageSize2(bytes);
|
|
@@ -458,15 +2609,15 @@ async function prepareModelView(root, original, bytes) {
|
|
|
458
2609
|
sha256: imageHash(jpeg),
|
|
459
2610
|
byte_size: jpeg.length
|
|
460
2611
|
};
|
|
461
|
-
const temporary =
|
|
462
|
-
await
|
|
2612
|
+
const temporary = path8.join(root, `.model-view-${randomUUID4()}`);
|
|
2613
|
+
await mkdir3(temporary, { mode: 448 });
|
|
463
2614
|
try {
|
|
464
|
-
await writeFile2(
|
|
2615
|
+
await writeFile2(path8.join(temporary, "view.jpg"), jpeg, {
|
|
465
2616
|
flag: "wx",
|
|
466
2617
|
mode: 384
|
|
467
2618
|
});
|
|
468
2619
|
await writeFile2(
|
|
469
|
-
|
|
2620
|
+
path8.join(temporary, "metadata.json"),
|
|
470
2621
|
JSON.stringify({ original_sha256: original.sha256, view }),
|
|
471
2622
|
{ flag: "wx", mode: 384 }
|
|
472
2623
|
);
|
|
@@ -495,7 +2646,7 @@ var ImageArtifactStore = class {
|
|
|
495
2646
|
const dimensions = mediaType === "image/png" ? await validateImagePng(bytes) : validateImageAttachment(bytes, "image/jpeg");
|
|
496
2647
|
if (mediaType === "image/jpeg" && (bytes.at(-2) !== 255 || bytes.at(-1) !== 217))
|
|
497
2648
|
throw new Error("Invalid generated JPEG: missing end marker");
|
|
498
|
-
const artifact_id = `codelia-image-${
|
|
2649
|
+
const artifact_id = `codelia-image-${randomUUID5()}`;
|
|
499
2650
|
const metadata = parseImageMetadata({
|
|
500
2651
|
...provenance,
|
|
501
2652
|
...dimensions,
|
|
@@ -511,7 +2662,7 @@ var ImageArtifactStore = class {
|
|
|
511
2662
|
return metadata;
|
|
512
2663
|
}
|
|
513
2664
|
async saveAttachment(bytes, mediaType, {
|
|
514
|
-
artifactId = `codelia-image-${
|
|
2665
|
+
artifactId = `codelia-image-${randomUUID5()}`,
|
|
515
2666
|
ownerSessionId
|
|
516
2667
|
} = {}) {
|
|
517
2668
|
if (!ID2.test(artifactId)) throw new Error("Invalid image artifact id");
|
|
@@ -545,15 +2696,15 @@ var ImageArtifactStore = class {
|
|
|
545
2696
|
const { metadata } = await this.read(ref.artifact_id, sessionId);
|
|
546
2697
|
if (metadata.kind !== "attachment" || metadata.sha256 !== ref.sha256 || metadata.byte_size !== ref.byte_size)
|
|
547
2698
|
throw new Error("Image attachment rollback reference mismatch");
|
|
548
|
-
await rm3(
|
|
2699
|
+
await rm3(path9.join(this.root, ref.artifact_id), { recursive: true });
|
|
549
2700
|
}
|
|
550
2701
|
async persist(bytes, metadata, ownerSessionId) {
|
|
551
|
-
await
|
|
552
|
-
const temporary =
|
|
553
|
-
await
|
|
2702
|
+
await mkdir4(this.root, { recursive: true, mode: 448 });
|
|
2703
|
+
const temporary = path9.join(this.root, `.pending-${randomUUID5()}`);
|
|
2704
|
+
await mkdir4(temporary, { mode: 448 });
|
|
554
2705
|
try {
|
|
555
2706
|
await writeFile3(
|
|
556
|
-
|
|
2707
|
+
path9.join(temporary, imageOriginalFilename(metadata.media_type)),
|
|
557
2708
|
bytes,
|
|
558
2709
|
{
|
|
559
2710
|
flag: "wx",
|
|
@@ -561,14 +2712,14 @@ var ImageArtifactStore = class {
|
|
|
561
2712
|
}
|
|
562
2713
|
);
|
|
563
2714
|
await writeFile3(
|
|
564
|
-
|
|
2715
|
+
path9.join(temporary, "metadata.json"),
|
|
565
2716
|
JSON.stringify({
|
|
566
2717
|
...metadata,
|
|
567
2718
|
...ownerSessionId !== void 0 ? { owner_session_id: ownerSessionId } : {}
|
|
568
2719
|
}),
|
|
569
2720
|
{ flag: "wx", mode: 384 }
|
|
570
2721
|
);
|
|
571
|
-
await rename3(temporary,
|
|
2722
|
+
await rename3(temporary, path9.join(this.root, metadata.artifact_id));
|
|
572
2723
|
} catch (error) {
|
|
573
2724
|
await rm3(temporary, { recursive: true, force: true });
|
|
574
2725
|
throw error;
|
|
@@ -577,18 +2728,18 @@ var ImageArtifactStore = class {
|
|
|
577
2728
|
async read(artifactId, sessionId = this.getSessionId?.() ?? null) {
|
|
578
2729
|
if (!ID2.test(artifactId)) throw new Error("Invalid image artifact id");
|
|
579
2730
|
try {
|
|
580
|
-
const dir =
|
|
2731
|
+
const dir = path9.join(this.root, artifactId);
|
|
581
2732
|
if (!(await lstat3(dir)).isDirectory())
|
|
582
2733
|
throw new Error("Invalid artifact directory");
|
|
583
2734
|
const rawMetadata = JSON.parse(
|
|
584
|
-
(await readImageFileBounded(
|
|
2735
|
+
(await readImageFileBounded(path9.join(dir, "metadata.json"), 16384)).toString()
|
|
585
2736
|
);
|
|
586
2737
|
const metadata = parseImageMetadata(rawMetadata);
|
|
587
2738
|
const owner = rawMetadata.owner_session_id;
|
|
588
2739
|
if (owner !== void 0 && (metadata.kind !== "attachment" || typeof owner !== "string" || !owner || owner !== sessionId))
|
|
589
2740
|
throw new Error("Image artifact owned by another session");
|
|
590
2741
|
const bytes = await readImageFileBounded(
|
|
591
|
-
|
|
2742
|
+
path9.join(dir, imageOriginalFilename(metadata.media_type)),
|
|
592
2743
|
IMAGE_MAX_BYTES
|
|
593
2744
|
);
|
|
594
2745
|
const dims = metadata.kind === "attachment" ? validateImageAttachment(bytes, metadata.media_type) : metadata.media_type === "image/png" ? await validateImagePng(bytes) : validateImageAttachment(bytes, "image/jpeg");
|
|
@@ -617,7 +2768,7 @@ var ImageArtifactStore = class {
|
|
|
617
2768
|
};
|
|
618
2769
|
if (original) return ref;
|
|
619
2770
|
const model_view = await prepareModelView(
|
|
620
|
-
|
|
2771
|
+
path9.join(this.root, artifactId),
|
|
621
2772
|
metadata,
|
|
622
2773
|
bytes
|
|
623
2774
|
);
|
|
@@ -628,7 +2779,7 @@ var ImageArtifactStore = class {
|
|
|
628
2779
|
if (metadata.sha256 !== ref.sha256 || metadata.byte_size !== ref.byte_size || metadata.media_type !== ref.media_type || metadata.width !== ref.width || metadata.height !== ref.height)
|
|
629
2780
|
throw new Error("Image artifact reference mismatch");
|
|
630
2781
|
const input = ref.model_view !== void 0 ? await readModelView(
|
|
631
|
-
|
|
2782
|
+
path9.join(this.root, ref.artifact_id),
|
|
632
2783
|
metadata,
|
|
633
2784
|
ref.model_view
|
|
634
2785
|
) : { bytes, view: metadata };
|
|
@@ -640,101 +2791,87 @@ var ImageArtifactStore = class {
|
|
|
640
2791
|
}
|
|
641
2792
|
};
|
|
642
2793
|
}
|
|
643
|
-
};
|
|
644
|
-
|
|
645
|
-
// src/mcp-auth-store.ts
|
|
646
|
-
import { promises as fs } from "fs";
|
|
647
|
-
|
|
648
|
-
// src/paths.ts
|
|
649
|
-
import { mkdir as mkdir4 } from "fs/promises";
|
|
650
|
-
import os from "os";
|
|
651
|
-
import path4 from "path";
|
|
652
|
-
var DEFAULT_ROOT_DIR = ".codelia";
|
|
653
|
-
var LAYOUT_ENV = "CODELIA_LAYOUT";
|
|
654
|
-
var XDG_DIR_NAME = "codelia";
|
|
655
|
-
var CONFIG_FILENAME = "config.json";
|
|
656
|
-
var AUTH_FILENAME = "auth.json";
|
|
657
|
-
var MCP_AUTH_FILENAME = "mcp-auth.json";
|
|
658
|
-
var PROJECTS_FILENAME = "projects.json";
|
|
659
|
-
var CACHE_DIRNAME = "cache";
|
|
660
|
-
var TOOL_OUTPUT_CACHE_DIRNAME = "tool-output";
|
|
661
|
-
var SESSIONS_DIRNAME = "sessions";
|
|
662
|
-
var LOGS_DIRNAME = "logs";
|
|
663
|
-
function resolveStoragePaths(options = {}) {
|
|
664
|
-
if (options.rootOverride) {
|
|
665
|
-
return buildHomeLayout(options.rootOverride);
|
|
666
|
-
}
|
|
667
|
-
const layoutValue = options.layout ?? process.env[LAYOUT_ENV];
|
|
668
|
-
const layout = normalizeLayout(layoutValue);
|
|
669
|
-
if (layout === "xdg") {
|
|
670
|
-
return buildXdgLayout();
|
|
671
|
-
}
|
|
672
|
-
return buildHomeLayout(defaultHomeRoot());
|
|
673
|
-
}
|
|
674
|
-
async function ensureStorageDirs(paths) {
|
|
675
|
-
await Promise.all([
|
|
676
|
-
mkdir4(paths.configDir, { recursive: true }),
|
|
677
|
-
mkdir4(paths.cacheDir, { recursive: true }),
|
|
678
|
-
mkdir4(paths.toolOutputCacheDir, { recursive: true }),
|
|
679
|
-
mkdir4(paths.sessionsDir, { recursive: true }),
|
|
680
|
-
mkdir4(paths.logsDir, { recursive: true })
|
|
681
|
-
]);
|
|
682
|
-
}
|
|
683
|
-
function normalizeLayout(value) {
|
|
684
|
-
if (value && value.toLowerCase() === "xdg") return "xdg";
|
|
685
|
-
return "home";
|
|
686
|
-
}
|
|
687
|
-
function defaultHomeRoot() {
|
|
688
|
-
return path4.join(os.homedir(), DEFAULT_ROOT_DIR);
|
|
689
|
-
}
|
|
690
|
-
function buildHomeLayout(root) {
|
|
691
|
-
const configDir = root;
|
|
692
|
-
return {
|
|
693
|
-
root,
|
|
694
|
-
configDir,
|
|
695
|
-
configFile: path4.join(configDir, CONFIG_FILENAME),
|
|
696
|
-
authFile: path4.join(configDir, AUTH_FILENAME),
|
|
697
|
-
mcpAuthFile: path4.join(configDir, MCP_AUTH_FILENAME),
|
|
698
|
-
projectsFile: path4.join(configDir, PROJECTS_FILENAME),
|
|
699
|
-
cacheDir: path4.join(root, CACHE_DIRNAME),
|
|
700
|
-
toolOutputCacheDir: path4.join(
|
|
701
|
-
root,
|
|
702
|
-
CACHE_DIRNAME,
|
|
703
|
-
TOOL_OUTPUT_CACHE_DIRNAME
|
|
704
|
-
),
|
|
705
|
-
sessionsDir: path4.join(root, SESSIONS_DIRNAME),
|
|
706
|
-
logsDir: path4.join(root, LOGS_DIRNAME)
|
|
707
|
-
};
|
|
708
|
-
}
|
|
709
|
-
function buildXdgLayout() {
|
|
710
|
-
const home = os.homedir();
|
|
711
|
-
const configRoot = process.env.XDG_CONFIG_HOME ?? path4.join(home, ".config");
|
|
712
|
-
const cacheRoot = process.env.XDG_CACHE_HOME ?? path4.join(home, ".cache");
|
|
713
|
-
const stateRoot = process.env.XDG_STATE_HOME ?? path4.join(home, ".local", "state");
|
|
714
|
-
const configDir = path4.join(configRoot, XDG_DIR_NAME);
|
|
715
|
-
const cacheDir = path4.join(cacheRoot, XDG_DIR_NAME);
|
|
716
|
-
const stateDir = path4.join(stateRoot, XDG_DIR_NAME);
|
|
717
|
-
return {
|
|
718
|
-
root: stateDir,
|
|
719
|
-
configDir,
|
|
720
|
-
configFile: path4.join(configDir, CONFIG_FILENAME),
|
|
721
|
-
authFile: path4.join(configDir, AUTH_FILENAME),
|
|
722
|
-
mcpAuthFile: path4.join(configDir, MCP_AUTH_FILENAME),
|
|
723
|
-
projectsFile: path4.join(configDir, PROJECTS_FILENAME),
|
|
724
|
-
cacheDir,
|
|
725
|
-
toolOutputCacheDir: path4.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
|
|
726
|
-
sessionsDir: path4.join(stateDir, SESSIONS_DIRNAME),
|
|
727
|
-
logsDir: path4.join(stateDir, LOGS_DIRNAME)
|
|
728
|
-
};
|
|
729
|
-
}
|
|
2794
|
+
};
|
|
730
2795
|
|
|
731
2796
|
// src/mcp-auth-store.ts
|
|
732
|
-
|
|
733
|
-
var
|
|
734
|
-
var
|
|
2797
|
+
import { promises as fs6 } from "fs";
|
|
2798
|
+
var MCP_AUTH_VERSION = 2;
|
|
2799
|
+
var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2800
|
+
var pickString = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
|
|
735
2801
|
var pickNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
2802
|
+
var canonicalizeMcpUri = (raw) => {
|
|
2803
|
+
const parsed = new URL(raw.trim());
|
|
2804
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
2805
|
+
throw new Error(`Unsupported MCP URI scheme: ${parsed.protocol}`);
|
|
2806
|
+
}
|
|
2807
|
+
parsed.hash = "";
|
|
2808
|
+
parsed.hostname = parsed.hostname.toLowerCase();
|
|
2809
|
+
if (parsed.protocol === "http:" && parsed.port === "80" || parsed.protocol === "https:" && parsed.port === "443") {
|
|
2810
|
+
parsed.port = "";
|
|
2811
|
+
}
|
|
2812
|
+
return parsed.toString();
|
|
2813
|
+
};
|
|
2814
|
+
var deriveMcpIssuer = (options) => {
|
|
2815
|
+
if (options.issuer?.trim()) return options.issuer;
|
|
2816
|
+
const endpoint = options.tokenUrl ?? options.authorizationUrl;
|
|
2817
|
+
if (!endpoint?.trim()) return void 0;
|
|
2818
|
+
try {
|
|
2819
|
+
return new URL(canonicalizeMcpUri(endpoint)).origin;
|
|
2820
|
+
} catch {
|
|
2821
|
+
return void 0;
|
|
2822
|
+
}
|
|
2823
|
+
};
|
|
2824
|
+
var buildMcpAuthBinding = (options) => {
|
|
2825
|
+
const resource_uri = canonicalizeMcpUri(options.resourceUri);
|
|
2826
|
+
const issuer = deriveMcpIssuer({
|
|
2827
|
+
issuer: options.issuer,
|
|
2828
|
+
tokenUrl: options.tokenEndpoint
|
|
2829
|
+
});
|
|
2830
|
+
const token_endpoint = options.tokenEndpoint?.trim() ? canonicalizeMcpUri(options.tokenEndpoint) : void 0;
|
|
2831
|
+
const client_id = pickString(options.clientId);
|
|
2832
|
+
return {
|
|
2833
|
+
resource_uri,
|
|
2834
|
+
...issuer ? { issuer } : {},
|
|
2835
|
+
...token_endpoint ? { token_endpoint } : {},
|
|
2836
|
+
...client_id ? { client_id } : {}
|
|
2837
|
+
};
|
|
2838
|
+
};
|
|
2839
|
+
var mcpAuthBindingMatches = (stored, resolved) => {
|
|
2840
|
+
let storedResource;
|
|
2841
|
+
let resolvedResource;
|
|
2842
|
+
try {
|
|
2843
|
+
storedResource = canonicalizeMcpUri(stored.resource_uri);
|
|
2844
|
+
resolvedResource = canonicalizeMcpUri(resolved.resource_uri);
|
|
2845
|
+
} catch {
|
|
2846
|
+
return false;
|
|
2847
|
+
}
|
|
2848
|
+
if (storedResource !== resolvedResource) return false;
|
|
2849
|
+
if (stored.issuer) {
|
|
2850
|
+
const normStored = deriveMcpIssuer({ issuer: stored.issuer });
|
|
2851
|
+
const normResolved = resolved.issuer ? deriveMcpIssuer({ issuer: resolved.issuer }) : resolved.token_endpoint ? deriveMcpIssuer({ tokenUrl: resolved.token_endpoint }) : void 0;
|
|
2852
|
+
if (!normStored || !normResolved || normStored !== normResolved) {
|
|
2853
|
+
return false;
|
|
2854
|
+
}
|
|
2855
|
+
}
|
|
2856
|
+
if (stored.token_endpoint) {
|
|
2857
|
+
if (!resolved.token_endpoint) return false;
|
|
2858
|
+
try {
|
|
2859
|
+
if (canonicalizeMcpUri(stored.token_endpoint) !== canonicalizeMcpUri(resolved.token_endpoint)) {
|
|
2860
|
+
return false;
|
|
2861
|
+
}
|
|
2862
|
+
} catch {
|
|
2863
|
+
return false;
|
|
2864
|
+
}
|
|
2865
|
+
}
|
|
2866
|
+
if (stored.client_id) {
|
|
2867
|
+
if (!resolved.client_id || stored.client_id !== resolved.client_id) {
|
|
2868
|
+
return false;
|
|
2869
|
+
}
|
|
2870
|
+
}
|
|
2871
|
+
return true;
|
|
2872
|
+
};
|
|
736
2873
|
var normalizeTokens = (value) => {
|
|
737
|
-
if (!
|
|
2874
|
+
if (!isRecord4(value)) return null;
|
|
738
2875
|
const accessToken = pickString(value.access_token);
|
|
739
2876
|
if (!accessToken) return null;
|
|
740
2877
|
return {
|
|
@@ -747,59 +2884,245 @@ var normalizeTokens = (value) => {
|
|
|
747
2884
|
...pickString(value.client_secret) ? { client_secret: pickString(value.client_secret) } : {}
|
|
748
2885
|
};
|
|
749
2886
|
};
|
|
2887
|
+
var normalizeBinding = (value) => {
|
|
2888
|
+
if (!isRecord4(value)) return null;
|
|
2889
|
+
const rawResource = pickString(value.resource_uri);
|
|
2890
|
+
if (!rawResource) return null;
|
|
2891
|
+
try {
|
|
2892
|
+
return buildMcpAuthBinding({
|
|
2893
|
+
resourceUri: rawResource,
|
|
2894
|
+
issuer: pickString(value.issuer),
|
|
2895
|
+
tokenEndpoint: pickString(value.token_endpoint),
|
|
2896
|
+
clientId: pickString(value.client_id)
|
|
2897
|
+
});
|
|
2898
|
+
} catch {
|
|
2899
|
+
return null;
|
|
2900
|
+
}
|
|
2901
|
+
};
|
|
2902
|
+
var parseMcpAuthDocument = (text) => {
|
|
2903
|
+
const parsed = JSON.parse(text);
|
|
2904
|
+
if (!isRecord4(parsed)) {
|
|
2905
|
+
throw new Error("mcp-auth.json has unsupported format");
|
|
2906
|
+
}
|
|
2907
|
+
if (parsed.version === 1) {
|
|
2908
|
+
const serversRaw2 = isRecord4(parsed.servers) ? parsed.servers : {};
|
|
2909
|
+
const droppedLegacyServers = Object.entries(serversRaw2).filter(([, entry]) => normalizeTokens(entry) !== null).map(([id2]) => id2).sort();
|
|
2910
|
+
return {
|
|
2911
|
+
normalized: { version: MCP_AUTH_VERSION, servers: {} },
|
|
2912
|
+
sourceVersion: 1,
|
|
2913
|
+
droppedLegacyServers
|
|
2914
|
+
};
|
|
2915
|
+
}
|
|
2916
|
+
if (parsed.version !== MCP_AUTH_VERSION) {
|
|
2917
|
+
throw new Error("mcp-auth.json has unsupported version");
|
|
2918
|
+
}
|
|
2919
|
+
if (parsed.servers !== void 0 && !isRecord4(parsed.servers)) {
|
|
2920
|
+
throw new Error("mcp-auth.json v2 has invalid servers map");
|
|
2921
|
+
}
|
|
2922
|
+
const serversRaw = isRecord4(parsed.servers) ? parsed.servers : {};
|
|
2923
|
+
const servers = {};
|
|
2924
|
+
for (const [id2, entry] of Object.entries(serversRaw)) {
|
|
2925
|
+
if (!isRecord4(entry)) {
|
|
2926
|
+
throw new Error(`mcp-auth.json v2 has invalid entry for '${id2}'`);
|
|
2927
|
+
}
|
|
2928
|
+
const binding = normalizeBinding(entry.binding);
|
|
2929
|
+
if (!binding) {
|
|
2930
|
+
throw new Error(`mcp-auth.json v2 has invalid binding for '${id2}'`);
|
|
2931
|
+
}
|
|
2932
|
+
const tokens = normalizeTokens(entry.tokens);
|
|
2933
|
+
if (!tokens) {
|
|
2934
|
+
throw new Error(`mcp-auth.json v2 has invalid tokens for '${id2}'`);
|
|
2935
|
+
}
|
|
2936
|
+
servers[id2] = { binding, tokens };
|
|
2937
|
+
}
|
|
2938
|
+
return {
|
|
2939
|
+
normalized: { version: MCP_AUTH_VERSION, servers },
|
|
2940
|
+
sourceVersion: 2,
|
|
2941
|
+
droppedLegacyServers: []
|
|
2942
|
+
};
|
|
2943
|
+
};
|
|
2944
|
+
var mcpAuthStoreAdapter = {
|
|
2945
|
+
name: "mcp_auth",
|
|
2946
|
+
service: CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
|
|
2947
|
+
filePath: (paths) => paths.mcpAuthFile,
|
|
2948
|
+
legacyFilePath: (paths) => paths.legacyMcpAuthFile,
|
|
2949
|
+
empty: () => ({ version: MCP_AUTH_VERSION, servers: {} }),
|
|
2950
|
+
isNonEmpty: (doc) => Object.keys(doc.servers).length > 0,
|
|
2951
|
+
parse: (text) => {
|
|
2952
|
+
const parsed = parseMcpAuthDocument(text);
|
|
2953
|
+
return {
|
|
2954
|
+
normalized: parsed.normalized,
|
|
2955
|
+
sourceVersion: parsed.sourceVersion,
|
|
2956
|
+
extraWarnings: parsed.droppedLegacyServers
|
|
2957
|
+
};
|
|
2958
|
+
}
|
|
2959
|
+
};
|
|
2960
|
+
var readTextIfPresent2 = async (filePath) => {
|
|
2961
|
+
if (!await verifyWindowsCredentialFileAcl(filePath)) return null;
|
|
2962
|
+
try {
|
|
2963
|
+
return await fs6.readFile(filePath, "utf8");
|
|
2964
|
+
} catch (error) {
|
|
2965
|
+
if (error?.code === "ENOENT") return null;
|
|
2966
|
+
throw error;
|
|
2967
|
+
}
|
|
2968
|
+
};
|
|
750
2969
|
var McpAuthStore = class {
|
|
751
2970
|
paths;
|
|
752
|
-
|
|
2971
|
+
lockOptions;
|
|
2972
|
+
storageMode;
|
|
2973
|
+
keychain;
|
|
2974
|
+
constructor(paths, options) {
|
|
753
2975
|
this.paths = paths ?? resolveStoragePaths();
|
|
2976
|
+
this.lockOptions = options?.lock;
|
|
2977
|
+
this.storageMode = options?.storageMode;
|
|
2978
|
+
this.keychain = options?.keychain ?? new MacOsKeychainClient({ credentialsDir: this.paths.credentialsDir });
|
|
2979
|
+
}
|
|
2980
|
+
lockPath() {
|
|
2981
|
+
return authLockPathFor(this.paths.credentialsDir);
|
|
2982
|
+
}
|
|
2983
|
+
keychainAccount() {
|
|
2984
|
+
return keychainAccountForConfigDir(this.paths.configDir);
|
|
2985
|
+
}
|
|
2986
|
+
resolveBackendUnlocked() {
|
|
2987
|
+
return coordinateCredentialBackendUnlocked({
|
|
2988
|
+
paths: this.paths,
|
|
2989
|
+
storageMode: this.storageMode,
|
|
2990
|
+
keychain: this.keychain,
|
|
2991
|
+
authAdapter: providerAuthStoreAdapter,
|
|
2992
|
+
mcpAdapter: mcpAuthStoreAdapter
|
|
2993
|
+
});
|
|
754
2994
|
}
|
|
755
|
-
async
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
2995
|
+
async recordDroppedLegacyServers(dropped) {
|
|
2996
|
+
if (!dropped.length) return;
|
|
2997
|
+
await ensureStorageDirs(this.paths);
|
|
2998
|
+
const existing = await readAuthStorageState(this.paths.authStateFile).catch(
|
|
2999
|
+
() => null
|
|
3000
|
+
);
|
|
3001
|
+
const merged = [
|
|
3002
|
+
.../* @__PURE__ */ new Set([...existing?.mcp_reauth_required ?? [], ...dropped])
|
|
3003
|
+
].sort();
|
|
3004
|
+
await writeAuthStorageState(this.paths.authStateFile, {
|
|
3005
|
+
version: 1,
|
|
3006
|
+
status: "steady",
|
|
3007
|
+
active_backend: existing?.active_backend ?? "file",
|
|
3008
|
+
mcp_reauth_required: merged
|
|
3009
|
+
});
|
|
3010
|
+
}
|
|
3011
|
+
async readFromBackend(active) {
|
|
3012
|
+
if (active === "keyring") {
|
|
3013
|
+
const text2 = await this.keychain.get(
|
|
3014
|
+
CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
|
|
3015
|
+
this.keychainAccount()
|
|
3016
|
+
);
|
|
3017
|
+
if (text2 === null) {
|
|
777
3018
|
return { version: MCP_AUTH_VERSION, servers: {} };
|
|
778
3019
|
}
|
|
779
|
-
|
|
3020
|
+
const parsed2 = parseMcpAuthDocument(text2);
|
|
3021
|
+
if (parsed2.sourceVersion === 1) {
|
|
3022
|
+
await this.writeToBackend("keyring", parsed2.normalized);
|
|
3023
|
+
await this.recordDroppedLegacyServers(parsed2.droppedLegacyServers);
|
|
3024
|
+
}
|
|
3025
|
+
return parsed2.normalized;
|
|
3026
|
+
}
|
|
3027
|
+
const text = await readTextIfPresent2(this.paths.mcpAuthFile);
|
|
3028
|
+
if (text === null) {
|
|
3029
|
+
return { version: MCP_AUTH_VERSION, servers: {} };
|
|
3030
|
+
}
|
|
3031
|
+
const parsed = parseMcpAuthDocument(text);
|
|
3032
|
+
if (parsed.sourceVersion === 1) {
|
|
3033
|
+
await this.writeToBackend("file", parsed.normalized);
|
|
3034
|
+
await this.recordDroppedLegacyServers(parsed.droppedLegacyServers);
|
|
780
3035
|
}
|
|
3036
|
+
return parsed.normalized;
|
|
781
3037
|
}
|
|
782
|
-
async
|
|
3038
|
+
async clearReauthenticatedServers(authenticatedServers) {
|
|
3039
|
+
if (!authenticatedServers.length) return;
|
|
3040
|
+
const existing = await readAuthStorageState(this.paths.authStateFile).catch(
|
|
3041
|
+
() => null
|
|
3042
|
+
);
|
|
3043
|
+
if (!existing?.mcp_reauth_required?.length) return;
|
|
3044
|
+
const authenticated = new Set(authenticatedServers);
|
|
3045
|
+
const remaining = existing.mcp_reauth_required.filter(
|
|
3046
|
+
(id2) => !authenticated.has(id2)
|
|
3047
|
+
);
|
|
3048
|
+
if (remaining.length === existing.mcp_reauth_required.length) return;
|
|
3049
|
+
const { mcp_reauth_required: _prev, ...rest } = existing;
|
|
3050
|
+
await writeAuthStorageState(this.paths.authStateFile, {
|
|
3051
|
+
...rest,
|
|
3052
|
+
...remaining.length ? { mcp_reauth_required: remaining } : {}
|
|
3053
|
+
});
|
|
3054
|
+
}
|
|
3055
|
+
async writeToBackend(active, auth) {
|
|
3056
|
+
if (active === "keyring") {
|
|
3057
|
+
await this.keychain.set(
|
|
3058
|
+
CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
|
|
3059
|
+
this.keychainAccount(),
|
|
3060
|
+
JSON.stringify(auth)
|
|
3061
|
+
);
|
|
3062
|
+
await this.clearReauthenticatedServers(Object.keys(auth.servers));
|
|
3063
|
+
return;
|
|
3064
|
+
}
|
|
783
3065
|
await ensureStorageDirs(this.paths);
|
|
784
3066
|
const data = JSON.stringify(auth, null, 2);
|
|
785
|
-
await
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
3067
|
+
await writeFileAtomic(this.paths.mcpAuthFile, data, { mode: 384 });
|
|
3068
|
+
await this.clearReauthenticatedServers(Object.keys(auth.servers));
|
|
3069
|
+
}
|
|
3070
|
+
/**
|
|
3071
|
+
* Load normalized v2 MCP auth from the active backend (macOS Keychain or
|
|
3072
|
+
* protected `credentials/` file), running safe two-phase migration if needed.
|
|
3073
|
+
*/
|
|
3074
|
+
async load() {
|
|
3075
|
+
return withAuthStoreLock(
|
|
3076
|
+
this.lockPath(),
|
|
3077
|
+
async () => {
|
|
3078
|
+
const resolved = await this.resolveBackendUnlocked();
|
|
3079
|
+
return this.readFromBackend(resolved.active);
|
|
3080
|
+
},
|
|
3081
|
+
this.lockOptions
|
|
3082
|
+
);
|
|
3083
|
+
}
|
|
3084
|
+
/**
|
|
3085
|
+
* Reload, mutate, and atomically save under the interprocess auth lock.
|
|
3086
|
+
* Skips writing if the serialized document did not change.
|
|
3087
|
+
*/
|
|
3088
|
+
update(mutate) {
|
|
3089
|
+
return withAuthStoreLock(
|
|
3090
|
+
this.lockPath(),
|
|
3091
|
+
async () => {
|
|
3092
|
+
const resolved = await this.resolveBackendUnlocked();
|
|
3093
|
+
const auth = await this.readFromBackend(resolved.active);
|
|
3094
|
+
const before = JSON.stringify(auth);
|
|
3095
|
+
const result = await mutate(auth);
|
|
3096
|
+
if (JSON.stringify(auth) !== before) {
|
|
3097
|
+
await this.writeToBackend(resolved.active, auth);
|
|
3098
|
+
}
|
|
3099
|
+
return result;
|
|
3100
|
+
},
|
|
3101
|
+
this.lockOptions
|
|
3102
|
+
);
|
|
3103
|
+
}
|
|
3104
|
+
async save(auth) {
|
|
3105
|
+
await withAuthStoreLock(
|
|
3106
|
+
this.lockPath(),
|
|
3107
|
+
async () => {
|
|
3108
|
+
const resolved = await this.resolveBackendUnlocked();
|
|
3109
|
+
await this.writeToBackend(resolved.active, auth);
|
|
3110
|
+
},
|
|
3111
|
+
this.lockOptions
|
|
3112
|
+
);
|
|
790
3113
|
}
|
|
791
3114
|
};
|
|
792
3115
|
|
|
793
3116
|
// src/process-identity.ts
|
|
794
|
-
import { execFile } from "child_process";
|
|
795
|
-
import { promises as
|
|
3117
|
+
import { execFile as execFile3 } from "child_process";
|
|
3118
|
+
import { promises as fs7 } from "fs";
|
|
796
3119
|
var getProcessIdentity = async (pid, options = {}) => {
|
|
797
3120
|
if (!Number.isSafeInteger(pid) || pid <= 0) return null;
|
|
798
3121
|
if (process.platform === "linux") {
|
|
799
3122
|
try {
|
|
800
3123
|
const [stat, boot] = await Promise.all([
|
|
801
|
-
|
|
802
|
-
|
|
3124
|
+
fs7.readFile(`/proc/${pid}/stat`, "utf8"),
|
|
3125
|
+
fs7.readFile("/proc/sys/kernel/random/boot_id", "utf8")
|
|
803
3126
|
]);
|
|
804
3127
|
return `${boot.trim()}:${stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]}`;
|
|
805
3128
|
} catch {
|
|
@@ -808,7 +3131,7 @@ var getProcessIdentity = async (pid, options = {}) => {
|
|
|
808
3131
|
}
|
|
809
3132
|
if (process.platform === "darwin")
|
|
810
3133
|
return new Promise((resolve) => {
|
|
811
|
-
|
|
3134
|
+
execFile3(
|
|
812
3135
|
"/bin/ps",
|
|
813
3136
|
["-p", String(pid), "-o", "lstart="],
|
|
814
3137
|
{
|
|
@@ -823,79 +3146,209 @@ var getProcessIdentity = async (pid, options = {}) => {
|
|
|
823
3146
|
};
|
|
824
3147
|
|
|
825
3148
|
// src/projects-store.ts
|
|
826
|
-
import { randomUUID as
|
|
827
|
-
import { constants as
|
|
828
|
-
import
|
|
829
|
-
import
|
|
830
|
-
import { setTimeout as delay } from "timers/promises";
|
|
3149
|
+
import { randomUUID as randomUUID6 } from "crypto";
|
|
3150
|
+
import { constants as constants4, promises as fs9 } from "fs";
|
|
3151
|
+
import path11 from "path";
|
|
3152
|
+
import { setTimeout as delay2 } from "timers/promises";
|
|
831
3153
|
import {
|
|
832
3154
|
parseApprovalMode,
|
|
833
3155
|
parseSandboxMode
|
|
834
3156
|
} from "@codelia/shared-types";
|
|
835
3157
|
|
|
836
|
-
// src/
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
3158
|
+
// src/user-storage-boundary.ts
|
|
3159
|
+
import { promises as fs8, lstatSync as lstatSync2, realpathSync as realpathSync2, statSync } from "fs";
|
|
3160
|
+
import os3 from "os";
|
|
3161
|
+
import path10 from "path";
|
|
3162
|
+
var isWithinPath = (root, target) => {
|
|
3163
|
+
const relative = path10.relative(root, target);
|
|
3164
|
+
return !path10.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path10.sep}`);
|
|
3165
|
+
};
|
|
3166
|
+
var canonicalPathOrResolvedSync = (target) => {
|
|
3167
|
+
const resolved = path10.resolve(target);
|
|
3168
|
+
try {
|
|
3169
|
+
return realpathSync2(resolved);
|
|
3170
|
+
} catch (error) {
|
|
3171
|
+
if (error.code !== "ENOENT") return resolved;
|
|
3172
|
+
const parent = path10.dirname(resolved);
|
|
3173
|
+
if (parent === resolved) return resolved;
|
|
3174
|
+
return path10.join(
|
|
3175
|
+
canonicalPathOrResolvedSync(parent),
|
|
3176
|
+
path10.basename(resolved)
|
|
3177
|
+
);
|
|
3178
|
+
}
|
|
3179
|
+
};
|
|
3180
|
+
var isSameConfigFilePath = (leftPath, rightPath) => {
|
|
3181
|
+
const left = canonicalPathOrResolvedSync(leftPath);
|
|
3182
|
+
const right = canonicalPathOrResolvedSync(rightPath);
|
|
3183
|
+
const samePath = process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
|
|
3184
|
+
if (samePath) return true;
|
|
3185
|
+
const leftStat = statSync(left, { bigint: true, throwIfNoEntry: false });
|
|
3186
|
+
const rightStat = statSync(right, { bigint: true, throwIfNoEntry: false });
|
|
3187
|
+
return !!leftStat && !!rightStat && leftStat.ino !== 0n && leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
|
|
3188
|
+
};
|
|
3189
|
+
var isCanonicalHomeWorkspaceSync = (workspace) => {
|
|
3190
|
+
try {
|
|
3191
|
+
const home = path10.resolve(os3.homedir());
|
|
3192
|
+
return realpathSync2(workspace) === realpathSync2(home);
|
|
3193
|
+
} catch {
|
|
3194
|
+
return false;
|
|
3195
|
+
}
|
|
3196
|
+
};
|
|
3197
|
+
var isOwnedAncestor = (info, uid) => info.isDirectory() && (info.uid === 0 || info.uid === uid) && ((info.mode & 18) === 0 || (info.mode & 512) !== 0);
|
|
3198
|
+
var isOwnedPrivateDirectory = (info, uid) => info.isDirectory() && info.uid === BigInt(uid) && (info.mode & 0o022n) === 0n;
|
|
3199
|
+
var verifyOwnedAncestors = async (directory2, uid, errorMessage = "unsafe_projects_policy_ancestor") => {
|
|
3200
|
+
let child = directory2;
|
|
3201
|
+
while (child !== path10.dirname(child)) {
|
|
3202
|
+
child = path10.dirname(child);
|
|
3203
|
+
const info = await fs8.stat(child);
|
|
3204
|
+
if (!isOwnedAncestor(info, uid)) throw new Error(errorMessage);
|
|
3205
|
+
}
|
|
3206
|
+
};
|
|
3207
|
+
var verifyOwnedAncestorsSync = (directory2, uid, errorMessage = "unsafe_projects_policy_ancestor") => {
|
|
3208
|
+
let child = directory2;
|
|
3209
|
+
while (child !== path10.dirname(child)) {
|
|
3210
|
+
child = path10.dirname(child);
|
|
3211
|
+
const info = statSync(child);
|
|
3212
|
+
if (!isOwnedAncestor(info, uid)) throw new Error(errorMessage);
|
|
3213
|
+
}
|
|
3214
|
+
};
|
|
3215
|
+
var evaluateHomeReservedStorage = ({
|
|
3216
|
+
workspace,
|
|
3217
|
+
configured,
|
|
3218
|
+
resolved,
|
|
3219
|
+
relativePath,
|
|
3220
|
+
reservedOverride,
|
|
3221
|
+
home,
|
|
3222
|
+
canonicalHome,
|
|
3223
|
+
errorMessage,
|
|
3224
|
+
redirectErrorMessage
|
|
3225
|
+
}) => {
|
|
3226
|
+
const apparentHome = isWithinPath(home, configured) ? home : canonicalHome;
|
|
3227
|
+
const base = resolveDefaultHomeConfigDir(apparentHome);
|
|
3228
|
+
const expectedReserved = path10.resolve(
|
|
3229
|
+
reservedOverride ?? (relativePath ? path10.join(base, relativePath) : base)
|
|
3230
|
+
);
|
|
3231
|
+
if (workspace !== canonicalHome || configured !== expectedReserved || !isWithinPath(apparentHome, configured))
|
|
3232
|
+
throw new Error(errorMessage);
|
|
3233
|
+
const expectedResolved = path10.join(
|
|
3234
|
+
canonicalHome,
|
|
3235
|
+
path10.relative(apparentHome, configured)
|
|
3236
|
+
);
|
|
3237
|
+
if (resolved !== expectedResolved) throw new Error(redirectErrorMessage);
|
|
3238
|
+
};
|
|
3239
|
+
var verifyUserStorageLocation = async ({
|
|
3240
|
+
workspace,
|
|
3241
|
+
configured,
|
|
3242
|
+
resolved,
|
|
3243
|
+
relativePath = "",
|
|
3244
|
+
reservedOverride,
|
|
3245
|
+
errorMessage = "unsafe_projects_policy_path",
|
|
3246
|
+
redirectErrorMessage = errorMessage
|
|
3247
|
+
}) => {
|
|
3248
|
+
const resolvedConfigured = path10.resolve(configured);
|
|
3249
|
+
if (!isWithinPath(workspace, resolvedConfigured) && !isWithinPath(workspace, resolved))
|
|
3250
|
+
return { insideWorkspace: false };
|
|
3251
|
+
const home = path10.resolve(os3.homedir());
|
|
3252
|
+
let canonicalHome;
|
|
3253
|
+
try {
|
|
3254
|
+
canonicalHome = await fs8.realpath(home);
|
|
3255
|
+
} catch {
|
|
3256
|
+
throw new Error(errorMessage);
|
|
3257
|
+
}
|
|
3258
|
+
evaluateHomeReservedStorage({
|
|
3259
|
+
workspace,
|
|
3260
|
+
configured: resolvedConfigured,
|
|
3261
|
+
resolved,
|
|
3262
|
+
relativePath,
|
|
3263
|
+
reservedOverride,
|
|
3264
|
+
home,
|
|
3265
|
+
canonicalHome,
|
|
3266
|
+
errorMessage,
|
|
3267
|
+
redirectErrorMessage
|
|
3268
|
+
});
|
|
3269
|
+
return { insideWorkspace: true };
|
|
3270
|
+
};
|
|
3271
|
+
var verifyUserStorageLocationSync = ({
|
|
3272
|
+
workspace,
|
|
3273
|
+
configured,
|
|
3274
|
+
resolved,
|
|
3275
|
+
relativePath = "",
|
|
3276
|
+
reservedOverride,
|
|
3277
|
+
errorMessage = "unsafe_projects_policy_path",
|
|
3278
|
+
redirectErrorMessage = errorMessage
|
|
3279
|
+
}) => {
|
|
3280
|
+
const resolvedConfigured = path10.resolve(configured);
|
|
3281
|
+
if (!isWithinPath(workspace, resolvedConfigured) && !isWithinPath(workspace, resolved))
|
|
3282
|
+
return { insideWorkspace: false };
|
|
3283
|
+
const home = path10.resolve(os3.homedir());
|
|
3284
|
+
let canonicalHome;
|
|
3285
|
+
try {
|
|
3286
|
+
canonicalHome = realpathSync2(home);
|
|
3287
|
+
} catch {
|
|
3288
|
+
throw new Error(errorMessage);
|
|
3289
|
+
}
|
|
3290
|
+
evaluateHomeReservedStorage({
|
|
3291
|
+
workspace,
|
|
3292
|
+
configured: resolvedConfigured,
|
|
3293
|
+
resolved,
|
|
3294
|
+
relativePath,
|
|
3295
|
+
reservedOverride,
|
|
3296
|
+
home,
|
|
3297
|
+
canonicalHome,
|
|
3298
|
+
errorMessage,
|
|
3299
|
+
redirectErrorMessage
|
|
3300
|
+
});
|
|
3301
|
+
return { insideWorkspace: true };
|
|
3302
|
+
};
|
|
3303
|
+
var isTrustedGlobalConfigLocationSync = (workingDir, configPath) => {
|
|
3304
|
+
try {
|
|
3305
|
+
const workspace = realpathSync2(workingDir);
|
|
3306
|
+
const configured = path10.resolve(configPath);
|
|
3307
|
+
const resolved = canonicalPathOrResolvedSync(configured);
|
|
3308
|
+
const { insideWorkspace } = verifyUserStorageLocationSync({
|
|
3309
|
+
workspace,
|
|
3310
|
+
configured,
|
|
3311
|
+
resolved,
|
|
3312
|
+
relativePath: "config.json",
|
|
3313
|
+
errorMessage: "untrusted_global_config_path"
|
|
3314
|
+
});
|
|
3315
|
+
if (!insideWorkspace) return true;
|
|
3316
|
+
if (typeof process.geteuid !== "function") return false;
|
|
3317
|
+
const uid = process.geteuid();
|
|
3318
|
+
const dir = path10.dirname(resolved);
|
|
3319
|
+
if (!isOwnedPrivateDirectory(lstatSync2(dir, { bigint: true }), uid))
|
|
3320
|
+
return false;
|
|
3321
|
+
verifyOwnedAncestorsSync(dir, uid, "untrusted_global_config_path");
|
|
3322
|
+
const fileInfo = lstatSync2(resolved, {
|
|
3323
|
+
bigint: true,
|
|
3324
|
+
throwIfNoEntry: false
|
|
3325
|
+
});
|
|
3326
|
+
if (fileInfo && (!fileInfo.isFile() || fileInfo.nlink !== 1n || fileInfo.uid !== BigInt(uid) || (fileInfo.mode & 0o022n) !== 0n))
|
|
3327
|
+
return false;
|
|
3328
|
+
return true;
|
|
3329
|
+
} catch {
|
|
3330
|
+
return false;
|
|
856
3331
|
}
|
|
857
|
-
const betterSqliteSpecifier = "better-sqlite3";
|
|
858
|
-
const betterSqliteModule = await import(betterSqliteSpecifier);
|
|
859
|
-
const BetterSqlite3 = betterSqliteModule.default ?? betterSqliteModule;
|
|
860
|
-
const db = new BetterSqlite3(filename);
|
|
861
|
-
return {
|
|
862
|
-
close: () => db.close(),
|
|
863
|
-
exec: (sql) => {
|
|
864
|
-
db.exec(sql);
|
|
865
|
-
},
|
|
866
|
-
run: (sql, params = []) => {
|
|
867
|
-
db.prepare(sql).run(...params);
|
|
868
|
-
},
|
|
869
|
-
get: (sql, params = []) => {
|
|
870
|
-
const row = db.prepare(sql).get(...params);
|
|
871
|
-
return row ?? void 0;
|
|
872
|
-
},
|
|
873
|
-
all: (sql, params = []) => db.prepare(sql).all(...params)
|
|
874
|
-
};
|
|
875
3332
|
};
|
|
876
3333
|
|
|
877
3334
|
// src/projects-store.ts
|
|
878
|
-
var
|
|
879
|
-
var within = (root, target) => {
|
|
880
|
-
const relative = path5.relative(root, target);
|
|
881
|
-
return !path5.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path5.sep}`);
|
|
882
|
-
};
|
|
3335
|
+
var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
883
3336
|
var missing = (error) => error.code === "ENOENT";
|
|
884
|
-
var lockFileFor = (file) =>
|
|
885
|
-
var
|
|
3337
|
+
var lockFileFor = (file) => path11.join(path11.dirname(file), ".projects-policy-lock.sqlite");
|
|
3338
|
+
var lstatIfPresent2 = (file) => fs9.lstat(file).catch((error) => {
|
|
886
3339
|
if (!missing(error)) throw error;
|
|
887
3340
|
return void 0;
|
|
888
3341
|
});
|
|
889
|
-
var
|
|
890
|
-
const info = await
|
|
3342
|
+
var verifyLockFile2 = async (file) => {
|
|
3343
|
+
const info = await lstatIfPresent2(file);
|
|
891
3344
|
if (info && (!info.isFile() || info.uid !== process.geteuid?.() || info.size === 0 || (info.mode & 18) !== 0))
|
|
892
3345
|
throw new Error("unsafe_projects_policy_lock");
|
|
893
3346
|
};
|
|
894
3347
|
var initializeUpdateLock = async (lockPath) => {
|
|
895
|
-
if (await
|
|
896
|
-
const temporary = `${lockPath}.${
|
|
3348
|
+
if (await lstatIfPresent2(lockPath)) return;
|
|
3349
|
+
const temporary = `${lockPath}.${randomUUID6()}.tmp`;
|
|
897
3350
|
try {
|
|
898
|
-
const file = await
|
|
3351
|
+
const file = await fs9.open(temporary, "wx", 384);
|
|
899
3352
|
await file.close();
|
|
900
3353
|
const db = await openSqlite(temporary);
|
|
901
3354
|
try {
|
|
@@ -904,17 +3357,17 @@ var initializeUpdateLock = async (lockPath) => {
|
|
|
904
3357
|
db.close();
|
|
905
3358
|
}
|
|
906
3359
|
try {
|
|
907
|
-
await
|
|
3360
|
+
await fs9.link(temporary, lockPath);
|
|
908
3361
|
} catch (error) {
|
|
909
3362
|
if (error.code !== "EEXIST") throw error;
|
|
910
3363
|
}
|
|
911
3364
|
} finally {
|
|
912
|
-
await
|
|
3365
|
+
await fs9.unlink(temporary).catch(() => void 0);
|
|
913
3366
|
}
|
|
914
3367
|
};
|
|
915
3368
|
var openUpdateLock = async (lockPath) => {
|
|
916
3369
|
await initializeUpdateLock(lockPath);
|
|
917
|
-
await
|
|
3370
|
+
await verifyLockFile2(lockPath);
|
|
918
3371
|
const db = await openSqlite(lockPath);
|
|
919
3372
|
const deadline = performance.now() + 1e3;
|
|
920
3373
|
try {
|
|
@@ -926,7 +3379,7 @@ var openUpdateLock = async (lockPath) => {
|
|
|
926
3379
|
} catch (error) {
|
|
927
3380
|
if (error.code !== "SQLITE_BUSY" || performance.now() >= deadline)
|
|
928
3381
|
throw error;
|
|
929
|
-
await
|
|
3382
|
+
await delay2(20);
|
|
930
3383
|
}
|
|
931
3384
|
}
|
|
932
3385
|
} catch (error) {
|
|
@@ -934,17 +3387,8 @@ var openUpdateLock = async (lockPath) => {
|
|
|
934
3387
|
throw error;
|
|
935
3388
|
}
|
|
936
3389
|
};
|
|
937
|
-
var verifyAncestors = async (directory2, uid) => {
|
|
938
|
-
let child = directory2;
|
|
939
|
-
while (child !== path5.dirname(child)) {
|
|
940
|
-
child = path5.dirname(child);
|
|
941
|
-
const info = await fs3.stat(child);
|
|
942
|
-
if (!info.isDirectory() || info.uid !== 0 && info.uid !== uid || (info.mode & 18) !== 0 && (info.mode & 512) === 0)
|
|
943
|
-
throw new Error("unsafe_projects_policy_ancestor");
|
|
944
|
-
}
|
|
945
|
-
};
|
|
946
3390
|
var normalizeProjectPolicy = (value, field) => {
|
|
947
|
-
if (!
|
|
3391
|
+
if (!isRecord5(value)) throw new Error(`${field} must be an object`);
|
|
948
3392
|
const { approval_mode, sandbox_mode, protected_paths, trust_project_allows } = value;
|
|
949
3393
|
if (trust_project_allows !== void 0 && typeof trust_project_allows !== "boolean")
|
|
950
3394
|
throw new Error(`${field}.trust_project_allows must be boolean`);
|
|
@@ -952,7 +3396,7 @@ var normalizeProjectPolicy = (value, field) => {
|
|
|
952
3396
|
const sandboxMode = parseSandboxMode(sandbox_mode);
|
|
953
3397
|
const toolAllows = value.remembered_tool_allows;
|
|
954
3398
|
if (toolAllows !== void 0 && (!Array.isArray(toolAllows) || toolAllows.some(
|
|
955
|
-
(rule) => !
|
|
3399
|
+
(rule) => !isRecord5(rule) || Object.keys(rule).length !== 1 || typeof rule.tool !== "string" || !/^[a-z][a-z0-9_]*$/.test(rule.tool)
|
|
956
3400
|
)))
|
|
957
3401
|
throw new Error(
|
|
958
3402
|
`${field}.remembered_tool_allows must contain tool-only rules`
|
|
@@ -962,7 +3406,7 @@ var normalizeProjectPolicy = (value, field) => {
|
|
|
962
3406
|
if (sandbox_mode !== void 0 && !sandboxMode)
|
|
963
3407
|
throw new Error(`${field}.sandbox_mode is invalid`);
|
|
964
3408
|
if (protected_paths !== void 0 && (!Array.isArray(protected_paths) || protected_paths.some(
|
|
965
|
-
(entry) => typeof entry !== "string" || !
|
|
3409
|
+
(entry) => typeof entry !== "string" || !path11.isAbsolute(entry) || [...entry].some(
|
|
966
3410
|
(character) => character < " " || character === "\x7F"
|
|
967
3411
|
)
|
|
968
3412
|
)))
|
|
@@ -976,7 +3420,7 @@ var normalizeProjectPolicy = (value, field) => {
|
|
|
976
3420
|
};
|
|
977
3421
|
};
|
|
978
3422
|
var normalizeProjectsPolicyFile = (value) => {
|
|
979
|
-
if (!
|
|
3423
|
+
if (!isRecord5(value)) {
|
|
980
3424
|
throw new Error("projects policy must be an object");
|
|
981
3425
|
}
|
|
982
3426
|
if (value.version !== 1) {
|
|
@@ -991,7 +3435,7 @@ var normalizeProjectsPolicyFile = (value) => {
|
|
|
991
3435
|
if (Object.keys(entry).length) normalized.default = entry;
|
|
992
3436
|
}
|
|
993
3437
|
if (value.projects !== void 0) {
|
|
994
|
-
if (!
|
|
3438
|
+
if (!isRecord5(value.projects))
|
|
995
3439
|
throw new Error("projects policy projects must be an object");
|
|
996
3440
|
const entries2 = Object.entries(value.projects).flatMap(([key, value2]) => {
|
|
997
3441
|
const entry = normalizeProjectPolicy(
|
|
@@ -1005,16 +3449,16 @@ var normalizeProjectsPolicyFile = (value) => {
|
|
|
1005
3449
|
return normalized;
|
|
1006
3450
|
};
|
|
1007
3451
|
var atomicWriteFile = async (filePath, content) => {
|
|
1008
|
-
const dirPath =
|
|
1009
|
-
const fileName =
|
|
1010
|
-
const tempPath =
|
|
3452
|
+
const dirPath = path11.dirname(filePath);
|
|
3453
|
+
const fileName = path11.basename(filePath);
|
|
3454
|
+
const tempPath = path11.join(
|
|
1011
3455
|
dirPath,
|
|
1012
3456
|
`.${fileName}.${process.pid}.${Date.now()}.tmp`
|
|
1013
3457
|
);
|
|
1014
|
-
await
|
|
1015
|
-
await
|
|
3458
|
+
await fs9.writeFile(tempPath, content, { mode: 384 });
|
|
3459
|
+
await fs9.rename(tempPath, filePath);
|
|
1016
3460
|
if (process.platform !== "win32") {
|
|
1017
|
-
await
|
|
3461
|
+
await fs9.chmod(filePath, 384);
|
|
1018
3462
|
}
|
|
1019
3463
|
};
|
|
1020
3464
|
var ProjectsPolicyStore = class {
|
|
@@ -1025,67 +3469,72 @@ var ProjectsPolicyStore = class {
|
|
|
1025
3469
|
getFilePath() {
|
|
1026
3470
|
return this.paths.projectsFile;
|
|
1027
3471
|
}
|
|
1028
|
-
async verifyWorkspaceLocation(workspace, configured, file, access, reservedFile = resolveStoragePaths().projectsFile) {
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
3472
|
+
async verifyWorkspaceLocation(workspace, configured, file, access, relativePath = "projects.json", reservedFile = resolveStoragePaths().projectsFile) {
|
|
3473
|
+
await verifyUserStorageLocation({
|
|
3474
|
+
workspace,
|
|
3475
|
+
configured,
|
|
3476
|
+
resolved: file,
|
|
3477
|
+
relativePath,
|
|
3478
|
+
// Preserve existing read compatibility for owner-verified custom
|
|
3479
|
+
// XDG_CONFIG_HOME paths inside ~ so stored readonly/protected_paths are
|
|
3480
|
+
// never silently dropped, while restricting writes to default layouts.
|
|
3481
|
+
...access === "read" ? { reservedOverride: reservedFile } : {},
|
|
3482
|
+
errorMessage: "unsafe_projects_policy_path"
|
|
3483
|
+
});
|
|
1036
3484
|
}
|
|
1037
|
-
async trustedPath(workspace, access, configured =
|
|
3485
|
+
async trustedPath(workspace, access, configured = path11.resolve(this.paths.projectsFile), relativePath = "projects.json", reservedFile = resolveStoragePaths().projectsFile) {
|
|
1038
3486
|
const uid = process.geteuid?.();
|
|
1039
3487
|
if (uid === void 0) throw new Error("unsafe_projects_policy_path");
|
|
1040
|
-
const destination =
|
|
3488
|
+
const destination = path11.dirname(configured);
|
|
1041
3489
|
let ancestor = destination;
|
|
1042
3490
|
let canonical;
|
|
1043
3491
|
for (; ; ) {
|
|
1044
3492
|
try {
|
|
1045
|
-
canonical = await
|
|
3493
|
+
canonical = await fs9.realpath(ancestor);
|
|
1046
3494
|
break;
|
|
1047
3495
|
} catch (error) {
|
|
1048
|
-
if (!missing(error) || ancestor ===
|
|
1049
|
-
if (await
|
|
3496
|
+
if (!missing(error) || ancestor === path11.dirname(ancestor)) throw error;
|
|
3497
|
+
if (await lstatIfPresent2(ancestor))
|
|
1050
3498
|
throw new Error("unsafe_projects_policy_path");
|
|
1051
|
-
ancestor =
|
|
3499
|
+
ancestor = path11.dirname(ancestor);
|
|
1052
3500
|
}
|
|
1053
3501
|
}
|
|
1054
|
-
const directory2 =
|
|
3502
|
+
const directory2 = path11.join(
|
|
1055
3503
|
canonical,
|
|
1056
|
-
|
|
3504
|
+
path11.relative(ancestor, destination)
|
|
1057
3505
|
);
|
|
1058
|
-
const file =
|
|
3506
|
+
const file = path11.join(directory2, path11.basename(configured));
|
|
1059
3507
|
await this.verifyWorkspaceLocation(
|
|
1060
3508
|
workspace,
|
|
1061
3509
|
configured,
|
|
1062
3510
|
file,
|
|
1063
3511
|
access,
|
|
3512
|
+
relativePath,
|
|
1064
3513
|
reservedFile
|
|
1065
3514
|
);
|
|
1066
|
-
const owner = await
|
|
3515
|
+
const owner = await fs9.stat(canonical);
|
|
1067
3516
|
if (!owner.isDirectory() || owner.uid !== uid || (owner.mode & 18) !== 0)
|
|
1068
3517
|
throw new Error("unsafe_projects_policy_directory");
|
|
1069
|
-
await
|
|
1070
|
-
if (ancestor !== canonical) await
|
|
3518
|
+
await verifyOwnedAncestors(canonical, uid);
|
|
3519
|
+
if (ancestor !== canonical) await verifyOwnedAncestors(ancestor, uid);
|
|
1071
3520
|
if (access !== "read")
|
|
1072
|
-
await
|
|
3521
|
+
await fs9.access(canonical, constants4.W_OK | constants4.X_OK);
|
|
1073
3522
|
if (access === "create" && ancestor !== destination) {
|
|
1074
|
-
await
|
|
1075
|
-
if (await
|
|
3523
|
+
await fs9.mkdir(directory2, { recursive: true, mode: 448 });
|
|
3524
|
+
if (await fs9.realpath(directory2) !== directory2)
|
|
1076
3525
|
throw new Error("unsafe_projects_policy_directory");
|
|
1077
3526
|
return this.trustedPath(workspace, "write");
|
|
1078
3527
|
}
|
|
1079
3528
|
return file;
|
|
1080
3529
|
}
|
|
1081
3530
|
async readUserFile(file, owner) {
|
|
1082
|
-
const info = await
|
|
3531
|
+
const info = await lstatIfPresent2(file);
|
|
1083
3532
|
if (!info) return void 0;
|
|
1084
3533
|
if (!info.isFile() || info.nlink !== 1)
|
|
1085
3534
|
throw new Error("unsafe_projects_policy_file");
|
|
1086
|
-
const handle = await
|
|
3535
|
+
const handle = await fs9.open(
|
|
1087
3536
|
file,
|
|
1088
|
-
|
|
3537
|
+
constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0) | (constants4.O_NONBLOCK ?? 0)
|
|
1089
3538
|
);
|
|
1090
3539
|
try {
|
|
1091
3540
|
const current = await handle.stat();
|
|
@@ -1103,7 +3552,8 @@ var ProjectsPolicyStore = class {
|
|
|
1103
3552
|
const file = await this.trustedPath(
|
|
1104
3553
|
workspace,
|
|
1105
3554
|
"read",
|
|
1106
|
-
|
|
3555
|
+
path11.resolve(configured),
|
|
3556
|
+
"config.json",
|
|
1107
3557
|
this.paths.configFile
|
|
1108
3558
|
);
|
|
1109
3559
|
return this.readUserFile(file, uid);
|
|
@@ -1120,21 +3570,21 @@ var ProjectsPolicyStore = class {
|
|
|
1120
3570
|
return this.readPolicyFile(file, owner);
|
|
1121
3571
|
}
|
|
1122
3572
|
async hasUnverifiableProtectedPaths(workspace) {
|
|
1123
|
-
const configured =
|
|
1124
|
-
const canonicalParent = await
|
|
1125
|
-
const file =
|
|
3573
|
+
const configured = path11.resolve(this.paths.projectsFile);
|
|
3574
|
+
const canonicalParent = await fs9.realpath(path11.dirname(configured));
|
|
3575
|
+
const file = path11.join(canonicalParent, path11.basename(configured));
|
|
1126
3576
|
await this.verifyWorkspaceLocation(workspace, configured, file, "read");
|
|
1127
3577
|
const { normalized: policy } = await this.readPolicyFile(file, null);
|
|
1128
3578
|
return Boolean(
|
|
1129
3579
|
policy.default?.protected_paths?.length || Object.entries(policy.projects ?? {}).some(
|
|
1130
|
-
([root, entry]) => entry.protected_paths?.length &&
|
|
3580
|
+
([root, entry]) => entry.protected_paths?.length && path11.isAbsolute(root) && path11.relative(workspace, root) === ""
|
|
1131
3581
|
)
|
|
1132
3582
|
);
|
|
1133
3583
|
}
|
|
1134
3584
|
async loadUserOwned(workspace, { strict = false } = {}) {
|
|
1135
3585
|
let hasUnverifiablePaths;
|
|
1136
3586
|
try {
|
|
1137
|
-
if (strict && !await
|
|
3587
|
+
if (strict && !await lstatIfPresent2(this.paths.projectsFile))
|
|
1138
3588
|
return null;
|
|
1139
3589
|
if (strict && process.geteuid?.() === void 0) {
|
|
1140
3590
|
hasUnverifiablePaths = await this.hasUnverifiableProtectedPaths(workspace);
|
|
@@ -1154,7 +3604,7 @@ var ProjectsPolicyStore = class {
|
|
|
1154
3604
|
async verifyProjectModeWritable(workspace) {
|
|
1155
3605
|
const file = await this.trustedPath(workspace, "write");
|
|
1156
3606
|
await this.readTrusted(file);
|
|
1157
|
-
await
|
|
3607
|
+
await verifyLockFile2(lockFileFor(file));
|
|
1158
3608
|
}
|
|
1159
3609
|
/** Merge into a private user policy while other runtimes are excluded. */
|
|
1160
3610
|
async writeProjectMode(workspace, mode) {
|
|
@@ -1193,7 +3643,7 @@ var ProjectsPolicyStore = class {
|
|
|
1193
3643
|
async updateProject(workspace, patch, verify) {
|
|
1194
3644
|
const file = await this.trustedPath(workspace, "create");
|
|
1195
3645
|
const lock = await openUpdateLock(lockFileFor(file));
|
|
1196
|
-
const temporary = `${file}.${
|
|
3646
|
+
const temporary = `${file}.${randomUUID6()}.tmp`;
|
|
1197
3647
|
try {
|
|
1198
3648
|
const { raw: policy } = await this.readTrusted(file);
|
|
1199
3649
|
const projects = policy.projects;
|
|
@@ -1209,26 +3659,26 @@ var ProjectsPolicyStore = class {
|
|
|
1209
3659
|
[workspace]: { ...projects?.[workspace], ...changes }
|
|
1210
3660
|
}
|
|
1211
3661
|
};
|
|
1212
|
-
await
|
|
3662
|
+
await fs9.writeFile(temporary, `${JSON.stringify(next, null, 2)}
|
|
1213
3663
|
`, {
|
|
1214
3664
|
mode: 384,
|
|
1215
3665
|
flag: "wx"
|
|
1216
3666
|
});
|
|
1217
|
-
await
|
|
3667
|
+
await fs9.chmod(temporary, 384);
|
|
1218
3668
|
if (await this.trustedPath(workspace, "write") !== file)
|
|
1219
3669
|
throw new Error("unsafe_projects_policy_path");
|
|
1220
3670
|
verify?.();
|
|
1221
|
-
await
|
|
3671
|
+
await fs9.rename(temporary, file);
|
|
1222
3672
|
} finally {
|
|
1223
3673
|
lock.close();
|
|
1224
|
-
await
|
|
3674
|
+
await fs9.unlink(temporary).catch(() => void 0);
|
|
1225
3675
|
}
|
|
1226
3676
|
}
|
|
1227
3677
|
async load(canonicalPath) {
|
|
1228
3678
|
try {
|
|
1229
|
-
const handle = await
|
|
3679
|
+
const handle = await fs9.open(
|
|
1230
3680
|
canonicalPath ?? this.paths.projectsFile,
|
|
1231
|
-
canonicalPath ?
|
|
3681
|
+
canonicalPath ? constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0) | (constants4.O_NONBLOCK ?? 0) : "r"
|
|
1232
3682
|
);
|
|
1233
3683
|
let parsed;
|
|
1234
3684
|
try {
|
|
@@ -1262,36 +3712,36 @@ var ProjectsPolicyStore = class {
|
|
|
1262
3712
|
};
|
|
1263
3713
|
|
|
1264
3714
|
// src/session-store.ts
|
|
1265
|
-
import { promises as
|
|
1266
|
-
import
|
|
3715
|
+
import { promises as fs12 } from "fs";
|
|
3716
|
+
import path14 from "path";
|
|
1267
3717
|
|
|
1268
3718
|
// src/run-log-paths.ts
|
|
1269
|
-
import { createHash as
|
|
1270
|
-
import
|
|
3719
|
+
import { createHash as createHash4 } from "crypto";
|
|
3720
|
+
import path12 from "path";
|
|
1271
3721
|
var runDatePath = (startedAt) => {
|
|
1272
3722
|
const date = new Date(startedAt);
|
|
1273
3723
|
if (!Number.isFinite(date.getTime()))
|
|
1274
3724
|
throw new Error("Invalid run start time");
|
|
1275
|
-
return [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].map((part, index) => String(part).padStart(index === 0 ? 4 : 2, "0")).join(
|
|
3725
|
+
return [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].map((part, index) => String(part).padStart(index === 0 ? 4 : 2, "0")).join(path12.sep);
|
|
1276
3726
|
};
|
|
1277
3727
|
var validateRunLogId = (id2) => {
|
|
1278
3728
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(id2))
|
|
1279
3729
|
throw new Error("Invalid run/session log id");
|
|
1280
3730
|
return id2;
|
|
1281
3731
|
};
|
|
1282
|
-
var activeRunDirectory = (paths, sessionId) =>
|
|
3732
|
+
var activeRunDirectory = (paths, sessionId) => path12.join(
|
|
1283
3733
|
paths.sessionsDir,
|
|
1284
3734
|
"active-runs",
|
|
1285
|
-
|
|
3735
|
+
createHash4("sha256").update(sessionId).digest("hex")
|
|
1286
3736
|
);
|
|
1287
|
-
var usageLogPath = (paths, datePath, runId) =>
|
|
3737
|
+
var usageLogPath = (paths, datePath, runId) => path12.join(paths.root, "usage", datePath, `${validateRunLogId(runId)}.jsonl`);
|
|
1288
3738
|
|
|
1289
3739
|
// src/session-run-index.ts
|
|
1290
|
-
import { promises as
|
|
1291
|
-
import
|
|
3740
|
+
import { promises as fs11, lstatSync as lstatSync3 } from "fs";
|
|
3741
|
+
import path13 from "path";
|
|
1292
3742
|
|
|
1293
3743
|
// src/run-log-reader.ts
|
|
1294
|
-
import { constants as
|
|
3744
|
+
import { constants as constants5, existsSync, promises as fs10 } from "fs";
|
|
1295
3745
|
import { createInterface } from "readline";
|
|
1296
3746
|
import { Readable } from "stream";
|
|
1297
3747
|
import { createGunzip } from "zlib";
|
|
@@ -1300,17 +3750,17 @@ async function* readRunLogChunks(file) {
|
|
|
1300
3750
|
let resolved = resolveRunLogPath(file);
|
|
1301
3751
|
let handle;
|
|
1302
3752
|
try {
|
|
1303
|
-
handle = await
|
|
3753
|
+
handle = await fs10.open(
|
|
1304
3754
|
resolved,
|
|
1305
|
-
|
|
3755
|
+
constants5.O_RDONLY | (constants5.O_NOFOLLOW ?? 0)
|
|
1306
3756
|
);
|
|
1307
3757
|
} catch (error) {
|
|
1308
3758
|
if (error.code !== "ENOENT" || file.endsWith(".gz"))
|
|
1309
3759
|
throw error;
|
|
1310
3760
|
resolved = `${file}.gz`;
|
|
1311
|
-
handle = await
|
|
3761
|
+
handle = await fs10.open(
|
|
1312
3762
|
resolved,
|
|
1313
|
-
|
|
3763
|
+
constants5.O_RDONLY | (constants5.O_NOFOLLOW ?? 0)
|
|
1314
3764
|
);
|
|
1315
3765
|
}
|
|
1316
3766
|
const source = handle.createReadStream();
|
|
@@ -1345,18 +3795,18 @@ var normalizeRunStartedAt = (startedAt) => {
|
|
|
1345
3795
|
};
|
|
1346
3796
|
var isRegularFile = (file) => {
|
|
1347
3797
|
try {
|
|
1348
|
-
return
|
|
3798
|
+
return lstatSync3(file).isFile();
|
|
1349
3799
|
} catch {
|
|
1350
3800
|
return false;
|
|
1351
3801
|
}
|
|
1352
3802
|
};
|
|
1353
3803
|
var toRunLogRelPath = (sessionsDir, file) => {
|
|
1354
|
-
const relative =
|
|
3804
|
+
const relative = path13.relative(sessionsDir, file).split(path13.sep).join("/").replace(/\.gz$/, "");
|
|
1355
3805
|
return REL_PATH_PATTERN.test(relative) ? relative : void 0;
|
|
1356
3806
|
};
|
|
1357
3807
|
var resolveIndexedRunLog = (sessionsDir, relPath) => {
|
|
1358
3808
|
if (!REL_PATH_PATTERN.test(relPath)) return void 0;
|
|
1359
|
-
const plain =
|
|
3809
|
+
const plain = path13.join(sessionsDir, ...relPath.split("/"));
|
|
1360
3810
|
if (isRegularFile(plain)) return plain;
|
|
1361
3811
|
if (isRegularFile(`${plain}.gz`)) return `${plain}.gz`;
|
|
1362
3812
|
return void 0;
|
|
@@ -1376,7 +3826,7 @@ var readHeader = async (file) => {
|
|
|
1376
3826
|
var errorCode2 = (error) => error?.code;
|
|
1377
3827
|
var readDirs = async (directory2) => {
|
|
1378
3828
|
try {
|
|
1379
|
-
return await
|
|
3829
|
+
return await fs11.readdir(directory2, {
|
|
1380
3830
|
withFileTypes: true,
|
|
1381
3831
|
encoding: "utf8"
|
|
1382
3832
|
});
|
|
@@ -1394,13 +3844,13 @@ var listRunLogFiles = async (sessionsDir) => {
|
|
|
1394
3844
|
const files = [];
|
|
1395
3845
|
for (const year of await readDirs(sessionsDir)) {
|
|
1396
3846
|
if (!year.isDirectory() || !/^\d{4}$/.test(year.name)) continue;
|
|
1397
|
-
const yearPath =
|
|
3847
|
+
const yearPath = path13.join(sessionsDir, year.name);
|
|
1398
3848
|
for (const month of await readDirs(yearPath)) {
|
|
1399
3849
|
if (!month.isDirectory() || !/^\d{2}$/.test(month.name)) continue;
|
|
1400
|
-
const monthPath =
|
|
3850
|
+
const monthPath = path13.join(yearPath, month.name);
|
|
1401
3851
|
for (const day of await readDirs(monthPath)) {
|
|
1402
3852
|
if (!day.isDirectory() || !/^\d{2}$/.test(day.name)) continue;
|
|
1403
|
-
const dayPath =
|
|
3853
|
+
const dayPath = path13.join(monthPath, day.name);
|
|
1404
3854
|
const entries2 = (await readDirs(dayPath)).filter(
|
|
1405
3855
|
(entry) => entry.isFile() && /\.jsonl(?:\.gz)?$/.test(entry.name)
|
|
1406
3856
|
);
|
|
@@ -1410,7 +3860,7 @@ var listRunLogFiles = async (sessionsDir) => {
|
|
|
1410
3860
|
for (const entry of entries2) {
|
|
1411
3861
|
if (entry.name.endsWith(".gz") && plain.has(entry.name.slice(0, -3)))
|
|
1412
3862
|
continue;
|
|
1413
|
-
files.push(
|
|
3863
|
+
files.push(path13.join(dayPath, entry.name));
|
|
1414
3864
|
}
|
|
1415
3865
|
}
|
|
1416
3866
|
}
|
|
@@ -1430,10 +3880,10 @@ var scanSessionRunLogs = async (sessionsDir) => {
|
|
|
1430
3880
|
try {
|
|
1431
3881
|
const header = await readHeader(file);
|
|
1432
3882
|
if (!header || typeof header.session_id !== "string") continue;
|
|
1433
|
-
const startedAt = typeof header.started_at === "string" ? header.started_at : new Date((await
|
|
3883
|
+
const startedAt = typeof header.started_at === "string" ? header.started_at : new Date((await fs11.stat(file)).mtimeMs).toISOString();
|
|
1434
3884
|
entries2.push({
|
|
1435
3885
|
session_id: header.session_id,
|
|
1436
|
-
run_id: typeof header.run_id === "string" ? header.run_id :
|
|
3886
|
+
run_id: typeof header.run_id === "string" ? header.run_id : path13.posix.basename(relPath, ".jsonl"),
|
|
1437
3887
|
rel_path: relPath,
|
|
1438
3888
|
started_at: normalizeRunStartedAt(startedAt)
|
|
1439
3889
|
});
|
|
@@ -1506,7 +3956,7 @@ var SessionStoreWriterImpl = class {
|
|
|
1506
3956
|
this.runId = validateRunLogId(options.runId);
|
|
1507
3957
|
this.startedAt = options.startedAt;
|
|
1508
3958
|
const datePath = runDatePath(options.startedAt);
|
|
1509
|
-
this.filePath =
|
|
3959
|
+
this.filePath = path14.join(
|
|
1510
3960
|
paths.sessionsDir,
|
|
1511
3961
|
datePath,
|
|
1512
3962
|
`${this.runId}.jsonl`
|
|
@@ -1514,7 +3964,7 @@ var SessionStoreWriterImpl = class {
|
|
|
1514
3964
|
this.usageFilePath = usageLogPath(paths, datePath, this.runId);
|
|
1515
3965
|
const dump = options.dump ?? /^(1|true)$/i.test(process.env.CODELIA_SESSION_DUMP ?? "");
|
|
1516
3966
|
if (dump)
|
|
1517
|
-
this.diagnosticFilePath =
|
|
3967
|
+
this.diagnosticFilePath = path14.join(
|
|
1518
3968
|
paths.sessionsDir,
|
|
1519
3969
|
"diagnostics",
|
|
1520
3970
|
datePath,
|
|
@@ -1589,9 +4039,9 @@ var SessionStoreWriterImpl = class {
|
|
|
1589
4039
|
if (markerSessionId) {
|
|
1590
4040
|
await this.recordRun(markerSessionId, startedAt ?? this.startedAt);
|
|
1591
4041
|
const directory2 = activeRunDirectory(this.paths, markerSessionId);
|
|
1592
|
-
await
|
|
1593
|
-
this.activePath =
|
|
1594
|
-
await
|
|
4042
|
+
await fs12.mkdir(directory2, { recursive: true });
|
|
4043
|
+
this.activePath = path14.join(directory2, `${this.runId}.json`);
|
|
4044
|
+
await fs12.writeFile(
|
|
1595
4045
|
this.activePath,
|
|
1596
4046
|
JSON.stringify({
|
|
1597
4047
|
pid: process.pid,
|
|
@@ -1608,11 +4058,11 @@ var SessionStoreWriterImpl = class {
|
|
|
1608
4058
|
[this.diagnosticFilePath, dump]
|
|
1609
4059
|
]) {
|
|
1610
4060
|
if (!file || line === void 0) continue;
|
|
1611
|
-
await
|
|
1612
|
-
await
|
|
4061
|
+
await fs12.mkdir(path14.dirname(file), { recursive: true });
|
|
4062
|
+
await fs12.appendFile(file, line, { encoding: "utf8", mode: 384 });
|
|
1613
4063
|
}
|
|
1614
4064
|
if (terminal && this.activePath) {
|
|
1615
|
-
await
|
|
4065
|
+
await fs12.unlink(this.activePath);
|
|
1616
4066
|
this.activePath = void 0;
|
|
1617
4067
|
}
|
|
1618
4068
|
});
|
|
@@ -1626,22 +4076,22 @@ var SessionStoreWriterImpl = class {
|
|
|
1626
4076
|
import {
|
|
1627
4077
|
closeSync as closeSync2,
|
|
1628
4078
|
existsSync as existsSync2,
|
|
1629
|
-
promises as
|
|
4079
|
+
promises as fs13,
|
|
1630
4080
|
fsyncSync as fsyncSync2,
|
|
1631
|
-
lstatSync as
|
|
4081
|
+
lstatSync as lstatSync4,
|
|
1632
4082
|
openSync as openSync2,
|
|
1633
|
-
readFileSync,
|
|
4083
|
+
readFileSync as readFileSync3,
|
|
1634
4084
|
renameSync,
|
|
1635
4085
|
unlinkSync,
|
|
1636
4086
|
writeFileSync
|
|
1637
4087
|
} from "fs";
|
|
1638
|
-
import
|
|
4088
|
+
import path15 from "path";
|
|
1639
4089
|
import { stringifyContent as stringifyContent2 } from "@codelia/core";
|
|
1640
4090
|
|
|
1641
4091
|
// src/conversation-archive.ts
|
|
1642
4092
|
import {
|
|
1643
4093
|
closeSync,
|
|
1644
|
-
constants as
|
|
4094
|
+
constants as constants6,
|
|
1645
4095
|
createReadStream,
|
|
1646
4096
|
fstatSync,
|
|
1647
4097
|
fsyncSync,
|
|
@@ -1660,7 +4110,7 @@ function appendOriginalMessages(file, messages, provenance) {
|
|
|
1660
4110
|
);
|
|
1661
4111
|
const fd = openSync(
|
|
1662
4112
|
file,
|
|
1663
|
-
|
|
4113
|
+
constants6.O_RDWR | constants6.O_CREAT | constants6.O_APPEND | (constants6.O_NOFOLLOW ?? 0),
|
|
1664
4114
|
384
|
|
1665
4115
|
);
|
|
1666
4116
|
try {
|
|
@@ -1699,7 +4149,7 @@ var textOf = (message) => {
|
|
|
1699
4149
|
${JSON.stringify(message.tool_calls.map((call) => ({ id: call.id, function: call.function })))}` : text;
|
|
1700
4150
|
};
|
|
1701
4151
|
async function* entries(file, start, maxBytes) {
|
|
1702
|
-
const fd = openSync(file,
|
|
4152
|
+
const fd = openSync(file, constants6.O_RDONLY | (constants6.O_NOFOLLOW ?? 0));
|
|
1703
4153
|
let stream;
|
|
1704
4154
|
try {
|
|
1705
4155
|
const stat = fstatSync(fd);
|
|
@@ -1923,9 +4373,9 @@ var MESSAGES_DIRNAME = "messages";
|
|
|
1923
4373
|
var STATE_DB_FILENAME = "state.db";
|
|
1924
4374
|
var SESSION_WORKSPACE_ROOT_META_KEY = "codelia_workspace_root";
|
|
1925
4375
|
var RUN_INDEX_BACKFILL_KEY = "session_runs_backfilled_at";
|
|
1926
|
-
var resolveLegacyStateDir = (paths) =>
|
|
1927
|
-
var resolveMessagesDir = (paths) =>
|
|
1928
|
-
var resolveStateDbPath = (paths) =>
|
|
4376
|
+
var resolveLegacyStateDir = (paths) => path15.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
|
|
4377
|
+
var resolveMessagesDir = (paths) => path15.join(paths.sessionsDir, MESSAGES_DIRNAME);
|
|
4378
|
+
var resolveStateDbPath = (paths) => path15.join(paths.sessionsDir, STATE_DB_FILENAME);
|
|
1929
4379
|
var extractLastUserMessage = (messages) => {
|
|
1930
4380
|
for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
|
|
1931
4381
|
const message = messages[idx];
|
|
@@ -1996,13 +4446,13 @@ var SessionStateStoreImpl = class {
|
|
|
1996
4446
|
this.sessionsDir = paths.sessionsDir;
|
|
1997
4447
|
this.legacyStateDir = resolveLegacyStateDir(paths);
|
|
1998
4448
|
this.messagesDir = resolveMessagesDir(paths);
|
|
1999
|
-
this.contextsDir =
|
|
4449
|
+
this.contextsDir = path15.join(paths.sessionsDir, "contexts");
|
|
2000
4450
|
this.stateDbPath = resolveStateDbPath(paths);
|
|
2001
4451
|
this.ensureDirs = Promise.all([
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
4452
|
+
fs13.mkdir(paths.sessionsDir, { recursive: true }),
|
|
4453
|
+
fs13.mkdir(this.legacyStateDir, { recursive: true }),
|
|
4454
|
+
fs13.mkdir(this.messagesDir, { recursive: true }),
|
|
4455
|
+
fs13.mkdir(this.contextsDir, { recursive: true })
|
|
2006
4456
|
]).then(() => {
|
|
2007
4457
|
});
|
|
2008
4458
|
this.onError = options.onError;
|
|
@@ -2017,18 +4467,18 @@ var SessionStateStoreImpl = class {
|
|
|
2017
4467
|
return this.db;
|
|
2018
4468
|
}
|
|
2019
4469
|
resolveLegacyPath(sessionId) {
|
|
2020
|
-
return
|
|
4470
|
+
return path15.join(this.legacyStateDir, `${sessionId}.json`);
|
|
2021
4471
|
}
|
|
2022
4472
|
resolveMessagePath(sessionId) {
|
|
2023
|
-
return
|
|
4473
|
+
return path15.join(this.messagesDir, `${validateRunLogId(sessionId)}.jsonl`);
|
|
2024
4474
|
}
|
|
2025
4475
|
contextPath(sessionId) {
|
|
2026
|
-
return
|
|
4476
|
+
return path15.join(this.contextsDir, `${validateRunLogId(sessionId)}.json`);
|
|
2027
4477
|
}
|
|
2028
4478
|
writeContext(sessionId, messages) {
|
|
2029
4479
|
const target = this.contextPath(sessionId);
|
|
2030
4480
|
const temporary = `${target}.${crypto.randomUUID()}.tmp`;
|
|
2031
|
-
const archiveBytes =
|
|
4481
|
+
const archiveBytes = lstatSync4(this.resolveMessagePath(sessionId)).size;
|
|
2032
4482
|
try {
|
|
2033
4483
|
const fd = openSync2(temporary, "wx", 384);
|
|
2034
4484
|
try {
|
|
@@ -2051,16 +4501,16 @@ var SessionStateStoreImpl = class {
|
|
|
2051
4501
|
[sessionId]
|
|
2052
4502
|
);
|
|
2053
4503
|
if (row?.archive_version === 1) {
|
|
2054
|
-
if (!
|
|
4504
|
+
if (!lstatSync4(this.resolveMessagePath(sessionId)).isFile())
|
|
2055
4505
|
throw new Error("Invalid original conversation archive");
|
|
2056
4506
|
return false;
|
|
2057
4507
|
}
|
|
2058
4508
|
const file = this.resolveMessagePath(sessionId);
|
|
2059
4509
|
let messages = [];
|
|
2060
4510
|
if (existsSync2(file)) {
|
|
2061
|
-
if (!
|
|
4511
|
+
if (!lstatSync4(file).isFile())
|
|
2062
4512
|
throw new Error("Invalid legacy conversation file");
|
|
2063
|
-
messages = deserializeMessages(
|
|
4513
|
+
messages = deserializeMessages(readFileSync3(file, "utf8"));
|
|
2064
4514
|
} else appendOriginalMessages(file, []);
|
|
2065
4515
|
this.writeContext(sessionId, messages);
|
|
2066
4516
|
db.run(
|
|
@@ -2188,7 +4638,7 @@ var SessionStateStoreImpl = class {
|
|
|
2188
4638
|
}
|
|
2189
4639
|
async loadLegacy(sessionId) {
|
|
2190
4640
|
try {
|
|
2191
|
-
const file = await
|
|
4641
|
+
const file = await fs13.readFile(this.resolveLegacyPath(sessionId), "utf8");
|
|
2192
4642
|
const parsed = JSON.parse(file);
|
|
2193
4643
|
if (!parsed || typeof parsed !== "object") return null;
|
|
2194
4644
|
if (!parsed.session_id || !parsed.updated_at) return null;
|
|
@@ -2228,14 +4678,14 @@ var SessionStateStoreImpl = class {
|
|
|
2228
4678
|
try {
|
|
2229
4679
|
if (row.archive_version === 1) {
|
|
2230
4680
|
const checkpoint = JSON.parse(
|
|
2231
|
-
await
|
|
4681
|
+
await fs13.readFile(this.contextPath(sessionId), "utf8")
|
|
2232
4682
|
);
|
|
2233
4683
|
if (checkpoint.version !== 1 || !Array.isArray(checkpoint.messages))
|
|
2234
4684
|
throw new Error("Invalid active conversation checkpoint");
|
|
2235
4685
|
messages = checkpoint.messages;
|
|
2236
4686
|
} else
|
|
2237
4687
|
messages = deserializeMessages(
|
|
2238
|
-
await
|
|
4688
|
+
await fs13.readFile(this.resolveMessagePath(sessionId), "utf8")
|
|
2239
4689
|
);
|
|
2240
4690
|
} catch (error) {
|
|
2241
4691
|
if (error.code === "ENOENT" && row.archive_version !== 1) {
|
|
@@ -2573,7 +5023,7 @@ var SessionStateStoreImpl = class {
|
|
|
2573
5023
|
async listLegacySummaries() {
|
|
2574
5024
|
let entries2;
|
|
2575
5025
|
try {
|
|
2576
|
-
entries2 = await
|
|
5026
|
+
entries2 = await fs13.readdir(this.legacyStateDir, {
|
|
2577
5027
|
withFileTypes: true,
|
|
2578
5028
|
encoding: "utf8"
|
|
2579
5029
|
});
|
|
@@ -2585,9 +5035,9 @@ var SessionStateStoreImpl = class {
|
|
|
2585
5035
|
for (const entry of entries2) {
|
|
2586
5036
|
if (!entry.isFile()) continue;
|
|
2587
5037
|
if (!entry.name.endsWith(".json")) continue;
|
|
2588
|
-
const filePath =
|
|
5038
|
+
const filePath = path15.join(this.legacyStateDir, entry.name);
|
|
2589
5039
|
try {
|
|
2590
|
-
const contents = await
|
|
5040
|
+
const contents = await fs13.readFile(filePath, "utf8");
|
|
2591
5041
|
const parsed = JSON.parse(contents);
|
|
2592
5042
|
if (!parsed || typeof parsed !== "object") continue;
|
|
2593
5043
|
if (!parsed.session_id || !parsed.updated_at) continue;
|
|
@@ -2657,18 +5107,18 @@ var RunEventStoreFactoryImpl = class {
|
|
|
2657
5107
|
|
|
2658
5108
|
// src/run-log-retention.ts
|
|
2659
5109
|
import {
|
|
2660
|
-
promises as
|
|
5110
|
+
promises as fs17,
|
|
2661
5111
|
linkSync,
|
|
2662
|
-
lstatSync as
|
|
5112
|
+
lstatSync as lstatSync6,
|
|
2663
5113
|
renameSync as renameSync2,
|
|
2664
5114
|
unlinkSync as unlinkSync3,
|
|
2665
5115
|
utimesSync
|
|
2666
5116
|
} from "fs";
|
|
2667
|
-
import
|
|
5117
|
+
import path18 from "path";
|
|
2668
5118
|
|
|
2669
5119
|
// src/run-log-compression.ts
|
|
2670
|
-
import { createHash as
|
|
2671
|
-
import { createReadStream as createReadStream2, createWriteStream, promises as
|
|
5120
|
+
import { createHash as createHash5 } from "crypto";
|
|
5121
|
+
import { createReadStream as createReadStream2, createWriteStream, promises as fs14 } from "fs";
|
|
2672
5122
|
import { Readable as Readable2, Transform } from "stream";
|
|
2673
5123
|
import { pipeline } from "stream/promises";
|
|
2674
5124
|
import { createGunzip as createGunzip2, createGzip } from "zlib";
|
|
@@ -2768,7 +5218,7 @@ async function* projectArchivedRunLog(file, usage) {
|
|
|
2768
5218
|
// src/run-log-compression.ts
|
|
2769
5219
|
async function prepareCompressedLog(file, usage) {
|
|
2770
5220
|
const temporary = `${file}.${crypto.randomUUID()}.gz.tmp`;
|
|
2771
|
-
const hash =
|
|
5221
|
+
const hash = createHash5("sha256");
|
|
2772
5222
|
let bytes = 0;
|
|
2773
5223
|
try {
|
|
2774
5224
|
await pipeline(
|
|
@@ -2784,7 +5234,7 @@ async function prepareCompressedLog(file, usage) {
|
|
|
2784
5234
|
createWriteStream(temporary, { flags: "wx", mode: 384 })
|
|
2785
5235
|
);
|
|
2786
5236
|
const expected = hash.digest("hex");
|
|
2787
|
-
const verification =
|
|
5237
|
+
const verification = createHash5("sha256");
|
|
2788
5238
|
let decoded = 0;
|
|
2789
5239
|
await pipeline(
|
|
2790
5240
|
createReadStream2(temporary),
|
|
@@ -2799,32 +5249,32 @@ async function prepareCompressedLog(file, usage) {
|
|
|
2799
5249
|
);
|
|
2800
5250
|
if (decoded !== bytes || verification.digest("hex") !== expected)
|
|
2801
5251
|
throw new Error("Compressed run log verification failed");
|
|
2802
|
-
const persisted = await
|
|
5252
|
+
const persisted = await fs14.open(temporary, "r+");
|
|
2803
5253
|
try {
|
|
2804
5254
|
await persisted.sync();
|
|
2805
5255
|
} finally {
|
|
2806
5256
|
await persisted.close();
|
|
2807
5257
|
}
|
|
2808
|
-
return { temporary, size: (await
|
|
5258
|
+
return { temporary, size: (await fs14.stat(temporary)).size };
|
|
2809
5259
|
} catch (error) {
|
|
2810
|
-
await
|
|
5260
|
+
await fs14.rm(temporary, { force: true });
|
|
2811
5261
|
throw error;
|
|
2812
5262
|
}
|
|
2813
5263
|
}
|
|
2814
5264
|
|
|
2815
5265
|
// src/run-log-files.ts
|
|
2816
5266
|
import {
|
|
2817
|
-
promises as
|
|
2818
|
-
lstatSync as
|
|
5267
|
+
promises as fs15,
|
|
5268
|
+
lstatSync as lstatSync5,
|
|
2819
5269
|
readdirSync,
|
|
2820
|
-
readFileSync as
|
|
5270
|
+
readFileSync as readFileSync4,
|
|
2821
5271
|
unlinkSync as unlinkSync2
|
|
2822
5272
|
} from "fs";
|
|
2823
|
-
import
|
|
5273
|
+
import path16 from "path";
|
|
2824
5274
|
var MAX_ACTIVE_RUN_MARKER_BYTES = 256;
|
|
2825
5275
|
var isRegularDirectory = async (directory2) => {
|
|
2826
5276
|
try {
|
|
2827
|
-
return (await
|
|
5277
|
+
return (await fs15.lstat(directory2)).isDirectory();
|
|
2828
5278
|
} catch {
|
|
2829
5279
|
return false;
|
|
2830
5280
|
}
|
|
@@ -2850,9 +5300,9 @@ async function readHeader2(file) {
|
|
|
2850
5300
|
}
|
|
2851
5301
|
async function inspectCandidate(root, datePath, name, diagnostic) {
|
|
2852
5302
|
const compressed = name.endsWith(".jsonl.gz");
|
|
2853
|
-
const file =
|
|
5303
|
+
const file = path16.join(root, datePath, name);
|
|
2854
5304
|
try {
|
|
2855
|
-
const stat = await
|
|
5305
|
+
const stat = await fs15.lstat(file);
|
|
2856
5306
|
if (!stat.isFile()) return void 0;
|
|
2857
5307
|
const header = await readHeader2(file);
|
|
2858
5308
|
if (!header || name !== `${header.run_id}.jsonl${compressed ? ".gz" : ""}` || compressed && header.meta?.codelia_log_archive_version === RUN_LOG_ARCHIVE_VERSION)
|
|
@@ -2877,19 +5327,19 @@ async function inspectCandidate(root, datePath, name, diagnostic) {
|
|
|
2877
5327
|
async function collectRunLogCandidates(root, diagnostic = false) {
|
|
2878
5328
|
if (!await isRegularDirectory(root)) return [];
|
|
2879
5329
|
const candidates = [];
|
|
2880
|
-
for (const year of await
|
|
5330
|
+
for (const year of await fs15.readdir(root, { withFileTypes: true })) {
|
|
2881
5331
|
if (!year.isDirectory() || !/^\d{4}$/.test(year.name)) continue;
|
|
2882
|
-
for (const month of await
|
|
5332
|
+
for (const month of await fs15.readdir(path16.join(root, year.name), {
|
|
2883
5333
|
withFileTypes: true
|
|
2884
5334
|
})) {
|
|
2885
5335
|
if (!month.isDirectory() || !/^\d{2}$/.test(month.name)) continue;
|
|
2886
|
-
for (const day of await
|
|
2887
|
-
|
|
5336
|
+
for (const day of await fs15.readdir(
|
|
5337
|
+
path16.join(root, year.name, month.name),
|
|
2888
5338
|
{ withFileTypes: true }
|
|
2889
5339
|
)) {
|
|
2890
5340
|
if (!day.isDirectory() || !/^\d{2}$/.test(day.name)) continue;
|
|
2891
|
-
const datePath =
|
|
2892
|
-
const entries2 = await
|
|
5341
|
+
const datePath = path16.join(year.name, month.name, day.name);
|
|
5342
|
+
const entries2 = await fs15.readdir(path16.join(root, datePath), {
|
|
2893
5343
|
withFileTypes: true
|
|
2894
5344
|
});
|
|
2895
5345
|
const plain = new Set(
|
|
@@ -2921,10 +5371,10 @@ async function collectRunLogCandidatesAt(root, relPaths, diagnostic = false) {
|
|
|
2921
5371
|
const name = parts.pop();
|
|
2922
5372
|
if (!name?.endsWith(".jsonl") || parts.length !== 3 || !/^\d{4}$/.test(parts[0] ?? "") || !/^\d{2}$/.test(parts[1] ?? "") || !/^\d{2}$/.test(parts[2] ?? "") || name.includes("\\"))
|
|
2923
5373
|
continue;
|
|
2924
|
-
const datePath =
|
|
5374
|
+
const datePath = path16.join(...parts);
|
|
2925
5375
|
let selected = name;
|
|
2926
5376
|
try {
|
|
2927
|
-
await
|
|
5377
|
+
await fs15.lstat(path16.join(root, datePath, name));
|
|
2928
5378
|
} catch {
|
|
2929
5379
|
if (diagnostic) continue;
|
|
2930
5380
|
selected = `${name}.gz`;
|
|
@@ -2948,19 +5398,19 @@ async function removeReusedProcessMarkers(paths, sessionId, identify = (pid) =>
|
|
|
2948
5398
|
return;
|
|
2949
5399
|
}
|
|
2950
5400
|
for (const entry of entries2) {
|
|
2951
|
-
const file =
|
|
5401
|
+
const file = path16.join(directory2, entry);
|
|
2952
5402
|
try {
|
|
2953
|
-
const before =
|
|
5403
|
+
const before = lstatSync5(file);
|
|
2954
5404
|
if (!before.isFile() || before.size > MAX_ACTIVE_RUN_MARKER_BYTES)
|
|
2955
5405
|
continue;
|
|
2956
|
-
const contents =
|
|
5406
|
+
const contents = readFileSync4(file, "utf8");
|
|
2957
5407
|
const { pid, identity } = JSON.parse(contents);
|
|
2958
5408
|
if (!Number.isSafeInteger(pid) || pid < 1 || typeof identity !== "string" || !identity)
|
|
2959
5409
|
continue;
|
|
2960
5410
|
const current = await identify(pid);
|
|
2961
5411
|
if (!current || current === identity) continue;
|
|
2962
|
-
const after =
|
|
2963
|
-
if (after.isFile() && after.ino === before.ino && after.dev === before.dev && after.size === before.size && after.mtimeMs === before.mtimeMs &&
|
|
5412
|
+
const after = lstatSync5(file);
|
|
5413
|
+
if (after.isFile() && after.ino === before.ino && after.dev === before.dev && after.size === before.size && after.mtimeMs === before.mtimeMs && readFileSync4(file, "utf8") === contents)
|
|
2964
5414
|
unlinkSync2(file);
|
|
2965
5415
|
} catch {
|
|
2966
5416
|
}
|
|
@@ -2972,9 +5422,9 @@ function hasActiveRunWriter(paths, sessionId) {
|
|
|
2972
5422
|
for (const entry of readdirSync(directory2, { withFileTypes: true })) {
|
|
2973
5423
|
if (!entry.isFile()) return true;
|
|
2974
5424
|
try {
|
|
2975
|
-
const file =
|
|
2976
|
-
if (
|
|
2977
|
-
const { pid } = JSON.parse(
|
|
5425
|
+
const file = path16.join(directory2, entry.name);
|
|
5426
|
+
if (lstatSync5(file).size > MAX_ACTIVE_RUN_MARKER_BYTES) return true;
|
|
5427
|
+
const { pid } = JSON.parse(readFileSync4(file, "utf8"));
|
|
2978
5428
|
if (!Number.isSafeInteger(pid) || pid < 1) return true;
|
|
2979
5429
|
try {
|
|
2980
5430
|
process.kill(pid, 0);
|
|
@@ -2993,8 +5443,8 @@ function hasActiveRunWriter(paths, sessionId) {
|
|
|
2993
5443
|
}
|
|
2994
5444
|
|
|
2995
5445
|
// src/run-log-usage.ts
|
|
2996
|
-
import { promises as
|
|
2997
|
-
import
|
|
5446
|
+
import { promises as fs16 } from "fs";
|
|
5447
|
+
import path17 from "path";
|
|
2998
5448
|
|
|
2999
5449
|
// src/run-log-request-model.ts
|
|
3000
5450
|
var TOKENS = /["\\{}[\]:,]/g;
|
|
@@ -3141,7 +5591,7 @@ async function preserveRunUsage(paths, source) {
|
|
|
3141
5591
|
const records = /* @__PURE__ */ new Map();
|
|
3142
5592
|
const requestModels = /* @__PURE__ */ new Map();
|
|
3143
5593
|
try {
|
|
3144
|
-
const stat = await
|
|
5594
|
+
const stat = await fs16.lstat(destination);
|
|
3145
5595
|
if (!stat.isFile()) throw new Error("Invalid usage log");
|
|
3146
5596
|
for await (const record2 of readUsageRecords(destination))
|
|
3147
5597
|
if (record2.type === "llm.usage")
|
|
@@ -3182,15 +5632,15 @@ async function preserveRunUsage(paths, source) {
|
|
|
3182
5632
|
name: record2.model?.name ?? source.model?.name
|
|
3183
5633
|
})
|
|
3184
5634
|
);
|
|
3185
|
-
await
|
|
5635
|
+
await fs16.mkdir(path17.dirname(destination), { recursive: true });
|
|
3186
5636
|
const temporary = `${destination}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
|
3187
5637
|
try {
|
|
3188
5638
|
const lines = ordered.map((record2) => JSON.stringify(record2)).join("\n");
|
|
3189
|
-
await
|
|
5639
|
+
await fs16.writeFile(temporary, `${lines}
|
|
3190
5640
|
`, { mode: 384 });
|
|
3191
|
-
await
|
|
5641
|
+
await fs16.rename(temporary, destination);
|
|
3192
5642
|
} finally {
|
|
3193
|
-
await
|
|
5643
|
+
await fs16.rm(temporary, { force: true });
|
|
3194
5644
|
}
|
|
3195
5645
|
return ordered;
|
|
3196
5646
|
}
|
|
@@ -3205,7 +5655,7 @@ var eligible = (summary, newestMtime, now) => {
|
|
|
3205
5655
|
};
|
|
3206
5656
|
function commitCandidate(candidate, compressed, result) {
|
|
3207
5657
|
try {
|
|
3208
|
-
const stat =
|
|
5658
|
+
const stat = lstatSync6(candidate.file);
|
|
3209
5659
|
if (!stat.isFile() || stat.ino !== candidate.ino || stat.dev !== candidate.dev || stat.size !== candidate.size || stat.mtimeMs !== candidate.mtimeMs) {
|
|
3210
5660
|
result.skipped++;
|
|
3211
5661
|
return;
|
|
@@ -3243,7 +5693,7 @@ async function processCandidate(context, candidate, newestMtime, usage) {
|
|
|
3243
5693
|
} catch {
|
|
3244
5694
|
result.failed++;
|
|
3245
5695
|
} finally {
|
|
3246
|
-
if (compressed) await
|
|
5696
|
+
if (compressed) await fs17.rm(compressed.temporary, { force: true });
|
|
3247
5697
|
}
|
|
3248
5698
|
}
|
|
3249
5699
|
async function cleanupRunLogs(options) {
|
|
@@ -3258,7 +5708,7 @@ async function cleanupRunLogs(options) {
|
|
|
3258
5708
|
};
|
|
3259
5709
|
const context = { paths, sessions, now, result };
|
|
3260
5710
|
if (!await isRegularDirectory(paths.sessionsDir)) return result;
|
|
3261
|
-
const diagnosticsDir =
|
|
5711
|
+
const diagnosticsDir = path18.join(paths.sessionsDir, "diagnostics");
|
|
3262
5712
|
let relPaths;
|
|
3263
5713
|
if (options.sessionId) {
|
|
3264
5714
|
try {
|
|
@@ -3307,8 +5757,8 @@ async function cleanupRunLogs(options) {
|
|
|
3307
5757
|
result.skipped += group.length - selected.length;
|
|
3308
5758
|
if (selected.length === 0) continue;
|
|
3309
5759
|
try {
|
|
3310
|
-
const snapshot = await
|
|
3311
|
-
|
|
5760
|
+
const snapshot = await fs17.lstat(
|
|
5761
|
+
path18.join(paths.sessionsDir, "messages", `${sessionId}.jsonl`)
|
|
3312
5762
|
);
|
|
3313
5763
|
if (!snapshot.isFile() || snapshot.size === 0) {
|
|
3314
5764
|
result.skipped += selected.length;
|
|
@@ -3344,8 +5794,8 @@ var StoragePathServiceImpl = class {
|
|
|
3344
5794
|
};
|
|
3345
5795
|
|
|
3346
5796
|
// src/task-registry.ts
|
|
3347
|
-
import { promises as
|
|
3348
|
-
import
|
|
5797
|
+
import { promises as fs18 } from "fs";
|
|
5798
|
+
import path19 from "path";
|
|
3349
5799
|
var TASKS_DIRNAME = "tasks";
|
|
3350
5800
|
var sortByUpdatedDesc = (tasks) => [...tasks].sort((a, b) => b.updated_at.localeCompare(a.updated_at));
|
|
3351
5801
|
var toShellKeyBase = (label2) => {
|
|
@@ -3403,14 +5853,14 @@ var assignMissingShellKeys = (tasks) => {
|
|
|
3403
5853
|
return updates;
|
|
3404
5854
|
};
|
|
3405
5855
|
var atomicWrite = async (filePath, payload) => {
|
|
3406
|
-
const dir =
|
|
3407
|
-
const base =
|
|
3408
|
-
const tmp =
|
|
5856
|
+
const dir = path19.dirname(filePath);
|
|
5857
|
+
const base = path19.basename(filePath);
|
|
5858
|
+
const tmp = path19.join(
|
|
3409
5859
|
dir,
|
|
3410
5860
|
`${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
|
|
3411
5861
|
);
|
|
3412
|
-
await
|
|
3413
|
-
await
|
|
5862
|
+
await fs18.writeFile(tmp, payload, "utf8");
|
|
5863
|
+
await fs18.rename(tmp, filePath);
|
|
3414
5864
|
};
|
|
3415
5865
|
var isTaskState = (value) => value === "queued" || value === "running" || value === "completed" || value === "failed" || value === "cancelled";
|
|
3416
5866
|
var isTaskKind = (value) => value === "shell" || value === "subagent";
|
|
@@ -3521,7 +5971,7 @@ var normalizeTaskRecord = (value) => {
|
|
|
3521
5971
|
};
|
|
3522
5972
|
var readTaskFile = async (filePath) => {
|
|
3523
5973
|
try {
|
|
3524
|
-
const raw = await
|
|
5974
|
+
const raw = await fs18.readFile(filePath, "utf8");
|
|
3525
5975
|
return normalizeTaskRecord(JSON.parse(raw));
|
|
3526
5976
|
} catch {
|
|
3527
5977
|
return null;
|
|
@@ -3536,19 +5986,19 @@ var TaskRegistryStore = class {
|
|
|
3536
5986
|
return;
|
|
3537
5987
|
}
|
|
3538
5988
|
const root = resolveStoragePaths().root;
|
|
3539
|
-
this.tasksDir =
|
|
5989
|
+
this.tasksDir = path19.join(root, TASKS_DIRNAME);
|
|
3540
5990
|
}
|
|
3541
5991
|
async ensureDir() {
|
|
3542
|
-
await
|
|
5992
|
+
await fs18.mkdir(this.tasksDir, { recursive: true });
|
|
3543
5993
|
}
|
|
3544
5994
|
taskPath(taskId) {
|
|
3545
|
-
return
|
|
5995
|
+
return path19.join(this.tasksDir, taskFileName(taskId));
|
|
3546
5996
|
}
|
|
3547
5997
|
async list() {
|
|
3548
5998
|
await this.ensureDir();
|
|
3549
|
-
const entries2 = await
|
|
5999
|
+
const entries2 = await fs18.readdir(this.tasksDir, { withFileTypes: true });
|
|
3550
6000
|
const tasks = (await Promise.all(
|
|
3551
|
-
entries2.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(
|
|
6001
|
+
entries2.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(path19.join(this.tasksDir, entry.name)))
|
|
3552
6002
|
)).filter((task) => task !== null);
|
|
3553
6003
|
const keyBackfills = assignMissingShellKeys(tasks);
|
|
3554
6004
|
if (keyBackfills.length > 0) {
|
|
@@ -3590,8 +6040,8 @@ var TaskRegistryStore = class {
|
|
|
3590
6040
|
};
|
|
3591
6041
|
|
|
3592
6042
|
// src/tool-output-cache.ts
|
|
3593
|
-
import { promises as
|
|
3594
|
-
import
|
|
6043
|
+
import { promises as fs19 } from "fs";
|
|
6044
|
+
import path20 from "path";
|
|
3595
6045
|
var DEFAULT_MAX_MATCHES = 50;
|
|
3596
6046
|
var DEFAULT_MAX_LINE_LENGTH = 1e3;
|
|
3597
6047
|
var DEFAULT_MAX_READ_BYTES = 64 * 1024;
|
|
@@ -3703,15 +6153,15 @@ var ToolOutputCacheStoreImpl = class {
|
|
|
3703
6153
|
async save(record2) {
|
|
3704
6154
|
const refId = normalizeRefId(record2.tool_call_id);
|
|
3705
6155
|
const filePath = this.resolvePath(refId);
|
|
3706
|
-
await
|
|
3707
|
-
await
|
|
6156
|
+
await fs19.mkdir(this.baseDir, { recursive: true });
|
|
6157
|
+
await fs19.writeFile(filePath, record2.content, "utf8");
|
|
3708
6158
|
const byteSize = Buffer.byteLength(record2.content, "utf8");
|
|
3709
6159
|
const lineCount = record2.content.split(/\r?\n/).length;
|
|
3710
6160
|
return { id: refId, byte_size: byteSize, line_count: lineCount };
|
|
3711
6161
|
}
|
|
3712
6162
|
async read(refId, options = {}) {
|
|
3713
6163
|
const filePath = this.resolvePath(refId);
|
|
3714
|
-
const content = await
|
|
6164
|
+
const content = await fs19.readFile(filePath, "utf8");
|
|
3715
6165
|
const lines = content.split(/\r?\n/);
|
|
3716
6166
|
const offset = options.offset ?? 0;
|
|
3717
6167
|
const limit = options.limit ?? lines.length;
|
|
@@ -3770,7 +6220,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
|
|
|
3770
6220
|
}
|
|
3771
6221
|
async readTail(refId, options) {
|
|
3772
6222
|
const filePath = this.resolvePath(refId);
|
|
3773
|
-
const content = await
|
|
6223
|
+
const content = await fs19.readFile(filePath, "utf8");
|
|
3774
6224
|
const lines = content.split(/\r?\n/);
|
|
3775
6225
|
const tailLines = Math.max(1, Math.trunc(options.tail_lines));
|
|
3776
6226
|
const start = Math.max(0, lines.length - tailLines);
|
|
@@ -3782,7 +6232,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
|
|
|
3782
6232
|
}
|
|
3783
6233
|
async readLine(refId, options) {
|
|
3784
6234
|
const filePath = this.resolvePath(refId);
|
|
3785
|
-
const content = await
|
|
6235
|
+
const content = await fs19.readFile(filePath, "utf8");
|
|
3786
6236
|
const lines = content.split(/\r?\n/);
|
|
3787
6237
|
const lineIndex = options.line_number - 1;
|
|
3788
6238
|
if (lineIndex < 0 || lineIndex >= lines.length) {
|
|
@@ -3823,7 +6273,7 @@ tool_output_cache_line({"ref_id":"${normalizeRefId(refId)}","line_number":${opti
|
|
|
3823
6273
|
}
|
|
3824
6274
|
async grep(refId, options) {
|
|
3825
6275
|
const filePath = this.resolvePath(refId);
|
|
3826
|
-
const content = await
|
|
6276
|
+
const content = await fs19.readFile(filePath, "utf8");
|
|
3827
6277
|
const lines = content.split(/\r?\n/);
|
|
3828
6278
|
const regex = options.regex ? new RegExp(options.pattern) : new RegExp(options.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
3829
6279
|
const before = Math.max(0, options.before ?? 0);
|
|
@@ -3874,13 +6324,23 @@ ${snippet}`;
|
|
|
3874
6324
|
return output;
|
|
3875
6325
|
}
|
|
3876
6326
|
resolvePath(refId) {
|
|
3877
|
-
return
|
|
6327
|
+
return path20.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
|
|
3878
6328
|
}
|
|
3879
6329
|
};
|
|
3880
6330
|
export {
|
|
6331
|
+
AUTH_VERSION_V1,
|
|
6332
|
+
AUTH_VERSION_V2,
|
|
6333
|
+
CODELIA_AUTH_KEYCHAIN_SERVICE,
|
|
6334
|
+
CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
|
|
6335
|
+
CredentialConflictError,
|
|
6336
|
+
DEFAULT_AUTH_LOCK_TIMEOUT_MS,
|
|
6337
|
+
DEFAULT_OAUTH_REFRESH_TIMEOUT_MS,
|
|
3881
6338
|
FileAttachmentStore,
|
|
3882
6339
|
IMAGE_MAX_BYTES,
|
|
3883
6340
|
ImageArtifactStore,
|
|
6341
|
+
KeychainError,
|
|
6342
|
+
MCP_AUTH_VERSION,
|
|
6343
|
+
MacOsKeychainClient,
|
|
3884
6344
|
McpAuthStore,
|
|
3885
6345
|
ProjectsPolicyStore,
|
|
3886
6346
|
RUN_LOG_RETENTION_MS,
|
|
@@ -3891,17 +6351,57 @@ export {
|
|
|
3891
6351
|
StoragePathServiceImpl,
|
|
3892
6352
|
TaskRegistryStore,
|
|
3893
6353
|
ToolOutputCacheStoreImpl,
|
|
6354
|
+
authLockPathFor,
|
|
6355
|
+
buildMcpAuthBinding,
|
|
6356
|
+
canonicalJsonEqual,
|
|
6357
|
+
canonicalJsonStringify,
|
|
6358
|
+
canonicalPathOrResolvedSync,
|
|
6359
|
+
canonicalizeMcpUri,
|
|
3894
6360
|
cleanupRunLogs,
|
|
6361
|
+
clearStoreAcrossAllLocationsUnlocked,
|
|
6362
|
+
coordinateCredentialBackend,
|
|
6363
|
+
coordinateCredentialBackendUnlocked,
|
|
3895
6364
|
createAttachmentId,
|
|
6365
|
+
deriveMcpIssuer,
|
|
3896
6366
|
detectImageAttachmentType,
|
|
6367
|
+
enforceWindowsOwnerOnlyDacl,
|
|
6368
|
+
ensureCredentialsDirectory,
|
|
3897
6369
|
ensureStorageDirs,
|
|
3898
6370
|
getProcessIdentity,
|
|
6371
|
+
inspectCredentialStorageStatus,
|
|
3899
6372
|
isAttachmentId,
|
|
6373
|
+
isCanonicalHomeWorkspaceSync,
|
|
6374
|
+
isSameConfigFilePath,
|
|
6375
|
+
isTrustedGlobalConfigLocationSync,
|
|
6376
|
+
isWithinPath,
|
|
6377
|
+
keychainAccountForConfigDir,
|
|
6378
|
+
mcpAuthBindingMatches,
|
|
6379
|
+
mcpAuthStoreAdapter,
|
|
6380
|
+
openSqlite,
|
|
6381
|
+
parseAuthDocument,
|
|
6382
|
+
parseAuthStorageState,
|
|
6383
|
+
parseMcpAuthDocument,
|
|
6384
|
+
providerAuthStoreAdapter,
|
|
6385
|
+
readAuthStorageState,
|
|
6386
|
+
readAuthStorageStateSync,
|
|
3900
6387
|
readRunLogLines,
|
|
6388
|
+
resolveConfiguredAuthStorageMode,
|
|
6389
|
+
resolveCredentialConflict,
|
|
3901
6390
|
resolveIndexedRunLog,
|
|
3902
6391
|
resolveRunLogPath,
|
|
3903
6392
|
resolveStoragePaths,
|
|
6393
|
+
resolveWindowsSystem32Dir,
|
|
6394
|
+
runTwoPhaseMigration,
|
|
3904
6395
|
scanSessionRunLogs,
|
|
3905
6396
|
validateImageAttachment,
|
|
3906
|
-
validateImagePng
|
|
6397
|
+
validateImagePng,
|
|
6398
|
+
verifyOwnedAncestors,
|
|
6399
|
+
verifyOwnedAncestorsSync,
|
|
6400
|
+
verifyUserStorageLocation,
|
|
6401
|
+
verifyUserStorageLocationSync,
|
|
6402
|
+
verifyWindowsCredentialFileAcl,
|
|
6403
|
+
verifyWindowsCredentialFileAclSync,
|
|
6404
|
+
withAuthStoreLock,
|
|
6405
|
+
writeAuthStorageState,
|
|
6406
|
+
writeFileAtomic
|
|
3907
6407
|
};
|