Local credential protection. Host failure qualifications and coverage limitations apply.

Keep recognized credentials out of supported Claude Code model inputs. Redacton scans prompt text/context, Read text, and Bash stdout/stderr, replacing detected credentials with placeholders. Recognized private keys block the entire event.
Redacton targets macOS and Linux CLI installations with one shared Mod/helper implementation; Windows has a PowerShell installer candidate but no qualification path. The published verified release remains macOS ARM64, Claude Code 2.1.294, Node 22.16.0. Portable packages, Unix/PowerShell candidate installers and CI are development paths until each platform's actual host is qualified. See the target and verified matrix.
Powered by Redact Secret, a deterministic Rust detection engine with native and WebAssembly runtimes. Scanning runs locally, without sending content to a detection service. Explore Redact Secret for local redaction in your own apps, and star the project to support it.
This command installs the existing verified macOS Apple Silicon release, not a universal cross-platform package.
Have Claude Code and Node.js 22 installed on macOS Apple Silicon. The verified combination is Claude Code 2.1.294 and Node 22.16.0; other platforms, host versions and Desktop have not been qualified. Required follow-on support targets macOS x64, Linux x64/ARM64 and Linux x64/ARM64; native Windows and WSL have no qualification path. Those targets are not supported by this installer.
curl -fsSL https://raw.githubusercontent.com/milocosmopolitan/redacton/main/scripts/install.sh | bash
claude --plugin-dir "$HOME/.local/share/redacton/current"
The installer downloads the published package, verifies its pinned checksum, and installs it without npm or a build step. You can inspect the installer or download packages from Releases.
The --plugin-dir option requests loading for that Claude Code launch. Use the same launch command for future sessions. Installed files and a successful helper check do not prove that the Mod is active. Confirm /redacton answers locally with Protect ready; fallback text saying protection is inactive means there is no interception. Cowork remains unsupported, with its activation blocker recorded in host authority.
Linux, Intel Mac, native Windows and WSL users should follow the candidate installation and qualification guidance. Native Windows and WSL are separate environments; Desktop is a separate host surface. A helper/installer success does not establish protection of model inputs.
After launch, run /redacton and confirm Protect ready before your first task.
New, resumed and branched CLI sessions start with protection requested ON. Readiness is shown separately as loading, ready or unavailable.
| Command | Effect |
|---|---|
/redacton | Request protection and make one bounded recovery attempt after a local failure. |
/redactoff | From the local terminal, bypass scans for subsequent operations in this session. |
/redact:status | Show cached readiness, coverage, rules and recent outcomes. |
/redact:config, /redact:add-rule, /redact:remove-rule | Manage custom formats through local forms. |
/redactconfig | Open the same local configuration form immediately during an active turn. |
Commands take no arguments. Never paste secrets, patterns or test text into slash-command arguments; the host can store them before local rejection. Running operations keep the policy they started with. OFF displays a prompt-area warning: ⚠ Redacton OFF — credential protection disabled.
Disabling protection and opening configuration require the host's local composer origin. SDK, plugin, bridge and other origins cannot authorize these actions; /redacton recovery and cached status remain usable. After a transient settings/helper fault, remove its local cause and run /redacton in the same session. Corrupt settings require explicit local repair or scope reset. During recovery selected ON content is withheld and approved rules are retained. See recovery and refusal scope and settings ownership/environment.
Custom rules use guided token formats or assignment names. Validate, inspect synthetic sample outcomes, then explicitly Apply session; personal/project saving and portable import/export are separate actions. Confirm the form has keyboard focus before typing, and close it before ordinary chat. Never enter actual credential values as rule definitions. See configuration and scope.
Protection depends on the functioning host and outer guard. Unsupported selected results and scanner failures withhold content under those guard conditions; a host that bypasses all guards can expose it.
Original prompts and tool arguments can remain in host storage. Encoded/base64 credentials can be missed, and zero findings does not mean safe content. Grep text, Glob paths, WebFetch, Write arguments and effects, MCP, other tools, binary/image/audio content, PII and existing history are outside coverage. Withholding output does not undo a tool's effects. The route audit distinguishes these boundaries and links their existing adapter owners.
See compatibility and evidence and the threat model for exact limits. For vulnerabilities, use private security reporting; public issues are not confidential.
Contributing · Security policy · Code of conduct · Dependency notices · MIT license
mod/index.tsx 2053 lines1import type {
2 EngineInterface,
3 On,
4 RenderChildren,
5 ToolCallInput,
6 ToolCallResult,
7} from 'claude-code';
8import type { TrustedToolResult } from './adapters/text.ts';
9import {
10 extractPrompt,
11 extractToolResult,
12 rebuildPrompt,
13 rebuildToolResult,
14} from './adapters/text.ts';
15import { isExplicitLocalUser } from './authority.ts';
16import {
17 type ActiveConfiguration,
18 ConfigController,
19 effectiveConfiguration,
20 removeRule,
21 sharedNamesAction,
22 type TokenRule,
23} from './config.ts';
24import {
25 candidateConfiguration,
26 candidateDocument,
27 freshForm,
28 populateForm,
29 type RuleForm,
30} from './form.ts';
31import type { HelperRequest, HelperResponse } from './protocol.ts';
32import {
33 LIMITS,
34 makeRequest,
35 POLICY_ID,
36 utf8Bytes,
37 validateProcessResponse,
38} from './protocol.ts';
39import { failureScope, settingsRemediation } from './recovery.ts';
40import { ImportReviewController, SavedSettingsController } from './settings.ts';
41import type { OperationSnapshot, SessionState } from './state.ts';
42import {
43 createSessionState,
44 record,
45 requestProtection,
46 setReadiness,
47 snapshot,
48} from './state.ts';
49import {
50 type StorageRequest,
51 type StorageResponse,
52 type TransferResponse,
53 validateStorageResponse,
54 validateTransferResponse,
55} from './storage.ts';
56import { removalView, statusView } from './view.ts';
57
58interface Runtime {
59 sequence: number;
60 pending: number;
61 observedAt: number | null;
62 personalLoad: 'pending' | 'ready' | 'failed';
63 settingsCode: string;
64 generation: number;
65 personalPromise: Promise<void> | null;
66 recoveryPromise: Promise<void> | null;
67 checkPromise: Promise<void> | null;
68 healthRevision: string;
69 healthEpoch: number;
70}
71interface OperationSlot {
72 captured: OperationSnapshot;
73 config: ActiveConfiguration;
74 controller: SessionState;
75 trusted: TrustedToolResult | null;
76}
77
78// Child input is stdin only; scanner imports never enter the Mod runtime.
79async function runHelper(
80 $: EngineInterface,
81 controller: SessionState,
82 request: HelperRequest,
83 signal: AbortSignal | undefined,
84 runtime: Runtime,
85): Promise<HelperResponse> {
86 const localFailure = (errorCode: string): HelperResponse => {
87 if (request.operation === 'sanitize') {
88 record(controller, { errorCode, count: 0 });
89 $.ui.invalidate('ui.render');
90 }
91 return { status: 'failed', errorCode };
92 };
93 if (signal?.aborted) return localFailure('CANCELLED');
94 const generation = runtime.generation;
95 const healthEpoch = runtime.healthEpoch;
96 const payload = JSON.stringify(request);
97 if (utf8Bytes(payload) > LIMITS.inputBytes)
98 return localFailure('INPUT_LIMIT');
99 if (runtime.pending >= LIMITS.pending) return localFailure('QUEUE_SATURATED');
100 runtime.pending += 1;
101 try {
102 const result = await $.process.run(
103 ['node', `${$.plugin.root}/helper/dist/index.js`],
104 {
105 stdin: payload,
106 timeoutMs: LIMITS.timeoutMs,
107 env: { NODE_OPTIONS: '', NODE_PATH: '' },
108 },
109 );
110 if (signal?.aborted) return localFailure('CANCELLED');
111 const response = validateProcessResponse(result, request);
112 if (response.status !== 'ok' && request.operation === 'sanitize') {
113 record(controller, { errorCode: response.errorCode, count: 0 });
114 if (
115 failureScope(request.operation, response.errorCode) === 'scanner' &&
116 runtime.generation === generation &&
117 runtime.healthEpoch === healthEpoch &&
118 runtime.healthRevision === request.config?.revision
119 ) {
120 runtime.healthEpoch += 1;
121 runtime.observedAt = Date.now();
122 setReadiness(controller, 'unavailable');
123 }
124 $.ui.invalidate('ui.render');
125 }
126 return response;
127 } catch {
128 if (request.operation === 'sanitize') {
129 record(controller, { errorCode: 'HELPER_UNAVAILABLE', count: 0 });
130 if (
131 runtime.generation === generation &&
132 runtime.healthEpoch === healthEpoch &&
133 runtime.healthRevision === request.config?.revision
134 ) {
135 runtime.healthEpoch += 1;
136 setReadiness(controller, 'unavailable');
137 runtime.observedAt = Date.now();
138 }
139 $.ui.invalidate('ui.render');
140 }
141 return { status: 'failed', errorCode: 'HELPER_UNAVAILABLE' };
142 } finally {
143 runtime.pending -= 1;
144 }
145}
146
147async function checkReadiness(
148 $: EngineInterface,
149 controller: SessionState,
150 runtime: Runtime,
151 config: ActiveConfiguration,
152): Promise<void> {
153 if (!controller.requestedProtection || runtime.personalLoad !== 'ready')
154 return;
155 if (runtime.checkPromise && runtime.healthRevision === config.revision) {
156 await runtime.checkPromise;
157 return;
158 }
159 const generation = runtime.generation;
160 const epoch = ++runtime.healthEpoch;
161 runtime.healthRevision = config.revision;
162 setReadiness(controller, 'loading');
163 const work = (async () => {
164 const response = await runHelper(
165 $,
166 controller,
167 {
168 protocolVersion: 2,
169 config,
170 requestId: `check-${++runtime.sequence}`,
171 operation: 'self-check',
172 policyId: POLICY_ID,
173 },
174 undefined,
175 runtime,
176 );
177 if (
178 runtime.generation !== generation ||
179 runtime.healthRevision !== config.revision ||
180 runtime.healthEpoch !== epoch
181 )
182 return;
183 setReadiness(
184 controller,
185 response.status === 'ok' ? 'ready' : 'unavailable',
186 );
187 runtime.observedAt = Date.now();
188 $.ui.invalidate('ui.render');
189 })();
190 runtime.checkPromise = work;
191 try {
192 await work;
193 } finally {
194 if (runtime.checkPromise === work) runtime.checkPromise = null;
195 }
196}
197
198async function runSettings(
199 $: EngineInterface,
200 request: StorageRequest,
201 runtime: Runtime,
202): Promise<StorageResponse> {
203 const payload = JSON.stringify(request);
204 if (utf8Bytes(payload) > LIMITS.inputBytes)
205 return { ok: false, code: 'INPUT_LIMIT' };
206 if (runtime.pending >= LIMITS.pending)
207 return { ok: false, code: 'QUEUE_SATURATED' };
208 runtime.pending += 1;
209 try {
210 const result = await $.process.run(
211 ['node', `${$.plugin.root}/helper/dist/index.js`],
212 {
213 stdin: payload,
214 timeoutMs: LIMITS.settingsTimeoutMs,
215 env: { NODE_OPTIONS: '', NODE_PATH: '' },
216 },
217 );
218 return validateStorageResponse(result, request);
219 } catch {
220 return { ok: false, code: 'SETTINGS_UNAVAILABLE' };
221 } finally {
222 runtime.pending -= 1;
223 }
224}
225
226async function runTransfer(
227 $: EngineInterface,
228 request: StorageRequest,
229 runtime: Runtime,
230): Promise<TransferResponse> {
231 const payload = JSON.stringify(request);
232 if (utf8Bytes(payload) > LIMITS.inputBytes)
233 return { ok: false, code: 'INPUT_LIMIT' };
234 if (runtime.pending >= LIMITS.pending)
235 return { ok: false, code: 'QUEUE_SATURATED' };
236 runtime.pending += 1;
237 try {
238 const result = await $.process.run(
239 ['node', `${$.plugin.root}/helper/dist/index.js`],
240 {
241 stdin: payload,
242 timeoutMs: LIMITS.settingsTimeoutMs,
243 env: { NODE_OPTIONS: '', NODE_PATH: '' },
244 },
245 );
246 return validateTransferResponse(result, request);
247 } catch {
248 return { ok: false, code: 'SETTINGS_UNAVAILABLE' };
249 } finally {
250 runtime.pending -= 1;
251 }
252}
253
254async function loadPersonal(
255 $: EngineInterface,
256 controller: SessionState,
257 config: ConfigController,
258 settings: SavedSettingsController,
259 runtime: Runtime,
260): Promise<void> {
261 if (!controller.requestedProtection || runtime.personalLoad !== 'pending')
262 return;
263 const generation = runtime.generation;
264 const initial = config.snapshot();
265 const response = await runSettings(
266 $,
267 {
268 protocolVersion: 2,
269 requestId: `personal-${++runtime.sequence}`,
270 operation: 'load-config',
271 policyId: POLICY_ID,
272 storage: { scope: 'personal', approved: true },
273 },
274 runtime,
275 );
276 if (runtime.generation !== generation || !controller.requestedProtection)
277 return;
278 if (response.ok) {
279 settings.observe(response.settings);
280 if (initial.scope !== 'session')
281 config.replaceApproved(
282 response.settings.document,
283 'personal',
284 initial.revision,
285 );
286 runtime.personalLoad = 'ready';
287 runtime.settingsCode = '';
288 } else {
289 runtime.personalLoad = 'failed';
290 runtime.settingsCode = response.code;
291 setReadiness(controller, 'unavailable');
292 runtime.observedAt = Date.now();
293 }
294 $.ui.invalidate('ui.render');
295}
296
297async function ensurePersonal(
298 $: EngineInterface,
299 controller: SessionState,
300 config: ConfigController,
301 settings: SavedSettingsController,
302 runtime: Runtime,
303): Promise<void> {
304 if (runtime.personalPromise) {
305 await runtime.personalPromise;
306 return;
307 }
308 if (runtime.personalLoad !== 'pending' || !controller.requestedProtection)
309 return;
310 const work = loadPersonal($, controller, config, settings, runtime);
311 runtime.personalPromise = work;
312 try {
313 await work;
314 } finally {
315 if (runtime.personalPromise === work) runtime.personalPromise = null;
316 }
317}
318
319const ALPHABETS: readonly TokenRule['alphabet'][] = [
320 'alnum',
321 'alnum-dash',
322 'alnum-dash-dot',
323 'upper-alnum',
324 'digit',
325 'lower-hex',
326 'base64-body',
327];
328
329async function focusLocal(
330 $: EngineInterface,
331 target: { requestId: string; key: string },
332): Promise<boolean> {
333 try {
334 const response = await $.ui.focus(target);
335 return !response.deny;
336 } catch {
337 return false;
338 }
339}
340
341// The engine's record of open panes is authoritative: a host can remove the
342// pane without raising `ui.close`. An unreadable record keeps the guard.
343async function localPaneListed($: EngineInterface): Promise<boolean> {
344 try {
345 return (await $.ui.panes()).some((pane) => pane.id === 'redact-config');
346 } catch {
347 return true;
348 }
349}
350
351function operationKey(event: {
352 tool_use_id?: unknown;
353 agentId?: unknown;
354 tool?: unknown;
355}): string | null {
356 if (
357 typeof event.tool_use_id !== 'string' ||
358 !event.tool_use_id.length ||
359 (event.agentId !== undefined && typeof event.agentId !== 'string')
360 )
361 return null;
362 return JSON.stringify([event.agentId ?? null, event.tool, event.tool_use_id]);
363}
364
365async function sanitizeSelectedTool<E extends ToolCallInput>(
366 $: EngineInterface,
367 e: E,
368 next: ((event: E) => Promise<ToolCallResult>) & {
369 readonly signal: AbortSignal;
370 },
371 slots: Map<string, OperationSlot>,
372 runtime: Runtime,
373): Promise<ToolCallResult> {
374 const key = operationKey(e);
375 const slot = key === null ? undefined : slots.get(key);
376 // OFF bypass is associated by the outer operation, not the current toggle.
377 if (!slot) return { deny: 'REDACTON_WITHHELD' };
378 if (!slot.captured.requestedProtection) return next(e);
379 const answer = await next(e);
380 if (answer.deny) {
381 slot.trusted = { deny: 'REDACTON_TOOL_DENIED' };
382 return slot.trusted;
383 }
384 const extraction = extractToolResult(e.tool, answer);
385 if (extraction.status !== 'ok') {
386 record(slot.controller, { errorCode: 'UNSUPPORTED_SHAPE', count: 0 });
387 slot.trusted = { deny: 'REDACTON_UNSUPPORTED_SHAPE' };
388 return slot.trusted;
389 }
390 const request = makeRequest(
391 `tool-${++runtime.sequence}`,
392 extraction.segments,
393 slot.config,
394 );
395 if (!request) {
396 record(slot.controller, { errorCode: 'INPUT_LIMIT', count: 0 });
397 slot.trusted = { deny: 'REDACTON_INPUT_LIMIT' };
398 return slot.trusted;
399 }
400 const response = await runHelper(
401 $,
402 slot.controller,
403 request,
404 next.signal,
405 runtime,
406 );
407 if (response.status !== 'ok' || next.signal?.aborted) {
408 slot.trusted = { deny: 'REDACTON_WITHHELD' };
409 return slot.trusted;
410 }
411 const trusted = rebuildToolResult(extraction, response.segments);
412 if ('deny' in trusted) return trusted;
413 record(slot.controller, { errorCode: 'SCANNED', count: response.count });
414 $.ui.invalidate('ui.render');
415 slot.trusted = trusted;
416 return trusted;
417}
418
419function freshFormWithNotice(notice: string): RuleForm {
420 const form = freshForm();
421 form.notice = notice;
422 return form;
423}
424
425export function register(on: On) {
426 let state = createSessionState('initial');
427 const runtime: Runtime = {
428 sequence: 0,
429 pending: 0,
430 observedAt: null,
431 personalLoad: 'pending',
432 settingsCode: '',
433 generation: 0,
434 personalPromise: null,
435 recoveryPromise: null,
436 checkPromise: null,
437 healthRevision: '',
438 healthEpoch: 0,
439 };
440 let config = new ConfigController();
441 let form: RuleForm = freshForm();
442 let paneOpen = false;
443 const settings = new SavedSettingsController();
444 const imports = new ImportReviewController();
445 const slots = new Map<string, OperationSlot>();
446
447 on('session.start', async ($, e, next) => {
448 paneOpen = false;
449 state = createSessionState(await $.session.id());
450 config = new ConfigController();
451 settings.resetSession();
452 imports.cancel();
453 runtime.observedAt = null;
454 runtime.generation += 1;
455 runtime.personalPromise = null;
456 runtime.recoveryPromise = null;
457 runtime.checkPromise = null;
458 runtime.healthRevision = '';
459 runtime.healthEpoch += 1;
460 runtime.personalLoad = 'pending';
461 runtime.settingsCode = '';
462 const controller = state;
463 const owner = config;
464 const generation = runtime.generation;
465 await $.command.register({
466 name: 'redacton',
467 description: 'Request local credential protection for new operations',
468 immediate: true,
469 });
470 await $.command.register({
471 name: 'redactoff',
472 description:
473 'Disable credential protection for new operations in this session',
474 immediate: true,
475 });
476 await $.command.register({
477 name: 'redactconfig',
478 description: 'Open local configuration, including during an active tool',
479 immediate: true,
480 });
481 if (runtime.generation !== generation) return next(e);
482 await ensurePersonal($, controller, owner, settings, runtime);
483 if (runtime.generation === generation)
484 await checkReadiness($, controller, runtime, owner.snapshot());
485 return next(e);
486 }).catch((_$, e, next) => next(e));
487
488 // The host does not reload this module on restore/branch; clear OFF at session.end.
489 on('session.end', ($, e, next) => {
490 config = new ConfigController();
491 settings.resetSession();
492 imports.cancel();
493 runtime.observedAt = null;
494 runtime.generation += 1;
495 runtime.personalPromise = null;
496 runtime.recoveryPromise = null;
497 runtime.checkPromise = null;
498 runtime.healthRevision = '';
499 runtime.healthEpoch += 1;
500 runtime.personalLoad = 'pending';
501 runtime.settingsCode = '';
502 paneOpen = false;
503 form = freshForm();
504 $.ui.close({ id: 'redact-config' });
505 state = createSessionState(`reset-${++runtime.sequence}`);
506 return next(e);
507 });
508
509 on('command.run', { command: 'redactoff' }, ($, e) => {
510 if (e.args?.trim()) return { text: 'Redacton commands take no arguments.' };
511 if (!isExplicitLocalUser(e.origin))
512 return {
513 text: 'REDACTON_USER_ACTION_REQUIRED: Use /redactoff directly in the local terminal.',
514 };
515 requestProtection(state, false);
516 runtime.generation += 1;
517 runtime.personalPromise = null;
518 runtime.recoveryPromise = null;
519 runtime.checkPromise = null;
520 $.ui.invalidate('ui.render');
521 return {
522 text: 'Warning: Redacton is OFF. Credentials may reach Claude unchanged.',
523 };
524 }).catch(() => ({ text: 'REDACTON_COMMAND_UNAVAILABLE' }));
525
526 on('command.run', { command: 'redacton' }, async ($, e) => {
527 if (e.args?.trim()) return { text: 'Redacton commands take no arguments.' };
528 requestProtection(state, true);
529 $.ui.invalidate('ui.render');
530 const controller = state;
531 const owner = config;
532 if (!runtime.recoveryPromise) {
533 if (runtime.personalLoad === 'failed') runtime.personalLoad = 'pending';
534 setReadiness(controller, 'loading');
535 const generation = runtime.generation;
536 const work = (async () => {
537 await ensurePersonal($, controller, owner, settings, runtime);
538 if (runtime.generation === generation && controller.requestedProtection)
539 await checkReadiness($, controller, runtime, owner.snapshot());
540 })();
541 runtime.recoveryPromise = work;
542 try {
543 await work;
544 } finally {
545 if (runtime.recoveryPromise === work) runtime.recoveryPromise = null;
546 }
547 } else await runtime.recoveryPromise;
548 return {
549 text: !state.requestedProtection
550 ? 'Redacton OFF. Recovery cancelled; no scanning helper is dispatched for OFF operations.'
551 : state.readiness === 'ready'
552 ? 'Redacton ON. Protect ready. Partial coverage: supported prompt text, Read text, Bash stdout/stderr.'
553 : `Redacton ON. Protection unavailable; selected content will be withheld. ${settingsRemediation(runtime.settingsCode)}`,
554 };
555 }).catch(() => ({
556 text: `Redacton ON. Protection unavailable; selected content will be withheld. ${settingsRemediation(runtime.settingsCode)}`,
557 }));
558
559 on(
560 'command.run',
561 {
562 command: [
563 'redact:status',
564 'redactconfig',
565 'redact:config',
566 'redact:add-rule',
567 'redact:remove-rule',
568 ],
569 },
570 async ($, e) => {
571 if (e.args.trim())
572 return {
573 text: 'Redacton local commands take no arguments. Never put credentials in slash commands.',
574 };
575 if (e.command === 'redact:status') {
576 const view = statusView(state, config.snapshot(), runtime.observedAt);
577 return {
578 text: `Redacton ${view.protection} · Protect ${view.readiness}. Saved settings: ${runtime.settingsCode || runtime.personalLoad}. Cached observation: ${view.observedAt === null ? 'not observed' : new Date(view.observedAt).toISOString()}. This is not a health check.\nConfiguration ${view.revision} · source ${view.source} · scope ${view.scope} · ${view.customRuleCount} custom rules: ${view.ruleIds.join(', ') || 'none'}.\nSupported: prompt text/context, Read text, Bash stdout/stderr. Excluded: Grep, Glob paths, WebFetch, Write arguments/effects, MCP and other tools; tool arguments, binary/image/audio, PII, existing history. Encoded/base64 credentials can be missed. Zero findings does not mean safe content.\nRecent: ${view.recent.map((item) => `${item.code}:${item.count}`).join(', ') || 'none'}`,
579 };
580 }
581 if (!isExplicitLocalUser(e.origin))
582 return {
583 text: 'REDACTON_USER_ACTION_REQUIRED: Open configuration directly in the local terminal.',
584 };
585 imports.cancel();
586 form = freshForm();
587 form.mode =
588 e.command === 'redact:add-rule'
589 ? 'add'
590 : e.command === 'redact:remove-rule'
591 ? 'remove'
592 : 'config';
593 await $.prompt.fill({ text: '', mode: 'replace' });
594 const placement = await $.ui.open({
595 id: 'redact-config',
596 title: 'Redacton local configuration',
597 focus: true,
598 closeOnEscape: true,
599 rows: 32,
600 });
601 paneOpen = placement.isPlaced;
602 if (!placement.isPlaced) await $.ui.close({ id: 'redact-config' });
603 if (placement.isPlaced)
604 await focusLocal($, {
605 requestId: 'redact-config',
606 key:
607 form.mode === 'add'
608 ? 'rule-id'
609 : form.mode === 'remove' && config.snapshot().rules[0]
610 ? `remove-${config.snapshot().rules[0]?.id}`
611 : 'edit-add',
612 });
613 return {
614 text: placement.isPlaced
615 ? 'Redacton local panel opened. No credentials or exact secret values. Changes require validation, synthetic preview, then Apply.'
616 : 'Redacton local panel unavailable on this surface. Configuration unchanged.',
617 };
618 },
619 ).catch(() => ({ text: 'REDACTON_LOCAL_COMMAND_UNAVAILABLE' }));
620
621 const releaseLocalPane = () => {
622 const draft = config.currentDraft();
623 if (draft) config.cancel(draft.token);
624 imports.cancel();
625 paneOpen = false;
626 form = freshForm();
627 };
628
629 on('ui.close', ($, e, next) => {
630 if (e.id !== 'redact-config') return next(e);
631 if (form.durableBusy && e.origin.kind !== 'unload') {
632 form.notice =
633 'Operation in progress. Wait for completion; a durable write may already commit.';
634 $.ui.invalidate('ui.render');
635 return { value: undefined };
636 }
637 releaseLocalPane();
638 return next(e);
639 });
640
641 // Terminal and desktop element tables both carry every element the form
642 // uses; other surfaces keep the host's default (nothing drawn).
643 on(
644 'ui.render',
645 { component: 'Pane', requestId: 'redact-config' },
646 ($, e, next) => {
647 if (e.surface !== 'terminal' && e.surface !== 'desktop') return next(e);
648 const { Box, Text, Input, Select, Button } = $.ui.resolve(e);
649 // The terminal tree stays as qualified; only the desktop is restyled.
650 const desktop = e.surface === 'desktop';
651 const tab = (name: RuleForm['tab']) => !desktop || form.tab === name;
652 const row = desktop ? { gap: 1, flexWrap: 'wrap' as const } : {};
653 const primary = desktop ? { variant: 'primary' as const } : {};
654 const Card = ({
655 title,
656 children,
657 }: {
658 title?: string;
659 children?: RenderChildren;
660 }) =>
661 desktop ? (
662 <Box
663 flexDirection="column"
664 gap={1}
665 borderStyle="round"
666 paddingX={1}
667 paddingY={1}
668 >
669 {title ? <Text bold>{title}</Text> : null}
670 {children}
671 </Box>
672 ) : (
673 <Box flexDirection="column">{children}</Box>
674 );
675 const owner = config;
676 const formOwner = form;
677 const sessionOwner = state;
678 const active = owner.snapshot();
679 const draft = owner.currentDraft();
680 const update = () => $.ui.invalidate('ui.render');
681 const changed = () => {
682 if (!validOwner()) return;
683 if (draft) owner.cancel(draft.token);
684 form.notice = '';
685 update();
686 };
687 const close = async () => {
688 if (!validOwner()) return;
689 if (form.durableBusy) {
690 form.notice =
691 'Operation in progress. Wait for completion; a durable save may already commit.';
692 update();
693 return;
694 }
695 if (draft) owner.cancel(draft.token);
696 form = freshForm();
697 try {
698 await $.ui.close({ id: 'redact-config' });
699 paneOpen = false;
700 imports.cancel();
701 form = freshForm();
702 } catch {
703 form.notice = 'LOCAL_PANEL_CLOSE_UNAVAILABLE';
704 update();
705 }
706 };
707 const validOwner = () =>
708 owner === config &&
709 sessionOwner === state &&
710 formOwner === form &&
711 paneOpen;
712 const setKind = (choice: RuleForm['kind']) => {
713 if (!validOwner()) return;
714 form.kind = choice;
715 form.namesGroupAction = false;
716 if (form.kind === 'names') form.action = sharedNamesAction(active);
717 changed();
718 };
719 const setAction = (choice: RuleForm['action']) => {
720 if (!validOwner()) return;
721 form.action = choice;
722 if (form.kind === 'names') form.namesGroupAction = true;
723 changed();
724 };
725 const setAlphabet = (choice: TokenRule['alphabet']) => {
726 if (!validOwner()) return;
727 form.alphabet = choice;
728 changed();
729 };
730 const setRunKind = (choice: RuleForm['runKind']) => {
731 if (!validOwner()) return;
732 form.runKind = choice;
733 changed();
734 };
735 const setSpecificity = (choice: RuleForm['specificity']) => {
736 if (!validOwner()) return;
737 form.specificity = choice;
738 changed();
739 };
740 const setValidator = (choice: RuleForm['validator']) => {
741 if (!validOwner()) return;
742 form.validator = choice;
743 changed();
744 };
745 return (
746 <Box
747 flexDirection="column"
748 {...(desktop ? { gap: 1, padding: 1 } : {})}
749 >
750 {desktop ? (
751 <Card>
752 <Text bold>
753 {!state.requestedProtection
754 ? '⚠ Redacton OFF · credentials may reach Claude unchanged'
755 : `Redacton ON · Protect ${state.readiness} · Partial coverage`}
756 </Text>
757 <Text>
758 Partial coverage: prompt text, Read text and Bash output only.
759 Encoded credentials can be missed. Zero findings is not a safety
760 guarantee.
761 </Text>
762 {e.props.isFocused ? null : (
763 <Text bold>
764 WARNING: local panel is not focused. Do not type patterns into
765 the composer. Focus this panel before editing.
766 </Text>
767 )}
768 <Text>
769 Local declarative patterns only. Never enter a credential or
770 exact secret. Nothing is saved until an explicit Save.
771 </Text>
772 <Text
773 dimColor
774 >{`Configuration ${active.revision} · ${active.source}/${active.scope} · custom rules ${active.rules.length} · built-in credentials stay enabled`}</Text>
775 {runtime.settingsCode ? (
776 <Text>{runtime.settingsCode}</Text>
777 ) : null}
778 <Box {...row}>
779 <Button
780 key="details"
781 onPress={() => {
782 if (!validOwner()) return;
783 form.details = !form.details;
784 update();
785 }}
786 >
787 {form.details
788 ? 'Hide coverage details'
789 : 'Show coverage details'}
790 </Button>
791 </Box>
792 {form.details ? (
793 <Text>
794 Supported: prompt text/context, Read text, Bash stdout/stderr.
795 Unprotected: Grep, Glob paths, WebFetch, Write
796 arguments/effects, MCP, other tools and existing history.
797 </Text>
798 ) : null}
799 </Card>
800 ) : (
801 <Box flexDirection="column">
802 <Text>
803 {!state.requestedProtection
804 ? '⚠ Redacton OFF · credentials may reach Claude unchanged'
805 : `Redacton ON · Protect ${state.readiness} · Partial coverage`}
806 </Text>
807 <Text>
808 Supported: prompt text/context, Read text, Bash stdout/stderr.
809 Unprotected: Grep, Glob paths, WebFetch, Write
810 arguments/effects, MCP, other tools and existing history.
811 Encoded/base64 credentials can be missed.
812 </Text>
813 <Text>{`Configuration ${active.revision} · ${active.source}/${active.scope} · custom rules ${active.rules.length}. Built-in credentials remain enabled. Zero findings is not a safety guarantee.`}</Text>
814 <Text>
815 {e.props.isFocused
816 ? 'Local panel has keyboard focus. Type only in labeled fields.'
817 : 'WARNING: local panel is not focused. Do not type patterns into the composer. Focus this panel before editing.'}
818 </Text>
819 <Text>
820 Local declarative patterns only. Never enter a credential or
821 exact secret. Nothing is saved until an explicit Save.
822 </Text>
823 <Text>{runtime.settingsCode}</Text>
824 </Box>
825 )}
826 {desktop ? (
827 <Box gap={1} flexWrap="wrap">
828 {(
829 [
830 ['rules', 'Rules'],
831 ['storage', 'Save and load'],
832 ['transfer', 'Import and export'],
833 ] as const
834 ).map(([id, label]) => (
835 <Button
836 key={`tab-${id}`}
837 variant={form.tab === id ? 'primary' : 'secondary'}
838 onPress={() => {
839 if (!validOwner()) return;
840 form.tab = id;
841 update();
842 }}
843 >
844 {label}
845 </Button>
846 ))}
847 </Box>
848 ) : null}
849 {desktop && form.notice ? (
850 <Card>
851 <Text>{form.notice}</Text>
852 </Card>
853 ) : null}
854 {tab('rules') ? (
855 <Card title="Custom rules">
856 <Box {...row}>
857 <Button
858 key="edit-add"
859 onPress={() => {
860 if (!validOwner()) return;
861 form = freshForm();
862 form.mode = 'add';
863 update();
864 }}
865 >
866 Add rule
867 </Button>
868 <Button
869 key="edit-remove"
870 onPress={async () => {
871 if (!validOwner()) return;
872 form = freshForm();
873 form.mode = 'remove';
874 update();
875 const first = active.rules[0];
876 if (first)
877 await focusLocal($, {
878 requestId: 'redact-config',
879 key: `remove-${first.id}`,
880 });
881 }}
882 >
883 Remove rule
884 </Button>
885 <Button
886 key="revert"
887 onPress={async () => {
888 if (!validOwner() || form.busy) return;
889 const result = owner.revert(active.revision);
890 form.notice = result.ok
891 ? 'Reverted to previous configuration.'
892 : result.code;
893 if (result.ok && state.requestedProtection)
894 await checkReadiness(
895 $,
896 sessionOwner,
897 runtime,
898 result.config,
899 );
900 if (!validOwner()) return;
901 update();
902 }}
903 >
904 Revert
905 </Button>
906 {desktop ? null : (
907 <Button key="cancel" onPress={close}>
908 Cancel / close
909 </Button>
910 )}
911 </Box>
912 {desktop ? null : <Text>{form.notice}</Text>}
913 <Text>
914 Editing any inherited custom rule creates a session override.
915 Personal and project files stay unchanged until explicit scoped
916 Save.
917 </Text>
918 {desktop && !active.rules.length ? (
919 <Text dimColor>No custom rules yet. Choose Add rule.</Text>
920 ) : null}
921 <Box {...row}>
922 {active.rules.map((rule) => (
923 <Button
924 key={`edit-${rule.id}`}
925 onPress={async () => {
926 if (!validOwner() || form.busy) return;
927 const pending = owner.currentDraft();
928 if (pending) owner.cancel(pending.token);
929 form = populateForm(rule);
930 form.notice = `Editing custom rule ${rule.id} as a session override. Validate, preview, Apply.`;
931 update();
932 await focusLocal($, {
933 requestId: 'redact-config',
934 key: 'rule-id',
935 });
936 }}
937 >{`Edit ${rule.id}`}</Button>
938 ))}
939 </Box>
940 {form.mode === 'add' ? (
941 <Box flexDirection="column">
942 {desktop ? (
943 <Select
944 key="kind"
945 label="Rule kind"
946 value={form.kind}
947 options={[
948 {
949 value: 'token',
950 label: 'Token: public prefix + shape',
951 },
952 { value: 'names', label: 'Assignment names' },
953 ]}
954 onSelect={(value) =>
955 setKind(value === 'names' ? 'names' : 'token')
956 }
957 />
958 ) : (
959 <Button
960 key="kind"
961 onPress={() =>
962 setKind(form.kind === 'token' ? 'names' : 'token')
963 }
964 >{`Kind: ${form.kind}`}</Button>
965 )}
966 <Input
967 key="rule-id"
968 label="Rule ID"
969 value={form.id}
970 autoFocus
971 onInput={(value) => {
972 if (!validOwner()) return;
973 form.id = value;
974 changed();
975 }}
976 onSubmit={async (value) => {
977 if (!validOwner()) return;
978 form.id = value;
979 changed();
980 update();
981 await focusLocal($, {
982 requestId: 'redact-config',
983 key: form.kind === 'token' ? 'prefix' : 'names',
984 });
985 }}
986 />
987 {desktop ? (
988 <Select
989 key="action"
990 label={
991 form.kind === 'names'
992 ? 'Action for ALL assignment-name rules'
993 : 'Action'
994 }
995 value={form.action}
996 options={[
997 {
998 value: 'redact',
999 label: 'Redact (replace with placeholder)',
1000 },
1001 {
1002 value: 'block',
1003 label: 'Block (withhold the content)',
1004 },
1005 ]}
1006 onSelect={(value) =>
1007 setAction(value === 'block' ? 'block' : 'redact')
1008 }
1009 />
1010 ) : (
1011 <Button
1012 key="action"
1013 onPress={() =>
1014 setAction(form.action === 'redact' ? 'block' : 'redact')
1015 }
1016 >
1017 {form.kind === 'names'
1018 ? `Action for ALL assignment-name rules: ${form.action}`
1019 : `Action: ${form.action}`}
1020 </Button>
1021 )}
1022 {form.kind === 'token' ? (
1023 <Box flexDirection="column">
1024 <Input
1025 key="prefix"
1026 label="Public prefix, 3–64 bytes"
1027 value={form.prefix}
1028 onInput={(value) => {
1029 if (!validOwner()) return;
1030 form.prefix = value;
1031 changed();
1032 }}
1033 onSubmit={async (value) => {
1034 if (!validOwner()) return;
1035 form.prefix = value;
1036 changed();
1037 update();
1038 await focusLocal($, {
1039 requestId: 'redact-config',
1040 key: 'length',
1041 });
1042 }}
1043 />
1044 {desktop ? (
1045 <Select
1046 key="alphabet"
1047 label="Characters after the prefix"
1048 value={form.alphabet}
1049 options={ALPHABETS.map((value) => ({ value }))}
1050 onSelect={(value) =>
1051 setAlphabet(
1052 ALPHABETS.find((item) => item === value) ??
1053 'alnum',
1054 )
1055 }
1056 />
1057 ) : (
1058 <Button
1059 key="alphabet"
1060 onPress={() =>
1061 setAlphabet(
1062 ALPHABETS[
1063 (ALPHABETS.indexOf(form.alphabet) + 1) %
1064 ALPHABETS.length
1065 ] ?? 'alnum',
1066 )
1067 }
1068 >{`Alphabet: ${form.alphabet}`}</Button>
1069 )}
1070 {desktop ? (
1071 <Select
1072 key="run-kind"
1073 label="Length mode"
1074 value={form.runKind}
1075 options={[
1076 { value: 'exact', label: 'Exactly this many' },
1077 { value: 'at-least', label: 'At least this many' },
1078 ]}
1079 onSelect={(value) =>
1080 setRunKind(
1081 value === 'at-least' ? 'at-least' : 'exact',
1082 )
1083 }
1084 />
1085 ) : (
1086 <Button
1087 key="run-kind"
1088 onPress={() =>
1089 setRunKind(
1090 form.runKind === 'exact' ? 'at-least' : 'exact',
1091 )
1092 }
1093 >{`Length mode: ${form.runKind}`}</Button>
1094 )}
1095 <Input
1096 key="length"
1097 label="Run length, 1–4096"
1098 value={form.length}
1099 onInput={(value) => {
1100 if (!validOwner()) return;
1101 form.length = value;
1102 changed();
1103 }}
1104 onSubmit={async (value) => {
1105 if (!validOwner()) return;
1106 form.length = value;
1107 changed();
1108 update();
1109 await focusLocal($, {
1110 requestId: 'redact-config',
1111 key: 'build',
1112 });
1113 }}
1114 />
1115 {desktop ? (
1116 <Select
1117 key="specificity"
1118 label="Specificity"
1119 value={form.specificity}
1120 options={[
1121 { value: 'contextual', label: 'Contextual' },
1122 { value: 'entropy', label: 'Entropy' },
1123 ]}
1124 onSelect={(value) =>
1125 setSpecificity(
1126 value === 'entropy' ? 'entropy' : 'contextual',
1127 )
1128 }
1129 />
1130 ) : (
1131 <Button
1132 key="specificity"
1133 onPress={() =>
1134 setSpecificity(
1135 form.specificity === 'contextual'
1136 ? 'entropy'
1137 : 'contextual',
1138 )
1139 }
1140 >{`Specificity: ${form.specificity}`}</Button>
1141 )}
1142 {desktop ? (
1143 <Select
1144 key="validator"
1145 label="Validator"
1146 value={form.validator}
1147 options={[
1148 { value: 'none', label: 'None' },
1149 {
1150 value: 'trailing-lower-hex',
1151 label: 'Trailing lowercase hex',
1152 },
1153 ]}
1154 onSelect={(value) =>
1155 setValidator(
1156 value === 'trailing-lower-hex'
1157 ? 'trailing-lower-hex'
1158 : 'none',
1159 )
1160 }
1161 />
1162 ) : (
1163 <Button
1164 key="validator"
1165 onPress={() =>
1166 setValidator(
1167 form.validator === 'none'
1168 ? 'trailing-lower-hex'
1169 : 'none',
1170 )
1171 }
1172 >{`Validator: ${form.validator}`}</Button>
1173 )}
1174 </Box>
1175 ) : (
1176 <Box flexDirection="column">
1177 <Input
1178 key="names"
1179 label="Assignment names, comma-separated (max 32)"
1180 value={form.names}
1181 onInput={(value) => {
1182 if (!validOwner()) return;
1183 form.names = value;
1184 changed();
1185 }}
1186 onSubmit={async (value) => {
1187 if (!validOwner()) return;
1188 form.names = value;
1189 changed();
1190 update();
1191 await focusLocal($, {
1192 requestId: 'redact-config',
1193 key: 'build',
1194 });
1195 }}
1196 />
1197 <Text>
1198 Names share one action across all name rules. Names
1199 apply only to contextual assignments. A name is not an
1200 exact value.mod/adapters/text.ts 325 lines1import type { PromptOrigin, PromptSubmitInput } from 'claude-code';
2import type { Segment } from '../protocol.ts';
3import {
4 isNonnegativeInteger,
5 isStringArray,
6 hasOnlyDataKeys as keys,
7 hasOwn as own,
8} from '../validation.ts';
9
10export interface UnsupportedShape {
11 status: 'blocked';
12 errorCode: 'UNSUPPORTED_SHAPE';
13}
14export interface PromptExtraction {
15 status: 'ok';
16 shape: 'prompt';
17 segments: Segment[];
18 metadata: { wait: boolean; origin: PromptOrigin; turnId?: string };
19}
20export interface BashExtraction {
21 status: 'ok';
22 shape: 'Bash';
23 segments: Segment[];
24 metadata: { interrupted: boolean };
25}
26export interface ReadExtraction {
27 status: 'ok';
28 shape: 'Read';
29 segments: Segment[];
30 metadata: { numLines: number; startLine: number; totalLines: number };
31}
32export type ToolExtraction = BashExtraction | ReadExtraction;
33export type Extraction = PromptExtraction | ToolExtraction;
34export type TrustedToolResult =
35 | { deny: string }
36 | {
37 result:
38 | { stdout: string; stderr: string; interrupted: boolean }
39 | {
40 type: 'text';
41 file: {
42 filePath: string;
43 content: string;
44 numLines: number;
45 startLine: number;
46 totalLines: number;
47 };
48 };
49 };
50const blocked = (): UnsupportedShape => ({
51 status: 'blocked',
52 errorCode: 'UNSUPPORTED_SHAPE',
53});
54
55// The model-origin host envelope retains these optional keys as undefined.
56// Populated values can carry paths, aliases or background output, so withhold them.
57const emptyBashFields = [
58 'returnCodeInterpretation',
59 'backgroundTaskId',
60 'backgroundedByUser',
61 'backgroundedByTurnAbort',
62 'backgroundedToDeliverMessage',
63 'timedOutAfterMs',
64 'backgroundEndsWithFinalResponse',
65 'backgroundCwdHint',
66 'dangerouslyDisableSandbox',
67 'persistedOutputPath',
68 'persistedOutputSize',
69 'staleReadFileStateHint',
70 'ghRateLimitHint',
71 'gitOperation',
72 'bashEditDiff',
73 'rawOutputPath',
74 'structuredContent',
75];
76const safeOriginKinds = new Set([
77 'composer',
78 'bridge',
79 'sdk',
80 'task-notification',
81 'scheduled-trigger',
82 'peer',
83 'peer-send-message',
84 'projects-relay',
85 'coordinator',
86 'observer',
87 'observer-activity',
88 'auto-continuation',
89 'unclassified',
90 'slack-ping',
91]);
92function validOrigin(origin: unknown): origin is PromptOrigin {
93 if (
94 keys(origin, ['kind']) &&
95 typeof origin.kind === 'string' &&
96 safeOriginKinds.has(origin.kind)
97 )
98 return true;
99 if (
100 keys(origin, ['kind', 'name', 'asUser']) &&
101 origin.kind === 'plugin' &&
102 typeof origin.name === 'string'
103 ) {
104 return !own(origin, 'asUser') || origin.asUser === true;
105 }
106 return (
107 keys(origin, ['kind', 'server']) &&
108 origin.kind === 'channel' &&
109 typeof origin.server === 'string'
110 );
111}
112
113export function extractPrompt(
114 value: unknown,
115): PromptExtraction | UnsupportedShape {
116 if (
117 !keys(value, [
118 'text',
119 'context',
120 'attachments',
121 'wait',
122 'origin',
123 'turnId',
124 ]) ||
125 typeof value.text !== 'string' ||
126 typeof value.wait !== 'boolean' ||
127 !validOrigin(value.origin) ||
128 (own(value, 'turnId') && typeof value.turnId !== 'string') ||
129 (own(value, 'attachments') &&
130 (!Array.isArray(value.attachments) || value.attachments.length)) ||
131 (own(value, 'context') && !isStringArray(value.context))
132 )
133 return blocked();
134 const context = isStringArray(value.context) ? value.context : [];
135 return {
136 status: 'ok',
137 shape: 'prompt',
138 segments: [
139 { id: 'text', text: value.text },
140 ...context.map((text, index) => ({ id: `context${index}`, text })),
141 ],
142 metadata: {
143 wait: value.wait,
144 origin: value.origin,
145 ...(typeof value.turnId === 'string' ? { turnId: value.turnId } : {}),
146 },
147 };
148}
149
150function sanitized(
151 extraction: Extraction | UnsupportedShape,
152 segments: unknown,
153): Map<string, string> | null {
154 if (
155 extraction?.status !== 'ok' ||
156 !Array.isArray(segments) ||
157 segments.length !== extraction.segments.length
158 )
159 return null;
160 const expected = new Set(extraction.segments.map((segment) => segment.id));
161 const output = new Map<string, string>();
162 for (const segment of segments) {
163 if (
164 !keys(segment, ['id', 'text']) ||
165 typeof segment.id !== 'string' ||
166 !expected.has(segment.id) ||
167 output.has(segment.id) ||
168 typeof segment.text !== 'string'
169 )
170 return null;
171 output.set(segment.id, segment.text);
172 }
173 return output;
174}
175
176export function rebuildPrompt(
177 extraction: PromptExtraction | UnsupportedShape,
178 segments: unknown,
179): PromptSubmitInput | { drop: string } {
180 const values = sanitized(extraction, segments);
181 if (!values || extraction.status !== 'ok' || extraction.shape !== 'prompt')
182 return { drop: 'INVALID_RESPONSE' };
183 const text = values.get('text');
184 if (text === undefined) return { drop: 'INVALID_RESPONSE' };
185 const result: PromptSubmitInput = {
186 text,
187 wait: extraction.metadata.wait,
188 origin: extraction.metadata.origin,
189 };
190 if (own(extraction.metadata, 'turnId'))
191 result.turnId = extraction.metadata.turnId;
192 if (values.size > 1)
193 result.context = extraction.segments.slice(1).map((segment) => {
194 const text = values.get(segment.id);
195 if (text === undefined) throw new Error('INVALID_RESPONSE');
196 return text;
197 });
198 return result;
199}
200
201export function extractToolResult(
202 tool: string,
203 value: unknown,
204): ToolExtraction | UnsupportedShape {
205 if (
206 !keys(value, [
207 'result',
208 'text',
209 'ref',
210 'context',
211 'isError',
212 'isReadOnly',
213 'deny',
214 ]) ||
215 value.isError === true ||
216 (own(value, 'deny') && value.deny !== undefined) ||
217 (own(value, 'context') &&
218 (!Array.isArray(value.context) || value.context.length)) ||
219 (own(value, 'isError') && value.isError !== undefined) ||
220 (own(value, 'isReadOnly') &&
221 value.isReadOnly !== true &&
222 value.isReadOnly !== undefined) ||
223 (own(value, 'text') &&
224 value.text !== undefined &&
225 typeof value.text !== 'string') ||
226 (own(value, 'ref') &&
227 value.ref !== undefined &&
228 !Number.isSafeInteger(value.ref))
229 )
230 return blocked();
231 const result = value.result;
232 if (tool === 'Bash') {
233 if (
234 !keys(result, [
235 'stdout',
236 'stderr',
237 'interrupted',
238 'isImage',
239 'noOutputExpected',
240 ...emptyBashFields,
241 ]) ||
242 emptyBashFields.some(
243 (field) => own(result, field) && result[field] !== undefined,
244 ) ||
245 typeof result.stdout !== 'string' ||
246 typeof result.stderr !== 'string' ||
247 typeof result.interrupted !== 'boolean' ||
248 (own(result, 'isImage') && result.isImage !== false) ||
249 (own(result, 'noOutputExpected') &&
250 typeof result.noOutputExpected !== 'boolean')
251 )
252 return blocked();
253 return {
254 status: 'ok',
255 shape: 'Bash',
256 metadata: { interrupted: result.interrupted },
257 segments: [
258 { id: 'stdout', text: result.stdout },
259 { id: 'stderr', text: result.stderr },
260 ],
261 };
262 }
263 if (tool === 'Read') {
264 if (
265 !keys(result, ['type', 'file']) ||
266 result.type !== 'text' ||
267 !keys(result.file, [
268 'filePath',
269 'content',
270 'numLines',
271 'startLine',
272 'totalLines',
273 ]) ||
274 typeof result.file.filePath !== 'string' ||
275 typeof result.file.content !== 'string' ||
276 !isNonnegativeInteger(result.file.numLines) ||
277 !isNonnegativeInteger(result.file.startLine) ||
278 !isNonnegativeInteger(result.file.totalLines)
279 )
280 return blocked();
281 return {
282 status: 'ok',
283 shape: 'Read',
284 metadata: {
285 numLines: result.file.numLines,
286 startLine: result.file.startLine,
287 totalLines: result.file.totalLines,
288 },
289 segments: [
290 { id: 'filePath', text: result.file.filePath },
291 { id: 'content', text: result.file.content },
292 ],
293 };
294 }
295 return blocked();
296}
297
298export function rebuildToolResult(
299 extraction: ToolExtraction | UnsupportedShape,
300 segments: unknown,
301): TrustedToolResult {
302 const values = sanitized(extraction, segments);
303 if (!values || extraction.status !== 'ok')
304 return { deny: 'INVALID_RESPONSE' };
305 if (extraction.shape === 'Bash') {
306 const stdout = values.get('stdout');
307 const stderr = values.get('stderr');
308 if (stdout === undefined || stderr === undefined)
309 return { deny: 'INVALID_RESPONSE' };
310 return {
311 result: { stdout, stderr, interrupted: extraction.metadata.interrupted },
312 };
313 }
314 const filePath = values.get('filePath');
315 const content = values.get('content');
316 if (filePath === undefined || content === undefined)
317 return { deny: 'INVALID_RESPONSE' };
318 return {
319 result: {
320 type: 'text',
321 file: { filePath, content, ...extraction.metadata },
322 },
323 };
324}
325mod/authority.ts 12 lines1import { hasOnlyDataKeys, isPlainRecord } from './validation.ts';
2
3// Only the host-attested local user gesture authorizes reducing protection.
4// Slash text and plugin-provided claims are never provenance.
5export function isExplicitLocalUser(origin: unknown): boolean {
6 return (
7 isPlainRecord(origin) &&
8 hasOnlyDataKeys(origin, ['kind']) &&
9 origin.kind === 'composer'
10 );
11}
12mod/config.ts 259 lines1import type {
2 ActiveConfiguration,
3 ConfigDocument,
4 ConfigScope,
5} from '../helper/src/config.ts';
6
7export type {
8 Action,
9 ActiveConfiguration,
10 ConfigDocument,
11 ConfigScope,
12 CustomRule,
13 NamesRule,
14 TokenRule,
15} from '../helper/src/config.ts';
16
17export type ConfigResult =
18 | Readonly<{ ok: true; config: ActiveConfiguration }>
19 | Readonly<{
20 ok: false;
21 code: 'STALE_REVISION' | 'INVALID_STAGE' | 'INVALID_CANDIDATE';
22 }>;
23
24// Defensive copies prevent a caller's form edits from changing in-flight policy.
25export function freezeDocument(document: ConfigDocument): ConfigDocument {
26 return Object.freeze({
27 schemaVersion: 1,
28 rules: Object.freeze(
29 document.rules.map((rule) =>
30 rule.kind === 'token'
31 ? Object.freeze({
32 kind: rule.kind,
33 id: rule.id,
34 action: rule.action,
35 prefix: rule.prefix,
36 alphabet: rule.alphabet,
37 run: Object.freeze({
38 kind: rule.run.kind,
39 length: rule.run.length,
40 }),
41 specificity: rule.specificity,
42 validator: rule.validator,
43 })
44 : Object.freeze({
45 kind: rule.kind,
46 id: rule.id,
47 action: rule.action,
48 names: Object.freeze([...rule.names]),
49 }),
50 ),
51 ),
52 });
53}
54export function effectiveConfiguration(layers: {
55 personal?: ConfigDocument;
56 project?: ConfigDocument;
57 session?: ConfigDocument;
58}): Readonly<{ document: ConfigDocument; source: ConfigScope }> {
59 // Each approved layer replaces the entire custom-rule list, including an empty list.
60 for (const source of ['session', 'project', 'personal'] as const) {
61 const document = layers[source];
62 if (document)
63 return Object.freeze({ document: freezeDocument(document), source });
64 }
65 return Object.freeze({
66 document: freezeDocument({ schemaVersion: 1, rules: [] }),
67 source: 'defaults',
68 });
69}
70
71export interface Draft {
72 readonly token: string;
73 readonly baseRevision: string;
74 readonly scope: ConfigScope;
75 readonly document: ConfigDocument;
76 readonly stage: 'editing' | 'validated' | 'previewed';
77}
78let controllerSequence = 0;
79export class ConfigController {
80 private readonly identity = ++controllerSequence;
81 private epoch = 0;
82 private draftEpoch = 0;
83 private active: ActiveConfiguration;
84 private draft: Draft | undefined;
85 private undo:
86 | Readonly<{ expectedRevision: string; config: ActiveConfiguration }>
87 | undefined;
88 constructor(
89 initial: ConfigDocument = { schemaVersion: 1, rules: [] },
90 source: ConfigScope = 'defaults',
91 ) {
92 this.active = this.activate(initial, source);
93 }
94 private activate(
95 document: ConfigDocument,
96 source: ConfigScope,
97 ): ActiveConfiguration {
98 this.epoch += 1;
99 return Object.freeze({
100 ...freezeDocument(document),
101 revision: `cfg-${this.identity}-${this.epoch}`,
102 source,
103 scope: source,
104 });
105 }
106 snapshot(): ActiveConfiguration {
107 return this.active;
108 }
109 begin(document: ConfigDocument, scope: ConfigScope = 'session'): Draft {
110 this.draftEpoch += 1;
111 this.draft = Object.freeze({
112 token: `draft-${this.identity}-${this.draftEpoch}`,
113 baseRevision: this.active.revision,
114 scope,
115 document: freezeDocument(document),
116 stage: 'editing',
117 });
118 return this.draft;
119 }
120 currentDraft(): Draft | undefined {
121 return this.draft;
122 }
123 // Only the registration adapter invokes these after matching helper replies.
124 validated(token: string, valid: boolean): boolean {
125 if (
126 !this.draft ||
127 this.draft.token !== token ||
128 this.draft.stage !== 'editing' ||
129 !valid
130 )
131 return false;
132 this.draft = Object.freeze({ ...this.draft, stage: 'validated' });
133 return true;
134 }
135 previewed(token: string, success: boolean): boolean {
136 if (
137 !this.draft ||
138 this.draft.token !== token ||
139 this.draft.stage !== 'validated' ||
140 !success
141 )
142 return false;
143 this.draft = Object.freeze({ ...this.draft, stage: 'previewed' });
144 return true;
145 }
146 cancel(token: string): void {
147 if (this.draft?.token === token) this.draft = undefined;
148 }
149 apply(token: string): ConfigResult {
150 const draft = this.draft;
151 if (!draft || draft.token !== token || draft.stage !== 'previewed')
152 return Object.freeze({ ok: false, code: 'INVALID_STAGE' });
153 if (draft.baseRevision !== this.active.revision)
154 return Object.freeze({ ok: false, code: 'STALE_REVISION' });
155 const previous = this.active;
156 this.active = this.activate(draft.document, draft.scope);
157 this.undo = Object.freeze({
158 expectedRevision: this.active.revision,
159 config: previous,
160 });
161 this.draft = undefined;
162 return Object.freeze({ ok: true, config: this.active });
163 }
164 replaceApproved(
165 document: ConfigDocument,
166 scope: ConfigScope,
167 expectedRevision: string,
168 ): ConfigResult {
169 if (this.active.revision !== expectedRevision)
170 return Object.freeze({ ok: false, code: 'STALE_REVISION' });
171 const previous = this.active;
172 this.active = this.activate(document, scope);
173 this.undo = Object.freeze({
174 expectedRevision: this.active.revision,
175 config: previous,
176 });
177 return Object.freeze({ ok: true, config: this.active });
178 }
179 revert(expectedRevision: string): ConfigResult {
180 if (
181 !this.undo ||
182 this.active.revision !== expectedRevision ||
183 this.undo.expectedRevision !== expectedRevision
184 )
185 return Object.freeze({ ok: false, code: 'STALE_REVISION' });
186 this.active = this.activate(this.undo.config, this.undo.config.source);
187 this.undo = undefined;
188 this.draft = undefined;
189 return Object.freeze({ ok: true, config: this.active });
190 }
191}
192
193export function addRule(
194 document: ConfigDocument,
195 rule: import('../helper/src/config.ts').CustomRule,
196): ConfigDocument | null {
197 if (document.rules.some((existing) => existing.id === rule.id)) return null;
198 return freezeDocument({ schemaVersion: 1, rules: [...document.rules, rule] });
199}
200export function removeRule(
201 document: ConfigDocument,
202 id: string,
203): ConfigDocument | null {
204 if (!document.rules.some((rule) => rule.id === id)) return null;
205 return freezeDocument({
206 schemaVersion: 1,
207 rules: document.rules.filter((rule) => rule.id !== id),
208 });
209}
210
211export function operationConfiguration(
212 state: import('./state.ts').OperationSnapshot,
213 config: ActiveConfiguration,
214): Readonly<{
215 protection: import('./state.ts').OperationSnapshot;
216 config: ActiveConfiguration;
217}> {
218 return Object.freeze({ protection: Object.freeze({ ...state }), config });
219}
220
221export function replaceRule(
222 document: ConfigDocument,
223 originalId: string,
224 edited: import('../helper/src/config.ts').CustomRule,
225): ConfigDocument | null {
226 if (
227 document.rules.filter((rule) => rule.id === originalId).length !== 1 ||
228 document.rules.some(
229 (rule) => rule.id !== originalId && rule.id === edited.id,
230 )
231 )
232 return null;
233 return freezeDocument({
234 schemaVersion: 1,
235 rules: document.rules.map((rule) =>
236 rule.id === originalId ? edited : rule,
237 ),
238 });
239}
240
241export function sharedNamesAction(
242 document: ConfigDocument,
243): import('../helper/src/config.ts').Action {
244 return (
245 document.rules.find((rule) => rule.kind === 'names')?.action ?? 'redact'
246 );
247}
248export function setNamesAction(
249 document: ConfigDocument,
250 action: import('../helper/src/config.ts').Action,
251): ConfigDocument {
252 return freezeDocument({
253 schemaVersion: 1,
254 rules: document.rules.map((rule) =>
255 rule.kind === 'names' ? { ...rule, action } : rule,
256 ),
257 });
258}
259mod/form.ts 133 lines1import { validateConfigDocument } from '../helper/src/config.ts';
2import {
3 addRule,
4 type ConfigDocument,
5 type CustomRule,
6 freezeDocument,
7 replaceRule,
8 setNamesAction,
9 type TokenRule,
10} from './config.ts';
11export interface RuleForm {
12 mode: 'config' | 'add' | 'remove' | 'project';
13 kind: 'token' | 'names';
14 id: string;
15 prefix: string;
16 names: string;
17 action: 'redact' | 'block';
18 alphabet: TokenRule['alphabet'];
19 runKind: 'exact' | 'at-least';
20 length: string;
21 specificity: 'contextual' | 'entropy';
22 validator: 'none' | 'trailing-lower-hex';
23 notice: string;
24 busy: boolean;
25 durableBusy: boolean;
26 editingId: string | null;
27 namesGroupAction: boolean;
28 resetScope: 'personal' | 'project' | null;
29 tab: 'rules' | 'storage' | 'transfer';
30 details: boolean;
31}
32export function freshForm(): RuleForm {
33 return {
34 mode: 'config',
35 kind: 'token',
36 id: '',
37 prefix: '',
38 names: '',
39 action: 'redact',
40 alphabet: 'alnum',
41 runKind: 'exact',
42 length: '16',
43 specificity: 'contextual',
44 validator: 'none',
45 notice: '',
46 busy: false,
47 durableBusy: false,
48 editingId: null,
49 namesGroupAction: false,
50 resetScope: null,
51 tab: 'rules',
52 details: false,
53 };
54}
55export function formRule(form: RuleForm): CustomRule | null {
56 const rule =
57 form.kind === 'token'
58 ? {
59 kind: 'token',
60 id: form.id,
61 action: form.action,
62 prefix: form.prefix,
63 alphabet: form.alphabet,
64 run: { kind: form.runKind, length: Number(form.length) },
65 specificity: form.specificity,
66 validator: form.validator,
67 }
68 : {
69 kind: 'names',
70 id: form.id,
71 action: form.action,
72 names: form.names.split(',').map((name) => name.trim()),
73 };
74 try {
75 return (
76 validateConfigDocument({ schemaVersion: 1, rules: [rule] }).rules[0] ??
77 null
78 );
79 } catch {
80 return null;
81 }
82}
83export function candidateConfiguration(
84 document: ConfigDocument,
85 token: string,
86): import('./config.ts').ActiveConfiguration {
87 return Object.freeze({
88 ...freezeDocument(document),
89 revision: token,
90 source: 'session',
91 scope: 'session',
92 });
93}
94
95export function populateForm(rule: CustomRule): RuleForm {
96 const form = freshForm();
97 form.mode = 'add';
98 form.editingId = rule.id;
99 form.kind = rule.kind;
100 form.id = rule.id;
101 form.action = rule.action;
102 if (rule.kind === 'token') {
103 form.prefix = rule.prefix;
104 form.alphabet = rule.alphabet;
105 form.runKind = rule.run.kind;
106 form.length = String(rule.run.length);
107 form.specificity = rule.specificity;
108 form.validator = rule.validator;
109 } else form.names = rule.names.join(', ');
110 return form;
111}
112export function candidateDocument(
113 active: ConfigDocument,
114 form: RuleForm,
115): ConfigDocument | null {
116 const rule = formRule(form);
117 if (!rule) return null;
118 const document =
119 form.editingId === null
120 ? addRule(active, rule)
121 : replaceRule(active, form.editingId, rule);
122 if (!document) return null;
123 try {
124 return validateConfigDocument(
125 rule.kind === 'names' && form.namesGroupAction
126 ? setNamesAction(document, rule.action)
127 : document,
128 );
129 } catch {
130 return null;
131 }
132}
133mod/protocol.ts 374 lines1import { canonicalTypes } from './canonical-types.ts';
2import type { ActiveConfiguration } from './config.ts';
3import {
4 isNonnegativeInteger,
5 hasOnlyKeys as keys,
6 isPlainRecord as plain,
7} from './validation.ts';
8
9export interface Segment {
10 id: string;
11 text: string;
12}
13interface RequestIdentity {
14 protocolVersion: 1 | 2;
15 config?: ActiveConfiguration;
16 requestId: string;
17 policyId: string;
18}
19export interface SanitizeRequest extends RequestIdentity {
20 operation: 'sanitize';
21 segments: Segment[];
22}
23export interface SelfCheckRequest extends RequestIdentity {
24 operation: 'self-check';
25}
26export interface ConfigurationRequest extends RequestIdentity {
27 operation: 'validate-config' | 'preview';
28 config: ActiveConfiguration;
29}
30export type HelperRequest =
31 | SanitizeRequest
32 | SelfCheckRequest
33 | ConfigurationRequest;
34export interface PreviewOutcome {
35 id: string;
36 positive: {
37 detected: boolean;
38 action: 'redact' | 'block' | 'none';
39 findingCounts: Record<string, number>;
40 };
41 negative: {
42 detected: boolean;
43 action: 'redact' | 'block' | 'none';
44 findingCounts: Record<string, number>;
45 };
46}
47export type HelperResponse =
48 | { status: 'failed' | 'blocked'; errorCode: string }
49 | {
50 status: 'ok';
51 segments?: Segment[];
52 validated?: true;
53 outcomes?: PreviewOutcome[];
54 configRevision?: string;
55 findingCounts: Record<string, number>;
56 count: number;
57 artifact: 'addon' | 'wasm';
58 };
59
60export const LIMITS = Object.freeze({
61 inputBytes: 262144,
62 segments: 256,
63 findings: 1000,
64 outputBytes: 2097152,
65 timeoutMs: 2000,
66 settingsTimeoutMs: 5000,
67 pending: 4,
68});
69export const POLICY_ID = 'credentials-alpha1';
70export const ENGINE_VERSION = '0.1.0-beta.14';
71const typeSet: ReadonlySet<string> = new Set(canonicalTypes);
72const opaqueId = /^[A-Za-z0-9_-]{1,64}$/;
73const codes = new Set([
74 'INVALID_REQUEST',
75 'INPUT_LIMIT',
76 'ENGINE_VERSION',
77 'ENGINE_UNAVAILABLE',
78 'ENGINE_RESPONSE',
79 'FINDING_LIMIT',
80 'POLICY_FAILURE',
81 'PRIVATE_KEY_BLOCKED',
82 'ENGINE_FAILURE',
83 'OUTPUT_LIMIT',
84 'TIMEOUT',
85 'INVALID_JSON',
86 'INPUT_FAILURE',
87 'RULE_BLOCKED',
88 'INVALID_CONFIG',
89 'NAMES_ACTION_CONFLICT',
90]);
91
92export function utf8Bytes(text: string): number {
93 let bytes = 0;
94 for (let i = 0; i < text.length; i++) {
95 const code = text.charCodeAt(i);
96 if (code < 0x80) bytes += 1;
97 else if (code < 0x800) bytes += 2;
98 else if (
99 code >= 0xd800 &&
100 code <= 0xdbff &&
101 i + 1 < text.length &&
102 text.charCodeAt(i + 1) >= 0xdc00 &&
103 text.charCodeAt(i + 1) <= 0xdfff
104 ) {
105 bytes += 4;
106 i += 1;
107 } else bytes += 3;
108 }
109 return bytes;
110}
111
112export function makeRequest(
113 requestId: unknown,
114 segments: unknown,
115 config?: ActiveConfiguration,
116): SanitizeRequest | null {
117 if (
118 typeof requestId !== 'string' ||
119 !opaqueId.test(requestId) ||
120 !Array.isArray(segments) ||
121 segments.length > LIMITS.segments ||
122 !segments.length
123 )
124 return null;
125 const ids = new Set<string>();
126 let bytes = 0;
127 const validated: Segment[] = [];
128 for (const segment of segments) {
129 if (
130 !keys(segment, ['id', 'text']) ||
131 typeof segment.id !== 'string' ||
132 !opaqueId.test(segment.id) ||
133 typeof segment.text !== 'string' ||
134 ids.has(segment.id)
135 )
136 return null;
137 ids.add(segment.id);
138 validated.push({ id: segment.id, text: segment.text });
139 bytes += utf8Bytes(segment.text);
140 if (bytes > LIMITS.inputBytes) return null;
141 }
142 const request: SanitizeRequest = {
143 protocolVersion: config ? 2 : 1,
144 ...(config ? { config } : {}),
145 requestId,
146 operation: 'sanitize',
147 policyId: POLICY_ID,
148 segments: validated,
149 };
150 return utf8Bytes(JSON.stringify(request)) <= LIMITS.inputBytes
151 ? request
152 : null;
153}
154
155export function validateProcessResponse(
156 processResult: unknown,
157 request: HelperRequest,
158): HelperResponse {
159 const invalid: HelperResponse = {
160 status: 'failed',
161 errorCode: 'INVALID_HELPER_RESPONSE',
162 };
163 if (
164 !keys(processResult, [
165 'exitCode',
166 'stdout',
167 'stderr',
168 'isStdoutTruncated',
169 'isStderrTruncated',
170 ]) ||
171 processResult.exitCode !== 0 ||
172 processResult.isStdoutTruncated !== false ||
173 processResult.isStderrTruncated !== false ||
174 processResult.stderr !== '' ||
175 typeof processResult.stdout !== 'string' ||
176 utf8Bytes(processResult.stdout) > LIMITS.outputBytes
177 )
178 return invalid;
179 let value: unknown;
180 try {
181 value = JSON.parse(processResult.stdout);
182 } catch {
183 return invalid;
184 }
185 if (
186 !plain(value) ||
187 value.protocolVersion !== request.protocolVersion ||
188 (request.protocolVersion === 2 &&
189 (!request.config || value.configRevision !== request.config.revision)) ||
190 value.requestId !== request.requestId ||
191 value.engineVersion !== ENGINE_VERSION ||
192 value.policyId !== POLICY_ID
193 )
194 return invalid;
195 if (value.status === 'blocked' || value.status === 'failed') {
196 if (
197 !keys(value, [
198 'protocolVersion',
199 'requestId',
200 'status',
201 'engineVersion',
202 'policyId',
203 'errorCode',
204 ...(request.protocolVersion === 2 ? ['configRevision'] : []),
205 ]) ||
206 typeof value.errorCode !== 'string' ||
207 !codes.has(value.errorCode)
208 )
209 return invalid;
210 return { status: value.status, errorCode: value.errorCode };
211 }
212 const boundKeys = request.protocolVersion === 2 ? ['configRevision'] : [];
213 const allowedTypes = new Set(typeSet);
214 for (const rule of request.config?.rules ?? [])
215 if (rule.kind === 'token') allowedTypes.add(rule.id);
216 function counts(input: unknown): Record<string, number> | null {
217 if (!plain(input)) return null;
218 const result: Record<string, number> = {};
219 let total = 0;
220 for (const [type, count] of Object.entries(input)) {
221 if (!allowedTypes.has(type) || !isNonnegativeInteger(count)) return null;
222 total += count;
223 if (total > LIMITS.findings) return null;
224 result[type] = count;
225 }
226 return result;
227 }
228 if (
229 request.operation === 'validate-config' ||
230 request.operation === 'preview'
231 ) {
232 if (
233 value.status !== 'ok' ||
234 (value.artifact !== 'addon' && value.artifact !== 'wasm')
235 )
236 return invalid;
237 const common = [
238 'protocolVersion',
239 'requestId',
240 'status',
241 'engineVersion',
242 'policyId',
243 'artifact',
244 ...boundKeys,
245 ];
246 if (request.operation === 'validate-config') {
247 if (
248 !keys(value, [...common, 'validated', 'ruleCount']) ||
249 value.validated !== true ||
250 value.ruleCount !== request.config.rules.length
251 )
252 return invalid;
253 return {
254 status: 'ok',
255 validated: true,
256 findingCounts: {},
257 count: 0,
258 artifact: value.artifact,
259 configRevision: request.config.revision,
260 };
261 }
262 if (
263 !keys(value, [...common, 'outcomes']) ||
264 !Array.isArray(value.outcomes) ||
265 value.outcomes.length !== request.config.rules.length
266 )
267 return invalid;
268 const expected = new Map(
269 request.config.rules.map((rule) => [rule.id, rule]),
270 );
271 const outcomes: PreviewOutcome[] = [];
272 let total = 0;
273 function preview(input: unknown): PreviewOutcome['positive'] | null {
274 if (
275 !keys(input, ['detected', 'action', 'findingCounts']) ||
276 typeof input.detected !== 'boolean' ||
277 (input.action !== 'redact' &&
278 input.action !== 'block' &&
279 input.action !== 'none')
280 )
281 return null;
282 const findingCounts = counts(input.findingCounts);
283 if (!findingCounts) return null;
284 const count = Object.values(findingCounts).reduce((a, b) => a + b, 0);
285 total += count;
286 if (
287 total > LIMITS.findings ||
288 input.detected !== count > 0 ||
289 (input.action === 'none') !== (count === 0)
290 )
291 return null;
292 return { detected: input.detected, action: input.action, findingCounts };
293 }
294 for (const outcome of value.outcomes) {
295 if (
296 !keys(outcome, ['id', 'positive', 'negative']) ||
297 typeof outcome.id !== 'string'
298 )
299 return invalid;
300 const rule = expected.get(outcome.id);
301 if (!rule) return invalid;
302 expected.delete(outcome.id);
303 const positive = preview(outcome.positive),
304 negative = preview(outcome.negative);
305 if (!positive || !negative) return invalid;
306 outcomes.push({ id: outcome.id, positive, negative });
307 }
308 if (expected.size) return invalid;
309 return {
310 status: 'ok',
311 outcomes,
312 findingCounts: {},
313 count: total,
314 artifact: value.artifact,
315 configRevision: request.config.revision,
316 };
317 }
318 if (
319 value.status !== 'ok' ||
320 !keys(value, [
321 'protocolVersion',
322 'requestId',
323 'status',
324 'engineVersion',
325 'policyId',
326 'artifact',
327 'segments',
328 'findingCounts',
329 ...boundKeys,
330 ]) ||
331 (value.artifact !== 'addon' && value.artifact !== 'wasm') ||
332 !plain(value.findingCounts)
333 )
334 return invalid;
335 const findingCounts: Record<string, number> = {};
336 let total = 0;
337 for (const [type, count] of Object.entries(value.findingCounts)) {
338 if (!allowedTypes.has(type) || !isNonnegativeInteger(count)) return invalid;
339 findingCounts[type] = count;
340 total += count;
341 if (total > LIMITS.findings) return invalid;
342 }
343 const segments: Segment[] = [];
344 if (request.operation === 'self-check') {
345 if ('segments' in value || total !== 0) return invalid;
346 } else if (request.operation === 'sanitize') {
347 if (
348 !Array.isArray(value.segments) ||
349 value.segments.length !== request.segments.length
350 )
351 return invalid;
352 const expected = new Set(request.segments.map((segment) => segment.id));
353 for (const segment of value.segments) {
354 if (
355 !keys(segment, ['id', 'text']) ||
356 typeof segment.id !== 'string' ||
357 typeof segment.text !== 'string' ||
358 !expected.delete(segment.id)
359 )
360 return invalid;
361 segments.push({ id: segment.id, text: segment.text });
362 }
363 if (expected.size) return invalid;
364 } else return invalid;
365 return {
366 status: 'ok',
367 ...(request.operation === 'sanitize' ? { segments } : {}),
368 findingCounts,
369 count: total,
370 artifact: value.artifact,
371 ...(request.config ? { configRevision: request.config.revision } : {}),
372 };
373}
374mod/recovery.ts 36 lines1// Only fixed protocol/local codes receive operation-local treatment.
2export function failureScope(
3 operation: string,
4 code: string,
5): 'operation' | 'scanner' {
6 if (
7 operation === 'sanitize' &&
8 new Set([
9 'INPUT_LIMIT',
10 'OUTPUT_LIMIT',
11 'FINDING_LIMIT',
12 'PRIVATE_KEY_BLOCKED',
13 'RULE_BLOCKED',
14 'CANCELLED',
15 'QUEUE_SATURATED',
16 'UNSUPPORTED_SHAPE',
17 ]).has(code)
18 )
19 return 'operation';
20 return 'scanner';
21}
22
23export function settingsRemediation(code: string): string {
24 if (
25 new Set([
26 'SETTINGS_CORRUPT',
27 'INVALID_CONFIG',
28 'NAMES_ACTION_CONFLICT',
29 ]).has(code)
30 )
31 return 'Saved settings require local repair: restore a valid approved personal settings file, or explicitly remove that scope file to reset its custom rules, then run /redacton. Active rules are unchanged until recovery succeeds.';
32 return code
33 ? `Settings: ${code}. Remove the local fault, then run /redacton for one recovery attempt.`
34 : 'Run /redacton for one scanner self-check recovery attempt.';
35}
36mod/settings.ts 187 lines1import { type ConfigDocument, freezeDocument } from './config.ts';
2export type SavedScope = 'personal' | 'project';
3export interface SavedConfiguration {
4 readonly scope: SavedScope;
5 readonly identity: string;
6 readonly revision: string;
7 readonly document: ConfigDocument;
8}
9export interface SaveIntent {
10 readonly token: string;
11 readonly scope: SavedScope;
12 readonly identity: string;
13 readonly expectedRevision: string;
14 readonly document: ConfigDocument;
15}
16// The host supplies only validated helper receipts. Project data remains unapproved
17// until a local review explicitly grants trust for the exact loaded revision.
18let settingsSequence = 0;
19export class SavedSettingsController {
20 private readonly identity = ++settingsSequence;
21 private loaded = new Map<SavedScope, SavedConfiguration>();
22 private approved = new Map<SavedScope, string>();
23 private pending: SaveIntent | undefined;
24 private epoch = 0;
25 private pendingBase: ConfigDocument | undefined;
26 resetSession(): void {
27 this.loaded.clear();
28 this.approved.clear();
29 this.pending = undefined;
30 this.pendingBase = undefined;
31 }
32 loadedConfiguration(scope: SavedScope): SavedConfiguration | undefined {
33 return this.loaded.get(scope);
34 }
35 observe(value: SavedConfiguration): void {
36 const prior = this.loaded.get(value.scope);
37 const safe = Object.freeze({
38 scope: value.scope,
39 identity: value.identity,
40 revision: value.revision,
41 document: freezeDocument(value.document),
42 });
43 this.loaded.set(value.scope, safe);
44 if (value.scope === 'personal')
45 this.approved.set(value.scope, value.revision);
46 else if (
47 prior?.identity !== value.identity ||
48 prior.revision !== value.revision ||
49 JSON.stringify(prior.document) !== JSON.stringify(safe.document)
50 )
51 this.approved.delete(value.scope);
52 }
53 approveProject(
54 identity: string,
55 revision: string,
56 reviewed: ConfigDocument,
57 ): boolean {
58 const value = this.loaded.get('project');
59 if (
60 !value ||
61 value.identity !== identity ||
62 value.revision !== revision ||
63 JSON.stringify(value.document) !==
64 JSON.stringify(freezeDocument(reviewed))
65 )
66 return false;
67 this.approved.set('project', revision);
68 return true;
69 }
70 approvedLayers(): Readonly<{
71 personal?: ConfigDocument;
72 project?: ConfigDocument;
73 }> {
74 const result: { personal?: ConfigDocument; project?: ConfigDocument } = {};
75 for (const scope of ['personal', 'project'] as const) {
76 const saved = this.loaded.get(scope);
77 if (saved && this.approved.get(scope) === saved.revision)
78 result[scope] = saved.document;
79 }
80 return Object.freeze(result);
81 }
82 beginSave(scope: SavedScope, document: ConfigDocument): SaveIntent | null {
83 const saved = this.loaded.get(scope);
84 if (
85 !saved ||
86 (scope === 'project' && this.approved.get(scope) !== saved.revision)
87 )
88 return null;
89 this.epoch += 1;
90 this.pendingBase = saved.document;
91 this.pending = Object.freeze({
92 token: `save-${this.identity}-${this.epoch}`,
93 scope,
94 identity: saved.identity,
95 expectedRevision: saved.revision,
96 document: freezeDocument(document),
97 });
98 return this.pending;
99 }
100 cancel(token: string): void {
101 if (this.pending?.token === token) {
102 this.pending = undefined;
103 this.pendingBase = undefined;
104 }
105 }
106 saved(token: string, receipt: SavedConfiguration): boolean {
107 const pending = this.pending;
108 const current = pending && this.loaded.get(pending.scope);
109 if (
110 !pending ||
111 pending.token !== token ||
112 !current ||
113 current.revision !== pending.expectedRevision ||
114 current.identity !== pending.identity ||
115 JSON.stringify(current.document) !== JSON.stringify(this.pendingBase) ||
116 receipt.scope !== pending.scope ||
117 receipt.identity !== pending.identity ||
118 receipt.revision === pending.expectedRevision
119 )
120 return false;
121 // Match the declarative payload as well as the privileged write identity.
122 if (
123 JSON.stringify(freezeDocument(receipt.document)) !==
124 JSON.stringify(pending.document)
125 )
126 return false;
127 this.observe(receipt);
128 this.approved.set(receipt.scope, receipt.revision);
129 this.pending = undefined;
130 this.pendingBase = undefined;
131 return true;
132 }
133}
134
135export interface ImportCandidate {
136 readonly token: string;
137 readonly scope: SavedScope;
138 readonly identity: string;
139 readonly document: ConfigDocument;
140}
141let importSequence = 0;
142export class ImportReviewController {
143 private readonly identity = ++importSequence;
144 private epoch = 0;
145 private candidate: ImportCandidate | undefined;
146 private approvedToken: string | undefined;
147 stage(
148 scope: SavedScope,
149 identity: string,
150 document: ConfigDocument,
151 ): ImportCandidate {
152 this.epoch += 1;
153 this.approvedToken = undefined;
154 this.candidate = Object.freeze({
155 token: `import-${this.identity}-${this.epoch}`,
156 scope,
157 identity,
158 document: freezeDocument(document),
159 });
160 return this.candidate;
161 }
162 snapshot(): ImportCandidate | undefined {
163 return this.candidate;
164 }
165 approve(token: string, reviewed: ConfigDocument): boolean {
166 const candidate = this.candidate;
167 if (
168 !candidate ||
169 candidate.token !== token ||
170 JSON.stringify(candidate.document) !==
171 JSON.stringify(freezeDocument(reviewed))
172 )
173 return false;
174 this.approvedToken = token;
175 return true;
176 }
177 approved(token: string): ConfigDocument | null {
178 return this.candidate?.token === token && this.approvedToken === token
179 ? this.candidate.document
180 : null;
181 }
182 cancel(): void {
183 this.candidate = undefined;
184 this.approvedToken = undefined;
185 }
186}
187mod/state.ts 112 lines1export type Readiness = 'loading' | 'ready' | 'unavailable';
2
3export interface RecentEvent {
4 errorCode: string;
5 count: number;
6}
7export interface SessionState {
8 sessionId: string;
9 requestedProtection: boolean;
10 readiness: Readiness;
11 policyEpoch: number;
12 recent: Readonly<RecentEvent>[];
13}
14export type OperationSnapshot = Readonly<Omit<SessionState, 'recent'>>;
15
16const readinessValues = new Set(['loading', 'ready', 'unavailable']);
17const errorCodes = new Set([
18 'SCANNED',
19 'FAILED',
20 'UNSUPPORTED_SHAPE',
21 'INVALID_RESPONSE',
22 'INVALID_REQUEST',
23 'INPUT_LIMIT',
24 'OUTPUT_LIMIT',
25 'FINDING_LIMIT',
26 'TIMEOUT',
27 'ENGINE_VERSION',
28 'ENGINE_UNAVAILABLE',
29 'ENGINE_RESPONSE',
30 'ENGINE_FAILURE',
31 'POLICY_FAILURE',
32 'PRIVATE_KEY_BLOCKED',
33 'HELPER_UNAVAILABLE',
34 'CANCELLED',
35 'QUEUE_LIMIT',
36 'QUEUE_SATURATED',
37 'RULE_BLOCKED',
38 'INVALID_CONFIG',
39 'NAMES_ACTION_CONFLICT',
40 'INVALID_JSON',
41 'INPUT_FAILURE',
42 'INVALID_HELPER_RESPONSE',
43]);
44
45export function createSessionState(sessionId: string): SessionState {
46 if (typeof sessionId !== 'string' || !sessionId.length)
47 throw new Error('INVALID_SESSION');
48 return {
49 sessionId,
50 requestedProtection: true,
51 readiness: 'loading',
52 policyEpoch: 0,
53 recent: [],
54 };
55}
56
57export function snapshot(state: SessionState): OperationSnapshot {
58 return Object.freeze({
59 sessionId: state.sessionId,
60 requestedProtection: state.requestedProtection,
61 readiness: state.readiness,
62 policyEpoch: state.policyEpoch,
63 });
64}
65
66export function requestProtection(
67 state: SessionState,
68 enabled: boolean,
69): OperationSnapshot {
70 if (typeof enabled !== 'boolean') throw new Error('INVALID_STATE');
71 if (state.requestedProtection !== enabled) {
72 state.requestedProtection = enabled;
73 state.policyEpoch += 1;
74 }
75 return snapshot(state);
76}
77
78export function setReadiness(
79 state: SessionState,
80 readiness: Readiness,
81): OperationSnapshot {
82 if (!readinessValues.has(readiness)) throw new Error('INVALID_READINESS');
83 if (state.readiness !== readiness) {
84 state.readiness = readiness;
85 state.policyEpoch += 1;
86 }
87 return snapshot(state);
88}
89
90export function record(
91 state: SessionState,
92 event: RecentEvent,
93): Readonly<RecentEvent> {
94 if (
95 !event ||
96 !errorCodes.has(event.errorCode) ||
97 !Number.isSafeInteger(event.count) ||
98 event.count < 0
99 ) {
100 throw new Error('INVALID_RECORD');
101 }
102 // Project fixed metadata; never copy arbitrary diagnostic or input fields.
103 const safe = Object.freeze({
104 errorCode: event.errorCode,
105 count: event.count,
106 });
107 state.recent.push(safe);
108 if (state.recent.length > 100)
109 state.recent.splice(0, state.recent.length - 100);
110 return safe;
111}
112mod/storage.ts 235 lines1import { validateConfigDocument } from '../helper/src/config.ts';
2import type { ConfigDocument } from './config.ts';
3import { ENGINE_VERSION, LIMITS, POLICY_ID, utf8Bytes } from './protocol.ts';
4import type { SavedConfiguration, SavedScope } from './settings.ts';
5import { hasOnlyKeys as keys, isPlainRecord as plain } from './validation.ts';
6export interface StorageRequest {
7 protocolVersion: 2;
8 requestId: string;
9 operation:
10 | 'load-config'
11 | 'save-config'
12 | 'reset-config'
13 | 'import-config'
14 | 'export-config';
15 policyId: typeof POLICY_ID;
16 storage: {
17 scope: SavedScope;
18 approved: boolean;
19 projectRoot?: string;
20 expectedRevision?: string;
21 expectedIdentity?: string;
22 expectedDocument?: ConfigDocument;
23 document?: ConfigDocument;
24 };
25}
26export type StorageResponse =
27 | { ok: true; settings: SavedConfiguration }
28 | { ok: false; code: string };
29const codes = new Set([
30 'SETTINGS_UNAVAILABLE',
31 'SETTINGS_CONFLICT',
32 'SETTINGS_BUSY',
33 'SETTINGS_CORRUPT',
34 'ENGINE_VERSION',
35 'ENGINE_UNAVAILABLE',
36 'PROJECT_TRUST_REQUIRED',
37 'INVALID_CONFIG',
38 'NAMES_ACTION_CONFLICT',
39 'INVALID_REQUEST',
40 'INPUT_LIMIT',
41 'OUTPUT_LIMIT',
42 'INPUT_FAILURE',
43 'TIMEOUT',
44]);
45export function validateStorageResponse(
46 result: unknown,
47 request: StorageRequest,
48): StorageResponse {
49 const failure: StorageResponse = {
50 ok: false,
51 code: 'INVALID_SETTINGS_RESPONSE',
52 };
53 if (
54 !keys(result, [
55 'exitCode',
56 'stdout',
57 'stderr',
58 'isStdoutTruncated',
59 'isStderrTruncated',
60 ]) ||
61 result.exitCode !== 0 ||
62 result.stderr !== '' ||
63 result.isStdoutTruncated !== false ||
64 result.isStderrTruncated !== false ||
65 typeof result.stdout !== 'string' ||
66 utf8Bytes(result.stdout) > LIMITS.outputBytes
67 )
68 return failure;
69 let value: unknown;
70 try {
71 value = JSON.parse(result.stdout);
72 } catch {
73 return failure;
74 }
75 if (
76 !plain(value) ||
77 value.protocolVersion !== 2 ||
78 value.requestId !== request.requestId ||
79 value.engineVersion !== ENGINE_VERSION ||
80 value.policyId !== POLICY_ID
81 )
82 return failure;
83 if (value.status === 'failed') {
84 if (
85 !keys(value, [
86 'protocolVersion',
87 'requestId',
88 'status',
89 'engineVersion',
90 'policyId',
91 'errorCode',
92 ]) ||
93 typeof value.errorCode !== 'string' ||
94 !codes.has(value.errorCode)
95 )
96 return failure;
97 return { ok: false, code: value.errorCode };
98 }
99 if (
100 value.status !== 'ok' ||
101 (value.artifact !== 'addon' && value.artifact !== 'wasm') ||
102 !keys(value, [
103 'protocolVersion',
104 'requestId',
105 'status',
106 'engineVersion',
107 'policyId',
108 'artifact',
109 'settings',
110 ]) ||
111 !keys(value.settings, ['scope', 'identity', 'revision', 'document']) ||
112 value.settings.scope !== request.storage.scope ||
113 typeof value.settings.identity !== 'string' ||
114 !/^[0-9a-f]{64}$/.test(value.settings.identity) ||
115 typeof value.settings.revision !== 'string' ||
116 !/^(?:absent|[0-9a-f-]{36})$/.test(value.settings.revision)
117 )
118 return failure;
119 try {
120 const document = validateConfigDocument(value.settings.document);
121 return {
122 ok: true,
123 settings: {
124 scope: request.storage.scope,
125 identity: value.settings.identity,
126 revision: value.settings.revision,
127 document,
128 },
129 };
130 } catch {
131 return failure;
132 }
133}
134
135export interface TransferReceipt {
136 scope: SavedScope;
137 identity: string;
138 document: ConfigDocument;
139}
140export type TransferResponse =
141 | { ok: true; transfer: TransferReceipt }
142 | { ok: false; code: string };
143export function validateTransferResponse(
144 result: unknown,
145 request: StorageRequest,
146): TransferResponse {
147 const failure: TransferResponse = {
148 ok: false,
149 code: 'INVALID_TRANSFER_RESPONSE',
150 };
151 if (
152 !keys(result, [
153 'exitCode',
154 'stdout',
155 'stderr',
156 'isStdoutTruncated',
157 'isStderrTruncated',
158 ]) ||
159 result.exitCode !== 0 ||
160 result.stderr !== '' ||
161 result.isStdoutTruncated !== false ||
162 result.isStderrTruncated !== false ||
163 typeof result.stdout !== 'string' ||
164 utf8Bytes(result.stdout) > LIMITS.outputBytes
165 )
166 return failure;
167 let value: unknown;
168 try {
169 value = JSON.parse(result.stdout);
170 } catch {
171 return failure;
172 }
173 if (
174 !plain(value) ||
175 value.protocolVersion !== 2 ||
176 value.requestId !== request.requestId ||
177 value.engineVersion !== ENGINE_VERSION ||
178 value.policyId !== POLICY_ID
179 )
180 return failure;
181 if (value.status === 'failed') {
182 if (
183 !keys(value, [
184 'protocolVersion',
185 'requestId',
186 'status',
187 'engineVersion',
188 'policyId',
189 'errorCode',
190 ]) ||
191 typeof value.errorCode !== 'string' ||
192 !codes.has(value.errorCode)
193 )
194 return failure;
195 return { ok: false, code: value.errorCode };
196 }
197 if (
198 value.status !== 'ok' ||
199 (value.artifact !== 'addon' && value.artifact !== 'wasm') ||
200 !keys(value, [
201 'protocolVersion',
202 'requestId',
203 'status',
204 'engineVersion',
205 'policyId',
206 'artifact',
207 'transfer',
208 ]) ||
209 !keys(value.transfer, ['scope', 'identity', 'document']) ||
210 value.transfer.scope !== request.storage.scope ||
211 typeof value.transfer.identity !== 'string' ||
212 !/^[0-9a-f]{64}$/.test(value.transfer.identity)
213 )
214 return failure;
215 try {
216 const document = validateConfigDocument(value.transfer.document);
217 if (
218 request.operation === 'export-config' &&
219 (value.transfer.identity !== request.storage.expectedIdentity ||
220 JSON.stringify(document) !== JSON.stringify(request.storage.document))
221 )
222 return failure;
223 return {
224 ok: true,
225 transfer: {
226 scope: request.storage.scope,
227 identity: value.transfer.identity,
228 document,
229 },
230 };
231 } catch {
232 return failure;
233 }
234}
235mod/view.ts 78 lines1import type { ActiveConfiguration } from './config.ts';
2import type { SessionState } from './state.ts';
3
4export interface StatusView {
5 readonly protection: 'ON' | 'OFF';
6 readonly readiness: 'loading' | 'ready' | 'unavailable';
7 readonly observedAt: number | null;
8 readonly readinessNote: 'CACHED_OBSERVATION_NOT_HEALTH_CHECK';
9 readonly customRuleCount: number;
10 readonly ruleIds: readonly string[];
11 readonly source: ActiveConfiguration['source'];
12 readonly scope: ActiveConfiguration['scope'];
13 readonly revision: string;
14 readonly supported: readonly string[];
15 readonly excluded: readonly string[];
16 readonly recent: readonly Readonly<{ code: string; count: number }>[];
17 readonly zeroFindingsNote: 'ZERO_FINDINGS_NOT_SAFE_CONTENT';
18}
19export function statusView(
20 state: SessionState,
21 config: ActiveConfiguration,
22 observedAt: number | null,
23): StatusView {
24 return Object.freeze({
25 protection: state.requestedProtection ? 'ON' : 'OFF',
26 readiness: state.readiness,
27 observedAt:
28 observedAt !== null && Number.isSafeInteger(observedAt) && observedAt >= 0
29 ? observedAt
30 : null,
31 readinessNote: 'CACHED_OBSERVATION_NOT_HEALTH_CHECK',
32 customRuleCount: config.rules.length,
33 ruleIds: Object.freeze(config.rules.map((rule) => rule.id)),
34 source: config.source,
35 scope: config.scope,
36 revision: config.revision,
37 supported: Object.freeze([
38 'PROMPT_TEXT_CONTEXT',
39 'READ_TEXT',
40 'BASH_STDOUT_STDERR',
41 ]),
42 excluded: Object.freeze([
43 'MCP_OTHER_TOOLS',
44 'TOOL_ARGUMENTS',
45 'BINARY_IMAGE_AUDIO',
46 'PII',
47 'EXISTING_HISTORY',
48 ]),
49 recent: Object.freeze(
50 state.recent
51 .slice(-100)
52 .map((event) =>
53 Object.freeze({ code: event.errorCode, count: event.count }),
54 ),
55 ),
56 zeroFindingsNote: 'ZERO_FINDINGS_NOT_SAFE_CONTENT',
57 });
58}
59export function removalView(
60 config: ActiveConfiguration,
61 id: string,
62): Readonly<{
63 id: string;
64 source: ActiveConfiguration['source'];
65 scope: ActiveConfiguration['scope'];
66 removable: boolean;
67 impact: string;
68}> | null {
69 if (!config.rules.some((rule) => rule.id === id)) return null;
70 return Object.freeze({
71 id,
72 source: config.source,
73 scope: config.scope,
74 removable: config.scope === 'session',
75 impact: 'REMOVES_ADDITIONAL_RULE_BUILTINS_MAY_STILL_MATCH',
76 });
77}
78mod/validation.ts 47 lines1export function isPlainRecord(
2 value: unknown,
3): value is Record<string, unknown> {
4 if (value === null || typeof value !== 'object' || Array.isArray(value))
5 return false;
6 const prototype = Object.getPrototypeOf(value);
7 return prototype === Object.prototype || prototype === null;
8}
9
10export function hasOwn(value: object, key: PropertyKey): boolean {
11 return Object.hasOwn(value, key);
12}
13
14// Reject accessors and symbols at content boundaries, before reading their values.
15export function hasOnlyDataKeys(
16 value: unknown,
17 allowed: readonly string[],
18): value is Record<string, unknown> {
19 if (!isPlainRecord(value)) return false;
20 return Reflect.ownKeys(value).every((key) => {
21 if (typeof key !== 'string' || !allowed.includes(key)) return false;
22 const descriptor = Object.getOwnPropertyDescriptor(value, key);
23 return descriptor !== undefined && 'value' in descriptor;
24 });
25}
26
27export function hasOnlyKeys(
28 value: unknown,
29 allowed: readonly string[],
30): value is Record<string, unknown> {
31 return (
32 isPlainRecord(value) &&
33 Object.keys(value).every((key) => allowed.includes(key))
34 );
35}
36
37export function isNonnegativeInteger(value: unknown): value is number {
38 return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
39}
40
41export function isStringArray(value: unknown): value is string[] {
42 return (
43 Array.isArray(value) &&
44 value.every((entry: unknown) => typeof entry === 'string')
45 );
46}
47