@dailephd/my-centcom 0.1.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,652 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { appendFileSync, closeSync, existsSync, fstatSync, lstatSync, openSync, opendirSync, readFileSync, readSync, realpathSync, statSync, truncateSync } from 'node:fs';
|
|
3
|
+
import { join, sep } from 'node:path';
|
|
4
|
+
/**
|
|
5
|
+
* C07 BOUNDED PROJECT READ SERVICE (SW-074). Provider-neutral. Node built-ins only (the MCP adapter that serves it must stay a small, auditable closure).
|
|
6
|
+
*
|
|
7
|
+
* Authority model. The agent-visible surface is three READ-ONLY operations bound to one run-scoped capability. The capability descriptor is written by the daemon only after
|
|
8
|
+
* C03 authorization and is read-only for the agent identity; THIS module re-reads and re-verifies it on EVERY request (digest pinned at start, expiry, run/project binding,
|
|
9
|
+
* canonical root), so a revoked, replaced, deleted or expired capability stops working at the next call even though the server process is long-lived. Tool arguments are
|
|
10
|
+
* untrusted: there is no root, project or run argument at all; a relative path is validated lexically, then walked component by component with lstat (no link, no alias),
|
|
11
|
+
* then compared with the physical path, then opened and re-verified by handle identity before AND after the read. Nothing is written to the project. All filesystem work uses
|
|
12
|
+
* real filesystem APIs; no shell, no command is ever built from agent input.
|
|
13
|
+
*
|
|
14
|
+
* Known limit (reported in SW-074): Node cannot open relative to a directory handle, so a directory swapped for a junction between the walk and the open is detected by the
|
|
15
|
+
* post-read identity/realpath re-check, which DISCARDS the content (nothing is returned); it is not prevented at the OS level. Hard-linked files are refused wholesale.
|
|
16
|
+
*/
|
|
17
|
+
export const PR_PROTOCOL = 'my-centcom.project-read/1';
|
|
18
|
+
export const PR_LIMITS = Object.freeze({
|
|
19
|
+
maxPathChars: 260, maxSegments: 32, maxSegmentChars: 120, maxFileBytes: 1_048_576, maxReadBytes: 32_768, defaultReadBytes: 16_384, maxListEntries: 200, defaultListEntries: 100,
|
|
20
|
+
maxRequests: 200, maxTotalResponseBytes: 524_288, maxLifetimeMs: 15 * 60 * 1000, listScanCap: 2_000, maxDescriptorBytes: 8_192,
|
|
21
|
+
});
|
|
22
|
+
export const PR_TOOLS = ['list_project_entries', 'read_project_text', 'get_project_file_metadata'];
|
|
23
|
+
/** SW-080: the proposal tool is separate from the read tools and only exists in a capability that lists it. */
|
|
24
|
+
export const PR_PROPOSE_TOOL = 'propose_change';
|
|
25
|
+
export const PR_CAPABILITY_TOOLS = Object.freeze([...PR_TOOLS, PR_PROPOSE_TOOL]);
|
|
26
|
+
export const PR_MAX_PROPOSALS_PER_CAPABILITY = 3;
|
|
27
|
+
const MESSAGES = Object.freeze({
|
|
28
|
+
CAPABILITY_INVALID: 'the project-read capability is not valid', CAPABILITY_EXPIRED: 'the project-read capability has expired', CAPABILITY_REVOKED: 'the project-read capability was revoked',
|
|
29
|
+
CAPABILITY_MISMATCH: 'the project-read capability does not match this server', PROJECT_ROOT_INVALID: 'the approved project root is no longer valid',
|
|
30
|
+
ARGUMENTS_INVALID: 'the arguments are not valid for this tool', PATH_INVALID: 'the path is not a valid project-relative path', PATH_TRAVERSAL: 'parent-directory segments are not allowed',
|
|
31
|
+
PATH_ABSOLUTE: 'absolute paths are not allowed', PATH_ALTERNATE_SYNTAX: 'this path syntax is not allowed', PATH_DEVICE: 'device names are not allowed', PATH_STREAM: 'stream syntax is not allowed',
|
|
32
|
+
PATH_DENIED_POLICY: 'this path is not available to project read access', PATH_NOT_FOUND: 'no such file or directory', PATH_ESCAPES_ROOT: 'the path resolves outside the approved project',
|
|
33
|
+
PATH_LINK: 'links and aliases are not followed', PATH_HARDLINK: 'hard-linked files are not served', NOT_A_FILE: 'the path is not a regular file', NOT_A_DIRECTORY: 'the path is not a directory',
|
|
34
|
+
FILE_TOO_LARGE: 'the file exceeds the size limit', BINARY_CONTENT: 'the file is not text', INVALID_ENCODING: 'the file is not valid UTF-8', OFFSET_INVALID: 'the offset or length is not on a character boundary',
|
|
35
|
+
FILE_CHANGED_DURING_READ: 'the file changed while it was being read', REQUEST_BUDGET_EXHAUSTED: 'the request budget for this run is exhausted', RESPONSE_BUDGET_EXHAUSTED: 'the response budget for this run is exhausted',
|
|
36
|
+
AUDIT_UNAVAILABLE: 'the audit record cannot be written, so nothing is served', TOOL_UNKNOWN: 'unknown tool', READ_FAILED: 'the read could not be completed',
|
|
37
|
+
PROPOSAL_BUDGET_EXHAUSTED: 'the proposal budget for this run is exhausted', PROPOSAL_DUPLICATE: 'this exact proposal was already submitted', PROPOSAL_WRITE_FAILED: 'the proposal could not be recorded',
|
|
38
|
+
});
|
|
39
|
+
const deny = (code) => ({ ok: false, code, message: MESSAGES[code] ?? 'denied' });
|
|
40
|
+
const WIN = process.platform === 'win32';
|
|
41
|
+
const same = (a, b) => (WIN ? a.toLowerCase() === b.toLowerCase() : a === b);
|
|
42
|
+
const trimSep = (p) => (p.length > 3 ? p.replace(/[\\/]+$/, '') : p);
|
|
43
|
+
const sha256 = (b) => createHash('sha256').update(b).digest('hex');
|
|
44
|
+
// ---------- policy (code, not data: a capability can never widen it) ----------------------------------------------------------------------------
|
|
45
|
+
const DENY_DIRS = new Set(['.git', '.switchyard-data', '.switchyard-dev', '.my-dev-kit', '.my-dev-kit-orchestrator', '.my-dev-kit-workflow', '.my-dev-kit-context', '.ssh', '.aws', '.azure', '.gnupg', '.kube', '.docker', '.codex', '.claude']);
|
|
46
|
+
const DENY_FILES = new Set(['.npmrc', '.netrc', '.pypirc', '.git-credentials', '.htpasswd', 'auth.json', 'credentials', 'credentials.json', 'secrets.json', 'secret.json', 'terraform.tfstate', 'known_hosts']);
|
|
47
|
+
const DENY_NAME_RE = [/^\.env($|\.)/i, /^id_(rsa|dsa|ecdsa|ed25519)/i, /\.(pem|key|pfx|p12|jks|keystore|kdbx|ppk|tfvars)$/i];
|
|
48
|
+
const DEVICE_RE = new RegExp('^(con|prn|aux|nul|conin\\$|conout\\$|clock\\$|com[0-9' + String.fromCharCode(0xb9, 0xb2, 0xb3) + ']|lpt[0-9' + String.fromCharCode(0xb9, 0xb2, 0xb3) + '])$', 'i');
|
|
49
|
+
const BAD_RANGES = [[0x200b, 0x200f], [0x2028, 0x2029], [0x202a, 0x202e], [0x2066, 0x2069], [0xfeff, 0xfeff]];
|
|
50
|
+
const BAD_CHARS = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f' + BAD_RANGES.map(([a, b]) => String.fromCharCode(a) + '-' + String.fromCharCode(b)).join('') + ']');
|
|
51
|
+
const WILDCARD = /[<>"|?*]/;
|
|
52
|
+
function policyDeniesName(name) {
|
|
53
|
+
const l = name.toLowerCase();
|
|
54
|
+
return DENY_DIRS.has(l) || DENY_FILES.has(l) || DENY_NAME_RE.some((re) => re.test(l)) || /^git~\d/i.test(l);
|
|
55
|
+
}
|
|
56
|
+
/** Lexical validation of an agent-supplied relative path. Returns its segments (empty = the project root itself). */
|
|
57
|
+
export function validateRelativePath(p, opts) {
|
|
58
|
+
if (typeof p !== 'string')
|
|
59
|
+
return deny('PATH_INVALID');
|
|
60
|
+
if (p === '' || p === '.')
|
|
61
|
+
return opts.allowRoot ? { ok: true, value: [] } : deny('PATH_INVALID');
|
|
62
|
+
if (p.length > PR_LIMITS.maxPathChars || BAD_CHARS.test(p) || p !== p.trim())
|
|
63
|
+
return deny('PATH_INVALID');
|
|
64
|
+
if (/^[\\/]/.test(p) || /^[A-Za-z]:/.test(p))
|
|
65
|
+
return deny('PATH_ABSOLUTE');
|
|
66
|
+
if (p.includes('\\'))
|
|
67
|
+
return deny('PATH_ALTERNATE_SYNTAX');
|
|
68
|
+
if (p.includes(':'))
|
|
69
|
+
return deny('PATH_STREAM');
|
|
70
|
+
const segs = p.split('/');
|
|
71
|
+
if (segs.length > PR_LIMITS.maxSegments)
|
|
72
|
+
return deny('PATH_INVALID');
|
|
73
|
+
for (const s of segs) {
|
|
74
|
+
if (s === '')
|
|
75
|
+
return deny('PATH_INVALID');
|
|
76
|
+
if (s === '..')
|
|
77
|
+
return deny('PATH_TRAVERSAL');
|
|
78
|
+
if (s === '.')
|
|
79
|
+
return deny('PATH_INVALID');
|
|
80
|
+
if (s.length > PR_LIMITS.maxSegmentChars)
|
|
81
|
+
return deny('PATH_INVALID');
|
|
82
|
+
if (WILDCARD.test(s) || /[. ]$/.test(s))
|
|
83
|
+
return deny('PATH_ALTERNATE_SYNTAX');
|
|
84
|
+
if (DEVICE_RE.test(s.split('.')[0].trimEnd()))
|
|
85
|
+
return deny('PATH_DEVICE');
|
|
86
|
+
if (policyDeniesName(s))
|
|
87
|
+
return deny('PATH_DENIED_POLICY');
|
|
88
|
+
}
|
|
89
|
+
return { ok: true, value: segs };
|
|
90
|
+
}
|
|
91
|
+
const KEYS = ['protocol', 'capabilityId', 'projectId', 'runId', 'grantId', 'canonicalRoot', 'issuedAt', 'expiresAt', 'tools', 'auditRequired', 'limits'];
|
|
92
|
+
const LKEYS = ['maxFileBytes', 'maxReadBytes', 'maxListEntries', 'maxRequests', 'maxTotalResponseBytes'];
|
|
93
|
+
const isoMs = (s) => (typeof s === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/.test(s) ? Date.parse(s) : NaN);
|
|
94
|
+
export function parseCapability(bytes) {
|
|
95
|
+
let o;
|
|
96
|
+
try {
|
|
97
|
+
o = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
if (o === null || typeof o !== 'object' || Array.isArray(o))
|
|
103
|
+
return undefined;
|
|
104
|
+
const r = o;
|
|
105
|
+
const ks = Object.keys(r);
|
|
106
|
+
if (ks.length !== KEYS.length || !KEYS.every((k) => ks.includes(k)))
|
|
107
|
+
return undefined;
|
|
108
|
+
const str = (k, max, re) => typeof r[k] === 'string' && r[k].length > 0 && r[k].length <= max && (re ? re.test(r[k]) : true);
|
|
109
|
+
if (r.protocol !== PR_PROTOCOL || !str('capabilityId', 80, /^cap\.[A-Za-z0-9_-]{16,64}$/) || !str('projectId', 200) || !str('runId', 200) || !str('grantId', 200) || !str('canonicalRoot', 1024))
|
|
110
|
+
return undefined;
|
|
111
|
+
const issued = isoMs(r.issuedAt);
|
|
112
|
+
const expires = isoMs(r.expiresAt);
|
|
113
|
+
if (!(issued > 0) || !(expires > issued) || expires - issued > PR_LIMITS.maxLifetimeMs)
|
|
114
|
+
return undefined;
|
|
115
|
+
if (!Array.isArray(r.tools) || r.tools.length < 1 || r.tools.length > PR_CAPABILITY_TOOLS.length || !r.tools.every((t) => PR_CAPABILITY_TOOLS.includes(t)) || new Set(r.tools).size !== r.tools.length)
|
|
116
|
+
return undefined;
|
|
117
|
+
if (typeof r.auditRequired !== 'boolean')
|
|
118
|
+
return undefined;
|
|
119
|
+
const l = r.limits;
|
|
120
|
+
if (l === null || typeof l !== 'object' || Array.isArray(l) || Object.keys(l).length !== LKEYS.length || !LKEYS.every((k) => Object.keys(l).includes(k)))
|
|
121
|
+
return undefined;
|
|
122
|
+
const lim = (k, max) => Number.isInteger(l[k]) && l[k] > 0 && l[k] <= max;
|
|
123
|
+
if (!lim('maxFileBytes', PR_LIMITS.maxFileBytes) || !lim('maxReadBytes', PR_LIMITS.maxReadBytes) || !lim('maxListEntries', PR_LIMITS.maxListEntries) || !lim('maxRequests', PR_LIMITS.maxRequests) || !lim('maxTotalResponseBytes', PR_LIMITS.maxTotalResponseBytes))
|
|
124
|
+
return undefined;
|
|
125
|
+
return Object.freeze(JSON.parse(JSON.stringify(r)));
|
|
126
|
+
}
|
|
127
|
+
/** Reads a small regular, non-link file fully. Returns undefined for anything else. */
|
|
128
|
+
function readSmallFile(path) {
|
|
129
|
+
try {
|
|
130
|
+
const st = lstatSync(path);
|
|
131
|
+
if (!st.isFile() || st.isSymbolicLink() || st.size < 2 || st.size > PR_LIMITS.maxDescriptorBytes)
|
|
132
|
+
return undefined;
|
|
133
|
+
return readFileSync(path);
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function displayPath(p) {
|
|
140
|
+
// bounded, display-safe, never trusted: only for correlating a refusal in the evidence record
|
|
141
|
+
const s = typeof p === 'string' ? p : JSON.stringify(p) ?? '';
|
|
142
|
+
return s.replace(/[^\x20-\x7e]/g, '?').slice(0, 120);
|
|
143
|
+
}
|
|
144
|
+
const idOf = (st) => `${st.dev.toString(16)}:${st.ino.toString(16)}`;
|
|
145
|
+
/** Walks root + segments with lstat per component. No link, no alias, no nested repository, then compares with the physical path. */
|
|
146
|
+
export function walkProjectPath(root, segs, want) {
|
|
147
|
+
let cur = root;
|
|
148
|
+
let st;
|
|
149
|
+
try {
|
|
150
|
+
for (let i = 0; i < segs.length; i += 1) {
|
|
151
|
+
cur = join(cur, segs[i]);
|
|
152
|
+
st = lstatSync(cur, { bigint: true });
|
|
153
|
+
if (st.isSymbolicLink())
|
|
154
|
+
return deny('PATH_LINK');
|
|
155
|
+
const last = i === segs.length - 1;
|
|
156
|
+
if (!last && !st.isDirectory())
|
|
157
|
+
return deny('PATH_INVALID');
|
|
158
|
+
// a directory that is itself a Git worktree root below the approved project is an unrelated/nested repository
|
|
159
|
+
if (st.isDirectory()) {
|
|
160
|
+
try {
|
|
161
|
+
lstatSync(join(cur, '.git'));
|
|
162
|
+
return deny('PATH_DENIED_POLICY');
|
|
163
|
+
}
|
|
164
|
+
catch { /* no nested repository */ }
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (segs.length === 0)
|
|
168
|
+
st = lstatSync(cur, { bigint: true });
|
|
169
|
+
}
|
|
170
|
+
catch (e) {
|
|
171
|
+
return deny(e.code === 'ENOENT' || e.code === 'ENOTDIR' ? 'PATH_NOT_FOUND' : 'READ_FAILED');
|
|
172
|
+
}
|
|
173
|
+
if (!st)
|
|
174
|
+
return deny('READ_FAILED');
|
|
175
|
+
let phys;
|
|
176
|
+
try {
|
|
177
|
+
phys = trimSep(realpathSync.native(cur));
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return deny('PATH_NOT_FOUND');
|
|
181
|
+
}
|
|
182
|
+
const prefix = root + sep;
|
|
183
|
+
if (!(same(phys, root) || (WIN ? phys.toLowerCase().startsWith(prefix.toLowerCase()) : phys.startsWith(prefix))))
|
|
184
|
+
return deny('PATH_ESCAPES_ROOT');
|
|
185
|
+
if (!same(phys, cur))
|
|
186
|
+
return deny('PATH_LINK'); // junction, 8.3 short name, reparse point or any alias that resolves elsewhere
|
|
187
|
+
if (want === 'file') {
|
|
188
|
+
if (!st.isFile())
|
|
189
|
+
return deny('NOT_A_FILE');
|
|
190
|
+
if (st.nlink > 1n)
|
|
191
|
+
return deny('PATH_HARDLINK');
|
|
192
|
+
}
|
|
193
|
+
else if (!st.isDirectory())
|
|
194
|
+
return deny('NOT_A_DIRECTORY');
|
|
195
|
+
return { ok: true, value: { kind: want, path: cur, ino: idOf(st) } };
|
|
196
|
+
}
|
|
197
|
+
export function readProjectFileWhole(node, root, segs, maxBytes) {
|
|
198
|
+
let fd;
|
|
199
|
+
try {
|
|
200
|
+
fd = openSync(node.path, 'r');
|
|
201
|
+
const st = fstatSync(fd, { bigint: true });
|
|
202
|
+
if (!st.isFile() || idOf(st) !== node.ino)
|
|
203
|
+
return deny('FILE_CHANGED_DURING_READ');
|
|
204
|
+
if (st.nlink > 1n)
|
|
205
|
+
return deny('PATH_HARDLINK');
|
|
206
|
+
if (st.size > BigInt(maxBytes))
|
|
207
|
+
return deny('FILE_TOO_LARGE');
|
|
208
|
+
const size = Number(st.size);
|
|
209
|
+
const buf = Buffer.allocUnsafe(size + 1);
|
|
210
|
+
let n = 0;
|
|
211
|
+
for (;;) {
|
|
212
|
+
const k = readSync(fd, buf, n, buf.length - n, n);
|
|
213
|
+
if (k === 0)
|
|
214
|
+
break;
|
|
215
|
+
n += k;
|
|
216
|
+
if (n > size)
|
|
217
|
+
break;
|
|
218
|
+
}
|
|
219
|
+
if (n !== size)
|
|
220
|
+
return deny('FILE_CHANGED_DURING_READ'); // grew or shrank while being read
|
|
221
|
+
const st2 = fstatSync(fd, { bigint: true });
|
|
222
|
+
if (st2.size !== st.size || st2.mtimeNs !== st.mtimeNs || idOf(st2) !== node.ino)
|
|
223
|
+
return deny('FILE_CHANGED_DURING_READ');
|
|
224
|
+
closeSync(fd);
|
|
225
|
+
fd = undefined;
|
|
226
|
+
// post-read: the same path must still resolve to the same physical object inside the root (detects a directory swapped for a junction mid-read)
|
|
227
|
+
const again = walkProjectPath(root, segs, 'file');
|
|
228
|
+
if (!again.ok)
|
|
229
|
+
return again.code === 'PATH_NOT_FOUND' ? deny('FILE_CHANGED_DURING_READ') : again;
|
|
230
|
+
if (again.value.ino !== node.ino)
|
|
231
|
+
return deny('FILE_CHANGED_DURING_READ');
|
|
232
|
+
return { ok: true, value: { bytes: buf.subarray(0, size), ino: node.ino, mtimeMs: Number(st.mtimeNs / 1000000n) } };
|
|
233
|
+
}
|
|
234
|
+
catch (e) {
|
|
235
|
+
const c = e.code;
|
|
236
|
+
return deny(c === 'ENOENT' ? 'PATH_NOT_FOUND' : 'READ_FAILED');
|
|
237
|
+
}
|
|
238
|
+
finally {
|
|
239
|
+
if (fd !== undefined) {
|
|
240
|
+
try {
|
|
241
|
+
closeSync(fd);
|
|
242
|
+
}
|
|
243
|
+
catch { /* closed */ }
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
export function createProjectReadService(cfg) {
|
|
248
|
+
const now = cfg.now ?? Date.now;
|
|
249
|
+
const first = readSmallFile(cfg.capabilityPath);
|
|
250
|
+
if (!first)
|
|
251
|
+
return deny('CAPABILITY_INVALID');
|
|
252
|
+
const parsedCap = parseCapability(first);
|
|
253
|
+
if (!parsedCap)
|
|
254
|
+
return deny('CAPABILITY_INVALID');
|
|
255
|
+
const cap = parsedCap;
|
|
256
|
+
if (cap.auditRequired && !cfg.auditPath)
|
|
257
|
+
return deny('AUDIT_UNAVAILABLE'); // evidence before disclosure: a capability that demands an audit never runs without one
|
|
258
|
+
if (cfg.expect?.runId !== undefined && cfg.expect.runId !== cap.runId)
|
|
259
|
+
return deny('CAPABILITY_MISMATCH');
|
|
260
|
+
if (cfg.expect?.projectId !== undefined && cfg.expect.projectId !== cap.projectId)
|
|
261
|
+
return deny('CAPABILITY_MISMATCH');
|
|
262
|
+
const pinned = sha256(first);
|
|
263
|
+
let requests = 0;
|
|
264
|
+
let responseBytes = 0;
|
|
265
|
+
let seq = 0;
|
|
266
|
+
let proposals = 0;
|
|
267
|
+
let prev = sha256(`genesis:${cap.capabilityId}`);
|
|
268
|
+
// A restarted server continues the SAME hash chain: the last complete record is read back, and a final fragment left by a killed process is cut off (it was never a record).
|
|
269
|
+
if (cfg.auditPath && existsSync(cfg.auditPath)) {
|
|
270
|
+
try {
|
|
271
|
+
if (statSync(cfg.auditPath).size > 4 * 1024 * 1024)
|
|
272
|
+
return deny('READ_FAILED');
|
|
273
|
+
const text = readFileSync(cfg.auditPath, 'utf8');
|
|
274
|
+
const cut = text.lastIndexOf('\n') + 1;
|
|
275
|
+
if (cut < text.length)
|
|
276
|
+
truncateSync(cfg.auditPath, Buffer.byteLength(text.slice(0, cut), 'utf8'));
|
|
277
|
+
const lines = text.slice(0, cut).split('\n').filter((l) => l.length > 0);
|
|
278
|
+
if (lines.length > 0) {
|
|
279
|
+
const last = JSON.parse(lines[lines.length - 1]);
|
|
280
|
+
prev = sha256(lines[lines.length - 1]);
|
|
281
|
+
seq = Number(last.seq) + 1;
|
|
282
|
+
if (!Number.isInteger(seq))
|
|
283
|
+
return deny('READ_FAILED');
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
return deny('READ_FAILED');
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
const audit = (r) => {
|
|
291
|
+
if (!cfg.auditPath)
|
|
292
|
+
return true;
|
|
293
|
+
const rec = { v: 1, seq, at: new Date(now()).toISOString(), runId: cap.runId, projectId: cap.projectId, capabilityId: cap.capabilityId, ...r, prev };
|
|
294
|
+
const line = JSON.stringify(rec);
|
|
295
|
+
try {
|
|
296
|
+
appendFileSync(cfg.auditPath, line + '\n', { encoding: 'utf8', flag: 'a' });
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
return false;
|
|
300
|
+
}
|
|
301
|
+
prev = sha256(line);
|
|
302
|
+
seq += 1;
|
|
303
|
+
return true;
|
|
304
|
+
};
|
|
305
|
+
/** Per-request authority check. Returns the canonical root on success. */
|
|
306
|
+
function authorize() {
|
|
307
|
+
const bytes = readSmallFile(cfg.capabilityPath);
|
|
308
|
+
if (!bytes)
|
|
309
|
+
return deny('CAPABILITY_REVOKED');
|
|
310
|
+
if (sha256(bytes) !== pinned)
|
|
311
|
+
return deny('CAPABILITY_REVOKED');
|
|
312
|
+
if (!(now() < Date.parse(cap.expiresAt)))
|
|
313
|
+
return deny('CAPABILITY_EXPIRED');
|
|
314
|
+
if (now() < Date.parse(cap.issuedAt) - 60_000)
|
|
315
|
+
return deny('CAPABILITY_INVALID');
|
|
316
|
+
try {
|
|
317
|
+
const st = lstatSync(cap.canonicalRoot);
|
|
318
|
+
if (!st.isDirectory() || st.isSymbolicLink() || !same(trimSep(realpathSync.native(cap.canonicalRoot)), trimSep(cap.canonicalRoot)))
|
|
319
|
+
return deny('PROJECT_ROOT_INVALID');
|
|
320
|
+
}
|
|
321
|
+
catch {
|
|
322
|
+
return deny('PROJECT_ROOT_INVALID');
|
|
323
|
+
}
|
|
324
|
+
return { ok: true, value: trimSep(cap.canonicalRoot) };
|
|
325
|
+
}
|
|
326
|
+
const FATAL = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
327
|
+
function textCheck(b) {
|
|
328
|
+
for (let i = 0; i < b.length; i += 1) {
|
|
329
|
+
const c = b[i];
|
|
330
|
+
if (c === 0 || (c < 0x20 && c !== 0x09 && c !== 0x0a && c !== 0x0c && c !== 0x0d))
|
|
331
|
+
return 'BINARY_CONTENT';
|
|
332
|
+
}
|
|
333
|
+
try {
|
|
334
|
+
FATAL.decode(b);
|
|
335
|
+
return 'OK';
|
|
336
|
+
}
|
|
337
|
+
catch {
|
|
338
|
+
return 'INVALID_ENCODING';
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
const isCont = (b) => (b & 0xc0) === 0x80;
|
|
342
|
+
const prov = () => ({ protocol: PR_PROTOCOL, projectId: cap.projectId, runId: cap.runId, capabilityId: cap.capabilityId, observedAt: new Date(now()).toISOString() });
|
|
343
|
+
function ownKeys(a, allowed, required) {
|
|
344
|
+
if (a === null || typeof a !== 'object' || Array.isArray(a))
|
|
345
|
+
return false;
|
|
346
|
+
const proto = Object.getPrototypeOf(a);
|
|
347
|
+
if (proto !== Object.prototype && proto !== null)
|
|
348
|
+
return false;
|
|
349
|
+
const ks = Object.keys(a);
|
|
350
|
+
return ks.every((k) => allowed.includes(k)) && required.every((k) => ks.includes(k));
|
|
351
|
+
}
|
|
352
|
+
const intIn = (v, lo, hi) => typeof v === 'number' && Number.isInteger(v) && v >= lo && v <= hi;
|
|
353
|
+
function run(tool, args, root) {
|
|
354
|
+
const meta = {};
|
|
355
|
+
const L = cap.limits;
|
|
356
|
+
if (tool === 'list_project_entries') {
|
|
357
|
+
if (!ownKeys(args, ['path', 'limit'], []))
|
|
358
|
+
return { r: deny('ARGUMENTS_INVALID'), meta };
|
|
359
|
+
if (args.path !== undefined && typeof args.path !== 'string')
|
|
360
|
+
return { r: deny('ARGUMENTS_INVALID'), meta };
|
|
361
|
+
if (args.limit !== undefined && !intIn(args.limit, 1, Math.min(L.maxListEntries, PR_LIMITS.maxListEntries)))
|
|
362
|
+
return { r: deny('ARGUMENTS_INVALID'), meta };
|
|
363
|
+
const rel = args.path ?? '.';
|
|
364
|
+
meta.pathSha256 = sha256(rel);
|
|
365
|
+
meta.pathDisplay = displayPath(rel);
|
|
366
|
+
const segs = validateRelativePath(rel, { allowRoot: true });
|
|
367
|
+
if (!segs.ok)
|
|
368
|
+
return { r: segs, meta };
|
|
369
|
+
const dir = walkProjectPath(root, segs.value, 'directory');
|
|
370
|
+
if (!dir.ok)
|
|
371
|
+
return { r: dir, meta };
|
|
372
|
+
const limit = args.limit ?? Math.min(PR_LIMITS.defaultListEntries, L.maxListEntries);
|
|
373
|
+
const found = [];
|
|
374
|
+
let omitted = 0;
|
|
375
|
+
let scanned = 0;
|
|
376
|
+
let more = false;
|
|
377
|
+
let d;
|
|
378
|
+
try {
|
|
379
|
+
d = opendirSync(dir.value.path);
|
|
380
|
+
}
|
|
381
|
+
catch {
|
|
382
|
+
return { r: deny('READ_FAILED'), meta };
|
|
383
|
+
}
|
|
384
|
+
try {
|
|
385
|
+
for (;;) {
|
|
386
|
+
const ent = d.readSync();
|
|
387
|
+
if (!ent)
|
|
388
|
+
break;
|
|
389
|
+
scanned += 1;
|
|
390
|
+
if (scanned > PR_LIMITS.listScanCap) {
|
|
391
|
+
more = true;
|
|
392
|
+
break;
|
|
393
|
+
}
|
|
394
|
+
const name = ent.name;
|
|
395
|
+
if (BAD_CHARS.test(name) || policyDeniesName(name) || WILDCARD.test(name) || /[. ]$/.test(name) || DEVICE_RE.test(name.split('.')[0].trimEnd())) {
|
|
396
|
+
omitted += 1;
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
let st;
|
|
400
|
+
try {
|
|
401
|
+
st = lstatSync(join(dir.value.path, name), { bigint: true });
|
|
402
|
+
}
|
|
403
|
+
catch {
|
|
404
|
+
omitted += 1;
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
407
|
+
if (st.isSymbolicLink() || !(st.isFile() || st.isDirectory())) {
|
|
408
|
+
omitted += 1;
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
if (st.isDirectory()) {
|
|
412
|
+
try {
|
|
413
|
+
lstatSync(join(dir.value.path, name, '.git'));
|
|
414
|
+
omitted += 1;
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
catch { /* not a nested repository */ }
|
|
418
|
+
}
|
|
419
|
+
if (st.isFile() && st.nlink > 1n) {
|
|
420
|
+
omitted += 1;
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
found.push({ name, kind: st.isDirectory() ? 'directory' : 'file', sizeBytes: st.isFile() ? Number(st.size) : null });
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
finally {
|
|
427
|
+
try {
|
|
428
|
+
d.closeSync();
|
|
429
|
+
}
|
|
430
|
+
catch { /* closed */ }
|
|
431
|
+
}
|
|
432
|
+
found.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
433
|
+
const truncated = more || found.length > limit;
|
|
434
|
+
return { r: { ok: true, value: { provenance: prov(), path: segs.value.length === 0 ? '.' : segs.value.join('/'), entries: found.slice(0, limit), truncated, omittedByPolicy: omitted } }, meta };
|
|
435
|
+
}
|
|
436
|
+
if (tool === 'read_project_text') {
|
|
437
|
+
if (!ownKeys(args, ['path', 'offset', 'max_bytes'], ['path']))
|
|
438
|
+
return { r: deny('ARGUMENTS_INVALID'), meta };
|
|
439
|
+
if (typeof args.path !== 'string')
|
|
440
|
+
return { r: deny('ARGUMENTS_INVALID'), meta };
|
|
441
|
+
if (args.offset !== undefined && !intIn(args.offset, 0, PR_LIMITS.maxFileBytes))
|
|
442
|
+
return { r: deny('ARGUMENTS_INVALID'), meta };
|
|
443
|
+
if (args.max_bytes !== undefined && !intIn(args.max_bytes, 1, Math.min(L.maxReadBytes, PR_LIMITS.maxReadBytes)))
|
|
444
|
+
return { r: deny('ARGUMENTS_INVALID'), meta };
|
|
445
|
+
meta.pathSha256 = sha256(args.path);
|
|
446
|
+
meta.pathDisplay = displayPath(args.path);
|
|
447
|
+
const segs = validateRelativePath(args.path, { allowRoot: false });
|
|
448
|
+
if (!segs.ok)
|
|
449
|
+
return { r: segs, meta };
|
|
450
|
+
const node = walkProjectPath(root, segs.value, 'file');
|
|
451
|
+
if (!node.ok)
|
|
452
|
+
return { r: node, meta };
|
|
453
|
+
const whole = readProjectFileWhole(node.value, root, segs.value, Math.min(L.maxFileBytes, PR_LIMITS.maxFileBytes));
|
|
454
|
+
if (!whole.ok)
|
|
455
|
+
return { r: whole, meta };
|
|
456
|
+
const bytes = whole.value.bytes;
|
|
457
|
+
const tc = textCheck(bytes);
|
|
458
|
+
if (tc !== 'OK')
|
|
459
|
+
return { r: deny(tc), meta };
|
|
460
|
+
const offset = args.offset ?? 0;
|
|
461
|
+
if (offset > bytes.length || (offset < bytes.length && isCont(bytes[offset])))
|
|
462
|
+
return { r: deny('OFFSET_INVALID'), meta };
|
|
463
|
+
let end = Math.min(bytes.length, offset + (args.max_bytes ?? Math.min(PR_LIMITS.defaultReadBytes, L.maxReadBytes)));
|
|
464
|
+
while (end < bytes.length && end > offset && isCont(bytes[end]))
|
|
465
|
+
end -= 1;
|
|
466
|
+
if (end === offset && offset < bytes.length)
|
|
467
|
+
return { r: deny('OFFSET_INVALID'), meta };
|
|
468
|
+
const slice = bytes.subarray(offset, end);
|
|
469
|
+
const fileSha = sha256(bytes);
|
|
470
|
+
const sliceSha = sha256(slice);
|
|
471
|
+
meta.fileSha256 = fileSha;
|
|
472
|
+
meta.returnedSha256 = sliceSha;
|
|
473
|
+
meta.returnedBytes = slice.length;
|
|
474
|
+
meta.offset = offset;
|
|
475
|
+
return { r: { ok: true, value: {
|
|
476
|
+
provenance: prov(), path: segs.value.join('/'), encoding: 'utf-8', offset, returnedBytes: slice.length, nextOffset: end < bytes.length ? end : null, fileSizeBytes: bytes.length,
|
|
477
|
+
fileSha256: fileSha, returnedSha256: sliceSha, fileIdentity: whole.value.ino, truncated: end < bytes.length, text: new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(slice),
|
|
478
|
+
} }, meta };
|
|
479
|
+
}
|
|
480
|
+
if (tool === 'get_project_file_metadata') {
|
|
481
|
+
if (!ownKeys(args, ['path'], ['path']) || typeof args.path !== 'string')
|
|
482
|
+
return { r: deny('ARGUMENTS_INVALID'), meta };
|
|
483
|
+
meta.pathSha256 = sha256(args.path);
|
|
484
|
+
meta.pathDisplay = displayPath(args.path);
|
|
485
|
+
const segs = validateRelativePath(args.path, { allowRoot: false });
|
|
486
|
+
if (!segs.ok)
|
|
487
|
+
return { r: segs, meta };
|
|
488
|
+
const node = walkProjectPath(root, segs.value, 'file');
|
|
489
|
+
if (!node.ok)
|
|
490
|
+
return { r: node, meta };
|
|
491
|
+
const whole = readProjectFileWhole(node.value, root, segs.value, Math.min(L.maxFileBytes, PR_LIMITS.maxFileBytes));
|
|
492
|
+
if (!whole.ok)
|
|
493
|
+
return { r: whole, meta };
|
|
494
|
+
const fileSha = sha256(whole.value.bytes);
|
|
495
|
+
meta.fileSha256 = fileSha;
|
|
496
|
+
return { r: { ok: true, value: {
|
|
497
|
+
provenance: prov(), path: segs.value.join('/'), sizeBytes: whole.value.bytes.length, sha256: fileSha, fileIdentity: whole.value.ino,
|
|
498
|
+
modifiedAt: new Date(whole.value.mtimeMs).toISOString(), looksLikeText: textCheck(whole.value.bytes) === 'OK',
|
|
499
|
+
} }, meta };
|
|
500
|
+
}
|
|
501
|
+
if (tool === PR_PROPOSE_TOOL) {
|
|
502
|
+
const pc = cfg.propose;
|
|
503
|
+
if (!pc)
|
|
504
|
+
return { r: deny('TOOL_UNKNOWN'), meta };
|
|
505
|
+
meta.pathDisplay = 'proposal';
|
|
506
|
+
if (proposals >= PR_MAX_PROPOSALS_PER_CAPABILITY)
|
|
507
|
+
return { r: deny('PROPOSAL_BUDGET_EXHAUSTED'), meta };
|
|
508
|
+
const v = pc.validate(args, root);
|
|
509
|
+
if (!v.ok)
|
|
510
|
+
return { r: { ok: false, code: v.code, message: v.message }, meta };
|
|
511
|
+
meta.returnedSha256 = v.digest;
|
|
512
|
+
meta.returnedBytes = Buffer.byteLength(v.canonicalJson, 'utf8');
|
|
513
|
+
const envelope = JSON.stringify({ schema: 'my-centcom.proposal-envelope/1', capabilityId: cap.capabilityId, runId: cap.runId, projectId: cap.projectId, digest: v.digest, canonicalJson: v.canonicalJson, submittedAt: new Date(now()).toISOString() });
|
|
514
|
+
const rec = pc.record(cap.capabilityId + '.' + v.digest.slice(0, 16) + '.proposal.json', envelope);
|
|
515
|
+
if (rec !== 'OK')
|
|
516
|
+
return { r: deny(rec === 'EXISTS' ? 'PROPOSAL_DUPLICATE' : 'PROPOSAL_WRITE_FAILED'), meta };
|
|
517
|
+
proposals += 1;
|
|
518
|
+
return { r: { ok: true, value: { provenance: prov(), accepted: true, digest: v.digest, effect: v.effect, notice: 'Recorded. The project has NOT been modified. A person must review and approve this exact proposal before anything is applied.' } }, meta };
|
|
519
|
+
}
|
|
520
|
+
return { r: deny('TOOL_UNKNOWN'), meta };
|
|
521
|
+
}
|
|
522
|
+
if (!audit({ event: 'SERVER_START' }))
|
|
523
|
+
return deny('READ_FAILED');
|
|
524
|
+
return {
|
|
525
|
+
ok: true,
|
|
526
|
+
value: Object.freeze({
|
|
527
|
+
capabilityId: cap.capabilityId,
|
|
528
|
+
tools: Object.freeze([...cap.tools]),
|
|
529
|
+
call(tool, args) {
|
|
530
|
+
let outcome;
|
|
531
|
+
let meta = {};
|
|
532
|
+
try {
|
|
533
|
+
requests += 1;
|
|
534
|
+
if (typeof tool !== 'string' || !PR_CAPABILITY_TOOLS.includes(tool))
|
|
535
|
+
outcome = deny('TOOL_UNKNOWN');
|
|
536
|
+
else if (requests > Math.min(cap.limits.maxRequests, PR_LIMITS.maxRequests))
|
|
537
|
+
outcome = deny('REQUEST_BUDGET_EXHAUSTED');
|
|
538
|
+
else {
|
|
539
|
+
const a = authorize();
|
|
540
|
+
if (!a.ok)
|
|
541
|
+
outcome = a;
|
|
542
|
+
else if (!cap.tools.includes(tool))
|
|
543
|
+
outcome = deny('TOOL_UNKNOWN');
|
|
544
|
+
else {
|
|
545
|
+
const x = run(tool, args, a.value);
|
|
546
|
+
outcome = x.r;
|
|
547
|
+
meta = x.meta;
|
|
548
|
+
// SW-075: authorization is re-checked AFTER the read and BEFORE anything is returned. A capability revoked or expired while the read was in flight yields NO content
|
|
549
|
+
// (the audit records a DENIED call, never an ALLOWED one). Revocation is therefore not only 'at the next request': it also cancels the response of a request that has not yet completed.
|
|
550
|
+
if (outcome.ok) {
|
|
551
|
+
const still = authorize();
|
|
552
|
+
if (!still.ok) {
|
|
553
|
+
outcome = still;
|
|
554
|
+
meta = { pathSha256: meta.pathSha256, pathDisplay: meta.pathDisplay };
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
if (outcome.ok) {
|
|
558
|
+
const size = Buffer.byteLength(JSON.stringify(outcome.value), 'utf8');
|
|
559
|
+
if (responseBytes + size > Math.min(cap.limits.maxTotalResponseBytes, PR_LIMITS.maxTotalResponseBytes)) {
|
|
560
|
+
outcome = deny('RESPONSE_BUDGET_EXHAUSTED');
|
|
561
|
+
meta = { pathSha256: meta.pathSha256, pathDisplay: meta.pathDisplay };
|
|
562
|
+
}
|
|
563
|
+
else
|
|
564
|
+
responseBytes += size;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
catch {
|
|
570
|
+
outcome = deny('READ_FAILED');
|
|
571
|
+
}
|
|
572
|
+
// Evidence BEFORE disclosure: if the record cannot be written, nothing is returned.
|
|
573
|
+
const wrote = audit({ event: 'TOOL_CALL', tool: typeof tool === 'string' ? tool.slice(0, 64) : 'INVALID', decision: outcome.ok ? 'ALLOWED' : 'DENIED', ...(outcome.ok ? {} : { code: outcome.code }), ...meta });
|
|
574
|
+
return wrote ? outcome : deny('READ_FAILED');
|
|
575
|
+
},
|
|
576
|
+
stop() { audit({ event: 'SERVER_STOP' }); },
|
|
577
|
+
}),
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Independent verification of an audit log (daemon or test side). Chain integrity is recomputed from the text; allowed reads are matched to ground truth computed WITHOUT the
|
|
582
|
+
* model; "the token came from a tool result" is proven only when an ALLOWED read of the expected path returned a slice whose digest equals the digest of that range of the
|
|
583
|
+
* independently known file bytes and the token lies inside that range, and the token was never in the prompt. The answer text alone proves nothing.
|
|
584
|
+
*/
|
|
585
|
+
export function assessProjectReadAudit(i) {
|
|
586
|
+
const terminated = i.auditText.slice(0, i.auditText.lastIndexOf('\n') + 1); // an unterminated final fragment (killed mid-append) was never a record
|
|
587
|
+
const lines = terminated.split('\n').filter((l) => l.length > 0);
|
|
588
|
+
let prev = sha256(`genesis:${i.capabilityId}`);
|
|
589
|
+
let intact = true;
|
|
590
|
+
let n = 0;
|
|
591
|
+
const recs = [];
|
|
592
|
+
for (const line of lines) {
|
|
593
|
+
let r;
|
|
594
|
+
try {
|
|
595
|
+
r = JSON.parse(line);
|
|
596
|
+
}
|
|
597
|
+
catch {
|
|
598
|
+
intact = false;
|
|
599
|
+
break;
|
|
600
|
+
}
|
|
601
|
+
if (r.prev !== prev || r.seq !== n || r.capabilityId !== i.capabilityId || r.v !== 1) {
|
|
602
|
+
intact = false;
|
|
603
|
+
break;
|
|
604
|
+
}
|
|
605
|
+
prev = sha256(line);
|
|
606
|
+
n += 1;
|
|
607
|
+
recs.push(r);
|
|
608
|
+
}
|
|
609
|
+
const calls = recs.filter((r) => r.event === 'TOOL_CALL');
|
|
610
|
+
const refusals = calls.filter((r) => r.decision === 'DENIED');
|
|
611
|
+
const out = { chainIntact: intact, records: recs.length, allowedReads: 0, refusals: refusals.length, refusalCodes: [...new Set(refusals.map((r) => String(r.code)))].sort(), verifiedRead: false, tokenInToolResult: false,
|
|
612
|
+
tokenInPrompt: i.groundTruth !== undefined && typeof i.promptText === 'string' ? i.promptText.includes(i.groundTruth.token) : false };
|
|
613
|
+
const reads = calls.filter((r) => r.tool === 'read_project_text' && r.decision === 'ALLOWED');
|
|
614
|
+
out.allowedReads = reads.length;
|
|
615
|
+
if (!intact)
|
|
616
|
+
return { ...out, verdict: 'NOT_PROVEN_AUDIT_UNTRUSTED' };
|
|
617
|
+
if (!i.groundTruth)
|
|
618
|
+
return { ...out, verdict: reads.length > 0 ? 'TOOL_PROVEN' : 'NOT_PROVEN_NO_TOOL_READ' };
|
|
619
|
+
const gt = i.groundTruth;
|
|
620
|
+
const whole = Buffer.from(gt.fileBytes);
|
|
621
|
+
const pSha = sha256(gt.relativePath);
|
|
622
|
+
const fSha = sha256(whole);
|
|
623
|
+
const tokenAt = whole.indexOf(Buffer.from(gt.token, 'utf8'));
|
|
624
|
+
let sawPath = false;
|
|
625
|
+
let mismatch = false;
|
|
626
|
+
for (const r of reads) {
|
|
627
|
+
if (r.pathSha256 !== pSha)
|
|
628
|
+
continue;
|
|
629
|
+
sawPath = true;
|
|
630
|
+
if (r.fileSha256 !== fSha) {
|
|
631
|
+
mismatch = true;
|
|
632
|
+
continue;
|
|
633
|
+
}
|
|
634
|
+
const off = Number(r.offset);
|
|
635
|
+
const len = Number(r.returnedBytes);
|
|
636
|
+
if (!Number.isInteger(off) || !Number.isInteger(len) || sha256(whole.subarray(off, off + len)) !== r.returnedSha256) {
|
|
637
|
+
mismatch = true;
|
|
638
|
+
continue;
|
|
639
|
+
}
|
|
640
|
+
out.verifiedRead = true;
|
|
641
|
+
if (tokenAt >= off && tokenAt + Buffer.byteLength(gt.token) <= off + len)
|
|
642
|
+
out.tokenInToolResult = true;
|
|
643
|
+
}
|
|
644
|
+
if (out.tokenInPrompt)
|
|
645
|
+
return { ...out, verdict: 'NOT_PROVEN_TOKEN_IN_PROMPT' };
|
|
646
|
+
if (!sawPath)
|
|
647
|
+
return { ...out, verdict: 'NOT_PROVEN_NO_TOOL_READ' };
|
|
648
|
+
if (!out.tokenInToolResult)
|
|
649
|
+
return { ...out, verdict: mismatch ? 'NOT_PROVEN_DIGEST_MISMATCH' : 'NOT_PROVEN_NO_TOOL_READ' };
|
|
650
|
+
return { ...out, verdict: 'TOOL_PROVEN' };
|
|
651
|
+
}
|
|
652
|
+
//# sourceMappingURL=projectReadService.js.map
|