From 59f4aabe1f17dadbde7c789d4c2a1706ee8d6c3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Oliveira?= Date: Mon, 16 Nov 2026 10:06:38 -0300 Subject: [PATCH 1/3] feat: redact home directories and secrets from discovery output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Manifest package and dependency names are untrusted text. The inventory now replaces home-directory prefixes with `~` and known secret shapes with `[redacted]` before they reach the graph, store, API or CLI output. The archwise.graph validator rejects labels that still contain a home directory (`home-path`), and `--json` no longer prints the absolute workspace root. Closes Phase 2: the roadmap records the exit-gate evidence, and the user guide gains a store-failure section. Co-Authored-By: Claude Opus 5.5 Signed-off-by: André Oliveira --- apps/cli/src/bin.ts | 9 +++- apps/cli/src/inventory.ts | 9 ++-- apps/cli/tests/inventory.test.ts | 22 +++++++++ docs/alpha-testing.md | 6 ++- docs/implementation-roadmap.md | 20 ++++++-- docs/security.md | 6 +++ packages/domain/README.md | 4 +- packages/domain/src/primitives.ts | 30 ++++++++++++ packages/domain/src/validation.ts | 3 ++ packages/domain/tests/primitives.test.ts | 56 +++++++++++++++++++++++ packages/domain/tests/validation.test.ts | 10 ++++ packages/schemas/tests/graph-json.test.ts | 14 ++++++ scripts/tests/cli-smoke.test.mjs | 25 ++++++++++ 13 files changed, 203 insertions(+), 11 deletions(-) diff --git a/apps/cli/src/bin.ts b/apps/cli/src/bin.ts index bd4abcb..6d86f4b 100644 --- a/apps/cli/src/bin.ts +++ b/apps/cli/src/bin.ts @@ -106,7 +106,14 @@ if (command.kind === 'output') { } else if (command.graph) { process.stdout.write(`${JSON.stringify(graph, null, 2)}\n`); } else if (command.json) { - process.stdout.write(`${JSON.stringify(result, null, 2)}\n`); + // Allowlist: the absolute root identifies the user and machine, so it is never printed. + const portable = { + version: result.version, + manifests: result.manifests, + diagnostics: result.diagnostics, + inspectedEntries: result.inspectedEntries, + }; + process.stdout.write(`${JSON.stringify(portable, null, 2)}\n`); } else { process.stdout.write(`Archwise — local inventory (${result.manifests.length} manifests)\n`); for (const item of result.manifests) { diff --git a/apps/cli/src/inventory.ts b/apps/cli/src/inventory.ts index c643fd9..b7a3ea4 100644 --- a/apps/cli/src/inventory.ts +++ b/apps/cli/src/inventory.ts @@ -1,5 +1,6 @@ import { lstat, readdir, readFile, realpath } from 'node:fs/promises'; import { resolve, relative, join, sep } from 'node:path'; +import { redactSensitiveText } from '@archwise/domain'; const IGNORED = new Set([ '.git', @@ -82,6 +83,8 @@ export async function inspectWorkspace(rootInput: string): Promise value && typeof value === 'object' && !Array.isArray(value) ? Object.keys(value) : [], ); + // Manifest text is untrusted: home directories and secret shapes never leave this boundary. + const dependencyNames = deps.map(redactSensitiveText); const frameworks = [ 'next', 'expo', @@ -91,12 +94,12 @@ export async function inspectWorkspace(rootInput: string): Promise deps.includes(item)) ?? null; + const framework = frameworks.find((item) => dependencyNames.includes(item)) ?? null; manifests.push({ path: relativePath, - name: typeof data.name === 'string' ? data.name : relativePath, + name: typeof data.name === 'string' ? redactSensitiveText(data.name) : relativePath, framework, - dependencies: [...new Set(deps)].sort(), + dependencies: [...new Set(dependencyNames)].sort(), }); } catch { diagnostics.push(`Invalid or unreadable manifest: ${relativePath}`); diff --git a/apps/cli/tests/inventory.test.ts b/apps/cli/tests/inventory.test.ts index 5aebe53..fcd48f9 100644 --- a/apps/cli/tests/inventory.test.ts +++ b/apps/cli/tests/inventory.test.ts @@ -41,3 +41,25 @@ test('reports malformed manifests without failing the entire scan', async () => await rm(root, { recursive: true, force: true }); } }); + +test('redacts home directories and secret shapes in names read from manifests', async () => { + const root = await mkdtemp(join(tmpdir(), 'archwise-redact-')); + const token = 'AKIA' + 'ABCDEFGHIJKLMNOP'; + try { + await mkdir(join(root, 'a'), { recursive: true }); + await mkdir(join(root, 'b'), { recursive: true }); + await writeFile( + join(root, 'a', 'package.json'), + JSON.stringify({ name: '/Users/alex/app', dependencies: { [`dep-${token}`]: '1' } }), + ); + await writeFile(join(root, 'b', 'package.json'), JSON.stringify({ name: `dep-${token}` })); + const result = await inspectWorkspace(root); + expect(result.manifests.map((item) => item.name)).toEqual(['~/app', 'dep-[redacted]']); + expect(result.manifests[0]?.dependencies).toEqual(['dep-[redacted]']); + const text = JSON.stringify(result.manifests); + expect(text).not.toContain('/Users/alex'); + expect(text).not.toContain(token); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/docs/alpha-testing.md b/docs/alpha-testing.md index 4452b84..c9a21eb 100644 --- a/docs/alpha-testing.md +++ b/docs/alpha-testing.md @@ -30,7 +30,7 @@ The CLI starts a server bound to `127.0.0.1` on an available port. If the browse node apps/cli/dist/bin.js --path /absolute/path/to/your/project --graph ``` -Use `--json` for the inventory instead of the graph, or `--serve --no-open` to avoid automatic browser launch. +Use `--json` for the inventory instead of the graph, or `--serve --no-open` to avoid automatic browser launch. Both JSON outputs use repository-relative paths and omit the absolute project root. They still contain your package names, so review them before sharing. ## What to verify @@ -58,6 +58,10 @@ Use `--json` for the inventory instead of the graph, or `--serve --no-open` to a - Default analysis reads project files; it never executes scripts from the inspected repository. No cloud account or remote AI is required. - Browser access requires a one-time local session URL; do not share the URL or browser session cookie. +## If the local store fails + +Archwise never deletes your sessions to recover. When the store is corrupt it moves the file aside, starts a fresh store and prints where the old file is. When the store was written by a newer Archwise, or an upgrade fails, it exits with code 2 and leaves the file untouched. Run with `--no-store` to keep inspecting without sessions, or set `ARCHWISE_DATA_DIR` to use another directory. The full table is in [Sessions: recovery and failures](sessions.md#recovery-and-failures). + ## Verified automated checks The `main` branch passes the full `pnpm check` matrix on Linux, macOS and Windows using Node 24 and Node 26, including an authenticated HTTP smoke test of discovery → graph → server → compiled Studio assets. The `Browser Studio Smoke` workflow also exercises the Studio in headless Chromium on Ubuntu (see [Browser QA](browser-qa.md)). **Visual review, touch input, Safari/Firefox and OS-specific browser launch are still verified manually.** diff --git a/docs/implementation-roadmap.md b/docs/implementation-roadmap.md index 5ff08bb..59b3117 100644 --- a/docs/implementation-roadmap.md +++ b/docs/implementation-roadmap.md @@ -34,13 +34,13 @@ Finalization does not mean development stops. It establishes a reliable open-sou ## Current state -Snapshot as of 2026-11-15, after PRs #5, #6 and #7 merged into `main`. Issues and milestones remain the live tracker. +Snapshot as of 2026-11-16, after the Phase 2 redaction PR. Issues and milestones remain the live tracker. | Phase | State on `main` | What is missing for the exit gate | |---|---|---| | 0 | Complete (2026-11-15) | — | | 1 | Complete (2026-11-15) | — | -| 2 | Partial: graph contracts; SQLite store with ports, migrations, backup and recovery; sessions with Studio autosave and resume | Export redaction of home paths; storage recovery in an end-user release guide | +| 2 | Complete (2026-11-16) | — | | 3 | Alpha only: manifest-only inventory in `apps/cli` | Budgets, ignore rules, symlink and nested-repository handling, `--repo` / `--workspace`, persisted scan metadata | | 4 | Alpha only: Node package manifests | Analyzer SDK, TS imports, HTTP/DB/queue detectors, Compose, golden graphs | | 5 | Alpha only: protected loopback server and Svelte Flow Studio | SSE progress, evidence navigation from domain revisions, accessibility, large-graph strategy | @@ -139,13 +139,25 @@ Detailed execution plan: [`superpowers/plans/2026-11-08-archwise-foundation.md`] ## Phase 2 — Domain contracts and local persistence -Status: in progress. The graph-contracts slice is implemented in `@archwise/domain` and `@archwise/schemas`. It covers the validated, immutable and canonically serialized `archwise.graph` v1 revision, strict import, and sandbox base references; see the [spec](superpowers/specs/2026-11-11-graph-contracts-design.md). The sessions slice adds the following (see [Sessions](sessions.md) and [ADR 0006](decisions/0006-local-store-node-sqlite.md)): +Status: complete (2026-11-16). The graph-contracts slice is implemented in `@archwise/domain` and `@archwise/schemas`. It covers the validated, immutable and canonically serialized `archwise.graph` v1 revision, strict import, and sandbox base references; see the [spec](superpowers/specs/2026-11-11-graph-contracts-design.md). The sessions slice adds the following (see [Sessions](sessions.md) and [ADR 0006](decisions/0006-local-store-node-sqlite.md)): - application store ports and a `SessionService`; - the `@archwise/storage` SQLite adapter, with transactional migrations, pre-migration backup, corruption quarantine and refusal of newer schemas; - revision recording from discovery; - the protected session API and `--sessions` / `--no-store`. -The Studio uses the store: autosave, a session list, resume, a changed-architecture notice and `--resume`. Still open: redaction of absolute home paths in exports. The phase exit gate is not yet satisfied. +The Studio uses the store: autosave, a session list, resume, a changed-architecture notice and `--resume`. Manifest text is redacted at the discovery boundary, and the graph validator rejects labels with home directories or secret shapes ([Security](security.md#redaction-at-the-discovery-boundary)). + +Exit-gate evidence: + +| Exit criterion | Evidence | +|---|---| +| Domain and schemas stay independent of Node APIs and frameworks | `scripts/check-boundaries.mjs` rules with regression tests in `scripts/tests/boundaries.test.mjs`, run by `pnpm check` | +| The same fixture serializes identically across platforms | The golden canonical-bytes test in `packages/schemas/tests/graph-json.test.ts` passes on the CI matrix (Linux, macOS, Windows × Node 24, 26) | +| Corrupt or future-version data fails safely with actionable diagnostics | Graph import rejects future versions (`unsupported-future-version`); the store quarantines corrupt files and refuses newer schemas untouched (`packages/storage/tests/lifecycle.test.ts`) | +| Storage recovery is documented and tested | [Sessions: recovery and failures](sessions.md#recovery-and-failures), the user guide's [store failure section](alpha-testing.md#if-the-local-store-fails), and the lifecycle tests | +| Redaction tests (required tests) | Domain primitive and validation tests, the inventory adapter test and the built-CLI test in `scripts/tests/cli-smoke.test.mjs` | + +Work packages moved to the phase that first needs them, so no port exists without a caller: the filesystem inventory port and scan repositories (Phase 3), scan lifecycle events and event publication (Phase 5), and the provider port (Phase 9). Browser launch stays in `apps/cli` until the server moves out of it (ADR 0005 debt). ### Goal diff --git a/docs/security.md b/docs/security.md index 72d14e9..7a7522c 100644 --- a/docs/security.md +++ b/docs/security.md @@ -24,6 +24,12 @@ The local SQLite store ([ADR 0006](decisions/0006-local-store-node-sqlite.md)) l It never contains source file contents. It is not synchronized or exported, and the API never returns root paths. Session routes require the local session capability. Mutations also require a same-origin `Origin` header, a JSON content type and a body under 300,000 bytes. Users can delete the directory to remove all stored data. +## Redaction at the discovery boundary + +Text read from analyzed manifests (package and dependency names) is untrusted. Before it reaches the graph, the store, the API or any output, the CLI inventory replaces home-directory prefixes (`/Users/`, `/home/`, `/var/home/`, `/root`, `C:\Users\`) with `~` and known secret shapes with `[redacted]`. The `archwise.graph` validator then rejects any label that still contains either, so a revision cannot carry them. `--json` and `--graph` output contain repository-relative paths only, never the absolute workspace root. Tests cover each layer: domain primitives and validation, the inventory adapter, and the built CLI output. + +Pattern matching is defense in depth. It does not prove that text is free of sensitive data. + ## Secret handling Archwise inventories the existence of sensitive configuration only when useful; it does not read `.env` values, private keys, credential directories, or known secret files by default. Provider keys live in the OS credential store where supported. Diagnostic bundles require preview and explicit export, with a second redaction pass. diff --git a/packages/domain/README.md b/packages/domain/README.md index eb21917..18d3a15 100644 --- a/packages/domain/README.md +++ b/packages/domain/README.md @@ -3,11 +3,11 @@ Pure graph contracts with no runtime dependencies, filesystem, clock or randomness. - `graph.ts`: the `archwise.graph` v1 vocabulary. It covers repositories, evidence, analyzer coverage, nodes, edges, diagnostics, `GraphRevision` and the safety `LIMITS`. -- `primitives.ts`: validators for IDs, codes, labels, timestamps and relative paths, known secret-pattern detection, and code-unit ordering. +- `primitives.ts`: validators for IDs, codes, labels, timestamps and relative paths, known secret-pattern and home-directory detection, `redactSensitiveText` for adapters, and code-unit ordering. - `validation.ts`: `validateRevision` returns stable error codes with structural paths and never echoes rejected values. - `revision.ts`: `createRevision` copies the input, validates it and returns a canonical, deeply frozen revision. `canonicalizeRevision` applies the deterministic ordering. - `sandbox.ts`: `bindSandbox` checks that a readonly sandbox reference matches its base revision. Operation logs are not part of this package yet. -Secret-pattern checks are defense in depth, not proof that a label or path contains no sensitive data. +Labels that contain a known secret shape (`secret-pattern`) or an absolute home-directory path such as `/Users/`, `/home/` or `C:\Users\` (`home-path`) are rejected. These checks are defense in depth, not proof that a label or path contains no sensitive data. Public exports live in `src/index.ts`. Tests live in `tests/`. Run `pnpm --filter @archwise/domain test` from the root. Build dependencies first with `pnpm build`. diff --git a/packages/domain/src/primitives.ts b/packages/domain/src/primitives.ts index 72be144..e1355d6 100644 --- a/packages/domain/src/primitives.ts +++ b/packages/domain/src/primitives.ts @@ -22,6 +22,17 @@ const SECRET_PATTERNS: readonly RegExp[] = [ /eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\./, ]; +// A home directory is a recognizable absolute prefix. The look-behind keeps relative paths such +// as `src/home/page` and route-like labels such as `/api/users` out of the match. +const HOME_PATH_SOURCES: readonly string[] = [ + String.raw`(?|]+`, + String.raw`(?|]|$)`, + String.raw`(?|]+`, +]; +const HOME_PATH_PATTERNS: readonly RegExp[] = HOME_PATH_SOURCES.map( + (source) => new RegExp(source, 'i'), +); + export function isValidId(value: string): boolean { return ID_PATTERN.test(value); } @@ -78,6 +89,25 @@ export function containsSecretPattern(value: string): boolean { return SECRET_PATTERNS.some((pattern) => pattern.test(value)); } +/** Detects absolute home-directory paths (macOS, Linux, Windows), which identify the user and machine. */ +export function containsHomePath(value: string): boolean { + return HOME_PATH_PATTERNS.some((pattern) => pattern.test(value)); +} + +/** + * Replaces home-directory prefixes with `~` and known secret shapes with `[redacted]`. + * Adapters use it on text read from analyzed projects before that text can reach a graph, + * an export or an API response. Validation still rejects anything that slips through. + */ +export function redactSensitiveText(value: string): string { + let result = value; + for (const source of HOME_PATH_SOURCES) result = result.replace(new RegExp(source, 'gi'), '~'); + for (const pattern of SECRET_PATTERNS) { + result = result.replace(new RegExp(pattern.source, 'g'), '[redacted]'); + } + return result; +} + /** Locale-independent ordering by UTF-16 code unit. */ export function compareCodeUnits(a: string, b: string): number { if (a < b) return -1; diff --git a/packages/domain/src/validation.ts b/packages/domain/src/validation.ts index 5003b22..a91297d 100644 --- a/packages/domain/src/validation.ts +++ b/packages/domain/src/validation.ts @@ -12,6 +12,7 @@ import { } from './graph.js'; import { checkRelativePath, + containsHomePath, containsSecretPattern, isValidCode, isValidId, @@ -32,6 +33,7 @@ export type ValidationErrorCode = | 'invalid-line-range' | 'unsafe-path' | 'secret-pattern' + | 'home-path' | 'limit-exceeded' | 'containment-cycle' | 'self-containment' @@ -79,6 +81,7 @@ class IssueCollector { label(value: string, path: IssuePath): void { if (!isValidLabel(value)) this.add('invalid-label', path); else if (containsSecretPattern(value)) this.add('secret-pattern', path); + else if (containsHomePath(value)) this.add('home-path', path); } code(value: string, path: IssuePath): void { diff --git a/packages/domain/tests/primitives.test.ts b/packages/domain/tests/primitives.test.ts index 823b5c3..9d35da2 100644 --- a/packages/domain/tests/primitives.test.ts +++ b/packages/domain/tests/primitives.test.ts @@ -2,12 +2,14 @@ import { describe, expect, test } from 'vitest'; import { checkRelativePath, compareCodeUnits, + containsHomePath, containsSecretPattern, isValidCode, isValidId, isValidLabel, isValidTimestamp, LIMITS, + redactSensitiveText, } from '../src/index.js'; import { syntheticSecrets } from './secrets.js'; @@ -90,6 +92,60 @@ describe('containsSecretPattern', () => { }); }); +describe('containsHomePath', () => { + test.each([ + '/Users/alex', + '/Users/alex/projects/app', + '/home/alex/app', + '/var/home/alex/app', + '/root/app', + '/root', + 'C:\\Users\\alex\\app', + 'c:/users/alex/app', + 'name at /Users/alex/x', + 'file:///home/alex/app', + ])('detects %s', (value) => { + expect(containsHomePath(value)).toBe(true); + }); + test.each([ + 'src/home/page', + 'apps/users/list', + '@scope/users', + '/api/users', + '/usr/local/lib', + '~/projects/app', + 'rootless', + '/rooted', + 'ordinary-label', + ])('ignores %s', (value) => { + expect(containsHomePath(value)).toBe(false); + }); +}); + +describe('redactSensitiveText', () => { + test.each([ + ['/Users/alex/projects/app', '~/projects/app'], + ['/home/alex', '~'], + ['/var/home/alex/app', '~/app'], + ['/root/app', '~/app'], + ['C:\\Users\\alex\\app', '~\\app'], + ['pkg at /home/alex/a and /Users/bo/b', 'pkg at ~/a and ~/b'], + ])('replaces the home directory in %s', (input, expected) => { + expect(redactSensitiveText(input)).toBe(expected); + expect(containsHomePath(redactSensitiveText(input))).toBe(false); + }); + test.each(Object.entries(syntheticSecrets))('replaces a %s secret', (_name, secret) => { + const redacted = redactSensitiveText(`before ${secret} after`); + expect(redacted.startsWith('before [redacted]')).toBe(true); + expect(redacted.endsWith(' after')).toBe(true); + expect(redacted).not.toContain(secret); + expect(containsSecretPattern(redacted)).toBe(false); + }); + test('leaves ordinary text unchanged', () => { + expect(redactSensitiveText('@scope/users-api')).toBe('@scope/users-api'); + }); +}); + test('compareCodeUnits sorts by UTF-16 code unit, not locale', () => { expect(['b', 'B', 'a', '_'].sort(compareCodeUnits)).toEqual(['B', '_', 'a', 'b']); expect(compareCodeUnits('a', 'a')).toBe(0); diff --git a/packages/domain/tests/validation.test.ts b/packages/domain/tests/validation.test.ts index d6536e5..8aea548 100644 --- a/packages/domain/tests/validation.test.ts +++ b/packages/domain/tests/validation.test.ts @@ -131,6 +131,16 @@ describe('rejects each invariant violation with a stable code and structural pat (r) => (r.nodes[0]!.label = `key ${syntheticSecrets.aws}`), { code: 'secret-pattern', path: ['nodes', 0, 'label'] }, ], + [ + 'home directory in node label', + (r) => (r.nodes[0]!.label = '/Users/alex/app'), + { code: 'home-path', path: ['nodes', 0, 'label'] }, + ], + [ + 'home directory in repository label', + (r) => (r.repositories[0]!.label = 'C:\\Users\\alex\\repo'), + { code: 'home-path', path: ['repositories', 0, 'label'] }, + ], [ 'secret in path', (r) => (r.evidence[0]!.path = `config/${syntheticSecrets.github}`), diff --git a/packages/schemas/tests/graph-json.test.ts b/packages/schemas/tests/graph-json.test.ts index 7b2ce80..48bd2f8 100644 --- a/packages/schemas/tests/graph-json.test.ts +++ b/packages/schemas/tests/graph-json.test.ts @@ -111,6 +111,20 @@ test('refuses to serialize a secret-bearing label and does not echo it', () => { expect(JSON.stringify(result)).not.toContain(syntheticAwsKey); }); +test('neither export nor import accepts a label with a home directory, and neither echoes it', () => { + const revision = revisionOf(validEnvelope()); + const home = '/home/alex/private-app'; + const tampered = { ...revision, nodes: revision.nodes.map((n) => ({ ...n, label: home })) }; + const exported = serializeGraphRevision(tampered); + expect(exported.ok ? [] : exported.issues.map((i) => i.code)).toContain('home-path'); + expect(JSON.stringify(exported)).not.toContain(home); + const envelope = validEnvelope(); + envelope.revision.nodes[0].label = home; + const imported = importGraphJson(JSON.stringify(envelope)); + expect(imported.ok ? [] : imported.issues.map((i) => i.code)).toContain('home-path'); + expect(JSON.stringify(imported)).not.toContain(home); +}); + test('serialization excludes undeclared fields', () => { const revision = revisionOf(validEnvelope()); const withExtra = { ...revision, absoluteRoot: '/home/user/repo' } as GraphRevision; diff --git a/scripts/tests/cli-smoke.test.mjs b/scripts/tests/cli-smoke.test.mjs index ca5da80..9134cd9 100644 --- a/scripts/tests/cli-smoke.test.mjs +++ b/scripts/tests/cli-smoke.test.mjs @@ -22,3 +22,28 @@ test('built CLI exposes help and version with correct exit codes', () => { assert.equal(unsupported.stdout, ''); assert.match(unsupported.stderr, /Unsupported/); }); + +test('--json and --graph never print the absolute root, home directories or secret shapes', async () => { + const { mkdtempSync, mkdirSync, writeFileSync, realpathSync, rmSync } = await import('node:fs'); + const { join } = await import('node:path'); + const { tmpdir } = await import('node:os'); + const root = realpathSync(mkdtempSync(join(tmpdir(), 'archwise-export-'))); + const token = 'AKIA' + 'ABCDEFGHIJKLMNOP'; + try { + mkdirSync(join(root, 'app')); + writeFileSync( + join(root, 'app', 'package.json'), + JSON.stringify({ name: '/home/alex/app', dependencies: { [`x-${token}`]: '1' } }), + ); + for (const flag of ['--json', '--graph']) { + const run = spawnSync(process.execPath, [entry, '--path', root, flag], { encoding: 'utf8' }); + assert.equal(run.status, 0, run.stderr); + JSON.parse(run.stdout); + assert.ok(!run.stdout.includes(root), `${flag} printed the absolute root`); + assert.ok(!run.stdout.includes('/home/alex'), `${flag} printed a home directory`); + assert.ok(!run.stdout.includes(token), `${flag} printed a secret shape`); + } + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); From 8575e838fccf3c8e1d7430062625da23aba8d72b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Oliveira?= Date: Mon, 16 Nov 2026 10:12:03 -0300 Subject: [PATCH 2/3] fix: redaction never reassembles secrets or home paths, and keeps routes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review findings on the redaction change: - Secrets are removed before home paths and redaction repeats until stable, so `[redacted]/Users/x` can no longer appear. - Secret redaction removes the whole token: a private-key block through its end marker and a JWT including its signature. - Generic detection is limited to `/Users/` (case-sensitive) and `X:\Users\`, so route labels such as `GET /users/:id` and `/home/feed` stay valid. The CLI passes the running user's real home directory for exact redaction instead. The graph-contracts spec records the `home-path` amendment, and the security docs state what is and is not redacted. Co-Authored-By: Claude Opus 5.5 Signed-off-by: André Oliveira --- apps/cli/src/bin.ts | 5 +- apps/cli/src/inventory.ts | 15 +++- apps/cli/tests/inventory.test.ts | 15 ++++ docs/alpha-testing.md | 2 +- docs/implementation-roadmap.md | 2 +- docs/security.md | 9 ++- .../2026-11-11-graph-contracts-design.md | 2 +- packages/domain/README.md | 2 +- packages/domain/src/primitives.ts | 65 ++++++++++----- packages/domain/tests/primitives.test.ts | 79 ++++++++++++++----- packages/schemas/tests/graph-json.test.ts | 2 +- scripts/tests/cli-smoke.test.mjs | 8 +- 12 files changed, 155 insertions(+), 51 deletions(-) diff --git a/apps/cli/src/bin.ts b/apps/cli/src/bin.ts index 6d86f4b..f77e958 100644 --- a/apps/cli/src/bin.ts +++ b/apps/cli/src/bin.ts @@ -1,5 +1,6 @@ #!/usr/bin/env node import { readFileSync } from 'node:fs'; +import { realpath } from 'node:fs/promises'; import { spawn } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { basename, resolve } from 'node:path'; @@ -51,7 +52,9 @@ if (command.kind === 'output') { } else { const dataDir = resolveDataDir(process.env, process.platform, homedir()); try { - const result = await inspectWorkspace(command.path); + const home = homedir(); + const knownHomes = [home, await realpath(home).catch(() => home)]; + const result = await inspectWorkspace(command.path, { knownHomes }); const graph = buildArchitectureGraph(result); const prepareRuntime = async (enabled: boolean) => { const runtime = await prepareStore({ diff --git a/apps/cli/src/inventory.ts b/apps/cli/src/inventory.ts index b7a3ea4..ab97f6f 100644 --- a/apps/cli/src/inventory.ts +++ b/apps/cli/src/inventory.ts @@ -32,8 +32,17 @@ export interface InventoryResult { readonly inspectedEntries: number; } +export interface InventoryOptions { + /** The running user's home directories (as given and resolved), redacted from manifest text. */ + readonly knownHomes?: readonly string[]; +} + /** Inspect manifests as data. Do not execute/import any code in the target workspace. */ -export async function inspectWorkspace(rootInput: string): Promise { +export async function inspectWorkspace( + rootInput: string, + options: InventoryOptions = {}, +): Promise { + const redact = (text: string): string => redactSensitiveText(text, options.knownHomes ?? []); const root = await realpath(resolve(rootInput)); if (!(await lstat(root)).isDirectory()) throw new Error('Workspace root must be a directory'); const manifests: ManifestEvidence[] = []; @@ -84,7 +93,7 @@ export async function inspectWorkspace(rootInput: string): Promise dependencyNames.includes(item)) ?? null; manifests.push({ path: relativePath, - name: typeof data.name === 'string' ? redactSensitiveText(data.name) : relativePath, + name: typeof data.name === 'string' ? redact(data.name) : relativePath, framework, dependencies: [...new Set(dependencyNames)].sort(), }); diff --git a/apps/cli/tests/inventory.test.ts b/apps/cli/tests/inventory.test.ts index fcd48f9..475d994 100644 --- a/apps/cli/tests/inventory.test.ts +++ b/apps/cli/tests/inventory.test.ts @@ -63,3 +63,18 @@ test('redacts home directories and secret shapes in names read from manifests', await rm(root, { recursive: true, force: true }); } }); + +test('redacts the running user home directory supplied by the caller', async () => { + const root = await mkdtemp(join(tmpdir(), 'archwise-home-')); + try { + await writeFile( + join(root, 'package.json'), + JSON.stringify({ name: '/home/alex/app', dependencies: { '/home/feed': '1' } }), + ); + const result = await inspectWorkspace(root, { knownHomes: ['/home/alex'] }); + expect(result.manifests[0]?.name).toBe('~/app'); + expect(result.manifests[0]?.dependencies).toEqual(['/home/feed']); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/docs/alpha-testing.md b/docs/alpha-testing.md index c9a21eb..ea3f526 100644 --- a/docs/alpha-testing.md +++ b/docs/alpha-testing.md @@ -60,7 +60,7 @@ Use `--json` for the inventory instead of the graph, or `--serve --no-open` to a ## If the local store fails -Archwise never deletes your sessions to recover. When the store is corrupt it moves the file aside, starts a fresh store and prints where the old file is. When the store was written by a newer Archwise, or an upgrade fails, it exits with code 2 and leaves the file untouched. Run with `--no-store` to keep inspecting without sessions, or set `ARCHWISE_DATA_DIR` to use another directory. The full table is in [Sessions: recovery and failures](sessions.md#recovery-and-failures). +Archwise never deletes your sessions to recover. When the store is corrupt it moves the file aside, starts a fresh store and prints where the old file is. When the store was written by a newer Archwise, or an upgrade fails, it exits with code 2 and leaves the file untouched. It also exits with code 2 when the data directory is not writable. Run with `--no-store` to keep inspecting without sessions, or set `ARCHWISE_DATA_DIR` to use another directory. The full table is in [Sessions: recovery and failures](sessions.md#recovery-and-failures). ## Verified automated checks diff --git a/docs/implementation-roadmap.md b/docs/implementation-roadmap.md index 59b3117..5e628ca 100644 --- a/docs/implementation-roadmap.md +++ b/docs/implementation-roadmap.md @@ -34,7 +34,7 @@ Finalization does not mean development stops. It establishes a reliable open-sou ## Current state -Snapshot as of 2026-11-16, after the Phase 2 redaction PR. Issues and milestones remain the live tracker. +Snapshot as of 2026-11-16, after PRs #5 to #12 and the Phase 2 redaction change. Issues and milestones remain the live tracker. | Phase | State on `main` | What is missing for the exit gate | |---|---|---| diff --git a/docs/security.md b/docs/security.md index 7a7522c..ed58ed0 100644 --- a/docs/security.md +++ b/docs/security.md @@ -26,7 +26,14 @@ It never contains source file contents. It is not synchronized or exported, and ## Redaction at the discovery boundary -Text read from analyzed manifests (package and dependency names) is untrusted. Before it reaches the graph, the store, the API or any output, the CLI inventory replaces home-directory prefixes (`/Users/`, `/home/`, `/var/home/`, `/root`, `C:\Users\`) with `~` and known secret shapes with `[redacted]`. The `archwise.graph` validator then rejects any label that still contains either, so a revision cannot carry them. `--json` and `--graph` output contain repository-relative paths only, never the absolute workspace root. Tests cover each layer: domain primitives and validation, the inventory adapter, and the built CLI output. +Text read from analyzed manifests (package and dependency names) is untrusted. Before it reaches the graph, the store, the API or any output, the CLI inventory: +- replaces known secret shapes with `[redacted]`, removing the whole token (a private-key block up to its end marker, a JWT including its signature); +- replaces home directories with `~`: the running user's real home directory, plus the generic `/Users/` and `X:\Users\` shapes; +- repeats until nothing changes, so removing one piece cannot reassemble another. + +The `archwise.graph` validator rejects labels that still contain a secret shape or a generic home-directory shape. Linux `/home/` is redacted only for the running user, because route labels such as `/home/feed` share its shape. `--json` and `--graph` output use repository-relative paths and never print the absolute workspace root. Directory names are not redacted: a directory named like a secret appears in evidence paths, and the graph validator then rejects that revision, so sessions are not saved for that run. + +Tests cover the domain primitives and validation, the inventory adapter, and the built CLI output. Pattern matching is defense in depth. It does not prove that text is free of sensitive data. diff --git a/docs/superpowers/specs/2026-11-11-graph-contracts-design.md b/docs/superpowers/specs/2026-11-11-graph-contracts-design.md index c8edcbf..aaa0f9b 100644 --- a/docs/superpowers/specs/2026-11-11-graph-contracts-design.md +++ b/docs/superpowers/specs/2026-11-11-graph-contracts-design.md @@ -51,7 +51,7 @@ The JSON importer accepts text up to 16 MiB measured as UTF-8 before parsing. Li Canonical serialization uses explicit object field order, sorts record collections by ID, coverage by repository/analyzer/version, and set-like reference/reason lists by ASCII code-unit order. Reject duplicate coverage keys and duplicate reference/reason entries. Do not use locale-sensitive sorting. Emit compact JSON without a trailing newline; preserve Unicode label spelling. Same logical revision, IDs, timestamp and schema version must produce identical UTF-8 bytes regardless of input collection order or OS. -Serialization validates again and includes only declared portable fields. Labels and paths remain untrusted strings: reject control characters and known secret-value patterns before export, and test synthetic credential examples. This is defense in depth, not proof that arbitrary labels contain no sensitive information. A later user-facing export flow must offer review; documentation must not claim perfect secret detection. No source content or absolute-root field is accepted by the format. +Serialization validates again and includes only declared portable fields. Labels and paths remain untrusted strings: reject control characters and known secret-value patterns before export, and test synthetic credential examples. Amendment (2026-11-16, Phase 2 redaction): labels with a generic home-directory shape, `/Users/` (case-sensitive) or `X:\Users\`, are rejected as `home-path`. Linux `/home/` and `/root` are not rejected by the format, because route labels such as `/home/feed` share that shape; adapters redact the running user's actual home directory instead. This is defense in depth, not proof that arbitrary labels contain no sensitive information. A later user-facing export flow must offer review; documentation must not claim perfect secret detection. No source content or absolute-root field is accepted by the format. ## Sandbox boundary diff --git a/packages/domain/README.md b/packages/domain/README.md index 18d3a15..d616320 100644 --- a/packages/domain/README.md +++ b/packages/domain/README.md @@ -8,6 +8,6 @@ Pure graph contracts with no runtime dependencies, filesystem, clock or randomne - `revision.ts`: `createRevision` copies the input, validates it and returns a canonical, deeply frozen revision. `canonicalizeRevision` applies the deterministic ordering. - `sandbox.ts`: `bindSandbox` checks that a readonly sandbox reference matches its base revision. Operation logs are not part of this package yet. -Labels that contain a known secret shape (`secret-pattern`) or an absolute home-directory path such as `/Users/`, `/home/` or `C:\Users\` (`home-path`) are rejected. These checks are defense in depth, not proof that a label or path contains no sensitive data. +Labels that contain a known secret shape (`secret-pattern`) or a generic home-directory path, `/Users/` or `C:\Users\` (`home-path`), are rejected. `redactSensitiveText` also accepts the running user's home directories, so adapters can redact Linux homes without flagging route labels such as `/home/feed`. These checks are defense in depth, not proof that a label or path contains no sensitive data. Public exports live in `src/index.ts`. Tests live in `tests/`. Run `pnpm --filter @archwise/domain test` from the root. Build dependencies first with `pnpm build`. diff --git a/packages/domain/src/primitives.ts b/packages/domain/src/primitives.ts index e1355d6..7d37683 100644 --- a/packages/domain/src/primitives.ts +++ b/packages/domain/src/primitives.ts @@ -22,16 +22,31 @@ const SECRET_PATTERNS: readonly RegExp[] = [ /eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\./, ]; -// A home directory is a recognizable absolute prefix. The look-behind keeps relative paths such -// as `src/home/page` and route-like labels such as `/api/users` out of the match. -const HOME_PATH_SOURCES: readonly string[] = [ - String.raw`(?|]+`, - String.raw`(?|]|$)`, - String.raw`(?|]+`, +// Generic home-directory shapes that ordinary route labels do not use: the macOS `/Users/` +// (case-sensitive, so the common `/users/:id` route stays intact) and the Windows +// `X:\Users\`. The Windows form runs first so `C:/Users/x` is replaced as one unit. +// Linux `/home/` and `/root` collide with routes, so adapters pass the real home directory. +const HOME_PATH_RULES: readonly { readonly source: string; readonly flags: string }[] = [ + { + source: String.raw`(?|()]+`, + flags: 'i', + }, + { source: String.raw`(?|()]+`, flags: '' }, ]; -const HOME_PATH_PATTERNS: readonly RegExp[] = HOME_PATH_SOURCES.map( - (source) => new RegExp(source, 'i'), +const HOME_PATH_PATTERNS: readonly RegExp[] = HOME_PATH_RULES.map( + (rule) => new RegExp(rule.source, rule.flags), ); +// Redaction removes the whole token or block, not only the prefix that detection needs. +const SECRET_REDACTIONS: readonly RegExp[] = [ + /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, + /AKIA[0-9A-Z]{16}/g, + /gh[pousr]_[A-Za-z0-9]{36,}/g, + /xox[abprs]-[A-Za-z0-9-]{10,}/g, + /(?|()])`; +const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); export function isValidId(value: string): boolean { return ID_PATTERN.test(value); @@ -89,23 +104,37 @@ export function containsSecretPattern(value: string): boolean { return SECRET_PATTERNS.some((pattern) => pattern.test(value)); } -/** Detects absolute home-directory paths (macOS, Linux, Windows), which identify the user and machine. */ +/** + * Detects the generic home-directory shapes (`/Users/`, `X:\Users\`), which identify + * the user and machine. Linux homes are only recognizable when the adapter knows them. + */ export function containsHomePath(value: string): boolean { return HOME_PATH_PATTERNS.some((pattern) => pattern.test(value)); } /** - * Replaces home-directory prefixes with `~` and known secret shapes with `[redacted]`. - * Adapters use it on text read from analyzed projects before that text can reach a graph, - * an export or an API response. Validation still rejects anything that slips through. + * Replaces known secret shapes with `[redacted]`, then home directories with `~`: the generic + * shapes plus each of `knownHomes` (the running user's real home directory, supplied by the + * adapter). It repeats until nothing changes, so removing one piece cannot reassemble another. + * Adapters use it on text read from analyzed projects; validation still rejects what slips through. */ -export function redactSensitiveText(value: string): string { - let result = value; - for (const source of HOME_PATH_SOURCES) result = result.replace(new RegExp(source, 'gi'), '~'); - for (const pattern of SECRET_PATTERNS) { - result = result.replace(new RegExp(pattern.source, 'g'), '[redacted]'); +export function redactSensitiveText(value: string, knownHomes: readonly string[] = []): string { + const homes = knownHomes + .map((home) => home.replace(/[\\/]+$/, '')) + .filter((home) => home.length > 1) + .map((home) => new RegExp(escapeRegExp(home) + PATH_END, 'g')); + let current = value; + for (let pass = 0; pass < 8; pass++) { + let next = current; + for (const pattern of SECRET_REDACTIONS) next = next.replace(pattern, '[redacted]'); + for (const rule of HOME_PATH_RULES) { + next = next.replace(new RegExp(rule.source, `g${rule.flags}`), '~'); + } + for (const home of homes) next = next.replace(home, '~'); + if (next === current) break; + current = next; } - return result; + return current; } /** Locale-independent ordering by UTF-16 code unit. */ diff --git a/packages/domain/tests/primitives.test.ts b/packages/domain/tests/primitives.test.ts index 9d35da2..5c9932f 100644 --- a/packages/domain/tests/primitives.test.ts +++ b/packages/domain/tests/primitives.test.ts @@ -96,14 +96,11 @@ describe('containsHomePath', () => { test.each([ '/Users/alex', '/Users/alex/projects/app', - '/home/alex/app', - '/var/home/alex/app', - '/root/app', - '/root', 'C:\\Users\\alex\\app', 'c:/users/alex/app', 'name at /Users/alex/x', - 'file:///home/alex/app', + 'file:///Users/alex/app', + '(/Users/alex)', ])('detects %s', (value) => { expect(containsHomePath(value)).toBe(true); }); @@ -112,12 +109,13 @@ describe('containsHomePath', () => { 'apps/users/list', '@scope/users', '/api/users', + 'GET /users/:id', + '/home/feed', + '/root', '/usr/local/lib', '~/projects/app', - 'rootless', - '/rooted', 'ordinary-label', - ])('ignores %s', (value) => { + ])('ignores route-like and relative text %s', (value) => { expect(containsHomePath(value)).toBe(false); }); }); @@ -125,24 +123,65 @@ describe('containsHomePath', () => { describe('redactSensitiveText', () => { test.each([ ['/Users/alex/projects/app', '~/projects/app'], - ['/home/alex', '~'], - ['/var/home/alex/app', '~/app'], - ['/root/app', '~/app'], + ['(/Users/alex)', '(~)'], ['C:\\Users\\alex\\app', '~\\app'], - ['pkg at /home/alex/a and /Users/bo/b', 'pkg at ~/a and ~/b'], + ['c:/users/alex/app', '~/app'], + ['pkg at /Users/alex/a and /Users/bo/b', 'pkg at ~/a and ~/b'], ])('replaces the home directory in %s', (input, expected) => { expect(redactSensitiveText(input)).toBe(expected); - expect(containsHomePath(redactSensitiveText(input))).toBe(false); }); - test.each(Object.entries(syntheticSecrets))('replaces a %s secret', (_name, secret) => { - const redacted = redactSensitiveText(`before ${secret} after`); - expect(redacted.startsWith('before [redacted]')).toBe(true); - expect(redacted.endsWith(' after')).toBe(true); - expect(redacted).not.toContain(secret); - expect(containsSecretPattern(redacted)).toBe(false); + + test('replaces the known home directory exactly, without touching routes or longer names', () => { + const homes = ['/home/alex']; + expect(redactSensitiveText('/home/alex/app and /home/alexander', homes)).toBe( + '~/app and /home/alexander', + ); + expect(redactSensitiveText('/home/alex', homes)).toBe('~'); + expect(redactSensitiveText('GET /home/feed', homes)).toBe('GET /home/feed'); + expect(redactSensitiveText('/root/app', ['/root'])).toBe('~/app'); }); + + // An unterminated private key block runs to the end of the text; the next test covers PEM. + test.each(Object.entries(syntheticSecrets).filter(([name]) => name !== 'pem'))( + 'removes a whole %s secret', + (_name, secret) => { + expect(redactSensitiveText(`before ${secret} after`)).toBe('before [redacted] after'); + }, + ); + + test('removes a private key body and a JWT signature, not just their prefixes', () => { + const pem = '-----BEGIN ' + 'RSA PRIVATE KEY-----MIIEbody\nmore-----END RSA PRIVATE KEY-----'; + expect(redactSensitiveText(`a ${pem} b`)).toBe('a [redacted] b'); + expect(redactSensitiveText('-----BEGIN ' + 'PRIVATE KEY-----MIIEunterminated')).toBe( + '[redacted]', + ); + expect(redactSensitiveText(`${syntheticSecrets.jwt}SIGNATURE x`)).toBe('[redacted] x'); + }); + + test('never reassembles a home path or a secret from adjacent pieces', () => { + const pieces = [ + ...Object.values(syntheticSecrets), + '/Users/alex', + '/home/alex', + 'C:\\Users\\alex', + '/', + 'x', + ' ', + ]; + for (const a of pieces) { + for (const b of pieces) { + for (const c of pieces) { + const out = redactSensitiveText(a + b + c, ['/home/alex']); + expect(containsHomePath(out), out).toBe(false); + expect(containsSecretPattern(out), out).toBe(false); + expect(out.includes('/home/alex/') || out.endsWith('/home/alex'), out).toBe(false); + } + } + } + }); + test('leaves ordinary text unchanged', () => { - expect(redactSensitiveText('@scope/users-api')).toBe('@scope/users-api'); + expect(redactSensitiveText('@scope/users-api', ['/home/alex'])).toBe('@scope/users-api'); }); }); diff --git a/packages/schemas/tests/graph-json.test.ts b/packages/schemas/tests/graph-json.test.ts index 48bd2f8..8400e2f 100644 --- a/packages/schemas/tests/graph-json.test.ts +++ b/packages/schemas/tests/graph-json.test.ts @@ -113,7 +113,7 @@ test('refuses to serialize a secret-bearing label and does not echo it', () => { test('neither export nor import accepts a label with a home directory, and neither echoes it', () => { const revision = revisionOf(validEnvelope()); - const home = '/home/alex/private-app'; + const home = '/Users/alex/private-app'; const tampered = { ...revision, nodes: revision.nodes.map((n) => ({ ...n, label: home })) }; const exported = serializeGraphRevision(tampered); expect(exported.ok ? [] : exported.issues.map((i) => i.code)).toContain('home-path'); diff --git a/scripts/tests/cli-smoke.test.mjs b/scripts/tests/cli-smoke.test.mjs index 9134cd9..8687cfb 100644 --- a/scripts/tests/cli-smoke.test.mjs +++ b/scripts/tests/cli-smoke.test.mjs @@ -26,21 +26,23 @@ test('built CLI exposes help and version with correct exit codes', () => { test('--json and --graph never print the absolute root, home directories or secret shapes', async () => { const { mkdtempSync, mkdirSync, writeFileSync, realpathSync, rmSync } = await import('node:fs'); const { join } = await import('node:path'); - const { tmpdir } = await import('node:os'); + const { tmpdir, homedir } = await import('node:os'); + const home = homedir(); const root = realpathSync(mkdtempSync(join(tmpdir(), 'archwise-export-'))); const token = 'AKIA' + 'ABCDEFGHIJKLMNOP'; try { mkdirSync(join(root, 'app')); writeFileSync( join(root, 'app', 'package.json'), - JSON.stringify({ name: '/home/alex/app', dependencies: { [`x-${token}`]: '1' } }), + JSON.stringify({ name: join(home, 'app'), dependencies: { [`x-${token}`]: '1' } }), ); for (const flag of ['--json', '--graph']) { const run = spawnSync(process.execPath, [entry, '--path', root, flag], { encoding: 'utf8' }); assert.equal(run.status, 0, run.stderr); JSON.parse(run.stdout); assert.ok(!run.stdout.includes(root), `${flag} printed the absolute root`); - assert.ok(!run.stdout.includes('/home/alex'), `${flag} printed a home directory`); + // JSON escapes Windows backslashes, so compare against the escaped form. + assert.ok(!run.stdout.includes(JSON.stringify(home).slice(1, -1)), `${flag} printed home`); assert.ok(!run.stdout.includes(token), `${flag} printed a secret shape`); } } finally { From 1d6be564872e52da453d6538bdc50d12c99da8b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Oliveira?= Date: Mon, 16 Nov 2026 10:15:24 -0300 Subject: [PATCH 3/3] fix(domain): trim known-home separators in linear time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeQL js/polynomial-redos flagged the anchored trailing-separator regex. Co-Authored-By: Claude Opus 5.5 Signed-off-by: André Oliveira --- packages/domain/src/primitives.ts | 8 +++++++- packages/domain/tests/primitives.test.ts | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/domain/src/primitives.ts b/packages/domain/src/primitives.ts index 7d37683..32c31c0 100644 --- a/packages/domain/src/primitives.ts +++ b/packages/domain/src/primitives.ts @@ -46,6 +46,12 @@ const SECRET_REDACTIONS: readonly RegExp[] = [ /eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]*/g, ]; const PATH_END = String.raw`(?=$|[\\/\s"'<>|()])`; +/** Linear-time trim; an anchored `[\\/]+$` regex is polynomial on long runs of separators. */ +function trimTrailingSeparators(path: string): string { + let end = path.length; + while (end > 0 && (path[end - 1] === '/' || path[end - 1] === '\\')) end--; + return path.slice(0, end); +} const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); export function isValidId(value: string): boolean { @@ -120,7 +126,7 @@ export function containsHomePath(value: string): boolean { */ export function redactSensitiveText(value: string, knownHomes: readonly string[] = []): string { const homes = knownHomes - .map((home) => home.replace(/[\\/]+$/, '')) + .map(trimTrailingSeparators) .filter((home) => home.length > 1) .map((home) => new RegExp(escapeRegExp(home) + PATH_END, 'g')); let current = value; diff --git a/packages/domain/tests/primitives.test.ts b/packages/domain/tests/primitives.test.ts index 5c9932f..cd9b682 100644 --- a/packages/domain/tests/primitives.test.ts +++ b/packages/domain/tests/primitives.test.ts @@ -180,6 +180,12 @@ describe('redactSensitiveText', () => { } }); + test('accepts known homes with trailing separators and ignores the filesystem root', () => { + expect(redactSensitiveText('/home/alex/app', ['/home/alex///'])).toBe('~/app'); + expect(redactSensitiveText('C:\\home\\x', ['C:\\home\\'])).toBe('~\\x'); + expect(redactSensitiveText('/etc/app', ['/', '//'])).toBe('/etc/app'); + }); + test('leaves ordinary text unchanged', () => { expect(redactSensitiveText('@scope/users-api', ['/home/alex'])).toBe('@scope/users-api'); });