Skip to content

Commit 54a8f32

Browse files
authored
docs(changelog): v0.9.5 entry (#1088)
* docs(changelog): v0.9.5 entry The v0.9.5 release PR (#1086) merged without a CHANGELOG entry because I mistakenly split it out. `CHANGELOG.md` is baked into the compiled binary at build time (`script/build.ts` embeds it as `OPENCODE_CHANGELOG`) and copied into every platform-specific npm package (`script/publish.ts`), so shipping v0.9.5 without this entry would give users an artifact whose embedded changelog stops at v0.9.4. Entry incorporates PM's release-notes feedback from the pre-release persona review: leads with the Windows grep fix (~16% of Windows users broken since v0.9.2, hard number from telemetry), collapses the welcome-panel two-round fix into a single bullet, includes the YOLO deny-rules-still-apply safety caveat, and files the three telemetry / instrumentation commits under Changed (observability) rather than Added (user-visible feature) so the release isn't overstated. * test(skill): adversarial coverage for v0.9.5 surfaces Per the release skill's Step 6, every release ships with an adversarial test file under `test/skill/release-v{X}-adversarial.test.ts` — one per release since v0.5.14. The v0.9.5 file was written but not committed; adding it here so the release PR carries the intended coverage. Categories per the skill (empty/null/undefined, boundary values, type confusion, injection attacks, error propagation), applied to the v0.9.5 code surface: - **Flag.truthyEnv:** 32KB env values, embedded null bytes, whitespace, unknown keys — all must not enable and must not throw. - **Telemetry.classifyProvider:** 10KB providerIDs, control characters, JSON-stringified inputs, prototype keys (`__proto__` / `prototype` / `hasOwnProperty` / `isPrototypeOf`), unusual modelID values — all must fall through to "other" without leaking a raw id or extending Object. - **OnboardingTelemetry.claimEnvironmentScan:** empty / 10KB / path-shaped / SQL-shaped sessionIDs — idempotent and session-scoped; the composed gate short-circuits correctly when the session was never marked. - **redactPaths / countSampleContents:** empty input, 100KB input in <1s, regex metacharacters in `extras`, user text already containing `<path>`, fs symlink loops on `countSampleContents`. - **buildCliContext / buildAuthorizeUrl:** base64url shape, `v=1` payload, redirect / state encoding on hostile inputs (newlines, tabs, fragment chars), fragment-goes-last invariant, graceful degradation when the machine-id path is unreadable (payload valid, `machine_id` omitted). 22 tests, all pass locally. No `mock.module()`; real helpers, real fs where needed, real `process.env` mutation with `beforeEach` / `afterEach` snapshot-and-restore. * test(skill): escape null bytes as `\x00` so git treats the file as text Previous commit landed the adversarial file with three raw null bytes embedded in string literals meant to test null-byte handling. Git classified the file as binary because of them, showing `Bin 0 -> 13936 bytes` and 0 insertions/deletions on the diff — reviewers on the PR couldn't see the file contents. Runtime behavior of the tests is unchanged; the JS string `"true\x00"` compiles to the same "true"+NUL sequence as a literal 0x00 byte in the source, without tripping git's binary detector. 22/22 tests still pass after the escape. * fix(pr-review): address coderabbit + cubic findings on PR #1088 Three inline findings, all valid, all small: - **CHANGELOG.md:25** (coderabbit + cubic, both P3) — repo-relative telemetry doc path was `docs/reference/telemetry.md`; the file actually lives at `docs/docs/reference/telemetry.md` (content root is `docs/` per `docs/mkdocs.yml`, published at `reference/telemetry/` on the docs site). Fixed the path so a maintainer following the link in the changelog finds the file. - **adversarial.test.ts:180** (coderabbit) — the 100KB stress test used `repeat(1000)` which is ~20KB, not 100KB as advertised, and asserted a wall-clock `performance.now()` budget which is flaky under host load / parallel test runners. Built exactly 100_000 characters via `Math.ceil(100_000 / segment.length)` slicing, and dropped the timing assertion — the test now proves only what it claims (redaction shape survives large input). - **adversarial.test.ts:225** (coderabbit) — the symlink-loop test had a bare `catch { return }` that would swallow every setup failure into a passing test, and `toBeGreaterThanOrEqual(0)` accepted incorrect positive counts. Narrowed the catch to the one known unsupported- symlink error class (`EPERM` on Windows without dev-mode), re-throw everything else, and tightened the assertion to exact `.toBe(0)` — a nonzero count would mean the helper is following the loop. 22/22 adversarial tests still pass after the changes. * test(skill): scope `ALTIMATE_TELEMETRY_DISABLED` snapshot hooks to their describe block Kilo review on PR #1088: `beforeEach` / `afterEach` for the `ALTIMATE_TELEMETRY_DISABLED` env-var snapshot were declared at file scope, so they ran for all 22 tests even though only the four tests in `Flag.truthyEnv adversarial` ever set that variable. Moved the `const`, the `let`, and both hooks inside that describe block so scope matches usage. Behavior unchanged (still 22/22 pass); noise removed from unrelated tests' setup/teardown timeline. --------- Co-authored-by: Haider <[email protected]>
1 parent 5f51d65 commit 54a8f32

2 files changed

Lines changed: 332 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,26 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [0.9.5] - 2026-08-10
9+
10+
Windows `grep` back for the ~16% of Windows users it silently broke since v0.9.2, plus a mid-session YOLO toggle and a welcome panel that stops eating half of narrow terminals.
11+
12+
### Added
13+
14+
- **`Ctrl+Y` toggles YOLO mode mid-session.** Previously YOLO was launch-time only — you either started the CLI with `--yolo` / `ALTIMATE_CLI_YOLO=true` or opened a new one. Now you can flip it on or off from inside the TUI. Enabling requires a one-tap confirmation; disabling is instant. The toggle is **session and subagent scoped and lives in memory only** — restart the CLI and it defaults back to whatever `--yolo`, `ALTIMATE_CLI_YOLO`, or `OPENCODE_YOLO` was at launch. Explicit `deny` rules stay enforced (`DROP DATABASE`, `DROP SCHEMA`, `TRUNCATE` remain blocked even with the toggle on). Heads-up: `Ctrl+Y` is `readline`'s "yank" keystroke in some shells — the toggle defaults to "No" on the confirmation, so a stray keypress can't do anything dangerous. (#1078)
15+
16+
### Fixed
17+
18+
- **Windows `grep` for the ~16% of Windows users it was silently broken for.** Since v0.9.2, ripgrep extraction shelled out to `powershell.exe` for the download's zip, and 99 of 617 Windows machines in a 14-day telemetry window couldn't complete the extraction — the tool failed silently on `grep` / `glob` from that point on. Extraction is now in-process via `@zip.js/zip.js` (`checkSignature: true`, exact-pinned) with atomic staged-then-renamed installs, no PowerShell dependency at all. Landed with a real Windows CI job (`windows-ripgrep-e2e`) that runs with PowerShell stripped from `PATH`, so this class of regression can't come back silently. (#1074, closes #1072)
19+
- **Welcome panel no longer eats 40% of narrow or short terminals.** On anything smaller than ~110 cols wide or ~44 rows tall the panel now scales through three responsive tiers instead of holding the full desktop-sized dimensions. Landed in two rounds — the first added the breakpoint function; the second corrected the width measurement so the `full` tier no longer fired at ~84 usable cols. (#1067, #1069, #1071)
20+
- **Telemetry opt-out honors `=1` and case-insensitive `true`, and finally wires up `OPENCODE_DISABLE_TELEMETRY`.** `ALTIMATE_TELEMETRY_DISABLED=1` and `=TRUE` used to be silently ignored (only `=true` worked). The v0.9.4 CHANGELOG advertised `OPENCODE_DISABLE_TELEMETRY=1` as an opt-out env var but that name was wired into test fixtures only, never checked in product — users who set it based on the release notes were not opted out. Both env vars now route through a shared helper that accepts `"true"` / `"TRUE"` / `"1"`. If you set either one and expected it to work, this release makes it actually work. (#1086)
21+
22+
### Changed
23+
24+
- **`cli_context` on the sign-in URL for PostHog session correlation.** After successful sign-in, the frontend registers the CLI machine-id as the `cli_machine_id` PostHog super-property so CLI activity is attributed to the authenticated account in aggregate funnel analytics. The value travels in the URL *fragment* (`#cli_context=…`, not a query string) so the durable identifier stays out of server access logs, CDN/WAF, and the `Referer` header — the frontend reads it via `location.hash`. (#1068)
25+
- **First-run onboarding and review feature usage now emit funnel telemetry.** New event types: `activation_menu_shown`, `activation_job_selected`, `first_prompt_sent`, `environment_scan_completed`, plus review-lane latency and outcome events. All existing opt-out mechanisms (`ALTIMATE_TELEMETRY_DISABLED`, `OPENCODE_DISABLE_TELEMETRY`, `telemetry.disabled` in config) gate every new event; full list in `docs/docs/reference/telemetry.md`. (#1049, #1064)
26+
- **UTM parameters on outbound `altimate.ai` marketing links.** Non-functional; helps attribute web traffic back to the CLI. (#1063)
27+
828
## [0.9.4] - 2026-07-31
929

1030
Onboarding UX + first-run OAuth reliability. Ships the CLI's first-run scan + activation menu (Altimate LLM Gateway top of picker; bundled jaffle-shop DuckDB sample for users with no warehouse yet), then hardens the sign-in flow that path leads into.
Lines changed: 312 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,312 @@
1+
/**
2+
* Adversarial tests for the v0.9.5 release surface.
3+
*
4+
* Covers the 8 upstream commits (`#1049`, `#1063`, `#1064`, `#1067`, `#1068`,
5+
* `#1069`+`#1071`, `#1074`, `#1078`) plus the 6 pre-release review-fix commits
6+
* that landed via PR #1086. The per-surface unit tests
7+
* (`test/telemetry/*`, `test/altimate/sample-setup-helpers.test.ts`) hit the
8+
* happy path and the documented failure modes; this file layers boundary /
9+
* injection / type-confusion / oversized-input cases on top so the FINAL
10+
* shipped code — not just what the unit tests exercised — is what gets tagged.
11+
*
12+
* Every assertion is deterministic — no timing dependencies, no shared state,
13+
* no `mock.module()`. Real helpers, real fs where needed, real
14+
* `process.env` mutation with snapshot/restore.
15+
*/
16+
17+
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
18+
import fs from "node:fs"
19+
import os from "node:os"
20+
import path from "node:path"
21+
22+
import { Flag } from "../../src/flag/flag"
23+
import { Telemetry } from "../../src/altimate/telemetry"
24+
import * as OnboardingTelemetry from "../../src/altimate/telemetry/onboarding"
25+
import { redactPaths, countSampleContents } from "../../src/altimate/tools/sample-setup"
26+
import { buildCliContext, buildAuthorizeUrl } from "../../src/altimate/plugin/altimate"
27+
28+
// -----------------------------------------------------------------------------
29+
// 1. Telemetry opt-out — `Flag.truthyEnv` on hostile / oversized env values
30+
// -----------------------------------------------------------------------------
31+
32+
describe("v0.9.5 — Flag.truthyEnv adversarial", () => {
33+
// Kilo review on PR #1088: env-var snapshot/restore hooks were previously
34+
// file-scoped, so they ran for every test in this file even though only the
35+
// tests in this describe block ever touch `ALTIMATE_TELEMETRY_DISABLED`.
36+
// Scoping them here matches usage.
37+
const OPT_OUT_VAR = "ALTIMATE_TELEMETRY_DISABLED"
38+
let optOutSnapshot: string | undefined
39+
beforeEach(() => {
40+
optOutSnapshot = process.env[OPT_OUT_VAR]
41+
})
42+
afterEach(() => {
43+
if (optOutSnapshot === undefined) delete process.env[OPT_OUT_VAR]
44+
else process.env[OPT_OUT_VAR] = optOutSnapshot
45+
})
46+
47+
test("very long value (32KB) — must not enable, must not throw", () => {
48+
// A 32KB env value should be rejected as a non-truthy string, not crash the
49+
// parser. Real users don't hit this, but a shell injection into the env
50+
// could.
51+
process.env[OPT_OUT_VAR] = "x".repeat(32 * 1024)
52+
expect(Flag.truthyEnv(OPT_OUT_VAR)).toBe(false)
53+
})
54+
55+
test("value with embedded null byte — must not enable", () => {
56+
process.env[OPT_OUT_VAR] = "true\x00"
57+
// JS's `===` doesn't treat "true\0" as "true", so this rejects — asserting
58+
// that the parser doesn't stringify-and-substring-check.
59+
expect(Flag.truthyEnv(OPT_OUT_VAR)).toBe(false)
60+
})
61+
62+
test("value with leading/trailing whitespace — rejected (no trimming)", () => {
63+
// Documented semantic — matches the existing `truthy()` behaviour. If a
64+
// future edit adds trim(), this test flips and the reviewer must decide
65+
// whether that's intentional.
66+
process.env[OPT_OUT_VAR] = "\ttrue\n"
67+
expect(Flag.truthyEnv(OPT_OUT_VAR)).toBe(false)
68+
})
69+
70+
test("unknown env var name — always false, never crash on missing key", () => {
71+
expect(Flag.truthyEnv("SOME_TOTALLY_UNSET_VAR_" + "A".repeat(50))).toBe(false)
72+
})
73+
})
74+
75+
// -----------------------------------------------------------------------------
76+
// 2. `Telemetry.classifyProvider` — hostile ids + prototype defense stress
77+
// -----------------------------------------------------------------------------
78+
79+
describe("v0.9.5 — Telemetry.classifyProvider adversarial", () => {
80+
test("very long providerID (10K chars) — 'other', no id leaked, no throw", () => {
81+
const huge = "z".repeat(10_000)
82+
const r = Telemetry.classifyProvider(huge)
83+
expect(r.provider).toBe("other")
84+
expect(r.provider_id).toBeUndefined()
85+
})
86+
87+
test("providerID with embedded null byte — 'other', id dropped", () => {
88+
const r = Telemetry.classifyProvider("anthropic\x00injected")
89+
expect(r.provider).toBe("other")
90+
expect(r.provider_id).toBeUndefined()
91+
})
92+
93+
test("providerID with newlines and control characters — 'other', id dropped", () => {
94+
const r = Telemetry.classifyProvider("anthropic\n\r\tinjected")
95+
expect(r.provider).toBe("other")
96+
expect(r.provider_id).toBeUndefined()
97+
})
98+
99+
test("providerID that is a JSON stringification of an object — 'other'", () => {
100+
const r = Telemetry.classifyProvider('{"provider":"anthropic"}')
101+
expect(r.provider).toBe("other")
102+
expect(r.provider_id).toBeUndefined()
103+
})
104+
105+
test("__proto__ / prototype as providerID — must NOT poison and must NOT enum", () => {
106+
for (const key of ["__proto__", "prototype", "hasOwnProperty", "isPrototypeOf"]) {
107+
const r = Telemetry.classifyProvider(key)
108+
expect(r.provider).toBe("other")
109+
}
110+
// Sanity: prototype pollution attempt at this call site didn't extend Object.
111+
// If CURATED_PROVIDER_ENUM were a plain object and a caller managed to write
112+
// to it, unrelated code paths could leak an inherited property here.
113+
expect(({} as any).polluted).toBeUndefined()
114+
})
115+
116+
test("modelID with unusual types (empty string, whitespace, unicode) — no big_pickle unless exact", () => {
117+
// Contract: `big_pickle` only fires on the exact pair ("opencode","big-pickle").
118+
// Anything else on the opencode provider must fall through to "other" with the id kept.
119+
for (const modelID of ["", " big-pickle ", "BIG-PICKLE", "big-pickle​" /* zero-width */]) {
120+
const r = Telemetry.classifyProvider("opencode", modelID)
121+
expect(r.provider).toBe("other")
122+
expect(r.provider_id).toBe("opencode")
123+
}
124+
})
125+
})
126+
127+
// -----------------------------------------------------------------------------
128+
// 3. `OnboardingTelemetry.claimEnvironmentScan` — hostile sessionIDs
129+
// -----------------------------------------------------------------------------
130+
131+
describe("v0.9.5 — OnboardingTelemetry claim adversarial", () => {
132+
beforeEach(() => OnboardingTelemetry.resetForTest())
133+
afterEach(() => OnboardingTelemetry.resetForTest())
134+
135+
test("empty-string sessionID — treated as its own session", () => {
136+
// Not a user-reachable shape (SessionPrompt always synthesizes an id) but
137+
// the helper must not crash and must remain idempotent for whatever key it
138+
// receives.
139+
expect(OnboardingTelemetry.claimEnvironmentScan("")).toBe(true)
140+
expect(OnboardingTelemetry.claimEnvironmentScan("")).toBe(false)
141+
})
142+
143+
test("very long sessionID (10K chars) — one claim, then locked", () => {
144+
const huge = "s".repeat(10_000)
145+
expect(OnboardingTelemetry.claimEnvironmentScan(huge)).toBe(true)
146+
expect(OnboardingTelemetry.claimEnvironmentScan(huge)).toBe(false)
147+
})
148+
149+
test("sessionID with special characters — treated as distinct keys", () => {
150+
const a = "sess/../etc/passwd"
151+
const b = "sess'; DROP TABLE users;--"
152+
const c = "sess\x00null"
153+
for (const s of [a, b, c]) {
154+
expect(OnboardingTelemetry.claimEnvironmentScan(s)).toBe(true)
155+
expect(OnboardingTelemetry.claimEnvironmentScan(s)).toBe(false)
156+
}
157+
})
158+
159+
test("isOnboardingSession stays false for a session that only claimed (no markOnboardingSession)", () => {
160+
// The composed gate (`isOnboardingSession && claim`) at project-scan.ts:952
161+
// relies on markOnboardingSession being called separately. A session that
162+
// only ever hit `claim()` must NOT be reported as onboarding — that would
163+
// silently promote random /discover calls to funnel events.
164+
OnboardingTelemetry.claimEnvironmentScan("random-session")
165+
expect(OnboardingTelemetry.isOnboardingSession("random-session")).toBe(false)
166+
})
167+
})
168+
169+
// -----------------------------------------------------------------------------
170+
// 4. `redactPaths` / `countSampleContents` — oversize / metachar / hostile fs
171+
// -----------------------------------------------------------------------------
172+
173+
describe("v0.9.5 — sample-setup helpers adversarial", () => {
174+
test("redactPaths handles empty message without throwing", () => {
175+
expect(redactPaths("")).toBe("")
176+
})
177+
178+
test("redactPaths handles a 100KB message without leaking paths or degenerating markers", () => {
179+
// Coderabbit review on PR #1088: previous version used `repeat(1000)` which is
180+
// ~20 KB not 100 KB, and a `performance.now()` wall-clock assertion which is
181+
// flaky under host load / parallel test runners. Build exactly 100,000 chars
182+
// deterministically and assert only the redaction shape.
183+
const segment = "normal text here /Users/alice/x/y/z "
184+
const msg = segment.repeat(Math.ceil(100_000 / segment.length)).slice(0, 100_000)
185+
const out = redactPaths(msg)
186+
expect(out).not.toContain("/Users/alice")
187+
// Should not have degenerated to `<path><path><path>...`
188+
expect(out).not.toMatch(/<path><path>/)
189+
})
190+
191+
test("redactPaths accepts extras containing regex metacharacters (treated as literal via split)", () => {
192+
// The known-value pass uses `split(known).join("<path>")`, which is a literal
193+
// substring split — regex metachars in `known` don't have any special meaning.
194+
// A future rewrite that regressed to `.replace(new RegExp(known), ...)` would
195+
// either crash on the unclosed `[` or match wildly. This test locks the
196+
// literal-split semantics in.
197+
const out = redactPaths("failed at /tmp/checkout-.+*[xyz", ["/tmp/checkout-.+*[xyz"])
198+
expect(out).toBe("failed at <path>")
199+
})
200+
201+
test("redactPaths does not leak the marker back if a user's error text already contains '<path>'", () => {
202+
// If the input already contained `<path>` as literal user text, the collapse
203+
// step could double-eat surrounding characters. Assert the marker is
204+
// preserved as-is when it's not adjacent to another marker.
205+
const out = redactPaths("caller received sentinel <path> from upstream")
206+
expect(out).toContain("<path>")
207+
expect(out).toContain("sentinel")
208+
expect(out).toContain("upstream")
209+
})
210+
211+
test("countSampleContents on a symlink loop returns 0 rather than crashing", () => {
212+
// fs.readdirSync follows the surface entries but doesn't recurse into loops
213+
// in this helper (countFilesWithExtension only recurses via `isDirectory()`
214+
// on the entry itself). The loop link itself does not resolve to a
215+
// directory here, so it's counted as a file (and skipped by the .sql / .csv
216+
// extension filter). Still: the important adversarial guarantee is "does
217+
// not blow up".
218+
const root = fs.mkdtempSync(path.join(os.tmpdir(), "v095-adversarial-symlink-"))
219+
try {
220+
fs.mkdirSync(path.join(root, "models"))
221+
// Create a symlink pointing back to models — a real loop.
222+
// Coderabbit review on PR #1088: bare `catch` used to swallow every symlink
223+
// setup failure into a passing test, and `toBeGreaterThanOrEqual(0)` was
224+
// trivially true for any non-negative count. Narrow the skip to the one
225+
// known-unsupported-symlink error class (EPERM on Windows without
226+
// dev-mode); re-throw anything else so a real filesystem regression
227+
// doesn't hide behind the skip. Assert exact `models === 0` — the loop
228+
// link resolves to a directory but has no `.sql` inside; anything nonzero
229+
// would mean the helper is following the loop.
230+
try {
231+
fs.symlinkSync(path.join(root, "models"), path.join(root, "models", "loop"))
232+
} catch (error) {
233+
if ((error as NodeJS.ErrnoException).code === "EPERM") return
234+
throw error
235+
}
236+
const counts = countSampleContents(root)
237+
expect(counts.models).toBe(0)
238+
expect(counts.tables).toBe(0)
239+
} finally {
240+
fs.rmSync(root, { recursive: true, force: true })
241+
}
242+
})
243+
})
244+
245+
// -----------------------------------------------------------------------------
246+
// 5. `buildCliContext` / `buildAuthorizeUrl` — cli_context URL fragment
247+
// -----------------------------------------------------------------------------
248+
249+
describe("v0.9.5 — cli_context builder adversarial", () => {
250+
test("buildCliContext produces valid base64url that decodes to v=1 payload", async () => {
251+
// Machine-id file lives at ~/.altimate/machine-id in the runtime path;
252+
// point at a tmpfile so the runner's real state is untouched.
253+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "v095-adversarial-mid-"))
254+
try {
255+
const midPath = path.join(tmp, "machine-id")
256+
const encoded = await buildCliContext(midPath)
257+
// base64url characters only — no `+`, `/`, `=`.
258+
expect(encoded).toMatch(/^[A-Za-z0-9_-]+$/)
259+
const decoded = Buffer.from(encoded, "base64url").toString("utf8")
260+
const payload = JSON.parse(decoded)
261+
expect(payload.v).toBe(1)
262+
expect(typeof payload.cli_version).toBe("string")
263+
} finally {
264+
fs.rmSync(tmp, { recursive: true, force: true })
265+
}
266+
})
267+
268+
test("buildAuthorizeUrl encodes redirect and state (no naked control chars)", async () => {
269+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "v095-adversarial-authurl-"))
270+
try {
271+
const midPath = path.join(tmp, "machine-id")
272+
const hostile = "https://evil.example/callback?a=1&b=2#frag"
273+
const url = await buildAuthorizeUrl(
274+
"https://app.example.com",
275+
hostile,
276+
"state\nvalue\twith\tspecials",
277+
midPath,
278+
)
279+
// No literal newline / tab / naked `#` in the query-param portion.
280+
// (Fragment starts with `#cli_context=...` — that's the only allowed `#`.)
281+
const [queryPortion] = url.split("#")
282+
expect(queryPortion).not.toContain("\n")
283+
expect(queryPortion).not.toContain("\t")
284+
// Fragment is present and comes last.
285+
expect(url).toContain("#cli_context=")
286+
expect(url.indexOf("#cli_context=")).toBe(url.lastIndexOf("#"))
287+
// The redirect param carries the encoded form, not the raw URL —
288+
// an escaped `#` (%23) must be present, not a naked one.
289+
expect(url).toContain("redirect=" + encodeURIComponent(hostile))
290+
} finally {
291+
fs.rmSync(tmp, { recursive: true, force: true })
292+
}
293+
})
294+
295+
test("buildCliContext returns valid payload even when machine-id path is unreadable", async () => {
296+
// Point at a directory (not a file) — the machine-id read/write should
297+
// fail internally, but the builder should still return a valid payload
298+
// WITHOUT machine_id rather than throw.
299+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "v095-adversarial-badmid-"))
300+
try {
301+
const encoded = await buildCliContext(tmp) // tmp is a dir, not a file
302+
const decoded = Buffer.from(encoded, "base64url").toString("utf8")
303+
const payload = JSON.parse(decoded)
304+
expect(payload.v).toBe(1)
305+
// machine_id must NOT be present when it can't be read/minted.
306+
// (`buildCliContext` uses `if (machineId) ctx.machine_id = machineId`.)
307+
expect(payload.machine_id).toBeUndefined()
308+
} finally {
309+
fs.rmSync(tmp, { recursive: true, force: true })
310+
}
311+
})
312+
})

0 commit comments

Comments
 (0)