@cortexkit/common-auth 0.14.2 → 0.16.0
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/README.md +4 -4
- package/dist/claustrum/consumer.d.ts +33 -3
- package/dist/claustrum/consumer.js +96 -1
- package/dist/claustrum/custody.d.ts +4 -1
- package/dist/claustrum/enrollment.d.ts +3 -2
- package/dist/claustrum/enrollment.js +84 -42
- package/dist/claustrum/index.d.ts +2 -1
- package/dist/claustrum/index.js +5 -3
- package/dist/claustrum/insula.d.ts +69 -0
- package/dist/claustrum/insula.js +152 -0
- package/dist/claustrum/roster.d.ts +13 -0
- package/dist/claustrum/roster.js +28 -2
- package/dist/dump/index.d.ts +4 -3
- package/dist/dump/index.js +39 -12
- package/dist/fs/atomic-write.d.ts +5 -0
- package/dist/fs/atomic-write.js +21 -0
- package/dist/fs/index.d.ts +2 -0
- package/dist/fs/index.js +1 -0
- package/dist/fs/private-files.d.ts +66 -0
- package/dist/fs/private-files.js +302 -0
- package/dist/fs/refresh-file-lock.d.ts +1 -1
- package/dist/fs/refresh-file-lock.js +254 -37
- package/dist/fs/with-lock.d.ts +3 -0
- package/dist/fs/with-lock.js +4 -0
- package/dist/logger/engine.d.ts +6 -8
- package/dist/logger/engine.js +126 -11
- package/dist/pi-slot/slot.d.ts +2 -0
- package/dist/pi-slot/slot.js +34 -6
- package/dist/rpc/port-file.js +30 -8
- package/dist/rpc/rpc-client.js +15 -1
- package/dist/rpc/rpc-server.js +8 -3
- package/dist/setup/command-runner.d.ts +4 -0
- package/dist/setup/command-runner.js +49 -0
- package/dist/setup/command.d.ts +3 -0
- package/dist/setup/command.js +188 -0
- package/dist/setup/config-write.d.ts +11 -0
- package/dist/setup/config-write.js +60 -0
- package/dist/setup/detect.d.ts +6 -0
- package/dist/setup/detect.js +224 -0
- package/dist/setup/enroll.d.ts +4 -0
- package/dist/setup/enroll.js +70 -0
- package/dist/setup/index.d.ts +5 -0
- package/dist/setup/index.js +4 -0
- package/dist/setup/paths.d.ts +11 -0
- package/dist/setup/paths.js +33 -0
- package/dist/setup/process-fence.d.ts +41 -0
- package/dist/setup/process-fence.js +177 -0
- package/dist/setup/prompts.d.ts +4 -0
- package/dist/setup/prompts.js +26 -0
- package/dist/setup/register.d.ts +11 -0
- package/dist/setup/register.js +130 -0
- package/dist/setup/types.d.ts +93 -0
- package/dist/setup/types.js +1 -0
- package/dist/sidebar-file/sidebar-file.d.ts +5 -4
- package/dist/sidebar-file/sidebar-file.js +17 -8
- package/dist/store/mutate.js +2 -2
- package/dist/store/pool.d.ts +1 -0
- package/dist/store/pool.js +3 -0
- package/dist/store/refresh-lock.d.ts +4 -0
- package/dist/store/refresh-lock.js +5 -0
- package/dist/tui-prefs/tui-preferences.js +6 -4
- package/dist/tui-prefs/watcher.d.ts +3 -0
- package/dist/tui-prefs/watcher.js +26 -10
- package/package.json +14 -3
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { storeIdentity } from '@cortexkit/claustrum-client';
|
|
3
|
+
// A static import: claustrum-client already loads subc-client whenever
|
|
4
|
+
// /claustrum is imported, so loading it lazily saves nothing, and a dynamic
|
|
5
|
+
// import makes bundlers emit a separate chunk that a running host loses when
|
|
6
|
+
// its dist folder is rebuilt underneath it.
|
|
7
|
+
import { SubcClient } from '@cortexkit/subc-client';
|
|
8
|
+
/** Constructing this transport opens no connection; getUsage opens one per call. */
|
|
9
|
+
export function insulaUsageTransport(options) {
|
|
10
|
+
const identity = options.identity ??
|
|
11
|
+
storeIdentity(options.projectRoot ?? process.cwd(), options.storagePath ?? process.cwd());
|
|
12
|
+
return {
|
|
13
|
+
connectionFile: options.connectionFile,
|
|
14
|
+
async getUsage() {
|
|
15
|
+
let client;
|
|
16
|
+
let expired = false;
|
|
17
|
+
let timer;
|
|
18
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
19
|
+
timer = setTimeout(() => reject(new Error('insula usage timeout')), 3_000);
|
|
20
|
+
timer.unref?.();
|
|
21
|
+
});
|
|
22
|
+
const request = (async () => {
|
|
23
|
+
client = options.connector
|
|
24
|
+
? await options.connector({
|
|
25
|
+
connectionFile: options.connectionFile,
|
|
26
|
+
handshakeTimeoutMs: Math.min(options.handshakeTimeoutMs ?? 3_000, 3_000),
|
|
27
|
+
})
|
|
28
|
+
: await SubcClient.connect({
|
|
29
|
+
connectionFile: options.connectionFile,
|
|
30
|
+
handshakeTimeoutMs: Math.min(options.handshakeTimeoutMs ?? 3_000, 3_000),
|
|
31
|
+
});
|
|
32
|
+
// A slow connector may resolve after the whole-call deadline. It still
|
|
33
|
+
// owns a socket, which must not survive or open a route after fallback.
|
|
34
|
+
if (expired) {
|
|
35
|
+
client.close();
|
|
36
|
+
throw new Error('insula usage timeout');
|
|
37
|
+
}
|
|
38
|
+
// Managed call() retries warming routes. A single routeOpen/request
|
|
39
|
+
// instead lets the plugin fall back as soon as the daemon refuses.
|
|
40
|
+
const route = await client.routeOpen({ kind: 'management_surface', module_id: 'insula' }, identity);
|
|
41
|
+
return await client.request(route, { method: 'usage.get', params: {} });
|
|
42
|
+
})();
|
|
43
|
+
try {
|
|
44
|
+
return await Promise.race([request, timeout]);
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
expired = true;
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
client?.close();
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
const MINUTE = 60_000;
|
|
55
|
+
const MAX_AGE = 4 * MINUTE;
|
|
56
|
+
const sources = new Map();
|
|
57
|
+
// Keep only the minute budget after the last owner closes, so project churn
|
|
58
|
+
// cannot reset the bound. Expired budgets are pruned on the next tick.
|
|
59
|
+
const attempts = new Map();
|
|
60
|
+
function record(value) {
|
|
61
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
62
|
+
}
|
|
63
|
+
export class InsulaQuotaSource {
|
|
64
|
+
transport;
|
|
65
|
+
key;
|
|
66
|
+
#entries = [];
|
|
67
|
+
#pending;
|
|
68
|
+
constructor(transport, key) {
|
|
69
|
+
this.transport = transport;
|
|
70
|
+
this.key = key;
|
|
71
|
+
}
|
|
72
|
+
refresh(now) {
|
|
73
|
+
if (this.#pending)
|
|
74
|
+
return this.#pending;
|
|
75
|
+
for (const [key, time] of attempts) {
|
|
76
|
+
if (now - time >= MINUTE)
|
|
77
|
+
attempts.delete(key);
|
|
78
|
+
}
|
|
79
|
+
const lastAttempt = attempts.get(this.key);
|
|
80
|
+
if (lastAttempt !== undefined && now - lastAttempt < MINUTE)
|
|
81
|
+
return Promise.resolve();
|
|
82
|
+
// Reserve the minute before I/O, so concurrent projects cannot each poll.
|
|
83
|
+
attempts.set(this.key, now);
|
|
84
|
+
this.#pending = (async () => {
|
|
85
|
+
try {
|
|
86
|
+
const reply = await this.transport.getUsage();
|
|
87
|
+
if (!record(reply) ||
|
|
88
|
+
!Array.isArray(reply.result) ||
|
|
89
|
+
reply.error !== undefined)
|
|
90
|
+
throw new Error('unavailable insula usage');
|
|
91
|
+
// Each response is a snapshot, not a delta. Missing accounts fall back;
|
|
92
|
+
// neither pending nor the entry count asserts provider completeness.
|
|
93
|
+
this.#entries = reply.result.filter((entry) => record(entry) && typeof entry.provider === 'string');
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
// Refusal is absence, even if the previous reading was still young.
|
|
97
|
+
this.#entries = [];
|
|
98
|
+
}
|
|
99
|
+
})().finally(() => {
|
|
100
|
+
this.#pending = undefined;
|
|
101
|
+
});
|
|
102
|
+
return this.#pending;
|
|
103
|
+
}
|
|
104
|
+
current(provider, accountId, now) {
|
|
105
|
+
for (const entry of this.#entries) {
|
|
106
|
+
if (entry.provider !== provider ||
|
|
107
|
+
typeof entry.account !== 'string' ||
|
|
108
|
+
entry.account.trim() !== accountId)
|
|
109
|
+
continue;
|
|
110
|
+
if (entry.stale !== undefined ||
|
|
111
|
+
entry.errorClass !== undefined ||
|
|
112
|
+
!record(entry.usage))
|
|
113
|
+
continue;
|
|
114
|
+
const fetchedAt = typeof entry.fetchedAt === 'string'
|
|
115
|
+
? Date.parse(entry.fetchedAt)
|
|
116
|
+
: Number.NaN;
|
|
117
|
+
if (!Number.isFinite(fetchedAt) || now - fetchedAt >= MAX_AGE)
|
|
118
|
+
continue;
|
|
119
|
+
return {
|
|
120
|
+
entry,
|
|
121
|
+
context: {
|
|
122
|
+
fetchedAt,
|
|
123
|
+
...(typeof entry.source === 'string' && { source: entry.source }),
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
export function acquireInsulaQuotaSource(transport, tokenPath) {
|
|
131
|
+
const key = JSON.stringify([
|
|
132
|
+
resolve(transport.connectionFile),
|
|
133
|
+
resolve(tokenPath),
|
|
134
|
+
]);
|
|
135
|
+
let shared = sources.get(key);
|
|
136
|
+
if (!shared) {
|
|
137
|
+
shared = { source: new InsulaQuotaSource(transport, key), refs: 0 };
|
|
138
|
+
sources.set(key, shared);
|
|
139
|
+
}
|
|
140
|
+
shared.refs++;
|
|
141
|
+
let released = false;
|
|
142
|
+
return {
|
|
143
|
+
source: shared.source,
|
|
144
|
+
release() {
|
|
145
|
+
if (released)
|
|
146
|
+
return;
|
|
147
|
+
released = true;
|
|
148
|
+
if (--shared.refs === 0)
|
|
149
|
+
sources.delete(key);
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
}
|
|
@@ -133,6 +133,19 @@ export declare function recordVaultQuota(path: string, input: QuotaReceipt & {
|
|
|
133
133
|
routeId: string;
|
|
134
134
|
observation: QuotaObservation;
|
|
135
135
|
}): Promise<boolean>;
|
|
136
|
+
/**
|
|
137
|
+
* Merge a quota observation that belongs to an account rather than to a
|
|
138
|
+
* served credential, such as a background reading from insula. The write
|
|
139
|
+
* lands only while the row is still bound to that exact known account, so a
|
|
140
|
+
* reading taken before a replacement never reaches the successor. Unlike
|
|
141
|
+
* `recordVaultQuota` it never binds an account: a row without a known account
|
|
142
|
+
* is refused. Returns whether the observation was kept.
|
|
143
|
+
*/
|
|
144
|
+
export declare function recordVaultAccountQuota(path: string, input: {
|
|
145
|
+
routeId: string;
|
|
146
|
+
accountIdentity: string;
|
|
147
|
+
observation: QuotaObservation;
|
|
148
|
+
}): Promise<boolean>;
|
|
136
149
|
/**
|
|
137
150
|
* Discover and commit the roster. The lease covers the list call and the
|
|
138
151
|
* commit, not just the write: an opaque view cannot tell a delayed old reply
|
package/dist/claustrum/roster.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import { readFile } from 'node:fs/promises';
|
|
3
2
|
import { acquireRefreshFileLock, withLock, writeJsonAtomic, } from '../fs/index.js';
|
|
3
|
+
import { readPrivateText, windowsPrivateFiles } from '../fs/private-files.js';
|
|
4
4
|
import { isQuotaMap, mergeQuotaObservation, } from '../quota/index.js';
|
|
5
5
|
import { ClaustrumConsumerError } from './errors.js';
|
|
6
6
|
import { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
|
|
@@ -289,7 +289,7 @@ function decodeRoster(value) {
|
|
|
289
289
|
export async function readVaultRoster(path) {
|
|
290
290
|
let text;
|
|
291
291
|
try {
|
|
292
|
-
text = await
|
|
292
|
+
text = await readPrivateText(path, windowsPrivateFiles);
|
|
293
293
|
}
|
|
294
294
|
catch (error) {
|
|
295
295
|
if (error.code === 'ENOENT')
|
|
@@ -435,6 +435,32 @@ export function recordVaultQuota(path, input) {
|
|
|
435
435
|
};
|
|
436
436
|
});
|
|
437
437
|
}
|
|
438
|
+
/**
|
|
439
|
+
* Merge a quota observation that belongs to an account rather than to a
|
|
440
|
+
* served credential, such as a background reading from insula. The write
|
|
441
|
+
* lands only while the row is still bound to that exact known account, so a
|
|
442
|
+
* reading taken before a replacement never reaches the successor. Unlike
|
|
443
|
+
* `recordVaultQuota` it never binds an account: a row without a known account
|
|
444
|
+
* is refused. Returns whether the observation was kept.
|
|
445
|
+
*/
|
|
446
|
+
export function recordVaultAccountQuota(path, input) {
|
|
447
|
+
return mutateVaultRoster(path, (current) => {
|
|
448
|
+
const row = current?.rows.find((entry) => entry.routeId === input.routeId);
|
|
449
|
+
if (!current ||
|
|
450
|
+
!row ||
|
|
451
|
+
row.accountIdentity === undefined ||
|
|
452
|
+
row.accountIdentity !== input.accountIdentity)
|
|
453
|
+
return { result: false };
|
|
454
|
+
const quota = mergeQuotaObservation(row.quota, input.observation);
|
|
455
|
+
return {
|
|
456
|
+
next: {
|
|
457
|
+
...current,
|
|
458
|
+
rows: current.rows.map((entry) => entry === row ? { ...entry, quota } : entry),
|
|
459
|
+
},
|
|
460
|
+
result: true,
|
|
461
|
+
};
|
|
462
|
+
});
|
|
463
|
+
}
|
|
438
464
|
/**
|
|
439
465
|
* Discover and commit the roster. The lease covers the list call and the
|
|
440
466
|
* commit, not just the write: an opaque view cannot tell a delayed old reply
|
package/dist/dump/index.d.ts
CHANGED
|
@@ -171,10 +171,11 @@ export interface SweepDumpDirectoryOptions {
|
|
|
171
171
|
* writes are counted or removed, so unrelated files in a directory the user
|
|
172
172
|
* chose survive. A dump's files are evicted together, oldest dump first by
|
|
173
173
|
* its newest file, because a body without its metadata (or the reverse) is no
|
|
174
|
-
* use to anyone. Dumps younger than `minAgeMs`,
|
|
175
|
-
* are kept, and a symlinked directory
|
|
174
|
+
* use to anyone. Dumps younger than `minAgeMs`, caller-listed `protectedPaths`
|
|
175
|
+
* (such as a just-written dump) and symlinks are kept, and a symlinked directory
|
|
176
|
+
* is refused outright. Response staging
|
|
176
177
|
* files left by a crash are reclaimed once stale, even under the cap.
|
|
177
|
-
*
|
|
178
|
+
* Cleanup is best-effort, but Windows refuses an unverified private directory.
|
|
178
179
|
*/
|
|
179
180
|
export declare function sweepDumpDirectory(options: SweepDumpDirectoryOptions): Promise<DumpSweepResult>;
|
|
180
181
|
/**
|
package/dist/dump/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
-
import { chmod, lstat, mkdir, open, readdir,
|
|
2
|
+
import { chmod, lstat, mkdir, open, readdir, rename, unlink, writeFile, } from 'node:fs/promises';
|
|
3
3
|
import { join, resolve } from 'node:path';
|
|
4
|
+
import { createPrivateBytes, ensurePrivateDirectory, PrivateFileError, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from '../fs/private-files.js';
|
|
4
5
|
import { createRedactor } from '../logger/redact.js';
|
|
5
6
|
const PREVIOUS_BODY_LIMIT = 100;
|
|
6
7
|
const UNKNOWN_SESSION = 'session-unknown';
|
|
@@ -36,10 +37,11 @@ function isPartialName(name) {
|
|
|
36
37
|
* writes are counted or removed, so unrelated files in a directory the user
|
|
37
38
|
* chose survive. A dump's files are evicted together, oldest dump first by
|
|
38
39
|
* its newest file, because a body without its metadata (or the reverse) is no
|
|
39
|
-
* use to anyone. Dumps younger than `minAgeMs`,
|
|
40
|
-
* are kept, and a symlinked directory
|
|
40
|
+
* use to anyone. Dumps younger than `minAgeMs`, caller-listed `protectedPaths`
|
|
41
|
+
* (such as a just-written dump) and symlinks are kept, and a symlinked directory
|
|
42
|
+
* is refused outright. Response staging
|
|
41
43
|
* files left by a crash are reclaimed once stale, even under the cap.
|
|
42
|
-
*
|
|
44
|
+
* Cleanup is best-effort, but Windows refuses an unverified private directory.
|
|
43
45
|
*/
|
|
44
46
|
export async function sweepDumpDirectory(options) {
|
|
45
47
|
const { dir, maxBytes } = options;
|
|
@@ -50,6 +52,8 @@ export async function sweepDumpDirectory(options) {
|
|
|
50
52
|
if (!(maxBytes > 0))
|
|
51
53
|
return empty;
|
|
52
54
|
try {
|
|
55
|
+
if (windowsPrivateFiles)
|
|
56
|
+
await verifyPrivate(dir, 'directory');
|
|
53
57
|
if ((await lstat(dir)).isSymbolicLink())
|
|
54
58
|
return empty;
|
|
55
59
|
const protectedPaths = new Set((options.protectedPaths ?? []).map((path) => resolve(path)));
|
|
@@ -123,7 +127,10 @@ export async function sweepDumpDirectory(options) {
|
|
|
123
127
|
}
|
|
124
128
|
return { removed, freedBytes };
|
|
125
129
|
}
|
|
126
|
-
catch {
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (error instanceof PrivateFileError &&
|
|
132
|
+
error.code === 'ERR_PRIVATE_FILES_SECURITY')
|
|
133
|
+
throw error;
|
|
127
134
|
return empty;
|
|
128
135
|
}
|
|
129
136
|
}
|
|
@@ -133,6 +140,11 @@ export async function sweepDumpDirectory(options) {
|
|
|
133
140
|
* staging name is never followed.
|
|
134
141
|
*/
|
|
135
142
|
async function replaceFile(path, text, stageName) {
|
|
143
|
+
if (windowsPrivateFiles) {
|
|
144
|
+
return writePrivateAtomic(path, text, {
|
|
145
|
+
stagePath: `${path}.${stageName ? stageName() : randomBytes(12).toString('hex')}.partial`,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
136
148
|
for (let attempt = 0;; attempt += 1) {
|
|
137
149
|
const staging = `${path}.${stageName ? stageName() : randomBytes(12).toString('hex')}.partial`;
|
|
138
150
|
let created = false;
|
|
@@ -322,12 +334,15 @@ export function createDumper(options) {
|
|
|
322
334
|
.reverse();
|
|
323
335
|
for (const name of candidates) {
|
|
324
336
|
try {
|
|
325
|
-
const metadata = JSON.parse(await
|
|
337
|
+
const metadata = JSON.parse(await readPrivateText(join(dir, name), windowsPrivateFiles));
|
|
326
338
|
if (metadata?.baselineKey !== baselineKey)
|
|
327
339
|
continue;
|
|
328
|
-
return await
|
|
340
|
+
return await readPrivateText(join(dir, name.replace(/\.meta\.json$/, '.body.json')), windowsPrivateFiles);
|
|
329
341
|
}
|
|
330
|
-
catch {
|
|
342
|
+
catch (error) {
|
|
343
|
+
if (error instanceof PrivateFileError &&
|
|
344
|
+
(windowsPrivateFiles || error.code === 'ERR_PRIVATE_FILES_SECURITY'))
|
|
345
|
+
throw error;
|
|
331
346
|
// A file removed or half-written by another process: try the next.
|
|
332
347
|
}
|
|
333
348
|
}
|
|
@@ -372,9 +387,13 @@ export function createDumper(options) {
|
|
|
372
387
|
// full session id.
|
|
373
388
|
const baselineKey = hashText(`${input.channel}\u0000${session}`);
|
|
374
389
|
try {
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
390
|
+
if (windowsPrivateFiles)
|
|
391
|
+
await ensurePrivateDirectory(dir);
|
|
392
|
+
else {
|
|
393
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
394
|
+
// mkdir's mode does not apply to a directory that already exists.
|
|
395
|
+
await chmod(dir, 0o700);
|
|
396
|
+
}
|
|
378
397
|
let previous = previousBodies.get(baselineKey);
|
|
379
398
|
let baselineSource = previous === undefined ? undefined : 'memory';
|
|
380
399
|
if (previous === undefined) {
|
|
@@ -418,7 +437,9 @@ export function createDumper(options) {
|
|
|
418
437
|
: Object.fromEntries(new Headers(input.headers).entries()),
|
|
419
438
|
});
|
|
420
439
|
// `wx`: a name collision fails loudly instead of overwriting a dump.
|
|
421
|
-
const write = (path, text) =>
|
|
440
|
+
const write = (path, text) => windowsPrivateFiles
|
|
441
|
+
? createPrivateBytes(path, text)
|
|
442
|
+
: writeFile(path, text, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
422
443
|
const writes = [
|
|
423
444
|
[files.body, body.text],
|
|
424
445
|
[files.metadata, `${JSON.stringify(metadata, null, 2)}\n`],
|
|
@@ -443,6 +464,9 @@ export function createDumper(options) {
|
|
|
443
464
|
return { id, files, responseFile: `${prefix}.response.json` };
|
|
444
465
|
}
|
|
445
466
|
catch (error) {
|
|
467
|
+
if (error instanceof PrivateFileError &&
|
|
468
|
+
(windowsPrivateFiles || error.code === 'ERR_PRIVATE_FILES_SECURITY'))
|
|
469
|
+
throw error;
|
|
446
470
|
log?.warn('request dump failed', {
|
|
447
471
|
session: shortSession(session),
|
|
448
472
|
error: error instanceof Error ? error.message : String(error),
|
|
@@ -506,6 +530,9 @@ export function createDumper(options) {
|
|
|
506
530
|
return result.responseFile;
|
|
507
531
|
}
|
|
508
532
|
catch (error) {
|
|
533
|
+
if (error instanceof PrivateFileError &&
|
|
534
|
+
(windowsPrivateFiles || error.code === 'ERR_PRIVATE_FILES_SECURITY'))
|
|
535
|
+
throw error;
|
|
509
536
|
log?.warn('response dump failed', {
|
|
510
537
|
id: result.id,
|
|
511
538
|
error: error instanceof Error ? error.message : String(error),
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type PrivateWriteOutcome } from './private-files.js';
|
|
1
2
|
export interface AtomicWriteOptions {
|
|
2
3
|
serialize?: (value: unknown) => string;
|
|
3
4
|
beforeRename?: () => Promise<void>;
|
|
@@ -5,6 +6,10 @@ export interface AtomicWriteOptions {
|
|
|
5
6
|
stageName?: () => string;
|
|
6
7
|
/** Sync the staged file and, after rename, its parent directory. Opt-in. */
|
|
7
8
|
durable?: boolean;
|
|
9
|
+
/** Windows opt-in: flush file bytes, without promising directory metadata durability. */
|
|
10
|
+
durability?: 'file-only-on-windows';
|
|
11
|
+
/** Reports Windows rename success, file/directory durability, retry counts and error codes, never file bytes. */
|
|
12
|
+
onOutcome?: (outcome: PrivateWriteOutcome) => void;
|
|
8
13
|
}
|
|
9
14
|
/** Internal classification of fsync failures, including a failure after rename. */
|
|
10
15
|
export declare class AtomicSyncError extends Error {
|
package/dist/fs/atomic-write.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { mkdir, open, rename, rm } from 'node:fs/promises';
|
|
3
3
|
import { dirname } from 'node:path';
|
|
4
|
+
import { PrivateFileError, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from './private-files.js';
|
|
4
5
|
/** Internal classification of fsync failures, including a failure after rename. */
|
|
5
6
|
export class AtomicSyncError extends Error {
|
|
6
7
|
constructor(cause) {
|
|
@@ -16,6 +17,18 @@ export async function writeJsonAtomic(path, value, options = {}) {
|
|
|
16
17
|
* and removed ids here, because a later directory sync cannot undo the rename.
|
|
17
18
|
*/
|
|
18
19
|
export async function writeJsonAtomicTracked(path, value, options, onRenamed) {
|
|
20
|
+
if (windowsPrivateFiles) {
|
|
21
|
+
return writePrivateAtomic(path, options.serialize
|
|
22
|
+
? options.serialize(value)
|
|
23
|
+
: `${JSON.stringify(value, null, 2)}\n`, {
|
|
24
|
+
beforeRename: options.beforeRename,
|
|
25
|
+
stagePath: `${path}.${(options.stageName ?? randomUUID)()}.tmp`,
|
|
26
|
+
onRenamed,
|
|
27
|
+
durable: options.durable,
|
|
28
|
+
durability: options.durability,
|
|
29
|
+
onOutcome: options.onOutcome,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
19
32
|
await mkdir(dirname(path), { recursive: true });
|
|
20
33
|
const tempPath = `${path}.${(options.stageName ?? randomUUID)()}.tmp`;
|
|
21
34
|
let handle;
|
|
@@ -63,6 +76,14 @@ export async function writeJsonAtomicTracked(path, value, options, onRenamed) {
|
|
|
63
76
|
}
|
|
64
77
|
/** Make an already renamed file and its directory durable without rewriting bytes. */
|
|
65
78
|
export async function syncJsonFile(path) {
|
|
79
|
+
if (windowsPrivateFiles) {
|
|
80
|
+
await verifyPrivate(path, 'file');
|
|
81
|
+
const error = new PrivateFileError(path, 'directory-sync-unsupported', {
|
|
82
|
+
code: 'ENOTSUP',
|
|
83
|
+
});
|
|
84
|
+
error.published = true;
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
66
87
|
const file = await open(path, 'r');
|
|
67
88
|
try {
|
|
68
89
|
await file.sync();
|
package/dist/fs/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
export type { AtomicWriteOptions } from './atomic-write.js';
|
|
2
2
|
export { writeJsonAtomic } from './atomic-write.js';
|
|
3
3
|
export { WRITER_LOCK_CONSTANTS } from './lock-constants.js';
|
|
4
|
+
export type { PrivateWriteOutcome } from './private-files.js';
|
|
5
|
+
export { PrivateFileError } from './private-files.js';
|
|
4
6
|
export type { LockLoss, RefreshFileLock } from './refresh-file-lock.js';
|
|
5
7
|
export { acquireRefreshFileLock, isLostMarkerRaceError, } from './refresh-file-lock.js';
|
|
6
8
|
export type { LockOptions, LockOwnershipDetails } from './with-lock.js';
|
package/dist/fs/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { writeJsonAtomic } from './atomic-write.js';
|
|
2
2
|
export { WRITER_LOCK_CONSTANTS } from './lock-constants.js';
|
|
3
|
+
export { PrivateFileError } from './private-files.js';
|
|
3
4
|
// The try-once lock underneath withLock, for callers that hold a lock across
|
|
4
5
|
// several steps or poll instead of waiting (for example a refresh lease).
|
|
5
6
|
export { acquireRefreshFileLock, isLostMarkerRaceError, } from './refresh-file-lock.js';
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { rename } from 'node:fs/promises';
|
|
2
|
+
import type { PosixOwnerOnlyPathAsyncOptions } from '@cortexkit/private-files';
|
|
3
|
+
export declare const windowsPrivateFiles: boolean;
|
|
4
|
+
type Backend = typeof import('@cortexkit/private-files');
|
|
5
|
+
type Kind = 'file' | 'directory';
|
|
6
|
+
/** Tests inject a backend here; production always imports the private-files package. */
|
|
7
|
+
export declare function setPrivateFilesBackendForTest(api?: Backend): void;
|
|
8
|
+
export declare class PrivateFileError extends Error {
|
|
9
|
+
readonly path: string;
|
|
10
|
+
readonly stage: string;
|
|
11
|
+
readonly code: string;
|
|
12
|
+
readonly win32Code?: number;
|
|
13
|
+
readonly reason?: string;
|
|
14
|
+
published: boolean;
|
|
15
|
+
durabilityConfirmed: boolean;
|
|
16
|
+
fileDurable: boolean;
|
|
17
|
+
attempts: number;
|
|
18
|
+
elapsedMs: number;
|
|
19
|
+
orphanPath?: string;
|
|
20
|
+
constructor(path: string, stage: string, cause: unknown);
|
|
21
|
+
}
|
|
22
|
+
export declare function privateOperation<T>(path: string, stage: string, operation: () => Promise<T>): Promise<T>;
|
|
23
|
+
/** Tests only: policy options used by safe-parent checks that pass none. */
|
|
24
|
+
export declare function setSafeParentOptionsForTest(options?: PosixOwnerOnlyPathAsyncOptions): void;
|
|
25
|
+
/** Existing containing directories use the shared entry-integrity policy, not secret-file permissions. */
|
|
26
|
+
export declare function verifySafeDirectory(path: string, options?: PosixOwnerOnlyPathAsyncOptions): Promise<void>;
|
|
27
|
+
/** Repair only the specific owned secret file supplied by a caller, never an existing directory tree. */
|
|
28
|
+
export declare function verifyPrivate(path: string, kind: Kind, migrate?: boolean): Promise<void>;
|
|
29
|
+
/** Create missing components privately; inspect existing ancestors without modifying them. */
|
|
30
|
+
export declare function ensurePrivateDirectory(path: string, _migrate?: boolean, options?: PosixOwnerOnlyPathAsyncOptions): Promise<void>;
|
|
31
|
+
export declare function readPrivateText(path: string, migrate?: boolean): Promise<string>;
|
|
32
|
+
export declare function readPrivateBuffer(path: string, migrate?: boolean): Promise<Buffer>;
|
|
33
|
+
export declare function createPrivateBytes(path: string, bytes: string): Promise<void>;
|
|
34
|
+
export declare function createPrivateDirectoryExclusive(path: string): Promise<void>;
|
|
35
|
+
export interface ReplaceOptions {
|
|
36
|
+
beforeRename?: () => Promise<void>;
|
|
37
|
+
/** Absolute monotonic deadline, for an expiring lease. */
|
|
38
|
+
deadline?: number;
|
|
39
|
+
now?: () => number;
|
|
40
|
+
sleep?: (ms: number) => Promise<void>;
|
|
41
|
+
rename?: typeof rename;
|
|
42
|
+
}
|
|
43
|
+
/** Retry Windows rename sharing/access errors within a budget; they never prove lease contention. */
|
|
44
|
+
export declare function replaceWindowsFile(from: string, to: string, options?: ReplaceOptions): Promise<{
|
|
45
|
+
attempts: number;
|
|
46
|
+
elapsedMs: number;
|
|
47
|
+
}>;
|
|
48
|
+
export interface PrivateWriteOutcome {
|
|
49
|
+
path: string;
|
|
50
|
+
stage: string;
|
|
51
|
+
published: boolean;
|
|
52
|
+
fileDurable: boolean;
|
|
53
|
+
durabilityConfirmed: boolean;
|
|
54
|
+
attempts: number;
|
|
55
|
+
elapsedMs: number;
|
|
56
|
+
code?: string;
|
|
57
|
+
win32Code?: number;
|
|
58
|
+
}
|
|
59
|
+
export declare function writePrivateAtomic(path: string, bytes: string, options?: ReplaceOptions & {
|
|
60
|
+
stagePath?: string;
|
|
61
|
+
onRenamed?: () => void;
|
|
62
|
+
durable?: boolean;
|
|
63
|
+
durability?: 'file-only-on-windows';
|
|
64
|
+
onOutcome?: (outcome: PrivateWriteOutcome) => void;
|
|
65
|
+
}): Promise<void>;
|
|
66
|
+
export {};
|