@tnunamak/dalan 0.0.0-stage → 0.5.2
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/CHANGELOG.md +172 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +339 -0
- package/README.md +348 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +38 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +755 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/connect-chatgpt.md +78 -0
- package/docs/connection-longevity.md +37 -0
- package/docs/dalan-upgrade.md +242 -0
- package/docs/deadman.md +59 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +39 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +98 -0
- package/docs/operations.md +751 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +109 -0
- package/docs/pr-head-reviewer.md +54 -0
- package/docs/pr-preflight.md +26 -0
- package/docs/pull-workers.md +97 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +166 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +49 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +439 -0
- package/docs/worker-clients.md +285 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +65 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +412 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +497 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +172 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-slot.mjs +53 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +70 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1340 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3057 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +451 -0
- package/src/try-command.mjs +11 -0
- package/src/try.mjs +589 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +622 -0
- package/src/workspace.mjs +1058 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
import { defaultPath } from './paths.mjs';
|
|
2
|
+
import { secretContent, hasSecretContent, hasCredentialHints, registerSecret, registeredSecrets } from './redaction.mjs';
|
|
3
|
+
import {gitEnv} from './git-env.mjs';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { spawnSync } from 'node:child_process';
|
|
8
|
+
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
9
|
+
import { assignmentInput, prepareGithubRepo } from './projects.mjs';
|
|
10
|
+
import { firstSegment, laterSegment, readablePath, hasRouterSyntax } from './path-syntax.mjs';
|
|
11
|
+
|
|
12
|
+
const infrastructureError=message=>Object.assign(new Error(message),{code:'DOT_BRIDGE_INFRASTRUCTURE'});
|
|
13
|
+
export const submissionLimits = Object.freeze({brief:16384,instructions:24576,note:4096,notes:16384});
|
|
14
|
+
function bytes(value) { return Buffer.byteLength(value,'utf8'); }
|
|
15
|
+
// What the worker is told besides the brief: the instruction total that submissionLimits.instructions caps.
|
|
16
|
+
export const instructionBytes=r=>bytes(r.brief)+bytes(r.expected_output)+bytes(r.execution_scope||'')+bytes(typeof r.scope_text==='string'?r.scope_text:'')+bytes((r.scope_paths||[]).join('\n'))+bytes((Array.isArray(r.output_paths)?r.output_paths:[]).join('\n'));
|
|
17
|
+
// Tree paths a mistyped path may have meant: the same file name elsewhere, or a path within a small edit distance.
|
|
18
|
+
export function nearestPaths(target,files,limit=3) {
|
|
19
|
+
const edit=(a,b)=>{ let prev=Array.from({length:b.length+1},(_,i)=>i); for(let i=1;i<=a.length;i++) { const row=[i]; for(let j=1;j<=b.length;j++) row[j]=Math.min(prev[j]+1,row[j-1]+1,prev[j-1]+(a[i-1]===b[j-1]?0:1)); prev=row; } return prev[b.length]; };
|
|
20
|
+
const base=target.split('/').pop(), max=Math.max(2,Math.floor(target.length*0.12));
|
|
21
|
+
const dirs=new Set();for(const f of files) for(let i=f.indexOf('/');i>0;i=f.indexOf('/',i+1)) dirs.add(f.slice(0,i));
|
|
22
|
+
const scored=[];
|
|
23
|
+
for(const f of [...files,...dirs]) {
|
|
24
|
+
if(Math.abs(f.length-target.length)>max+3) continue;
|
|
25
|
+
const d=edit(target,f);
|
|
26
|
+
if(d<=max) scored.push([d,f]); else if(f.split('/').pop()===base) scored.push([max+1,f]);
|
|
27
|
+
}
|
|
28
|
+
return scored.sort((x,y)=>x[0]-y[0]||x[1].localeCompare(y[1])).slice(0,limit).map(x=>x[1]);
|
|
29
|
+
}
|
|
30
|
+
function cap(value,limit,label) {
|
|
31
|
+
if(typeof value!=='string') throw new Error(`invalid ${label}`);
|
|
32
|
+
const measured=bytes(value);
|
|
33
|
+
if(measured>limit) throw new Error(`${label}: ${measured} UTF-8 bytes exceeds ${limit}; cut at least ${measured-limit} bytes`);
|
|
34
|
+
return measured;
|
|
35
|
+
}
|
|
36
|
+
export function validateOwnerNote(text,existingNotes=[]) {
|
|
37
|
+
if(!text) throw new Error('invalid note text');
|
|
38
|
+
const measured=cap(text,submissionLimits.note,'owner note');
|
|
39
|
+
const total=existingNotes.reduce((sum,n)=>sum+bytes(n.text),measured);
|
|
40
|
+
if(total>submissionLimits.notes) throw new Error(`aggregate owner notes: ${total} UTF-8 bytes exceeds ${submissionLimits.notes}; cut at least ${total-submissionLimits.notes} bytes`);
|
|
41
|
+
}
|
|
42
|
+
// Brackets and parentheses are allowed only as whole router segments (`[id]`, `[...slug]`, `(group)`, `(.)x`; src/path-syntax.mjs).
|
|
43
|
+
function paths(value,label) {
|
|
44
|
+
if(!Array.isArray(value)||!value.length||value.some(p=>typeof p!=='string'||!p||p.includes('\0')||p.includes('\\')||p.startsWith('/')||p.split('/').some(x=>x==='..')||/[\x00-\x1f\x7f*?]/.test(p)||(hasRouterSyntax(p)&&!readablePath(p.replace(/^\.\//,'').replace(/\/$/,''))))) throw new Error(`invalid ${label}; explicit repository-relative paths required`);
|
|
45
|
+
return value.map(p=>p.replace(/^\.\//,'').replace(/\/$/,''));
|
|
46
|
+
}
|
|
47
|
+
// output_paths: NEW files the job may create (see docs/usage.md "Creating new files"). Shape only; existence and sensitivity are
|
|
48
|
+
// checked against the pinned tree in validateSubmission. Entries must already be in canonical form, so the assignment hash the
|
|
49
|
+
// submitter sent is the one that is stored.
|
|
50
|
+
export const outputPathLimits=Object.freeze({count:10,length:256});
|
|
51
|
+
export const outputPathsHeading='Output paths (output_paths; may create):';
|
|
52
|
+
// Comparison keys only: the assignment keeps the submitter's original path strings.
|
|
53
|
+
const outputPathKeys=[p=>p,p=>p.toLowerCase(),p=>p.normalize('NFC'),p=>p.normalize('NFC').toLowerCase()];
|
|
54
|
+
export function validateOutputPaths(value) {
|
|
55
|
+
const fail=reason=>{throw new Error(`invalid output_paths: ${reason}`);};
|
|
56
|
+
if(!Array.isArray(value)||!value.length) fail('give a non-empty list of repository-relative file paths, e.g. ["docs/notes/research.md"]');
|
|
57
|
+
if(value.length>outputPathLimits.count) fail(`${value.length} paths; at most ${outputPathLimits.count}. Split the job or write fewer files`);
|
|
58
|
+
const seen=new Set();
|
|
59
|
+
for(const p of value) {
|
|
60
|
+
if(typeof p!=='string'||!p) fail('every entry must be a non-empty string');
|
|
61
|
+
if(p.length>outputPathLimits.length) fail(`${p.slice(0,40)}... is ${p.length} characters; at most ${outputPathLimits.length}`);
|
|
62
|
+
if(p.startsWith('/')||/^(?:~|\$HOME)(?:\/|$)/.test(p)||p.includes('\\')) fail(`${p} is not repository-relative; write it relative to the repository root`);
|
|
63
|
+
if(p.split('/').includes('..')) fail(`${p} contains "..": name the file by its path from the repository root`);
|
|
64
|
+
if(/[\x00-\x1f\x7f*?]/.test(p)) fail(`${p} contains a glob or control character; name each file`);
|
|
65
|
+
if(p==='.'||p.endsWith('/')) fail(`${p} names a directory; list the files the job should create`);
|
|
66
|
+
if(p.startsWith('./')) fail(`${p}: write ${p.replace(/^(?:\.\/)+/,'')} (no leading ./)`);
|
|
67
|
+
if(p.split('/').some(x=>!x||x==='.'||x==='.git')) fail(`${p} has an empty, "." or ".git" segment`);
|
|
68
|
+
try { paths([p],'output_paths'); } catch { fail(`${p} has characters that scope paths cannot hold`); }
|
|
69
|
+
if(seen.has(p)) fail(`${p} is listed twice`);
|
|
70
|
+
const conflict=[...seen].find(other=>outputPathKeys.some(key=>{
|
|
71
|
+
const file=key(p),prior=key(other);
|
|
72
|
+
return file===prior||file.startsWith(`${prior}/`)||prior.startsWith(`${file}/`);
|
|
73
|
+
}));
|
|
74
|
+
if(conflict&&outputPathKeys.some(key=>key(p)===key(conflict))) fail(`${p} and ${conflict} name the same file on case-insensitive or Unicode-normalizing filesystems; choose distinct output paths`);
|
|
75
|
+
if(conflict) fail(`${p} and ${conflict} overlap as file and directory; list each new file, not its containing directory`);
|
|
76
|
+
seen.add(p);
|
|
77
|
+
}
|
|
78
|
+
return [...value];
|
|
79
|
+
}
|
|
80
|
+
// Advisory only: extensionless files are legitimate. Prose never authorizes paths or changes scope.
|
|
81
|
+
function warnOutputDirectoryMentions(outputs,text,warn) {
|
|
82
|
+
const mentions=mentionedPaths(text,outputs);
|
|
83
|
+
for(const output of outputs) {
|
|
84
|
+
if(path.posix.extname(output)) continue;
|
|
85
|
+
const nested=mentions.find(file=>file.startsWith(`${output}/`));
|
|
86
|
+
if(nested) warn(`output_paths entry ${output} is an exact new file, not a directory, but the instructions mention ${nested} beneath it. List each new file in output_paths; directories are not supported`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const outputBlock=list=>`${outputPathsHeading}\n${list.join('\n')}`;
|
|
90
|
+
export function renderAssignment(assignment) {
|
|
91
|
+
if(!assignment||typeof assignment!=='object') throw new Error('invalid assignment');
|
|
92
|
+
if(assignment.objective===undefined&&assignment.stop_rule===undefined) return assignment;
|
|
93
|
+
if(typeof assignment.objective!=='string'||!assignment.objective.trim()||typeof assignment.stop_rule!=='string'||!assignment.stop_rule.trim()) throw new Error('structured assignment requires objective and stop_rule');
|
|
94
|
+
const scope=assignment.scope_paths===undefined||assignment.scope_paths?.length===0?[]:paths(assignment.scope_paths,'scope_paths');
|
|
95
|
+
if(assignment.inputs?.some(i=>i.github_repo)&&!scope.length) throw new Error('structured repository assignment requires scope_paths');
|
|
96
|
+
const revisions=(assignment.inputs||[]).map(i=>i.github_repo?`${i.github_repo} at ${i.head_sha||i.base_sha}`:JSON.stringify(i)).join('\n')||'No repository inputs';
|
|
97
|
+
const outs=Array.isArray(assignment.output_paths)&&assignment.output_paths.length&&assignment.output_paths.every(p=>typeof p==='string')?`\n\n${outputBlock(assignment.output_paths)}`:'';
|
|
98
|
+
return {...assignment,brief:`Objective:\n${assignment.objective}\n\nExact inputs:\n${revisions}\n\nRead allow-list:\n${scope.length?scope.join('\n'):'No repository scope'}${outs}\n\nExpected output:\n${assignment.expected_output}\n\nStop rule:\n${assignment.stop_rule}`};
|
|
99
|
+
}
|
|
100
|
+
function loadPolicy() {
|
|
101
|
+
const file=defaultPath(os.homedir(),'.config/dot-bridge/submission-policy.json');
|
|
102
|
+
if(!fs.existsSync(file)) return {version:1,sensitive_paths:[],exceptions:[],sandbox_source_exemptions:[]};
|
|
103
|
+
if((fs.statSync(file).mode&0o777)!==0o600) throw new Error('submission policy must be mode 0600');
|
|
104
|
+
const p=JSON.parse(fs.readFileSync(file,'utf8'));
|
|
105
|
+
if(p.version!==1||!Array.isArray(p.sensitive_paths??[])||!Array.isArray(p.exceptions??[])||!Array.isArray(p.sandbox_source_exemptions??[])) throw new Error('invalid submission policy');
|
|
106
|
+
paths(p.sensitive_paths?.length?p.sensitive_paths:['placeholder'],'sensitive_paths');
|
|
107
|
+
for(const e of p.exceptions||[]) {
|
|
108
|
+
if(!e.id||typeof e.id!=='string'||!e.github_repo||typeof e.reason!=='string'||!e.reason.trim()) throw new Error('invalid sensitive scope exception');
|
|
109
|
+
paths([e.path],'exception path');
|
|
110
|
+
}
|
|
111
|
+
const sourceExemptions=(p.sandbox_source_exemptions||[]).map(e=>{
|
|
112
|
+
if(!e||Object.keys(e).sort().join(',')!=='blob_sha,github_repo,path,reason'||typeof e.github_repo!=='string'||!/^[-A-Za-z0-9_.]+\/[-A-Za-z0-9_.]+$/.test(e.github_repo)||e.github_repo.split('/').some(part=>part==='.'||part==='..'||part.includes('..'))||typeof e.blob_sha!=='string'||!/^[a-f0-9]{40}$/.test(e.blob_sha)||typeof e.reason!=='string'||!e.reason.trim()) throw new Error('invalid sandbox source exemption');
|
|
113
|
+
const [normalized]=paths([e.path],'sandbox source exemption path');
|
|
114
|
+
if(normalized!==e.path||e.path.length>256||e.path.split('/').some(part=>!part||part==='.'||part==='..'||part==='.git')||!isSourceExemptionPath(e.path)) throw new Error('invalid sandbox source exemption path');
|
|
115
|
+
return {github_repo:e.github_repo,path:e.path,blob_sha:e.blob_sha,reason:e.reason};
|
|
116
|
+
});
|
|
117
|
+
return {version:1,sensitive_paths:(p.sensitive_paths||[]).map(s=>paths([s],'sensitive_paths')[0]),exceptions:(p.exceptions||[]).map(e=>({...e,path:paths([e.path],'exception path')[0]})),sandbox_source_exemptions:sourceExemptions};
|
|
118
|
+
}
|
|
119
|
+
// Shared names and suffixes retain the same boundaries for both sensitive-path rules.
|
|
120
|
+
const alwaysHardNames=String.raw`\.env[^/]*|\.ssh|\.gnupg|\.aws|\.npmrc|\.netrc|\.git-credentials|\.pgpass|\.pypirc|\.htpasswd|kubeconfig(?:\.[^/]*)?|id_(?:rsa|dsa|ed25519|ecdsa)(?:[-_.][^/]*)?|sign[-_][^/]*release[^/]*`;
|
|
121
|
+
const sensitivePathTail=String.raw`(?:\/|$)|(?:^|\/)(?:\.docker|\.kube)\/config(?:\.json)?$|\.(?:pem|p12|pfx|key|keystore|jks|ppk|tfstate(?:\.backup)?)$`;
|
|
122
|
+
const alwaysHard=new RegExp(`(?:^|/)(?:${alwaysHardNames})${sensitivePathTail}`,'i');
|
|
123
|
+
const hardPath=new RegExp(String.raw`(?:^|/)(?:${alwaysHardNames}|service[-_]account(?:\.[^/]*)?|secrets?(?:\.[^/]*)?|[^/]*(?:credentials?|private[-_.]?key|gpg[-_.]?secret)[^/]*|(?:[^/]*[-_.])?signing(?:[-_.][^/]*)?)${sensitivePathTail}`,'i');
|
|
124
|
+
// "token" alone is not a credential: tokens.css and design-tokens.json are design tokens. A token file is sensitive when a
|
|
125
|
+
// credential word qualifies it (auth-token, access_token, gh-tokens.txt, npm.token), or it is a bare `token` file or a
|
|
126
|
+
// `tokens.txt|env|key|secret`. Plain `tokens/` and `tokens.json` are the usual design-token names and pass.
|
|
127
|
+
const credentialToken=/(?:^|[\/_.-])(?:auth|access|refresh|api|bearer|session|oauth|id|gh|github|gitlab|npm|pypi|slack|discord|telegram|bot|personal|service|deploy|registry|vault|jwt)[-_.]?tokens?(?=[\/_.-]|$)|(?:^|\/)\.?token(?:\.(?:txt|json|env|yaml|yml|key|secret|cfg|conf|ini))?(?=\/|$)|(?:^|\/)\.?tokens\.(?:txt|env|key|secret)(?=\/|$)|(?:^|[\/_.-])tokens?[-_.](?:secret|key|env)(?=[\/_.-]|$)/i;
|
|
128
|
+
const softPath=new RegExp(`(?:^|\\/)[^/]*(?:auth|secret|credential)[^/]*(?:\\/|$)|(?:^|[\\/_.-])sign(?:ing|ature)?(?=[\\/_.-]|$)|${credentialToken.source}`,'i');
|
|
129
|
+
// Source, test and documentation files often name credentials as code topics rather than secret material. Apply only the
|
|
130
|
+
// name rules that mark secret material regardless of extension; secret content is still refused by secretContent, and
|
|
131
|
+
// policy-listed paths by sensitive_paths. Shell scripts and SQL keep every name rule because they can hold secrets as plain
|
|
132
|
+
// variables, which secretContent does not catch.
|
|
133
|
+
const codeFile=/\.(?:ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|go|java|kt|kts|swift|rb|php|cs|c|h|cc|cpp|hpp|m|mm|scala|css|scss|less|html|vue|svelte|astro|md|mdx|rst|adoc|snap|graphql|gql|proto|dart|ex|exs|elm|lua|r|jl|zig|nix)$/i;
|
|
134
|
+
// A host pin may expose reviewed source code with a sensitive-looking filename (for example credentials.ts), but never a
|
|
135
|
+
// credential store, key, environment file, or file below a secret/credentials data directory.
|
|
136
|
+
export function isSourceExemptionPath(file) {
|
|
137
|
+
return typeof file==='string'&&(codeFile.test(file)||/\.sql$/i.test(file))&&!alwaysHard.test(file)&&!passwordName.test(file)&&!secretDirectory.test(file);
|
|
138
|
+
}
|
|
139
|
+
// In a code file's own name, the precise secret words still mark secret material (credentials.ts, secrets.py, private-key.ts,
|
|
140
|
+
// service-account.ts, owner-credential.ts); a word inside a longer name (logout-cancels-credential-setup.test.ts) does not.
|
|
141
|
+
const codeSecretName=/(?:^|\/)(?:credentials?|secrets?|private[-_.]?key|service[-_.]?account|[^/]*[-_.](?:credentials?|secrets?))\.[^/.]+$/i;
|
|
142
|
+
// Password stores are secret material by name in any form.
|
|
143
|
+
const passwordName=/(?:^|\/)(?:\.?htpasswd|shadow|[^/]*passw(?:or)?ds?(?:\.[^/]*)?)$/i;
|
|
144
|
+
const secretDirectory=/(?:^|\/)(?:secrets?|credentials?)\//i;
|
|
145
|
+
const hardName=file=>passwordName.test(file)||(codeFile.test(file)?alwaysHard.test(file)||codeSecretName.test(file)||secretDirectory.test(file):hardPath.test(file));
|
|
146
|
+
// The soft rule reads the file name only: a directory named for what its code does (provider-auth/, unified-auth-data-access/)
|
|
147
|
+
// marks no secret. The hard rules still read every segment (secrets/, .ssh/).
|
|
148
|
+
// A name without an extension is usually a directory (add-agent-authored-connectors): only the credential-token pattern applies.
|
|
149
|
+
const softName=file=>{ if(codeFile.test(file)) return false; const base=file.split('/').pop(); return base.includes('.')?softPath.test(base):credentialToken.test(base)||/secret|credential/i.test(base); };
|
|
150
|
+
// A host path the worker is told to read (never a repository path); other leading-slash tokens in prose are routes (/v1, /me).
|
|
151
|
+
// A token shaped like a file (a path, a dotfile, a home path or a known file extension), not an identifier like input.privateKey.
|
|
152
|
+
const fileShaped=file=>/[\/~$]/.test(file)||file.startsWith('.')||sourceExtension.test(file);
|
|
153
|
+
const hostPath=/^(?:~|\$HOME)(?:\/|$)|^\/(?:home|root|etc|var|tmp|usr|opt|proc|sys|dev|run|mnt|media|srv|boot|private|Users|Library|Volumes)(?:\/|$)/;
|
|
154
|
+
// Secret values by shape: private keys, GitHub/AWS/OpenAI/Stripe/Slack/Google/GitLab/npm tokens, URLs with an inline password
|
|
155
|
+
// (local and example hosts excepted: postgres://postgres:postgres@localhost is a test fixture).
|
|
156
|
+
export { secretContent } from './redaction.mjs';
|
|
157
|
+
const authority=/\b(?:we|you|dot)\s+(?:have|has|can use)\s+(?:\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:(?:free|available|live|idle|worker)\s+)*(?:slots?|lanes?|workers?)\b|\b(?:\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:free|available|live|idle)\s+(?:slots?|lanes?|workers?)\b|\b(?:\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:(?:free|available|live|idle|worker|dot)\s+)*(?:slots?|lanes?|workers?)\s+(?:are\s+)?(?:free|available|idle|remaining|open)\b|\b(?:keep|fill|maintain)\s+(?:all\s+)?(?:\d+\s+)?(?:slots?|lanes?)\s+(?:full|busy)/i;
|
|
158
|
+
// Role words only. A regex cannot tell a named person from a role or a product, so named-person claims are a documented residual.
|
|
159
|
+
const grantedAuthority=/\b(?:the\s+)?(?:owner|user|operator|admin(?:istrator)?|maintainer|requester)\s+(?:has\s+)?(?:grants?|granted|approves?|approved|authorizes?|authorized)\s+(?:new|additional|expanded)\s+(?:authority|access|permissions?)\b/i;
|
|
160
|
+
function within(p,scope) { return !/^(?:\/|~\/|\$HOME\/)/.test(p)&&!p.split('/').includes('..')&&scope.some(s=>s==='.'||p===s||p.startsWith(`${s}/`)); }
|
|
161
|
+
const sourceExtension=/\.(?:mjs|cjs|jsx|ts|tsx|py|rs|go|md|txt|html|css|scss|sh|json|yaml|yml|toml|ini|conf|sql|vue|svelte|xml|pem|key|asc|jks|keystore|ppk|tfstate(?:\.backup)?)$/i;
|
|
162
|
+
const pathToken=new RegExp(`(?<![A-Za-z0-9_.@-])((?:(?:~|\\$HOME)?\\/|\\.?\\.?\\/)?${firstSegment}(?:\\/${laterSegment})*\\/?)(?![A-Za-z0-9_@-])`,'gm');
|
|
163
|
+
const plainToken=/(?<![A-Za-z0-9_.@-])((?:(?:~|\$HOME)?\/|\.?\.?\/)?[A-Za-z0-9_.@-]+(?:\/[A-Za-z0-9_.@-]+)*\/?)(?![A-Za-z0-9_@-])/g;
|
|
164
|
+
// Router segments (`[id]`, `(group)`, `+page.svelte`) join a token only in a path with a `/`. A slash-free token with brackets or
|
|
165
|
+
// parentheses ("(credentials)", "[1]", "(x).env") is read as before, on plain characters, so a wrapped name is still seen.
|
|
166
|
+
function pathTokens(text) {
|
|
167
|
+
return [...text.matchAll(pathToken)].flatMap(m=>hasRouterSyntax(m[1])&&!m[1].includes('/')?[...m[1].matchAll(plainToken)].map(sub=>Object.assign([sub[0],sub[1]],{index:m.index+sub.index})):[m]);
|
|
168
|
+
}
|
|
169
|
+
function mentionedPaths(text,knownPaths=[]) {
|
|
170
|
+
const known=new Set(knownPaths.flatMap(file=>{const parts=file.split('/');return [file,...parts.slice(0,-1).map((_,i)=>parts.slice(0,i+1).join('/'))];}));
|
|
171
|
+
const authoritative=file=>known.has(file)||knownPaths.some(scope=>file.startsWith(`${scope}/`));
|
|
172
|
+
const unwrap=file=>{const name=file.replace(/^_+|_+$/g,'');return file.startsWith('_')&&file.endsWith('_')&&(known.has(name)||hardPath.test(name)||(name.startsWith('@')&&(known.has(name.slice(1))||hardPath.test(name.slice(1)))))?name:file;};
|
|
173
|
+
// Names written with a slash (./old.mjs, Makefile/) stay explicit paths after normalization.
|
|
174
|
+
const explicit=new Set();
|
|
175
|
+
const candidates=pathTokens(text).map(m=>{const file=normalize(m);if(file!==null&&m[1].includes('/')) explicit.add(file);return file;});
|
|
176
|
+
function normalize(m) {
|
|
177
|
+
const raw=m[1];
|
|
178
|
+
// A JSX/HTML tag name right after `<` or `</` (</Button>, <Card.Header>, <Icon />) is markup, not a path. A hard
|
|
179
|
+
// sensitive name in that position (<credentials>) is still treated as a reference.
|
|
180
|
+
if(text[m.index-1]==='<'&&/^\/?[A-Za-z][A-Za-z0-9_.:-]*$/.test(raw)&&!hardPath.test(raw.replace(/^\//,''))) return null;
|
|
181
|
+
if(authoritative(raw)) return raw;
|
|
182
|
+
// A leading slash inside an HTTP URL is not a host filesystem reference.
|
|
183
|
+
if(/https?:\/$/i.test(text.slice(0,m.index))) return null;
|
|
184
|
+
let file=raw.replace(/\/+$/,'').replace(/\.+$/,'');
|
|
185
|
+
if(authoritative(file)) return file;
|
|
186
|
+
file=unwrap(file);
|
|
187
|
+
const referenced=unwrap(file.replace(/^@/,''));
|
|
188
|
+
if(file.startsWith('@')&&(authoritative(referenced)||referenced.includes('/')||referenced.startsWith('.')||sourceExtension.test(referenced)||hardPath.test(referenced))) file=referenced;
|
|
189
|
+
if(authoritative(file)) return file;
|
|
190
|
+
if(/^(?:~\/|\$HOME\/|\/)/.test(file)) return file;
|
|
191
|
+
return file.replace(/^\.\//,'').replace(/^[ab]\//,'');
|
|
192
|
+
}
|
|
193
|
+
const found=candidates.filter(file=>{
|
|
194
|
+
// Exact tree/scope names and explicit lists carry authority. Ordinary words,
|
|
195
|
+
// framework brands and hostnames do not establish repository paths.
|
|
196
|
+
if(file===null) return false;
|
|
197
|
+
if(authoritative(file)) return true;
|
|
198
|
+
if(/^(?:e\.g\.|i\.e\.)\/(?:e\.g|i\.e)\.?$/i.test(file)) return false;
|
|
199
|
+
if(/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+\//.test(file)) return false;
|
|
200
|
+
if(/^(?:~\/|\$HOME\/|\/)/.test(file)) return true;
|
|
201
|
+
if(file.startsWith('.')) return hardPath.test(file)||file.includes('/');
|
|
202
|
+
if(file.includes('/')) return sourceExtension.test(file)||file.split('/').some(part=>part.includes('.'));
|
|
203
|
+
return sourceExtension.test(file)||(file.includes('.')&&hardPath.test(file));
|
|
204
|
+
});
|
|
205
|
+
return Object.assign(found,{explicit});
|
|
206
|
+
}
|
|
207
|
+
export function scanGit(mirror,args,spawn=spawnSync) {
|
|
208
|
+
const maxBuffer=32*1024*1024;
|
|
209
|
+
const r=spawn('git',['-C',mirror,...args],{encoding:'utf8',timeout:30000,maxBuffer,env:gitEnv()});
|
|
210
|
+
if(r.error?.code==='ENOBUFS'||r.error?.code==='ERR_CHILD_PROCESS_STDIO_MAXBUFFER') throw new Error(`PR diff too large to scan: more than ${maxBuffer/1024/1024} MiB; split the review or name fewer files`);
|
|
211
|
+
if(r.error||r.status!==0) {
|
|
212
|
+
// Inspect before clipping: a token crossing a clipping boundary must not leak.
|
|
213
|
+
const stderr=String(r.stderr??'');
|
|
214
|
+
let excerpt='';
|
|
215
|
+
if(!hasSecretContent(stderr)) {
|
|
216
|
+
const safe=mirror?stderr.split(String(mirror)).join('[mirror]'):stderr;
|
|
217
|
+
const data=Buffer.from(safe,'utf8'),limit=2048;
|
|
218
|
+
excerpt=(data.length>2*limit
|
|
219
|
+
?data.subarray(0,limit).toString('utf8')+'[truncated]'+data.subarray(-limit).toString('utf8')
|
|
220
|
+
:safe).trim();
|
|
221
|
+
if(secretContent.test(excerpt)) excerpt='';
|
|
222
|
+
}
|
|
223
|
+
// Never interpolate argv, environment, or the spawn error's raw message.
|
|
224
|
+
const subcommand=/^[a-z][a-z-]{0,31}$/.test(args[0]??'')&&!secretContent.test(args[0])?args[0]:'command';
|
|
225
|
+
const outcome=r.error?.code==='ETIMEDOUT'?'timed out':r.signal?`was stopped by ${r.signal}`:Number.isInteger(r.status)?`exited ${r.status}`:'failed to start';
|
|
226
|
+
throw infrastructureError(`submission scope scanner failed: git ${subcommand} ${outcome}${excerpt?': '+excerpt:''}`);
|
|
227
|
+
}
|
|
228
|
+
return r.stdout;
|
|
229
|
+
}
|
|
230
|
+
const git=scanGit;
|
|
231
|
+
// A bare word (no `/`, no extension) is prose, not a path: `web`, `data`, `tests`. Only a sensitive name that exists in
|
|
232
|
+
// the tree (credentials, id_rsa, kubeconfig) is still refused. A bare filename (README.md) names a path only when it
|
|
233
|
+
// resolves to exactly one file in the tree; ambiguous or absent names, and in-scope matches, are not rejections.
|
|
234
|
+
const bareToken=file=>!file.includes('/')&&!/^(?:~|\$HOME)/.test(file);
|
|
235
|
+
const bareWord=file=>bareToken(file)&&!file.slice(1).includes('.')&&!file.startsWith('.');
|
|
236
|
+
// The worker's auto-reviewer judges reads against the brief's prose as well as structured scope_paths. Include the scoped files
|
|
237
|
+
// in a free-form brief so both descriptions agree. Structured briefs already carry the list (renderAssignment). Idempotent:
|
|
238
|
+
// a brief that has the marker is left as it is.
|
|
239
|
+
// A unified diff inlined in a brief (raw or fenced) is code under review, not instructions: its content lines hold regex
|
|
240
|
+
// literals, URL routes, shebangs and relative imports (/changed/, /me, /usr/bin/env, ../../x.js). Only lines inside a real
|
|
241
|
+
// hunk count: a `diff --git` header, then `@@ -a,b +c,d @@`
|
|
242
|
+
// whose line counts are consumed exactly, so prose after a hunk (or under a forged header) is scanned as prose. Path-shaped
|
|
243
|
+
// tokens in code still go through inspect (hard and policy-listed names); the secret scan sees the whole assignment;
|
|
244
|
+
// header paths (diff --git, ---, +++) keep their scope checks.
|
|
245
|
+
const diffMeta=/^(?:index |--- |\+\+\+ |new file mode |deleted file mode |old mode |new mode |similarity index |rename (?:from|to) |copy (?:from|to) |Binary files )/;
|
|
246
|
+
const npmSpecifier=/^@[a-z0-9][\w.-]*\/[a-z0-9][\w.-]*(?:\/|$)/;
|
|
247
|
+
function codeInDiffFences(brief,inspect) {
|
|
248
|
+
const checkTokens=code=>{
|
|
249
|
+
for(let token of code.split(/[\s'"`(),;{}\[\]<>=|]+/)) {
|
|
250
|
+
if(!token||/^https?:\/\//i.test(token)||npmSpecifier.test(token)) continue;
|
|
251
|
+
const raw=token.slice(token.lastIndexOf(':')+1).replace(/^@/,'').replace(/^\/+/,'/');
|
|
252
|
+
token=raw.replace(/^(?:\.{1,2}\/)+|^\/+/,'').replace(/[.\/]+$/,'');
|
|
253
|
+
if(token&&(token.includes('/')||/\.[A-Za-z0-9]{1,8}$/.test(token))) inspect(token,raw);
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
// A hunk is code only if its line counts are consumed exactly; one cut short by a non-diff line is scanned as prose, whole.
|
|
257
|
+
const out=[];let state='prose',oldLeft=0,newLeft=0,hunk=null;
|
|
258
|
+
const closeHunk=complete=>{ if(!hunk) return; if(complete) { checkTokens(hunk.context);for(const l of hunk.lines) if(l[0]!=='\\') checkTokens(l.slice(1)); out.push(hunk.header,...hunk.lines.map(l=>l[0]==='\\'?l:l[0])); } else out.push(hunk.raw,...hunk.lines); hunk=null; };
|
|
259
|
+
for(const line of brief.split('\n')) {
|
|
260
|
+
if(hunk&&(oldLeft>0||newLeft>0)) {
|
|
261
|
+
const kind=line[0];
|
|
262
|
+
if(line==='\') { hunk.lines.push(line);continue; }
|
|
263
|
+
if(kind===' '&&oldLeft>0&&newLeft>0) { oldLeft--;newLeft--;hunk.lines.push(line);continue; }
|
|
264
|
+
if(kind==='-'&&oldLeft>0) { oldLeft--;hunk.lines.push(line);continue; }
|
|
265
|
+
if(kind==='+'&&newLeft>0) { newLeft--;hunk.lines.push(line);continue; }
|
|
266
|
+
closeHunk(false);state='prose';
|
|
267
|
+
} else if(hunk&&line==='\') { hunk.lines.push(line);continue; }
|
|
268
|
+
else closeHunk(true);
|
|
269
|
+
const header=/^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@(.*)$/.exec(line);
|
|
270
|
+
if(line.startsWith('diff --git ')) state='file';
|
|
271
|
+
else if(header&&state==='file') { hunk={raw:line,header:line.slice(0,line.length-header[3].length),context:header[3],lines:[]};oldLeft=Number(header[1]??1);newLeft=Number(header[2]??1);continue; }
|
|
272
|
+
else if(state==='file'&&!diffMeta.test(line)) state='prose';
|
|
273
|
+
out.push(line);
|
|
274
|
+
}
|
|
275
|
+
closeHunk(!(oldLeft>0||newLeft>0));
|
|
276
|
+
return out.join('\n');
|
|
277
|
+
}
|
|
278
|
+
const allowListMarker='Read allow-list (scope_paths';
|
|
279
|
+
export const allowListHeading=`${allowListMarker}; every path below, and everything under a listed directory, may be read):`;
|
|
280
|
+
const vagueExclusion=/\[excluded (?:file|path)\]|\b(?:omitted|excluded) by policy\b/i;
|
|
281
|
+
function withAllowList(result,warn) {
|
|
282
|
+
if(vagueExclusion.test(result.brief)) warn('the brief mentions an excluded file without naming it; the worker\'s reviewer then refuses in-scope reads that look like it. Name the path, or drop the sentence: the bridge scope note names dropped sensitive files');
|
|
283
|
+
const scope=result.scope_paths||[];
|
|
284
|
+
// The whole repository ('.', the ACP scope) needs no list.
|
|
285
|
+
if(!scope.length||scope.includes('.')||result.brief.includes(allowListMarker)||result.brief.includes('\nRead allow-list:\n')) return result;
|
|
286
|
+
const head=`\n\n${allowListHeading}\n`;
|
|
287
|
+
const room=Math.min(submissionLimits.brief-bytes(result.brief),submissionLimits.instructions-(bytes(result.brief)+bytes(result.expected_output)+bytes(result.execution_scope||'')+bytes(typeof result.scope_text==='string'?result.scope_text:'')+bytes(scope.join('\n'))))-bytes(head)-80;
|
|
288
|
+
const listed=[];let used=0;
|
|
289
|
+
for(const p of scope) { if(used+bytes(p)+1>room) break; listed.push(p);used+=bytes(p)+1; }
|
|
290
|
+
if(!listed.length) { warn('the brief has no room for the scope_paths allow-list; the worker\'s reviewer may refuse in-scope reads'); return result; }
|
|
291
|
+
const more=scope.length-listed.length;
|
|
292
|
+
const expanded={...result,brief:`${result.brief}${head}${listed.join('\n')}${more?`\n...and ${more} more paths in scope_paths, all readable`:''}`};
|
|
293
|
+
const n=bytes(expanded.brief);
|
|
294
|
+
if(n>submissionLimits.brief) throw Object.assign(new Error(`brief: ${n} UTF-8 bytes exceeds ${submissionLimits.brief}; cut at least ${n-submissionLimits.brief} bytes`),{expandedPayload:expanded});
|
|
295
|
+
return expanded;
|
|
296
|
+
}
|
|
297
|
+
// The brief names the files the job may create; the worker's reviewer judges a write by the brief's prose. Idempotent.
|
|
298
|
+
function withOutputPaths(result) {
|
|
299
|
+
const list=result.output_paths||[];
|
|
300
|
+
if(!list.length||result.brief.includes(outputPathsHeading)) return result;
|
|
301
|
+
const brief=`${result.brief}\n\n${outputBlock(list)}`;
|
|
302
|
+
const expanded={...result,brief},n=bytes(brief);
|
|
303
|
+
if(n>submissionLimits.brief) throw Object.assign(new Error(`brief: ${n} UTF-8 bytes exceeds ${submissionLimits.brief}; cut at least ${n-submissionLimits.brief} bytes`),{expandedPayload:expanded});
|
|
304
|
+
return expanded;
|
|
305
|
+
}
|
|
306
|
+
// The scope deny rule as a yes/no on one repository path: hard names (keys, env files, credential stores), the soft credential/auth/
|
|
307
|
+
// signing name lint, a router-group spelling of a hard name, and the owner's `sensitive_paths`. Submit uses these rules to refuse or drop
|
|
308
|
+
// scope paths; the check sandbox uses them to mask the same files (src/workspace.mjs). Exceptions are per-submission and do not unmask.
|
|
309
|
+
export function isSensitiveRepoPath(file,policyPaths=[]) {
|
|
310
|
+
return hardName(file)||(hasRouterSyntax(file)&&hardName(file.replace(/\[[^\]/]*\]\]?|\([^)/]*\)/g,'')))||softName(file)||policyPaths.some(x=>file===x||file.startsWith(`${x}/`));
|
|
311
|
+
}
|
|
312
|
+
// The owner's sensitive_paths, or an error message when the policy file cannot be read (execution callers must fail closed).
|
|
313
|
+
export function sensitivePolicyPaths() {
|
|
314
|
+
try { const policy=loadPolicy();return {paths:policy.sensitive_paths,sourceExemptions:policy.sandbox_source_exemptions,error:null}; } catch(error) { return {paths:[],sourceExemptions:[],error:error.message}; }
|
|
315
|
+
}
|
|
316
|
+
export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanInput,warnings=null,excludeSensitive=false,review=false,worker}={}) {
|
|
317
|
+
const warn=message=>{if(warnings&&!warnings.includes(message)) warnings.push(message);};
|
|
318
|
+
let p;
|
|
319
|
+
try { p=loadPolicy(); } catch(error) { throw infrastructureError(error.message); }
|
|
320
|
+
let rendered=renderAssignment(assignment);
|
|
321
|
+
const briefBytes=cap(rendered.brief,submissionLimits.brief,'brief');
|
|
322
|
+
const outputBytes=cap(rendered.expected_output,submissionLimits.instructions,'expected output');
|
|
323
|
+
if(rendered.scope_text!==undefined&&typeof rendered.scope_text!=='string') throw new Error('invalid scope_text');
|
|
324
|
+
const scopeText=typeof rendered.scope_text==='string'?rendered.scope_text:'';
|
|
325
|
+
const checkInstructionSize=r=>{
|
|
326
|
+
const total=instructionBytes(r);
|
|
327
|
+
if(total>submissionLimits.instructions) throw Object.assign(new Error(`task instructions: ${total} UTF-8 bytes exceeds ${submissionLimits.instructions}; cut at least ${total-submissionLimits.instructions} bytes`),{expandedPayload:r});
|
|
328
|
+
};
|
|
329
|
+
checkInstructionSize(rendered);
|
|
330
|
+
if([authority,grantedAuthority].some(pattern=>pattern.test([rendered.brief,rendered.expected_output,scopeText].join('\n')))) throw new Error('live-slot or expanded-authority claim in instructions');
|
|
331
|
+
if(hasSecretContent(rendered)) throw new Error('hard sensitive content exclusion');
|
|
332
|
+
// Labelled values are medium precision: every output sink masks them, so intake warns instead of refusing.
|
|
333
|
+
if(hasCredentialHints(rendered)) warn('the assignment contains a credential-labelled value; output to the worker masks it, so pass credentials through the bridge, not the brief');
|
|
334
|
+
const input=rendered.execution_scope==='implementation'||rendered.inputs?.some(i=>i.github_repo!==undefined)?assignmentInput(rendered):null;
|
|
335
|
+
const mismatch=(reads,scope)=>[...reads.filter(p=>!scope.includes(p)),...scope.filter(p=>!reads.includes(p))].join(', ')||'lists differ in length';
|
|
336
|
+
const scope=rendered.scope_paths===undefined||rendered.scope_paths?.length===0?[]:[...paths(rendered.scope_paths,'scope_paths')];
|
|
337
|
+
if(input&&!scope.length) throw new Error('unknown repository scope; scope_paths required');
|
|
338
|
+
if(rendered.read_paths!==undefined) {
|
|
339
|
+
const reads=paths(rendered.read_paths,'read_paths');
|
|
340
|
+
if(reads.length!==scope.length||reads.some(p=>!scope.includes(p))) throw new Error(`contradictory read_paths and scope_paths: ${mismatch(reads,scope)}`);
|
|
341
|
+
}
|
|
342
|
+
if(rendered.read_list!==undefined) {
|
|
343
|
+
const reads=paths(rendered.read_list,'read_list');
|
|
344
|
+
if(reads.length!==scope.length||reads.some(p=>!scope.includes(p))) throw new Error(`contradictory read_list and scope_paths: ${mismatch(reads,scope)}`);
|
|
345
|
+
}
|
|
346
|
+
const exception=sensitiveScopeOverride===null?null:p.exceptions.find(e=>e.id===sensitiveScopeOverride&&e.github_repo===input?.github_repo);
|
|
347
|
+
if(sensitiveScopeOverride!==null&&!exception) throw new Error('unknown sensitive scope override');
|
|
348
|
+
// Why a path is sensitive, for the record kept when a directory scope drops it.
|
|
349
|
+
const sensitiveReason=file=>hardName(file)||(hasRouterSyntax(file)&&hardName(file.replace(/\[[^\]/]*\]\]?|\([^)/]*\)/g,'')))?'hard sensitive path (credential, key or signing material)':p.sensitive_paths.some(x=>file===x||file.startsWith(`${x}/`))?'listed in the submission policy sensitive_paths':'name matches the credential, auth or signing lint';
|
|
350
|
+
function inspectPath(file) {
|
|
351
|
+
// A router group cannot hide a sensitive name: `(x).env` is also checked as `.env`.
|
|
352
|
+
if(hardName(file)||(hasRouterSyntax(file)&&hardName(file.replace(/\[[^\]/]*\]\]?|\([^)/]*\)/g,'')))) throw new Error(`hard sensitive path exclusion: ${file}`);
|
|
353
|
+
if((softName(file)||p.sensitive_paths.some(s=>file===s||file.startsWith(`${s}/`)))&&(!exception||file!==exception.path)) throw new Error(`sensitive scope path: ${file}`);
|
|
354
|
+
}
|
|
355
|
+
for(const file of scope) inspectPath(file);
|
|
356
|
+
// output_paths: shape here, the pinned tree below. Review mode is read-only, so it takes no output file.
|
|
357
|
+
const outputs=rendered.output_paths===undefined?[]:validateOutputPaths(rendered.output_paths);
|
|
358
|
+
if(outputs.length) {
|
|
359
|
+
if(review) throw new Error('output_paths are not allowed with --review: review mode is read-only. Remove output_paths from the assignment, or submit without --review');
|
|
360
|
+
if(!input) throw new Error('output_paths require pinned repository input (inputs: [{github_repo, base_sha}])');
|
|
361
|
+
if(input.input_patch) throw new Error('output_paths cannot be combined with input_patch: the patch is applied to the workspace and would count as a change outside output_paths. Submit the input patch as a separate job, or push it and pin head_sha');
|
|
362
|
+
for(const file of outputs) {
|
|
363
|
+
try { inspectPath(file); }
|
|
364
|
+
catch(error) { throw new Error(`output_paths: ${error.message}. Name the new file so that it does not look like credential, auth or signing material`); }
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
const outputSet=new Set(outputs);
|
|
368
|
+
// Unified-diff /dev/null markers are sentinels, not filesystem requests. An exact exclusion diagnostic grants no
|
|
369
|
+
// read permission. Keep scanning its content for secrets above and checking scope/diff paths below; remove only
|
|
370
|
+
// a well-formed, actually sensitive name from instruction references.
|
|
371
|
+
const instructionBrief=rendered.brief.replace(/^(?:---|\+\+\+) \/dev\/null$/gm,'').replace(/^omitted: (.+) \(sensitive\)$/gm,(line,file)=>{
|
|
372
|
+
try { paths([file],'omitted path'); } catch { return line; }
|
|
373
|
+
try { inspectPath(file); return line; }
|
|
374
|
+
catch(error) { if(/^(?:hard sensitive path exclusion|sensitive scope path): /.test(error.message)) return '';throw error; }
|
|
375
|
+
});
|
|
376
|
+
// input_patch is a diff, linted as one below (numstat paths, sensitive names, secrets), not instruction prose.
|
|
377
|
+
// A name in code is a reference, not a read. The worker reads only scope files, and every scope and diff file gets inspectPath.
|
|
378
|
+
// A code token refuses only when it points at host secret material (for example, ~/.ssh/id_rsa) or a policy-listed path.
|
|
379
|
+
const inspectCode=(file,raw=file)=>{
|
|
380
|
+
if(hostPath.test(raw)&&hardPath.test(file)) throw new Error(`hard sensitive path exclusion: ${raw}`);
|
|
381
|
+
if(p.sensitive_paths.some(x=>file===x||file.startsWith(`${x}/`))&&(!exception||file!==exception.path)) throw new Error(`sensitive scope path: ${file}`);
|
|
382
|
+
};
|
|
383
|
+
const text=[codeInDiffFences(instructionBrief,inspectCode),rendered.expected_output,scopeText,rendered.objective||'',rendered.stop_rule||'',JSON.stringify((rendered.inputs||[]).map(({input_patch,...rest})=>rest))].join('\n\n');
|
|
384
|
+
warnOutputDirectoryMentions(outputs,text,warn);
|
|
385
|
+
if(input) {
|
|
386
|
+
for(const list of text.matchAll(/(?:read[- ](?:allow[- ]?list|list|paths)|allowed (?:files|paths))[ \t]*:[ \t]*(?:\n)?([^\n]*(?:\n(?!\n)[^\n]+)*)/gi)) {
|
|
387
|
+
const reads=list[1].split(/[\n,]/).map(line=>line.trim().replace(/^[-*] +/,'').replace(/^[`'"]|[`'"]$/g,'')).filter(Boolean);
|
|
388
|
+
for(const file of paths(reads,'brief read-list')) {
|
|
389
|
+
inspectPath(file);
|
|
390
|
+
if(!within(file,scope)) throw new Error(`contradictory brief read-list and scope_paths: ${file} is read-listed but outside scope_paths`);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
const dropped=[];let narrowedScope=null;
|
|
395
|
+
const firstPass=mentionedPaths(text,scope);
|
|
396
|
+
for(const file of firstPass) {
|
|
397
|
+
const bare=bareToken(file)&&!firstPass.explicit.has(file);
|
|
398
|
+
if(bare&&bareWord(file)&&!hardPath.test(file)) continue;
|
|
399
|
+
// Repository work resolves every mention against the tree below; without a repository, mentions are only inspected.
|
|
400
|
+
if(input) continue;
|
|
401
|
+
inspectPath(file);
|
|
402
|
+
}
|
|
403
|
+
if(input) {
|
|
404
|
+
const scan=scanInput?scanInput(input):(()=>{
|
|
405
|
+
let mirror;
|
|
406
|
+
try { mirror=prepareGithubRepo(input,{worker}); } catch(error) { if(error.code==='DOT_BRIDGE_INVALID_INPUT') throw error;throw infrastructureError(error.message); }
|
|
407
|
+
const revision=input.head_sha||input.base_sha;
|
|
408
|
+
const tree=git(mirror,['ls-tree','-r','-z',revision]).split('\0').filter(Boolean).map(entry=>{const tab=entry.indexOf('\t');if(tab<0) throw infrastructureError('submission scope scanner failed');return {mode:entry.slice(0,6),path:entry.slice(tab+1)};});
|
|
409
|
+
const files=tree.map(entry=>entry.path),symlinks=tree.filter(entry=>entry.mode==='120000').map(entry=>entry.path);
|
|
410
|
+
const diff=input.head_sha?git(mirror,['diff','--no-ext-diff','--no-textconv','--binary',input.base_sha,input.head_sha]):'';
|
|
411
|
+
const diffFiles=input.head_sha?git(mirror,['diff','--no-ext-diff','--name-only','-z',input.base_sha,input.head_sha]).split('\0').filter(Boolean):[];
|
|
412
|
+
return {files,diff,diffFiles,symlinks};
|
|
413
|
+
})();
|
|
414
|
+
if(!scan||!Array.isArray(scan.files)||!Array.isArray(scan.diffFiles)||typeof scan.diff!=='string') throw infrastructureError('submission scope scanner failed');
|
|
415
|
+
// A free-form read-only or review assignment may grow its scope by the files its own brief names and its PR changes: the
|
|
416
|
+
// submitter asked for them, each still passes inspectPath, and the workspace enforces the result. Implementation work,
|
|
417
|
+
// structured briefs and explicit read lists keep the scope exactly as declared.
|
|
418
|
+
const growable=(rendered.execution_scope==='read-only'||review)&&rendered.objective===undefined&&rendered.read_paths===undefined&&rendered.read_list===undefined&&!scope.includes('.');
|
|
419
|
+
const added=[],undeclared=[],fixable=[],ambiguous=[],mentionedAs=new Map();
|
|
420
|
+
// Review mode cannot write (apply_patch refuses review submissions), so growing a review assignment's scope adds read access only.
|
|
421
|
+
const maxGrowth=200;
|
|
422
|
+
const want=(file,mention=file)=>{ if(within(file,scope)) return; if(mention!==file) mentionedAs.set(file,mention); if(growable) { if(added.length>=maxGrowth) throw new Error(`scope growth limit: the brief names more than ${maxGrowth} files outside scope_paths; list them in scope_paths`); scope.push(file);added.push(file); } else fixable.push(file); };
|
|
423
|
+
const treeFiles=new Set(scan.files),isTreeDir=file=>scan.files.some(f=>f.startsWith(`${file}/`));
|
|
424
|
+
const treePass=mentionedPaths(text,[...scope,...scan.files]);
|
|
425
|
+
for(const file of treePass) {
|
|
426
|
+
if(file===input.github_repo||outputSet.has(file)) continue;
|
|
427
|
+
const bare=bareToken(file)&&!treePass.explicit.has(file);
|
|
428
|
+
if(bare&&bareWord(file)&&!hardPath.test(file)) { if(!within(file,scope)) warn(`bare word "${file}" matches a repository path outside scope_paths; it is not treated as a path reference`); continue; }
|
|
429
|
+
// In scope, or a directory that holds scope entries (`gateway` for gateway/x.py): context, not a new read.
|
|
430
|
+
if(within(file,scope)) { inspectPath(file);continue; }
|
|
431
|
+
if(scope.some(s=>s.startsWith(`${file}/`))) continue;
|
|
432
|
+
// A bare filename (README.md) names a file only when it resolves to exactly one tree path.
|
|
433
|
+
if(bare) {
|
|
434
|
+
const matches=scan.files.filter(f=>f===file||f.endsWith(`/${file}`));
|
|
435
|
+
if(matches.some(f=>within(f,scope))) continue;
|
|
436
|
+
if(matches.length===1) { inspectPath(matches[0]);want(matches[0],file);continue; }
|
|
437
|
+
// A file name the tree lacks (gh-tokens.txt, secrets.yaml) may point the worker at a host file: full inspect. An identifier
|
|
438
|
+
// (input.privateKey) is not file-shaped and passes.
|
|
439
|
+
if(fileShaped(file)) inspectPath(file);
|
|
440
|
+
// Both outcomes predict a broken job: the worker looks for a file it cannot pick out, or cannot find. Refused with the fix.
|
|
441
|
+
ambiguous.push(matches.length?`ambiguous bare filename "${file}": it matches ${matches.length} repository paths outside scope_paths (${matches.slice(0,5).join(', ')}${matches.length>5?', ...':''}). Write the full path of the one you mean, for example ${matches[0]===file?'./':''}${matches[0]} instead of ${file}`:`unknown bare filename "${file}": it is not in the repository tree. Write the full repository path of the file (a new file needs its full path too; ./${file} names a file at the repository root), or remove the mention`);
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
if(treeFiles.has(file)) { inspectPath(file);want(file);continue; }
|
|
445
|
+
if(isTreeDir(file)) { inspectPath(file);warn(`the brief mentions directory ${file}, outside scope_paths; the worker cannot read it`);continue; }
|
|
446
|
+
// Not in the tree: an identifier, route or URL path (input.privateKey, secrets.API_TOKEN, /v1) names no file the worker could
|
|
447
|
+
// read. A file-shaped secret name (/home/u/credentials, .env, secrets.yaml) still refuses, and so do host paths, parent
|
|
448
|
+
// traversal and an absolute spelling of a repository path (/README.md never inherits scope).
|
|
449
|
+
// A router group cannot hide a sensitive name: web/(x).env is checked as web/.env.
|
|
450
|
+
if(fileShaped(file)&&(hardName(file)||(hasRouterSyntax(file)&&hardName(file.replace(/\[[^\]/]*\]\]?|\([^)/]*\)/g,''))))) throw new Error(`hard sensitive path exclusion: ${file}`);
|
|
451
|
+
const rest=file.replace(/^\/+/,''),unrouted=file.replace(/\[[^\]/]*\]\]?|\([^)/]*\)/g,'');
|
|
452
|
+
// A relative path the tree lacks is usually abbreviated (bin/x.ts for packages/p/bin/x.ts) or not a path (a branch name):
|
|
453
|
+
// it resolves like a bare filename, by suffix, and otherwise warns. Invalid syntax, traversal and router segments the tree
|
|
454
|
+
// lacks (x/$(id)/y.ts) refuse. Leading-slash routes (/v1, /me) pass; a file extension makes it a host file (/y.ts).
|
|
455
|
+
// A bare host directory in prose ("use ~/.tmp, not /tmp") names no file: it warns.
|
|
456
|
+
if(/^~\/\.(?:docker|kube)\/?$/.test(file)) throw new Error(`hard sensitive path exclusion: ${file}`);
|
|
457
|
+
if(/^(?:\/(?:tmp|home|var|etc|usr|opt)|~|~\/\.?\w[\w-]*|\$HOME)\/?$/.test(file)) { warn(`the brief mentions host directory ${file}; the worker cannot read host paths`);continue; }
|
|
458
|
+
if(hostPath.test(file)||hostPath.test(unrouted)) { undeclared.push(file);continue; }
|
|
459
|
+
if(!file.startsWith('/')) {
|
|
460
|
+
const invalid=hasRouterSyntax(file)||file.split('/').includes('..')||(()=>{try{paths([file],'mention');return false;}catch{return true;}})();
|
|
461
|
+
if(invalid) { undeclared.push(file);continue; }
|
|
462
|
+
const matches=scan.files.filter(f=>f.endsWith(`/${file}`));
|
|
463
|
+
if(matches.some(f=>within(f,scope))) continue;
|
|
464
|
+
if(matches.length===1) { inspectPath(matches[0]);want(matches[0],file);continue; }
|
|
465
|
+
if(matches.length) { ambiguous.push(`ambiguous abbreviated path "${file}": it matches ${matches.length} repository paths outside scope_paths (${matches.slice(0,5).join(', ')}${matches.length>5?', ...':''}). Write the full path of the one you mean, for example ${matches[0]===file?'./':''}${matches[0]} instead of ${file}`);continue; }
|
|
466
|
+
warn(`the brief names ${file}, which is not in the repository tree`);
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
// A leading-slash token with no file extension whose remainder is a tree directory (/showcase/docs) is a URL route.
|
|
470
|
+
if(!file.split('/').includes('..')&&!/\.[^/]*$/.test(file)&&!treeFiles.has(rest)&&isTreeDir(rest)) { warn(`the brief mentions ${file}, read as a route; the worker cannot read it`);continue; }
|
|
471
|
+
if(hostPath.test(file)||(file.startsWith('/')&&sourceExtension.test(file))||hostPath.test(unrouted)||file.split('/').includes('..')||(file.startsWith('/')&&(treeFiles.has(rest)||isTreeDir(rest)))) undeclared.push(file);
|
|
472
|
+
}
|
|
473
|
+
for(const file of scan.diffFiles) { inspectPath(file);if(!within(file,scope)) { if(growable&&input.head_sha) { scope.push(file);added.push(file); } else throw new Error(`diff outside scope_paths: ${file}`); } }
|
|
474
|
+
if(undeclared.length||fixable.length||ambiguous.length) {
|
|
475
|
+
const named=[...new Set([...undeclared,...fixable])];
|
|
476
|
+
const label=file=>mentionedAs.has(file)?`${file} (the brief names it as "${mentionedAs.get(file)}"; write the full path)`:file;
|
|
477
|
+
// Every offender is listed in one refusal. Without ambiguous mentions the first line keeps its short form.
|
|
478
|
+
const lines=[...(named.length?[`undeclared instruction path: ${named.map(label).join(', ')}`]:[]),...new Set(ambiguous)];
|
|
479
|
+
const error=new Error(lines.join('\n'));
|
|
480
|
+
// Only repository files that passed inspectPath are fixable: with any other kind of path the brief itself must change.
|
|
481
|
+
if(!undeclared.length&&!ambiguous.length) error.suggested_scope_paths=[...new Set([...scope,...fixable])];
|
|
482
|
+
throw error;
|
|
483
|
+
}
|
|
484
|
+
if(added.length) { warn(`scope_paths grew by ${added.length} path(s) the brief names or the PR changes: ${added.slice(0,10).join(', ')}${added.length>10?', ...':''}`);rendered={...rendered,scope_paths:[...scope]}; }
|
|
485
|
+
const taken=[];
|
|
486
|
+
// Case-insensitive and Unicode-normalizing filesystems (macOS) hold one file under several spellings. An output path that matches
|
|
487
|
+
// an existing tree path, directory or PR-diff path after lowercasing or NFC normalization (or both) would overwrite it there.
|
|
488
|
+
const lookalikeKeys=outputPathKeys.slice(1);
|
|
489
|
+
const existingPaths=new Set([...scan.files,...scan.diffFiles]);
|
|
490
|
+
for(const f of scan.files) for(let i=f.indexOf('/');i>0;i=f.indexOf('/',i+1)) existingPaths.add(f.slice(0,i));
|
|
491
|
+
const lookalikes=lookalikeKeys.map(key=>{const byKey=new Map();for(const e of existingPaths) { const k=key(e); if(!byKey.has(k)) byKey.set(k,e); } return byKey;});
|
|
492
|
+
// The output itself or any ancestor directory: an exact existing path is handled by the branches below, not here.
|
|
493
|
+
const lookalikeOf=file=>{
|
|
494
|
+
const parts=file.split('/');
|
|
495
|
+
for(let i=1;i<=parts.length;i++) {
|
|
496
|
+
const p=parts.slice(0,i).join('/');
|
|
497
|
+
if(existingPaths.has(p)) continue;
|
|
498
|
+
const hit=lookalikes.map((byKey,k)=>byKey.get(lookalikeKeys[k](p))).find(Boolean);
|
|
499
|
+
if(hit) return hit;
|
|
500
|
+
}
|
|
501
|
+
return undefined;
|
|
502
|
+
};
|
|
503
|
+
for(const file of outputs) {
|
|
504
|
+
const parts=file.split('/'),parent=parts.slice(1).map((_,i)=>parts.slice(0,i+1).join('/')).find(x=>treeFiles.has(x)),near=lookalikeOf(file);
|
|
505
|
+
if(treeFiles.has(file)||scan.diffFiles.includes(file)) taken.push(`${file} already exists at ${input.head_sha||input.base_sha}. output_paths declare NEW files only; ${rendered.execution_scope==='implementation'?'to change an existing file list it in scope_paths':'read-only scope cannot change an existing file'}, or choose a new path`);
|
|
506
|
+
else if(near) taken.push(`output path ${file} collides with existing ${near} on case-insensitive or Unicode-normalizing filesystems (macOS); choose another name`);
|
|
507
|
+
else if(isTreeDir(file)||scan.diffFiles.some(f=>f.startsWith(`${file}/`))) taken.push(`${file} is an existing directory (or the prefix of existing files); name a new file inside it, for example ${file}/notes.md`);
|
|
508
|
+
else if(parent) taken.push(`${file} cannot be created: ${parent} is a file at ${input.head_sha||input.base_sha}; choose a path whose parent directories are not files`);
|
|
509
|
+
}
|
|
510
|
+
if(taken.length) throw new Error(`output_paths: ${taken.join('\n')}`);
|
|
511
|
+
const unknown=scope.filter(s=>s!=='.'&&!scan.files.some(f=>f===s||f.startsWith(`${s}/`))&&!scan.diffFiles.includes(s));
|
|
512
|
+
if(unknown.length) {
|
|
513
|
+
const error=new Error(`unknown scope path: ${unknown.join(', ')}`), rest=scope.filter(s=>!unknown.includes(s));
|
|
514
|
+
// Where a path looks like a typo, the requester gets the tree paths it may have meant.
|
|
515
|
+
error.candidates=Object.fromEntries(unknown.map(u=>[u,nearestPaths(u,scan.files)]).filter(([,c])=>c.length));
|
|
516
|
+
if(rest.length) error.suggested_scope_paths=rest;
|
|
517
|
+
throw error;
|
|
518
|
+
}
|
|
519
|
+
// A directory scope can hold a sensitive file the submitter never named. With excludeSensitive those files leave the scope
|
|
520
|
+
// (it only narrows) and the reason is recorded; without it the whole submit fails, as before. A path the submitter named
|
|
521
|
+
// (a scope entry, a brief mention, a diff file) is never dropped quietly.
|
|
522
|
+
for(const file of scan.files.filter(f=>within(f,scope)&&!scope.includes(f))) {
|
|
523
|
+
try { inspectPath(file); }
|
|
524
|
+
catch(error) {
|
|
525
|
+
if(!/^(?:hard sensitive path exclusion|sensitive scope path): /.test(error.message)) throw error;
|
|
526
|
+
if(!excludeSensitive) throw error;
|
|
527
|
+
// Narrowing turns a directory into a file list; for implementation work that would forbid new files, so it is refused.
|
|
528
|
+
if(rendered.execution_scope==='implementation') throw new Error(`${error.message} (--exclude-sensitive applies to read-only work, not implementation scope)`);
|
|
529
|
+
dropped.push({path:file,reason:sensitiveReason(file)});
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
for(const file of scan.files.filter(f=>scope.includes(f))) inspectPath(file);
|
|
533
|
+
// A symlink inside a directory scope: the workspace never follows one (list skips it, read refuses), so read-only work
|
|
534
|
+
// with excludeSensitive records it as dropped instead of refusing the scope. A named symlink still refuses.
|
|
535
|
+
for(const file of scan.symlinks||[]) if(within(file,scope)&&!scope.includes(file)&&excludeSensitive&&rendered.execution_scope!=='implementation') dropped.push({path:file,reason:'symlink (the workspace never follows symlinks)'});
|
|
536
|
+
// A scope whose narrowing needs more than maxNarrowedEntries entries is refused (fail closed): keeping the broad scope
|
|
537
|
+
// would rest on an exact-path exclusion that a case or Unicode alias on a case-insensitive filesystem can miss.
|
|
538
|
+
if(dropped.length) narrowedScope=narrowScope(scope,[...new Set([...scan.files,...scan.diffFiles])],dropped.map(d=>d.path));
|
|
539
|
+
for(const file of scan.symlinks||[]) if(within(file,narrowedScope??scope)&&!dropped.some(d=>d.path===file)) throw new Error(`symlink in repository scope: ${file}`);
|
|
540
|
+
if(input.input_patch) {
|
|
541
|
+
if(/^new (?:file )?mode 120000$/m.test(input.input_patch)) throw new Error('symlink in input patch scope');
|
|
542
|
+
const parsed=spawnSync('git',['apply','--numstat','-z','-'],{input:input.input_patch,encoding:'utf8',timeout:10000,maxBuffer:1048576,env:gitEnv()});
|
|
543
|
+
if(parsed.error) throw infrastructureError('input patch scanner unavailable');
|
|
544
|
+
if(parsed.status!==0||!parsed.stdout) throw new Error('incomplete input patch; scanner failed');
|
|
545
|
+
for(const entry of parsed.stdout.split('\0').filter(Boolean)) {
|
|
546
|
+
const file=entry.includes('\t')?entry.split('\t').slice(2).join('\t'):entry;
|
|
547
|
+
if(!file) continue;
|
|
548
|
+
inspectPath(file);if(!within(file,scope)) throw new Error(`patch outside scope_paths: ${file}`);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
const patch=[scan.diff,input.input_patch||''].join('\n');
|
|
552
|
+
if(secretContent.test(patch)) throw new Error('hard sensitive patch content exclusion');
|
|
553
|
+
// The PR diff and input_patch are code under review: path-shaped tokens get the hard and policy checks, like an inlined diff.
|
|
554
|
+
codeInDiffFences(patch,inspectCode);
|
|
555
|
+
for(const m of patch.matchAll(/^(?:diff --git a\/(.+) b\/(.+)|(?:---|\+\+\+) [ab]\/(.+)|(?:rename (?:from|to)|copy (?:from|to)) (.+))$/gm)) for(const file of m.slice(1).filter(Boolean)) {
|
|
556
|
+
inspectPath(file);if(!within(file,scope)) throw new Error(`patch outside scope_paths: ${file}`);
|
|
557
|
+
}
|
|
558
|
+
if(input.input_patch&&!/^diff --git /m.test(input.input_patch)) throw new Error('incomplete input patch');
|
|
559
|
+
} else if(scope.length) throw new Error('scope_paths require pinned repository input');
|
|
560
|
+
if(!dropped.length) {const done=withOutputPaths(withAllowList(rendered,warn));checkInstructionSize(done);return done;}
|
|
561
|
+
const final=renderAssignment({...assignment,scope_paths:narrowedScope});
|
|
562
|
+
const note=`\n\nBridge scope note: ${dropped.length} sensitive file(s) are outside scope_paths; do not read them: ${dropped.slice(0,20).map(d=>d.path).join(', ')}${dropped.length>20?`, and ${dropped.length-20} more`:''}.`;
|
|
563
|
+
const brief=final.brief+note;
|
|
564
|
+
const expanded={...final,brief,scope_paths:narrowedScope,scope_excluded:dropped,...(final.read_paths!==undefined?{read_paths:narrowedScope}:{}),...(final.read_list!==undefined?{read_list:narrowedScope}:{})};
|
|
565
|
+
const finalBriefBytes=bytes(brief);
|
|
566
|
+
if(finalBriefBytes>submissionLimits.brief) throw Object.assign(new Error(`brief: ${finalBriefBytes} UTF-8 bytes exceeds ${submissionLimits.brief}; cut at least ${finalBriefBytes-submissionLimits.brief} bytes`),{expandedPayload:expanded});
|
|
567
|
+
warn(`${dropped.length} sensitive file(s) dropped from the directory scope (reasons in scope_excluded): ${dropped.slice(0,5).map(d=>d.path).join(', ')}${dropped.length>5?', ...':''}`);
|
|
568
|
+
// read_paths and read_list must keep equalling scope_paths, or they would still name a dropped file's directory.
|
|
569
|
+
const result=expanded;
|
|
570
|
+
checkInstructionSize(result);
|
|
571
|
+
const done=withOutputPaths(withAllowList(result,warn));
|
|
572
|
+
checkInstructionSize(done);
|
|
573
|
+
return done;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// The scope entries that cover every file under `scope` except `bad`: a directory with no bad file below it stays whole, one with
|
|
577
|
+
// a bad file is replaced by its children. Throws when that needs more entries than a scope should hold.
|
|
578
|
+
const maxNarrowedEntries=200;
|
|
579
|
+
export function narrowScope(scope,files,bad) {
|
|
580
|
+
const badSet=new Set(bad),badDirs=new Set(),children=new Map(),add=(dir,child)=>{if(!children.has(dir)) children.set(dir,new Set());children.get(dir).add(child);};
|
|
581
|
+
for(const file of files) {
|
|
582
|
+
const parts=file.split('/');
|
|
583
|
+
for(let i=0;i<parts.length;i++) add(parts.slice(0,i).join('/'),parts.slice(0,i+1).join('/'));
|
|
584
|
+
}
|
|
585
|
+
for(const file of badSet) { const parts=file.split('/'); for(let i=0;i<parts.length;i++) badDirs.add(parts.slice(0,i).join('/')); }
|
|
586
|
+
const out=[];
|
|
587
|
+
const visit=path=>{
|
|
588
|
+
if(badSet.has(path)) return;
|
|
589
|
+
if(!children.has(path)) { out.push(path); return; } // a file
|
|
590
|
+
if(!badDirs.has(path)) { out.push(path===''?'.':path); return; } // a directory with no bad file below
|
|
591
|
+
for(const child of [...children.get(path)].sort()) visit(child);
|
|
592
|
+
};
|
|
593
|
+
for(const entry of scope) visit(entry==='.'?'':entry);
|
|
594
|
+
const narrowed=[...new Set(out)];
|
|
595
|
+
if(!narrowed.length) throw new Error(`sensitive scope path: ${bad[0]} (every file in the scope is sensitive)`);
|
|
596
|
+
if(narrowed.length>maxNarrowedEntries) throw new Error(`sensitive scope path: ${bad[0]} (too many files to exclude from ${scope.map(s=>`"${s}"`).join(', ')}: dropping ${bad.length} sensitive file(s) would need ${narrowed.length} scope entries, over the ${maxNarrowedEntries} limit; submit a narrower scope that avoids them)`);
|
|
597
|
+
const unnameable=narrowed.find(entry=>{try{paths([entry],'scope_paths');return false;}catch{return true;}});
|
|
598
|
+
if(unnameable!==undefined) throw new Error(`sensitive scope path: ${bad[0]} (cannot narrow the scope: ${unnameable} has a name that scope_paths cannot hold; exclude it or name the files you want)`);
|
|
599
|
+
return paths(narrowed,'scope_paths');
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// Git fetch/diff are synchronous legacy helpers. Run admission scans off the
|
|
603
|
+
// server thread so slow repository I/O cannot stop progress on existing claims.
|
|
604
|
+
export async function validateSubmissionAsync(assignment,options={}) {
|
|
605
|
+
if(assignment.execution_scope!=='implementation'&&!assignment.inputs?.some(input=>input.github_repo!==undefined)) return validateSubmission(assignment,options);
|
|
606
|
+
let worker;
|
|
607
|
+
try { worker=new Worker(new URL(import.meta.url),{workerData:{operation:'submission',assignment,options:{...options,warnings:undefined},secrets:registeredSecrets()}}); }
|
|
608
|
+
catch(error) { throw infrastructureError(error.message); }
|
|
609
|
+
return new Promise((resolve,reject)=>{
|
|
610
|
+
const timer=setTimeout(()=>{reject(infrastructureError('submission scope scanner timeout'));worker.terminate();},180000);
|
|
611
|
+
// The worker holds a snapshot of the registry taken when it started. A secret registered later is checked here,
|
|
612
|
+
// in the main thread, before any verdict is returned.
|
|
613
|
+
const lateSecret=()=>{try{return hasSecretContent(renderAssignment(assignment));}catch{return false;}};
|
|
614
|
+
worker.once('message',message=>{clearTimeout(timer);if(lateSecret())reject(new Error('hard sensitive content exclusion'));else if(message.error)reject(message.code==='DOT_BRIDGE_INFRASTRUCTURE'?infrastructureError(message.error):Object.assign(new Error(message.error),message.suggested_scope_paths?{suggested_scope_paths:message.suggested_scope_paths}:{},message.candidates?{candidates:message.candidates}:{},message.expandedPayload?{expandedPayload:message.expandedPayload}:{}));else {for(const w of message.warnings||[]) if(options.warnings&&!options.warnings.includes(w)) options.warnings.push(w);resolve(message.assignment);}});
|
|
615
|
+
worker.once('error',error=>{clearTimeout(timer);reject(infrastructureError(error.message));});
|
|
616
|
+
worker.once('exit',code=>{clearTimeout(timer);if(code!==0)reject(infrastructureError('submission scope scanner failed'));});
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
if(!isMainThread&&workerData?.operation==='submission') {
|
|
620
|
+
for(const secret of workerData.secrets??[]) registerSecret(secret);
|
|
621
|
+
try {const warnings=[];parentPort.postMessage({assignment:validateSubmission(workerData.assignment,{...workerData.options,warnings}),warnings});}
|
|
622
|
+
catch(error) {parentPort.postMessage({error:error.message,code:error.code,suggested_scope_paths:error.suggested_scope_paths,candidates:error.candidates,expandedPayload:error.expandedPayload??null});}
|
|
623
|
+
}
|