@ant0/mcp 0.0.0-stage → 0.3.22-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +95 -2
  3. package/THIRD_PARTY_NOTICES +311 -0
  4. package/dist/api/generated/schema.d.ts +3856 -0
  5. package/dist/api/generated/schema.js +6 -0
  6. package/dist/api/index.d.ts +171 -0
  7. package/dist/api/index.js +332 -0
  8. package/dist/bin.d.ts +3 -0
  9. package/dist/bin.js +59 -0
  10. package/dist/call-permits.d.ts +10 -0
  11. package/dist/call-permits.js +67 -0
  12. package/dist/connection.d.ts +20 -0
  13. package/dist/connection.js +157 -0
  14. package/dist/credential-file.d.ts +33 -0
  15. package/dist/credential-file.js +773 -0
  16. package/dist/daemon.d.ts +7 -0
  17. package/dist/daemon.js +260 -0
  18. package/dist/errors.d.ts +69 -0
  19. package/dist/errors.js +78 -0
  20. package/dist/export-files.d.ts +37 -0
  21. package/dist/export-files.js +167 -0
  22. package/dist/grant.d.ts +5 -0
  23. package/dist/grant.js +11 -0
  24. package/dist/http.d.ts +59 -0
  25. package/dist/http.js +556 -0
  26. package/dist/index.d.ts +19 -0
  27. package/dist/index.js +85 -0
  28. package/dist/key-contract.d.ts +325 -0
  29. package/dist/key-contract.js +241 -0
  30. package/dist/limits.d.ts +22 -0
  31. package/dist/limits.js +22 -0
  32. package/dist/local-routes.d.ts +26 -0
  33. package/dist/local-routes.js +146 -0
  34. package/dist/output-descriptor.d.ts +3 -0
  35. package/dist/output-descriptor.js +19 -0
  36. package/dist/output-worker-body.d.ts +3 -0
  37. package/dist/output-worker-body.js +77 -0
  38. package/dist/output-worker.d.ts +2 -0
  39. package/dist/output-worker.js +4 -0
  40. package/dist/output-writer.d.ts +39 -0
  41. package/dist/output-writer.js +199 -0
  42. package/dist/peer-watchdog.d.ts +4 -0
  43. package/dist/peer-watchdog.js +55 -0
  44. package/dist/server.d.ts +28 -0
  45. package/dist/server.js +33 -0
  46. package/dist/text-budget.d.ts +13 -0
  47. package/dist/text-budget.js +42 -0
  48. package/dist/tools.d.ts +38 -0
  49. package/dist/tools.js +1284 -0
  50. package/dist/transport.d.ts +45 -0
  51. package/dist/transport.js +313 -0
  52. package/package.json +66 -4
@@ -0,0 +1,773 @@
1
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
2
+ import { execFile, execFileSync } from "node:child_process";
3
+ import { closeSync, constants, fsyncSync, fstatSync as nativeFstatSync, linkSync, lstatSync as nativeLstatSync, openSync, readSync, readdirSync, unlinkSync, writeFileSync, } from "node:fs";
4
+ import { dirname, join, parse, resolve } from "node:path";
5
+ import { CredentialFailure, credentialFileSchema, matchingMetadata, credentialResultSchema, rejectCredentialEcho, } from "./key-contract.js";
6
+ export * from "./key-contract.js";
7
+ const MAX_BYTES = 64 * 1024;
8
+ // File IDs can exceed JavaScript's safe-integer range on Windows. Preserve their exact bits.
9
+ const lstatSync = (path) => nativeLstatSync(path, { bigint: true });
10
+ const fstatSync = (fd) => nativeFstatSync(fd, { bigint: true });
11
+ const fail = () => new CredentialFailure();
12
+ const same = (a, b) => a.dev === b.dev &&
13
+ a.ino === b.ino &&
14
+ a.nlink === b.nlink &&
15
+ a.mode === b.mode &&
16
+ a.uid === b.uid &&
17
+ a.gid === b.gid &&
18
+ a.size === b.size &&
19
+ a.mtimeNs === b.mtimeNs &&
20
+ a.ctimeNs === b.ctimeNs;
21
+ // Higher ancestors have an identity/reparse policy, not a private-ACL policy. Their content
22
+ // timestamps can change on every PowerShell startup (__PSScriptPolicyTest_* in %TEMP%).
23
+ // Files and the immediate private parent retain the complete permission/ChangeTime fence.
24
+ const sameBoundary = (a, b, privateAcl) => privateAcl
25
+ ? same(a, b)
26
+ : a.dev === b.dev &&
27
+ a.ino === b.ino &&
28
+ a.isDirectory() &&
29
+ b.isDirectory() &&
30
+ !a.isSymbolicLink() &&
31
+ !b.isSymbolicLink();
32
+ function parentEvidence(file) {
33
+ const result = [];
34
+ for (let path = dirname(file);; path = dirname(path)) {
35
+ const stat = lstatSync(path);
36
+ if (!stat.isDirectory() || stat.isSymbolicLink() || result.length >= 256)
37
+ throw fail();
38
+ result.push({ path, stat, privateAcl: path === dirname(file) });
39
+ if (path === parse(path).root)
40
+ return result;
41
+ }
42
+ }
43
+ function sameParents(before, after) {
44
+ return (before.length === after.length &&
45
+ before.every((value, i) => value.path === after[i].path && sameBoundary(value.stat, after[i].stat, value.privateAcl)));
46
+ }
47
+ // Never interpolate file paths or secrets into a shell command. Fail closed if ACL inspection is
48
+ // unavailable. Ancestors are checked for reparse points separately, including junctions.
49
+ const WINDOWS_ACL_SCRIPT = `
50
+ $ErrorActionPreference = 'Stop'
51
+ $p = $env:ANT0_PRIVATE_FILE
52
+ function Test-Private($p, $action) {
53
+ $item = Get-Item -LiteralPath $p -Force
54
+ if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'reparse' }
55
+ if ($action -eq 'ancestor') { return }
56
+ $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User
57
+ if ($action -eq 'private') {
58
+ $acl = if ($item.PSIsContainer) { New-Object Security.AccessControl.DirectorySecurity } else { New-Object Security.AccessControl.FileSecurity }
59
+ $acl.SetOwner($sid)
60
+ $acl.SetAccessRuleProtection($true, $false)
61
+ $rule = New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'Allow')
62
+ $acl.AddAccessRule($rule)
63
+ $system = New-Object Security.Principal.SecurityIdentifier('S-1-5-18')
64
+ $acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($system, 'FullControl', 'Allow')))
65
+ Set-Acl -LiteralPath $p -AclObject $acl
66
+ }
67
+ $acl = Get-Acl -LiteralPath $p
68
+ if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value -or !$acl.AreAccessRulesProtected) { throw 'owner' }
69
+ $rules = $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])
70
+ $ownerAllow = $false
71
+ $systemAllow = $false
72
+ if ($rules.Count -ne 2) { throw 'access' }
73
+ foreach ($r in $rules) {
74
+ if ($r.AccessControlType -ne 'Allow' -or $r.IsInherited) { throw 'access' }
75
+ $full = [int][Security.AccessControl.FileSystemRights]::FullControl
76
+ if (([int]$r.FileSystemRights -band $full) -ne $full) { throw 'access' }
77
+ if ($r.IdentityReference.Value -eq $sid.Value) { $ownerAllow = $true }
78
+ elseif ($r.IdentityReference.Value -eq 'S-1-5-18') { $systemAllow = $true }
79
+ else { throw 'access' }
80
+ }
81
+ if (!$ownerAllow -or !$systemAllow) { throw 'access' }
82
+ }
83
+ if ($env:ANT0_PRIVATE_ACTION -eq 'batch' -or $env:ANT0_PRIVATE_ACTION -eq 'all' -or $env:ANT0_PRIVATE_ACTION -eq 'parents') {
84
+ $paths = if ($env:ANT0_PRIVATE_ACTION -eq 'batch') { @($p | ConvertFrom-Json) } else { @($p) }
85
+ foreach ($path in $paths) {
86
+ if ($env:ANT0_PRIVATE_ACTION -ne 'parents') { Test-Private $path 'check' }
87
+ $parent = [IO.Path]::GetDirectoryName($path)
88
+ Test-Private $parent 'check'
89
+ while ($parent) {
90
+ Test-Private $parent 'ancestor'
91
+ $parent = [IO.Path]::GetDirectoryName($parent)
92
+ }
93
+ }
94
+ } else { Test-Private $p $env:ANT0_PRIVATE_ACTION }
95
+ `;
96
+ function windowsAcl(file, action, validation) {
97
+ if (validation)
98
+ return validation.check(file, action);
99
+ try {
100
+ execFileSync(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", WINDOWS_ACL_SCRIPT], {
101
+ env: { ...process.env, ANT0_PRIVATE_FILE: file, ANT0_PRIVATE_ACTION: action },
102
+ stdio: ["ignore", "ignore", "ignore"],
103
+ timeout: 10_000,
104
+ windowsHide: true,
105
+ });
106
+ }
107
+ catch {
108
+ throw fail();
109
+ }
110
+ }
111
+ /** Only a synchronous logical operation owns this lease. Every reuse lstats the parent chain;
112
+ * files and the private parent retain full stamps, higher ancestors retain identity/type checks.
113
+ * All ancestors receive native reparse inspection in the ACL batch. Nothing survives an await. */
114
+ class WindowsValidation {
115
+ checked = new Map();
116
+ handles = new Map();
117
+ check(file, action) {
118
+ if (action === "private") {
119
+ this.checked.delete(file);
120
+ windowsAcl(file, action);
121
+ return;
122
+ }
123
+ if (action === "batch")
124
+ throw fail(); // batches enter through typed paths, not caller JSON
125
+ this.checkPaths([file], action === "parents");
126
+ }
127
+ checkFiles(files) {
128
+ if (files.length < 1 || files.length > 2)
129
+ throw fail();
130
+ this.checkPaths(files, false);
131
+ }
132
+ checkPaths(files, parentsOnly) {
133
+ // Inspect a file and its entire parent chain in one subprocess, rather than starting
134
+ // separate processes for directories(), regular() and stableParent().
135
+ const checks = new Map();
136
+ for (const file of files) {
137
+ if (!parentsOnly)
138
+ checks.set(file, true);
139
+ let path = dirname(file);
140
+ for (;;) {
141
+ checks.set(path, checks.get(path) === true || path === dirname(file));
142
+ if (path === parse(path).root)
143
+ break;
144
+ path = dirname(path);
145
+ }
146
+ }
147
+ const paths = [...checks].map(([path, acl]) => ({ path, acl }));
148
+ if (paths.length > 256)
149
+ throw fail();
150
+ for (let attempt = 0; attempt < 3; attempt++) {
151
+ const before = paths.map(({ path }) => lstatSync(path));
152
+ paths.forEach(({ path }, i) => {
153
+ if (!parentsOnly && files.includes(path))
154
+ regular(path, before[i], false, true);
155
+ else if (!before[i].isDirectory() || before[i].isSymbolicLink())
156
+ throw fail();
157
+ });
158
+ for (const file of parentsOnly ? [] : files) {
159
+ const stat = before[paths.findIndex(({ path }) => path === file)];
160
+ const fd = this.handles.get(file);
161
+ if (fd !== undefined && !same(fstatSync(fd), stat)) {
162
+ closeSync(fd);
163
+ this.handles.delete(file);
164
+ }
165
+ }
166
+ const unchanged = () => paths.every(({ path, acl }, i) => sameBoundary(before[i], lstatSync(path), acl)) &&
167
+ (parentsOnly ||
168
+ files.every((file) => !this.handles.has(file) ||
169
+ same(before[paths.findIndex(({ path }) => path === file)], fstatSync(this.handles.get(file)))));
170
+ if ((parentsOnly || files.every((file) => this.handles.has(file))) &&
171
+ paths.every(({ path, acl }, i) => {
172
+ const previous = this.checked.get(path);
173
+ return previous && (!acl || previous.acl) && sameBoundary(previous.stat, before[i], acl);
174
+ }) &&
175
+ unchanged())
176
+ return;
177
+ windowsAcl(files.length === 1 ? files[0] : JSON.stringify(files), parentsOnly ? "parents" : files.length === 1 ? "all" : "batch");
178
+ // A concurrent publication can change directory ChangeTime. Retry inspection, never
179
+ // associate an ACL result with a different stamp or ignore the changed permission state.
180
+ if (!unchanged())
181
+ continue;
182
+ // New paths must pass ACL/reparse inspection before opening. Bind that result to a
183
+ // live descriptor only if the file and complete chain still have the inspected stamps.
184
+ for (const file of parentsOnly ? [] : files) {
185
+ if (!this.handles.has(file)) {
186
+ if (this.handles.size >= 256)
187
+ throw fail();
188
+ this.handles.set(file, openSync(file, constants.O_RDONLY | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0)));
189
+ }
190
+ }
191
+ if (!unchanged())
192
+ throw fail();
193
+ paths.forEach(({ path, acl }, i) => {
194
+ if (this.checked.size >= 256 && !this.checked.has(path))
195
+ throw fail();
196
+ this.checked.set(path, { stat: before[i], acl });
197
+ });
198
+ return;
199
+ }
200
+ throw fail();
201
+ }
202
+ close() {
203
+ for (const fd of this.handles.values())
204
+ closeSync(fd);
205
+ this.handles.clear();
206
+ this.checked.clear();
207
+ }
208
+ }
209
+ function withValidation(operation) {
210
+ const validation = process.platform === "win32" ? new WindowsValidation() : undefined;
211
+ try {
212
+ return operation(validation);
213
+ }
214
+ finally {
215
+ validation?.close();
216
+ }
217
+ }
218
+ function directories(file, checkAcl = true, validation) {
219
+ let path = dirname(file);
220
+ let parent;
221
+ const immediate = path;
222
+ for (;;) {
223
+ const stat = lstatSync(path);
224
+ if (!stat.isDirectory() || stat.isSymbolicLink())
225
+ throw fail();
226
+ if (process.platform === "win32") {
227
+ /* Batch ACL/reparse inspection after collecting identity. */
228
+ }
229
+ else {
230
+ const uid = BigInt(process.getuid());
231
+ if (path === immediate) {
232
+ if (stat.uid !== uid || (stat.mode & 63n) !== 0n)
233
+ throw fail();
234
+ }
235
+ else if ((stat.uid !== uid && stat.uid !== 0n) ||
236
+ ((stat.mode & 18n) !== 0n && !(stat.uid === 0n && (stat.mode & 512n) !== 0n)))
237
+ throw fail();
238
+ }
239
+ parent ??= stat;
240
+ if (path === parse(path).root) {
241
+ if (process.platform === "win32" && checkAcl)
242
+ windowsAcl(file, "parents", validation);
243
+ return parent;
244
+ }
245
+ path = dirname(path);
246
+ }
247
+ }
248
+ function regular(file, stat, checkAcl = true, allowTwo = false, validation) {
249
+ if (!stat.isFile() ||
250
+ stat.isSymbolicLink() ||
251
+ (stat.nlink !== 1n && !(allowTwo && stat.nlink === 2n)) ||
252
+ stat.size > BigInt(MAX_BYTES))
253
+ throw fail();
254
+ if (process.platform === "win32") {
255
+ if (checkAcl)
256
+ windowsAcl(file, "check", validation);
257
+ }
258
+ else if (stat.uid !== BigInt(process.getuid()) || (stat.mode & 63n) !== 0n)
259
+ throw fail();
260
+ }
261
+ function stableParent(file, parent, checkAcl = true, validation) {
262
+ const now = directories(file, checkAcl, validation);
263
+ if (now.dev !== parent.dev || now.ino !== parent.ino)
264
+ throw fail();
265
+ }
266
+ function readRaw(file, checkAcl = true, allowTwo = false, validation) {
267
+ let fd;
268
+ const path = resolve(file);
269
+ try {
270
+ const parent = directories(path, process.platform === "win32" ? false : checkAcl, validation);
271
+ const stat = lstatSync(path);
272
+ if (process.platform === "win32" && checkAcl)
273
+ windowsAcl(path, "all", validation);
274
+ regular(path, stat, false, allowTwo);
275
+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0));
276
+ const opened = fstatSync(fd);
277
+ if (!same(stat, opened))
278
+ throw fail();
279
+ const buffer = Buffer.alloc(MAX_BYTES + 1);
280
+ let size = 0;
281
+ while (size < buffer.length) {
282
+ const n = readSync(fd, buffer, size, buffer.length - size, null);
283
+ if (!n)
284
+ break;
285
+ size += n;
286
+ }
287
+ if (size > MAX_BYTES || !same(opened, fstatSync(fd)) || !same(opened, lstatSync(path)))
288
+ throw fail();
289
+ stableParent(path, parent, checkAcl, validation);
290
+ if (!same(opened, fstatSync(fd)) || !same(opened, lstatSync(path)))
291
+ throw fail();
292
+ const bytes = buffer.subarray(0, size);
293
+ const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
294
+ return { path, stat: opened, parent, text, bytes };
295
+ }
296
+ finally {
297
+ if (fd !== undefined)
298
+ closeSync(fd);
299
+ }
300
+ }
301
+ const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
302
+ const RESERVED = new RegExp(`^\\.ant0-key-publish-v1\\.(credential|result)\\.(${UUID})\\.(${UUID})\\.tmp$`);
303
+ const digest = (source) => createHash("sha256").update(source.bytes).digest("hex");
304
+ const sameObject = (a, b) => a.stat.dev === b.stat.dev &&
305
+ a.stat.ino === b.stat.ino &&
306
+ a.parent.dev === b.parent.dev &&
307
+ a.parent.ino === b.parent.ino &&
308
+ a.bytes.equals(b.bytes);
309
+ function absent(path) {
310
+ try {
311
+ lstatSync(path);
312
+ return false;
313
+ }
314
+ catch (error) {
315
+ if (error.code === "ENOENT")
316
+ return true;
317
+ throw error;
318
+ }
319
+ }
320
+ function readPublished(path, kind, validate, checkAcl = true, validation) {
321
+ let raw;
322
+ for (let attempt = 0; attempt < 3; attempt++) {
323
+ try {
324
+ raw = readRaw(path, checkAcl, true, validation);
325
+ break;
326
+ }
327
+ catch (error) {
328
+ if (attempt === 2)
329
+ throw error;
330
+ }
331
+ }
332
+ if (!raw)
333
+ throw fail();
334
+ const original = raw;
335
+ const id = validate(raw);
336
+ if (raw.stat.nlink === 1n)
337
+ return raw;
338
+ const normalized = () => {
339
+ const current = readRaw(path, checkAcl, false, validation);
340
+ if (!sameObject(original, current) || validate(current) !== id)
341
+ throw fail();
342
+ pinRaw(current, validation).close();
343
+ const final = readRaw(path, checkAcl, false, validation);
344
+ if (!sameObject(original, final) || validate(final) !== id)
345
+ throw fail();
346
+ return final;
347
+ };
348
+ const names = readdirSync(dirname(path));
349
+ if (names.length > 16_384)
350
+ throw fail();
351
+ const aliases = [];
352
+ for (const name of names) {
353
+ const match = RESERVED.exec(name);
354
+ if (!match || match[1] !== kind || match[2] !== id)
355
+ continue;
356
+ const alias = join(dirname(path), name);
357
+ try {
358
+ const stat = lstatSync(alias);
359
+ if (stat.dev === raw.stat.dev && stat.ino === raw.stat.ino)
360
+ aliases.push(alias);
361
+ }
362
+ catch (error) {
363
+ if (error.code !== "ENOENT")
364
+ throw error;
365
+ }
366
+ }
367
+ if (aliases.length === 0)
368
+ return normalized(); // a concurrent publisher may have removed its alias
369
+ if (aliases.length !== 1)
370
+ throw fail();
371
+ const alias = aliases[0];
372
+ try {
373
+ const candidate = readRaw(alias, checkAcl, true, validation);
374
+ if (!sameObject(raw, candidate) || validate(candidate) !== id)
375
+ throw fail();
376
+ const current = readRaw(path, checkAcl, true, validation);
377
+ if (!same(current.stat, raw.stat) ||
378
+ !sameObject(raw, current) ||
379
+ !same(lstatSync(alias), candidate.stat))
380
+ throw fail();
381
+ unlinkSync(alias);
382
+ }
383
+ catch (error) {
384
+ if (!absent(alias))
385
+ throw error;
386
+ return normalized();
387
+ }
388
+ return normalized();
389
+ }
390
+ function parseOriginal(raw) {
391
+ const parsed = credentialFileSchema.safeParse(JSON.parse(raw.text));
392
+ if (!parsed.success)
393
+ throw fail();
394
+ if (parsed.data.key)
395
+ rejectCredentialEcho(parsed.data.key, parsed.data.create.credential);
396
+ return parsed.data;
397
+ }
398
+ function parseReceipt(raw, original, source) {
399
+ const parsed = credentialResultSchema.safeParse(JSON.parse(raw.text));
400
+ if (!parsed.success ||
401
+ parsed.data.credential_file_sha256 !== digest(source) ||
402
+ !matchingMetadata(original, parsed.data.key))
403
+ throw fail();
404
+ rejectCredentialEcho(parsed.data.key, original.create.credential);
405
+ return parsed.data.key;
406
+ }
407
+ function readSnapshot(file, checkAcl = true, validation) {
408
+ const path = resolve(file);
409
+ const receiptPath = `${path}.result.json`;
410
+ if (checkAcl && validation)
411
+ validation.checkFiles([path, ...(!absent(receiptPath) ? [receiptPath] : [])]);
412
+ const raw = readPublished(path, "credential", (value) => parseOriginal(value).create.id, checkAcl, validation);
413
+ const original = parseOriginal(raw);
414
+ let receipt;
415
+ let value = original;
416
+ if (!absent(receiptPath)) {
417
+ receipt = readPublished(receiptPath, "result", (r) => {
418
+ parseReceipt(r, original, raw);
419
+ return original.create.id;
420
+ }, checkAcl, validation);
421
+ const key = parseReceipt(receipt, original, raw);
422
+ if (original.phase === "pending")
423
+ value = { ...original, phase: "ready", key };
424
+ }
425
+ compareRaw(raw, readRaw(path, checkAcl, false, validation));
426
+ return { ...raw, rawValue: original, value, ...(receipt ? { receipt } : {}) };
427
+ }
428
+ export function readCredentialFile(file) {
429
+ try {
430
+ return withValidation((validation) => readSnapshot(file, true, validation));
431
+ }
432
+ catch {
433
+ throw fail();
434
+ }
435
+ }
436
+ export function assertCredentialUnchanged(snapshot) {
437
+ const current = readCredentialFile(snapshot.path);
438
+ compareSnapshot(snapshot, current);
439
+ }
440
+ /** Re-establish durability even after a failed fsync or killed writer. Pin the file through
441
+ * dispatch (also its parent on POSIX); syncing the lock is not credential durability. */
442
+ export function flushCredentialBeforeSubmission(snapshot) {
443
+ return withValidation((validation) => {
444
+ compareSnapshot(snapshot, readSnapshot(snapshot.path, true, validation));
445
+ const pinned = pinRaw(snapshot, validation);
446
+ try {
447
+ compareSnapshot(snapshot, readSnapshot(snapshot.path, true, validation));
448
+ return pinned;
449
+ }
450
+ catch (error) {
451
+ pinned.close();
452
+ throw error;
453
+ }
454
+ });
455
+ }
456
+ function pinRaw(snapshot, validation) {
457
+ let file;
458
+ let parent;
459
+ const close = () => {
460
+ if (file !== undefined) {
461
+ closeSync(file);
462
+ file = undefined;
463
+ }
464
+ if (parent !== undefined) {
465
+ closeSync(parent);
466
+ parent = undefined;
467
+ }
468
+ };
469
+ try {
470
+ compareRaw(snapshot, readRaw(snapshot.path, true, false, validation));
471
+ file = openSync(snapshot.path, constants.O_RDWR | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0));
472
+ if (!same(fstatSync(file), snapshot.stat))
473
+ throw fail();
474
+ if (process.platform !== "win32") {
475
+ parent = openSync(dirname(snapshot.path), constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
476
+ const stat = fstatSync(parent);
477
+ if (stat.dev !== snapshot.parent.dev || stat.ino !== snapshot.parent.ino)
478
+ throw fail();
479
+ }
480
+ fsyncSync(file);
481
+ if (parent !== undefined)
482
+ fsyncSync(parent);
483
+ else
484
+ flushWindowsParent(snapshot.path);
485
+ if (!same(fstatSync(file), snapshot.stat))
486
+ throw fail();
487
+ compareRaw(snapshot, readRaw(snapshot.path, true, false, validation));
488
+ return { close };
489
+ }
490
+ catch {
491
+ close();
492
+ throw new CredentialFailure("private credential durability unavailable");
493
+ }
494
+ }
495
+ function flushWindowsParent(path) {
496
+ const script = `
497
+ $ErrorActionPreference='Stop'
498
+ Add-Type -TypeDefinition @'
499
+ using System;
500
+ using System.Runtime.InteropServices;
501
+ public static class Ant0Durability {
502
+ [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] public static extern IntPtr CreateFile(string p,uint access,uint share,IntPtr sa,uint mode,uint flags,IntPtr template);
503
+ [DllImport("kernel32.dll",SetLastError=true)] public static extern bool FlushFileBuffers(IntPtr h);
504
+ [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr h);
505
+ }
506
+ '@
507
+ $h=[Ant0Durability]::CreateFile($env:ANT0_PRIVATE_PARENT,0x40000000,3,[IntPtr]::Zero,3,0x02200000,[IntPtr]::Zero)
508
+ if ($h -eq [IntPtr](-1)) { throw 'open' }
509
+ try { if (![Ant0Durability]::FlushFileBuffers($h)) { throw 'flush' } }
510
+ finally { [void][Ant0Durability]::CloseHandle($h) }
511
+ `;
512
+ try {
513
+ execFileSync(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
514
+ env: { ...process.env, ANT0_PRIVATE_PARENT: dirname(path) },
515
+ stdio: "ignore",
516
+ timeout: 10_000,
517
+ windowsHide: true,
518
+ });
519
+ }
520
+ catch {
521
+ throw fail();
522
+ }
523
+ }
524
+ function compareRaw(snapshot, current) {
525
+ if (!same(current.stat, snapshot.stat) ||
526
+ current.text !== snapshot.text ||
527
+ current.parent.dev !== snapshot.parent.dev ||
528
+ current.parent.ino !== snapshot.parent.ino)
529
+ throw new CredentialFailure("private credential file changed");
530
+ }
531
+ function compareSnapshot(snapshot, current) {
532
+ compareRaw(snapshot, current);
533
+ if (snapshot.receipt) {
534
+ if (!current.receipt)
535
+ throw fail();
536
+ compareRaw(snapshot.receipt, current.receipt);
537
+ }
538
+ if (snapshot.value.key &&
539
+ current.value.key &&
540
+ !matchingMetadata(snapshot.value, current.value.key))
541
+ throw fail();
542
+ }
543
+ /** ACL checks must not block MCP's ping/EOF/cancellation loop. Keep admission until the child
544
+ * has closed, including on abort; no secret is passed in argv, environment or child output. */
545
+ export async function assertCredentialUnchangedAsync(snapshot, signal) {
546
+ signal.throwIfAborted();
547
+ if (process.platform !== "win32") {
548
+ assertCredentialUnchanged(snapshot);
549
+ return;
550
+ }
551
+ for (let attempt = 0; attempt < 3; attempt++) {
552
+ signal.throwIfAborted();
553
+ const before = readSnapshot(snapshot.path, false);
554
+ compareSnapshot(snapshot, before);
555
+ const parents = parentEvidence(snapshot.path);
556
+ const paths = [snapshot.path, ...(before.receipt ? [before.receipt.path] : [])];
557
+ await new Promise((resolve, reject) => {
558
+ const child = execFile(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", WINDOWS_ACL_SCRIPT], {
559
+ env: {
560
+ ...process.env,
561
+ ANT0_PRIVATE_FILE: JSON.stringify(paths),
562
+ ANT0_PRIVATE_ACTION: "batch",
563
+ },
564
+ signal,
565
+ timeout: 10_000,
566
+ maxBuffer: 1024,
567
+ windowsHide: true,
568
+ });
569
+ child.on("error", () => { });
570
+ child.on("close", (code) => (code === 0 && !signal.aborted ? resolve() : reject(fail())));
571
+ });
572
+ signal.throwIfAborted();
573
+ const after = readSnapshot(snapshot.path, false);
574
+ if (!before.receipt && after.receipt)
575
+ throw fail();
576
+ compareSnapshot(before, after);
577
+ const currentParents = parentEvidence(snapshot.path);
578
+ // No proof/cache crosses this await. A private-parent stamp change requires a fresh
579
+ // batch, even if its inode and both immutable files survived. Replacement fails outright.
580
+ if (parents.length !== currentParents.length ||
581
+ parents.some((parent, i) => parent.path !== currentParents[i].path ||
582
+ !sameBoundary(parent.stat, currentParents[i].stat, false)))
583
+ throw fail();
584
+ if (sameParents(parents, currentParents))
585
+ return;
586
+ }
587
+ throw fail();
588
+ }
589
+ function syncDirectory(path) {
590
+ // Windows publication uses MoveFileEx WRITE_THROUGH after flushing the file itself.
591
+ if (process.platform === "win32")
592
+ return;
593
+ const fd = openSync(dirname(path), constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
594
+ try {
595
+ fsyncSync(fd);
596
+ }
597
+ finally {
598
+ closeSync(fd);
599
+ }
600
+ }
601
+ function windowsPublish(source, target) {
602
+ const script = `
603
+ $ErrorActionPreference='Stop'
604
+ Add-Type -TypeDefinition @'
605
+ using System;
606
+ using System.Runtime.InteropServices;
607
+ public static class Ant0PrivateMove {
608
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
609
+ public static extern bool MoveFileEx(string source, string target, uint flags);
610
+ }
611
+ '@
612
+ $flags = [uint32]8
613
+ if (![Ant0PrivateMove]::MoveFileEx($env:ANT0_PRIVATE_SOURCE, $env:ANT0_PRIVATE_TARGET, $flags)) { throw 'move' }
614
+ `;
615
+ try {
616
+ execFileSync(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
617
+ env: {
618
+ ...process.env,
619
+ ANT0_PRIVATE_SOURCE: source,
620
+ ANT0_PRIVATE_TARGET: target,
621
+ },
622
+ stdio: "ignore",
623
+ timeout: 10_000,
624
+ windowsHide: true,
625
+ });
626
+ }
627
+ catch {
628
+ throw fail();
629
+ }
630
+ }
631
+ export class CredentialCollision extends CredentialFailure {
632
+ }
633
+ /** Publish bytes once. Collision is never permission to replace a destination. */
634
+ function publish(path, kind, id, bytes, beforePublish, validation) {
635
+ const tmp = join(dirname(path), `.ant0-key-publish-v1.${kind}.${id}.${randomUUID()}.tmp`);
636
+ let fd;
637
+ let owned;
638
+ try {
639
+ const parent = directories(path, true, validation);
640
+ if (!absent(path))
641
+ return false;
642
+ fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
643
+ owned = fstatSync(fd);
644
+ if (process.platform === "win32")
645
+ windowsAcl(tmp, "private", validation);
646
+ regular(tmp, fstatSync(fd), true, false, validation);
647
+ writeFileSync(fd, bytes);
648
+ fsyncSync(fd);
649
+ const written = fstatSync(fd);
650
+ closeSync(fd);
651
+ fd = undefined;
652
+ const closed = lstatSync(tmp);
653
+ // Windows may finalize last-write times when the final writing handle closes.
654
+ if (written.dev !== closed.dev || written.ino !== closed.ino || written.size !== closed.size)
655
+ throw fail();
656
+ regular(tmp, closed, true, false, validation);
657
+ stableParent(path, parent, true, validation);
658
+ beforePublish?.();
659
+ try {
660
+ if (process.platform === "win32")
661
+ windowsPublish(tmp, path);
662
+ else
663
+ linkSync(tmp, path);
664
+ }
665
+ catch (error) {
666
+ if (error.code === "EEXIST" ||
667
+ (process.platform === "win32" && !absent(path)))
668
+ return false;
669
+ throw error;
670
+ }
671
+ if (process.platform !== "win32") {
672
+ try {
673
+ unlinkSync(tmp);
674
+ }
675
+ catch (error) {
676
+ if (error.code !== "ENOENT")
677
+ throw error;
678
+ }
679
+ }
680
+ owned = undefined;
681
+ syncDirectory(path);
682
+ const saved = readRaw(path, true, false, validation);
683
+ if (saved.stat.dev !== written.dev ||
684
+ saved.stat.ino !== written.ino ||
685
+ !saved.bytes.equals(bytes))
686
+ throw fail();
687
+ return true;
688
+ }
689
+ finally {
690
+ if (fd !== undefined)
691
+ closeSync(fd);
692
+ if (owned) {
693
+ try {
694
+ const current = lstatSync(tmp);
695
+ if (current.dev === owned.dev && current.ino === owned.ino)
696
+ unlinkSync(tmp);
697
+ }
698
+ catch {
699
+ /* Only this invocation's private temporary name can be cleaned up. */
700
+ }
701
+ }
702
+ }
703
+ }
704
+ export function saveCredentialFile(file, value, previous) {
705
+ return withValidation((validation) => saveValidated(file, value, previous, validation));
706
+ }
707
+ function saveValidated(file, value, previous, validation) {
708
+ try {
709
+ const path = resolve(file);
710
+ const parsed = credentialFileSchema.safeParse(value);
711
+ if (!parsed.success)
712
+ throw fail();
713
+ if (parsed.data.key)
714
+ rejectCredentialEcho(parsed.data.key, parsed.data.create.credential);
715
+ if (!previous) {
716
+ const bytes = Buffer.from(JSON.stringify(parsed.data) + "\n");
717
+ if (!publish(path, "credential", parsed.data.create.id, bytes, undefined, validation))
718
+ throw new CredentialCollision();
719
+ return readSnapshot(path, true, validation);
720
+ }
721
+ if (path !== previous.path ||
722
+ parsed.data.phase !== "ready" ||
723
+ !parsed.data.key ||
724
+ JSON.stringify(parsed.data.expected) !== JSON.stringify(previous.rawValue.expected) ||
725
+ JSON.stringify(parsed.data.create) !== JSON.stringify(previous.rawValue.create))
726
+ throw fail();
727
+ let current = readSnapshot(path, true, validation);
728
+ compareSnapshot(previous, current);
729
+ if (!matchingMetadata(current.value, parsed.data.key))
730
+ throw fail();
731
+ if (current.rawValue.phase === "pending" && !current.receipt) {
732
+ const receipt = {
733
+ schema: "ant0-api-key-result/v1",
734
+ credential_file_sha256: digest(current),
735
+ key: parsed.data.key,
736
+ };
737
+ publish(`${path}.result.json`, "result", current.rawValue.create.id, Buffer.from(JSON.stringify(receipt) + "\n"), () => compareSnapshot(previous, readSnapshot(path, true, validation)), validation);
738
+ current = readSnapshot(path, true, validation);
739
+ compareSnapshot(previous, current);
740
+ if (!current.receipt || !matchingMetadata(current.value, parsed.data.key))
741
+ throw fail();
742
+ }
743
+ pinRaw(current, validation).close();
744
+ if (current.receipt)
745
+ pinRaw(current.receipt, validation).close();
746
+ compareSnapshot(current, readSnapshot(path, true, validation));
747
+ return current;
748
+ }
749
+ catch (error) {
750
+ if (error instanceof CredentialCollision)
751
+ throw error;
752
+ throw fail();
753
+ }
754
+ }
755
+ export function newCredential(id) {
756
+ return `ant0_sk_v1_${id}_${randomBytes(32).toString("base64url")}`;
757
+ }
758
+ const localLocks = new Set();
759
+ /** Optional in-process convenience only. Correctness rests on create-only publication and replay. */
760
+ export async function withCredentialLock(file, operation) {
761
+ const path = resolve(file);
762
+ if (localLocks.has(path))
763
+ throw new CredentialFailure("private credential file busy");
764
+ try {
765
+ directories(path);
766
+ localLocks.add(path);
767
+ return await operation();
768
+ }
769
+ finally {
770
+ localLocks.delete(path);
771
+ }
772
+ }
773
+ //# sourceMappingURL=credential-file.js.map