Skip to content

feat(mobile-web-bundle): manifest and RPC contract for the desktop-served mobile web bundle (OTA phase A, 1/5) - #21325

Merged
Jinwoo-H merged 11 commits into
mainfrom
ota-a1-contract
Sep 18, 2026
Merged

Jinwoo-H merged 11 commits into
mainfrom
ota-a1-contract

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

What this is

First of five PRs for Phase A of the mobile OTA work: the desktop builds a content-addressed mobile web bundle with each release and serves it to a paired phone behind a new capability, so a future thin native shell can update its UI whenever the desktop does. Phase A changes nothing a released phone calls; old phones keep the native UI over unchanged RPCs.

This PR is pure vocabulary: three modules under src/shared/mobile-web-bundle/ and their tests. No host wiring, no build step, no mobile files, no wire change. Runtime-neutral: no node: imports, so the phone can value-import the schemas and verify a buildId itself in Phase B.

Contract

  • manifest-contract.ts: the manifest schema (schemaVersion 1, buildId, desktopVersion, the protocol window minCompatibleRuntimeProtocolVersion/runtimeProtocolVersion recorded now so a future update wall can judge a cached bundle without re-cutting it, entrypoint, totalBytes, sorted assets[{ path, sha256, byteLength, contentType }]), the canonical serializer and computeMobileWebBundleId (pure-JS sha256 over the sorted asset list, so buildId is a pure function of content), and the permanent ceilings (256 assets, 32 MiB total, 10 MiB per asset). Invariants beyond the field list, each tested: totalBytes equals the sum of asset lengths; paths strictly ascending in code-unit order; no two paths fold to the same name (macOS/Windows collisions); no ./../trailing-dot/Windows-reserved segments; the entrypoint is a listed asset; the protocol window is not inverted; buildId equals the recomputed id (a stale id is a parse failure); the hash only runs once every cheaper invariant passed. contentType is lowercase with one canonical ; charset= spelling so identical bytes cannot get two ids. The manifest is closed (.strict() + literal schemaVersion): any change is a version bump, and Phase B must read an unknown version as a bundle to re-fetch, never a crash.
  • bundle-rpc-contract.ts: MOBILE_WEB_BUNDLE_CHUNK_BYTES (48 KiB: fits the 1 MiB frame ceiling after base64 and E2EE base64 expansion with an order of magnitude of headroom), the method names mobileWeb.bundle.manifest and mobileWeb.bundle.chunk, params and result schemas (the chunk reply echoes buildId/path/offset so out-of-order reassembly cannot misplace a chunk; assetByteLength and sha256 describe the whole asset so any single chunk is self-describing; dataBase64 is length-bounded with the skill-upload arithmetic; chunkBytes in the manifest reply is capped at the constant, shrink-only; offset alignment is deliberately a host-side check against the advertised chunk size), and the six stable error codes as a closed union pinned with hostUnionArms.
  • mobile-web-bundle-capability.ts: the mobileWeb.bundle.v1 constant alone, import-free, so protocol-version.ts can name it in a later PR without pulling zod onto the phone's capability path.

Reuse: the serializer follows computeSkillPackageDigest's idiom; the path rules follow skill-package-manifest.ts.

Review

Round 1: ship after fixes, applied: node:crypto replaced by the repo's pure-JS sha256 (digest parity checked at the padding boundaries and at 18 sizes against node:crypto), the buildId recompute refinement, lowercase content types, the capability constant split out, and the assetByteLength rename. Round 2 (fresh): ship after fixes, applied: case-fold collisions and Windows-reserved segments rejected, one canonical charset spelling, early return before the hash (mutation-checked), the closed-manifest doc. Round 2 also confirmed TextEncoder is available on Hermes empirically (mobile-e2ee-v2-client-session.ts:98) and that a 256-asset manifest at the ceilings parses in about 1 ms.

Gates

Root tsc (config/tsconfig.node.json) 0 · vitest 2 files, 44 passed · oxfmt and oxlint clean · changed-code quality 0 findings across 5 files · git diff -- mobile empty.

Design: /tmp/step2-parallel/phase-a-design.md; tracking docs/reference/plans/mobile-ota-phase-a.local.md (untracked).

…sed build id

The schema every later Phase A lane parses against: the ceilings that bound host
memory (256 assets, 32 MiB total, 10 MiB per asset), and a build id that is a
pure function of content so a client can use it as a cache key unconditionally.

The serializer sorts its input rather than trusting the caller, so a producer
that emits assets in any order still lands on the same id.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
Method names, capability name, the 48 KiB chunk size, params/result schemas for
both methods, and the six error codes as a closed union pinned by a coverage
record. Constants and data only; the host wiring and the capability push land in
later lanes.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
@coderabbitai

coderabbitai Bot commented Sep 18, 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: 9f7ac8c0-90e5-48b7-8109-2f2026338023

📥 Commits

Reviewing files that changed from the base of the PR and between eb4b67d and 9099126.

📒 Files selected for processing (2)
  • src/shared/mobile-web-bundle/manifest-contract.test.ts
  • src/shared/mobile-web-bundle/manifest-contract.ts

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


📝 Walkthrough

Walkthrough

Adds a content-addressed mobile web bundle manifest contract. It validates asset paths, hashes, sizes, content types, manifest limits, ordering, totals, entrypoints, and protocol versions. It adds deterministic asset serialization and bundle ID computation. A related RPC contract defines wire constants, error codes, manifest messages, chunk messages, size limits, a negotiated capability, and inferred types. New tests cover the manifest and RPC validation rules.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to 90991

Chunk responses can pass validation despite malformed Base64 or exceeding the declared chunk size. This is a bounded contract risk before consumers are wired.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the scope, contract, rationale, testing, and reported gates. However, it omits several required template sections, including a linked issue, explicit visual proof or N/A state… Add all missing template sections. Provide a valid issue reference after Fixes #, state N/A with a reason for visual proof, complete the testing checklist and list tested platforms, complete the AI disclosure when applicable, address th…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change: the mobile web bundle manifest and RPC contract for OTA Phase A. It is specific and related to the changeset.
Full details: Description check

Explanation

The description explains the scope, contract, rationale, testing, and reported gates. However, it omits several required template sections, including a linked issue, explicit visual proof or N/A statement, the testing checklist with platforms, AI disclosure, agent boundary, notes, and the final checklist.

Resolution

Add all missing template sections. Provide a valid issue reference after Fixes #, state N/A with a reason for visual proof, complete the testing checklist and list tested platforms, complete the AI disclosure when applicable, address the agent skill boundary, add notes for security and compatibility, and complete the final checklist.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 150f0282-6247-42f9-a3dc-1f64afc3bdc6

📥 Commits

Reviewing files that changed from the base of the PR and between 27bddc6 and dc4b660.

📒 Files selected for processing (4)
  • src/shared/mobile-web-bundle/bundle-rpc-contract.test.ts
  • src/shared/mobile-web-bundle/bundle-rpc-contract.ts
  • src/shared/mobile-web-bundle/manifest-contract.test.ts
  • src/shared/mobile-web-bundle/manifest-contract.ts

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

/** The whole asset's length and hash, not this chunk's, so a reassembler needs no second index. */
byteLength: z.number().int().nonnegative().max(MOBILE_WEB_BUNDLE_MAX_ASSET_BYTES),
sha256: z.string().regex(SHA256_PATTERN),
dataBase64: z.string().max(MAX_DATA_BASE64_LENGTH),

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,100p' src/shared/mobile-web-bundle/bundle-rpc-contract.ts
sed -n '110,195p' src/shared/mobile-web-bundle/bundle-rpc-contract.test.ts
rg -n '"zod"|from .zod.|\.base64\(|z\.base64' package.json yarn.lock pnpm-lock.yaml package-lock.json src --glob '!**/node_modules/**'

Repository: stablyai/orca

Length of output: 25503


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- root metadata ---'
find . -maxdepth 1 -type f -printf '%f\n' | sort
printf '%s\n' '--- package manager declarations ---'
sed -n '175,210p' package.json
for f in pnpm-lock.yaml package-lock.json yarn.lock bun.lockb; do
  if [ -f "$f" ]; then
    printf '%s\n' "--- $f zod entries ---"
    rg -n -A4 -B2 '(^|[ /])zod([@:/]|$)|zod:' "$f" | head -80
  fi
done
printf '%s\n' '--- chunk schema references and consumers ---'
rg -n -C3 'MobileWebBundleChunkResultSchema|dataBase64|MOBILE_WEB_BUNDLE_CHUNK_BYTES|MAX_DATA_BASE64_LENGTH' src/shared/mobile-web-bundle src/main src/renderer --glob '*.ts' --glob '*.tsx'
printf '%s\n' '--- base64-related repository contracts ---'
rg -n -C3 'Buffer\.from\([^)]*base64|atob|fromBase64|base64.*decode|decode.*base64|byteLength.*dataBase64|dataBase64.*byteLength' src --glob '*.ts' --glob '*.tsx'

Repository: stablyai/orca

Length of output: 50370


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/architecture /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 47550


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- root metadata ---'
find . -maxdepth 1 -type f -printf '%f\n' | sort
printf '%s\n' '--- package manager and zod version ---'
sed -n '175,210p' package.json
if [ -f pnpm-lock.yaml ]; then rg -n -A5 -B2 '(^|[ /])zod([@:/]|$)|zod:' pnpm-lock.yaml | head -100; fi
if [ -f package-lock.json ]; then rg -n -A5 -B2 '"zod"' package-lock.json | head -100; fi
if [ -f yarn.lock ]; then rg -n -A5 -B2 '^zod@' yarn.lock | head -100; fi
printf '%s\n' '--- chunk schema references and consumers ---'
rg -n -C4 'MobileWebBundleChunkResultSchema|dataBase64|MOBILE_WEB_BUNDLE_CHUNK_BYTES|MAX_DATA_BASE64_LENGTH' src --glob '*.ts' --glob '*.tsx'
printf '%s\n' '--- Base64 decoding and host-limit references ---'
rg -n -C4 'Buffer\.from|atob|fromBase64|base64.*decode|decode.*base64|read.*chunk|chunkBytes|readLimited|MOBILE_WEB_BUNDLE_CHUNK' src --glob '*.ts' --glob '*.tsx'

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

set -e
rg -n -C4 'MobileWebBundleChunkResultSchema|dataBase64|MOBILE_WEB_BUNDLE_CHUNK_BYTES|chunkBytes|readLimited|Buffer\.from|atob' src --glob '*.ts' --glob '*.tsx'
printf '%s\n' '--- package metadata ---'
sed -n '190,202p' package.json
find . -maxdepth 1 -type f \( -name '*lock*' -o -name 'pnpm-workspace.yaml' \) -print

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- exact mobile-web-bundle files ---'
git ls-files '*mobile-web-bundle*'
printf '%s\n' '--- exact mobile bundle symbols and methods ---'
rg -n -C5 'MobileWebBundle|mobileWeb\.bundle|mobile_web_bundle|MOBILE_WEB_BUNDLE' src --glob '*.ts' --glob '*.tsx' --glob '!**/*.test.ts' --glob '!**/*.spec.ts'
printf '%s\n' '--- focused tests and nearby host-boundary code ---'
sed -n '1,230p' src/shared/mobile-web-bundle/bundle-rpc-contract.test.ts
rg -n -C6 'readFileRange|readFile|Buffer\.from\(.*dataBase64|dataBase64.*Buffer|chunk.*byte|byte.*chunk' src/main/runtime src/main/ipc src/shared/mobile-web-bundle --glob '*.ts' --glob '!**/*.test.ts'

Repository: stablyai/orca

Length of output: 50370


🌐 Web query:

Zod 4.5.4 z.base64 API documentation validation padding alphabet

💡 Result:

<search_synthesis>
In Zod (including version 4.5.4), the z.base64() API is used to validate that a string is a valid base64-encoded string [1][2][3]. ### Validation Behavior * Strictness: z.base64() is designed to be strict [4]. Internally, it validates inputs using a combination of checks to ensure the string conforms to canonical base64 specifications [5][4]. * Padding: The validator expects valid base64 padding (the = characters) where required by the base64 encoding rules [6]. * Alphabet: It adheres to the standard base64 alphabet (A-Z, a-z, 0-9, +, /) [6]. * Whitespace: Recent updates have reinforced that z.base64() rejects strings containing whitespace (including spaces, tabs, and newlines), closing previous vulnerabilities where internal parsing mechanisms like atob() would silently strip whitespace and potentially allow invalid inputs [5][4]. * Empty Strings: Consistent with RFC 4648, an empty string is considered valid [7]. ### Comparison with z.base64url() While z.base64() expects standard base64 encoding with padding [3][8], z.base64url() is used for URL-safe base64 encoding, which uses a different alphabet (- and _ instead of + and /) and typically does not include padding [1][3]. ### Implementation Details For performance and reliability, Zod&#39;s internal validation for z.base64() has evolved from relying on complex regular expressions (which could cause stack overflow errors on very large strings) to using a more efficient check that includes an explicit whitespace rejection (/\s/.test(data)) followed by a standard atob()-based verification [5][4][6]. For scenarios requiring conversion between base64 strings and Uint8Array byte arrays, Zod provides z.codec utilities like base64ToBytes and base64urlToBytes [9].
</search_synthesis>

<source_evidence>

<title>Defining schemas | Zod</title> https://zod.dev/api Copy Text ``` z.email(); z.uuid(); z.url(); z.httpUrl(); // http or https URLs only z.hostname(); z.e164(); // E.164 phone numbers z.emoji(); // validates a single emoji character z.base64(); z.base64url(); z.hex(); z.jwt(); z.nanoid(); z.cuid(); z.cuid2(); z.ulid(); z.ipv4(); z.ipv6(); z.mac(); z.cidrv4(); // ipv4 CIDR block z.cidrv6(); // ipv6 CIDR block z.creditCard(); // credit card number (Luhn checksum) z.hash("sha256"); // or "sha1", "sha384", "sha512", "md5" z.iso.date(); z.iso.time(); z.iso.datetime(); z.iso.duration(); ``` ... By default, `z.hash()` expects hexadecimal encoding, as is conventional. You can specify a different encoding with the `enc` parameter: ... Copy Text ``` z.hash("sha256", { enc: "hex" }); // default z.hash("sha256", { enc: "base64" }); // base64 encoding z.hash("sha256", { enc: "base64url" }); // base64url encoding (no padding) ``` <title>Defining schemas | Zod</title> https://zod.dev/api?id=zod-enums Copy Text ``` z.email(); z.uuid(); z.url(); z.httpUrl(); // http or https URLs only z.hostname(); z.e164(); // E.164 phone numbers z.emoji(); // validates a single emoji character z.base64(); z.base64url(); z.hex(); z.jwt(); z.nanoid(); z.cuid(); z.cuid2(); z.ulid(); z.ipv4(); z.ipv6(); z.mac(); z.cidrv4(); // ipv4 CIDR block z.cidrv6(); // ipv6 CIDR block z.creditCard(); // credit card number (Luhn checksum) z.currencyCode(); // ISO 4217 currency code z.iban(); // IBAN (ISO 7064 mod-97 checksum) z.hash("sha256"); // or "sha1", "sha384", "sha512", "md5" z.iso.date(); z.iso.time(); z.iso.datetime(); z.iso.duration(); ``` ... By default, `z.hash()` expects hexadecimal encoding, as is conventional. You can specify a different encoding with the `enc` parameter: ... ``` z.hash("sha256", { enc: "hex" }); // default z.hash("sha256", { enc: "base64" }); // base64 encoding z.hash("sha256", { enc: "base64url" }); // base64url encoding (no padding) ``` <title>packages/docs/content/api.mdx</title> https://github.com/colinhacks/zod/blob/c7805073/packages/docs/content/api.mdx ## String formats ... To validate against some common string formats: ```ts z.email(); z.uuid(); z.url(); z.httpUrl(); // http or https URLs only z.hostname(); z.emoji(); // validates a single emoji character z.base64(); z.base64url(); z.hex(); z.jwt(); z.nanoid(); z.cuid(); z.cuid2(); z.ulid(); z.ipv4(); z.ipv6(); z.mac(); z.cidrv4(); // ipv4 CIDR block z.cidrv6(); // ipv6 CIDR block z.hash("sha256"); // or "sha1", "sha384", "sha512", "md5" z.iso.date(); z.iso.time(); z.iso.datetime(); z.iso.duration(); ``` ... By default, `z.hash()` expects hexadecimal encoding, as is conventional. You can specify a different encoding with the `enc` parameter: ```ts z.hash("sha256", { enc: "hex" }); // default z.hash("sha256", { enc: "base64" }); // base64 encoding z.hash("sha256", { enc: "base64url" }); // base64url encoding (no padding) ``` | Algorithm / Encoding | `"hex"` | `"base64"` | `"base64url"` | |-----------|-----------|--------------|-----------------| | `"md5"` | 32 | 24 (22 + "==") | 22 | | `"sha1"` | 40 | 28 (27 + "=") | 27 | | `"sha256"`| 64 | 44 (43 + "=") | 43 | | `"sha384"`| 96 | 64 (no padding)| 64 | | `"sha512"`| 128 | 88 (86 + "==") | 86 | <title>fix(v4): reject whitespace in z.base64() to close atob bypass</title> GitHub pull request 5888 in colinhacks/zod (link omitted to avoid creating a cross-reference) # fix(v4): reject whitespace in z.base64() to close atob bypass - State: merged - Author: colinhacks - Created: 2026-04-28T16:53:24Z - Updated: 2026-04-30T16:15:14Z - Repository: colinhacks/zod - Number: `#5888` - +17 -0 in 3 files - Merged: 2026-04-28T17:05:01Z - Merge commit: 584b1089e1fc7bfcc97797576eff8da85bcdf031 --- ## Summary Closes the whitespace bypass in `isValidBase64()` raised in `#5865`. `atob()` strips ASCII whitespace before decoding, which lets strings like `"123 "` (length 4, mod-4 passes, `atob` strips and parses `"123"`) sneak past the existing length check. Fix: reject whitespace explicitly before the length check so the runtime matches the strict regex we already advertise via `bag.patterns` / `contentEncoding`. ## Why not just enforce `regexes.base64` at runtime? That&`#39`;s what the validator originally did. It was replaced with the `atob`-based check specifically for perf on large inputs in `#4386` (commit `ec7c89d9`), which also added the `big base64 and base64url` regression test in `packages/zod/src/v4/classic/tests/string.test.ts` that round-trips 10MB through `z.base64().parse()`. The `/\s/.test()` short-circuit is a single deterministic linear scan with no backtracking, so it fits inside that perf envelope without reintroducing the regex. ## Why keep the strict default at all? Discussed in detail at https://github.com/colinhacks/zod/pull/5865#issuecomment-4337242184. Short version: zod&`#39`;s string formats are strict by default, the unpadded base64url niche is already served by `z.base64url()` / `z.jwt()`, and strict-vs-lenient is asymmetric — strict can be loosened later via opt-in (`z.base64({ padding: "optional" })`) non-breakingly, while lenient cannot be tightened without a breaking change. ## Test plan - [x] `pnpm vitest run packages/zod/src/v4/classic/tests/string.test.ts -t "base64"` — passes - [x] `pnpm vitest run packages/zod/src/v4` — 2640 tests passing - [x] Full `pnpm vitest run` (via pre-push hook) — 3689 tests passing, no type errors - [x] New invalid cases added in `packages/zod/src/v4/classic/tests/string.test.ts` covering the bypass (`"123 "`) plus leading/trailing/internal space, newline, and tab - [x] Mini parity in `packages/zod/src/v4/mini/tests/string.test.ts` Refs `#5865`. ## Timeline - someone committed **pullfrog[bot]** commented on 2026-04-28T16:54:46Z: > TL;DR — Fixes a whitespace bypass in `z.base64()` where `atob()`&`#39`;s internal whitespace-stripping let inputs like `"123 "` pass validation despite not being canonical Base64 (RFC 4648 §3.3). A single `/\s/.test()` guard in `isValidBase64()` rejects whitespace up front, preserving the perf-oriented `atob` path introduced in `#4386`. > > ### Key changes > > - **Reject whitespace in `isValidBase64()`** — Adds a `/\s/.test(data)` short-circuit before the length check so whitespace-containing strings are rejected before reaching `atob()`. > - **Classic test coverage for whitespace bypass** — Adds 6 invalid-input cases covering trailing, leading, and internal whitespace (space, newline, tab) plus the original `"123 "` bypass. > - **Mini test parity** — Mirrors 4 whitespace rejection cases in the mini string tests. > > Summary | 3 files | 1 commit | base: `main` ← `base64-whitespace` > > > > > **Before:** `isValidBase64()` relied on `atob()` after a length-mod-4 check — `atob()` silently strips ASCII whitespace before decoding, so inputs like `"123 "` (length 4, mod-4 passes) were accepted as valid Base64. **After:** A `/\s/.test(data)` guard rejects any string containing whitespace before the length check runs, closing the bypass without reintroducing the regex that was removed for performance in `#4386`. > > The fix is a single linear scan (`/\s/.test()`) that runs before the existing `atob` path. This keeps the `O(n)` perf profile for large inputs while enforcing the strict canonical encoding tha…[truncated] <title>base64 native parser only · Issue `#5865` · colinhacks/zod</title> GitHub issue 5865 in colinhacks/zod (link omitted to avoid creating a cross-reference) > **Review (commented):** > > > [!IMPORTANT] > > This PR relaxes base64 validation in ways that go beyond just removing the padding requirement — it also makes whitespace-containing strings valid, which is a significant behavioral change. > > ### Summary > > The core change removes the `data.length % 4 !== 0` guard from `isValidBase64` and relies entirely on `atob()`. The PR author&`#39`;s argument that the previous length check didn&`#39`;t actually enforce padding correctly (due to `atob` ignoring whitespace) is valid — the old check was inconsistent. > > However, delegating entirely to `atob` introduces a different problem: `atob` silently strips ASCII whitespace (space, tab, newline, form feed, carriage return). This means `z.string().base64()` would now accept strings like `"SGVs bG8g V29ybGQ"` or `"SGVsbG8\ngV29ybGQ\n"` as valid base64. Most base64 specifications (RFC 4648) do not permit embedded whitespace in the encoded output, and most interop scenarios would not expect a "base64 validator" to accept such strings. > > The right fix likely involves either: > > 1. A regex pre-check against the base64 alphabet (like `isValidBase64URL` already does with `regexes.base64url`), followed by an `atob` call for structural validation. > 2. Stripping whitespace before the length check, which preserves padding enforcement while fixing the original inconsistency. > > Unrelated trailing-whitespace cleanup in the JIT code should be in a separate commit. > ... Task list (4/4 completed)** ... x] Read ... Investigate impact of relaxing base64 ... ) > - [x] Check for ... > - [x] Submit review ... > > _Comment written with AI assistance._ ... > Thanks for digging into this. Going ... worth getting on the record ... ## Standards landscape ... > > | Spec / API | Padding behavior | > | --- | --- | ... > | RFC 4648 §3.2 (the base64 spec) | Implementations **MUST** include padding by default when emitting. Unpadded is allowed only when "the spec referring to the encoding" explicitly says so. | > | RFC 4648 §3.3 | Implementations SHOULD reject non-alphabet characters (including whitespace) unless the referring spec says otherwise. | ... Padded, ... broken every 76 chars. Used by email and ... > | RFC 7515 / 7519 (JWS / JWT) | base64url **without** padding. Already covered by `z.base64url()` / `z.jwt()`. | ... > | `atob()` | Strips ASCII whitespace, accepts unpadded, lenient about trailing chars. | > | `Buffer.from(s, "base64")` | Extremely lenient — silently truncates on invalid chars, accepts whitespace, accepts unpadded. | > | `Uint8Array.fromBase64()` (Stage 4, baseline 2024) | Explicit `{ lastChunkHandling: "loose" \ | "strict" \ | "stop-before-partial" }`. The platform itself acknowledges both modes are legitimate and forces the caller to pick. | > > The directional signal: the spec says padded is canonical, and the newest platform API (`Uint8Array.fromBase64`) treats padded-vs-unpadded as a *deliberate choice the caller has to make*. That&`#39`;s the position a validator should take. ... > > The notable thing about this column: every common unpadded use case is already served by a different zod validator. The remaining "want unpadded standard-alphabet base64" niche is small, and the workaround is one line: ... > > ```ts > z.string().transform(s => s.padEnd(Math.ceil(s.length / 4) * 4, "=")).pipe(z.base64()) > ``` > > …or a future opt-in like `z.base64({ padding: "optional" })` if demand materializes. ... > > ## Cross-validator consistency inside zod ... > > | Validator | Today&`#39`;s behavior | > | --- | --- | > | `z.base64()` | Strict regex (advertised via `bag.patterns` / `contentEncoding`); lenient runtime. **Inconsistent today.** | > | `z.base64url()` | Strict — disall…[truncated]

Citations:


🏁 Script executed:

set -e
git ls-files '*mobile-web-bundle*'
rg -n -C5 'MobileWebBundle|mobileWeb\.bundle|mobile_web_bundle|MOBILE_WEB_BUNDLE' src --glob '*.ts' --glob '*.tsx' --glob '!**/*.test.ts' --glob '!**/*.spec.ts'
sed -n '145,180p' src/shared/mobile-web-bundle/bundle-rpc-contract.test.ts

Repository: stablyai/orca

Length of output: 19459


Validate dataBase64 as Base64.

The schema accepts any string up to 65,544 characters, including malformed values such as !, A, and AAAA . Zod 4.5.4 provides z.base64() for this contract.

Keep the + 8 allowance. The tests define that slack for the later host boundary to enforce the negotiated chunk size. The current bound admits canonical Base64 payloads up to 49,158 bytes, while the host must enforce the 48 KiB or smaller advertised limit.

Proposed fix
-    dataBase64: z.string().max(MAX_DATA_BASE64_LENGTH),
+    dataBase64: z.base64().max(MAX_DATA_BASE64_LENGTH),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
dataBase64: z.string().max(MAX_DATA_BASE64_LENGTH),
dataBase64: z.base64().max(MAX_DATA_BASE64_LENGTH),

Metro ships no Node core shims, so a value import from these modules would fail
to bundle on the phone. The pure-JS sha256 keeps both contract modules
runtime-neutral, which also lets a cached manifest be re-verified on device.

Verified digest parity against node:crypto across the 55/56/64-byte padding
boundaries before the swap.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
…ntent hash

A stale id passed every other check and would then serve the wrong bytes under a
cache key the client already trusts. Runs last of the invariants because it is
the only one that hashes.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
The pattern carried an `i` flag over lowercase character classes, so the same
bytes described as `Text/HTML` and `text/html` produced two different build ids.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
…odule

A4 wires this constant into protocol-version.ts, which the phone reads on the
capability path. Leaving it in the schema module would have dragged zod along
with it.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
…ength

It is the whole asset's length, not the chunk's, and sitting beside dataBase64
under the old name it read as the chunk's. Both are non-negative integers, so a
producer that emitted the wrong one would only surface at the final hash check.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

@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.

Important

The shared contract imports node:crypto, which the React Native/Hermes mobile bundle cannot resolve, and the repo already ships a pure-JS sha256 for exactly this boundary. One inline comment below, plus a question about buildId verification.

Reviewed changes

  • Manifest contract — manifest-contract.ts defines the schema, the canonical serializer, the content-addressed buildId, the permanent ceilings, and the four superRefine invariants.
  • Bundle RPC contract — bundle-rpc-contract.ts defines the 48 KiB chunk size, the two method names, the capability constant, the params/result schemas, and the six closed error codes.
  • Tests — 32 unit tests across the two files pin the ceilings, the invariants, the asset-path rules, and the base64 bound.

ℹ️ Nitpicks

  • bundle-rpc-contract.ts:19-20 re-declares SHA256_PATTERN and MAX_DATA_BASE64_LENGTH that manifest-contract.ts already owns; export them from one module so the two bounds cannot drift.
  • bundle-rpc-contract.ts:9-10 justifies 48 KiB against a "1 MiB frame ceiling" that no constant in the repo matches — MAX_MESSAGE_SIZE is 16 MiB, REMOTE_RUNTIME_MAX_WEBSOCKET_FRAME_BYTES is 8 MiB + 64, and MAX_E2EE_TEXT_PLAINTEXT_BYTES is 4 MiB. The chosen value is safe either way; the cited ceiling just needs reconciling.

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

@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 new issues found.

Reviewed changes

Reviewed the five commits landed since the prior pullfrog review (dc4b660 → eb4b67d). Both prior findings are fixed and the new changes are clean.

  • Pure-JS build id — computeMobileWebBundleId now hashes through src/shared/sha256.ts with TextEncoder plus hex encoding, dropping the node:crypto import so the contract can load in the mobile bundle.
  • buildId content verification — validateManifestInvariants now rejects a manifest whose buildId is not computeMobileWebBundleId(assets), pinned by a stale-id test.
  • Lowercase content types — CONTENT_TYPE_PATTERN drops the i flag, so case variants cannot give the same bytes two ids.
  • Zod-free capability module — MOBILE_WEB_BUNDLE_CAPABILITY moved to mobile-web-bundle-capability.ts so the phone's capability path does not pull a schema library.
  • Chunk field rename — the chunk reply's whole-asset length is now assetByteLength, distinct from the chunk body.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…hat fold together

Two paths differing only in case are one file on macOS and Windows, so the host
would serve the same bytes under two entries and one of the two hashes could
never match. Windows-reserved segment names and trailing dots cannot be written
to the bundle root at all.

Both follow skill-package-manifest's checks, the folded-path Set and the
reserved-segment pattern.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
…t type

The optional space in `; ?charset=` let the same bytes carry two content types
and therefore two build ids. Pinned to the single-space form the bundle builder
emits.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
…already rejected

zod runs superRefine even after the asset-array ceiling has failed, so a 257
asset manifest was still sorted and hashed. Each invariant now returns on its
own issue and the count is checked first, which is what the comment claimed.

The tests read the issue paths: an oversized or otherwise invalid manifest with
a deliberately wrong buildId reports no buildId issue, while the same wrong id
inside the ceiling does.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
`.strict()` plus a literal schemaVersion closes the shape completely, so the
version bump is the only way to change it. The phone value-imports this schema,
so Phase B must read an unrecognised schemaVersion as a bundle to re-fetch
rather than as a parse crash.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

@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 new issues found.

Reviewed changes

Reviewed the four commits landed since the prior pullfrog review (eb4b67d → 9099126). Both earlier threads are resolved and the new validation is clean.

  • Portable asset paths — MobileWebBundleAssetPathSchema now rejects Windows-reserved names and trailing-dot segments through isPortableAssetSegment, reusing the exact WINDOWS_RESERVED_SEGMENT regex from skill-package-manifest.ts.
  • Case-fold collision rejection — validateManifestInvariants rejects two paths that fold to the same name, since they are one file on macOS and Windows.
  • One canonical charset spelling — CONTENT_TYPE_PATTERN now requires the single-space ; charset= form, so the same bytes cannot hash under two ids.
  • Hash short-circuit — the refinement returns after the array ceiling, totalBytes, entrypoint, and protocol-window checks, so the content hash runs only once every cheaper invariant passed; the new refinement short-circuit tests pin each path.
  • Closed-manifest doc — a JSDoc note that .strict() plus the literal schemaVersion leave no additive path, so an unknown version must be re-fetched rather than crashed on.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit f2ca3cb into main Sep 18, 2026
28 checks passed
@Jinwoo-H
Jinwoo-H deleted the ota-a1-contract branch September 18, 2026 02:08
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…rved mobile web bundle (OTA phase A, 1/5) (stablyai#21325)

* feat(mobile-web-bundle): add the manifest contract and content-addressed build id

The schema every later Phase A lane parses against: the ceilings that bound host
memory (256 assets, 32 MiB total, 10 MiB per asset), and a build id that is a
pure function of content so a client can use it as a cache key unconditionally.

The serializer sorts its input rather than trusting the caller, so a producer
that emits assets in any order still lands on the same id.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* feat(mobile-web-bundle): add the bundle RPC payload contract

Method names, capability name, the 48 KiB chunk size, params/result schemas for
both methods, and the six error codes as a closed union pinned by a coverage
record. Constants and data only; the host wiring and the capability push land in
later lanes.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(mobile-web-bundle): hash the build id without node:crypto

Metro ships no Node core shims, so a value import from these modules would fail
to bundle on the phone. The pure-JS sha256 keeps both contract modules
runtime-neutral, which also lets a cached manifest be re-verified on device.

Verified digest parity against node:crypto across the 55/56/64-byte padding
boundaries before the swap.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(mobile-web-bundle): reject a manifest whose buildId is not its content hash

A stale id passed every other check and would then serve the wrong bytes under a
cache key the client already trusts. Runs last of the invariants because it is
the only one that hashes.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(mobile-web-bundle): require a lowercase content type

The pattern carried an `i` flag over lowercase character classes, so the same
bytes described as `Text/HTML` and `text/html` produced two different build ids.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile-web-bundle): move the capability name to a zod-free module

A4 wires this constant into protocol-version.ts, which the phone reads on the
capability path. Leaving it in the schema module would have dragged zod along
with it.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* refactor(mobile-web-bundle): name the chunk reply's length assetByteLength

It is the whole asset's length, not the chunk's, and sitting beside dataBase64
under the old name it read as the chunk's. Both are non-negative integers, so a
producer that emitted the wrong one would only surface at the final hash check.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(mobile-web-bundle): reject asset paths that are not portable or that fold together

Two paths differing only in case are one file on macOS and Windows, so the host
would serve the same bytes under two entries and one of the two hashes could
never match. Windows-reserved segment names and trailing dots cannot be written
to the bundle root at all.

Both follow skill-package-manifest's checks, the folded-path Set and the
reserved-segment pattern.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(mobile-web-bundle): accept one spelling of a parameterised content type

The optional space in `; ?charset=` let the same bytes carry two content types
and therefore two build ids. Pinned to the single-space form the bundle builder
emits.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* perf(mobile-web-bundle): stop hashing a manifest a cheaper invariant already rejected

zod runs superRefine even after the asset-array ceiling has failed, so a 257
asset manifest was still sorted and hashed. Each invariant now returns on its
own issue and the count is checked first, which is what the comment claimed.

The tests read the issue paths: an oversized or otherwise invalid manifest with
a deliberately wrong buildId reports no buildId issue, while the same wrong id
inside the ceiling does.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* docs(mobile-web-bundle): say that the manifest has no additive path

`.strict()` plus a literal schemaVersion closes the shape completely, so the
version bump is the only way to change it. The phone value-imports this schema,
so Phase B must read an unrecognised schemaVersion as a bundle to re-fetch
rather than as a parse crash.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
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.

1 participant