crysk 0.3.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +26 -17
  2. package/config/models/anthropic.json +1 -1
  3. package/dist/SKILL-dsnffnfp.md +140 -0
  4. package/dist/SKILL-gnrbph72.md +140 -0
  5. package/dist/SKILL-k4k0zn1w.md +143 -0
  6. package/dist/SKILL-kq0xejn3.md +553 -0
  7. package/dist/SKILL-qaqsbygw.md +66 -0
  8. package/dist/SKILL-vhb4c3vv.md +553 -0
  9. package/dist/SKILL-vws0aqb8.md +553 -0
  10. package/dist/SKILL-xpf6kmdw.md +74 -0
  11. package/dist/ci-admission-0ken6ehx.md +128 -0
  12. package/dist/ci-admission-t0f5qwth.md +128 -0
  13. package/dist/cli.js +3366 -1680
  14. package/dist/index.js +1884 -947
  15. package/dist/opencode-ci-ac5zksdn.md +106 -0
  16. package/dist/workflow-4pkyck01.yml +160 -0
  17. package/package.json +2 -2
  18. package/prompts/default/PROVENANCE.md +1 -0
  19. package/skills/crysk/SKILL.md +16 -16
  20. package/skills/crysk-ci-setup/SKILL.md +42 -39
  21. package/skills/crysk-ci-setup/assets/workflow.yml +31 -22
  22. package/skills/crysk-ci-setup/references/ci-admission.md +2 -2
  23. package/skills/crysk-ci-setup/references/opencode-ci.md +53 -88
  24. package/skills/crysk-loop/SKILL.md +20 -9
  25. package/skills/crysk-pr/SKILL.md +1 -1
  26. package/src/asset-manifest.ts +0 -4
  27. package/src/assets.ts +2 -2
  28. package/src/ci/admission-ledger.ts +4 -0
  29. package/src/ci/classify-error.ts +21 -24
  30. package/src/ci/cli-record.ts +53 -1
  31. package/src/ci/crysk-secrets.ts +409 -0
  32. package/src/ci/gates.ts +31 -42
  33. package/src/ci/outcome.ts +421 -330
  34. package/src/ci/platform-config.ts +127 -0
  35. package/src/ci/platform-report.ts +935 -0
  36. package/src/ci/platform-trace.ts +551 -0
  37. package/src/ci/platform.ts +465 -0
  38. package/src/ci/publish.ts +19 -6
  39. package/src/ci/reporter.ts +9 -7
  40. package/src/ci/review-admission.ts +8 -4
  41. package/src/ci/review-levels.ts +8 -7
  42. package/src/ci/run.ts +88 -0
  43. package/src/ci/setup.ts +547 -109
  44. package/src/ci/trace-bundle.ts +1282 -0
  45. package/src/ci/trace-transcripts.ts +415 -0
  46. package/src/ci/trigger.ts +176 -33
  47. package/src/cli.ts +11 -3
  48. package/src/commands/ci-setup-questions.ts +3 -3
  49. package/src/commands/ci-setup.ts +152 -6
  50. package/src/commands/config.ts +3 -0
  51. package/src/commands/doctor.ts +15 -6
  52. package/src/compare/loop.ts +9 -1
  53. package/src/compare/martian-adapter.ts +1 -1
  54. package/src/config/config.ts +16 -3
  55. package/src/diversity/clustering.ts +0 -1
  56. package/src/diversity/identity.ts +4 -5
  57. package/src/diversity/pipeline-integration.ts +1 -9
  58. package/src/doctor.ts +3 -3
  59. package/src/execution/attempt-evidence.ts +10 -5
  60. package/src/execution/claude-session-trace.ts +480 -0
  61. package/src/execution/contracts.ts +21 -4
  62. package/src/execution/harness.ts +105 -8
  63. package/src/execution/model-fallback.ts +239 -0
  64. package/src/execution/usage-normalized.ts +6 -4
  65. package/src/home-preflight.ts +1 -1
  66. package/src/index.ts +1 -1
  67. package/src/model/catalog.ts +13 -37
  68. package/src/model/free-discovery.ts +117 -8
  69. package/src/model/model-name.ts +404 -0
  70. package/src/model/provider-capabilities.ts +22 -7
  71. package/src/model/routing.ts +346 -467
  72. package/src/pr/admission.ts +71 -11
  73. package/src/pr/ci-admission-gate.ts +2 -1
  74. package/src/pr/finding-state-record.ts +58 -0
  75. package/src/pr/gate-record.ts +22 -0
  76. package/src/pr/inline.ts +3 -0
  77. package/src/pr/plan.ts +20 -4
  78. package/src/pr/posting.ts +4 -0
  79. package/src/pr/pr-status.ts +27 -7
  80. package/src/pr/pr.ts +39 -8
  81. package/src/pr/preflight.ts +44 -2
  82. package/src/pr/publish-outcome.ts +11 -3
  83. package/src/pr/review-pr.ts +20 -4
  84. package/src/pr/target.ts +12 -3
  85. package/src/production-runtime.ts +760 -331
  86. package/src/rereview/classify.ts +4 -0
  87. package/src/rereview/prepare.ts +47 -22
  88. package/src/rereview/state.ts +34 -8
  89. package/src/review/pipeline.ts +277 -101
  90. package/src/review/preflight.ts +201 -294
  91. package/src/review/report.ts +60 -40
  92. package/src/review/review.ts +20 -3
  93. package/src/review/route-preflight.ts +79 -11
  94. package/src/review/run.ts +28 -6
  95. package/src/review/scout.ts +1 -1
  96. package/src/review/spec.ts +3 -3
  97. package/src/review/step-runner.ts +70 -1
  98. package/src/runner-authority.ts +127 -9
  99. package/src/security/binding-policy.ts +1 -2
  100. package/src/security/claude-credential.ts +355 -0
  101. package/src/security/credential-broker.ts +56 -40
  102. package/src/security/evidence-redaction.ts +179 -4
  103. package/src/security/opencode-secret-manifest.ts +114 -0
  104. package/src/security/published-text.ts +161 -0
  105. package/src/security/redact.ts +45 -0
  106. package/src/system-tools.ts +48 -21
  107. package/src/transport-registry.ts +12 -2
  108. package/src/transports/claude-code-cli.ts +21 -2
  109. package/src/transports/opencode-sdk.ts +11 -9
  110. package/src/transports/opencode-server.ts +7 -10
  111. package/src/triage/triage.ts +2 -1
  112. package/src/ui/config-edit.ts +9 -20
  113. package/src/ui/config.ts +32 -27
  114. package/src/ui/plan.ts +76 -47
  115. package/src/updater.ts +10 -7
  116. package/prompts/default/deep-review-lifecycle.md +0 -362
@@ -0,0 +1,355 @@
1
+ // Which Claude credential a run uses (odd/tasks/role-model-routing.md, S5, S8, L6 items 2-3, L12 "E-e").
2
+ //
3
+ // Before S5 nobody chose: the Claude CLI prefers a per-token key to the subscription
4
+ // token, so a non-empty ANTHROPIC_API_KEY silently won over CLAUDE_CODE_OAUTH_TOKEN and
5
+ // the review billed per token. Now `credentials.claude` names the order (default
6
+ // `["subscription", "api_key"]`), the run uses the FIRST listed credential that is
7
+ // present, decided once at run start and never switched mid-run, and the child sees
8
+ // exactly that one credential under the CLI's own variable name.
9
+ //
10
+ // Three halves, kept apart so the decision is pure and testable:
11
+ // * claudeCredentialPresence: which credentials exist, and where each came from.
12
+ // * selectClaudeCredential: the order applied to that presence. Pure.
13
+ // * claudeRunEnv: the run's environment with every Claude credential variable
14
+ // removed and only the chosen one put back. Every reader downstream (the binding's
15
+ // credential kind, the CI ceiling, the usage record's billing mode, the failure's
16
+ // credential) reads this env, so they all follow the choice without a second copy
17
+ // of it.
18
+ //
19
+ // WHY the env is rebuilt rather than `process.env` edited: Bun.spawn without an
20
+ // explicit `env` hands the child the environment the process STARTED with, so a
21
+ // `delete process.env.X` never reaches it (L14 (a)). The run env is passed explicitly
22
+ // to the runner authority and as the harness's `childEnv`.
23
+
24
+ import { existsSync } from "node:fs";
25
+ import { homedir } from "node:os";
26
+ import path from "node:path";
27
+ import type { CliErrorClass, ErrorParams } from "#ci/outcome";
28
+ import {
29
+ claudeCredentialProjectionReady,
30
+ defaultKeychainCredentialPresent,
31
+ } from "#model/provider-capabilities";
32
+ import type {
33
+ ClaudeCredentialKind,
34
+ CredentialsConfig,
35
+ } from "#review/preflight";
36
+ import { CliError } from "../errors";
37
+
38
+ export const DEFAULT_CLAUDE_CREDENTIAL_ORDER: readonly ClaudeCredentialKind[] =
39
+ ["subscription", "api_key"];
40
+
41
+ // Where each credential may come from in the environment, the CRYSK_* secret first
42
+ // (S8). The old names are the Claude CLI's own variables, which a local run exports;
43
+ // in CI the action reads only the crysk-secrets input (the intake below, U5).
44
+ const ENV_SOURCES = {
45
+ subscription: ["CRYSK_CLAUDE_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"],
46
+ api_key: ["CRYSK_CLAUDE_API_KEY", "ANTHROPIC_API_KEY"],
47
+ } as const satisfies Record<ClaudeCredentialKind, readonly string[]>;
48
+
49
+ type EnvSource = (typeof ENV_SOURCES)[ClaudeCredentialKind][number];
50
+
51
+ // "login" is a subscription the machine already holds outside the environment: the
52
+ // macOS Keychain item the credential broker projects, or the CLI's OAuth store
53
+ // `~/.claude/.credentials.json`.
54
+ export type ClaudeCredentialSource = EnvSource | "login";
55
+
56
+ // The variable the Claude CLI reads for each kind. The child gets exactly one.
57
+ export const CLAUDE_CHILD_VARIABLE = {
58
+ subscription: "CLAUDE_CODE_OAUTH_TOKEN",
59
+ api_key: "ANTHROPIC_API_KEY",
60
+ } as const satisfies Record<ClaudeCredentialKind, string>;
61
+
62
+ // Every variable that can carry a Claude credential. All of them leave the run env.
63
+ // ANTHROPIC_AUTH_TOKEN is one too (a bearer token the CLI also bills per token), but no
64
+ // `credentials.claude` kind names it, so it is removed and never chosen.
65
+ export const CLAUDE_CREDENTIAL_VARIABLES = [
66
+ "CRYSK_CLAUDE_OAUTH_TOKEN",
67
+ "CRYSK_CLAUDE_API_KEY",
68
+ "CLAUDE_CODE_OAUTH_TOKEN",
69
+ "ANTHROPIC_API_KEY",
70
+ "ANTHROPIC_AUTH_TOKEN",
71
+ ] as const;
72
+
73
+ export interface ClaudeCredentialPresence {
74
+ readonly subscription?: ClaudeCredentialSource;
75
+ readonly api_key?: ClaudeCredentialSource;
76
+ // Set when ANTHROPIC_AUTH_TOKEN holds a value: it is stripped, and a refusal says so.
77
+ readonly authTokenIgnored?: true;
78
+ // Set when the env came from the crysk-secrets intake (the action, U5): the only
79
+ // sources were the CRYSK_* secrets in that input, so a refusal names those.
80
+ readonly fromCryskSecrets?: true;
81
+ }
82
+
83
+ export type ClaudeCredentialSelection =
84
+ | {
85
+ readonly status: "chosen";
86
+ readonly kind: ClaudeCredentialKind;
87
+ readonly source: ClaudeCredentialSource;
88
+ readonly order: readonly ClaudeCredentialKind[];
89
+ readonly orderDefaulted: boolean;
90
+ }
91
+ | {
92
+ readonly status: "none";
93
+ readonly order: readonly ClaudeCredentialKind[];
94
+ readonly orderDefaulted: boolean;
95
+ readonly presence: ClaudeCredentialPresence;
96
+ };
97
+
98
+ function hasValue(value: string | undefined): value is string {
99
+ return value !== undefined && value.trim() !== "";
100
+ }
101
+
102
+ // Which credentials exist. The trim matches envBillsMetered: a whitespace-only value is
103
+ // no credential (GitHub renders an unset input as "", and a stray space must not count).
104
+ export function claudeCredentialPresence(
105
+ env: Readonly<Record<string, string | undefined>>,
106
+ loginPresent: boolean,
107
+ ): ClaudeCredentialPresence {
108
+ const found = (kind: ClaudeCredentialKind): EnvSource | undefined =>
109
+ ENV_SOURCES[kind].find((name) => hasValue(env[name]));
110
+ const subscription =
111
+ found("subscription") ?? (loginPresent ? "login" : undefined);
112
+ const apiKey = found("api_key");
113
+ return {
114
+ ...(subscription === undefined ? {} : { subscription }),
115
+ ...(apiKey === undefined ? {} : { api_key: apiKey }),
116
+ ...(hasValue(env.ANTHROPIC_AUTH_TOKEN)
117
+ ? { authTokenIgnored: true as const }
118
+ : {}),
119
+ };
120
+ }
121
+
122
+ // The first listed credential that is present. A present credential that the order
123
+ // does not list is never used: listing is consent to pay with it.
124
+ export function selectClaudeCredential(
125
+ order: readonly ClaudeCredentialKind[] | undefined,
126
+ presence: ClaudeCredentialPresence,
127
+ ): ClaudeCredentialSelection {
128
+ const effective = order ?? DEFAULT_CLAUDE_CREDENTIAL_ORDER;
129
+ const orderDefaulted = order === undefined;
130
+ for (const kind of effective) {
131
+ const source = presence[kind];
132
+ if (source !== undefined) {
133
+ return {
134
+ status: "chosen",
135
+ kind,
136
+ source,
137
+ order: effective,
138
+ orderDefaulted,
139
+ };
140
+ }
141
+ }
142
+ return { status: "none", order: effective, orderDefaulted, presence };
143
+ }
144
+
145
+ function describeSources(
146
+ kind: ClaudeCredentialKind,
147
+ fromCryskSecrets: boolean,
148
+ ): string {
149
+ const names = fromCryskSecrets
150
+ ? `${ENV_SOURCES[kind][0]} in the crysk-secrets input`
151
+ : ENV_SOURCES[kind].join(" or ");
152
+ return kind === "subscription"
153
+ ? `${names}, or a Claude login on this machine`
154
+ : names;
155
+ }
156
+
157
+ // A run refused at admission because a route has no credential it may use. It stops
158
+ // before any binding or provider call (the OpenCode refusal follows only the free
159
+ // model probe, which spends no tokens), so it spent nothing: a CI run settles its
160
+ // admission row as an unspent gate skip, with `ledgerReason`
161
+ // (settleClaudeCredentialRefusal, pr/admission.ts). It names its record class and params,
162
+ // so cli.json carries the code and the route's fixes (classifyCliError,
163
+ // cliErrorParams in ci/classify-error.ts). The CLI still prints it as the one line it
164
+ // prints any CliError.
165
+ export class CredentialRefusalError extends CliError {
166
+ readonly params: ErrorParams;
167
+ readonly ledgerReason: string;
168
+
169
+ constructor(
170
+ message: string,
171
+ cls: CliErrorClass,
172
+ params: ErrorParams,
173
+ ledgerReason: string,
174
+ ) {
175
+ super(message, { cls });
176
+ this.params = params;
177
+ this.ledgerReason = ledgerReason;
178
+ }
179
+ }
180
+
181
+ // The Claude refusal (claudeCredentialRefusal below): no listed Claude credential
182
+ // reached the run, which is CRYSK-CRED-MISSING, the code the trigger records for a run
183
+ // with no credential at all.
184
+ export class ClaudeCredentialRefusalError extends CredentialRefusalError {
185
+ constructor(message: string) {
186
+ super(
187
+ message,
188
+ { kind: "trigger", check: "no-credential" },
189
+ { backend: "claude" },
190
+ "no Claude credential the run may use is set; refused before any provider spend",
191
+ );
192
+ }
193
+ }
194
+
195
+ // The admission refusal for a plan that has a Claude route and no listed credential
196
+ // present, or undefined when the run can go ahead. A plan with no Claude route ignores
197
+ // Claude credentials, so it is never refused here. The message names the order and what
198
+ // is set, never a value.
199
+ export function claudeCredentialRefusal(
200
+ selection: ClaudeCredentialSelection,
201
+ planHasClaudeRoute: boolean,
202
+ ): string | undefined {
203
+ if (selection.status === "chosen" || !planHasClaudeRoute) return undefined;
204
+ const order = `credentials.claude is [${selection.order.join(", ")}]${selection.orderDefaulted ? " (the default)" : ""}`;
205
+ const missing = selection.order
206
+ .map(
207
+ (kind) =>
208
+ `${kind} (${describeSources(kind, selection.presence.fromCryskSecrets === true)})`,
209
+ )
210
+ .join("; ");
211
+ const unlisted = (["subscription", "api_key"] as const).filter(
212
+ (kind) =>
213
+ !selection.order.includes(kind) && selection.presence[kind] !== undefined,
214
+ );
215
+ const parts = [
216
+ `no Claude credential this run may use is set: ${order}, and none of those is set: ${missing}`,
217
+ ];
218
+ if (unlisted.length > 0) {
219
+ parts.push(
220
+ `${unlisted.join(" and ")} ${unlisted.length === 1 ? "is" : "are"} set but not listed, so ${unlisted.length === 1 ? "it is" : "they are"} not used`,
221
+ );
222
+ }
223
+ if (selection.presence.authTokenIgnored) {
224
+ parts.push(
225
+ "ANTHROPIC_AUTH_TOKEN is set but no longer used: put an API key in CRYSK_CLAUDE_API_KEY or ANTHROPIC_API_KEY",
226
+ );
227
+ }
228
+ parts.push(
229
+ "Set a listed credential, or change credentials.claude in your person config",
230
+ );
231
+ return parts.join(". ");
232
+ }
233
+
234
+ // The run's environment: every Claude credential variable removed, then only the
235
+ // chosen credential put back under the CLI's own name. A subscription that comes from
236
+ // the machine's login puts nothing back: the broker projects it, or the CLI reads its
237
+ // own store. With no credential chosen, every Claude credential is gone.
238
+ export function claudeRunEnv(
239
+ env: Readonly<Record<string, string | undefined>>,
240
+ selection: ClaudeCredentialSelection,
241
+ ): Record<string, string | undefined> {
242
+ const run: Record<string, string | undefined> = { ...env };
243
+ for (const name of CLAUDE_CREDENTIAL_VARIABLES) delete run[name];
244
+ if (selection.status === "chosen" && selection.source !== "login") {
245
+ run[CLAUDE_CHILD_VARIABLE[selection.kind]] = env[selection.source];
246
+ }
247
+ return run;
248
+ }
249
+
250
+ // U5: the Claude values the Run Crysk step took from the crysk-secrets input
251
+ // (src/ci/run.ts, which reads the input on stdin), keyed by kind. Undefined until
252
+ // run.ts takes them, which only the action does; a local run never sets it.
253
+ let cryskClaudeIntake:
254
+ | { readonly subscription?: string; readonly api_key?: string }
255
+ | undefined;
256
+
257
+ // Called once by src/ci/run.ts, before the CLI starts, with the parsed input's
258
+ // Claude secrets (parseCryskSecrets's `secrets.claude`). Nothing is written to
259
+ // process.env: Bun hands a child the environment it started with, and readers of
260
+ // the startup env (the transport's billingMode getter, a `{...process.env}` copy)
261
+ // would see a value assigned there. resolveRunClaudeCredential reads the intake.
262
+ export function takeCryskClaudeSecrets(claude: {
263
+ readonly subscription?: string;
264
+ readonly api_key?: string;
265
+ }): void {
266
+ cryskClaudeIntake = { ...claude };
267
+ }
268
+
269
+ // For tests: forget the intake, so a later test reads the process env again.
270
+ export function clearCryskClaudeIntake(): void {
271
+ cryskClaudeIntake = undefined;
272
+ }
273
+
274
+ // The env a CI run reads its Claude credential from: every Claude variable of the
275
+ // process env removed (a job-level ANTHROPIC_API_KEY nobody passed through the
276
+ // crysk-secrets input must not be chosen), then the intake's values under their
277
+ // CRYSK_* names. Pure; the run env (claudeRunEnv) is built from it as from any env.
278
+ export function cryskIntakeEnv(
279
+ env: Readonly<Record<string, string | undefined>>,
280
+ claude: { readonly subscription?: string; readonly api_key?: string },
281
+ ): Record<string, string | undefined> {
282
+ const out: Record<string, string | undefined> = { ...env };
283
+ for (const name of CLAUDE_CREDENTIAL_VARIABLES) delete out[name];
284
+ for (const kind of ["subscription", "api_key"] as const) {
285
+ const value = claude[kind];
286
+ if (value !== undefined) out[ENV_SOURCES[kind][0]] = value;
287
+ }
288
+ return out;
289
+ }
290
+
291
+ export interface RunClaudeCredential {
292
+ readonly selection: ClaudeCredentialSelection;
293
+ // The environment every runner, binding and gate of this run reads.
294
+ readonly env: Record<string, string | undefined>;
295
+ // The chosen kind, for the runner authority (an API key attaches no Keychain broker).
296
+ readonly kind?: ClaudeCredentialKind;
297
+ }
298
+
299
+ // The probes behind defaultClaudeLoginPresent. Tests inject all three, so no test
300
+ // reads the real Keychain or HOME.
301
+ export interface ClaudeLoginProbe {
302
+ readonly platform?: NodeJS.Platform;
303
+ readonly existsFn?: (p: string) => boolean;
304
+ readonly keychainProbe?: () => boolean;
305
+ }
306
+
307
+ // The machine's own Claude login: a Keychain item the broker can project (macOS), or
308
+ // the CLI's OAuth store. `~/.claude.json` does not count: every Claude user has it,
309
+ // API-key users included, and counting it would strip their key.
310
+ // WHY the item and not only the broker (R001, #494): `security` is on every Mac, so
311
+ // counting the broker alone chose the login on a Mac that has only an API key; the
312
+ // key was stripped, the projection found no item (`source_read_failed`) and every
313
+ // step failed. The item check is metadata-only (no `-w`, no secret read).
314
+ export function defaultClaudeLoginPresent(
315
+ env: Readonly<Record<string, string | undefined>> = process.env,
316
+ probe: ClaudeLoginProbe = {},
317
+ ): boolean {
318
+ const exists = probe.existsFn ?? existsSync;
319
+ const home = hasValue(env.HOME) ? env.HOME : homedir();
320
+ if (exists(path.join(home, ".claude", ".credentials.json"))) return true;
321
+ return (
322
+ claudeCredentialProjectionReady({
323
+ ...(probe.platform === undefined ? {} : { platform: probe.platform }),
324
+ existsFn: exists,
325
+ }) && (probe.keychainProbe ?? defaultKeychainCredentialPresent)()
326
+ );
327
+ }
328
+
329
+ // Called once at run start, before any plan is admitted. With no env given it reads
330
+ // the process env, or, in the action, the crysk-secrets intake over it (U5).
331
+ export function resolveRunClaudeCredential(input: {
332
+ readonly credentials?: CredentialsConfig;
333
+ readonly env?: Readonly<Record<string, string | undefined>>;
334
+ readonly loginPresent?: boolean;
335
+ }): RunClaudeCredential {
336
+ const fromIntake = input.env === undefined && cryskClaudeIntake !== undefined;
337
+ const env =
338
+ input.env ??
339
+ (cryskClaudeIntake === undefined
340
+ ? process.env
341
+ : cryskIntakeEnv(process.env, cryskClaudeIntake));
342
+ const found = claudeCredentialPresence(
343
+ env,
344
+ input.loginPresent ?? defaultClaudeLoginPresent(env),
345
+ );
346
+ const presence: ClaudeCredentialPresence = fromIntake
347
+ ? { ...found, fromCryskSecrets: true }
348
+ : found;
349
+ const selection = selectClaudeCredential(input.credentials?.claude, presence);
350
+ return {
351
+ selection,
352
+ env: claudeRunEnv(env, selection),
353
+ ...(selection.status === "chosen" ? { kind: selection.kind } : {}),
354
+ };
355
+ }
@@ -386,51 +386,66 @@ export class OpenCodeAuthBroker implements CredentialBroker {
386
386
  );
387
387
  }
388
388
 
389
- let raw: string;
390
- try {
391
- raw = await this.readerFn();
392
- } catch {
393
- throw new CredentialProjectionError("source_read_failed");
394
- }
395
-
396
- let parsed: unknown;
397
- try {
398
- parsed = JSON.parse(raw);
399
- } catch {
400
- throw new CredentialProjectionError("malformed_payload");
401
- }
402
-
403
- if (typeof parsed !== "object" || parsed === null) {
404
- throw new CredentialProjectionError("malformed_payload");
405
- }
406
-
407
- const record = (parsed as Record<string, unknown>).openai;
408
- if (typeof record !== "object" || record === null) {
409
- throw new CredentialProjectionError("missing_subscription_record");
410
- }
411
- // This kind promises ChatGPT OAuth specifically. An `openai` entry holding
412
- // a pay-as-you-go API key is a different credential on different billing,
413
- // and projecting it here would make the capability report's
414
- // `billing.mode: "subscription"` a lie rather than a claim.
415
- //
416
- // #133 note: this lock is also what makes credentialKindForRoute's
417
- // provider-keyed decision safe. That function does NOT read the store, so
418
- // an `openai` entry holding an API key still resolves to this OAuth kind —
419
- // and lands here, refused, rather than being silently routed metered. A
420
- // bounded, stated limit, not a bug: the failure is loud and the fix is to
421
- // name that provider differently in the routing config.
422
- if ((record as Record<string, unknown>).type !== "oauth") {
423
- throw new CredentialProjectionError("missing_subscription_record");
389
+ const lookup = await lookupOpenCodeOAuthRecord(this.readerFn);
390
+ if (!lookup.ok) {
391
+ throw new CredentialProjectionError(lookup.failureClass);
424
392
  }
425
393
 
426
394
  return buildOpenCodeProjection(
427
395
  input.kind,
428
396
  OPENCODE_OAUTH_PROVIDER,
429
- record as OpenCodeProviderRecord,
397
+ lookup.record,
430
398
  );
431
399
  }
432
400
  }
433
401
 
402
+ // The read+parse+validate sequence for the `openai` ChatGPT OAuth record, the
403
+ // OAuth broker's own (above) and admission's credential check
404
+ // (openCodeCredentialRefusal, production-runtime.ts). One copy, so admission
405
+ // asks exactly what the broker will ask when the route runs.
406
+ export async function lookupOpenCodeOAuthRecord(
407
+ readerFn: () => Promise<string>,
408
+ ): Promise<OpenCodeRecordLookup> {
409
+ let raw: string;
410
+ try {
411
+ raw = await readerFn();
412
+ } catch {
413
+ return { ok: false, failureClass: "source_read_failed" };
414
+ }
415
+
416
+ let parsed: unknown;
417
+ try {
418
+ parsed = JSON.parse(raw);
419
+ } catch {
420
+ return { ok: false, failureClass: "malformed_payload" };
421
+ }
422
+
423
+ if (typeof parsed !== "object" || parsed === null) {
424
+ return { ok: false, failureClass: "malformed_payload" };
425
+ }
426
+
427
+ const record = (parsed as Record<string, unknown>).openai;
428
+ if (typeof record !== "object" || record === null) {
429
+ return { ok: false, failureClass: "missing_subscription_record" };
430
+ }
431
+ // This kind promises ChatGPT OAuth specifically. An `openai` entry holding
432
+ // a pay-as-you-go API key is a different credential on different billing,
433
+ // and projecting it here would make the capability report's
434
+ // `billing.mode: "subscription"` a lie rather than a claim.
435
+ //
436
+ // #133 note: this lock is also what makes credentialKindForRoute's
437
+ // provider-keyed decision safe. That function does NOT read the store, so
438
+ // an `openai` entry holding an API key still resolves to this OAuth kind —
439
+ // and lands here, refused, rather than being silently routed metered. A
440
+ // bounded, stated limit, not a bug: the failure is loud and the fix is to
441
+ // name that provider differently in the model name (`opencode:<provider>/...`).
442
+ if ((record as Record<string, unknown>).type !== "oauth") {
443
+ return { ok: false, failureClass: "missing_subscription_record" };
444
+ }
445
+
446
+ return { ok: true, record: record as OpenCodeProviderRecord };
447
+ }
448
+
434
449
  // ONE builder for both OpenCode brokers. A third copy of the create+lstat+hash
435
450
  // sequence is exactly the drift `openCodeProjectionLayout` already exists to
436
451
  // prevent (pr-hero F001 on PR #80: two hand-maintained path lists, three
@@ -526,7 +541,7 @@ function buildOpenCodeProjection(
526
541
  // traversal, a prototype key, or anything requiring escaping.
527
542
  const OPENCODE_PROVIDER_NAME = /^[a-z0-9][a-z0-9_-]*$/;
528
543
 
529
- type OpenCodeApiRecordLookup =
544
+ export type OpenCodeRecordLookup =
530
545
  | { readonly ok: true; readonly record: OpenCodeProviderRecord }
531
546
  | {
532
547
  readonly ok: false;
@@ -541,11 +556,12 @@ type OpenCodeApiRecordLookup =
541
556
  // hash sequence: a third hand-maintained copy is exactly the drift that
542
557
  // comment warns about, and here it would additionally let the two callers'
543
558
  // validation silently diverge (e.g. one broker accepting a record shape the
544
- // other refuses).
545
- async function lookupOpenCodeApiRecord(
559
+ // other refuses). Admission's credential check (openCodeCredentialRefusal,
560
+ // production-runtime.ts) is the third caller, for the same reason.
561
+ export async function lookupOpenCodeApiRecord(
546
562
  readerFn: () => Promise<string>,
547
563
  provider: string,
548
- ): Promise<OpenCodeApiRecordLookup> {
564
+ ): Promise<OpenCodeRecordLookup> {
549
565
  let raw: string;
550
566
  try {
551
567
  raw = await readerFn();
@@ -1,8 +1,184 @@
1
1
  const MAX_BYTES = 4 * 1024 * 1024;
2
+ const REDACTED = "[REDACTED]";
2
3
  const SECRET =
3
4
  /authorization|cookie|password|secret|api.?key|access.?token|refresh.?token|^token$|^key$/i;
4
- export function redactEvidenceText(value: string): string {
5
+
6
+ // The words of an identifier, lower-cased. camelCase, snake_case, kebab-case
7
+ // and dotted names split the same way: `AWS_SECRET_ACCESS_KEY` and
8
+ // `awsSecretAccessKey` both give aws, secret, access, key.
9
+ export function nameParts(name: string): string[] {
10
+ return name
11
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
12
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
13
+ .toLowerCase()
14
+ .split(/[^a-z0-9]+/)
15
+ .filter((part) => part.length > 0);
16
+ }
17
+
18
+ const SECRET_WORDS = new Set([
19
+ "secret",
20
+ "secrets",
21
+ "password",
22
+ "passwords",
23
+ "passwd",
24
+ "passphrase",
25
+ "apikey",
26
+ "apitoken",
27
+ "accesskey",
28
+ "accesstoken",
29
+ "authtoken",
30
+ "privatekey",
31
+ "secretkey",
32
+ "clientsecret",
33
+ "refreshtoken",
34
+ ]);
35
+ const KEY_QUALIFIERS = new Set([
36
+ "api",
37
+ "access",
38
+ "private",
39
+ "secret",
40
+ "client",
41
+ "signing",
42
+ "encryption",
43
+ "master",
44
+ "session",
45
+ ]);
46
+
47
+ // Whether a name says its value is a credential: it holds a secret or password
48
+ // word anywhere, or it ends in `token` or in a qualified `key` (api, access,
49
+ // private...). Counts and descriptors survive: `max_tokens`, `token_type`,
50
+ // `tokenCount` and `apiKeySource` are not credentials.
51
+ export function isSecretName(name: string): boolean {
52
+ const parts = nameParts(name);
53
+ const last = parts.at(-1);
54
+ if (last === undefined) return false;
55
+ if (parts.some((part) => SECRET_WORDS.has(part))) return true;
56
+ if (last === "token") return true;
57
+ const qualifier = parts.at(-2);
58
+ return (
59
+ last === "key" && qualifier !== undefined && KEY_QUALIFIERS.has(qualifier)
60
+ );
61
+ }
62
+
63
+ // Values that cannot be a credential, whatever name they are assigned to: a
64
+ // GitHub Actions expression, a permission or `secrets:` word, a YAML block
65
+ // scalar indicator, a placeholder, an environment reference, a boolean, or a
66
+ // small number. A workflow file a hunter reads is full of them
67
+ // (`id-token: write`, `API_KEY=${{ secrets.API_KEY }}`). The whole value must
68
+ // match, so `write-abc123` or `xxxabc123` is still a value to hide. A number
69
+ // stays hidden under a password name, and past five digits under any name,
70
+ // since a PIN or a numeric key is a secret.
71
+ const NON_SECRET_VALUES: readonly RegExp[] = [
72
+ /^\$\{\{(?:(?!\}\})[^\r\n])*\}\}$/,
73
+ /^(?:read|write|none|read-all|write-all|inherit)$/,
74
+ /^[|>][+-]?[1-9]?$/,
75
+ /^<[^<>\r\n]*>$/,
76
+ /^(?:x{3,}|X{3,}|\*{3,}|changeme|\[REDACTED\])$/,
77
+ /^\$[A-Z_][A-Z0-9_]*$/,
78
+ /^\$\{[A-Z_][A-Z0-9_]*\}$/,
79
+ /^(?:process\.env|Bun\.env|import\.meta\.env)\.[A-Za-z_]\w*$/,
80
+ /^(?:true|false)$/i,
81
+ ];
82
+ const PASSWORD_WORDS = new Set(["password", "passwd", "passphrase", "pin"]);
83
+
84
+ export function isNonSecretValue(value: string, name = ""): boolean {
85
+ const bare = value.replace(/^\\*(["'])(.*)\\*\1$/, "$2");
86
+ if (bare === "" || NON_SECRET_VALUES.some((shape) => shape.test(bare))) {
87
+ return true;
88
+ }
89
+ return (
90
+ /^\d{1,5}$/.test(bare) &&
91
+ !nameParts(name).some((part) => PASSWORD_WORDS.has(part))
92
+ );
93
+ }
94
+
95
+ // A GitHub Actions expression is one value even though it holds spaces, so
96
+ // `token: ${{ github.token }}` is read whole and kept, not cut at `${{`.
97
+ // Its body never holds another `${{` and is at most 512 characters, so a line
98
+ // of unclosed `token=${{ ` is scanned once, not to its end from every start.
99
+ export const EXPRESSION_VALUE = String.raw`\$\{\{(?:[^$}\r\n]|\$(?!\{\{)|\}(?!\})){0,512}\}\}(?=[\s,;&"'\\]|$)`;
100
+ // A YAML `:` value may sit below its key, past up to three blank or comment
101
+ // lines, unless that line is a key of its own: a `secrets:` section's first
102
+ // entry is not its value, and a comment is never one. The key must end its
103
+ // line, so each line is crossed from at most the three keys above it.
104
+ const YAML_VALUE_BELOW = String.raw`:(?:[ \t]*\r?\n(?:[ \t]*(?:#[^\r\n]*)?\r?\n){0,3}(?![ \t]*[\w.-]+[ \t]*:(?:\s|$))[ \t]*(?!#)|[ \t]*)`;
105
+
106
+ // Every pattern below stops at quotes and backslashes, so it can run on JSON
107
+ // text without breaking the parse that follows. Each one starts only where a
108
+ // run begins (lookbehind, not \b), so a long run of word characters is
109
+ // scanned once, not once per character.
110
+ // A block cut before its END line runs to the last base64 character. The run
111
+ // also takes the gutter of a line-numbered Read (` 2→` or ` 2\t`,
112
+ // raw or JSON-escaped): digits and whitespace are already base64 run
113
+ // characters, so only the arrow and the escaped tab are added.
114
+ const PEM_PRIVATE_KEY =
115
+ /-----BEGIN[A-Z0-9 ]*PRIVATE KEY[A-Z ]*-----(?:[\s\S]*?-----END[A-Z0-9 ]*PRIVATE KEY[A-Z ]*-----|(?:[A-Za-z0-9+/=\s\u2192]|\\[nrt])*)/g;
116
+ // `scheme://user:password@`, for every scheme: postgres, mysql, mongodb+srv,
117
+ // redis, amqp. The user goes too, since it is often a key id.
118
+ const URL_CREDENTIALS =
119
+ /(?<![a-z0-9+.-])([a-z][a-z0-9+.-]*:\/\/)[^\s/@:'"<>\\]*:[^\s/@'"<>\\]+@/gi;
120
+ const AWS_ACCESS_KEY_ID = /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g;
121
+ const STRIPE_KEY = /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{10,}/g;
122
+ const JWT =
123
+ /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{4,}\.eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*/g;
124
+ // `"name": "value"`, `name = 'value'` and `{\"name\":\"value\"}`: the value
125
+ // is quoted, so code such as `token_count = usage.total` keeps reading.
126
+ const QUOTED_ASSIGNMENT =
127
+ /(?<![\w.-])([\w.-]+)(\\*["']?\s*[=:]\s*\\*["'])([^"'\\\r\n]+)/g;
128
+ // `NAME=value` and `name: value` in env, ini and YAML files, for UPPER_SNAKE,
129
+ // snake_case and kebab-case names. camelCase is left to the quoted form unless
130
+ // the caller asks for it, so `privateKey = loadKey()` in a code window reads as
131
+ // before; the session copy asks, since a YAML file spells `privateKey: abc`.
132
+ // An `=` value stays on its line, so an empty `TOKEN=` never takes the next
133
+ // variable. A `:` value may sit below its key (YAML_VALUE_BELOW).
134
+ const UNQUOTED_ASSIGNMENT = new RegExp(
135
+ String.raw`(?<![\w.-])([A-Za-z][\w-]*)([ \t]*(?:=[ \t]*|${YAML_VALUE_BELOW}))(${EXPRESSION_VALUE}|[^\s,;&"'\\]+)`,
136
+ "g",
137
+ );
138
+
139
+ /**
140
+ * The credential shapes that need no surrounding context, plus assignments to
141
+ * a name `isSecret` accepts. Safe on JSON text: it never removes a quote.
142
+ */
143
+ export function redactSecretShapes(
144
+ value: string,
145
+ isSecret: (name: string) => boolean = isSecretName,
146
+ unquotedCamelCase = false,
147
+ ): string {
5
148
  return value
149
+ .replace(PEM_PRIVATE_KEY, REDACTED)
150
+ .replace(URL_CREDENTIALS, `$1${REDACTED}@`)
151
+ .replace(AWS_ACCESS_KEY_ID, REDACTED)
152
+ .replace(STRIPE_KEY, REDACTED)
153
+ .replace(JWT, REDACTED)
154
+ .replace(
155
+ QUOTED_ASSIGNMENT,
156
+ (match, name: string, separator: string, value: string) =>
157
+ isSecret(name) && !isNonSecretValue(value, name)
158
+ ? `${name}${separator}${REDACTED}`
159
+ : match,
160
+ )
161
+ .replace(
162
+ UNQUOTED_ASSIGNMENT,
163
+ (match, name: string, separator: string, value: string) =>
164
+ (unquotedCamelCase || !/[a-z][A-Z]/.test(name)) &&
165
+ isSecret(name) &&
166
+ !isNonSecretValue(value, name)
167
+ ? `${name}${separator}${REDACTED}`
168
+ : match,
169
+ );
170
+ }
171
+
172
+ // A credential keyword, its separator, and the value: on the same line after
173
+ // `=`, and after `:` also below the key (YAML_VALUE_BELOW), so a camelCase
174
+ // `apiKey:` the unquoted rule leaves alone still loses a value on a later line.
175
+ const LEGACY_KEYWORD_VALUE = new RegExp(
176
+ String.raw`((?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|secret)[ \t]*(?:=[ \t]*|${YAML_VALUE_BELOW}))(${EXPRESSION_VALUE}|[^\s,;&]+)`,
177
+ "gi",
178
+ );
179
+
180
+ export function redactEvidenceText(value: string): string {
181
+ return redactSecretShapes(value)
6
182
  .replace(
7
183
  /\b(?:authorization|proxy-authorization|cookie|set-cookie)\s*:[^\r\n]*/gi,
8
184
  "[REDACTED HEADER]",
@@ -23,9 +199,8 @@ export function redactEvidenceText(value: string): string {
23
199
  /\b(?:sk-[\w-]+|gh[pousr]_[\w]+|github_pat_[\w]+|Bearer\s+[^\s,;]+)/gi,
24
200
  "[REDACTED]",
25
201
  )
26
- .replace(
27
- /((?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|secret)\s*[=:]\s*)[^\s,;&]+/gi,
28
- "$1[REDACTED]",
202
+ .replace(LEGACY_KEYWORD_VALUE, (match, keyword: string, value: string) =>
203
+ isNonSecretValue(value, keyword) ? match : `${keyword}[REDACTED]`,
29
204
  );
30
205
  }
31
206
  /** JSON-only bounded traversal: never call getters, custom iterators or toJSON. */