@verax-ai/proxy 0.8.2 → 0.10.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/dist/anchors.d.ts +28 -5
- package/dist/anchors.js +21 -8
- package/dist/approvals.js +2 -0
- package/dist/canary.d.ts +118 -0
- package/dist/canary.js +755 -0
- package/dist/explain.js +7 -0
- package/dist/index.d.ts +9 -4
- package/dist/index.js +6 -2
- package/dist/inputs.d.ts +5 -0
- package/dist/inputs.js +38 -0
- package/dist/ledger.js +17 -1
- package/dist/policy.d.ts +9 -1
- package/dist/policy.js +38 -1
- package/dist/proxy.js +274 -26
- package/dist/session-taint.d.ts +92 -0
- package/dist/session-taint.js +343 -0
- package/dist/signed-statement.d.ts +26 -0
- package/dist/signed-statement.js +146 -0
- package/dist/tool-labels.d.ts +43 -0
- package/dist/tool-labels.js +94 -0
- package/dist/transparency-receipt.d.ts +38 -0
- package/dist/transparency-receipt.js +103 -1
- package/dist/types.d.ts +82 -1
- package/dist/verify-ledger.d.ts +12 -0
- package/dist/verify-ledger.js +81 -33
- package/package.json +7 -7
package/dist/canary.js
ADDED
|
@@ -0,0 +1,755 @@
|
|
|
1
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync, writeSync, } from "node:fs";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { writeFileAtomic } from "./atomic-write.js";
|
|
5
|
+
import { currentBootId, lockHolderAlive } from "./ledger.js";
|
|
6
|
+
import { clearProcessHalted, isHaltedSwitchFile, markProcessHalted } from "./process-halt.js";
|
|
7
|
+
/**
|
|
8
|
+
* A canary is a credential-shaped value nothing legitimate uses. The gate
|
|
9
|
+
* compares a call with the active values before the tool runs. The files and
|
|
10
|
+
* the decision name the id, never the value.
|
|
11
|
+
*
|
|
12
|
+
* `CANARY_CHECK_BOUND_MS` is the ceiling `canary-perf` enforces for one check
|
|
13
|
+
* of 50 canaries against about 4 KiB of punctuated prose and URLs. The
|
|
14
|
+
* measured median lives in `docs/PERF.md`.
|
|
15
|
+
*/
|
|
16
|
+
export const CANARY_FILE = "canaries.json";
|
|
17
|
+
/** Exclusive create, same idea as `ledger.lock`. Held only across one add or remove. */
|
|
18
|
+
export const CANARY_LOCK_FILE = "canaries.lock";
|
|
19
|
+
export const CANARY_FINDING = "canary-exfiltration";
|
|
20
|
+
/**
|
|
21
|
+
* A local finding, not a signed alarm. `verax.incident.v1` is the memory
|
|
22
|
+
* integrity record: the incident writer accepts only those codes, signs them
|
|
23
|
+
* with the record key, and copies them to the alarm outbox. This file is
|
|
24
|
+
* written by the proxy, which does not hold that key, including when policy
|
|
25
|
+
* is `deny` and nothing halts. No alarm is sent.
|
|
26
|
+
*/
|
|
27
|
+
export const CANARY_INCIDENT_PURPOSE = "verax.canary-finding.v1";
|
|
28
|
+
export const CANARY_CHECK_BOUND_MS = 25;
|
|
29
|
+
export const CANARY_SHAPES = ["api-key", "bearer", "password", "card"];
|
|
30
|
+
export class CanaryStoreError extends Error {
|
|
31
|
+
constructor(message) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "CanaryStoreError";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const MIN_VALUE = 8;
|
|
37
|
+
const MAX_LABEL = 200;
|
|
38
|
+
const MAX_DEPTH = 32;
|
|
39
|
+
const MAX_CHARS = 1_000_000;
|
|
40
|
+
const MAX_PERCENT_ROUNDS = 3;
|
|
41
|
+
const MIN_FORM = 8;
|
|
42
|
+
const SAFE_SEGMENT = /^[A-Za-z0-9_-]{1,32}$/;
|
|
43
|
+
const ID_RE = /^cny_[0-9a-f]{16}$/;
|
|
44
|
+
let cache = null;
|
|
45
|
+
function canaryPath(stateDir) {
|
|
46
|
+
return join(stateDir, CANARY_FILE);
|
|
47
|
+
}
|
|
48
|
+
function dropCache(stateDir) {
|
|
49
|
+
if (cache && cache.key === resolve(stateDir))
|
|
50
|
+
cache = null;
|
|
51
|
+
}
|
|
52
|
+
function labelOk(label) {
|
|
53
|
+
if (label.length > MAX_LABEL)
|
|
54
|
+
return false;
|
|
55
|
+
for (let i = 0; i < label.length; i += 1) {
|
|
56
|
+
const c = label.charCodeAt(i);
|
|
57
|
+
if (c < 0x20 || c === 0x7f)
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
function isShape(value) {
|
|
63
|
+
return CANARY_SHAPES.includes(value);
|
|
64
|
+
}
|
|
65
|
+
function parseFile(text) {
|
|
66
|
+
let raw;
|
|
67
|
+
try {
|
|
68
|
+
raw = JSON.parse(text);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
throw new CanaryStoreError("canary-unreadable");
|
|
72
|
+
}
|
|
73
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
74
|
+
throw new CanaryStoreError("canary-unreadable");
|
|
75
|
+
}
|
|
76
|
+
const rec = raw;
|
|
77
|
+
if (rec.v !== 1 || !Array.isArray(rec.canaries)) {
|
|
78
|
+
throw new CanaryStoreError("canary-unreadable");
|
|
79
|
+
}
|
|
80
|
+
const out = [];
|
|
81
|
+
for (const item of rec.canaries) {
|
|
82
|
+
if (item === null || typeof item !== "object" || Array.isArray(item)) {
|
|
83
|
+
throw new CanaryStoreError("canary-unreadable");
|
|
84
|
+
}
|
|
85
|
+
const row = item;
|
|
86
|
+
if (typeof row.id !== "string" || !ID_RE.test(row.id))
|
|
87
|
+
throw new CanaryStoreError("canary-unreadable");
|
|
88
|
+
if (typeof row.label !== "string" || !labelOk(row.label))
|
|
89
|
+
throw new CanaryStoreError("canary-unreadable");
|
|
90
|
+
if (typeof row.shape !== "string" || !isShape(row.shape))
|
|
91
|
+
throw new CanaryStoreError("canary-unreadable");
|
|
92
|
+
if (typeof row.value !== "string")
|
|
93
|
+
throw new CanaryStoreError("canary-unreadable");
|
|
94
|
+
if (typeof row.createdAt !== "string" || row.createdAt === "")
|
|
95
|
+
throw new CanaryStoreError("canary-unreadable");
|
|
96
|
+
if (row.retiredAt !== null && typeof row.retiredAt !== "string")
|
|
97
|
+
throw new CanaryStoreError("canary-unreadable");
|
|
98
|
+
out.push({
|
|
99
|
+
id: row.id,
|
|
100
|
+
label: row.label,
|
|
101
|
+
shape: row.shape,
|
|
102
|
+
value: row.value,
|
|
103
|
+
createdAt: row.createdAt,
|
|
104
|
+
retiredAt: row.retiredAt,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
export function readCanaryFile(stateDir) {
|
|
110
|
+
let text;
|
|
111
|
+
try {
|
|
112
|
+
text = readFileSync(canaryPath(stateDir), "utf8");
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
if (err.code === "ENOENT")
|
|
116
|
+
return [];
|
|
117
|
+
throw new CanaryStoreError("canary-unreadable");
|
|
118
|
+
}
|
|
119
|
+
return parseFile(text);
|
|
120
|
+
}
|
|
121
|
+
export function writeCanaryFile(stateDir, rows) {
|
|
122
|
+
writeFileAtomic(canaryPath(stateDir), `${JSON.stringify({ v: 1, canaries: rows })}\n`);
|
|
123
|
+
dropCache(stateDir);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Runs after the store is read and before it is written, while the
|
|
127
|
+
* cross-process lock is held. The race test pauses one update on the
|
|
128
|
+
* snapshot it already read. Production leaves this null.
|
|
129
|
+
*/
|
|
130
|
+
export const canaryTestHooks = { afterRead: null };
|
|
131
|
+
/** How long a live holder may keep the lock before the waiter gives up. */
|
|
132
|
+
const CANARY_LOCK_WAIT_MS = 20_000;
|
|
133
|
+
const lockNap = new Int32Array(new SharedArrayBuffer(4));
|
|
134
|
+
function readCanaryLock(path) {
|
|
135
|
+
try {
|
|
136
|
+
const raw = JSON.parse(readFileSync(path, "utf8"));
|
|
137
|
+
if (typeof raw.pid !== "number" || !Number.isInteger(raw.pid))
|
|
138
|
+
return null;
|
|
139
|
+
if (typeof raw.startedAt !== "number" || !Number.isFinite(raw.startedAt))
|
|
140
|
+
return null;
|
|
141
|
+
return {
|
|
142
|
+
pid: raw.pid,
|
|
143
|
+
startedAt: raw.startedAt,
|
|
144
|
+
...(typeof raw.bootId === "string" && raw.bootId !== "" ? { bootId: raw.bootId } : {}),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* One lock across processes for the read, update and write of add and
|
|
153
|
+
* remove. The file is `canaries.lock`, taken with an exclusive `wx`
|
|
154
|
+
* create, the same way `FileLedger.acquireLock` takes `ledger.lock`.
|
|
155
|
+
* A holder `lockHolderAlive` rejects is stale. That is the ledger rule
|
|
156
|
+
* (`ledger.ts`): a dead pid, a boot id from another boot, or this pid
|
|
157
|
+
* stamped before this process started. A stale file is removed so a
|
|
158
|
+
* dead process does not block the next update. The lock is freed in
|
|
159
|
+
* `finally`.
|
|
160
|
+
*/
|
|
161
|
+
function withCanaryLock(stateDir, fn) {
|
|
162
|
+
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
163
|
+
const path = join(stateDir, CANARY_LOCK_FILE);
|
|
164
|
+
const bootId = currentBootId();
|
|
165
|
+
const body = `${JSON.stringify({
|
|
166
|
+
pid: process.pid,
|
|
167
|
+
startedAt: Date.now(),
|
|
168
|
+
token: randomBytes(8).toString("hex"),
|
|
169
|
+
...(bootId ? { bootId } : {}),
|
|
170
|
+
})}\n`;
|
|
171
|
+
const deadline = Date.now() + CANARY_LOCK_WAIT_MS;
|
|
172
|
+
for (;;) {
|
|
173
|
+
try {
|
|
174
|
+
writeFileSync(path, body, { encoding: "utf8", flag: "wx", mode: 0o600 });
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
catch (err) {
|
|
178
|
+
const code = err.code;
|
|
179
|
+
if (code !== "EEXIST")
|
|
180
|
+
throw err;
|
|
181
|
+
const holder = readCanaryLock(path);
|
|
182
|
+
if (holder && !lockHolderAlive(holder)) {
|
|
183
|
+
try {
|
|
184
|
+
unlinkSync(path);
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
// Already gone, or another waiter removed it.
|
|
188
|
+
}
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
if (Date.now() >= deadline)
|
|
192
|
+
throw new CanaryStoreError("canary-locked");
|
|
193
|
+
Atomics.wait(lockNap, 0, 0, 20);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
try {
|
|
197
|
+
return fn();
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
try {
|
|
201
|
+
if (readFileSync(path, "utf8") === body)
|
|
202
|
+
unlinkSync(path);
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
// Already released.
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
function take(alphabet, n) {
|
|
210
|
+
const bytes = randomBytes(n);
|
|
211
|
+
let out = "";
|
|
212
|
+
for (let i = 0; i < n; i += 1)
|
|
213
|
+
out += alphabet[bytes[i] % alphabet.length];
|
|
214
|
+
return out;
|
|
215
|
+
}
|
|
216
|
+
/** Check digit for a payload, doubling from the right as Luhn does once the digit is appended. */
|
|
217
|
+
function luhnCheckDigit(payload) {
|
|
218
|
+
let sum = 0;
|
|
219
|
+
let doubleIt = true;
|
|
220
|
+
for (let i = payload.length - 1; i >= 0; i -= 1) {
|
|
221
|
+
let n = payload.charCodeAt(i) - 48;
|
|
222
|
+
if (doubleIt) {
|
|
223
|
+
n *= 2;
|
|
224
|
+
if (n > 9)
|
|
225
|
+
n -= 9;
|
|
226
|
+
}
|
|
227
|
+
sum += n;
|
|
228
|
+
doubleIt = !doubleIt;
|
|
229
|
+
}
|
|
230
|
+
return (10 - (sum % 10)) % 10;
|
|
231
|
+
}
|
|
232
|
+
function makeCard() {
|
|
233
|
+
// 9999 is not a payment BIN. The last digit is not the Luhn digit, so the
|
|
234
|
+
// card detector (which requires a passing Luhn) does not classify it.
|
|
235
|
+
const payload = `9999${take("0123456789", 11)}`;
|
|
236
|
+
const bad = (luhnCheckDigit(payload) + 3) % 10;
|
|
237
|
+
return `${payload}${bad}`;
|
|
238
|
+
}
|
|
239
|
+
function makePassword() {
|
|
240
|
+
const lower = "abcdefghijkmnopqrstuvwxyz";
|
|
241
|
+
const upper = "ABCDEFGHJKLMNPQRSTUVWXYZ";
|
|
242
|
+
const digits = "23456789";
|
|
243
|
+
const symbols = "!@#";
|
|
244
|
+
const all = lower + upper + digits + symbols;
|
|
245
|
+
const chars = (take(lower, 1) + take(upper, 1) + take(digits, 1) + take(symbols, 1) + take(all, 16)).split("");
|
|
246
|
+
const rnd = randomBytes(chars.length);
|
|
247
|
+
for (let i = chars.length - 1; i > 0; i -= 1) {
|
|
248
|
+
const j = rnd[i] % (i + 1);
|
|
249
|
+
const swap = chars[i];
|
|
250
|
+
chars[i] = chars[j];
|
|
251
|
+
chars[j] = swap;
|
|
252
|
+
}
|
|
253
|
+
return chars.join("");
|
|
254
|
+
}
|
|
255
|
+
function makeValue(shape) {
|
|
256
|
+
if (shape === "api-key")
|
|
257
|
+
return `sk-${take("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 48)}`;
|
|
258
|
+
if (shape === "bearer")
|
|
259
|
+
return randomBytes(32).toString("base64url");
|
|
260
|
+
if (shape === "password")
|
|
261
|
+
return makePassword();
|
|
262
|
+
return makeCard();
|
|
263
|
+
}
|
|
264
|
+
export function addCanary(stateDir, opts = {}) {
|
|
265
|
+
const shape = opts.shape ?? "api-key";
|
|
266
|
+
if (!isShape(shape))
|
|
267
|
+
throw new CanaryStoreError("canary-shape");
|
|
268
|
+
const label = opts.label ?? "";
|
|
269
|
+
if (typeof label !== "string" || !labelOk(label))
|
|
270
|
+
throw new CanaryStoreError("canary-label");
|
|
271
|
+
const value = makeValue(shape);
|
|
272
|
+
const createdAt = new Date(opts.now ?? Date.now()).toISOString();
|
|
273
|
+
return withCanaryLock(stateDir, () => {
|
|
274
|
+
const rows = readCanaryFile(stateDir);
|
|
275
|
+
canaryTestHooks.afterRead?.();
|
|
276
|
+
let id = "";
|
|
277
|
+
for (let attempt = 0; attempt < 5 && id === ""; attempt += 1) {
|
|
278
|
+
const next = `cny_${randomBytes(8).toString("hex")}`;
|
|
279
|
+
if (!rows.some((row) => row.id === next))
|
|
280
|
+
id = next;
|
|
281
|
+
}
|
|
282
|
+
if (id === "")
|
|
283
|
+
throw new CanaryStoreError("canary-id");
|
|
284
|
+
rows.push({ id, label, shape, value, createdAt, retiredAt: null });
|
|
285
|
+
writeCanaryFile(stateDir, rows);
|
|
286
|
+
return { id, value, label, shape, createdAt };
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
/** `retired` when this call retired it or it was already retired. `missing` when the id is unknown. */
|
|
290
|
+
export function retireCanary(stateDir, id, now = Date.now()) {
|
|
291
|
+
if (!ID_RE.test(id))
|
|
292
|
+
return "missing";
|
|
293
|
+
return withCanaryLock(stateDir, () => {
|
|
294
|
+
const rows = readCanaryFile(stateDir);
|
|
295
|
+
canaryTestHooks.afterRead?.();
|
|
296
|
+
const row = rows.find((item) => item.id === id);
|
|
297
|
+
if (!row)
|
|
298
|
+
return "missing";
|
|
299
|
+
if (row.retiredAt !== null)
|
|
300
|
+
return "retired";
|
|
301
|
+
row.retiredAt = new Date(now).toISOString();
|
|
302
|
+
row.value = "";
|
|
303
|
+
writeCanaryFile(stateDir, rows);
|
|
304
|
+
return "retired";
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
export function listCanaries(stateDir) {
|
|
308
|
+
return readCanaryFile(stateDir).map((row) => ({
|
|
309
|
+
id: row.id,
|
|
310
|
+
label: row.label,
|
|
311
|
+
createdAt: row.createdAt,
|
|
312
|
+
status: row.retiredAt === null ? "active" : "retired",
|
|
313
|
+
}));
|
|
314
|
+
}
|
|
315
|
+
/** The active value, for the operator plant path. A retired id returns null. */
|
|
316
|
+
export function activeCanaryValue(stateDir, id) {
|
|
317
|
+
const row = readCanaryFile(stateDir).find((item) => item.id === id);
|
|
318
|
+
if (!row || row.retiredAt !== null || row.value.length < MIN_VALUE)
|
|
319
|
+
return null;
|
|
320
|
+
return row.value;
|
|
321
|
+
}
|
|
322
|
+
export function loadActiveCanaries(stateDir) {
|
|
323
|
+
const path = canaryPath(stateDir);
|
|
324
|
+
let st;
|
|
325
|
+
try {
|
|
326
|
+
st = statSync(path);
|
|
327
|
+
}
|
|
328
|
+
catch (err) {
|
|
329
|
+
if (err.code === "ENOENT")
|
|
330
|
+
return { ok: true, canaries: [] };
|
|
331
|
+
return { ok: false, reason: "canary-unreadable" };
|
|
332
|
+
}
|
|
333
|
+
if (!st.isFile())
|
|
334
|
+
return { ok: false, reason: "canary-unreadable" };
|
|
335
|
+
const key = resolve(stateDir);
|
|
336
|
+
if (cache && cache.key === key && cache.mtimeMs === st.mtimeMs && cache.size === st.size) {
|
|
337
|
+
return { ok: true, canaries: cache.canaries };
|
|
338
|
+
}
|
|
339
|
+
let rows;
|
|
340
|
+
try {
|
|
341
|
+
rows = parseFile(readFileSync(path, "utf8"));
|
|
342
|
+
}
|
|
343
|
+
catch {
|
|
344
|
+
return { ok: false, reason: "canary-unreadable" };
|
|
345
|
+
}
|
|
346
|
+
const canaries = rows
|
|
347
|
+
.filter((row) => row.retiredAt === null && row.value.length >= MIN_VALUE)
|
|
348
|
+
.map((row) => ({ id: row.id, value: row.value }));
|
|
349
|
+
cache = { key, mtimeMs: st.mtimeMs, size: st.size, canaries };
|
|
350
|
+
return { ok: true, canaries };
|
|
351
|
+
}
|
|
352
|
+
function collapseSpace(text) {
|
|
353
|
+
return text.replace(/\s+/g, "");
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Candidate slices of one base64 encoding. A slice finds a place to look.
|
|
357
|
+
* It is not a match until `candidateConfirms` decodes the whole value there.
|
|
358
|
+
* Alignment covers a value buried in a longer run. Fragments shorter than
|
|
359
|
+
* a canary are left out. Percent-encoding is not generated: the call text
|
|
360
|
+
* is decoded instead, which is what ordinary encoders produce.
|
|
361
|
+
*/
|
|
362
|
+
function base64Candidates(bytes, encoding) {
|
|
363
|
+
const forms = new Set();
|
|
364
|
+
const add = (form) => {
|
|
365
|
+
if (form.length >= MIN_FORM)
|
|
366
|
+
forms.add(form);
|
|
367
|
+
};
|
|
368
|
+
const full = bytes.toString(encoding);
|
|
369
|
+
add(full);
|
|
370
|
+
add(full.replace(/=+$/, ""));
|
|
371
|
+
for (let skip = 0; skip < 3; skip += 1) {
|
|
372
|
+
const usable = bytes.length - skip;
|
|
373
|
+
const groups = usable - (usable % 3);
|
|
374
|
+
if (groups < 3)
|
|
375
|
+
continue;
|
|
376
|
+
add(bytes.subarray(skip, skip + groups).toString(encoding).replace(/=+$/, ""));
|
|
377
|
+
}
|
|
378
|
+
return [...forms];
|
|
379
|
+
}
|
|
380
|
+
function prepare(canaries) {
|
|
381
|
+
const out = [];
|
|
382
|
+
for (const row of canaries) {
|
|
383
|
+
if (row.value.length < MIN_VALUE)
|
|
384
|
+
continue;
|
|
385
|
+
const bytes = Buffer.from(row.value, "utf8");
|
|
386
|
+
const hexLower = bytes.toString("hex");
|
|
387
|
+
out.push({
|
|
388
|
+
id: row.id,
|
|
389
|
+
value: row.value,
|
|
390
|
+
bytes,
|
|
391
|
+
hexLower,
|
|
392
|
+
base64: base64Candidates(bytes, "base64"),
|
|
393
|
+
base64url: base64Candidates(bytes, "base64url"),
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
return out;
|
|
397
|
+
}
|
|
398
|
+
function isBase64Char(code, url) {
|
|
399
|
+
if (code >= 48 && code <= 57)
|
|
400
|
+
return true;
|
|
401
|
+
if (code >= 65 && code <= 90)
|
|
402
|
+
return true;
|
|
403
|
+
if (code >= 97 && code <= 122)
|
|
404
|
+
return true;
|
|
405
|
+
if (url)
|
|
406
|
+
return code === 45 || code === 95;
|
|
407
|
+
return code === 43 || code === 47;
|
|
408
|
+
}
|
|
409
|
+
/** Decode one alphabet run. A character outside that alphabet is not a value. */
|
|
410
|
+
function decodeBase64Slice(slice, encoding) {
|
|
411
|
+
let body = slice;
|
|
412
|
+
while (body.endsWith("="))
|
|
413
|
+
body = body.slice(0, -1);
|
|
414
|
+
if (body.length === 0)
|
|
415
|
+
return null;
|
|
416
|
+
const url = encoding === "base64url";
|
|
417
|
+
for (let i = 0; i < body.length; i += 1) {
|
|
418
|
+
if (!isBase64Char(body.charCodeAt(i), url))
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
const pad = (4 - (body.length % 4)) % 4;
|
|
422
|
+
return Buffer.from(pad === 0 ? body : body + "=".repeat(pad), encoding);
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* The candidate marks an aligned slice. One group on either side is enough
|
|
426
|
+
* to cover the bytes the slice left off. The decode has to contain the
|
|
427
|
+
* whole value: a near miss shares the slice and fails here.
|
|
428
|
+
*/
|
|
429
|
+
function candidateConfirms(text, at, formLength, url, valueBytes) {
|
|
430
|
+
let runStart = at;
|
|
431
|
+
while (runStart > 0 && isBase64Char(text.charCodeAt(runStart - 1), url))
|
|
432
|
+
runStart -= 1;
|
|
433
|
+
let runEnd = at + formLength;
|
|
434
|
+
while (runEnd < text.length && isBase64Char(text.charCodeAt(runEnd), url))
|
|
435
|
+
runEnd += 1;
|
|
436
|
+
let padEnd = runEnd;
|
|
437
|
+
while (padEnd < text.length && text.charCodeAt(padEnd) === 61)
|
|
438
|
+
padEnd += 1;
|
|
439
|
+
const rel = at - runStart;
|
|
440
|
+
const align = rel % 4;
|
|
441
|
+
const from = rel - 4 >= align ? rel - 4 : align;
|
|
442
|
+
const to = Math.min(padEnd - runStart, rel + formLength + 4);
|
|
443
|
+
if (to <= from)
|
|
444
|
+
return false;
|
|
445
|
+
const decoded = decodeBase64Slice(text.slice(runStart + from, runStart + to), url ? "base64url" : "base64");
|
|
446
|
+
return decoded !== null && decoded.includes(valueBytes);
|
|
447
|
+
}
|
|
448
|
+
function base64Hit(text, forms, url, valueBytes) {
|
|
449
|
+
for (const form of forms) {
|
|
450
|
+
if (form.length === 0)
|
|
451
|
+
continue;
|
|
452
|
+
let from = 0;
|
|
453
|
+
while (from <= text.length - form.length) {
|
|
454
|
+
const at = text.indexOf(form, from);
|
|
455
|
+
if (at < 0)
|
|
456
|
+
break;
|
|
457
|
+
if (candidateConfirms(text, at, form.length, url, valueBytes))
|
|
458
|
+
return true;
|
|
459
|
+
from = at + 1;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
return false;
|
|
463
|
+
}
|
|
464
|
+
function hexNibble(code) {
|
|
465
|
+
if (code >= 48 && code <= 57)
|
|
466
|
+
return code - 48;
|
|
467
|
+
if (code >= 65 && code <= 70)
|
|
468
|
+
return code - 55;
|
|
469
|
+
if (code >= 97 && code <= 102)
|
|
470
|
+
return code - 87;
|
|
471
|
+
return -1;
|
|
472
|
+
}
|
|
473
|
+
/** Percent-decode one pass. An invalid `%` sequence is copied through. `+` becomes a space only when asked. */
|
|
474
|
+
function percentDecode(text, plusAsSpace) {
|
|
475
|
+
const parts = [];
|
|
476
|
+
const bytes = [];
|
|
477
|
+
const flush = () => {
|
|
478
|
+
if (bytes.length === 0)
|
|
479
|
+
return;
|
|
480
|
+
parts.push(Buffer.from(bytes).toString("utf8"));
|
|
481
|
+
bytes.length = 0;
|
|
482
|
+
};
|
|
483
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
484
|
+
const code = text.charCodeAt(i);
|
|
485
|
+
if (plusAsSpace && code === 43) {
|
|
486
|
+
flush();
|
|
487
|
+
parts.push(" ");
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
if (code === 37) {
|
|
491
|
+
const hi = hexNibble(text.charCodeAt(i + 1));
|
|
492
|
+
const lo = hexNibble(text.charCodeAt(i + 2));
|
|
493
|
+
if (hi >= 0 && lo >= 0) {
|
|
494
|
+
bytes.push((hi << 4) | lo);
|
|
495
|
+
i += 2;
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
flush();
|
|
500
|
+
parts.push(text[i]);
|
|
501
|
+
}
|
|
502
|
+
flush();
|
|
503
|
+
return parts.join("");
|
|
504
|
+
}
|
|
505
|
+
/** Up to three decodes. Each pass is tried with `+` left as `+` and with `+` read as a space. */
|
|
506
|
+
function decodedTexts(text) {
|
|
507
|
+
if (!text.includes("%") && !text.includes("+"))
|
|
508
|
+
return [];
|
|
509
|
+
const out = [];
|
|
510
|
+
const seen = new Set([text]);
|
|
511
|
+
let layer = [text];
|
|
512
|
+
for (let round = 0; round < MAX_PERCENT_ROUNDS && layer.length > 0; round += 1) {
|
|
513
|
+
const next = [];
|
|
514
|
+
for (const cur of layer) {
|
|
515
|
+
const plain = percentDecode(cur, false);
|
|
516
|
+
const plus = cur.includes("+") ? percentDecode(cur, true) : plain;
|
|
517
|
+
for (const decoded of plain === plus ? [plain] : [plain, plus]) {
|
|
518
|
+
if (seen.has(decoded))
|
|
519
|
+
continue;
|
|
520
|
+
seen.add(decoded);
|
|
521
|
+
out.push(decoded);
|
|
522
|
+
if (decoded.includes("%") || decoded.includes("+"))
|
|
523
|
+
next.push(decoded);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
layer = next;
|
|
527
|
+
}
|
|
528
|
+
return out;
|
|
529
|
+
}
|
|
530
|
+
function rawIn(text, rows) {
|
|
531
|
+
const collapsed = collapseSpace(text);
|
|
532
|
+
for (const row of rows) {
|
|
533
|
+
if (text.includes(row.value))
|
|
534
|
+
return row;
|
|
535
|
+
if (collapsed !== text && collapsed.includes(row.value))
|
|
536
|
+
return row;
|
|
537
|
+
}
|
|
538
|
+
return null;
|
|
539
|
+
}
|
|
540
|
+
function findRaw(text, rows) {
|
|
541
|
+
const direct = rawIn(text, rows);
|
|
542
|
+
if (direct)
|
|
543
|
+
return direct;
|
|
544
|
+
const variants = decodedTexts(text);
|
|
545
|
+
for (let i = 0; i < variants.length; i += 1) {
|
|
546
|
+
const hit = rawIn(variants[i], rows);
|
|
547
|
+
if (hit)
|
|
548
|
+
return hit;
|
|
549
|
+
}
|
|
550
|
+
return null;
|
|
551
|
+
}
|
|
552
|
+
function encodedIn(text, rows) {
|
|
553
|
+
const collapsed = collapseSpace(text);
|
|
554
|
+
const haystacks = collapsed === text ? [text] : [text, collapsed];
|
|
555
|
+
for (const hay of haystacks) {
|
|
556
|
+
// A hex decoder reads any letter case, so hex is compared on lower-cased text.
|
|
557
|
+
const lower = hay.toLowerCase();
|
|
558
|
+
for (const row of rows) {
|
|
559
|
+
if (lower.includes(row.hexLower))
|
|
560
|
+
return row;
|
|
561
|
+
if (base64Hit(hay, row.base64, false, row.bytes))
|
|
562
|
+
return row;
|
|
563
|
+
if (base64Hit(hay, row.base64url, true, row.bytes))
|
|
564
|
+
return row;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return null;
|
|
568
|
+
}
|
|
569
|
+
function findEncoded(text, rows) {
|
|
570
|
+
const direct = encodedIn(text, rows);
|
|
571
|
+
if (direct)
|
|
572
|
+
return direct;
|
|
573
|
+
const variants = decodedTexts(text);
|
|
574
|
+
for (let i = 0; i < variants.length; i += 1) {
|
|
575
|
+
const hit = encodedIn(variants[i], rows);
|
|
576
|
+
if (hit)
|
|
577
|
+
return hit;
|
|
578
|
+
}
|
|
579
|
+
return null;
|
|
580
|
+
}
|
|
581
|
+
function findAny(text, rows) {
|
|
582
|
+
return findRaw(text, rows) ?? findEncoded(text, rows);
|
|
583
|
+
}
|
|
584
|
+
function whereFor(segments, value) {
|
|
585
|
+
if (segments.length === 0)
|
|
586
|
+
return "arguments";
|
|
587
|
+
if (segments.some((seg) => !SAFE_SEGMENT.test(seg) || seg.includes(value)))
|
|
588
|
+
return "arguments";
|
|
589
|
+
const path = `arguments.${segments.join(".")}`;
|
|
590
|
+
return path.includes(value) ? "arguments" : path;
|
|
591
|
+
}
|
|
592
|
+
function subjectOf(hit, toolName) {
|
|
593
|
+
return toolName.includes(hit.value) ? "tool" : toolName || "tool";
|
|
594
|
+
}
|
|
595
|
+
function located(hit, segments, toolName) {
|
|
596
|
+
return { id: hit.id, where: whereFor(segments, hit.value), subject: subjectOf(hit, toolName) };
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* The first active canary found in the arguments, the tool name, or the
|
|
600
|
+
* arguments joined so a value split across fields is still one string.
|
|
601
|
+
* String leaves are joined on their own, so a number sitting between two
|
|
602
|
+
* halves is not part of that string. A second join runs only when a number
|
|
603
|
+
* leaf is present, and it includes those leaves with the strings. A secret
|
|
604
|
+
* split into two JSON numbers is still one string when no string value sits
|
|
605
|
+
* between them. The string join is searched first. Hex is the whole value
|
|
606
|
+
* in any letter case. Base64 and base64url are searched at each byte
|
|
607
|
+
* alignment; an aligned slice is only a candidate until that slice and
|
|
608
|
+
* the bytes beside it decode to the whole value. A one-character near
|
|
609
|
+
* miss is not that value. Both are searched in the text and in each
|
|
610
|
+
* percent-decoded variant, including that variant with whitespace
|
|
611
|
+
* removed. Percent-encoding is decoded up to three times; an invalid `%`
|
|
612
|
+
* sequence is left as it is, and `+` is also tried as a space. A number
|
|
613
|
+
* leaf is read as `String(value)`. Past 32 levels or 1,000,000 characters
|
|
614
|
+
* the walk continues, iteratively, for the raw search only. A value that
|
|
615
|
+
* is found is a match. Otherwise the result is `too-wide`. The result
|
|
616
|
+
* never carries the value.
|
|
617
|
+
*/
|
|
618
|
+
export function matchCanary(args, canaries, toolName = "") {
|
|
619
|
+
const active = prepare(canaries);
|
|
620
|
+
if (active.length === 0)
|
|
621
|
+
return null;
|
|
622
|
+
if (toolName !== "") {
|
|
623
|
+
const named = findAny(toolName, active);
|
|
624
|
+
if (named)
|
|
625
|
+
return { id: named.id, where: "tool name", subject: "tool" };
|
|
626
|
+
}
|
|
627
|
+
let chars = toolName.length;
|
|
628
|
+
let limited = false;
|
|
629
|
+
const leaves = [];
|
|
630
|
+
const joinedHit = (rows, encoded) => {
|
|
631
|
+
const search = encoded ? findAny : findRaw;
|
|
632
|
+
const pick = (includeNumbers) => {
|
|
633
|
+
const parts = rows.filter((row) => includeNumbers || !row.number);
|
|
634
|
+
if (parts.length < 2)
|
|
635
|
+
return null;
|
|
636
|
+
const hit = search(parts.map((row) => row.text).join("\n"), active);
|
|
637
|
+
if (!hit)
|
|
638
|
+
return null;
|
|
639
|
+
return { id: hit.id, where: "arguments", subject: subjectOf(hit, toolName) };
|
|
640
|
+
};
|
|
641
|
+
return pick(false) ?? (rows.some((row) => row.number) ? pick(true) : null);
|
|
642
|
+
};
|
|
643
|
+
const stack = [{ value: args, segments: [], depth: 0 }];
|
|
644
|
+
const absorb = (text, segments, number) => {
|
|
645
|
+
const rawHit = findRaw(text, active);
|
|
646
|
+
if (rawHit)
|
|
647
|
+
return located(rawHit, segments, toolName);
|
|
648
|
+
if (limited)
|
|
649
|
+
return null;
|
|
650
|
+
if (chars + text.length > MAX_CHARS) {
|
|
651
|
+
const hit = joinedHit([...leaves, { text, number }], false);
|
|
652
|
+
if (hit)
|
|
653
|
+
return hit;
|
|
654
|
+
limited = true;
|
|
655
|
+
return null;
|
|
656
|
+
}
|
|
657
|
+
const encodedHit = findEncoded(text, active);
|
|
658
|
+
if (encodedHit)
|
|
659
|
+
return located(encodedHit, segments, toolName);
|
|
660
|
+
chars += text.length;
|
|
661
|
+
leaves.push({ text, number });
|
|
662
|
+
return null;
|
|
663
|
+
};
|
|
664
|
+
while (stack.length > 0) {
|
|
665
|
+
const frame = stack.pop();
|
|
666
|
+
if (frame.depth > MAX_DEPTH)
|
|
667
|
+
limited = true;
|
|
668
|
+
const cur = frame.value;
|
|
669
|
+
if (typeof cur === "string") {
|
|
670
|
+
const hit = absorb(cur, frame.segments, false);
|
|
671
|
+
if (hit)
|
|
672
|
+
return hit;
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
if (typeof cur === "number") {
|
|
676
|
+
const hit = absorb(String(cur), frame.segments, true);
|
|
677
|
+
if (hit)
|
|
678
|
+
return hit;
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
if (Array.isArray(cur)) {
|
|
682
|
+
for (let i = cur.length - 1; i >= 0; i -= 1) {
|
|
683
|
+
stack.push({ value: cur[i], segments: [...frame.segments, String(i)], depth: frame.depth + 1 });
|
|
684
|
+
}
|
|
685
|
+
continue;
|
|
686
|
+
}
|
|
687
|
+
if (cur !== null && typeof cur === "object") {
|
|
688
|
+
const rec = cur;
|
|
689
|
+
const keys = Object.keys(rec);
|
|
690
|
+
for (let i = keys.length - 1; i >= 0; i -= 1) {
|
|
691
|
+
const key = keys[i];
|
|
692
|
+
const keyHit = absorb(key, frame.segments, false);
|
|
693
|
+
if (keyHit)
|
|
694
|
+
return keyHit;
|
|
695
|
+
stack.push({ value: rec[key], segments: [...frame.segments, key], depth: frame.depth + 1 });
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
if (limited)
|
|
700
|
+
return "too-wide";
|
|
701
|
+
const joined = joinedHit(leaves, true);
|
|
702
|
+
if (joined)
|
|
703
|
+
return joined;
|
|
704
|
+
return null;
|
|
705
|
+
}
|
|
706
|
+
export function writeCanaryIncident(stateDir, hit) {
|
|
707
|
+
const eventId = randomUUID();
|
|
708
|
+
const record = {
|
|
709
|
+
v: 1,
|
|
710
|
+
purpose: CANARY_INCIDENT_PURPOSE,
|
|
711
|
+
finding: CANARY_FINDING,
|
|
712
|
+
eventId,
|
|
713
|
+
observedAt: hit.observedAt,
|
|
714
|
+
triggerCode: CANARY_FINDING,
|
|
715
|
+
canaryId: hit.id,
|
|
716
|
+
where: hit.where,
|
|
717
|
+
enforcement: hit.enforcement,
|
|
718
|
+
};
|
|
719
|
+
writeFileAtomic(join(stateDir, "incidents", `${eventId}.json`), `${JSON.stringify(record)}\n`);
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* The same switch `verax halt` writes: an empty `halted` file, then one
|
|
723
|
+
* history line. A later call copies that line into the ledger. The line names
|
|
724
|
+
* the actor and does not name the value.
|
|
725
|
+
*/
|
|
726
|
+
export function haltForCanary(stateDir, atMs) {
|
|
727
|
+
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
|
|
728
|
+
const switchPath = join(stateDir, "halted");
|
|
729
|
+
let had = false;
|
|
730
|
+
try {
|
|
731
|
+
had = statSync(switchPath).isFile();
|
|
732
|
+
}
|
|
733
|
+
catch {
|
|
734
|
+
had = false;
|
|
735
|
+
}
|
|
736
|
+
if (!had)
|
|
737
|
+
writeFileSync(switchPath, "", { encoding: "utf8", mode: 0o600 });
|
|
738
|
+
if (isHaltedSwitchFile(stateDir))
|
|
739
|
+
clearProcessHalted(stateDir);
|
|
740
|
+
if (had || !isHaltedSwitchFile(stateDir))
|
|
741
|
+
return;
|
|
742
|
+
const event = { action: "halt", atMs, by: "verax:canary", via: "cli" };
|
|
743
|
+
const fd = openSync(join(stateDir, "halt-history.jsonl"), "a", 0o600);
|
|
744
|
+
try {
|
|
745
|
+
writeSync(fd, `${JSON.stringify(event)}\n`, null, "utf8");
|
|
746
|
+
fsyncSync(fd);
|
|
747
|
+
}
|
|
748
|
+
finally {
|
|
749
|
+
closeSync(fd);
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
/** Used when the switch file could not be written. Same flag the proxy already honours. */
|
|
753
|
+
export function markCanaryHalted(stateDir) {
|
|
754
|
+
markProcessHalted(stateDir);
|
|
755
|
+
}
|