opencode-workflow-guard 1.19.2 → 1.19.4
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/docs/installation.md +16 -0
- package/docs/policies.md +5 -4
- package/docs/testing.md +6 -2
- package/docs/troubleshooting.md +3 -2
- package/package.json +6 -6
- package/src/lib/custom-tools.ts +32 -4
- package/src/lib/guard-dispatcher.ts +28 -14
- package/src/lib/project-config.ts +5 -0
- package/src/lib/types.ts +8 -0
- package/src/lib/v2-plugin.ts +44 -3
- package/src/lib/verify.ts +19 -0
- package/src/policies/boundary.ts +128 -7
- package/src/policies/continuation.ts +66 -2
- package/src/policies/file-claims.ts +61 -15
- package/src/policies/interpreter.ts +6 -2
- package/src/workflow-guard.ts +13 -1
- package/test/test-e2e.mts +20 -4
- package/test/test.mts +278 -17
package/src/policies/boundary.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { realpathSync } from "node:fs";
|
|
1
|
+
import { lstatSync, realpathSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { dirname, join, resolve } from "node:path";
|
|
4
4
|
import type { ShellMutation } from "../lib/types.ts";
|
|
@@ -11,7 +11,8 @@ import { isLeadingEvalSegment, maskDataHeredocBodies, prepareRedirectResidue, pl
|
|
|
11
11
|
import { isCollaborationInvocation, isProtectedPath, PROTECTED_PATH_REASON } from "./tamper.ts";
|
|
12
12
|
import { isSecretPath, secretIn } from "./secrets.ts";
|
|
13
13
|
import { isGitTreeWriteText, branchGuardReason, onProtectedBranch, parseGitInvocation } from "./git.ts";
|
|
14
|
-
import { isSameGitRepo } from "../lib/project-config.ts";
|
|
14
|
+
import { findGitRoot, isSameGitRepo, projectRootKey } from "../lib/project-config.ts";
|
|
15
|
+
import { canonicalPath } from "./file-claims.ts";
|
|
15
16
|
import {
|
|
16
17
|
effectiveTodos,
|
|
17
18
|
effectiveTodoOwnerSessionID,
|
|
@@ -81,6 +82,61 @@ export function isEnvironmentScratchTarget(targetPath: string, root: string): bo
|
|
|
81
82
|
return resolved === OPENCODE_SCRATCH_DIR || resolved.startsWith(OPENCODE_SCRATCH_DIR + "/");
|
|
82
83
|
}
|
|
83
84
|
|
|
85
|
+
/**
|
|
86
|
+
* Real path of the scratch root, or undefined when it is missing or a symlink.
|
|
87
|
+
*
|
|
88
|
+
* The scratch allowance is scoped to one real directory. A symlinked root
|
|
89
|
+
* would make `/tmp/opencode -> /etc` a write grant over `/etc`, so the root
|
|
90
|
+
* itself must be a real directory; symlinks *inside* it are resolved and
|
|
91
|
+
* refused below when they leave.
|
|
92
|
+
*/
|
|
93
|
+
function scratchRealRoot(scratchRoot: string): string | undefined {
|
|
94
|
+
try {
|
|
95
|
+
const stat = lstatSync(scratchRoot);
|
|
96
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) return undefined;
|
|
97
|
+
return realpathSync(scratchRoot);
|
|
98
|
+
} catch {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Whether a resolved path is a sanctioned scratch write.
|
|
105
|
+
*
|
|
106
|
+
* Writes are allowed only under the exact pre-created scratch directory, only
|
|
107
|
+
* for a real session (the session id gates the allowance), and only when the
|
|
108
|
+
* target's canonical location stays inside that directory. Symlinks that
|
|
109
|
+
* leave it are refused. This is a write allowance only: it does not make the
|
|
110
|
+
* directory an execution surface and it does not widen the workspace boundary
|
|
111
|
+
* anywhere else.
|
|
112
|
+
*/
|
|
113
|
+
export function isAllowedScratchPath(
|
|
114
|
+
resolvedPath: string,
|
|
115
|
+
sessionID: string | undefined,
|
|
116
|
+
scratchRoot = OPENCODE_SCRATCH_DIR,
|
|
117
|
+
): boolean {
|
|
118
|
+
if (!sessionID || !resolvedPath) return false;
|
|
119
|
+
const scratch = resolve(scratchRoot);
|
|
120
|
+
if (resolvedPath !== scratch && !resolvedPath.startsWith(scratch + "/")) return false;
|
|
121
|
+
const realScratch = scratchRealRoot(scratchRoot);
|
|
122
|
+
if (!realScratch) return false;
|
|
123
|
+
const canonical = canonicalPath(resolvedPath);
|
|
124
|
+
return canonical === realScratch || canonical.startsWith(realScratch + "/");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Resolve a command's target against its run root, then judge scratch scope. */
|
|
128
|
+
export function isAllowedScratchTarget(
|
|
129
|
+
targetPath: string,
|
|
130
|
+
root: string,
|
|
131
|
+
sessionID: string | undefined,
|
|
132
|
+
scratchRoot = OPENCODE_SCRATCH_DIR,
|
|
133
|
+
): boolean {
|
|
134
|
+
if (!sessionID || !targetPath) return false;
|
|
135
|
+
const expanded = expandShellTargetPath(targetPath);
|
|
136
|
+
if (expanded === null) return false;
|
|
137
|
+
return isAllowedScratchPath(resolve(root, expanded), sessionID, scratchRoot);
|
|
138
|
+
}
|
|
139
|
+
|
|
84
140
|
export function isPathOutsideWorkspace(targetPath: string, root: string): boolean {
|
|
85
141
|
if (!targetPath) return false;
|
|
86
142
|
const expanded = expandShellTargetPath(targetPath);
|
|
@@ -136,6 +192,42 @@ export function isPathOutsideWorkspace(targetPath: string, root: string): boolea
|
|
|
136
192
|
return lexicallyOutside && !canonicallyInside;
|
|
137
193
|
}
|
|
138
194
|
|
|
195
|
+
/**
|
|
196
|
+
* The linked worktree a target belongs to when the session is bound elsewhere.
|
|
197
|
+
*
|
|
198
|
+
* A subagent's workspace is the directory its session opened in, not the
|
|
199
|
+
* worktree named in its brief. The mutation is still refused (a tool-call path
|
|
200
|
+
* never re-anchors the boundary), but the block must name the mismatch and the
|
|
201
|
+
* move, or the agent works around the guard through the shell.
|
|
202
|
+
*/
|
|
203
|
+
export function linkedWorktreeMismatch(targetPath: string, root: string, boundRoot = root): string | undefined {
|
|
204
|
+
const expanded = expandShellTargetPath(targetPath);
|
|
205
|
+
if (expanded === null) return undefined;
|
|
206
|
+
const resolved = resolve(root, expanded);
|
|
207
|
+
if (!isPathOutsideWorkspace(resolved, boundRoot)) return undefined;
|
|
208
|
+
let ancestor = resolved;
|
|
209
|
+
while (true) {
|
|
210
|
+
try {
|
|
211
|
+
const stat = lstatSync(ancestor);
|
|
212
|
+
if (stat.isDirectory() || stat.isFile()) break;
|
|
213
|
+
} catch {}
|
|
214
|
+
const parent = dirname(ancestor);
|
|
215
|
+
if (parent === ancestor) return undefined;
|
|
216
|
+
ancestor = parent;
|
|
217
|
+
}
|
|
218
|
+
const worktreeRoot = findGitRoot(ancestor);
|
|
219
|
+
if (!worktreeRoot) return undefined;
|
|
220
|
+
if (projectRootKey(worktreeRoot) === projectRootKey(boundRoot)) return undefined;
|
|
221
|
+
if (!isSameGitRepo(worktreeRoot, boundRoot)) return undefined;
|
|
222
|
+
return worktreeRoot;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function linkedWorktreeMismatchReason(targetPath: string, root: string, boundRoot = root): string | undefined {
|
|
226
|
+
const worktreeRoot = linkedWorktreeMismatch(targetPath, root, boundRoot);
|
|
227
|
+
if (!worktreeRoot) return undefined;
|
|
228
|
+
return `Blocked: file path '${targetPath}' is inside the linked worktree '${worktreeRoot}', but this session is bound to '${boundRoot}'. Move the session with the OpenCode session_move tool (directory: '${worktreeRoot}'), or start the subagent in that worktree, before editing.`;
|
|
229
|
+
}
|
|
230
|
+
|
|
139
231
|
export function extractPatchPaths(patchText: string): string[] {
|
|
140
232
|
const paths: string[] = [];
|
|
141
233
|
const markerRe =
|
|
@@ -386,6 +478,7 @@ function stripQuotedSpans(segment: string): string {
|
|
|
386
478
|
export function foreignSegmentMutationReason(
|
|
387
479
|
segments: ShellSegmentPlan[],
|
|
388
480
|
workspaceRoot: string,
|
|
481
|
+
sessionID?: string,
|
|
389
482
|
): string | undefined {
|
|
390
483
|
for (const { segment, root } of segments) {
|
|
391
484
|
const mutation = detectShellMutation(segment);
|
|
@@ -394,6 +487,17 @@ export function foreignSegmentMutationReason(
|
|
|
394
487
|
if (root === undefined) {
|
|
395
488
|
return `Blocked: the command changes directory to a target that cannot be determined without executing shell expansion, then runs a mutation (${mutation?.what ?? "git write"}). Indeterminate destinations are treated as outside the workspace root (${workspaceRoot}). Use a literal directory inside the workspace.`;
|
|
396
489
|
}
|
|
490
|
+
// A directory change into the sanctioned scratch root is not a foreign
|
|
491
|
+
// tree. A file mutation there is judged by its target in the per-segment
|
|
492
|
+
// loop, so a target that leaves the directory gets the right cause. A git
|
|
493
|
+
// write gets none of that, and scratch is not a repository this session
|
|
494
|
+
// may mutate.
|
|
495
|
+
if (isAllowedScratchPath(root, sessionID)) {
|
|
496
|
+
if (gitWrite) {
|
|
497
|
+
return `Blocked: a git write runs in ${OPENCODE_SCRATCH_DIR}, the scratch directory, which is not a repository this session may mutate. Run git from the workspace checkout instead.`;
|
|
498
|
+
}
|
|
499
|
+
continue;
|
|
500
|
+
}
|
|
397
501
|
if (!isPathOutsideWorkspace(root, workspaceRoot) || isSameGitRepo(root, workspaceRoot)) continue;
|
|
398
502
|
return `Blocked: the command changes into '${root}' and mutates it (${mutation?.what ?? "git write"}), but that directory is outside workspace root (${workspaceRoot}) and is not a linked worktree of this repository. Relative targets there cannot be validated against the tree the command would actually change. Run the command from inside the workspace instead.`;
|
|
399
503
|
}
|
|
@@ -575,6 +679,7 @@ export function nestedPayloadMutationReason(
|
|
|
575
679
|
command: string,
|
|
576
680
|
baseDir: string,
|
|
577
681
|
workspaceRoot: string,
|
|
682
|
+
sessionID?: string,
|
|
578
683
|
depth = 0,
|
|
579
684
|
): string | undefined {
|
|
580
685
|
// Nesting deeper than this is not modelled. A launcher chain that deep is
|
|
@@ -608,12 +713,12 @@ export function nestedPayloadMutationReason(
|
|
|
608
713
|
if (foreignRepo) {
|
|
609
714
|
return `Blocked: the inline interpreter script runs a git write against '${foreignRepo}', outside workspace root (${workspaceRoot}) and not a linked worktree of this repository. Run the command from inside the workspace instead.`;
|
|
610
715
|
}
|
|
611
|
-
const nested = foreignSegmentMutationReason(planShellSegments(payload, launcherRoot), workspaceRoot);
|
|
716
|
+
const nested = foreignSegmentMutationReason(planShellSegments(payload, launcherRoot), workspaceRoot, sessionID);
|
|
612
717
|
if (nested) return nested;
|
|
613
718
|
// A payload can launch another interpreter: `bash -c "bash -c 'cd
|
|
614
719
|
// <other> && git commit'"` only extracts its own quoted body. Re-plan
|
|
615
720
|
// each payload until the nesting bottoms out.
|
|
616
|
-
const inner = nestedPayloadMutationReason(extractPayloads, writesIn, payload, launcherRoot, workspaceRoot, depth + 1);
|
|
721
|
+
const inner = nestedPayloadMutationReason(extractPayloads, writesIn, payload, launcherRoot, workspaceRoot, sessionID, depth + 1);
|
|
617
722
|
if (inner) return inner;
|
|
618
723
|
const declared = payloadWorkingRoot(payload);
|
|
619
724
|
if (declared.status === "none") continue;
|
|
@@ -622,6 +727,13 @@ export function nestedPayloadMutationReason(
|
|
|
622
727
|
return `Blocked: the inline interpreter script runs a mutating command in a working directory that cannot be determined without executing the script (${declared.raw}). Indeterminate destinations are treated as outside the workspace root (${workspaceRoot}). Use a literal directory inside the workspace.`;
|
|
623
728
|
}
|
|
624
729
|
const targetRoot = resolve(launcherRoot, declared.root);
|
|
730
|
+
// A payload whose declared working directory and every detected
|
|
731
|
+
// write stay inside the sanctioned scratch root is a scratch write,
|
|
732
|
+
// not a foreign-tree mutation.
|
|
733
|
+
if (isAllowedScratchPath(targetRoot, sessionID) && !isGitTreeWriteText(payload)) {
|
|
734
|
+
const scratchWrites = writesIn(payload);
|
|
735
|
+
if (scratchWrites.length > 0 && scratchWrites.every((write) => isAllowedScratchTarget(write, targetRoot, sessionID))) continue;
|
|
736
|
+
}
|
|
625
737
|
if (!isPathOutsideWorkspace(targetRoot, workspaceRoot) || isSameGitRepo(targetRoot, workspaceRoot)) continue;
|
|
626
738
|
return `Blocked: the inline interpreter script runs a mutating command in '${targetRoot}', outside workspace root (${workspaceRoot}) and not a linked worktree of this repository. Relative targets there cannot be validated against the tree the command would actually change. Run the command from inside the workspace instead.`;
|
|
627
739
|
}
|
|
@@ -667,7 +779,7 @@ export async function guardShellMutation(
|
|
|
667
779
|
// The foreign-tree gate runs here too, so this function is safe when called
|
|
668
780
|
// on its own: an indeterminate or foreign `cd` is refused instead of silently
|
|
669
781
|
// falling back to judging relative targets against the wrong tree.
|
|
670
|
-
const foreignReason = foreignSegmentMutationReason(plan, workspaceRoot);
|
|
782
|
+
const foreignReason = foreignSegmentMutationReason(plan, workspaceRoot, sessionID);
|
|
671
783
|
if (foreignReason) return foreignReason;
|
|
672
784
|
let hasMutation = false;
|
|
673
785
|
for (const { segment, root: segmentRoot } of plan) {
|
|
@@ -722,7 +834,6 @@ export async function guardShellMutation(
|
|
|
722
834
|
if (fallbackMutation) mutations.push(fallbackMutation);
|
|
723
835
|
}
|
|
724
836
|
for (const mutation of mutations) {
|
|
725
|
-
hasMutation = true;
|
|
726
837
|
const secret = secretIn(cleanSegment);
|
|
727
838
|
if (secret) {
|
|
728
839
|
return `Blocked: shell file mutation payload appears to contain a ${secret}. Secrets must not be written to disk from agent commands.`;
|
|
@@ -731,6 +842,12 @@ export async function guardShellMutation(
|
|
|
731
842
|
if (target && isProtectedPath(target)) {
|
|
732
843
|
return PROTECTED_PATH_REASON;
|
|
733
844
|
}
|
|
845
|
+
// A scratch write is sanctioned only for a real session and only
|
|
846
|
+
// while its canonical target stays inside the pre-created root. It
|
|
847
|
+
// is not a repository mutation, so it does not advance task evidence
|
|
848
|
+
// or the feature-branch requirement.
|
|
849
|
+
if (isAllowedScratchTarget(target, runRoot, sessionID)) continue;
|
|
850
|
+
hasMutation = true;
|
|
734
851
|
if (target && outsideWorkspace(target)) {
|
|
735
852
|
// The workspace boundary has no override: a write outside the
|
|
736
853
|
// workspace is out of bounds even with WORKFLOW_GUARD_ALLOW_LIVE
|
|
@@ -739,8 +856,12 @@ export async function guardShellMutation(
|
|
|
739
856
|
return `Blocked: shell mutation '${mutation.what}' targets '${target}', which contains an unresolvable variable reference; indeterminate destinations are treated as outside the workspace root (${workspaceRoot}). Use a literal workspace-relative path.`;
|
|
740
857
|
}
|
|
741
858
|
if (isEnvironmentScratchTarget(target, runRoot)) {
|
|
742
|
-
return
|
|
859
|
+
return sessionID
|
|
860
|
+
? `Blocked: shell mutation '${mutation.what}' targets '${target}', which is under ${OPENCODE_SCRATCH_DIR} but does not resolve inside it (a symlink leaves the directory, or the root is not a real directory), so the scratch allowance does not cover it. Use a real path inside that directory or inside the workspace root (${workspaceRoot}).`
|
|
861
|
+
: `Blocked: shell mutation '${mutation.what}' targets '${target}' under ${OPENCODE_SCRATCH_DIR}, the environment scratch directory the workspace boundary does not cover without a session; write scratch as an untracked file inside the workspace root (${workspaceRoot}) instead (for example .tmp-notes.md).`;
|
|
743
862
|
}
|
|
863
|
+
const mismatch = linkedWorktreeMismatchReason(target, runRoot, workspaceRoot);
|
|
864
|
+
if (mismatch) return mismatch;
|
|
744
865
|
return `Blocked: shell mutation '${mutation.what}' targets a path outside the workspace root (${workspaceRoot}). All changes must stay within the workspace.`;
|
|
745
866
|
}
|
|
746
867
|
if (onProtectedBranch(runRoot)) {
|
|
@@ -36,16 +36,80 @@ export async function waitForSessionTitle(sessionID: string): Promise<void> {
|
|
|
36
36
|
const session = getSdkClient()?.session;
|
|
37
37
|
if (typeof session?.get !== "function") return;
|
|
38
38
|
for (let attempt = 0; attempt < TITLE_SETTLE_ATTEMPTS; attempt++) {
|
|
39
|
+
// Register the wake-up BEFORE reading, then release it once the read is
|
|
40
|
+
// done. A rename that commits during the read is therefore still
|
|
41
|
+
// observed: registering afterwards would let it land in the gap between
|
|
42
|
+
// the read and the registration, which reads as "not yet renamed" and
|
|
43
|
+
// costs a whole extra interval even though the title already settled.
|
|
44
|
+
const wait = beginRenameWait(sessionID);
|
|
45
|
+
let settled = false;
|
|
39
46
|
try {
|
|
40
47
|
const current = (await session.get({ path: { id: sessionID } }))?.data;
|
|
41
|
-
|
|
48
|
+
settled = Boolean(current?.parentID) || typeof current?.title !== "string" || !DEFAULT_SESSION_TITLE.test(current.title);
|
|
42
49
|
} catch {
|
|
50
|
+
wait.cancel();
|
|
43
51
|
return;
|
|
44
52
|
}
|
|
45
|
-
if (
|
|
53
|
+
if (settled) {
|
|
54
|
+
wait.cancel();
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (attempt + 1 >= TITLE_SETTLE_ATTEMPTS) {
|
|
58
|
+
wait.cancel();
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
await wait.promise;
|
|
46
62
|
}
|
|
47
63
|
}
|
|
48
64
|
|
|
65
|
+
/**
|
|
66
|
+
* A pending wait for one session's title, resolved by `session.renamed` or by
|
|
67
|
+
* one poll interval elapsing.
|
|
68
|
+
*
|
|
69
|
+
* The poll exists because the host generates a title asynchronously and a
|
|
70
|
+
* continuation sent too early can be titled with the placeholder. `title` is a
|
|
71
|
+
* model-request hook, so it runs *before* the title is written and cannot
|
|
72
|
+
* report that the write happened. `session.renamed` is delivered when it does,
|
|
73
|
+
* so the normal case ends as soon as the title commits while the worst case
|
|
74
|
+
* stays the old interval. A host that never emits the event keeps the old
|
|
75
|
+
* timing exactly.
|
|
76
|
+
*/
|
|
77
|
+
function beginRenameWait(sessionID: string): { promise: Promise<void>; cancel: () => void } {
|
|
78
|
+
const waiters = renaming.get(sessionID) ?? new Set<() => void>();
|
|
79
|
+
renaming.set(sessionID, waiters);
|
|
80
|
+
let finish!: () => void;
|
|
81
|
+
const promise = new Promise<void>((resolve) => {
|
|
82
|
+
finish = resolve;
|
|
83
|
+
});
|
|
84
|
+
let settled = false;
|
|
85
|
+
const done = (): void => {
|
|
86
|
+
if (settled) return;
|
|
87
|
+
settled = true;
|
|
88
|
+
waiters.delete(done);
|
|
89
|
+
if (waiters.size === 0) renaming.delete(sessionID);
|
|
90
|
+
clearTimeout(timer);
|
|
91
|
+
finish();
|
|
92
|
+
};
|
|
93
|
+
waiters.add(done);
|
|
94
|
+
// A plain timer, not `unref`: an unref'd timer lets the process exit while
|
|
95
|
+
// this promise is still pending, which would drop the wait.
|
|
96
|
+
const timer = setTimeout(done, TITLE_SETTLE_MS);
|
|
97
|
+
return { promise, cancel: done };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Named `renaming` rather than `sessions` to read as the event, not the store. */
|
|
101
|
+
const renaming = new Map<string, Set<() => void>>();
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Wake any wait for this session's title. Called from the `session.renamed`
|
|
105
|
+
* subscription; a session with no waiter is a no-op.
|
|
106
|
+
*/
|
|
107
|
+
export function notifySessionRenamed(sessionID: string): void {
|
|
108
|
+
const waiters = renaming.get(sessionID);
|
|
109
|
+
if (!waiters) return;
|
|
110
|
+
for (const waiter of [...waiters]) waiter();
|
|
111
|
+
}
|
|
112
|
+
|
|
49
113
|
function getState(): ContinuationState | undefined {
|
|
50
114
|
const client = getSdkClient();
|
|
51
115
|
if (!client || (typeof client !== "object" && typeof client !== "function")) return undefined;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readlinkSync, realpathSync } from "node:fs";
|
|
2
2
|
import { dirname, relative, resolve } from "node:path";
|
|
3
3
|
import { audit } from "../lib/audit.ts";
|
|
4
|
-
import { getSdkClient } from "../lib/state.ts";
|
|
4
|
+
import { getProjectConfig, getSdkClient, getWorkspaceRoot } from "../lib/state.ts";
|
|
5
5
|
|
|
6
6
|
interface FileClaim {
|
|
7
7
|
sessionID: string;
|
|
@@ -12,6 +12,21 @@ interface FileClaim {
|
|
|
12
12
|
|
|
13
13
|
const claims = new Map<string, FileClaim>();
|
|
14
14
|
|
|
15
|
+
/** Default claim TTL: a claim this old is leaked, because a tool call is not that long. */
|
|
16
|
+
export const DEFAULT_FILE_CLAIM_TTL_MS = 5 * 60_000;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Effective claim TTL: `WORKFLOW_GUARD_CLAIM_TTL_MS` wins, then project config
|
|
20
|
+
* `claimTtlMs`, then the 5-minute default. Non-positive or unparseable values
|
|
21
|
+
* fall back to the default so a typo cannot disable expiry.
|
|
22
|
+
*/
|
|
23
|
+
export function fileClaimTtlMs(root: string = getWorkspaceRoot()): number {
|
|
24
|
+
const envValue = Number(process.env.WORKFLOW_GUARD_CLAIM_TTL_MS);
|
|
25
|
+
if (Number.isFinite(envValue) && envValue > 0) return envValue;
|
|
26
|
+
const configured = getProjectConfig(root).claimTtlMs;
|
|
27
|
+
return typeof configured === "number" && Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_FILE_CLAIM_TTL_MS;
|
|
28
|
+
}
|
|
29
|
+
|
|
15
30
|
export function canonicalPath(path: string, seen = new Set<string>()): string {
|
|
16
31
|
const resolved = resolve(path);
|
|
17
32
|
if (seen.has(resolved)) return resolved;
|
|
@@ -53,12 +68,15 @@ export function claimFiles(paths: string[], sessionID: string, callID: string):
|
|
|
53
68
|
return undefined;
|
|
54
69
|
}
|
|
55
70
|
|
|
56
|
-
export function fileClaimConflictReason(paths: string[], sessionID: string): string | undefined {
|
|
71
|
+
export function fileClaimConflictReason(paths: string[], sessionID: string, root: string = getWorkspaceRoot()): string | undefined {
|
|
57
72
|
const canonical = [...new Set(paths.map((path) => canonicalPath(path)))];
|
|
73
|
+
const ttlMs = fileClaimTtlMs(root);
|
|
58
74
|
for (const path of canonical) {
|
|
59
75
|
const existing = claims.get(path);
|
|
60
76
|
if (existing && existing.sessionID !== sessionID) {
|
|
61
|
-
|
|
77
|
+
const ageMs = Math.max(0, Date.now() - existing.ts);
|
|
78
|
+
const remainingSec = Math.max(1, Math.ceil((ttlMs - ageMs) / 1000));
|
|
79
|
+
return `Blocked: file '${path}' is claimed by session '${existing.sessionID}' (claimed ${Math.round(ageMs / 1000)}s ago). Reclaim step: retry after the claim TTL (${remainingSec}s remaining), when the guard releases and audits a stale claim. Otherwise wait for that session's edit to finish, or use an isolated worktree.`;
|
|
62
80
|
}
|
|
63
81
|
}
|
|
64
82
|
return undefined;
|
|
@@ -67,22 +85,50 @@ export function fileClaimConflictReason(paths: string[], sessionID: string): str
|
|
|
67
85
|
/**
|
|
68
86
|
* A claim is normally released by its owning tool call (after-hook) or by the
|
|
69
87
|
* owner's session.idle/session.deleted events. When an idle release is missed,
|
|
70
|
-
* the claim would otherwise block every other session forever.
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
88
|
+
* the claim would otherwise block every other session forever. Two provable
|
|
89
|
+
* staleness rules reclaim it, each audited:
|
|
90
|
+
*
|
|
91
|
+
* - TTL: a claim older than `claimTtlMs` cannot belong to an in-flight tool
|
|
92
|
+
* call. It is released even when the owner's session record cannot be read,
|
|
93
|
+
* which covers a deleted session and a server restart.
|
|
94
|
+
* - Idle: a claim created BEFORE its owner's last recorded idle timestamp
|
|
95
|
+
* finished before the turn ended. Without an SDK client, or when the owner
|
|
96
|
+
* record cannot be read, this rule releases nothing: fail-closed keeps live
|
|
97
|
+
* two-session protection intact.
|
|
98
|
+
*
|
|
99
|
+
* Clock skew between this process and the server is not expected for a local
|
|
100
|
+
* (same-host) service: negative skew fails closed; forward skew could make
|
|
101
|
+
* fresh claims look stale and is accepted for that deployment. Concurrent
|
|
102
|
+
* claimants can emit duplicate reclaim audits (append-only, harmless). Release
|
|
103
|
+
* is per-claim: only claims whose ts is provably stale are dropped, re-read
|
|
81
104
|
* AFTER the lookup round-trip so an owner that re-claimed (and refreshed) a
|
|
82
105
|
* path meanwhile keeps its live claim.
|
|
83
106
|
*/
|
|
84
|
-
export async function releaseStaleFileClaims(paths: string[], claimantSessionID: string): Promise<void> {
|
|
107
|
+
export async function releaseStaleFileClaims(paths: string[], claimantSessionID: string, root: string = getWorkspaceRoot()): Promise<void> {
|
|
85
108
|
const canonical = [...new Set(paths.map((path) => canonicalPath(path)))];
|
|
109
|
+
// A claim older than the TTL cannot belong to an in-flight tool call, so it
|
|
110
|
+
// is a leak from a session that ended without an idle/deleted release. It
|
|
111
|
+
// is released even when the owner's record cannot be read (a deleted
|
|
112
|
+
// session, a missing SDK lookup, a server restart), with an audited
|
|
113
|
+
// reclaim. Only the contended paths are examined, so a long-running command
|
|
114
|
+
// elsewhere keeps its claim.
|
|
115
|
+
const ttlMs = fileClaimTtlMs(root);
|
|
116
|
+
const now = Date.now();
|
|
117
|
+
for (const claimPath of canonical) {
|
|
118
|
+
const claim = claims.get(claimPath);
|
|
119
|
+
if (!claim || claim.sessionID === claimantSessionID) continue;
|
|
120
|
+
if (now - claim.ts < ttlMs) continue;
|
|
121
|
+
claims.delete(claimPath);
|
|
122
|
+
audit({
|
|
123
|
+
ts: new Date().toISOString(),
|
|
124
|
+
sessionID: claimantSessionID,
|
|
125
|
+
tool: "file-claims",
|
|
126
|
+
decision: "allow",
|
|
127
|
+
phase: "event",
|
|
128
|
+
reason: "claim_ttl_expired",
|
|
129
|
+
evidence: { mutation: false, targetPath: claimPath, claimOwnerSessionID: claim.sessionID, claimAgeMs: now - claim.ts },
|
|
130
|
+
});
|
|
131
|
+
}
|
|
86
132
|
const staleOwners = new Map<string, string>();
|
|
87
133
|
for (const path of canonical) {
|
|
88
134
|
const existing = claims.get(path);
|
|
@@ -154,7 +154,11 @@ const WRITE_TARGET_PATTERNS: RegExp[] = [
|
|
|
154
154
|
* workspace root) initiated from inline interpreter payloads. Extracts destination
|
|
155
155
|
* file arguments from file-writing APIs and shell redirects.
|
|
156
156
|
*/
|
|
157
|
-
export function outsideWritePathInPayload(
|
|
157
|
+
export function outsideWritePathInPayload(
|
|
158
|
+
payload: string,
|
|
159
|
+
root: string,
|
|
160
|
+
isAllowed: (candidate: string) => boolean = () => false,
|
|
161
|
+
): string | undefined {
|
|
158
162
|
const candidates = new Set<string>();
|
|
159
163
|
|
|
160
164
|
for (const pattern of WRITE_TARGET_PATTERNS) {
|
|
@@ -166,7 +170,7 @@ export function outsideWritePathInPayload(payload: string, root: string): string
|
|
|
166
170
|
|
|
167
171
|
for (const candidate of candidates) {
|
|
168
172
|
if (/^\/dev\/(?:null|stdout|stderr|tty|fd\/\d+)$/.test(candidate)) continue;
|
|
169
|
-
if (isPathOutsideWorkspace(candidate, root)) {
|
|
173
|
+
if (isPathOutsideWorkspace(candidate, root) && !isAllowed(candidate)) {
|
|
170
174
|
return candidate;
|
|
171
175
|
}
|
|
172
176
|
}
|
package/src/workflow-guard.ts
CHANGED
|
@@ -107,7 +107,9 @@ import {
|
|
|
107
107
|
resolveSessionBoundWorkspace,
|
|
108
108
|
resolveEffectiveWorkspace,
|
|
109
109
|
} from "./lib/state.ts";
|
|
110
|
-
import { findGitRoot, isSameGitRepo, loadProjectConfig, reloadProjectConfig, stripJsonComments } from "./lib/project-config.ts";
|
|
110
|
+
import { existingProjectConfigPath, findGitRoot, isSameGitRepo, loadProjectConfig, reloadProjectConfig, stripJsonComments } from "./lib/project-config.ts";
|
|
111
|
+
|
|
112
|
+
export { existingProjectConfigPath };
|
|
111
113
|
|
|
112
114
|
export {
|
|
113
115
|
setWorkspaceRoot,
|
|
@@ -247,6 +249,7 @@ import {
|
|
|
247
249
|
getGitStatusSummary,
|
|
248
250
|
getGitWorktreeFingerprint,
|
|
249
251
|
getTrackedWorktreeFingerprint,
|
|
252
|
+
verifyCommandSource,
|
|
250
253
|
} from "./lib/verify.ts";
|
|
251
254
|
|
|
252
255
|
export {
|
|
@@ -258,6 +261,7 @@ export {
|
|
|
258
261
|
getGitStatusSummary,
|
|
259
262
|
getGitWorktreeFingerprint,
|
|
260
263
|
getTrackedWorktreeFingerprint,
|
|
264
|
+
verifyCommandSource,
|
|
261
265
|
};
|
|
262
266
|
export type { VerifyRun } from "./lib/verify.ts";
|
|
263
267
|
|
|
@@ -349,6 +353,14 @@ import { isSecretPath, secretIn, isEnvFilePath, generateMaskedEnvSchema } from "
|
|
|
349
353
|
|
|
350
354
|
export { isSecretPath, isEnvFilePath, generateMaskedEnvSchema };
|
|
351
355
|
|
|
356
|
+
import { isAllowedScratchTarget } from "./policies/boundary.ts";
|
|
357
|
+
|
|
358
|
+
export { isAllowedScratchTarget, OPENCODE_SCRATCH_DIR };
|
|
359
|
+
|
|
360
|
+
import { DEFAULT_FILE_CLAIM_TTL_MS, fileClaimTtlMs } from "./policies/file-claims.ts";
|
|
361
|
+
|
|
362
|
+
export { DEFAULT_FILE_CLAIM_TTL_MS, fileClaimTtlMs };
|
|
363
|
+
|
|
352
364
|
import {
|
|
353
365
|
extractInterpreterPayload,
|
|
354
366
|
secretPathInPayload,
|
package/test/test-e2e.mts
CHANGED
|
@@ -34,6 +34,20 @@ console.log("- OpenCode Plugin Installation & Runtime Load Test -");
|
|
|
34
34
|
// checks run even when the optional live OpenCode binary is unavailable.
|
|
35
35
|
const testDir = mkdtempSync(join(tmpdir(), "wg-install-test-"));
|
|
36
36
|
|
|
37
|
+
// Every isolated XDG root that a live probe may start a managed service under.
|
|
38
|
+
const liveServiceEnvs: NodeJS.ProcessEnv[] = [];
|
|
39
|
+
// `opencode debug config` auto-starts a detached `serve --service` under the
|
|
40
|
+
// probe's own XDG roots. Killing the probe child leaves that service running and
|
|
41
|
+
// writing into testDir, so a bare rmSync races it and fails with ENOTEMPTY.
|
|
42
|
+
// Stop each tracked service first, then retry the removal.
|
|
43
|
+
const cleanupTestDir = (): void => {
|
|
44
|
+
if (process.env.WG_E2E_KEEP) return;
|
|
45
|
+
for (const env of liveServiceEnvs) {
|
|
46
|
+
spawnSync("opencode", ["service", "stop"], { cwd: testDir, encoding: "utf8", env, timeout: 30_000 });
|
|
47
|
+
}
|
|
48
|
+
rmSync(testDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
|
49
|
+
};
|
|
50
|
+
|
|
37
51
|
// Verify the publish artifact resolves its modular entrypoint, not only the
|
|
38
52
|
// checkout/local-copy layout used by the live plugin test below.
|
|
39
53
|
const packResult = spawnSync("npm", ["pack", "--pack-destination", testDir], {
|
|
@@ -143,7 +157,7 @@ check("server and TUI package specs resolve to different modules", installedPack
|
|
|
143
157
|
const opencodeCheck = spawnSync("opencode", ["--version"], { encoding: "utf8" });
|
|
144
158
|
if (opencodeCheck.status !== 0) {
|
|
145
159
|
console.log("SKIP: opencode CLI is not available in PATH. Package checks passed; skipping live runtime load tests.");
|
|
146
|
-
|
|
160
|
+
cleanupTestDir();
|
|
147
161
|
console.log(`\n${pass} passed, ${fail} failed`);
|
|
148
162
|
process.exit(fail > 0 ? 1 : 0);
|
|
149
163
|
}
|
|
@@ -326,6 +340,7 @@ const runtimeEnv: NodeJS.ProcessEnv = {
|
|
|
326
340
|
XDG_STATE_HOME: join(testDir, "runtime-state"),
|
|
327
341
|
XDG_DATA_HOME: join(testDir, "runtime-data"),
|
|
328
342
|
};
|
|
343
|
+
liveServiceEnvs.push(runtimeEnv);
|
|
329
344
|
delete runtimeEnv.OPENCODE_PID;
|
|
330
345
|
delete runtimeEnv.OPENCODE_PURE;
|
|
331
346
|
delete runtimeEnv.OPENCODE;
|
|
@@ -482,6 +497,7 @@ if (isOpenCodeV2 && (opencodeMajor > 2 || (opencodeMajor === 2 && hostMinor >= 1
|
|
|
482
497
|
XDG_STATE_HOME: join(testDir, "runtime-state-todo"),
|
|
483
498
|
XDG_DATA_HOME: join(testDir, "runtime-data-todo"),
|
|
484
499
|
};
|
|
500
|
+
liveServiceEnvs.push(todoEnv);
|
|
485
501
|
const todoPort = 49400 + ((process.pid + 500) % 1000);
|
|
486
502
|
spawnSync("opencode", ["service", "set", "port", String(todoPort)], { cwd: testDir, encoding: "utf8", env: todoEnv, timeout: 30_000 });
|
|
487
503
|
try {
|
|
@@ -537,7 +553,7 @@ if (isOpenCodeV2 && (opencodeMajor > 2 || (opencodeMajor === 2 && hostMinor >= 1
|
|
|
537
553
|
|
|
538
554
|
if (process.env.WORKFLOW_GUARD_LIVE_E2E !== "1") {
|
|
539
555
|
console.log("SKIP: model-driven policy probes require WORKFLOW_GUARD_LIVE_E2E=1.");
|
|
540
|
-
|
|
556
|
+
cleanupTestDir();
|
|
541
557
|
console.log(`\n${pass} passed, ${fail} failed`);
|
|
542
558
|
process.exit(fail > 0 ? 1 : 0);
|
|
543
559
|
}
|
|
@@ -557,7 +573,7 @@ try {
|
|
|
557
573
|
const liveModel = process.env.WORKFLOW_GUARD_LIVE_MODEL?.trim() || recentModel;
|
|
558
574
|
if (!liveModel) {
|
|
559
575
|
console.error(`FAIL: no recent OpenCode model found in ${recentModelPath}; select a model in OpenCode or set WORKFLOW_GUARD_LIVE_MODEL=provider/model.`);
|
|
560
|
-
|
|
576
|
+
cleanupTestDir();
|
|
561
577
|
process.exit(1);
|
|
562
578
|
}
|
|
563
579
|
console.log(` Using live model: ${liveModel}`);
|
|
@@ -608,7 +624,7 @@ if (!run3AccountedFor) {
|
|
|
608
624
|
}
|
|
609
625
|
|
|
610
626
|
// Clean up
|
|
611
|
-
|
|
627
|
+
cleanupTestDir();
|
|
612
628
|
|
|
613
629
|
console.log(`\n${pass} passed, ${fail} failed, ${unavailable} live unavailable`);
|
|
614
630
|
process.exit(fail ? 1 : 0);
|