mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-03 22:12:01 +09:00
* fix: sign companion helpers and refuse symlinked .claude-flow writes (#4746) * fix: sign companion helpers and refuse symlinked .claude-flow writes (#4746) * fix: sign companion helpers and refuse symlinked .claude-flow writes (#4746) * fix: sign companion helpers and refuse symlinked .claude-flow writes (#4746) * fix: sign companion helpers and refuse symlinked .claude-flow writes (#4746) * fix: sign companion helpers and refuse symlinked .claude-flow writes (#4746) * fix: sign companion helpers and refuse symlinked .claude-flow writes (#4746) * fix(ruflo-mods): route every .claude-flow write through the link guard (#4746) The PR guarded only the session heartbeat and the compaction snapshot. Edit records, the learning-loop ledger, guidance observations, context-delegation metrics, cost attribution and the console toast ring still wrote through $.fs.write, which follows links. All of them now go through one helper, projectWrite (state.ts), over writeWithoutLinks: a symlinked .claude-flow or any symlinked folder below it refuses the write. Appends are read-then- rewrite, so they are covered by the same path. The cost hook's project check no longer counts a symlinked .claude-flow as the project's state (the live engine reports the target's kind plus isLink). The mods harness gains liveLinkStat (stat as the live engine answers it), and mods-every-write-guarded-4746.test.ts drives every writing hook entry point: a control run proves each path writes into a real .claude-flow, and runs with a symlinked .claude-flow and with symlinked data/cost/metrics/sessions folders must leave the outside directory byte-identical. Without this change those two runs fail with six files written outside the project. Co-Authored-By: RuFlo <ruv@ruv.net> * fix(cli): init --upgrade installs the signed companion bytes (#4746) session.cjs and memory.cjs joined the signed critical set in this PR, but executeUpgrade still regenerated both from the CLI's generators, whose output is not byte-identical to the packaged copies. The next run's integrity check then reported both as tampered: once (healed) on a normal install, on every run under .LOCKED, RUFLO_HELPERS_LOCKED or an ahead stamp, where the refresh only inspects. ensureCommonJsCompanions takes an optional sourceDir. The upgrade passes the package's own .claude/helpers (findPackageHelpersDir, the source the startup refresh verifies against): a companion present there as a regular file is copied byte-for-byte through the existing link-safe atomic write; only a missing one (or one shipped as a link) comes from the generators. The startup ensure for missing companions is unchanged. upgrade-companion-integrity-4746.test.ts upgrades a project and runs the startup integrity check against a throwaway-key manifest over the package's companion bytes; without this change it reports ['session.cjs', 'memory.cjs'] as tampered. Co-Authored-By: RuFlo <ruv@ruv.net> * chore(ruflo-mods): 0.17.3 — every .claude-flow write is link-guarded (#4746) Co-Authored-By: RuFlo <ruv@ruv.net> * test(ruflo-mods): cover the toast writer session.start binds (#4746) With engine.create, the $.ruflo noun's toast writer is the one in use, so the binder in session.start was guarded but never exercised. A run without engine.create drives it; reverting session.ts alone now fails that case (console/toasts/mods.jsonl written outside the project). Reverting any other call-site file alone fails the existing cases. Co-Authored-By: RuFlo <ruv@ruv.net> * chore(helpers): re-sign manifest with session.cjs and memory.cjs (#4746) Co-Authored-By: RuFlo <ruv@ruv.net> --------- Co-authored-by: Aditya Chandrajit Deore <adityadeoreofficial@gmail.com> Co-authored-by: r <r@x>
This commit is contained in:
25 files changed
+823
-36
No files matched your search
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ruflo-mods",
|
||||
"description": "ruflo as a Claude Code mod (function hooks, ADR-404): in-process prompt routing, edit learning signals, tighten-only tool checks from ruflo policy, the cost-tracker budget ladder, a mod trust gate for newly installed mods, and the $.ruflo noun other mods compose their status with. Opt-in and removable: the classic hook-handler hooks stay the default and take every event back whenever the mod is not loaded.",
|
||||
"version": "0.17.3",
|
||||
"version": "0.17.4",
|
||||
"repository": "https://github.com/ruvnet/ruflo",
|
||||
"author": {
|
||||
"name": "ruvnet",
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
Newest first. One `## <version> — <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-mods`.
|
||||
|
||||
## 0.17.4 — 2026-11-19
|
||||
- fix: every file the mod writes under `.claude-flow` refuses a link on the way (#4746): edit records, the learning-loop ledger, guidance observations, context-delegation metrics, cost attribution and the console toast ring, as well as the session heartbeat and compaction snapshots. A symlinked `.claude-flow`, or a symlinked folder below it, can no longer steer a write outside the project; the refused write is dropped like any other failed one.
|
||||
- fix: the cost ledger no longer counts a symlinked `.claude-flow` as the project's state.
|
||||
|
||||
## 0.17.3 — 2026-11-17
|
||||
- fix: learning-loop lessons are shown only from a `learned-lessons.json` the CLI on this machine wrote (#4747). The ingest stamps the file with an id kept in `~/.claude-flow/learning-loop-origin`, and the mod and the classic `learning-loop.cjs` helper show nothing from a file without it, so one committed to a cloned repository is never presented as the project's own test and build history. A file written before this version shows nothing until the next ingest rewrites it.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { On } from 'claude-code'
|
||||
|
||||
import { openIdLines } from '../compact/block'
|
||||
import { under, type ModState } from '../state'
|
||||
import { projectWrite, under, type ModState } from '../state'
|
||||
import { reloadBlock } from './reload'
|
||||
import { buildSnapshot, MAX_SNAPSHOTS, pickSlot, slotPath } from './snapshot'
|
||||
|
||||
@@ -21,7 +21,8 @@ const ANY = /^[\s\S]*$/
|
||||
* `.claude-flow/sessions/compactions/snapshot-<n>.jsonl` (role, text cut to 2,000 characters, tool names and ids;
|
||||
* never tool inputs or outputs; each line screened), at most 400 messages and 2 MiB, ten slots, the oldest
|
||||
* overwritten. The write runs beside the compaction: it is never blocked, delayed or rewritten, and a failed write
|
||||
* is logged to debug and dropped.
|
||||
* is logged to debug and dropped. The write refuses a link on the way (#4746): a symlinked `.claude-flow` tree
|
||||
* never steers a snapshot outside the project.
|
||||
* - The next main-loop `prompt.submit` (not a slash command) after a compaction that stood gets one
|
||||
* `[RUFLO_AFTER_COMPACT]` context block of at most 2,000 characters, then the flag clears.
|
||||
*/
|
||||
@@ -43,7 +44,7 @@ export function registerCompactSnapshot(on: On, state: ModState) {
|
||||
writing = Promise.all(stats)
|
||||
.then(async mtimes => {
|
||||
const path = slotPath(pickSlot(mtimes))
|
||||
await $.fs.write(under(state, path), snap.text)
|
||||
await projectWrite({ stat: p => $.fs.stat(p), write: (p, t) => $.fs.write(p, t) }, state)(under(state, path), snap.text)
|
||||
return path
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { On } from 'claude-code'
|
||||
|
||||
import { routeTask } from '../route/route-task'
|
||||
import { under, type ModState } from '../state'
|
||||
import { projectWrite, under, type ModState } from '../state'
|
||||
import { decide, LIMITS, MAX_QUESTION_CHARS, WORKER_MODEL } from './plan'
|
||||
import { METRICS_PATH, metricsJson, record } from './stats'
|
||||
import { renderExtract, sha256, verifyReply, WORKER_SYSTEM, workerPrompt } from './verify'
|
||||
@@ -55,7 +55,7 @@ export function registerContextDelegate(on: On, state: ModState, mode: 'observe'
|
||||
if (plan.route === 'direct') return result
|
||||
|
||||
const at = new Date().toISOString()
|
||||
const flush = () => $.fs.write(under(state, METRICS_PATH), metricsJson(s)).catch(() => undefined)
|
||||
const flush = () => projectWrite({ stat: p => $.fs.stat(p), write: (p, t) => $.fs.write(p, t) }, state)(under(state, METRICS_PATH), metricsJson(s)).catch(() => undefined)
|
||||
if (s.mode === 'observe') {
|
||||
record(s, { at, path, outcome: 'would-delegate', reason: plan.reason, bytesRead: bytes, bytesShown: bytes })
|
||||
await flush()
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { On } from 'claude-code'
|
||||
|
||||
import { cachedFile, isMissing } from '../files'
|
||||
import type { ModOptions } from '../options'
|
||||
import { redraw, under, type ModState } from '../state'
|
||||
import { projectWrite, redraw, under, type ModState } from '../state'
|
||||
import {
|
||||
apiErrorText, appendLines, ATTRIBUTION_PATH, attributionLine, createAttribution, isBudgetRefusal, noteCost, noteSpawn, noteTool, resetAttribution,
|
||||
} from './attribution'
|
||||
@@ -125,7 +125,8 @@ export function registerCost(on: On, state: ModState, options: ModOptions) {
|
||||
|
||||
on('session.end', { reason: ANY }, async ($, e, next) => {
|
||||
try {
|
||||
project ??= await $.fs.stat(under(state, '.claude-flow')).then(stat => stat.kind === 'dir', () => false)
|
||||
// A symlinked .claude-flow reads as its target's kind plus isLink: it is not this project's state (#4746).
|
||||
project ??= await $.fs.stat(under(state, '.claude-flow')).then(stat => stat.kind === 'dir' && stat.isLink !== true, () => false)
|
||||
if (project && (attribution.totalUsd > 0 || attribution.refusals > 0)) {
|
||||
const line = attributionLine(attribution, String(e.reason), Date.now(), optionLimit === undefined ? fileWindow : { usd: optionLimit, period: 'session' })
|
||||
const path = under(state, ATTRIBUTION_PATH)
|
||||
@@ -133,7 +134,7 @@ export function registerCost(on: On, state: ModState, options: ModOptions) {
|
||||
if (isMissing(error)) return ''
|
||||
throw error // a file that exists but cannot be read is never overwritten
|
||||
})
|
||||
await $.fs.write(path, appendLines(existing, [line]))
|
||||
await projectWrite({ stat: p => $.fs.stat(p), write: (p, t) => $.fs.write(p, t) }, state)(path, appendLines(existing, [line]))
|
||||
}
|
||||
} catch {
|
||||
// the breakdown is best effort; a session must end whatever happens here
|
||||
|
||||
@@ -10,6 +10,15 @@ export type FileHost = {
|
||||
readonly read: (path: string) => Promise<string>
|
||||
}
|
||||
|
||||
/**
|
||||
* The `$.fs` calls a guarded write needs, built the same way: the hook
|
||||
* spells `$.fs.stat` / `$.fs.write` at the call site.
|
||||
*/
|
||||
export type WriteHost = {
|
||||
readonly stat: (path: string) => Promise<FsStat>
|
||||
readonly write: (path: string, text: string) => Promise<void>
|
||||
}
|
||||
|
||||
/** Under `$.fs.read`'s own 4 MiB bound, so an oversized file reads as too big. */
|
||||
export const MAX_READ_BYTES = 4 * 1024 * 1024
|
||||
|
||||
@@ -81,3 +90,46 @@ async function readAndParse<T>(fs: FileHost, path: string, parse: (text: string)
|
||||
return { kind: 'error', message: messageOf(error) }
|
||||
}
|
||||
}
|
||||
|
||||
const isLinkKind = (kind: string | undefined): boolean => kind === 'symlink' || kind === 'link'
|
||||
|
||||
/**
|
||||
* Writes `text` to `path` only when the way from `root` down to the file
|
||||
* holds no link. `$.fs.stat` reports a link (`isLink`, plus the target's
|
||||
* kind) instead of following it silently, but `$.fs.write` follows one, so
|
||||
* a symlinked `.claude-flow` tree in a cloned project could steer a write
|
||||
* outside the project (#4746). Every component below the root that exists
|
||||
* must be a real folder, and an existing target must be a regular file; a
|
||||
* missing component ends the walk, since nothing below it can exist and
|
||||
* the write creates the folders. Only ENOENT is "missing": any other stat
|
||||
* failure refuses the write, as does a path that is not lexically under
|
||||
* the root. The root itself is never statted: it may legitimately be an
|
||||
* alias. Throws on a refusal, naming the component, and writes nothing
|
||||
* then. The check and the write are not atomic — a link planted between
|
||||
* them still wins — but a planted link is the threat here, not a second
|
||||
* writer racing the check.
|
||||
*/
|
||||
export async function writeWithoutLinks(fs: WriteHost, root: string, path: string, text: string): Promise<void> {
|
||||
const base = root.replace(/\/+$/, '')
|
||||
const prefix = base === '' ? '/' : `${base}/`
|
||||
const outside = `${path} is outside the project: only paths under ${base === '' ? '/' : base} are written`
|
||||
if (!path.startsWith(prefix)) throw new Error(outside)
|
||||
const parts = path.slice(prefix.length).split('/').filter(part => part !== '' && part !== '.')
|
||||
if (parts.length === 0 || parts.includes('..')) throw new Error(outside)
|
||||
let at = base
|
||||
for (const [index, part] of parts.entries()) {
|
||||
at = `${at}/${part}`
|
||||
const last = index === parts.length - 1
|
||||
let stat: FsStat
|
||||
try {
|
||||
stat = await fs.stat(at)
|
||||
} catch (error) {
|
||||
if (!isMissing(error, at)) throw new Error(`${at.slice(base.length)} cannot be checked, so it is not written through`)
|
||||
break
|
||||
}
|
||||
if (stat.isLink === true || isLinkKind(stat.kind)) throw new Error(`${at.slice(base.length)} is a link: it could lead outside the project, so it is not written through`)
|
||||
if (!last && stat.kind !== undefined && stat.kind !== 'dir' && stat.kind !== 'directory') throw new Error(`${at.slice(base.length)} is not a folder, so it is not written through`)
|
||||
if (last && stat.kind !== undefined && stat.kind !== 'file') throw new Error(`${at.slice(base.length)} is not a regular file, so it is not written through`)
|
||||
}
|
||||
await fs.write(path, text)
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import type { EngineInterface, On } from 'claude-code'
|
||||
|
||||
import { isMissing } from '../files'
|
||||
import type { GuidanceHooks } from '../guidance'
|
||||
import { redraw, under, type ModState } from '../state'
|
||||
import { projectWrite, redraw, under, type ModState } from '../state'
|
||||
import { appendRecords, EDIT_TOOLS, editedFile, MAX_LINES, PENDING_PATH, rufloSessionId, SESSION_PATH } from './insights'
|
||||
|
||||
/** Written early once this many edits wait, so a long turn holds little. */
|
||||
@@ -23,7 +23,7 @@ export async function flushEdits($: EngineInterface, state: ModState): Promise<v
|
||||
if (isMissing(error)) return ''
|
||||
throw error
|
||||
})
|
||||
await $.fs.write(under(state, PENDING_PATH), appendRecords(existing, records.map(r => ({ ...r, sessionId }))))
|
||||
await projectWrite({ stat: p => $.fs.stat(p), write: (p, t) => $.fs.write(p, t) }, state)(under(state, PENDING_PATH), appendRecords(existing, records.map(r => ({ ...r, sessionId }))))
|
||||
} catch (error) {
|
||||
state.edits.unshift(...records)
|
||||
state.edits.splice(0, Math.max(0, state.edits.length - MAX_LINES))
|
||||
@@ -65,7 +65,7 @@ export function registerLearn(on: On, state: ModState, guidance?: GuidanceHooks)
|
||||
const result = await next(e)
|
||||
if (guidance) {
|
||||
guidance.complete(e.turnId, e.isAborted)
|
||||
await guidance.flush({ read: path => $.fs.read(path), write: (path, text) => $.fs.write(path, text) })
|
||||
await guidance.flush({ read: path => $.fs.read(path), write: projectWrite({ stat: p => $.fs.stat(p), write: (p, t) => $.fs.write(p, t) }, state) })
|
||||
}
|
||||
await flushEdits($, state)
|
||||
return result
|
||||
@@ -74,7 +74,7 @@ export function registerLearn(on: On, state: ModState, guidance?: GuidanceHooks)
|
||||
on('session.end', async ($, e, next) => {
|
||||
if (guidance) {
|
||||
guidance.end()
|
||||
await guidance.flush({ read: path => $.fs.read(path), write: (path, text) => $.fs.write(path, text) })
|
||||
await guidance.flush({ read: path => $.fs.read(path), write: projectWrite({ stat: p => $.fs.stat(p), write: (p, t) => $.fs.write(p, t) }, state) })
|
||||
}
|
||||
await flushEdits($, state)
|
||||
return next(e)
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { On } from 'claude-code'
|
||||
|
||||
import { cachedFile, isMissing } from '../files'
|
||||
import { routeTask } from '../route/route-task'
|
||||
import { redraw, under, type ModState } from '../state'
|
||||
import { projectWrite, redraw, under, type ModState } from '../state'
|
||||
import { trustHome } from '../trust'
|
||||
import { lessonBlock, parseLessons, parseOrigin, pick, recordedHere } from './lessons'
|
||||
import { appendLines, line, LESSONS_PATH, MAX_PENDING, ORIGIN_PATH, outcomeOf, start, step, VERIFIED_PATH } from './record'
|
||||
@@ -93,12 +93,12 @@ export function registerLoop(on: On, state: ModState) {
|
||||
if (loop.pending.length > MAX_PENDING) loop.dropped += loop.pending.splice(0, loop.pending.length - MAX_PENDING).length
|
||||
redraw(state)
|
||||
}
|
||||
await flush(path => $.fs.read(path), (path, text) => $.fs.write(path, text))
|
||||
await flush(path => $.fs.read(path), projectWrite({ stat: p => $.fs.stat(p), write: (p, t) => $.fs.write(p, t) }, state))
|
||||
return result
|
||||
})
|
||||
|
||||
on('session.end', { reason: ANY }, async ($, e, next) => {
|
||||
await flush(path => $.fs.read(path), (path, text) => $.fs.write(path, text))
|
||||
await flush(path => $.fs.read(path), projectWrite({ stat: p => $.fs.stat(p), write: (p, t) => $.fs.write(p, t) }, state))
|
||||
return next(e)
|
||||
})
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { EngineInterface, On } from 'claude-code'
|
||||
|
||||
import type { RufloSnapshot } from '../types'
|
||||
import { redraw, setSegment, sortedSegments, type ModState } from './state'
|
||||
import { projectWrite, redraw, setSegment, sortedSegments, type ModState } from './state'
|
||||
import { bindToasts } from './toast'
|
||||
|
||||
/** The snapshot `$.ruflo.snapshot()` answers: copies, never live state. */
|
||||
@@ -47,7 +47,7 @@ export function registerNoun(on: On, state: ModState) {
|
||||
show: (line, options) => beneath.ui.toast(line, options),
|
||||
after: (ms, fn) => beneath.clock.after(ms, fn),
|
||||
read: path => beneath.fs.read(`${state.root}/${path}`),
|
||||
write: (path, text) => beneath.fs.write(`${state.root}/${path}`, text),
|
||||
write: (path, text) => projectWrite({ stat: p => beneath.fs.stat(p), write: (p, t) => beneath.fs.write(p, t) }, state)(`${state.root}/${path}`, text),
|
||||
exists: path => beneath.fs.exists(`${state.root}/${path}`),
|
||||
})
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import { HANDSHAKE_MARKER, ownedEvents } from './ownership'
|
||||
import type { ModOptions } from './options'
|
||||
import { ATTENTION_MAX_BYTES, ATTENTION_STATUS, attentionLine } from './attention'
|
||||
import { MAX_BYTES, PROTECTOR_STATUS, protectorLine } from './protector'
|
||||
import { redraw, report, under, type ModState } from './state'
|
||||
import { projectWrite, redraw, report, under, type ModState } from './state'
|
||||
import { runSelfCheck } from './selfcheck'
|
||||
import { bindToasts } from './toast'
|
||||
|
||||
@@ -104,7 +104,7 @@ export function registerSession(on: On, state: ModState, options: ModOptions, gu
|
||||
show: (line, options) => $.ui.toast(line, options),
|
||||
after: (ms, fn) => $.clock.after(ms, fn),
|
||||
read: path => $.fs.read(`${state.root}/${path}`),
|
||||
write: (path, text) => $.fs.write(`${state.root}/${path}`, text),
|
||||
write: (path, text) => projectWrite({ stat: p => $.fs.stat(p), write: (p, t) => $.fs.write(p, t) }, state)(under(state, path), text),
|
||||
exists: path => $.fs.exists(`${state.root}/${path}`),
|
||||
})
|
||||
// A user-scoped install loads in every project. Existing Ruflo state is
|
||||
@@ -128,7 +128,14 @@ export function registerSession(on: On, state: ModState, options: ModOptions, gu
|
||||
.catch(() => undefined)
|
||||
if (project) {
|
||||
const heartbeat = { startedAt: new Date().toISOString(), owned: [...state.owned], statusLine: state.statusLine, ...(state.probe.enabled ? { engine: state.probe.version ?? null, events: [...state.probe.registered].sort() } : {}) }
|
||||
await $.fs.write(under(state, HEARTBEAT_PATH), `${JSON.stringify(heartbeat, null, 2)}\n`).catch(() => undefined)
|
||||
// The heartbeat never follows a link out of the project (#4746); a refusal is dropped like any failed write, after a debug log.
|
||||
await projectWrite({ stat: p => $.fs.stat(p), write: (p, t) => $.fs.write(p, t) }, state)(under(state, HEARTBEAT_PATH), `${JSON.stringify(heartbeat, null, 2)}\n`).catch((error: unknown) => {
|
||||
try {
|
||||
$.ui.log(`ruflo mods: heartbeat not written (${String((error as Error)?.message ?? error)})`, { to: 'debug' })
|
||||
} catch {
|
||||
// A refused log is swallowed: the heartbeat stays best-effort.
|
||||
}
|
||||
})
|
||||
}
|
||||
return next(e)
|
||||
}).catch(async ($, e, next) => {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { probeLine, probeState, type ProbeState } from './probe'
|
||||
import { loopLine, loopSegment, loopState, type LoopState } from './loop/status'
|
||||
import { snapshotLine, snapshotState, type SnapshotState } from './compact-snapshot/snapshot'
|
||||
import type { RouteResult } from './route/route-task'
|
||||
import { writeWithoutLinks, type WriteHost } from './files'
|
||||
import { createDelegateState, type ContextDelegateState } from './context-delegate/stats'
|
||||
|
||||
/**
|
||||
@@ -105,6 +106,20 @@ export function createState(): ModState {
|
||||
/** A path under the session's project root. */
|
||||
export const under = (s: ModState, relative: string) => `${s.root}/${relative}`
|
||||
|
||||
/**
|
||||
* The one writer for every file the mod keeps under the project (#4746): a
|
||||
* `(path, text)` write of an absolute path under the session's root that
|
||||
* refuses (rejects, writing nothing) when a link stands anywhere on the way,
|
||||
* `.claude-flow` itself included, or when the path leaves the root. Appends
|
||||
* are read-then-rewrite, so they go through here too. The hook builds `fs`
|
||||
* from `$.fs.stat` / `$.fs.write` spelled at the call site; the root is read
|
||||
* at write time, as `session.start` sets it.
|
||||
*/
|
||||
export const projectWrite =
|
||||
(fs: WriteHost, s: ModState) =>
|
||||
(path: string, text: string): Promise<void> =>
|
||||
writeWithoutLinks(fs, s.root, path, text)
|
||||
|
||||
export const MAX_SEGMENTS = 8
|
||||
export const MAX_SEGMENT_CHARS = 48
|
||||
const SEGMENT_ID = /^[A-Za-z0-9_-]{1,32}$/
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Structural + security smoke for ruflo-mods v0.17.3 (ADR-404, ADR-447).
|
||||
# Structural + security smoke for ruflo-mods v0.17.4 (ADR-404, ADR-447).
|
||||
# Static only: CI has no Claude Code, so the hooks module's behaviour is held
|
||||
# by v3/@claude-flow/cli/__tests__/mods/*.test.ts and, where function hooks are
|
||||
# on, by `claude plugin test plugins/ruflo-mods`.
|
||||
@@ -12,9 +12,9 @@ ok() { printf "PASS\n"; PASS=$((PASS+1)); }
|
||||
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
|
||||
HOOKS="$ROOT/hooks"
|
||||
|
||||
step "1. plugin.json declares ruflo-mods 0.17.3"
|
||||
step "1. plugin.json declares ruflo-mods 0.17.4"
|
||||
grep -q '"name": "ruflo-mods"' "$ROOT/.claude-plugin/plugin.json" \
|
||||
&& grep -q '"version": "0.17.3"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
|
||||
&& grep -q '"version": "0.17.4"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"
|
||||
|
||||
step "2. hooks.json names exactly one module and no classic hook commands"
|
||||
grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \
|
||||
|
||||
@@ -35,7 +35,7 @@ try {
|
||||
mkdirSync(join(fixture, 'scripts'), { recursive: true });
|
||||
mkdirSync(join(fixture, '.claude', 'helpers'), { recursive: true });
|
||||
cpSync(signer, join(fixture, 'scripts', 'sign-helpers.mjs'));
|
||||
for (const name of ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs', 'statusline.cjs', 'router.cjs', 'learning-loop.cjs']) {
|
||||
for (const name of ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs', 'statusline.cjs', 'router.cjs', 'learning-loop.cjs', 'session.cjs', 'memory.cjs']) {
|
||||
cpSync(join(cli, '.claude', 'helpers', name), join(fixture, '.claude', 'helpers', name));
|
||||
}
|
||||
writeFileSync(join(fixture, 'package.json'), JSON.stringify({ version: '0.0.0-security-test' }));
|
||||
|
||||
@@ -7,9 +7,11 @@
|
||||
"intelligence.cjs": "ffdcfa6d2665a16e417dedd5bc67080c8192820f76265de5013fcb49f668ec71",
|
||||
"statusline.cjs": "284b95629ced4340667872b977de3f2beac90fc6bb7ab1a62dd7f7ae75c5e5d1",
|
||||
"router.cjs": "16648b3c0d73b6681ac2d8d13def6a68286c57f5a11004de5b19a0fa088c833d",
|
||||
"learning-loop.cjs": "33caa41ce9edacbb0d403a337558f7a77c27b0864e4dfe8f6c2b541188602c1d"
|
||||
"learning-loop.cjs": "33caa41ce9edacbb0d403a337558f7a77c27b0864e4dfe8f6c2b541188602c1d",
|
||||
"session.cjs": "b9972858615343120c7a65092c1c426fc859c6f9c308ce0ff6b4caace8ac6813",
|
||||
"memory.cjs": "2ef989f4640e357c1ac3eae09330242c1f6b037e6ef676a5999b8a7c11d53c33"
|
||||
}
|
||||
},
|
||||
"signature": "ZC9lNq90ReaIiqKZW9Vr29cbt43aOBvtHmjwWDx1x24GvYhBuyDtXrxipcTw9zMhgy+qF7x3WKO6Z9y2xYj7Cw==",
|
||||
"signature": "ZsIYs6Y+Eub0yrwV0ToKRUP10Q/kKVSn6vVqI7+YkgERKrzFRGskLA4DOfnnlO9pjppxzXA3vXGXDRHcsY5YDw==",
|
||||
"algorithm": "ed25519"
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* #4746 (remainder): the companion helpers belong to the signed release set.
|
||||
*
|
||||
* `session.cjs` and `memory.cjs` load on every hook (hook-handler.cjs requires
|
||||
* them) but were not in `CRITICAL_HELPERS`, so no signed hash ever covered the
|
||||
* bytes a project runs. These tests prove the lists name them and the
|
||||
* fail-closed refresh gate copies and verifies them from a signed source —
|
||||
* using throwaway-keypair fixtures, never this repo's real manifest, which is
|
||||
* routinely stale mid-development and only a maintainer can re-sign
|
||||
* (docs/helpers-sync.md). The committed manifest itself is NOT touched here:
|
||||
* a maintainer must re-sign it before merge, or the gate below would refuse
|
||||
* every refresh.
|
||||
*/
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { generateKeyPairSync, sign as edSign } from 'node:crypto';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import {
|
||||
autoRefreshHelpersIfStale,
|
||||
getInstalledCliVersion,
|
||||
CRITICAL_HELPERS,
|
||||
HELPERS_STAMP_FILE,
|
||||
} from '../src/init/helper-refresh.js';
|
||||
import { canonicalManifestBytes, sha256Hex } from '../src/init/helper-signing.js';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const PKG_ROOT = join(here, '..');
|
||||
const REPO_ROOT = join(PKG_ROOT, '..', '..', '..');
|
||||
const COMPANIONS = ['session.cjs', 'memory.cjs'] as const;
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function makeProject(): { cwd: string; helpersDir: string } {
|
||||
const cwd = mkdtempSync(join(tmpdir(), 'helper-companion-signing-'));
|
||||
roots.push(cwd);
|
||||
const helpersDir = join(cwd, '.claude', 'helpers');
|
||||
mkdirSync(helpersDir, { recursive: true });
|
||||
return { cwd, helpersDir };
|
||||
}
|
||||
|
||||
/**
|
||||
* Throwaway-keypair-signed source fixture holding the given files, mirroring
|
||||
* helper-refresh.test.ts's makeSignedSource. `tamper` replaces a file's bytes
|
||||
* AFTER the manifest is signed, so its hash no longer matches.
|
||||
*/
|
||||
function makeSignedSource(
|
||||
version: string,
|
||||
files: Record<string, string>,
|
||||
tamper?: { name: string; bytes: string },
|
||||
): { sourceDir: string; pubkeyPem: string } {
|
||||
const sourceDir = mkdtempSync(join(tmpdir(), 'helper-companion-signing-source-'));
|
||||
roots.push(sourceDir);
|
||||
const hashes: Record<string, string> = {};
|
||||
for (const [name, content] of Object.entries(files)) {
|
||||
writeFileSync(join(sourceDir, name), content);
|
||||
hashes[name] = sha256Hex(content);
|
||||
}
|
||||
const { publicKey, privateKey } = generateKeyPairSync('ed25519');
|
||||
const manifest = { version, files: hashes };
|
||||
const signature = edSign(null, canonicalManifestBytes(manifest), privateKey).toString('base64');
|
||||
writeFileSync(
|
||||
join(sourceDir, 'helpers.manifest.json'),
|
||||
JSON.stringify({ manifest, signature, algorithm: 'ed25519' }),
|
||||
);
|
||||
if (tamper) writeFileSync(join(sourceDir, tamper.name), tamper.bytes);
|
||||
return { sourceDir, pubkeyPem: publicKey.export({ type: 'spki', format: 'pem' }).toString() };
|
||||
}
|
||||
|
||||
const SIGNED = {
|
||||
'hook-handler.cjs': '// signed hook-handler fixture\n',
|
||||
'session.cjs': '// signed session companion fixture\n',
|
||||
'memory.cjs': '// signed memory companion fixture\n',
|
||||
};
|
||||
|
||||
describe('companion helpers in the signed set (#4746)', () => {
|
||||
it('CRITICAL_HELPERS names both companion helpers', () => {
|
||||
for (const name of COMPANIONS) expect(CRITICAL_HELPERS).toContain(name);
|
||||
});
|
||||
|
||||
it('every signing list names both companion helpers', () => {
|
||||
// Mirrors the learning-loop list-consistency test: the signer, the
|
||||
// publish-time verifier, and the offline signing smoke must all agree
|
||||
// with CRITICAL_HELPERS, or the next sign/verify/smoke run diverges.
|
||||
// executor.ts is deliberately NOT in this list: its upgrade step copies
|
||||
// critical helpers and then ensureCommonJsCompanions(force=true) owns the
|
||||
// companions (#4198), so naming them there would only add a redundant copy.
|
||||
for (const f of ['scripts/sign-helpers.mjs', 'scripts/verify-helpers.mjs']) {
|
||||
const text = readFileSync(join(PKG_ROOT, f), 'utf8');
|
||||
for (const name of COMPANIONS) expect(text).toContain(`'${name}'`);
|
||||
}
|
||||
const smoke = readFileSync(join(REPO_ROOT, 'scripts', 'smoke-helper-signing-security.mjs'), 'utf8');
|
||||
for (const name of COMPANIONS) expect(smoke).toContain(`'${name}'`);
|
||||
});
|
||||
|
||||
it('a stale-stamped refresh copies the signed companions from the verified source', async () => {
|
||||
const { cwd, helpersDir } = makeProject();
|
||||
writeFileSync(join(helpersDir, 'hook-handler.cjs'), '// OLD hook-handler\n');
|
||||
writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), '0.0.1-old');
|
||||
const version = getInstalledCliVersion();
|
||||
const { sourceDir, pubkeyPem } = makeSignedSource(version, SIGNED);
|
||||
|
||||
const r = await autoRefreshHelpersIfStale(cwd, { sourceDirOverride: sourceDir, pubkeyPemOverride: pubkeyPem });
|
||||
|
||||
expect(r.refreshed).toBe(true);
|
||||
// The installed bytes are the SIGNED fixture bytes, not the generated
|
||||
// companion output: the refresh copied them through the verify gate.
|
||||
for (const name of COMPANIONS) {
|
||||
expect(readFileSync(join(helpersDir, name), 'utf8')).toBe(SIGNED[name]);
|
||||
}
|
||||
expect(readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf8')).toBe(SIGNED['hook-handler.cjs']);
|
||||
});
|
||||
|
||||
it('a companion whose bytes differ from the signed manifest blocks the whole refresh', async () => {
|
||||
const { cwd, helpersDir } = makeProject();
|
||||
writeFileSync(join(helpersDir, 'hook-handler.cjs'), '// OLD hook-handler\n');
|
||||
writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), '0.0.1-old');
|
||||
const version = getInstalledCliVersion();
|
||||
const { sourceDir, pubkeyPem } = makeSignedSource(version, SIGNED, {
|
||||
name: 'session.cjs',
|
||||
bytes: '// TAMPERED session companion\n',
|
||||
});
|
||||
|
||||
const r = await autoRefreshHelpersIfStale(cwd, { sourceDirOverride: sourceDir, pubkeyPemOverride: pubkeyPem });
|
||||
|
||||
expect(r.refreshed).toBe(false);
|
||||
expect(r.blocked).toContain('session.cjs');
|
||||
expect(readFileSync(join(helpersDir, 'hook-handler.cjs'), 'utf8')).toBe('// OLD hook-handler\n');
|
||||
});
|
||||
|
||||
it('a tampered installed companion is healed from the signed source', async () => {
|
||||
const { cwd, helpersDir } = makeProject();
|
||||
const version = getInstalledCliVersion();
|
||||
writeFileSync(join(helpersDir, 'hook-handler.cjs'), SIGNED['hook-handler.cjs']);
|
||||
writeFileSync(join(helpersDir, 'session.cjs'), '// TAMPERED installed session companion\n');
|
||||
writeFileSync(join(helpersDir, 'memory.cjs'), SIGNED['memory.cjs']);
|
||||
writeFileSync(join(helpersDir, HELPERS_STAMP_FILE), version);
|
||||
const { sourceDir, pubkeyPem } = makeSignedSource(version, SIGNED);
|
||||
|
||||
const r = await autoRefreshHelpersIfStale(cwd, { sourceDirOverride: sourceDir, pubkeyPemOverride: pubkeyPem });
|
||||
|
||||
expect(r.refreshed).toBe(true);
|
||||
expect(r.healed).toBe(true);
|
||||
expect(r.tampered).toContain('session.cjs');
|
||||
expect(readFileSync(join(helpersDir, 'session.cjs'), 'utf8')).toBe(SIGNED['session.cjs']);
|
||||
});
|
||||
});
|
||||
@@ -42,6 +42,12 @@ export interface World {
|
||||
failStat?: (path: string) => Error | undefined;
|
||||
failWrite?: (path: string) => Error | undefined;
|
||||
failLog?: boolean;
|
||||
/**
|
||||
* `fs.stat` as the live engine answers it (plugins/ruflo-console/tests/mods-section.spec.ts): a link reports its
|
||||
* target's kind plus `isLink: true`, so a symlinked `.claude-flow` reads as a dir. Default (unset) keeps `lstat`
|
||||
* semantics, where a link to a dir reads as `other`.
|
||||
*/
|
||||
liveLinkStat?: boolean;
|
||||
/** What `$.tool.list()` returns (default: none). `mcp` marks an MCP server's tool. */
|
||||
tools?: { name: string; description: string; mcp: boolean }[];
|
||||
/** What `$.session.messages()` returns (default: none). */
|
||||
@@ -72,6 +78,10 @@ function engineOf(world: World) {
|
||||
return { kind: 'file', size: Buffer.byteLength(f.text), mtimeMs: f.mtimeMs, isLink: false };
|
||||
}
|
||||
const s = lstatSync(path);
|
||||
if (world.liveLinkStat && s.isSymbolicLink()) {
|
||||
const t = statSync(path);
|
||||
return { kind: t.isFile() ? 'file' : t.isDirectory() ? 'dir' : 'other', size: t.size, mtimeMs: t.mtimeMs, isLink: true };
|
||||
}
|
||||
return { kind: s.isFile() ? 'file' : s.isDirectory() ? 'dir' : 'other', size: s.size, mtimeMs: s.mtimeMs, isLink: s.isSymbolicLink() };
|
||||
},
|
||||
async read(path: string) {
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* #4746 (remainder): the mods' `.claude-flow` writes must not follow symlinks.
|
||||
*
|
||||
* The session heartbeat (session.ts) and the pre-compaction snapshot
|
||||
* (compact-snapshot/index.ts) wrote through `$.fs.write` with no link check,
|
||||
* so a symlinked `.claude-flow` tree in a cloned project could steer those
|
||||
* writes outside the project. These tests drive the real mod through the
|
||||
* harness against real directories and real symlinks, and assert nothing
|
||||
* outside the project is ever written.
|
||||
*
|
||||
* One shape cannot be reproduced through this harness: a symlinked
|
||||
* `.claude-flow` directory itself. The harness stats with `lstat`, which
|
||||
* reports a link-to-dir as kind `other`, so the mod already stands down
|
||||
* before writing; the live engine reports the target's kind plus `isLink`
|
||||
* (see plugins/ruflo-console/tests/mods-section.spec.ts), which is the shape
|
||||
* the guard's own tests (mods-write-without-links-4746.test.ts) cover. The
|
||||
* symlinked-`.claude-flow` cases below are pins for the harness outcome.
|
||||
*/
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import {
|
||||
existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
import { register } from '../../../../../plugins/ruflo-mods/hooks/register';
|
||||
import { HEARTBEAT_PATH } from '../../../../../plugins/ruflo-mods/hooks/session';
|
||||
import { MAX_SNAPSHOTS, slotPath } from '../../../../../plugins/ruflo-mods/hooks/compact-snapshot/snapshot';
|
||||
import { loadMod, realWorld, type World } from './harness';
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function projectWithOutside(): { project: string; outside: string; world: World } {
|
||||
const root = mkdtempSync(join(tmpdir(), 'ruflo-mods-write-safety-'));
|
||||
roots.push(root);
|
||||
const project = join(root, 'project');
|
||||
const outside = join(root, 'outside');
|
||||
mkdirSync(project, { recursive: true });
|
||||
mkdirSync(outside, { recursive: true });
|
||||
return { project, outside, world: realWorld(project) };
|
||||
}
|
||||
|
||||
async function boot(world: World) {
|
||||
const mod = loadMod(register, world, {});
|
||||
await mod.create();
|
||||
await mod.dispatch('session.start', { cwd: world.root, surface: null, isInteractive: false }, (e) => ({ cwd: e.cwd }));
|
||||
return mod;
|
||||
}
|
||||
type Mod = Awaited<ReturnType<typeof boot>>;
|
||||
|
||||
const msg = (role: 'user' | 'assistant', text: string) => ({ role, text, toolUses: [], handle: `h-${Math.random()}` });
|
||||
|
||||
async function compact(mod: Mod) {
|
||||
return mod.dispatch(
|
||||
'session.compact',
|
||||
{ trigger: 'manual', messages: [msg('user', 'please fix bug 0'), msg('assistant', 'looking at it')] },
|
||||
() => ({ messages: [msg('user', 'summary')] }),
|
||||
);
|
||||
}
|
||||
|
||||
describe('session heartbeat', () => {
|
||||
it('writes the heartbeat in a normal project', async () => {
|
||||
const { project, world } = projectWithOutside();
|
||||
mkdirSync(join(project, '.claude-flow'), { recursive: true });
|
||||
await boot(world);
|
||||
const heartbeat = JSON.parse(readFileSync(join(project, HEARTBEAT_PATH), 'utf8'));
|
||||
expect(heartbeat.startedAt).toEqual(expect.any(String));
|
||||
expect(heartbeat.owned).toEqual(expect.any(Array));
|
||||
});
|
||||
|
||||
it('never writes through a symlinked session.json target', async () => {
|
||||
const { project, outside, world } = projectWithOutside();
|
||||
const target = join(outside, 'target.json');
|
||||
writeFileSync(target, 'outside-owned');
|
||||
mkdirSync(join(project, '.claude-flow', 'mods'), { recursive: true });
|
||||
symlinkSync(target, join(project, HEARTBEAT_PATH));
|
||||
await boot(world);
|
||||
expect(readFileSync(target, 'utf8')).toBe('outside-owned');
|
||||
expect(lstatSync(join(project, HEARTBEAT_PATH)).isSymbolicLink()).toBe(true);
|
||||
});
|
||||
|
||||
it('never writes through a symlinked mods dir', async () => {
|
||||
const { project, outside, world } = projectWithOutside();
|
||||
mkdirSync(join(project, '.claude-flow'), { recursive: true });
|
||||
symlinkSync(outside, join(project, '.claude-flow', 'mods'), 'dir');
|
||||
await boot(world);
|
||||
expect(readdirSync(outside)).toEqual([]);
|
||||
});
|
||||
|
||||
it('a symlinked .claude-flow dir writes nothing outside (pin: the harness lstat already stands the mod down)', async () => {
|
||||
const { project, outside, world } = projectWithOutside();
|
||||
symlinkSync(outside, join(project, '.claude-flow'), 'dir');
|
||||
await boot(world);
|
||||
expect(readdirSync(outside)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('compaction snapshots', () => {
|
||||
it('writes one snapshot in a normal project', async () => {
|
||||
const { project, world } = projectWithOutside();
|
||||
mkdirSync(join(project, '.claude-flow'), { recursive: true });
|
||||
const mod = await boot(world);
|
||||
await compact(mod);
|
||||
const snap = join(project, slotPath(0));
|
||||
expect(existsSync(snap)).toBe(true);
|
||||
const head = JSON.parse(readFileSync(snap, 'utf8').split('\n')[0]);
|
||||
expect(head).toMatchObject({ kind: 'ruflo-compact-snapshot', messages: 2, kept: 2 });
|
||||
});
|
||||
|
||||
it('never writes through a symlinked slot when rotating', async () => {
|
||||
const { project, outside, world } = projectWithOutside();
|
||||
const dir = join(project, '.claude-flow', 'sessions', 'compactions');
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const target = join(outside, 'target.jsonl');
|
||||
writeFileSync(target, 'outside-owned');
|
||||
// The link is created first, so its mtime is the oldest: rotation picks it.
|
||||
symlinkSync(target, join(project, slotPath(0)));
|
||||
for (let n = 1; n < MAX_SNAPSHOTS; n++) {
|
||||
writeFileSync(join(project, slotPath(n)), '{"v":1}\n');
|
||||
}
|
||||
const mod = await boot(world);
|
||||
const result = await compact(mod);
|
||||
expect(result).toEqual({ messages: [expect.objectContaining({ text: 'summary' })] });
|
||||
expect(readFileSync(target, 'utf8')).toBe('outside-owned');
|
||||
expect(lstatSync(join(project, slotPath(0))).isSymbolicLink()).toBe(true);
|
||||
expect(world.logs.some((l) => l.includes('compaction snapshot not written'))).toBe(true);
|
||||
});
|
||||
|
||||
it('never writes through a symlinked compactions dir', async () => {
|
||||
const { project, outside, world } = projectWithOutside();
|
||||
mkdirSync(join(project, '.claude-flow', 'sessions'), { recursive: true });
|
||||
symlinkSync(outside, join(project, '.claude-flow', 'sessions', 'compactions'), 'dir');
|
||||
const mod = await boot(world);
|
||||
const result = await compact(mod);
|
||||
expect(result).toEqual({ messages: [expect.objectContaining({ text: 'summary' })] });
|
||||
expect(readdirSync(outside)).toEqual([]);
|
||||
expect(world.logs.some((l) => l.includes('compaction snapshot not written'))).toBe(true);
|
||||
});
|
||||
|
||||
it('a symlinked .claude-flow dir writes nothing outside (pin: the harness lstat already stands the mod down)', async () => {
|
||||
const { project, outside, world } = projectWithOutside();
|
||||
symlinkSync(outside, join(project, '.claude-flow'), 'dir');
|
||||
const mod = await boot(world);
|
||||
const result = await compact(mod);
|
||||
expect(result).toEqual({ messages: [expect.objectContaining({ text: 'summary' })] });
|
||||
expect(readdirSync(outside)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* #4746 (review follow-up): EVERY file the mod writes under `.claude-flow`
|
||||
* goes through the link guard, not only the heartbeat and the snapshot.
|
||||
*
|
||||
* One session drives each hook entry point that writes: session.start (the
|
||||
* heartbeat), prompt.submit + tool.call + turn.complete (edit records, the
|
||||
* learning-loop ledger, guidance observations, context-delegation metrics),
|
||||
* a budget refusal (the console toast ring), session.compact (a snapshot)
|
||||
* and session.end (cost attribution). The harness stats the way the live
|
||||
* engine does (`liveLinkStat`): a symlinked `.claude-flow` reads as a dir with
|
||||
* `isLink`, so the mod treats the project as initialized and every write path
|
||||
* is reached. A control run against a real `.claude-flow` proves each path
|
||||
* writes; the symlinked run must leave the outside directory byte-identical.
|
||||
*/
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, relative } from 'node:path';
|
||||
|
||||
import { GuidanceCompiler } from '../../../guidance/src/compiler';
|
||||
import { register } from '../../../../../plugins/ruflo-mods/hooks/register';
|
||||
import { HEARTBEAT_PATH } from '../../../../../plugins/ruflo-mods/hooks/session';
|
||||
import { PROJECTION_PATH } from '../../../../../plugins/ruflo-mods/hooks/guidance/projection';
|
||||
import { PENDING_PATH } from '../../../../../plugins/ruflo-mods/hooks/learn/insights';
|
||||
import { VERIFIED_PATH } from '../../../../../plugins/ruflo-mods/hooks/loop/record';
|
||||
import { METRICS_PATH } from '../../../../../plugins/ruflo-mods/hooks/context-delegate/stats';
|
||||
import { ATTRIBUTION_PATH } from '../../../../../plugins/ruflo-mods/hooks/cost/attribution';
|
||||
import { CONSOLE_DIR, TOAST_DIR } from '../../../../../plugins/ruflo-mods/hooks/toast/policy';
|
||||
import { slotPath } from '../../../../../plugins/ruflo-mods/hooks/compact-snapshot/snapshot';
|
||||
import { buildModProjection } from '../../src/guidance/mod-projection';
|
||||
import { loadMod, realWorld, type World } from './harness';
|
||||
|
||||
const SOURCE = '# Project guidance\n## Testing\n- TEST-001: Always run parser tests when changing a parser.\n';
|
||||
const REVISION = '8ce24908c51c26aa859308bdb2e7e819e4f9fc88';
|
||||
const OPTIONS = { learningLoop: true, guidanceLearning: true, guidanceContext: true, contextDelegation: 'observe', routeContext: false };
|
||||
const REFUSAL = 'API Error: 400 {"error":{"message":"Authentication Error, ExceededTokenBudget: Current spend for token: 7.2e-05; Max Budget for Token: 2e-07","type":"budget_exceeded","param":null,"code":"400"}}';
|
||||
const BIG = Array.from({ length: 1200 }, (_, i) => `export const pad_${i} = ${i}; // filler line for a large module`).join('\n') + '\n';
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
/** A project and a sibling directory standing in for "anywhere outside the project". */
|
||||
function layout(): { project: string; outside: string; world: World } {
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), 'ruflo-mods-every-write-')));
|
||||
roots.push(root);
|
||||
const project = join(root, 'project');
|
||||
const outside = join(root, 'outside');
|
||||
mkdirSync(join(project, 'src'), { recursive: true });
|
||||
mkdirSync(outside, { recursive: true });
|
||||
writeFileSync(join(project, 'src', 'config.ts'), BIG);
|
||||
const world = realWorld(project);
|
||||
world.liveLinkStat = true;
|
||||
return { project, outside, world };
|
||||
}
|
||||
|
||||
/** What the mod needs to find under `.claude-flow` (wherever it really lives) for every write path to fire. */
|
||||
function seedState(dir: string): void {
|
||||
mkdirSync(join(dir, CONSOLE_DIR.replace(/^\.claude-flow\//, '')), { recursive: true });
|
||||
const projection = join(dir, PROJECTION_PATH.replace(/^\.claude-flow\//, ''));
|
||||
mkdirSync(join(projection, '..'), { recursive: true });
|
||||
writeFileSync(projection, JSON.stringify(buildModProjection(new GuidanceCompiler().compile(SOURCE), REVISION)));
|
||||
}
|
||||
|
||||
/** Every file below `dir` with its bytes, so "unchanged" covers new, rewritten and appended files alike. */
|
||||
function tree(dir: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
const walk = (at: string) => {
|
||||
for (const name of readdirSync(at)) {
|
||||
const path = join(at, name);
|
||||
if (statSync(path).isDirectory()) walk(path);
|
||||
else out[relative(dir, path)] = readFileSync(path, 'utf8');
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `create: false` skips engine.create, so the toast writer session.start binds is the one in use (no `$.ruflo` noun beneath). */
|
||||
async function driveEveryWrite(world: World, create = true): Promise<void> {
|
||||
const mod = loadMod(register, world, OPTIONS);
|
||||
if (create) await mod.create();
|
||||
await mod.dispatch('session.start', { cwd: world.root, surface: null, isInteractive: false }, (e: { cwd: string }) => ({ cwd: e.cwd }));
|
||||
await mod.dispatch('prompt.submit', { text: 'explore the config and find the retry limit', wait: false, origin: { kind: 'composer' } }, (e: unknown) => e);
|
||||
const file = join(world.root, 'src', 'config.ts');
|
||||
await mod.dispatch('tool.call', { tool: 'Read', tool_use_id: 'r1', file_path: file }, () => ({
|
||||
result: { type: 'text', file: { filePath: file, content: BIG, numLines: 1201, startLine: 1, totalLines: 1201 } },
|
||||
}));
|
||||
await mod.dispatch('tool.call', { tool: 'Edit', tool_use_id: 'e1', file_path: file }, () => ({ result: 'ok' }));
|
||||
await mod.dispatch('tool.call', { tool: 'Bash', tool_use_id: 'b1', command: 'npm test' }, () => ({ result: { stdout: 'ok', stderr: '', interrupted: false } }));
|
||||
await mod.dispatch('session.measure', { context: {}, rateLimits: [], cost: { usd: 0.5 }, changed: ['cost'] }, (e: { changed: unknown }) => ({ changed: e.changed }));
|
||||
await mod.dispatch('turn.complete', { turnId: 't1', reason: 'answer', answer: 'done', durationMs: 5, isAborted: false }, () => ({ text: 'done' }));
|
||||
await mod.dispatch('turn.complete', { turnId: 't2', reason: 'error', answer: REFUSAL, durationMs: 1, isAborted: false }, () => ({ text: REFUSAL }));
|
||||
const msg = (role: 'user' | 'assistant', text: string) => ({ role, text, toolUses: [], handle: `h-${role}` });
|
||||
await mod.dispatch('session.compact', { trigger: 'manual', messages: [msg('user', 'please fix bug 0'), msg('assistant', 'looking at it')] }, () => ({ messages: [msg('user', 'summary')] }));
|
||||
await mod.dispatch('session.end', { reason: 'other', sessionId: 's1', resume: {} }, () => ({ sessionId: 's1' }));
|
||||
// The toast ring and the snapshot are written beside the hook: let them settle.
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
|
||||
/** Each write path, relative to `.claude-flow`. */
|
||||
const EXPECTED = [HEARTBEAT_PATH, PENDING_PATH, VERIFIED_PATH, METRICS_PATH, ATTRIBUTION_PATH, slotPath(0)].map((p) => p.replace(/^\.claude-flow\//, ''));
|
||||
|
||||
describe('#4746: every .claude-flow write is link-guarded', () => {
|
||||
it('control: in a real .claude-flow each write path writes', async () => {
|
||||
const { project, world } = layout();
|
||||
const state = join(project, '.claude-flow');
|
||||
seedState(state);
|
||||
await driveEveryWrite(world);
|
||||
const written = Object.keys(tree(state));
|
||||
for (const path of EXPECTED) expect(written, path).toContain(path);
|
||||
expect(written.some((p) => p.startsWith('mods/guidance/observations/')), 'guidance observations').toBe(true);
|
||||
expect(written.some((p) => p.startsWith(TOAST_DIR.replace(/^\.claude-flow\//, '') + '/')), 'toast ring').toBe(true);
|
||||
});
|
||||
|
||||
it('a symlinked .claude-flow -> outside dir: nothing outside the project is created or changed', async () => {
|
||||
const { project, outside, world } = layout();
|
||||
seedState(outside);
|
||||
symlinkSync(outside, join(project, '.claude-flow'), 'dir');
|
||||
const before = tree(outside);
|
||||
await driveEveryWrite(world);
|
||||
expect(tree(outside)).toEqual(before);
|
||||
});
|
||||
|
||||
it('a symlinked .claude-flow without engine.create (the toast writer session.start binds): nothing outside is written', async () => {
|
||||
const { project, outside, world } = layout();
|
||||
seedState(outside);
|
||||
symlinkSync(outside, join(project, '.claude-flow'), 'dir');
|
||||
const before = tree(outside);
|
||||
await driveEveryWrite(world, false);
|
||||
expect(tree(outside)).toEqual(before);
|
||||
});
|
||||
|
||||
it('a symlinked parent of .claude-flow subfolders (data/, cost/, metrics/) is refused too', async () => {
|
||||
const { project, outside, world } = layout();
|
||||
const state = join(project, '.claude-flow');
|
||||
seedState(state);
|
||||
for (const sub of ['data', 'cost', 'metrics', 'sessions']) {
|
||||
mkdirSync(join(outside, sub), { recursive: true });
|
||||
symlinkSync(join(outside, sub), join(state, sub), 'dir');
|
||||
}
|
||||
const before = tree(outside);
|
||||
await driveEveryWrite(world);
|
||||
expect(tree(outside)).toEqual(before);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* `writeWithoutLinks` (files.ts): the one guarded write for the mods'
|
||||
* `.claude-flow` files (#4746). The engine's `$.fs` has no `lstat` or
|
||||
* `realpath`, but its `stat` reports a link (`isLink`, plus the target's
|
||||
* kind) instead of following it silently — so the guard walks every path
|
||||
* component below the project root and refuses the write when any of them
|
||||
* is a link, is the wrong kind, or cannot be statted. These tests drive the
|
||||
* guard with a fake host shaped like the live engine's answers.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
import { writeWithoutLinks, type WriteHost } from '../../../../../plugins/ruflo-mods/hooks/files';
|
||||
|
||||
type Entry = { kind?: string; isLink?: boolean; error?: Error };
|
||||
const enoent = () => Object.assign(new Error("ENOENT: no such file or directory"), { code: 'ENOENT' });
|
||||
|
||||
function host(entries: Record<string, Entry>, missing: 'enoent' | 'refuse' = 'enoent') {
|
||||
const writes: { path: string; text: string }[] = [];
|
||||
const stats: string[] = [];
|
||||
const fs: WriteHost = {
|
||||
stat: async (path: string) => {
|
||||
stats.push(path);
|
||||
const entry = entries[path];
|
||||
if (!entry) {
|
||||
if (missing === 'enoent') throw enoent();
|
||||
throw new Error('EACCES: permission denied');
|
||||
}
|
||||
if (entry.error) throw entry.error;
|
||||
return { kind: entry.kind ?? 'file', size: 1, mtimeMs: 1, isLink: entry.isLink ?? false } as never;
|
||||
},
|
||||
write: async (path: string, text: string) => {
|
||||
writes.push({ path, text });
|
||||
},
|
||||
};
|
||||
return { fs, writes, stats };
|
||||
}
|
||||
|
||||
const ROOT = '/work';
|
||||
const PATH = '/work/.claude-flow/mods/session.json';
|
||||
const DIRS = {
|
||||
'/work/.claude-flow': { kind: 'dir' },
|
||||
'/work/.claude-flow/mods': { kind: 'dir' },
|
||||
};
|
||||
|
||||
describe('writeWithoutLinks', () => {
|
||||
it('writes when the folders and the target are all missing', async () => {
|
||||
const { fs, writes, stats } = host({});
|
||||
await writeWithoutLinks(fs, ROOT, PATH, 'hello');
|
||||
expect(writes).toEqual([{ path: PATH, text: 'hello' }]);
|
||||
// The first missing component ends the walk: nothing below it can exist.
|
||||
expect(stats).toEqual(['/work/.claude-flow']);
|
||||
});
|
||||
|
||||
it('overwrites an existing regular file', async () => {
|
||||
const { fs, writes } = host({ ...DIRS, [PATH]: { kind: 'file' } });
|
||||
await writeWithoutLinks(fs, ROOT, PATH, 'hello');
|
||||
expect(writes).toEqual([{ path: PATH, text: 'hello' }]);
|
||||
});
|
||||
|
||||
it('refuses a linked .claude-flow dir (the live engine reports the target kind plus isLink)', async () => {
|
||||
const { fs, writes } = host({ '/work/.claude-flow': { kind: 'dir', isLink: true } });
|
||||
await expect(writeWithoutLinks(fs, ROOT, PATH, 'hello')).rejects.toThrow(/is a link/);
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
|
||||
it('refuses a linked intermediate dir', async () => {
|
||||
const { fs, writes } = host({ '/work/.claude-flow': { kind: 'dir' }, '/work/.claude-flow/mods': { kind: 'dir', isLink: true } });
|
||||
await expect(writeWithoutLinks(fs, ROOT, PATH, 'hello')).rejects.toThrow(/is a link/);
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
|
||||
it('refuses a linked target', async () => {
|
||||
const { fs, writes } = host({ ...DIRS, [PATH]: { kind: 'file', isLink: true } });
|
||||
await expect(writeWithoutLinks(fs, ROOT, PATH, 'hello')).rejects.toThrow(/is a link/);
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
|
||||
it('refuses a target that exists but is not a regular file', async () => {
|
||||
const { fs, writes } = host({ ...DIRS, [PATH]: { kind: 'dir' } });
|
||||
await expect(writeWithoutLinks(fs, ROOT, PATH, 'hello')).rejects.toThrow(/not a regular file/);
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
|
||||
it('refuses an intermediate component that exists but is not a dir', async () => {
|
||||
const { fs, writes } = host({ '/work/.claude-flow': { kind: 'file' } });
|
||||
await expect(writeWithoutLinks(fs, ROOT, PATH, 'hello')).rejects.toThrow(/not a folder/);
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
|
||||
it('refuses a path outside the root', async () => {
|
||||
const { fs, writes } = host({});
|
||||
await expect(writeWithoutLinks(fs, ROOT, '/work/../outside/x.json', 'hello')).rejects.toThrow(/outside the project/);
|
||||
await expect(writeWithoutLinks(fs, ROOT, '/etc/x.json', 'hello')).rejects.toThrow(/outside the project/);
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
|
||||
it('refuses when a stat fails with anything but ENOENT (fail closed)', async () => {
|
||||
const { fs, writes } = host({ '/work/.claude-flow': { error: Object.assign(new Error('EACCES'), { code: 'EACCES' }) } });
|
||||
await expect(writeWithoutLinks(fs, ROOT, PATH, 'hello')).rejects.toThrow(/cannot be checked/);
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses a 'symlink' kind even when isLink is not set", async () => {
|
||||
const { fs, writes } = host({ ...DIRS, [PATH]: { kind: 'symlink', isLink: false } });
|
||||
await expect(writeWithoutLinks(fs, ROOT, PATH, 'hello')).rejects.toThrow(/is a link/);
|
||||
expect(writes).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not stat the project root itself (the root may legitimately be an alias)', async () => {
|
||||
const { fs, stats } = host({ '/work/.claude-flow': { kind: 'dir', isLink: true } });
|
||||
await expect(writeWithoutLinks(fs, ROOT, PATH, 'hello')).rejects.toThrow(/is a link/);
|
||||
expect(stats).not.toContain('/work');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* #4746 (review follow-up): `init --upgrade` must not leave companions that the
|
||||
* next run's integrity check reads as tampered.
|
||||
*
|
||||
* session.cjs and memory.cjs are signed critical helpers now, so the startup
|
||||
* refresh compares the installed bytes with the package's signed copies.
|
||||
* executeUpgrade used to regenerate both from the CLI's generators, whose
|
||||
* output is not byte-identical to the packaged copies, so every upgraded
|
||||
* project reported both as tampered (forever, under `.LOCKED` or an ahead
|
||||
* stamp, where the refresh only inspects). The upgrade now copies the
|
||||
* package's own bytes and falls back to the generators only when the package
|
||||
* ships no copy.
|
||||
*
|
||||
* The manifest here is signed with a throwaway key over the package's real
|
||||
* companion bytes: this repo's committed manifest is re-signed only by a
|
||||
* maintainer, at publish time (docs/helpers-sync.md).
|
||||
*/
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { generateKeyPairSync, sign as edSign } from 'node:crypto';
|
||||
|
||||
import { executeUpgrade } from '../src/init/executor.js';
|
||||
import { ensureCommonJsCompanions } from '../src/init/helper-companions.js';
|
||||
import { CRITICAL_HELPERS, findPackageHelpersDir, getInstalledCliVersion } from '../src/init/helper-refresh.js';
|
||||
import { verifyInstalledCriticalHelpers } from '../src/init/helper-integrity.js';
|
||||
import { canonicalManifestBytes, sha256Hex } from '../src/init/helper-signing.js';
|
||||
import { generateMemoryHelper, generateSessionManager } from '../src/init/helpers-generator.js';
|
||||
|
||||
const COMPANIONS = ['session.cjs', 'memory.cjs'] as const;
|
||||
const roots: string[] = [];
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function project(): { cwd: string; helpersDir: string } {
|
||||
const cwd = mkdtempSync(join(tmpdir(), 'ruflo-upgrade-integrity-4746-'));
|
||||
roots.push(cwd);
|
||||
const helpersDir = join(cwd, '.claude', 'helpers');
|
||||
mkdirSync(helpersDir, { recursive: true });
|
||||
mkdirSync(join(cwd, '.claude-flow', 'sessions'), { recursive: true });
|
||||
for (const name of COMPANIONS) writeFileSync(join(helpersDir, name), '// stale companion\n');
|
||||
return { cwd, helpersDir };
|
||||
}
|
||||
|
||||
/** A source dir holding the package's companion bytes under a throwaway-key manifest for this CLI version. */
|
||||
function signedPackageCopy(packageHelpers: string): { sourceDir: string; pubkeyPem: string } {
|
||||
const sourceDir = mkdtempSync(join(tmpdir(), 'ruflo-upgrade-integrity-4746-source-'));
|
||||
roots.push(sourceDir);
|
||||
const files: Record<string, string> = {};
|
||||
for (const name of COMPANIONS) {
|
||||
const bytes = readFileSync(join(packageHelpers, name));
|
||||
writeFileSync(join(sourceDir, name), bytes);
|
||||
files[name] = sha256Hex(bytes);
|
||||
}
|
||||
const { publicKey, privateKey } = generateKeyPairSync('ed25519');
|
||||
const manifest = { version: getInstalledCliVersion(), files };
|
||||
const signature = edSign(null, canonicalManifestBytes(manifest), privateKey).toString('base64');
|
||||
writeFileSync(join(sourceDir, 'helpers.manifest.json'), JSON.stringify({ manifest, signature, algorithm: 'ed25519' }));
|
||||
return { sourceDir, pubkeyPem: publicKey.export({ type: 'spki', format: 'pem' }).toString() };
|
||||
}
|
||||
|
||||
describe('#4746: init --upgrade then the integrity check', () => {
|
||||
const packageHelpers = findPackageHelpersDir();
|
||||
|
||||
it('the package ships both companions, and their bytes differ from the generators (the precondition of the bug)', () => {
|
||||
expect(packageHelpers).not.toBeNull();
|
||||
expect(readFileSync(join(packageHelpers!, 'session.cjs'), 'utf8')).not.toBe(generateSessionManager());
|
||||
expect(readFileSync(join(packageHelpers!, 'memory.cjs'), 'utf8')).not.toBe(generateMemoryHelper());
|
||||
});
|
||||
|
||||
it('an upgraded project passes the integrity check: the companions are the package\'s signed bytes', async () => {
|
||||
const { cwd, helpersDir } = project();
|
||||
const result = await executeUpgrade(cwd);
|
||||
expect(result.success).toBe(true);
|
||||
|
||||
// What the next run's startup refresh checks: before the fix both companions read as tampered.
|
||||
const { sourceDir, pubkeyPem } = signedPackageCopy(packageHelpers!);
|
||||
const integrity = verifyInstalledCriticalHelpers(helpersDir, sourceDir, CRITICAL_HELPERS, pubkeyPem, getInstalledCliVersion());
|
||||
expect(integrity.blocked).toBeUndefined();
|
||||
expect(integrity.tampered).toEqual([]);
|
||||
for (const name of COMPANIONS) {
|
||||
expect(result.updated).toContain(`.claude/helpers/${name}`);
|
||||
expect(readFileSync(join(helpersDir, name))).toEqual(readFileSync(join(packageHelpers!, name)));
|
||||
}
|
||||
});
|
||||
|
||||
it('falls back to the generators only for a companion the package does not ship (or ships as a link)', async () => {
|
||||
const { helpersDir } = project();
|
||||
const sourceDir = mkdtempSync(join(tmpdir(), 'ruflo-upgrade-integrity-4746-partial-'));
|
||||
roots.push(sourceDir);
|
||||
writeFileSync(join(sourceDir, 'session.cjs'), '// packaged session\n');
|
||||
writeFileSync(join(sourceDir, 'elsewhere.cjs'), '// not a companion\n');
|
||||
symlinkSync(join(sourceDir, 'elsewhere.cjs'), join(sourceDir, 'memory.cjs'));
|
||||
expect(await ensureCommonJsCompanions(helpersDir, true, sourceDir)).toEqual(['session.cjs', 'memory.cjs']);
|
||||
expect(readFileSync(join(helpersDir, 'session.cjs'), 'utf8')).toBe('// packaged session\n');
|
||||
expect(readFileSync(join(helpersDir, 'memory.cjs'), 'utf8')).toBe(generateMemoryHelper());
|
||||
});
|
||||
});
|
||||
@@ -31,7 +31,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const PKG_ROOT = join(__dirname, '..');
|
||||
const HELPERS_DIR = join(PKG_ROOT, '.claude', 'helpers');
|
||||
// Keep in sync with src/init/helper-refresh.ts:CRITICAL_HELPERS.
|
||||
const CRITICAL = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs', 'statusline.cjs', 'router.cjs', 'learning-loop.cjs'];
|
||||
const CRITICAL = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs', 'statusline.cjs', 'router.cjs', 'learning-loop.cjs', 'session.cjs', 'memory.cjs'];
|
||||
|
||||
function loadPrivateKey() {
|
||||
if (process.argv.includes('--stdin-key')) {
|
||||
|
||||
@@ -22,7 +22,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const PKG_ROOT = join(__dirname, '..');
|
||||
const HELPERS_DIR = resolve(process.argv[2] || join(PKG_ROOT, '.claude', 'helpers'));
|
||||
// Keep in sync with sign-helpers.mjs:CRITICAL and src/init/helper-refresh.ts:CRITICAL_HELPERS.
|
||||
const CRITICAL = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs', 'statusline.cjs', 'router.cjs', 'learning-loop.cjs'];
|
||||
const CRITICAL = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs', 'statusline.cjs', 'router.cjs', 'learning-loop.cjs', 'session.cjs', 'memory.cjs'];
|
||||
|
||||
function die(msg) { console.error(`[verify-helpers] ${msg}`); process.exit(1); }
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
generateAutoMemoryHook,
|
||||
generateRufloHookCjs,
|
||||
} from './helpers-generator.js';
|
||||
import { getInstalledCliVersion, HELPERS_STAMP_FILE } from './helper-refresh.js';
|
||||
import { findPackageHelpersDir, getInstalledCliVersion, HELPERS_STAMP_FILE } from './helper-refresh.js';
|
||||
import { generateClaudeMd } from './claudemd-generator.js';
|
||||
import { writeDualClaudeMd } from './dual-instructions.js';
|
||||
import { detectRufloPlugins, emptyDedupReport, type PluginDedupReport, type PluginProvided } from './plugin-dedup.js';
|
||||
@@ -652,7 +652,9 @@ export async function executeUpgrade(targetDir: string, upgradeSettings = false,
|
||||
// 0. ALWAYS update critical helpers (force overwrite)
|
||||
const sourceHelpersForUpgrade = findSourceHelpersDir();
|
||||
if (sourceHelpersForUpgrade) {
|
||||
// Keep in sync with helper-refresh.ts:CRITICAL_HELPERS.
|
||||
// Keep in sync with helper-refresh.ts:CRITICAL_HELPERS, except the
|
||||
// companions: ensureCommonJsCompanions(force=true) below owns them
|
||||
// (#4198) and copies the package's signed bytes when it has them.
|
||||
const criticalHelpers = ['auto-memory-hook.mjs', 'hook-handler.cjs', 'intelligence.cjs', 'statusline.cjs', 'router.cjs', 'learning-loop.cjs'];
|
||||
for (const helperName of criticalHelpers) {
|
||||
const targetPath = path.join(targetDir, '.claude', 'helpers', helperName);
|
||||
@@ -688,12 +690,16 @@ export async function executeUpgrade(targetDir: string, upgradeSettings = false,
|
||||
}
|
||||
|
||||
// #4198: refresh existing companions too, so upgraded hook handlers never
|
||||
// keep obsolete session/memory logic. Generate from the CLI trust root.
|
||||
// keep obsolete session/memory logic. #4746: the companions are signed
|
||||
// critical helpers now, so copy the package's signed bytes (the source the
|
||||
// startup refresh verifies against); a generated copy would differ from
|
||||
// the manifest and read as tampered on every later run. The generators
|
||||
// are the fallback only when the package ships no copy.
|
||||
const helpersDir = path.join(targetDir, '.claude', 'helpers');
|
||||
const existingCompanions = new Set<string>(COMMONJS_COMPANION_HELPERS.filter(
|
||||
(name) => fs.existsSync(path.join(helpersDir, name)),
|
||||
));
|
||||
for (const name of await ensureCommonJsCompanions(helpersDir, true)) {
|
||||
for (const name of await ensureCommonJsCompanions(helpersDir, true, findPackageHelpersDir())) {
|
||||
const changes = existingCompanions.has(name)
|
||||
? result.updated : result.created;
|
||||
changes.push(`.claude/helpers/${name}`);
|
||||
|
||||
@@ -8,7 +8,14 @@
|
||||
* refresh writes any missing `.cjs` companion from the CLI's own compiled
|
||||
* generators (the trust root; no external file to verify). Stale `.js` copies
|
||||
* are left in place and ignored. Existing `.cjs` files are preserved during
|
||||
* startup refresh; an explicit init upgrade replaces them from the generators.
|
||||
* startup refresh; an explicit init upgrade replaces them.
|
||||
*
|
||||
* Since #4746 both companions are also in the signed critical set, so the
|
||||
* startup integrity check compares them with the package's signed copies. A
|
||||
* caller that has the package's `.claude/helpers` passes it as `sourceDir`:
|
||||
* a companion present there is copied byte-for-byte (what the manifest
|
||||
* signs), and only a companion missing from it comes from the generators,
|
||||
* whose output is not byte-identical to the signed copy.
|
||||
*/
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
@@ -37,7 +44,18 @@ function safeHelpersDirectory(helpersDir: string): boolean {
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
export async function ensureCommonJsCompanions(helpersDir: string, force = false): Promise<string[]> {
|
||||
/** The package's own copy of a companion, or null when it has none (missing, a link, unreadable). */
|
||||
function packagedCompanion(sourceDir: string | null | undefined, name: string): string | null {
|
||||
if (!sourceDir) return null;
|
||||
const source = path.join(sourceDir, name);
|
||||
try {
|
||||
const stat = fs.lstatSync(source);
|
||||
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
||||
return fs.readFileSync(source, 'utf-8');
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
export async function ensureCommonJsCompanions(helpersDir: string, force = false, sourceDir?: string | null): Promise<string[]> {
|
||||
helpersDir = path.resolve(helpersDir);
|
||||
if (!safeHelpersDirectory(helpersDir)) return [];
|
||||
const missing = COMMONJS_COMPANION_HELPERS.filter((name) => {
|
||||
@@ -63,7 +81,7 @@ export async function ensureCommonJsCompanions(helpersDir: string, force = false
|
||||
const descriptor = fs.openSync(temporary, 'wx', 0o755);
|
||||
created = true;
|
||||
try {
|
||||
fs.writeFileSync(descriptor, content[name](), { encoding: 'utf-8' });
|
||||
fs.writeFileSync(descriptor, packagedCompanion(sourceDir, name) ?? content[name](), { encoding: 'utf-8' });
|
||||
fs.fchmodSync(descriptor, 0o755);
|
||||
} finally { fs.closeSync(descriptor); }
|
||||
if (!safeHelpersDirectory(helpersDir)) continue;
|
||||
|
||||
@@ -110,6 +110,13 @@ export const CRITICAL_HELPERS = [
|
||||
// bundled from the ruflo-mods loop source; here so every install records verified turns
|
||||
// and sees lessons on its next `ruflo` command, not only with the mod.
|
||||
'learning-loop.cjs',
|
||||
// session.cjs and memory.cjs are required by hook-handler.cjs on every hook,
|
||||
// so they carry the same trust as the rest of this list (#4746): the refresh
|
||||
// verifies them against the signed manifest and heals a tampered copy.
|
||||
// `ruflo init` still generates them from the CLI's own generators; the
|
||||
// signed copy wins on the next refresh.
|
||||
'session.cjs',
|
||||
'memory.cjs',
|
||||
];
|
||||
|
||||
function errorCode(error: unknown): string | undefined {
|
||||
|
||||
Reference in new issue
Block a user