Skip to content

fix(web): use createBrowserUuid in non-secure contexts - #20465

Closed
minhtuancn wants to merge 1 commit into
stablyai:mainfrom
minhtuancn:fix/web-nonsecure-context-crypto-uuid
Closed

minhtuancn wants to merge 1 commit into
stablyai:mainfrom
minhtuancn:fix/web-nonsecure-context-crypto-uuid

Conversation

@minhtuancn

Copy link
Copy Markdown

ELI5

The web client connects over plain HTTP on a LAN. Browsers treat those pages as non-secure contexts and hide crypto.randomUUID, so the right sidebar crashed at render. This PR routes every raw crypto.randomUUID() call in the renderer through the existing context-safe createBrowserUuid() helper (with a small equivalent fallback for the shared sequencer), and adds a regression test.

What Changed

  • right-sidebar/ai-vault-session-refresh.ts: request token minted via createBrowserUuid() — fixes the reported right-sidebar crash.
  • Migrate ~20 remaining raw crypto.randomUUID() call sites in the renderer (skills dialogs/delete-flow, workspace-cleanup scan/prune/removal-targets, sidebar visibility + snapshot prune, native-chat outbox, automations save, settings visibility sources, structured-agent-session launch) to createBrowserUuid().
  • shared/agent-status-observation.ts: createAgentStatusAuthorityId gets the same fallback inline (shared code cannot import the renderer lib).
  • New regression test in right-sidebar/ai-vault-session-refresh.test.ts that hides crypto.randomUUID and asserts a well-formed v4 request token is still minted.

Why

Plain-HTTP web clients (the default LAN setup for this app) are non-secure contexts. crypto.randomUUID is undefined there, so any panel minting a UUID at render time crashes. The renderer already shipped a fallback helper (renderer/lib/browser-uuid.ts) — the bug was raw call sites bypassing it.

Linked Issue

Fixes #20464

Visual Proof

N/A — behavior fix (crash on open → panel renders normally on plain HTTP LAN web client). Verified in a headless Chromium against the real served web client: before the fix the console captured TypeError: crypto.randomUUID is not a function and the boundary fallback; after the fix the panel renders and the console is clean.

Testing

  • Automated: ai-vault-session-refresh.test.ts 35/35 pass (incl. new non-secure-context regression); related suites (launch, outbox, visibility, skills, git-evidence, cleanup) 153 tests pass.

  • tsc --noEmit -p config/tsconfig.tc.web.json: clean.

  • Changed-code quality gate: 0 findings.

  • Manual: served build:web output, paired a headless Chromium via the real web client, opened repo start → right sidebar renders, no console errors.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

The LAN web client runs on plain HTTP (non-secure context), where browsers hide crypto.randomUUID. The right-sidebar Vault panel crashed at render ("The right sidebar hit an error") because a request token was minted with a raw crypto.randomUUID() call.

Migrate renderer call sites to the existing createBrowserUuid() helper (getRandomValues/Math.random fallback) and give the shared agent-status-observation sequencer the same fallback. Add a regression test minting a request token with crypto.randomUUID unavailable.
@coderabbitai

coderabbitai Bot commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: dc5d73bd-c431-493d-8da4-c7d80d346b90

📥 Commits

Reviewing files that changed from the base of the PR and between fe4237c and f20fbc3.

📒 Files selected for processing (22)
  • src/renderer/src/components/automations/automation-orca-save-operations.ts
  • src/renderer/src/components/native-chat/structured-agent-session-outbox-storage.ts
  • src/renderer/src/components/native-chat/use-structured-agent-session-outbox.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-refresh.test.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-refresh.ts
  • src/renderer/src/components/settings/GlobalWorktreeVisibilitySourcesSetting.tsx
  • src/renderer/src/components/sidebar/WorktreeVisibilityDialog.tsx
  • src/renderer/src/components/sidebar/worktree-snapshot-prune-batch.ts
  • src/renderer/src/components/skills/SkillBundleInstallFlow.tsx
  • src/renderer/src/components/skills/SkillInstallDialog.tsx
  • src/renderer/src/components/skills/SkillInstallManagementDialog.tsx
  • src/renderer/src/components/skills/use-skill-delete-flow.ts
  • src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-git-evidence.ts
  • src/renderer/src/components/workspace-cleanup/workspace-cleanup-snapshot-prune-batch.ts
  • src/renderer/src/lib/launch-structured-agent-session.ts
  • src/renderer/src/lib/non-secure-context-crypto.repro.test.ts
  • src/renderer/src/lib/structured-agent-session-launch-prompt.ts
  • src/renderer/src/store/slices/workspace-cleanup-removal-targets.ts
  • src/renderer/src/store/slices/workspace-cleanup-scan-lifecycle.ts
  • src/renderer/src/store/slices/workspace-cleanup.ts
  • src/renderer/src/store/slices/worktrees/teardown/removed-worktree-snapshot-prune.ts
  • src/shared/agent-status-observation.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

The change replaces direct crypto.randomUUID() calls with createBrowserUuid() across renderer operations that create IDs. Shared agent status IDs now use local fallback generation when browser UUID APIs are unavailable. Regression tests cover non-secure contexts where crypto.randomUUID is undefined.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to f20fb

The browser-safe UUID fallback changes are covered without a remaining actionable regression, so the change is ready to merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.74% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 22 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: using createBrowserUuid in non-secure contexts.
Description check ✅ Passed The description covers the problem, changes, rationale, linked issue, visual proof, testing, and required test checkboxes. Several template sections are omitted, but the core information is complete a…
Linked Issues check ✅ Passed The PR meets the coding requirements in #20464. The right-sidebar request token now uses createBrowserUuid(), and the regression test disables crypto.randomUUID and verifies a valid v4 `requestTok…
Out of Scope Changes check ✅ Passed The changes stay within #20464. The UUID call-site migrations, shared fallback, and regression tests directly prevent non-secure-context failures. No unrelated behavior or unrelated feature change is …
  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — a few minor suggestions inline.

Reviewed changes

  • Context-safe UUIDs at every remaining raw call site — the right-sidebar Vault request token (ai-vault-session-refresh.ts:94) plus ~18 other renderer sites now mint through the existing createBrowserUuid() fallback, which is what unblocks plain-HTTP LAN web clients (non-secure contexts hide crypto.randomUUID).
  • Shared sequencer fallback — createAgentStatusAuthorityId gains an inline createRandomUuid/bytesToUuid equivalent in src/shared/agent-status-observation.ts, since src/shared cannot import the renderer helper.
  • Regression coverage — an integration test in ai-vault-session-refresh.test.ts hides crypto.randomUUID and asserts a well-formed v4 request token is still minted, plus a shared-sequencer case in the existing non-secure-context repro test.

Verified independently: no unguarded crypto.randomUUID() calls remain in src/renderer (all leftovers use crypto?.randomUUID?.() ?? ...); the new regression test fails with TypeError: crypto.randomUUID is not a function when the fix is reverted; existing crypto.randomUUID spies still intercept (outbox + launch-prompt 18/18, shared sequencer 8/8, ai-vault 35/35); oxlint and the changed-code quality gate are clean.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏


// Why: the LAN web client runs on plain HTTP, where browsers hide
// crypto.randomUUID (secure-context-only). Fall back like browser-uuid.
function createRandomUuid(): string {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fallback duplicates src/renderer/src/lib/browser-uuid.ts almost verbatim, so the two implementations can drift apart. Since the renderer may import src/shared (but not the reverse), the canonical helper belongs in a shared module and browser-uuid.ts can re-export it — keeping the shared sequencer working without a second copy.

Technical details
# Deduplicate the UUID fallback

## Affected sites
- `src/shared/agent-status-observation.ts:203` — new `createRandomUuid` + `bytesToUuid`
- `src/renderer/src/lib/browser-uuid.ts:1` — existing `createBrowserUuid` + `bytesToUuid`

## Required outcome
- One implementation of the secure-context UUID fallback, importable from both `src/shared` and the renderer.

## Suggested approach
- Move `createBrowserUuid`/`bytesToUuid` into e.g. `src/shared/random-uuid.ts`.
- Have `src/renderer/src/lib/browser-uuid.ts` re-export it so the ~100 existing `@/lib/browser-uuid` call sites stay unchanged.
- Import the shared helper in `agent-status-observation.ts` and delete the local copy.

Comment on lines +829 to +831
if (randomUUIDDescriptor) {
Object.defineProperty(globalThis.crypto, 'randomUUID', randomUUIDDescriptor)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cleanup only restores randomUUID when a pre-existing own descriptor exists. In happy-dom (and Node) randomUUID lives on Crypto.prototype, so getOwnPropertyDescriptor(globalThis.crypto, 'randomUUID') is undefined and the value: undefined shadow installed above is never removed. Delete the own property in the else branch so a later test added to this file cannot inherit a hidden randomUUID.

Suggested change
if (randomUUIDDescriptor) {
Object.defineProperty(globalThis.crypto, 'randomUUID', randomUUIDDescriptor)
}
if (randomUUIDDescriptor) {
Object.defineProperty(globalThis.crypto, 'randomUUID', randomUUIDDescriptor)
} else {
delete (globalThis.crypto as { randomUUID?: unknown }).randomUUID
}

function storageKey(sessionId: string): string {
return `${OUTBOX_PREFIX}${encodeURIComponent(sessionId)}`
}
import { createBrowserUuid } from '@/lib/browser-uuid'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The import is inserted after a function declaration. It is legal (imports are hoisted) but inconsistent with the file's top import block, and the same mid-file insertion appears across roughly ten files in this PR: use-structured-agent-session-outbox.ts:26 (after an exported function), SkillBundleInstallFlow.tsx:31, GlobalWorktreeVisibilitySourcesSetting.tsx:27, use-skill-delete-flow.ts:38, use-workspace-cleanup-git-evidence.ts:17, launch-structured-agent-session.ts:30, structured-agent-session-launch-prompt.ts:21, workspace-cleanup-removal-targets.ts:52, workspace-cleanup.ts:32. Moving each into the existing import block would keep the diff style-consistent.

nwparker added a commit to mmarabel/orca that referenced this pull request Sep 25, 2026
…ndomUUID

The reported stack was the store chunk, not two named modules, so the repro test now
evaluates the store root under the stubbed non-secure crypto. Any new import-time
secure-context call anywhere in that graph fails here, not just the one this branch
removed.

Also ports the request-token regression from stablyai#20465, the one piece of coverage the
competing branches for this bug contributed that this one lacked. Both cases fail with
"randomUUID is not a function" when their production change is reverted.
@nwparker

Copy link
Copy Markdown
Contributor

Flagging overlap rather than closing: #22516 now covers this bug end to end — every crypto.randomUUID call site in src/renderer/src and src/shared, one shared generator instead of the per-site fallbacks, and an oxlint ratchet over both layers so a new call site cannot regress it. It also carries a before/after of the real web bundle on a non-secure origin.

The AI Vault request-token test from #20465 has been ported into #22516, so that coverage is not lost. A maintainer should close this in favour of #22516 unless it covers something #22516 misses — if it does, please say so on #22516.

nwparker added a commit that referenced this pull request Sep 25, 2026
…omUUID (#22516)

* fix(web): keep Remote Web loading over plain HTTP without crypto.randomUUID

Browsers hide crypto.randomUUID outside secure contexts, so Remote Web over
http://<lan-or-tailnet-ip> threw while importing the store and never painted.
createAgentStatusAuthorityId now takes its UUID source (renderer passes
createBrowserUuid, main passes node:crypto randomUUID), and the other
unguarded renderer calls go through createBrowserUuid.

* refactor(renderer): route remaining randomUUID fallbacks through createBrowserUuid

Replaces five hand-rolled crypto?.randomUUID?.() fallbacks (including a copy
of the browser-uuid fallback in mint-stable-pane-id) with createBrowserUuid,
and adds an oxlint no-restricted-properties rule so renderer code cannot call
randomUUID directly again.

* refactor(shared): move the non-secure-context UUID generator into src/shared

The white screen came from src/shared, so the fix belongs there. src/shared had
three hand-rolled copies of the same randomUUID-then-getRandomValues-then-Math.random
ladder (nested-repo-telemetry, project-groups, setup-agent-sequencing) because there
was nothing in that layer to import; createBrowserUuid lived one directory over in
the renderer.

createNonSecureContextUuid() now holds the single implementation, @/lib/browser-uuid
re-exports it under the renderer's existing name so no renderer import site changes,
and the three duplicates call it.

That also lets createAgentStatusAuthorityId go back to one argument. The injected
randomUuid source was justified as keeping browser APIs out of shared code, but this
generator is runtime-agnostic — it works unchanged in Node. Injecting it bought no
layering and made the safe choice a parameter every future caller had to get right,
unguarded: a caller could pass () => globalThis.crypto.randomUUID() and restore the
white screen with lint and tests green.

* fix(lint): ban crypto.randomUUID in src/shared and scope the escape hatch

vite.web.config.ts compiles src/shared straight into the web bundle, but the new
randomUUID ban only covered src/renderer/src — so the exact module that white-screened
the app sat outside the guard it shipped with, and the regression could come back with
a green lint. The override now covers src/shared/**/*.ts too; it costs zero diagnostics
because the duplicates it would have flagged are gone. `import { randomUUID } from
'node:crypto'` is untouched, so main-only shared modules keep working.

Both blanket "off" overrides are gone. no-restricted-properties is keyed by property
name, so the moment a second property joins the renderer block those overrides would
have silently exempted it — in the one file that is the escape hatch, and in every test
in the repo. Tests are where people copy patterns from, so they stay covered; the four
real uses carry line-scoped disables with a reason.

* fix(terminal): keep render-desync capture ids inside main's 120-char cap

createCaptureId builds `${Date.now()}-${panePart}-${nonce}`. A real paneKey is
`${tabId}:${leafId}` — two UUIDs, 73 chars after sanitizing — so with a 36-char UUID
nonce the id is 124 chars and main rejects it with 'Invalid render-desync capture id'.
persistHealedReference swallows that into console.error, so it shows up as diagnostics
that silently never appear.

This was already broken on the desktop app, where randomUUID is available; routing the
non-secure path through the same generator would have made it unconditional, including
on the plain-HTTP web client this branch exists to repair.

Bound the pane part rather than the nonce: keep the trailing 40 chars, which is the
whole leaf id (the identifying half, unique on its own) and drop the tab-id prefix, so
ids stay unique and traceable at 91 chars. The 120-char contract now lives in
src/shared next to the IPC args, imported by both sides, so the renderer cannot mint an
id main will reject without the test noticing.

* test(web): cover the whole store graph and the Vault token without randomUUID

The reported stack was the store chunk, not two named modules, so the repro test now
evaluates the store root under the stubbed non-secure crypto. Any new import-time
secure-context call anywhere in that graph fails here, not just the one this branch
removed.

Also ports the request-token regression from #20465, the one piece of coverage the
competing branches for this bug contributed that this one lacked. Both cases fail with
"randomUUID is not a function" when their production change is reverted.

* test(web): restore the real crypto.randomUUID after the non-secure Vault case

randomUUID lives on Crypto.prototype, so stubbing it as an own property of
globalThis.crypto left the restore branch with an undefined descriptor and a
leaked own `randomUUID: undefined`. Swap the whole crypto own property instead,
through one shared stub the repro suite already needed.

---------

Co-authored-by: Neil <[email protected]>
@nwparker

nwparker commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Closing as superseded by #22516, which is merged and present on main.

I checked this PR's scope and discussion against the merged implementation. The replacement explicitly supersedes this PR and covers its requested behavior. Thanks for the contribution; the branch is preserved.

@nwparker nwparker closed this Oct 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Web client: right sidebar crashes — crypto.randomUUID unavailable in non-secure (plain HTTP) contexts

2 participants