Holds gcloud and gsutil commands that would create, change or delete cloud resources, shows the account, project, location and the current state of the…

Holds a gcloud or gsutil command that would create, change or delete cloud resources before Claude runs it, shows which account and project it would hit and what the targets look like right now, and opens a pane with Proceed and Cancel. Cancel refuses the command and tells Claude why, so it knows nothing ran. Read-only commands (describe, list, ls, get-iam-policy, …) and local ones (auth login, components update) pass straight through.
The hold-and-ask pattern follows Anthropic's blast-radius mod in this repo; the code is written fresh (MIT) and aimed at Google Cloud.
╭─ ⚠ gcloud-guard · destructive ──────────────────────────────────────────────╮
│ delete compute instances web-1, web-2 │
│ Command │
│ │ gcloud config list && │
│ ▶ gcloud compute instances delete web-1 web-2 --zone us-central1-a │
│ Account dev@example.com │
│ Project demo-proj ← from gcloud config · Config default │
│ Location us-central1-a │
│ │
│ web-1 · RUNNING · us-central1-a · e2-small · created 2026-09-01 · 2 disks │
│ web-2 · TERMINATED · us-central1-a · e2-medium · created 2026-09-03 │
│ web-2: deletion protection is on; a delete fails unless it is turned off │
│ │
│ 1: Proceed 2: Cancel Claude is waiting on your answer │
╰─────────────────────────────────────────────────────────────────────────────╯
The command is shown one segment per row, split at &&, ||, ;, | and newlines, with the operator at the end of each row. The segment that would change something is marked ▶: gcloud / gsutil and the verb in red, alpha / beta in magenta, --quiet, --force and -r style flags in red, other flags dim, targets in yellow; the other segments are dim. A chain longer than eight segments folds the quiet ones around it.
The command line is split on &&, ||, ;, | and newlines; VAR=value, sudo, env, nohup, time, nice and ( … ) wrappers are stripped; the first gcloud (or gsutil) segment that would change something decides. The first word after gcloud is the command group, the first table word after it is the verb.
| Severity | gcloud verbs | gsutil |
|---|---|---|
| destructive | delete, remove, destroy, purge, rm, rb, reset, abandon, cancel, revoke, wipe, detach, rollback, unregister, unbind, uninstall, terminate, and the prefixes remove-*, delete-*, detach-*, revoke-*, unregister-*, unbind-*, drop-*, purge-*, destroy-*; remove-iam-policy-binding | rm, rb; notification delete, … clear |
| mutating | update, patch, set, enable, disable, start, stop, suspend, resume, resize, move, rename, promote, failover, restart, reboot, attach, migrate, apply, replace, restore, import, export, upload, rotate, activate, deactivate, deploy, submit, execute, run, trigger, undelete, rsync, cp, mv, and the prefixes update-*, set-*, add-*, attach-*, start-*, stop-*, enable-*, disable-*, restore-*, resize-*, rotate-*, …; add-iam-policy-binding, set-iam-policy; config set / unset / configurations activate (see below) | cp, mv, rsync, setmeta, compose, rewrite; iam ch, acl set, defacl set, lifecycle set, versioning set, cors set, label set, retention set, … |
| create | create, add, insert, clone, snapshot, publish, register, reserve, provision, and create-* | mb; notification create |
Special cases:
gcloud projects delete, organizations delete, folders delete are destructive with a scope badge; the pane shows the project's state, when it was created and how many services are enabled, and reminds you of the 30-day recovery window.deploy (run deploy, app deploy, functions deploy): mutating, labelled as a deploy, since it creates or replaces a revision. builds submit: mutating, labelled as a build.set-iam-policy the number of bindings in the policy file is compared with the current policy.gcloud storage rm/mv/rsync, gsutil rm/rb/mv/rsync): the objects under each source URL are counted with a read-only ls -r (capped at 2000); rsync -d / --delete-unmatched-destination-objects gets a warning.gcloud config set (and unset, configurations activate): held as a local-config change, because switching the project or account silently changes what every later command hits. The pane shows the current value. Turn this off with hold_config_set.gcloud compute instances perform-rollout …): held as mutating with a note, to be safe. An unknown verb under an unknown group is not held.Never held: describe, list, get, get-iam-policy, get-value, get-credentials, ls, cat, stat, du, logs, read, tail, print-access-token, ssh, scp, wait, test-iam-permissions, the list-* / describe-* / get-* / print-* prefixes; the whole auth, components, help, info, version, emulators and init groups; config list / get-value; container clusters get-credentials (it only writes your kubeconfig); compute ssh / scp (a remote shell is not a resource change; see Limits).
--project or the gcloud config) and the active configuration; the location (--zone / --region / --location, or (default)); an alpha/beta badge; a yellow warning when --quiet is given, since gcloud then skips its own confirmation.describe --format=json: name, status, zone/region, machine type, database version and tier, size, node count, creation date, labels, attached disks and how many are auto-delete, IAM bindings. Deletion protection raises a note. A target that is not found raises a note too: the delete would fail, or hit something else than you think.--machine-type, --size, --tier, --num-nodes, --image, --memory, --cpu, …).gcloud is not on PATH or does not answer, the pane says so and the command is still held.At all times, not only while holding, a dim line above the prompt, in its own rounded frame, says which project the session is pointed at, so a gcloud … delete is never a surprise about where:
☁ gcloud · project side-project-staging · account dev@example.com · config default · GKE my-cluster (us-central1)
Where the values come from (files and environment variables only; no gcloud process is started for this line):
| Part | Source |
|---|---|
| config directory | $CLOUDSDK_CONFIG, else ~/.config/gcloud |
| configuration | $CLOUDSDK_ACTIVE_CONFIG_NAME, else the active_config file, else default |
| project, account, zone, region | $CLOUDSDK_CORE_PROJECT, $CLOUDSDK_CORE_ACCOUNT, $CLOUDSDK_COMPUTE_ZONE, $CLOUDSDK_COMPUTE_REGION, else configurations/config_<name> ([core] project = …, [compute] zone = …) |
| GKE cluster | the current-context: line of $KUBECONFIG (colon-separated; the first file with a current context wins), else ~/.kube/config; a gke_<project>_<location>_<cluster> context is shown as GKE <cluster> (<location>) |
A project that comes from CLOUDSDK_CORE_PROJECT is marked ← CLOUDSDK_CORE_PROJECT. Parts that are unknown are left out; when nothing is known (no gcloud configuration at all) the line is not drawn. A kubectl context that is not a GKE cluster (docker-desktop, an EKS ARN) is shown as k8s <name> only with show_other_contexts on.
The line is re-read at session start, every 5 seconds when one of those files' modification times changed (a cheap stat, no read otherwise), after a held gcloud / gsutil command proceeds, and after any Bash command that mentions gcloud config, gcloud auth, gcloud container clusters get-credentials, kubectl config use-context or kubectx. While a command is held, the hold report replaces the line; the hold pane also shows the GKE cluster, in yellow when the cluster's project differs from the project the command would hit.
/gcloud-guard prints the whole snapshot (config directory, configuration, project and its source, account, zone/region, kubeconfig path, current context, the parsed GKE fields) and the hold setting; /gcloud-guard off / on hide and show the line for the session; /gcloud-guard refresh re-reads the files now.
It works as soon as it is installed. The only command is /gcloud-guard (above).
1 for Proceed or 2 for Cancel. Prefer the digits.Backgrounding after the current tool finishes…. To use the arrows, click the pane first, or press ctrl+x then tab to hand it the keyboard.| Option | Default | Meaning |
|---|---|---|
language | auto | Language of the pane, the toast and the refusal: auto (from LC_ALL, then LC_MESSAGES, then LANG: zh* gives Traditional Chinese, ja* Japanese, anything else English), en, zh-TW or ja. |
hold | all | destructive holds delete-class commands only; mutating holds delete- and update-class; all also holds create-class. |
include_gsutil | true | Also watch gsutil. |
hold_config_set | true | Hold gcloud config set / unset / configurations activate. |
describe_timeout_seconds | 15 | How long each read-only lookup may take before it is reported as failed (3 to 60). |
show_context | true | Draw the context line above the prompt. |
show_other_contexts | false | Also show the current kubectl context when it is not a GKE cluster. |
band_style | box | How the context line is framed: box (its own rounded frame, dim normally and yellow when the GKE context belongs to a project other than gcloud's), rule (a thin line beneath it), plain (text only). The hold report always draws its own box. |
Set them with /plugin configure gcloud-guard@cockpit, or --config hold=destructive at install. Command words in the pane (delete, compute instances, …) are never translated. Every refusal ends with the same English line, (gcloud-guard: the user did not approve this command; do not retry unless asked.), so Claude reads a Japanese or Chinese refusal as a refusal, not as a transient error.
band_style switches to a rule or plain text). While it holds a command and the pane cannot be placed, the hold report takes over the band; the other frames return once you answer.gcloud compute instances delete x && rm -rf build is held by both, one after the other.$.process.run), never through a shell: a target name, a URL or a flag value is one argv element, so nothing in it runs as shell. The lookups are config get-value, config configurations list, describe, get-iam-policy, projects describe, services list, storage ls -r / gsutil ls -r.active_config, configurations/config_<name>) and the current-context: line of your kubeconfig, and stats them every 5 seconds. It reads the policy file named on set-iam-policy to count its bindings. It writes no files, sends nothing anywhere and calls no model.get / list permissions; where they fail the pane says so and the command is still held.claude plugin validate ./plugins/gcloud-guard
Result (v0.1.0):
hooks: session.start, command.run{command=gcloud-guard}, tool.call{tool=Bash},
ui.render{component=Pane, requestId=gcloud-guard}, ui.render{component=AbovePrompt}
calls: $.clock.every, $.clock.now, $.command.register, $.env.get, $.fs.read, $.fs.stat,
$.process.run, $.state.get, $.state.set, $.ui.close, $.ui.invalidate, $.ui.open,
$.ui.resolve, $.ui.toast
env reads: CLOUDSDK_ACTIVE_CONFIG_NAME, CLOUDSDK_COMPUTE_REGION, CLOUDSDK_COMPUTE_ZONE,
CLOUDSDK_CONFIG, CLOUDSDK_CORE_ACCOUNT, CLOUDSDK_CORE_PROJECT, HOME, KUBECONFIG,
LANG, LC_ALL, LC_MESSAGES · env writes: nothing
$.process.run runs the read-only lookups above and the 0.25-second sleep that paces the hold; $.fs.read and $.fs.stat read the gcloud and kube config files for the context line and a set-iam-policy file; $.clock.every is the 5-second file check; no network of its own, no model calls.
$(…), aliases, eval, bash -c "…", xargs gcloud, scripts and Makefiles that call gcloud, terraform, kubectl, bq, the Python client libraries and the Console are not covered.compute ssh is not held, although a command run on the VM can change anything there.--flag value is read as a value unless the flag is a known boolean (--quiet, --async, --force, --to-latest, --no-*, --enable-*, …). A boolean flag it does not know, followed by a resource name, swallows that name from the target list; the command is still held.perform-*, trigger-*, …) under a known group; anything else is let through. gcloud grows faster than this table.describe needs permissions and time: up to 5 targets, each with the configured timeout, plus the config lookups. On a slow network the pane can take a few seconds to appear; the command is held from the start regardless.2000+; gsutil ls -r on a huge bucket may hit the timeout, which is reported as a note.--project on a later command, a gcloud config set in another shell before the next 5-second check, or a kubeconfig merged from several files with no current-context: in the first one can make the line lag or differ. /gcloud-guard refresh re-reads at once.gcloud config set was held, the pane showed the account and project, and Proceed ran it.claude --plugin-dir ./plugins/gcloud-guard # load once
claude plugin validate ./plugins/gcloud-guard
claude plugin test ./plugins/gcloud-guard # classifier table, lookups, the hold with a fake gcloud
The classifier and the report text live in hooks/logic.ts (pure), the strings in hooks/i18n.ts, the hooks and the drawing in hooks/register.tsx. If blast-radius is installed while you work on this mod, write test files with the editor rather than a heredoc: a literal rm -rf in a Bash command line is held by it.
hooks/register.tsx 740 lines1// gcloud-guard: holds a gcloud / gsutil command that would create, change or delete
2// cloud resources, shows what it would touch, and waits for Proceed or Cancel.
3//
4// - tool.call (Bash): classify the command line; when it is held, look up the account,
5// project and the targets' current state with read-only gcloud calls, open a pane
6// (or draw in the band when the terminal is too narrow) and hold the call.
7// - Holding: a hook has 10 s of its own time, but time spent inside a `$` call is free,
8// so the hold loop waits on `$.process.run(["sleep", "0.25"])` until a button sets the
9// decision. One hold at a time; a second risky call waits for the first.
10// - Lookups pass every value as an argv element, never as shell source. No files are
11// written, nothing is sent anywhere, no model is called.
12// The hold-and-ask pattern follows Anthropic's blast-radius mod in this repo.
13
14import { atom, read, update } from 'claude-code'
15import type { Register } from 'claude-code'
16
17import type { GcloudContext, HeldView, Report, ReportContext, Risk } from '../types'
18import { DEFAULT_LANG, resolveLang, t } from './i18n'
19import type { Lang } from './i18n'
20import {
21 CONTEXT_TICK_MS,
22 HOLD_LIMIT_MS,
23 MAX_LINES,
24 MAX_TARGETS_DESCRIBED,
25 PANE,
26 POLL_SECONDS,
27 buildContext,
28 classify,
29 configGetArgv,
30 contextLine,
31 contextText,
32 countObjects,
33 currentContextOf,
34 denyText,
35 describeArgv,
36 emptyContext,
37 gcloudConfigDir,
38 getIamPolicyArgv,
39 headline,
40 isHeld,
41 isNotFound,
42 isRsyncDelete,
43 keyFlagsLine,
44 listObjectsArgv,
45 commandRows,
46 paneRows,
47 riskyWords,
48 projectDescribeArgv,
49 readSettings,
50 servicesListArgv,
51 severityLabel,
52 splitKubeconfigList,
53 storageUrls,
54 kubeProjectMismatch,
55 summarizeDescribe,
56 touchesContext,
57 truncate,
58} from './logic'
59import type { BandStyle, ContextEnv, Settings } from './logic'
60
61const langState = atom({ plugin: 'gcloud-guard', key: 'lang' } as const, DEFAULT_LANG)
62const heldState = atom({ plugin: 'gcloud-guard', key: 'held' } as const, null)
63const contextState = atom({ plugin: 'gcloud-guard', key: 'context' } as const, null)
64const isBandHidden = atom({ plugin: 'gcloud-guard', key: 'isBandHidden' } as const, false)
65
66type Decision = 'proceed' | 'cancel' | 'timeout' | 'interrupted' | 'error'
67
68/** The hold in progress: the view the render hooks draw plus the decision the buttons set. */
69type Hold = { view: HeldView; decision: Decision | null }
70
71// Module state: a hot reload mid-hold loses it, and the old hook then refuses the command.
72let settings: Settings = readSettings(undefined)
73let lang: Lang = DEFAULT_LANG
74let held: Hold | null = null
75let holdSeq = 0
76/** The mtimes of the files the context line was last read from, keyed by path; the timer re-reads when one moved. */
77let watched: Record<string, number> = {}
78let refreshing = false
79
80type Run = { exitCode: number; stdout: string; stderr: string }
81
82function toast($: any, text: string): void {
83 try {
84 $.ui.toast(text)
85 } catch {}
86}
87
88async function resolveLanguage($: any): Promise<Lang> {
89 const env: { LC_ALL?: string; LC_MESSAGES?: string; LANG?: string } = {}
90 try {
91 env.LC_ALL = await $.env.get('LC_ALL')
92 env.LC_MESSAGES = await $.env.get('LC_MESSAGES')
93 env.LANG = await $.env.get('LANG')
94 } catch {}
95 return resolveLang(settings.language, env)
96}
97
98// ── The context line: read from the config files, no process ───────────────
99
100async function contextEnv($: any): Promise<ContextEnv> {
101 const env: ContextEnv = {}
102 try {
103 env.CLOUDSDK_CONFIG = await $.env.get('CLOUDSDK_CONFIG')
104 env.HOME = await $.env.get('HOME')
105 env.CLOUDSDK_CORE_PROJECT = await $.env.get('CLOUDSDK_CORE_PROJECT')
106 env.CLOUDSDK_CORE_ACCOUNT = await $.env.get('CLOUDSDK_CORE_ACCOUNT')
107 env.CLOUDSDK_ACTIVE_CONFIG_NAME = await $.env.get('CLOUDSDK_ACTIVE_CONFIG_NAME')
108 env.CLOUDSDK_COMPUTE_ZONE = await $.env.get('CLOUDSDK_COMPUTE_ZONE')
109 env.CLOUDSDK_COMPUTE_REGION = await $.env.get('CLOUDSDK_COMPUTE_REGION')
110 } catch {}
111 return env
112}
113
114async function kubeconfigList($: any, home: string | null): Promise<string[]> {
115 let value: string | undefined
116 try {
117 value = await $.env.get('KUBECONFIG')
118 } catch {}
119 return splitKubeconfigList(value, home)
120}
121
122/** A file's text, or null when it is missing or unreadable. */
123async function readText($: any, path: string): Promise<string | null> {
124 try {
125 const text = await $.fs.read(path)
126 return typeof text === 'string' ? text : null
127 } catch {
128 return null
129 }
130}
131
132async function mtimeOf($: any, path: string): Promise<number> {
133 try {
134 const st = await $.fs.stat(path)
135 return Number(st?.mtimeMs ?? 0)
136 } catch {
137 return 0
138 }
139}
140
141/** Re-reads the gcloud and kube config files and writes the snapshot; remembers the files' mtimes for the timer. */
142async function refreshContext($: any): Promise<GcloudContext | null> {
143 if (refreshing) return null
144 refreshing = true
145 try {
146 const env = await contextEnv($)
147 const home = (env.HOME ?? '').trim() || null
148 const configDir = gcloudConfigDir(env)
149 const next: Record<string, number> = {}
150 let activeConfigText: string | null = null
151 let configText: string | null = null
152 if (configDir) {
153 const activePath = `${configDir}/active_config`
154 activeConfigText = await readText($, activePath)
155 next[activePath] = await mtimeOf($, activePath)
156 const name = (env.CLOUDSDK_ACTIVE_CONFIG_NAME ?? '').trim() || (activeConfigText ?? '').trim() || 'default'
157 const configPath = `${configDir}/configurations/config_${name}`
158 configText = await readText($, configPath)
159 next[configPath] = await mtimeOf($, configPath)
160 }
161 let kubeconfigPath: string | null = null
162 let kubeconfigText: string | null = null
163 for (const path of await kubeconfigList($, home)) {
164 const text = await readText($, path)
165 next[path] = await mtimeOf($, path)
166 if (text !== null && currentContextOf(text) !== null) {
167 kubeconfigPath = path
168 kubeconfigText = text
169 break
170 }
171 if (kubeconfigPath === null && text !== null) kubeconfigPath = path
172 }
173 watched = next
174 const snapshot = buildContext({ env, configDir, activeConfigText, configText, kubeconfigPath, kubeconfigText, now: await $.clock.now() })
175 const known = snapshot.project || snapshot.account || snapshot.kube
176 const value = known ? snapshot : null
177 await update($, contextState, () => value)
178 return value
179 } catch {
180 return null
181 } finally {
182 refreshing = false
183 }
184}
185
186/** The timer: re-read only when one of the watched files moved. */
187async function onContextTick($: any): Promise<void> {
188 if (refreshing) return
189 for (const [path, mtime] of Object.entries(watched)) {
190 if ((await mtimeOf($, path)) !== mtime) {
191 await refreshContext($)
192 return
193 }
194 }
195 // Nothing watched yet (no config dir found at start): look again for the files
196 if (!Object.keys(watched).length) await refreshContext($)
197}
198
199/** Runs a read-only lookup; never throws. `null` when the process could not start (gcloud missing). */
200async function lookup($: any, argv: string[]): Promise<Run | null> {
201 try {
202 const r = await $.process.run(argv, { timeoutMs: settings.describeTimeoutMs })
203 return { exitCode: Number(r.exitCode), stdout: String(r.stdout ?? ''), stderr: String(r.stderr ?? '') }
204 } catch {
205 return null
206 }
207}
208
209function lastLine(s: string): string {
210 return truncate(s.trim().split('\n').pop() ?? '', 80)
211}
212
213/** Account, project (and where it came from) and the active configuration. */
214async function readContext($: any, risk: Risk): Promise<{ context: ReportContext; gcloudMissing: boolean; failed: boolean }> {
215 const context = emptyContext(risk)
216 let gcloudMissing = false
217 let failed = false
218 if (risk.tool === 'gsutil' && risk.flags.project && risk.flags.account) return { context, gcloudMissing, failed }
219 if (!context.account) {
220 const r = await lookup($, configGetArgv('account', risk.flags))
221 if (r === null) gcloudMissing = true
222 else if (r.exitCode === 0 && r.stdout.trim()) context.account = r.stdout.trim()
223 else failed = true
224 }
225 if (!context.project && !gcloudMissing) {
226 const r = await lookup($, configGetArgv('project', risk.flags))
227 if (r === null) gcloudMissing = true
228 else if (r.exitCode === 0 && r.stdout.trim()) {
229 context.project = r.stdout.trim()
230 context.projectSource = 'config'
231 } else failed = true
232 }
233 if (!context.configuration && !gcloudMissing) {
234 const r = await lookup($, ['gcloud', 'config', 'configurations', 'list', '--filter=is_active=true', '--format=value(name)'])
235 if (r !== null && r.exitCode === 0 && r.stdout.trim()) context.configuration = r.stdout.trim().split('\n')[0] ?? null
236 }
237 return { context, gcloudMissing, failed }
238}
239
240function pushLine(report: Report, line: string): void {
241 if (report.lines.length < MAX_LINES) report.lines.push(truncate(line, 160))
242}
243
244/** Looks up what the command would touch. Never throws: a failed lookup becomes a note. */
245async function measure($: any, risk: Risk): Promise<Report> {
246 const { context, gcloudMissing, failed } = await readContext($, risk)
247 const report: Report = { severity: risk.severity, headline: headline(lang, risk), context, lines: [], notes: [] }
248 if (gcloudMissing) {
249 report.notes.push(t(lang, 'note.noGcloud'))
250 return report
251 }
252 if (failed) report.notes.push(t(lang, 'note.contextFailed'))
253 if (risk.unknownVerb) report.notes.push(t(lang, 'note.unknownVerb'))
254
255 // A whole project, organization or folder
256 if (risk.scope) {
257 const id = risk.targets[0]
258 if (id && risk.scope === 'project') {
259 const d = await lookup($, projectDescribeArgv(id, risk.flags))
260 if (d && d.exitCode === 0) {
261 try {
262 const o = JSON.parse(d.stdout) as Record<string, unknown>
263 pushLine(report, [String(o.name ?? id), String(o.lifecycleState ?? o.state ?? ''), o.createTime ? t(lang, 'line.created', { date: String(o.createTime).slice(0, 10) }) : ''].filter(Boolean).join(' · '))
264 } catch {}
265 } else if (d) report.notes.push(isNotFound(d.stderr) ? t(lang, 'note.notFound', { target: id }) : t(lang, 'note.describeFailed', { target: id, err: lastLine(d.stderr) }))
266 const s = await lookup($, servicesListArgv(id, risk.flags))
267 if (s && s.exitCode === 0) pushLine(report, t(lang, 'line.servicesEnabled', { n: s.stdout.split('\n').filter(l => l.trim()).length }))
268 report.notes.push(t(lang, 'note.projectRecovery'))
269 }
270 return report
271 }
272
273 // gcloud config set: the current value of the property
274 if (risk.kind === 'local-config') {
275 const property = risk.targets[0]
276 if (property && risk.verb !== 'activate') {
277 const cur = await lookup($, configGetArgv(property, risk.flags))
278 const current = cur && cur.exitCode === 0 && cur.stdout.trim() ? cur.stdout.trim() : t(lang, 'value.unknown')
279 report.headline = headline(lang, risk, current)
280 pushLine(report, t(lang, 'line.property', { property, current, value: risk.verb === 'unset' ? '(unset)' : (risk.targets[1] ?? '?') }))
281 }
282 return report
283 }
284
285 // Storage: count the objects under the sources
286 if (risk.kind === 'storage') {
287 if (isRsyncDelete(risk)) report.notes.push(t(lang, 'note.rsyncDelete'))
288 if (risk.verb === 'rm' || risk.verb === 'rb' || risk.verb === 'mv' || risk.verb === 'rsync') {
289 for (const url of storageUrls(risk).slice(0, MAX_TARGETS_DESCRIBED)) {
290 const r = await lookup($, listObjectsArgv(risk, url))
291 if (r && r.exitCode === 0) {
292 const { n, cut } = countObjects(r.stdout)
293 pushLine(report, cut ? t(lang, 'line.objectsMore', { url, n }) : t(lang, 'line.objects', { url, n }))
294 } else if (r) report.notes.push(isNotFound(r.stderr) ? t(lang, 'note.notFound', { target: url }) : t(lang, 'note.listFailed', { url, err: lastLine(r.stderr) }))
295 }
296 }
297 return report
298 }
299
300 // IAM: the member and role; for set-iam-policy the policy file against the current policy
301 if (risk.kind === 'iam' && risk.tool === 'gcloud') {
302 const member = risk.extra.member
303 const role = risk.extra.role
304 if (typeof member === 'string') pushLine(report, t(lang, 'line.member', { member }))
305 if (typeof role === 'string') pushLine(report, t(lang, 'line.role', { role }))
306 const target = risk.targets[0]
307 if (target && risk.verb === 'set-iam-policy') {
308 const file = risk.targets[1]
309 let inFile = '?'
310 if (file) {
311 try {
312 const text = await $.fs.read(file)
313 const o = JSON.parse(String(text)) as Record<string, unknown>
314 inFile = String(Array.isArray(o.bindings) ? (o.bindings as unknown[]).length : 0)
315 } catch {}
316 }
317 const cur = await lookup($, getIamPolicyArgv(risk, target))
318 let current = '?'
319 if (cur && cur.exitCode === 0) {
320 try {
321 const o = JSON.parse(cur.stdout) as Record<string, unknown>
322 current = String(Array.isArray(o.bindings) ? (o.bindings as unknown[]).length : 0)
323 } catch {}
324 }
325 pushLine(report, t(lang, 'line.policyFile', { file: file ?? '?', n: inFile, current }))
326 } else if (target) {
327 await describeTargets($, risk, report, [target])
328 }
329 return report
330 }
331
332 // Create-class: what is being asked for
333 if (risk.severity === 'create') {
334 const flags = keyFlagsLine(risk)
335 if (flags) pushLine(report, `${t(lang, 'label.flags')}: ${flags}`)
336 return report
337 }
338
339 // Delete- and update-class: the current state of each target
340 await describeTargets($, risk, report, risk.targets)
341 return report
342}
343
344async function describeTargets($: any, risk: Risk, report: Report, targets: string[]): Promise<void> {
345 if (!targets.length || !risk.path.length) return
346 for (const target of targets.slice(0, MAX_TARGETS_DESCRIBED)) {
347 const d = await lookup($, describeArgv(risk, target))
348 if (d === null) {
349 report.notes.push(t(lang, 'note.noGcloud'))
350 return
351 }
352 if (d.exitCode !== 0) {
353 report.notes.push(isNotFound(d.stderr) ? t(lang, 'note.notFound', { target }) : t(lang, 'note.describeFailed', { target, err: lastLine(d.stderr) }))
354 continue
355 }
356 try {
357 const { line, notes } = summarizeDescribe(lang, target, JSON.parse(d.stdout))
358 pushLine(report, line)
359 report.notes.push(...notes)
360 } catch {
361 pushLine(report, target)
362 }
363 }
364 if (targets.length > MAX_TARGETS_DESCRIBED) pushLine(report, t(lang, 'more', { n: targets.length - MAX_TARGETS_DESCRIBED }))
365}
366
367// ── Drawing ────────────────────────────────────────────────────────────────
368
369function severityColor(severity: Risk['severity']): string {
370 return severity === 'destructive' ? 'red' : severity === 'mutating' ? 'yellow' : 'green'
371}
372
373function draw($: any, e: any, view: HeldView, columns: number, gke: GcloudContext['kube'] | null) {
374 const { Box, Text, Button } = $.ui.resolve(e)
375 const L = lang
376 const risk = view.risk
377 const report = view.report
378 const color = severityColor(risk.severity)
379 const ctx = report?.context ?? emptyContext(risk)
380 const unknown = t(L, 'value.unknown')
381 const projectSource = ctx.projectSource === 'flag' ? t(L, 'source.flag') : ctx.projectSource === 'config' ? t(L, 'source.config') : ''
382 const location = ctx.location ?? t(L, 'value.default')
383 const decide = (choice: Decision) => () => {
384 if (held && held.view.id === view.id && held.decision === null) held.decision = choice
385 }
386 const rows: any[] = []
387 // Labels of the context block share one column width, measured in terminal cells
388 const labelWidth = Math.max(...[t(L, 'label.account'), t(L, 'label.project'), t(L, 'label.location'), t(L, 'label.gke')].map(cellWidth))
389 const label = (text: string) => <Text dimColor>{`${padCells(text, labelWidth)} `}</Text>
390 rows.push(
391 <Text key="head" bold color={color} wrap="wrap">
392 {`⚠ ${severityLabel(L, risk.severity)} · ${report?.headline ?? headline(L, risk)}`}
393 </Text>,
394 )
395 rows.push(<Text key="gap-1">{' '}</Text>)
396 rows.push(
397 <Text key="cmd-label" dimColor>
398 {t(L, 'label.command')}
399 </Text>,
400 )
401 commandRows(view.command, risk.raw).forEach((row, i) => {
402 const key = `cmd-${i}`
403 if ('fold' in row) {
404 rows.push(
405 <Text key={key} dimColor>
406 {` ┆ ${t(L, 'more', { n: row.fold })}`}
407 </Text>,
408 )
409 return
410 }
411 const op = row.op ? <Text dimColor>{` ${row.op}`}</Text> : null
412 if (!row.isRisky) {
413 rows.push(
414 <Text key={key} dimColor wrap="wrap">
415 {` │ ${row.text}`}
416 {op}
417 </Text>,
418 )
419 return
420 }
421 rows.push(
422 <Text key={key} wrap="wrap">
423 <Text color={color} bold>
424 {' ▶ '}
425 </Text>
426 {riskyWords(row.text, risk).map((w, j) =>
427 w.kind === 'space' ? (
428 w.text
429 ) : (
430 <Text
431 key={`${key}-${j}`}
432 color={w.kind === 'head' || w.kind === 'verb' || w.kind === 'danger-flag' ? 'red' : w.kind === 'target' ? 'yellow' : w.kind === 'track' ? 'magenta' : undefined}
433 bold={w.kind === 'head' || w.kind === 'verb' || w.kind === 'danger-flag' || w.kind === 'group' || undefined}
434 dimColor={w.kind === 'prefix' || w.kind === 'flag' || undefined}
435 >
436 {w.text}
437 </Text>
438 ),
439 )}
440 {op}
441 </Text>,
442 )
443 })
444 rows.push(<Text key="gap-2">{' '}</Text>)
445 rows.push(
446 <Text key="account" wrap="truncate-end">
447 {label(t(L, 'label.account'))}
448 <Text>{ctx.account ?? unknown}</Text>
449 {ctx.impersonate ? <Text dimColor>{` (impersonating ${ctx.impersonate})`}</Text> : null}
450 </Text>,
451 )
452 rows.push(
453 <Text key="project" wrap="truncate-end">
454 {label(t(L, 'label.project'))}
455 <Text bold>{ctx.project ?? unknown}</Text>
456 {projectSource ? <Text dimColor>{` ${projectSource}`}</Text> : null}
457 {ctx.configuration ? <Text dimColor>{` · ${t(L, 'label.configuration')} ${ctx.configuration}`}</Text> : null}
458 </Text>,
459 )
460 rows.push(
461 <Text key="location" wrap="truncate-end">
462 {label(t(L, 'label.location'))}
463 <Text>{location}</Text>
464 {ctx.track !== 'ga' ? <Text color="magenta">{` · ${t(L, 'label.track')} ${ctx.track}`}</Text> : null}
465 </Text>,
466 )
467 if (gke && gke.kind === 'gke') {
468 rows.push(
469 <Text key="gke" wrap="truncate-end">
470 {label(t(L, 'label.gke'))}
471 <Text>{`${gke.cluster} (${gke.location})`}</Text>
472 {gke.project && ctx.project && gke.project !== ctx.project ? <Text color="yellow">{` ≠ ${t(L, 'label.project').toLowerCase()} ${gke.project}`}</Text> : null}
473 </Text>,
474 )
475 }
476 if (ctx.quiet) {
477 rows.push(<Text key="gap-3">{' '}</Text>)
478 rows.push(
479 <Text key="quiet" color="yellow" bold wrap="wrap">
480 {`! ${t(L, 'quiet.warn')}`}
481 </Text>,
482 )
483 }
484 if (report && report.lines.length) {
485 rows.push(
486 <Box key="lines" flexDirection="column" marginTop={1}>
487 {report.lines.map((line, i) => (
488 <Text key={`l${i}`} wrap="truncate-end">
489 {` ${line}`}
490 </Text>
491 ))}
492 </Box>,
493 )
494 }
495 if (report && report.notes.length) {
496 rows.push(
497 <Box key="notes" flexDirection="column" marginTop={1}>
498 {report.notes.map((note, i) => (
499 <Text key={`n${i}`} dimColor italic wrap="wrap">
500 {note}
501 </Text>
502 ))}
503 </Box>,
504 )
505 }
506 if (!report) {
507 rows.push(
508 <Text key="measuring" dimColor>
509 …
510 </Text>,
511 )
512 }
513 rows.push(
514 <Box key="buttons" marginTop={1} gap={2}>
515 <Button key="proceed" label={t(L, 'btn.proceed')} hotkey="1" plain onPress={decide('proceed')} />
516 <Button key="cancel" label={t(L, 'btn.cancel')} hotkey="2" plain autoFocus onPress={decide('cancel')} />
517 <Text key="hint" dimColor>
518 {t(L, 'waiting')}
519 </Text>
520 </Box>,
521 )
522 // The pane has its own frame (and a tab naming the mod), so only the band draws a border
523 return view.where === 'band' ? (
524 <Box flexDirection="column" borderStyle="round" borderColor={color} paddingX={1}>
525 {rows}
526 </Box>
527 ) : (
528 <Box flexDirection="column" paddingX={1}>
529 {rows}
530 </Box>
531 )
532}
533
534/** Terminal cells a string takes: wide (CJK, fullwidth) characters take two. */
535function cellWidth(text: string): number {
536 let n = 0
537 for (const ch of text) n += /[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6]/.test(ch) ? 2 : 1
538 return n
539}
540
541function padCells(text: string, width: number): string {
542 return text + ' '.repeat(Math.max(0, width - cellWidth(text)))
543}
544
545// ── The hold ───────────────────────────────────────────────────────────────
546
547async function sleepTick($: any): Promise<void> {
548 await $.process.run(['sleep', POLL_SECONDS], { timeoutMs: 5000 })
549}
550
551async function holdCommand($: any, e: any, next: any, risk: Risk): Promise<any> {
552 const command = String(e.command ?? '')
553 // One hold at a time: wait for the one in progress (a subagent's, say). `held` is claimed
554 // with no await between the check and the claim, so two waiting calls never both get through.
555 while (held !== null) {
556 if (next.signal.aborted) return { deny: denyText(lang, 'interrupted', headline(lang, risk), risk.flags.project ?? null) }
557 await sleepTick($)
558 }
559 holdSeq += 1
560 const view: HeldView = { id: holdSeq, command, risk, report: null, where: 'pane' }
561 const mine: Hold = { view, decision: null }
562 held = mine
563 let opened: { isPlaced?: boolean } = { isPlaced: false }
564 let report: Report | null = null
565 try {
566 report = await measure($, risk)
567 mine.view = { ...mine.view, report }
568 await update($, heldState, () => mine.view)
569 try {
570 const snap = (await read($, contextState)) as GcloudContext | null
571 opened = await $.ui.open({ id: PANE, title: `gcloud-guard · ${severityLabel(lang, risk.severity)}`, focus: true, rows: paneRows(report, snap?.kube?.kind === 'gke', commandRows(command, risk.raw).length) })
572 } catch {
573 opened = { isPlaced: false }
574 }
575 if (!opened.isPlaced) {
576 mine.view = { ...mine.view, where: 'band' }
577 await update($, heldState, () => mine.view)
578 }
579 try {
580 $.ui.invalidate('ui.render')
581 } catch {}
582 const startedAt: number = await $.clock.now()
583 while (mine.decision === null) {
584 if (next.signal.aborted) {
585 mine.decision = 'interrupted'
586 break
587 }
588 if ((await $.clock.now()) - startedAt > HOLD_LIMIT_MS) {
589 mine.decision = 'timeout'
590 break
591 }
592 await sleepTick($)
593 }
594 } catch {
595 mine.decision = 'error'
596 } finally {
597 // Close this hold's pane before releasing the hold, so the next hold's pane is never the one closed
598 try {
599 if (opened.isPlaced) await $.ui.close({ id: PANE })
600 } catch {}
601 if (held === mine) held = null
602 try {
603 await update($, heldState, () => null)
604 } catch {}
605 try {
606 $.ui.invalidate('ui.render')
607 } catch {}
608 }
609 const decision = mine.decision ?? 'error'
610 if (decision === 'proceed') {
611 toast($, t(lang, 'toast.proceed'))
612 const ran = await next(e)
613 // A proceeded gcloud / gsutil command may have changed the project, account or kube context
614 await refreshContext($)
615 return ran
616 }
617 const why = decision === 'cancel' ? 'cancel' : decision === 'timeout' ? 'timeout' : decision === 'interrupted' ? 'interrupted' : 'error'
618 return { deny: denyText(lang, why, report?.headline ?? headline(lang, risk), report?.context.project ?? risk.flags.project ?? null) }
619}
620
621// ── Hooks ──────────────────────────────────────────────────────────────────
622
623export const register: Register = (on, options) => {
624 settings = readSettings(options as Record<string, unknown> | undefined)
625
626 on('session.start', async ($, e, next) => {
627 const out = await next(e)
628 lang = await resolveLanguage($)
629 await update($, langState, () => lang)
630 // A hot reload mid-hold left a stale view behind: clear it
631 await update($, heldState, () => null)
632 await $.command.register({ name: 'gcloud-guard', description: t(lang, 'cmd.description'), argumentHint: '[off|on|refresh]' })
633 await refreshContext($)
634 // Nobody looks at the band in `claude -p`: no timer there
635 if (e.isInteractive) {
636 $.clock.every(CONTEXT_TICK_MS, () => {
637 void onContextTick($).catch(() => {})
638 })
639 }
640 return out
641 })
642
643 on('command.run', { command: 'gcloud-guard' }, async ($, e) => {
644 const arg = String(e.args ?? '').trim()
645 if (arg === 'off') {
646 await update($, isBandHidden, () => true)
647 return { text: t(lang, 'cmd.off') }
648 }
649 if (arg === 'on') {
650 await update($, isBandHidden, () => false)
651 return { text: t(lang, 'cmd.on') }
652 }
653 if (arg === 'refresh') {
654 await refreshContext($)
655 return { text: `${t(lang, 'cmd.refreshed')}\n${contextText(lang, (await read($, contextState)) as GcloudContext | null, settings)}` }
656 }
657 if (arg !== '') return { text: t(lang, 'cmd.usage') }
658 return { text: contextText(lang, (await read($, contextState)) as GcloudContext | null, settings) }
659 })
660
661 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
662 const command = String(e.command ?? '')
663 const risk = classify(command, settings)
664 if (risk !== null && isHeld(risk, settings)) return holdCommand($, e, next, risk)
665 if (!touchesContext(command)) return next(e)
666 // Not held, but it may change the project, account or kube context: re-read afterwards
667 const ran = await next(e)
668 await refreshContext($)
669 return ran
670 })
671
672 on('ui.render', { component: 'Pane', requestId: 'gcloud-guard' }, async ($, e, next) => {
673 const view = (await read($, heldState)) as HeldView | null
674 if (view === null) return next(e)
675 await read($, langState)
676 const snap = (await read($, contextState)) as GcloudContext | null
677 return draw($, e, view, e.props.bodyColumns ?? 80, snap?.kube ?? null)
678 })
679
680 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
681 const view = (await read($, heldState)) as HeldView | null
682 await read($, langState)
683 if (view !== null) {
684 if (view.where !== 'band') return next(e)
685 // The report takes the whole band while the command is held: the buttons must be on top
686 const snap = (await read($, contextState)) as GcloudContext | null
687 return draw($, e, view, e.props.bodyColumns ?? 80, snap?.kube ?? null)
688 }
689 if (e.props.hasSurvey || !settings.showContext || (await read($, isBandHidden))) return next(e)
690 const ctx = (await read($, contextState)) as GcloudContext | null
691 const text = contextLine(lang, ctx, settings)
692 if (text === null) return next(e)
693 const ui = $.ui.resolve(e)
694 const { Text } = ui
695 // AbovePrompt is a chain: draw our line in its frame, then whatever the plugins beneath drew
696 const below = await next(e)
697 return frameBand(
698 ui,
699 settings.bandStyle,
700 kubeProjectMismatch(ctx),
701 e.props.bodyColumns,
702 <Text wrap="truncate-end" dimColor>
703 {text}
704 </Text>,
705 below,
706 )
707 })
708}
709
710/**
711 * Frames the context line per `band_style` and stacks the plugins beneath under it.
712 * `box`: a rounded frame (yellow when `isWarning`, here when the GKE context's project differs from
713 * gcloud's); `rule`: a dim line beneath, only when another plugin drew something below; `plain`: bare text.
714 */
715function frameBand(ui: { Box: any; Text: any }, style: BandStyle, isWarning: boolean, bodyColumns: number | undefined, content: any, below: any) {
716 const { Box, Text } = ui
717 const hasBelow = below !== null && below !== undefined && (below as { type?: string }).type !== 'engine'
718 const own =
719 style === 'box' ? (
720 <Box key="frame" flexDirection="column" borderStyle="round" borderDimColor={isWarning ? undefined : true} borderColor={isWarning ? 'yellow' : undefined} paddingX={1}>
721 {content}
722 </Box>
723 ) : style === 'rule' ? (
724 <Box key="frame" flexDirection="column">
725 {content}
726 {hasBelow ? <Text key="rule" dimColor>{'─'.repeat(Math.max(8, Math.min(bodyColumns ?? 60, 200)))}</Text> : null}
727 </Box>
728 ) : (
729 <Box key="frame" flexDirection="column">
730 {content}
731 </Box>
732 )
733 return (
734 <Box flexDirection="column">
735 {own}
736 {below}
737 </Box>
738 )
739}
740hooks/i18n.ts 316 lines1// gcloud-guard i18n: the UI language, how it is resolved, and every string a person
2// or the model reads, in English, Traditional Chinese and Japanese.
3// Pure: no `$`. Shared with logic.ts, register.tsx and the tests.
4
5export type Lang = 'en' | 'zh-TW' | 'ja'
6export const LANGS: readonly Lang[] = ['en', 'zh-TW', 'ja']
7export const DEFAULT_LANG: Lang = 'en'
8
9export type LangEnv = { LC_ALL?: string; LC_MESSAGES?: string; LANG?: string }
10
11/**
12 * Picks the language: an explicit option (`en`, `zh-TW`, `ja`) wins; `auto`,
13 * undefined or anything else reads LC_ALL, then LC_MESSAGES, then LANG.
14 * Any `zh*` locale maps to zh-TW (only Traditional is shipped), `ja*` to ja,
15 * everything else (including C, POSIX and empty) to en.
16 */
17export function resolveLang(option: unknown, env: LangEnv): Lang {
18 if (option === 'en' || option === 'zh-TW' || option === 'ja') return option
19 for (const raw of [env.LC_ALL, env.LC_MESSAGES, env.LANG]) {
20 const v = (raw ?? '').trim()
21 if (!v) continue
22 const low = v.toLowerCase()
23 if (low === 'c' || low === 'posix') return 'en'
24 if (low.startsWith('zh')) return 'zh-TW'
25 if (low.startsWith('ja')) return 'ja'
26 return 'en'
27 }
28 return DEFAULT_LANG
29}
30
31export type Params = Record<string, string | number>
32type Message = string | ((p: Params) => string)
33
34/** Every refusal ends with this English line, so a model never reads a translated refusal as a transient error. */
35export const DENY_TAIL = '(gcloud-guard: the user did not approve this command; do not retry unless asked.)'
36
37const en = {
38 // severities
39 'severity.destructive': 'destructive',
40 'severity.mutating': 'mutating',
41 'severity.create': 'create',
42 // pane
43 'title': (p: Params) => `⚠ gcloud-guard · ${p.severity}`,
44 'label.command': 'Command',
45 'label.account': 'Account',
46 'label.project': 'Project',
47 'label.configuration': 'Config',
48 'label.location': 'Location',
49 'label.track': 'Track',
50 'label.flags': 'Flags',
51 'source.flag': '← from --project',
52 'source.config': '← from gcloud config',
53 'value.unknown': 'unknown',
54 'value.default': '(default)',
55 'quiet.warn': '--quiet: gcloud will not ask for its own confirmation',
56 'more': (p: Params) => `+ ${p.n} more`,
57 'btn.proceed': 'Proceed',
58 'btn.cancel': 'Cancel',
59 'waiting': 'Claude is waiting on your answer',
60 'toast.proceed': 'gcloud-guard: running it',
61 // headlines
62 'headline.generic': (p: Params) => `${p.verb} ${p.type}${p.targets ? ` ${p.targets}` : ''}`,
63 'headline.project': (p: Params) => `shut down project ${p.id} (30-day recovery window)`,
64 'headline.org': (p: Params) => `delete ${p.kind} ${p.id}`,
65 'headline.config': (p: Params) => `switch gcloud config ${p.property} → ${p.value} (now: ${p.current})`,
66 'headline.deploy': (p: Params) => `deploy ${p.type}${p.targets ? ` ${p.targets}` : ''} (creates or replaces the revision)`,
67 'headline.build': (p: Params) => `submit a build${p.targets ? ` from ${p.targets}` : ''}`,
68 'headline.iamAdd': (p: Params) => `grant ${p.role} to ${p.member} on ${p.type} ${p.targets}`,
69 'headline.iamRemove': (p: Params) => `revoke ${p.role} from ${p.member} on ${p.type} ${p.targets}`,
70 'headline.iamSet': (p: Params) => `replace the IAM policy of ${p.type} ${p.targets}`,
71 'headline.storageRm': (p: Params) => `delete ${p.targets}`,
72 'headline.storageCopy': (p: Params) => `${p.verb} ${p.targets}`,
73 // describe lines
74 'line.created': (p: Params) => `created ${p.date}`,
75 'line.labels': (p: Params) => `${p.n} labels`,
76 'line.nodes': (p: Params) => `${p.n} nodes`,
77 'line.disks': (p: Params) => `${p.n} disks (${p.autoDelete} auto-delete)`,
78 'line.bindings': (p: Params) => `${p.n} IAM bindings`,
79 'line.objects': (p: Params) => `${p.url}: ${p.n} objects`,
80 'line.objectsMore': (p: Params) => `${p.url}: ${p.n}+ objects (listing cut)`,
81 'line.servicesEnabled': (p: Params) => `${p.n} services enabled`,
82 'line.member': (p: Params) => `member ${p.member}`,
83 'line.role': (p: Params) => `role ${p.role}`,
84 'line.policyFile': (p: Params) => `policy file ${p.file}: ${p.n} bindings (current policy: ${p.current})`,
85 'line.property': (p: Params) => `${p.property}: ${p.current} → ${p.value}`,
86 // notes
87 'note.noGcloud': 'gcloud is not on PATH (or did not answer): nothing could be looked up; holding anyway',
88 'note.notFound': (p: Params) => `${p.target}: not found, so this would fail (or hit something else than you think)`,
89 'note.describeFailed': (p: Params) => `${p.target}: could not describe it (${p.err})`,
90 'note.deletionProtection': (p: Params) => `${p.target}: deletion protection is on; a delete fails unless it is turned off first`,
91 'note.unknownVerb': 'this verb is not in the table; held to be safe',
92 'note.rsyncDelete': 'rsync with delete: objects in the destination that are not in the source are deleted',
93 'note.listFailed': (p: Params) => `${p.url}: could not list it (${p.err})`,
94 'note.projectRecovery': 'a deleted project can be restored within 30 days; its resources stop at once',
95 'note.contextFailed': 'could not read the gcloud config (account / project unknown)',
96 // context line and command
97 'ctx.project': (p: Params) => `project ${p.project}`,
98 'ctx.fromEnv': '← CLOUDSDK_CORE_PROJECT',
99 'ctx.account': (p: Params) => `account ${p.account}`,
100 'ctx.config': (p: Params) => `config ${p.name}`,
101 'ctx.gke': (p: Params) => `GKE ${p.cluster} (${p.location})`,
102 'ctx.k8s': (p: Params) => `k8s ${p.name}`,
103 'label.gke': 'GKE',
104 'cmd.description': 'Show which gcloud project, account and GKE cluster the session is pointed at; off / on hides or shows the line, refresh re-reads the config files',
105 'cmd.usage': 'Usage: /gcloud-guard (context), /gcloud-guard off | on (hide / show the line), /gcloud-guard refresh (re-read the config files)',
106 'cmd.off': 'gcloud-guard: context line hidden for this session. /gcloud-guard on shows it again.',
107 'cmd.on': 'gcloud-guard: context line shown.',
108 'cmd.refreshed': 'gcloud-guard: config files re-read.',
109 'cmd.none': 'gcloud-guard: no gcloud configuration found (no config directory, or no active configuration).',
110 'cmd.configDir': (p: Params) => `config dir ${p.dir}`,
111 'cmd.configuration': (p: Params) => `configuration ${p.name}`,
112 'cmd.project': (p: Params) => `project ${p.project} (${p.source})`,
113 'cmd.account': (p: Params) => `account ${p.account}`,
114 'cmd.zone': (p: Params) => `zone / region ${p.zone} / ${p.region}`,
115 'cmd.kubeconfig': (p: Params) => `kubeconfig ${p.path}`,
116 'cmd.kubeContext': (p: Params) => `kube context ${p.name}`,
117 'cmd.gke': (p: Params) => `GKE project ${p.project} · location ${p.location} · cluster ${p.cluster}`,
118 'cmd.hold': (p: Params) => `hold setting ${p.hold}${p.gsutil ? ' + gsutil' : ''}${p.configSet ? ' + config set' : ''}`,
119 'cmd.source.env': 'from the CLOUDSDK_CORE_PROJECT env var',
120 'cmd.source.file': 'from the configuration file',
121 'value.none': 'none',
122 // deny
123 'deny': (p: Params) => `gcloud-guard held this command and did not run it: ${p.why}. It would have: ${p.headline} in project ${p.project}. ${DENY_TAIL}`,
124 'why.cancel': 'the user pressed Cancel',
125 'why.timeout': 'no answer within 10 minutes',
126 'why.interrupted': 'the turn was interrupted',
127 'why.error': 'gcloud-guard hit an error while holding it',
128 'why.none': 'no answer was recorded',
129} as const
130
131export type MessageKey = keyof typeof en
132
133export type Messages = Record<MessageKey, Message>
134
135const zhTW: Messages = {
136 'severity.destructive': '破壞性',
137 'severity.mutating': '修改',
138 'severity.create': '建立',
139 'title': p => `⚠ gcloud-guard · ${p.severity}`,
140 'label.command': '指令',
141 'label.account': '帳號',
142 'label.project': '專案',
143 'label.configuration': '設定檔',
144 'label.location': '位置',
145 'label.track': '版本',
146 'label.flags': '參數',
147 'source.flag': '← 來自 --project',
148 'source.config': '← 來自 gcloud config',
149 'value.unknown': '不明',
150 'value.default': '(預設)',
151 'quiet.warn': '--quiet:gcloud 不會再自己確認一次',
152 'more': p => `還有 ${p.n} 個`,
153 'btn.proceed': '執行',
154 'btn.cancel': '取消',
155 'waiting': 'Claude 在等你的回答',
156 'toast.proceed': 'gcloud-guard:執行中',
157 'headline.generic': p => `${p.verb} ${p.type}${p.targets ? ` ${p.targets}` : ''}`,
158 'headline.project': p => `關閉專案 ${p.id}(30 天內可復原)`,
159 'headline.org': p => `刪除 ${p.kind} ${p.id}`,
160 'headline.config': p => `切換 gcloud 設定 ${p.property} → ${p.value}(目前:${p.current})`,
161 'headline.deploy': p => `部署 ${p.type}${p.targets ? ` ${p.targets}` : ''}(會建立或取代 revision)`,
162 'headline.build': p => `送出一次 build${p.targets ? `(來源 ${p.targets})` : ''}`,
163 'headline.iamAdd': p => `把 ${p.role} 授予 ${p.member}(${p.type} ${p.targets})`,
164 'headline.iamRemove': p => `收回 ${p.member} 的 ${p.role}(${p.type} ${p.targets})`,
165 'headline.iamSet': p => `整個取代 ${p.type} ${p.targets} 的 IAM policy`,
166 'headline.storageRm': p => `刪除 ${p.targets}`,
167 'headline.storageCopy': p => `${p.verb} ${p.targets}`,
168 'line.created': p => `建立於 ${p.date}`,
169 'line.labels': p => `${p.n} 個 label`,
170 'line.nodes': p => `${p.n} 個節點`,
171 'line.disks': p => `${p.n} 個磁碟(${p.autoDelete} 個會一起刪)`,
172 'line.bindings': p => `${p.n} 條 IAM binding`,
173 'line.objects': p => `${p.url}:${p.n} 個物件`,
174 'line.objectsMore': p => `${p.url}:超過 ${p.n} 個物件(清單截斷)`,
175 'line.servicesEnabled': p => `已啟用 ${p.n} 個服務`,
176 'line.member': p => `成員 ${p.member}`,
177 'line.role': p => `角色 ${p.role}`,
178 'line.policyFile': p => `policy 檔 ${p.file}:${p.n} 條 binding(目前 policy:${p.current})`,
179 'line.property': p => `${p.property}:${p.current} → ${p.value}`,
180 'note.noGcloud': '找不到 gcloud(或它沒有回應),查不到任何資訊;仍然先攔住',
181 'note.notFound': p => `${p.target}:找不到,這個指令會失敗(或打到你以為以外的東西)`,
182 'note.describeFailed': p => `${p.target}:無法 describe(${p.err})`,
183 'note.deletionProtection': p => `${p.target}:已開啟刪除保護,不先關掉的話刪除會失敗`,
184 'note.unknownVerb': '這個動詞不在表裡,保險起見先攔住',
185 'note.rsyncDelete': 'rsync 帶刪除:目的端有、來源端沒有的物件會被刪掉',
186 'note.listFailed': p => `${p.url}:無法列出(${p.err})`,
187 'note.projectRecovery': '刪除的專案 30 天內可復原,但裡面的資源會立刻停止',
188 'note.contextFailed': '讀不到 gcloud 設定(帳號/專案不明)',
189 'ctx.project': p => `專案 ${p.project}`,
190 'ctx.fromEnv': '← CLOUDSDK_CORE_PROJECT',
191 'ctx.account': p => `帳號 ${p.account}`,
192 'ctx.config': p => `設定檔 ${p.name}`,
193 'ctx.gke': p => `GKE ${p.cluster}(${p.location})`,
194 'ctx.k8s': p => `k8s ${p.name}`,
195 'label.gke': 'GKE',
196 'cmd.description': '顯示這個 session 指向哪個 gcloud 專案、帳號與 GKE 叢集;off / on 隱藏或顯示那一行,refresh 重新讀設定檔',
197 'cmd.usage': '用法:/gcloud-guard(目前的 context)、/gcloud-guard off | on(隱藏/顯示那一行)、/gcloud-guard refresh(重新讀設定檔)',
198 'cmd.off': 'gcloud-guard:本 session 已隱藏 context 行。/gcloud-guard on 重新顯示。',
199 'cmd.on': 'gcloud-guard:已顯示 context 行。',
200 'cmd.refreshed': 'gcloud-guard:已重新讀取設定檔。',
201 'cmd.none': 'gcloud-guard:找不到 gcloud 設定(沒有設定目錄,或沒有使用中的 configuration)。',
202 'cmd.configDir': p => `設定目錄 ${p.dir}`,
203 'cmd.configuration': p => `configuration ${p.name}`,
204 'cmd.project': p => `專案 ${p.project}(${p.source})`,
205 'cmd.account': p => `帳號 ${p.account}`,
206 'cmd.zone': p => `zone / region ${p.zone} / ${p.region}`,
207 'cmd.kubeconfig': p => `kubeconfig ${p.path}`,
208 'cmd.kubeContext': p => `kube context ${p.name}`,
209 'cmd.gke': p => `GKE 專案 ${p.project} · 位置 ${p.location} · 叢集 ${p.cluster}`,
210 'cmd.hold': p => `攔截設定 ${p.hold}${p.gsutil ? ' + gsutil' : ''}${p.configSet ? ' + config set' : ''}`,
211 'cmd.source.env': '來自環境變數 CLOUDSDK_CORE_PROJECT',
212 'cmd.source.file': '來自 configuration 檔',
213 'value.none': '無',
214 'deny': p => `gcloud-guard 攔住了這個指令,沒有執行:${p.why}。它原本會:${p.headline},專案 ${p.project}。${DENY_TAIL}`,
215 'why.cancel': '使用者按了取消',
216 'why.timeout': '10 分鐘內沒有回答',
217 'why.interrupted': '這一輪被中斷',
218 'why.error': 'gcloud-guard 在攔住期間發生錯誤',
219 'why.none': '沒有記錄到回答',
220}
221
222const ja: Messages = {
223 'severity.destructive': '破壊的',
224 'severity.mutating': '変更',
225 'severity.create': '作成',
226 'title': p => `⚠ gcloud-guard · ${p.severity}`,
227 'label.command': 'コマンド',
228 'label.account': 'アカウント',
229 'label.project': 'プロジェクト',
230 'label.configuration': '構成',
231 'label.location': 'ロケーション',
232 'label.track': 'トラック',
233 'label.flags': 'フラグ',
234 'source.flag': '← --project から',
235 'source.config': '← gcloud config から',
236 'value.unknown': '不明',
237 'value.default': '(デフォルト)',
238 'quiet.warn': '--quiet:gcloud 自身の確認は出ません',
239 'more': p => `他 ${p.n} 件`,
240 'btn.proceed': '実行',
241 'btn.cancel': 'キャンセル',
242 'waiting': 'Claude はあなたの回答を待っています',
243 'toast.proceed': 'gcloud-guard:実行します',
244 'headline.generic': p => `${p.verb} ${p.type}${p.targets ? ` ${p.targets}` : ''}`,
245 'headline.project': p => `プロジェクト ${p.id} をシャットダウン(30日以内なら復元可)`,
246 'headline.org': p => `${p.kind} ${p.id} を削除`,
247 'headline.config': p => `gcloud 設定 ${p.property} を ${p.value} に切り替え(現在:${p.current})`,
248 'headline.deploy': p => `${p.type}${p.targets ? ` ${p.targets}` : ''} をデプロイ(リビジョンを作成または置換)`,
249 'headline.build': p => `ビルドを送信${p.targets ? `(ソース ${p.targets})` : ''}`,
250 'headline.iamAdd': p => `${p.member} に ${p.role} を付与(${p.type} ${p.targets})`,
251 'headline.iamRemove': p => `${p.member} から ${p.role} を剥奪(${p.type} ${p.targets})`,
252 'headline.iamSet': p => `${p.type} ${p.targets} の IAM ポリシーを丸ごと置換`,
253 'headline.storageRm': p => `${p.targets} を削除`,
254 'headline.storageCopy': p => `${p.verb} ${p.targets}`,
255 'line.created': p => `作成 ${p.date}`,
256 'line.labels': p => `ラベル ${p.n} 件`,
257 'line.nodes': p => `ノード ${p.n} 台`,
258 'line.disks': p => `ディスク ${p.n} 台(${p.autoDelete} 台は同時削除)`,
259 'line.bindings': p => `IAM バインディング ${p.n} 件`,
260 'line.objects': p => `${p.url}:オブジェクト ${p.n} 件`,
261 'line.objectsMore': p => `${p.url}:オブジェクト ${p.n} 件以上(一覧を打ち切り)`,
262 'line.servicesEnabled': p => `有効なサービス ${p.n} 件`,
263 'line.member': p => `メンバー ${p.member}`,
264 'line.role': p => `ロール ${p.role}`,
265 'line.policyFile': p => `ポリシーファイル ${p.file}:バインディング ${p.n} 件(現在のポリシー:${p.current})`,
266 'line.property': p => `${p.property}:${p.current} → ${p.value}`,
267 'note.noGcloud': 'gcloud が PATH にない(または応答なし)ため何も調べられませんでした。保留は続けます',
268 'note.notFound': p => `${p.target}:見つかりません。このコマンドは失敗します(または別の対象に当たります)`,
269 'note.describeFailed': p => `${p.target}:describe できませんでした(${p.err})`,
270 'note.deletionProtection': p => `${p.target}:削除保護が有効です。先に解除しないと削除は失敗します`,
271 'note.unknownVerb': 'この動詞は表にありません。念のため保留します',
272 'note.rsyncDelete': '削除付き rsync:ソースにない宛先オブジェクトは削除されます',
273 'note.listFailed': p => `${p.url}:一覧できませんでした(${p.err})`,
274 'note.projectRecovery': '削除したプロジェクトは30日以内に復元できますが、リソースは直ちに停止します',
275 'note.contextFailed': 'gcloud の設定を読めませんでした(アカウント/プロジェクト不明)',
276 'ctx.project': p => `プロジェクト ${p.project}`,
277 'ctx.fromEnv': '← CLOUDSDK_CORE_PROJECT',
278 'ctx.account': p => `アカウント ${p.account}`,
279 'ctx.config': p => `構成 ${p.name}`,
280 'ctx.gke': p => `GKE ${p.cluster}(${p.location})`,
281 'ctx.k8s': p => `k8s ${p.name}`,
282 'label.gke': 'GKE',
283 'cmd.description': 'このセッションが向いている gcloud プロジェクト・アカウント・GKE クラスタを表示;off / on で行を隠す/表示、refresh で設定ファイルを読み直す',
284 'cmd.usage': '使い方:/gcloud-guard(現在のコンテキスト)、/gcloud-guard off | on(行を隠す/表示)、/gcloud-guard refresh(設定ファイルを読み直す)',
285 'cmd.off': 'gcloud-guard:このセッションではコンテキスト行を隠しました。/gcloud-guard on で再表示。',
286 'cmd.on': 'gcloud-guard:コンテキスト行を表示しました。',
287 'cmd.refreshed': 'gcloud-guard:設定ファイルを読み直しました。',
288 'cmd.none': 'gcloud-guard:gcloud の設定が見つかりません(設定ディレクトリがない、または有効な構成がない)。',
289 'cmd.configDir': p => `設定ディレクトリ ${p.dir}`,
290 'cmd.configuration': p => `構成 ${p.name}`,
291 'cmd.project': p => `プロジェクト ${p.project}(${p.source})`,
292 'cmd.account': p => `アカウント ${p.account}`,
293 'cmd.zone': p => `zone / region ${p.zone} / ${p.region}`,
294 'cmd.kubeconfig': p => `kubeconfig ${p.path}`,
295 'cmd.kubeContext': p => `kube context ${p.name}`,
296 'cmd.gke': p => `GKE プロジェクト ${p.project} · ロケーション ${p.location} · クラスタ ${p.cluster}`,
297 'cmd.hold': p => `保留の設定 ${p.hold}${p.gsutil ? ' + gsutil' : ''}${p.configSet ? ' + config set' : ''}`,
298 'cmd.source.env': '環境変数 CLOUDSDK_CORE_PROJECT から',
299 'cmd.source.file': '構成ファイルから',
300 'value.none': 'なし',
301 'deny': p => `gcloud-guard はこのコマンドを保留し、実行しませんでした:${p.why}。実行すると:${p.headline}(プロジェクト ${p.project})。${DENY_TAIL}`,
302 'why.cancel': 'ユーザーがキャンセルを押しました',
303 'why.timeout': '10分以内に回答がありませんでした',
304 'why.interrupted': 'ターンが中断されました',
305 'why.error': '保留中に gcloud-guard でエラーが起きました',
306 'why.none': '回答が記録されていません',
307}
308
309export const MESSAGES: Record<Lang, Messages> = { en: en as Messages, 'zh-TW': zhTW, ja }
310
311/** The message for `key` in `lang`, falling back to English when a language lacks it. */
312export function t(lang: Lang, key: MessageKey, params: Params = {}): string {
313 const m = MESSAGES[lang]?.[key] ?? MESSAGES.en[key]
314 return typeof m === 'function' ? m(params) : m
315}
316hooks/logic.ts 911 lines1// gcloud-guard pure functions: tokenizer, segment splitting, the gcloud / gsutil
2// classifier, the argv of the read-only lookups, and the report text.
3// No `$` here; shared with register.tsx and the tests.
4
5import type { GcloudContext, GuardTool, KubeContext, Report, ReportContext, Risk, RiskFlags, Severity, Track } from '../types'
6import { t } from './i18n'
7import type { Lang } from './i18n'
8
9export type { GcloudContext, GuardTool, KubeContext, Report, ReportContext, Risk, RiskFlags, Severity, Track }
10
11/** The context line is re-read when one of its files changed; the timer looks every 5 seconds. */
12export const CONTEXT_TICK_MS = 5000
13
14export const PLUGIN = 'gcloud-guard'
15export const PANE = 'gcloud-guard'
16export const HOLD_LIMIT_MS = 10 * 60 * 1000
17export const POLL_SECONDS = '0.25'
18export const MAX_TARGETS_DESCRIBED = 5
19export const MAX_LINES = 12
20export const MAX_OBJECTS_COUNTED = 2000
21export const DEFAULT_DESCRIBE_TIMEOUT_S = 15
22export const MIN_DESCRIBE_TIMEOUT_S = 3
23export const MAX_DESCRIBE_TIMEOUT_S = 60
24
25// ── Settings ───────────────────────────────────────────────────────────────
26
27export type HoldLevel = 'all' | 'mutating' | 'destructive'
28
29export type Settings = {
30 language: unknown
31 hold: HoldLevel
32 includeGsutil: boolean
33 holdConfigSet: boolean
34 describeTimeoutMs: number
35 showContext: boolean
36 showOtherContexts: boolean
37 /** How the context line is framed (`band_style`); the hold report draws its own box. */
38 bandStyle: BandStyle
39}
40
41function num(v: unknown, fallback: number): number {
42 const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : NaN
43 return Number.isFinite(n) ? n : fallback
44}
45
46function bool(v: unknown, fallback: boolean): boolean {
47 if (typeof v === 'boolean') return v
48 if (v === 'true') return true
49 if (v === 'false') return false
50 return fallback
51}
52
53export function readSettings(options: Readonly<Record<string, unknown>> | undefined): Settings {
54 const o = options ?? {}
55 const hold = o.hold === 'mutating' || o.hold === 'destructive' ? o.hold : 'all'
56 const seconds = Math.min(MAX_DESCRIBE_TIMEOUT_S, Math.max(MIN_DESCRIBE_TIMEOUT_S, num(o.describe_timeout_seconds, DEFAULT_DESCRIBE_TIMEOUT_S)))
57 return {
58 language: o.language,
59 hold,
60 includeGsutil: bool(o.include_gsutil, true),
61 holdConfigSet: bool(o.hold_config_set, true),
62 describeTimeoutMs: Math.round(seconds * 1000),
63 showContext: bool(o.show_context, true),
64 showOtherContexts: bool(o.show_other_contexts, false),
65 bandStyle: parseBandStyle(o.band_style),
66 }
67}
68
69/** True when the current GKE context points at a project other than the one gcloud is set to. */
70export function kubeProjectMismatch(ctx: GcloudContext | null): boolean {
71 if (!ctx || !ctx.project || ctx.kube?.kind !== 'gke') return false
72 return !!ctx.kube.project && ctx.kube.project !== ctx.project
73}
74
75/** Whether a risk of this severity is held under the configured level. */
76export function isHeld(risk: Risk, settings: Settings): boolean {
77 if (risk.kind === 'local-config' && !settings.holdConfigSet) return false
78 if (settings.hold === 'destructive') return risk.severity === 'destructive'
79 if (settings.hold === 'mutating') return risk.severity !== 'create'
80 return true
81}
82
83// ── Text ───────────────────────────────────────────────────────────────────
84
85export function truncate(s: string, max: number): string {
86 const one = s.replace(/\s+/g, ' ').trim()
87 return one.length <= max ? one : `${one.slice(0, Math.max(0, max - 1))}…`
88}
89
90export function baseName(s: string): string {
91 return s.slice(s.lastIndexOf('/') + 1)
92}
93
94/** Splits one segment into words, honouring double and single quotes. Good enough to read flags and names. */
95export function tokenize(text: string): string[] {
96 const words: string[] = []
97 const re = /"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+)/g
98 let m: RegExpExecArray | null
99 while ((m = re.exec(text)) !== null) words.push(m[1] ?? m[2] ?? m[3] ?? '')
100 return words
101}
102
103/**
104 * The command line with heredoc bodies removed (`<<EOF` … `EOF`, `<<-'EOF'` …): their text is
105 * data handed to a program on stdin, not commands, so a script or a test file written through
106 * `python3 - <<'EOF'` that merely mentions `gcloud … delete` is not held.
107 */
108export function stripHeredocs(command: string): string {
109 const lines = command.split('\n')
110 const out: string[] = []
111 let end: { word: string; tabs: boolean } | null = null
112 for (const line of lines) {
113 if (end) {
114 const probe = end.tabs ? line.replace(/^\t+/, '') : line
115 if (probe === end.word) end = null
116 continue
117 }
118 out.push(line)
119 const m = /<<(-?)\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\2/.exec(line)
120 if (m && m[3]) end = { word: m[3], tabs: m[1] === '-' }
121 }
122 return out.join('\n')
123}
124
125/** The command line split on &&, ||, ;, | and newlines (quotes are not honoured here, as in the shell's coarse view). */
126export function splitSegments(command: string): string[] {
127 return command
128 .split(/&&|\|\||;|\||\n/)
129 .map(s => s.trim())
130 .filter(Boolean)
131}
132
133// sudo options that take a value, so the value is not read as the command.
134const SUDO_VALUE_OPTIONS = new Set(['-u', '-g', '-C', '-D', '-h', '-p', '-r', '-t', '-T', '-U'])
135// Words that can come before the real command without changing what it does.
136const PREFIXES = new Set(['command', 'exec', 'env', 'nohup', 'time', 'then', 'do', 'else', '!'])
137
138/** Strips VAR=value, sudo, nice, env/exec/nohup/time and ( { wrappers from the front of a segment's words. */
139export function stripWrappers(input: readonly string[]): string[] {
140 const words = [...input]
141 while (words.length && /^[({]+$/.test(words[0] as string)) words.shift()
142 if (words.length) words[0] = (words[0] as string).replace(/^[({]+/, '')
143 while (words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0] as string)) words.shift()
144 if (words[0] === 'sudo') {
145 words.shift()
146 while (words.length && (words[0] as string).startsWith('-')) {
147 const option = words.shift() as string
148 if (SUDO_VALUE_OPTIONS.has(option)) words.shift()
149 }
150 }
151 while (words.length && (PREFIXES.has(words[0] as string) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0] as string))) words.shift()
152 if (words[0] === 'nice') {
153 words.shift()
154 const after: string | undefined = words[0]
155 if (after === '-n') words.splice(0, 2)
156 else if (/^-\d+$/.test(after ?? '')) words.shift()
157 }
158 if (words.length) {
159 const last = words.length - 1
160 words[last] = (words[last] as string).replace(/[)}]+$/, '')
161 if (words[last] === '') words.pop()
162 }
163 return words
164}
165
166// ── gcloud vocabulary ──────────────────────────────────────────────────────
167
168/** Groups whose commands only touch the local machine: credentials, the SDK itself, help. Never held. */
169const LOCAL_GROUPS = new Set(['auth', 'components', 'help', 'info', 'version', 'feedback', 'topic', 'cheat-sheet', 'survey', 'interactive', 'meta', 'emulators', 'init', 'docker'])
170
171/** Verbs that only read. Always win. */
172export const READ_ONLY_VERBS = new Set([
173 'describe', 'list', 'get', 'get-iam-policy', 'get-value', 'get-ancestors', 'get-ancestors-iam-policy', 'get-credentials',
174 'ls', 'cat', 'stat', 'du', 'hash', 'version', 'info', 'help', 'read', 'tail', 'print-access-token', 'print-identity-token',
175 'print-settings', 'check', 'test-iam-permissions', 'ssh', 'scp', 'logs', 'log', 'explain', 'lint', 'search', 'query',
176 'diff', 'which', 'lookup', 'sign-blob', 'sign-jwt', 'generate-id-token', 'wait', 'stream-logs', 'get-serial-port-output',
177 'tail-serial-port-output', 'get-guest-attributes', 'get-shielded-identity', 'get-screenshot', 'get-config', 'sign-url',
178 'exists', 'validate', 'preview', 'simulate', 'dry-run', 'show', 'export-schema',
179])
180const READ_ONLY_PREFIXES = ['list-', 'describe-', 'get-', 'print-', 'show-', 'check-', 'test-', 'verify-', 'search-', 'lookup-', 'explain-', 'tail-', 'fetch-']
181
182export const DESTRUCTIVE_VERBS = new Set([
183 'delete', 'remove', 'destroy', 'purge', 'rm', 'rb', 'reset', 'abandon', 'cancel', 'revoke', 'wipe', 'detach', 'rollback',
184 'erase', 'unregister', 'unbind', 'uninstall', 'terminate', 'kill', 'drop', 'truncate', 'evict', 'teardown', 'expire', 'unlink',
185])
186const DESTRUCTIVE_PREFIXES = ['remove-', 'delete-', 'detach-', 'revoke-', 'unregister-', 'unbind-', 'drop-', 'purge-', 'destroy-']
187
188export const MUTATING_VERBS = new Set([
189 'update', 'patch', 'set', 'enable', 'disable', 'start', 'stop', 'suspend', 'resume', 'resize', 'move', 'rename', 'promote',
190 'failover', 'restart', 'reboot', 'attach', 'migrate', 'apply', 'replace', 'restore', 'import', 'export', 'upload', 'rotate',
191 'activate', 'deactivate', 'deploy', 'submit', 'unset', 'rsync', 'cp', 'mv', 'setmeta', 'undelete', 'execute', 'run', 'trigger', 'edit',
192 'bind', 'grant', 'install', 'upgrade', 'downgrade', 'lock', 'unlock', 'scale', 'drain', 'cordon', 'uncordon', 'approve',
193 'reject', 'abort', 'retry', 'rerun', 'recreate', 'reconcile', 'sync', 'flush', 'refresh', 'repair', 'recover', 'reload',
194 'redeploy', 'override', 'acquire', 'release', 'renew', 'extend', 'pause', 'unpause', 'simulate-maintenance-event',
195 'send', 'perform', 'invalidate', 'modify', 'transfer', 'label', 'tag', 'compose', 'rewrite', 'setup', 'configure', 'mark',
196 'ack', 'seek', 'pull-and-ack', 'modify-ack-deadline', 'modify-message-ack-deadline', 'modify-push-config',
197 'add-iam-policy-binding', 'remove-iam-policy-binding', 'set-iam-policy',
198])
199const MUTATING_PREFIXES = ['update-', 'set-', 'add-', 'attach-', 'start-', 'stop-', 'enable-', 'disable-', 'restore-', 'resize-',
200 'rotate-', 'move-', 'import-', 'export-', 'upload-', 'apply-', 'replace-', 'promote-', 'suspend-', 'resume-', 'migrate-',
201 'modify-', 'reset-', 'simulate-', 'send-', 'trigger-', 'bind-', 'grant-', 'install-', 'upgrade-', 'lock-', 'unlock-', 'scale-',
202 'approve-', 'reject-', 'abort-', 'retry-', 'sync-', 'flush-', 'refresh-', 'repair-', 'recover-', 'reload-', 'override-',
203 'acquire-', 'release-', 'renew-', 'extend-', 'pause-', 'unpause-', 'mark-', 'ack-', 'seek-', 'configure-', 'setup-']
204
205export const CREATE_VERBS = new Set(['create', 'add', 'insert', 'mb', 'clone', 'snapshot', 'publish', 'register', 'copy', 'reserve', 'provision', 'generate', 'issue', 'mint'])
206const CREATE_PREFIXES = ['create-', 'clone-', 'snapshot-', 'register-', 'provision-', 'generate-']
207
208/** Flags that never take a value (so the next word is not swallowed). `--no-*`, `--enable-*` and the like are handled by prefix. */
209const BOOL_FLAGS = new Set([
210 'quiet', 'q', 'async', 'force', 'help', 'h', 'all', 'recursive', 'r', 'R', 'dry-run', 'verbose', 'v', 'to-latest',
211 'delete', 'delete-unmatched-destination-objects', 'continue-on-error', 'no-clobber', 'ignore-existing', 'gzip-local',
212 'm', 'n', 'd', 'a', 'f', 'p', 'u', 'preemptible', 'spot', 'interactive', 'detailed', 'uri', 'log-http', 'user-output-enabled',
213 'allow-unauthenticated', 'ingress-internal', 'cpu-throttling', 'clear-labels', 'clear-env-vars', 'clear-secrets', 'clear-tags',
214 'await', 'keep-disks', 'strict', 'exact', 'readonly', 'public', 'private', 'yes', 'y', 'global', 'default', 'primary',
215])
216const BOOL_PREFIXES = ['no-', 'enable-', 'disable-', 'allow-', 'use-', 'skip-', 'clear-', 'is-', 'include-', 'exclude-', 'with-', 'without-', 'auto-']
217
218/** Flags whose value names the project, account or location: read into `flags`. */
219const GLOBAL_VALUE_FLAGS = new Set(['project', 'account', 'configuration', 'zone', 'region', 'location', 'impersonate-service-account', 'format', 'filter', 'billing-project', 'verbosity', 'access-token-file', 'flags-file', 'limit', 'sort-by', 'page-size'])
220
221function isBoolFlag(name: string): boolean {
222 if (BOOL_FLAGS.has(name)) return true
223 return BOOL_PREFIXES.some(p => name.startsWith(p))
224}
225
226function verbSeverity(verb: string): { severity: Severity; readOnly?: true } | null {
227 if (READ_ONLY_VERBS.has(verb) || READ_ONLY_PREFIXES.some(p => verb.startsWith(p))) return { severity: 'create', readOnly: true }
228 if (verb === 'undelete') return { severity: 'mutating' }
229 if (DESTRUCTIVE_VERBS.has(verb) || DESTRUCTIVE_PREFIXES.some(p => verb.startsWith(p))) return { severity: 'destructive' }
230 if (MUTATING_VERBS.has(verb) || MUTATING_PREFIXES.some(p => verb.startsWith(p))) return { severity: 'mutating' }
231 if (CREATE_VERBS.has(verb) || CREATE_PREFIXES.some(p => verb.startsWith(p))) return { severity: 'create' }
232 return null
233}
234
235/** Verb stems that mean "do something to the resource", for a verb the table does not know. */
236const ACTION_STEMS = new Set(['simulate', 'send', 'trigger', 'run', 'execute', 'perform', 'apply', 'reset', 'invoke', 'modify', 'replace',
237 'attach', 'detach', 'bind', 'unbind', 'grant', 'revoke', 'lock', 'unlock', 'register', 'unregister', 'install', 'uninstall', 'upgrade',
238 'downgrade', 'scale', 'drain', 'cordon', 'uncordon', 'provision', 'deprovision', 'approve', 'reject', 'promote', 'abort', 'retry',
239 'rerun', 'recreate', 'reconcile', 'sync', 'seal', 'unseal', 'rotate', 'flush', 'truncate', 'refresh', 'repair', 'repack', 'vacuum',
240 'convert', 'transform', 'encrypt', 'recover', 'restore', 'reload', 'redeploy', 'override', 'acquire', 'release', 'renew', 'extend',
241 'reduce', 'increase', 'decrease', 'shrink', 'grow', 'expand', 'pause', 'unpause', 'terminate', 'kill', 'drop', 'evict', 'migrate',
242 'patch', 'update', 'set', 'add', 'remove', 'delete', 'create', 'enable', 'disable', 'start', 'stop', 'resume', 'suspend'])
243
244/** Groups whose commands can reach cloud resources; an unknown action verb under one of these is held to be safe. */
245const KNOWN_GROUPS = new Set(['compute', 'container', 'run', 'sql', 'storage', 'iam', 'projects', 'functions', 'pubsub', 'redis', 'memcache',
246 'spanner', 'bigtable', 'firestore', 'datastore', 'dataproc', 'dataflow', 'composer', 'scheduler', 'tasks', 'secrets', 'kms', 'dns',
247 'domains', 'app', 'builds', 'artifacts', 'deploy', 'workflows', 'eventarc', 'logging', 'monitoring', 'services', 'resource-manager',
248 'organizations', 'folders', 'billing', 'filestore', 'netapp', 'apigee', 'ai', 'ai-platform', 'notebooks', 'workstations', 'batch',
249 'vmware', 'bms', 'transfer', 'certificate-manager', 'endpoints', 'api-gateway', 'access-context-manager', 'identity', 'beyondcorp',
250 'essential-contacts', 'asset', 'recommender', 'scc', 'source', 'firebase', 'healthcare', 'lifesciences', 'alloydb', 'datastream',
251 'data-catalog', 'dataplex', 'looker', 'iap', 'privateca', 'network-security', 'network-services', 'network-connectivity',
252 'infra-manager', 'edge-cache', 'bq', 'gke-hub', 'fleet', 'anthos', 'backup-dr', 'parallelstore', 'memorystore', 'developer-connect',
253 'immersive-stream', 'media', 'migration', 'policy-intelligence', 'policy-troubleshoot', 'publicca', 'quotas', 'runtime-config',
254 'service-directory', 'service-extensions', 'telco-automation', 'colab', 'database-migration', 'dataplex', 'edge-container', 'ids',
255 'metastore', 'ml', 'ml-engine', 'oracle-database', 'managed-kafka', 'netapp', 'org-policies', 'recaptcha', 'resource-settings',
256 'storage-insights', 'web-security-scanner', 'workload-certificate', 'workspace-add-ons'])
257
258const STORAGE_VERBS = new Set(['rm', 'rb', 'mb', 'cp', 'mv', 'rsync', 'setmeta', 'compose', 'rewrite', 'ls', 'cat', 'stat', 'du', 'hash', 'sign-url'])
259
260// ── gcloud ─────────────────────────────────────────────────────────────────
261
262type Parsed = {
263 track: Track
264 path: string[]
265 verb: string | null
266 targets: string[]
267 flags: RiskFlags
268 extra: Record<string, string | true>
269}
270
271/** Reads the words after `gcloud`: the release track, the group path, the verb, the targets and the flags. */
272export function parseGcloudArgs(args: readonly string[]): Parsed {
273 const out: Parsed = { track: 'ga', path: [], verb: null, targets: [], flags: { quiet: false }, extra: {} }
274 let i = 0
275 if (args[0] === 'alpha' || args[0] === 'beta') {
276 out.track = args[0]
277 i = 1
278 }
279 const setGlobal = (name: string, value: string | true) => {
280 if (value === true) return
281 if (name === 'project') out.flags.project = value
282 else if (name === 'account') out.flags.account = value
283 else if (name === 'configuration') out.flags.configuration = value
284 else if (name === 'zone') out.flags.zone = value
285 else if (name === 'region') out.flags.region = value
286 else if (name === 'location') out.flags.location = value
287 else if (name === 'impersonate-service-account') out.flags.impersonate = value
288 }
289 for (; i < args.length; i += 1) {
290 const w = args[i] as string
291 if (w === '--') {
292 for (const rest of args.slice(i + 1)) (out.verb === null ? out.path : out.targets).push(rest)
293 break
294 }
295 if (w.startsWith('--')) {
296 const eq = w.indexOf('=')
297 const name = eq === -1 ? w.slice(2) : w.slice(2, eq)
298 let value: string | true = eq === -1 ? true : w.slice(eq + 1)
299 if (eq === -1 && !isBoolFlag(name)) {
300 const next = args[i + 1]
301 if (next !== undefined && !next.startsWith('-')) {
302 value = next
303 i += 1
304 }
305 }
306 if (name === 'quiet') out.flags.quiet = true
307 else if (GLOBAL_VALUE_FLAGS.has(name)) setGlobal(name, value)
308 out.extra[name] = value
309 continue
310 }
311 if (w === '-q') {
312 out.flags.quiet = true
313 out.extra.q = true
314 continue
315 }
316 if (w.startsWith('-') && w.length > 1) {
317 out.extra[w.slice(1)] = true
318 continue
319 }
320 if (out.verb === null) {
321 // The first word is always a group (`run`, `deploy`, `config`), even when it is also a verb elsewhere
322 if (out.path.length > 0 && verbSeverity(w) !== null) out.verb = w
323 else out.path.push(w)
324 } else out.targets.push(w)
325 }
326 return out
327}
328
329function unknownVerbOf(path: readonly string[]): number {
330 for (let k = 1; k < path.length; k += 1) {
331 const w = path[k] as string
332 const stem = w.includes('-') ? (w.split('-')[0] as string) : w
333 if (ACTION_STEMS.has(stem)) return k
334 }
335 return -1
336}
337
338/** One gcloud segment (words after `gcloud`) to a risk, or null when it only reads or stays local. */
339export function classifyGcloud(args: readonly string[], raw: string, settings: Settings): Risk | null {
340 const p = parseGcloudArgs(args)
341 const group = p.path[0] ?? ''
342 if (LOCAL_GROUPS.has(group)) return null
343 const base: Omit<Risk, 'severity' | 'verb'> = { tool: 'gcloud', track: p.track, path: p.path, targets: p.targets, flags: p.flags, extra: p.extra, raw }
344
345 // gcloud config: only set / unset / configurations activate|create|delete|rename change what later commands hit
346 if (group === 'config') {
347 const sub = p.path[1]
348 if (p.verb === 'set' || p.verb === 'unset' || (sub === 'configurations' && (p.verb === 'activate' || p.verb === 'create' || p.verb === 'delete' || p.verb === 'rename'))) {
349 return { ...base, verb: p.verb, severity: 'mutating', kind: 'local-config' }
350 }
351 return null
352 }
353
354 if (p.verb === null) {
355 if (!KNOWN_GROUPS.has(group)) return null
356 const k = unknownVerbOf(p.path)
357 if (k === -1) return null
358 const verb = p.path[k] as string
359 return { ...base, path: p.path.slice(0, k), targets: [...p.path.slice(k + 1), ...p.targets], verb, severity: 'mutating', kind: 'unknown', unknownVerb: true }
360 }
361 const sev = verbSeverity(p.verb)
362 if (sev === null || sev.readOnly) return null
363 const risk: Risk = { ...base, verb: p.verb, severity: sev.severity }
364 void settings
365
366 // Kinds the UI treats specially
367 if (group === 'storage' && STORAGE_VERBS.has(p.verb)) risk.kind = 'storage'
368 else if (p.verb === 'deploy') {
369 risk.kind = 'deploy'
370 risk.severity = 'mutating'
371 } else if (group === 'builds' && p.verb === 'submit') {
372 risk.kind = 'build'
373 risk.severity = 'mutating'
374 } else if (p.verb === 'add-iam-policy-binding' || p.verb === 'remove-iam-policy-binding' || p.verb === 'set-iam-policy') {
375 risk.kind = 'iam'
376 risk.severity = p.verb === 'remove-iam-policy-binding' ? 'destructive' : 'mutating'
377 }
378 // Whole-project / org / folder operations
379 if (risk.severity === 'destructive' && p.path.length === 1) {
380 if (group === 'projects') risk.scope = 'project'
381 else if (group === 'organizations') risk.scope = 'org'
382 else if (group === 'folders') risk.scope = 'folder'
383 }
384 return risk
385}
386
387// ── gsutil ─────────────────────────────────────────────────────────────────
388
389/** gsutil commands whose first positional word is a sub-verb (get / set / ch / ...). */
390const GSUTIL_CONFIG_CMDS = new Set(['acl', 'defacl', 'iam', 'lifecycle', 'versioning', 'web', 'cors', 'label', 'retention', 'logging',
391 'requesterpays', 'ubla', 'pap', 'autoclass', 'kms', 'notification', 'hmac', 'bucketpolicyonly', 'defstorageclass', 'rpo'])
392const GSUTIL_READ_ONLY = new Set(['ls', 'cat', 'stat', 'du', 'hash', 'version', 'help', 'test', 'signurl'])
393const GSUTIL_GLOBAL_VALUE = new Set(['-o', '-h', '-i', '-u'])
394
395/** One gsutil segment (words after `gsutil`) to a risk, or null. */
396export function classifyGsutil(args: readonly string[], raw: string): Risk | null {
397 const flags: RiskFlags = { quiet: false }
398 const extra: Record<string, string | true> = {}
399 let i = 0
400 // Global options come before the command: -m, -q, -D, -o X, -h X, -i SA, -u PROJECT
401 while (i < args.length && (args[i] as string).startsWith('-')) {
402 const w = args[i] as string
403 if (GSUTIL_GLOBAL_VALUE.has(w)) {
404 const v = args[i + 1] ?? ''
405 if (w === '-u') flags.project = v
406 if (w === '-i') flags.impersonate = v
407 extra[w.slice(1)] = v
408 i += 2
409 continue
410 }
411 if (w === '-q') flags.quiet = true
412 extra[w.slice(1)] = true
413 i += 1
414 }
415 const cmd = args[i]
416 if (!cmd) return null
417 i += 1
418 const rest = args.slice(i)
419 const positional: string[] = []
420 for (const w of rest) {
421 if (w.startsWith('-')) extra[w.replace(/^-+/, '')] = true
422 else positional.push(w)
423 }
424 const base = { tool: 'gsutil' as const, track: 'ga' as const, flags, extra, raw }
425 if (GSUTIL_READ_ONLY.has(cmd)) return null
426 if (GSUTIL_CONFIG_CMDS.has(cmd)) {
427 const sub = positional[0] ?? ''
428 const targets = positional.slice(1)
429 if (sub === 'get' || sub === 'list' || sub === '') return null
430 const severity: Severity = sub === 'delete' || sub === 'clear' || sub === 'del' ? 'destructive' : sub === 'create' ? 'create' : 'mutating'
431 return { ...base, path: [cmd], verb: sub, severity, kind: cmd === 'iam' || cmd === 'acl' || cmd === 'defacl' ? 'iam' : 'storage', targets }
432 }
433 if (cmd === 'rm' || cmd === 'rb') return { ...base, path: [], verb: cmd, severity: 'destructive', kind: 'storage', targets: positional }
434 if (cmd === 'mb') return { ...base, path: [], verb: cmd, severity: 'create', kind: 'storage', targets: positional }
435 if (cmd === 'cp' || cmd === 'mv' || cmd === 'rsync' || cmd === 'setmeta' || cmd === 'compose' || cmd === 'rewrite' || cmd === 'perfdiag') {
436 return { ...base, path: [], verb: cmd, severity: 'mutating', kind: 'storage', targets: positional }
437 }
438 return null
439}
440
441// ── The command line ───────────────────────────────────────────────────────
442
443/** The first gcloud / gsutil segment of the command line that would change something, or null. */
444export function classify(command: string, settings: Settings): Risk | null {
445 for (const raw of splitSegments(stripHeredocs(command))) {
446 const words = stripWrappers(tokenize(raw))
447 const first = words[0]
448 if (!first) continue
449 const cmd = first.replace(/^\\/, '')
450 if (cmd === 'gcloud' || cmd.endsWith('/gcloud')) {
451 const risk = classifyGcloud(words.slice(1), raw, settings)
452 if (risk) return risk
453 continue
454 }
455 if (settings.includeGsutil && (cmd === 'gsutil' || cmd.endsWith('/gsutil'))) {
456 const risk = classifyGsutil(words.slice(1), raw)
457 if (risk) return risk
458 }
459 }
460 return null
461}
462
463// ── Lookups: the argv of the read-only commands ────────────────────────────
464
465/** `--zone=…`, `--region=…`, `--location=…`, `--project=…`, `--account=…`, `--impersonate-service-account=…` as given. */
466export function scopeFlags(flags: RiskFlags): string[] {
467 const out: string[] = []
468 if (flags.zone) out.push(`--zone=${flags.zone}`)
469 if (flags.region) out.push(`--region=${flags.region}`)
470 if (flags.location) out.push(`--location=${flags.location}`)
471 if (flags.project) out.push(`--project=${flags.project}`)
472 if (flags.account) out.push(`--account=${flags.account}`)
473 if (flags.configuration) out.push(`--configuration=${flags.configuration}`)
474 if (flags.impersonate) out.push(`--impersonate-service-account=${flags.impersonate}`)
475 return out
476}
477
478function trackWords(track: Track): string[] {
479 return track === 'ga' ? [] : [track]
480}
481
482/** `gcloud [track] <path> describe <target> --format=json <scope flags>` */
483export function describeArgv(risk: Risk, target: string): string[] {
484 return ['gcloud', ...trackWords(risk.track), ...risk.path, 'describe', target, '--format=json', ...scopeFlags(risk.flags)]
485}
486
487/** `gcloud [track] <path> get-iam-policy <target> --format=json <scope flags>` */
488export function getIamPolicyArgv(risk: Risk, target: string): string[] {
489 return ['gcloud', ...trackWords(risk.track), ...risk.path, 'get-iam-policy', target, '--format=json', ...scopeFlags(risk.flags)]
490}
491
492/** The read-only listing of a storage URL, with the tool the person used. */
493export function listObjectsArgv(risk: Risk, url: string): string[] {
494 if (risk.tool === 'gsutil') return ['gsutil', 'ls', '-r', url]
495 return ['gcloud', 'storage', 'ls', '-r', url, ...scopeFlags(risk.flags)]
496}
497
498export function configGetArgv(property: string, flags: RiskFlags): string[] {
499 const out = ['gcloud', 'config', 'get-value', property]
500 if (flags.configuration) out.push(`--configuration=${flags.configuration}`)
501 return out
502}
503
504export function projectDescribeArgv(id: string, flags: RiskFlags): string[] {
505 const out = ['gcloud', 'projects', 'describe', id, '--format=json']
506 if (flags.account) out.push(`--account=${flags.account}`)
507 if (flags.impersonate) out.push(`--impersonate-service-account=${flags.impersonate}`)
508 return out
509}
510
511export function servicesListArgv(id: string, flags: RiskFlags): string[] {
512 const out = ['gcloud', 'services', 'list', '--enabled', `--project=${id}`, '--format=value(config.name)', '--limit=50']
513 if (flags.account) out.push(`--account=${flags.account}`)
514 if (flags.impersonate) out.push(`--impersonate-service-account=${flags.impersonate}`)
515 return out
516}
517
518/** Whether the storage verb deletes objects at the destination (rsync -d / --delete-unmatched-destination-objects). */
519export function isRsyncDelete(risk: Risk): boolean {
520 return risk.verb === 'rsync' && (risk.extra.d === true || risk.extra['delete-unmatched-destination-objects'] === true)
521}
522
523/** Storage URLs among the targets (sources of rm / mv / rb / rsync, destination of cp excluded). */
524export function storageUrls(risk: Risk): string[] {
525 const urls = risk.targets.filter(x => x.startsWith('gs://'))
526 if (risk.verb === 'cp' || risk.verb === 'mv' || risk.verb === 'rsync') return urls.slice(0, Math.max(0, urls.length - 1))
527 return urls
528}
529
530/** The flags that say how big a thing is being created, for the create-class summary. */
531export const KEY_CREATE_FLAGS = ['machine-type', 'size', 'tier', 'num-nodes', 'image', 'image-family', 'memory', 'cpu', 'min-instances', 'max-instances', 'disk-size', 'database-version', 'storage-size', 'node-count', 'replicas', 'capacity', 'boot-disk-size']
532
533export function keyFlagsLine(risk: Risk): string | null {
534 const parts: string[] = []
535 for (const name of KEY_CREATE_FLAGS) {
536 const v = risk.extra[name]
537 if (v !== undefined && v !== true) parts.push(`--${name}=${v}`)
538 }
539 return parts.length ? parts.join(' ') : null
540}
541
542// ── Describe JSON → one line ───────────────────────────────────────────────
543
544type Json = Record<string, unknown>
545
546function str(v: unknown): string | null {
547 return typeof v === 'string' && v !== '' ? v : null
548}
549
550function numOf(v: unknown): number | null {
551 if (typeof v === 'number') return v
552 if (typeof v === 'string' && /^\d+$/.test(v)) return Number(v)
553 return null
554}
555
556function dateOf(v: unknown): string | null {
557 const s = str(v)
558 if (!s) return null
559 const m = /^(\d{4}-\d{2}-\d{2})/.exec(s)
560 return m ? (m[1] as string) : s
561}
562
563/** A compact description of a resource from its describe JSON, and the notes it raises (deletion protection). */
564export function summarizeDescribe(lang: Lang, target: string, json: unknown): { line: string; notes: string[] } {
565 const o = (json && typeof json === 'object' ? json : {}) as Json
566 const parts: string[] = [str(o.name) ?? target]
567 const status = str(o.status) ?? str(o.state)
568 if (status) parts.push(status)
569 const where = str(o.zone) ?? str(o.region) ?? str(o.location) ?? str(o.locationId)
570 if (where) parts.push(baseName(where))
571 const machine = str(o.machineType)
572 if (machine) parts.push(baseName(machine))
573 const settings = (o.settings && typeof o.settings === 'object' ? o.settings : null) as Json | null
574 const tier = settings ? str(settings.tier) : null
575 const dbv = str(o.databaseVersion)
576 if (dbv) parts.push(tier ? `${dbv} ${tier}` : dbv)
577 const size = numOf(o.sizeGb) ?? numOf(o.diskSizeGb)
578 if (size !== null) parts.push(`${size} GB`)
579 const nodes = numOf(o.currentNodeCount) ?? numOf(o.initialNodeCount)
580 if (nodes !== null) parts.push(t(lang, 'line.nodes', { n: nodes }))
581 const created = dateOf(o.creationTimestamp) ?? dateOf(o.createTime)
582 if (created) parts.push(t(lang, 'line.created', { date: created }))
583 const labels = o.labels && typeof o.labels === 'object' ? Object.keys(o.labels as Json).length : 0
584 if (labels) parts.push(t(lang, 'line.labels', { n: labels }))
585 const disks = Array.isArray(o.disks) ? (o.disks as Json[]) : null
586 if (disks && disks.length) parts.push(t(lang, 'line.disks', { n: disks.length, autoDelete: disks.filter(d => d.autoDelete === true).length }))
587 const bindings = Array.isArray(o.bindings) ? (o.bindings as unknown[]).length : null
588 if (bindings !== null) parts.push(t(lang, 'line.bindings', { n: bindings }))
589 const notes: string[] = []
590 if (o.deletionProtection === true || o.deleteProtection === true || (settings && settings.deletionProtectionEnabled === true)) {
591 notes.push(t(lang, 'note.deletionProtection', { target }))
592 }
593 return { line: parts.join(' · '), notes }
594}
595
596/** Whether a failed describe says the resource does not exist. */
597export function isNotFound(stderr: string): boolean {
598 return /not found|notfound|404|does not exist|could not fetch resource/i.test(stderr)
599}
600
601/** The objects a storage listing holds: lines that are object URLs, not bucket or prefix headers. */
602export function countObjects(stdout: string): { n: number; cut: boolean } {
603 let n = 0
604 for (const line of stdout.split('\n')) {
605 const s = line.trim()
606 if (!s.startsWith('gs://') || s.endsWith('/') || s.endsWith(':')) continue
607 n += 1
608 if (n >= MAX_OBJECTS_COUNTED) return { n, cut: true }
609 }
610 return { n, cut: false }
611}
612
613// ── Report text ────────────────────────────────────────────────────────────
614
615export function severityLabel(lang: Lang, severity: Severity): string {
616 return t(lang, severity === 'destructive' ? 'severity.destructive' : severity === 'mutating' ? 'severity.mutating' : 'severity.create')
617}
618
619export function typeLabel(risk: Risk): string {
620 if (risk.tool === 'gsutil') return risk.path.length ? `gsutil ${risk.path.join(' ')}` : 'gsutil'
621 return risk.path.join(' ') || 'gcloud'
622}
623
624export function targetsLabel(risk: Risk, max = 4): string {
625 const list = risk.targets
626 if (!list.length) return ''
627 const shown = list.slice(0, max).map(x => truncate(x, 48))
628 return list.length > max ? `${shown.join(', ')} (+${list.length - max})` : shown.join(', ')
629}
630
631/** The headline of the pane and of the refusal. `current` is the current config value for a local-config change. */
632export function headline(lang: Lang, risk: Risk, current: string | null = null): string {
633 const type = typeLabel(risk)
634 const targets = targetsLabel(risk)
635 if (risk.scope === 'project') return t(lang, 'headline.project', { id: risk.targets[0] ?? '?' })
636 if (risk.scope === 'org' || risk.scope === 'folder') return t(lang, 'headline.org', { kind: risk.scope === 'org' ? 'organization' : 'folder', id: risk.targets[0] ?? '?' })
637 if (risk.kind === 'local-config') {
638 const property = risk.targets[0] ?? '?'
639 const value = risk.verb === 'unset' ? '(unset)' : (risk.targets[1] ?? '?')
640 return t(lang, 'headline.config', { property, value, current: current ?? t(lang, 'value.unknown') })
641 }
642 if (risk.kind === 'deploy') return t(lang, 'headline.deploy', { type, targets })
643 if (risk.kind === 'build') return t(lang, 'headline.build', { targets })
644 if (risk.kind === 'iam' && risk.tool === 'gcloud') {
645 const member = String(risk.extra.member ?? '?')
646 const role = String(risk.extra.role ?? '?')
647 if (risk.verb === 'add-iam-policy-binding') return t(lang, 'headline.iamAdd', { member, role, type, targets })
648 if (risk.verb === 'remove-iam-policy-binding') return t(lang, 'headline.iamRemove', { member, role, type, targets })
649 if (risk.verb === 'set-iam-policy') return t(lang, 'headline.iamSet', { type, targets: risk.targets[0] ?? '?' })
650 }
651 if (risk.kind === 'storage') {
652 if (risk.verb === 'rm' || risk.verb === 'rb') return t(lang, 'headline.storageRm', { targets: targetsLabel(risk, 3) })
653 if (risk.verb === 'cp' || risk.verb === 'mv' || risk.verb === 'rsync') return t(lang, 'headline.storageCopy', { verb: risk.verb, targets: targetsLabel(risk, 3) })
654 }
655 return t(lang, 'headline.generic', { verb: risk.verb, type, targets })
656}
657
658export function emptyContext(risk: Risk): ReportContext {
659 return {
660 account: risk.flags.account ?? null,
661 project: risk.flags.project ?? null,
662 projectSource: risk.flags.project ? 'flag' : 'unknown',
663 configuration: risk.flags.configuration ?? null,
664 location: risk.flags.zone ?? risk.flags.region ?? risk.flags.location ?? null,
665 track: risk.track,
666 quiet: risk.flags.quiet,
667 impersonate: risk.flags.impersonate ?? null,
668 }
669}
670
671/** The text of the refusal Claude reads. */
672export function denyText(lang: Lang, why: 'cancel' | 'timeout' | 'interrupted' | 'error' | 'none', head: string, project: string | null): string {
673 const whyKey = why === 'cancel' ? 'why.cancel' : why === 'timeout' ? 'why.timeout' : why === 'interrupted' ? 'why.interrupted' : why === 'error' ? 'why.error' : 'why.none'
674 return t(lang, 'deny', { why: t(lang, whyKey), headline: head, project: project ?? t(lang, 'value.unknown') })
675}
676
677/** The rows the pane would need: title and headline, the context block, the lines, the notes, the buttons row. */
678export function paneRows(report: Report | null, hasGke = false, commandRowCount = 1): number {
679 const extra = Math.max(0, commandRowCount)
680 if (!report) return 8 + extra
681 return Math.min(32, 9 + extra + report.lines.length + report.notes.length + (report.context.quiet ? 1 : 0) + (report.context.track !== 'ga' ? 1 : 0) + (hasGke ? 1 : 0))
682}
683
684// ── The context line: gcloud and kube config files ─────────────────────────
685
686/** A gcloud configuration file (INI): `[section]` headers, `key = value` rows, `#` and `;` comments. Keys are `section/key`. */
687export function parseGcloudIni(text: string): Record<string, string> {
688 const out: Record<string, string> = {}
689 let section = ''
690 for (const raw of text.split('\n')) {
691 const line = raw.trim()
692 if (!line || line.startsWith('#') || line.startsWith(';')) continue
693 const head = /^\[([^\]]+)\]$/.exec(line)
694 if (head) {
695 section = (head[1] as string).trim()
696 continue
697 }
698 const eq = line.indexOf('=')
699 if (eq === -1) continue
700 const key = line.slice(0, eq).trim()
701 const value = line.slice(eq + 1).trim()
702 if (!key) continue
703 out[section ? `${section}/${key}` : key] = value
704 }
705 return out
706}
707
708/** The current kubectl context by name: `gke_<project>_<location>_<cluster>` is a GKE cluster, anything else is `other`. */
709export function parseKubeContext(name: string): KubeContext {
710 const n = name.trim()
711 if (n.startsWith('gke_')) {
712 const parts = n.split('_')
713 // gke, project, location, then the cluster (which may hold no `_`, so the rest is joined back for safety)
714 if (parts.length >= 4 && parts[1] && parts[2] && parts[3]) {
715 return { kind: 'gke', name: n, project: parts[1], location: parts[2], cluster: parts.slice(3).join('_') }
716 }
717 }
718 return { kind: 'other', name: n }
719}
720
721/** The `current-context:` line of a kubeconfig, or null. No YAML parser: one regex. */
722export function currentContextOf(kubeconfigText: string): string | null {
723 const m = /^\s*current-context:\s*["']?([^"'\n#]+?)["']?\s*(?:#.*)?$/m.exec(kubeconfigText)
724 const v = m?.[1]?.trim()
725 return v ? v : null
726}
727
728/** KUBECONFIG is a colon-separated list; the first file that names a current context wins. */
729export function splitKubeconfigList(value: string | undefined, home: string | null): string[] {
730 const list = (value ?? '').split(':').map(s => s.trim()).filter(Boolean)
731 if (list.length) return list
732 return home ? [`${home.replace(/\/+$/, '')}/.kube/config`] : []
733}
734
735export type ContextEnv = {
736 CLOUDSDK_CONFIG?: string
737 HOME?: string
738 CLOUDSDK_CORE_PROJECT?: string
739 CLOUDSDK_CORE_ACCOUNT?: string
740 CLOUDSDK_ACTIVE_CONFIG_NAME?: string
741 CLOUDSDK_COMPUTE_ZONE?: string
742 CLOUDSDK_COMPUTE_REGION?: string
743}
744
745export function gcloudConfigDir(env: ContextEnv): string | null {
746 const explicit = (env.CLOUDSDK_CONFIG ?? '').trim()
747 if (explicit) return explicit.replace(/\/+$/, '')
748 const home = (env.HOME ?? '').trim()
749 return home ? `${home.replace(/\/+$/, '')}/.config/gcloud` : null
750}
751
752/** Builds the snapshot from the files' texts and the env; the file reads themselves are the caller's. */
753export function buildContext(input: {
754 env: ContextEnv
755 configDir: string | null
756 activeConfigText: string | null
757 configText: string | null
758 kubeconfigPath: string | null
759 kubeconfigText: string | null
760 now: number
761}): GcloudContext {
762 const { env } = input
763 const configuration = (env.CLOUDSDK_ACTIVE_CONFIG_NAME ?? '').trim() || (input.activeConfigText ?? '').trim() || (input.configDir ? 'default' : '')
764 const ini = input.configText !== null ? parseGcloudIni(input.configText) : {}
765 const envProject = (env.CLOUDSDK_CORE_PROJECT ?? '').trim()
766 const fileProject = (ini['core/project'] ?? '').trim()
767 const project = envProject || fileProject || null
768 const account = (env.CLOUDSDK_CORE_ACCOUNT ?? '').trim() || (ini['core/account'] ?? '').trim() || null
769 const zone = (env.CLOUDSDK_COMPUTE_ZONE ?? '').trim() || (ini['compute/zone'] ?? '').trim() || null
770 const region = (env.CLOUDSDK_COMPUTE_REGION ?? '').trim() || (ini['compute/region'] ?? '').trim() || null
771 const name = input.kubeconfigText !== null ? currentContextOf(input.kubeconfigText) : null
772 return {
773 configDir: input.configDir,
774 configuration: configuration || null,
775 project,
776 projectSource: project ? (envProject ? 'env' : 'file') : null,
777 account,
778 zone,
779 region,
780 kubeconfig: input.kubeconfigPath,
781 kube: name ? parseKubeContext(name) : null,
782 readAt: input.now,
783 }
784}
785
786/** The dim line above the prompt; null when nothing is known. */
787export function contextLine(lang: Lang, ctx: GcloudContext | null, settings: Settings): string | null {
788 if (!ctx) return null
789 const parts: string[] = []
790 if (ctx.project) parts.push(`${t(lang, 'ctx.project', { project: ctx.project })}${ctx.projectSource === 'env' ? ` ${t(lang, 'ctx.fromEnv')}` : ''}`)
791 if (ctx.account) parts.push(t(lang, 'ctx.account', { account: ctx.account }))
792 if (ctx.configuration && (ctx.project || ctx.account)) parts.push(t(lang, 'ctx.config', { name: ctx.configuration }))
793 if (ctx.kube?.kind === 'gke') parts.push(t(lang, 'ctx.gke', { cluster: ctx.kube.cluster, location: ctx.kube.location }))
794 else if (ctx.kube && settings.showOtherContexts) parts.push(t(lang, 'ctx.k8s', { name: ctx.kube.name }))
795 if (!parts.length) return null
796 return `☁ gcloud · ${parts.join(' · ')}`
797}
798
799/** The `/gcloud-guard` output: the whole snapshot and the hold setting. */
800export function contextText(lang: Lang, ctx: GcloudContext | null, settings: Settings): string {
801 const none = t(lang, 'value.none')
802 const lines: string[] = []
803 if (!ctx || (!ctx.configDir && !ctx.project && !ctx.account)) lines.push(t(lang, 'cmd.none'))
804 else {
805 lines.push(t(lang, 'cmd.configDir', { dir: ctx.configDir ?? none }))
806 lines.push(t(lang, 'cmd.configuration', { name: ctx.configuration ?? none }))
807 lines.push(t(lang, 'cmd.project', { project: ctx.project ?? none, source: ctx.projectSource === 'env' ? t(lang, 'cmd.source.env') : t(lang, 'cmd.source.file') }))
808 lines.push(t(lang, 'cmd.account', { account: ctx.account ?? none }))
809 lines.push(t(lang, 'cmd.zone', { zone: ctx.zone ?? none, region: ctx.region ?? none }))
810 }
811 lines.push(t(lang, 'cmd.kubeconfig', { path: ctx?.kubeconfig ?? none }))
812 lines.push(t(lang, 'cmd.kubeContext', { name: ctx?.kube?.name ?? none }))
813 if (ctx?.kube?.kind === 'gke') lines.push(t(lang, 'cmd.gke', { project: ctx.kube.project, location: ctx.kube.location, cluster: ctx.kube.cluster }))
814 lines.push(t(lang, 'cmd.hold', { hold: settings.hold, gsutil: settings.includeGsutil ? 1 : 0, configSet: settings.holdConfigSet ? 1 : 0 }))
815 return lines.join('\n')
816}
817
818/** Bash commands after which the context may have changed: config, credentials, kube context switches. */
819export function touchesContext(command: string): boolean {
820 return /gcloud\s+(?:alpha\s+|beta\s+)?(?:config\b|auth\b|container\s+clusters\s+get-credentials)|kubectl\s+config\s+(?:use-context|set-context|set-cluster|unset)|\bkubectx\b/.test(command)
821}
822
823
824// ── Band framing ───────────────────────────────────────────────────────────
825
826/** How the mod's line above the prompt is framed: a rounded box, a thin rule beneath, or bare text. */
827export type BandStyle = 'box' | 'rule' | 'plain'
828
829/** The `band_style` option; anything but `rule` or `plain` is the default box. */
830export function parseBandStyle(v: unknown): BandStyle {
831 return v === 'rule' || v === 'plain' ? v : 'box'
832}
833
834// ── Showing the command ────────────────────────────────────────────────────
835
836/** More segments than this and the quiet ones around the risky one are folded. */
837export const SHOWN_SEGMENTS = 8
838
839export type CommandRow = { text: string; op: string; isRisky: boolean } | { fold: number }
840
841/**
842 * The command split where splitSegments() splits it, one row per segment with the operator
843 * that follows it, the segment classify() matched marked; long chains fold around it.
844 */
845export function commandRows(command: string, riskyRaw: string): CommandRow[] {
846 const parts = command.split(/(&&|\|\||;|\||\n)/)
847 const rows: { text: string; op: string; isRisky: boolean }[] = []
848 let marked = false
849 for (let i = 0; i < parts.length; i += 2) {
850 const text = (parts[i] ?? '').trim()
851 const sep = parts[i + 1]
852 const op = sep === undefined || sep === '\n' ? '' : sep
853 if (!text && !op) continue
854 const isRisky = !marked && text === riskyRaw.trim()
855 if (isRisky) marked = true
856 rows.push({ text, op, isRisky })
857 }
858 if (rows.length <= SHOWN_SEGMENTS) return rows
859 const at = Math.max(0, rows.findIndex(r => r.isRisky))
860 const from = Math.max(0, Math.min(at - 3, rows.length - SHOWN_SEGMENTS))
861 const to = from + SHOWN_SEGMENTS
862 const out: CommandRow[] = []
863 if (from > 0) out.push({ fold: from })
864 out.push(...rows.slice(from, to))
865 if (to < rows.length) out.push({ fold: rows.length - to })
866 return out
867}
868
869export type WordKind = 'space' | 'prefix' | 'head' | 'track' | 'group' | 'verb' | 'danger-flag' | 'flag' | 'target' | 'plain'
870
871const DANGER_FLAGS = /^(-q|--quiet|--force|-f|--delete-unmatched-destination-objects|-d|--recursive|-r|-R)$/
872
873/**
874 * The risky segment as classified words for colouring: the tool and the verb red, the
875 * release track magenta, `--quiet` / `--force` style flags red, other flags dim, targets yellow.
876 */
877export function riskyWords(text: string, risk: Pick<Risk, 'path' | 'verb' | 'targets'>): { text: string; kind: WordKind }[] {
878 const pieces = text.split(/(\s+)/)
879 const targets = new Set(risk.targets)
880 const groups = [...risk.path]
881 let seenHead = false
882 let seenVerb = false
883 return pieces
884 .filter(p => p !== '')
885 .map(piece => {
886 if (/^\s+$/.test(piece)) return { text: piece, kind: 'space' as const }
887 const bare = piece.replace(/^['"]|['"]$/g, '')
888 if (!seenHead) {
889 if (/^(gcloud|gsutil)$/.test(bare.replace(/^.*\//, '').replace(/^\\/, ''))) {
890 seenHead = true
891 return { text: piece, kind: 'head' as const }
892 }
893 return { text: piece, kind: 'prefix' as const }
894 }
895 if (!seenVerb) {
896 if (bare === 'alpha' || bare === 'beta') return { text: piece, kind: 'track' as const }
897 if (bare === risk.verb) {
898 seenVerb = true
899 return { text: piece, kind: 'verb' as const }
900 }
901 if (groups.length && bare === groups[0]) {
902 groups.shift()
903 return { text: piece, kind: 'group' as const }
904 }
905 }
906 if (bare.startsWith('-')) return { text: piece, kind: DANGER_FLAGS.test(bare.split('=')[0] ?? bare) ? ('danger-flag' as const) : ('flag' as const) }
907 if (targets.has(bare)) return { text: piece, kind: 'target' as const }
908 return { text: piece, kind: 'plain' as const }
909 })
910}
911types/index.d.ts 107 lines1// gcloud-guard: data types and the $.state contract.
2
3export type GuardLang = 'en' | 'zh-TW' | 'ja'
4
5/** How much a command changes: delete-class, update-class, or create-class. */
6export type Severity = 'destructive' | 'mutating' | 'create'
7
8export type GuardTool = 'gcloud' | 'gsutil'
9
10export type Track = 'ga' | 'alpha' | 'beta'
11
12/** The global flags read off the command line. */
13export type RiskFlags = {
14 project?: string
15 account?: string
16 configuration?: string
17 zone?: string
18 region?: string
19 location?: string
20 quiet: boolean
21 impersonate?: string
22}
23
24/** What the classifier found: the first gcloud / gsutil segment that would change something. */
25export type Risk = {
26 tool: GuardTool
27 track: Track
28 /** The command group words before the verb, e.g. ['compute', 'instances'] */
29 path: string[]
30 verb: string
31 severity: Severity
32 /** A finer label for the UI: 'deploy', 'local-config', 'storage', 'iam', 'build', 'unknown' */
33 kind?: string
34 /** Positional words after the verb: resource names, URLs, properties */
35 targets: string[]
36 flags: RiskFlags
37 /** Every other flag on the segment, by name without the dashes; `true` when it took no value */
38 extra: Record<string, string | true>
39 /** The segment as written */
40 raw: string
41 /** Set when the target is a whole project, organization or folder */
42 scope?: 'project' | 'org' | 'folder'
43 /** The verb was not in the table; held to be safe */
44 unknownVerb?: boolean
45}
46
47export type ReportContext = {
48 account: string | null
49 project: string | null
50 projectSource: 'flag' | 'config' | 'unknown'
51 configuration: string | null
52 location: string | null
53 track: Track
54 quiet: boolean
55 impersonate: string | null
56}
57
58export type Report = {
59 severity: Severity
60 headline: string
61 context: ReportContext
62 /** Facts about the targets, at most 12 */
63 lines: string[]
64 /** Caveats: a describe that failed, a missing gcloud, deletion protection */
65 notes: string[]
66}
67
68/** What the render hooks read: the hold as a frozen value. The decision lives in the module. */
69export type HeldView = {
70 id: number
71 command: string
72 risk: Risk
73 report: Report | null
74 where: 'pane' | 'band'
75}
76
77/** The current kubectl context, parsed: a GKE one carries its project, location and cluster. */
78export type KubeContext = { kind: 'gke'; name: string; project: string; location: string; cluster: string } | { kind: 'other'; name: string }
79
80/** What the session is pointed at, read from the gcloud and kube config files (no process). */
81export type GcloudContext = {
82 configDir: string | null
83 configuration: string | null
84 project: string | null
85 /** Where the project came from: the CLOUDSDK_CORE_PROJECT env var or the configuration file */
86 projectSource: 'env' | 'file' | null
87 account: string | null
88 zone: string | null
89 region: string | null
90 kubeconfig: string | null
91 kube: KubeContext | null
92 /** When the snapshot was taken, in $.clock.now() milliseconds */
93 readAt: number
94}
95
96declare module 'claude-code' {
97 interface PluginState {
98 'gcloud-guard': {
99 lang: GuardLang
100 held: HeldView | null
101 context: GcloudContext | null
102 /** /gcloud-guard off hides the context line for the session */
103 isBandHidden: boolean
104 }
105 }
106}
107