@qlairoslabs/acp-client 0.6.0 → 0.7.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/CONSUMER_GUIDE.md +579 -292
- package/README.md +25 -0
- package/package.json +1 -1
- package/src/agent-session.ts +2188 -96
- package/src/cli/index.ts +33 -5
- package/src/cli/managed.ts +220 -0
- package/src/controller.ts +13 -0
- package/src/index.ts +228 -3
- package/src/metering/engine.ts +9 -1
- package/src/metering/record.ts +2 -1
- package/src/persistence/activity-projection.ts +71 -0
- package/src/persistence/audit-log-reader.ts +506 -0
- package/src/persistence/audit-runtime.ts +162 -0
- package/src/persistence/checkpoint.ts +304 -0
- package/src/persistence/config.ts +538 -0
- package/src/persistence/configuration-state.ts +191 -0
- package/src/persistence/deletion.ts +227 -0
- package/src/persistence/file-registry-store.ts +740 -0
- package/src/persistence/integrity.ts +147 -0
- package/src/persistence/legacy-registry-import.ts +240 -0
- package/src/persistence/managed-checkpoint.ts +81 -0
- package/src/persistence/managed-creation.ts +456 -0
- package/src/persistence/managed-load.ts +172 -0
- package/src/persistence/managed-registry.ts +57 -0
- package/src/persistence/migration.ts +298 -0
- package/src/persistence/paths.ts +172 -0
- package/src/persistence/projection.ts +373 -0
- package/src/persistence/reconfiguration.ts +453 -0
- package/src/persistence/records.ts +873 -0
- package/src/persistence/reducer.ts +498 -0
- package/src/persistence/registry.ts +446 -0
- package/src/persistence/restoration.ts +689 -0
- package/src/persistence/session-log-writer.ts +480 -0
- package/src/persistence/state-runtime.ts +176 -0
- package/src/persistence/transcript-reader.ts +980 -0
- package/src/persistence/transcript-runtime.ts +667 -0
- package/src/persistence/transcript-scanner.ts +385 -0
- package/src/persistence/truncation.ts +276 -0
- package/src/session-manager.ts +257 -7
- package/src/transcript.ts +3 -3
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { AggregatedRecord } from "../activity.ts";
|
|
2
|
+
import type { ActivityEvent, ToolActivity } from "../types.ts";
|
|
3
|
+
import type { JsonObject, JsonValue } from "./checkpoint.ts";
|
|
4
|
+
import type { NormalizedPersistenceEvent } from "./projection.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Classify an already-folded live activity record into persistence security buckets.
|
|
8
|
+
* This function deliberately does not serialize or hash values: capture projection gets
|
|
9
|
+
* to discard a bucket before the writer ever examines its potentially sensitive content.
|
|
10
|
+
*/
|
|
11
|
+
export function persistenceEventFromActivity(
|
|
12
|
+
record: AggregatedRecord,
|
|
13
|
+
operationId: string,
|
|
14
|
+
): NormalizedPersistenceEvent {
|
|
15
|
+
if (record.event.kind === "thinking") {
|
|
16
|
+
return {
|
|
17
|
+
kind: "reasoning",
|
|
18
|
+
reasoningId: record.recordId,
|
|
19
|
+
reasoningRevision: record.seq,
|
|
20
|
+
operationId,
|
|
21
|
+
text: record.event.text,
|
|
22
|
+
status: record.reason === "settled" || record.reason === "flushed" ? "completed" : "in_progress",
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
if (record.event.kind === "tool") {
|
|
27
|
+
return {
|
|
28
|
+
kind: "activity",
|
|
29
|
+
activity: toolProjection(record, record.event, operationId),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return {
|
|
34
|
+
kind: "activity",
|
|
35
|
+
activity: {
|
|
36
|
+
activityId: record.recordId,
|
|
37
|
+
activityRevision: record.seq,
|
|
38
|
+
operationId,
|
|
39
|
+
reason: record.reason,
|
|
40
|
+
kind: record.event.kind,
|
|
41
|
+
content: { event: record.event as unknown as JsonValue },
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function toolProjection(
|
|
47
|
+
record: AggregatedRecord,
|
|
48
|
+
event: ToolActivity,
|
|
49
|
+
operationId: string,
|
|
50
|
+
) {
|
|
51
|
+
const content: Record<string, JsonValue> = {
|
|
52
|
+
toolKind: event.toolKind,
|
|
53
|
+
...(event.title === undefined ? {} : { title: event.title }),
|
|
54
|
+
...(event.rawOutput === undefined ? {} : { rawOutput: event.rawOutput as JsonValue }),
|
|
55
|
+
...(event.content === undefined ? {} : { content: event.content as unknown as JsonValue }),
|
|
56
|
+
...(event.locations === undefined ? {} : { locations: event.locations as unknown as JsonValue }),
|
|
57
|
+
};
|
|
58
|
+
return {
|
|
59
|
+
activityId: record.recordId,
|
|
60
|
+
activityRevision: record.seq,
|
|
61
|
+
operationId,
|
|
62
|
+
reason: record.reason,
|
|
63
|
+
kind: "tool",
|
|
64
|
+
status: event.status,
|
|
65
|
+
metadata: { providerActivityId: event.toolCallId },
|
|
66
|
+
...(event.rawInput === undefined
|
|
67
|
+
? {}
|
|
68
|
+
: { input: { value: event.rawInput as JsonValue } as JsonObject }),
|
|
69
|
+
content: content as JsonObject,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
import { open, type FileHandle } from "node:fs/promises";
|
|
2
|
+
import { isAbsolute } from "node:path";
|
|
3
|
+
import type { JsonObject } from "./checkpoint.ts";
|
|
4
|
+
import { canonicalizeJson } from "./integrity.ts";
|
|
5
|
+
import {
|
|
6
|
+
validateAuditLogRecord,
|
|
7
|
+
type AuditLogHeaderRecord,
|
|
8
|
+
type AuditLogRecordType,
|
|
9
|
+
type KnownAuditLogRecord,
|
|
10
|
+
type UnknownAuditLogRecord,
|
|
11
|
+
} from "./records.ts";
|
|
12
|
+
import {
|
|
13
|
+
SESSION_LOG_READER_INTERNALS as IO,
|
|
14
|
+
TranscriptCursorInvalidError,
|
|
15
|
+
TranscriptReaderError,
|
|
16
|
+
type SessionLogPhysicalLine,
|
|
17
|
+
type TranscriptPage,
|
|
18
|
+
} from "./transcript-reader.ts";
|
|
19
|
+
|
|
20
|
+
const DEFAULT_LIMIT = 50;
|
|
21
|
+
const MAX_LIMIT = 500;
|
|
22
|
+
const CURSOR_VERSION = 1;
|
|
23
|
+
const UTF8 = new TextDecoder("utf-8", { fatal: true });
|
|
24
|
+
const AUDIT_TYPE_ORDER: readonly AuditLogRecordType[] = Object.freeze([
|
|
25
|
+
"header", "operation", "reasoning", "activity", "configuration", "permission",
|
|
26
|
+
"transition", "metering_reference", "lifecycle",
|
|
27
|
+
]);
|
|
28
|
+
const AUDIT_TYPES = new Set(AUDIT_TYPE_ORDER);
|
|
29
|
+
|
|
30
|
+
export type AuditLogCursor = string & { readonly __auditLogCursor: unique symbol };
|
|
31
|
+
export type AuditLogSnapshotCursor = string & { readonly __auditLogSnapshotCursor: unique symbol };
|
|
32
|
+
|
|
33
|
+
export interface ReadAuditLogPageOptions {
|
|
34
|
+
readonly cursor?: AuditLogCursor;
|
|
35
|
+
readonly limit?: number;
|
|
36
|
+
readonly types?: readonly AuditLogRecordType[];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class AuditLogCursorInvalidError extends Error {
|
|
40
|
+
constructor(message: string, options?: ErrorOptions) {
|
|
41
|
+
super(message, options);
|
|
42
|
+
this.name = "AuditLogCursorInvalidError";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export class AuditLogReaderError extends Error {
|
|
47
|
+
constructor(message: string, options?: ErrorOptions) {
|
|
48
|
+
super(message, options);
|
|
49
|
+
this.name = "AuditLogReaderError";
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
interface SnapshotBoundary {
|
|
54
|
+
readonly id: string;
|
|
55
|
+
readonly generation: number;
|
|
56
|
+
readonly highSequence: number;
|
|
57
|
+
readonly highOffset: number;
|
|
58
|
+
readonly prefixDigest: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface SnapshotPayload extends SnapshotBoundary {
|
|
62
|
+
readonly kind: "snapshot";
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface NavigationPayload extends SnapshotBoundary {
|
|
66
|
+
readonly kind: "navigation";
|
|
67
|
+
readonly direction: "older" | "newer";
|
|
68
|
+
readonly boundarySequence: number;
|
|
69
|
+
readonly boundaryStart: number;
|
|
70
|
+
readonly boundaryEnd: number;
|
|
71
|
+
readonly boundaryDigest: string;
|
|
72
|
+
readonly types: readonly AuditLogRecordType[];
|
|
73
|
+
readonly filterProvided: boolean;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
interface PhysicalRecord {
|
|
77
|
+
readonly item: KnownAuditLogRecord | UnknownAuditLogRecord;
|
|
78
|
+
readonly sequence: number;
|
|
79
|
+
readonly start: number;
|
|
80
|
+
readonly end: number;
|
|
81
|
+
readonly digest: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
interface SnapshotContext {
|
|
85
|
+
readonly handle: FileHandle;
|
|
86
|
+
readonly header: AuditLogHeaderRecord;
|
|
87
|
+
readonly payload: SnapshotPayload;
|
|
88
|
+
readonly snapshotCursor: AuditLogSnapshotCursor;
|
|
89
|
+
readonly navigation: NavigationPayload | null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
interface TypeFilter {
|
|
93
|
+
readonly provided: boolean;
|
|
94
|
+
readonly types: readonly AuditLogRecordType[];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Snapshot-bound, cursor-paginated reader for one audit-log generation. */
|
|
98
|
+
export class AuditLogReader {
|
|
99
|
+
constructor(readonly path: string) {
|
|
100
|
+
if (!isAbsolute(path)) throw new AuditLogReaderError("audit-log reader path must be absolute");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async readPage(
|
|
104
|
+
options: ReadAuditLogPageOptions = {},
|
|
105
|
+
): Promise<TranscriptPage<KnownAuditLogRecord | UnknownAuditLogRecord, AuditLogCursor, AuditLogSnapshotCursor>> {
|
|
106
|
+
const limit = validatedLimit(options.limit);
|
|
107
|
+
const filter = normalizeTypes(options.types);
|
|
108
|
+
const snapshot = await this.openSnapshot(options.cursor);
|
|
109
|
+
try {
|
|
110
|
+
const navigation = snapshot.navigation;
|
|
111
|
+
if (navigation) {
|
|
112
|
+
if (navigation.filterProvided !== filter.provided
|
|
113
|
+
|| canonicalizeJson(navigation.types) !== canonicalizeJson(filter.types)) {
|
|
114
|
+
throw new AuditLogCursorInvalidError("audit-log cursor type filter changed");
|
|
115
|
+
}
|
|
116
|
+
await validateBoundary(snapshot.handle, snapshot.header, navigation);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
let selected: PhysicalRecord[];
|
|
120
|
+
let hasOlder: boolean;
|
|
121
|
+
let hasNewer: boolean;
|
|
122
|
+
if (!navigation || navigation.direction === "older") {
|
|
123
|
+
const matches = await collectBackward(
|
|
124
|
+
snapshot.handle,
|
|
125
|
+
snapshot.header,
|
|
126
|
+
navigation?.boundaryStart ?? snapshot.payload.highOffset,
|
|
127
|
+
limit + 1,
|
|
128
|
+
navigation ? navigation.boundarySequence - 1 : snapshot.payload.highSequence,
|
|
129
|
+
filter,
|
|
130
|
+
);
|
|
131
|
+
hasOlder = matches.length > limit;
|
|
132
|
+
selected = matches.slice(0, limit).reverse();
|
|
133
|
+
hasNewer = navigation !== null;
|
|
134
|
+
} else {
|
|
135
|
+
const matches = await collectForward(
|
|
136
|
+
snapshot.handle,
|
|
137
|
+
snapshot.header,
|
|
138
|
+
navigation.boundaryEnd,
|
|
139
|
+
snapshot.payload.highOffset,
|
|
140
|
+
limit + 1,
|
|
141
|
+
navigation.boundarySequence + 1,
|
|
142
|
+
filter,
|
|
143
|
+
);
|
|
144
|
+
hasOlder = true;
|
|
145
|
+
hasNewer = matches.length > limit;
|
|
146
|
+
selected = matches.slice(0, limit);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const first = selected[0];
|
|
150
|
+
const last = selected.at(-1);
|
|
151
|
+
return Object.freeze({
|
|
152
|
+
items: Object.freeze(selected.map(({ item }) => structuredClone(item))),
|
|
153
|
+
olderCursor: hasOlder && first
|
|
154
|
+
? boundedNavigationCursor(encodeNavigation(snapshot.payload, "older", first, filter), snapshot.header)
|
|
155
|
+
: null,
|
|
156
|
+
newerCursor: hasNewer && last
|
|
157
|
+
? boundedNavigationCursor(encodeNavigation(snapshot.payload, "newer", last, filter), snapshot.header)
|
|
158
|
+
: null,
|
|
159
|
+
hasOlder,
|
|
160
|
+
hasNewer,
|
|
161
|
+
snapshot: snapshot.snapshotCursor,
|
|
162
|
+
});
|
|
163
|
+
} catch (error) {
|
|
164
|
+
throw translateError(error);
|
|
165
|
+
} finally {
|
|
166
|
+
await snapshot.handle.close().catch(() => undefined);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
private async openSnapshot(cursor: AuditLogCursor | undefined): Promise<SnapshotContext> {
|
|
171
|
+
let handle: FileHandle;
|
|
172
|
+
try {
|
|
173
|
+
handle = await open(this.path, "r");
|
|
174
|
+
} catch (error) {
|
|
175
|
+
throw new AuditLogReaderError(`cannot open audit log: ${this.path}`, { cause: error });
|
|
176
|
+
}
|
|
177
|
+
try {
|
|
178
|
+
const stat = await handle.stat();
|
|
179
|
+
if (!stat.isFile()) throw new AuditLogReaderError("audit-log reader target is not a regular file");
|
|
180
|
+
const header = await readHeader(handle, stat.size);
|
|
181
|
+
let payload: SnapshotPayload;
|
|
182
|
+
let navigation: NavigationPayload | null = null;
|
|
183
|
+
if (cursor !== undefined) {
|
|
184
|
+
const decoded = decodeCursor(cursor, header.effectiveLimits.maxCursorBytes);
|
|
185
|
+
payload = snapshotFrom(decoded);
|
|
186
|
+
navigation = decoded;
|
|
187
|
+
validateSnapshot(payload, header, stat.size);
|
|
188
|
+
if (await IO.digestPrefix(handle, payload.highOffset) !== payload.prefixDigest) {
|
|
189
|
+
throw new AuditLogCursorInvalidError("audit-log content changed before the cursor snapshot boundary");
|
|
190
|
+
}
|
|
191
|
+
await validateHighBoundary(handle, header, payload);
|
|
192
|
+
} else {
|
|
193
|
+
const highOffset = await IO.lastCompleteOffset(handle, stat.size);
|
|
194
|
+
if (highOffset === 0) throw new AuditLogReaderError("audit log has no complete records");
|
|
195
|
+
const high = parsePhysical(
|
|
196
|
+
await IO.readLastPhysical(handle, highOffset, header.effectiveLimits.maxRecordBytes),
|
|
197
|
+
header,
|
|
198
|
+
);
|
|
199
|
+
payload = {
|
|
200
|
+
kind: "snapshot",
|
|
201
|
+
id: identityTag(header.auditLogId),
|
|
202
|
+
generation: header.generation,
|
|
203
|
+
highSequence: high.sequence,
|
|
204
|
+
highOffset,
|
|
205
|
+
prefixDigest: await IO.digestPrefix(handle, highOffset),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
handle,
|
|
210
|
+
header,
|
|
211
|
+
payload,
|
|
212
|
+
snapshotCursor: boundedSnapshotCursor(encodeSnapshot(payload), header),
|
|
213
|
+
navigation,
|
|
214
|
+
};
|
|
215
|
+
} catch (error) {
|
|
216
|
+
await handle.close().catch(() => undefined);
|
|
217
|
+
throw translateError(error);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async function collectBackward(
|
|
223
|
+
handle: FileHandle,
|
|
224
|
+
header: AuditLogHeaderRecord,
|
|
225
|
+
end: number,
|
|
226
|
+
count: number,
|
|
227
|
+
expectedFirstSequence: number,
|
|
228
|
+
filter: TypeFilter,
|
|
229
|
+
): Promise<PhysicalRecord[]> {
|
|
230
|
+
const output: PhysicalRecord[] = [];
|
|
231
|
+
let expected = expectedFirstSequence;
|
|
232
|
+
for await (const physical of IO.backwardLines(handle, end, header.effectiveLimits.maxRecordBytes)) {
|
|
233
|
+
const parsed = parsePhysical(physical, header);
|
|
234
|
+
if (parsed.sequence !== expected--) throw new AuditLogReaderError("audit-log sequence is not physically contiguous");
|
|
235
|
+
if (!filter.provided || filter.types.includes(parsed.item.t as AuditLogRecordType)) output.push(parsed);
|
|
236
|
+
if (output.length >= count) break;
|
|
237
|
+
}
|
|
238
|
+
return output;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async function collectForward(
|
|
242
|
+
handle: FileHandle,
|
|
243
|
+
header: AuditLogHeaderRecord,
|
|
244
|
+
start: number,
|
|
245
|
+
end: number,
|
|
246
|
+
count: number,
|
|
247
|
+
expectedFirstSequence: number,
|
|
248
|
+
filter: TypeFilter,
|
|
249
|
+
): Promise<PhysicalRecord[]> {
|
|
250
|
+
const output: PhysicalRecord[] = [];
|
|
251
|
+
let expected = expectedFirstSequence;
|
|
252
|
+
for await (const physical of IO.forwardLines(handle, start, end, header.effectiveLimits.maxRecordBytes)) {
|
|
253
|
+
const parsed = parsePhysical(physical, header);
|
|
254
|
+
if (parsed.sequence !== expected++) throw new AuditLogReaderError("audit-log sequence is not physically contiguous");
|
|
255
|
+
if (!filter.provided || filter.types.includes(parsed.item.t as AuditLogRecordType)) output.push(parsed);
|
|
256
|
+
if (output.length >= count) break;
|
|
257
|
+
}
|
|
258
|
+
return output;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function parsePhysical(physical: SessionLogPhysicalLine, header: AuditLogHeaderRecord): PhysicalRecord {
|
|
262
|
+
if (physical.bytes.byteLength === 0) throw new AuditLogReaderError("audit log contains an empty record");
|
|
263
|
+
let value: unknown;
|
|
264
|
+
try {
|
|
265
|
+
value = JSON.parse(UTF8.decode(physical.bytes));
|
|
266
|
+
} catch (error) {
|
|
267
|
+
throw new AuditLogReaderError("audit log contains malformed UTF-8 or JSON", { cause: error });
|
|
268
|
+
}
|
|
269
|
+
if (!isRecord(value)) throw new AuditLogReaderError("audit-log record must be an object");
|
|
270
|
+
if (value.v !== 1 || typeof value.t !== "string" || value.t.length === 0
|
|
271
|
+
|| value.auditLogId !== header.auditLogId || value.generation !== header.generation
|
|
272
|
+
|| value.agentSessionId !== header.agentSessionId || !IO.positiveInteger(value.seq)
|
|
273
|
+
|| !Number.isSafeInteger(value.ts)) {
|
|
274
|
+
throw new AuditLogReaderError("audit-log record envelope is invalid or changes identity");
|
|
275
|
+
}
|
|
276
|
+
let item: KnownAuditLogRecord | UnknownAuditLogRecord;
|
|
277
|
+
if (AUDIT_TYPES.has(value.t as AuditLogRecordType)) {
|
|
278
|
+
try {
|
|
279
|
+
validateAuditLogRecord(value, {
|
|
280
|
+
agentSessionId: header.agentSessionId,
|
|
281
|
+
logId: header.auditLogId,
|
|
282
|
+
generation: header.generation,
|
|
283
|
+
});
|
|
284
|
+
} catch (error) {
|
|
285
|
+
throw new AuditLogReaderError(`invalid audit-log record at sequence ${String(value.seq)}`, { cause: error });
|
|
286
|
+
}
|
|
287
|
+
item = value;
|
|
288
|
+
} else {
|
|
289
|
+
try {
|
|
290
|
+
canonicalizeJson(value);
|
|
291
|
+
} catch (error) {
|
|
292
|
+
throw new AuditLogReaderError("unknown audit-log record is not canonical JSON", { cause: error });
|
|
293
|
+
}
|
|
294
|
+
item = {
|
|
295
|
+
v: 1,
|
|
296
|
+
t: value.t,
|
|
297
|
+
auditLogId: header.auditLogId,
|
|
298
|
+
generation: header.generation,
|
|
299
|
+
agentSessionId: header.agentSessionId,
|
|
300
|
+
seq: value.seq as number,
|
|
301
|
+
ts: value.ts as number,
|
|
302
|
+
value: structuredClone(value) as JsonObject,
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
return {
|
|
306
|
+
item,
|
|
307
|
+
sequence: value.seq as number,
|
|
308
|
+
start: physical.start,
|
|
309
|
+
end: physical.end,
|
|
310
|
+
digest: IO.sha256Bytes(physical.bytes),
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function readHeader(handle: FileHandle, fileSize: number): Promise<AuditLogHeaderRecord> {
|
|
315
|
+
if (fileSize === 0) throw new AuditLogReaderError("audit log is empty");
|
|
316
|
+
const physical = await IO.firstPhysical(handle, fileSize);
|
|
317
|
+
if (physical.bytes.byteLength > IO.hardMaxRecordBytes) throw new AuditLogReaderError("audit-log header exceeds safety ceiling");
|
|
318
|
+
let value: unknown;
|
|
319
|
+
try {
|
|
320
|
+
value = JSON.parse(UTF8.decode(physical.bytes));
|
|
321
|
+
validateAuditLogRecord(value);
|
|
322
|
+
} catch (error) {
|
|
323
|
+
throw new AuditLogReaderError("audit-log header is invalid", { cause: error });
|
|
324
|
+
}
|
|
325
|
+
if (value.t !== "header" || value.seq !== 1) throw new AuditLogReaderError("first audit-log record is not its header");
|
|
326
|
+
return value;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async function validateBoundary(
|
|
330
|
+
handle: FileHandle,
|
|
331
|
+
header: AuditLogHeaderRecord,
|
|
332
|
+
cursor: NavigationPayload,
|
|
333
|
+
): Promise<void> {
|
|
334
|
+
if (cursor.boundaryStart < 0 || cursor.boundaryEnd <= cursor.boundaryStart || cursor.boundaryEnd > cursor.highOffset) {
|
|
335
|
+
throw new AuditLogCursorInvalidError("audit-log cursor boundary offsets are invalid");
|
|
336
|
+
}
|
|
337
|
+
const bytes = await IO.readBytes(handle, cursor.boundaryStart, cursor.boundaryEnd - cursor.boundaryStart);
|
|
338
|
+
if (bytes.byteLength === 0 || bytes.at(-1) !== 0x0a) {
|
|
339
|
+
throw new AuditLogCursorInvalidError("audit-log cursor boundary is no longer a complete record");
|
|
340
|
+
}
|
|
341
|
+
let parsed: PhysicalRecord;
|
|
342
|
+
try {
|
|
343
|
+
parsed = parsePhysical({
|
|
344
|
+
bytes: bytes.subarray(0, bytes.byteLength - 1),
|
|
345
|
+
start: cursor.boundaryStart,
|
|
346
|
+
end: cursor.boundaryEnd,
|
|
347
|
+
}, header);
|
|
348
|
+
} catch (error) {
|
|
349
|
+
throw new AuditLogCursorInvalidError("audit-log cursor boundary is invalid", { cause: error });
|
|
350
|
+
}
|
|
351
|
+
if (parsed.sequence !== cursor.boundarySequence || parsed.digest !== cursor.boundaryDigest) {
|
|
352
|
+
throw new AuditLogCursorInvalidError("audit-log cursor boundary changed");
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async function validateHighBoundary(
|
|
357
|
+
handle: FileHandle,
|
|
358
|
+
header: AuditLogHeaderRecord,
|
|
359
|
+
cursor: SnapshotPayload,
|
|
360
|
+
): Promise<void> {
|
|
361
|
+
try {
|
|
362
|
+
const physical = await IO.readLastPhysical(handle, cursor.highOffset, header.effectiveLimits.maxRecordBytes);
|
|
363
|
+
const parsed = parsePhysical(physical, header);
|
|
364
|
+
if (parsed.sequence !== cursor.highSequence || physical.end !== cursor.highOffset) throw new Error("changed");
|
|
365
|
+
} catch (error) {
|
|
366
|
+
throw new AuditLogCursorInvalidError("audit-log cursor high-water boundary changed", { cause: error });
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function encodeSnapshot(payload: SnapshotPayload): string {
|
|
371
|
+
return Buffer.from(JSON.stringify([
|
|
372
|
+
CURSOR_VERSION, "as", payload.id, payload.generation, payload.highSequence,
|
|
373
|
+
payload.highOffset, payload.prefixDigest,
|
|
374
|
+
]), "utf8").toString("base64url");
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function encodeNavigation(
|
|
378
|
+
snapshot: SnapshotPayload,
|
|
379
|
+
direction: "older" | "newer",
|
|
380
|
+
boundary: PhysicalRecord,
|
|
381
|
+
filter: TypeFilter,
|
|
382
|
+
): string {
|
|
383
|
+
return Buffer.from(JSON.stringify([
|
|
384
|
+
CURSOR_VERSION, "an", snapshot.id, snapshot.generation, snapshot.highSequence,
|
|
385
|
+
snapshot.highOffset, snapshot.prefixDigest, direction === "older" ? "o" : "n",
|
|
386
|
+
boundary.sequence, boundary.start, boundary.end, boundary.digest,
|
|
387
|
+
filter.provided ? typesMask(filter.types) : null,
|
|
388
|
+
]), "utf8").toString("base64url");
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function decodeCursor(cursor: string, maxBytes: number): NavigationPayload {
|
|
392
|
+
if (typeof cursor !== "string" || cursor.length === 0 || Buffer.byteLength(cursor, "utf8") > maxBytes
|
|
393
|
+
|| !/^[A-Za-z0-9_-]+$/.test(cursor)) {
|
|
394
|
+
throw new AuditLogCursorInvalidError("audit-log cursor is blank, malformed, or oversized");
|
|
395
|
+
}
|
|
396
|
+
let value: unknown;
|
|
397
|
+
try {
|
|
398
|
+
const bytes = Buffer.from(cursor, "base64url");
|
|
399
|
+
if (bytes.toString("base64url") !== cursor) throw new Error("non-canonical base64url");
|
|
400
|
+
value = JSON.parse(bytes.toString("utf8"));
|
|
401
|
+
} catch (error) {
|
|
402
|
+
throw new AuditLogCursorInvalidError("audit-log cursor is malformed", { cause: error });
|
|
403
|
+
}
|
|
404
|
+
if (!Array.isArray(value) || value.length !== 13 || value[0] !== 1 || value[1] !== "an"
|
|
405
|
+
|| !IO.integrityTag(value[2]) || !IO.positiveInteger(value[3]) || !IO.positiveInteger(value[4])
|
|
406
|
+
|| !IO.positiveInteger(value[5]) || !IO.integrityTag(value[6])
|
|
407
|
+
|| (value[7] !== "o" && value[7] !== "n") || !IO.positiveInteger(value[8])
|
|
408
|
+
|| !IO.nonnegativeInteger(value[9]) || !IO.positiveInteger(value[10])
|
|
409
|
+
|| !IO.integrityTag(value[11])) {
|
|
410
|
+
throw new AuditLogCursorInvalidError("audit-log cursor payload is invalid");
|
|
411
|
+
}
|
|
412
|
+
const types = value[12] === null ? [] : typesFromMask(value[12]);
|
|
413
|
+
if (types === null) throw new AuditLogCursorInvalidError("audit-log cursor filter is invalid");
|
|
414
|
+
return {
|
|
415
|
+
kind: "navigation",
|
|
416
|
+
id: value[2],
|
|
417
|
+
generation: value[3] as number,
|
|
418
|
+
highSequence: value[4] as number,
|
|
419
|
+
highOffset: value[5] as number,
|
|
420
|
+
prefixDigest: value[6],
|
|
421
|
+
direction: value[7] === "o" ? "older" : "newer",
|
|
422
|
+
boundarySequence: value[8] as number,
|
|
423
|
+
boundaryStart: value[9] as number,
|
|
424
|
+
boundaryEnd: value[10] as number,
|
|
425
|
+
boundaryDigest: value[11] as string,
|
|
426
|
+
types,
|
|
427
|
+
filterProvided: value[12] !== null,
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function snapshotFrom(payload: NavigationPayload): SnapshotPayload {
|
|
432
|
+
return {
|
|
433
|
+
kind: "snapshot",
|
|
434
|
+
id: payload.id,
|
|
435
|
+
generation: payload.generation,
|
|
436
|
+
highSequence: payload.highSequence,
|
|
437
|
+
highOffset: payload.highOffset,
|
|
438
|
+
prefixDigest: payload.prefixDigest,
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function validateSnapshot(payload: SnapshotPayload, header: AuditLogHeaderRecord, fileSize: number): void {
|
|
443
|
+
if (payload.id !== identityTag(header.auditLogId) || payload.generation !== header.generation) {
|
|
444
|
+
throw new AuditLogCursorInvalidError("audit-log cursor belongs to another log generation");
|
|
445
|
+
}
|
|
446
|
+
if (payload.highOffset > fileSize) throw new AuditLogCursorInvalidError("audit log was truncated after cursor creation");
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function normalizeTypes(input: readonly AuditLogRecordType[] | undefined): TypeFilter {
|
|
450
|
+
if (input === undefined) return Object.freeze({ provided: false, types: Object.freeze([]) });
|
|
451
|
+
const unique = [...new Set(input)].sort();
|
|
452
|
+
for (const type of unique) {
|
|
453
|
+
if (!AUDIT_TYPES.has(type)) throw new AuditLogReaderError(`unknown audit-log record type: ${String(type)}`);
|
|
454
|
+
}
|
|
455
|
+
return Object.freeze({ provided: true, types: Object.freeze(unique) });
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function validatedLimit(value: number | undefined): number {
|
|
459
|
+
const limit = value ?? DEFAULT_LIMIT;
|
|
460
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
|
|
461
|
+
throw new AuditLogReaderError(`limit must be an integer from 1 through ${MAX_LIMIT}`);
|
|
462
|
+
}
|
|
463
|
+
return limit;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function identityTag(value: string): string {
|
|
467
|
+
return IO.sha256Bytes(Buffer.from(value, "utf8"));
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function typesMask(types: readonly AuditLogRecordType[]): number {
|
|
471
|
+
let mask = 0;
|
|
472
|
+
for (const type of types) mask |= 1 << AUDIT_TYPE_ORDER.indexOf(type);
|
|
473
|
+
return mask;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function typesFromMask(value: unknown): AuditLogRecordType[] | null {
|
|
477
|
+
if (!IO.nonnegativeInteger(value) || value >= (1 << AUDIT_TYPE_ORDER.length)) return null;
|
|
478
|
+
return AUDIT_TYPE_ORDER.filter((_, index) => (value & (1 << index)) !== 0).sort();
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function boundedNavigationCursor(value: string, header: AuditLogHeaderRecord): AuditLogCursor {
|
|
482
|
+
if (Buffer.byteLength(value, "utf8") > header.effectiveLimits.maxCursorBytes) {
|
|
483
|
+
throw new AuditLogReaderError("generated audit-log navigation cursor exceeds the engraved limit");
|
|
484
|
+
}
|
|
485
|
+
return value as AuditLogCursor;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function boundedSnapshotCursor(value: string, header: AuditLogHeaderRecord): AuditLogSnapshotCursor {
|
|
489
|
+
if (Buffer.byteLength(value, "utf8") > header.effectiveLimits.maxCursorBytes) {
|
|
490
|
+
throw new AuditLogReaderError("generated audit-log snapshot cursor exceeds the engraved limit");
|
|
491
|
+
}
|
|
492
|
+
return value as AuditLogSnapshotCursor;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function translateError(error: unknown): Error {
|
|
496
|
+
if (error instanceof AuditLogReaderError || error instanceof AuditLogCursorInvalidError) return error;
|
|
497
|
+
if (error instanceof TranscriptCursorInvalidError) {
|
|
498
|
+
return new AuditLogCursorInvalidError(error.message, { cause: error });
|
|
499
|
+
}
|
|
500
|
+
if (error instanceof TranscriptReaderError) return new AuditLogReaderError(error.message, { cause: error });
|
|
501
|
+
return new AuditLogReaderError("cannot read audit log", { cause: error });
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
505
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
506
|
+
}
|