@dailephd/my-centcom 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -5
- package/apps/daemon/dist/artifacts/returnSnapshots.d.ts +12 -0
- package/apps/daemon/dist/artifacts/returnSnapshots.js +41 -0
- package/apps/daemon/dist/bootstrap/app.d.ts +21 -0
- package/apps/daemon/dist/bootstrap/app.js +27 -0
- package/apps/daemon/dist/bootstrap/installLayout.d.ts +81 -0
- package/apps/daemon/dist/bootstrap/installLayout.js +164 -0
- package/apps/daemon/dist/bootstrap/main.d.ts +14 -0
- package/apps/daemon/dist/bootstrap/main.js +141 -0
- package/apps/daemon/dist/bootstrap/operatorConsole.d.ts +75 -0
- package/apps/daemon/dist/bootstrap/operatorConsole.js +293 -0
- package/apps/daemon/dist/bootstrap/privateDataRoot.d.ts +38 -0
- package/apps/daemon/dist/bootstrap/privateDataRoot.js +204 -0
- package/apps/daemon/dist/bootstrap/secureMain.d.ts +118 -0
- package/apps/daemon/dist/bootstrap/secureMain.js +403 -0
- package/apps/daemon/dist/bootstrap/setup.d.ts +93 -0
- package/apps/daemon/dist/bootstrap/setup.js +738 -0
- package/apps/daemon/dist/context/changeProposal.d.ts +97 -0
- package/apps/daemon/dist/context/changeProposal.js +259 -0
- package/apps/daemon/dist/context/gitEvidence.d.ts +88 -0
- package/apps/daemon/dist/context/gitEvidence.js +332 -0
- package/apps/daemon/dist/context/gitObservation.d.ts +30 -0
- package/apps/daemon/dist/context/gitObservation.js +113 -0
- package/apps/daemon/dist/context/projectReadIssuer.d.ts +68 -0
- package/apps/daemon/dist/context/projectReadIssuer.js +158 -0
- package/apps/daemon/dist/context/projectReadService.d.ts +153 -0
- package/apps/daemon/dist/context/projectReadService.js +652 -0
- package/apps/daemon/dist/context/projectViewService.d.ts +85 -0
- package/apps/daemon/dist/context/projectViewService.js +332 -0
- package/apps/daemon/dist/context/proposalRecorder.d.ts +11 -0
- package/apps/daemon/dist/context/proposalRecorder.js +19 -0
- package/apps/daemon/dist/plugins/drivers/codexMcpConfig.d.ts +40 -0
- package/apps/daemon/dist/plugins/drivers/codexMcpConfig.js +73 -0
- package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.d.ts +49 -0
- package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.js +70 -0
- package/apps/daemon/dist/plugins/drivers/fakePluginDriver.d.ts +16 -0
- package/apps/daemon/dist/plugins/drivers/fakePluginDriver.js +115 -0
- package/apps/daemon/dist/plugins/drivers/finiteCliDriver.d.ts +153 -0
- package/apps/daemon/dist/plugins/drivers/finiteCliDriver.js +505 -0
- package/apps/daemon/dist/plugins/registry/operationCatalog.d.ts +23 -0
- package/apps/daemon/dist/plugins/registry/operationCatalog.js +41 -0
- package/apps/daemon/dist/plugins/registry/registryOperationCatalog.d.ts +14 -0
- package/apps/daemon/dist/plugins/registry/registryOperationCatalog.js +29 -0
- package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.d.ts +151 -0
- package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.js +579 -0
- package/apps/daemon/dist/projects/codingAuthority.d.ts +102 -0
- package/apps/daemon/dist/projects/codingAuthority.js +244 -0
- package/apps/daemon/dist/projects/fixtureAuthorization.d.ts +54 -0
- package/apps/daemon/dist/projects/fixtureAuthorization.js +172 -0
- package/apps/daemon/dist/projects/pairedAuthority.d.ts +158 -0
- package/apps/daemon/dist/projects/pairedAuthority.js +273 -0
- package/apps/daemon/dist/projects/trustedCliConsent.d.ts +47 -0
- package/apps/daemon/dist/projects/trustedCliConsent.js +84 -0
- package/apps/daemon/dist/runs/changeApplier.d.ts +59 -0
- package/apps/daemon/dist/runs/changeApplier.js +319 -0
- package/apps/daemon/dist/runs/codingWorkflowService.d.ts +283 -0
- package/apps/daemon/dist/runs/codingWorkflowService.js +785 -0
- package/apps/daemon/dist/runs/durableIntentCoordinator.d.ts +72 -0
- package/apps/daemon/dist/runs/durableIntentCoordinator.js +160 -0
- package/apps/daemon/dist/runs/inMemoryCoordinator.d.ts +55 -0
- package/apps/daemon/dist/runs/inMemoryCoordinator.js +375 -0
- package/apps/daemon/dist/runs/runExecutor.d.ts +154 -0
- package/apps/daemon/dist/runs/runExecutor.js +295 -0
- package/apps/daemon/dist/runs/workflowService.d.ts +185 -0
- package/apps/daemon/dist/runs/workflowService.js +300 -0
- package/apps/daemon/dist/runtime/boundedProcessHost.d.ts +111 -0
- package/apps/daemon/dist/runtime/boundedProcessHost.js +752 -0
- package/apps/daemon/dist/runtime/evidenceRedaction.d.ts +30 -0
- package/apps/daemon/dist/runtime/evidenceRedaction.js +79 -0
- package/apps/daemon/dist/runtime/executionDiagnostics.d.ts +134 -0
- package/apps/daemon/dist/runtime/executionDiagnostics.js +213 -0
- package/apps/daemon/dist/runtime/modelExecutionPolicy.d.ts +22 -0
- package/apps/daemon/dist/runtime/modelExecutionPolicy.js +19 -0
- package/apps/daemon/dist/runtime/mxcExecution.d.ts +12 -0
- package/apps/daemon/dist/runtime/mxcExecution.js +163 -0
- package/apps/daemon/dist/runtime/mxcIntegrity.d.ts +24 -0
- package/apps/daemon/dist/runtime/mxcIntegrity.js +81 -0
- package/apps/daemon/dist/runtime/mxcWorker.d.ts +2 -0
- package/apps/daemon/dist/runtime/mxcWorker.js +45 -0
- package/apps/daemon/dist/runtime/provisionedExecution.d.ts +150 -0
- package/apps/daemon/dist/runtime/provisionedExecution.js +653 -0
- package/apps/daemon/dist/runtime/testExecution.d.ts +76 -0
- package/apps/daemon/dist/runtime/testExecution.js +106 -0
- package/apps/daemon/dist/runtime/testProfiles.d.ts +10 -0
- package/apps/daemon/dist/runtime/testProfiles.js +4 -0
- package/apps/daemon/dist/runtime/trustedAgentStaging.d.ts +89 -0
- package/apps/daemon/dist/runtime/trustedAgentStaging.js +262 -0
- package/apps/daemon/dist/runtime/trustedCaBundle.d.ts +77 -0
- package/apps/daemon/dist/runtime/trustedCaBundle.js +125 -0
- package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.d.ts +166 -0
- package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.js +521 -0
- package/apps/daemon/dist/storage/diagnosticLog.d.ts +63 -0
- package/apps/daemon/dist/storage/diagnosticLog.js +136 -0
- package/apps/daemon/dist/storage/executionTelemetry.d.ts +63 -0
- package/apps/daemon/dist/storage/executionTelemetry.js +247 -0
- package/apps/daemon/dist/storage/protectedSecrets.d.ts +39 -0
- package/apps/daemon/dist/storage/protectedSecrets.js +106 -0
- package/apps/daemon/dist/storage/sqliteLedger.d.ts +786 -0
- package/apps/daemon/dist/storage/sqliteLedger.js +1303 -0
- package/apps/daemon/dist/transports/http/dispatch.d.ts +43 -0
- package/apps/daemon/dist/transports/http/dispatch.js +405 -0
- package/apps/daemon/dist/transports/http/secureRoutes.d.ts +40 -0
- package/apps/daemon/dist/transports/http/secureRoutes.js +332 -0
- package/apps/daemon/dist/transports/http/workflowRoutes.d.ts +41 -0
- package/apps/daemon/dist/transports/http/workflowRoutes.js +473 -0
- package/apps/daemon/dist/transports/mcp/localProjectReadServer.d.ts +182 -0
- package/apps/daemon/dist/transports/mcp/localProjectReadServer.js +221 -0
- package/apps/daemon/dist/transports/native/nativeHost.d.ts +24 -0
- package/apps/daemon/dist/transports/native/nativeHost.js +344 -0
- package/apps/daemon/package.json +24 -0
- package/apps/daemon/src/runtime/benign/referenceEcho.mjs +27 -0
- package/apps/daemon/src/runtime/windows/buildSupervisor.mjs +87 -0
- package/apps/daemon/src/runtime/windows/supervisorMain.cs +676 -0
- package/apps/extension/manifest.secure.json +25 -0
- package/apps/extension/scripts/build.mjs +173 -0
- package/apps/extension/src/background/secureWorker.ts +1595 -0
- package/apps/extension/src/background/serviceWorker.ts +892 -0
- package/apps/extension/src/content/captureSelection.ts +64 -0
- package/apps/extension/src/content/secureInsert.ts +207 -0
- package/apps/extension/src/probe/index.html +41 -0
- package/apps/extension/src/probe/main.ts +201 -0
- package/apps/extension/src/sidepanel/index.html +203 -0
- package/apps/extension/src/sidepanel/main.ts +903 -0
- package/package.json +19 -3
- package/packages/contracts/dist/artifacts.d.ts +66 -0
- package/packages/contracts/dist/artifacts.js +64 -0
- package/packages/contracts/dist/automation.d.ts +540 -0
- package/packages/contracts/dist/automation.js +191 -0
- package/packages/contracts/dist/browser.d.ts +251 -0
- package/packages/contracts/dist/browser.js +131 -0
- package/packages/contracts/dist/context.d.ts +71 -0
- package/packages/contracts/dist/context.js +73 -0
- package/packages/contracts/dist/diagnostics.d.ts +99 -0
- package/packages/contracts/dist/diagnostics.js +284 -0
- package/packages/contracts/dist/effects.d.ts +42 -0
- package/packages/contracts/dist/effects.js +42 -0
- package/packages/contracts/dist/errors.d.ts +75 -0
- package/packages/contracts/dist/errors.js +70 -0
- package/packages/contracts/dist/events.d.ts +50 -0
- package/packages/contracts/dist/events.js +34 -0
- package/packages/contracts/dist/executionDiagnostics.d.ts +212 -0
- package/packages/contracts/dist/executionDiagnostics.js +101 -0
- package/packages/contracts/dist/identity.d.ts +54 -0
- package/packages/contracts/dist/identity.js +40 -0
- package/packages/contracts/dist/index.d.ts +20 -0
- package/packages/contracts/dist/index.js +20 -0
- package/packages/contracts/dist/invocation.d.ts +90 -0
- package/packages/contracts/dist/invocation.js +77 -0
- package/packages/contracts/dist/lifecycle.d.ts +130 -0
- package/packages/contracts/dist/lifecycle.js +135 -0
- package/packages/contracts/dist/plugin.d.ts +214 -0
- package/packages/contracts/dist/plugin.js +117 -0
- package/packages/contracts/dist/projectRead.d.ts +205 -0
- package/packages/contracts/dist/projectRead.js +162 -0
- package/packages/contracts/dist/secure.d.ts +128 -0
- package/packages/contracts/dist/secure.js +99 -0
- package/packages/contracts/package.json +32 -0
- package/packages/contracts/src/artifacts.ts +83 -0
- package/packages/contracts/src/automation.ts +238 -0
- package/packages/contracts/src/browser.ts +164 -0
- package/packages/contracts/src/context.ts +91 -0
- package/packages/contracts/src/diagnostics.ts +318 -0
- package/packages/contracts/src/effects.ts +49 -0
- package/packages/contracts/src/errors.ts +83 -0
- package/packages/contracts/src/events.ts +46 -0
- package/packages/contracts/src/executionDiagnostics.ts +116 -0
- package/packages/contracts/src/identity.ts +68 -0
- package/packages/contracts/src/index.ts +20 -0
- package/packages/contracts/src/invocation.ts +96 -0
- package/packages/contracts/src/lifecycle.ts +169 -0
- package/packages/contracts/src/plugin.ts +174 -0
- package/packages/contracts/src/projectRead.ts +179 -0
- package/packages/contracts/src/secure.ts +136 -0
- package/provenance.json +179 -9
- package/source.zip +0 -0
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { DIAG_LEVEL_RANK, formatDiagEvent, makeDiagEvent } from '../../../../packages/contracts/dist/index.js';
|
|
4
|
+
/**
|
|
5
|
+
* SW-062: the daemon's single diagnostic log (C09 owns durable local state).
|
|
6
|
+
*
|
|
7
|
+
* - JSON Lines, one sanitised event per line (contracts `makeDiagEvent` is the only constructor: secrets, challenge/approval codes, prompts,
|
|
8
|
+
* conversation text, bearer tokens and filesystem paths cannot be recorded).
|
|
9
|
+
* - Lives in `<private data root>/logs/`. That directory is created INSIDE the already verified private data root, so it inherits the
|
|
10
|
+
* protected current-user + SYSTEM DACL (POSIX: 0700 dir / 0600 file). The inheritance of the logs files themselves is NOT separately verified.
|
|
11
|
+
* - Bounded: each file is capped (`maxBytes`), at most `maxFiles` files exist (daemon.log, daemon.log.1 ...), a single line is capped, and an
|
|
12
|
+
* in-memory ring of recent events serves the operator console. Oldest data is dropped, never grown.
|
|
13
|
+
* - Never throws: a logging failure must not change the outcome of a request. Failures are only counted (`writeFailures`).
|
|
14
|
+
*/
|
|
15
|
+
export const DIAG_LOG_DIR_NAME = 'logs';
|
|
16
|
+
export const DIAG_LOG_FILE_NAME = 'daemon.log';
|
|
17
|
+
export const DIAG_LOG_DEFAULT_MAX_BYTES = 1_048_576;
|
|
18
|
+
export const DIAG_LOG_DEFAULT_MAX_FILES = 4;
|
|
19
|
+
export const DIAG_LOG_MAX_LINE_BYTES = 2048;
|
|
20
|
+
export const DIAG_RING_SIZE = 200;
|
|
21
|
+
export class DiagnosticLog {
|
|
22
|
+
dir;
|
|
23
|
+
maxBytes;
|
|
24
|
+
maxFiles;
|
|
25
|
+
minRank;
|
|
26
|
+
ringSize;
|
|
27
|
+
now;
|
|
28
|
+
fileName;
|
|
29
|
+
ring = [];
|
|
30
|
+
size = 0;
|
|
31
|
+
writeFailures = 0;
|
|
32
|
+
constructor(opts = {}) {
|
|
33
|
+
this.dir = opts.dir;
|
|
34
|
+
this.maxBytes = Math.max(1024, opts.maxBytes ?? DIAG_LOG_DEFAULT_MAX_BYTES);
|
|
35
|
+
this.maxFiles = Math.max(1, Math.min(10, opts.maxFiles ?? DIAG_LOG_DEFAULT_MAX_FILES));
|
|
36
|
+
this.minRank = DIAG_LEVEL_RANK[opts.minLevel ?? 'INFO'];
|
|
37
|
+
this.ringSize = Math.max(10, opts.ringSize ?? DIAG_RING_SIZE);
|
|
38
|
+
this.now = opts.now ?? Date.now;
|
|
39
|
+
this.fileName = opts.fileName !== undefined && /^[a-z][a-z0-9-]{0,40}\.log$/.test(opts.fileName) ? opts.fileName : DIAG_LOG_FILE_NAME;
|
|
40
|
+
if (this.dir !== undefined) {
|
|
41
|
+
try {
|
|
42
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
43
|
+
const f = this.file(0);
|
|
44
|
+
this.size = existsSync(f) ? statSync(f).size : 0;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
this.writeFailures += 1;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
get filePath() { return this.dir === undefined ? undefined : this.file(0); }
|
|
52
|
+
file(i) { return join(this.dir, i === 0 ? this.fileName : `${this.fileName}.${i}`); }
|
|
53
|
+
log(level, component, operation, event, f = {}) {
|
|
54
|
+
const e = makeDiagEvent({ ts: new Date(this.now()).toISOString(), level, component, operation, event, ...f });
|
|
55
|
+
if (DIAG_LEVEL_RANK[level] < this.minRank)
|
|
56
|
+
return e;
|
|
57
|
+
this.ring.push(e);
|
|
58
|
+
if (this.ring.length > this.ringSize)
|
|
59
|
+
this.ring.splice(0, this.ring.length - this.ringSize);
|
|
60
|
+
this.append(e);
|
|
61
|
+
return e;
|
|
62
|
+
}
|
|
63
|
+
debug(c, op, ev, f) { return this.log('DEBUG', c, op, ev, f); }
|
|
64
|
+
info(c, op, ev, f) { return this.log('INFO', c, op, ev, f); }
|
|
65
|
+
warn(c, op, ev, f) { return this.log('WARN', c, op, ev, f); }
|
|
66
|
+
error(c, op, ev, f) { return this.log('ERROR', c, op, ev, f); }
|
|
67
|
+
recent(n = 20, correlationId) {
|
|
68
|
+
const all = correlationId === undefined ? this.ring : this.ring.filter((e) => e.correlationId === correlationId);
|
|
69
|
+
return all.slice(-Math.max(1, Math.min(n, this.ringSize)));
|
|
70
|
+
}
|
|
71
|
+
/** SW-097 allowlisted daemon lifecycle only, replayed from the existing rotated log.
|
|
72
|
+
* No request, project, metadata, path or log body crosses this boundary. */
|
|
73
|
+
lifecycleHistory() {
|
|
74
|
+
const out = new Map();
|
|
75
|
+
const take = (v) => {
|
|
76
|
+
if (v.component !== 'DAEMON' || typeof v.ts !== 'string' || !Number.isFinite(Date.parse(v.ts)) || !['DAEMON_STARTING', 'DAEMON_LISTENING', 'DAEMON_STOPPING', 'DAEMON_STOPPED'].includes(String(v.event)))
|
|
77
|
+
return;
|
|
78
|
+
out.set(`${v.ts}:${v.event}`, { ts: v.ts, event: String(v.event) });
|
|
79
|
+
};
|
|
80
|
+
if (this.dir)
|
|
81
|
+
for (let i = this.maxFiles - 1; i >= 0; i--) {
|
|
82
|
+
try {
|
|
83
|
+
const file = this.file(i);
|
|
84
|
+
if (statSync(file).size > this.maxBytes + DIAG_LOG_MAX_LINE_BYTES)
|
|
85
|
+
continue;
|
|
86
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
87
|
+
try {
|
|
88
|
+
take(JSON.parse(line));
|
|
89
|
+
}
|
|
90
|
+
catch { /* incomplete last line is unavailable */ }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
catch { /* absent/rotated file: no invented event */ }
|
|
94
|
+
}
|
|
95
|
+
for (const e of this.ring)
|
|
96
|
+
take(e);
|
|
97
|
+
return [...out.values()].sort((a, b) => a.ts.localeCompare(b.ts)).slice(-12);
|
|
98
|
+
}
|
|
99
|
+
append(e) {
|
|
100
|
+
if (this.dir === undefined)
|
|
101
|
+
return;
|
|
102
|
+
let line = JSON.stringify(e);
|
|
103
|
+
if (Buffer.byteLength(line, 'utf8') > DIAG_LOG_MAX_LINE_BYTES) {
|
|
104
|
+
line = JSON.stringify({ ts: e.ts, level: e.level, component: e.component, operation: e.operation, event: e.event, ...(e.correlationId ? { correlationId: e.correlationId } : {}), meta: { _truncated: true } });
|
|
105
|
+
}
|
|
106
|
+
line += '\n';
|
|
107
|
+
const bytes = Buffer.byteLength(line, 'utf8');
|
|
108
|
+
try {
|
|
109
|
+
if (this.size + bytes > this.maxBytes && this.size > 0)
|
|
110
|
+
this.rotate();
|
|
111
|
+
appendFileSync(this.file(0), line, { encoding: 'utf8', mode: 0o600 });
|
|
112
|
+
this.size += bytes;
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
this.writeFailures += 1;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
rotate() {
|
|
119
|
+
try {
|
|
120
|
+
rmSync(this.file(this.maxFiles - 1), { force: true });
|
|
121
|
+
}
|
|
122
|
+
catch { /* best effort */ }
|
|
123
|
+
for (let i = this.maxFiles - 2; i >= 0; i -= 1) {
|
|
124
|
+
try {
|
|
125
|
+
if (existsSync(this.file(i)))
|
|
126
|
+
renameSync(this.file(i), this.file(i + 1));
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
this.writeFailures += 1;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
this.size = 0;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
export const formatDiagLine = formatDiagEvent;
|
|
136
|
+
//# sourceMappingURL=diagnosticLog.js.map
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { type ExecutionClassification, type ExecutionEvidenceExport, type ExecutionFailureView } from '../../../../packages/contracts/dist/index.js';
|
|
2
|
+
import { type ClassifierInput } from '../runtime/executionDiagnostics.js';
|
|
3
|
+
import type { ProcessObserver } from '../runtime/boundedProcessHost.js';
|
|
4
|
+
import type { SqliteLedger } from './sqliteLedger.js';
|
|
5
|
+
/**
|
|
6
|
+
* C09 execution telemetry (SW-068): the single, generic, fail-closed evidence recorder for every external CLI execution.
|
|
7
|
+
*
|
|
8
|
+
* - begin() writes the evidence header BEFORE any process exists; if the store cannot be written the operation is not launched (TelemetryUnavailableError).
|
|
9
|
+
* - Every later fact is its own committed row (incremental): lifecycle stages, bounded redacted stdout/stderr LINES in arrival order, parser problems, notes.
|
|
10
|
+
* A crash, timeout, kill or daemon restart therefore leaves everything recorded up to that moment, including the last confirmed stage.
|
|
11
|
+
* - Nothing raw is stored: all text passes through evidenceRedaction first (credentials masked, prompt lines masked, model output text omitted, lines bounded).
|
|
12
|
+
* - Bounded: at most EVIDENCE_LIMITS.maxEventsPerRun rows and maxStreamCharsPerRun characters per stream; what is dropped is COUNTED and recorded as a NOTE.
|
|
13
|
+
* - A write failure after launch never disturbs the running process; it is remembered and reported at the end (degraded evidence is itself evidence).
|
|
14
|
+
* It knows no provider: provider wording lives in PROVIDER_RULES (executionDiagnostics.ts).
|
|
15
|
+
*/
|
|
16
|
+
export declare class TelemetryUnavailableError extends Error {
|
|
17
|
+
constructor();
|
|
18
|
+
}
|
|
19
|
+
export interface RunTelemetryHandle {
|
|
20
|
+
readonly correlationId: string;
|
|
21
|
+
readonly observer: ProcessObserver;
|
|
22
|
+
stage(stage: string, data?: Record<string, string | number | boolean | null>): void;
|
|
23
|
+
/** Records the terminal facts and returns the stored classification. */
|
|
24
|
+
finish(input: FinishInput): ExecutionClassification;
|
|
25
|
+
}
|
|
26
|
+
export interface FinishInput {
|
|
27
|
+
lifecycleState: string | undefined;
|
|
28
|
+
observed: ClassifierInput['observed'];
|
|
29
|
+
note?: string;
|
|
30
|
+
}
|
|
31
|
+
export interface BeginInfo {
|
|
32
|
+
runId: string;
|
|
33
|
+
driver: string;
|
|
34
|
+
outputProfile: string | null;
|
|
35
|
+
pluginId: string;
|
|
36
|
+
operationId: string;
|
|
37
|
+
executableSha256: string;
|
|
38
|
+
manifestFingerprint: string;
|
|
39
|
+
/** Non-sensitive launch configuration (argv TEMPLATE, identity, tier, timeout, transport, environment variable NAMES). Never the prompt. */
|
|
40
|
+
config: Record<string, unknown>;
|
|
41
|
+
/** The approved prompt: used ONLY to mask its lines if the CLI echoes them; never stored. */
|
|
42
|
+
prompt: string;
|
|
43
|
+
}
|
|
44
|
+
export declare class ExecutionTelemetry {
|
|
45
|
+
private readonly ledger;
|
|
46
|
+
private readonly now;
|
|
47
|
+
constructor(ledger: SqliteLedger, now?: () => number);
|
|
48
|
+
private iso;
|
|
49
|
+
/** Throws TelemetryUnavailableError unless the store accepts a committed write and returns it. */
|
|
50
|
+
assertWritable(): void;
|
|
51
|
+
begin(info: BeginInfo): RunTelemetryHandle;
|
|
52
|
+
/** The category + correlation id the application shows for a run, or undefined when it did not fail / has no evidence. */
|
|
53
|
+
describeFailure(runId: string, lifecycleState: string): ExecutionFailureView | undefined;
|
|
54
|
+
private classificationOf;
|
|
55
|
+
/** The shareable redacted export of one execution (by run id, correlation id, or the latest). */
|
|
56
|
+
exportEvidence(key: {
|
|
57
|
+
runId?: string;
|
|
58
|
+
correlationId?: string;
|
|
59
|
+
}, lifecycleState: string): ExecutionEvidenceExport | undefined;
|
|
60
|
+
/** Retention rule: evidence older than EVIDENCE_LIMITS.retentionDays is deleted (called at daemon start). */
|
|
61
|
+
purgeExpired(): number;
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=executionTelemetry.d.ts.map
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
2
|
+
import { EVIDENCE_LIMITS, newCorrelationId, ExecutionClassificationSchema, } from '../../../../packages/contracts/dist/index.js';
|
|
3
|
+
import { classifyExecution } from '../runtime/executionDiagnostics.js';
|
|
4
|
+
import { promptLinesOf, redactText, summarizeStdoutLine } from '../runtime/evidenceRedaction.js';
|
|
5
|
+
/**
|
|
6
|
+
* C09 execution telemetry (SW-068): the single, generic, fail-closed evidence recorder for every external CLI execution.
|
|
7
|
+
*
|
|
8
|
+
* - begin() writes the evidence header BEFORE any process exists; if the store cannot be written the operation is not launched (TelemetryUnavailableError).
|
|
9
|
+
* - Every later fact is its own committed row (incremental): lifecycle stages, bounded redacted stdout/stderr LINES in arrival order, parser problems, notes.
|
|
10
|
+
* A crash, timeout, kill or daemon restart therefore leaves everything recorded up to that moment, including the last confirmed stage.
|
|
11
|
+
* - Nothing raw is stored: all text passes through evidenceRedaction first (credentials masked, prompt lines masked, model output text omitted, lines bounded).
|
|
12
|
+
* - Bounded: at most EVIDENCE_LIMITS.maxEventsPerRun rows and maxStreamCharsPerRun characters per stream; what is dropped is COUNTED and recorded as a NOTE.
|
|
13
|
+
* - A write failure after launch never disturbs the running process; it is remembered and reported at the end (degraded evidence is itself evidence).
|
|
14
|
+
* It knows no provider: provider wording lives in PROVIDER_RULES (executionDiagnostics.ts).
|
|
15
|
+
*/
|
|
16
|
+
export class TelemetryUnavailableError extends Error {
|
|
17
|
+
constructor() { super('TELEMETRY_UNAVAILABLE'); this.name = 'TelemetryUnavailableError'; }
|
|
18
|
+
}
|
|
19
|
+
const STAGE_RE = /^[A-Z][A-Z0-9_]{1,40}$/;
|
|
20
|
+
export class ExecutionTelemetry {
|
|
21
|
+
ledger;
|
|
22
|
+
now;
|
|
23
|
+
constructor(ledger, now = Date.now) {
|
|
24
|
+
this.ledger = ledger;
|
|
25
|
+
this.now = now;
|
|
26
|
+
}
|
|
27
|
+
iso() { return new Date(this.now()).toISOString(); }
|
|
28
|
+
/** Throws TelemetryUnavailableError unless the store accepts a committed write and returns it. */
|
|
29
|
+
assertWritable() {
|
|
30
|
+
try {
|
|
31
|
+
this.ledger.telemetryProbe(this.iso());
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
throw new TelemetryUnavailableError();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
begin(info) {
|
|
38
|
+
const correlationId = newCorrelationId();
|
|
39
|
+
const cfg = JSON.stringify(info.config);
|
|
40
|
+
const configJson = cfg.length <= EVIDENCE_LIMITS.maxConfigJsonChars ? cfg : JSON.stringify({ _truncated: true, keys: Object.keys(info.config).slice(0, 32) });
|
|
41
|
+
try {
|
|
42
|
+
this.ledger.beginExecutionEvidence({
|
|
43
|
+
runId: info.runId, correlationId, createdAt: this.iso(), driver: info.driver, outputProfile: info.outputProfile, pluginId: info.pluginId, operationId: info.operationId,
|
|
44
|
+
executableSha256: info.executableSha256, manifestFingerprint: info.manifestFingerprint, configJson, lastStage: 'LAUNCH_INTENT_COMMITTED',
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
throw new TelemetryUnavailableError();
|
|
49
|
+
}
|
|
50
|
+
const prompt = promptLinesOf(info.prompt);
|
|
51
|
+
const ledger = this.ledger;
|
|
52
|
+
const now = this.iso.bind(this);
|
|
53
|
+
const runId = info.runId;
|
|
54
|
+
let events = 1;
|
|
55
|
+
let degraded = 0;
|
|
56
|
+
let notedLimit = false;
|
|
57
|
+
let finished = false;
|
|
58
|
+
const dropped = { LIFECYCLE: 0, STDOUT: 0, STDERR: 0, PARSER: 0, NOTE: 0 };
|
|
59
|
+
const streamChars = { stdout: 0, stderr: 0 };
|
|
60
|
+
const streamDropped = { stdout: 0, stderr: 0 };
|
|
61
|
+
const RESERVE = 8; // rows kept free for the terminal facts
|
|
62
|
+
const write = (kind, stage, data, truncated = false, terminal = false) => {
|
|
63
|
+
if (!terminal && events >= EVIDENCE_LIMITS.maxEventsPerRun - RESERVE) {
|
|
64
|
+
dropped[kind] += 1;
|
|
65
|
+
if (!notedLimit) {
|
|
66
|
+
notedLimit = true;
|
|
67
|
+
try {
|
|
68
|
+
ledger.appendExecutionEvidence(runId, { ts: now(), kind: 'NOTE', data: 'EVIDENCE_EVENT_LIMIT_REACHED: further events are counted, not stored', truncated: true });
|
|
69
|
+
events += 1;
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
degraded += 1;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
const failedStage = stage !== undefined && stage.startsWith('FAILED_');
|
|
78
|
+
try {
|
|
79
|
+
ledger.appendExecutionEvidence(runId, { ts: now(), kind, ...(stage && !failedStage && STAGE_RE.test(stage) ? { stage } : {}), data: (failedStage ? `${stage} ${data}` : data).slice(0, 1000), truncated });
|
|
80
|
+
events += 1;
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
degraded += 1;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const red = (v) => redactText(typeof v === 'string' ? v : JSON.stringify(v), { promptLines: prompt, max: 240 }).text;
|
|
87
|
+
const dataOf = (d) => (d ? Object.entries(d).slice(0, 12).map(([k, v]) => `${k.replace(/[^A-Za-z0-9_]/g, '').slice(0, 24)}=${red(v)}`).join(' ') : '');
|
|
88
|
+
const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') };
|
|
89
|
+
const partial = { stdout: '', stderr: '' };
|
|
90
|
+
const emit = (stream, line, forceTruncated = false) => {
|
|
91
|
+
if (line.trim().length === 0)
|
|
92
|
+
return;
|
|
93
|
+
const kind = stream === 'stdout' ? 'STDOUT' : 'STDERR';
|
|
94
|
+
let text;
|
|
95
|
+
let truncated = forceTruncated;
|
|
96
|
+
if (stream === 'stdout') {
|
|
97
|
+
const s = summarizeStdoutLine(line, { promptLines: prompt });
|
|
98
|
+
text = s.text;
|
|
99
|
+
truncated = truncated || s.truncated;
|
|
100
|
+
if (s.jsonInvalid)
|
|
101
|
+
write('PARSER', undefined, `INVALID_JSON_LINE ${text.slice(0, 200)}`, s.truncated);
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
const r = redactText(line, { promptLines: prompt });
|
|
105
|
+
text = r.text;
|
|
106
|
+
truncated = truncated || r.truncated;
|
|
107
|
+
}
|
|
108
|
+
if (streamChars[stream] + text.length > EVIDENCE_LIMITS.maxStreamCharsPerRun) {
|
|
109
|
+
if (streamDropped[stream] === 0)
|
|
110
|
+
write('NOTE', undefined, `${stream.toUpperCase()}_BUDGET_REACHED: further ${stream} lines are counted, not stored`, true);
|
|
111
|
+
streamDropped[stream] += text.length;
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
streamChars[stream] += text.length;
|
|
115
|
+
write(kind, undefined, text, truncated);
|
|
116
|
+
};
|
|
117
|
+
const feed = (stream, text) => {
|
|
118
|
+
let buf = partial[stream] + text;
|
|
119
|
+
let nl;
|
|
120
|
+
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
121
|
+
emit(stream, buf.slice(0, nl).replace(/\r$/, ''));
|
|
122
|
+
buf = buf.slice(nl + 1);
|
|
123
|
+
}
|
|
124
|
+
if (buf.length > 4096) {
|
|
125
|
+
emit(stream, buf.slice(0, 4096), true);
|
|
126
|
+
buf = '';
|
|
127
|
+
}
|
|
128
|
+
partial[stream] = buf;
|
|
129
|
+
};
|
|
130
|
+
const flush = () => { for (const s of ['stdout', 'stderr']) {
|
|
131
|
+
const tail = decoders[s].end();
|
|
132
|
+
if (tail)
|
|
133
|
+
feed(s, tail);
|
|
134
|
+
if (partial[s].length > 0) {
|
|
135
|
+
emit(s, partial[s]);
|
|
136
|
+
partial[s] = '';
|
|
137
|
+
}
|
|
138
|
+
} };
|
|
139
|
+
const observer = {
|
|
140
|
+
lifecycle: (stage, data) => { try {
|
|
141
|
+
write('LIFECYCLE', stage, dataOf(data));
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
degraded += 1;
|
|
145
|
+
} },
|
|
146
|
+
chunk: (stream, bytes) => { try {
|
|
147
|
+
feed(stream, decoders[stream].write(Buffer.from(bytes)));
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
degraded += 1;
|
|
151
|
+
} },
|
|
152
|
+
};
|
|
153
|
+
write('LIFECYCLE', 'TELEMETRY_STARTED', `driver=${red(info.driver)} operation=${red(info.operationId)} exe=${info.executableSha256.slice(0, 12)}`);
|
|
154
|
+
return {
|
|
155
|
+
correlationId,
|
|
156
|
+
observer,
|
|
157
|
+
stage: (stage, data) => write('LIFECYCLE', stage, dataOf(data)),
|
|
158
|
+
finish: (input) => {
|
|
159
|
+
if (!finished) {
|
|
160
|
+
finished = true;
|
|
161
|
+
flush();
|
|
162
|
+
if (streamDropped.stdout > 0 || streamDropped.stderr > 0)
|
|
163
|
+
write('NOTE', undefined, `OUTPUT_NOT_STORED stdout_chars=${streamDropped.stdout} stderr_chars=${streamDropped.stderr}`, true, true);
|
|
164
|
+
const lost = Object.values(dropped).reduce((a, b) => a + b, 0);
|
|
165
|
+
if (lost > 0)
|
|
166
|
+
write('NOTE', undefined, `EVENTS_NOT_STORED count=${lost}`, true, true);
|
|
167
|
+
if (degraded > 0)
|
|
168
|
+
write('NOTE', undefined, `EVIDENCE_WRITE_FAILURES count=${degraded}`, true, true);
|
|
169
|
+
if (input.note)
|
|
170
|
+
write('NOTE', undefined, red(input.note), false, true);
|
|
171
|
+
}
|
|
172
|
+
const rows = ledger.getExecutionEvidence(runId);
|
|
173
|
+
const cls = classifyExecution({
|
|
174
|
+
outputProfile: info.outputProfile, lifecycleState: input.lifecycleState, observed: input.observed, events: rows?.events ?? [], lastStage: rows?.header.lastStage ?? 'LAUNCH_INTENT_COMMITTED',
|
|
175
|
+
});
|
|
176
|
+
try {
|
|
177
|
+
ledger.finalizeExecutionEvidence(runId, JSON.stringify(cls), now());
|
|
178
|
+
}
|
|
179
|
+
catch { /* the export recomputes */ }
|
|
180
|
+
return cls;
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/** The category + correlation id the application shows for a run, or undefined when it did not fail / has no evidence. */
|
|
185
|
+
describeFailure(runId, lifecycleState) {
|
|
186
|
+
let rec;
|
|
187
|
+
try {
|
|
188
|
+
rec = this.ledger.getExecutionEvidence(runId);
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
return undefined;
|
|
192
|
+
}
|
|
193
|
+
if (!rec)
|
|
194
|
+
return undefined;
|
|
195
|
+
const cls = this.classificationOf(rec.header.classificationJson, rec.header.outputProfile, lifecycleState, rec.events, rec.header.lastStage).cls;
|
|
196
|
+
if (cls.category === null)
|
|
197
|
+
return undefined;
|
|
198
|
+
return { category: cls.category, basis: cls.basis, causeDetermined: cls.causeDetermined, correlationId: rec.header.correlationId };
|
|
199
|
+
}
|
|
200
|
+
classificationOf(stored, outputProfile, lifecycleState, events, lastStage) {
|
|
201
|
+
if (stored) {
|
|
202
|
+
try {
|
|
203
|
+
const p = ExecutionClassificationSchema.safeParse(JSON.parse(stored));
|
|
204
|
+
if (p.success)
|
|
205
|
+
return { cls: p.data, at: 'FINALIZATION' };
|
|
206
|
+
}
|
|
207
|
+
catch { /* recompute */ }
|
|
208
|
+
}
|
|
209
|
+
// Never finalized (daemon died, hard crash): classify from what was durably recorded.
|
|
210
|
+
return { cls: classifyExecution({ outputProfile, lifecycleState, observed: { kind: 'NONE' }, events, lastStage }), at: 'EXPORT' };
|
|
211
|
+
}
|
|
212
|
+
/** The shareable redacted export of one execution (by run id, correlation id, or the latest). */
|
|
213
|
+
exportEvidence(key, lifecycleState) {
|
|
214
|
+
const runId = key.runId ?? this.ledger.findExecutionEvidenceRun(key.correlationId);
|
|
215
|
+
if (!runId)
|
|
216
|
+
return undefined;
|
|
217
|
+
const rec = this.ledger.getExecutionEvidence(runId);
|
|
218
|
+
if (!rec)
|
|
219
|
+
return undefined;
|
|
220
|
+
const { cls, at } = this.classificationOf(rec.header.classificationJson, rec.header.outputProfile, lifecycleState, rec.events, rec.header.lastStage);
|
|
221
|
+
let launch = {};
|
|
222
|
+
try {
|
|
223
|
+
launch = JSON.parse(rec.header.configJson);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
launch = { _unreadable: true };
|
|
227
|
+
}
|
|
228
|
+
const notes = [];
|
|
229
|
+
if (!rec.header.finalizedAt)
|
|
230
|
+
notes.push('NOT_FINALIZED: no terminal record was written (crash, kill or restart); classification computed from the recorded evidence');
|
|
231
|
+
if (rec.events.some((e) => e.truncated))
|
|
232
|
+
notes.push('SOME_LINES_TRUNCATED: marked per event');
|
|
233
|
+
notes.push('REDACTED: credentials, prompt text and model output text are never stored; opaque 32+ character strings, e-mail addresses and profile names are masked');
|
|
234
|
+
return {
|
|
235
|
+
schemaVersion: 1, correlationId: rec.header.correlationId, runId, exportedAt: this.iso(), driver: rec.header.driver, outputProfile: rec.header.outputProfile, operationId: rec.header.operationId,
|
|
236
|
+
executableSha256: rec.header.executableSha256, launch, lifecycleState, lastStage: rec.header.lastStage, classification: cls, classificationComputedAt: at,
|
|
237
|
+
// defense in depth: stored text is already redacted; the export redacts it again
|
|
238
|
+
events: rec.events.map((e) => ({ seq: e.seq, ts: e.ts, kind: e.kind, stage: e.stage, data: redactText(e.data, { max: 1000 }).text, truncated: e.truncated })),
|
|
239
|
+
notes,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
/** Retention rule: evidence older than EVIDENCE_LIMITS.retentionDays is deleted (called at daemon start). */
|
|
243
|
+
purgeExpired() {
|
|
244
|
+
return this.ledger.purgeExecutionEvidence(new Date(this.now() - EVIDENCE_LIMITS.retentionDays * 86_400_000).toISOString());
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
//# sourceMappingURL=executionTelemetry.js.map
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* C09 at-rest protection (SW-062).
|
|
3
|
+
*
|
|
4
|
+
* - Windows DPAPI, CurrentUser scope, with a fixed application entropy: protects the installation secret and the data key so a copy of the private data root
|
|
5
|
+
* is useless to another Windows account or another machine. It does NOT protect against code already running as the same user (stated, not hidden).
|
|
6
|
+
* - AES-256-GCM sealing of capture snapshots and return targets with ONE random data key per private data root. Layout: [1 version][12 iv][16 tag][ciphertext].
|
|
7
|
+
*
|
|
8
|
+
* DPAPI is reached through the in-box Windows PowerShell 5.1 binary at its fixed System32 path (never PATH), hidden, no profile, input on stdin, no secret on the
|
|
9
|
+
* command line. The protect/unprotect functions are injectable so non-Windows logic can be unit tested; production always uses the real one.
|
|
10
|
+
*/
|
|
11
|
+
export declare const DPAPI_ENTROPY = "my-centcom.v1";
|
|
12
|
+
export declare const DATA_KEY_DIR = "keys";
|
|
13
|
+
export declare const DATA_KEY_FILE = "data-key.dpapi";
|
|
14
|
+
export interface Dpapi {
|
|
15
|
+
protect(plain: Buffer): Buffer;
|
|
16
|
+
unprotect(sealed: Buffer): Buffer;
|
|
17
|
+
}
|
|
18
|
+
export declare class ProtectedSecretError extends Error {
|
|
19
|
+
readonly code: 'DPAPI_UNAVAILABLE' | 'DPAPI_FAILED' | 'KEY_INVALID' | 'SEAL_INVALID';
|
|
20
|
+
constructor(code: 'DPAPI_UNAVAILABLE' | 'DPAPI_FAILED' | 'KEY_INVALID' | 'SEAL_INVALID');
|
|
21
|
+
}
|
|
22
|
+
/** The real Windows DPAPI (CurrentUser). */
|
|
23
|
+
export declare const windowsDpapi: Dpapi;
|
|
24
|
+
/** Seals and opens JSON values with one 32-byte key. Any tampering (bit flip, truncation, other key) fails closed with SEAL_INVALID. */
|
|
25
|
+
export declare class Sealer {
|
|
26
|
+
private readonly key;
|
|
27
|
+
constructor(key: Buffer);
|
|
28
|
+
seal(value: unknown): Uint8Array;
|
|
29
|
+
open(sealed: Uint8Array): unknown;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Loads (or, once, creates) the data key of one VERIFIED private data root. The key file lives in <dataRoot>\keys\ (created inside the private root, so it
|
|
33
|
+
* inherits the exact {user, SYSTEM} DACL) and holds only the DPAPI blob. A blob that DPAPI refuses (another user, another machine, corruption) fails closed:
|
|
34
|
+
* the key is never silently regenerated, because that would orphan existing sealed rows without telling anyone.
|
|
35
|
+
*/
|
|
36
|
+
export declare function loadOrCreateDataKey(dataRoot: string, dpapi?: Dpapi): Buffer;
|
|
37
|
+
/** Lazily created sealer: DPAPI is only invoked the first time something must be sealed or opened. */
|
|
38
|
+
export declare function lazySealer(dataRoot: string, dpapi?: Dpapi): () => Sealer;
|
|
39
|
+
//# sourceMappingURL=protectedSecrets.d.ts.map
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
/**
|
|
6
|
+
* C09 at-rest protection (SW-062).
|
|
7
|
+
*
|
|
8
|
+
* - Windows DPAPI, CurrentUser scope, with a fixed application entropy: protects the installation secret and the data key so a copy of the private data root
|
|
9
|
+
* is useless to another Windows account or another machine. It does NOT protect against code already running as the same user (stated, not hidden).
|
|
10
|
+
* - AES-256-GCM sealing of capture snapshots and return targets with ONE random data key per private data root. Layout: [1 version][12 iv][16 tag][ciphertext].
|
|
11
|
+
*
|
|
12
|
+
* DPAPI is reached through the in-box Windows PowerShell 5.1 binary at its fixed System32 path (never PATH), hidden, no profile, input on stdin, no secret on the
|
|
13
|
+
* command line. The protect/unprotect functions are injectable so non-Windows logic can be unit tested; production always uses the real one.
|
|
14
|
+
*/
|
|
15
|
+
export const DPAPI_ENTROPY = 'my-centcom.v1';
|
|
16
|
+
export const DATA_KEY_DIR = 'keys';
|
|
17
|
+
export const DATA_KEY_FILE = 'data-key.dpapi';
|
|
18
|
+
const SEAL_VERSION = 1;
|
|
19
|
+
export class ProtectedSecretError extends Error {
|
|
20
|
+
code;
|
|
21
|
+
constructor(code) {
|
|
22
|
+
super(code);
|
|
23
|
+
this.code = code;
|
|
24
|
+
this.name = 'ProtectedSecretError';
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const powershell = () => join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
28
|
+
function dpapiCall(op, input) {
|
|
29
|
+
if (process.platform !== 'win32')
|
|
30
|
+
throw new ProtectedSecretError('DPAPI_UNAVAILABLE');
|
|
31
|
+
const script = "$ErrorActionPreference='Stop';Add-Type -AssemblyName System.Security;" +
|
|
32
|
+
'$i=[Convert]::FromBase64String([Console]::In.ReadToEnd().Trim());' +
|
|
33
|
+
`$e=[Text.Encoding]::UTF8.GetBytes('${DPAPI_ENTROPY}');` +
|
|
34
|
+
`[Convert]::ToBase64String([Security.Cryptography.ProtectedData]::${op}($i,$e,[Security.Cryptography.DataProtectionScope]::CurrentUser))`;
|
|
35
|
+
let out;
|
|
36
|
+
try {
|
|
37
|
+
out = execFileSync(powershell(), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script], {
|
|
38
|
+
input: input.toString('base64'), windowsHide: true, shell: false, encoding: 'utf8', timeout: 30_000, stdio: ['pipe', 'pipe', 'ignore'],
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw new ProtectedSecretError('DPAPI_FAILED');
|
|
43
|
+
}
|
|
44
|
+
const b64 = out.trim();
|
|
45
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(b64))
|
|
46
|
+
throw new ProtectedSecretError('DPAPI_FAILED');
|
|
47
|
+
return Buffer.from(b64, 'base64');
|
|
48
|
+
}
|
|
49
|
+
/** The real Windows DPAPI (CurrentUser). */
|
|
50
|
+
export const windowsDpapi = {
|
|
51
|
+
protect: (plain) => dpapiCall('Protect', plain),
|
|
52
|
+
unprotect: (sealed) => dpapiCall('Unprotect', sealed),
|
|
53
|
+
};
|
|
54
|
+
/** Seals and opens JSON values with one 32-byte key. Any tampering (bit flip, truncation, other key) fails closed with SEAL_INVALID. */
|
|
55
|
+
export class Sealer {
|
|
56
|
+
key;
|
|
57
|
+
constructor(key) {
|
|
58
|
+
this.key = key;
|
|
59
|
+
if (!Buffer.isBuffer(key) || key.length !== 32)
|
|
60
|
+
throw new ProtectedSecretError('KEY_INVALID');
|
|
61
|
+
}
|
|
62
|
+
seal(value) {
|
|
63
|
+
const iv = randomBytes(12);
|
|
64
|
+
const c = createCipheriv('aes-256-gcm', this.key, iv);
|
|
65
|
+
const ct = Buffer.concat([c.update(Buffer.from(JSON.stringify(value), 'utf8')), c.final()]);
|
|
66
|
+
return new Uint8Array(Buffer.concat([Buffer.from([SEAL_VERSION]), iv, c.getAuthTag(), ct]));
|
|
67
|
+
}
|
|
68
|
+
open(sealed) {
|
|
69
|
+
const b = Buffer.from(sealed);
|
|
70
|
+
if (b.length < 1 + 12 + 16 + 1 || b[0] !== SEAL_VERSION)
|
|
71
|
+
throw new ProtectedSecretError('SEAL_INVALID');
|
|
72
|
+
try {
|
|
73
|
+
const d = createDecipheriv('aes-256-gcm', this.key, b.subarray(1, 13));
|
|
74
|
+
d.setAuthTag(b.subarray(13, 29));
|
|
75
|
+
return JSON.parse(Buffer.concat([d.update(b.subarray(29)), d.final()]).toString('utf8'));
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
throw new ProtectedSecretError('SEAL_INVALID');
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Loads (or, once, creates) the data key of one VERIFIED private data root. The key file lives in <dataRoot>\keys\ (created inside the private root, so it
|
|
84
|
+
* inherits the exact {user, SYSTEM} DACL) and holds only the DPAPI blob. A blob that DPAPI refuses (another user, another machine, corruption) fails closed:
|
|
85
|
+
* the key is never silently regenerated, because that would orphan existing sealed rows without telling anyone.
|
|
86
|
+
*/
|
|
87
|
+
export function loadOrCreateDataKey(dataRoot, dpapi = windowsDpapi) {
|
|
88
|
+
const dir = join(dataRoot, DATA_KEY_DIR);
|
|
89
|
+
const file = join(dir, DATA_KEY_FILE);
|
|
90
|
+
if (existsSync(file)) {
|
|
91
|
+
const key = dpapi.unprotect(readFileSync(file));
|
|
92
|
+
if (key.length !== 32)
|
|
93
|
+
throw new ProtectedSecretError('KEY_INVALID');
|
|
94
|
+
return key;
|
|
95
|
+
}
|
|
96
|
+
mkdirSync(dir, { recursive: true });
|
|
97
|
+
const key = randomBytes(32);
|
|
98
|
+
writeFileSync(file, dpapi.protect(key), { flag: 'wx' });
|
|
99
|
+
return key;
|
|
100
|
+
}
|
|
101
|
+
/** Lazily created sealer: DPAPI is only invoked the first time something must be sealed or opened. */
|
|
102
|
+
export function lazySealer(dataRoot, dpapi = windowsDpapi) {
|
|
103
|
+
let s;
|
|
104
|
+
return () => (s ??= new Sealer(loadOrCreateDataKey(dataRoot, dpapi)));
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=protectedSecrets.js.map
|