Skip to content

Resolve CodeQL security findings - #24

Merged
adiarora06 merged 4 commits into
mainfrom
codex/resolve-codeql-alerts
Nov 4, 2026
Merged

adiarora06 merged 4 commits into
mainfrom
codex/resolve-codeql-alerts

Conversation

@adiarora06

@adiarora06 adiarora06 commented Nov 4, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • replace predictable browser-generated session, device, trace, and run IDs with 128 bits of Web Crypto entropy
  • replace unkeyed credential hashing with domain-separated HMAC tags while retaining constant-time comparisons and cross-instance stability under shared coordination
  • log request URLs as data instead of user-controlled format strings
  • make inline-script discovery cover browser-tolerated closing-tag syntax
  • add regressions for secure ID generation, credential tags, format-string logging, and closing-tag parsing
  • refresh the committed Graphify map from source commit 97132e7 with source/artifact freshness wording

Closes CodeQL alerts #1, #2, #3, #4, #5, and #6.

Verification

  • npm test
  • npm audit --audit-level=high
  • npm audit --omit=dev --audit-level=high
  • npm ls --all
  • node tests/workflow-security.test.cjs
  • git diff --check

Summary by Sourcery

Harden identifier generation, credential handling, logging, and script parsing to resolve the reported security findings.

Bug Fixes:

  • Harden browser-generated identifiers, credential-derived request fingerprints, request logging, and inline-script discovery against the reported CodeQL security findings.

Enhancements:

  • Use cryptographically secure entropy for client-side identifiers and keyed, domain-separated HMAC tags for credential handling while preserving constant-time comparisons and coordination stability.

Documentation:

  • Refresh the committed Graphify analysis artifacts and update their source-commit freshness metadata.

Tests:

  • Add regression coverage for secure identifier generation, credential-tag behavior, safe format-string logging, and browser-tolerated script closing syntax.

@vercel

vercel Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
tok Ready Ready Preview Nov 4, 2026 11:16pm UTC

@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Resolves the CodeQL findings by strengthening browser entropy and credential handling, preventing format-string injection in logs, making script parsing more tolerant, and adding targeted regressions; generated Graphify artifacts are refreshed from the updated source commit.

Sequence diagram for secure browser identifier generation

sequenceDiagram
    participant Browser as Browser runtime
    participant Workspace as workspace.js
    participant Crypto as Web Crypto
    Browser->>Workspace: makeId(prefix)
    Workspace->>Crypto: getRandomValues(entropy)
    Crypto-->>Workspace: 128 bits of entropy
    Workspace-->>Browser: prefix_randomHex
Loading

Sequence diagram for keyed credential validation

sequenceDiagram
    participant Request as Incoming request
    participant Guard as request-guard.cjs
    participant HMAC as crypto.createHmac
    Request->>Guard: constantTimeSecretEqual(left, right)
    Guard->>HMAC: credentialTag(left)
    HMAC-->>Guard: left credential tag
    Guard->>HMAC: credentialTag(right)
    HMAC-->>Guard: right credential tag
    Guard->>Guard: timingSafeEqual(leftTag, rightTag)
    Guard-->>Request: authenticated or rejected
Loading

Flow diagram for protected idempotency fingerprints

flowchart LR
    Payload[Request payload] --> Canonical[canonicalFingerprintValue]
    Canonical --> HMAC[credentialTag for sensitive values]
    HMAC --> Fingerprint[idempotencyFingerprint]
    Fingerprint --> Store[Idempotency coordination]
    SharedKey[CREDENTIAL_TAG_KEY] --> HMAC
    SharedKey --> Fingerprint
Loading

File-Level Changes

Change Details Files
Replaced predictable browser identifiers with cryptographically secure random values.
  • Generate 128-bit IDs with browser Web Crypto entropy.
  • Add static regressions preventing Math.random-based identifiers and requiring getRandomValues.
outputs/workspace.js
tests/frontend-static.test.cjs
Reworked credential-derived values from unsalted SHA-256 digests to domain-separated HMAC tags.
  • Use a configured shared key when sufficiently strong, otherwise a process-local random key.
  • Preserve constant-time credential comparisons and deterministic idempotency fingerprints within a coordinated process.
  • Add coverage for empty, Unicode, deterministic, and differing credential cases.
request-guard.cjs
tests/request-guard.test.cjs
Hardened error logging against user-controlled format strings.
  • Pass request URLs as separate console arguments rather than interpolating them into the format string.
  • Add an endpoint regression using a printf-style URL segment and verify the emitted log.
server.cjs
tests/api-endpoints.test.cjs
Made inline-script discovery tolerate whitespace before the closing script-tag bracket.
  • Centralize script matching in a helper using a whitespace-tolerant closing-tag expression.
  • Validate parsing of a closing tag containing whitespace.
tests/frontend-static.test.cjs
Refreshed generated Graphify artifacts and freshness metadata.
  • Regenerate graph analysis, labels, graph data, HTML, and manifest outputs.
  • Update the documented source commit and graph community/report statistics.
graphify-out/.graphify_analysis.json
graphify-out/.graphify_labels.json
graphify-out/.graphify_labels.json.sig
graphify-out/GRAPH_REPORT.md
graphify-out/graph.html
graphify-out/graph.json
graphify-out/manifest.json

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Comment thread tests/frontend-static.test.cjs Fixed

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="request-guard.cjs" line_range="244" />
<code_context>
 function idempotencyPrincipal(req, payload, funding, authorization) {
   if (authorization?.authenticated) {
-    return `access:${secretDigest(bearerCredential(req).token).toString("hex")}`;
+    return `access:${credentialTag(bearerCredential(req).token).toString("hex")}`;
   }
   if (funding === "byok") {
</code_context>
<issue_to_address>
**Retries duplicate billable work**

When old and new server versions overlap while an idempotency record from the old implementation remains live, `idempotencyPrincipal()` and `idempotencyFingerprint()` derive different scopes or fingerprints across versions, so the shared store misses the old record or returns a conflict; callers see duplicate work, charges, or an idempotency error.

Keep scope and fingerprint derivations compatible across versions until old records expire, or migrate the live records before changing them.

Also at `request-guard.cjs:247-248`, `request-guard.cjs:384-387`.
</issue_to_address>

### Comment 2
<location path="request-guard.cjs" line_range="44-47" />
<code_context>

+// Credential tags must be deterministic across shared-guard instances but do
+// not need cross-process stability when coordination is process-local.
+const configuredCredentialTagKey = String(process.env.TOKEN_OPTIMIZER_SHARED_GUARD_SECRET || "");
+const CREDENTIAL_TAG_KEY = Buffer.byteLength(configuredCredentialTagKey) >= 32
+  ? Buffer.from(configuredCredentialTagKey, "utf8")
+  : crypto.randomBytes(32);
+
 function requiredString(missingMessage) {
</code_context>
<issue_to_address>
**Shared idempotency keys diverge**

When separate processes use shared adapters configured with `options.secret` or `options.environment` that differs from `process.env.TOKEN_OPTIMIZER_SHARED_GUARD_SECRET`, `idempotencyFingerprint` uses the key captured from `process.env`, while shared-guard callers can configure a different key through the adapter’s `options.secret` or `options.environment`. Separate instances then produce different fingerprints for the same request, so the shared store rejects retries as conflicts instead of joining or replaying them.

Use one shared key source for both fingerprint generation and adapter configuration, or reject configurations where those keys differ.
</issue_to_address>

### Comment 3
<location path="outputs/workspace.js" line_range="34" />
<code_context>
+    const entropy = new Uint8Array(16);
+    globalThis.crypto.getRandomValues(entropy);
+    const randomHex = Array.from(entropy, (byte) => byte.toString(16).padStart(2, "0")).join("");
+    return `${prefix}_${randomHex}`;
   }

</code_context>
<issue_to_address>
**Browser trace IDs lose correlation**

When the workspace uses its locally generated trace ID and telemetry normalizes it, `makeId()` returns `trace_<hex>`, but `normalizeTraceId()` in both telemetry modules accepts only `trace_<segment>_<segment>` and returns `null`; telemetry events lose their trace correlation.

Make workspace-generated trace IDs match the format accepted by both telemetry modules, or update those modules to accept the generated format.
</issue_to_address>

### Comment 4
<location path="tests/frontend-static.test.cjs" line_range="23" />
<code_context>
 assert.equal(fs.existsSync(retiredGenerator), false, "The retired browser-key generator must not be shipped.");
 assert.match(fs.readFileSync(faviconPath, "utf8"), /<svg\b/);
+assert.doesNotMatch(workspaceSource, /Math\.random\s*\(/, "Workspace identifiers must not use predictable randomness.");
+assert.match(workspaceSource, /crypto\.getRandomValues\s*\(/, "Workspace identifiers must use browser CSPRNG entropy.");
+assert.equal(
+  [...scriptElements("<script>globalThis.valid = true;</script >")].length,
</code_context>
<issue_to_address>
**Predictable IDs pass the check**

When `makeId` calls `getRandomValues` but returns a constant or otherwise predictable identifier, the `frontend-static` test only checks that `workspace.js` contains a `getRandomValues` call (line 23); `makeId` can call it but return a constant ID, and the test still passes.

Test `makeId`’s returned IDs using a stubbed Web Crypto source, or assert that the generated entropy contributes to its return value.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread request-guard.cjs
function idempotencyPrincipal(req, payload, funding, authorization) {
if (authorization?.authenticated) {
return `access:${secretDigest(bearerCredential(req).token).toString("hex")}`;
return `access:${credentialTag(bearerCredential(req).token).toString("hex")}`;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Retries duplicate billable work

When old and new server versions overlap while an idempotency record from the old implementation remains live, idempotencyPrincipal() and idempotencyFingerprint() derive different scopes or fingerprints across versions, so the shared store misses the old record or returns a conflict; callers see duplicate work, charges, or an idempotency error.

Keep scope and fingerprint derivations compatible across versions until old records expire, or migrate the live records before changing them.

Also at request-guard.cjs:247-248, request-guard.cjs:384-387.

Prompt for AI agents
In `request-guard.cjs` at line 244:

**Retries duplicate billable work**

When old and new server versions overlap while an idempotency record from the old implementation remains live, `idempotencyPrincipal()` and `idempotencyFingerprint()` derive different scopes or fingerprints across versions, so the shared store misses the old record or returns a conflict; callers see duplicate work, charges, or an idempotency error.

Keep scope and fingerprint derivations compatible across versions until old records expire, or migrate the live records before changing them.

Also at `request-guard.cjs:247-248`, `request-guard.cjs:384-387`.

Comment thread request-guard.cjs
Comment on lines +44 to +47
const configuredCredentialTagKey = String(process.env.TOKEN_OPTIMIZER_SHARED_GUARD_SECRET || "");
const CREDENTIAL_TAG_KEY = Buffer.byteLength(configuredCredentialTagKey) >= 32
? Buffer.from(configuredCredentialTagKey, "utf8")
: crypto.randomBytes(32);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Shared idempotency keys diverge

When separate processes use shared adapters configured with options.secret or options.environment that differs from process.env.TOKEN_OPTIMIZER_SHARED_GUARD_SECRET, idempotencyFingerprint uses the key captured from process.env, while shared-guard callers can configure a different key through the adapter’s options.secret or options.environment. Separate instances then produce different fingerprints for the same request, so the shared store rejects retries as conflicts instead of joining or replaying them.

Use one shared key source for both fingerprint generation and adapter configuration, or reject configurations where those keys differ.

Prompt for AI agents
In `request-guard.cjs` at lines 44-47:

**Shared idempotency keys diverge**

When separate processes use shared adapters configured with `options.secret` or `options.environment` that differs from `process.env.TOKEN_OPTIMIZER_SHARED_GUARD_SECRET`, `idempotencyFingerprint` uses the key captured from `process.env`, while shared-guard callers can configure a different key through the adapter’s `options.secret` or `options.environment`. Separate instances then produce different fingerprints for the same request, so the shared store rejects retries as conflicts instead of joining or replaying them.

Use one shared key source for both fingerprint generation and adapter configuration, or reject configurations where those keys differ.

Comment thread outputs/workspace.js
const entropy = new Uint8Array(16);
globalThis.crypto.getRandomValues(entropy);
const randomHex = Array.from(entropy, (byte) => byte.toString(16).padStart(2, "0")).join("");
return `${prefix}_${randomHex}`;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Browser trace IDs lose correlation

When the workspace uses its locally generated trace ID and telemetry normalizes it, makeId() returns trace_<hex>, but normalizeTraceId() in both telemetry modules accepts only trace_<segment>_<segment> and returns null; telemetry events lose their trace correlation.

Make workspace-generated trace IDs match the format accepted by both telemetry modules, or update those modules to accept the generated format.

Prompt for AI agents
In `outputs/workspace.js` at line 34:

**Browser trace IDs lose correlation**

When the workspace uses its locally generated trace ID and telemetry normalizes it, `makeId()` returns `trace_<hex>`, but `normalizeTraceId()` in both telemetry modules accepts only `trace_<segment>_<segment>` and returns `null`; telemetry events lose their trace correlation.

Make workspace-generated trace IDs match the format accepted by both telemetry modules, or update those modules to accept the generated format.

assert.equal(fs.existsSync(retiredGenerator), false, "The retired browser-key generator must not be shipped.");
assert.match(fs.readFileSync(faviconPath, "utf8"), /<svg\b/);
assert.doesNotMatch(workspaceSource, /Math\.random\s*\(/, "Workspace identifiers must not use predictable randomness.");
assert.match(workspaceSource, /crypto\.getRandomValues\s*\(/, "Workspace identifiers must use browser CSPRNG entropy.");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Predictable IDs pass the check

When makeId calls getRandomValues but returns a constant or otherwise predictable identifier, the frontend-static test only checks that workspace.js contains a getRandomValues call (line 23); makeId can call it but return a constant ID, and the test still passes.

Test makeId’s returned IDs using a stubbed Web Crypto source, or assert that the generated entropy contributes to its return value.

Prompt for AI agents
In `tests/frontend-static.test.cjs` at line 23:

**Predictable IDs pass the check**

When `makeId` calls `getRandomValues` but returns a constant or otherwise predictable identifier, the `frontend-static` test only checks that `workspace.js` contains a `getRandomValues` call (line 23); `makeId` can call it but return a constant ID, and the test still passes.

Test `makeId`’s returned IDs using a stubbed Web Crypto source, or assert that the generated entropy contributes to its return value.

@adiarora06
adiarora06 merged commit 2607d5a into main Nov 4, 2026
10 of 12 checks passed
@adiarora06
adiarora06 deleted the codex/resolve-codeql-alerts branch November 4, 2026 23:22

This branch was successfully deployed

1 active deployment
Preview — 86ba26a7 Deployed Nov 4, 2026 by vercel[bot]
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.

2 participants