hmcp-core 0.0.1 → 0.1.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 +19 -3
- package/dist/approvals.d.ts +508 -0
- package/dist/approvals.js +1445 -0
- package/dist/argpath.d.ts +75 -0
- package/dist/argpath.js +189 -0
- package/dist/audit.d.ts +289 -0
- package/dist/audit.js +512 -0
- package/dist/canonical.d.ts +78 -0
- package/dist/canonical.js +146 -0
- package/dist/classify-held.d.ts +47 -0
- package/dist/classify-held.js +60 -0
- package/dist/classify-name.d.ts +55 -0
- package/dist/classify-name.js +255 -0
- package/dist/decide.d.ts +168 -0
- package/dist/decide.js +518 -0
- package/dist/egress.d.ts +123 -0
- package/dist/egress.js +544 -0
- package/dist/enforce.d.ts +78 -0
- package/dist/enforce.js +231 -0
- package/dist/exposure-apply.d.ts +51 -0
- package/dist/exposure-apply.js +69 -0
- package/dist/exposure.d.ts +81 -0
- package/dist/exposure.js +65 -0
- package/dist/file-lock.d.ts +70 -0
- package/dist/file-lock.js +165 -0
- package/dist/glob.d.ts +11 -0
- package/dist/glob.js +55 -0
- package/dist/grants.d.ts +204 -0
- package/dist/grants.js +372 -0
- package/dist/http-util.d.ts +52 -0
- package/dist/http-util.js +81 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +36 -0
- package/dist/inventory.d.ts +100 -0
- package/dist/inventory.js +88 -0
- package/dist/ip.d.ts +15 -0
- package/dist/ip.js +186 -0
- package/dist/jwt.d.ts +57 -0
- package/dist/jwt.js +199 -0
- package/dist/live-state.d.ts +76 -0
- package/dist/live-state.js +57 -0
- package/dist/migrate.d.ts +22 -0
- package/dist/migrate.js +318 -0
- package/dist/pins.d.ts +119 -0
- package/dist/pins.js +125 -0
- package/dist/policy-batch.d.ts +89 -0
- package/dist/policy-batch.js +340 -0
- package/dist/policy-source.d.ts +161 -0
- package/dist/policy-source.js +299 -0
- package/dist/policy-write.d.ts +627 -0
- package/dist/policy-write.js +1697 -0
- package/dist/policy.d.ts +456 -0
- package/dist/policy.js +448 -0
- package/dist/redact.d.ts +65 -0
- package/dist/redact.js +191 -0
- package/dist/registry.d.ts +41 -0
- package/dist/registry.js +121 -0
- package/dist/remember-defaults.d.ts +9 -0
- package/dist/remember-defaults.js +9 -0
- package/dist/remember.d.ts +91 -0
- package/dist/remember.js +371 -0
- package/dist/resolve.d.ts +22 -0
- package/dist/resolve.js +34 -0
- package/dist/runtime-state.d.ts +65 -0
- package/dist/runtime-state.js +35 -0
- package/dist/secrets.d.ts +159 -0
- package/dist/secrets.js +361 -0
- package/dist/tenant.d.ts +83 -0
- package/dist/tenant.js +182 -0
- package/dist/unicode.d.ts +40 -0
- package/dist/unicode.js +103 -0
- package/dist/within-host.d.ts +33 -0
- package/dist/within-host.js +91 -0
- package/dist/within-real.d.ts +7 -0
- package/dist/within-real.js +28 -0
- package/package.json +33 -4
package/dist/audit.js
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync, unlinkSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { canonicalJson, hashValue, sha256 } from "./canonical.js";
|
|
5
|
+
import { globMatch } from "./glob.js";
|
|
6
|
+
import { redactArgs, redactText } from "./redact.js";
|
|
7
|
+
import { expandPath } from "./policy.js";
|
|
8
|
+
export const GENESIS_HASH = "0".repeat(64);
|
|
9
|
+
function computeHash(record) {
|
|
10
|
+
return sha256(record.prev_hash, canonicalJson({ ...record, hash: undefined }));
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Who a record says made the call.
|
|
14
|
+
*
|
|
15
|
+
* One column holds three very different kinds of answer: an operating-system
|
|
16
|
+
* user (a human at a console or a terminal), the literal "agent" for a server
|
|
17
|
+
* that serves one client and has no identity to offer, and — once a gateway
|
|
18
|
+
* verifies a caller's token — whoever that token names.
|
|
19
|
+
*
|
|
20
|
+
* Only the last of those is chosen by someone outside the deployment, which
|
|
21
|
+
* is why only the last is namespaced. A token minted with `sub: "aditya"`
|
|
22
|
+
* must not produce a line indistinguishable from a human's console approval,
|
|
23
|
+
* and a reserved prefix is what makes that forgery unrepresentable rather
|
|
24
|
+
* than merely unlikely. Prefixing the operator too would churn stored history
|
|
25
|
+
* to protect against nobody.
|
|
26
|
+
*/
|
|
27
|
+
/** A server with one client and no caller identity to claim. */
|
|
28
|
+
export const ACTOR_AGENT = "agent";
|
|
29
|
+
/** The gateway process itself: startup findings, structural refusals. */
|
|
30
|
+
export const ACTOR_GATEWAY = "gateway";
|
|
31
|
+
/**
|
|
32
|
+
* A token that verified but named no subject.
|
|
33
|
+
*
|
|
34
|
+
* Deliberately not "unknown", which already means "could not name the
|
|
35
|
+
* operating-system user". This says something narrower and truer: the token
|
|
36
|
+
* proved a *tenant*, not an identity.
|
|
37
|
+
*/
|
|
38
|
+
export const ACTOR_ANONYMOUS = "token:anonymous";
|
|
39
|
+
/** The longest actor recorded. Generous for a subject, short of a payload. */
|
|
40
|
+
const MAX_ACTOR = 128;
|
|
41
|
+
/**
|
|
42
|
+
* The actor for a caller named by a verified token.
|
|
43
|
+
*
|
|
44
|
+
* The subject is not quoted anywhere it could be mistaken for structure, but
|
|
45
|
+
* it is interpolated into prose reasons in the console and the admin API, so
|
|
46
|
+
* it is flattened to one line and capped here rather than at each use.
|
|
47
|
+
*
|
|
48
|
+
* The tenant is deliberately *not* folded in: every record already carries a
|
|
49
|
+
* `tenant` column, and `(tenant, actor)` is the real key. Nor is the issuer,
|
|
50
|
+
* which is pinned to one value per deployment. If multiple issuers ever
|
|
51
|
+
* become possible the format grows to `token:<iss>#<sub>`.
|
|
52
|
+
*/
|
|
53
|
+
export function tokenActor(subject) {
|
|
54
|
+
if (subject === undefined)
|
|
55
|
+
return ACTOR_ANONYMOUS;
|
|
56
|
+
// eslint-disable-next-line no-control-regex
|
|
57
|
+
const flat = subject.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
|
|
58
|
+
if (flat.length === 0)
|
|
59
|
+
return ACTOR_ANONYMOUS;
|
|
60
|
+
const capped = flat.length > MAX_ACTOR ? `${flat.slice(0, MAX_ACTOR - 1)}\u2026` : flat;
|
|
61
|
+
return `token:${capped}`;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Append-only JSONL audit log with an optional hash chain.
|
|
65
|
+
*
|
|
66
|
+
* Each record commits to the one before it, so a deleted or edited line makes
|
|
67
|
+
* `verifyAuditLog` fail at that point. Appends are guarded by an exclusive lock
|
|
68
|
+
* file, because the chain requires a read-tail-then-append critical section and
|
|
69
|
+
* a generated server plus a gateway may share one log.
|
|
70
|
+
*/
|
|
71
|
+
export class AuditLog {
|
|
72
|
+
path;
|
|
73
|
+
enabled;
|
|
74
|
+
config;
|
|
75
|
+
actor;
|
|
76
|
+
session;
|
|
77
|
+
component;
|
|
78
|
+
constructor(options) {
|
|
79
|
+
this.config = options.config;
|
|
80
|
+
this.enabled = options.config.enabled;
|
|
81
|
+
this.path = expandPath(options.config.path, options.cwd ?? process.cwd());
|
|
82
|
+
this.actor = options.actor ?? process.env["HMCP_ACTOR"] ?? `${process.env["USER"] ?? "unknown"}`;
|
|
83
|
+
this.session = options.session ?? randomUUID();
|
|
84
|
+
this.component = options.component ?? "hmcp";
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Writes one record and returns it. Failure to log is reported to stderr but
|
|
88
|
+
* never thrown: a broken log must not become a way to suppress enforcement.
|
|
89
|
+
* Callers that need write-or-refuse semantics should use `appendStrict`.
|
|
90
|
+
*/
|
|
91
|
+
append(entry) {
|
|
92
|
+
try {
|
|
93
|
+
return this.appendStrict(entry);
|
|
94
|
+
}
|
|
95
|
+
catch (err) {
|
|
96
|
+
process.stderr.write(`[hmcp] audit append failed: ${err.message}\n`);
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
appendStrict(entry) {
|
|
101
|
+
if (!this.enabled)
|
|
102
|
+
return null;
|
|
103
|
+
mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
|
|
104
|
+
return withLock(this.path, () => {
|
|
105
|
+
const tail = this.config.hash_chain ? readTail(this.path) : null;
|
|
106
|
+
const prev_hash = tail?.hash ?? GENESIS_HASH;
|
|
107
|
+
const seq = (tail?.seq ?? -1) + 1;
|
|
108
|
+
const args = entry.args_redacted;
|
|
109
|
+
const unhashed = {
|
|
110
|
+
ts: new Date().toISOString(),
|
|
111
|
+
seq,
|
|
112
|
+
id: randomUUID(),
|
|
113
|
+
actor: entry.actor ?? this.actor,
|
|
114
|
+
session: entry.session ?? this.session,
|
|
115
|
+
component: entry.component ?? this.component,
|
|
116
|
+
tool: entry.tool,
|
|
117
|
+
effect: entry.effect ?? null,
|
|
118
|
+
decision: entry.decision,
|
|
119
|
+
rule_id: entry.rule_id ?? "",
|
|
120
|
+
reason: entry.reason ?? "",
|
|
121
|
+
tenant: entry.tenant ?? null,
|
|
122
|
+
args_hash: entry.args_hash ?? hashValue(args ?? {}),
|
|
123
|
+
args_redacted: this.config.record_args ? (args ?? null) : null,
|
|
124
|
+
upstream: entry.upstream ?? null,
|
|
125
|
+
outcome: entry.outcome,
|
|
126
|
+
error: entry.error ?? null,
|
|
127
|
+
duration_ms: entry.duration_ms ?? null,
|
|
128
|
+
approval_id: entry.approval_id ?? null,
|
|
129
|
+
grant_id: entry.grant_id ?? null,
|
|
130
|
+
...(entry.observe ? { observe: true } : {}),
|
|
131
|
+
prev_hash
|
|
132
|
+
};
|
|
133
|
+
const record = { ...unhashed, hash: computeHash(unhashed) };
|
|
134
|
+
appendFileSync(this.path, JSON.stringify(record) + "\n", { encoding: "utf8", mode: 0o600 });
|
|
135
|
+
return record;
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Throws unless a record could be appended right now.
|
|
140
|
+
*
|
|
141
|
+
* For a caller about to do something it must not do unrecorded. Opening the
|
|
142
|
+
* file for append is what an append does first, so this fails for a missing
|
|
143
|
+
* or read-only directory, a path that is not a file, or a full quota, and
|
|
144
|
+
* leaves the log untouched when it succeeds. It cannot promise the append
|
|
145
|
+
* that follows will work -- nothing can -- but it turns the common, lasting
|
|
146
|
+
* failures into a refusal rather than a line on stderr.
|
|
147
|
+
*/
|
|
148
|
+
assertWritable() {
|
|
149
|
+
if (!this.enabled)
|
|
150
|
+
return;
|
|
151
|
+
mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
|
|
152
|
+
closeSync(openSync(this.path, "a", 0o600));
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Redacts free text bound for this log -- an upstream's error message --
|
|
156
|
+
* with the same key list the arguments beside it are redacted with.
|
|
157
|
+
*/
|
|
158
|
+
prepareText(text, args) {
|
|
159
|
+
return redactText(text, { args, extraKeys: this.config.redact });
|
|
160
|
+
}
|
|
161
|
+
/** Redacts arguments with this log's configured key list and hashes the original. */
|
|
162
|
+
prepareArgs(args) {
|
|
163
|
+
return {
|
|
164
|
+
args_hash: hashValue(args ?? {}),
|
|
165
|
+
args_redacted: redactArgs(args, this.config.redact)
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/** How much of the end of the log one tail read may look at before giving up. */
|
|
170
|
+
const TAIL_READ_LIMIT = 4 * 1024 * 1024;
|
|
171
|
+
/**
|
|
172
|
+
* The last complete record, found by seeking backwards from the end.
|
|
173
|
+
*
|
|
174
|
+
* Every append needs this, because each record carries the previous one's
|
|
175
|
+
* hash. It used to read the whole file, which is fine for a day and not for a
|
|
176
|
+
* year: on a 6 MB log every tool call read 6 MB synchronously, inside the
|
|
177
|
+
* append lock, so the cost of using the gateway grew with how long it had
|
|
178
|
+
* been used.
|
|
179
|
+
*
|
|
180
|
+
* Read backwards in blocks instead. Three things this has to keep getting
|
|
181
|
+
* right, and each has a test:
|
|
182
|
+
*
|
|
183
|
+
* - a torn trailing line, left by a process killed mid-append, is skipped and
|
|
184
|
+
* the search continues to the last *complete* record;
|
|
185
|
+
* - a record longer than one block is still found, because a block boundary
|
|
186
|
+
* is not a record boundary;
|
|
187
|
+
* - and when nothing can be found within `TAIL_READ_LIMIT`, this says so by
|
|
188
|
+
* returning null rather than reading an unbounded amount -- a log that has
|
|
189
|
+
* been corrupted at the end must not turn every append into a full scan.
|
|
190
|
+
*/
|
|
191
|
+
export function readLastRecord(path) {
|
|
192
|
+
if (!existsSync(path))
|
|
193
|
+
return null;
|
|
194
|
+
const size = statSync(path).size;
|
|
195
|
+
if (size === 0)
|
|
196
|
+
return null;
|
|
197
|
+
const fd = openSync(path, "r");
|
|
198
|
+
try {
|
|
199
|
+
const block = 64 * 1024;
|
|
200
|
+
let end = size;
|
|
201
|
+
let carry = "";
|
|
202
|
+
let bytesRead = 0;
|
|
203
|
+
while (end > 0 && bytesRead < TAIL_READ_LIMIT) {
|
|
204
|
+
const length = Math.min(block, end);
|
|
205
|
+
const start = end - length;
|
|
206
|
+
const buffer = Buffer.allocUnsafe(length);
|
|
207
|
+
readSync(fd, buffer, 0, length, start);
|
|
208
|
+
bytesRead += length;
|
|
209
|
+
/*
|
|
210
|
+
* The block may begin in the middle of a multi-byte character. Only the
|
|
211
|
+
* portion after the first newline is guaranteed to decode correctly, and
|
|
212
|
+
* that is all this looks at: anything before it belongs to a line that
|
|
213
|
+
* will be examined on the next, earlier block.
|
|
214
|
+
*/
|
|
215
|
+
const text = buffer.toString("utf8") + carry;
|
|
216
|
+
const lines = text.split("\n");
|
|
217
|
+
carry = lines.shift() ?? "";
|
|
218
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
219
|
+
const line = lines[i].trim();
|
|
220
|
+
if (line.length === 0)
|
|
221
|
+
continue;
|
|
222
|
+
try {
|
|
223
|
+
const parsed = JSON.parse(line);
|
|
224
|
+
if (typeof parsed.hash === "string" && typeof parsed.seq === "number") {
|
|
225
|
+
return { hash: parsed.hash, seq: parsed.seq, bytesRead };
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
// A torn trailing line: keep looking backwards.
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
end = start;
|
|
233
|
+
// At the start of the file the carry is a whole line, not a fragment.
|
|
234
|
+
if (end === 0 && carry.trim().length > 0) {
|
|
235
|
+
try {
|
|
236
|
+
const parsed = JSON.parse(carry.trim());
|
|
237
|
+
if (typeof parsed.hash === "string" && typeof parsed.seq === "number") {
|
|
238
|
+
return { hash: parsed.hash, seq: parsed.seq, bytesRead };
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
/* nothing usable */
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
finally {
|
|
249
|
+
closeSync(fd);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
function readTail(path) {
|
|
253
|
+
const found = readLastRecord(path);
|
|
254
|
+
return found ? { hash: found.hash, seq: found.seq } : null;
|
|
255
|
+
}
|
|
256
|
+
/** Exclusive lock around the read-tail/append critical section. */
|
|
257
|
+
function withLock(path, fn) {
|
|
258
|
+
const lockPath = `${path}.lock`;
|
|
259
|
+
const deadline = Date.now() + 5000;
|
|
260
|
+
let fd;
|
|
261
|
+
for (;;) {
|
|
262
|
+
try {
|
|
263
|
+
fd = openSync(lockPath, "wx");
|
|
264
|
+
break;
|
|
265
|
+
}
|
|
266
|
+
catch (err) {
|
|
267
|
+
if (err.code !== "EEXIST")
|
|
268
|
+
throw err;
|
|
269
|
+
// Reclaim a lock left behind by a process that died mid-append.
|
|
270
|
+
try {
|
|
271
|
+
if (Date.now() - statSync(lockPath).mtimeMs > 10_000) {
|
|
272
|
+
unlinkSync(lockPath);
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
if (Date.now() > deadline)
|
|
280
|
+
throw new Error(`timed out waiting for audit lock at ${lockPath}`);
|
|
281
|
+
// Busy-wait briefly; the critical section is a few milliseconds long.
|
|
282
|
+
const spinUntil = Date.now() + 5;
|
|
283
|
+
while (Date.now() < spinUntil) {
|
|
284
|
+
/* spin */
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
try {
|
|
289
|
+
return fn();
|
|
290
|
+
}
|
|
291
|
+
finally {
|
|
292
|
+
try {
|
|
293
|
+
if (fd !== undefined)
|
|
294
|
+
closeSync(fd);
|
|
295
|
+
unlinkSync(lockPath);
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
/* best effort */
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Walks the chain and reports the first point at which it stops being
|
|
304
|
+
* consistent: a modified record, a removed one, or a reordered one.
|
|
305
|
+
*/
|
|
306
|
+
export function verifyAuditLog(path, options = {}) {
|
|
307
|
+
const full = expandPath(path);
|
|
308
|
+
const problems = [];
|
|
309
|
+
if (!existsSync(full)) {
|
|
310
|
+
return {
|
|
311
|
+
ok: false,
|
|
312
|
+
count: 0,
|
|
313
|
+
problems: [
|
|
314
|
+
{
|
|
315
|
+
line: 0,
|
|
316
|
+
message: `no audit log at ${full}` +
|
|
317
|
+
(options.expectHead === undefined
|
|
318
|
+
? ""
|
|
319
|
+
: `, so the recorded head ${short(options.expectHead)} cannot be found in it. A log that ` +
|
|
320
|
+
`existed and does not now is an incident, not an absence.`)
|
|
321
|
+
}
|
|
322
|
+
]
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
const lines = readFileSync(full, "utf8").split("\n");
|
|
326
|
+
let prevHash = GENESIS_HASH;
|
|
327
|
+
let expectedSeq = 0;
|
|
328
|
+
let count = 0;
|
|
329
|
+
let headPosition;
|
|
330
|
+
for (let i = 0; i < lines.length; i++) {
|
|
331
|
+
const line = lines[i];
|
|
332
|
+
if (line.trim().length === 0)
|
|
333
|
+
continue;
|
|
334
|
+
const lineNo = i + 1;
|
|
335
|
+
let record;
|
|
336
|
+
try {
|
|
337
|
+
record = JSON.parse(line);
|
|
338
|
+
}
|
|
339
|
+
catch (err) {
|
|
340
|
+
problems.push({ line: lineNo, message: `unparseable JSON: ${err.message}` });
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
count++;
|
|
344
|
+
if (record.seq !== expectedSeq) {
|
|
345
|
+
problems.push({
|
|
346
|
+
line: lineNo,
|
|
347
|
+
message: `sequence gap: expected seq ${expectedSeq}, found ${record.seq} (a record was removed or reordered)`
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
if (record.prev_hash !== prevHash) {
|
|
351
|
+
problems.push({
|
|
352
|
+
line: lineNo,
|
|
353
|
+
message: `chain break: prev_hash ${short(record.prev_hash)} does not match the previous record's hash ${short(prevHash)}`
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
const recomputed = computeHash({ ...record, hash: undefined });
|
|
357
|
+
if (recomputed !== record.hash) {
|
|
358
|
+
problems.push({
|
|
359
|
+
line: lineNo,
|
|
360
|
+
message: `record altered: stored hash ${short(record.hash)} but contents hash to ${short(recomputed)}`
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
prevHash = record.hash;
|
|
364
|
+
expectedSeq = record.seq + 1;
|
|
365
|
+
if (options.expectHead !== undefined && record.hash === options.expectHead)
|
|
366
|
+
headPosition = count - 1;
|
|
367
|
+
}
|
|
368
|
+
const head = count > 0 && prevHash !== GENESIS_HASH ? prevHash : undefined;
|
|
369
|
+
if (options.expectHead !== undefined && headPosition === undefined) {
|
|
370
|
+
/*
|
|
371
|
+
* The one failure a chain cannot find on its own. Everything still in the
|
|
372
|
+
* file may verify perfectly; what the recorded head proves is that
|
|
373
|
+
* something which used to be in it still is.
|
|
374
|
+
*/
|
|
375
|
+
problems.push({
|
|
376
|
+
line: count,
|
|
377
|
+
message: `the recorded head ${short(options.expectHead)} is not in this log. Either records have been ` +
|
|
378
|
+
`removed from the end -- which a chain cannot detect on its own, because what remains still ` +
|
|
379
|
+
`verifies -- or that head came from a different log. Treat it as an incident.`
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
return {
|
|
383
|
+
ok: problems.length === 0,
|
|
384
|
+
count,
|
|
385
|
+
problems,
|
|
386
|
+
...(head !== undefined ? { head } : {}),
|
|
387
|
+
...(headPosition !== undefined ? { headPosition } : {})
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
function short(h) {
|
|
391
|
+
return typeof h === "string" ? h.slice(0, 12) : String(h);
|
|
392
|
+
}
|
|
393
|
+
export function readAuditLog(path) {
|
|
394
|
+
const full = expandPath(path);
|
|
395
|
+
if (!existsSync(full))
|
|
396
|
+
return [];
|
|
397
|
+
return readFileSync(full, "utf8")
|
|
398
|
+
.split("\n")
|
|
399
|
+
.filter((l) => l.trim().length > 0)
|
|
400
|
+
.map((l) => JSON.parse(l));
|
|
401
|
+
}
|
|
402
|
+
/** Anything refused, or anything that did not complete. */
|
|
403
|
+
export function isNoteworthy(record) {
|
|
404
|
+
return record.decision === "deny" || record.outcome !== "completed";
|
|
405
|
+
}
|
|
406
|
+
const QUERY_CHUNK = 64 * 1024;
|
|
407
|
+
const QUERY_LIMIT_CAP = 1000;
|
|
408
|
+
/**
|
|
409
|
+
* Bounded, newest-first query over the log.
|
|
410
|
+
*
|
|
411
|
+
* `readAuditLog` parses the whole file and throws on the first malformed line,
|
|
412
|
+
* which makes it unusable for a long-running reader: a console asking for the
|
|
413
|
+
* last 50 records should not pay for a 200MB log, and one torn line should not
|
|
414
|
+
* hide every record around it. This scans backwards in fixed chunks and stops
|
|
415
|
+
* as soon as the limit is met, so the cost is proportional to what was asked
|
|
416
|
+
* for rather than to the size of the log.
|
|
417
|
+
*
|
|
418
|
+
* Chunk boundaries are handled as bytes, not text: a partial line is carried
|
|
419
|
+
* over as a Buffer so a multi-byte character split across two reads is decoded
|
|
420
|
+
* once, intact.
|
|
421
|
+
*/
|
|
422
|
+
export function queryAuditLog(path, query = {}) {
|
|
423
|
+
const full = expandPath(path);
|
|
424
|
+
if (!existsSync(full))
|
|
425
|
+
return { records: [], nextCursor: null, scanned: 0, malformed: 0 };
|
|
426
|
+
const limit = Math.min(Math.max(query.limit ?? 100, 1), QUERY_LIMIT_CAP);
|
|
427
|
+
const records = [];
|
|
428
|
+
let scanned = 0;
|
|
429
|
+
let malformed = 0;
|
|
430
|
+
const fd = openSync(full, "r");
|
|
431
|
+
try {
|
|
432
|
+
let pos = statSync(full).size;
|
|
433
|
+
let carry = Buffer.alloc(0);
|
|
434
|
+
while (pos > 0 && records.length < limit) {
|
|
435
|
+
const len = Math.min(QUERY_CHUNK, pos);
|
|
436
|
+
pos -= len;
|
|
437
|
+
const buf = Buffer.alloc(len);
|
|
438
|
+
readSync(fd, buf, 0, len, pos);
|
|
439
|
+
const combined = Buffer.concat([buf, carry]);
|
|
440
|
+
let start = 0;
|
|
441
|
+
if (pos > 0) {
|
|
442
|
+
// The first line in this window begins earlier in the file; hold its
|
|
443
|
+
// bytes back until the chunk containing its start has been read.
|
|
444
|
+
const nl = combined.indexOf(0x0a);
|
|
445
|
+
if (nl === -1) {
|
|
446
|
+
carry = combined;
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
carry = combined.subarray(0, nl);
|
|
450
|
+
start = nl + 1;
|
|
451
|
+
}
|
|
452
|
+
else {
|
|
453
|
+
carry = Buffer.alloc(0);
|
|
454
|
+
}
|
|
455
|
+
const lines = combined.subarray(start).toString("utf8").split("\n");
|
|
456
|
+
for (let i = lines.length - 1; i >= 0 && records.length < limit; i--) {
|
|
457
|
+
const line = lines[i];
|
|
458
|
+
if (line.trim().length === 0)
|
|
459
|
+
continue;
|
|
460
|
+
scanned++;
|
|
461
|
+
let record;
|
|
462
|
+
try {
|
|
463
|
+
record = JSON.parse(line);
|
|
464
|
+
}
|
|
465
|
+
catch {
|
|
466
|
+
malformed++;
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
if (matchesQuery(record, query))
|
|
470
|
+
records.push(record);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
finally {
|
|
475
|
+
closeSync(fd);
|
|
476
|
+
}
|
|
477
|
+
// A short page means the backwards scan ran out of log, so there is nothing
|
|
478
|
+
// older to fetch. A full page means there may be more, even if this pass
|
|
479
|
+
// happened to read as far as byte zero: the loop stops at the limit, not at
|
|
480
|
+
// the start of the file. Reporting "reached the start" from `pos === 0` would
|
|
481
|
+
// silently truncate paging whenever a whole log fit in one chunk.
|
|
482
|
+
const oldest = records[records.length - 1];
|
|
483
|
+
const nextCursor = records.length < limit || !oldest ? null : oldest.seq;
|
|
484
|
+
return { records, nextCursor, scanned, malformed };
|
|
485
|
+
}
|
|
486
|
+
function matchesQuery(record, q) {
|
|
487
|
+
if (q.beforeSeq !== undefined && !(record.seq < q.beforeSeq))
|
|
488
|
+
return false;
|
|
489
|
+
if (q.noteworthy && !isNoteworthy(record))
|
|
490
|
+
return false;
|
|
491
|
+
if (q.decision && !q.decision.includes(record.decision))
|
|
492
|
+
return false;
|
|
493
|
+
if (q.outcome && !q.outcome.includes(record.outcome))
|
|
494
|
+
return false;
|
|
495
|
+
if (q.component && !q.component.includes(record.component))
|
|
496
|
+
return false;
|
|
497
|
+
if (q.excludeComponent && q.excludeComponent.includes(record.component))
|
|
498
|
+
return false;
|
|
499
|
+
if (q.tenant && !q.tenant.includes(record.tenant ?? ""))
|
|
500
|
+
return false;
|
|
501
|
+
if (q.actor && !q.actor.includes(record.actor))
|
|
502
|
+
return false;
|
|
503
|
+
if (q.tool && !globMatch(q.tool, record.tool))
|
|
504
|
+
return false;
|
|
505
|
+
// ISO 8601 UTC strings order lexicographically, which is why the log stores
|
|
506
|
+
// them that way.
|
|
507
|
+
if (q.since && record.ts < q.since)
|
|
508
|
+
return false;
|
|
509
|
+
if (q.until && record.ts > q.until)
|
|
510
|
+
return false;
|
|
511
|
+
return true;
|
|
512
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic JSON serialization: object keys sorted, no insignificant
|
|
3
|
+
* whitespace, `undefined` properties dropped. Two structurally equal values
|
|
4
|
+
* always produce the same string, which is what makes argument-bound approval
|
|
5
|
+
* grants and the audit hash chain meaningful.
|
|
6
|
+
*/
|
|
7
|
+
export declare function canonicalJson(value: unknown): string;
|
|
8
|
+
/**
|
|
9
|
+
* Sets an own property, whatever the key is called.
|
|
10
|
+
*
|
|
11
|
+
* `out[key] = value` is not that. For the key `__proto__` on an ordinary
|
|
12
|
+
* object it calls the inherited setter, which replaces the object's prototype
|
|
13
|
+
* and creates no property at all -- so a copy built with plain assignment
|
|
14
|
+
* drops exactly the key an attacker gets to choose, and `JSON.stringify`
|
|
15
|
+
* agrees with the copy rather than with what was sent. `JSON.parse`, by
|
|
16
|
+
* contrast, does create it as an own property, which is how the key arrives
|
|
17
|
+
* here in the first place.
|
|
18
|
+
*
|
|
19
|
+
* Every function that rebuilds an argument object goes through this, so the
|
|
20
|
+
* binding, the audit hash and the redacted view all describe the arguments
|
|
21
|
+
* that actually reach the upstream.
|
|
22
|
+
*/
|
|
23
|
+
export declare function setOwn(target: Record<string, unknown>, key: string, value: unknown): void;
|
|
24
|
+
export declare function sha256(...parts: string[]): string;
|
|
25
|
+
/** Hash of a value's canonical form. Used for args_hash in the audit log. */
|
|
26
|
+
export declare function hashValue(value: unknown): string;
|
|
27
|
+
/**
|
|
28
|
+
* The scheme a newly written approval is bound under, stored on the row.
|
|
29
|
+
*
|
|
30
|
+
* Rows carry it so redemption can be exact rather than hopeful: a digest
|
|
31
|
+
* computed under one scheme is only ever compared against rows written under
|
|
32
|
+
* that same scheme. Without it, supporting an older scheme would mean matching
|
|
33
|
+
* a row on either digest, and a v1 digest could then release a v2 row.
|
|
34
|
+
*/
|
|
35
|
+
export declare const BINDING_VERSION = 2;
|
|
36
|
+
/**
|
|
37
|
+
* Identity of a specific call: the tool plus its exact arguments. An approval
|
|
38
|
+
* grant is bound to this, so approving `{amount: 10}` cannot release
|
|
39
|
+
* `{amount: 10000}`.
|
|
40
|
+
*
|
|
41
|
+
* The tool and the arguments go through one canonical document rather than
|
|
42
|
+
* being concatenated into the digest. Concatenating them means the boundary
|
|
43
|
+
* between the two is only a convention, and a tool name carrying the separator
|
|
44
|
+
* could stand in for a different (tool, arguments) pair. Tool names are
|
|
45
|
+
* validated elsewhere, but a hash this load-bearing should not depend on a
|
|
46
|
+
* check in another package.
|
|
47
|
+
*
|
|
48
|
+
* The scheme string is inside the hash, so changing this function produces
|
|
49
|
+
* different hashes by construction rather than by hope.
|
|
50
|
+
*
|
|
51
|
+
* Scope stays out: approvals are filtered by `(component, tenant)` in SQL,
|
|
52
|
+
* where the isolation can be read, grepped and tested. See `ScopedApprovals`.
|
|
53
|
+
*/
|
|
54
|
+
export declare function bindingHash(tool: string, args: unknown): string;
|
|
55
|
+
/**
|
|
56
|
+
* The previous framing: the tool, a newline, and the canonical arguments, fed
|
|
57
|
+
* to one digest as three updates.
|
|
58
|
+
*
|
|
59
|
+
* Kept only so an approval that was already granted when this build was
|
|
60
|
+
* deployed can still be redeemed. A reviewer who approved a call should not
|
|
61
|
+
* find that their approval evaporated because the binary was upgraded between
|
|
62
|
+
* the approval and the retry -- and the alternative, telling the agent to ask
|
|
63
|
+
* again, trains exactly the behaviour approvals exist to interrupt.
|
|
64
|
+
*
|
|
65
|
+
* It is self-limiting rather than permanent. It is only ever compared against
|
|
66
|
+
* rows stamped `binding_version = 1`, no new row is ever written under it, and
|
|
67
|
+
* approvals expire -- `ttl_seconds`, 300 by default -- so within minutes of an
|
|
68
|
+
* upgrade there is nothing left for it to match.
|
|
69
|
+
*/
|
|
70
|
+
export declare function legacyBindingHash(tool: string, args: unknown): string;
|
|
71
|
+
/** Every digest a call could be redeemed under, newest scheme first. */
|
|
72
|
+
export interface CallBindings {
|
|
73
|
+
/** What a new row is written with. */
|
|
74
|
+
readonly current: string;
|
|
75
|
+
/** Matched only against rows written before the framing changed. */
|
|
76
|
+
readonly legacy: string;
|
|
77
|
+
}
|
|
78
|
+
export declare function callBindings(tool: string, args: unknown): CallBindings;
|