Computer use for Claude Code on macOS (Apple silicon) and Linux (X11) through OpenAI's computer-use runtime: a stdio MCP server running the pinned runtime that…

Lets Claude Code read and operate macOS and Linux apps (accessibility tree, screenshots, clicks, typing, menus). cua serve (the plugin runs it through cua-shim.mjs) is a stdio MCP server: supported sessions now use cua's own JavaScript REPL host and vendor-compatible cua API; macOS computer sessions keep OpenAI's host (see Use). Both still need the pinned runtime that cua install verifies and places under CUA_HOME, for the native engine and the retained vendor host. The sandbox that confines the model's JavaScript is cua's own on both platforms, and no Codex CLI is installed or launched (#115; see Configuration). Vendor files stay unmodified, and nothing in ChatGPT.app or ~/.codex is read or modified. With the browser surface turned on it also drives your existing Chrome profiles, signed-in sessions included, through cua's own browser service, Chrome extension and native host, with no ChatGPT account or Codex login (see Chrome), and with cua agent it serves a client on another machine (see Remote control). The design and its status are in docs/doperpowers/specs/2026-10-02-standalone-cua-design.md, for the sandbox in docs/doperpowers/specs/2026-10-17-own-sandbox-design.md, for remote control in docs/doperpowers/specs/2026-10-06-remote-and-linux-design.md, for the Chrome extension in docs/doperpowers/specs/2026-10-07-own-chrome-extension-design.md, for the browser service in docs/doperpowers/specs/2026-10-13-own-browser-service-design.md, and for the REPL host in docs/doperpowers/specs/2026-10-14-own-repl-host-design.md.
unsupported_platform), and Node matching ^22.14 || >=23.7 as node on PATH for cua itself (the plugin starts the server with --disable-sigusr1, which those versions introduced). cua's own REPL host needs Node 24 or later: cua install places a pinned official Node 24 for it under $CUA_HOME/node, and CUA_NODE, the node running cua or PATH can supply one too (see Use); sessions on the vendor host keep the pinned vendor Node. The one npm dependency, ws, is needed only for remote control through a relay (npm ci); everything else runs without node_modules.CUA_HOME (default ~/Library/Application Support/cua) by cua install: it downloads OpenAI's pinned ChatGPT archive from its official URL (about 690 MB), or takes a local copy with --archive <zip>, and refuses anything whose length, SHA-256, layout or OpenAI code signatures (team 2DC432GLL2) differ from runtime/releases/*.json. Vendor files are never modified or re-signed.Codex Computer Use.app, started by the runtime through LaunchServices). macOS asks on first use; cua doctor cannot see these grants and reports them as blocked until a live run shows them. Where ChatGPT's Computer Use already runs, its compatible helper serves this runtime too and is reused as it is, never stopped or replaced.~/.codex. macOS computer sessions, the one place the vendor's node_repl still runs, give it its own CODEX_HOME under CUA_HOME (state/codex, its config and app approvals) until #117; cua's own host and Linux use none.extension/ today; it will be listed on the Chrome Web Store) and cua chrome register run once (see Chrome). No account or login is needed. cua never installs the extension for you.A clean Mac without ChatGPT installed has been shown, in a macOS 27 VM (docs/evidence/clean-machine-acceptance.md). There, the pinned helper started from cua's release tree, macOS asked for Accessibility and Screen Recording on the helper's behalf once, the native slice passed (accept-native items 1 and 3–8, with item 2 shown by the download installs and item 9 BLOCKED by design), and the Chrome acceptance passed C1–C7. The helper first shows its own "Enable ChatGPT Computer Use" window, which lists the permissions.
From a checkout (or after npm link, the same commands as cua):
npm test # Node only; no runtime, GUI, network or credentials
node bin/cua.mjs install # or: install --archive <ChatGPT-darwin-arm64-26.928.40906.zip>
node bin/cua.mjs doctor # --json for the structured checks; exit 1 when one fails
cua install is idempotent for a verified release and never repairs one in place; cua runtime use <release> switches between verified installed releases. A release that no longer verifies is reported with its offline recovery: stop the servers using it, remove its directory, install again. On Linux it also fetches cua's sandbox helper (see Linux).
Removing the Codex CLI's leftovers. This cua no longer uses what the Codex CLI left in its home (#115), but an older cua sharing the same CUA_HOME may: an earlier plugin version, a long-running cua serve or agent from an older checkout, whose vendor host still launches the release's CodexCLI.app. So a plain cua install removes nothing and only says what is there. Update the plugin, and every other cua that uses this home, first; then run:
node bin/cua.mjs install --prune-leftovers
It removes, by name, and prints each name, never its content: in CUA_HOME/state/codex (cua's own CODEX_HOME; the environment's CODEX_HOME and ~/.codex are never looked at), auth.json, installation_id, the *.sqlite files with their -wal and -shm, models_cache.json, cache/, plugins/, skills/, log/, tmp/arg0 and browser/sessions (what node_repl keeps there, config.toml, computer-use/sessions and node_repl/active_execs, stays); and in each installed release whose pin no longer lists it, the unused CodexCLI.app (about 229 MB; on Linux the codex file). A release's Codex CLI is removed only while no cua serve or profile listing of this home runs: the prune checks right before removing it, renames it aside in one step, checks again, and puts it back if a session appeared; otherwise it says so and leaves it for a later prune. A session that starts in the instant after that second check is not seen; only an older cua would launch the CLI then. On macOS that older cua's launch fails; on Linux an older cua on the vendor host may run its kernel unconfined after a failed launch (#135). So updating every cua that shares the home before pruning is a precondition, not a nicety, and it holds for the whole time after the prune, not only that instant. If run/, state/, state/compat/ or kernel/ in the home is a symbolic link, the prune refuses and removes nothing, and a directory it cannot read is reported, never taken as clean. A Codex CLI the prune renamed aside but could not delete (.CodexCLI.app.pruning-<hex> beside the release's files) stays a leftover: doctor names it and the next prune removes it. Nothing is followed through a symbolic link: a leftover that is itself a link is unlinked and its target left, and a linked directory on the way to one (state/codex, its tmp/ or browser/, runtimes/, a release directory) is skipped and named as not inspected, by doctor, the prune and a plain install alike, so it never reads as clean. Until then cua doctor's runtime.leftovers row names what is left and the command (warn, never a failure).
cua install does not take the pinned archive's Chrome plugin (OpenAI's native host for the ChatGPT extension): the route that used it was removed (#79), and cua's own host comes from the checkout (cua chrome register; see Chrome). A release installed earlier keeps the chrome-plugin directory it was given; nothing reads or launches it.
claude plugin marketplace add SSFSKIM/cua
claude plugin install cua@cua
This repository is its own marketplace, so the installed plugin follows main (claude plugin marketplace update cua picks up a new version). The plugin runs node --disable-sigusr1 cua-shim.mjs, which is cua serve, as the MCP server plugin:cua:cua_repl with CUA_SHIM_SURFACES=computer,browser; its tools are mcp__plugin_cua_cua_repl__*. The installed copy needs no npm ci: ws, the one dependency, is loaded only on the relay path of cua agent, never by serve (the suite checks that; a copy without node_modules reaches the runtime check). The plugin cannot install the runtime: run cua install from a checkout once (Install, above), into the same CUA_HOME. If you registered cua serve yourself before (Plain MCP server, below), remove that registration under the name you gave it (claude mcp remove cua -s user for the example there, or cua_repl), or two servers drive the same Mac.
The same server drives other machines too: devices_list and devices_use switch its tools to a device you registered with cua devices (Remote control, 4), with no registration in Claude Code per device. The plugin also carries the cua-remote skill, the procedure for setting up or driving another computer through cua (Remote control), and, where function hooks are enabled (CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1), the /secret KEY command: a value typed into a masked field and stored for the session's project (/secret -g KEY: for every project; mode 600, see Secrets), which the model sees only by its key, and a secrets guard that redacts secrets in what the model reads (hooks/mods/README.md). Allow the tools in your settings so each call does not prompt: "mcp__plugin_cua_cua_repl__*" under permissions.allow. App approvals are a separate dialog; see the next section. This repository is the plugin's source of truth.
Secrets need nothing extra: every copy of cua, the plugin's included, reads the same store in your home directory (see Secrets).
cua serve speaks MCP over stdin/stdout. Register it yourself under a name you do not already use; nothing in this repository registers or replaces a server for you. For Claude Code, for example:
claude mcp list # check what is already registered
claude mcp add --scope user cua -- node /absolute/path/to/cua/bin/cua.mjs serve
Settings (below) go in the server's environment, e.g. claude mcp add ... -e CUA_SHIM_SECRETS=off -- .... For a client on another machine, see Remote control.
Apart from Claude Code's tool permission, OpenAI's stack asks before an app is first used, Allow Computer Use to use "X"?, as an MCP elicitation that Claude Code shows as a dialog; on Linux cua's trusted wrapper asks the same per app (see Linux). An app declined is remembered for the connection; whether one accepted is depends on CUA_SHIM_PERSIST:
session (the default): the connection remembers it until it closes, through the runtime's idle stops, so every new connection asks once more per app. (The vendor's host, which macOS computer sessions run, also writes $CUA_HOME/state/codex/computer-use/sessions/<session id>.toml, removed when its connection closes.)none: an accepted app is asked about again on every use.always is refused at start (invalid_setting): cua remembers an approval for its connection only. To stop being asked, let the plugin's Elicitation hook answer (below); a stricter hook is where a veto lives.The plugin answers these dialogs for you, by design. Its Elicitation hook (hooks/hooks.json, matcher cua_repl|plugin:cua:cua_repl) runs hooks/cua-approve.sh, which accepts every elicitation cua_repl sends (cua's browser service sends none of its own; see Chrome, Using it); Claude Code runs the hook before it would show the dialog and takes its answer as the user's. This follows the owner's trust model (the agent is trusted and cua adds no policy of its own; issues #20 and #36), and it is what lets an unattended or headless session (claude -p, a remote client) use an app at all. Other servers' elicitations are untouched. The script uses jq when present and prints the same answer without it, so a missing jq never leaves a dialog nobody answers.
Be clear about what it removes: the model can bind any app OpenAI's policy allows, and binding hands it that app's whole front window (see Use). To narrow it, edit hooks/cua-approve.sh in your copy to test .message and print nothing for the rest (empty output leaves the dialog to you), for example jq -c 'if (.message // "" | startswith("Allow Computer Use to use ")) then {hookSpecificOutput:{hookEventName:"Elicitation",action:"accept",content:{}}} else empty end'; to drop it, remove the Elicitation entry from the plugin's hooks/hooks.json (an edit to the installed copy lasts until the next plugin update). Without the plugin, register the same script yourself under hooks.Elicitation in ~/.claude/settings.json with that matcher and "command": "bash /path/to/cua/hooks/cua-approve.sh".
Ask for the task in plain words: "open Notes and read my latest note", "in Preview, rotate this image and save". The first call returns the cua API document to the model, which then writes small JavaScript cells against that API. On cua's own host the document is a port of OpenAI's, with the recorded exclusions (Licences and sources). That first call is also when cua serve launches the runtime (a few seconds; see Process footprint below), so it takes longer than the ones after it. The server adds rules covering what that document leaves out: how to run a task, in the host notes it appends to the server instructions (see Operating guidance for agents), and the native quirks (index-first addressing, dropping an app handle after quitting it, typeText and emoji, and so on), ahead of the REPL's text in the js description.
The model sees four tools: js and js_reset (the vendor-compatible REPL tools), end_task, and secrets_list (the keys of your stored secrets, never values; see Secrets). Calls on one connection form a task until the model calls end_task, which waits for running JavaScript and then has the runtime complete the task. The plugin no longer installs Stop/SubagentStop hooks for this; if completion cannot be confirmed, the connection fails closed and stops its runtime, and native cleanup of what was already submitted is unconfirmed. With either host a forwarded MCP cancellation does not stop a running cell and js_reset waits behind it, so a cell's timeout_ms is what bounds runaway work; cancelling never means control has been handed back.
REPL host. cua now supplies its own execution host (src/repl-host/) and model-facing API (src/cua-api/, with the documents in docs/cua-api/). The choice is fixed when a connection opens, including its later idle relaunches. With CUA_REPL_HOST unset or empty, the defaults are:
| session | REPL host | why |
|---|---|---|
| Linux | cua, with Node 24+ | The owned host serves Linux computer and browser sessions (linux); it is the only host there: the vendor host is retired on Linux (#115), so CUA_REPL_HOST=vendor is refused (repl_host_refused) and a missing Node 24 refuses (repl_host_node) |
| macOS, browser only (MAWS and profile listing included) | cua, with Node 24+ | No native-helper peer is needed (browser_only) |
| macOS, computer enabled | vendor | The native helper accepts only the vendor host's node_repl as a peer until #117 (macos_native_peer_requires_vendor); MAWS does not override this |
Either host runs cua's own browser service with the browser surface (Chrome).
The own host takes the first Node 24 or later it finds through CUA_NODE (an absolute path), the Node cua install placed under $CUA_HOME/node, the node running cua, then the first node on PATH, never the vendor's pinned Node. cua itself keeps running on your Node; only the own host's processes use the installed one. After the runtime, cua install downloads the official nodejs.org tarball of the pinned Node 24 for this platform (or takes a local copy with --node-archive <tarball>), refuses it unless its length and SHA-256 match runtime/releases/node/*.json (on macOS also unless bin/node carries the OpenJS Foundation's Developer ID signature, team HX7739G8FX) and its --version is the pinned one, and keeps only bin/node and its licence in $CUA_HOME/node/<version>, recording the binary's SHA-256: a bin/node that no longer matches its record is never run, neither by a later install nor as a candidate. Like the runtime, a verified Node makes it a no-op, and a damaged one is reported, never repaired in place. If that step fails, the command fails after the runtime is in place and says so; --no-node skips it, as for an offline install without the tarball. If no candidate qualifies, a macOS session that would default to cua keeps the vendor host with reason own_host_node_unavailable, and a Linux session is refused: run cua install, install Node 24 or later yourself, or set CUA_NODE to one. This is selection before launch, not a retry on another host after a failed launch. On macOS CUA_REPL_HOST=vendor is the rollback. An explicit CUA_REPL_HOST=cua instead refuses when no suitable Node is found (repl_host_node) or when the computer surface is enabled on macOS (repl_host_refused); it is never silently downgraded. This replaces the host and facade on supported sessions, not the installed vendor runtime.
cua doctor's repl.host row names the host and reason for the configured session and the separate browser-only profile listing. It reads pass for usable selections, fail for a setting or explicit selection that refuses, and warn when either would use cua's host but cannot find Node 24, naming the candidates tried and the remedies above. A warn does not make ok false or the exit nonzero: on macOS the session keeps working on the vendor host.
Process footprint. Claude Code starts the plugin's server in every session, used or not, so cua serve holds no runtime until a call needs one. It answers the MCP handshake and the tool list itself and launches the selected host on the first js or js_reset: cua's supervisor on user Node, with its kernel and trusted worker, or the vendor's node, node_repl and their children. Both hosts confine their children with cua's own sandbox (Configuration); no codex process runs. A runtime that goes 15 minutes (CUA_RUNTIME_IDLE_MS, in milliseconds; 0 keeps it for the session's life) without a js, js_reset, end_task or profiles_list live check is stopped as a task's end and a session's close stop it: an open task is completed first (its app and Chrome attachments released, a MAWS browser's lease included), the processes are torn down and the connection's working directory under run/ removed, while the session's MCP connection, its MAWS socket and its app approvals (which the connection remembers, not the runtime) stay. A running call never counts as idle. The next js or js_reset launches a fresh runtime, and its result opens with a line telling the model that the runtime restarted after idling and its REPL state (variables, app handles, tabs) is gone, ahead of the API document a fresh runtime returns; a call that arrives while the runtime is being stopped waits for the fresh one. secrets_list, devices_list, devices_use, an end_task with no task open and the registry part of profiles_list never launch it (a bound profile's live check makes its own short launch, see Profiles), and a session that never used cua exits with nothing to tear down. The handshake answers come from the selected host itself: the first connection of an installed release (per host and host/API version, enabled surfaces and client protocol version) launches at its handshake, as every connection used to, and its answers are recorded under $CUA_HOME/state/handshake/<release>/ for the connections after it. A vendor answer cannot stand in for cua's, or an older host/API version for a new one.
cua serve (the plugin's server) adds two more: devices_list and devices_use, which switch every other tool to a remote machine and back (Remote control, 4). The agent's HTTP sessions never list them.
Be aware that binding an app hands the model that app's whole front window as text, chat lists and inboxes included. For a messaging app, open the room you mean before asking.
cua relays js and js_reset results with two rewrites and no other filtering: what a cell returns, text, screenshots and page content included, reaches the client's transcript as the runtime produced it.
image/png).token, key, secret or apikey (token, access_token, refresh_token, api_key, apiKey, key, client_secret, X-Refresh-Token; not monkey, keyword or tokens_left; a percent-encoded name is decoded first) becomes <redacted>, also inside a redirect parameter, raw or URL-encoded, and in a bare ?… or #… reference. A value runs to the next delimiter of its URL or to a closing bracket it did not open (the ) of a Markdown link), less a trailing }, , or .. The Playwright MCP extension's connection URL (chrome-extension://<id>/connect.html?mcpRelayUrl=…&token=…) has every parameter value redacted, and a loopback relay URL (ws://127.0.0.1:<port>/extension/…) its path. The rest of the result is unchanged.The redaction exists because a first real run printed an extension connection URL with its token in a tab inventory (docs/evidence/2026-10-05-homework-1b-dogfooding.md). It is a pattern list, not a data-loss filter: a credential in any other shape (a cookie value, a header, a token in page text, a password typed into a field and read back), a URL in an image, and JSON-RPC error replies pass unchanged, and nothing the agent sends is rewritten. In the other direction, URL-like text that is not a URL (x?key=1 in code or prose; a & or ? after a space starts no parameter) is rewritten too. Keep secrets out of results with {{secret:<KEY>}} (see Secrets) and by asking for focused reads.
Secrets are plain files, one value per file, in the directory the plugin's /secret mod writes (hooks/mods/secrets.tsx): ~/.config/claude-secrets/<KEY> (file mode 0600, directory 0700; $HOME decides where ~ is). A KEY is letters, digits and _, not starting with a digit. One store serves cua on macOS and Linux, locally and through the remote agent, and any other tool that reads that directory.
The store has two tiers. That directory is the global one, for every project. Each project has its own beside it, ~/.config/claude-secrets/projects/<slug>/<KEY>, the slug being the project's path in the form Claude Code names its ~/.claude/projects/ folders (every character other than a letter or digit becomes -: /Users/me/repo is -Users-me-repo). The project is the main checkout of the git repository around the working directory, so every worktree of a repository shares its secrets, and outside a repository the directory itself. A key stored in both is read from the project's tier: the project's value shadows the global one. Device credentials (CUA_DEVICE_…, Remote control) live in the global tier only, and so does everything a device's remote agent serves: it has no project. Existing files stay where they are; nothing
hooks/mods/register.tsx 17 lines1import type { On } from 'claude-code'
2
3import { registerSecrets as registerGuard } from './guard/secrets'
4import { registerSecrets } from './secrets'
5
6/**
7 * The plugin's one hooks module. The engine loads it only where function
8 * hooks are enabled (CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1); the shell hook
9 * beside this folder (cua-approve.sh) runs everywhere. `/secret` is cua's
10 * own; the secrets guard is devcloud's, vendored (./guard), and stands down
11 * while devcloud's plugin is loaded (./one-guard.tsx).
12 */
13export function register(on: On) {
14 registerSecrets(on)
15 registerGuard(on)
16}
17hooks/mods/guard/secrets.tsx 420 lines1// Vendored from SSFSKIM/doperpowers devcloud/hooks/mods/secrets.tsx at 823f772f634003278886446940fe9fb6b679e254
2// (devcloud 0.5.0); the adaptations and the resync are in hooks/mods/guard/VENDORED.md.
3
4import type { EngineInterface, Hook, On } from 'claude-code'
5
6import { Handles } from './secrets-handles'
7import { PATTERN_READ, readNotice } from './secrets-reads'
8import type { Read } from './secrets-reads'
9import type { Known } from './secrets-handles'
10import {
11 CREDENTIAL_FILES,
12 GCLOUD_DIR,
13 GCLOUD_SKIP,
14 KEY,
15 PROJECTS,
16 STORE_DIR,
17 credentialFields,
18 credentialLabels,
19 projectSlug,
20 rootFromGit,
21 storeValue,
22} from './secrets-sources'
23import type { Format } from './secrets-sources'
24import { devcloudGuards } from '../one-guard' // cua: one guard per session
25
26/**
27 * The secrets guard. Values are replaced by handles wherever its hooks reach
28 * before text leaves the process: a tool's result as the model reads it and
29 * as the transcript keeps it (`toolUseResult`), every row appended to the
30 * conversation, an oversized output's persisted file, the system prompt's
31 * sections, the first message's context blocks, each attachment as a request
32 * carries it, and a compaction's instructions and summary. No call is refused for touching the store: a command
33 * that prints a value is caught at its output. Handles in the input of a
34 * Write, Edit, MultiEdit, NotebookEdit or Bash call are restored to their
35 * bytes before it runs, so a file edited through a handle keeps its secret.
36 *
37 * The values known: those stored through `/secret` (`cua`'s store, read here,
38 * Interfaces I1), those in well-known credential files, re-read when they
39 * change, and token-shaped strings anywhere (secrets-detect).
40 */
41
42// The tools whose input a handle is restored in before they run.
43const RESTORED = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit', 'Bash'])
44// `tool.call`'s own keys beside the tool's arguments: never rewritten.
45const RESERVED = new Set(['tool', 'tool_use_id', 'agentId', 'requestMeta', 'consent'])
46// What one `$.fs.read` or a process's output carries at most.
47const READ_MAX = 4 * 1024 * 1024
48// How often the rows' hook may re-read the sources; a tool call always does.
49const REFRESH_EVERY_MS = 1000
50
51const PROMPT_LINE =
52 'Secrets in what you read are replaced by handles: [secret:KEY] stands for a stored or credential-file value ' +
53 '(~b64, ~hex, ~url and the like name an encoding of it), [redacted:<kind>#<id>] for a token-shaped string, ' +
54 '[superseded:…] for a value that has since changed. Write a handle where its value belongs. In Write, Edit, ' +
55 'MultiEdit and NotebookEdit it is restored to the exact bytes before the call runs, so a file edited through a ' +
56 'handle keeps its secret. In Bash only a plain token in a plain position is restored ' +
57 '(`Authorization: Bearer [secret:KEY]` inside double quotes, `--token=[secret:KEY]`); any other handle stays as ' +
58 "written, and the tool's result names a read that works in its place. A [superseded:…] handle, or another " +
59 "session's [redacted:…] one, is never restored, and the result says so."
60
61// Four base32 characters, drawn when the module loads: this process's pattern handles.
62function namespace(): string {
63 const alphabet = 'abcdefghijklmnopqrstuvwxyz234567'
64 return Array.from(crypto.getRandomValues(new Uint8Array(4)), (b) => alphabet[b % 32]).join('')
65}
66
67const handles = new Handles(namespace())
68
69// The session's project root, once resolved; $HOME; and each source file as
70// last read, so a file is read again only when it changed.
71let project: string | undefined
72let home: string | undefined
73const sources = new Map<string, { mtimeMs: number; size: number; known: Known[] }>()
74let refreshedAt = 0
75// Where each store label's file is, from $HOME: the read a command can do in
76// place of a handle the guard cannot restore into it.
77// Each known label's source, as setKnown named it (`#2` and on included): the
78// read a command can do in place of a handle the guard leaves in it.
79const reads = new Map<string, Read>()
80
81async function projectOf($: EngineInterface, cwd?: string): Promise<string> {
82 if (project !== undefined) return project
83 const dir = cwd ?? (await $.session.cwd())
84 let root = dir
85 try {
86 const git = await $.process.run(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir', '--show-toplevel'], { cwd: dir, timeoutMs: 5000 })
87 const [commonDir, topLevel] = git.stdout.trim().split('\n')
88 // A git older than 2.31 echoes `--path-format=absolute` back as a line of
89 // its own; only two absolute paths are an answer.
90 if (git.exitCode === 0 && commonDir?.startsWith('/') && topLevel?.startsWith('/')) root = rootFromGit(commonDir, topLevel)
91 } catch {}
92 project = root
93 return root
94}
95
96// A source file's known values: read again only when its time or size moved.
97async function readSource($: EngineInterface, path: string, stat: { mtimeMs: number; size: number }, parse: (text: string) => Known[]): Promise<Known[]> {
98 const cached = sources.get(path)
99 if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.known
100 let known: Known[] = []
101 try {
102 known = parse(await $.fs.read(path))
103 } catch {}
104 sources.set(path, { mtimeMs: stat.mtimeMs, size: stat.size, known })
105 return known
106}
107
108// One tier of the store: each key's value, read from its own file.
109async function readTier($: EngineInterface, dir: string, isGlobal: boolean): Promise<Known[]> {
110 let entries: Awaited<ReturnType<EngineInterface['fs']['list']>>
111 try {
112 entries = await $.fs.list(dir)
113 } catch {
114 return []
115 }
116 const out: Known[] = []
117 for (const entry of entries) {
118 if (entry.kind !== 'file' || !KEY.test(entry.name) || (isGlobal && PROJECTS.test(entry.name))) continue
119 out.push(...(await readSource($, `${dir}/${entry.name}`, entry, (text) => [{ label: entry.name, value: storeValue(text) }])))
120 }
121 return out
122}
123
124// The project tiers the store holds: each folder under `projects/`.
125async function projectTiers($: EngineInterface, store: string): Promise<string[]> {
126 try {
127 return (await $.fs.list(`${store}/projects`)).filter((e) => e.kind === 'dir').map((e) => e.name)
128 } catch {
129 return []
130 }
131}
132
133async function statFile($: EngineInterface, path: string) {
134 try {
135 const stat = await $.fs.stat(path)
136 return stat.kind === 'file' ? stat : undefined
137 } catch {
138 return undefined
139 }
140}
141
142// gcloud's JSON files, below its folder: where its key files live.
143async function gcloudFiles($: EngineInterface, dir: string, depth: number): Promise<string[]> {
144 let entries: Awaited<ReturnType<EngineInterface['fs']['list']>>
145 try {
146 entries = await $.fs.list(`${home}/${dir}`)
147 } catch {
148 return []
149 }
150 const out: string[] = []
151 for (const entry of entries) {
152 if (entry.kind === 'file' && entry.name.endsWith('.json')) out.push(`${dir}/${entry.name}`)
153 else if (entry.kind === 'dir' && depth > 0 && !GCLOUD_SKIP.has(entry.name)) out.push(...(await gcloudFiles($, `${dir}/${entry.name}`, depth - 1)))
154 }
155 return out
156}
157
158/**
159 * Reads what is known now: the store's project tier, then its global one (a
160 * global key the project's shadows is `KEY@global`), then every other
161 * project's tier (`KEY@<slug>`), then the credential files. A source that cannot be read adds nothing and stops nothing.
162 */
163async function refresh($: EngineInterface, isForced: boolean) {
164 const now = Date.now()
165 if (!isForced && now - refreshedAt < REFRESH_EVERY_MS) return
166 refreshedAt = now
167 home ??= await $.env.get('HOME')
168 if (!home) return
169 const store = `${home}/${STORE_DIR}`
170 const own = projectSlug(await projectOf($))
171 const projectKnown = await readTier($, `${store}/projects/${own}`, false)
172 const shadowed = new Set(projectKnown.map((k) => k.label))
173 const known: (Known & { read?: Read })[] = projectKnown.map((k) => ({ ...k, read: { kind: 'store', path: `${STORE_DIR}/projects/${own}/${k.label}` } }))
174 for (const { label, value } of await readTier($, store, true)) {
175 known.push({ label: shadowed.has(label) ? `${label}@global` : label, value, read: { kind: 'store', path: `${STORE_DIR}/${label}` } })
176 }
177 // Every other project's tier: a command can print any of them.
178 for (const slug of await projectTiers($, store)) {
179 if (slug === own) continue
180 for (const { label, value } of await readTier($, `${store}/projects/${slug}`, false)) {
181 known.push({ label: `${label}@${slug}`, value, read: { kind: 'store', path: `${STORE_DIR}/projects/${slug}/${label}` } })
182 }
183 }
184
185 const files: { path: string; format: Format }[] = [...CREDENTIAL_FILES, ...(await gcloudFiles($, GCLOUD_DIR, 3)).map((path) => ({ path, format: 'gcloud' as const }))]
186 const present: { path: string; format: Format; stat: { mtimeMs: number; size: number } }[] = []
187 for (const file of files) {
188 const stat = await statFile($, `${home}/${file.path}`)
189 if (stat) present.push({ ...file, stat })
190 }
191 const labels = credentialLabels(present.map((f) => f.path))
192 for (const { path, format, stat } of present) {
193 const name = labels.get(path)!
194 known.push(...(await readSource($, `${home}/${path}`, stat, (text) => credentialFields(format, text, path).map((f) => ({ label: `${name}:${f.field}`, value: f.value, read: f.read })))))
195 }
196 const names = handles.setKnown(known)
197 reads.clear()
198 names.forEach((name, i) => {
199 const read = known[i]!.read
200 if (read && !reads.has(name)) reads.set(name, read)
201 })
202}
203
204// A file of more than one read's worth, in pieces through `dd`, base64 so no
205// piece splits a character.
206async function readLarge($: EngineInterface, path: string, size: number): Promise<string> {
207 const MIB = 1024 * 1024
208 const pieces: Uint8Array[] = []
209 for (let mib = 0; mib * MIB < size; mib += 2) {
210 const r = await $.process.run(['/bin/sh', '-c', 'dd if="$1" bs=1048576 skip="$2" count=2 2>/dev/null | base64', 'sh', path, String(mib)])
211 if (r.exitCode !== 0 || r.isStdoutTruncated) throw new Error('secrets: a persisted output could not be read')
212 pieces.push(Uint8Array.from(atob(r.stdout.replace(/\s+/g, '')), (c) => c.charCodeAt(0)))
213 }
214 const bytes = new Uint8Array(pieces.reduce((n, p) => n + p.length, 0))
215 let at = 0
216 for (const p of pieces) {
217 bytes.set(p, at)
218 at += p.length
219 }
220 return new TextDecoder().decode(bytes)
221}
222
223/**
224 * An oversized output the engine wrote to the session's `tool-results/`
225 * before any hook saw the result: rewritten in place, scrubbed, before the
226 * call returns, so the session store's first copy of it holds handles.
227 */
228async function scrubPersisted($: EngineInterface, path: string) {
229 const stat = await $.fs.stat(path)
230 const text = stat.size <= READ_MAX ? await $.fs.read(path) : await readLarge($, path, stat.size)
231 const scrubbed = handles.scrub(text)
232 if (scrubbed === text) return
233 // Handles can grow a file: the writer goes by the scrubbed size. Past what
234 // `$.fs.write` takes, through a child's input into a file beside it (`.tmp`,
235 // which the session store skips) renamed over it.
236 if (new TextEncoder().encode(scrubbed).length <= READ_MAX) {
237 await $.fs.write(path, scrubbed)
238 return
239 }
240 const r = await $.process.run(['/bin/sh', '-c', 'umask 077 && cat > "$1.scrub.tmp" && mv -f "$1.scrub.tmp" "$1"', 'sh', path], { stdin: scrubbed, timeoutMs: 60_000 })
241 if (r.exitCode !== 0) throw new Error('secrets: a persisted output could not be rewritten')
242}
243
244const persistedPath = (result: unknown): string | undefined => {
245 if (result === null || typeof result !== 'object') return undefined
246 const record = result as Record<string, unknown>
247 return typeof record.persistedOutputPath === 'string' && record.persistedOutputPath && record.isImage !== true ? record.persistedOutputPath : undefined
248}
249
250// Withheld rather than passed on unread: the call ran, its result is not shown.
251const WITHHELD = 'secrets: the guard could not scrub this result, so it is withheld.'
252
253const notRestored = (unrestored: readonly string[]) =>
254 `secrets: not restored, so written as is: ${unrestored.join(', ')} ` +
255 "(a superseded value, a key no longer stored, or another session's redaction)."
256
257// A read that works in the command where a handle could not be restored.
258function readInstead(handle: string): string {
259 const { kind, label = '', enc } = handles.describe(handle)
260 if (kind === 'redacted') return PATTERN_READ
261 return readNotice(reads.get(label), enc, handles.valueOf(handle)?.endsWith('\n') ?? false)
262}
263
264// One line per handle left in a command: why, and the read to use instead.
265const notQuoted = (unquotable: readonly string[]) =>
266 unquotable.map(
267 (h) => `secrets: ${h} was not restored into this command (the guard restores into a shell command only a plain value, at a plain position, in a plain command); ${readInstead(h)}.`,
268 )
269
270/**
271 * Interfaces I9: devcloud's guard is in the session's chain exactly while this
272 * module is loaded, and the guard marker says so. It is this module's answer
273 * to a read, through a `state.get` hook, and never a value the host stores:
274 * any plugin's `$.state.get({ plugin: 'devcloud', key: 'secrets-guard' })`
275 * resolves to the marker at version 0 (where the host holds nothing) while the
276 * module is loaded, and falls through to the host once it is gone (devcloud
277 * disabled and the plugins reloaded), which then answers `undefined`. A marker
278 * the host kept would outlive the module, and `cua`'s scrubbing, which stands
279 * down on it, would leave the session with no guard (board #101). The engine runs a
280 * `$` call through every hook on its event but the one that made the call,
281 * the calling plugin's other hooks included: the read reaches this hook
282 * whichever plugin sits outside the other, and a module that answered the
283 * marker would read its own answer, so a guard that reads it to stand down
284 * must never answer it. A child process (a
285 * `claude` a tool call starts) has its own session and decides for itself.
286 * Its type is the plugin's contract (types/devcloud.d.ts). Not a `globalThis`
287 * symbol: the engine evaluates each plugin's module in a realm of its own
288 * (probed 2026-10-17, 2.1.302).
289 */
290// cua adaptation: devcloud's answer to its marker (MARKER_READ, and the
291// `state.get` hook registerSecrets takes it with) is removed. cua's copy only
292// reads the marker (../one-guard.tsx); answering it, cua would stand down to
293// itself.
294
295// Taken with both matchers: an event is registered without one once per module.
296const secretsStart: Hook<'session.start'> = async ($, e, next) => {
297 if (await devcloudGuards($)) return next(e) // cua: one guard per session
298 project = undefined
299 await projectOf($, e.cwd)
300 await refresh($, true)
301 return next(e)
302}
303
304export function registerSecrets(on: On) {
305 on('session.start', { isInteractive: true }, secretsStart)
306 on('session.start', { isInteractive: false }, secretsStart)
307
308 on('tool.call', async ($, e, next) => {
309 if (await devcloudGuards($)) return next(e) // cua: one guard per session
310 let input = e
311 const notes: string[] = []
312 if (RESTORED.has(e.tool)) {
313 await refresh($, true)
314 if (e.tool === 'Bash' && typeof e.command === 'string') {
315 // The command alone, which a shell reads, by the safe rule: a value
316 // goes in only where its bytes are proved to arrive as data.
317 const shell = handles.restoreShell(e.command)
318 if (shell.text !== e.command) input = { ...e, command: shell.text }
319 if (shell.unrestored.length) notes.push(notRestored(shell.unrestored))
320 notes.push(...notQuoted(shell.unquotable))
321 } else {
322 const args = Object.fromEntries(Object.entries(e).filter(([k]) => !RESERVED.has(k)))
323 const restored = handles.restoreRecord(args)
324 if (restored.value !== args) input = { ...e, ...restored.value }
325 if (restored.unrestored.length) notes.push(notRestored(restored.unrestored))
326 }
327 }
328 const ran = await next(input)
329 try {
330 await refresh($, true)
331 if (ran.deny !== undefined) {
332 const deny = handles.scrub(ran.deny)
333 return deny === ran.deny ? ran : { deny }
334 }
335 if (ran.isError) {
336 const text = handles.scrub(ran.text ?? '')
337 return text === ran.text && notes.length === 0 ? ran : { deny: [text, ...notes].join('\n') }
338 }
339 const path = persistedPath(ran.result)
340 if (path !== undefined) await scrubPersisted($, path)
341 const result = handles.scrubRecord(ran.result)
342 const context = notes.length ? [...(ran.context ?? []), ...notes] : ran.context
343 if (result === ran.result && context === ran.context) return ran
344 return { result, context }
345 } catch {
346 return { deny: WITHHELD }
347 }
348 }).catch(async ($, e, next) => ((await devcloudGuards($)) ? next(e) : next.called ? { deny: WITHHELD } : { deny: 'secrets: the guard failed before the call ran, so it did not run.' })) // cua: one guard per session
349
350 // Every row the conversation keeps, whatever door it came in by. An engine
351 // row cannot be refused: one the guard failed on is kept as it came.
352 on('session.append', async ($, e, next) => {
353 if (await devcloudGuards($)) return next(e) // cua: one guard per session
354 await refresh($, false)
355 let isChanged = false
356 const content = e.message.content.map((block) => {
357 if (block.type === 'text' && typeof block.text === 'string') {
358 const text = handles.scrub(block.text)
359 if (text === block.text) return block
360 isChanged = true
361 return { ...block, text }
362 }
363 if (block.type === 'tool_result') {
364 const inner = handles.scrubRecord(block.content)
365 if (inner === block.content) return block
366 isChanged = true
367 return { ...block, content: inner }
368 }
369 return block
370 })
371 return isChanged ? next({ ...e, message: { ...e.message, content } }) : next(e)
372 }).catch((_, e, next) => next(e))
373
374 // A compaction's instructions (the text after `/compact`) go to the
375 // summarizer, and its summary rows are kept without passing `session.append`.
376 on('session.compact', async ($, e, next) => {
377 if (await devcloudGuards($)) return next(e) // cua: one guard per session
378 await refresh($, false)
379 const instructions = e.instructions === undefined ? undefined : handles.scrub(e.instructions)
380 const compacted = await next(instructions === e.instructions ? e : { ...e, instructions })
381 if (!('messages' in compacted) || compacted.messages === undefined) return compacted
382 let isChanged = false
383 const messages = compacted.messages.map((m) => {
384 const text = handles.scrub(m.text)
385 if (text === m.text) return m
386 isChanged = true
387 // Without its handle: a message the engine reads as built, not its own.
388 const { handle: _, ...rest } = m
389 return { ...rest, text }
390 })
391 return isChanged ? { ...compacted, messages } : compacted
392 }).catch((_, e, next) => next(e))
393
394 on('prompt.compose', async ($, e, next) => {
395 if (await devcloudGuards($)) return next(e) // cua: one guard per session
396 const composed = await next(e)
397 await refresh($, false)
398 const sections = composed.sections.map((s) => {
399 const text = handles.scrub(s.text)
400 return text === s.text ? s : { ...s, text }
401 })
402 return { sections: [...sections, { id: 'cua:secrets-guard', scope: 'session' as const, text: PROMPT_LINE }] } // cua: devcloud's id is 'devcloud:secrets'
403 })
404
405 on('prompt.context', async ($, e, next) => {
406 if (await devcloudGuards($)) return next(e) // cua: one guard per session
407 const context = await next(e)
408 await refresh($, false)
409 return { ...context, blocks: context.blocks.map((b) => ({ ...b, text: handles.scrub(b.text) })) }
410 })
411
412 on('prompt.attachment', async ($, e, next) => {
413 if (await devcloudGuards($)) return next(e) // cua: one guard per session
414 const attached = await next(e)
415 if (attached.text === null) return attached
416 await refresh($, false)
417 return { text: handles.scrub(attached.text) }
418 })
419}
420hooks/mods/secrets.tsx 386 lines1import type { EngineInterface, Hook, On } from 'claude-code'
2
3/**
4 * `/secret KEY` opens a field in a pane; the value typed there is drawn as
5 * bullets, stored as `~/.config/claude-secrets/projects/<slug>/KEY` for the
6 * session's project (`/secret -g KEY`: `~/.config/claude-secrets/KEY`, for
7 * every project; mode 600), and the model sees only the key. The value never passes through the prompt box, so neither
8 * the prompt history nor the transcript can hold it. A stored value that turns
9 * up in a tool's output is the secrets guard's (./guard, devcloud's, vendored).
10 *
11 * Not the prompt box: when the last keys and Enter arrive in one read (mosh,
12 * a slow link), the editor inserts and submits them before a `prompt.edit`
13 * answer lands, so they reach the history raw. The box still masks a value
14 * typed there out of habit, and the command refuses it.
15 */
16
17// A file per key, not the Keychain: a session under ssh, mosh or a daemon
18// finds the login keychain locked and cannot raise its unlock dialog.
19export const DIR = '.config/claude-secrets'
20export const MASK = '•'
21// `/secret KEY ` or `/secret KEY=`, `-g` or `--global` before the key or not:
22// the value starts after the one character that ends the key.
23const PREFIX = /^\/secret[ \t]+(?:(?:-g|--global)[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t=]/
24const FLAG = /^(?:(-g|--global)(?:[ \t]+|$))?([\s\S]*)$/
25const ARGS = /^([A-Za-z_][A-Za-z0-9_]*)[ \t=]([\s\S]*)$/
26// The echo of a `/secret` run as the conversation keeps it.
27const ECHO = /(<command-name>\/secret<\/command-name>[\s\S]*?<command-args>[ \t]*(?:(?:-g|--global)[ \t]+)?[A-Za-z_][A-Za-z0-9_]*[ \t=])([\s\S]*?)(<\/command-args>)/g
28// Device credentials (cua's reserved keys, src/secrets/label.mjs) are read
29// from the global tier only, so they are stored there whatever the project.
30const RESERVED = /^CUA_DEVICE_/i
31// The global tier's folder of the project tiers, so never a key (in any case:
32// macOS's file system would open PROJECTS for projects).
33const PROJECTS = /^projects$/i
34// Claude Code cuts a slug at this length and adds a hash of the whole path.
35const SLUG_MAX = 200
36
37const PANE = 'secret'
38const FIELD = 'secret-value'
39
40type Scope = 'project' | 'global'
41type Pending = { key: string; scope: Scope }
42type Listed = { key: string; scope: Scope; shadowed: boolean }
43
44// What is typed lives only in this module's memory, never in `$.state` (which
45// every plugin can read): `drafted` behind the prompt box's bullets, `typed`
46// behind the field's, for the key and tier in `pending`.
47let drafted = ''
48let typed = ''
49let pending: Pending | undefined
50// The session's project root, once resolved.
51let project: string | undefined
52// Every stored key of both tiers, by `<scope>/<key>`, for the system prompt.
53const known = new Map<string, { key: string; scope: Scope }>()
54
55type Edit = { text: string; start: number; end: number; inputText: string }
56type Masked = { held: string; box?: { text: string; cursor: number } }
57
58/**
59 * One edit of the prompt box, given the value held so far. While the draft
60 * reads `/secret KEY ` (or `KEY=`), what follows is kept in `held` and the box
61 * shows one bullet per character; `box` absent means the edit is not ours.
62 */
63export function maskEdit(held: string, e: Edit): Masked {
64 const before = PREFIX.exec(e.text)?.[0].length
65 const isMasked = before !== undefined && e.text.slice(before) === MASK.repeat(held.length)
66 const cursor = e.start + e.inputText.length
67
68 if (isMasked && e.start < before) {
69 // An edit to `/secret KEY ` itself drops the value, so a moved boundary
70 // between key and value can never show part of it.
71 const prefix = e.text.slice(0, before)
72 return { held: '', box: { text: prefix.slice(0, e.start) + e.inputText + prefix.slice(Math.min(e.end, before)), cursor } }
73 }
74
75 const real = isMasked ? e.text.slice(0, before) + held : e.text
76 const spliced = real.slice(0, e.start) + e.inputText + real.slice(e.end)
77 const after = PREFIX.exec(spliced)?.[0].length
78 if (after === undefined) return { held: '' }
79 const value = spliced.slice(after)
80 return { held: value, box: { text: spliced.slice(0, after) + MASK.repeat(value.length), cursor } }
81}
82
83/**
84 * The field's text read back against what it held: bullets for the characters
85 * kept, then whatever was typed since the last redraw (several characters when
86 * they arrived together, Enter among them). Undefined for an edit inside the
87 * bullets, which cannot be placed.
88 */
89export function readField(held: string, value: string): string | undefined {
90 const kept = value.length - value.replace(/^•+/, '').length
91 const added = value.slice(kept)
92 if (kept > held.length || added.includes(MASK)) return undefined
93 return held.slice(0, kept) + added
94}
95
96/** A `/secret` echo with its value masked, for one typed where nothing masked it. */
97export function maskEcho(text: string): string {
98 return text.replace(ECHO, (_, head: string, value: string, tail: string) => head + MASK.repeat(value.length) + tail)
99}
100
101// A tool's record with every `/secret` echo in it masked; the same object when none changed.
102function maskRecord(value: unknown): unknown {
103 if (typeof value === 'string') return maskEcho(value)
104 if (Array.isArray(value)) {
105 const items = value.map(maskRecord)
106 return items.some((item, i) => item !== value[i]) ? items : value
107 }
108 if (value !== null && typeof value === 'object') {
109 const entries = Object.entries(value).map(([k, v]) => [k, maskRecord(v)] as const)
110 return entries.some(([k, v]) => v !== (value as Record<string, unknown>)[k]) ? Object.fromEntries(entries) : value
111 }
112 return value
113}
114
115/**
116 * A project's path as Claude Code names its folder under ~/.claude/projects/:
117 * every character other than an ASCII letter or digit becomes '-', and a slug
118 * longer than 200 characters keeps its first 200 and gains '-' and a base-36
119 * hash of the path. cua's store (src/secrets/store.mjs) carries the same.
120 */
121export function projectSlug(path: string): string {
122 const slug = path.replace(/[^a-zA-Z0-9]/g, '-')
123 if (slug.length <= SLUG_MAX) return slug
124 let hash = 0
125 for (let i = 0; i < path.length; i++) hash = ((hash << 5) - hash + path.charCodeAt(i)) | 0
126 return `${slug.slice(0, SLUG_MAX)}-${Math.abs(hash).toString(36)}`
127}
128
129/**
130 * The project root from `git rev-parse --path-format=absolute
131 * --git-common-dir --show-toplevel`'s two lines: the main checkout's root
132 * (the parent of its `.git`, which every linked worktree shares), or the
133 * repository's top level where the common directory is no `.git` folder (a
134 * submodule's). cua's src/secrets/project.mjs resolves it the same way.
135 */
136export function rootFromGit(commonDir: string, topLevel: string): string {
137 return /\/\.git$/.test(commonDir) ? commonDir.slice(0, -'/.git'.length) || '/' : topLevel
138}
139
140// The session's project: the main worktree root of the git repository around
141// its directory, else that directory. Resolved once, at session start.
142async function projectOf($: EngineInterface, cwd?: string): Promise<string> {
143 if (project !== undefined) return project
144 const dir = cwd ?? (await $.session.cwd())
145 let root = dir
146 try {
147 const git = await $.process.run(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir', '--show-toplevel'], { cwd: dir, timeoutMs: 5000 })
148 const [commonDir, topLevel] = git.stdout.trim().split('\n')
149 // A git older than 2.31 echoes `--path-format=absolute` back as a line of
150 // its own; only two absolute paths are an answer.
151 if (git.exitCode === 0 && commonDir?.startsWith('/') && topLevel?.startsWith('/')) root = rootFromGit(commonDir, topLevel)
152 } catch {}
153 project = root
154 return root
155}
156
157// The tier's folder, relative to $HOME.
158async function tierDir($: EngineInterface, scope: Scope): Promise<string> {
159 return scope === 'global' ? DIR : `${DIR}/projects/${projectSlug(await projectOf($))}`
160}
161
162async function usage($: EngineInterface, key: string, scope: Scope): Promise<string> {
163 return `"$(cat ~/${await tierDir($, scope)}/${key})"`
164}
165
166const TIER = { project: 'for this project', global: 'for every project (global)' }
167
168async function storeField($: EngineInterface, { key, scope }: Pending, value: string) {
169 if (value === '') return
170 // The bullets hide a mistyped character, an input method left on.
171 if (/[^\x20-\x7e]/.test(value)) {
172 typed = ''
173 $.ui.toast('secret: a character outside printable ASCII (an input method on?); type it again')
174 return
175 }
176 // The value goes in on stdin, so no process's arguments carry it, and is
177 // created under umask 077 (`$.fs.write` sets no mode).
178 const dir = `${await $.env.get('HOME')}/${await tierDir($, scope)}`
179 const added = await $.process.run(
180 ['/bin/sh', '-c', 'umask 077 && mkdir -p "$1" && chmod 700 "$1" && cat > "$1/$2" && chmod 600 "$1/$2"', 'sh', dir, key],
181 { stdin: value },
182 )
183 if (added.exitCode !== 0) {
184 $.ui.toast(`secret: not stored, ${added.stderr.trim().split('\n')[0] || 'the write failed'}`)
185 return
186 }
187 known.set(`${scope}/${key}`, { key, scope })
188 typed = ''
189 pending = undefined
190 await $.ui.close({ id: PANE })
191 $.ui.toast(`secret: stored ${key} (${scope})`)
192 await $.session.append({
193 message: {
194 type: 'user',
195 content: [
196 {
197 type: 'text',
198 text: `The person stored a secret under ${key}, ${TIER[scope]}. You never see its value. In a shell command, read it as ${await usage($, key, scope)}, never printing it.`,
199 },
200 ],
201 },
202 })
203}
204
205// The stored keys, sorted by key with the project's first; a global key the
206// project's of the same name shadows is marked so.
207function listed(): Listed[] {
208 return [...known.values()]
209 .map(({ key, scope }) => ({ key, scope, shadowed: scope === 'global' && known.has(`project/${key}`) }))
210 .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : a.scope === 'project' ? -1 : 1))
211}
212
213function describe({ key, scope, shadowed }: Listed): string {
214 return `${key} (${scope}${shadowed ? ", shadowed by the project's" : ''})`
215}
216
217// The tier's folder as the pane shows it, the project resolved at session start.
218function shownDir(scope: Scope): string {
219 return scope === 'global' || project === undefined ? DIR : `${DIR}/projects/${projectSlug(project)}`
220}
221
222// Taken with both matchers below: the secrets guard (./guard) registers
223// session.start too, and an event is registered without one once per module.
224const secretsStart: Hook<'session.start'> = async ($, e, next) => {
225 await $.command.register({
226 name: 'secret',
227 description: 'Store a secret for this project (-g: for every project) that the model sees only by its key; the value goes in the field it opens',
228 argumentHint: '[-g] KEY',
229 })
230 project = undefined
231 known.clear()
232 await projectOf($, e.cwd)
233 const home = await $.env.get('HOME')
234 for (const scope of ['project', 'global'] as const) {
235 const dir = `${home}/${await tierDir($, scope)}`
236 if (!(await $.fs.exists(dir))) continue
237 for (const entry of await $.fs.list(dir)) {
238 if (entry.kind === 'file' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(entry.name)) known.set(`${scope}/${entry.name}`, { key: entry.name, scope })
239 }
240 }
241 return next(e)
242}
243
244export function registerSecrets(on: On) {
245 on('session.start', { isInteractive: true }, secretsStart)
246 on('session.start', { isInteractive: false }, secretsStart)
247
248 // Masks a value typed into the box out of habit; the command refuses it.
249 on('prompt.edit', async (_, e, next) => {
250 const masked = maskEdit(drafted, e)
251 drafted = masked.held
252 return masked.box ?? next(e)
253 })
254
255 on('command.run', { command: 'secret' }, async ($, e) => {
256 const [, flag, rest = ''] = FLAG.exec(e.args.trim()) ?? []
257 const args = rest.trim()
258 if (args === '' && !flag) {
259 return { text: known.size ? `Stored: ${listed().map(describe).join(', ')}` : 'No secrets stored.' }
260 }
261 const parsed = ARGS.exec(args)
262 drafted = ''
263 if (parsed) {
264 return {
265 text:
266 'Not stored: type `/secret KEY` alone and the value in the field it opens. ' +
267 'A value typed in the prompt box may be in the prompt history (~/.claude/history.jsonl), whole or in part.',
268 }
269 }
270 if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(args)) return { text: 'Usage: /secret [-g|--global] KEY (letters, digits and _)' }
271 if (PROJECTS.test(args)) return { text: 'Not stored: "projects" is the folder that holds the projects\' secrets, so it is not a key.' }
272 const isDevice = !flag && RESERVED.test(args)
273 pending = { key: args, scope: flag || isDevice ? 'global' : 'project' }
274 typed = ''
275 await projectOf($)
276 await $.ui.open({ id: PANE, title: `secret ${args} (${pending.scope})`, focus: true, closeOnEscape: true, rows: 2 })
277 const where = isDevice
278 ? 'for every project, as device credentials are'
279 : pending.scope === 'project'
280 ? `${TIER.project} (/secret -g ${args} stores it for every project)`
281 : TIER.global
282 return { text: `Type the value of ${args} in the field of the pane it opened; it is stored ${where}. Enter stores it, Escape cancels.` }
283 })
284
285 on('ui.render', { component: 'Pane', requestId: PANE }, ($, e) => {
286 if (e.surface === 'mobile') {
287 const { Text } = $.ui.resolve(e)
288 return <Text>The mobile app draws no field: type the value from a terminal, the desktop app or VS Code.</Text>
289 }
290 const { Box, Input, Text } = $.ui.resolve(e)
291 return (
292 <Box flexDirection="column">
293 <Input
294 key={FIELD}
295 label={`${pending?.key ?? ''} `}
296 value={MASK.repeat(typed.length)}
297 placeholder="value"
298 submitLabel="store"
299 autoFocus
300 onSubmit={() => {}}
301 />
302 <Text dimColor>Escape cancels. Stored in ~/{pending ? `${shownDir(pending.scope)}/${pending.key}` : DIR}, mode 600.</Text>
303 </Box>
304 )
305 })
306
307 // Taken here rather than in the element's closures, which have no `$`.
308 on('ui.input', { element: FIELD }, async ($, e) => {
309 const value = readField(typed, e.value)
310 typed = value ?? ''
311 if (value === undefined) $.ui.toast('secret: edit at the end of the field; it was cleared')
312 $.ui.invalidate('ui.render')
313 if (e.kind === 'submit' && value !== undefined && pending !== undefined) await storeField($, pending, value)
314 return { element: e.element, value: MASK.repeat(typed.length) }
315 })
316
317 on('ui.close', { id: PANE }, (_, e, next) => {
318 typed = ''
319 pending = undefined
320 return next(e)
321 })
322
323 // A `/secret` echo typed where nothing masked it is masked wherever the
324 // model or the transcript would read it, whichever guard holds the session:
325 // the echo is `/secret`'s, and its value may be stored nowhere (refused) or
326 // shaped like no token. In a tool's record here, since the transcript keeps
327 // it (`toolUseResult`) beside the row the model reads, which
328 // `session.append` cannot reach. Each taken with a matcher every event
329 // meets: the guard registers tool.call and session.append too.
330 on('tool.call', { tool: /(?:)/ }, async (_, e, next) => {
331 const ran = await next(e)
332 if (ran.deny !== undefined) {
333 const deny = maskEcho(ran.deny)
334 return deny === ran.deny ? ran : { deny }
335 }
336 if (ran.isError) {
337 const text = maskEcho(ran.text ?? '')
338 return text === ran.text ? ran : { deny: text }
339 }
340 const result = maskRecord(ran.result)
341 return result === ran.result ? ran : { result, context: ran.context }
342 }).catch((_, e, next) => (next.called ? { deny: 'secret: the echo mask failed on this result, so it is withheld.' } : next(e)))
343
344 on('session.append', { uuid: /(?:)/ }, async (_, e, next) => {
345 let isChanged = false
346 const content = e.message.content.map((block) => {
347 if (block.type === 'text' && typeof block.text === 'string') {
348 const text = maskEcho(block.text)
349 if (text === block.text) return block
350 isChanged = true
351 return { ...block, text }
352 }
353 if (block.type === 'tool_result') {
354 const inner = maskRecord(block.content)
355 if (inner === block.content) return block
356 isChanged = true
357 return { ...block, content: inner }
358 }
359 return block
360 })
361 return isChanged ? next({ ...e, message: { ...e.message, content } }) : next(e)
362 })
363
364 // Taken with a matcher every composition meets: the guard registers
365 // prompt.compose too.
366 on('prompt.compose', { model: /(?:)/ }, async ($, e, next) => {
367 const composed = await next(e)
368 if (known.size === 0) return composed
369 const lines = await Promise.all(listed().map(async (s) => `- ${describe(s)}: ${await usage($, s.key, s.scope)}`))
370 return {
371 sections: [
372 ...composed.sections,
373 {
374 id: 'cua:secrets',
375 scope: 'session',
376 text:
377 'Secrets the person stored, one file each, for this project or for every project (global). ' +
378 'You see only their keys; read a value inside the shell command that uses it, never printing it. ' +
379 "Where a key is stored in both, use the project's:\n" +
380 lines.join('\n'),
381 },
382 ],
383 }
384 })
385}
386hooks/mods/guard/secrets-handles.tsx 280 lines1// Vendored from SSFSKIM/doperpowers devcloud/hooks/mods/secrets-handles.tsx at 823f772f634003278886446940fe9fb6b679e254
2// (devcloud 0.5.0); the adaptations and the resync are in hooks/mods/guard/VENDORED.md.
3
4import { detect, keepFirst } from './secrets-detect'
5import { isInert, isPlainCommand, isPlainPosition } from './secrets-shell'
6
7/**
8 * Handles: the text that stands where a secret was, one per distinct byte
9 * string, and the way back to those bytes. Pure: the hooks module feeds it the
10 * known values it reads and calls it on every text it passes.
11 *
12 * [secret:LABEL] a known value: a store key (`KEY`, `KEY@global`
13 * for a global value a project key shadows,
14 * `KEY@<slug>` for another project's) or a
15 * credential file's field (`hosts.yml:<field>`);
16 * whitespace, `[`, `]`, `~` and `%` in a label
17 * are written %XX, and a second value under a
18 * label already taken is `LABEL#2`, `#3`, ...
19 * [secret:LABEL~<enc>] an encoded spelling of it
20 * [superseded:LABEL] a value LABEL held earlier in this process
21 * [redacted:<kind>#<ns>.<n>] a pattern detection, bound to this process
22 *
23 * A known handle names a credential, so it restores to the credential's
24 * current value; a pattern handle stands for exactly the bytes it replaced,
25 * and only the process that issued it (its namespace) can restore it.
26 */
27
28export type Known = { label: string; value: string }
29export type Spelling = { enc: string; text: string }
30
31// Shorter values would scrub ordinary words out of everything the model reads.
32export const SCRUB_MIN = 6
33
34const HANDLE = /\[(secret|superseded|redacted):([^\]\s]+)\]/g
35// What looks like a handle, parsable or not: one that is not is named as not
36// restored rather than passed over.
37const HANDLE_LIKE = /\[(secret|superseded|redacted):([^\]\n]*)\]/g
38const PARSABLE = /^[^\]\s]+$/
39
40// A label's characters the handle grammar reserves, written %XX (UTF-8).
41const RESERVED = /[\s[\]~%]|[^\x21-\x7e]/gu
42export const encodeLabel = (label: string) =>
43 label.replace(RESERVED, (c) => Array.from(utf8(c), (b) => `%${b.toString(16).toUpperCase().padStart(2, '0')}`).join(''))
44const decodeLabel = (body: string): string | undefined => {
45 try {
46 return decodeURIComponent(body.replace(/%(?![0-9A-Fa-f]{2})/g, '%25'))
47 } catch {
48 return undefined
49 }
50}
51
52const utf8 = (value: string) => new TextEncoder().encode(value)
53const base64 = (value: string) => {
54 let binary = ''
55 for (const byte of utf8(value)) binary += String.fromCharCode(byte)
56 return btoa(binary)
57}
58const hex = (value: string) => Array.from(utf8(value), (b) => b.toString(16).padStart(2, '0')).join('')
59
60// The spellings a command prints a value in by accident, each its own
61// encoding name; a spelling that equals an earlier one is the earlier one.
62const ENCODINGS: readonly [string, (value: string) => string][] = [
63 ['', (v) => v],
64 ['b64', (v) => base64(v)],
65 ['b64np', (v) => base64(v).replace(/=+$/, '')],
66 ['b64u', (v) => base64(v).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_')],
67 ['b64up', (v) => base64(v).replace(/\+/g, '-').replace(/\//g, '_')],
68 ['hex', (v) => hex(v)],
69 ['HEX', (v) => hex(v).toUpperCase()],
70 ['url', (v) => encodeURIComponent(v)],
71 // As a JSON string's body prints it: a key file's PEM with `\n` escapes.
72 ['json', (v) => JSON.stringify(v).slice(1, -1)],
73 // As a .pgpass line prints it: `\` and `:` escaped with a backslash.
74 ['pgpass', (v) => v.replace(/[\\:]/g, '\\$&')],
75]
76const ENCODING = new Map(ENCODINGS)
77
78/** Every distinct spelling of `value`, the value itself first (`enc` ''). */
79export function spellings(value: string): Spelling[] {
80 const seen = new Set<string>()
81 const out: Spelling[] = []
82 for (const [enc, encode] of ENCODINGS) {
83 const text = encode(value)
84 if (seen.has(text)) continue
85 seen.add(text)
86 out.push({ enc, text })
87 }
88 return out
89}
90
91const handleOf = (kind: 'secret' | 'superseded', label: string, enc: string) => `[${kind}:${encodeLabel(label)}${enc ? `~${enc}` : ''}]`
92
93type Candidate = { start: number; end: number; rank: number; replace?: string; kind?: string }
94
95export class Handles {
96 /** The namespace of this process's pattern handles. */
97 readonly ns: string
98 private current = new Map<string, string>()
99 private former = new Map<string, string>()
100 private known = new Map<string, string>()
101 private issued = new Map<string, string>()
102 private bytes = new Map<string, string>()
103
104 constructor(ns: string) {
105 this.ns = ns
106 }
107
108 /**
109 * The values known now, in priority order (the first label to hold a value
110 * keeps it). A distinct value under a label already taken gets `#2`, `#3`,
111 * ...; none is dropped. Returns the name each entry got, in order. A label whose value changed or vanished leaves its old
112 * value superseded, unless another label holds it now.
113 */
114 setKnown(list: readonly Known[]): string[] {
115 // Every label stays resolvable, two holding the same bytes included; only
116 // which handle the bytes display as goes to the first (below).
117 const next = new Map<string, string>()
118 const names: string[] = []
119 for (const { label, value } of list) {
120 let name = label
121 for (let n = 2; next.has(name) && next.get(name) !== value; n++) name = `${label}#${n}`
122 next.set(name, value)
123 names.push(name)
124 }
125 for (const [label, value] of this.current) if (next.get(label) !== value) this.former.set(value, label)
126 this.current = next
127 this.known = new Map()
128 for (const [label, value] of next) {
129 if (value.length < SCRUB_MIN) continue
130 for (const { enc, text } of spellings(value)) if (!this.known.has(text)) this.known.set(text, handleOf('secret', label, enc))
131 }
132 const current = new Set(next.values())
133 for (const [value, label] of this.former) {
134 if (current.has(value) || value.length < SCRUB_MIN) continue
135 for (const { enc, text } of spellings(value)) if (!this.known.has(text)) this.known.set(text, handleOf('superseded', label, enc))
136 }
137 return names
138 }
139
140 private patternHandle(kind: string, text: string): string {
141 let handle = this.issued.get(text)
142 if (handle === undefined) {
143 handle = `[redacted:${kind}#${this.ns}.${this.issued.size + 1}]`
144 this.issued.set(text, handle)
145 this.bytes.set(handle, text)
146 }
147 return handle
148 }
149
150 /**
151 * `text` with every known value, superseded value and token-shaped string
152 * replaced by its handle, in one pass: a handle already in the text is kept
153 * as it is, and nothing the pass wrote is read again.
154 */
155 scrub(text: string): string {
156 const candidates: Candidate[] = []
157 for (const m of text.matchAll(HANDLE)) candidates.push({ start: m.index ?? 0, end: (m.index ?? 0) + m[0].length, rank: 0 })
158 // `indexOf` per spelling: far quicker over a long output than one
159 // alternation of every spelling, tried at each position.
160 for (const [spelling, handle] of this.known) {
161 for (let at = text.indexOf(spelling); at !== -1; at = text.indexOf(spelling, at + spelling.length)) {
162 candidates.push({ start: at, end: at + spelling.length, rank: 1, replace: handle })
163 }
164 }
165 for (const span of detect(text)) candidates.push({ ...span, rank: 2 })
166 if (candidates.every((c) => c.rank === 0)) return text
167
168 // A handle in the text first, then known values (the longest where two
169 // start together), then patterns; each kept unless it overlaps one kept.
170 candidates.sort((a, b) => a.rank - b.rank || a.start - b.start || b.end - a.end)
171 const kept = keepFirst(candidates, text.length)
172
173 let out = ''
174 let at = 0
175 for (const c of kept) {
176 if (c.rank === 0) continue
177 out += text.slice(at, c.start) + (c.replace ?? this.patternHandle(c.kind ?? 'pattern', text.slice(c.start, c.end)))
178 at = c.end
179 }
180 return out + text.slice(at)
181 }
182
183 /** The bytes a handle restores to now, or undefined. */
184 valueOf(handle: string): string | undefined {
185 const m = /^\[(secret|superseded|redacted):([^\]\s]+)\]$/.exec(handle)
186 return m ? this.resolve(m[1]!, m[2]!) : undefined
187 }
188
189 /** What a handle names: its kind, and for a known one its label and encoding (`''` for the value itself). */
190 describe(handle: string): { kind: string; label?: string; enc: string } {
191 const m = /^\[(secret|superseded|redacted):([^\]\s]+)\]$/.exec(handle)
192 if (!m) return { kind: 'unparsed', enc: '' }
193 const body = m[2]!
194 const tilde = body.lastIndexOf('~')
195 const enc = tilde > 0 && ENCODING.has(body.slice(tilde + 1)) ? body.slice(tilde + 1) : ''
196 return { kind: m[1]!, label: decodeLabel(enc ? body.slice(0, tilde) : body), enc }
197 }
198
199 /** What a handle's text stands for now, or undefined when nothing it names can be restored. */
200 private resolve(kind: string, body: string): string | undefined {
201 if (kind === 'redacted') return this.bytes.get(`[redacted:${body}]`)
202 if (kind !== 'secret') return undefined
203 const tilde = body.lastIndexOf('~')
204 const enc = tilde > 0 && ENCODING.has(body.slice(tilde + 1)) ? body.slice(tilde + 1) : ''
205 const label = decodeLabel(enc ? body.slice(0, tilde) : body)
206 const value = label === undefined ? undefined : this.current.get(label)
207 return value === undefined ? undefined : ENCODING.get(enc)!(value)
208 }
209
210 /**
211 * `text` with each handle this process can restore replaced by its bytes;
212 * every other handle-like text, parsable or not, left as it is and named.
213 */
214 restore(text: string): { text: string; unrestored: string[] } {
215 const { unquotable: _, ...restored } = this.restoreWith(text, (value) => value)
216 return restored
217 }
218
219 // Each handle resolved and written through `write`; one `write` declines is
220 // named in `unquotable`, one nothing resolves in `unrestored`.
221 private restoreWith(text: string, write: (value: string, at: number, length: number) => string | undefined): { text: string; unrestored: string[]; unquotable: string[] } {
222 const unrestored: string[] = []
223 const unquotable: string[] = []
224 const restored = text.replace(HANDLE_LIKE, (handle: string, kind: string, body: string, at: number) => {
225 const value = PARSABLE.test(body) ? this.resolve(kind, body) : undefined
226 if (value === undefined) {
227 if (!unrestored.includes(handle)) unrestored.push(handle)
228 return handle
229 }
230 const written = write(value, at, handle.length)
231 if (written !== undefined) return written
232 if (!unquotable.includes(handle)) unquotable.push(handle)
233 return handle
234 })
235 return { text: restored, unrestored, unquotable }
236 }
237
238 /**
239 * A shell command with its handles restored where that is shown safe
240 * (secrets-shell): an inert value, at a plain position, in a plain command.
241 * Every other handle stays as written and is named in `unquotable`.
242 */
243 restoreShell(command: string): { text: string; unrestored: string[]; unquotable: string[] } {
244 const isPlain = isPlainCommand(command)
245 return this.restoreWith(command, (value, at, length) => (isPlain && isInert(value) && isPlainPosition(command, at, length, value) ? value : undefined))
246 }
247
248 /** A record with every string scrubbed (an image's bytes left); the same object when none changed. */
249 scrubRecord<T>(value: T): T {
250 return mapStrings(value, (s) => this.scrub(s)) as T
251 }
252
253 /** A record with every string's handles restored, and the handles left as written. */
254 restoreRecord<T>(value: T): { value: T; unrestored: string[] } {
255 const unrestored: string[] = []
256 const out = mapStrings(value, (s) => {
257 const r = this.restore(s)
258 for (const h of r.unrestored) if (!unrestored.includes(h)) unrestored.push(h)
259 return r.text
260 }) as T
261 return { value: out, unrestored }
262 }
263}
264
265// Each string of a JSON-like value mapped; the same object where none changed.
266function mapStrings(value: unknown, map: (s: string) => string): unknown {
267 if (typeof value === 'string') return map(value)
268 if (Array.isArray(value)) {
269 const items = value.map((item) => mapStrings(item, map))
270 return items.some((item, i) => item !== value[i]) ? items : value
271 }
272 if (value !== null && typeof value === 'object') {
273 const record = value as Record<string, unknown>
274 if (record.type === 'image' || record.type === 'base64') return value
275 const entries = Object.entries(record).map(([k, v]) => [k, mapStrings(v, map)] as const)
276 return entries.some(([k, v]) => v !== record[k]) ? Object.fromEntries(entries) : value
277 }
278 return value
279}
280hooks/mods/guard/secrets-reads.tsx 113 lines1// Vendored from SSFSKIM/doperpowers devcloud/hooks/mods/secrets-reads.tsx at 823f772f634003278886446940fe9fb6b679e254
2// (devcloud 0.5.0); the adaptations and the resync are in hooks/mods/guard/VENDORED.md.
3
4/**
5 * What to read in a shell command where the guard left a handle: for each
6 * kind of source, a command that prints exactly the value's bytes (no newline
7 * added, the file's own escaping undone), and the notice that names it. Pure;
8 * each command is run against real files by tests/mods/shell-exec.ts.
9 */
10
11/** Where a known value comes from, enough for a command to read it. Paths are from $HOME. */
12export type Read =
13 | { kind: 'store'; path: string }
14 | { kind: 'json'; path: string; keys: readonly string[] }
15 | { kind: 'gh'; host: string; user?: string }
16 | { kind: 'toml'; path: string; table: string; index?: number; key: string }
17 | { kind: 'pgpass'; path: string; match: string[]; nth: number }
18 | { kind: 'netrc'; path: string; machine: string; nth: number }
19 | { kind: 'git-credentials'; path: string; id: string; nth: number }
20 | { kind: 'npmrc'; path: string; key: string; nth: number }
21
22/** The step that turns a value read in a command into a handle's encoding. */
23export const ENCODE: Record<string, string> = {
24 b64: "base64 | tr -d '\\n'",
25 b64np: "base64 | tr -d '\\n='",
26 b64u: "base64 | tr -d '\\n=' | tr '+/' '-_'",
27 b64up: "base64 | tr -d '\\n' | tr '+/' '-_'",
28 hex: "xxd -p | tr -d '\\n'",
29 HEX: "xxd -p | tr -d '\\n' | tr a-f A-F",
30 url: `python3 -c 'import sys,urllib.parse; sys.stdout.write(urllib.parse.quote(sys.stdin.read(), safe="!*()\\x27"))'`,
31 json: `python3 -c 'import sys,json; sys.stdout.write(json.dumps(sys.stdin.read(), ensure_ascii=False)[1:-1])'`,
32 pgpass: "sed 's/[\\\\:]/\\\\&/g'",
33}
34
35// An argument as the shell will read it back: as it is when plain, else
36// single-quoted.
37export const quote = (arg: string) => (/^[A-Za-z0-9_./@:%+=,-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`)
38const home = (path: string) => `~/${/^[A-Za-z0-9_./@:%+=,-]+$/.test(path) ? path : quote(path)}`
39
40// The Python each file kind is read with, written for a single-quoted shell
41// string (no `'` inside); each prints the value and nothing else.
42const PY = {
43 json: String.raw`import json,sys,functools;a=sys.argv;sys.stdout.write(functools.reduce(lambda v,k:v[int(k)] if isinstance(v,list) else v[k],a[2:],json.load(open(a[1]))))`,
44 toml: String.raw`import sys,tomllib,functools;a=sys.argv;t=functools.reduce(lambda t,k:t[k],[k for k in a[2].split(".") if k],tomllib.load(open(a[1],"rb")));t=t[int(a[3])] if a[3] else t;sys.stdout.write(t[a[4]])`,
45 pgpass: String.raw`import re,sys;a=sys.argv;m=[p for p in (re.split(r"(?<!\\):",l.rstrip("\n")) for l in open(a[1]) if l.strip() and not l.startswith("#")) if len(p)==5 and p[:4]==a[2:6]];sys.stdout.write(re.sub(r"\\(.)",r"\1",m[int(a[6])][4]))`,
46 // Tokenized as secrets-sources reads .netrc (curl's rules: `\n`, `\r`, `\t`
47 // in a quoted word), not as Python's netrc module does.
48 netrc: String.raw`import re,sys;a=sys.argv;w=[re.sub(r"\\([\s\S]?)",lambda e:{"n":"\n","r":"\r","t":"\t"}.get(e[1],e[1]),q) if u=="" else u for q,u in re.findall(r"\"((?:\\[\s\S]?|[^\"\\])*)\"?|(\S+)",open(a[1]).read())];m="";it=iter(w);o=[(m,v) for x in it if (m:=(next(it,"") if x=="machine" else "default" if x=="default" else m)) is not None and (v:=(next(it,None) if x=="password" else [next(it,None),None][1] if x in ("login","account") else None)) is not None];sys.stdout.write([v for k,v in o if k==a[2]][int(a[3])])`,
49 gitCredentials: String.raw`import sys,urllib.parse as u;a=sys.argv;m=[s for s in (u.urlsplit(l.strip()) for l in open(a[1])) if s.password is not None and u.unquote(s.username or "")+"@"+s.netloc.rpartition("@")[2]+s.path==a[2]];sys.stdout.write(u.unquote(m[int(a[3])].password))`,
50 npmrc: String.raw`import sys;a=sys.argv;m=[l.split("=",1)[1].strip() for l in open(a[1]) if "=" in l and l.split("=",1)[0].strip()==a[2]];v=m[int(a[3])];sys.stdout.write(v[1:-1] if len(v)>1 and v[0]==v[-1] and v[0] in "\x22\x27" else v)`,
51}
52
53// A jq path to a JSON field's keys, or undefined where one would need quoting.
54const jqPath = (keys: readonly string[]) =>
55 keys.some((k) => k.includes("'"))
56 ? undefined
57 : keys.map((k) => (/^\d+$/.test(k) ? `[${k}]` : /^[A-Za-z_][A-Za-z0-9_]*$/.test(k) ? `.${k}` : `[${JSON.stringify(k)}]`)).join('').replace(/^\[/, '.[')
58
59/** A command that prints exactly the value `read` names. */
60export function readCommand(read: Read): string {
61 switch (read.kind) {
62 case 'store':
63 // The store drops one trailing newline on read; so does this.
64 return `perl -pe 'chomp if eof' ${home(read.path)}`
65 case 'json': {
66 const path = jqPath(read.keys)
67 return path ? `jq -j '${path}' ${home(read.path)}` : `python3 -c '${PY.json}' ${home(read.path)} ${read.keys.map(quote).join(' ')}`
68 }
69 case 'gh':
70 return `gh auth token --hostname ${quote(read.host)}${read.user ? ` --user ${quote(read.user)}` : ''} | tr -d '\\n'`
71 case 'toml':
72 return `python3 -c '${PY.toml}' ${home(read.path)} ${quote(read.table) || "''"} ${read.index ?? "''"} ${quote(read.key)}`
73 case 'pgpass':
74 return `python3 -c '${PY.pgpass}' ${home(read.path)} ${read.match.map((f) => quote(f)).join(' ')} ${read.nth}`
75 case 'netrc':
76 return `python3 -c '${PY.netrc}' ${home(read.path)} ${quote(read.machine)} ${read.nth}`
77 case 'git-credentials':
78 return `python3 -c '${PY.gitCredentials}' ${home(read.path)} ${quote(read.id)} ${read.nth}`
79 case 'npmrc':
80 return `python3 -c '${PY.npmrc}' ${home(read.path)} ${quote(read.key)} ${read.nth}`
81 }
82}
83
84// What the read undoes of how the file writes the value.
85const DECODES: Partial<Record<Read['kind'], string>> = {
86 pgpass: "it undoes .pgpass's backslash escapes",
87 'git-credentials': 'it URL-decodes the password',
88 netrc: 'it decodes netrc quoting',
89 toml: 'tomllib decodes TOML strings',
90 npmrc: "it drops .npmrc's quotes",
91}
92
93/**
94 * The notice's read for a handle: `"$(…)"` of the exact read (piped through
95 * the handle's encoding), or, for bytes that end in a newline `"$(…)"` would
96 * drop, the read to pipe or pass as a file. `endsInNewline` is about the
97 * bytes the handle stands for (its encoding applied).
98 */
99export function readNotice(read: Read | undefined, enc: string, endsInNewline: boolean): string {
100 if (!read) return 'read its source in the command'
101 const encode = enc ? ENCODE[enc] : undefined
102 const decodes = DECODES[read.kind] ? ` (${DECODES[read.kind]})` : ''
103 const full = encode ? `${readCommand(read)} | ${encode}` : readCommand(read)
104 if (endsInNewline) return `pipe it, as its value ends in a newline that "$(…)" would drop: ${full} | <command>, or pass it as a file: <(${full})${decodes}`
105 if (!encode && read.kind === 'store') return `use "$(cat ${home(read.path)})" in the command`
106 if (!encode && read.kind === 'gh') return `use "$(gh auth token --hostname ${quote(read.host)}${read.user ? ` --user ${quote(read.user)}` : ''})" in the command`
107 return `use "$(${full})" in the command${decodes}`
108}
109
110/** The notice's read for a pattern handle, which has no source on disk. */
111export const PATTERN_READ =
112 'it has no source on disk, so it stays unrestored in shell commands: to use it, write it with a file tool (file tools restore it) to a temporary file, then use "$(cat <that file>)" in the command'
113hooks/mods/guard/secrets-sources.tsx 324 lines1// Vendored from SSFSKIM/doperpowers devcloud/hooks/mods/secrets-sources.tsx at 823f772f634003278886446940fe9fb6b679e254
2// (devcloud 0.5.0); the adaptations and the resync are in hooks/mods/guard/VENDORED.md.
3
4/**
5 * Where known values come from, read without `$`: the secret store's layout
6 * (Interfaces I1, as `cua`'s `src/secrets/store.mjs` documents it) and the
7 * well-known credential files, each parsed into its secret fields. The hooks
8 * module lists and reads the files; this one says what they hold.
9 */
10
11import type { Read } from './secrets-reads'
12
13/** A secret field: its name in handles, its value, and how a command reads it from its file. */
14export type Field = { field: string; value: string; read?: Read }
15export type Format = 'yaml' | 'json' | 'gcloud' | 'toml' | 'pgpass' | 'netrc' | 'git-credentials' | 'npmrc'
16
17/** The secret store, relative to $HOME: one value per file, a folder per project under `projects/`. */
18export const STORE_DIR = '.config/claude-secrets'
19export const KEY = /^[A-Za-z_][A-Za-z0-9_]*$/
20// The global tier's folder of the project tiers, so never a key (in any case:
21// macOS's file system would open PROJECTS for projects).
22export const PROJECTS = /^projects$/i
23
24/** The credential files read at fixed paths, relative to $HOME, with the format each is parsed as. */
25export const CREDENTIAL_FILES: readonly { path: string; format: Format }[] = [
26 { path: '.config/gh/hosts.yml', format: 'yaml' },
27 { path: '.pgpass', format: 'pgpass' },
28 { path: '.codex/auth.json', format: 'json' },
29 { path: '.claude/.credentials.json', format: 'json' },
30 { path: '.config/hcloud/cli.toml', format: 'toml' },
31 { path: '.docker/config.json', format: 'json' },
32 { path: '.netrc', format: 'netrc' },
33 { path: '.git-credentials', format: 'git-credentials' },
34 { path: '.npmrc', format: 'npmrc' },
35]
36/** gcloud's folder, whose JSON key files (service account, authorized user) are read too. */
37export const GCLOUD_DIR = '.config/gcloud'
38// Its folders that hold no key file, left unwalked.
39export const GCLOUD_SKIP = new Set(['logs', 'cache', 'configurations', 'surface_data', 'virtenv'])
40
41// A field whose name says it holds a credential, and the names that only
42// point at one (an address, an id, a kind).
43const SECRET_FIELD = /token|secret|password|passwd|private_?key|api_?key|credential|^auth$/i
44const NOT_SECRET_FIELD = /(?:uri|url|_id|Id|type|mode)$/i
45// Shorter strings are flags and kinds, not credentials.
46const FIELD_MIN = 8
47
48const isSecretField = (name: string, value: string) =>
49 SECRET_FIELD.test(name) && !NOT_SECRET_FIELD.test(name) && value.length >= FIELD_MIN && !/^[a-z][a-z0-9+.-]*:\/\//i.test(value)
50
51function jsonFields(value: unknown, path: string[] = [], out: Field[] = []): Field[] {
52 if (Array.isArray(value)) value.forEach((item, i) => jsonFields(item, [...path, String(i)], out))
53 else if (value !== null && typeof value === 'object') {
54 for (const [k, v] of Object.entries(value)) {
55 if (typeof v === 'string') {
56 if (isSecretField(k, v)) out.push({ field: [...path, k].join('.'), value: v, read: { kind: 'json', path: '', keys: [...path, k] } })
57 } else jsonFields(v, [...path, k], out)
58 }
59 }
60 return out
61}
62
63const unquote = (text: string) => {
64 const t = text.trim()
65 return /^(["']).*\1$/.test(t) ? t.slice(1, -1) : t
66}
67
68function yamlFields(text: string): Field[] {
69 const out: Field[] = []
70 const stack: { indent: number; key: string }[] = []
71 for (const line of text.split('\n')) {
72 const m = /^(\s*)(?:-\s+)?([^:#\s][^:#]*?):(?:\s+(.*))?$/.exec(line)
73 if (!m) continue
74 const indent = (m[1] ?? '').length
75 while (stack.length && stack[stack.length - 1]!.indent >= indent) stack.pop()
76 const key = m[2]!.trim()
77 const value = unquote((m[3] ?? '').replace(/\s+#.*$/, ''))
78 if (value === '') stack.push({ indent, key })
79 else if (isSecretField(key, value)) {
80 const keys = [...stack.map((s) => s.key), key]
81 // gh's hosts.yml: `gh auth token` reads it, from the keyring too.
82 const read: Read | undefined =
83 keys.length === 2 && key === 'oauth_token'
84 ? { kind: 'gh', host: keys[0]! }
85 : keys.length === 4 && keys[1] === 'users' && key === 'oauth_token'
86 ? { kind: 'gh', host: keys[0]!, user: keys[2]! }
87 : undefined
88 out.push({ field: keys.join('.'), value, ...(read ? { read } : {}) })
89 }
90 }
91 return out
92}
93
94// A TOML value as the file means it: a basic string's escapes decoded, a
95// literal string as written, a bare value up to an inline comment.
96function tomlValue(raw: string): string {
97 const quote = raw[0]
98 if (quote === "'") {
99 const end = raw.indexOf("'", 1)
100 return end === -1 ? raw.slice(1) : raw.slice(1, end)
101 }
102 if (quote === '"') {
103 let out = ''
104 for (let i = 1; i < raw.length; i++) {
105 const c = raw[i]!
106 if (c === '"') return out
107 if (c !== '\\') {
108 out += c
109 continue
110 }
111 const e = raw[++i] ?? ''
112 if (e === 'u' || e === 'U') {
113 const n = e === 'u' ? 4 : 8
114 out += String.fromCodePoint(parseInt(raw.slice(i + 1, i + 1 + n), 16))
115 i += n
116 } else out += ({ n: '\n', t: '\t', r: '\r', b: '\b', f: '\f' } as Record<string, string>)[e] ?? e
117 }
118 return out
119 }
120 return raw.replace(/\s+#.*$/, '').trim()
121}
122
123function tomlFields(text: string): Field[] {
124 const out: Field[] = []
125 type Block = { prefix: string; isArray: boolean; index: number; entries: [string, string][] }
126 const counts = new Map<string, number>()
127 let block: Block = { prefix: '', isArray: false, index: 0, entries: [] }
128 const flush = () => {
129 const name = block.entries.find(([k]) => k === 'name')?.[1]
130 const base = block.isArray ? `${block.prefix}.${name ?? block.index}` : block.prefix
131 for (const [k, v] of block.entries) {
132 if (!isSecretField(k, v)) continue
133 const read: Read = { kind: 'toml', path: '', table: block.prefix, key: k, ...(block.isArray ? { index: block.index } : {}) }
134 out.push({ field: base ? `${base}.${k}` : k, value: v, read })
135 }
136 }
137 for (const line of text.split('\n')) {
138 const table = /^\s*(\[\[?)\s*([^\]]+?)\s*\]\]?\s*$/.exec(line)
139 if (table) {
140 flush()
141 const prefix = table[2]!
142 const isArray = table[1] === '[['
143 const index = counts.get(prefix) ?? 0
144 if (isArray) counts.set(prefix, index + 1)
145 block = { prefix, isArray, index, entries: [] }
146 continue
147 }
148 const kv = /^\s*([A-Za-z0-9_.-]+)\s*=\s*(.+?)\s*$/.exec(line)
149 if (kv) block.entries.push([kv[1]!, tomlValue(kv[2]!)])
150 }
151 flush()
152 return out
153}
154
155function pgpassFields(text: string): Field[] {
156 const out: Field[] = []
157 for (const line of text.split('\n')) {
158 if (line.trim() === '' || line.startsWith('#')) continue
159 const parts = line.split(/(?<!\\):/)
160 if (parts.length !== 5) continue
161 const value = parts[4]!.replace(/\\(.)/g, '$1')
162 const match = parts.slice(0, 4)
163 const nth = out.filter((f) => f.read?.kind === 'pgpass' && f.read.match.join('\0') === match.join('\0')).length
164 if (value) out.push({ field: match.join(':'), value, read: { kind: 'pgpass', path: '', match, nth } })
165 }
166 return out
167}
168
169// A .netrc's tokens: whitespace-separated, a double-quoted token taken whole
170// with its backslash escapes decoded as curl reads them (`\n`, `\r`, `\t` the
171// control characters, any other `\x` the character itself).
172function netrcTokens(text: string): string[] {
173 const words: string[] = []
174 for (let i = 0; i < text.length; ) {
175 while (i < text.length && /\s/.test(text[i]!)) i++
176 if (i >= text.length) break
177 let word = ''
178 if (text[i] === '"') {
179 for (i++; i < text.length && text[i] !== '"'; i++) {
180 if (text[i] !== '\\') word += text[i]
181 else {
182 const e = text[++i] ?? ''
183 word += ({ n: '\n', r: '\r', t: '\t' } as Record<string, string>)[e] ?? e
184 }
185 }
186 i++
187 } else for (; i < text.length && !/\s/.test(text[i]!); i++) word += text[i]
188 words.push(word)
189 }
190 return words
191}
192
193function netrcFields(text: string): Field[] {
194 const out: Field[] = []
195 const words = netrcTokens(text)
196 let machine = ''
197 const seen = new Map<string, number>()
198 for (let i = 0; i < words.length; i++) {
199 const word = words[i]
200 if (word === 'machine') machine = words[++i] ?? ''
201 else if (word === 'default') machine = 'default'
202 else if (word === 'password' && words[i + 1] !== undefined) {
203 const nth = seen.get(machine) ?? 0
204 seen.set(machine, nth + 1)
205 out.push({ field: `${machine}.password`, value: words[++i]!, read: { kind: 'netrc', path: '', machine, nth } })
206 }
207 else if (word === 'login' || word === 'account') i++
208 }
209 return out
210}
211
212function gitCredentialFields(text: string): Field[] {
213 const out: Field[] = []
214 const decode = (s: string) => {
215 try {
216 return decodeURIComponent(s)
217 } catch {
218 return s
219 }
220 }
221 for (const line of text.split('\n')) {
222 // The repository path is part of the identity: one user may hold a
223 // credential per repository on one host.
224 const m = /^[a-z][a-z0-9+.-]*:\/\/([^:@/]*):([^@/]+)@([^/\s]+)(\/\S*)?/i.exec(line.trim())
225 if (!m) continue
226 const id = `${decode(m[1]!)}@${m[3]}${m[4] ?? ''}`
227 const nth = out.filter((f) => f.field === id).length
228 out.push({ field: id, value: decode(m[2]!), read: { kind: 'git-credentials', path: '', id, nth } })
229 }
230 return out
231}
232
233function npmrcFields(text: string): Field[] {
234 const out: Field[] = []
235 for (const line of text.split('\n')) {
236 const m = /^\s*([^=#;\s][^=]*?)\s*=\s*(.+?)\s*$/.exec(line)
237 if (m && /(?:^|:)(?:_authToken|_auth|_password|token)$/i.test(m[1]!) && m[2]!.length >= FIELD_MIN) {
238 const nth = out.filter((f) => f.field === m[1]).length
239 out.push({ field: m[1]!, value: unquote(m[2]!), read: { kind: 'npmrc', path: '', key: m[1]!, nth } })
240 }
241 }
242 return out
243}
244
245/**
246 * The secret fields of a credential file's text, by its format; nothing for
247 * one that does not parse. `path` (from $HOME) is the file each read names.
248 */
249export function credentialFields(format: Format, text: string, path = ''): Field[] {
250 return parseFields(format, text).map((f) => (f.read && 'path' in f.read ? { ...f, read: { ...f.read, path } } : f))
251}
252
253function parseFields(format: Format, text: string): Field[] {
254 try {
255 switch (format) {
256 case 'json':
257 return jsonFields(JSON.parse(text))
258 case 'gcloud': {
259 // A key file only: a service account's or an authorized user's.
260 const parsed = JSON.parse(text) as Record<string, unknown> | null
261 const kind = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed.type : undefined
262 return kind === 'service_account' || kind === 'authorized_user' ? jsonFields(parsed) : []
263 }
264 case 'yaml':
265 return yamlFields(text)
266 case 'toml':
267 return tomlFields(text)
268 case 'pgpass':
269 return pgpassFields(text)
270 case 'netrc':
271 return netrcFields(text)
272 case 'git-credentials':
273 return gitCredentialFields(text)
274 case 'npmrc':
275 return npmrcFields(text)
276 }
277 } catch {
278 return []
279 }
280}
281
282/**
283 * The name each credential file goes by in its handles: its basename, or its
284 * path from $HOME where two of the files share a basename (gcloud keeps an
285 * `adc.json` per account), so that no two files' fields share a label.
286 */
287export function credentialLabels(paths: readonly string[]): Map<string, string> {
288 const base = (path: string) => path.slice(path.lastIndexOf('/') + 1)
289 const count = new Map<string, number>()
290 for (const path of paths) count.set(base(path), (count.get(base(path)) ?? 0) + 1)
291 return new Map(paths.map((path) => [path, count.get(base(path))! > 1 ? path : base(path)]))
292}
293
294/** A stored value as the store reads it: exactly one trailing newline dropped (a file written by `echo`). */
295export const storeValue = (text: string) => (text.endsWith('\n') ? text.slice(0, -1) : text)
296
297// Claude Code cuts a slug at this length and adds a hash of the whole path.
298const SLUG_MAX = 200
299
300/**
301 * A project's path as Claude Code names its folder under ~/.claude/projects/:
302 * every character other than an ASCII letter or digit becomes '-', and a slug
303 * longer than 200 characters keeps its first 200 and gains '-' and a base-36
304 * hash of the path. `cua`'s store carries the same.
305 */
306export function projectSlug(path: string): string {
307 const slug = path.replace(/[^a-zA-Z0-9]/g, '-')
308 if (slug.length <= SLUG_MAX) return slug
309 let hash = 0
310 for (let i = 0; i < path.length; i++) hash = ((hash << 5) - hash + path.charCodeAt(i)) | 0
311 return `${slug.slice(0, SLUG_MAX)}-${Math.abs(hash).toString(36)}`
312}
313
314/**
315 * The project root from `git rev-parse --path-format=absolute
316 * --git-common-dir --show-toplevel`'s two lines: the main checkout's root
317 * (the parent of its `.git`, which every linked worktree shares), or the
318 * repository's top level where the common directory is no `.git` folder (a
319 * submodule's).
320 */
321export function rootFromGit(commonDir: string, topLevel: string): string {
322 return /\/\.git$/.test(commonDir) ? commonDir.slice(0, -'/.git'.length) || '/' : topLevel
323}
324hooks/mods/one-guard.tsx 36 lines1import type { EngineInterface } from 'claude-code'
2
3/**
4 * One guard per session. cua carries devcloud's secrets guard (./guard, a
5 * vendored copy); while devcloud's own guard is in the session's chain, it
6 * decides every handle and each hook of cua's copy passes the event straight
7 * on, since two guards in sequence would lose the encoding a handle names
8 * (`[secret:KEY~b64]` collapsed by the first). devcloud says its guard is there
9 * through its marker (Interfaces I9 of its design, ./guard/devcloud.d.ts): its
10 * loaded module answers the read itself, at version 0, and stores nothing, so
11 * the answer exists exactly while the module does, whichever plugin sits
12 * outside the other. Read at hook time, on every event, so cua's guard acts
13 * from the first event after devcloud is disabled and the plugins reloaded. A
14 * marker at any other version is a value the host keeps, which a devcloud
15 * before 0.5.0 stored and which outlives its module (doperpowers board #101):
16 * cua's guard acts. cua never writes or answers the marker, nor one of its
17 * own: nothing reads one.
18 */
19
20/** Exactly the marker devcloud answers: anything else leaves cua's guard acting. */
21export function isDevcloudMarker(value: unknown): boolean {
22 if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
23 const marker = value as Record<string, unknown>
24 return Object.keys(marker).length === 2 && marker.owner === 'devcloud' && marker.version === 1
25}
26
27/** Whether devcloud's guard holds this session now: its loaded module's answer, at version 0; a read that fails says no. */
28export async function devcloudGuards($: EngineInterface): Promise<boolean> {
29 try {
30 const { value, version } = await $.state.get({ plugin: 'devcloud', key: 'secrets-guard' })
31 return version === 0 && isDevcloudMarker(value)
32 } catch {
33 return false
34 }
35}
36hooks/mods/guard/secrets-detect.tsx 151 lines1// Vendored from SSFSKIM/doperpowers devcloud/hooks/mods/secrets-detect.tsx at 823f772f634003278886446940fe9fb6b679e254
2// (devcloud 0.5.0); the adaptations and the resync are in hooks/mods/guard/VENDORED.md.
3
4/**
5 * The detector: where a text holds a token-shaped string. Pure, so the tests
6 * pin it without a session. gitleaks' rule set is the reference for the
7 * prefixes; a bare run of hex or base64 with neither a prefix nor a
8 * secret-named assignment is never a span, or commit hashes and checksums
9 * would drown the transcript.
10 */
11
12export type Span = { start: number; end: number; kind: string }
13
14/**
15 * The spans, taken in the order given, each kept unless it overlaps one
16 * already kept; returned in text order. Linear in the spans' total length.
17 */
18export function keepFirst<T extends { start: number; end: number }>(spans: readonly T[], length: number): T[] {
19 if (spans.length === 0) return []
20 const taken = new Uint8Array(length)
21 const kept: T[] = []
22 for (const span of spans) {
23 let isFree = true
24 for (let i = span.start; i < span.end && isFree; i++) isFree = taken[i] === 0
25 if (!isFree) continue
26 taken.fill(1, span.start, span.end)
27 kept.push(span)
28 }
29 return kept.sort((a, b) => a.start - b.start)
30}
31
32// In order: the first rule to claim a character keeps it. Each pattern opens
33// with its literal prefix, which lets the engine skip ahead to it; that the
34// token does not start inside a longer word (`risk-…` holds no `sk-` token) is
35// checked after a match (NOT_LEAD), as a lookbehind would cost a test at every
36// position of the text.
37const RULES: readonly { kind: string; pattern: RegExp }[] = [
38 // PEM blocks, raw or JSON-escaped (`\n` as two characters, as a key file prints).
39 {
40 kind: 'pem',
41 pattern: /-----BEGIN ((?:[A-Z0-9]+ )*)PRIVATE KEY( BLOCK)?-----[\s\S]*?-----END \1PRIVATE KEY\2-----/g,
42 },
43 { kind: 'anthropic', pattern: /sk-ant-[A-Za-z0-9_-]{20,}/g },
44 { kind: 'openrouter', pattern: /sk-or-v1-[A-Za-z0-9]{20,}/g },
45 { kind: 'openai', pattern: /sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}/g },
46 { kind: 'github-pat', pattern: /ghp_[A-Za-z0-9]{30,}/g },
47 { kind: 'github-oauth', pattern: /gho_[A-Za-z0-9]{30,}/g },
48 { kind: 'github-app-token', pattern: /gh[us]_[A-Za-z0-9]{30,}/g },
49 { kind: 'github-refresh-token', pattern: /ghr_[A-Za-z0-9]{30,}/g },
50 { kind: 'github-fine-grained-pat', pattern: /github_pat_[A-Za-z0-9_]{22,}/g },
51 { kind: 'tailscale', pattern: /tskey-[A-Za-z0-9-]{16,}/g },
52 { kind: 'slack', pattern: /xox[abprs]-[A-Za-z0-9-]{10,}/g },
53 { kind: 'aws-access-key', pattern: /A(?:KIA|SIA)[0-9A-Z]{16}(?![0-9A-Za-z])/g },
54 { kind: 'gitlab-pat', pattern: /glpat-[A-Za-z0-9_-]{20,}/g },
55 { kind: 'huggingface', pattern: /hf_[A-Za-z0-9]{30,}/g },
56 { kind: 'gcp-api-key', pattern: /AIza[0-9A-Za-z_-]{35}/g },
57 // Google OAuth: an access token, bare as `gcloud auth print-access-token`
58 // prints it (a service account's carries dotted segments, `ya29.c.…`), and
59 // a refresh token. A sentence's closing dot is not taken.
60 { kind: 'google-access-token', pattern: /ya29\.(?:[0-9A-Za-z_-]+\.)*[0-9A-Za-z_-]{20,}/g },
61 { kind: 'google-refresh-token', pattern: /1\/\/0[0-9A-Za-z_-]{40,}/g },
62]
63const NOT_LEAD = /[A-Za-z0-9_]/
64
65// A name that says secret: one of these words as a whole part of the name,
66// parts split at `_`, `-`, `.` and a camelCase boundary (`apiKey`).
67const SECRET_WORDS = new Set(['token', 'tokens', 'secret', 'secrets', 'password', 'passwords', 'passwd', 'apikey', 'bearer', 'credential', 'credentials'])
68const SECRET_PAIRS = new Set(['api key', 'private key'])
69
70export function isSecretName(name: string): boolean {
71 const parts = name
72 .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
73 .toLowerCase()
74 .split(/[_.-]+/)
75 .filter(Boolean)
76 return parts.some((part, i) => SECRET_WORDS.has(part) || SECRET_PAIRS.has(`${part} ${parts[i + 1]}`))
77}
78
79// `NAME = value`, `NAME: value`, `"name": "value"`; and `Bearer value`. The
80// value stops at whitespace, a quote, or punctuation no token carries. A name
81// right after `[` is a handle's (`[secret:…]`), never an assignment.
82const VALUE = `(["']?)([^\\s"'\`,;:{}()<>[\\]\\\\]+)`
83const ASSIGNMENT = new RegExp(`(?<![A-Za-z0-9_[])(["']?)([A-Za-z_][A-Za-z0-9_.-]*)\\1[ \\t]*(?::=|=|:)[ \\t]*${VALUE}`, 'g')
84const BEARER = new RegExp(`(?<![A-Za-z0-9_])(Bearer)[ \\t]+${VALUE}`, 'g')
85
86const VALUE_MIN = 16
87const ENTROPY_MIN = 3.5
88// A reference, a path or an address: what names a value rather than holds one.
89const NOT_A_VALUE = /^(?:\$|%|~|\.{0,2}\/|[a-z][a-z0-9+.-]*:\/\/)/i
90// Unquoted, an expression in code rather than a literal: a dotted name
91// (`process.env.API_KEY`, `credentials.password`) or a bare identifier with no
92// digit (`userSuppliedPassword`); a credential almost always carries a digit.
93const REFERENCE = /^[A-Za-z_$][A-Za-z_$]*(?:\.[A-Za-z_$][A-Za-z_$]*)*$/
94
95/** Shannon entropy of the string's characters, in bits per character. */
96export function entropy(text: string): number {
97 const counts = new Map<string, number>()
98 for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1)
99 let bits = 0
100 for (const n of counts.values()) {
101 const p = n / text.length
102 bits -= p * Math.log2(p)
103 }
104 return bits
105}
106
107// A line that may hold a secret-named assignment: only these are searched for
108// one, so a long output of ordinary lines costs one quick test each.
109// The separators match `isSecretName`'s split (`_`, `-`, `.`, or none).
110const MAY_ASSIGN = /token|secret|passw|api[_.-]?key|private[_.-]?key|bearer|credential/i
111
112function assignments(text: string): Span[] {
113 const spans: Span[] = []
114 let at = 0
115 for (const line of text.split('\n')) {
116 if (MAY_ASSIGN.test(line)) {
117 for (const [pattern, nameAt, valueAt] of [[ASSIGNMENT, 2, 4], [BEARER, 1, 3]] as const) {
118 for (const m of line.matchAll(pattern)) {
119 const value = m[valueAt] ?? ''
120 if (!isSecretName(m[nameAt] ?? '')) continue
121 if (value.length < VALUE_MIN || NOT_A_VALUE.test(value) || entropy(value) < ENTROPY_MIN) continue
122 // Unquoted and followed by a call or an index, or shaped as a name: code.
123 const after = line[(m.index ?? 0) + m[0].length]
124 if (!m[valueAt - 1] && (after === '(' || after === '[' || REFERENCE.test(value))) continue
125 const end = at + (m.index ?? 0) + m[0].length
126 spans.push({ start: end - value.length, end, kind: 'assignment' })
127 }
128 }
129 }
130 at += line.length + 1
131 }
132 return spans
133}
134
135/**
136 * The token-shaped strings in `text`, in order and never overlapping: each
137 * span the bytes a handle stands for, `kind` the rule that found it.
138 */
139export function detect(text: string): Span[] {
140 const found: Span[] = []
141 for (const { kind, pattern } of RULES) {
142 for (const m of text.matchAll(pattern)) {
143 const start = m.index ?? 0
144 if (start > 0 && NOT_LEAD.test(text[start - 1]!)) continue
145 found.push({ start, end: start + m[0].length, kind })
146 }
147 }
148 found.push(...assignments(text))
149 return keepFirst(found, text.length)
150}
151hooks/mods/guard/secrets-shell.tsx 92 lines1// Vendored from SSFSKIM/doperpowers devcloud/hooks/mods/secrets-shell.tsx at 823f772f634003278886446940fe9fb6b679e254
2// (devcloud 0.5.0); the adaptations and the resync are in hooks/mods/guard/VENDORED.md.
3
4/**
5 * Which handles go back into a Bash command as their bytes. Only what can be
6 * shown safe (Decision Log, 2026-10-17): an inert value, standing in a plain
7 * string or a plain word, in a command free of the constructs that read words
8 * again. Nothing is ever quoted: a value that would need quoting is not
9 * restored, and the result says how to read it in the command instead. Pure;
10 * proved by executing restored commands under bash and zsh
11 * (tests/mods/shell-exec.ts).
12 */
13
14/**
15 * Inert: non-empty, of letters, digits and `_ . / + : @ -` (no expansion,
16 * glob, comment, history, tilde, brace or extended-glob meaning in either
17 * shell), with `=` and `%` past the first character (zsh expands a leading
18 * `=cmd`; a leading `%` names a job). An `=` right after `=` or `:` starts an
19 * `=cmd` expansion under zsh's MAGIC_EQUAL_SUBST, so it may only be part of a
20 * trailing run of `=` and `:` (base64 padding), which zsh leaves alone.
21 */
22const ALPHABET = /^[A-Za-z0-9_./+:@-][A-Za-z0-9_./+:@=%-]*$/
23const EQUALS_INSIDE = /[=:]=+(?=.*[^=:])/
24
25export const isInert = (value: string) => ALPHABET.test(value) && !EQUALS_INSIDE.test(value)
26
27// What reads a word again: heredocs and here-strings, backticks, arithmetic
28// (`((`, `$[`, `[[`, `let`, `integer`, `float`), parameter expansion (`${`),
29// any declaration with a flag (integer, float, nameref), line continuations.
30const REREADS =
31 /<<|`|\(\(|\$\[|\$\{|\[\[|\\\n|(?:^|[\s;&|(])(?:let|integer|float)\s|(?:^|[\s;&|(])(?:declare|typeset|local|export|readonly)\s+-/
32// A comment: `#` where a word starts.
33const COMMENT = /(?:^|[\s;&|()])#/
34
35/** Whether the command holds none of the constructs that read a word again. */
36export const isPlainCommand = (command: string) => !REREADS.test(command) && !COMMENT.test(command)
37
38// Where words end, outside quotes.
39const OPERATOR = /[\s;|&()<>]/
40// What else a plain word may hold beside the handle (the inert alphabet).
41const PLAIN_WORD = /^[A-Za-z0-9_./+:@=%-]*$/
42
43/**
44 * Whether a handle at `at` (`length` long), whose value is `value`, stands in
45 * a plain string or word, so that its bytes, put there as they are, reach the
46 * command unchanged: inside a `'…'` string; inside a `"…"` string that holds
47 * no `$`, backtick, `\` or `!` besides; or in an unquoted word (between
48 * whitespace and `; | & ( ) < >`) of the inert alphabet throughout, which,
49 * restored, is inert as a whole (no leading `=` or `%`, no `==` or `:=`), and
50 * which neither follows a redirection nor touches a `(` that opens a glob,
51 * a qualifier or a function.
52 */
53export function isPlainPosition(command: string, at: number, length: number, value: string): boolean {
54 // Which quoted string, if any, holds the handle.
55 for (let i = 0; i < command.length; ) {
56 const c = command[i]!
57 if (c === '\\') {
58 i += 2
59 continue
60 }
61 if (c === "'" || c === '"') {
62 let end = i + 1
63 while (end < command.length && command[end] !== c) end += c === '"' && command[end] === '\\' ? 2 : 1
64 if (end >= command.length) return false
65 if (at > i && at + length <= end) {
66 if (c === "'") return true
67 const rest = command.slice(i + 1, at) + command.slice(at + length, end)
68 return !/[$`\\!]/.test(rest)
69 }
70 if (at < end && at + length > i) return false
71 i = end + 1
72 continue
73 }
74 if (i >= at + length) break
75 i++
76 }
77 // An unquoted word: from the operator before to the operator after.
78 let start = at
79 while (start > 0 && !OPERATOR.test(command[start - 1]!)) start--
80 let end = at + length
81 while (end < command.length && !OPERATOR.test(command[end]!)) end++
82 const before = command.slice(start, at)
83 const after = command.slice(at + length, end)
84 if (!PLAIN_WORD.test(before) || !PLAIN_WORD.test(after) || !isInert(before + value + after)) return false
85 // Not the target of a redirection (`>`, `<`, `>&`, `<&`, `&>`, `>|`).
86 if (/[<>]\s*[&|]?\s*$/.test(command.slice(0, start))) return false
87 // Not touching a `(` but one that opens a subshell or a substitution.
88 if (command[end] === '(') return false
89 if (command[start - 1] === '(' && !/(?:^|[\s;&|($=])$/.test(command.slice(0, start - 1))) return false
90 return true
91}
92