crysk 0.5.0 → 0.6.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.
- package/README.md +2 -1
- package/package.json +3 -2
- package/skills/crysk-ci-setup/assets/workflow.yml +3 -0
- package/src/asset-manifest.ts +11 -0
- package/src/assets.ts +1 -1
- package/src/ci/credential-refresh.ts +524 -0
- package/src/ci/crysk-secrets.ts +20 -6
- package/src/ci/force-comment.ts +14 -1
- package/src/ci/gates.ts +64 -21
- package/src/ci/outcome.ts +165 -15
- package/src/ci/platform-estimate.ts +111 -0
- package/src/ci/platform-trace.ts +30 -0
- package/src/ci/platform.ts +183 -5
- package/src/ci/reporter.ts +14 -4
- package/src/ci/setup.ts +96 -6
- package/src/ci/trace-bundle.ts +231 -27
- package/src/ci/trace-transcripts.ts +65 -0
- package/src/ci/trigger.ts +20 -4
- package/src/commands/ci-setup.ts +12 -3
- package/src/commands/doctor.ts +25 -23
- package/src/diversity/identity.ts +11 -1
- package/src/diversity/pipeline-integration.ts +19 -6
- package/src/doctor.ts +133 -4
- package/src/execution/contracts.ts +15 -3
- package/src/harness/materiality-judge.ts +153 -0
- package/src/harness/pipeline-plan.ts +133 -0
- package/src/harness/replay-rows.ts +172 -0
- package/src/harness/route-runner.ts +288 -0
- package/src/harness/single-step.ts +153 -0
- package/src/index.ts +1 -1
- package/src/model/catalog.ts +10 -7
- package/src/model/model-name.ts +14 -0
- package/src/model/profiles/claude.ts +34 -0
- package/src/model/profiles/openai.ts +44 -0
- package/src/model/profiles.ts +213 -0
- package/src/model/routing.ts +155 -50
- package/src/pr/ci-admission-gate.ts +2 -0
- package/src/pr/discovery.ts +18 -0
- package/src/pr/plan.ts +41 -2
- package/src/pr/review-pr.ts +43 -6
- package/src/pr/target.ts +67 -15
- package/src/production-runtime.ts +100 -13
- package/src/review/pipeline.ts +193 -58
- package/src/review/preflight.ts +91 -9
- package/src/review/prompt-set.ts +68 -0
- package/src/review/report.ts +4 -0
- package/src/review/review.ts +21 -11
- package/src/review/route-preflight.ts +117 -67
- package/src/review/run.ts +50 -4
- package/src/security/credential-broker.ts +21 -9
- package/src/security/oauth-providers.ts +101 -0
- package/src/transport-registry.ts +33 -0
- package/src/transports/opencode-sdk.ts +33 -1
- package/src/ui/config-edit.ts +9 -0
- package/src/ui/config.ts +1 -0
- package/src/ui/menu.ts +9 -2
- package/src/ui/plan.ts +8 -3
- package/src/updater.ts +21 -13
- package/src/wizard.ts +23 -0
package/README.md
CHANGED
|
@@ -289,13 +289,14 @@ never be able to enlarge *your* bill: on the two keys that spend, the team can o
|
|
|
289
289
|
| `suspicion_priors` | **repo only** | `[{path, weight, reason}]` hints injected into hunter prompts — point them at your known hotspots. |
|
|
290
290
|
| `summary.enabled` | both — team may only turn it **off** | Whether the engine-owned summarizer runs. Defaults to `true`, because it spends money and a silent opt-out would make the bill differ from the plan. |
|
|
291
291
|
| `models` | **global only** | The models per role (`default`, `hunter.<key>`, `refuter`, `consolidate`, `scout`, `summary`, `judge`), each a list of one to three tried in order, e.g. `{"summary": ["claude:haiku-latest"]}`. Unset, each step runs the model its prompt declares. See [Models](docs/configuration.md#models). `summary.model` is gone: `"haiku"` still reads, with a warning; anything else is refused. |
|
|
292
|
+
| `profile` | **global only** | The ready-made models for every role: `claude` (the default) or `openai`, e.g. `"profile": "openai"`. `models` still wins role by role. See [Profiles](docs/configuration.md#profiles). |
|
|
292
293
|
| `credentials` | **global only** | Which Claude credential a run uses, in order: `{"claude": ["subscription", "api_key"]}` (the default). See [Credentials](docs/configuration.md#credentials). |
|
|
293
294
|
| `max_verification_steps` | both — team may only **lower** it | Cap on re-review verification spawns (item 7). Defaults to `8`; `0` is legal and pauses verification. |
|
|
294
295
|
| `max_concurrent_steps` | both — team may only **lower** it | Cap on steps (hunters, refuters, verify, scout, summarizer) in flight at once. Unset means unlimited. Set it below a provider's concurrency limit (e.g. `8` for one that allows 10 in-flight requests) so a refuter fan-out does not draw HTTP 429s. |
|
|
295
296
|
| `max_changed_lines` | both — team may only **lower** it | Line budget threshold before the size gate skips a review. Defaults to `4000`; `0` disables line budget check. |
|
|
296
297
|
| `max_changed_files` | both — team may only **lower** it | File count budget threshold before the size gate skips a review. Defaults to `150`; `0` disables file budget check. |
|
|
297
298
|
| `scout` | both — team may only turn it **off** | Whether the reconnaissance scout hunter runs before review. Defaults to `false`. |
|
|
298
|
-
| `materiality_gate` | both — team may only turn it **off** | Defaults to `false`. When `true`, an extra isolated judge checks each blocking finding against Crysk's posting policy; a finding judged not material under normal use is posted as advisory instead of blocking. Findings about security, credentials or data loss are never demoted. Adds one judge call per blocking finding.
|
|
299
|
+
| `materiality_gate` | both — team may only turn it **off** | Defaults to `false`. When `true`, an extra isolated judge checks each blocking finding against Crysk's posting policy; a finding judged not material under normal use is posted as advisory instead of blocking. Findings about security, credentials or data loss are never demoted. Adds one judge call per blocking finding. It runs only on its profile's judge models (Claude sonnet or opus on `claude`, OpenAI Terra on `openai`); on any other route findings stay blocking. Known limitation: on a re-review, a finding that was blocking on an earlier head still counts toward the gate. |
|
|
299
300
|
| `post` | both — team may only turn it **off** | Whether review reports publish as GitHub PR comments by default. Defaults to `false`. |
|
|
300
301
|
| `post_min_severity` | both — the repo file wins either way | The lowest finding a PR review posts: `suggestion` (everything), `warning` (hides advisory suggestions) or `blocking` (hides every advisory finding). A blocking finding always posts. Hidden findings get no comment; the summary counts them in one line. The gate and local reports still see every finding; re-review admission scores only what was posted, so a hidden finding never triggers a re-review. Unset posts everything; `setup --ci` writes the recommended `warning` when the file has no value. |
|
|
301
302
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "crysk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -70,7 +70,8 @@
|
|
|
70
70
|
"check": "biome check src test benchmarks"
|
|
71
71
|
},
|
|
72
72
|
"dependencies": {
|
|
73
|
-
"@opencode-ai/sdk": "1.18.25"
|
|
73
|
+
"@opencode-ai/sdk": "1.18.25",
|
|
74
|
+
"libsodium-wrappers": "0.8.4"
|
|
74
75
|
},
|
|
75
76
|
"devDependencies": {
|
|
76
77
|
"@biomejs/biome": "^2",
|
|
@@ -157,4 +157,7 @@ jobs:
|
|
|
157
157
|
# and the subscription is tried first.
|
|
158
158
|
models: ${{ vars.CRYSK_MODELS }}
|
|
159
159
|
credentials: ${{ vars.CRYSK_CREDENTIALS }}
|
|
160
|
+
# The model profile (claude or openai) from a repository variable.
|
|
161
|
+
# Unset, the claude profile. models still wins role by role.
|
|
162
|
+
profile: ${{ vars.CRYSK_PROFILE }}
|
|
160
163
|
mode: gate
|
package/src/asset-manifest.ts
CHANGED
|
@@ -53,6 +53,17 @@ export const BUNDLED_AGENT_FILES: Record<string, string> = {
|
|
|
53
53
|
"review-refuter.md": refuterPrompt,
|
|
54
54
|
};
|
|
55
55
|
|
|
56
|
+
// Model-profile prompt sets (odd/tasks/model-profiles.md S4): set name ->
|
|
57
|
+
// logical filename -> path, read from `prompts/profiles/<set>/<file>`. A set
|
|
58
|
+
// holds only the files that differ from the default set; every other file
|
|
59
|
+
// falls back to it (profilePromptSet, src/review/prompt-set.ts). Bun embeds
|
|
60
|
+
// only what is imported, so each override needs its own `with { type: "file" }`
|
|
61
|
+
// import above and an entry here; test/assets.test.ts checks this map against
|
|
62
|
+
// the disk. No profile ships a set yet.
|
|
63
|
+
export const PROFILE_PROMPT_FILES: Readonly<
|
|
64
|
+
Record<string, Readonly<Record<string, string>>>
|
|
65
|
+
> = {};
|
|
66
|
+
|
|
56
67
|
export const CONSOLIDATE_PROMPT_PATH = consolidatePrompt;
|
|
57
68
|
export const MATERIALITY_PROMPT_PATH = materialityPrompt;
|
|
58
69
|
export const SCOUT_PROMPT_PATH = scoutPrompt;
|
package/src/assets.ts
CHANGED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
// The action's credential refresh step (cryskai/platform odd/tasks/openai-oauth.md,
|
|
2
|
+
// E3): renews an OpenCode subscription login on the customer's runner, seals the
|
|
3
|
+
// new record with the target's GitHub public key, and hands the platform only
|
|
4
|
+
// the ciphertext, which it writes back as the same CRYSK_OPENCODE_<P>_OAUTH
|
|
5
|
+
// secret.
|
|
6
|
+
//
|
|
7
|
+
// It runs only when the platform dispatched the workflow with
|
|
8
|
+
// `operation: refresh-credential` (action.yml), after the connect step and
|
|
9
|
+
// `bun install`. A review never renews a rotating login (E1): the refresh token
|
|
10
|
+
// rotates on use and a reused one is refused for good, so this step is the one
|
|
11
|
+
// serialized place where the chain moves.
|
|
12
|
+
//
|
|
13
|
+
// The order is the contract with the platform (CREDENTIAL_REFRESH_PATHS):
|
|
14
|
+
// 1. `targets`: the public key of the secret's target. Everything that can fail
|
|
15
|
+
// on the runner (provider, record, key) is checked before step 2, so a
|
|
16
|
+
// failure there spends nothing and the platform may dispatch again.
|
|
17
|
+
// 2. `begin`: the platform records that the stored refresh token is about to
|
|
18
|
+
// be spent. Then ONE POST to the provider's token endpoint, never retried:
|
|
19
|
+
// a request that may have reached the provider may have spent the token.
|
|
20
|
+
// 3. `result`: the sealed record, or `{failure}`. Once the provider answered
|
|
21
|
+
// with new tokens the stored refresh token is spent, so the sealed record
|
|
22
|
+
// is kept in memory and this POST is retried for minutes before giving up.
|
|
23
|
+
//
|
|
24
|
+
// WHY nothing is written: no file, no step output. Every token is masked with
|
|
25
|
+
// `::add-mask::` before anything else is printed, and every message goes through
|
|
26
|
+
// `redact`, so no value reaches the log even when a request fails.
|
|
27
|
+
//
|
|
28
|
+
// The provider's behavior (token URL, client id, permanent errors, account id)
|
|
29
|
+
// is data in src/security/oauth-providers.ts; this script never names a provider.
|
|
30
|
+
|
|
31
|
+
import {
|
|
32
|
+
type OAuthProviderDescriptor,
|
|
33
|
+
oauthProvider,
|
|
34
|
+
} from "../security/oauth-providers";
|
|
35
|
+
import {
|
|
36
|
+
type OpenCodeOAuthRecord,
|
|
37
|
+
opencodeSecretsFor,
|
|
38
|
+
opencodeSecretToken,
|
|
39
|
+
parseCryskSecrets,
|
|
40
|
+
} from "./crysk-secrets";
|
|
41
|
+
import { PLATFORM_API_URL } from "./platform";
|
|
42
|
+
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
// The platform contract. The Crysk platform implements the same three
|
|
45
|
+
// endpoints (docs/github-actions.md, "Subscription logins"). Every request is a
|
|
46
|
+
// JSON POST with `Authorization: Bearer <run token>` (the connect step's) and
|
|
47
|
+
// `X-Crysk-Dispatch-Id: <dispatch id>` (the workflow_dispatch input).
|
|
48
|
+
// ---------------------------------------------------------------------------
|
|
49
|
+
|
|
50
|
+
export const CREDENTIAL_REFRESH_PATHS = {
|
|
51
|
+
targets: "/runs/credential-refresh/targets",
|
|
52
|
+
begin: "/runs/credential-refresh/begin",
|
|
53
|
+
result: "/runs/credential-refresh",
|
|
54
|
+
} as const;
|
|
55
|
+
|
|
56
|
+
// `targets` and `begin` carry only the provider; the platform checks it against
|
|
57
|
+
// the refresh it dispatched.
|
|
58
|
+
export interface CredentialRefreshProviderBody {
|
|
59
|
+
provider: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// `targets` answers the GitHub public key of the secret's target (the
|
|
63
|
+
// organization or the repository), as GitHub's `.../secrets/public-key` does.
|
|
64
|
+
export interface CredentialRefreshTargetsReply {
|
|
65
|
+
key_id: string;
|
|
66
|
+
key: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type CredentialRefreshResultBody =
|
|
70
|
+
| {
|
|
71
|
+
provider: string;
|
|
72
|
+
key_id: string;
|
|
73
|
+
// Standard padded base64 of the libsodium sealed box, as GitHub's
|
|
74
|
+
// "create or update a secret" API takes it. The sealed plaintext is the
|
|
75
|
+
// secret's value: standard base64 of the record's JSON, as
|
|
76
|
+
// CRYSK_OPENCODE_<P>_OAUTH stores it.
|
|
77
|
+
encrypted_value: string;
|
|
78
|
+
// ISO 8601, UTC. When the provider issued the new access token (the
|
|
79
|
+
// runner's clock at its answer) and when the record says it expires.
|
|
80
|
+
issued_at: string;
|
|
81
|
+
expires_at: string;
|
|
82
|
+
// The provider's account id (ChatGPT's account for OpenAI), or null.
|
|
83
|
+
provider_account_id: string | null;
|
|
84
|
+
}
|
|
85
|
+
| {
|
|
86
|
+
provider: string;
|
|
87
|
+
// One of the descriptor's permanent error codes (log in again), or
|
|
88
|
+
// PROVIDER_ERROR_FAILURE.
|
|
89
|
+
failure: string;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// The provider answered with an error that is not one of its permanent codes
|
|
93
|
+
// (a 5xx, a 429, an unknown code, or a 200 without an access token). Whether the
|
|
94
|
+
// stored refresh token survived is unknown; the platform decides what follows.
|
|
95
|
+
export const PROVIDER_ERROR_FAILURE = "provider_error";
|
|
96
|
+
|
|
97
|
+
// The result POST is retried on a transport failure, a 5xx or a 429, with this
|
|
98
|
+
// backoff, for at most RESULT_RETRY_BUDGET_MS. The worst case for the step is
|
|
99
|
+
// that budget plus one request timeout; the platform's lease must outlast it.
|
|
100
|
+
export const RESULT_RETRY_BUDGET_MS = 10 * 60 * 1000;
|
|
101
|
+
const RESULT_RETRY_FIRST_DELAY_MS = 5_000;
|
|
102
|
+
const RESULT_RETRY_MAX_DELAY_MS = 60_000;
|
|
103
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
104
|
+
// OpenCode's own fallback when the token response states no `expires_in`.
|
|
105
|
+
const DEFAULT_EXPIRES_IN_S = 3600;
|
|
106
|
+
// The longest lifetime believed from a provider's answer. OpenAI's tokens live
|
|
107
|
+
// 240 hours; a stated expiry past a year is a malformed answer, and one past what
|
|
108
|
+
// Date can print would throw after the stored refresh token was spent.
|
|
109
|
+
const MAX_EXPIRES_IN_MS = 366 * 24 * 60 * 60 * 1000;
|
|
110
|
+
|
|
111
|
+
export const REFRESH_OPERATION = "refresh-credential";
|
|
112
|
+
|
|
113
|
+
export type Sealer = (value: string) => string;
|
|
114
|
+
|
|
115
|
+
// Loads libsodium and returns a sealer for one GitHub public key, or throws when
|
|
116
|
+
// the key is not a 32-byte X25519 key in standard base64. Loaded lazily, here
|
|
117
|
+
// only, so no other step's import closure gains the package.
|
|
118
|
+
export async function githubSealer(publicKeyBase64: string): Promise<Sealer> {
|
|
119
|
+
const { default: sodium } = await import("libsodium-wrappers");
|
|
120
|
+
await sodium.ready;
|
|
121
|
+
let key: Uint8Array;
|
|
122
|
+
try {
|
|
123
|
+
key = sodium.from_base64(publicKeyBase64, sodium.base64_variants.ORIGINAL);
|
|
124
|
+
} catch {
|
|
125
|
+
throw new Error("the target's public key is not base64");
|
|
126
|
+
}
|
|
127
|
+
if (key.length !== sodium.crypto_box_PUBLICKEYBYTES) {
|
|
128
|
+
throw new Error("the target's public key is not the expected size");
|
|
129
|
+
}
|
|
130
|
+
return (value) =>
|
|
131
|
+
sodium.to_base64(
|
|
132
|
+
sodium.crypto_box_seal(sodium.from_string(value), key),
|
|
133
|
+
sodium.base64_variants.ORIGINAL,
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface CredentialRefreshDeps {
|
|
138
|
+
fetch: typeof fetch;
|
|
139
|
+
env: Readonly<Record<string, string | undefined>>;
|
|
140
|
+
// The crysk-secrets input, read from stdin by the entry point.
|
|
141
|
+
cryskSecrets: string;
|
|
142
|
+
baseUrl: string;
|
|
143
|
+
stdout: (text: string) => void;
|
|
144
|
+
now: () => number;
|
|
145
|
+
sleep: (ms: number) => Promise<void>;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function escapeCommandData(text: string): string {
|
|
149
|
+
return text.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
153
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// The JWT payload's claims, or undefined when the token is not a JWT.
|
|
157
|
+
function jwtClaims(token: unknown): Record<string, unknown> | undefined {
|
|
158
|
+
if (typeof token !== "string") return undefined;
|
|
159
|
+
const parts = token.split(".");
|
|
160
|
+
if (parts.length !== 3) return undefined;
|
|
161
|
+
try {
|
|
162
|
+
const claims: unknown = JSON.parse(
|
|
163
|
+
Buffer.from(parts[1] as string, "base64url").toString("utf8"),
|
|
164
|
+
);
|
|
165
|
+
return isPlainObject(claims) ? claims : undefined;
|
|
166
|
+
} catch {
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function claimAt(
|
|
172
|
+
claims: unknown,
|
|
173
|
+
pathParts: readonly (string | number)[],
|
|
174
|
+
): unknown {
|
|
175
|
+
let value: unknown = claims;
|
|
176
|
+
for (const part of pathParts) {
|
|
177
|
+
if (typeof part === "number") {
|
|
178
|
+
if (!Array.isArray(value)) return undefined;
|
|
179
|
+
value = value[part];
|
|
180
|
+
} else {
|
|
181
|
+
if (!isPlainObject(value)) return undefined;
|
|
182
|
+
value = value[part];
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return value;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// The account id the descriptor says where to find: the first claim path that
|
|
189
|
+
// holds a non-empty string in the first token that has one, else the stored
|
|
190
|
+
// record's field (OpenCode's order: extractAccountId, then the record's).
|
|
191
|
+
export function accountIdFor(
|
|
192
|
+
descriptor: OAuthProviderDescriptor,
|
|
193
|
+
tokens: Record<string, unknown>,
|
|
194
|
+
record: OpenCodeOAuthRecord,
|
|
195
|
+
): string | undefined {
|
|
196
|
+
const source = descriptor.accountId;
|
|
197
|
+
if (source === undefined) return undefined;
|
|
198
|
+
for (const tokenName of source.tokens) {
|
|
199
|
+
const claims = jwtClaims(tokens[tokenName]);
|
|
200
|
+
if (claims === undefined) continue;
|
|
201
|
+
for (const claimPath of source.claims) {
|
|
202
|
+
const value = claimAt(claims, claimPath);
|
|
203
|
+
if (typeof value === "string" && value !== "") return value;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const kept = record[source.recordField];
|
|
207
|
+
return typeof kept === "string" && kept !== "" ? kept : undefined;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// The error code in a token endpoint's error body: RFC 6749's string `error`,
|
|
211
|
+
// OpenAI's `error.code`, or a top-level `code`.
|
|
212
|
+
export function providerErrorCode(body: unknown): string | undefined {
|
|
213
|
+
if (!isPlainObject(body)) return undefined;
|
|
214
|
+
const { error, code } = body;
|
|
215
|
+
if (typeof error === "string" && error !== "") return error;
|
|
216
|
+
if (isPlainObject(error) && typeof error.code === "string" && error.code) {
|
|
217
|
+
return error.code;
|
|
218
|
+
}
|
|
219
|
+
return typeof code === "string" && code !== "" ? code : undefined;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export async function runCredentialRefresh(
|
|
223
|
+
deps: CredentialRefreshDeps,
|
|
224
|
+
): Promise<number> {
|
|
225
|
+
const secrets: string[] = [];
|
|
226
|
+
const redact = (text: string): string => {
|
|
227
|
+
let safe = text;
|
|
228
|
+
// Longest first, so a secret that contains another is hidden whole.
|
|
229
|
+
for (const secret of [...secrets].sort((a, b) => b.length - a.length)) {
|
|
230
|
+
if (secret !== "") safe = safe.split(secret).join("***");
|
|
231
|
+
}
|
|
232
|
+
return safe;
|
|
233
|
+
};
|
|
234
|
+
const mask = (value: string): void => {
|
|
235
|
+
if (value.length < 4 || secrets.includes(value)) return;
|
|
236
|
+
secrets.push(value);
|
|
237
|
+
deps.stdout(`::add-mask::${escapeCommandData(value)}\n`);
|
|
238
|
+
};
|
|
239
|
+
const fail = (message: string): number => {
|
|
240
|
+
deps.stdout(
|
|
241
|
+
`::error title=crysk::${escapeCommandData(redact(`Crysk credential refresh failed: ${message}`))}\n`,
|
|
242
|
+
);
|
|
243
|
+
return 1;
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
const operation = deps.env.CRYSK_OPERATION ?? "";
|
|
247
|
+
if (operation !== REFRESH_OPERATION) {
|
|
248
|
+
return fail(
|
|
249
|
+
`the operation input is "${operation}", which is neither "review" (the default) nor "${REFRESH_OPERATION}".`,
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
const providerId = deps.env.CRYSK_REFRESH_PROVIDER ?? "";
|
|
253
|
+
const descriptor = oauthProvider(providerId);
|
|
254
|
+
const token = opencodeSecretToken(providerId);
|
|
255
|
+
if (descriptor === undefined || token === undefined) {
|
|
256
|
+
return fail(
|
|
257
|
+
`the refresh-provider input "${providerId}" is not a subscription provider Crysk can renew.`,
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
const secretName = `CRYSK_OPENCODE_${token}_OAUTH`;
|
|
261
|
+
const runToken = deps.env.CRYSK_RUN_TOKEN ?? "";
|
|
262
|
+
const dispatchId = deps.env.CRYSK_DISPATCH_ID ?? "";
|
|
263
|
+
if (runToken === "" || dispatchId === "") {
|
|
264
|
+
return fail(
|
|
265
|
+
"no Crysk run token or dispatch id reached this step; a refresh runs only when the Crysk platform dispatches it.",
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
mask(runToken);
|
|
269
|
+
|
|
270
|
+
const parse = parseCryskSecrets(deps.cryskSecrets);
|
|
271
|
+
for (const value of parse.masks) mask(value);
|
|
272
|
+
const problem = parse.problems.find((text) => text.startsWith(secretName));
|
|
273
|
+
if (problem !== undefined) return fail(`${problem}.`);
|
|
274
|
+
const record = opencodeSecretsFor(parse.secrets, providerId)?.oauth;
|
|
275
|
+
if (record === undefined) {
|
|
276
|
+
return fail(
|
|
277
|
+
`${secretName} is not set in the crysk-secrets input; connect the subscription again from the Crysk dashboard.`,
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
const storedRefresh = record.refresh;
|
|
281
|
+
if (typeof storedRefresh !== "string" || storedRefresh === "") {
|
|
282
|
+
return fail(
|
|
283
|
+
`${secretName} holds no refresh token; connect the subscription again from the Crysk dashboard.`,
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const post = async (
|
|
288
|
+
endpoint: string,
|
|
289
|
+
body: unknown,
|
|
290
|
+
): Promise<{ ok: true; reply: unknown } | { ok: false; status?: number }> => {
|
|
291
|
+
try {
|
|
292
|
+
const response = await deps.fetch(`${deps.baseUrl}${endpoint}`, {
|
|
293
|
+
method: "POST",
|
|
294
|
+
headers: {
|
|
295
|
+
Authorization: `Bearer ${runToken}`,
|
|
296
|
+
"X-Crysk-Dispatch-Id": dispatchId,
|
|
297
|
+
"Content-Type": "application/json",
|
|
298
|
+
},
|
|
299
|
+
body: JSON.stringify(body),
|
|
300
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
301
|
+
});
|
|
302
|
+
if (!response.ok) return { ok: false, status: response.status };
|
|
303
|
+
return { ok: true, reply: await response.json().catch(() => ({})) };
|
|
304
|
+
} catch {
|
|
305
|
+
return { ok: false };
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
const describe = (status: number | undefined): string =>
|
|
309
|
+
status === undefined ? "the request could not complete" : `HTTP ${status}`;
|
|
310
|
+
|
|
311
|
+
// Retried while the platform may still take it (a transport failure, a 5xx, a
|
|
312
|
+
// 429); any other 4xx is a refusal and retrying cannot change it.
|
|
313
|
+
const postResult = async (
|
|
314
|
+
body: CredentialRefreshResultBody,
|
|
315
|
+
): Promise<{ ok: true } | { ok: false; status?: number }> => {
|
|
316
|
+
const deadline = deps.now() + RESULT_RETRY_BUDGET_MS;
|
|
317
|
+
let delay = RESULT_RETRY_FIRST_DELAY_MS;
|
|
318
|
+
for (;;) {
|
|
319
|
+
const sent = await post(CREDENTIAL_REFRESH_PATHS.result, body);
|
|
320
|
+
if (sent.ok) return { ok: true };
|
|
321
|
+
const retryable =
|
|
322
|
+
sent.status === undefined || sent.status >= 500 || sent.status === 429;
|
|
323
|
+
if (!retryable || deps.now() + delay > deadline) return sent;
|
|
324
|
+
await deps.sleep(delay);
|
|
325
|
+
delay = Math.min(delay * 2, RESULT_RETRY_MAX_DELAY_MS);
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
const reportFailure = async (
|
|
329
|
+
failure: string,
|
|
330
|
+
message: string,
|
|
331
|
+
): Promise<number> => {
|
|
332
|
+
const sent = await postResult({ provider: providerId, failure });
|
|
333
|
+
return fail(
|
|
334
|
+
sent.ok
|
|
335
|
+
? message
|
|
336
|
+
: `${message} The platform was not told (${describe(sent.status)}).`,
|
|
337
|
+
);
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
// 1. The target's public key, and the sealer for it, before anything is spent.
|
|
341
|
+
const targets = await post(CREDENTIAL_REFRESH_PATHS.targets, {
|
|
342
|
+
provider: providerId,
|
|
343
|
+
} satisfies CredentialRefreshProviderBody);
|
|
344
|
+
if (!targets.ok) {
|
|
345
|
+
return fail(
|
|
346
|
+
`the Crysk platform did not answer the refresh target (${describe(targets.status)}); nothing was spent.`,
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
const target = targets.reply;
|
|
350
|
+
if (
|
|
351
|
+
!isPlainObject(target) ||
|
|
352
|
+
typeof target.key_id !== "string" ||
|
|
353
|
+
target.key_id === "" ||
|
|
354
|
+
typeof target.key !== "string"
|
|
355
|
+
) {
|
|
356
|
+
return fail(
|
|
357
|
+
"the Crysk platform answered the refresh target without a key_id and key; nothing was spent.",
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
const keyId = target.key_id;
|
|
361
|
+
let seal: Sealer;
|
|
362
|
+
try {
|
|
363
|
+
seal = await githubSealer(target.key);
|
|
364
|
+
} catch (error) {
|
|
365
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
366
|
+
return fail(`${detail}; nothing was spent.`);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// 2. The platform records the spend, then one request to the provider.
|
|
370
|
+
const begun = await post(CREDENTIAL_REFRESH_PATHS.begin, {
|
|
371
|
+
provider: providerId,
|
|
372
|
+
} satisfies CredentialRefreshProviderBody);
|
|
373
|
+
if (!begun.ok) {
|
|
374
|
+
return fail(
|
|
375
|
+
`the Crysk platform did not start the refresh (${describe(begun.status)}); nothing was spent.`,
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
let response: Response;
|
|
380
|
+
try {
|
|
381
|
+
response = await deps.fetch(descriptor.refresh.tokenUrl, {
|
|
382
|
+
method: "POST",
|
|
383
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
384
|
+
body: new URLSearchParams({
|
|
385
|
+
...descriptor.refresh.extraParams,
|
|
386
|
+
grant_type: "refresh_token",
|
|
387
|
+
refresh_token: storedRefresh,
|
|
388
|
+
client_id: descriptor.refresh.clientId,
|
|
389
|
+
}).toString(),
|
|
390
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
391
|
+
});
|
|
392
|
+
} catch {
|
|
393
|
+
// Not retried and not reported: the request may have reached the provider
|
|
394
|
+
// and spent the stored token, so only the platform's own rule may follow.
|
|
395
|
+
return fail(
|
|
396
|
+
`the ${providerId} token endpoint could not be reached; the stored login may have been spent.`,
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
let tokens: unknown;
|
|
400
|
+
try {
|
|
401
|
+
tokens = await response.json();
|
|
402
|
+
} catch {
|
|
403
|
+
tokens = undefined;
|
|
404
|
+
}
|
|
405
|
+
// Every token is masked before any other write, whatever the answer looks
|
|
406
|
+
// like (`access_token`, `refresh_token`, `id_token`; not `token_type`, whose
|
|
407
|
+
// `Bearer` would blank ordinary text across the log).
|
|
408
|
+
if (isPlainObject(tokens)) {
|
|
409
|
+
for (const [key, value] of Object.entries(tokens)) {
|
|
410
|
+
if (key.endsWith("token") && typeof value === "string") mask(value);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
if (!response.ok) {
|
|
414
|
+
const code = providerErrorCode(tokens);
|
|
415
|
+
if (code !== undefined && descriptor.permanentErrors.includes(code)) {
|
|
416
|
+
return reportFailure(
|
|
417
|
+
code,
|
|
418
|
+
`${providerId} refused the stored login (${code}); connect the subscription again from the Crysk dashboard.`,
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
return reportFailure(
|
|
422
|
+
PROVIDER_ERROR_FAILURE,
|
|
423
|
+
`the ${providerId} token endpoint answered HTTP ${response.status}.`,
|
|
424
|
+
);
|
|
425
|
+
}
|
|
426
|
+
if (
|
|
427
|
+
!isPlainObject(tokens) ||
|
|
428
|
+
typeof tokens.access_token !== "string" ||
|
|
429
|
+
tokens.access_token === ""
|
|
430
|
+
) {
|
|
431
|
+
return reportFailure(
|
|
432
|
+
PROVIDER_ERROR_FAILURE,
|
|
433
|
+
`the ${providerId} token endpoint answered without an access token.`,
|
|
434
|
+
);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// 3. From here the stored refresh token is spent: nothing may stop the
|
|
438
|
+
// result POST. The record is OpenCode's own shape after a refresh.
|
|
439
|
+
const issuedAt = deps.now();
|
|
440
|
+
const access = tokens.access_token;
|
|
441
|
+
const refresh =
|
|
442
|
+
typeof tokens.refresh_token === "string" && tokens.refresh_token !== ""
|
|
443
|
+
? tokens.refresh_token
|
|
444
|
+
: storedRefresh;
|
|
445
|
+
const expiresIn = tokens.expires_in;
|
|
446
|
+
const jwtExp = jwtClaims(access)?.exp;
|
|
447
|
+
const believable = (at: number) =>
|
|
448
|
+
Number.isFinite(at) && at > issuedAt && at <= issuedAt + MAX_EXPIRES_IN_MS;
|
|
449
|
+
const fromAnswer =
|
|
450
|
+
typeof expiresIn === "number" ? issuedAt + expiresIn * 1000 : Number.NaN;
|
|
451
|
+
const fromJwt = typeof jwtExp === "number" ? jwtExp * 1000 : Number.NaN;
|
|
452
|
+
const expires = believable(fromAnswer)
|
|
453
|
+
? fromAnswer
|
|
454
|
+
: believable(fromJwt)
|
|
455
|
+
? fromJwt
|
|
456
|
+
: issuedAt + DEFAULT_EXPIRES_IN_S * 1000;
|
|
457
|
+
const accountId = accountIdFor(descriptor, tokens, record);
|
|
458
|
+
const recordField = descriptor.accountId?.recordField;
|
|
459
|
+
const renewed: Record<string, unknown> = {
|
|
460
|
+
type: "oauth",
|
|
461
|
+
refresh,
|
|
462
|
+
access,
|
|
463
|
+
expires,
|
|
464
|
+
...(accountId !== undefined && recordField !== undefined
|
|
465
|
+
? { [recordField]: accountId }
|
|
466
|
+
: {}),
|
|
467
|
+
};
|
|
468
|
+
const value = Buffer.from(JSON.stringify(renewed), "utf8").toString("base64");
|
|
469
|
+
mask(value);
|
|
470
|
+
let encrypted: string;
|
|
471
|
+
try {
|
|
472
|
+
encrypted = seal(value);
|
|
473
|
+
} catch (error) {
|
|
474
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
475
|
+
return fail(
|
|
476
|
+
`the renewed login could not be sealed (${detail}); the stored login was spent.`,
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
const sent = await postResult({
|
|
480
|
+
provider: providerId,
|
|
481
|
+
key_id: keyId,
|
|
482
|
+
encrypted_value: encrypted,
|
|
483
|
+
issued_at: new Date(issuedAt).toISOString(),
|
|
484
|
+
expires_at: new Date(expires).toISOString(),
|
|
485
|
+
provider_account_id: accountId ?? null,
|
|
486
|
+
});
|
|
487
|
+
if (!sent.ok) {
|
|
488
|
+
return fail(
|
|
489
|
+
`the Crysk platform did not take the renewed login (${describe(sent.status)}); the stored login was spent, so connect the subscription again from the Crysk dashboard.`,
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
deps.stdout(
|
|
493
|
+
`::notice title=crysk::${escapeCommandData(`Renewed the ${providerId} subscription login; it expires at ${new Date(expires).toISOString()}.`)}\n`,
|
|
494
|
+
);
|
|
495
|
+
return 0;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// Like the trigger and setup steps: the input arrives on stdin, never in the
|
|
499
|
+
// environment of a process bun starts.
|
|
500
|
+
const CRYSK_SECRETS_ENV = "CRYSK_SECRETS_INPUT";
|
|
501
|
+
const CRYSK_SECRETS_STDIN_FLAG = "--crysk-secrets-stdin";
|
|
502
|
+
|
|
503
|
+
if (import.meta.main) {
|
|
504
|
+
if ((process.env[CRYSK_SECRETS_ENV] ?? "") !== "") {
|
|
505
|
+
process.stderr.write(
|
|
506
|
+
`crysk: the crysk-secrets input reached credential-refresh.ts through its environment; pipe it on stdin with ${CRYSK_SECRETS_STDIN_FLAG} and run bun with ${CRYSK_SECRETS_ENV} empty.\n`,
|
|
507
|
+
);
|
|
508
|
+
process.exit(1);
|
|
509
|
+
}
|
|
510
|
+
const cryskSecrets = process.argv.includes(CRYSK_SECRETS_STDIN_FLAG)
|
|
511
|
+
? await Bun.stdin.text()
|
|
512
|
+
: "";
|
|
513
|
+
process.exit(
|
|
514
|
+
await runCredentialRefresh({
|
|
515
|
+
fetch,
|
|
516
|
+
env: process.env,
|
|
517
|
+
cryskSecrets,
|
|
518
|
+
baseUrl: PLATFORM_API_URL,
|
|
519
|
+
stdout: (text) => process.stdout.write(text),
|
|
520
|
+
now: () => Date.now(),
|
|
521
|
+
sleep: (ms) => Bun.sleep(ms),
|
|
522
|
+
}),
|
|
523
|
+
);
|
|
524
|
+
}
|
package/src/ci/crysk-secrets.ts
CHANGED
|
@@ -93,7 +93,8 @@ const CLAUDE_RESERVED_RE = /^CRYSK_CLAUDE_(?:OAUTH_TOKEN|API_KEY)_[A-Z0-9_]+$/;
|
|
|
93
93
|
// <P> is exactly the image of opencodeSecretToken: one or more [A-Z0-9] runs
|
|
94
94
|
// joined by single underscores. The provider runs up to the fixed suffix, so a
|
|
95
95
|
// provider whose own name ends in `_API` still parses (FOO_API + _API_KEY).
|
|
96
|
-
|
|
96
|
+
// Exported for outcome.ts's copy (knownFailureCredential), which a test pins to it.
|
|
97
|
+
export const OPENCODE_SECRET_NAME_RE =
|
|
97
98
|
/^CRYSK_OPENCODE_([A-Z0-9]+(?:_[A-Z0-9]+)*)_(API_KEY|OAUTH)$/;
|
|
98
99
|
// A line is NAME=value when it starts with an identifier and an `=`; the value
|
|
99
100
|
// runs from the FIRST `=`, so base64 padding survives.
|
|
@@ -157,6 +158,20 @@ export function opencodeSecretToken(providerId: string): string | undefined {
|
|
|
157
158
|
return providerId.toUpperCase().replace(/[.-]/g, "_");
|
|
158
159
|
}
|
|
159
160
|
|
|
161
|
+
// The name of an OpenCode provider's secret of one kind, or undefined when no secret
|
|
162
|
+
// name can carry the provider id. The one builder: chooseOpenCodeSecret and the
|
|
163
|
+
// transport factory (a failed attempt's failureCredential, S7) both use it.
|
|
164
|
+
export function opencodeSecretName(
|
|
165
|
+
providerId: string,
|
|
166
|
+
kind: "api_key" | "oauth",
|
|
167
|
+
): string | undefined {
|
|
168
|
+
const token = opencodeSecretToken(providerId);
|
|
169
|
+
if (token === undefined) return undefined;
|
|
170
|
+
return kind === "api_key"
|
|
171
|
+
? `CRYSK_OPENCODE_${token}_API_KEY`
|
|
172
|
+
: `CRYSK_OPENCODE_${token}_OAUTH`;
|
|
173
|
+
}
|
|
174
|
+
|
|
160
175
|
export function opencodeSecretsFor(
|
|
161
176
|
secrets: CryskSecrets,
|
|
162
177
|
providerId: string,
|
|
@@ -195,10 +210,9 @@ export function chooseOpenCodeSecret(
|
|
|
195
210
|
providerId: string,
|
|
196
211
|
names: readonly string[],
|
|
197
212
|
): OpenCodeSecretChoice | undefined {
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
const oauth = `CRYSK_OPENCODE_${token}_OAUTH`;
|
|
213
|
+
const apiKey = opencodeSecretName(providerId, "api_key");
|
|
214
|
+
const oauth = opencodeSecretName(providerId, "oauth");
|
|
215
|
+
if (apiKey === undefined || oauth === undefined) return undefined;
|
|
202
216
|
const hasApiKey = names.includes(apiKey);
|
|
203
217
|
if (names.includes(oauth)) {
|
|
204
218
|
if (providerId !== OPENCODE_OAUTH_SECRET_PROVIDER) {
|
|
@@ -364,7 +378,7 @@ export function parseCryskSecrets(raw: string): CryskSecretsParse {
|
|
|
364
378
|
}
|
|
365
379
|
|
|
366
380
|
const claudeKind = CLAUDE_NAMES[name];
|
|
367
|
-
const opencodeMatch =
|
|
381
|
+
const opencodeMatch = OPENCODE_SECRET_NAME_RE.exec(name);
|
|
368
382
|
if (claudeKind === undefined && opencodeMatch === null) {
|
|
369
383
|
notices.push(`${name} is not a Crysk credential name; it is ignored.`);
|
|
370
384
|
continue;
|
package/src/ci/force-comment.ts
CHANGED
|
@@ -28,7 +28,20 @@ export function ciForceReviewDispatch(prNumber: number): string {
|
|
|
28
28
|
return `gh workflow run ${CI_FORCE_WORKFLOW_FILE} -f pr=${prNumber}`;
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
|
|
31
|
+
// `platformConnected`: the run came through the Crysk platform. Its workflow is
|
|
32
|
+
// the platform's stub, which listens for the `/crysk` spellings only and was
|
|
33
|
+
// never scaffolded here, so the legacy names, the force workflow and the
|
|
34
|
+
// re-scaffold do not apply there (cryskai/platform#12).
|
|
35
|
+
export function ciForceReviewHintLine(
|
|
36
|
+
prNumber: number,
|
|
37
|
+
platformConnected = false,
|
|
38
|
+
): string {
|
|
39
|
+
if (platformConnected) {
|
|
40
|
+
return (
|
|
41
|
+
`Comment \`${CI_REVIEW_COMMENT}\` on this pull request to run it anyway ` +
|
|
42
|
+
`(\`${CI_REVIEW_FULL_COMMENT}\` re-discovers the whole range).`
|
|
43
|
+
);
|
|
44
|
+
}
|
|
32
45
|
return (
|
|
33
46
|
`Comment ${commandHint(CI_REVIEW_COMMENT)} on this pull request to run it ` +
|
|
34
47
|
`on GitHub Actions anyway (${commandHint(CI_REVIEW_FULL_COMMENT)} re-discovers the ` +
|