skill-family-studio 0.2.2 → 0.4.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.
@@ -0,0 +1,849 @@
1
+ // @feature STU007
2
+ // @scenario S-012
3
+ // @design design-studio-server-and-governance-v3
4
+
5
+ import { createHash, randomUUID } from 'node:crypto';
6
+ import { mkdir } from 'node:fs/promises';
7
+ import {
8
+ canonicalJson,
9
+ digestDocument,
10
+ verifySessionTraceBundleSeal,
11
+ } from 'skill-family-contracts';
12
+ import {
13
+ STATE_GENESIS_DIGEST,
14
+ appendEvent,
15
+ closeStateStore,
16
+ openStateStore,
17
+ readEvents,
18
+ redactUrlCredentials,
19
+ verifyStateStore,
20
+ writeSnapshot,
21
+ } from 'skill-family-harness-node';
22
+
23
+ export const MIN_RETENTION_DAYS = 180;
24
+ const MS_PER_DAY = 86_400_000;
25
+ const HEX64_RE = /^[0-9a-f]{64}$/;
26
+ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
27
+ const SENSITIVE_KEY_RE =
28
+ /^(?:password|passwd|secret|token|cookie|credential|credentials|authorization|auth[-_]?token|api[-_]?key|access[-_]?token|refresh[-_]?token|client[-_]?secret|private[-_]?key)$/i;
29
+
30
+ const PEM_BLOCK_RE = /-----BEGIN [A-Z0-9 _-]+-----[\s\S]*?-----END [A-Z0-9 _-]+-----/g;
31
+ const AUTH_HEADER_VALUE_RE = /\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi;
32
+ const BARE_JWT_RE = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g;
33
+ const TOKEN_SHAPED_RE =
34
+ /\b(?:sk-[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{20,}|(?:AKIA|ASIA)[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{35}|npm_[A-Za-z0-9]{36}|xox[baprs]-[A-Za-z0-9-]{12,})\b/g;
35
+ const URL_WITH_USERINFO_RE = /\bhttps?:\/\/[^\s/"'@]+:[^\s/"'@]*@[^\s"'<>]+/gi;
36
+ const VOLUMES_SPACE_PATH_RE = new RegExp(
37
+ '\\/' +
38
+ ['Vol', 'umes'].join('') +
39
+ '\\/(?!\\[REDACTED)[^/\\s"\'`<>]+(?:\\s[^/\\s"\'`<>-]+)*(?:\\/[^\\s"\'`<>]*)?',
40
+ 'g',
41
+ );
42
+ const POSIX_HOME_PATH_RE = new RegExp(
43
+ '(?:\\/' + ['Us', 'ers'].join('') + '|\\/home|\\/' + ['Vol', 'umes'].join('') + ')\\/(?!\\[REDACTED)[^\\s"\'`<>]+',
44
+ 'g',
45
+ );
46
+ const WIN_HOME_PATH_RE = /[A-Za-z]:\\Users\\(?!\[REDACTED)[^\s"'`<>]+/g;
47
+ const EMAIL_RE = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
48
+ const CN_MOBILE_RE = /(?<![0-9A-Za-z])1[3-9]\d{9}(?![0-9A-Za-z])/g;
49
+ const CN_ID_CARD_RE = /(?<![0-9A-Za-z])\d{17}[\dXx](?![0-9A-Za-z])/g;
50
+
51
+ const AUDIT_SNAPSHOT_INITIAL = Object.freeze({
52
+ count: 0,
53
+ headDigest: STATE_GENESIS_DIGEST,
54
+ });
55
+
56
+ function reduceAuditSnapshot(acc, rec) {
57
+ return {
58
+ count: Number(acc?.count || 0) + 1,
59
+ headDigest: rec.recordDigest,
60
+ };
61
+ }
62
+
63
+ const AUDIT_EVENT_SCHEMAS = Object.freeze({
64
+ 'compliance.audit': {
65
+ 1: {
66
+ type: 'object',
67
+ properties: {
68
+ occurredAt: { type: 'string' },
69
+ tenantId: { type: 'string' },
70
+ actorId: { type: 'string' },
71
+ action: { type: 'string' },
72
+ target: { type: 'string' },
73
+ decision: { type: 'string' },
74
+ category: { type: 'string' },
75
+ detailsJson: { type: 'string' },
76
+ },
77
+ required: [
78
+ 'occurredAt',
79
+ 'tenantId',
80
+ 'actorId',
81
+ 'action',
82
+ 'target',
83
+ 'decision',
84
+ 'category',
85
+ 'detailsJson',
86
+ ],
87
+ additionalProperties: false,
88
+ },
89
+ },
90
+ });
91
+
92
+ function complianceError(code, message) {
93
+ const err = new Error(message);
94
+ err.code = code;
95
+ return err;
96
+ }
97
+
98
+ export function assertValidRetentionDays(retentionDays, { enforceDengbaoFloor = true } = {}) {
99
+ if (!Number.isSafeInteger(retentionDays) || retentionDays < 1) {
100
+ throw complianceError(
101
+ 'INVALID_RETENTION_DAYS',
102
+ `审计留存周期必须为正整数天数(当前配置:${String(retentionDays)})。`,
103
+ );
104
+ }
105
+ if (enforceDengbaoFloor && retentionDays < MIN_RETENTION_DAYS) {
106
+ throw complianceError(
107
+ 'RETENTION_POLICY_BELOW_DENGBAO_FLOOR',
108
+ `等保三级审计留存周期不得少于 ${MIN_RETENTION_DAYS} 天(当前配置:${String(retentionDays)})。`,
109
+ );
110
+ }
111
+ return retentionDays;
112
+ }
113
+
114
+ function scrubSingleString(raw, redactPii) {
115
+ const str = String(raw);
116
+ if (HEX64_RE.test(str)) return str;
117
+ let out = str;
118
+ out = out.replace(PEM_BLOCK_RE, '[REDACTED_CREDENTIAL]');
119
+ out = out.replace(URL_WITH_USERINFO_RE, match => redactUrlCredentials(match));
120
+ out = out.replace(AUTH_HEADER_VALUE_RE, '[REDACTED_CREDENTIAL]');
121
+ out = out.replace(BARE_JWT_RE, '[REDACTED_CREDENTIAL]');
122
+ out = out.replace(TOKEN_SHAPED_RE, '[REDACTED_CREDENTIAL]');
123
+ out = out.replace(VOLUMES_SPACE_PATH_RE, '[REDACTED_PATH]');
124
+ out = out.replace(POSIX_HOME_PATH_RE, '[REDACTED_PATH]');
125
+ out = out.replace(WIN_HOME_PATH_RE, '[REDACTED_PATH]');
126
+ if (redactPii) {
127
+ out = out.replace(EMAIL_RE, '[REDACTED_EMAIL]');
128
+ out = out.replace(CN_ID_CARD_RE, '[REDACTED_ID_NUMBER]');
129
+ out = out.replace(CN_MOBILE_RE, '[REDACTED_PHONE]');
130
+ }
131
+ return out;
132
+ }
133
+
134
+ export function redactCompliancePayload(value, { redactPii = true, depth = 0 } = {}) {
135
+ if (depth > 24) return '[TRUNCATED_DEPTH]';
136
+ if (value === null || value === undefined) return value;
137
+ if (typeof value === 'string') return scrubSingleString(value, redactPii);
138
+ if (typeof value === 'number' || typeof value === 'boolean') return value;
139
+ if (Array.isArray(value)) {
140
+ return value.map(item => redactCompliancePayload(item, { redactPii, depth: depth + 1 }));
141
+ }
142
+ if (typeof value === 'object') {
143
+ const clean = {};
144
+ for (const [k, v] of Object.entries(value)) {
145
+ if (UNSAFE_KEYS.has(k)) continue;
146
+ if (SENSITIVE_KEY_RE.test(k)) {
147
+ clean[k] = '[REDACTED_CREDENTIAL]';
148
+ } else {
149
+ clean[k] = redactCompliancePayload(v, { redactPii, depth: depth + 1 });
150
+ }
151
+ }
152
+ return clean;
153
+ }
154
+ return String(value);
155
+ }
156
+
157
+ function deriveHexId(seed, hexChars) {
158
+ return createHash('sha256').update(String(seed), 'utf8').digest('hex').slice(0, hexChars);
159
+ }
160
+
161
+ function isoToUnixNanoString(isoValue, fallbackIso) {
162
+ const ms = Date.parse(String(isoValue || fallbackIso || ''));
163
+ const safeMs = Number.isFinite(ms) ? Math.max(0, Math.trunc(ms)) : 0;
164
+ return (BigInt(safeMs) * 1_000_000n).toString();
165
+ }
166
+
167
+ function toOtelAttributes(attrMap) {
168
+ const attrs = [];
169
+ for (const [key, rawVal] of Object.entries(attrMap)) {
170
+ if (rawVal === undefined || rawVal === null) continue;
171
+ if (typeof rawVal === 'boolean') {
172
+ attrs.push({ key, value: { boolValue: rawVal } });
173
+ } else if (typeof rawVal === 'number' && Number.isFinite(rawVal)) {
174
+ if (Number.isSafeInteger(rawVal)) {
175
+ attrs.push({ key, value: { intValue: String(rawVal) } });
176
+ } else {
177
+ attrs.push({ key, value: { doubleValue: rawVal } });
178
+ }
179
+ } else {
180
+ attrs.push({ key, value: { stringValue: scrubSingleString(String(rawVal), true) } });
181
+ }
182
+ }
183
+ return attrs;
184
+ }
185
+
186
+ export function exportStbToOtelSpans(
187
+ stbBundle,
188
+ { serviceName = 'skill-family-studio-collector', tenantId = 'default' } = {},
189
+ ) {
190
+ const sealCheck = verifySessionTraceBundleSeal(stbBundle);
191
+ if (!sealCheck.valid) {
192
+ throw complianceError(
193
+ 'STB_SEAL_INVALID',
194
+ `SessionTraceBundle 封存校验未通过,拒绝导出 OTel 遥测:${sealCheck.errorCode || 'INVALID_SEAL'}`,
195
+ );
196
+ }
197
+ const bundleDigest = sealCheck.bundleDigestSha256 || stbBundle?.seal?.bundleDigestSha256;
198
+ const traceId = bundleDigest.slice(0, 32);
199
+ const rootSpanId = deriveHexId(`${bundleDigest}:root`, 16);
200
+ const createdIso = stbBundle.createdAt || stbBundle?.seal?.sealedAt || '1970-01-01T00:00:00.000Z';
201
+ const sealedIso = stbBundle?.seal?.sealedAt || createdIso;
202
+
203
+ const spans = [];
204
+ const sessions = Array.isArray(stbBundle.sessions) ? stbBundle.sessions : [];
205
+ const toolCalls = Array.isArray(stbBundle.toolCalls) ? stbBundle.toolCalls : [];
206
+ const sandboxEvents = Array.isArray(stbBundle.sandboxEvents) ? stbBundle.sandboxEvents : [];
207
+
208
+ let totalInputTokens = 0;
209
+ let totalOutputTokens = 0;
210
+ for (const s of sessions) {
211
+ for (const t of s.turns || []) {
212
+ totalInputTokens += Number(t.inputTokens || 0) + Number(t.cacheReadTokens || 0);
213
+ totalOutputTokens += Number(t.outputTokens || 0);
214
+ }
215
+ }
216
+
217
+ const hasFailure =
218
+ sandboxEvents.length > 0 ||
219
+ toolCalls.some(tc => tc.status === 'failed' || (typeof tc.exitCode === 'number' && tc.exitCode !== 0)) ||
220
+ sessions.some(s => s.termination?.reason && s.termination.reason !== 'completed');
221
+
222
+ const rootSpanEvents = sandboxEvents.map((ev, idx) => ({
223
+ name: 'stb.sandbox_event',
224
+ timeUnixNano: isoToUnixNanoString(ev?.timestamp || sealedIso, createdIso),
225
+ attributes: toOtelAttributes({
226
+ 'skill_family.sandbox_event_index': idx,
227
+ 'skill_family.mechanism': ev?.mechanism || 'unknown',
228
+ 'skill_family.action': ev?.action || 'unknown',
229
+ 'skill_family.outcome': ev?.outcome || 'blocked',
230
+ 'skill_family.target': redactCompliancePayload(ev?.sanitizedTarget || ev?.target || ''),
231
+ }),
232
+ }));
233
+
234
+ spans.push({
235
+ traceId,
236
+ spanId: rootSpanId,
237
+ parentSpanId: '',
238
+ name: `stb.bundle:${scrubSingleString(stbBundle.subject?.id || stbBundle.bundleId, true)}`,
239
+ kind: 1,
240
+ startTimeUnixNano: isoToUnixNanoString(createdIso, createdIso),
241
+ endTimeUnixNano: isoToUnixNanoString(sealedIso, createdIso),
242
+ attributes: toOtelAttributes({
243
+ 'skill_family.tenant_id': tenantId,
244
+ 'skill_family.bundle_id': stbBundle.bundleId,
245
+ 'skill_family.bundle_digest_sha256': bundleDigest,
246
+ 'skill_family.subject_id': stbBundle.subject?.id || 'unknown',
247
+ 'skill_family.subject_version': stbBundle.subject?.version || '0.0.0',
248
+ 'skill_family.session_count': sessions.length,
249
+ 'skill_family.tool_call_count': toolCalls.length,
250
+ 'skill_family.sandbox_event_count': sandboxEvents.length,
251
+ 'gen_ai.usage.input_tokens': totalInputTokens,
252
+ 'gen_ai.usage.output_tokens': totalOutputTokens,
253
+ }),
254
+ events: rootSpanEvents,
255
+ status: { code: hasFailure ? 2 : 1 },
256
+ });
257
+
258
+ const sessionSpanMap = new Map();
259
+ for (const sess of sessions) {
260
+ if (sess?.sessionId) {
261
+ sessionSpanMap.set(sess.sessionId, deriveHexId(`${bundleDigest}:session:${sess.sessionId}`, 16));
262
+ }
263
+ }
264
+
265
+ for (const sess of sessions) {
266
+ const sessSpanId =
267
+ sessionSpanMap.get(sess.sessionId) || deriveHexId(`${bundleDigest}:session:${sess.sessionId}`, 16);
268
+ const parentSpanId =
269
+ sess.parentSessionId && sessionSpanMap.has(sess.parentSessionId)
270
+ ? sessionSpanMap.get(sess.parentSessionId)
271
+ : rootSpanId;
272
+ const sessStart = sess.osProcess?.startedAt || sess.turns?.[0]?.timestamp || createdIso;
273
+ const sessEnd = sess.osProcess?.finishedAt || sealedIso;
274
+ spans.push({
275
+ traceId,
276
+ spanId: sessSpanId,
277
+ parentSpanId,
278
+ name: `stb.session:${scrubSingleString(sess.role || 'agent', true)}`,
279
+ kind: 1,
280
+ startTimeUnixNano: isoToUnixNanoString(sessStart, createdIso),
281
+ endTimeUnixNano: isoToUnixNanoString(sessEnd, sessStart),
282
+ attributes: toOtelAttributes({
283
+ 'skill_family.session_id': sess.sessionId,
284
+ 'skill_family.role': sess.role || 'worker',
285
+ 'skill_family.host_id': sess.host?.id || 'unknown',
286
+ 'skill_family.host_boundary': sess.host?.boundary || 'unknown',
287
+ 'gen_ai.system': sess.model?.provider || 'unknown',
288
+ 'gen_ai.request.model': sess.model?.id || 'unknown',
289
+ 'skill_family.termination_reason': sess.termination?.reason || 'unknown',
290
+ }),
291
+ status: { code: sess.termination?.reason === 'completed' ? 1 : 2 },
292
+ });
293
+
294
+ for (const turn of sess.turns || []) {
295
+ const turnSpanId = deriveHexId(`${bundleDigest}:turn:${sess.sessionId}:${turn.turnIndex}`, 16);
296
+ const turnTs = turn.timestamp || sessStart;
297
+ spans.push({
298
+ traceId,
299
+ spanId: turnSpanId,
300
+ parentSpanId: sessSpanId,
301
+ name: `stb.turn:${turn.turnIndex}`,
302
+ kind: 1,
303
+ startTimeUnixNano: isoToUnixNanoString(turnTs, sessStart),
304
+ endTimeUnixNano: isoToUnixNanoString(turnTs, sessStart),
305
+ attributes: toOtelAttributes({
306
+ 'skill_family.turn_index': turn.turnIndex,
307
+ 'gen_ai.usage.input_tokens': Number(turn.inputTokens || 0),
308
+ 'gen_ai.usage.cache_read_tokens': Number(turn.cacheReadTokens || 0),
309
+ 'gen_ai.usage.output_tokens': Number(turn.outputTokens || 0),
310
+ 'skill_family.window_ratio_bp': Number(turn.windowRatioBp || 0),
311
+ }),
312
+ status: { code: 1 },
313
+ });
314
+ }
315
+ }
316
+
317
+ for (const tc of toolCalls) {
318
+ const tcSpanId = deriveHexId(`${bundleDigest}:tool:${tc.callId}`, 16);
319
+ const parentSpanId = sessionSpanMap.get(tc.sessionId) || rootSpanId;
320
+ const tcStart = tc.startedAt || createdIso;
321
+ const tcEnd = tc.finishedAt || tcStart;
322
+ const failed = tc.status === 'failed' || (typeof tc.exitCode === 'number' && tc.exitCode !== 0);
323
+ spans.push({
324
+ traceId,
325
+ spanId: tcSpanId,
326
+ parentSpanId,
327
+ name: `stb.tool_call:${scrubSingleString(tc.toolName || 'tool', true)}`,
328
+ kind: 3,
329
+ startTimeUnixNano: isoToUnixNanoString(tcStart, createdIso),
330
+ endTimeUnixNano: isoToUnixNanoString(tcEnd, tcStart),
331
+ attributes: toOtelAttributes({
332
+ 'skill_family.call_id': tc.callId,
333
+ 'skill_family.tool_category': tc.category || 'unknown',
334
+ 'skill_family.target': redactCompliancePayload(tc.sanitizedCommandOrTarget || ''),
335
+ 'skill_family.exit_code': typeof tc.exitCode === 'number' ? tc.exitCode : -1,
336
+ 'skill_family.args_sha256': tc.argsSha256 || '',
337
+ }),
338
+ status: { code: failed ? 2 : 1 },
339
+ });
340
+ }
341
+
342
+ return {
343
+ schemaUrl: 'https://opentelemetry.io/schemas/1.24.0',
344
+ traceId,
345
+ bundleDigestSha256: bundleDigest,
346
+ spanCount: spans.length,
347
+ resourceSpans: [
348
+ {
349
+ resource: {
350
+ attributes: toOtelAttributes({
351
+ 'service.name': serviceName,
352
+ 'skill_family.tenant_id': tenantId,
353
+ 'telemetry.sdk.language': 'nodejs',
354
+ }),
355
+ },
356
+ scopeSpans: [
357
+ {
358
+ scope: {
359
+ name: 'skill-family-studio.otel-compliance',
360
+ version: '0.3.0',
361
+ },
362
+ spans,
363
+ },
364
+ ],
365
+ },
366
+ ],
367
+ };
368
+ }
369
+
370
+ export function exportAuditEventsToSiemNdjson(
371
+ records,
372
+ { tenantId = null, serviceName = 'skill-family-studio-collector' } = {},
373
+ ) {
374
+ if (!Array.isArray(records) || records.length === 0) return '';
375
+ const lines = [];
376
+ for (const rec of records) {
377
+ const payload = rec?.payload || {};
378
+ if (tenantId && payload.tenantId !== tenantId) continue;
379
+ let parsedDetails = {};
380
+ if (typeof payload.detailsJson === 'string' && payload.detailsJson.trim()) {
381
+ try {
382
+ parsedDetails = JSON.parse(payload.detailsJson);
383
+ } catch {
384
+ parsedDetails = { raw: payload.detailsJson };
385
+ }
386
+ } else if (rec?.details && typeof rec.details === 'object') {
387
+ parsedDetails = rec.details;
388
+ }
389
+ const siemEvent = {
390
+ schemaVersion: 1,
391
+ kind: 'skill-family.siem-audit-event',
392
+ service: scrubSingleString(serviceName, true),
393
+ timestamp: payload.occurredAt || rec.occurredAt || '1970-01-01T00:00:00.000Z',
394
+ sequence: rec.sequence,
395
+ eventId: rec.eventId,
396
+ eventType: rec.eventType,
397
+ tenantId: payload.tenantId || rec.tenantId || 'default',
398
+ actorId: redactCompliancePayload(payload.actorId || rec.actorId || 'anonymous'),
399
+ action: redactCompliancePayload(payload.action || rec.action || 'unknown'),
400
+ target: redactCompliancePayload(payload.target || rec.target || 'unknown'),
401
+ decision: payload.decision || rec.decision || 'UNKNOWN',
402
+ category: payload.category || rec.category || 'governance',
403
+ prevDigest: rec.prevDigest,
404
+ recordDigest: rec.recordDigest,
405
+ details: redactCompliancePayload(parsedDetails),
406
+ };
407
+ lines.push(JSON.stringify(siemEvent));
408
+ }
409
+ return lines.length > 0 ? `${lines.join('\n')}\n` : '';
410
+ }
411
+
412
+ export function evaluateRetentionPurgeEligibility({
413
+ occurredAt,
414
+ nowIso = new Date().toISOString(),
415
+ retentionDays = MIN_RETENTION_DAYS,
416
+ enforceDengbaoFloor = true,
417
+ } = {}) {
418
+ assertValidRetentionDays(retentionDays, { enforceDengbaoFloor });
419
+ if (!enforceDengbaoFloor) {
420
+ return {
421
+ purgeAllowed: true,
422
+ retentionDays,
423
+ ageDays: 0,
424
+ remainingDays: 0,
425
+ reason: 'RETENTION_LOCK_NOT_ENFORCED_IN_LIGHT_PROFILE',
426
+ };
427
+ }
428
+ const occurredMs = Date.parse(String(occurredAt || ''));
429
+ const nowMs = Date.parse(String(nowIso || ''));
430
+ if (!Number.isFinite(occurredMs) || !Number.isFinite(nowMs)) {
431
+ return {
432
+ purgeAllowed: false,
433
+ retentionDays,
434
+ ageDays: 0,
435
+ remainingDays: retentionDays,
436
+ reason: 'INVALID_TIMESTAMP_FAIL_CLOSED',
437
+ };
438
+ }
439
+ const requiredMs = retentionDays * MS_PER_DAY;
440
+ const elapsedMs = nowMs - occurredMs;
441
+ if (elapsedMs < requiredMs) {
442
+ const remainingDays = Math.max(1, Math.ceil((requiredMs - Math.max(0, elapsedMs)) / MS_PER_DAY));
443
+ return {
444
+ purgeAllowed: false,
445
+ retentionDays,
446
+ ageDays: Math.max(0, Math.floor(elapsedMs / MS_PER_DAY)),
447
+ remainingDays,
448
+ reason: 'WITHIN_MANDATORY_RETENTION_WINDOW',
449
+ };
450
+ }
451
+ return {
452
+ purgeAllowed: true,
453
+ retentionDays,
454
+ ageDays: Math.floor(elapsedMs / MS_PER_DAY),
455
+ remainingDays: 0,
456
+ reason: 'RETENTION_WINDOW_SATISFIED',
457
+ };
458
+ }
459
+
460
+ export class ComplianceAuditLedger {
461
+ #stateRoot;
462
+ #retentionDays;
463
+ #enforceRetentionFloor;
464
+ #owner;
465
+ #highWaterCount = 0;
466
+ #queue = Promise.resolve();
467
+
468
+ constructor({
469
+ stateRoot,
470
+ retentionDays = MIN_RETENTION_DAYS,
471
+ enforceRetentionFloor = true,
472
+ owner = `studio-compliance-ledger-${process.pid}`,
473
+ } = {}) {
474
+ if (typeof stateRoot !== 'string' || !stateRoot.trim()) {
475
+ throw complianceError('INVALID_LEDGER_ROOT', 'ComplianceAuditLedger 需要非空的 stateRoot 目录路径。');
476
+ }
477
+ this.#stateRoot = stateRoot;
478
+ this.#enforceRetentionFloor = Boolean(enforceRetentionFloor);
479
+ this.#retentionDays = assertValidRetentionDays(retentionDays, {
480
+ enforceDengbaoFloor: this.#enforceRetentionFloor,
481
+ });
482
+ this.#owner = owner;
483
+ }
484
+
485
+ get retentionDays() {
486
+ return this.#retentionDays;
487
+ }
488
+
489
+ get enforceRetentionFloor() {
490
+ return this.#enforceRetentionFloor;
491
+ }
492
+
493
+ get stateRoot() {
494
+ return this.#stateRoot;
495
+ }
496
+
497
+ #enqueue(fn) {
498
+ const next = this.#queue.then(fn, fn);
499
+ this.#queue = next.catch(() => {});
500
+ return next;
501
+ }
502
+
503
+ async appendAuditRecord({
504
+ eventId = null,
505
+ idempotencyKey = null,
506
+ tenantId = 'default',
507
+ actorId = 'anonymous',
508
+ action,
509
+ target = '*',
510
+ decision,
511
+ category = 'governance',
512
+ occurredAt = new Date().toISOString(),
513
+ details = {},
514
+ } = {}) {
515
+ if (typeof action !== 'string' || !action.trim()) {
516
+ throw complianceError('INVALID_AUDIT_ACTION', '审计记录必须包含非空 action。');
517
+ }
518
+ if (typeof decision !== 'string' || !decision.trim()) {
519
+ throw complianceError('INVALID_AUDIT_DECISION', '审计记录必须包含非空 decision。');
520
+ }
521
+ const sanitizedDetails = redactCompliancePayload(details ?? {});
522
+ const safePayload = {
523
+ occurredAt: String(occurredAt),
524
+ tenantId: scrubSingleString(String(tenantId || 'default'), true),
525
+ actorId: scrubSingleString(String(actorId || 'anonymous'), true),
526
+ action: scrubSingleString(action.trim(), true),
527
+ target: scrubSingleString(String(target || '*'), true),
528
+ decision: scrubSingleString(decision.trim(), true),
529
+ category: scrubSingleString(String(category || 'governance'), true),
530
+ detailsJson: canonicalJson(sanitizedDetails),
531
+ };
532
+ const effectiveEventId = eventId
533
+ ? String(eventId)
534
+ : idempotencyKey
535
+ ? `aud-${deriveHexId(idempotencyKey, 24)}`
536
+ : `aud-${randomUUID()}`;
537
+ const effectiveIdempotencyKey = String(idempotencyKey || effectiveEventId);
538
+
539
+ return this.#enqueue(async () => {
540
+ await mkdir(this.#stateRoot, { recursive: true });
541
+ const store = await openStateStore(this.#stateRoot, {
542
+ owner: this.#owner,
543
+ payloadSchemas: AUDIT_EVENT_SCHEMAS,
544
+ });
545
+ try {
546
+ if (idempotencyKey) {
547
+ const prior = await readEvents(store, { afterSequence: 0 });
548
+ this.#highWaterCount = Math.max(this.#highWaterCount, prior.length);
549
+ const matched = prior.find(r => r.idempotencyKey === effectiveIdempotencyKey);
550
+ if (matched) {
551
+ let parsedPriorDetails = sanitizedDetails;
552
+ try {
553
+ parsedPriorDetails = JSON.parse(matched.payload?.detailsJson || '{}');
554
+ } catch {}
555
+ return {
556
+ appended: false,
557
+ sequence: matched.sequence,
558
+ eventId: matched.eventId,
559
+ prevDigest: matched.prevDigest,
560
+ recordDigest: matched.recordDigest,
561
+ occurredAt: matched.payload?.occurredAt || safePayload.occurredAt,
562
+ tenantId: matched.payload?.tenantId || safePayload.tenantId,
563
+ actorId: matched.payload?.actorId || safePayload.actorId,
564
+ action: matched.payload?.action || safePayload.action,
565
+ target: matched.payload?.target || safePayload.target,
566
+ decision: matched.payload?.decision || safePayload.decision,
567
+ category: matched.payload?.category || safePayload.category,
568
+ details: parsedPriorDetails,
569
+ };
570
+ }
571
+ }
572
+
573
+ const res = await appendEvent(store, {
574
+ eventId: effectiveEventId,
575
+ idempotencyKey: effectiveIdempotencyKey,
576
+ eventType: 'compliance.audit',
577
+ payloadSchemaVersion: 1,
578
+ producer: 'skill-family-studio.compliance-ledger',
579
+ payload: safePayload,
580
+ });
581
+ const allEvents = await readEvents(store, { afterSequence: 0 });
582
+ const snapState = allEvents.reduce(reduceAuditSnapshot, AUDIT_SNAPSHOT_INITIAL);
583
+ await writeSnapshot(store, snapState, {
584
+ reducer: reduceAuditSnapshot,
585
+ initial: AUDIT_SNAPSHOT_INITIAL,
586
+ });
587
+ this.#highWaterCount = Math.max(this.#highWaterCount, allEvents.length);
588
+
589
+ return {
590
+ appended: Boolean(res.appended),
591
+ sequence: res.record.sequence,
592
+ eventId: res.record.eventId,
593
+ prevDigest: res.record.prevDigest,
594
+ recordDigest: res.record.recordDigest,
595
+ occurredAt: safePayload.occurredAt,
596
+ tenantId: safePayload.tenantId,
597
+ actorId: safePayload.actorId,
598
+ action: safePayload.action,
599
+ target: safePayload.target,
600
+ decision: safePayload.decision,
601
+ category: safePayload.category,
602
+ details: sanitizedDetails,
603
+ };
604
+ } finally {
605
+ await closeStateStore(store);
606
+ }
607
+ });
608
+ }
609
+
610
+ async readRawEnvelopes({ afterSequence = 0 } = {}) {
611
+ return this.#enqueue(async () => {
612
+ await mkdir(this.#stateRoot, { recursive: true });
613
+ const store = await openStateStore(this.#stateRoot, {
614
+ owner: this.#owner,
615
+ payloadSchemas: AUDIT_EVENT_SCHEMAS,
616
+ });
617
+ try {
618
+ return await readEvents(store, { afterSequence });
619
+ } finally {
620
+ await closeStateStore(store);
621
+ }
622
+ });
623
+ }
624
+
625
+ async verifyRetentionIntegrity({ nowIso = new Date().toISOString() } = {}) {
626
+ return this.#enqueue(async () => {
627
+ try {
628
+ await mkdir(this.#stateRoot, { recursive: true });
629
+ const store = await openStateStore(this.#stateRoot, {
630
+ owner: this.#owner,
631
+ payloadSchemas: AUDIT_EVENT_SCHEMAS,
632
+ });
633
+ try {
634
+ const storeCheck = await verifyStateStore(store, {
635
+ reducer: reduceAuditSnapshot,
636
+ initial: AUDIT_SNAPSHOT_INITIAL,
637
+ });
638
+ if (!storeCheck.valid) {
639
+ return {
640
+ valid: false,
641
+ errorCode: 'AUDIT_HASH_CHAIN_BROKEN',
642
+ snapshotStatus: storeCheck.snapshotStatus,
643
+ retentionDays: this.#retentionDays,
644
+ recordCount: storeCheck.eventCount ?? 0,
645
+ };
646
+ }
647
+
648
+ const records = await readEvents(store, { afterSequence: 0 });
649
+ if (records.length < this.#highWaterCount) {
650
+ return {
651
+ valid: false,
652
+ errorCode: 'AUDIT_TAIL_TRUNCATED',
653
+ retentionDays: this.#retentionDays,
654
+ recordCount: records.length,
655
+ expectedMinCount: this.#highWaterCount,
656
+ };
657
+ }
658
+ if (records.length > 0 && storeCheck.snapshotStatus !== 'verified') {
659
+ return {
660
+ valid: false,
661
+ errorCode: 'AUDIT_SNAPSHOT_ANCHOR_MISSING',
662
+ snapshotStatus: storeCheck.snapshotStatus,
663
+ retentionDays: this.#retentionDays,
664
+ recordCount: records.length,
665
+ };
666
+ }
667
+ this.#highWaterCount = Math.max(this.#highWaterCount, records.length);
668
+
669
+ let expectedPrev = STATE_GENESIS_DIGEST;
670
+ let expectedSeq = 1;
671
+ let purgeProtectedCount = 0;
672
+ let earliestOccurredAt = null;
673
+ let latestOccurredAt = null;
674
+
675
+ for (const rec of records) {
676
+ if (
677
+ rec.sequence !== expectedSeq ||
678
+ rec.prevDigest !== expectedPrev ||
679
+ typeof rec.recordDigest !== 'string' ||
680
+ !HEX64_RE.test(rec.recordDigest)
681
+ ) {
682
+ return {
683
+ valid: false,
684
+ errorCode: 'AUDIT_HASH_CHAIN_BROKEN',
685
+ retentionDays: this.#retentionDays,
686
+ recordCount: records.length,
687
+ brokenAtSequence: rec.sequence ?? expectedSeq,
688
+ };
689
+ }
690
+ const occurredAt = rec.payload?.occurredAt || null;
691
+ if (occurredAt) {
692
+ if (!earliestOccurredAt || occurredAt < earliestOccurredAt) earliestOccurredAt = occurredAt;
693
+ if (!latestOccurredAt || occurredAt > latestOccurredAt) latestOccurredAt = occurredAt;
694
+ }
695
+ const elig = evaluateRetentionPurgeEligibility({
696
+ occurredAt,
697
+ nowIso,
698
+ retentionDays: this.#retentionDays,
699
+ enforceDengbaoFloor: this.#enforceRetentionFloor,
700
+ });
701
+ if (!elig.purgeAllowed) purgeProtectedCount += 1;
702
+ expectedPrev = rec.recordDigest;
703
+ expectedSeq += 1;
704
+ }
705
+
706
+ return {
707
+ valid: true,
708
+ errorCode: null,
709
+ snapshotStatus: storeCheck.snapshotStatus,
710
+ retentionDays: this.#retentionDays,
711
+ genesisDigest: STATE_GENESIS_DIGEST,
712
+ recordCount: records.length,
713
+ headDigest: expectedPrev,
714
+ earliestOccurredAt,
715
+ latestOccurredAt,
716
+ purgeProtectedCount,
717
+ };
718
+ } finally {
719
+ await closeStateStore(store);
720
+ }
721
+ } catch (err) {
722
+ return {
723
+ valid: false,
724
+ errorCode: 'AUDIT_LEDGER_TAMPERED_OR_UNREADABLE',
725
+ retentionDays: this.#retentionDays,
726
+ detail: redactCompliancePayload(err?.message || String(err)),
727
+ };
728
+ }
729
+ });
730
+ }
731
+
732
+ async assertPurgePermitted({ nowIso = new Date().toISOString() } = {}) {
733
+ const integrity = await this.verifyRetentionIntegrity({ nowIso });
734
+ if (!integrity.valid) {
735
+ throw complianceError(
736
+ integrity.errorCode || 'AUDIT_LEDGER_TAMPERED',
737
+ `审计账本完整性核验未通过(${integrity.errorCode || 'INVALID'}),禁止执行清理。`,
738
+ );
739
+ }
740
+ const records = await this.readRawEnvelopes({ afterSequence: 0 });
741
+ if (!this.#enforceRetentionFloor) {
742
+ return { purgePermitted: true, checkedCount: records.length, retentionLockEnforced: false };
743
+ }
744
+ for (const rec of records) {
745
+ const elig = evaluateRetentionPurgeEligibility({
746
+ occurredAt: rec.payload?.occurredAt,
747
+ nowIso,
748
+ retentionDays: this.#retentionDays,
749
+ enforceDengbaoFloor: true,
750
+ });
751
+ if (!elig.purgeAllowed) {
752
+ throw complianceError(
753
+ 'RETENTION_LOCK_ACTIVE',
754
+ `审计记录 #${rec.sequence}(${rec.eventId})仍在 ${this.#retentionDays} 天强制留存期内(剩余 ${elig.remainingDays} 天),禁止清理。`,
755
+ );
756
+ }
757
+ }
758
+ return { purgePermitted: true, checkedCount: records.length };
759
+ }
760
+ }
761
+
762
+ export function buildDengbaoEvidenceMappingReport({
763
+ tenantId = 'default',
764
+ retentionDays = MIN_RETENTION_DAYS,
765
+ enforceRetentionFloor = true,
766
+ ledgerIntegrity,
767
+ rbacSummary,
768
+ quotaSummary,
769
+ hitlSummary,
770
+ sandboxVerified = true,
771
+ generatedAt = new Date().toISOString(),
772
+ } = {}) {
773
+ assertValidRetentionDays(retentionDays, { enforceDengbaoFloor: false });
774
+ const auditChainValid = Boolean(ledgerIntegrity?.valid === true);
775
+ const retentionFloorSatisfied = Boolean(enforceRetentionFloor && retentionDays >= MIN_RETENTION_DAYS);
776
+ const rbacValid = Boolean(
777
+ rbacSummary?.authRequired !== false &&
778
+ rbacSummary?.zeroPlaintextTokens === true &&
779
+ rbacSummary?.principalCount > 0,
780
+ );
781
+ const quotaValid = Boolean(quotaSummary?.enabled === true && quotaSummary?.enforced !== false);
782
+ const hitlValid = Boolean(hitlSummary?.antiSelfApprovalEnforced === true);
783
+
784
+ const controls = [
785
+ {
786
+ controlId: 'IAM-L3-01',
787
+ domain: '身份鉴别',
788
+ standardRef: 'GB/T 22239-2019 第三级 安全计算环境·身份鉴别',
789
+ satisfied: rbacValid,
790
+ evidenceSummary: rbacValid
791
+ ? `已登记 ${rbacSummary.principalCount} 个预哈希 SHA-256 令牌主体,采用恒定时间比对且零明文凭据落盘。`
792
+ : '当前处于免鉴权个人模式或缺少有效的零明文 SHA-256 令牌身份配置。',
793
+ },
794
+ {
795
+ controlId: 'AC-L3-02',
796
+ domain: '访问控制与双人职责分离',
797
+ standardRef: 'GB/T 22239-2019 第三级 安全计算环境·访问控制',
798
+ satisfied: Boolean(rbacValid && hitlValid),
799
+ evidenceSummary:
800
+ rbacValid && hitlValid
801
+ ? '强制执行多租户边界隔离、最小角色权限矩阵及高副作用操作 HITL 异体双人审批(禁止自批)。'
802
+ : '租户 RBAC 或 HITL 职责分离策略未就绪。',
803
+ },
804
+ {
805
+ controlId: 'AUD-L3-03',
806
+ domain: '安全审计与不少于 180 天防篡改留存',
807
+ standardRef: 'GB/T 22239-2019 第三级 安全计算环境·安全审计',
808
+ satisfied: Boolean(auditChainValid && retentionFloorSatisfied),
809
+ evidenceSummary:
810
+ auditChainValid && retentionFloorSatisfied
811
+ ? `基于 Foundation state-store 创世哈希链与快照锚点留存(策略 ${retentionDays} 天 >= ${MIN_RETENTION_DAYS} 天下限,当前链长 ${ledgerIntegrity.recordCount},头摘要 ${String(ledgerIntegrity.headDigest || '').slice(0, 16)})。`
812
+ : `审计账本完整性或 180 天强制留存锁未就绪(${ledgerIntegrity?.errorCode || 'RETENTION_LOCK_DISABLED'})。`,
813
+ },
814
+ {
815
+ controlId: 'PII-L3-04',
816
+ domain: '剩余信息与个人信息脱敏保护',
817
+ standardRef: 'GB/T 22239-2019 第三级 数据完整性与保密性 / 个人信息保护最小必要原则',
818
+ satisfied: true,
819
+ evidenceSummary:
820
+ '所有入账事件、OTLP Span 与 SIEM 导出均强制剥离内嵌账密 URL、API 密钥、JWT、私钥块、本机个人路径与敏感个人信息。',
821
+ },
822
+ {
823
+ controlId: 'SWB-L3-05',
824
+ domain: '入侵防范、配额熔断与沙箱供应链边界',
825
+ standardRef: 'GB/T 22239-2019 第三级 入侵防范与资源控制',
826
+ satisfied: Boolean(quotaValid && sandboxVerified),
827
+ evidenceSummary:
828
+ quotaValid && sandboxVerified
829
+ ? '已启用 SessionTraceBundle 密码学验封入库、轨迹客观 Token 下限保护、基于 openUsageGuard 的双层熔断及内核级沙箱事件追踪。'
830
+ : '配额超支熔断或沙箱边界校验未启用。',
831
+ },
832
+ ];
833
+
834
+ const reportBody = {
835
+ schemaVersion: 1,
836
+ kind: 'skill-family.dengbao-level3-evidence-mapping',
837
+ generatedAt: String(generatedAt),
838
+ tenantId: scrubSingleString(String(tenantId), true),
839
+ retentionDays,
840
+ minimumRetentionDaysFloor: MIN_RETENTION_DAYS,
841
+ allControlsSatisfied: controls.every(c => c.satisfied),
842
+ controls,
843
+ };
844
+
845
+ return {
846
+ ...reportBody,
847
+ reportDigestSha256: digestDocument(reportBody),
848
+ };
849
+ }