@codelia/storage 0.1.86 → 0.1.90
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.cjs
CHANGED
|
@@ -30,9 +30,19 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
30
30
|
// src/index.ts
|
|
31
31
|
var index_exports = {};
|
|
32
32
|
__export(index_exports, {
|
|
33
|
+
AUTH_VERSION_V1: () => AUTH_VERSION_V1,
|
|
34
|
+
AUTH_VERSION_V2: () => AUTH_VERSION_V2,
|
|
35
|
+
CODELIA_AUTH_KEYCHAIN_SERVICE: () => CODELIA_AUTH_KEYCHAIN_SERVICE,
|
|
36
|
+
CODELIA_MCP_AUTH_KEYCHAIN_SERVICE: () => CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
|
|
37
|
+
CredentialConflictError: () => CredentialConflictError,
|
|
38
|
+
DEFAULT_AUTH_LOCK_TIMEOUT_MS: () => DEFAULT_AUTH_LOCK_TIMEOUT_MS,
|
|
39
|
+
DEFAULT_OAUTH_REFRESH_TIMEOUT_MS: () => DEFAULT_OAUTH_REFRESH_TIMEOUT_MS,
|
|
33
40
|
FileAttachmentStore: () => FileAttachmentStore,
|
|
34
41
|
IMAGE_MAX_BYTES: () => IMAGE_MAX_BYTES,
|
|
35
42
|
ImageArtifactStore: () => ImageArtifactStore,
|
|
43
|
+
KeychainError: () => KeychainError,
|
|
44
|
+
MCP_AUTH_VERSION: () => MCP_AUTH_VERSION,
|
|
45
|
+
MacOsKeychainClient: () => MacOsKeychainClient,
|
|
36
46
|
McpAuthStore: () => McpAuthStore,
|
|
37
47
|
ProjectsPolicyStore: () => ProjectsPolicyStore,
|
|
38
48
|
RUN_LOG_RETENTION_MS: () => RUN_LOG_RETENTION_MS,
|
|
@@ -43,37 +53,111 @@ __export(index_exports, {
|
|
|
43
53
|
StoragePathServiceImpl: () => StoragePathServiceImpl,
|
|
44
54
|
TaskRegistryStore: () => TaskRegistryStore,
|
|
45
55
|
ToolOutputCacheStoreImpl: () => ToolOutputCacheStoreImpl,
|
|
56
|
+
authLockPathFor: () => authLockPathFor,
|
|
57
|
+
buildMcpAuthBinding: () => buildMcpAuthBinding,
|
|
58
|
+
canonicalJsonEqual: () => canonicalJsonEqual,
|
|
59
|
+
canonicalJsonStringify: () => canonicalJsonStringify,
|
|
60
|
+
canonicalPathOrResolvedSync: () => canonicalPathOrResolvedSync,
|
|
61
|
+
canonicalizeMcpUri: () => canonicalizeMcpUri,
|
|
46
62
|
cleanupRunLogs: () => cleanupRunLogs,
|
|
63
|
+
clearStoreAcrossAllLocationsUnlocked: () => clearStoreAcrossAllLocationsUnlocked,
|
|
64
|
+
coordinateCredentialBackend: () => coordinateCredentialBackend,
|
|
65
|
+
coordinateCredentialBackendUnlocked: () => coordinateCredentialBackendUnlocked,
|
|
47
66
|
createAttachmentId: () => createAttachmentId,
|
|
67
|
+
deriveMcpIssuer: () => deriveMcpIssuer,
|
|
48
68
|
detectImageAttachmentType: () => detectImageAttachmentType,
|
|
69
|
+
enforceWindowsOwnerOnlyDacl: () => enforceWindowsOwnerOnlyDacl,
|
|
70
|
+
ensureCredentialsDirectory: () => ensureCredentialsDirectory,
|
|
49
71
|
ensureStorageDirs: () => ensureStorageDirs,
|
|
50
72
|
getProcessIdentity: () => getProcessIdentity,
|
|
73
|
+
inspectCredentialStorageStatus: () => inspectCredentialStorageStatus,
|
|
51
74
|
isAttachmentId: () => isAttachmentId,
|
|
75
|
+
isCanonicalHomeWorkspaceSync: () => isCanonicalHomeWorkspaceSync,
|
|
76
|
+
isSameConfigFilePath: () => isSameConfigFilePath,
|
|
77
|
+
isTrustedGlobalConfigLocationSync: () => isTrustedGlobalConfigLocationSync,
|
|
78
|
+
isWithinPath: () => isWithinPath,
|
|
79
|
+
keychainAccountForConfigDir: () => keychainAccountForConfigDir,
|
|
80
|
+
mcpAuthBindingMatches: () => mcpAuthBindingMatches,
|
|
81
|
+
mcpAuthStoreAdapter: () => mcpAuthStoreAdapter,
|
|
82
|
+
openSqlite: () => openSqlite,
|
|
83
|
+
parseAuthDocument: () => parseAuthDocument,
|
|
84
|
+
parseAuthStorageState: () => parseAuthStorageState,
|
|
85
|
+
parseMcpAuthDocument: () => parseMcpAuthDocument,
|
|
86
|
+
providerAuthStoreAdapter: () => providerAuthStoreAdapter,
|
|
87
|
+
readAuthStorageState: () => readAuthStorageState,
|
|
88
|
+
readAuthStorageStateSync: () => readAuthStorageStateSync,
|
|
52
89
|
readRunLogLines: () => readRunLogLines,
|
|
90
|
+
resolveConfiguredAuthStorageMode: () => resolveConfiguredAuthStorageMode,
|
|
91
|
+
resolveCredentialConflict: () => resolveCredentialConflict,
|
|
53
92
|
resolveIndexedRunLog: () => resolveIndexedRunLog,
|
|
54
93
|
resolveRunLogPath: () => resolveRunLogPath,
|
|
55
94
|
resolveStoragePaths: () => resolveStoragePaths,
|
|
95
|
+
resolveWindowsSystem32Dir: () => resolveWindowsSystem32Dir,
|
|
96
|
+
runTwoPhaseMigration: () => runTwoPhaseMigration,
|
|
56
97
|
scanSessionRunLogs: () => scanSessionRunLogs,
|
|
57
98
|
validateImageAttachment: () => validateImageAttachment,
|
|
58
|
-
validateImagePng: () => validateImagePng
|
|
99
|
+
validateImagePng: () => validateImagePng,
|
|
100
|
+
verifyOwnedAncestors: () => verifyOwnedAncestors,
|
|
101
|
+
verifyOwnedAncestorsSync: () => verifyOwnedAncestorsSync,
|
|
102
|
+
verifyUserStorageLocation: () => verifyUserStorageLocation,
|
|
103
|
+
verifyUserStorageLocationSync: () => verifyUserStorageLocationSync,
|
|
104
|
+
verifyWindowsCredentialFileAcl: () => verifyWindowsCredentialFileAcl,
|
|
105
|
+
verifyWindowsCredentialFileAclSync: () => verifyWindowsCredentialFileAclSync,
|
|
106
|
+
withAuthStoreLock: () => withAuthStoreLock,
|
|
107
|
+
writeAuthStorageState: () => writeAuthStorageState,
|
|
108
|
+
writeFileAtomic: () => writeFileAtomic
|
|
59
109
|
});
|
|
60
110
|
module.exports = __toCommonJS(index_exports);
|
|
61
111
|
|
|
112
|
+
// src/atomic-file.ts
|
|
113
|
+
var import_node_crypto = require("crypto");
|
|
114
|
+
var import_node_fs = require("fs");
|
|
115
|
+
var import_node_path = __toESM(require("path"), 1);
|
|
116
|
+
var writeFileAtomic = async (targetPath, data, options = {}) => {
|
|
117
|
+
const mode = options.mode ?? 384;
|
|
118
|
+
const dir = import_node_path.default.dirname(targetPath);
|
|
119
|
+
const base = import_node_path.default.basename(targetPath);
|
|
120
|
+
const temporary = import_node_path.default.join(dir, `.${base}.${(0, import_node_crypto.randomUUID)()}.tmp`);
|
|
121
|
+
let handle;
|
|
122
|
+
try {
|
|
123
|
+
handle = await import_node_fs.promises.open(temporary, "wx", mode);
|
|
124
|
+
await handle.writeFile(data, "utf8");
|
|
125
|
+
await handle.sync();
|
|
126
|
+
await handle.close();
|
|
127
|
+
handle = void 0;
|
|
128
|
+
try {
|
|
129
|
+
await import_node_fs.promises.chmod(temporary, mode);
|
|
130
|
+
} catch {
|
|
131
|
+
}
|
|
132
|
+
await import_node_fs.promises.rename(temporary, targetPath);
|
|
133
|
+
try {
|
|
134
|
+
await import_node_fs.promises.chmod(targetPath, mode);
|
|
135
|
+
} catch {
|
|
136
|
+
}
|
|
137
|
+
} catch (error) {
|
|
138
|
+
if (handle) {
|
|
139
|
+
await handle.close().catch(() => void 0);
|
|
140
|
+
}
|
|
141
|
+
await import_node_fs.promises.unlink(temporary).catch(() => void 0);
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
|
|
62
146
|
// src/attachments.ts
|
|
63
|
-
var
|
|
64
|
-
var
|
|
147
|
+
var import_node_crypto3 = require("crypto");
|
|
148
|
+
var import_node_fs3 = require("fs");
|
|
65
149
|
var import_promises2 = require("fs/promises");
|
|
66
|
-
var
|
|
150
|
+
var import_node_path2 = __toESM(require("path"), 1);
|
|
67
151
|
|
|
68
152
|
// src/image-files.ts
|
|
69
|
-
var
|
|
70
|
-
var
|
|
153
|
+
var import_node_crypto2 = require("crypto");
|
|
154
|
+
var import_node_fs2 = require("fs");
|
|
71
155
|
var import_promises = require("fs/promises");
|
|
72
|
-
var imageHash = (bytes) => (0,
|
|
156
|
+
var imageHash = (bytes) => (0, import_node_crypto2.createHash)("sha256").update(bytes).digest("hex");
|
|
73
157
|
async function readImageFileBounded(file, limit) {
|
|
74
158
|
const handle = await (0, import_promises.open)(
|
|
75
159
|
file,
|
|
76
|
-
|
|
160
|
+
import_node_fs2.constants.O_RDONLY | (import_node_fs2.constants.O_NOFOLLOW ?? 0) | (import_node_fs2.constants.O_NONBLOCK ?? 0)
|
|
77
161
|
);
|
|
78
162
|
try {
|
|
79
163
|
const stat = await handle.stat();
|
|
@@ -104,8 +188,8 @@ var UUID = /^[0-9a-f-]{36}$/;
|
|
|
104
188
|
var SHA256 = /^[0-9a-f]{64}$/;
|
|
105
189
|
var MAX_BYTES = 32 * 1024 * 1024;
|
|
106
190
|
var BLOCK_BYTES = 64 * 1024;
|
|
107
|
-
var digest = (bytes) => (0,
|
|
108
|
-
var createAttachmentId = () => `codelia-attachment-${(0,
|
|
191
|
+
var digest = (bytes) => (0, import_node_crypto3.createHash)("sha256").update(bytes).digest("hex");
|
|
192
|
+
var createAttachmentId = () => `codelia-attachment-${(0, import_node_crypto3.randomUUID)()}`;
|
|
109
193
|
var isAttachmentId = (id2) => ID.test(id2);
|
|
110
194
|
var FileAttachmentStore = class {
|
|
111
195
|
constructor(root, images) {
|
|
@@ -117,9 +201,9 @@ var FileAttachmentStore = class {
|
|
|
117
201
|
resolveImage = (ref) => this.images.resolve(ref);
|
|
118
202
|
async commit(sessionId, entries2) {
|
|
119
203
|
if (!entries2.length) return;
|
|
120
|
-
const batch = (0,
|
|
121
|
-
const marker =
|
|
122
|
-
await (0, import_promises2.mkdir)(
|
|
204
|
+
const batch = (0, import_node_crypto3.randomUUID)();
|
|
205
|
+
const marker = import_node_path2.default.join(this.root, "committed", batch);
|
|
206
|
+
await (0, import_promises2.mkdir)(import_node_path2.default.join(this.root, "committed"), {
|
|
123
207
|
recursive: true,
|
|
124
208
|
mode: 448
|
|
125
209
|
});
|
|
@@ -131,7 +215,7 @@ var FileAttachmentStore = class {
|
|
|
131
215
|
if (!isAttachmentId(ref.attachment_id) || bytes.length !== ref.byte_size || bytes.length > MAX_BYTES || digest(bytes) !== ref.sha256) {
|
|
132
216
|
throw new Error("Invalid attachment original");
|
|
133
217
|
}
|
|
134
|
-
const dir =
|
|
218
|
+
const dir = import_node_path2.default.join(this.root, ref.attachment_id);
|
|
135
219
|
await (0, import_promises2.mkdir)(dir, { mode: 448 });
|
|
136
220
|
created.push(dir);
|
|
137
221
|
const metadata = { ...record2, sessionId, batch };
|
|
@@ -148,146 +232,2263 @@ var FileAttachmentStore = class {
|
|
|
148
232
|
digest(bytes.subarray(offset, offset + BLOCK_BYTES))
|
|
149
233
|
);
|
|
150
234
|
}
|
|
151
|
-
await (0, import_promises2.writeFile)(
|
|
235
|
+
await (0, import_promises2.writeFile)(import_node_path2.default.join(dir, "original"), bytes, {
|
|
152
236
|
flag: "wx",
|
|
153
237
|
mode: 384
|
|
154
238
|
});
|
|
155
239
|
}
|
|
156
240
|
await (0, import_promises2.writeFile)(
|
|
157
|
-
|
|
241
|
+
import_node_path2.default.join(dir, "metadata.json"),
|
|
158
242
|
JSON.stringify(metadata),
|
|
159
243
|
{ flag: "wx", mode: 384 }
|
|
160
244
|
);
|
|
161
245
|
}
|
|
162
|
-
await (0, import_promises2.writeFile)(`${marker}.pending`, "", { flag: "wx", mode: 384 });
|
|
163
|
-
await (0, import_promises2.rename)(`${marker}.pending`, marker);
|
|
164
|
-
} catch (error) {
|
|
165
|
-
await Promise.allSettled([
|
|
166
|
-
...created.map((dir) => (0, import_promises2.rm)(dir, { force: true, recursive: true })),
|
|
167
|
-
...createdImages.map(
|
|
168
|
-
(ref) => this.images.discardUnpublishedAttachment(ref, sessionId)
|
|
246
|
+
await (0, import_promises2.writeFile)(`${marker}.pending`, "", { flag: "wx", mode: 384 });
|
|
247
|
+
await (0, import_promises2.rename)(`${marker}.pending`, marker);
|
|
248
|
+
} catch (error) {
|
|
249
|
+
await Promise.allSettled([
|
|
250
|
+
...created.map((dir) => (0, import_promises2.rm)(dir, { force: true, recursive: true })),
|
|
251
|
+
...createdImages.map(
|
|
252
|
+
(ref) => this.images.discardUnpublishedAttachment(ref, sessionId)
|
|
253
|
+
),
|
|
254
|
+
(0, import_promises2.rm)(`${marker}.pending`, { force: true })
|
|
255
|
+
]);
|
|
256
|
+
throw error;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
async lookup(attachmentId, sessionId) {
|
|
260
|
+
const metadata = await this.metadata(attachmentId, sessionId);
|
|
261
|
+
if (!metadata) return null;
|
|
262
|
+
const { ref, imageRef } = metadata;
|
|
263
|
+
if (imageRef) {
|
|
264
|
+
await this.readImage(metadata);
|
|
265
|
+
} else {
|
|
266
|
+
const bytes = await readImageFileBounded(
|
|
267
|
+
import_node_path2.default.join(this.root, attachmentId, "original"),
|
|
268
|
+
ref.byte_size
|
|
269
|
+
);
|
|
270
|
+
if (bytes.length !== ref.byte_size || digest(bytes) !== ref.sha256)
|
|
271
|
+
throw new Error("Attachment original is corrupt");
|
|
272
|
+
}
|
|
273
|
+
return { ref, ...imageRef ? { imageRef } : {} };
|
|
274
|
+
}
|
|
275
|
+
async read(attachmentId, sessionId, offset, length) {
|
|
276
|
+
const metadata = await this.metadata(attachmentId, sessionId);
|
|
277
|
+
if (!metadata) throw new Error("Attachment unavailable in this session");
|
|
278
|
+
if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || length > 256 * 1024)
|
|
279
|
+
throw new Error("Invalid attachment byte range");
|
|
280
|
+
const end = Math.min(offset + length, metadata.ref.byte_size);
|
|
281
|
+
if (metadata.imageRef)
|
|
282
|
+
return (await this.readImage(metadata)).subarray(offset, end);
|
|
283
|
+
const file = await (0, import_promises2.open)(
|
|
284
|
+
import_node_path2.default.join(this.root, attachmentId, "original"),
|
|
285
|
+
import_node_fs3.constants.O_RDONLY | (import_node_fs3.constants.O_NOFOLLOW ?? 0) | (import_node_fs3.constants.O_NONBLOCK ?? 0)
|
|
286
|
+
);
|
|
287
|
+
try {
|
|
288
|
+
const stat = await file.stat();
|
|
289
|
+
if (!stat.isFile() || stat.size !== metadata.ref.byte_size)
|
|
290
|
+
throw new Error("Attachment original is corrupt");
|
|
291
|
+
if (offset >= end) return Buffer.alloc(0);
|
|
292
|
+
const firstBlock = Math.floor(offset / BLOCK_BYTES);
|
|
293
|
+
const lastBlock = Math.ceil(end / BLOCK_BYTES);
|
|
294
|
+
const start = firstBlock * BLOCK_BYTES;
|
|
295
|
+
const bytes = Buffer.alloc(
|
|
296
|
+
Math.min(lastBlock * BLOCK_BYTES, stat.size) - start
|
|
297
|
+
);
|
|
298
|
+
let count = 0;
|
|
299
|
+
while (count < bytes.length) {
|
|
300
|
+
const result = await file.read(
|
|
301
|
+
bytes,
|
|
302
|
+
count,
|
|
303
|
+
bytes.length - count,
|
|
304
|
+
start + count
|
|
305
|
+
);
|
|
306
|
+
if (!result.bytesRead)
|
|
307
|
+
throw new Error("Attachment original is corrupt");
|
|
308
|
+
count += result.bytesRead;
|
|
309
|
+
}
|
|
310
|
+
for (let block = firstBlock; block < lastBlock; block++) {
|
|
311
|
+
const beg = (block - firstBlock) * BLOCK_BYTES;
|
|
312
|
+
if (metadata.blocks?.[block] !== digest(bytes.subarray(beg, beg + BLOCK_BYTES))) {
|
|
313
|
+
throw new Error("Attachment original is corrupt");
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return bytes.subarray(offset - start, end - start);
|
|
317
|
+
} finally {
|
|
318
|
+
await file.close();
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
async metadata(attachmentId, sessionId) {
|
|
322
|
+
if (!isAttachmentId(attachmentId)) return null;
|
|
323
|
+
const dir = import_node_path2.default.join(this.root, attachmentId);
|
|
324
|
+
try {
|
|
325
|
+
if (!(await (0, import_promises2.lstat)(dir)).isDirectory()) return null;
|
|
326
|
+
const metadata = JSON.parse(
|
|
327
|
+
(await readImageFileBounded(import_node_path2.default.join(dir, "metadata.json"), 64 * 1024)).toString()
|
|
328
|
+
);
|
|
329
|
+
const { ref, imageRef, blocks } = metadata;
|
|
330
|
+
if (metadata.sessionId !== sessionId || !UUID.test(metadata.batch) || ref?.attachment_id !== attachmentId)
|
|
331
|
+
return null;
|
|
332
|
+
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")
|
|
333
|
+
throw new Error("Invalid attachment metadata");
|
|
334
|
+
if (!imageRef && (!Array.isArray(blocks) || blocks.length !== Math.ceil(ref.byte_size / BLOCK_BYTES)))
|
|
335
|
+
throw new Error("Invalid attachment block index");
|
|
336
|
+
const marker = import_node_path2.default.join(this.root, "committed", metadata.batch);
|
|
337
|
+
return (await (0, import_promises2.lstat)(marker)).isFile() ? metadata : null;
|
|
338
|
+
} catch (error) {
|
|
339
|
+
if (error.code === "ENOENT") return null;
|
|
340
|
+
throw error;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
async readImage({
|
|
344
|
+
ref,
|
|
345
|
+
imageRef,
|
|
346
|
+
sessionId
|
|
347
|
+
}) {
|
|
348
|
+
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)
|
|
349
|
+
throw new Error("Invalid image attachment reference");
|
|
350
|
+
const { metadata, bytes } = await this.images.read(
|
|
351
|
+
imageRef.artifact_id,
|
|
352
|
+
sessionId
|
|
353
|
+
);
|
|
354
|
+
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)
|
|
355
|
+
throw new Error("Image attachment original is corrupt");
|
|
356
|
+
return bytes;
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
// src/auth-lock.ts
|
|
361
|
+
var import_node_crypto4 = require("crypto");
|
|
362
|
+
var import_node_fs5 = require("fs");
|
|
363
|
+
var import_node_path4 = __toESM(require("path"), 1);
|
|
364
|
+
var import_promises3 = require("timers/promises");
|
|
365
|
+
|
|
366
|
+
// src/sqlite.ts
|
|
367
|
+
var openSqlite = async (filename) => {
|
|
368
|
+
if (process.versions.bun) {
|
|
369
|
+
const bunSqliteSpecifier = "bun:sqlite";
|
|
370
|
+
const { Database } = await import(bunSqliteSpecifier);
|
|
371
|
+
const db2 = new Database(filename, { create: true });
|
|
372
|
+
return {
|
|
373
|
+
close: () => db2.close(),
|
|
374
|
+
exec: (sql) => {
|
|
375
|
+
db2.exec(sql);
|
|
376
|
+
},
|
|
377
|
+
run: (sql, params = []) => {
|
|
378
|
+
db2.query(sql).run(...params);
|
|
379
|
+
},
|
|
380
|
+
get: (sql, params = []) => {
|
|
381
|
+
const row = db2.query(sql).get(...params);
|
|
382
|
+
return row ?? void 0;
|
|
383
|
+
},
|
|
384
|
+
all: (sql, params = []) => db2.query(sql).all(...params)
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
const betterSqliteSpecifier = "better-sqlite3";
|
|
388
|
+
const betterSqliteModule = await import(betterSqliteSpecifier);
|
|
389
|
+
const BetterSqlite3 = betterSqliteModule.default ?? betterSqliteModule;
|
|
390
|
+
const db = new BetterSqlite3(filename);
|
|
391
|
+
return {
|
|
392
|
+
close: () => db.close(),
|
|
393
|
+
exec: (sql) => {
|
|
394
|
+
db.exec(sql);
|
|
395
|
+
},
|
|
396
|
+
run: (sql, params = []) => {
|
|
397
|
+
db.prepare(sql).run(...params);
|
|
398
|
+
},
|
|
399
|
+
get: (sql, params = []) => {
|
|
400
|
+
const row = db.prepare(sql).get(...params);
|
|
401
|
+
return row ?? void 0;
|
|
402
|
+
},
|
|
403
|
+
all: (sql, params = []) => db.prepare(sql).all(...params)
|
|
404
|
+
};
|
|
405
|
+
};
|
|
406
|
+
|
|
407
|
+
// src/windows-acl.ts
|
|
408
|
+
var import_node_child_process = require("child_process");
|
|
409
|
+
var import_node_fs4 = require("fs");
|
|
410
|
+
var import_node_path3 = __toESM(require("path"), 1);
|
|
411
|
+
var import_node_util = require("util");
|
|
412
|
+
var execFileAsync = (0, import_node_util.promisify)(import_node_child_process.execFile);
|
|
413
|
+
var resolveWindowsSystem32Dir = (env = process.env) => {
|
|
414
|
+
const root = (env.SystemRoot ?? env.WINDIR ?? "").trim() || "C:\\Windows";
|
|
415
|
+
if (!/^[A-Za-z]:\\/u.test(root) || root.includes("..")) {
|
|
416
|
+
throw new Error("unsafe_windows_credentials_acl: invalid_system_root");
|
|
417
|
+
}
|
|
418
|
+
return import_node_path3.default.win32.join(root, "System32");
|
|
419
|
+
};
|
|
420
|
+
var execOptions = {
|
|
421
|
+
windowsHide: true,
|
|
422
|
+
timeout: 5e3,
|
|
423
|
+
maxBuffer: 32 * 1024
|
|
424
|
+
};
|
|
425
|
+
var defaultRunner = async (exe, args, options) => execFileAsync(exe, [...args], { ...options, ...execOptions });
|
|
426
|
+
var aclScript = `
|
|
427
|
+
$ErrorActionPreference = 'Stop'
|
|
428
|
+
$target = $env:CODELIA_ACL_TARGET
|
|
429
|
+
$operation = $env:CODELIA_ACL_OPERATION
|
|
430
|
+
$legacy = $operation -eq 'legacy_file'
|
|
431
|
+
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
|
|
432
|
+
$system = [System.Security.Principal.SecurityIdentifier]::new('S-1-5-18')
|
|
433
|
+
$administrators = 'S-1-5-32-544'
|
|
434
|
+
$sections = [System.Security.AccessControl.AccessControlSections]'Owner, Access'
|
|
435
|
+
$inherit = [System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'
|
|
436
|
+
$inheritAces = [System.Security.AccessControl.AceFlags]'ContainerInherit, ObjectInherit'
|
|
437
|
+
$full = [System.Security.AccessControl.FileSystemRights]::FullControl
|
|
438
|
+
# Include generic read and execute if Windows left the generic bits unmapped.
|
|
439
|
+
$legacyReadMask = (
|
|
440
|
+
[int][System.Security.AccessControl.FileSystemRights]::ReadAndExecute -bor
|
|
441
|
+
[int][System.Security.AccessControl.FileSystemRights]::Synchronize -bor
|
|
442
|
+
[int]::MinValue -bor 0x20000000
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
function Get-TargetType([string]$file, [bool]$directory) {
|
|
446
|
+
try {
|
|
447
|
+
$attributes = [System.IO.File]::GetAttributes($file)
|
|
448
|
+
} catch [System.IO.FileNotFoundException], [System.IO.DirectoryNotFoundException] {
|
|
449
|
+
return 'missing'
|
|
450
|
+
}
|
|
451
|
+
if ($attributes -band [System.IO.FileAttributes]::ReparsePoint) { return 'reparse_point' }
|
|
452
|
+
if ([bool]($attributes -band [System.IO.FileAttributes]::Directory) -ne $directory) {
|
|
453
|
+
return 'unexpected_target_type'
|
|
454
|
+
}
|
|
455
|
+
return 'ok'
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function Test-CredentialAcl($acl, [bool]$directory) {
|
|
459
|
+
$descriptor = [System.Security.AccessControl.RawSecurityDescriptor]::new(
|
|
460
|
+
$acl.GetSecurityDescriptorBinaryForm(), 0)
|
|
461
|
+
if ($descriptor.Owner.Value -ne $user.Value) { return 'owner_mismatch' }
|
|
462
|
+
if ($null -eq $descriptor.DiscretionaryAcl) { return 'null_dacl' }
|
|
463
|
+
if ($directory -and -not $acl.AreAccessRulesProtected) { return 'unprotected_dacl' }
|
|
464
|
+
$hasUser = $false
|
|
465
|
+
foreach ($ace in $descriptor.DiscretionaryAcl) {
|
|
466
|
+
if ($legacy -and ($ace.AceType -eq [System.Security.AccessControl.AceType]::AccessDenied -or
|
|
467
|
+
$ace.AceFlags.HasFlag([System.Security.AccessControl.AceFlags]::InheritOnly))) { continue }
|
|
468
|
+
if ($ace.AceType -ne [System.Security.AccessControl.AceType]::AccessAllowed) {
|
|
469
|
+
return 'unexpected_ace_type'
|
|
470
|
+
}
|
|
471
|
+
$sid = $ace.SecurityIdentifier.Value
|
|
472
|
+
if ($legacy) {
|
|
473
|
+
# The old config root may have inherited Administrators and read grants.
|
|
474
|
+
if ($sid -ne $user.Value -and $sid -ne $system.Value -and $sid -ne $administrators -and
|
|
475
|
+
($ace.AccessMask -band (-bnot $legacyReadMask))) { return 'legacy_write_grant' }
|
|
476
|
+
continue
|
|
477
|
+
}
|
|
478
|
+
if ($sid -ne $user.Value -and $sid -ne $system.Value) { return 'unexpected_principals' }
|
|
479
|
+
if ($directory -and ($ace.AccessMask -ne [int]$full -or $ace.AceFlags -ne $inheritAces)) {
|
|
480
|
+
return 'unexpected_directory_ace'
|
|
481
|
+
}
|
|
482
|
+
if ($sid -eq $user.Value) { $hasUser = $true }
|
|
483
|
+
}
|
|
484
|
+
if (-not $legacy -and -not $hasUser) { return 'missing_user_grant' }
|
|
485
|
+
return 'ok'
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
if ($operation -eq 'ensure_directory') {
|
|
489
|
+
$targetType = Get-TargetType $target $true
|
|
490
|
+
if ($targetType -ne 'ok') { $targetType; exit }
|
|
491
|
+
$acl = [System.IO.Directory]::GetAccessControl($target, $sections)
|
|
492
|
+
$result = Test-CredentialAcl $acl $true
|
|
493
|
+
if ($result -eq 'ok' -or $result -eq 'owner_mismatch') { $result; exit }
|
|
494
|
+
|
|
495
|
+
$privateAcl = [System.Security.AccessControl.DirectorySecurity]::new()
|
|
496
|
+
$privateAcl.SetAccessRuleProtection($true, $false)
|
|
497
|
+
$propagate = [System.Security.AccessControl.PropagationFlags]::None
|
|
498
|
+
$allow = [System.Security.AccessControl.AccessControlType]::Allow
|
|
499
|
+
$privateAcl.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new(
|
|
500
|
+
$user, $full, $inherit, $propagate, $allow))
|
|
501
|
+
if ($user.Value -ne $system.Value) {
|
|
502
|
+
$privateAcl.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new(
|
|
503
|
+
$system, $full, $inherit, $propagate, $allow))
|
|
504
|
+
}
|
|
505
|
+
[System.IO.Directory]::SetAccessControl($target, $privateAcl)
|
|
506
|
+
$targetType = Get-TargetType $target $true
|
|
507
|
+
if ($targetType -ne 'ok') { $targetType; exit }
|
|
508
|
+
Test-CredentialAcl ([System.IO.Directory]::GetAccessControl($target, $sections)) $true
|
|
509
|
+
exit
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
if ($operation -eq 'file') {
|
|
513
|
+
$parent = [System.IO.Path]::GetDirectoryName($target)
|
|
514
|
+
$parentType = Get-TargetType $parent $true
|
|
515
|
+
if ($parentType -ne 'ok') { $parentType; exit }
|
|
516
|
+
$parentAcl = Test-CredentialAcl ([System.IO.Directory]::GetAccessControl($parent, $sections)) $true
|
|
517
|
+
if ($parentAcl -ne 'ok') { $parentAcl; exit }
|
|
518
|
+
}
|
|
519
|
+
try {
|
|
520
|
+
$targetType = Get-TargetType $target $false
|
|
521
|
+
if ($targetType -ne 'ok') { $targetType; exit }
|
|
522
|
+
Test-CredentialAcl ([System.IO.File]::GetAccessControl($target, $sections)) $false
|
|
523
|
+
} catch [System.IO.FileNotFoundException], [System.IO.DirectoryNotFoundException] {
|
|
524
|
+
'missing'
|
|
525
|
+
}
|
|
526
|
+
`;
|
|
527
|
+
var encodedAclScript = Buffer.from(aclScript, "utf16le").toString("base64");
|
|
528
|
+
function aclCommand(target, operation, env) {
|
|
529
|
+
const system32 = resolveWindowsSystem32Dir(env);
|
|
530
|
+
return {
|
|
531
|
+
exe: import_node_path3.default.win32.join(
|
|
532
|
+
system32,
|
|
533
|
+
"WindowsPowerShell",
|
|
534
|
+
"v1.0",
|
|
535
|
+
"powershell.exe"
|
|
536
|
+
),
|
|
537
|
+
args: [
|
|
538
|
+
"-NoProfile",
|
|
539
|
+
"-NonInteractive",
|
|
540
|
+
"-EncodedCommand",
|
|
541
|
+
encodedAclScript
|
|
542
|
+
],
|
|
543
|
+
options: {
|
|
544
|
+
cwd: system32,
|
|
545
|
+
env: {
|
|
546
|
+
...env,
|
|
547
|
+
CODELIA_ACL_TARGET: import_node_path3.default.win32.resolve(target),
|
|
548
|
+
CODELIA_ACL_OPERATION: operation
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
var aclFailures = /* @__PURE__ */ new Set([
|
|
554
|
+
"missing",
|
|
555
|
+
"owner_mismatch",
|
|
556
|
+
"reparse_point",
|
|
557
|
+
"unexpected_target_type",
|
|
558
|
+
"null_dacl",
|
|
559
|
+
"unprotected_dacl",
|
|
560
|
+
"unexpected_ace_type",
|
|
561
|
+
"unexpected_principals",
|
|
562
|
+
"legacy_write_grant",
|
|
563
|
+
"unexpected_directory_ace",
|
|
564
|
+
"missing_user_grant"
|
|
565
|
+
]);
|
|
566
|
+
function verifyAclResult(stdout, operation) {
|
|
567
|
+
const result = stdout.trim();
|
|
568
|
+
if (result === "ok") return true;
|
|
569
|
+
if (operation !== "ensure_directory" && result === "missing") return false;
|
|
570
|
+
const reason = aclFailures.has(result) ? result : "invalid_probe_result";
|
|
571
|
+
throw new Error(`unsafe_windows_credentials_acl: ${reason}`);
|
|
572
|
+
}
|
|
573
|
+
async function runAclCommand(target, operation, runner, env) {
|
|
574
|
+
const { exe, args, options } = aclCommand(target, operation, env);
|
|
575
|
+
let stdout;
|
|
576
|
+
try {
|
|
577
|
+
({ stdout } = await runner(exe, args, options));
|
|
578
|
+
} catch {
|
|
579
|
+
throw new Error("unsafe_windows_credentials_acl: acl_probe_failed");
|
|
580
|
+
}
|
|
581
|
+
return verifyAclResult(stdout, operation);
|
|
582
|
+
}
|
|
583
|
+
var enforceWindowsOwnerOnlyDacl = async (dirPath, runner = defaultRunner, env = process.env) => {
|
|
584
|
+
await runAclCommand(dirPath, "ensure_directory", runner, env);
|
|
585
|
+
};
|
|
586
|
+
var isMissing = (error) => error?.code === "ENOENT";
|
|
587
|
+
var verifyWindowsCredentialFileAcl = async (filePath, legacy = false) => {
|
|
588
|
+
if (process.platform !== "win32") return true;
|
|
589
|
+
try {
|
|
590
|
+
await import_node_fs4.promises.lstat(filePath);
|
|
591
|
+
} catch (error) {
|
|
592
|
+
if (isMissing(error)) return false;
|
|
593
|
+
throw error;
|
|
594
|
+
}
|
|
595
|
+
return runAclCommand(
|
|
596
|
+
filePath,
|
|
597
|
+
legacy ? "legacy_file" : "file",
|
|
598
|
+
defaultRunner,
|
|
599
|
+
process.env
|
|
600
|
+
);
|
|
601
|
+
};
|
|
602
|
+
var verifyWindowsCredentialFileAclSync = (filePath, legacy = false) => {
|
|
603
|
+
if (process.platform !== "win32") return true;
|
|
604
|
+
try {
|
|
605
|
+
(0, import_node_fs4.lstatSync)(filePath);
|
|
606
|
+
} catch (error) {
|
|
607
|
+
if (isMissing(error)) return false;
|
|
608
|
+
throw error;
|
|
609
|
+
}
|
|
610
|
+
const operation = legacy ? "legacy_file" : "file";
|
|
611
|
+
const { exe, args, options } = aclCommand(filePath, operation, process.env);
|
|
612
|
+
let stdout;
|
|
613
|
+
try {
|
|
614
|
+
stdout = (0, import_node_child_process.execFileSync)(exe, args, {
|
|
615
|
+
...options,
|
|
616
|
+
...execOptions,
|
|
617
|
+
encoding: "utf8",
|
|
618
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
619
|
+
});
|
|
620
|
+
} catch {
|
|
621
|
+
throw new Error("unsafe_windows_credentials_acl: acl_probe_failed");
|
|
622
|
+
}
|
|
623
|
+
return verifyAclResult(stdout, operation);
|
|
624
|
+
};
|
|
625
|
+
var ensureCredentialsDirectory = async (credentialsDir, options) => {
|
|
626
|
+
const platform = options?.platform ?? process.platform;
|
|
627
|
+
await import_node_fs4.promises.mkdir(credentialsDir, { recursive: true, mode: 448 });
|
|
628
|
+
if (platform === "win32") {
|
|
629
|
+
await enforceWindowsOwnerOnlyDacl(credentialsDir, options?.windowsRunner);
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
const info = await import_node_fs4.promises.lstat(credentialsDir);
|
|
633
|
+
if (!info.isDirectory() || info.uid !== process.geteuid?.()) {
|
|
634
|
+
throw new Error("unsafe_credentials_directory");
|
|
635
|
+
}
|
|
636
|
+
if ((info.mode & 511) !== 448) await import_node_fs4.promises.chmod(credentialsDir, 448);
|
|
637
|
+
};
|
|
638
|
+
|
|
639
|
+
// src/auth-lock.ts
|
|
640
|
+
var DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 3e4;
|
|
641
|
+
var DEFAULT_AUTH_LOCK_TIMEOUT_MS = 35e3;
|
|
642
|
+
var DEFAULT_POLL_MS = 25;
|
|
643
|
+
var inProcessQueues = /* @__PURE__ */ new Map();
|
|
644
|
+
var authLockPathFor = (dir) => import_node_path4.default.join(dir, ".auth-store-lock.sqlite");
|
|
645
|
+
var isMissing2 = (error) => error?.code === "ENOENT";
|
|
646
|
+
var lstatIfPresent = (file) => import_node_fs5.promises.lstat(file).catch((error) => {
|
|
647
|
+
if (!isMissing2(error)) throw error;
|
|
648
|
+
return void 0;
|
|
649
|
+
});
|
|
650
|
+
var verifyLockFile = async (file) => {
|
|
651
|
+
const info = await lstatIfPresent(file);
|
|
652
|
+
if (!info) return;
|
|
653
|
+
const uid = process.geteuid?.();
|
|
654
|
+
if (!info.isFile() || info.size === 0 || uid !== void 0 && (info.uid !== uid || (info.mode & 18) !== 0)) {
|
|
655
|
+
throw new Error("unsafe_auth_store_lock");
|
|
656
|
+
}
|
|
657
|
+
};
|
|
658
|
+
var initializeLockFile = async (lockPath) => {
|
|
659
|
+
if (await lstatIfPresent(lockPath)) return;
|
|
660
|
+
const temporary = `${lockPath}.${(0, import_node_crypto4.randomUUID)()}.tmp`;
|
|
661
|
+
try {
|
|
662
|
+
const file = await import_node_fs5.promises.open(temporary, "wx", 384);
|
|
663
|
+
await file.close();
|
|
664
|
+
const db = await openSqlite(temporary);
|
|
665
|
+
try {
|
|
666
|
+
db.exec("PRAGMA user_version = 1");
|
|
667
|
+
} finally {
|
|
668
|
+
db.close();
|
|
669
|
+
}
|
|
670
|
+
try {
|
|
671
|
+
await import_node_fs5.promises.link(temporary, lockPath);
|
|
672
|
+
} catch (error) {
|
|
673
|
+
if (error.code !== "EEXIST") throw error;
|
|
674
|
+
}
|
|
675
|
+
} finally {
|
|
676
|
+
await import_node_fs5.promises.unlink(temporary).catch(() => void 0);
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
var isSqliteBusy = (error) => {
|
|
680
|
+
const code = error?.code;
|
|
681
|
+
if (code === "SQLITE_BUSY" || code === "SQLITE_LOCKED") return true;
|
|
682
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
683
|
+
return /database is locked|SQLITE_BUSY/i.test(message);
|
|
684
|
+
};
|
|
685
|
+
var openAuthLock = async (lockPath, timeoutMs, pollMs) => {
|
|
686
|
+
await ensureCredentialsDirectory(import_node_path4.default.dirname(lockPath));
|
|
687
|
+
await initializeLockFile(lockPath);
|
|
688
|
+
await verifyLockFile(lockPath);
|
|
689
|
+
if (process.platform === "win32") {
|
|
690
|
+
if (!await verifyWindowsCredentialFileAcl(lockPath)) {
|
|
691
|
+
throw new Error("unsafe_auth_store_lock");
|
|
692
|
+
}
|
|
693
|
+
await Promise.all(
|
|
694
|
+
["-journal", "-wal", "-shm"].map(
|
|
695
|
+
(suffix) => verifyWindowsCredentialFileAcl(lockPath + suffix)
|
|
696
|
+
)
|
|
697
|
+
);
|
|
698
|
+
}
|
|
699
|
+
const db = await openSqlite(lockPath);
|
|
700
|
+
const deadline = performance.now() + timeoutMs;
|
|
701
|
+
try {
|
|
702
|
+
db.exec("PRAGMA busy_timeout = 0");
|
|
703
|
+
for (; ; ) {
|
|
704
|
+
try {
|
|
705
|
+
db.exec("BEGIN IMMEDIATE");
|
|
706
|
+
return db;
|
|
707
|
+
} catch (error) {
|
|
708
|
+
if (!isSqliteBusy(error) || performance.now() >= deadline) {
|
|
709
|
+
throw error;
|
|
710
|
+
}
|
|
711
|
+
await (0, import_promises3.setTimeout)(pollMs);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
} catch (error) {
|
|
715
|
+
db.close();
|
|
716
|
+
throw error;
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
var enqueueInProcess = async (key, fn) => {
|
|
720
|
+
const previous = inProcessQueues.get(key) ?? Promise.resolve();
|
|
721
|
+
const next = previous.then(fn, fn);
|
|
722
|
+
const settled = next.then(
|
|
723
|
+
() => void 0,
|
|
724
|
+
() => void 0
|
|
725
|
+
);
|
|
726
|
+
inProcessQueues.set(key, settled);
|
|
727
|
+
try {
|
|
728
|
+
return await next;
|
|
729
|
+
} finally {
|
|
730
|
+
if (inProcessQueues.get(key) === settled) inProcessQueues.delete(key);
|
|
731
|
+
}
|
|
732
|
+
};
|
|
733
|
+
var withAuthStoreLock = (lockPath, fn, options = {}) => {
|
|
734
|
+
const resolved = import_node_path4.default.resolve(lockPath);
|
|
735
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_AUTH_LOCK_TIMEOUT_MS;
|
|
736
|
+
const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
|
|
737
|
+
return enqueueInProcess(resolved, async () => {
|
|
738
|
+
const db = await openAuthLock(resolved, timeoutMs, pollMs);
|
|
739
|
+
try {
|
|
740
|
+
return await fn();
|
|
741
|
+
} finally {
|
|
742
|
+
try {
|
|
743
|
+
db.exec("ROLLBACK");
|
|
744
|
+
} catch {
|
|
745
|
+
}
|
|
746
|
+
db.close();
|
|
747
|
+
}
|
|
748
|
+
});
|
|
749
|
+
};
|
|
750
|
+
|
|
751
|
+
// src/macos-keychain.ts
|
|
752
|
+
var import_node_child_process2 = require("child_process");
|
|
753
|
+
var import_node_crypto5 = require("crypto");
|
|
754
|
+
var import_node_fs6 = require("fs");
|
|
755
|
+
var import_node_os = __toESM(require("os"), 1);
|
|
756
|
+
var import_node_path5 = __toESM(require("path"), 1);
|
|
757
|
+
var CODELIA_AUTH_KEYCHAIN_SERVICE = "codelia.auth";
|
|
758
|
+
var CODELIA_MCP_AUTH_KEYCHAIN_SERVICE = "codelia.mcp-auth";
|
|
759
|
+
var DEFAULT_SECURITY_PATH = "/usr/bin/security";
|
|
760
|
+
var DEFAULT_ASYNC_TIMEOUT_MS = 5e3;
|
|
761
|
+
var DEFAULT_SYNC_TIMEOUT_MS = 2e3;
|
|
762
|
+
var AUTHORIZATION_TIMEOUT_MS = 12e4;
|
|
763
|
+
var MAX_SECURITY_BUFFER = 8 * 1024 * 1024;
|
|
764
|
+
var SECURITY_INTERACTIVE_MAX_LINE_BYTES = 4096;
|
|
765
|
+
var MAX_STDERR_CAPTURE_BYTES = 16384;
|
|
766
|
+
var MAX_CHUNKS = 64;
|
|
767
|
+
var SWEEP_CONSECUTIVE_MISS_LIMIT = 2;
|
|
768
|
+
var MAX_SNAPSHOT_ATTEMPTS = 3;
|
|
769
|
+
var CHUNK_RAW_BYTES = 1800;
|
|
770
|
+
var MAX_KEYCHAIN_PAYLOAD_BYTES = MAX_CHUNKS * CHUNK_RAW_BYTES;
|
|
771
|
+
var CHUNK_PREFIX = "cb1:";
|
|
772
|
+
var GEN_POINTER_PREFIX = "cb2:";
|
|
773
|
+
var SAFE_TOKEN_RE = /^[A-Za-z0-9._:#-]+$/;
|
|
774
|
+
var KeychainError = class extends Error {
|
|
775
|
+
code;
|
|
776
|
+
constructor(code, message) {
|
|
777
|
+
super(message);
|
|
778
|
+
this.name = "KeychainError";
|
|
779
|
+
this.code = code;
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
var canonicalDirForHash = (configDir) => {
|
|
783
|
+
const resolved = import_node_path5.default.resolve(configDir);
|
|
784
|
+
try {
|
|
785
|
+
return (0, import_node_fs6.realpathSync)(resolved);
|
|
786
|
+
} catch {
|
|
787
|
+
return resolved;
|
|
788
|
+
}
|
|
789
|
+
};
|
|
790
|
+
var keychainAccountForConfigDir = (configDir) => {
|
|
791
|
+
const digest2 = (0, import_node_crypto5.createHash)("sha256").update(canonicalDirForHash(configDir)).digest("hex").slice(0, 16);
|
|
792
|
+
return `codelia-${digest2}`;
|
|
793
|
+
};
|
|
794
|
+
var validateKeychainToken = (label2, value) => {
|
|
795
|
+
if (!value || !SAFE_TOKEN_RE.test(value)) {
|
|
796
|
+
throw new KeychainError(
|
|
797
|
+
"keychain_error",
|
|
798
|
+
`Invalid Keychain ${label2} identifier`
|
|
799
|
+
);
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
var chunkServiceName = (service, index) => index === 0 ? service : `${service}#${index}`;
|
|
803
|
+
var genChunkServiceName = (service, gen, index) => `${service}#g:${gen}:${index}`;
|
|
804
|
+
var encodePayloadChunks = (value) => {
|
|
805
|
+
const raw = Buffer.from(value, "utf8");
|
|
806
|
+
const total = Math.max(1, Math.ceil(raw.length / CHUNK_RAW_BYTES));
|
|
807
|
+
if (total > MAX_CHUNKS) {
|
|
808
|
+
throw new KeychainError(
|
|
809
|
+
"keychain_error",
|
|
810
|
+
`Keychain payload exceeds maximum size (${MAX_KEYCHAIN_PAYLOAD_BYTES} bytes)`
|
|
811
|
+
);
|
|
812
|
+
}
|
|
813
|
+
const chunks = [];
|
|
814
|
+
for (let i = 0; i < total; i += 1) {
|
|
815
|
+
const slice = raw.subarray(
|
|
816
|
+
i * CHUNK_RAW_BYTES,
|
|
817
|
+
Math.min(raw.length, (i + 1) * CHUNK_RAW_BYTES)
|
|
818
|
+
);
|
|
819
|
+
chunks.push(`${CHUNK_PREFIX}${total}:${slice.toString("base64")}`);
|
|
820
|
+
}
|
|
821
|
+
return chunks;
|
|
822
|
+
};
|
|
823
|
+
var FIXED_GEN_SLOTS = ["a", "b"];
|
|
824
|
+
var parseGenPointer = (raw) => {
|
|
825
|
+
if (!raw.startsWith(GEN_POINTER_PREFIX)) return null;
|
|
826
|
+
const parts = raw.slice(GEN_POINTER_PREFIX.length).split(":");
|
|
827
|
+
if (parts.length !== 2) {
|
|
828
|
+
throw new KeychainError(
|
|
829
|
+
"keychain_error",
|
|
830
|
+
"Corrupt Keychain generation pointer"
|
|
831
|
+
);
|
|
832
|
+
}
|
|
833
|
+
const [gen, totalStr] = parts;
|
|
834
|
+
const countAndDigest = /^([1-9][0-9]*)(?:\.([a-f0-9]{64}))?$/.exec(totalStr);
|
|
835
|
+
const total = Number(countAndDigest?.[1]);
|
|
836
|
+
if (!/^(?:a|b|[0-9a-f]{8,16})$/.test(gen) || !Number.isInteger(total) || total < 1 || total > MAX_CHUNKS) {
|
|
837
|
+
throw new KeychainError(
|
|
838
|
+
"keychain_error",
|
|
839
|
+
"Corrupt Keychain generation pointer metadata"
|
|
840
|
+
);
|
|
841
|
+
}
|
|
842
|
+
return { gen, total, digest: countAndDigest?.[2] };
|
|
843
|
+
};
|
|
844
|
+
var parseChunkEnvelope = (raw) => {
|
|
845
|
+
if (!raw.startsWith(CHUNK_PREFIX)) return null;
|
|
846
|
+
const rest = raw.slice(CHUNK_PREFIX.length);
|
|
847
|
+
const sep = rest.indexOf(":");
|
|
848
|
+
if (sep <= 0) {
|
|
849
|
+
throw new KeychainError(
|
|
850
|
+
"keychain_error",
|
|
851
|
+
"Corrupt Keychain chunk envelope"
|
|
852
|
+
);
|
|
853
|
+
}
|
|
854
|
+
const total = Number.parseInt(rest.slice(0, sep), 10);
|
|
855
|
+
const base64 = rest.slice(sep + 1);
|
|
856
|
+
if (!Number.isInteger(total) || total < 1 || total > MAX_CHUNKS || !/^[A-Za-z0-9+/=]*$/.test(base64)) {
|
|
857
|
+
throw new KeychainError(
|
|
858
|
+
"keychain_error",
|
|
859
|
+
"Corrupt Keychain chunk metadata"
|
|
860
|
+
);
|
|
861
|
+
}
|
|
862
|
+
return { total, base64 };
|
|
863
|
+
};
|
|
864
|
+
var extractValidatedChunkBase64 = (rawChunk, expectedTotal, index, service) => {
|
|
865
|
+
if (rawChunk === null) {
|
|
866
|
+
throw new KeychainError(
|
|
867
|
+
"keychain_error",
|
|
868
|
+
`Missing Keychain chunk ${index + 1}/${expectedTotal} for ${service}`
|
|
869
|
+
);
|
|
870
|
+
}
|
|
871
|
+
const parsed = parseChunkEnvelope(rawChunk);
|
|
872
|
+
if (!parsed || parsed.total !== expectedTotal) {
|
|
873
|
+
throw new KeychainError(
|
|
874
|
+
"keychain_error",
|
|
875
|
+
`Inconsistent Keychain chunk ${index + 1}/${expectedTotal} for ${service}`
|
|
876
|
+
);
|
|
877
|
+
}
|
|
878
|
+
return parsed.base64;
|
|
879
|
+
};
|
|
880
|
+
var decodeBase64Chunks = (parts) => Buffer.from(parts.join(""), "base64").toString("utf8");
|
|
881
|
+
var payloadDigest = (value) => (0, import_node_crypto5.createHash)("sha256").update(value, "utf8").digest("hex");
|
|
882
|
+
var decodeLegacyOrSingleValue = (trimmed) => {
|
|
883
|
+
if (trimmed.startsWith("{")) return trimmed;
|
|
884
|
+
if (/^[0-9a-fA-F]+$/.test(trimmed) && trimmed.length % 2 === 0) {
|
|
885
|
+
const decoded = Buffer.from(trimmed, "hex").toString("utf8");
|
|
886
|
+
if (decoded.startsWith("{")) return decoded;
|
|
887
|
+
}
|
|
888
|
+
throw new KeychainError(
|
|
889
|
+
"keychain_error",
|
|
890
|
+
"Keychain item contains unrecognized credential format"
|
|
891
|
+
);
|
|
892
|
+
};
|
|
893
|
+
function* readChunkedSnapshot(service, root) {
|
|
894
|
+
if (root === null) return { value: null };
|
|
895
|
+
const pointer = parseGenPointer(root);
|
|
896
|
+
const first = pointer ? null : parseChunkEnvelope(root);
|
|
897
|
+
if (!pointer && !first) return { value: decodeLegacyOrSingleValue(root) };
|
|
898
|
+
if (first?.total === 1) return { value: decodeBase64Chunks([first.base64]) };
|
|
899
|
+
const total = pointer?.total ?? first?.total ?? 0;
|
|
900
|
+
const parts = first ? [first.base64] : [];
|
|
901
|
+
let result;
|
|
902
|
+
try {
|
|
903
|
+
for (let i = parts.length; i < total; i += 1) {
|
|
904
|
+
const rawChunk = yield pointer ? genChunkServiceName(service, pointer.gen, i) : chunkServiceName(service, i);
|
|
905
|
+
parts.push(extractValidatedChunkBase64(rawChunk, total, i, service));
|
|
906
|
+
}
|
|
907
|
+
const value = decodeBase64Chunks(parts);
|
|
908
|
+
if (pointer?.digest && pointer.digest !== payloadDigest(value)) {
|
|
909
|
+
throw new KeychainError(
|
|
910
|
+
"keychain_error",
|
|
911
|
+
"Inconsistent Keychain payload"
|
|
912
|
+
);
|
|
913
|
+
}
|
|
914
|
+
result = { value };
|
|
915
|
+
} catch (error) {
|
|
916
|
+
result = { error };
|
|
917
|
+
}
|
|
918
|
+
const currentRoot = yield service;
|
|
919
|
+
if (currentRoot !== root) return { nextRoot: currentRoot };
|
|
920
|
+
if ("error" in result) throw result.error;
|
|
921
|
+
return result;
|
|
922
|
+
}
|
|
923
|
+
var isNotFoundOutput = (code, stderr) => code === 44 || /could not be found in the keychain|SecKeychainSearchCopyNext: The specified item could not be found/i.test(
|
|
924
|
+
stderr
|
|
925
|
+
);
|
|
926
|
+
var classifySecurityFailure = (code, stderr, timedOut = false) => {
|
|
927
|
+
if (timedOut) {
|
|
928
|
+
return new KeychainError(
|
|
929
|
+
"keychain_error",
|
|
930
|
+
"macOS Keychain operation timed out. Run `codelia auth authorize-keychain` from a local terminal, then retry."
|
|
931
|
+
);
|
|
932
|
+
}
|
|
933
|
+
if (code === 36 || /User interaction is not allowed|errSecInteractionNotAllowed|keychain is locked/i.test(
|
|
934
|
+
stderr
|
|
935
|
+
)) {
|
|
936
|
+
return new KeychainError(
|
|
937
|
+
"keychain_locked",
|
|
938
|
+
"macOS login Keychain is locked; run `security unlock-keychain ~/Library/Keychains/login.keychain-db`"
|
|
939
|
+
);
|
|
940
|
+
}
|
|
941
|
+
if (code === 128 || /User canceled the operation|errSecUserCanceled|errSecAuthFailed|The user name or passphrase you entered is not correct/i.test(
|
|
942
|
+
stderr
|
|
943
|
+
)) {
|
|
944
|
+
return new KeychainError(
|
|
945
|
+
"keychain_access_denied",
|
|
946
|
+
"macOS Keychain denied access; run `codelia auth authorize-keychain` from a local terminal"
|
|
947
|
+
);
|
|
948
|
+
}
|
|
949
|
+
return new KeychainError("keychain_error", "macOS Keychain operation failed");
|
|
950
|
+
};
|
|
951
|
+
var securityEnv = () => ({
|
|
952
|
+
HOME: import_node_os.default.homedir(),
|
|
953
|
+
PATH: "/usr/bin:/bin",
|
|
954
|
+
...process.env.USER ? { USER: process.env.USER } : {},
|
|
955
|
+
...process.env.LOGNAME ? { LOGNAME: process.env.LOGNAME } : {}
|
|
956
|
+
});
|
|
957
|
+
var MacOsKeychainClient = class {
|
|
958
|
+
securityBinary;
|
|
959
|
+
hasCustomBinary;
|
|
960
|
+
constructor(options) {
|
|
961
|
+
const custom = options?.securityPath ?? options?.helperPath;
|
|
962
|
+
this.securityBinary = custom ?? DEFAULT_SECURITY_PATH;
|
|
963
|
+
this.hasCustomBinary = Boolean(custom);
|
|
964
|
+
}
|
|
965
|
+
resolveBinary() {
|
|
966
|
+
if (!this.hasCustomBinary && process.platform !== "darwin") {
|
|
967
|
+
return null;
|
|
968
|
+
}
|
|
969
|
+
if (!this.hasCustomBinary && process.env.CODELIA_TEST_KEYCHAIN_DISABLED === "1") {
|
|
970
|
+
throw new KeychainError(
|
|
971
|
+
"keychain_unavailable",
|
|
972
|
+
"macOS Keychain is disabled for tests"
|
|
973
|
+
);
|
|
974
|
+
}
|
|
975
|
+
try {
|
|
976
|
+
(0, import_node_fs6.accessSync)(this.securityBinary, import_node_fs6.constants.X_OK);
|
|
977
|
+
return this.securityBinary;
|
|
978
|
+
} catch {
|
|
979
|
+
return null;
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
requireBinary() {
|
|
983
|
+
const binary = this.resolveBinary();
|
|
984
|
+
if (!binary) {
|
|
985
|
+
throw new KeychainError(
|
|
986
|
+
"keychain_unavailable",
|
|
987
|
+
process.platform !== "darwin" ? "unsupported_platform" : "macOS /usr/bin/security is unavailable"
|
|
988
|
+
);
|
|
989
|
+
}
|
|
990
|
+
return binary;
|
|
991
|
+
}
|
|
992
|
+
runArgsAsync(args, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
|
|
993
|
+
const binary = this.requireBinary();
|
|
994
|
+
return new Promise((resolve, reject) => {
|
|
995
|
+
(0, import_node_child_process2.execFile)(
|
|
996
|
+
binary,
|
|
997
|
+
[...args],
|
|
998
|
+
{
|
|
999
|
+
cwd: "/",
|
|
1000
|
+
env: securityEnv(),
|
|
1001
|
+
timeout: timeoutMs,
|
|
1002
|
+
killSignal: "SIGKILL",
|
|
1003
|
+
maxBuffer: MAX_SECURITY_BUFFER,
|
|
1004
|
+
encoding: "utf8"
|
|
1005
|
+
},
|
|
1006
|
+
(error, stdout, stderr) => {
|
|
1007
|
+
if (!error) {
|
|
1008
|
+
resolve({ code: 0, stdout, stderr });
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
const timedOut = Boolean(error.killed && error.code === null);
|
|
1012
|
+
const exitCode = typeof error.code === "number" ? error.code : null;
|
|
1013
|
+
if (timedOut) {
|
|
1014
|
+
reject(classifySecurityFailure(exitCode, stderr ?? "", true));
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
resolve({
|
|
1018
|
+
code: exitCode ?? 1,
|
|
1019
|
+
stdout: stdout ?? "",
|
|
1020
|
+
stderr: stderr ?? error.message
|
|
1021
|
+
});
|
|
1022
|
+
}
|
|
1023
|
+
);
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
runInteractiveBatchAsync(commands, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
|
|
1027
|
+
const binary = this.requireBinary();
|
|
1028
|
+
const payload = `${commands.join("\n")}
|
|
1029
|
+
`;
|
|
1030
|
+
for (const line of commands) {
|
|
1031
|
+
if (Buffer.byteLength(line, "utf8") + 1 >= SECURITY_INTERACTIVE_MAX_LINE_BYTES) {
|
|
1032
|
+
throw new KeychainError(
|
|
1033
|
+
"keychain_error",
|
|
1034
|
+
"Keychain batch command exceeds 4096-byte security -i line limit"
|
|
1035
|
+
);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
return new Promise((resolve, reject) => {
|
|
1039
|
+
const child = (0, import_node_child_process2.spawn)(binary, ["-i"], {
|
|
1040
|
+
cwd: "/",
|
|
1041
|
+
env: securityEnv(),
|
|
1042
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
1043
|
+
});
|
|
1044
|
+
let stderr = "";
|
|
1045
|
+
let timedOut = false;
|
|
1046
|
+
const timer = setTimeout(() => {
|
|
1047
|
+
timedOut = true;
|
|
1048
|
+
child.kill("SIGKILL");
|
|
1049
|
+
}, timeoutMs);
|
|
1050
|
+
child.stdout.on("data", () => void 0);
|
|
1051
|
+
child.stderr.on("data", (chunk) => {
|
|
1052
|
+
if (stderr.length < MAX_STDERR_CAPTURE_BYTES) {
|
|
1053
|
+
stderr += chunk.toString("utf8");
|
|
1054
|
+
}
|
|
1055
|
+
});
|
|
1056
|
+
child.once("error", () => {
|
|
1057
|
+
clearTimeout(timer);
|
|
1058
|
+
reject(
|
|
1059
|
+
new KeychainError(
|
|
1060
|
+
"keychain_unavailable",
|
|
1061
|
+
"Failed to launch macOS /usr/bin/security"
|
|
1062
|
+
)
|
|
1063
|
+
);
|
|
1064
|
+
});
|
|
1065
|
+
child.once("close", (code) => {
|
|
1066
|
+
clearTimeout(timer);
|
|
1067
|
+
if (timedOut) {
|
|
1068
|
+
reject(classifySecurityFailure(code, stderr, true));
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
if (code !== 0) {
|
|
1072
|
+
reject(classifySecurityFailure(code, stderr, false));
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
resolve();
|
|
1076
|
+
});
|
|
1077
|
+
child.stdin.on("error", () => void 0);
|
|
1078
|
+
child.stdin.end(payload);
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
findRawAsync(service, account, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
|
|
1082
|
+
validateKeychainToken("service", service);
|
|
1083
|
+
validateKeychainToken("account", account);
|
|
1084
|
+
return this.runArgsAsync(
|
|
1085
|
+
["find-generic-password", "-w", "-a", account, "-s", service],
|
|
1086
|
+
timeoutMs
|
|
1087
|
+
).then(({ code, stdout, stderr }) => {
|
|
1088
|
+
if (code === 0) return stdout.replace(/\r?\n$/, "");
|
|
1089
|
+
if (isNotFoundOutput(code, stderr)) return null;
|
|
1090
|
+
throw classifySecurityFailure(code, stderr);
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
findRawSync(service, account, timeoutMs = DEFAULT_SYNC_TIMEOUT_MS) {
|
|
1094
|
+
validateKeychainToken("service", service);
|
|
1095
|
+
validateKeychainToken("account", account);
|
|
1096
|
+
const binary = this.requireBinary();
|
|
1097
|
+
try {
|
|
1098
|
+
const stdout = (0, import_node_child_process2.execFileSync)(
|
|
1099
|
+
binary,
|
|
1100
|
+
["find-generic-password", "-w", "-a", account, "-s", service],
|
|
1101
|
+
{
|
|
1102
|
+
cwd: "/",
|
|
1103
|
+
env: securityEnv(),
|
|
1104
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1105
|
+
timeout: timeoutMs,
|
|
1106
|
+
killSignal: "SIGKILL",
|
|
1107
|
+
maxBuffer: MAX_SECURITY_BUFFER,
|
|
1108
|
+
encoding: "utf8"
|
|
1109
|
+
}
|
|
1110
|
+
);
|
|
1111
|
+
return stdout.replace(/\r?\n$/, "");
|
|
1112
|
+
} catch (error) {
|
|
1113
|
+
const err = error;
|
|
1114
|
+
const status = typeof err.status === "number" ? err.status : null;
|
|
1115
|
+
const stderr = typeof err.stderr === "string" ? err.stderr : Buffer.isBuffer(err.stderr) ? err.stderr.toString("utf8") : "";
|
|
1116
|
+
const timedOut = err.code === "ETIMEDOUT" || status === null && Boolean(err.signal);
|
|
1117
|
+
if (!timedOut && isNotFoundOutput(status, stderr)) {
|
|
1118
|
+
return null;
|
|
1119
|
+
}
|
|
1120
|
+
throw classifySecurityFailure(status, stderr, timedOut);
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
async probe() {
|
|
1124
|
+
if (!this.hasCustomBinary && process.platform !== "darwin") {
|
|
1125
|
+
return {
|
|
1126
|
+
available: false,
|
|
1127
|
+
reason: "unsupported_platform",
|
|
1128
|
+
message: "OS Keychain backend is currently supported on macOS only"
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
try {
|
|
1132
|
+
const binary = this.resolveBinary();
|
|
1133
|
+
if (!binary) {
|
|
1134
|
+
return {
|
|
1135
|
+
available: false,
|
|
1136
|
+
reason: "keychain_unavailable",
|
|
1137
|
+
message: "macOS /usr/bin/security is unavailable"
|
|
1138
|
+
};
|
|
1139
|
+
}
|
|
1140
|
+
const { code, stderr } = await this.runArgsAsync(["show-keychain-info"]);
|
|
1141
|
+
if (code === 0) return { available: true };
|
|
1142
|
+
const classified = classifySecurityFailure(code, stderr);
|
|
1143
|
+
return {
|
|
1144
|
+
available: false,
|
|
1145
|
+
reason: classified.code === "keychain_locked" ? "keychain_locked" : "keychain_unavailable",
|
|
1146
|
+
message: classified.message
|
|
1147
|
+
};
|
|
1148
|
+
} catch (error) {
|
|
1149
|
+
const isLocked = error instanceof KeychainError && error.code === "keychain_locked";
|
|
1150
|
+
return {
|
|
1151
|
+
available: false,
|
|
1152
|
+
reason: isLocked ? "keychain_locked" : "keychain_unavailable",
|
|
1153
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1154
|
+
};
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
async readFullAsync(service, account, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
|
|
1158
|
+
const find = (name) => this.findRawAsync(name, account, timeoutMs);
|
|
1159
|
+
let root = await find(service);
|
|
1160
|
+
for (let attempt = 0; attempt < MAX_SNAPSHOT_ATTEMPTS; attempt += 1) {
|
|
1161
|
+
const snapshot = readChunkedSnapshot(service, root);
|
|
1162
|
+
let step = snapshot.next();
|
|
1163
|
+
while (!step.done) step = snapshot.next(await find(step.value));
|
|
1164
|
+
if ("value" in step.value) return step.value.value;
|
|
1165
|
+
root = step.value.nextRoot;
|
|
1166
|
+
}
|
|
1167
|
+
throw new KeychainError(
|
|
1168
|
+
"keychain_error",
|
|
1169
|
+
"Keychain changed during read; retry"
|
|
1170
|
+
);
|
|
1171
|
+
}
|
|
1172
|
+
async get(service, account) {
|
|
1173
|
+
return this.readFullAsync(service, account, DEFAULT_ASYNC_TIMEOUT_MS);
|
|
1174
|
+
}
|
|
1175
|
+
getSync(service, account, timeoutMs = DEFAULT_SYNC_TIMEOUT_MS) {
|
|
1176
|
+
const deadline = performance.now() + timeoutMs;
|
|
1177
|
+
const find = (name) => {
|
|
1178
|
+
const remaining = Math.ceil(deadline - performance.now());
|
|
1179
|
+
if (remaining <= 0) throw classifySecurityFailure(null, "", true);
|
|
1180
|
+
return this.findRawSync(name, account, remaining);
|
|
1181
|
+
};
|
|
1182
|
+
let root = find(service);
|
|
1183
|
+
for (let attempt = 0; attempt < MAX_SNAPSHOT_ATTEMPTS; attempt += 1) {
|
|
1184
|
+
const snapshot = readChunkedSnapshot(service, root);
|
|
1185
|
+
let step = snapshot.next();
|
|
1186
|
+
while (!step.done) step = snapshot.next(find(step.value));
|
|
1187
|
+
if ("value" in step.value) return step.value.value;
|
|
1188
|
+
root = step.value.nextRoot;
|
|
1189
|
+
}
|
|
1190
|
+
throw new KeychainError(
|
|
1191
|
+
"keychain_error",
|
|
1192
|
+
"Keychain changed during read; retry"
|
|
1193
|
+
);
|
|
1194
|
+
}
|
|
1195
|
+
async sweepGenSlotBestEffort(service, account, gen, startIndex = 0) {
|
|
1196
|
+
let consecutiveMisses = 0;
|
|
1197
|
+
for (let i = startIndex; i < MAX_CHUNKS; i += 1) {
|
|
1198
|
+
const deleted = await this.deleteSingleItem(
|
|
1199
|
+
genChunkServiceName(service, gen, i),
|
|
1200
|
+
account
|
|
1201
|
+
).catch(() => false);
|
|
1202
|
+
if (deleted) {
|
|
1203
|
+
consecutiveMisses = 0;
|
|
1204
|
+
} else {
|
|
1205
|
+
consecutiveMisses += 1;
|
|
1206
|
+
if (consecutiveMisses >= SWEEP_CONSECUTIVE_MISS_LIMIT) break;
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* Exhaustively delete every possible chunk index (`0..MAX_CHUNKS-1`) in a
|
|
1212
|
+
* fixed generation slot and propagate any non-not-found delete error.
|
|
1213
|
+
*/
|
|
1214
|
+
async deleteAllSlotChunksStrict(service, account, gen) {
|
|
1215
|
+
let deletedAny = false;
|
|
1216
|
+
for (let i = 0; i < MAX_CHUNKS; i += 1) {
|
|
1217
|
+
const deleted = await this.deleteSingleItem(
|
|
1218
|
+
genChunkServiceName(service, gen, i),
|
|
1219
|
+
account
|
|
1220
|
+
);
|
|
1221
|
+
if (deleted) deletedAny = true;
|
|
1222
|
+
}
|
|
1223
|
+
return deletedAny;
|
|
1224
|
+
}
|
|
1225
|
+
async cleanupOldChunks(service, account, previousRoot, keepGen) {
|
|
1226
|
+
try {
|
|
1227
|
+
if (previousRoot) {
|
|
1228
|
+
let prevPtr = null;
|
|
1229
|
+
try {
|
|
1230
|
+
prevPtr = parseGenPointer(previousRoot);
|
|
1231
|
+
} catch {
|
|
1232
|
+
prevPtr = null;
|
|
1233
|
+
}
|
|
1234
|
+
if (prevPtr && prevPtr.gen !== keepGen) {
|
|
1235
|
+
for (let i = 0; i < prevPtr.total; i += 1) {
|
|
1236
|
+
await this.deleteSingleItem(
|
|
1237
|
+
genChunkServiceName(service, prevPtr.gen, i),
|
|
1238
|
+
account
|
|
1239
|
+
).catch(() => false);
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
let prevCb1 = null;
|
|
1243
|
+
try {
|
|
1244
|
+
prevCb1 = parseChunkEnvelope(previousRoot);
|
|
1245
|
+
} catch {
|
|
1246
|
+
prevCb1 = null;
|
|
1247
|
+
}
|
|
1248
|
+
if (prevCb1 && prevCb1.total > 1) {
|
|
1249
|
+
for (let i = 1; i < prevCb1.total; i += 1) {
|
|
1250
|
+
await this.deleteSingleItem(
|
|
1251
|
+
chunkServiceName(service, i),
|
|
1252
|
+
account
|
|
1253
|
+
).catch(() => false);
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
for (const slot of FIXED_GEN_SLOTS) {
|
|
1258
|
+
if (slot !== keepGen) {
|
|
1259
|
+
await this.sweepGenSlotBestEffort(service, account, slot, 0);
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
} catch {
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
async writeSingleChunk(service, account, encoded, previousRoot) {
|
|
1266
|
+
await this.runInteractiveBatchAsync([
|
|
1267
|
+
`add-generic-password -U -a ${account} -s ${service} -w ${encoded}`
|
|
1268
|
+
]);
|
|
1269
|
+
const verified = await this.findRawAsync(service, account);
|
|
1270
|
+
if (verified !== encoded) {
|
|
1271
|
+
throw new KeychainError(
|
|
1272
|
+
"keychain_error",
|
|
1273
|
+
"macOS Keychain write verification failed"
|
|
1274
|
+
);
|
|
1275
|
+
}
|
|
1276
|
+
await this.cleanupOldChunks(service, account, previousRoot);
|
|
1277
|
+
}
|
|
1278
|
+
/**
|
|
1279
|
+
* Multi-chunk write: alternates between fixed A/B slots (`a` and `b`) so
|
|
1280
|
+
* existing credentials stay untouched until every staged chunk verifies via
|
|
1281
|
+
* read-back AND crashed writes remain deterministically discoverable on logout.
|
|
1282
|
+
*/
|
|
1283
|
+
async writeMultiChunk(service, account, chunks, previousRoot, digest2) {
|
|
1284
|
+
const activeGen = previousRoot ? parseGenPointer(previousRoot)?.gen : void 0;
|
|
1285
|
+
const gen = activeGen === "a" ? "b" : "a";
|
|
1286
|
+
const stageCommands = chunks.map(
|
|
1287
|
+
(encoded, index) => `add-generic-password -U -a ${account} -s ${genChunkServiceName(service, gen, index)} -w ${encoded}`
|
|
1288
|
+
);
|
|
1289
|
+
const rollbackStaged = async () => {
|
|
1290
|
+
for (let i = 0; i < chunks.length; i += 1) {
|
|
1291
|
+
await this.deleteSingleItem(
|
|
1292
|
+
genChunkServiceName(service, gen, i),
|
|
1293
|
+
account
|
|
1294
|
+
).catch(() => false);
|
|
1295
|
+
}
|
|
1296
|
+
};
|
|
1297
|
+
try {
|
|
1298
|
+
await this.runInteractiveBatchAsync(stageCommands);
|
|
1299
|
+
for (let i = 0; i < chunks.length; i += 1) {
|
|
1300
|
+
const verified = await this.findRawAsync(
|
|
1301
|
+
genChunkServiceName(service, gen, i),
|
|
1302
|
+
account
|
|
1303
|
+
);
|
|
1304
|
+
if (verified !== chunks[i]) {
|
|
1305
|
+
throw new KeychainError(
|
|
1306
|
+
"keychain_error",
|
|
1307
|
+
`macOS Keychain staged chunk ${i + 1}/${chunks.length} failed verification`
|
|
1308
|
+
);
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
} catch (error) {
|
|
1312
|
+
await rollbackStaged();
|
|
1313
|
+
throw error;
|
|
1314
|
+
}
|
|
1315
|
+
const pointerValue = `${GEN_POINTER_PREFIX}${gen}:${chunks.length}.${digest2}`;
|
|
1316
|
+
await this.runInteractiveBatchAsync([
|
|
1317
|
+
`add-generic-password -U -a ${account} -s ${service} -w ${pointerValue}`
|
|
1318
|
+
]);
|
|
1319
|
+
const verifiedPointer = await this.findRawAsync(service, account);
|
|
1320
|
+
if (verifiedPointer !== pointerValue) {
|
|
1321
|
+
await rollbackStaged();
|
|
1322
|
+
throw new KeychainError(
|
|
1323
|
+
"keychain_error",
|
|
1324
|
+
"macOS Keychain pointer verification failed"
|
|
1325
|
+
);
|
|
1326
|
+
}
|
|
1327
|
+
await this.sweepGenSlotBestEffort(service, account, gen, chunks.length);
|
|
1328
|
+
await this.cleanupOldChunks(service, account, previousRoot, gen);
|
|
1329
|
+
}
|
|
1330
|
+
async set(service, account, value) {
|
|
1331
|
+
validateKeychainToken("service", service);
|
|
1332
|
+
validateKeychainToken("account", account);
|
|
1333
|
+
const chunks = encodePayloadChunks(value);
|
|
1334
|
+
const previousRoot = await this.findRawAsync(service, account);
|
|
1335
|
+
if (chunks.length === 1) {
|
|
1336
|
+
await this.writeSingleChunk(service, account, chunks[0], previousRoot);
|
|
1337
|
+
return;
|
|
1338
|
+
}
|
|
1339
|
+
await this.writeMultiChunk(
|
|
1340
|
+
service,
|
|
1341
|
+
account,
|
|
1342
|
+
chunks,
|
|
1343
|
+
previousRoot,
|
|
1344
|
+
payloadDigest(value)
|
|
1345
|
+
);
|
|
1346
|
+
}
|
|
1347
|
+
async deleteSingleItem(service, account) {
|
|
1348
|
+
validateKeychainToken("service", service);
|
|
1349
|
+
validateKeychainToken("account", account);
|
|
1350
|
+
const { code, stderr } = await this.runArgsAsync([
|
|
1351
|
+
"delete-generic-password",
|
|
1352
|
+
"-a",
|
|
1353
|
+
account,
|
|
1354
|
+
"-s",
|
|
1355
|
+
service
|
|
1356
|
+
]);
|
|
1357
|
+
if (code === 0) return true;
|
|
1358
|
+
if (isNotFoundOutput(code, stderr)) return false;
|
|
1359
|
+
throw classifySecurityFailure(code, stderr);
|
|
1360
|
+
}
|
|
1361
|
+
async delete(service, account) {
|
|
1362
|
+
validateKeychainToken("service", service);
|
|
1363
|
+
validateKeychainToken("account", account);
|
|
1364
|
+
const existing = await this.findRawAsync(service, account);
|
|
1365
|
+
let deletedAny = false;
|
|
1366
|
+
if (existing) {
|
|
1367
|
+
let prevCb1 = null;
|
|
1368
|
+
try {
|
|
1369
|
+
prevCb1 = parseChunkEnvelope(existing);
|
|
1370
|
+
} catch {
|
|
1371
|
+
prevCb1 = null;
|
|
1372
|
+
}
|
|
1373
|
+
if (prevCb1 && prevCb1.total > 1) {
|
|
1374
|
+
for (let i = 1; i < prevCb1.total; i += 1) {
|
|
1375
|
+
if (await this.deleteSingleItem(chunkServiceName(service, i), account)) {
|
|
1376
|
+
deletedAny = true;
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
let prevPtr = null;
|
|
1381
|
+
try {
|
|
1382
|
+
prevPtr = parseGenPointer(existing);
|
|
1383
|
+
} catch {
|
|
1384
|
+
prevPtr = null;
|
|
1385
|
+
}
|
|
1386
|
+
if (prevPtr && !FIXED_GEN_SLOTS.includes(
|
|
1387
|
+
prevPtr.gen
|
|
1388
|
+
)) {
|
|
1389
|
+
for (let i = 0; i < prevPtr.total; i += 1) {
|
|
1390
|
+
if (await this.deleteSingleItem(
|
|
1391
|
+
genChunkServiceName(service, prevPtr.gen, i),
|
|
1392
|
+
account
|
|
1393
|
+
)) {
|
|
1394
|
+
deletedAny = true;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
const deletedPrimary = await this.deleteSingleItem(service, account);
|
|
1400
|
+
if (deletedPrimary) deletedAny = true;
|
|
1401
|
+
for (const slot of FIXED_GEN_SLOTS) {
|
|
1402
|
+
if (await this.deleteAllSlotChunksStrict(service, account, slot)) {
|
|
1403
|
+
deletedAny = true;
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
return deletedAny;
|
|
1407
|
+
}
|
|
1408
|
+
/** Let macOS prompt the user to authorize reading each existing item. */
|
|
1409
|
+
async authorize(service, account) {
|
|
1410
|
+
const fullValue = await this.readFullAsync(
|
|
1411
|
+
service,
|
|
1412
|
+
account,
|
|
1413
|
+
AUTHORIZATION_TIMEOUT_MS
|
|
1414
|
+
);
|
|
1415
|
+
return fullValue !== null;
|
|
1416
|
+
}
|
|
1417
|
+
};
|
|
1418
|
+
|
|
1419
|
+
// src/auth-schema.ts
|
|
1420
|
+
var AUTH_VERSION_V1 = 1;
|
|
1421
|
+
var AUTH_VERSION_V2 = 2;
|
|
1422
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1423
|
+
var normalizeApiKey = (value) => {
|
|
1424
|
+
if (!isRecord(value) || typeof value.api_key !== "string") return null;
|
|
1425
|
+
return {
|
|
1426
|
+
api_key: value.api_key,
|
|
1427
|
+
...typeof value.api_base === "string" && value.api_base.length > 0 ? { api_base: value.api_base } : {}
|
|
1428
|
+
};
|
|
1429
|
+
};
|
|
1430
|
+
var normalizeOAuth = (value) => {
|
|
1431
|
+
if (!isRecord(value) || typeof value.access_token !== "string" || typeof value.refresh_token !== "string" || typeof value.expires_at !== "number" || !Number.isFinite(value.expires_at)) {
|
|
1432
|
+
return null;
|
|
1433
|
+
}
|
|
1434
|
+
return {
|
|
1435
|
+
access_token: value.access_token,
|
|
1436
|
+
refresh_token: value.refresh_token,
|
|
1437
|
+
expires_at: value.expires_at,
|
|
1438
|
+
...typeof value.account_id === "string" && value.account_id.length > 0 ? { account_id: value.account_id } : {}
|
|
1439
|
+
};
|
|
1440
|
+
};
|
|
1441
|
+
var normalizeProviderEntryV1 = (value) => {
|
|
1442
|
+
if (!isRecord(value)) {
|
|
1443
|
+
throw new Error("auth.json contains invalid provider entry");
|
|
1444
|
+
}
|
|
1445
|
+
if (value.method === "api_key") {
|
|
1446
|
+
const apiKey = normalizeApiKey(value);
|
|
1447
|
+
if (!apiKey) {
|
|
1448
|
+
throw new Error("auth.json contains invalid api_key entry");
|
|
1449
|
+
}
|
|
1450
|
+
return {
|
|
1451
|
+
chat_method: "api_key",
|
|
1452
|
+
credentials: { api_key: apiKey }
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
if (value.method === "oauth") {
|
|
1456
|
+
const oauth = normalizeOAuth(value.oauth);
|
|
1457
|
+
if (!oauth) {
|
|
1458
|
+
throw new Error("auth.json contains invalid oauth entry");
|
|
1459
|
+
}
|
|
1460
|
+
return {
|
|
1461
|
+
chat_method: "oauth",
|
|
1462
|
+
credentials: { oauth }
|
|
1463
|
+
};
|
|
1464
|
+
}
|
|
1465
|
+
throw new Error("auth.json contains unsupported auth method");
|
|
1466
|
+
};
|
|
1467
|
+
var normalizeProviderEntryV2 = (value) => {
|
|
1468
|
+
if (!isRecord(value) || !isRecord(value.credentials)) {
|
|
1469
|
+
throw new Error("auth.json v2 contains invalid provider entry");
|
|
1470
|
+
}
|
|
1471
|
+
const chatMethod = value.chat_method;
|
|
1472
|
+
if (chatMethod !== void 0 && chatMethod !== "api_key" && chatMethod !== "oauth") {
|
|
1473
|
+
throw new Error("auth.json v2 contains invalid chat_method");
|
|
1474
|
+
}
|
|
1475
|
+
const credentials = {};
|
|
1476
|
+
if (value.credentials.api_key !== void 0) {
|
|
1477
|
+
const apiKey = normalizeApiKey(value.credentials.api_key);
|
|
1478
|
+
if (!apiKey) {
|
|
1479
|
+
throw new Error("auth.json v2 contains invalid api_key credential");
|
|
1480
|
+
}
|
|
1481
|
+
credentials.api_key = apiKey;
|
|
1482
|
+
}
|
|
1483
|
+
if (value.credentials.oauth !== void 0) {
|
|
1484
|
+
const oauth = normalizeOAuth(value.credentials.oauth);
|
|
1485
|
+
if (!oauth) {
|
|
1486
|
+
throw new Error("auth.json v2 contains invalid oauth credential");
|
|
1487
|
+
}
|
|
1488
|
+
credentials.oauth = oauth;
|
|
1489
|
+
}
|
|
1490
|
+
return {
|
|
1491
|
+
...chatMethod ? { chat_method: chatMethod } : {},
|
|
1492
|
+
credentials
|
|
1493
|
+
};
|
|
1494
|
+
};
|
|
1495
|
+
var parseAuthDocument = (text) => {
|
|
1496
|
+
const parsed = JSON.parse(text);
|
|
1497
|
+
if (!isRecord(parsed)) {
|
|
1498
|
+
throw new Error("auth.json has unsupported format");
|
|
1499
|
+
}
|
|
1500
|
+
if (parsed.version === AUTH_VERSION_V1) {
|
|
1501
|
+
const rawProviders = isRecord(parsed.providers) ? parsed.providers : {};
|
|
1502
|
+
const providers = {};
|
|
1503
|
+
for (const [name, entry] of Object.entries(rawProviders)) {
|
|
1504
|
+
providers[name] = normalizeProviderEntryV1(entry);
|
|
1505
|
+
}
|
|
1506
|
+
return {
|
|
1507
|
+
normalized: { version: AUTH_VERSION_V2, providers },
|
|
1508
|
+
sourceVersion: 1
|
|
1509
|
+
};
|
|
1510
|
+
}
|
|
1511
|
+
if (parsed.version === AUTH_VERSION_V2) {
|
|
1512
|
+
const rawProviders = isRecord(parsed.providers) ? parsed.providers : {};
|
|
1513
|
+
const providers = {};
|
|
1514
|
+
for (const [name, entry] of Object.entries(rawProviders)) {
|
|
1515
|
+
providers[name] = normalizeProviderEntryV2(entry);
|
|
1516
|
+
}
|
|
1517
|
+
return {
|
|
1518
|
+
normalized: { version: AUTH_VERSION_V2, providers },
|
|
1519
|
+
sourceVersion: 2
|
|
1520
|
+
};
|
|
1521
|
+
}
|
|
1522
|
+
throw new Error("auth.json has unsupported version");
|
|
1523
|
+
};
|
|
1524
|
+
var providerAuthStoreAdapter = {
|
|
1525
|
+
name: "auth",
|
|
1526
|
+
service: CODELIA_AUTH_KEYCHAIN_SERVICE,
|
|
1527
|
+
filePath: (paths) => paths.authFile,
|
|
1528
|
+
legacyFilePath: (paths) => paths.legacyAuthFile,
|
|
1529
|
+
empty: () => ({ version: AUTH_VERSION_V2, providers: {} }),
|
|
1530
|
+
isNonEmpty: (doc) => Object.keys(doc.providers).length > 0,
|
|
1531
|
+
parse: (text) => parseAuthDocument(text)
|
|
1532
|
+
};
|
|
1533
|
+
|
|
1534
|
+
// src/credential-backend.ts
|
|
1535
|
+
var import_node_fs8 = require("fs");
|
|
1536
|
+
var import_node_path7 = __toESM(require("path"), 1);
|
|
1537
|
+
|
|
1538
|
+
// src/credential-migration.ts
|
|
1539
|
+
var import_node_fs7 = require("fs");
|
|
1540
|
+
var CredentialConflictError = class extends Error {
|
|
1541
|
+
code = "credential_storage_conflict";
|
|
1542
|
+
store;
|
|
1543
|
+
constructor(store, detail) {
|
|
1544
|
+
super(
|
|
1545
|
+
detail ?? `Credential storage conflict detected for '${store}': both source and destination contain different credentials. Resolve the conflict before continuing.`
|
|
1546
|
+
);
|
|
1547
|
+
this.name = "CredentialConflictError";
|
|
1548
|
+
this.store = store;
|
|
1549
|
+
}
|
|
1550
|
+
};
|
|
1551
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1552
|
+
var canonicalizeValue = (value) => {
|
|
1553
|
+
if (Array.isArray(value)) {
|
|
1554
|
+
return value.map(canonicalizeValue);
|
|
1555
|
+
}
|
|
1556
|
+
if (isRecord2(value)) {
|
|
1557
|
+
const sorted = {};
|
|
1558
|
+
for (const key of Object.keys(value).sort()) {
|
|
1559
|
+
const entry = value[key];
|
|
1560
|
+
if (entry !== void 0) {
|
|
1561
|
+
sorted[key] = canonicalizeValue(entry);
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
return sorted;
|
|
1565
|
+
}
|
|
1566
|
+
return value;
|
|
1567
|
+
};
|
|
1568
|
+
var canonicalJsonStringify = (value) => JSON.stringify(canonicalizeValue(value));
|
|
1569
|
+
var canonicalJsonEqual = (left, right) => canonicalJsonStringify(left) === canonicalJsonStringify(right);
|
|
1570
|
+
var parseAuthStorageState = (text) => {
|
|
1571
|
+
const parsed = JSON.parse(text);
|
|
1572
|
+
if (!isRecord2(parsed) || parsed.version !== 1) {
|
|
1573
|
+
throw new Error("storage-state.json has unsupported version");
|
|
1574
|
+
}
|
|
1575
|
+
const active = parsed.active_backend;
|
|
1576
|
+
if (active !== "file" && active !== "keyring") {
|
|
1577
|
+
throw new Error("storage-state.json has invalid active_backend");
|
|
1578
|
+
}
|
|
1579
|
+
if (parsed.mcp_reauth_required !== void 0 && (!Array.isArray(parsed.mcp_reauth_required) || !parsed.mcp_reauth_required.every((item) => typeof item === "string"))) {
|
|
1580
|
+
throw new Error("storage-state.json has invalid mcp_reauth_required");
|
|
1581
|
+
}
|
|
1582
|
+
const mcpReauth = parsed.mcp_reauth_required;
|
|
1583
|
+
if (parsed.status === "steady") {
|
|
1584
|
+
return {
|
|
1585
|
+
version: 1,
|
|
1586
|
+
status: "steady",
|
|
1587
|
+
active_backend: active,
|
|
1588
|
+
...mcpReauth?.length ? { mcp_reauth_required: mcpReauth } : {}
|
|
1589
|
+
};
|
|
1590
|
+
}
|
|
1591
|
+
if (parsed.status === "migrating") {
|
|
1592
|
+
const target = parsed.target_backend;
|
|
1593
|
+
const stores = isRecord2(parsed.stores) ? parsed.stores : null;
|
|
1594
|
+
const authStatus = stores?.auth;
|
|
1595
|
+
const mcpStatus = stores?.mcp_auth;
|
|
1596
|
+
if (target !== "file" && target !== "keyring" || authStatus !== "pending" && authStatus !== "verified" || mcpStatus !== "pending" && mcpStatus !== "verified") {
|
|
1597
|
+
throw new Error("storage-state.json has invalid migrating state");
|
|
1598
|
+
}
|
|
1599
|
+
let cleanupPending;
|
|
1600
|
+
if (parsed.cleanup_pending !== void 0) {
|
|
1601
|
+
if (!isRecord2(parsed.cleanup_pending)) {
|
|
1602
|
+
throw new Error("storage-state.json has invalid cleanup_pending");
|
|
1603
|
+
}
|
|
1604
|
+
const sourceBackend = parsed.cleanup_pending.source_backend;
|
|
1605
|
+
const authFlag = parsed.cleanup_pending.auth;
|
|
1606
|
+
const mcpFlag = parsed.cleanup_pending.mcp_auth;
|
|
1607
|
+
if (sourceBackend !== "file" && sourceBackend !== "legacy_file" && sourceBackend !== "keyring" || typeof authFlag !== "boolean" || typeof mcpFlag !== "boolean") {
|
|
1608
|
+
throw new Error("storage-state.json has invalid cleanup_pending");
|
|
1609
|
+
}
|
|
1610
|
+
cleanupPending = {
|
|
1611
|
+
source_backend: sourceBackend,
|
|
1612
|
+
auth: authFlag,
|
|
1613
|
+
mcp_auth: mcpFlag
|
|
1614
|
+
};
|
|
1615
|
+
}
|
|
1616
|
+
return {
|
|
1617
|
+
version: 1,
|
|
1618
|
+
status: "migrating",
|
|
1619
|
+
active_backend: active,
|
|
1620
|
+
target_backend: target,
|
|
1621
|
+
stores: { auth: authStatus, mcp_auth: mcpStatus },
|
|
1622
|
+
...cleanupPending ? { cleanup_pending: cleanupPending } : {},
|
|
1623
|
+
...mcpReauth?.length ? { mcp_reauth_required: mcpReauth } : {}
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1626
|
+
throw new Error("storage-state.json has invalid status");
|
|
1627
|
+
};
|
|
1628
|
+
var readAuthStorageState = async (stateFile) => {
|
|
1629
|
+
if (!await verifyWindowsCredentialFileAcl(stateFile)) return null;
|
|
1630
|
+
let text;
|
|
1631
|
+
try {
|
|
1632
|
+
text = await import_node_fs7.promises.readFile(stateFile, "utf8");
|
|
1633
|
+
} catch (error) {
|
|
1634
|
+
if (error?.code === "ENOENT") return null;
|
|
1635
|
+
throw error;
|
|
1636
|
+
}
|
|
1637
|
+
return parseAuthStorageState(text);
|
|
1638
|
+
};
|
|
1639
|
+
var readAuthStorageStateSync = (stateFile) => {
|
|
1640
|
+
if (!verifyWindowsCredentialFileAclSync(stateFile)) return null;
|
|
1641
|
+
let text;
|
|
1642
|
+
try {
|
|
1643
|
+
text = (0, import_node_fs7.readFileSync)(stateFile, "utf8");
|
|
1644
|
+
} catch (error) {
|
|
1645
|
+
if (error?.code === "ENOENT") return null;
|
|
1646
|
+
throw error;
|
|
1647
|
+
}
|
|
1648
|
+
return parseAuthStorageState(text);
|
|
1649
|
+
};
|
|
1650
|
+
var writeAuthStorageState = async (stateFile, state) => {
|
|
1651
|
+
await writeFileAtomic(stateFile, JSON.stringify(state, null, 2), {
|
|
1652
|
+
mode: 384
|
|
1653
|
+
});
|
|
1654
|
+
};
|
|
1655
|
+
var runTwoPhaseMigration = async (options) => {
|
|
1656
|
+
const [authSrc, authDst, mcpSrc, mcpDst] = await Promise.all([
|
|
1657
|
+
options.authSlot.readSource(),
|
|
1658
|
+
options.authSlot.readDest(),
|
|
1659
|
+
options.mcpSlot.readSource(),
|
|
1660
|
+
options.mcpSlot.readDest()
|
|
1661
|
+
]);
|
|
1662
|
+
const evaluate = (name, src, dst) => {
|
|
1663
|
+
if (!src.present) return "none";
|
|
1664
|
+
if (src.nonEmpty && dst.nonEmpty) {
|
|
1665
|
+
if (canonicalJsonEqual(src.normalized, dst.normalized)) {
|
|
1666
|
+
return "recover";
|
|
1667
|
+
}
|
|
1668
|
+
throw new CredentialConflictError(name);
|
|
1669
|
+
}
|
|
1670
|
+
if (!src.nonEmpty && dst.nonEmpty) {
|
|
1671
|
+
return "recover";
|
|
1672
|
+
}
|
|
1673
|
+
if (dst.present && canonicalJsonEqual(src.normalized, dst.normalized)) {
|
|
1674
|
+
return "recover";
|
|
1675
|
+
}
|
|
1676
|
+
return "copy";
|
|
1677
|
+
};
|
|
1678
|
+
const authAction = evaluate("auth", authSrc, authDst);
|
|
1679
|
+
const mcpAction = evaluate("mcp_auth", mcpSrc, mcpDst);
|
|
1680
|
+
const mcpReauthSet = /* @__PURE__ */ new Set([
|
|
1681
|
+
...options.existingMcpReauth ?? [],
|
|
1682
|
+
...mcpSrc.extraWarnings ?? []
|
|
1683
|
+
]);
|
|
1684
|
+
const mcpReauthRequired = [...mcpReauthSet].sort();
|
|
1685
|
+
if (authAction === "none" && mcpAction === "none") {
|
|
1686
|
+
if (options.fromBackend !== options.toBackend || options.commitSteadyIfEmpty) {
|
|
1687
|
+
await writeAuthStorageState(options.stateFile, {
|
|
1688
|
+
version: 1,
|
|
1689
|
+
status: "steady",
|
|
1690
|
+
active_backend: options.toBackend,
|
|
1691
|
+
...mcpReauthRequired.length ? { mcp_reauth_required: mcpReauthRequired } : {}
|
|
1692
|
+
});
|
|
1693
|
+
}
|
|
1694
|
+
return { migrated: false, mcpReauthRequired };
|
|
1695
|
+
}
|
|
1696
|
+
const migratingState = {
|
|
1697
|
+
version: 1,
|
|
1698
|
+
status: "migrating",
|
|
1699
|
+
active_backend: options.fromBackend,
|
|
1700
|
+
target_backend: options.toBackend,
|
|
1701
|
+
stores: {
|
|
1702
|
+
auth: authAction === "copy" ? "pending" : "verified",
|
|
1703
|
+
mcp_auth: mcpAction === "copy" ? "pending" : "verified"
|
|
1704
|
+
},
|
|
1705
|
+
...mcpReauthRequired.length ? { mcp_reauth_required: mcpReauthRequired } : {}
|
|
1706
|
+
};
|
|
1707
|
+
await writeAuthStorageState(options.stateFile, migratingState);
|
|
1708
|
+
if (authAction === "copy") {
|
|
1709
|
+
await options.authSlot.writeDest(authSrc.normalized);
|
|
1710
|
+
const verified = await options.authSlot.verifyDest(authSrc.normalized);
|
|
1711
|
+
if (!verified) {
|
|
1712
|
+
throw new Error("auth migration read-back verification failed");
|
|
1713
|
+
}
|
|
1714
|
+
migratingState.stores.auth = "verified";
|
|
1715
|
+
await writeAuthStorageState(options.stateFile, migratingState);
|
|
1716
|
+
}
|
|
1717
|
+
if (mcpAction === "copy") {
|
|
1718
|
+
await options.mcpSlot.writeDest(mcpSrc.normalized);
|
|
1719
|
+
const verified = await options.mcpSlot.verifyDest(mcpSrc.normalized);
|
|
1720
|
+
if (!verified) {
|
|
1721
|
+
throw new Error("mcp-auth migration read-back verification failed");
|
|
1722
|
+
}
|
|
1723
|
+
migratingState.stores.mcp_auth = "verified";
|
|
1724
|
+
await writeAuthStorageState(options.stateFile, migratingState);
|
|
1725
|
+
}
|
|
1726
|
+
if (authSrc.present || mcpSrc.present) {
|
|
1727
|
+
migratingState.cleanup_pending = {
|
|
1728
|
+
source_backend: options.cleanupSourceKind ?? options.fromBackend,
|
|
1729
|
+
auth: authSrc.present,
|
|
1730
|
+
mcp_auth: mcpSrc.present
|
|
1731
|
+
};
|
|
1732
|
+
await writeAuthStorageState(options.stateFile, migratingState);
|
|
1733
|
+
}
|
|
1734
|
+
if (authSrc.present) {
|
|
1735
|
+
await options.authSlot.cleanupSource();
|
|
1736
|
+
}
|
|
1737
|
+
if (mcpSrc.present) {
|
|
1738
|
+
await options.mcpSlot.cleanupSource();
|
|
1739
|
+
}
|
|
1740
|
+
await writeAuthStorageState(options.stateFile, {
|
|
1741
|
+
version: 1,
|
|
1742
|
+
status: "steady",
|
|
1743
|
+
active_backend: options.toBackend,
|
|
1744
|
+
...mcpReauthRequired.length ? { mcp_reauth_required: mcpReauthRequired } : {}
|
|
1745
|
+
});
|
|
1746
|
+
return { migrated: true, mcpReauthRequired };
|
|
1747
|
+
};
|
|
1748
|
+
|
|
1749
|
+
// src/paths.ts
|
|
1750
|
+
var import_promises4 = require("fs/promises");
|
|
1751
|
+
var import_node_os2 = __toESM(require("os"), 1);
|
|
1752
|
+
var import_node_path6 = __toESM(require("path"), 1);
|
|
1753
|
+
var DEFAULT_ROOT_DIR = ".codelia";
|
|
1754
|
+
var LAYOUT_ENV = "CODELIA_LAYOUT";
|
|
1755
|
+
var XDG_DIR_NAME = "codelia";
|
|
1756
|
+
var CONFIG_FILENAME = "config.json";
|
|
1757
|
+
var CREDENTIALS_DIRNAME = "credentials";
|
|
1758
|
+
var AUTH_FILENAME = "auth.json";
|
|
1759
|
+
var MCP_AUTH_FILENAME = "mcp-auth.json";
|
|
1760
|
+
var AUTH_STATE_FILENAME = "storage-state.json";
|
|
1761
|
+
var PROJECTS_FILENAME = "projects.json";
|
|
1762
|
+
var CACHE_DIRNAME = "cache";
|
|
1763
|
+
var TOOL_OUTPUT_CACHE_DIRNAME = "tool-output";
|
|
1764
|
+
var SESSIONS_DIRNAME = "sessions";
|
|
1765
|
+
var LOGS_DIRNAME = "logs";
|
|
1766
|
+
function resolveStoragePaths(options = {}) {
|
|
1767
|
+
if (options.rootOverride) {
|
|
1768
|
+
return buildHomeLayout(options.rootOverride);
|
|
1769
|
+
}
|
|
1770
|
+
const layoutValue = options.layout ?? process.env[LAYOUT_ENV];
|
|
1771
|
+
const layout = normalizeLayout(layoutValue);
|
|
1772
|
+
if (layout === "xdg") {
|
|
1773
|
+
return buildXdgLayout();
|
|
1774
|
+
}
|
|
1775
|
+
return buildHomeLayout(defaultHomeRoot());
|
|
1776
|
+
}
|
|
1777
|
+
async function ensureStorageDirs(paths) {
|
|
1778
|
+
await Promise.all([
|
|
1779
|
+
(0, import_promises4.mkdir)(paths.configDir, { recursive: true }),
|
|
1780
|
+
(0, import_promises4.mkdir)(paths.cacheDir, { recursive: true }),
|
|
1781
|
+
(0, import_promises4.mkdir)(paths.toolOutputCacheDir, { recursive: true }),
|
|
1782
|
+
(0, import_promises4.mkdir)(paths.sessionsDir, { recursive: true }),
|
|
1783
|
+
(0, import_promises4.mkdir)(paths.logsDir, { recursive: true })
|
|
1784
|
+
]);
|
|
1785
|
+
}
|
|
1786
|
+
function resolveDefaultHomeConfigDir(home = import_node_os2.default.homedir(), layoutValue = process.env[LAYOUT_ENV]) {
|
|
1787
|
+
const layout = normalizeLayout(layoutValue);
|
|
1788
|
+
return layout === "xdg" ? import_node_path6.default.join(home, ".config", XDG_DIR_NAME) : import_node_path6.default.join(home, DEFAULT_ROOT_DIR);
|
|
1789
|
+
}
|
|
1790
|
+
function normalizeLayout(value) {
|
|
1791
|
+
if (value && value.toLowerCase() === "xdg") return "xdg";
|
|
1792
|
+
return "home";
|
|
1793
|
+
}
|
|
1794
|
+
function defaultHomeRoot() {
|
|
1795
|
+
return import_node_path6.default.join(import_node_os2.default.homedir(), DEFAULT_ROOT_DIR);
|
|
1796
|
+
}
|
|
1797
|
+
function buildHomeLayout(root) {
|
|
1798
|
+
const configDir = root;
|
|
1799
|
+
const credentialsDir = import_node_path6.default.join(configDir, CREDENTIALS_DIRNAME);
|
|
1800
|
+
return {
|
|
1801
|
+
root,
|
|
1802
|
+
configDir,
|
|
1803
|
+
configFile: import_node_path6.default.join(configDir, CONFIG_FILENAME),
|
|
1804
|
+
credentialsDir,
|
|
1805
|
+
authFile: import_node_path6.default.join(credentialsDir, AUTH_FILENAME),
|
|
1806
|
+
mcpAuthFile: import_node_path6.default.join(credentialsDir, MCP_AUTH_FILENAME),
|
|
1807
|
+
legacyAuthFile: import_node_path6.default.join(configDir, AUTH_FILENAME),
|
|
1808
|
+
legacyMcpAuthFile: import_node_path6.default.join(configDir, MCP_AUTH_FILENAME),
|
|
1809
|
+
authStateFile: import_node_path6.default.join(credentialsDir, AUTH_STATE_FILENAME),
|
|
1810
|
+
projectsFile: import_node_path6.default.join(configDir, PROJECTS_FILENAME),
|
|
1811
|
+
cacheDir: import_node_path6.default.join(root, CACHE_DIRNAME),
|
|
1812
|
+
toolOutputCacheDir: import_node_path6.default.join(
|
|
1813
|
+
root,
|
|
1814
|
+
CACHE_DIRNAME,
|
|
1815
|
+
TOOL_OUTPUT_CACHE_DIRNAME
|
|
1816
|
+
),
|
|
1817
|
+
sessionsDir: import_node_path6.default.join(root, SESSIONS_DIRNAME),
|
|
1818
|
+
logsDir: import_node_path6.default.join(root, LOGS_DIRNAME)
|
|
1819
|
+
};
|
|
1820
|
+
}
|
|
1821
|
+
function buildXdgLayout() {
|
|
1822
|
+
const home = import_node_os2.default.homedir();
|
|
1823
|
+
const configRoot = process.env.XDG_CONFIG_HOME ?? import_node_path6.default.join(home, ".config");
|
|
1824
|
+
const cacheRoot = process.env.XDG_CACHE_HOME ?? import_node_path6.default.join(home, ".cache");
|
|
1825
|
+
const stateRoot = process.env.XDG_STATE_HOME ?? import_node_path6.default.join(home, ".local", "state");
|
|
1826
|
+
const configDir = import_node_path6.default.join(configRoot, XDG_DIR_NAME);
|
|
1827
|
+
const credentialsDir = import_node_path6.default.join(configDir, CREDENTIALS_DIRNAME);
|
|
1828
|
+
const cacheDir = import_node_path6.default.join(cacheRoot, XDG_DIR_NAME);
|
|
1829
|
+
const stateDir = import_node_path6.default.join(stateRoot, XDG_DIR_NAME);
|
|
1830
|
+
return {
|
|
1831
|
+
root: stateDir,
|
|
1832
|
+
configDir,
|
|
1833
|
+
configFile: import_node_path6.default.join(configDir, CONFIG_FILENAME),
|
|
1834
|
+
credentialsDir,
|
|
1835
|
+
authFile: import_node_path6.default.join(credentialsDir, AUTH_FILENAME),
|
|
1836
|
+
mcpAuthFile: import_node_path6.default.join(credentialsDir, MCP_AUTH_FILENAME),
|
|
1837
|
+
legacyAuthFile: import_node_path6.default.join(configDir, AUTH_FILENAME),
|
|
1838
|
+
legacyMcpAuthFile: import_node_path6.default.join(configDir, MCP_AUTH_FILENAME),
|
|
1839
|
+
authStateFile: import_node_path6.default.join(credentialsDir, AUTH_STATE_FILENAME),
|
|
1840
|
+
projectsFile: import_node_path6.default.join(configDir, PROJECTS_FILENAME),
|
|
1841
|
+
cacheDir,
|
|
1842
|
+
toolOutputCacheDir: import_node_path6.default.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
|
|
1843
|
+
sessionsDir: import_node_path6.default.join(stateDir, SESSIONS_DIRNAME),
|
|
1844
|
+
logsDir: import_node_path6.default.join(stateDir, LOGS_DIRNAME)
|
|
1845
|
+
};
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
// src/credential-backend.ts
|
|
1849
|
+
var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1850
|
+
var probeUnavailableError = (probe, message = probe.message) => new KeychainError(
|
|
1851
|
+
probe.reason === "keychain_locked" ? "keychain_locked" : "keychain_unavailable",
|
|
1852
|
+
message
|
|
1853
|
+
);
|
|
1854
|
+
var buildSteadyState = (activeBackend, mcpReauthRequired) => ({
|
|
1855
|
+
version: 1,
|
|
1856
|
+
status: "steady",
|
|
1857
|
+
active_backend: activeBackend,
|
|
1858
|
+
...mcpReauthRequired?.length ? { mcp_reauth_required: [...mcpReauthRequired] } : {}
|
|
1859
|
+
});
|
|
1860
|
+
var isKeyringOwnedOrTargeting = (state) => state?.active_backend === "keyring" || state?.status === "migrating" && state.target_backend === "keyring";
|
|
1861
|
+
var isKeyringInvolved = (state) => isKeyringOwnedOrTargeting(state) || state?.status === "migrating" && state.cleanup_pending?.source_backend === "keyring";
|
|
1862
|
+
var parseStorageModeValue = (value) => {
|
|
1863
|
+
if (value === "auto" || value === "keyring" || value === "file") {
|
|
1864
|
+
return value;
|
|
1865
|
+
}
|
|
1866
|
+
return void 0;
|
|
1867
|
+
};
|
|
1868
|
+
var resolveConfiguredAuthStorageMode = (paths, overrideMode) => {
|
|
1869
|
+
if (overrideMode) return overrideMode;
|
|
1870
|
+
const envRaw = process.env.CODELIA_AUTH_STORAGE?.trim();
|
|
1871
|
+
if (envRaw) {
|
|
1872
|
+
const parsed = parseStorageModeValue(envRaw);
|
|
1873
|
+
if (!parsed) {
|
|
1874
|
+
throw new Error(
|
|
1875
|
+
`Invalid CODELIA_AUTH_STORAGE="${envRaw}" (expected "auto", "keyring", or "file")`
|
|
1876
|
+
);
|
|
1877
|
+
}
|
|
1878
|
+
return parsed;
|
|
1879
|
+
}
|
|
1880
|
+
const globalConfigPath = process.env.CODELIA_CONFIG_PATH?.trim() ? import_node_path7.default.resolve(process.env.CODELIA_CONFIG_PATH.trim()) : paths.configFile;
|
|
1881
|
+
try {
|
|
1882
|
+
const raw = (0, import_node_fs8.readFileSync)(globalConfigPath, "utf8");
|
|
1883
|
+
const parsed = JSON.parse(raw);
|
|
1884
|
+
if (isRecord3(parsed) && isRecord3(parsed.auth)) {
|
|
1885
|
+
const mode = parsed.auth.storage;
|
|
1886
|
+
if (mode !== void 0) {
|
|
1887
|
+
const valid = parseStorageModeValue(mode);
|
|
1888
|
+
if (!valid) {
|
|
1889
|
+
throw new Error(
|
|
1890
|
+
`Invalid global auth.storage="${String(mode)}" (expected "auto", "keyring", or "file")`
|
|
1891
|
+
);
|
|
1892
|
+
}
|
|
1893
|
+
return valid;
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1896
|
+
} catch (error) {
|
|
1897
|
+
if (error?.code !== "ENOENT") {
|
|
1898
|
+
if (error instanceof Error && error.message.startsWith("Invalid global auth.storage")) {
|
|
1899
|
+
throw error;
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
return "auto";
|
|
1904
|
+
};
|
|
1905
|
+
var readTextIfPresent = async (filePath, legacy = false) => {
|
|
1906
|
+
if (!await verifyWindowsCredentialFileAcl(filePath, legacy)) return null;
|
|
1907
|
+
try {
|
|
1908
|
+
return await import_node_fs8.promises.readFile(filePath, "utf8");
|
|
1909
|
+
} catch (error) {
|
|
1910
|
+
if (error?.code === "ENOENT") return null;
|
|
1911
|
+
throw error;
|
|
1912
|
+
}
|
|
1913
|
+
};
|
|
1914
|
+
var readFileSlot = async (filePath, adapter, legacy = false) => {
|
|
1915
|
+
const text = await readTextIfPresent(filePath, legacy);
|
|
1916
|
+
if (text === null) {
|
|
1917
|
+
return { present: false, normalized: adapter.empty(), nonEmpty: false };
|
|
1918
|
+
}
|
|
1919
|
+
const parsed = adapter.parse(text);
|
|
1920
|
+
return {
|
|
1921
|
+
present: true,
|
|
1922
|
+
normalized: parsed.normalized,
|
|
1923
|
+
nonEmpty: adapter.isNonEmpty(parsed.normalized),
|
|
1924
|
+
sourceVersion: parsed.sourceVersion,
|
|
1925
|
+
extraWarnings: parsed.extraWarnings
|
|
1926
|
+
};
|
|
1927
|
+
};
|
|
1928
|
+
var readKeychainSlot = async (keychain, service, account, adapter) => {
|
|
1929
|
+
const text = await keychain.get(service, account);
|
|
1930
|
+
if (text === null) {
|
|
1931
|
+
return { present: false, normalized: adapter.empty(), nonEmpty: false };
|
|
1932
|
+
}
|
|
1933
|
+
const parsed = adapter.parse(text);
|
|
1934
|
+
return {
|
|
1935
|
+
present: true,
|
|
1936
|
+
normalized: parsed.normalized,
|
|
1937
|
+
nonEmpty: adapter.isNonEmpty(parsed.normalized)
|
|
1938
|
+
};
|
|
1939
|
+
};
|
|
1940
|
+
var unlinkIfPresent = async (filePath) => {
|
|
1941
|
+
try {
|
|
1942
|
+
await import_node_fs8.promises.unlink(filePath);
|
|
1943
|
+
} catch (error) {
|
|
1944
|
+
if (error?.code === "ENOENT") return;
|
|
1945
|
+
throw error;
|
|
1946
|
+
}
|
|
1947
|
+
};
|
|
1948
|
+
var makeKeychainTargetSlot = (keychain, account, adapter, sourcePath) => ({
|
|
1949
|
+
name: adapter.name,
|
|
1950
|
+
readSource: () => readFileSlot(sourcePath, adapter),
|
|
1951
|
+
readDest: () => readKeychainSlot(keychain, adapter.service, account, adapter),
|
|
1952
|
+
writeDest: async (normalized) => {
|
|
1953
|
+
await keychain.set(adapter.service, account, JSON.stringify(normalized));
|
|
1954
|
+
},
|
|
1955
|
+
verifyDest: async (expected) => {
|
|
1956
|
+
const back = await readKeychainSlot(
|
|
1957
|
+
keychain,
|
|
1958
|
+
adapter.service,
|
|
1959
|
+
account,
|
|
1960
|
+
adapter
|
|
1961
|
+
);
|
|
1962
|
+
return back.present && canonicalJsonEqual(back.normalized, expected);
|
|
1963
|
+
},
|
|
1964
|
+
cleanupSource: () => unlinkIfPresent(sourcePath)
|
|
1965
|
+
});
|
|
1966
|
+
var makeFileDestHandlers = (paths, adapter) => {
|
|
1967
|
+
const destPath = adapter.filePath(paths);
|
|
1968
|
+
return {
|
|
1969
|
+
readDest: () => readFileSlot(destPath, adapter),
|
|
1970
|
+
writeDest: async (normalized) => {
|
|
1971
|
+
await ensureStorageDirs(paths);
|
|
1972
|
+
await writeFileAtomic(destPath, JSON.stringify(normalized, null, 2), {
|
|
1973
|
+
mode: 384
|
|
1974
|
+
});
|
|
1975
|
+
},
|
|
1976
|
+
verifyDest: async (expected) => {
|
|
1977
|
+
const back = await readFileSlot(destPath, adapter);
|
|
1978
|
+
return back.present && canonicalJsonEqual(back.normalized, expected);
|
|
1979
|
+
}
|
|
1980
|
+
};
|
|
1981
|
+
};
|
|
1982
|
+
var makeFileFromKeychainSlot = (paths, keychain, account, adapter) => ({
|
|
1983
|
+
name: adapter.name,
|
|
1984
|
+
readSource: () => readKeychainSlot(keychain, adapter.service, account, adapter),
|
|
1985
|
+
...makeFileDestHandlers(paths, adapter),
|
|
1986
|
+
cleanupSource: async () => {
|
|
1987
|
+
await keychain.delete(adapter.service, account);
|
|
1988
|
+
}
|
|
1989
|
+
});
|
|
1990
|
+
var makeFileFromLegacySlot = (paths, adapter) => {
|
|
1991
|
+
const sourcePath = adapter.legacyFilePath(paths);
|
|
1992
|
+
return {
|
|
1993
|
+
name: adapter.name,
|
|
1994
|
+
readSource: () => readFileSlot(sourcePath, adapter, true),
|
|
1995
|
+
...makeFileDestHandlers(paths, adapter),
|
|
1996
|
+
cleanupSource: () => unlinkIfPresent(sourcePath)
|
|
1997
|
+
};
|
|
1998
|
+
};
|
|
1999
|
+
var completePendingCleanupUnlocked = async (options) => {
|
|
2000
|
+
const pending = options.state.cleanup_pending;
|
|
2001
|
+
if (!pending) return options.state;
|
|
2002
|
+
if (pending.source_backend === "keyring" && options.state.target_backend === "file") {
|
|
2003
|
+
const probe = await options.keychain.probe();
|
|
2004
|
+
if (!probe.available) {
|
|
2005
|
+
throw probeUnavailableError(
|
|
2006
|
+
probe,
|
|
2007
|
+
`Cannot finish cleanup of previous Keychain credentials after migration while Keychain is unavailable (${probe.reason}): ${probe.message}`
|
|
2008
|
+
);
|
|
2009
|
+
}
|
|
2010
|
+
if (pending.auth) {
|
|
2011
|
+
await options.keychain.delete(
|
|
2012
|
+
options.authAdapter.service,
|
|
2013
|
+
options.account
|
|
2014
|
+
);
|
|
2015
|
+
}
|
|
2016
|
+
if (pending.mcp_auth) {
|
|
2017
|
+
await options.keychain.delete(
|
|
2018
|
+
options.mcpAdapter.service,
|
|
2019
|
+
options.account
|
|
2020
|
+
);
|
|
2021
|
+
}
|
|
2022
|
+
} else if (pending.source_backend === "legacy_file") {
|
|
2023
|
+
if (pending.auth) {
|
|
2024
|
+
await unlinkIfPresent(options.authAdapter.legacyFilePath(options.paths));
|
|
2025
|
+
}
|
|
2026
|
+
if (pending.mcp_auth) {
|
|
2027
|
+
await unlinkIfPresent(options.mcpAdapter.legacyFilePath(options.paths));
|
|
2028
|
+
}
|
|
2029
|
+
} else {
|
|
2030
|
+
const isLegacyCleanup = options.state.target_backend !== "keyring";
|
|
2031
|
+
const cleanupAuthPath = isLegacyCleanup ? options.authAdapter.legacyFilePath(options.paths) : options.authAdapter.filePath(options.paths);
|
|
2032
|
+
const cleanupMcpPath = isLegacyCleanup ? options.mcpAdapter.legacyFilePath(options.paths) : options.mcpAdapter.filePath(options.paths);
|
|
2033
|
+
if (pending.auth) {
|
|
2034
|
+
await unlinkIfPresent(cleanupAuthPath);
|
|
2035
|
+
}
|
|
2036
|
+
if (pending.mcp_auth) {
|
|
2037
|
+
await unlinkIfPresent(cleanupMcpPath);
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
const committed = buildSteadyState(
|
|
2041
|
+
options.state.target_backend,
|
|
2042
|
+
options.state.mcp_reauth_required
|
|
2043
|
+
);
|
|
2044
|
+
await writeAuthStorageState(options.paths.authStateFile, committed);
|
|
2045
|
+
return committed;
|
|
2046
|
+
};
|
|
2047
|
+
var coordinateCredentialBackendUnlocked = async (options) => {
|
|
2048
|
+
const { paths, authAdapter, mcpAdapter } = options;
|
|
2049
|
+
const keychain = options.keychain ?? new MacOsKeychainClient({ credentialsDir: paths.credentialsDir });
|
|
2050
|
+
const configured = resolveConfiguredAuthStorageMode(
|
|
2051
|
+
paths,
|
|
2052
|
+
options.storageMode
|
|
2053
|
+
);
|
|
2054
|
+
const account = keychainAccountForConfigDir(paths.configDir);
|
|
2055
|
+
await ensureStorageDirs(paths);
|
|
2056
|
+
let state = await readAuthStorageState(
|
|
2057
|
+
paths.authStateFile
|
|
2058
|
+
);
|
|
2059
|
+
if (state?.status === "migrating" && state.cleanup_pending) {
|
|
2060
|
+
state = await completePendingCleanupUnlocked({
|
|
2061
|
+
paths,
|
|
2062
|
+
state,
|
|
2063
|
+
keychain,
|
|
2064
|
+
account,
|
|
2065
|
+
authAdapter,
|
|
2066
|
+
mcpAdapter
|
|
2067
|
+
});
|
|
2068
|
+
}
|
|
2069
|
+
const migrateLegacyToCredentials = async () => {
|
|
2070
|
+
const [legacyAuth, legacyMcp] = await Promise.all([
|
|
2071
|
+
readTextIfPresent(authAdapter.legacyFilePath(paths), true),
|
|
2072
|
+
readTextIfPresent(mcpAdapter.legacyFilePath(paths), true)
|
|
2073
|
+
]);
|
|
2074
|
+
if (legacyAuth === null && legacyMcp === null) return;
|
|
2075
|
+
await runTwoPhaseMigration({
|
|
2076
|
+
stateFile: paths.authStateFile,
|
|
2077
|
+
fromBackend: state?.active_backend ?? "file",
|
|
2078
|
+
toBackend: state?.active_backend ?? "file",
|
|
2079
|
+
cleanupSourceKind: "legacy_file",
|
|
2080
|
+
authSlot: makeFileFromLegacySlot(paths, authAdapter),
|
|
2081
|
+
mcpSlot: makeFileFromLegacySlot(paths, mcpAdapter),
|
|
2082
|
+
existingMcpReauth: state?.mcp_reauth_required
|
|
2083
|
+
});
|
|
2084
|
+
state = await readAuthStorageState(paths.authStateFile);
|
|
2085
|
+
};
|
|
2086
|
+
const keyringOwnedOrInFlight = isKeyringOwnedOrTargeting(state);
|
|
2087
|
+
if (configured === "file") {
|
|
2088
|
+
await migrateLegacyToCredentials();
|
|
2089
|
+
if (keyringOwnedOrInFlight) {
|
|
2090
|
+
const probe2 = await keychain.probe();
|
|
2091
|
+
if (!probe2.available) {
|
|
2092
|
+
throw probeUnavailableError(
|
|
2093
|
+
probe2,
|
|
2094
|
+
`Cannot switch auth.storage to "file" while Keychain is unavailable: ${probe2.message}`
|
|
2095
|
+
);
|
|
2096
|
+
}
|
|
2097
|
+
await runTwoPhaseMigration({
|
|
2098
|
+
stateFile: paths.authStateFile,
|
|
2099
|
+
fromBackend: "keyring",
|
|
2100
|
+
toBackend: "file",
|
|
2101
|
+
authSlot: makeFileFromKeychainSlot(
|
|
2102
|
+
paths,
|
|
2103
|
+
keychain,
|
|
2104
|
+
account,
|
|
2105
|
+
authAdapter
|
|
169
2106
|
),
|
|
170
|
-
(
|
|
171
|
-
|
|
172
|
-
|
|
2107
|
+
mcpSlot: makeFileFromKeychainSlot(paths, keychain, account, mcpAdapter),
|
|
2108
|
+
existingMcpReauth: state?.mcp_reauth_required,
|
|
2109
|
+
commitSteadyIfEmpty: true
|
|
2110
|
+
});
|
|
2111
|
+
state = await readAuthStorageState(paths.authStateFile);
|
|
2112
|
+
} else if (!state || state.status === "migrating") {
|
|
2113
|
+
await writeAuthStorageState(
|
|
2114
|
+
paths.authStateFile,
|
|
2115
|
+
buildSteadyState("file", state?.mcp_reauth_required)
|
|
2116
|
+
);
|
|
173
2117
|
}
|
|
2118
|
+
return {
|
|
2119
|
+
configured,
|
|
2120
|
+
active: "file",
|
|
2121
|
+
state: "steady"
|
|
2122
|
+
};
|
|
174
2123
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
if (
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
ref.byte_size
|
|
2124
|
+
const probe = await keychain.probe();
|
|
2125
|
+
if (!probe.available) {
|
|
2126
|
+
if (configured === "keyring") {
|
|
2127
|
+
throw probeUnavailableError(probe);
|
|
2128
|
+
}
|
|
2129
|
+
if (keyringOwnedOrInFlight) {
|
|
2130
|
+
throw probeUnavailableError(
|
|
2131
|
+
probe,
|
|
2132
|
+
`Credentials are managed in macOS Keychain. ${probe.message}`
|
|
185
2133
|
);
|
|
186
|
-
if (bytes.length !== ref.byte_size || digest(bytes) !== ref.sha256)
|
|
187
|
-
throw new Error("Attachment original is corrupt");
|
|
188
2134
|
}
|
|
189
|
-
|
|
2135
|
+
await migrateLegacyToCredentials();
|
|
2136
|
+
return {
|
|
2137
|
+
configured,
|
|
2138
|
+
active: "file",
|
|
2139
|
+
state: "steady",
|
|
2140
|
+
fallbackReason: probe.reason
|
|
2141
|
+
};
|
|
190
2142
|
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
2143
|
+
await migrateLegacyToCredentials();
|
|
2144
|
+
const [credAuthText, credMcpText] = await Promise.all([
|
|
2145
|
+
readTextIfPresent(authAdapter.filePath(paths)),
|
|
2146
|
+
readTextIfPresent(mcpAdapter.filePath(paths))
|
|
2147
|
+
]);
|
|
2148
|
+
if (credAuthText !== null || credMcpText !== null || state?.status === "migrating") {
|
|
2149
|
+
await runTwoPhaseMigration({
|
|
2150
|
+
stateFile: paths.authStateFile,
|
|
2151
|
+
fromBackend: "file",
|
|
2152
|
+
toBackend: "keyring",
|
|
2153
|
+
authSlot: makeKeychainTargetSlot(
|
|
2154
|
+
keychain,
|
|
2155
|
+
account,
|
|
2156
|
+
authAdapter,
|
|
2157
|
+
authAdapter.filePath(paths)
|
|
2158
|
+
),
|
|
2159
|
+
mcpSlot: makeKeychainTargetSlot(
|
|
2160
|
+
keychain,
|
|
2161
|
+
account,
|
|
2162
|
+
mcpAdapter,
|
|
2163
|
+
mcpAdapter.filePath(paths)
|
|
2164
|
+
),
|
|
2165
|
+
existingMcpReauth: state?.mcp_reauth_required,
|
|
2166
|
+
commitSteadyIfEmpty: true
|
|
2167
|
+
});
|
|
2168
|
+
state = await readAuthStorageState(paths.authStateFile);
|
|
2169
|
+
} else if (state?.active_backend !== "keyring") {
|
|
2170
|
+
await writeAuthStorageState(
|
|
2171
|
+
paths.authStateFile,
|
|
2172
|
+
buildSteadyState("keyring", state?.mcp_reauth_required)
|
|
202
2173
|
);
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
2174
|
+
}
|
|
2175
|
+
return {
|
|
2176
|
+
configured,
|
|
2177
|
+
active: "keyring",
|
|
2178
|
+
state: "steady"
|
|
2179
|
+
};
|
|
2180
|
+
};
|
|
2181
|
+
var coordinateCredentialBackend = (options) => {
|
|
2182
|
+
const paths = options.paths ?? resolveStoragePaths();
|
|
2183
|
+
return withAuthStoreLock(
|
|
2184
|
+
authLockPathFor(paths.credentialsDir),
|
|
2185
|
+
() => coordinateCredentialBackendUnlocked({
|
|
2186
|
+
...options,
|
|
2187
|
+
paths
|
|
2188
|
+
}),
|
|
2189
|
+
options.lock
|
|
2190
|
+
);
|
|
2191
|
+
};
|
|
2192
|
+
var clearStoreAcrossAllLocationsUnlocked = async (options) => {
|
|
2193
|
+
const { paths, adapter } = options;
|
|
2194
|
+
const keychain = options.keychain ?? new MacOsKeychainClient({ credentialsDir: paths.credentialsDir });
|
|
2195
|
+
const account = keychainAccountForConfigDir(paths.configDir);
|
|
2196
|
+
await ensureStorageDirs(paths);
|
|
2197
|
+
await unlinkIfPresent(adapter.filePath(paths));
|
|
2198
|
+
await unlinkIfPresent(adapter.legacyFilePath(paths));
|
|
2199
|
+
const probe = await keychain.probe();
|
|
2200
|
+
if (probe.available) {
|
|
2201
|
+
await keychain.delete(adapter.service, account);
|
|
2202
|
+
} else {
|
|
2203
|
+
const storedState = await readAuthStorageState(paths.authStateFile).catch(
|
|
2204
|
+
() => null
|
|
2205
|
+
);
|
|
2206
|
+
if (isKeyringInvolved(storedState)) {
|
|
2207
|
+
throw probeUnavailableError(
|
|
2208
|
+
probe,
|
|
2209
|
+
`Cannot clear Keychain credentials while Keychain is unavailable (${probe.reason}): ${probe.message}`
|
|
213
2210
|
);
|
|
214
|
-
let count = 0;
|
|
215
|
-
while (count < bytes.length) {
|
|
216
|
-
const result = await file.read(
|
|
217
|
-
bytes,
|
|
218
|
-
count,
|
|
219
|
-
bytes.length - count,
|
|
220
|
-
start + count
|
|
221
|
-
);
|
|
222
|
-
if (!result.bytesRead)
|
|
223
|
-
throw new Error("Attachment original is corrupt");
|
|
224
|
-
count += result.bytesRead;
|
|
225
|
-
}
|
|
226
|
-
for (let block = firstBlock; block < lastBlock; block++) {
|
|
227
|
-
const beg = (block - firstBlock) * BLOCK_BYTES;
|
|
228
|
-
if (metadata.blocks?.[block] !== digest(bytes.subarray(beg, beg + BLOCK_BYTES))) {
|
|
229
|
-
throw new Error("Attachment original is corrupt");
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
return bytes.subarray(offset - start, end - start);
|
|
233
|
-
} finally {
|
|
234
|
-
await file.close();
|
|
235
2211
|
}
|
|
236
2212
|
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
2213
|
+
};
|
|
2214
|
+
var resolveDefaultTargetBackend = async (configured, keychain) => {
|
|
2215
|
+
if (configured === "file") return "file";
|
|
2216
|
+
if (configured === "keyring") return "keyring";
|
|
2217
|
+
return (await keychain.probe()).available ? "keyring" : "file";
|
|
2218
|
+
};
|
|
2219
|
+
var resolveKeepKeyringStore = async (ctx, adapter) => {
|
|
2220
|
+
const probe = await ctx.keychain.probe();
|
|
2221
|
+
if (!probe.available) {
|
|
2222
|
+
throw probeUnavailableError(
|
|
2223
|
+
probe,
|
|
2224
|
+
`Cannot keep Keychain credentials while Keychain is unavailable: ${probe.message}`
|
|
2225
|
+
);
|
|
2226
|
+
}
|
|
2227
|
+
const slot = await readKeychainSlot(
|
|
2228
|
+
ctx.keychain,
|
|
2229
|
+
adapter.service,
|
|
2230
|
+
ctx.account,
|
|
2231
|
+
adapter
|
|
2232
|
+
);
|
|
2233
|
+
const fileSlot = await readFileSlot(
|
|
2234
|
+
adapter.filePath(ctx.paths),
|
|
2235
|
+
adapter
|
|
2236
|
+
).catch(() => ({ present: true, nonEmpty: true }));
|
|
2237
|
+
const legacySlot = await readFileSlot(
|
|
2238
|
+
adapter.legacyFilePath(ctx.paths),
|
|
2239
|
+
adapter,
|
|
2240
|
+
true
|
|
2241
|
+
).catch(() => ({ present: true, nonEmpty: true }));
|
|
2242
|
+
if (!slot.present && !fileSlot.present && !legacySlot.present) {
|
|
2243
|
+
return;
|
|
2244
|
+
}
|
|
2245
|
+
if (!slot.present || !slot.nonEmpty && (fileSlot.nonEmpty || legacySlot.nonEmpty)) {
|
|
2246
|
+
throw new Error(
|
|
2247
|
+
`Cannot keep Keychain store for '${adapter.name}': Keychain has no saved credentials`
|
|
2248
|
+
);
|
|
2249
|
+
}
|
|
2250
|
+
await unlinkIfPresent(adapter.filePath(ctx.paths));
|
|
2251
|
+
await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
|
|
2252
|
+
};
|
|
2253
|
+
var resolveKeepFileStore = async (ctx, adapter) => {
|
|
2254
|
+
const slot = await readFileSlot(adapter.filePath(ctx.paths), adapter);
|
|
2255
|
+
if (!slot.present) {
|
|
2256
|
+
throw new Error(
|
|
2257
|
+
`Cannot keep file store for '${adapter.name}': ${adapter.filePath(ctx.paths)} does not exist`
|
|
2258
|
+
);
|
|
2259
|
+
}
|
|
2260
|
+
await writeFileAtomic(
|
|
2261
|
+
adapter.filePath(ctx.paths),
|
|
2262
|
+
JSON.stringify(slot.normalized, null, 2),
|
|
2263
|
+
{ mode: 384 }
|
|
2264
|
+
);
|
|
2265
|
+
await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
|
|
2266
|
+
const probe = await ctx.keychain.probe();
|
|
2267
|
+
if (probe.available) {
|
|
2268
|
+
await ctx.keychain.delete(adapter.service, ctx.account);
|
|
2269
|
+
} else if (ctx.existingState?.active_backend === "keyring") {
|
|
2270
|
+
throw probeUnavailableError(
|
|
2271
|
+
probe,
|
|
2272
|
+
`Cannot remove superseded Keychain entry while Keychain is unavailable: ${probe.message}`
|
|
2273
|
+
);
|
|
2274
|
+
}
|
|
2275
|
+
};
|
|
2276
|
+
var resolveKeepLegacyStore = async (ctx, adapter) => {
|
|
2277
|
+
const legacy = await readFileSlot(
|
|
2278
|
+
adapter.legacyFilePath(ctx.paths),
|
|
2279
|
+
adapter,
|
|
2280
|
+
true
|
|
2281
|
+
);
|
|
2282
|
+
if (!legacy.present) {
|
|
2283
|
+
throw new Error(
|
|
2284
|
+
`Cannot keep legacy store for '${adapter.name}': ${adapter.legacyFilePath(ctx.paths)} does not exist`
|
|
2285
|
+
);
|
|
2286
|
+
}
|
|
2287
|
+
const targetBackend = await resolveDefaultTargetBackend(
|
|
2288
|
+
ctx.configured,
|
|
2289
|
+
ctx.keychain
|
|
2290
|
+
);
|
|
2291
|
+
if (targetBackend === "keyring") {
|
|
2292
|
+
const probe2 = await ctx.keychain.probe();
|
|
2293
|
+
if (!probe2.available) {
|
|
2294
|
+
throw probeUnavailableError(
|
|
2295
|
+
probe2,
|
|
2296
|
+
`Cannot promote legacy store to Keychain while Keychain is unavailable: ${probe2.message}`
|
|
244
2297
|
);
|
|
245
|
-
const { ref, imageRef, blocks } = metadata;
|
|
246
|
-
if (metadata.sessionId !== sessionId || !UUID.test(metadata.batch) || ref?.attachment_id !== attachmentId)
|
|
247
|
-
return null;
|
|
248
|
-
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")
|
|
249
|
-
throw new Error("Invalid attachment metadata");
|
|
250
|
-
if (!imageRef && (!Array.isArray(blocks) || blocks.length !== Math.ceil(ref.byte_size / BLOCK_BYTES)))
|
|
251
|
-
throw new Error("Invalid attachment block index");
|
|
252
|
-
const marker = import_node_path.default.join(this.root, "committed", metadata.batch);
|
|
253
|
-
return (await (0, import_promises2.lstat)(marker)).isFile() ? metadata : null;
|
|
254
|
-
} catch (error) {
|
|
255
|
-
if (error.code === "ENOENT") return null;
|
|
256
|
-
throw error;
|
|
257
2298
|
}
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
sessionId
|
|
263
|
-
}) {
|
|
264
|
-
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)
|
|
265
|
-
throw new Error("Invalid image attachment reference");
|
|
266
|
-
const { metadata, bytes } = await this.images.read(
|
|
267
|
-
imageRef.artifact_id,
|
|
268
|
-
sessionId
|
|
2299
|
+
await ctx.keychain.set(
|
|
2300
|
+
adapter.service,
|
|
2301
|
+
ctx.account,
|
|
2302
|
+
JSON.stringify(legacy.normalized)
|
|
269
2303
|
);
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
2304
|
+
const verify = await readKeychainSlot(
|
|
2305
|
+
ctx.keychain,
|
|
2306
|
+
adapter.service,
|
|
2307
|
+
ctx.account,
|
|
2308
|
+
adapter
|
|
2309
|
+
);
|
|
2310
|
+
if (!verify.present || !canonicalJsonEqual(verify.normalized, legacy.normalized)) {
|
|
2311
|
+
throw new Error(
|
|
2312
|
+
`Failed to verify promoted '${adapter.name}' in Keychain`
|
|
2313
|
+
);
|
|
2314
|
+
}
|
|
2315
|
+
await unlinkIfPresent(adapter.filePath(ctx.paths));
|
|
2316
|
+
await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
|
|
2317
|
+
return;
|
|
2318
|
+
}
|
|
2319
|
+
await writeFileAtomic(
|
|
2320
|
+
adapter.filePath(ctx.paths),
|
|
2321
|
+
JSON.stringify(legacy.normalized, null, 2),
|
|
2322
|
+
{ mode: 384 }
|
|
2323
|
+
);
|
|
2324
|
+
await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
|
|
2325
|
+
const probe = await ctx.keychain.probe();
|
|
2326
|
+
if (probe.available) {
|
|
2327
|
+
await ctx.keychain.delete(adapter.service, ctx.account);
|
|
2328
|
+
}
|
|
2329
|
+
};
|
|
2330
|
+
var resolveCredentialConflict = async (options) => {
|
|
2331
|
+
const paths = options.paths ?? resolveStoragePaths();
|
|
2332
|
+
const keychain = options.keychain ?? new MacOsKeychainClient({ credentialsDir: paths.credentialsDir });
|
|
2333
|
+
const account = keychainAccountForConfigDir(paths.configDir);
|
|
2334
|
+
const targets = options.stores?.length ? [...new Set(options.stores)] : ["auth", "mcp_auth"];
|
|
2335
|
+
return withAuthStoreLock(
|
|
2336
|
+
authLockPathFor(paths.credentialsDir),
|
|
2337
|
+
async () => {
|
|
2338
|
+
await ensureStorageDirs(paths);
|
|
2339
|
+
const configured = resolveConfiguredAuthStorageMode(
|
|
2340
|
+
paths,
|
|
2341
|
+
options.storageMode
|
|
2342
|
+
);
|
|
2343
|
+
const existingState = await readAuthStorageState(
|
|
2344
|
+
paths.authStateFile
|
|
2345
|
+
).catch(() => null);
|
|
2346
|
+
const ctx = {
|
|
2347
|
+
paths,
|
|
2348
|
+
keychain,
|
|
2349
|
+
account,
|
|
2350
|
+
configured,
|
|
2351
|
+
existingState
|
|
2352
|
+
};
|
|
2353
|
+
const resolveOne = async (adapter) => {
|
|
2354
|
+
switch (options.strategy) {
|
|
2355
|
+
case "clear_all":
|
|
2356
|
+
await clearStoreAcrossAllLocationsUnlocked({
|
|
2357
|
+
paths,
|
|
2358
|
+
adapter,
|
|
2359
|
+
keychain
|
|
2360
|
+
});
|
|
2361
|
+
return;
|
|
2362
|
+
case "keep_keyring":
|
|
2363
|
+
await resolveKeepKeyringStore(ctx, adapter);
|
|
2364
|
+
return;
|
|
2365
|
+
case "keep_file":
|
|
2366
|
+
await resolveKeepFileStore(ctx, adapter);
|
|
2367
|
+
return;
|
|
2368
|
+
case "keep_legacy":
|
|
2369
|
+
await resolveKeepLegacyStore(ctx, adapter);
|
|
2370
|
+
return;
|
|
2371
|
+
}
|
|
2372
|
+
};
|
|
2373
|
+
for (const storeName of targets) {
|
|
2374
|
+
if (storeName === "auth") {
|
|
2375
|
+
await resolveOne(options.authAdapter);
|
|
2376
|
+
} else {
|
|
2377
|
+
await resolveOne(options.mcpAdapter);
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
const targetActive = options.strategy === "keep_keyring" ? "keyring" : options.strategy === "keep_file" ? "file" : await resolveDefaultTargetBackend(configured, keychain);
|
|
2381
|
+
await writeAuthStorageState(
|
|
2382
|
+
paths.authStateFile,
|
|
2383
|
+
buildSteadyState(targetActive, existingState?.mcp_reauth_required)
|
|
2384
|
+
);
|
|
2385
|
+
return { active: targetActive, resolvedStores: targets };
|
|
2386
|
+
},
|
|
2387
|
+
options.lock
|
|
2388
|
+
);
|
|
2389
|
+
};
|
|
2390
|
+
var inspectCredentialStorageStatus = async (options) => {
|
|
2391
|
+
const paths = options.paths ?? resolveStoragePaths();
|
|
2392
|
+
const keychain = options.keychain ?? new MacOsKeychainClient({
|
|
2393
|
+
credentialsDir: paths.credentialsDir
|
|
2394
|
+
});
|
|
2395
|
+
const configured = resolveConfiguredAuthStorageMode(
|
|
2396
|
+
paths,
|
|
2397
|
+
options.storageMode
|
|
2398
|
+
);
|
|
2399
|
+
const account = keychainAccountForConfigDir(paths.configDir);
|
|
2400
|
+
let stateCorrupt = false;
|
|
2401
|
+
let storedState = null;
|
|
2402
|
+
try {
|
|
2403
|
+
storedState = await readAuthStorageState(paths.authStateFile);
|
|
2404
|
+
} catch {
|
|
2405
|
+
stateCorrupt = true;
|
|
2406
|
+
}
|
|
2407
|
+
const mcpReauthRequired = storedState?.mcp_reauth_required ?? [];
|
|
2408
|
+
const keyringOwned = isKeyringInvolved(storedState);
|
|
2409
|
+
const shouldProbeKeychain = configured !== "file" || keyringOwned;
|
|
2410
|
+
const probe = shouldProbeKeychain ? await keychain.probe() : {
|
|
2411
|
+
available: false,
|
|
2412
|
+
reason: "keychain_unavailable",
|
|
2413
|
+
message: "file mode selected"
|
|
2414
|
+
};
|
|
2415
|
+
const inspectStore = async (adapter) => {
|
|
2416
|
+
let issue;
|
|
2417
|
+
const inspectKeychain = async () => {
|
|
2418
|
+
if (!probe.available) {
|
|
2419
|
+
if (keyringOwned || configured === "keyring") {
|
|
2420
|
+
issue = probe.reason === "keychain_locked" ? "keychain_locked" : "keychain_unavailable";
|
|
2421
|
+
}
|
|
2422
|
+
return null;
|
|
2423
|
+
}
|
|
2424
|
+
try {
|
|
2425
|
+
return await readKeychainSlot(
|
|
2426
|
+
keychain,
|
|
2427
|
+
adapter.service,
|
|
2428
|
+
account,
|
|
2429
|
+
adapter
|
|
2430
|
+
);
|
|
2431
|
+
} catch (error) {
|
|
2432
|
+
if (!(error instanceof KeychainError)) throw error;
|
|
2433
|
+
issue = error.code === "keychain_locked" || error.code === "keychain_access_denied" ? error.code : "keychain_unavailable";
|
|
2434
|
+
return null;
|
|
2435
|
+
}
|
|
2436
|
+
};
|
|
2437
|
+
const [current, legacy, native] = await Promise.all([
|
|
2438
|
+
readFileSlot(adapter.filePath(paths), adapter),
|
|
2439
|
+
readFileSlot(adapter.legacyFilePath(paths), adapter, true),
|
|
2440
|
+
inspectKeychain()
|
|
2441
|
+
]);
|
|
2442
|
+
const file = current.nonEmpty ? current : legacy;
|
|
2443
|
+
const conflict = current.nonEmpty && legacy.nonEmpty && !canonicalJsonEqual(current.normalized, legacy.normalized) || file.nonEmpty && native?.nonEmpty && !canonicalJsonEqual(file.normalized, native.normalized);
|
|
2444
|
+
return { file, native, conflict, issue };
|
|
2445
|
+
};
|
|
2446
|
+
const [auth, mcp] = await Promise.all([
|
|
2447
|
+
inspectStore(options.authAdapter).catch(() => null),
|
|
2448
|
+
inspectStore(options.mcpAdapter).catch(() => null)
|
|
2449
|
+
]);
|
|
2450
|
+
const keychainIssue = auth?.issue ?? mcp?.issue;
|
|
2451
|
+
const unreadableStores = [];
|
|
2452
|
+
if (!auth) unreadableStores.push("auth");
|
|
2453
|
+
if (!mcp) unreadableStores.push("mcp_auth");
|
|
2454
|
+
if (stateCorrupt) unreadableStores.push("storage_state");
|
|
2455
|
+
const conflictStores = [];
|
|
2456
|
+
if (auth?.conflict) conflictStores.push("auth");
|
|
2457
|
+
if (mcp?.conflict) conflictStores.push("mcp_auth");
|
|
2458
|
+
const state = stateCorrupt || conflictStores.length > 0 ? "conflict" : storedState?.status ?? "steady";
|
|
2459
|
+
const active = storedState?.active_backend ?? (auth?.file.nonEmpty || mcp?.file.nonEmpty ? "file" : probe.available || configured === "keyring" ? "keyring" : "file");
|
|
2460
|
+
const fallbackReason = configured === "auto" && active === "file" && !probe.available ? probe.reason : void 0;
|
|
2461
|
+
if (state === "steady" && auth && !auth.issue) {
|
|
2462
|
+
const snapshot = active === "file" ? auth.file : auth.native;
|
|
2463
|
+
if (snapshot?.nonEmpty) options.onReadableAuth?.(snapshot.normalized);
|
|
273
2464
|
}
|
|
2465
|
+
return {
|
|
2466
|
+
configured,
|
|
2467
|
+
active,
|
|
2468
|
+
state,
|
|
2469
|
+
...fallbackReason ? { fallbackReason } : {},
|
|
2470
|
+
mcpReauthRequired,
|
|
2471
|
+
conflictStores,
|
|
2472
|
+
unreadableStores,
|
|
2473
|
+
...keychainIssue ? { keychainIssue } : {}
|
|
2474
|
+
};
|
|
274
2475
|
};
|
|
275
2476
|
|
|
276
2477
|
// src/image-artifacts.ts
|
|
277
|
-
var
|
|
278
|
-
var
|
|
279
|
-
var
|
|
2478
|
+
var import_node_crypto7 = require("crypto");
|
|
2479
|
+
var import_promises6 = require("fs/promises");
|
|
2480
|
+
var import_node_path9 = __toESM(require("path"), 1);
|
|
280
2481
|
|
|
281
2482
|
// src/image-attachment.ts
|
|
282
2483
|
var import_image_size = require("image-size");
|
|
283
2484
|
|
|
284
2485
|
// src/image-png.ts
|
|
285
|
-
var
|
|
2486
|
+
var import_node_util2 = require("util");
|
|
286
2487
|
var import_node_zlib = require("zlib");
|
|
287
2488
|
var IMAGE_MAX_BYTES = 32 * 1024 * 1024;
|
|
288
2489
|
var IMAGE_MAX_SIDE = 12288;
|
|
289
2490
|
var IMAGE_MAX_PIXELS = 2e7;
|
|
290
|
-
var inflateAsync = (0,
|
|
2491
|
+
var inflateAsync = (0, import_node_util2.promisify)(import_node_zlib.inflate);
|
|
291
2492
|
var crcTable = Uint32Array.from({ length: 256 }, (_, n) => {
|
|
292
2493
|
let c = n;
|
|
293
2494
|
for (let i = 0; i < 8; i++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
@@ -457,22 +2658,22 @@ function parseImageMetadata(value) {
|
|
|
457
2658
|
}
|
|
458
2659
|
|
|
459
2660
|
// src/image-model-view.ts
|
|
460
|
-
var
|
|
461
|
-
var
|
|
462
|
-
var
|
|
2661
|
+
var import_node_crypto6 = require("crypto");
|
|
2662
|
+
var import_promises5 = require("fs/promises");
|
|
2663
|
+
var import_node_path8 = __toESM(require("path"), 1);
|
|
463
2664
|
var import_shared_types2 = require("@codelia/shared-types");
|
|
464
2665
|
var import_image_size2 = require("image-size");
|
|
465
2666
|
var VERSION = "jpeg-q90-444-v1";
|
|
466
|
-
var directory = (root) =>
|
|
2667
|
+
var directory = (root) => import_node_path8.default.join(root, VERSION);
|
|
467
2668
|
var errorCode = (error) => error && typeof error === "object" && "code" in error ? error.code : void 0;
|
|
468
2669
|
async function readModelView(root, original, expected) {
|
|
469
2670
|
if (expected !== void 0 && !(0, import_shared_types2.isImageModelView)(expected))
|
|
470
2671
|
throw new Error("Invalid image model view");
|
|
471
2672
|
const dir = directory(root);
|
|
472
|
-
if (!(await (0,
|
|
2673
|
+
if (!(await (0, import_promises5.lstat)(dir)).isDirectory())
|
|
473
2674
|
throw new Error("Invalid model view directory");
|
|
474
2675
|
const record2 = JSON.parse(
|
|
475
|
-
(await readImageFileBounded(
|
|
2676
|
+
(await readImageFileBounded(import_node_path8.default.join(dir, "metadata.json"), 4096)).toString()
|
|
476
2677
|
);
|
|
477
2678
|
if (!record2 || record2.original_sha256 !== original.sha256 || !(0, import_shared_types2.isImageModelView)(record2.view))
|
|
478
2679
|
throw new Error("Invalid model view metadata");
|
|
@@ -480,7 +2681,7 @@ async function readModelView(root, original, expected) {
|
|
|
480
2681
|
if (expected && (view.sha256 !== expected.sha256 || view.byte_size !== expected.byte_size))
|
|
481
2682
|
throw new Error("Image model view reference mismatch");
|
|
482
2683
|
const bytes = await readImageFileBounded(
|
|
483
|
-
|
|
2684
|
+
import_node_path8.default.join(dir, "view.jpg"),
|
|
484
2685
|
32 * 1024 * 1024
|
|
485
2686
|
);
|
|
486
2687
|
const dims = (0, import_image_size2.imageSize)(bytes);
|
|
@@ -493,7 +2694,7 @@ async function prepareModelView(root, original, bytes) {
|
|
|
493
2694
|
return void 0;
|
|
494
2695
|
let exists = true;
|
|
495
2696
|
try {
|
|
496
|
-
await (0,
|
|
2697
|
+
await (0, import_promises5.lstat)(directory(root));
|
|
497
2698
|
} catch (error) {
|
|
498
2699
|
if (errorCode(error) !== "ENOENT") throw error;
|
|
499
2700
|
exists = false;
|
|
@@ -515,27 +2716,27 @@ async function prepareModelView(root, original, bytes) {
|
|
|
515
2716
|
sha256: imageHash(jpeg),
|
|
516
2717
|
byte_size: jpeg.length
|
|
517
2718
|
};
|
|
518
|
-
const temporary =
|
|
519
|
-
await (0,
|
|
2719
|
+
const temporary = import_node_path8.default.join(root, `.model-view-${(0, import_node_crypto6.randomUUID)()}`);
|
|
2720
|
+
await (0, import_promises5.mkdir)(temporary, { mode: 448 });
|
|
520
2721
|
try {
|
|
521
|
-
await (0,
|
|
2722
|
+
await (0, import_promises5.writeFile)(import_node_path8.default.join(temporary, "view.jpg"), jpeg, {
|
|
522
2723
|
flag: "wx",
|
|
523
2724
|
mode: 384
|
|
524
2725
|
});
|
|
525
|
-
await (0,
|
|
526
|
-
|
|
2726
|
+
await (0, import_promises5.writeFile)(
|
|
2727
|
+
import_node_path8.default.join(temporary, "metadata.json"),
|
|
527
2728
|
JSON.stringify({ original_sha256: original.sha256, view }),
|
|
528
2729
|
{ flag: "wx", mode: 384 }
|
|
529
2730
|
);
|
|
530
2731
|
try {
|
|
531
|
-
await (0,
|
|
2732
|
+
await (0, import_promises5.rename)(temporary, directory(root));
|
|
532
2733
|
} catch (error) {
|
|
533
2734
|
if (!["EEXIST", "ENOTEMPTY"].includes(String(errorCode(error))))
|
|
534
2735
|
throw error;
|
|
535
2736
|
}
|
|
536
2737
|
return (await readModelView(root, original)).view;
|
|
537
2738
|
} finally {
|
|
538
|
-
await (0,
|
|
2739
|
+
await (0, import_promises5.rm)(temporary, { recursive: true, force: true });
|
|
539
2740
|
}
|
|
540
2741
|
}
|
|
541
2742
|
|
|
@@ -552,7 +2753,7 @@ var ImageArtifactStore = class {
|
|
|
552
2753
|
const dimensions = mediaType === "image/png" ? await validateImagePng(bytes) : validateImageAttachment(bytes, "image/jpeg");
|
|
553
2754
|
if (mediaType === "image/jpeg" && (bytes.at(-2) !== 255 || bytes.at(-1) !== 217))
|
|
554
2755
|
throw new Error("Invalid generated JPEG: missing end marker");
|
|
555
|
-
const artifact_id = `codelia-image-${(0,
|
|
2756
|
+
const artifact_id = `codelia-image-${(0, import_node_crypto7.randomUUID)()}`;
|
|
556
2757
|
const metadata = parseImageMetadata({
|
|
557
2758
|
...provenance,
|
|
558
2759
|
...dimensions,
|
|
@@ -568,7 +2769,7 @@ var ImageArtifactStore = class {
|
|
|
568
2769
|
return metadata;
|
|
569
2770
|
}
|
|
570
2771
|
async saveAttachment(bytes, mediaType, {
|
|
571
|
-
artifactId = `codelia-image-${(0,
|
|
2772
|
+
artifactId = `codelia-image-${(0, import_node_crypto7.randomUUID)()}`,
|
|
572
2773
|
ownerSessionId
|
|
573
2774
|
} = {}) {
|
|
574
2775
|
if (!ID2.test(artifactId)) throw new Error("Invalid image artifact id");
|
|
@@ -602,50 +2803,50 @@ var ImageArtifactStore = class {
|
|
|
602
2803
|
const { metadata } = await this.read(ref.artifact_id, sessionId);
|
|
603
2804
|
if (metadata.kind !== "attachment" || metadata.sha256 !== ref.sha256 || metadata.byte_size !== ref.byte_size)
|
|
604
2805
|
throw new Error("Image attachment rollback reference mismatch");
|
|
605
|
-
await (0,
|
|
2806
|
+
await (0, import_promises6.rm)(import_node_path9.default.join(this.root, ref.artifact_id), { recursive: true });
|
|
606
2807
|
}
|
|
607
2808
|
async persist(bytes, metadata, ownerSessionId) {
|
|
608
|
-
await (0,
|
|
609
|
-
const temporary =
|
|
610
|
-
await (0,
|
|
2809
|
+
await (0, import_promises6.mkdir)(this.root, { recursive: true, mode: 448 });
|
|
2810
|
+
const temporary = import_node_path9.default.join(this.root, `.pending-${(0, import_node_crypto7.randomUUID)()}`);
|
|
2811
|
+
await (0, import_promises6.mkdir)(temporary, { mode: 448 });
|
|
611
2812
|
try {
|
|
612
|
-
await (0,
|
|
613
|
-
|
|
2813
|
+
await (0, import_promises6.writeFile)(
|
|
2814
|
+
import_node_path9.default.join(temporary, imageOriginalFilename(metadata.media_type)),
|
|
614
2815
|
bytes,
|
|
615
2816
|
{
|
|
616
2817
|
flag: "wx",
|
|
617
2818
|
mode: 384
|
|
618
2819
|
}
|
|
619
2820
|
);
|
|
620
|
-
await (0,
|
|
621
|
-
|
|
2821
|
+
await (0, import_promises6.writeFile)(
|
|
2822
|
+
import_node_path9.default.join(temporary, "metadata.json"),
|
|
622
2823
|
JSON.stringify({
|
|
623
2824
|
...metadata,
|
|
624
2825
|
...ownerSessionId !== void 0 ? { owner_session_id: ownerSessionId } : {}
|
|
625
2826
|
}),
|
|
626
2827
|
{ flag: "wx", mode: 384 }
|
|
627
2828
|
);
|
|
628
|
-
await (0,
|
|
2829
|
+
await (0, import_promises6.rename)(temporary, import_node_path9.default.join(this.root, metadata.artifact_id));
|
|
629
2830
|
} catch (error) {
|
|
630
|
-
await (0,
|
|
2831
|
+
await (0, import_promises6.rm)(temporary, { recursive: true, force: true });
|
|
631
2832
|
throw error;
|
|
632
2833
|
}
|
|
633
2834
|
}
|
|
634
2835
|
async read(artifactId, sessionId = this.getSessionId?.() ?? null) {
|
|
635
2836
|
if (!ID2.test(artifactId)) throw new Error("Invalid image artifact id");
|
|
636
2837
|
try {
|
|
637
|
-
const dir =
|
|
638
|
-
if (!(await (0,
|
|
2838
|
+
const dir = import_node_path9.default.join(this.root, artifactId);
|
|
2839
|
+
if (!(await (0, import_promises6.lstat)(dir)).isDirectory())
|
|
639
2840
|
throw new Error("Invalid artifact directory");
|
|
640
2841
|
const rawMetadata = JSON.parse(
|
|
641
|
-
(await readImageFileBounded(
|
|
2842
|
+
(await readImageFileBounded(import_node_path9.default.join(dir, "metadata.json"), 16384)).toString()
|
|
642
2843
|
);
|
|
643
2844
|
const metadata = parseImageMetadata(rawMetadata);
|
|
644
2845
|
const owner = rawMetadata.owner_session_id;
|
|
645
2846
|
if (owner !== void 0 && (metadata.kind !== "attachment" || typeof owner !== "string" || !owner || owner !== sessionId))
|
|
646
2847
|
throw new Error("Image artifact owned by another session");
|
|
647
2848
|
const bytes = await readImageFileBounded(
|
|
648
|
-
|
|
2849
|
+
import_node_path9.default.join(dir, imageOriginalFilename(metadata.media_type)),
|
|
649
2850
|
IMAGE_MAX_BYTES
|
|
650
2851
|
);
|
|
651
2852
|
const dims = metadata.kind === "attachment" ? validateImageAttachment(bytes, metadata.media_type) : metadata.media_type === "image/png" ? await validateImagePng(bytes) : validateImageAttachment(bytes, "image/jpeg");
|
|
@@ -674,124 +2875,110 @@ var ImageArtifactStore = class {
|
|
|
674
2875
|
};
|
|
675
2876
|
if (original) return ref;
|
|
676
2877
|
const model_view = await prepareModelView(
|
|
677
|
-
|
|
2878
|
+
import_node_path9.default.join(this.root, artifactId),
|
|
678
2879
|
metadata,
|
|
679
2880
|
bytes
|
|
680
2881
|
);
|
|
681
2882
|
return model_view ? { ...ref, model_view } : ref;
|
|
682
2883
|
}
|
|
683
|
-
async resolve(ref) {
|
|
684
|
-
const { metadata, bytes } = await this.read(ref.artifact_id);
|
|
685
|
-
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)
|
|
686
|
-
throw new Error("Image artifact reference mismatch");
|
|
687
|
-
const input = ref.model_view !== void 0 ? await readModelView(
|
|
688
|
-
|
|
689
|
-
metadata,
|
|
690
|
-
ref.model_view
|
|
691
|
-
) : { bytes, view: metadata };
|
|
692
|
-
return {
|
|
693
|
-
type: "image_url",
|
|
694
|
-
image_url: {
|
|
695
|
-
url: `data:${input.view.media_type};base64,${input.bytes.toString("base64")}`,
|
|
696
|
-
media_type: input.view.media_type
|
|
697
|
-
}
|
|
698
|
-
};
|
|
699
|
-
}
|
|
700
|
-
};
|
|
701
|
-
|
|
702
|
-
// src/mcp-auth-store.ts
|
|
703
|
-
var import_node_fs3 = require("fs");
|
|
704
|
-
|
|
705
|
-
// src/paths.ts
|
|
706
|
-
var import_promises5 = require("fs/promises");
|
|
707
|
-
var import_node_os = __toESM(require("os"), 1);
|
|
708
|
-
var import_node_path4 = __toESM(require("path"), 1);
|
|
709
|
-
var DEFAULT_ROOT_DIR = ".codelia";
|
|
710
|
-
var LAYOUT_ENV = "CODELIA_LAYOUT";
|
|
711
|
-
var XDG_DIR_NAME = "codelia";
|
|
712
|
-
var CONFIG_FILENAME = "config.json";
|
|
713
|
-
var AUTH_FILENAME = "auth.json";
|
|
714
|
-
var MCP_AUTH_FILENAME = "mcp-auth.json";
|
|
715
|
-
var PROJECTS_FILENAME = "projects.json";
|
|
716
|
-
var CACHE_DIRNAME = "cache";
|
|
717
|
-
var TOOL_OUTPUT_CACHE_DIRNAME = "tool-output";
|
|
718
|
-
var SESSIONS_DIRNAME = "sessions";
|
|
719
|
-
var LOGS_DIRNAME = "logs";
|
|
720
|
-
function resolveStoragePaths(options = {}) {
|
|
721
|
-
if (options.rootOverride) {
|
|
722
|
-
return buildHomeLayout(options.rootOverride);
|
|
723
|
-
}
|
|
724
|
-
const layoutValue = options.layout ?? process.env[LAYOUT_ENV];
|
|
725
|
-
const layout = normalizeLayout(layoutValue);
|
|
726
|
-
if (layout === "xdg") {
|
|
727
|
-
return buildXdgLayout();
|
|
728
|
-
}
|
|
729
|
-
return buildHomeLayout(defaultHomeRoot());
|
|
730
|
-
}
|
|
731
|
-
async function ensureStorageDirs(paths) {
|
|
732
|
-
await Promise.all([
|
|
733
|
-
(0, import_promises5.mkdir)(paths.configDir, { recursive: true }),
|
|
734
|
-
(0, import_promises5.mkdir)(paths.cacheDir, { recursive: true }),
|
|
735
|
-
(0, import_promises5.mkdir)(paths.toolOutputCacheDir, { recursive: true }),
|
|
736
|
-
(0, import_promises5.mkdir)(paths.sessionsDir, { recursive: true }),
|
|
737
|
-
(0, import_promises5.mkdir)(paths.logsDir, { recursive: true })
|
|
738
|
-
]);
|
|
739
|
-
}
|
|
740
|
-
function normalizeLayout(value) {
|
|
741
|
-
if (value && value.toLowerCase() === "xdg") return "xdg";
|
|
742
|
-
return "home";
|
|
743
|
-
}
|
|
744
|
-
function defaultHomeRoot() {
|
|
745
|
-
return import_node_path4.default.join(import_node_os.default.homedir(), DEFAULT_ROOT_DIR);
|
|
746
|
-
}
|
|
747
|
-
function buildHomeLayout(root) {
|
|
748
|
-
const configDir = root;
|
|
749
|
-
return {
|
|
750
|
-
root,
|
|
751
|
-
configDir,
|
|
752
|
-
configFile: import_node_path4.default.join(configDir, CONFIG_FILENAME),
|
|
753
|
-
authFile: import_node_path4.default.join(configDir, AUTH_FILENAME),
|
|
754
|
-
mcpAuthFile: import_node_path4.default.join(configDir, MCP_AUTH_FILENAME),
|
|
755
|
-
projectsFile: import_node_path4.default.join(configDir, PROJECTS_FILENAME),
|
|
756
|
-
cacheDir: import_node_path4.default.join(root, CACHE_DIRNAME),
|
|
757
|
-
toolOutputCacheDir: import_node_path4.default.join(
|
|
758
|
-
root,
|
|
759
|
-
CACHE_DIRNAME,
|
|
760
|
-
TOOL_OUTPUT_CACHE_DIRNAME
|
|
761
|
-
),
|
|
762
|
-
sessionsDir: import_node_path4.default.join(root, SESSIONS_DIRNAME),
|
|
763
|
-
logsDir: import_node_path4.default.join(root, LOGS_DIRNAME)
|
|
764
|
-
};
|
|
765
|
-
}
|
|
766
|
-
function buildXdgLayout() {
|
|
767
|
-
const home = import_node_os.default.homedir();
|
|
768
|
-
const configRoot = process.env.XDG_CONFIG_HOME ?? import_node_path4.default.join(home, ".config");
|
|
769
|
-
const cacheRoot = process.env.XDG_CACHE_HOME ?? import_node_path4.default.join(home, ".cache");
|
|
770
|
-
const stateRoot = process.env.XDG_STATE_HOME ?? import_node_path4.default.join(home, ".local", "state");
|
|
771
|
-
const configDir = import_node_path4.default.join(configRoot, XDG_DIR_NAME);
|
|
772
|
-
const cacheDir = import_node_path4.default.join(cacheRoot, XDG_DIR_NAME);
|
|
773
|
-
const stateDir = import_node_path4.default.join(stateRoot, XDG_DIR_NAME);
|
|
774
|
-
return {
|
|
775
|
-
root: stateDir,
|
|
776
|
-
configDir,
|
|
777
|
-
configFile: import_node_path4.default.join(configDir, CONFIG_FILENAME),
|
|
778
|
-
authFile: import_node_path4.default.join(configDir, AUTH_FILENAME),
|
|
779
|
-
mcpAuthFile: import_node_path4.default.join(configDir, MCP_AUTH_FILENAME),
|
|
780
|
-
projectsFile: import_node_path4.default.join(configDir, PROJECTS_FILENAME),
|
|
781
|
-
cacheDir,
|
|
782
|
-
toolOutputCacheDir: import_node_path4.default.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
|
|
783
|
-
sessionsDir: import_node_path4.default.join(stateDir, SESSIONS_DIRNAME),
|
|
784
|
-
logsDir: import_node_path4.default.join(stateDir, LOGS_DIRNAME)
|
|
785
|
-
};
|
|
786
|
-
}
|
|
2884
|
+
async resolve(ref) {
|
|
2885
|
+
const { metadata, bytes } = await this.read(ref.artifact_id);
|
|
2886
|
+
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)
|
|
2887
|
+
throw new Error("Image artifact reference mismatch");
|
|
2888
|
+
const input = ref.model_view !== void 0 ? await readModelView(
|
|
2889
|
+
import_node_path9.default.join(this.root, ref.artifact_id),
|
|
2890
|
+
metadata,
|
|
2891
|
+
ref.model_view
|
|
2892
|
+
) : { bytes, view: metadata };
|
|
2893
|
+
return {
|
|
2894
|
+
type: "image_url",
|
|
2895
|
+
image_url: {
|
|
2896
|
+
url: `data:${input.view.media_type};base64,${input.bytes.toString("base64")}`,
|
|
2897
|
+
media_type: input.view.media_type
|
|
2898
|
+
}
|
|
2899
|
+
};
|
|
2900
|
+
}
|
|
2901
|
+
};
|
|
787
2902
|
|
|
788
2903
|
// src/mcp-auth-store.ts
|
|
789
|
-
var
|
|
790
|
-
var
|
|
791
|
-
var
|
|
2904
|
+
var import_node_fs9 = require("fs");
|
|
2905
|
+
var MCP_AUTH_VERSION = 2;
|
|
2906
|
+
var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2907
|
+
var pickString = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
|
|
792
2908
|
var pickNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
2909
|
+
var canonicalizeMcpUri = (raw) => {
|
|
2910
|
+
const parsed = new URL(raw.trim());
|
|
2911
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
2912
|
+
throw new Error(`Unsupported MCP URI scheme: ${parsed.protocol}`);
|
|
2913
|
+
}
|
|
2914
|
+
parsed.hash = "";
|
|
2915
|
+
parsed.hostname = parsed.hostname.toLowerCase();
|
|
2916
|
+
if (parsed.protocol === "http:" && parsed.port === "80" || parsed.protocol === "https:" && parsed.port === "443") {
|
|
2917
|
+
parsed.port = "";
|
|
2918
|
+
}
|
|
2919
|
+
return parsed.toString();
|
|
2920
|
+
};
|
|
2921
|
+
var deriveMcpIssuer = (options) => {
|
|
2922
|
+
if (options.issuer?.trim()) return options.issuer;
|
|
2923
|
+
const endpoint = options.tokenUrl ?? options.authorizationUrl;
|
|
2924
|
+
if (!endpoint?.trim()) return void 0;
|
|
2925
|
+
try {
|
|
2926
|
+
return new URL(canonicalizeMcpUri(endpoint)).origin;
|
|
2927
|
+
} catch {
|
|
2928
|
+
return void 0;
|
|
2929
|
+
}
|
|
2930
|
+
};
|
|
2931
|
+
var buildMcpAuthBinding = (options) => {
|
|
2932
|
+
const resource_uri = canonicalizeMcpUri(options.resourceUri);
|
|
2933
|
+
const issuer = deriveMcpIssuer({
|
|
2934
|
+
issuer: options.issuer,
|
|
2935
|
+
tokenUrl: options.tokenEndpoint
|
|
2936
|
+
});
|
|
2937
|
+
const token_endpoint = options.tokenEndpoint?.trim() ? canonicalizeMcpUri(options.tokenEndpoint) : void 0;
|
|
2938
|
+
const client_id = pickString(options.clientId);
|
|
2939
|
+
return {
|
|
2940
|
+
resource_uri,
|
|
2941
|
+
...issuer ? { issuer } : {},
|
|
2942
|
+
...token_endpoint ? { token_endpoint } : {},
|
|
2943
|
+
...client_id ? { client_id } : {}
|
|
2944
|
+
};
|
|
2945
|
+
};
|
|
2946
|
+
var mcpAuthBindingMatches = (stored, resolved) => {
|
|
2947
|
+
let storedResource;
|
|
2948
|
+
let resolvedResource;
|
|
2949
|
+
try {
|
|
2950
|
+
storedResource = canonicalizeMcpUri(stored.resource_uri);
|
|
2951
|
+
resolvedResource = canonicalizeMcpUri(resolved.resource_uri);
|
|
2952
|
+
} catch {
|
|
2953
|
+
return false;
|
|
2954
|
+
}
|
|
2955
|
+
if (storedResource !== resolvedResource) return false;
|
|
2956
|
+
if (stored.issuer) {
|
|
2957
|
+
const normStored = deriveMcpIssuer({ issuer: stored.issuer });
|
|
2958
|
+
const normResolved = resolved.issuer ? deriveMcpIssuer({ issuer: resolved.issuer }) : resolved.token_endpoint ? deriveMcpIssuer({ tokenUrl: resolved.token_endpoint }) : void 0;
|
|
2959
|
+
if (!normStored || !normResolved || normStored !== normResolved) {
|
|
2960
|
+
return false;
|
|
2961
|
+
}
|
|
2962
|
+
}
|
|
2963
|
+
if (stored.token_endpoint) {
|
|
2964
|
+
if (!resolved.token_endpoint) return false;
|
|
2965
|
+
try {
|
|
2966
|
+
if (canonicalizeMcpUri(stored.token_endpoint) !== canonicalizeMcpUri(resolved.token_endpoint)) {
|
|
2967
|
+
return false;
|
|
2968
|
+
}
|
|
2969
|
+
} catch {
|
|
2970
|
+
return false;
|
|
2971
|
+
}
|
|
2972
|
+
}
|
|
2973
|
+
if (stored.client_id) {
|
|
2974
|
+
if (!resolved.client_id || stored.client_id !== resolved.client_id) {
|
|
2975
|
+
return false;
|
|
2976
|
+
}
|
|
2977
|
+
}
|
|
2978
|
+
return true;
|
|
2979
|
+
};
|
|
793
2980
|
var normalizeTokens = (value) => {
|
|
794
|
-
if (!
|
|
2981
|
+
if (!isRecord4(value)) return null;
|
|
795
2982
|
const accessToken = pickString(value.access_token);
|
|
796
2983
|
if (!accessToken) return null;
|
|
797
2984
|
return {
|
|
@@ -804,59 +2991,245 @@ var normalizeTokens = (value) => {
|
|
|
804
2991
|
...pickString(value.client_secret) ? { client_secret: pickString(value.client_secret) } : {}
|
|
805
2992
|
};
|
|
806
2993
|
};
|
|
2994
|
+
var normalizeBinding = (value) => {
|
|
2995
|
+
if (!isRecord4(value)) return null;
|
|
2996
|
+
const rawResource = pickString(value.resource_uri);
|
|
2997
|
+
if (!rawResource) return null;
|
|
2998
|
+
try {
|
|
2999
|
+
return buildMcpAuthBinding({
|
|
3000
|
+
resourceUri: rawResource,
|
|
3001
|
+
issuer: pickString(value.issuer),
|
|
3002
|
+
tokenEndpoint: pickString(value.token_endpoint),
|
|
3003
|
+
clientId: pickString(value.client_id)
|
|
3004
|
+
});
|
|
3005
|
+
} catch {
|
|
3006
|
+
return null;
|
|
3007
|
+
}
|
|
3008
|
+
};
|
|
3009
|
+
var parseMcpAuthDocument = (text) => {
|
|
3010
|
+
const parsed = JSON.parse(text);
|
|
3011
|
+
if (!isRecord4(parsed)) {
|
|
3012
|
+
throw new Error("mcp-auth.json has unsupported format");
|
|
3013
|
+
}
|
|
3014
|
+
if (parsed.version === 1) {
|
|
3015
|
+
const serversRaw2 = isRecord4(parsed.servers) ? parsed.servers : {};
|
|
3016
|
+
const droppedLegacyServers = Object.entries(serversRaw2).filter(([, entry]) => normalizeTokens(entry) !== null).map(([id2]) => id2).sort();
|
|
3017
|
+
return {
|
|
3018
|
+
normalized: { version: MCP_AUTH_VERSION, servers: {} },
|
|
3019
|
+
sourceVersion: 1,
|
|
3020
|
+
droppedLegacyServers
|
|
3021
|
+
};
|
|
3022
|
+
}
|
|
3023
|
+
if (parsed.version !== MCP_AUTH_VERSION) {
|
|
3024
|
+
throw new Error("mcp-auth.json has unsupported version");
|
|
3025
|
+
}
|
|
3026
|
+
if (parsed.servers !== void 0 && !isRecord4(parsed.servers)) {
|
|
3027
|
+
throw new Error("mcp-auth.json v2 has invalid servers map");
|
|
3028
|
+
}
|
|
3029
|
+
const serversRaw = isRecord4(parsed.servers) ? parsed.servers : {};
|
|
3030
|
+
const servers = {};
|
|
3031
|
+
for (const [id2, entry] of Object.entries(serversRaw)) {
|
|
3032
|
+
if (!isRecord4(entry)) {
|
|
3033
|
+
throw new Error(`mcp-auth.json v2 has invalid entry for '${id2}'`);
|
|
3034
|
+
}
|
|
3035
|
+
const binding = normalizeBinding(entry.binding);
|
|
3036
|
+
if (!binding) {
|
|
3037
|
+
throw new Error(`mcp-auth.json v2 has invalid binding for '${id2}'`);
|
|
3038
|
+
}
|
|
3039
|
+
const tokens = normalizeTokens(entry.tokens);
|
|
3040
|
+
if (!tokens) {
|
|
3041
|
+
throw new Error(`mcp-auth.json v2 has invalid tokens for '${id2}'`);
|
|
3042
|
+
}
|
|
3043
|
+
servers[id2] = { binding, tokens };
|
|
3044
|
+
}
|
|
3045
|
+
return {
|
|
3046
|
+
normalized: { version: MCP_AUTH_VERSION, servers },
|
|
3047
|
+
sourceVersion: 2,
|
|
3048
|
+
droppedLegacyServers: []
|
|
3049
|
+
};
|
|
3050
|
+
};
|
|
3051
|
+
var mcpAuthStoreAdapter = {
|
|
3052
|
+
name: "mcp_auth",
|
|
3053
|
+
service: CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
|
|
3054
|
+
filePath: (paths) => paths.mcpAuthFile,
|
|
3055
|
+
legacyFilePath: (paths) => paths.legacyMcpAuthFile,
|
|
3056
|
+
empty: () => ({ version: MCP_AUTH_VERSION, servers: {} }),
|
|
3057
|
+
isNonEmpty: (doc) => Object.keys(doc.servers).length > 0,
|
|
3058
|
+
parse: (text) => {
|
|
3059
|
+
const parsed = parseMcpAuthDocument(text);
|
|
3060
|
+
return {
|
|
3061
|
+
normalized: parsed.normalized,
|
|
3062
|
+
sourceVersion: parsed.sourceVersion,
|
|
3063
|
+
extraWarnings: parsed.droppedLegacyServers
|
|
3064
|
+
};
|
|
3065
|
+
}
|
|
3066
|
+
};
|
|
3067
|
+
var readTextIfPresent2 = async (filePath) => {
|
|
3068
|
+
if (!await verifyWindowsCredentialFileAcl(filePath)) return null;
|
|
3069
|
+
try {
|
|
3070
|
+
return await import_node_fs9.promises.readFile(filePath, "utf8");
|
|
3071
|
+
} catch (error) {
|
|
3072
|
+
if (error?.code === "ENOENT") return null;
|
|
3073
|
+
throw error;
|
|
3074
|
+
}
|
|
3075
|
+
};
|
|
807
3076
|
var McpAuthStore = class {
|
|
808
3077
|
paths;
|
|
809
|
-
|
|
3078
|
+
lockOptions;
|
|
3079
|
+
storageMode;
|
|
3080
|
+
keychain;
|
|
3081
|
+
constructor(paths, options) {
|
|
810
3082
|
this.paths = paths ?? resolveStoragePaths();
|
|
3083
|
+
this.lockOptions = options?.lock;
|
|
3084
|
+
this.storageMode = options?.storageMode;
|
|
3085
|
+
this.keychain = options?.keychain ?? new MacOsKeychainClient({ credentialsDir: this.paths.credentialsDir });
|
|
3086
|
+
}
|
|
3087
|
+
lockPath() {
|
|
3088
|
+
return authLockPathFor(this.paths.credentialsDir);
|
|
3089
|
+
}
|
|
3090
|
+
keychainAccount() {
|
|
3091
|
+
return keychainAccountForConfigDir(this.paths.configDir);
|
|
3092
|
+
}
|
|
3093
|
+
resolveBackendUnlocked() {
|
|
3094
|
+
return coordinateCredentialBackendUnlocked({
|
|
3095
|
+
paths: this.paths,
|
|
3096
|
+
storageMode: this.storageMode,
|
|
3097
|
+
keychain: this.keychain,
|
|
3098
|
+
authAdapter: providerAuthStoreAdapter,
|
|
3099
|
+
mcpAdapter: mcpAuthStoreAdapter
|
|
3100
|
+
});
|
|
811
3101
|
}
|
|
812
|
-
async
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
3102
|
+
async recordDroppedLegacyServers(dropped) {
|
|
3103
|
+
if (!dropped.length) return;
|
|
3104
|
+
await ensureStorageDirs(this.paths);
|
|
3105
|
+
const existing = await readAuthStorageState(this.paths.authStateFile).catch(
|
|
3106
|
+
() => null
|
|
3107
|
+
);
|
|
3108
|
+
const merged = [
|
|
3109
|
+
.../* @__PURE__ */ new Set([...existing?.mcp_reauth_required ?? [], ...dropped])
|
|
3110
|
+
].sort();
|
|
3111
|
+
await writeAuthStorageState(this.paths.authStateFile, {
|
|
3112
|
+
version: 1,
|
|
3113
|
+
status: "steady",
|
|
3114
|
+
active_backend: existing?.active_backend ?? "file",
|
|
3115
|
+
mcp_reauth_required: merged
|
|
3116
|
+
});
|
|
3117
|
+
}
|
|
3118
|
+
async readFromBackend(active) {
|
|
3119
|
+
if (active === "keyring") {
|
|
3120
|
+
const text2 = await this.keychain.get(
|
|
3121
|
+
CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
|
|
3122
|
+
this.keychainAccount()
|
|
3123
|
+
);
|
|
3124
|
+
if (text2 === null) {
|
|
834
3125
|
return { version: MCP_AUTH_VERSION, servers: {} };
|
|
835
3126
|
}
|
|
836
|
-
|
|
3127
|
+
const parsed2 = parseMcpAuthDocument(text2);
|
|
3128
|
+
if (parsed2.sourceVersion === 1) {
|
|
3129
|
+
await this.writeToBackend("keyring", parsed2.normalized);
|
|
3130
|
+
await this.recordDroppedLegacyServers(parsed2.droppedLegacyServers);
|
|
3131
|
+
}
|
|
3132
|
+
return parsed2.normalized;
|
|
837
3133
|
}
|
|
3134
|
+
const text = await readTextIfPresent2(this.paths.mcpAuthFile);
|
|
3135
|
+
if (text === null) {
|
|
3136
|
+
return { version: MCP_AUTH_VERSION, servers: {} };
|
|
3137
|
+
}
|
|
3138
|
+
const parsed = parseMcpAuthDocument(text);
|
|
3139
|
+
if (parsed.sourceVersion === 1) {
|
|
3140
|
+
await this.writeToBackend("file", parsed.normalized);
|
|
3141
|
+
await this.recordDroppedLegacyServers(parsed.droppedLegacyServers);
|
|
3142
|
+
}
|
|
3143
|
+
return parsed.normalized;
|
|
838
3144
|
}
|
|
839
|
-
async
|
|
3145
|
+
async clearReauthenticatedServers(authenticatedServers) {
|
|
3146
|
+
if (!authenticatedServers.length) return;
|
|
3147
|
+
const existing = await readAuthStorageState(this.paths.authStateFile).catch(
|
|
3148
|
+
() => null
|
|
3149
|
+
);
|
|
3150
|
+
if (!existing?.mcp_reauth_required?.length) return;
|
|
3151
|
+
const authenticated = new Set(authenticatedServers);
|
|
3152
|
+
const remaining = existing.mcp_reauth_required.filter(
|
|
3153
|
+
(id2) => !authenticated.has(id2)
|
|
3154
|
+
);
|
|
3155
|
+
if (remaining.length === existing.mcp_reauth_required.length) return;
|
|
3156
|
+
const { mcp_reauth_required: _prev, ...rest } = existing;
|
|
3157
|
+
await writeAuthStorageState(this.paths.authStateFile, {
|
|
3158
|
+
...rest,
|
|
3159
|
+
...remaining.length ? { mcp_reauth_required: remaining } : {}
|
|
3160
|
+
});
|
|
3161
|
+
}
|
|
3162
|
+
async writeToBackend(active, auth) {
|
|
3163
|
+
if (active === "keyring") {
|
|
3164
|
+
await this.keychain.set(
|
|
3165
|
+
CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
|
|
3166
|
+
this.keychainAccount(),
|
|
3167
|
+
JSON.stringify(auth)
|
|
3168
|
+
);
|
|
3169
|
+
await this.clearReauthenticatedServers(Object.keys(auth.servers));
|
|
3170
|
+
return;
|
|
3171
|
+
}
|
|
840
3172
|
await ensureStorageDirs(this.paths);
|
|
841
3173
|
const data = JSON.stringify(auth, null, 2);
|
|
842
|
-
await
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
3174
|
+
await writeFileAtomic(this.paths.mcpAuthFile, data, { mode: 384 });
|
|
3175
|
+
await this.clearReauthenticatedServers(Object.keys(auth.servers));
|
|
3176
|
+
}
|
|
3177
|
+
/**
|
|
3178
|
+
* Load normalized v2 MCP auth from the active backend (macOS Keychain or
|
|
3179
|
+
* protected `credentials/` file), running safe two-phase migration if needed.
|
|
3180
|
+
*/
|
|
3181
|
+
async load() {
|
|
3182
|
+
return withAuthStoreLock(
|
|
3183
|
+
this.lockPath(),
|
|
3184
|
+
async () => {
|
|
3185
|
+
const resolved = await this.resolveBackendUnlocked();
|
|
3186
|
+
return this.readFromBackend(resolved.active);
|
|
3187
|
+
},
|
|
3188
|
+
this.lockOptions
|
|
3189
|
+
);
|
|
3190
|
+
}
|
|
3191
|
+
/**
|
|
3192
|
+
* Reload, mutate, and atomically save under the interprocess auth lock.
|
|
3193
|
+
* Skips writing if the serialized document did not change.
|
|
3194
|
+
*/
|
|
3195
|
+
update(mutate) {
|
|
3196
|
+
return withAuthStoreLock(
|
|
3197
|
+
this.lockPath(),
|
|
3198
|
+
async () => {
|
|
3199
|
+
const resolved = await this.resolveBackendUnlocked();
|
|
3200
|
+
const auth = await this.readFromBackend(resolved.active);
|
|
3201
|
+
const before = JSON.stringify(auth);
|
|
3202
|
+
const result = await mutate(auth);
|
|
3203
|
+
if (JSON.stringify(auth) !== before) {
|
|
3204
|
+
await this.writeToBackend(resolved.active, auth);
|
|
3205
|
+
}
|
|
3206
|
+
return result;
|
|
3207
|
+
},
|
|
3208
|
+
this.lockOptions
|
|
3209
|
+
);
|
|
3210
|
+
}
|
|
3211
|
+
async save(auth) {
|
|
3212
|
+
await withAuthStoreLock(
|
|
3213
|
+
this.lockPath(),
|
|
3214
|
+
async () => {
|
|
3215
|
+
const resolved = await this.resolveBackendUnlocked();
|
|
3216
|
+
await this.writeToBackend(resolved.active, auth);
|
|
3217
|
+
},
|
|
3218
|
+
this.lockOptions
|
|
3219
|
+
);
|
|
847
3220
|
}
|
|
848
3221
|
};
|
|
849
3222
|
|
|
850
3223
|
// src/process-identity.ts
|
|
851
|
-
var
|
|
852
|
-
var
|
|
3224
|
+
var import_node_child_process3 = require("child_process");
|
|
3225
|
+
var import_node_fs10 = require("fs");
|
|
853
3226
|
var getProcessIdentity = async (pid, options = {}) => {
|
|
854
3227
|
if (!Number.isSafeInteger(pid) || pid <= 0) return null;
|
|
855
3228
|
if (process.platform === "linux") {
|
|
856
3229
|
try {
|
|
857
3230
|
const [stat, boot] = await Promise.all([
|
|
858
|
-
|
|
859
|
-
|
|
3231
|
+
import_node_fs10.promises.readFile(`/proc/${pid}/stat`, "utf8"),
|
|
3232
|
+
import_node_fs10.promises.readFile("/proc/sys/kernel/random/boot_id", "utf8")
|
|
860
3233
|
]);
|
|
861
3234
|
return `${boot.trim()}:${stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]}`;
|
|
862
3235
|
} catch {
|
|
@@ -865,7 +3238,7 @@ var getProcessIdentity = async (pid, options = {}) => {
|
|
|
865
3238
|
}
|
|
866
3239
|
if (process.platform === "darwin")
|
|
867
3240
|
return new Promise((resolve) => {
|
|
868
|
-
(0,
|
|
3241
|
+
(0, import_node_child_process3.execFile)(
|
|
869
3242
|
"/bin/ps",
|
|
870
3243
|
["-p", String(pid), "-o", "lstart="],
|
|
871
3244
|
{
|
|
@@ -880,76 +3253,206 @@ var getProcessIdentity = async (pid, options = {}) => {
|
|
|
880
3253
|
};
|
|
881
3254
|
|
|
882
3255
|
// src/projects-store.ts
|
|
883
|
-
var
|
|
884
|
-
var
|
|
885
|
-
var
|
|
886
|
-
var
|
|
887
|
-
var import_promises6 = require("timers/promises");
|
|
3256
|
+
var import_node_crypto8 = require("crypto");
|
|
3257
|
+
var import_node_fs12 = require("fs");
|
|
3258
|
+
var import_node_path11 = __toESM(require("path"), 1);
|
|
3259
|
+
var import_promises7 = require("timers/promises");
|
|
888
3260
|
var import_shared_types3 = require("@codelia/shared-types");
|
|
889
3261
|
|
|
890
|
-
// src/
|
|
891
|
-
var
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
3262
|
+
// src/user-storage-boundary.ts
|
|
3263
|
+
var import_node_fs11 = require("fs");
|
|
3264
|
+
var import_node_os3 = __toESM(require("os"), 1);
|
|
3265
|
+
var import_node_path10 = __toESM(require("path"), 1);
|
|
3266
|
+
var isWithinPath = (root, target) => {
|
|
3267
|
+
const relative = import_node_path10.default.relative(root, target);
|
|
3268
|
+
return !import_node_path10.default.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${import_node_path10.default.sep}`);
|
|
3269
|
+
};
|
|
3270
|
+
var canonicalPathOrResolvedSync = (target) => {
|
|
3271
|
+
const resolved = import_node_path10.default.resolve(target);
|
|
3272
|
+
try {
|
|
3273
|
+
return (0, import_node_fs11.realpathSync)(resolved);
|
|
3274
|
+
} catch (error) {
|
|
3275
|
+
if (error.code !== "ENOENT") return resolved;
|
|
3276
|
+
const parent = import_node_path10.default.dirname(resolved);
|
|
3277
|
+
if (parent === resolved) return resolved;
|
|
3278
|
+
return import_node_path10.default.join(
|
|
3279
|
+
canonicalPathOrResolvedSync(parent),
|
|
3280
|
+
import_node_path10.default.basename(resolved)
|
|
3281
|
+
);
|
|
3282
|
+
}
|
|
3283
|
+
};
|
|
3284
|
+
var isSameConfigFilePath = (leftPath, rightPath) => {
|
|
3285
|
+
const left = canonicalPathOrResolvedSync(leftPath);
|
|
3286
|
+
const right = canonicalPathOrResolvedSync(rightPath);
|
|
3287
|
+
const samePath = process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
|
|
3288
|
+
if (samePath) return true;
|
|
3289
|
+
const leftStat = (0, import_node_fs11.statSync)(left, { bigint: true, throwIfNoEntry: false });
|
|
3290
|
+
const rightStat = (0, import_node_fs11.statSync)(right, { bigint: true, throwIfNoEntry: false });
|
|
3291
|
+
return !!leftStat && !!rightStat && leftStat.ino !== 0n && leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
|
|
3292
|
+
};
|
|
3293
|
+
var isCanonicalHomeWorkspaceSync = (workspace) => {
|
|
3294
|
+
try {
|
|
3295
|
+
const home = import_node_path10.default.resolve(import_node_os3.default.homedir());
|
|
3296
|
+
return (0, import_node_fs11.realpathSync)(workspace) === (0, import_node_fs11.realpathSync)(home);
|
|
3297
|
+
} catch {
|
|
3298
|
+
return false;
|
|
3299
|
+
}
|
|
3300
|
+
};
|
|
3301
|
+
var isOwnedAncestor = (info, uid) => info.isDirectory() && (info.uid === 0 || info.uid === uid) && ((info.mode & 18) === 0 || (info.mode & 512) !== 0);
|
|
3302
|
+
var isOwnedPrivateDirectory = (info, uid) => info.isDirectory() && info.uid === BigInt(uid) && (info.mode & 0o022n) === 0n;
|
|
3303
|
+
var verifyOwnedAncestors = async (directory2, uid, errorMessage = "unsafe_projects_policy_ancestor") => {
|
|
3304
|
+
let child = directory2;
|
|
3305
|
+
while (child !== import_node_path10.default.dirname(child)) {
|
|
3306
|
+
child = import_node_path10.default.dirname(child);
|
|
3307
|
+
const info = await import_node_fs11.promises.stat(child);
|
|
3308
|
+
if (!isOwnedAncestor(info, uid)) throw new Error(errorMessage);
|
|
3309
|
+
}
|
|
3310
|
+
};
|
|
3311
|
+
var verifyOwnedAncestorsSync = (directory2, uid, errorMessage = "unsafe_projects_policy_ancestor") => {
|
|
3312
|
+
let child = directory2;
|
|
3313
|
+
while (child !== import_node_path10.default.dirname(child)) {
|
|
3314
|
+
child = import_node_path10.default.dirname(child);
|
|
3315
|
+
const info = (0, import_node_fs11.statSync)(child);
|
|
3316
|
+
if (!isOwnedAncestor(info, uid)) throw new Error(errorMessage);
|
|
3317
|
+
}
|
|
3318
|
+
};
|
|
3319
|
+
var evaluateHomeReservedStorage = ({
|
|
3320
|
+
workspace,
|
|
3321
|
+
configured,
|
|
3322
|
+
resolved,
|
|
3323
|
+
relativePath,
|
|
3324
|
+
reservedOverride,
|
|
3325
|
+
home,
|
|
3326
|
+
canonicalHome,
|
|
3327
|
+
errorMessage,
|
|
3328
|
+
redirectErrorMessage
|
|
3329
|
+
}) => {
|
|
3330
|
+
const apparentHome = isWithinPath(home, configured) ? home : canonicalHome;
|
|
3331
|
+
const base = resolveDefaultHomeConfigDir(apparentHome);
|
|
3332
|
+
const expectedReserved = import_node_path10.default.resolve(
|
|
3333
|
+
reservedOverride ?? (relativePath ? import_node_path10.default.join(base, relativePath) : base)
|
|
3334
|
+
);
|
|
3335
|
+
if (workspace !== canonicalHome || configured !== expectedReserved || !isWithinPath(apparentHome, configured))
|
|
3336
|
+
throw new Error(errorMessage);
|
|
3337
|
+
const expectedResolved = import_node_path10.default.join(
|
|
3338
|
+
canonicalHome,
|
|
3339
|
+
import_node_path10.default.relative(apparentHome, configured)
|
|
3340
|
+
);
|
|
3341
|
+
if (resolved !== expectedResolved) throw new Error(redirectErrorMessage);
|
|
3342
|
+
};
|
|
3343
|
+
var verifyUserStorageLocation = async ({
|
|
3344
|
+
workspace,
|
|
3345
|
+
configured,
|
|
3346
|
+
resolved,
|
|
3347
|
+
relativePath = "",
|
|
3348
|
+
reservedOverride,
|
|
3349
|
+
errorMessage = "unsafe_projects_policy_path",
|
|
3350
|
+
redirectErrorMessage = errorMessage
|
|
3351
|
+
}) => {
|
|
3352
|
+
const resolvedConfigured = import_node_path10.default.resolve(configured);
|
|
3353
|
+
if (!isWithinPath(workspace, resolvedConfigured) && !isWithinPath(workspace, resolved))
|
|
3354
|
+
return { insideWorkspace: false };
|
|
3355
|
+
const home = import_node_path10.default.resolve(import_node_os3.default.homedir());
|
|
3356
|
+
let canonicalHome;
|
|
3357
|
+
try {
|
|
3358
|
+
canonicalHome = await import_node_fs11.promises.realpath(home);
|
|
3359
|
+
} catch {
|
|
3360
|
+
throw new Error(errorMessage);
|
|
3361
|
+
}
|
|
3362
|
+
evaluateHomeReservedStorage({
|
|
3363
|
+
workspace,
|
|
3364
|
+
configured: resolvedConfigured,
|
|
3365
|
+
resolved,
|
|
3366
|
+
relativePath,
|
|
3367
|
+
reservedOverride,
|
|
3368
|
+
home,
|
|
3369
|
+
canonicalHome,
|
|
3370
|
+
errorMessage,
|
|
3371
|
+
redirectErrorMessage
|
|
3372
|
+
});
|
|
3373
|
+
return { insideWorkspace: true };
|
|
3374
|
+
};
|
|
3375
|
+
var verifyUserStorageLocationSync = ({
|
|
3376
|
+
workspace,
|
|
3377
|
+
configured,
|
|
3378
|
+
resolved,
|
|
3379
|
+
relativePath = "",
|
|
3380
|
+
reservedOverride,
|
|
3381
|
+
errorMessage = "unsafe_projects_policy_path",
|
|
3382
|
+
redirectErrorMessage = errorMessage
|
|
3383
|
+
}) => {
|
|
3384
|
+
const resolvedConfigured = import_node_path10.default.resolve(configured);
|
|
3385
|
+
if (!isWithinPath(workspace, resolvedConfigured) && !isWithinPath(workspace, resolved))
|
|
3386
|
+
return { insideWorkspace: false };
|
|
3387
|
+
const home = import_node_path10.default.resolve(import_node_os3.default.homedir());
|
|
3388
|
+
let canonicalHome;
|
|
3389
|
+
try {
|
|
3390
|
+
canonicalHome = (0, import_node_fs11.realpathSync)(home);
|
|
3391
|
+
} catch {
|
|
3392
|
+
throw new Error(errorMessage);
|
|
3393
|
+
}
|
|
3394
|
+
evaluateHomeReservedStorage({
|
|
3395
|
+
workspace,
|
|
3396
|
+
configured: resolvedConfigured,
|
|
3397
|
+
resolved,
|
|
3398
|
+
relativePath,
|
|
3399
|
+
reservedOverride,
|
|
3400
|
+
home,
|
|
3401
|
+
canonicalHome,
|
|
3402
|
+
errorMessage,
|
|
3403
|
+
redirectErrorMessage
|
|
3404
|
+
});
|
|
3405
|
+
return { insideWorkspace: true };
|
|
3406
|
+
};
|
|
3407
|
+
var isTrustedGlobalConfigLocationSync = (workingDir, configPath) => {
|
|
3408
|
+
try {
|
|
3409
|
+
const workspace = (0, import_node_fs11.realpathSync)(workingDir);
|
|
3410
|
+
const configured = import_node_path10.default.resolve(configPath);
|
|
3411
|
+
const resolved = canonicalPathOrResolvedSync(configured);
|
|
3412
|
+
const { insideWorkspace } = verifyUserStorageLocationSync({
|
|
3413
|
+
workspace,
|
|
3414
|
+
configured,
|
|
3415
|
+
resolved,
|
|
3416
|
+
relativePath: "config.json",
|
|
3417
|
+
errorMessage: "untrusted_global_config_path"
|
|
3418
|
+
});
|
|
3419
|
+
if (!insideWorkspace) return true;
|
|
3420
|
+
if (typeof process.geteuid !== "function") return false;
|
|
3421
|
+
const uid = process.geteuid();
|
|
3422
|
+
const dir = import_node_path10.default.dirname(resolved);
|
|
3423
|
+
if (!isOwnedPrivateDirectory((0, import_node_fs11.lstatSync)(dir, { bigint: true }), uid))
|
|
3424
|
+
return false;
|
|
3425
|
+
verifyOwnedAncestorsSync(dir, uid, "untrusted_global_config_path");
|
|
3426
|
+
const fileInfo = (0, import_node_fs11.lstatSync)(resolved, {
|
|
3427
|
+
bigint: true,
|
|
3428
|
+
throwIfNoEntry: false
|
|
3429
|
+
});
|
|
3430
|
+
if (fileInfo && (!fileInfo.isFile() || fileInfo.nlink !== 1n || fileInfo.uid !== BigInt(uid) || (fileInfo.mode & 0o022n) !== 0n))
|
|
3431
|
+
return false;
|
|
3432
|
+
return true;
|
|
3433
|
+
} catch {
|
|
3434
|
+
return false;
|
|
910
3435
|
}
|
|
911
|
-
const betterSqliteSpecifier = "better-sqlite3";
|
|
912
|
-
const betterSqliteModule = await import(betterSqliteSpecifier);
|
|
913
|
-
const BetterSqlite3 = betterSqliteModule.default ?? betterSqliteModule;
|
|
914
|
-
const db = new BetterSqlite3(filename);
|
|
915
|
-
return {
|
|
916
|
-
close: () => db.close(),
|
|
917
|
-
exec: (sql) => {
|
|
918
|
-
db.exec(sql);
|
|
919
|
-
},
|
|
920
|
-
run: (sql, params = []) => {
|
|
921
|
-
db.prepare(sql).run(...params);
|
|
922
|
-
},
|
|
923
|
-
get: (sql, params = []) => {
|
|
924
|
-
const row = db.prepare(sql).get(...params);
|
|
925
|
-
return row ?? void 0;
|
|
926
|
-
},
|
|
927
|
-
all: (sql, params = []) => db.prepare(sql).all(...params)
|
|
928
|
-
};
|
|
929
3436
|
};
|
|
930
3437
|
|
|
931
3438
|
// src/projects-store.ts
|
|
932
|
-
var
|
|
933
|
-
var within = (root, target) => {
|
|
934
|
-
const relative = import_node_path5.default.relative(root, target);
|
|
935
|
-
return !import_node_path5.default.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${import_node_path5.default.sep}`);
|
|
936
|
-
};
|
|
3439
|
+
var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
937
3440
|
var missing = (error) => error.code === "ENOENT";
|
|
938
|
-
var lockFileFor = (file) =>
|
|
939
|
-
var
|
|
3441
|
+
var lockFileFor = (file) => import_node_path11.default.join(import_node_path11.default.dirname(file), ".projects-policy-lock.sqlite");
|
|
3442
|
+
var lstatIfPresent2 = (file) => import_node_fs12.promises.lstat(file).catch((error) => {
|
|
940
3443
|
if (!missing(error)) throw error;
|
|
941
3444
|
return void 0;
|
|
942
3445
|
});
|
|
943
|
-
var
|
|
944
|
-
const info = await
|
|
3446
|
+
var verifyLockFile2 = async (file) => {
|
|
3447
|
+
const info = await lstatIfPresent2(file);
|
|
945
3448
|
if (info && (!info.isFile() || info.uid !== process.geteuid?.() || info.size === 0 || (info.mode & 18) !== 0))
|
|
946
3449
|
throw new Error("unsafe_projects_policy_lock");
|
|
947
3450
|
};
|
|
948
3451
|
var initializeUpdateLock = async (lockPath) => {
|
|
949
|
-
if (await
|
|
950
|
-
const temporary = `${lockPath}.${(0,
|
|
3452
|
+
if (await lstatIfPresent2(lockPath)) return;
|
|
3453
|
+
const temporary = `${lockPath}.${(0, import_node_crypto8.randomUUID)()}.tmp`;
|
|
951
3454
|
try {
|
|
952
|
-
const file = await
|
|
3455
|
+
const file = await import_node_fs12.promises.open(temporary, "wx", 384);
|
|
953
3456
|
await file.close();
|
|
954
3457
|
const db = await openSqlite(temporary);
|
|
955
3458
|
try {
|
|
@@ -958,17 +3461,17 @@ var initializeUpdateLock = async (lockPath) => {
|
|
|
958
3461
|
db.close();
|
|
959
3462
|
}
|
|
960
3463
|
try {
|
|
961
|
-
await
|
|
3464
|
+
await import_node_fs12.promises.link(temporary, lockPath);
|
|
962
3465
|
} catch (error) {
|
|
963
3466
|
if (error.code !== "EEXIST") throw error;
|
|
964
3467
|
}
|
|
965
3468
|
} finally {
|
|
966
|
-
await
|
|
3469
|
+
await import_node_fs12.promises.unlink(temporary).catch(() => void 0);
|
|
967
3470
|
}
|
|
968
3471
|
};
|
|
969
3472
|
var openUpdateLock = async (lockPath) => {
|
|
970
3473
|
await initializeUpdateLock(lockPath);
|
|
971
|
-
await
|
|
3474
|
+
await verifyLockFile2(lockPath);
|
|
972
3475
|
const db = await openSqlite(lockPath);
|
|
973
3476
|
const deadline = performance.now() + 1e3;
|
|
974
3477
|
try {
|
|
@@ -980,7 +3483,7 @@ var openUpdateLock = async (lockPath) => {
|
|
|
980
3483
|
} catch (error) {
|
|
981
3484
|
if (error.code !== "SQLITE_BUSY" || performance.now() >= deadline)
|
|
982
3485
|
throw error;
|
|
983
|
-
await (0,
|
|
3486
|
+
await (0, import_promises7.setTimeout)(20);
|
|
984
3487
|
}
|
|
985
3488
|
}
|
|
986
3489
|
} catch (error) {
|
|
@@ -988,17 +3491,8 @@ var openUpdateLock = async (lockPath) => {
|
|
|
988
3491
|
throw error;
|
|
989
3492
|
}
|
|
990
3493
|
};
|
|
991
|
-
var verifyAncestors = async (directory2, uid) => {
|
|
992
|
-
let child = directory2;
|
|
993
|
-
while (child !== import_node_path5.default.dirname(child)) {
|
|
994
|
-
child = import_node_path5.default.dirname(child);
|
|
995
|
-
const info = await import_node_fs5.promises.stat(child);
|
|
996
|
-
if (!info.isDirectory() || info.uid !== 0 && info.uid !== uid || (info.mode & 18) !== 0 && (info.mode & 512) === 0)
|
|
997
|
-
throw new Error("unsafe_projects_policy_ancestor");
|
|
998
|
-
}
|
|
999
|
-
};
|
|
1000
3494
|
var normalizeProjectPolicy = (value, field) => {
|
|
1001
|
-
if (!
|
|
3495
|
+
if (!isRecord5(value)) throw new Error(`${field} must be an object`);
|
|
1002
3496
|
const { approval_mode, sandbox_mode, protected_paths, trust_project_allows } = value;
|
|
1003
3497
|
if (trust_project_allows !== void 0 && typeof trust_project_allows !== "boolean")
|
|
1004
3498
|
throw new Error(`${field}.trust_project_allows must be boolean`);
|
|
@@ -1006,7 +3500,7 @@ var normalizeProjectPolicy = (value, field) => {
|
|
|
1006
3500
|
const sandboxMode = (0, import_shared_types3.parseSandboxMode)(sandbox_mode);
|
|
1007
3501
|
const toolAllows = value.remembered_tool_allows;
|
|
1008
3502
|
if (toolAllows !== void 0 && (!Array.isArray(toolAllows) || toolAllows.some(
|
|
1009
|
-
(rule) => !
|
|
3503
|
+
(rule) => !isRecord5(rule) || Object.keys(rule).length !== 1 || typeof rule.tool !== "string" || !/^[a-z][a-z0-9_]*$/.test(rule.tool)
|
|
1010
3504
|
)))
|
|
1011
3505
|
throw new Error(
|
|
1012
3506
|
`${field}.remembered_tool_allows must contain tool-only rules`
|
|
@@ -1016,7 +3510,7 @@ var normalizeProjectPolicy = (value, field) => {
|
|
|
1016
3510
|
if (sandbox_mode !== void 0 && !sandboxMode)
|
|
1017
3511
|
throw new Error(`${field}.sandbox_mode is invalid`);
|
|
1018
3512
|
if (protected_paths !== void 0 && (!Array.isArray(protected_paths) || protected_paths.some(
|
|
1019
|
-
(entry) => typeof entry !== "string" || !
|
|
3513
|
+
(entry) => typeof entry !== "string" || !import_node_path11.default.isAbsolute(entry) || [...entry].some(
|
|
1020
3514
|
(character) => character < " " || character === "\x7F"
|
|
1021
3515
|
)
|
|
1022
3516
|
)))
|
|
@@ -1030,7 +3524,7 @@ var normalizeProjectPolicy = (value, field) => {
|
|
|
1030
3524
|
};
|
|
1031
3525
|
};
|
|
1032
3526
|
var normalizeProjectsPolicyFile = (value) => {
|
|
1033
|
-
if (!
|
|
3527
|
+
if (!isRecord5(value)) {
|
|
1034
3528
|
throw new Error("projects policy must be an object");
|
|
1035
3529
|
}
|
|
1036
3530
|
if (value.version !== 1) {
|
|
@@ -1045,7 +3539,7 @@ var normalizeProjectsPolicyFile = (value) => {
|
|
|
1045
3539
|
if (Object.keys(entry).length) normalized.default = entry;
|
|
1046
3540
|
}
|
|
1047
3541
|
if (value.projects !== void 0) {
|
|
1048
|
-
if (!
|
|
3542
|
+
if (!isRecord5(value.projects))
|
|
1049
3543
|
throw new Error("projects policy projects must be an object");
|
|
1050
3544
|
const entries2 = Object.entries(value.projects).flatMap(([key, value2]) => {
|
|
1051
3545
|
const entry = normalizeProjectPolicy(
|
|
@@ -1059,16 +3553,16 @@ var normalizeProjectsPolicyFile = (value) => {
|
|
|
1059
3553
|
return normalized;
|
|
1060
3554
|
};
|
|
1061
3555
|
var atomicWriteFile = async (filePath, content) => {
|
|
1062
|
-
const dirPath =
|
|
1063
|
-
const fileName =
|
|
1064
|
-
const tempPath =
|
|
3556
|
+
const dirPath = import_node_path11.default.dirname(filePath);
|
|
3557
|
+
const fileName = import_node_path11.default.basename(filePath);
|
|
3558
|
+
const tempPath = import_node_path11.default.join(
|
|
1065
3559
|
dirPath,
|
|
1066
3560
|
`.${fileName}.${process.pid}.${Date.now()}.tmp`
|
|
1067
3561
|
);
|
|
1068
|
-
await
|
|
1069
|
-
await
|
|
3562
|
+
await import_node_fs12.promises.writeFile(tempPath, content, { mode: 384 });
|
|
3563
|
+
await import_node_fs12.promises.rename(tempPath, filePath);
|
|
1070
3564
|
if (process.platform !== "win32") {
|
|
1071
|
-
await
|
|
3565
|
+
await import_node_fs12.promises.chmod(filePath, 384);
|
|
1072
3566
|
}
|
|
1073
3567
|
};
|
|
1074
3568
|
var ProjectsPolicyStore = class {
|
|
@@ -1079,67 +3573,72 @@ var ProjectsPolicyStore = class {
|
|
|
1079
3573
|
getFilePath() {
|
|
1080
3574
|
return this.paths.projectsFile;
|
|
1081
3575
|
}
|
|
1082
|
-
async verifyWorkspaceLocation(workspace, configured, file, access, reservedFile = resolveStoragePaths().projectsFile) {
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
3576
|
+
async verifyWorkspaceLocation(workspace, configured, file, access, relativePath = "projects.json", reservedFile = resolveStoragePaths().projectsFile) {
|
|
3577
|
+
await verifyUserStorageLocation({
|
|
3578
|
+
workspace,
|
|
3579
|
+
configured,
|
|
3580
|
+
resolved: file,
|
|
3581
|
+
relativePath,
|
|
3582
|
+
// Preserve existing read compatibility for owner-verified custom
|
|
3583
|
+
// XDG_CONFIG_HOME paths inside ~ so stored readonly/protected_paths are
|
|
3584
|
+
// never silently dropped, while restricting writes to default layouts.
|
|
3585
|
+
...access === "read" ? { reservedOverride: reservedFile } : {},
|
|
3586
|
+
errorMessage: "unsafe_projects_policy_path"
|
|
3587
|
+
});
|
|
1090
3588
|
}
|
|
1091
|
-
async trustedPath(workspace, access, configured =
|
|
3589
|
+
async trustedPath(workspace, access, configured = import_node_path11.default.resolve(this.paths.projectsFile), relativePath = "projects.json", reservedFile = resolveStoragePaths().projectsFile) {
|
|
1092
3590
|
const uid = process.geteuid?.();
|
|
1093
3591
|
if (uid === void 0) throw new Error("unsafe_projects_policy_path");
|
|
1094
|
-
const destination =
|
|
3592
|
+
const destination = import_node_path11.default.dirname(configured);
|
|
1095
3593
|
let ancestor = destination;
|
|
1096
3594
|
let canonical;
|
|
1097
3595
|
for (; ; ) {
|
|
1098
3596
|
try {
|
|
1099
|
-
canonical = await
|
|
3597
|
+
canonical = await import_node_fs12.promises.realpath(ancestor);
|
|
1100
3598
|
break;
|
|
1101
3599
|
} catch (error) {
|
|
1102
|
-
if (!missing(error) || ancestor ===
|
|
1103
|
-
if (await
|
|
3600
|
+
if (!missing(error) || ancestor === import_node_path11.default.dirname(ancestor)) throw error;
|
|
3601
|
+
if (await lstatIfPresent2(ancestor))
|
|
1104
3602
|
throw new Error("unsafe_projects_policy_path");
|
|
1105
|
-
ancestor =
|
|
3603
|
+
ancestor = import_node_path11.default.dirname(ancestor);
|
|
1106
3604
|
}
|
|
1107
3605
|
}
|
|
1108
|
-
const directory2 =
|
|
3606
|
+
const directory2 = import_node_path11.default.join(
|
|
1109
3607
|
canonical,
|
|
1110
|
-
|
|
3608
|
+
import_node_path11.default.relative(ancestor, destination)
|
|
1111
3609
|
);
|
|
1112
|
-
const file =
|
|
3610
|
+
const file = import_node_path11.default.join(directory2, import_node_path11.default.basename(configured));
|
|
1113
3611
|
await this.verifyWorkspaceLocation(
|
|
1114
3612
|
workspace,
|
|
1115
3613
|
configured,
|
|
1116
3614
|
file,
|
|
1117
3615
|
access,
|
|
3616
|
+
relativePath,
|
|
1118
3617
|
reservedFile
|
|
1119
3618
|
);
|
|
1120
|
-
const owner = await
|
|
3619
|
+
const owner = await import_node_fs12.promises.stat(canonical);
|
|
1121
3620
|
if (!owner.isDirectory() || owner.uid !== uid || (owner.mode & 18) !== 0)
|
|
1122
3621
|
throw new Error("unsafe_projects_policy_directory");
|
|
1123
|
-
await
|
|
1124
|
-
if (ancestor !== canonical) await
|
|
3622
|
+
await verifyOwnedAncestors(canonical, uid);
|
|
3623
|
+
if (ancestor !== canonical) await verifyOwnedAncestors(ancestor, uid);
|
|
1125
3624
|
if (access !== "read")
|
|
1126
|
-
await
|
|
3625
|
+
await import_node_fs12.promises.access(canonical, import_node_fs12.constants.W_OK | import_node_fs12.constants.X_OK);
|
|
1127
3626
|
if (access === "create" && ancestor !== destination) {
|
|
1128
|
-
await
|
|
1129
|
-
if (await
|
|
3627
|
+
await import_node_fs12.promises.mkdir(directory2, { recursive: true, mode: 448 });
|
|
3628
|
+
if (await import_node_fs12.promises.realpath(directory2) !== directory2)
|
|
1130
3629
|
throw new Error("unsafe_projects_policy_directory");
|
|
1131
3630
|
return this.trustedPath(workspace, "write");
|
|
1132
3631
|
}
|
|
1133
3632
|
return file;
|
|
1134
3633
|
}
|
|
1135
3634
|
async readUserFile(file, owner) {
|
|
1136
|
-
const info = await
|
|
3635
|
+
const info = await lstatIfPresent2(file);
|
|
1137
3636
|
if (!info) return void 0;
|
|
1138
3637
|
if (!info.isFile() || info.nlink !== 1)
|
|
1139
3638
|
throw new Error("unsafe_projects_policy_file");
|
|
1140
|
-
const handle = await
|
|
3639
|
+
const handle = await import_node_fs12.promises.open(
|
|
1141
3640
|
file,
|
|
1142
|
-
|
|
3641
|
+
import_node_fs12.constants.O_RDONLY | (import_node_fs12.constants.O_NOFOLLOW ?? 0) | (import_node_fs12.constants.O_NONBLOCK ?? 0)
|
|
1143
3642
|
);
|
|
1144
3643
|
try {
|
|
1145
3644
|
const current = await handle.stat();
|
|
@@ -1157,7 +3656,8 @@ var ProjectsPolicyStore = class {
|
|
|
1157
3656
|
const file = await this.trustedPath(
|
|
1158
3657
|
workspace,
|
|
1159
3658
|
"read",
|
|
1160
|
-
|
|
3659
|
+
import_node_path11.default.resolve(configured),
|
|
3660
|
+
"config.json",
|
|
1161
3661
|
this.paths.configFile
|
|
1162
3662
|
);
|
|
1163
3663
|
return this.readUserFile(file, uid);
|
|
@@ -1174,21 +3674,21 @@ var ProjectsPolicyStore = class {
|
|
|
1174
3674
|
return this.readPolicyFile(file, owner);
|
|
1175
3675
|
}
|
|
1176
3676
|
async hasUnverifiableProtectedPaths(workspace) {
|
|
1177
|
-
const configured =
|
|
1178
|
-
const canonicalParent = await
|
|
1179
|
-
const file =
|
|
3677
|
+
const configured = import_node_path11.default.resolve(this.paths.projectsFile);
|
|
3678
|
+
const canonicalParent = await import_node_fs12.promises.realpath(import_node_path11.default.dirname(configured));
|
|
3679
|
+
const file = import_node_path11.default.join(canonicalParent, import_node_path11.default.basename(configured));
|
|
1180
3680
|
await this.verifyWorkspaceLocation(workspace, configured, file, "read");
|
|
1181
3681
|
const { normalized: policy } = await this.readPolicyFile(file, null);
|
|
1182
3682
|
return Boolean(
|
|
1183
3683
|
policy.default?.protected_paths?.length || Object.entries(policy.projects ?? {}).some(
|
|
1184
|
-
([root, entry]) => entry.protected_paths?.length &&
|
|
3684
|
+
([root, entry]) => entry.protected_paths?.length && import_node_path11.default.isAbsolute(root) && import_node_path11.default.relative(workspace, root) === ""
|
|
1185
3685
|
)
|
|
1186
3686
|
);
|
|
1187
3687
|
}
|
|
1188
3688
|
async loadUserOwned(workspace, { strict = false } = {}) {
|
|
1189
3689
|
let hasUnverifiablePaths;
|
|
1190
3690
|
try {
|
|
1191
|
-
if (strict && !await
|
|
3691
|
+
if (strict && !await lstatIfPresent2(this.paths.projectsFile))
|
|
1192
3692
|
return null;
|
|
1193
3693
|
if (strict && process.geteuid?.() === void 0) {
|
|
1194
3694
|
hasUnverifiablePaths = await this.hasUnverifiableProtectedPaths(workspace);
|
|
@@ -1208,7 +3708,7 @@ var ProjectsPolicyStore = class {
|
|
|
1208
3708
|
async verifyProjectModeWritable(workspace) {
|
|
1209
3709
|
const file = await this.trustedPath(workspace, "write");
|
|
1210
3710
|
await this.readTrusted(file);
|
|
1211
|
-
await
|
|
3711
|
+
await verifyLockFile2(lockFileFor(file));
|
|
1212
3712
|
}
|
|
1213
3713
|
/** Merge into a private user policy while other runtimes are excluded. */
|
|
1214
3714
|
async writeProjectMode(workspace, mode) {
|
|
@@ -1247,7 +3747,7 @@ var ProjectsPolicyStore = class {
|
|
|
1247
3747
|
async updateProject(workspace, patch, verify) {
|
|
1248
3748
|
const file = await this.trustedPath(workspace, "create");
|
|
1249
3749
|
const lock = await openUpdateLock(lockFileFor(file));
|
|
1250
|
-
const temporary = `${file}.${(0,
|
|
3750
|
+
const temporary = `${file}.${(0, import_node_crypto8.randomUUID)()}.tmp`;
|
|
1251
3751
|
try {
|
|
1252
3752
|
const { raw: policy } = await this.readTrusted(file);
|
|
1253
3753
|
const projects = policy.projects;
|
|
@@ -1263,26 +3763,26 @@ var ProjectsPolicyStore = class {
|
|
|
1263
3763
|
[workspace]: { ...projects?.[workspace], ...changes }
|
|
1264
3764
|
}
|
|
1265
3765
|
};
|
|
1266
|
-
await
|
|
3766
|
+
await import_node_fs12.promises.writeFile(temporary, `${JSON.stringify(next, null, 2)}
|
|
1267
3767
|
`, {
|
|
1268
3768
|
mode: 384,
|
|
1269
3769
|
flag: "wx"
|
|
1270
3770
|
});
|
|
1271
|
-
await
|
|
3771
|
+
await import_node_fs12.promises.chmod(temporary, 384);
|
|
1272
3772
|
if (await this.trustedPath(workspace, "write") !== file)
|
|
1273
3773
|
throw new Error("unsafe_projects_policy_path");
|
|
1274
3774
|
verify?.();
|
|
1275
|
-
await
|
|
3775
|
+
await import_node_fs12.promises.rename(temporary, file);
|
|
1276
3776
|
} finally {
|
|
1277
3777
|
lock.close();
|
|
1278
|
-
await
|
|
3778
|
+
await import_node_fs12.promises.unlink(temporary).catch(() => void 0);
|
|
1279
3779
|
}
|
|
1280
3780
|
}
|
|
1281
3781
|
async load(canonicalPath) {
|
|
1282
3782
|
try {
|
|
1283
|
-
const handle = await
|
|
3783
|
+
const handle = await import_node_fs12.promises.open(
|
|
1284
3784
|
canonicalPath ?? this.paths.projectsFile,
|
|
1285
|
-
canonicalPath ?
|
|
3785
|
+
canonicalPath ? import_node_fs12.constants.O_RDONLY | (import_node_fs12.constants.O_NOFOLLOW ?? 0) | (import_node_fs12.constants.O_NONBLOCK ?? 0) : "r"
|
|
1286
3786
|
);
|
|
1287
3787
|
let parsed;
|
|
1288
3788
|
try {
|
|
@@ -1316,55 +3816,55 @@ var ProjectsPolicyStore = class {
|
|
|
1316
3816
|
};
|
|
1317
3817
|
|
|
1318
3818
|
// src/session-store.ts
|
|
1319
|
-
var
|
|
1320
|
-
var
|
|
3819
|
+
var import_node_fs15 = require("fs");
|
|
3820
|
+
var import_node_path14 = __toESM(require("path"), 1);
|
|
1321
3821
|
|
|
1322
3822
|
// src/run-log-paths.ts
|
|
1323
|
-
var
|
|
1324
|
-
var
|
|
3823
|
+
var import_node_crypto9 = require("crypto");
|
|
3824
|
+
var import_node_path12 = __toESM(require("path"), 1);
|
|
1325
3825
|
var runDatePath = (startedAt) => {
|
|
1326
3826
|
const date = new Date(startedAt);
|
|
1327
3827
|
if (!Number.isFinite(date.getTime()))
|
|
1328
3828
|
throw new Error("Invalid run start time");
|
|
1329
|
-
return [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].map((part, index) => String(part).padStart(index === 0 ? 4 : 2, "0")).join(
|
|
3829
|
+
return [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].map((part, index) => String(part).padStart(index === 0 ? 4 : 2, "0")).join(import_node_path12.default.sep);
|
|
1330
3830
|
};
|
|
1331
3831
|
var validateRunLogId = (id2) => {
|
|
1332
3832
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(id2))
|
|
1333
3833
|
throw new Error("Invalid run/session log id");
|
|
1334
3834
|
return id2;
|
|
1335
3835
|
};
|
|
1336
|
-
var activeRunDirectory = (paths, sessionId) =>
|
|
3836
|
+
var activeRunDirectory = (paths, sessionId) => import_node_path12.default.join(
|
|
1337
3837
|
paths.sessionsDir,
|
|
1338
3838
|
"active-runs",
|
|
1339
|
-
(0,
|
|
3839
|
+
(0, import_node_crypto9.createHash)("sha256").update(sessionId).digest("hex")
|
|
1340
3840
|
);
|
|
1341
|
-
var usageLogPath = (paths, datePath, runId) =>
|
|
3841
|
+
var usageLogPath = (paths, datePath, runId) => import_node_path12.default.join(paths.root, "usage", datePath, `${validateRunLogId(runId)}.jsonl`);
|
|
1342
3842
|
|
|
1343
3843
|
// src/session-run-index.ts
|
|
1344
|
-
var
|
|
1345
|
-
var
|
|
3844
|
+
var import_node_fs14 = require("fs");
|
|
3845
|
+
var import_node_path13 = __toESM(require("path"), 1);
|
|
1346
3846
|
|
|
1347
3847
|
// src/run-log-reader.ts
|
|
1348
|
-
var
|
|
3848
|
+
var import_node_fs13 = require("fs");
|
|
1349
3849
|
var import_node_readline = require("readline");
|
|
1350
3850
|
var import_node_stream = require("stream");
|
|
1351
3851
|
var import_node_zlib2 = require("zlib");
|
|
1352
|
-
var resolveRunLogPath = (file) => (0,
|
|
3852
|
+
var resolveRunLogPath = (file) => (0, import_node_fs13.existsSync)(file) ? file : file.endsWith(".gz") ? file : `${file}.gz`;
|
|
1353
3853
|
async function* readRunLogChunks(file) {
|
|
1354
3854
|
let resolved = resolveRunLogPath(file);
|
|
1355
3855
|
let handle;
|
|
1356
3856
|
try {
|
|
1357
|
-
handle = await
|
|
3857
|
+
handle = await import_node_fs13.promises.open(
|
|
1358
3858
|
resolved,
|
|
1359
|
-
|
|
3859
|
+
import_node_fs13.constants.O_RDONLY | (import_node_fs13.constants.O_NOFOLLOW ?? 0)
|
|
1360
3860
|
);
|
|
1361
3861
|
} catch (error) {
|
|
1362
3862
|
if (error.code !== "ENOENT" || file.endsWith(".gz"))
|
|
1363
3863
|
throw error;
|
|
1364
3864
|
resolved = `${file}.gz`;
|
|
1365
|
-
handle = await
|
|
3865
|
+
handle = await import_node_fs13.promises.open(
|
|
1366
3866
|
resolved,
|
|
1367
|
-
|
|
3867
|
+
import_node_fs13.constants.O_RDONLY | (import_node_fs13.constants.O_NOFOLLOW ?? 0)
|
|
1368
3868
|
);
|
|
1369
3869
|
}
|
|
1370
3870
|
const source = handle.createReadStream();
|
|
@@ -1399,18 +3899,18 @@ var normalizeRunStartedAt = (startedAt) => {
|
|
|
1399
3899
|
};
|
|
1400
3900
|
var isRegularFile = (file) => {
|
|
1401
3901
|
try {
|
|
1402
|
-
return (0,
|
|
3902
|
+
return (0, import_node_fs14.lstatSync)(file).isFile();
|
|
1403
3903
|
} catch {
|
|
1404
3904
|
return false;
|
|
1405
3905
|
}
|
|
1406
3906
|
};
|
|
1407
3907
|
var toRunLogRelPath = (sessionsDir, file) => {
|
|
1408
|
-
const relative =
|
|
3908
|
+
const relative = import_node_path13.default.relative(sessionsDir, file).split(import_node_path13.default.sep).join("/").replace(/\.gz$/, "");
|
|
1409
3909
|
return REL_PATH_PATTERN.test(relative) ? relative : void 0;
|
|
1410
3910
|
};
|
|
1411
3911
|
var resolveIndexedRunLog = (sessionsDir, relPath) => {
|
|
1412
3912
|
if (!REL_PATH_PATTERN.test(relPath)) return void 0;
|
|
1413
|
-
const plain =
|
|
3913
|
+
const plain = import_node_path13.default.join(sessionsDir, ...relPath.split("/"));
|
|
1414
3914
|
if (isRegularFile(plain)) return plain;
|
|
1415
3915
|
if (isRegularFile(`${plain}.gz`)) return `${plain}.gz`;
|
|
1416
3916
|
return void 0;
|
|
@@ -1430,7 +3930,7 @@ var readHeader = async (file) => {
|
|
|
1430
3930
|
var errorCode2 = (error) => error?.code;
|
|
1431
3931
|
var readDirs = async (directory2) => {
|
|
1432
3932
|
try {
|
|
1433
|
-
return await
|
|
3933
|
+
return await import_node_fs14.promises.readdir(directory2, {
|
|
1434
3934
|
withFileTypes: true,
|
|
1435
3935
|
encoding: "utf8"
|
|
1436
3936
|
});
|
|
@@ -1448,13 +3948,13 @@ var listRunLogFiles = async (sessionsDir) => {
|
|
|
1448
3948
|
const files = [];
|
|
1449
3949
|
for (const year of await readDirs(sessionsDir)) {
|
|
1450
3950
|
if (!year.isDirectory() || !/^\d{4}$/.test(year.name)) continue;
|
|
1451
|
-
const yearPath =
|
|
3951
|
+
const yearPath = import_node_path13.default.join(sessionsDir, year.name);
|
|
1452
3952
|
for (const month of await readDirs(yearPath)) {
|
|
1453
3953
|
if (!month.isDirectory() || !/^\d{2}$/.test(month.name)) continue;
|
|
1454
|
-
const monthPath =
|
|
3954
|
+
const monthPath = import_node_path13.default.join(yearPath, month.name);
|
|
1455
3955
|
for (const day of await readDirs(monthPath)) {
|
|
1456
3956
|
if (!day.isDirectory() || !/^\d{2}$/.test(day.name)) continue;
|
|
1457
|
-
const dayPath =
|
|
3957
|
+
const dayPath = import_node_path13.default.join(monthPath, day.name);
|
|
1458
3958
|
const entries2 = (await readDirs(dayPath)).filter(
|
|
1459
3959
|
(entry) => entry.isFile() && /\.jsonl(?:\.gz)?$/.test(entry.name)
|
|
1460
3960
|
);
|
|
@@ -1464,7 +3964,7 @@ var listRunLogFiles = async (sessionsDir) => {
|
|
|
1464
3964
|
for (const entry of entries2) {
|
|
1465
3965
|
if (entry.name.endsWith(".gz") && plain.has(entry.name.slice(0, -3)))
|
|
1466
3966
|
continue;
|
|
1467
|
-
files.push(
|
|
3967
|
+
files.push(import_node_path13.default.join(dayPath, entry.name));
|
|
1468
3968
|
}
|
|
1469
3969
|
}
|
|
1470
3970
|
}
|
|
@@ -1484,10 +3984,10 @@ var scanSessionRunLogs = async (sessionsDir) => {
|
|
|
1484
3984
|
try {
|
|
1485
3985
|
const header = await readHeader(file);
|
|
1486
3986
|
if (!header || typeof header.session_id !== "string") continue;
|
|
1487
|
-
const startedAt = typeof header.started_at === "string" ? header.started_at : new Date((await
|
|
3987
|
+
const startedAt = typeof header.started_at === "string" ? header.started_at : new Date((await import_node_fs14.promises.stat(file)).mtimeMs).toISOString();
|
|
1488
3988
|
entries2.push({
|
|
1489
3989
|
session_id: header.session_id,
|
|
1490
|
-
run_id: typeof header.run_id === "string" ? header.run_id :
|
|
3990
|
+
run_id: typeof header.run_id === "string" ? header.run_id : import_node_path13.default.posix.basename(relPath, ".jsonl"),
|
|
1491
3991
|
rel_path: relPath,
|
|
1492
3992
|
started_at: normalizeRunStartedAt(startedAt)
|
|
1493
3993
|
});
|
|
@@ -1560,7 +4060,7 @@ var SessionStoreWriterImpl = class {
|
|
|
1560
4060
|
this.runId = validateRunLogId(options.runId);
|
|
1561
4061
|
this.startedAt = options.startedAt;
|
|
1562
4062
|
const datePath = runDatePath(options.startedAt);
|
|
1563
|
-
this.filePath =
|
|
4063
|
+
this.filePath = import_node_path14.default.join(
|
|
1564
4064
|
paths.sessionsDir,
|
|
1565
4065
|
datePath,
|
|
1566
4066
|
`${this.runId}.jsonl`
|
|
@@ -1568,7 +4068,7 @@ var SessionStoreWriterImpl = class {
|
|
|
1568
4068
|
this.usageFilePath = usageLogPath(paths, datePath, this.runId);
|
|
1569
4069
|
const dump = options.dump ?? /^(1|true)$/i.test(process.env.CODELIA_SESSION_DUMP ?? "");
|
|
1570
4070
|
if (dump)
|
|
1571
|
-
this.diagnosticFilePath =
|
|
4071
|
+
this.diagnosticFilePath = import_node_path14.default.join(
|
|
1572
4072
|
paths.sessionsDir,
|
|
1573
4073
|
"diagnostics",
|
|
1574
4074
|
datePath,
|
|
@@ -1643,9 +4143,9 @@ var SessionStoreWriterImpl = class {
|
|
|
1643
4143
|
if (markerSessionId) {
|
|
1644
4144
|
await this.recordRun(markerSessionId, startedAt ?? this.startedAt);
|
|
1645
4145
|
const directory2 = activeRunDirectory(this.paths, markerSessionId);
|
|
1646
|
-
await
|
|
1647
|
-
this.activePath =
|
|
1648
|
-
await
|
|
4146
|
+
await import_node_fs15.promises.mkdir(directory2, { recursive: true });
|
|
4147
|
+
this.activePath = import_node_path14.default.join(directory2, `${this.runId}.json`);
|
|
4148
|
+
await import_node_fs15.promises.writeFile(
|
|
1649
4149
|
this.activePath,
|
|
1650
4150
|
JSON.stringify({
|
|
1651
4151
|
pid: process.pid,
|
|
@@ -1662,11 +4162,11 @@ var SessionStoreWriterImpl = class {
|
|
|
1662
4162
|
[this.diagnosticFilePath, dump]
|
|
1663
4163
|
]) {
|
|
1664
4164
|
if (!file || line === void 0) continue;
|
|
1665
|
-
await
|
|
1666
|
-
await
|
|
4165
|
+
await import_node_fs15.promises.mkdir(import_node_path14.default.dirname(file), { recursive: true });
|
|
4166
|
+
await import_node_fs15.promises.appendFile(file, line, { encoding: "utf8", mode: 384 });
|
|
1667
4167
|
}
|
|
1668
4168
|
if (terminal && this.activePath) {
|
|
1669
|
-
await
|
|
4169
|
+
await import_node_fs15.promises.unlink(this.activePath);
|
|
1670
4170
|
this.activePath = void 0;
|
|
1671
4171
|
}
|
|
1672
4172
|
});
|
|
@@ -1677,12 +4177,12 @@ var SessionStoreWriterImpl = class {
|
|
|
1677
4177
|
};
|
|
1678
4178
|
|
|
1679
4179
|
// src/session-state.ts
|
|
1680
|
-
var
|
|
1681
|
-
var
|
|
4180
|
+
var import_node_fs17 = require("fs");
|
|
4181
|
+
var import_node_path15 = __toESM(require("path"), 1);
|
|
1682
4182
|
var import_core2 = require("@codelia/core");
|
|
1683
4183
|
|
|
1684
4184
|
// src/conversation-archive.ts
|
|
1685
|
-
var
|
|
4185
|
+
var import_node_fs16 = require("fs");
|
|
1686
4186
|
var import_core = require("@codelia/core");
|
|
1687
4187
|
function appendOriginalMessages(file, messages, provenance) {
|
|
1688
4188
|
const data = Buffer.from(
|
|
@@ -1692,17 +4192,17 @@ function appendOriginalMessages(file, messages, provenance) {
|
|
|
1692
4192
|
)
|
|
1693
4193
|
).join("\n") + (messages.length ? "\n" : "")
|
|
1694
4194
|
);
|
|
1695
|
-
const fd = (0,
|
|
4195
|
+
const fd = (0, import_node_fs16.openSync)(
|
|
1696
4196
|
file,
|
|
1697
|
-
|
|
4197
|
+
import_node_fs16.constants.O_RDWR | import_node_fs16.constants.O_CREAT | import_node_fs16.constants.O_APPEND | (import_node_fs16.constants.O_NOFOLLOW ?? 0),
|
|
1698
4198
|
384
|
|
1699
4199
|
);
|
|
1700
4200
|
try {
|
|
1701
|
-
const stat = (0,
|
|
4201
|
+
const stat = (0, import_node_fs16.fstatSync)(fd);
|
|
1702
4202
|
if (!stat.isFile()) throw new Error("Invalid conversation archive");
|
|
1703
4203
|
if (stat.size) {
|
|
1704
4204
|
const last = Buffer.alloc(1);
|
|
1705
|
-
(0,
|
|
4205
|
+
(0, import_node_fs16.readSync)(fd, last, 0, 1, stat.size - 1);
|
|
1706
4206
|
if (last[0] !== 10)
|
|
1707
4207
|
throw new Error(
|
|
1708
4208
|
"Incomplete conversation archive; original bytes retained"
|
|
@@ -1710,10 +4210,10 @@ function appendOriginalMessages(file, messages, provenance) {
|
|
|
1710
4210
|
}
|
|
1711
4211
|
let written = 0;
|
|
1712
4212
|
while (written < data.length)
|
|
1713
|
-
written += (0,
|
|
1714
|
-
(0,
|
|
4213
|
+
written += (0, import_node_fs16.writeSync)(fd, data, written, data.length - written);
|
|
4214
|
+
(0, import_node_fs16.fsyncSync)(fd);
|
|
1715
4215
|
} finally {
|
|
1716
|
-
(0,
|
|
4216
|
+
(0, import_node_fs16.closeSync)(fd);
|
|
1717
4217
|
}
|
|
1718
4218
|
}
|
|
1719
4219
|
var parseId = (id2) => {
|
|
@@ -1733,10 +4233,10 @@ var textOf = (message) => {
|
|
|
1733
4233
|
${JSON.stringify(message.tool_calls.map((call) => ({ id: call.id, function: call.function })))}` : text;
|
|
1734
4234
|
};
|
|
1735
4235
|
async function* entries(file, start, maxBytes) {
|
|
1736
|
-
const fd = (0,
|
|
4236
|
+
const fd = (0, import_node_fs16.openSync)(file, import_node_fs16.constants.O_RDONLY | (import_node_fs16.constants.O_NOFOLLOW ?? 0));
|
|
1737
4237
|
let stream;
|
|
1738
4238
|
try {
|
|
1739
|
-
const stat = (0,
|
|
4239
|
+
const stat = (0, import_node_fs16.fstatSync)(fd);
|
|
1740
4240
|
if (!stat.isFile()) throw new Error("Invalid conversation archive");
|
|
1741
4241
|
if (start > stat.size)
|
|
1742
4242
|
throw new Error("Conversation cursor is beyond the archive");
|
|
@@ -1745,11 +4245,11 @@ async function* entries(file, start, maxBytes) {
|
|
|
1745
4245
|
if (start === stat.size) return;
|
|
1746
4246
|
if (start > 0) {
|
|
1747
4247
|
const previous = Buffer.alloc(1);
|
|
1748
|
-
(0,
|
|
4248
|
+
(0, import_node_fs16.readSync)(fd, previous, 0, 1, start - 1);
|
|
1749
4249
|
if (previous[0] !== 10)
|
|
1750
4250
|
throw new Error("Conversation cursor is not a message boundary");
|
|
1751
4251
|
}
|
|
1752
|
-
stream = (0,
|
|
4252
|
+
stream = (0, import_node_fs16.createReadStream)(file, {
|
|
1753
4253
|
fd,
|
|
1754
4254
|
autoClose: true,
|
|
1755
4255
|
start,
|
|
@@ -1784,7 +4284,7 @@ async function* entries(file, start, maxBytes) {
|
|
|
1784
4284
|
if (maxBytes !== void 0 && length > 0)
|
|
1785
4285
|
throw new Error("Incomplete approval conversation window");
|
|
1786
4286
|
} finally {
|
|
1787
|
-
if (!stream) (0,
|
|
4287
|
+
if (!stream) (0, import_node_fs16.closeSync)(fd);
|
|
1788
4288
|
else if (!stream.closed) {
|
|
1789
4289
|
const closed = new Promise(
|
|
1790
4290
|
(resolve) => stream?.once("close", resolve)
|
|
@@ -1957,9 +4457,9 @@ var MESSAGES_DIRNAME = "messages";
|
|
|
1957
4457
|
var STATE_DB_FILENAME = "state.db";
|
|
1958
4458
|
var SESSION_WORKSPACE_ROOT_META_KEY = "codelia_workspace_root";
|
|
1959
4459
|
var RUN_INDEX_BACKFILL_KEY = "session_runs_backfilled_at";
|
|
1960
|
-
var resolveLegacyStateDir = (paths) =>
|
|
1961
|
-
var resolveMessagesDir = (paths) =>
|
|
1962
|
-
var resolveStateDbPath = (paths) =>
|
|
4460
|
+
var resolveLegacyStateDir = (paths) => import_node_path15.default.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
|
|
4461
|
+
var resolveMessagesDir = (paths) => import_node_path15.default.join(paths.sessionsDir, MESSAGES_DIRNAME);
|
|
4462
|
+
var resolveStateDbPath = (paths) => import_node_path15.default.join(paths.sessionsDir, STATE_DB_FILENAME);
|
|
1963
4463
|
var extractLastUserMessage = (messages) => {
|
|
1964
4464
|
for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
|
|
1965
4465
|
const message = messages[idx];
|
|
@@ -2030,13 +4530,13 @@ var SessionStateStoreImpl = class {
|
|
|
2030
4530
|
this.sessionsDir = paths.sessionsDir;
|
|
2031
4531
|
this.legacyStateDir = resolveLegacyStateDir(paths);
|
|
2032
4532
|
this.messagesDir = resolveMessagesDir(paths);
|
|
2033
|
-
this.contextsDir =
|
|
4533
|
+
this.contextsDir = import_node_path15.default.join(paths.sessionsDir, "contexts");
|
|
2034
4534
|
this.stateDbPath = resolveStateDbPath(paths);
|
|
2035
4535
|
this.ensureDirs = Promise.all([
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
4536
|
+
import_node_fs17.promises.mkdir(paths.sessionsDir, { recursive: true }),
|
|
4537
|
+
import_node_fs17.promises.mkdir(this.legacyStateDir, { recursive: true }),
|
|
4538
|
+
import_node_fs17.promises.mkdir(this.messagesDir, { recursive: true }),
|
|
4539
|
+
import_node_fs17.promises.mkdir(this.contextsDir, { recursive: true })
|
|
2040
4540
|
]).then(() => {
|
|
2041
4541
|
});
|
|
2042
4542
|
this.onError = options.onError;
|
|
@@ -2051,32 +4551,32 @@ var SessionStateStoreImpl = class {
|
|
|
2051
4551
|
return this.db;
|
|
2052
4552
|
}
|
|
2053
4553
|
resolveLegacyPath(sessionId) {
|
|
2054
|
-
return
|
|
4554
|
+
return import_node_path15.default.join(this.legacyStateDir, `${sessionId}.json`);
|
|
2055
4555
|
}
|
|
2056
4556
|
resolveMessagePath(sessionId) {
|
|
2057
|
-
return
|
|
4557
|
+
return import_node_path15.default.join(this.messagesDir, `${validateRunLogId(sessionId)}.jsonl`);
|
|
2058
4558
|
}
|
|
2059
4559
|
contextPath(sessionId) {
|
|
2060
|
-
return
|
|
4560
|
+
return import_node_path15.default.join(this.contextsDir, `${validateRunLogId(sessionId)}.json`);
|
|
2061
4561
|
}
|
|
2062
4562
|
writeContext(sessionId, messages) {
|
|
2063
4563
|
const target = this.contextPath(sessionId);
|
|
2064
4564
|
const temporary = `${target}.${crypto.randomUUID()}.tmp`;
|
|
2065
|
-
const archiveBytes = (0,
|
|
4565
|
+
const archiveBytes = (0, import_node_fs17.lstatSync)(this.resolveMessagePath(sessionId)).size;
|
|
2066
4566
|
try {
|
|
2067
|
-
const fd = (0,
|
|
4567
|
+
const fd = (0, import_node_fs17.openSync)(temporary, "wx", 384);
|
|
2068
4568
|
try {
|
|
2069
|
-
(0,
|
|
4569
|
+
(0, import_node_fs17.writeFileSync)(
|
|
2070
4570
|
fd,
|
|
2071
4571
|
JSON.stringify({ version: 1, archive_bytes: archiveBytes, messages })
|
|
2072
4572
|
);
|
|
2073
|
-
(0,
|
|
4573
|
+
(0, import_node_fs17.fsyncSync)(fd);
|
|
2074
4574
|
} finally {
|
|
2075
|
-
(0,
|
|
4575
|
+
(0, import_node_fs17.closeSync)(fd);
|
|
2076
4576
|
}
|
|
2077
|
-
(0,
|
|
4577
|
+
(0, import_node_fs17.renameSync)(temporary, target);
|
|
2078
4578
|
} finally {
|
|
2079
|
-
if ((0,
|
|
4579
|
+
if ((0, import_node_fs17.existsSync)(temporary)) (0, import_node_fs17.unlinkSync)(temporary);
|
|
2080
4580
|
}
|
|
2081
4581
|
}
|
|
2082
4582
|
ensureArchive(sessionId, db) {
|
|
@@ -2085,16 +4585,16 @@ var SessionStateStoreImpl = class {
|
|
|
2085
4585
|
[sessionId]
|
|
2086
4586
|
);
|
|
2087
4587
|
if (row?.archive_version === 1) {
|
|
2088
|
-
if (!(0,
|
|
4588
|
+
if (!(0, import_node_fs17.lstatSync)(this.resolveMessagePath(sessionId)).isFile())
|
|
2089
4589
|
throw new Error("Invalid original conversation archive");
|
|
2090
4590
|
return false;
|
|
2091
4591
|
}
|
|
2092
4592
|
const file = this.resolveMessagePath(sessionId);
|
|
2093
4593
|
let messages = [];
|
|
2094
|
-
if ((0,
|
|
2095
|
-
if (!(0,
|
|
4594
|
+
if ((0, import_node_fs17.existsSync)(file)) {
|
|
4595
|
+
if (!(0, import_node_fs17.lstatSync)(file).isFile())
|
|
2096
4596
|
throw new Error("Invalid legacy conversation file");
|
|
2097
|
-
messages = deserializeMessages((0,
|
|
4597
|
+
messages = deserializeMessages((0, import_node_fs17.readFileSync)(file, "utf8"));
|
|
2098
4598
|
} else appendOriginalMessages(file, []);
|
|
2099
4599
|
this.writeContext(sessionId, messages);
|
|
2100
4600
|
db.run(
|
|
@@ -2222,7 +4722,7 @@ var SessionStateStoreImpl = class {
|
|
|
2222
4722
|
}
|
|
2223
4723
|
async loadLegacy(sessionId) {
|
|
2224
4724
|
try {
|
|
2225
|
-
const file = await
|
|
4725
|
+
const file = await import_node_fs17.promises.readFile(this.resolveLegacyPath(sessionId), "utf8");
|
|
2226
4726
|
const parsed = JSON.parse(file);
|
|
2227
4727
|
if (!parsed || typeof parsed !== "object") return null;
|
|
2228
4728
|
if (!parsed.session_id || !parsed.updated_at) return null;
|
|
@@ -2262,14 +4762,14 @@ var SessionStateStoreImpl = class {
|
|
|
2262
4762
|
try {
|
|
2263
4763
|
if (row.archive_version === 1) {
|
|
2264
4764
|
const checkpoint = JSON.parse(
|
|
2265
|
-
await
|
|
4765
|
+
await import_node_fs17.promises.readFile(this.contextPath(sessionId), "utf8")
|
|
2266
4766
|
);
|
|
2267
4767
|
if (checkpoint.version !== 1 || !Array.isArray(checkpoint.messages))
|
|
2268
4768
|
throw new Error("Invalid active conversation checkpoint");
|
|
2269
4769
|
messages = checkpoint.messages;
|
|
2270
4770
|
} else
|
|
2271
4771
|
messages = deserializeMessages(
|
|
2272
|
-
await
|
|
4772
|
+
await import_node_fs17.promises.readFile(this.resolveMessagePath(sessionId), "utf8")
|
|
2273
4773
|
);
|
|
2274
4774
|
} catch (error) {
|
|
2275
4775
|
if (error.code === "ENOENT" && row.archive_version !== 1) {
|
|
@@ -2607,7 +5107,7 @@ var SessionStateStoreImpl = class {
|
|
|
2607
5107
|
async listLegacySummaries() {
|
|
2608
5108
|
let entries2;
|
|
2609
5109
|
try {
|
|
2610
|
-
entries2 = await
|
|
5110
|
+
entries2 = await import_node_fs17.promises.readdir(this.legacyStateDir, {
|
|
2611
5111
|
withFileTypes: true,
|
|
2612
5112
|
encoding: "utf8"
|
|
2613
5113
|
});
|
|
@@ -2619,9 +5119,9 @@ var SessionStateStoreImpl = class {
|
|
|
2619
5119
|
for (const entry of entries2) {
|
|
2620
5120
|
if (!entry.isFile()) continue;
|
|
2621
5121
|
if (!entry.name.endsWith(".json")) continue;
|
|
2622
|
-
const filePath =
|
|
5122
|
+
const filePath = import_node_path15.default.join(this.legacyStateDir, entry.name);
|
|
2623
5123
|
try {
|
|
2624
|
-
const contents = await
|
|
5124
|
+
const contents = await import_node_fs17.promises.readFile(filePath, "utf8");
|
|
2625
5125
|
const parsed = JSON.parse(contents);
|
|
2626
5126
|
if (!parsed || typeof parsed !== "object") continue;
|
|
2627
5127
|
if (!parsed.session_id || !parsed.updated_at) continue;
|
|
@@ -2690,14 +5190,14 @@ var RunEventStoreFactoryImpl = class {
|
|
|
2690
5190
|
};
|
|
2691
5191
|
|
|
2692
5192
|
// src/run-log-retention.ts
|
|
2693
|
-
var
|
|
2694
|
-
var
|
|
5193
|
+
var import_node_fs21 = require("fs");
|
|
5194
|
+
var import_node_path18 = __toESM(require("path"), 1);
|
|
2695
5195
|
|
|
2696
5196
|
// src/run-log-compression.ts
|
|
2697
|
-
var
|
|
2698
|
-
var
|
|
5197
|
+
var import_node_crypto10 = require("crypto");
|
|
5198
|
+
var import_node_fs18 = require("fs");
|
|
2699
5199
|
var import_node_stream2 = require("stream");
|
|
2700
|
-
var
|
|
5200
|
+
var import_promises8 = require("stream/promises");
|
|
2701
5201
|
var import_node_zlib3 = require("zlib");
|
|
2702
5202
|
|
|
2703
5203
|
// src/run-log-records.ts
|
|
@@ -2795,10 +5295,10 @@ async function* projectArchivedRunLog(file, usage) {
|
|
|
2795
5295
|
// src/run-log-compression.ts
|
|
2796
5296
|
async function prepareCompressedLog(file, usage) {
|
|
2797
5297
|
const temporary = `${file}.${crypto.randomUUID()}.gz.tmp`;
|
|
2798
|
-
const hash = (0,
|
|
5298
|
+
const hash = (0, import_node_crypto10.createHash)("sha256");
|
|
2799
5299
|
let bytes = 0;
|
|
2800
5300
|
try {
|
|
2801
|
-
await (0,
|
|
5301
|
+
await (0, import_promises8.pipeline)(
|
|
2802
5302
|
import_node_stream2.Readable.from(projectArchivedRunLog(file, usage)),
|
|
2803
5303
|
new import_node_stream2.Transform({
|
|
2804
5304
|
transform(chunk, _encoding, callback) {
|
|
@@ -2808,13 +5308,13 @@ async function prepareCompressedLog(file, usage) {
|
|
|
2808
5308
|
}
|
|
2809
5309
|
}),
|
|
2810
5310
|
(0, import_node_zlib3.createGzip)(),
|
|
2811
|
-
(0,
|
|
5311
|
+
(0, import_node_fs18.createWriteStream)(temporary, { flags: "wx", mode: 384 })
|
|
2812
5312
|
);
|
|
2813
5313
|
const expected = hash.digest("hex");
|
|
2814
|
-
const verification = (0,
|
|
5314
|
+
const verification = (0, import_node_crypto10.createHash)("sha256");
|
|
2815
5315
|
let decoded = 0;
|
|
2816
|
-
await (0,
|
|
2817
|
-
(0,
|
|
5316
|
+
await (0, import_promises8.pipeline)(
|
|
5317
|
+
(0, import_node_fs18.createReadStream)(temporary),
|
|
2818
5318
|
(0, import_node_zlib3.createGunzip)(),
|
|
2819
5319
|
new import_node_stream2.Transform({
|
|
2820
5320
|
transform(chunk, _encoding, callback) {
|
|
@@ -2826,26 +5326,26 @@ async function prepareCompressedLog(file, usage) {
|
|
|
2826
5326
|
);
|
|
2827
5327
|
if (decoded !== bytes || verification.digest("hex") !== expected)
|
|
2828
5328
|
throw new Error("Compressed run log verification failed");
|
|
2829
|
-
const persisted = await
|
|
5329
|
+
const persisted = await import_node_fs18.promises.open(temporary, "r+");
|
|
2830
5330
|
try {
|
|
2831
5331
|
await persisted.sync();
|
|
2832
5332
|
} finally {
|
|
2833
5333
|
await persisted.close();
|
|
2834
5334
|
}
|
|
2835
|
-
return { temporary, size: (await
|
|
5335
|
+
return { temporary, size: (await import_node_fs18.promises.stat(temporary)).size };
|
|
2836
5336
|
} catch (error) {
|
|
2837
|
-
await
|
|
5337
|
+
await import_node_fs18.promises.rm(temporary, { force: true });
|
|
2838
5338
|
throw error;
|
|
2839
5339
|
}
|
|
2840
5340
|
}
|
|
2841
5341
|
|
|
2842
5342
|
// src/run-log-files.ts
|
|
2843
|
-
var
|
|
2844
|
-
var
|
|
5343
|
+
var import_node_fs19 = require("fs");
|
|
5344
|
+
var import_node_path16 = __toESM(require("path"), 1);
|
|
2845
5345
|
var MAX_ACTIVE_RUN_MARKER_BYTES = 256;
|
|
2846
5346
|
var isRegularDirectory = async (directory2) => {
|
|
2847
5347
|
try {
|
|
2848
|
-
return (await
|
|
5348
|
+
return (await import_node_fs19.promises.lstat(directory2)).isDirectory();
|
|
2849
5349
|
} catch {
|
|
2850
5350
|
return false;
|
|
2851
5351
|
}
|
|
@@ -2871,9 +5371,9 @@ async function readHeader2(file) {
|
|
|
2871
5371
|
}
|
|
2872
5372
|
async function inspectCandidate(root, datePath, name, diagnostic) {
|
|
2873
5373
|
const compressed = name.endsWith(".jsonl.gz");
|
|
2874
|
-
const file =
|
|
5374
|
+
const file = import_node_path16.default.join(root, datePath, name);
|
|
2875
5375
|
try {
|
|
2876
|
-
const stat = await
|
|
5376
|
+
const stat = await import_node_fs19.promises.lstat(file);
|
|
2877
5377
|
if (!stat.isFile()) return void 0;
|
|
2878
5378
|
const header = await readHeader2(file);
|
|
2879
5379
|
if (!header || name !== `${header.run_id}.jsonl${compressed ? ".gz" : ""}` || compressed && header.meta?.codelia_log_archive_version === RUN_LOG_ARCHIVE_VERSION)
|
|
@@ -2898,19 +5398,19 @@ async function inspectCandidate(root, datePath, name, diagnostic) {
|
|
|
2898
5398
|
async function collectRunLogCandidates(root, diagnostic = false) {
|
|
2899
5399
|
if (!await isRegularDirectory(root)) return [];
|
|
2900
5400
|
const candidates = [];
|
|
2901
|
-
for (const year of await
|
|
5401
|
+
for (const year of await import_node_fs19.promises.readdir(root, { withFileTypes: true })) {
|
|
2902
5402
|
if (!year.isDirectory() || !/^\d{4}$/.test(year.name)) continue;
|
|
2903
|
-
for (const month of await
|
|
5403
|
+
for (const month of await import_node_fs19.promises.readdir(import_node_path16.default.join(root, year.name), {
|
|
2904
5404
|
withFileTypes: true
|
|
2905
5405
|
})) {
|
|
2906
5406
|
if (!month.isDirectory() || !/^\d{2}$/.test(month.name)) continue;
|
|
2907
|
-
for (const day of await
|
|
2908
|
-
|
|
5407
|
+
for (const day of await import_node_fs19.promises.readdir(
|
|
5408
|
+
import_node_path16.default.join(root, year.name, month.name),
|
|
2909
5409
|
{ withFileTypes: true }
|
|
2910
5410
|
)) {
|
|
2911
5411
|
if (!day.isDirectory() || !/^\d{2}$/.test(day.name)) continue;
|
|
2912
|
-
const datePath =
|
|
2913
|
-
const entries2 = await
|
|
5412
|
+
const datePath = import_node_path16.default.join(year.name, month.name, day.name);
|
|
5413
|
+
const entries2 = await import_node_fs19.promises.readdir(import_node_path16.default.join(root, datePath), {
|
|
2914
5414
|
withFileTypes: true
|
|
2915
5415
|
});
|
|
2916
5416
|
const plain = new Set(
|
|
@@ -2942,10 +5442,10 @@ async function collectRunLogCandidatesAt(root, relPaths, diagnostic = false) {
|
|
|
2942
5442
|
const name = parts.pop();
|
|
2943
5443
|
if (!name?.endsWith(".jsonl") || parts.length !== 3 || !/^\d{4}$/.test(parts[0] ?? "") || !/^\d{2}$/.test(parts[1] ?? "") || !/^\d{2}$/.test(parts[2] ?? "") || name.includes("\\"))
|
|
2944
5444
|
continue;
|
|
2945
|
-
const datePath =
|
|
5445
|
+
const datePath = import_node_path16.default.join(...parts);
|
|
2946
5446
|
let selected = name;
|
|
2947
5447
|
try {
|
|
2948
|
-
await
|
|
5448
|
+
await import_node_fs19.promises.lstat(import_node_path16.default.join(root, datePath, name));
|
|
2949
5449
|
} catch {
|
|
2950
5450
|
if (diagnostic) continue;
|
|
2951
5451
|
selected = `${name}.gz`;
|
|
@@ -2964,25 +5464,25 @@ async function removeReusedProcessMarkers(paths, sessionId, identify = (pid) =>
|
|
|
2964
5464
|
const directory2 = activeRunDirectory(paths, sessionId);
|
|
2965
5465
|
let entries2;
|
|
2966
5466
|
try {
|
|
2967
|
-
entries2 = (0,
|
|
5467
|
+
entries2 = (0, import_node_fs19.readdirSync)(directory2);
|
|
2968
5468
|
} catch {
|
|
2969
5469
|
return;
|
|
2970
5470
|
}
|
|
2971
5471
|
for (const entry of entries2) {
|
|
2972
|
-
const file =
|
|
5472
|
+
const file = import_node_path16.default.join(directory2, entry);
|
|
2973
5473
|
try {
|
|
2974
|
-
const before = (0,
|
|
5474
|
+
const before = (0, import_node_fs19.lstatSync)(file);
|
|
2975
5475
|
if (!before.isFile() || before.size > MAX_ACTIVE_RUN_MARKER_BYTES)
|
|
2976
5476
|
continue;
|
|
2977
|
-
const contents = (0,
|
|
5477
|
+
const contents = (0, import_node_fs19.readFileSync)(file, "utf8");
|
|
2978
5478
|
const { pid, identity } = JSON.parse(contents);
|
|
2979
5479
|
if (!Number.isSafeInteger(pid) || pid < 1 || typeof identity !== "string" || !identity)
|
|
2980
5480
|
continue;
|
|
2981
5481
|
const current = await identify(pid);
|
|
2982
5482
|
if (!current || current === identity) continue;
|
|
2983
|
-
const after = (0,
|
|
2984
|
-
if (after.isFile() && after.ino === before.ino && after.dev === before.dev && after.size === before.size && after.mtimeMs === before.mtimeMs && (0,
|
|
2985
|
-
(0,
|
|
5483
|
+
const after = (0, import_node_fs19.lstatSync)(file);
|
|
5484
|
+
if (after.isFile() && after.ino === before.ino && after.dev === before.dev && after.size === before.size && after.mtimeMs === before.mtimeMs && (0, import_node_fs19.readFileSync)(file, "utf8") === contents)
|
|
5485
|
+
(0, import_node_fs19.unlinkSync)(file);
|
|
2986
5486
|
} catch {
|
|
2987
5487
|
}
|
|
2988
5488
|
}
|
|
@@ -2990,12 +5490,12 @@ async function removeReusedProcessMarkers(paths, sessionId, identify = (pid) =>
|
|
|
2990
5490
|
function hasActiveRunWriter(paths, sessionId) {
|
|
2991
5491
|
try {
|
|
2992
5492
|
const directory2 = activeRunDirectory(paths, sessionId);
|
|
2993
|
-
for (const entry of (0,
|
|
5493
|
+
for (const entry of (0, import_node_fs19.readdirSync)(directory2, { withFileTypes: true })) {
|
|
2994
5494
|
if (!entry.isFile()) return true;
|
|
2995
5495
|
try {
|
|
2996
|
-
const file =
|
|
2997
|
-
if ((0,
|
|
2998
|
-
const { pid } = JSON.parse((0,
|
|
5496
|
+
const file = import_node_path16.default.join(directory2, entry.name);
|
|
5497
|
+
if ((0, import_node_fs19.lstatSync)(file).size > MAX_ACTIVE_RUN_MARKER_BYTES) return true;
|
|
5498
|
+
const { pid } = JSON.parse((0, import_node_fs19.readFileSync)(file, "utf8"));
|
|
2999
5499
|
if (!Number.isSafeInteger(pid) || pid < 1) return true;
|
|
3000
5500
|
try {
|
|
3001
5501
|
process.kill(pid, 0);
|
|
@@ -3014,8 +5514,8 @@ function hasActiveRunWriter(paths, sessionId) {
|
|
|
3014
5514
|
}
|
|
3015
5515
|
|
|
3016
5516
|
// src/run-log-usage.ts
|
|
3017
|
-
var
|
|
3018
|
-
var
|
|
5517
|
+
var import_node_fs20 = require("fs");
|
|
5518
|
+
var import_node_path17 = __toESM(require("path"), 1);
|
|
3019
5519
|
|
|
3020
5520
|
// src/run-log-request-model.ts
|
|
3021
5521
|
var TOKENS = /["\\{}[\]:,]/g;
|
|
@@ -3162,7 +5662,7 @@ async function preserveRunUsage(paths, source) {
|
|
|
3162
5662
|
const records = /* @__PURE__ */ new Map();
|
|
3163
5663
|
const requestModels = /* @__PURE__ */ new Map();
|
|
3164
5664
|
try {
|
|
3165
|
-
const stat = await
|
|
5665
|
+
const stat = await import_node_fs20.promises.lstat(destination);
|
|
3166
5666
|
if (!stat.isFile()) throw new Error("Invalid usage log");
|
|
3167
5667
|
for await (const record2 of readUsageRecords(destination))
|
|
3168
5668
|
if (record2.type === "llm.usage")
|
|
@@ -3203,15 +5703,15 @@ async function preserveRunUsage(paths, source) {
|
|
|
3203
5703
|
name: record2.model?.name ?? source.model?.name
|
|
3204
5704
|
})
|
|
3205
5705
|
);
|
|
3206
|
-
await
|
|
5706
|
+
await import_node_fs20.promises.mkdir(import_node_path17.default.dirname(destination), { recursive: true });
|
|
3207
5707
|
const temporary = `${destination}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
|
3208
5708
|
try {
|
|
3209
5709
|
const lines = ordered.map((record2) => JSON.stringify(record2)).join("\n");
|
|
3210
|
-
await
|
|
5710
|
+
await import_node_fs20.promises.writeFile(temporary, `${lines}
|
|
3211
5711
|
`, { mode: 384 });
|
|
3212
|
-
await
|
|
5712
|
+
await import_node_fs20.promises.rename(temporary, destination);
|
|
3213
5713
|
} finally {
|
|
3214
|
-
await
|
|
5714
|
+
await import_node_fs20.promises.rm(temporary, { force: true });
|
|
3215
5715
|
}
|
|
3216
5716
|
return ordered;
|
|
3217
5717
|
}
|
|
@@ -3226,21 +5726,21 @@ var eligible = (summary, newestMtime, now) => {
|
|
|
3226
5726
|
};
|
|
3227
5727
|
function commitCandidate(candidate, compressed, result) {
|
|
3228
5728
|
try {
|
|
3229
|
-
const stat = (0,
|
|
5729
|
+
const stat = (0, import_node_fs21.lstatSync)(candidate.file);
|
|
3230
5730
|
if (!stat.isFile() || stat.ino !== candidate.ino || stat.dev !== candidate.dev || stat.size !== candidate.size || stat.mtimeMs !== candidate.mtimeMs) {
|
|
3231
5731
|
result.skipped++;
|
|
3232
5732
|
return;
|
|
3233
5733
|
}
|
|
3234
5734
|
if (compressed) {
|
|
3235
5735
|
const target = candidate.compressed ? candidate.file : `${candidate.file}.gz`;
|
|
3236
|
-
if (candidate.compressed) (0,
|
|
3237
|
-
else (0,
|
|
3238
|
-
(0,
|
|
3239
|
-
if (!candidate.compressed) (0,
|
|
5736
|
+
if (candidate.compressed) (0, import_node_fs21.renameSync)(compressed.temporary, target);
|
|
5737
|
+
else (0, import_node_fs21.linkSync)(compressed.temporary, target);
|
|
5738
|
+
(0, import_node_fs21.utimesSync)(target, stat.atime, stat.mtime);
|
|
5739
|
+
if (!candidate.compressed) (0, import_node_fs21.unlinkSync)(candidate.file);
|
|
3240
5740
|
result.compressed++;
|
|
3241
5741
|
result.reclaimed_bytes += Math.max(0, stat.size - compressed.size);
|
|
3242
5742
|
} else {
|
|
3243
|
-
(0,
|
|
5743
|
+
(0, import_node_fs21.unlinkSync)(candidate.file);
|
|
3244
5744
|
result.deleted++;
|
|
3245
5745
|
result.reclaimed_bytes += stat.size;
|
|
3246
5746
|
}
|
|
@@ -3264,7 +5764,7 @@ async function processCandidate(context, candidate, newestMtime, usage) {
|
|
|
3264
5764
|
} catch {
|
|
3265
5765
|
result.failed++;
|
|
3266
5766
|
} finally {
|
|
3267
|
-
if (compressed) await
|
|
5767
|
+
if (compressed) await import_node_fs21.promises.rm(compressed.temporary, { force: true });
|
|
3268
5768
|
}
|
|
3269
5769
|
}
|
|
3270
5770
|
async function cleanupRunLogs(options) {
|
|
@@ -3279,7 +5779,7 @@ async function cleanupRunLogs(options) {
|
|
|
3279
5779
|
};
|
|
3280
5780
|
const context = { paths, sessions, now, result };
|
|
3281
5781
|
if (!await isRegularDirectory(paths.sessionsDir)) return result;
|
|
3282
|
-
const diagnosticsDir =
|
|
5782
|
+
const diagnosticsDir = import_node_path18.default.join(paths.sessionsDir, "diagnostics");
|
|
3283
5783
|
let relPaths;
|
|
3284
5784
|
if (options.sessionId) {
|
|
3285
5785
|
try {
|
|
@@ -3328,8 +5828,8 @@ async function cleanupRunLogs(options) {
|
|
|
3328
5828
|
result.skipped += group.length - selected.length;
|
|
3329
5829
|
if (selected.length === 0) continue;
|
|
3330
5830
|
try {
|
|
3331
|
-
const snapshot = await
|
|
3332
|
-
|
|
5831
|
+
const snapshot = await import_node_fs21.promises.lstat(
|
|
5832
|
+
import_node_path18.default.join(paths.sessionsDir, "messages", `${sessionId}.jsonl`)
|
|
3333
5833
|
);
|
|
3334
5834
|
if (!snapshot.isFile() || snapshot.size === 0) {
|
|
3335
5835
|
result.skipped += selected.length;
|
|
@@ -3365,8 +5865,8 @@ var StoragePathServiceImpl = class {
|
|
|
3365
5865
|
};
|
|
3366
5866
|
|
|
3367
5867
|
// src/task-registry.ts
|
|
3368
|
-
var
|
|
3369
|
-
var
|
|
5868
|
+
var import_node_fs22 = require("fs");
|
|
5869
|
+
var import_node_path19 = __toESM(require("path"), 1);
|
|
3370
5870
|
var TASKS_DIRNAME = "tasks";
|
|
3371
5871
|
var sortByUpdatedDesc = (tasks) => [...tasks].sort((a, b) => b.updated_at.localeCompare(a.updated_at));
|
|
3372
5872
|
var toShellKeyBase = (label2) => {
|
|
@@ -3424,14 +5924,14 @@ var assignMissingShellKeys = (tasks) => {
|
|
|
3424
5924
|
return updates;
|
|
3425
5925
|
};
|
|
3426
5926
|
var atomicWrite = async (filePath, payload) => {
|
|
3427
|
-
const dir =
|
|
3428
|
-
const base =
|
|
3429
|
-
const tmp =
|
|
5927
|
+
const dir = import_node_path19.default.dirname(filePath);
|
|
5928
|
+
const base = import_node_path19.default.basename(filePath);
|
|
5929
|
+
const tmp = import_node_path19.default.join(
|
|
3430
5930
|
dir,
|
|
3431
5931
|
`${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
|
|
3432
5932
|
);
|
|
3433
|
-
await
|
|
3434
|
-
await
|
|
5933
|
+
await import_node_fs22.promises.writeFile(tmp, payload, "utf8");
|
|
5934
|
+
await import_node_fs22.promises.rename(tmp, filePath);
|
|
3435
5935
|
};
|
|
3436
5936
|
var isTaskState = (value) => value === "queued" || value === "running" || value === "completed" || value === "failed" || value === "cancelled";
|
|
3437
5937
|
var isTaskKind = (value) => value === "shell" || value === "subagent";
|
|
@@ -3542,7 +6042,7 @@ var normalizeTaskRecord = (value) => {
|
|
|
3542
6042
|
};
|
|
3543
6043
|
var readTaskFile = async (filePath) => {
|
|
3544
6044
|
try {
|
|
3545
|
-
const raw = await
|
|
6045
|
+
const raw = await import_node_fs22.promises.readFile(filePath, "utf8");
|
|
3546
6046
|
return normalizeTaskRecord(JSON.parse(raw));
|
|
3547
6047
|
} catch {
|
|
3548
6048
|
return null;
|
|
@@ -3557,19 +6057,19 @@ var TaskRegistryStore = class {
|
|
|
3557
6057
|
return;
|
|
3558
6058
|
}
|
|
3559
6059
|
const root = resolveStoragePaths().root;
|
|
3560
|
-
this.tasksDir =
|
|
6060
|
+
this.tasksDir = import_node_path19.default.join(root, TASKS_DIRNAME);
|
|
3561
6061
|
}
|
|
3562
6062
|
async ensureDir() {
|
|
3563
|
-
await
|
|
6063
|
+
await import_node_fs22.promises.mkdir(this.tasksDir, { recursive: true });
|
|
3564
6064
|
}
|
|
3565
6065
|
taskPath(taskId) {
|
|
3566
|
-
return
|
|
6066
|
+
return import_node_path19.default.join(this.tasksDir, taskFileName(taskId));
|
|
3567
6067
|
}
|
|
3568
6068
|
async list() {
|
|
3569
6069
|
await this.ensureDir();
|
|
3570
|
-
const entries2 = await
|
|
6070
|
+
const entries2 = await import_node_fs22.promises.readdir(this.tasksDir, { withFileTypes: true });
|
|
3571
6071
|
const tasks = (await Promise.all(
|
|
3572
|
-
entries2.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(
|
|
6072
|
+
entries2.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(import_node_path19.default.join(this.tasksDir, entry.name)))
|
|
3573
6073
|
)).filter((task) => task !== null);
|
|
3574
6074
|
const keyBackfills = assignMissingShellKeys(tasks);
|
|
3575
6075
|
if (keyBackfills.length > 0) {
|
|
@@ -3611,8 +6111,8 @@ var TaskRegistryStore = class {
|
|
|
3611
6111
|
};
|
|
3612
6112
|
|
|
3613
6113
|
// src/tool-output-cache.ts
|
|
3614
|
-
var
|
|
3615
|
-
var
|
|
6114
|
+
var import_node_fs23 = require("fs");
|
|
6115
|
+
var import_node_path20 = __toESM(require("path"), 1);
|
|
3616
6116
|
var DEFAULT_MAX_MATCHES = 50;
|
|
3617
6117
|
var DEFAULT_MAX_LINE_LENGTH = 1e3;
|
|
3618
6118
|
var DEFAULT_MAX_READ_BYTES = 64 * 1024;
|
|
@@ -3724,15 +6224,15 @@ var ToolOutputCacheStoreImpl = class {
|
|
|
3724
6224
|
async save(record2) {
|
|
3725
6225
|
const refId = normalizeRefId(record2.tool_call_id);
|
|
3726
6226
|
const filePath = this.resolvePath(refId);
|
|
3727
|
-
await
|
|
3728
|
-
await
|
|
6227
|
+
await import_node_fs23.promises.mkdir(this.baseDir, { recursive: true });
|
|
6228
|
+
await import_node_fs23.promises.writeFile(filePath, record2.content, "utf8");
|
|
3729
6229
|
const byteSize = Buffer.byteLength(record2.content, "utf8");
|
|
3730
6230
|
const lineCount = record2.content.split(/\r?\n/).length;
|
|
3731
6231
|
return { id: refId, byte_size: byteSize, line_count: lineCount };
|
|
3732
6232
|
}
|
|
3733
6233
|
async read(refId, options = {}) {
|
|
3734
6234
|
const filePath = this.resolvePath(refId);
|
|
3735
|
-
const content = await
|
|
6235
|
+
const content = await import_node_fs23.promises.readFile(filePath, "utf8");
|
|
3736
6236
|
const lines = content.split(/\r?\n/);
|
|
3737
6237
|
const offset = options.offset ?? 0;
|
|
3738
6238
|
const limit = options.limit ?? lines.length;
|
|
@@ -3791,7 +6291,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
|
|
|
3791
6291
|
}
|
|
3792
6292
|
async readTail(refId, options) {
|
|
3793
6293
|
const filePath = this.resolvePath(refId);
|
|
3794
|
-
const content = await
|
|
6294
|
+
const content = await import_node_fs23.promises.readFile(filePath, "utf8");
|
|
3795
6295
|
const lines = content.split(/\r?\n/);
|
|
3796
6296
|
const tailLines = Math.max(1, Math.trunc(options.tail_lines));
|
|
3797
6297
|
const start = Math.max(0, lines.length - tailLines);
|
|
@@ -3803,7 +6303,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
|
|
|
3803
6303
|
}
|
|
3804
6304
|
async readLine(refId, options) {
|
|
3805
6305
|
const filePath = this.resolvePath(refId);
|
|
3806
|
-
const content = await
|
|
6306
|
+
const content = await import_node_fs23.promises.readFile(filePath, "utf8");
|
|
3807
6307
|
const lines = content.split(/\r?\n/);
|
|
3808
6308
|
const lineIndex = options.line_number - 1;
|
|
3809
6309
|
if (lineIndex < 0 || lineIndex >= lines.length) {
|
|
@@ -3844,7 +6344,7 @@ tool_output_cache_line({"ref_id":"${normalizeRefId(refId)}","line_number":${opti
|
|
|
3844
6344
|
}
|
|
3845
6345
|
async grep(refId, options) {
|
|
3846
6346
|
const filePath = this.resolvePath(refId);
|
|
3847
|
-
const content = await
|
|
6347
|
+
const content = await import_node_fs23.promises.readFile(filePath, "utf8");
|
|
3848
6348
|
const lines = content.split(/\r?\n/);
|
|
3849
6349
|
const regex = options.regex ? new RegExp(options.pattern) : new RegExp(options.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
3850
6350
|
const before = Math.max(0, options.before ?? 0);
|
|
@@ -3895,14 +6395,24 @@ ${snippet}`;
|
|
|
3895
6395
|
return output;
|
|
3896
6396
|
}
|
|
3897
6397
|
resolvePath(refId) {
|
|
3898
|
-
return
|
|
6398
|
+
return import_node_path20.default.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
|
|
3899
6399
|
}
|
|
3900
6400
|
};
|
|
3901
6401
|
// Annotate the CommonJS export names for ESM import in node:
|
|
3902
6402
|
0 && (module.exports = {
|
|
6403
|
+
AUTH_VERSION_V1,
|
|
6404
|
+
AUTH_VERSION_V2,
|
|
6405
|
+
CODELIA_AUTH_KEYCHAIN_SERVICE,
|
|
6406
|
+
CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
|
|
6407
|
+
CredentialConflictError,
|
|
6408
|
+
DEFAULT_AUTH_LOCK_TIMEOUT_MS,
|
|
6409
|
+
DEFAULT_OAUTH_REFRESH_TIMEOUT_MS,
|
|
3903
6410
|
FileAttachmentStore,
|
|
3904
6411
|
IMAGE_MAX_BYTES,
|
|
3905
6412
|
ImageArtifactStore,
|
|
6413
|
+
KeychainError,
|
|
6414
|
+
MCP_AUTH_VERSION,
|
|
6415
|
+
MacOsKeychainClient,
|
|
3906
6416
|
McpAuthStore,
|
|
3907
6417
|
ProjectsPolicyStore,
|
|
3908
6418
|
RUN_LOG_RETENTION_MS,
|
|
@@ -3913,17 +6423,57 @@ ${snippet}`;
|
|
|
3913
6423
|
StoragePathServiceImpl,
|
|
3914
6424
|
TaskRegistryStore,
|
|
3915
6425
|
ToolOutputCacheStoreImpl,
|
|
6426
|
+
authLockPathFor,
|
|
6427
|
+
buildMcpAuthBinding,
|
|
6428
|
+
canonicalJsonEqual,
|
|
6429
|
+
canonicalJsonStringify,
|
|
6430
|
+
canonicalPathOrResolvedSync,
|
|
6431
|
+
canonicalizeMcpUri,
|
|
3916
6432
|
cleanupRunLogs,
|
|
6433
|
+
clearStoreAcrossAllLocationsUnlocked,
|
|
6434
|
+
coordinateCredentialBackend,
|
|
6435
|
+
coordinateCredentialBackendUnlocked,
|
|
3917
6436
|
createAttachmentId,
|
|
6437
|
+
deriveMcpIssuer,
|
|
3918
6438
|
detectImageAttachmentType,
|
|
6439
|
+
enforceWindowsOwnerOnlyDacl,
|
|
6440
|
+
ensureCredentialsDirectory,
|
|
3919
6441
|
ensureStorageDirs,
|
|
3920
6442
|
getProcessIdentity,
|
|
6443
|
+
inspectCredentialStorageStatus,
|
|
3921
6444
|
isAttachmentId,
|
|
6445
|
+
isCanonicalHomeWorkspaceSync,
|
|
6446
|
+
isSameConfigFilePath,
|
|
6447
|
+
isTrustedGlobalConfigLocationSync,
|
|
6448
|
+
isWithinPath,
|
|
6449
|
+
keychainAccountForConfigDir,
|
|
6450
|
+
mcpAuthBindingMatches,
|
|
6451
|
+
mcpAuthStoreAdapter,
|
|
6452
|
+
openSqlite,
|
|
6453
|
+
parseAuthDocument,
|
|
6454
|
+
parseAuthStorageState,
|
|
6455
|
+
parseMcpAuthDocument,
|
|
6456
|
+
providerAuthStoreAdapter,
|
|
6457
|
+
readAuthStorageState,
|
|
6458
|
+
readAuthStorageStateSync,
|
|
3922
6459
|
readRunLogLines,
|
|
6460
|
+
resolveConfiguredAuthStorageMode,
|
|
6461
|
+
resolveCredentialConflict,
|
|
3923
6462
|
resolveIndexedRunLog,
|
|
3924
6463
|
resolveRunLogPath,
|
|
3925
6464
|
resolveStoragePaths,
|
|
6465
|
+
resolveWindowsSystem32Dir,
|
|
6466
|
+
runTwoPhaseMigration,
|
|
3926
6467
|
scanSessionRunLogs,
|
|
3927
6468
|
validateImageAttachment,
|
|
3928
|
-
validateImagePng
|
|
6469
|
+
validateImagePng,
|
|
6470
|
+
verifyOwnedAncestors,
|
|
6471
|
+
verifyOwnedAncestorsSync,
|
|
6472
|
+
verifyUserStorageLocation,
|
|
6473
|
+
verifyUserStorageLocationSync,
|
|
6474
|
+
verifyWindowsCredentialFileAcl,
|
|
6475
|
+
verifyWindowsCredentialFileAclSync,
|
|
6476
|
+
withAuthStoreLock,
|
|
6477
|
+
writeAuthStorageState,
|
|
6478
|
+
writeFileAtomic
|
|
3929
6479
|
});
|