Skip to content

feat(core): route sealed envelopes through the serialization layer - #3094

Merged
TooTallNate merged 2 commits into
mainfrom
nate/encp-payload-key
Jul 27, 2026
Merged

feat(core): route sealed envelopes through the serialization layer#3094
TooTallNate merged 2 commits into
mainfrom
nate/encp-payload-key

Conversation

@TooTallNate

@TooTallNate TooTallNate commented Jul 24, 2026

Copy link
Copy Markdown
Member

PR 2 of 7. Stacked on #3093; review the stack in order, starting from #3093.

The gap this closes

The serialization layer had no way to express "seal to this public key": every consumer expected a symmetric CryptoKey, and the encrypt primitive was unconditionally AES-GCM.

That gap was also a live footgun. A 32-byte X25519 public key is a structurally valid AES-256 key, so importKey(pubkey, 'AES-GCM') succeeds and silently produces ciphertext nobody can ever open — no compile error, no runtime error, just unreadable data. Making public keys reachable only through sealTo() turns that from "avoided by convention" into "unrepresentable".

PayloadKey is a widening, not a replacement

This is why the diff touches ~6 files instead of ~60, and why no existing call site or test needed to change:

Variant Writes Reads Held by
CryptoKey encr encr same-run (legacy shape)
RunPayloadKeys encr encr, encp the owning run, o11y
SealTarget encp cross-run writers

A run's own payloads deliberately stay symmetric even when the holder could seal: sealing costs a fresh ECDH and 32 bytes per envelope and buys nothing when the writer already holds the decryption key. The dual encr/encp model is the intended steady state, not a migration step — the encr read path has to exist forever for already-written payloads regardless, and readers dispatch on the 4-byte format prefix, so converging on one scheme would delete no code.

The variants are branded with Symbol.for rather than Symbol() because these values cross the host ↔ workflow VM realm boundary, where only the global symbol registry is shared.

Streams

Both directions handle sealed frames, keeping the length header in the clear so frame boundaries stay findable without a key.

Frames keep per-frame random nonces rather than a counter. Regression tests assert:

  • 100 frames of identical plaintext → 100 distinct ciphertexts
  • 10 writer incarnations (modelling reconnect / durable replay) → 10 distinct content keys

Error quality

Capability shortfalls fail loudly and specifically. Opening a sealed payload with a symmetric key (or a write-only seal target, or nothing) reports "no run keypair is available" rather than surfacing as a mysterious auth-tag failure further down.

Design note: why no new World method

An obvious alternative is to add a World.getEncryptionPublicKeyForRun() accessor so callers can ask the world for a run's public key. This PR deliberately does not.

The public key is data, not a capability: it arrives on the WorkflowRun entity that resumeHook already fetches, and (in a later PR) in the serialized stream descriptor. Nothing needs to ask for it. Keeping it out of the interface means the World contract is unchanged and custom World implementations get sealed-envelope support for free, with no new method to implement.

Worth a second opinion on that call, since it is the main structural choice in this PR.

20 new tests. Full core unit suite (1576) passes; workspace typecheck clean.

Copilot AI review requested due to automatic review settings July 24, 2026 20:56
@TooTallNate
TooTallNate requested review from a team and ijjk as code owners July 24, 2026 20:56
@changeset-bot

changeset-bot Bot commented Jul 24, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: c748b63

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 16 packages
Name Type
@workflow/core Minor
@workflow/builders Patch
@workflow/cli Patch
@workflow/next Patch
@workflow/nitro Patch
@workflow/vitest Patch
@workflow/web-shared Patch
@workflow/web Patch
workflow Minor
@workflow/world-testing Patch
@workflow/astro Patch
@workflow/nest Patch
@workflow/nuxt Patch
@workflow/rollup Patch
@workflow/sveltekit Patch
@workflow/vite Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel

vercel Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

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

Project Deployment Actions Updated (UTC)
example-nextjs-workflow-turbopack Ready Ready Preview, Comment Jul 27, 2026 7:50pm
example-nextjs-workflow-webpack Ready Ready Preview, Comment Jul 27, 2026 7:50pm
example-workflow Ready Ready Preview, Comment Jul 27, 2026 7:50pm
workbench-astro-workflow Ready Ready Preview, Comment Jul 27, 2026 7:50pm
workbench-express-workflow Ready Ready Preview, Comment Jul 27, 2026 7:50pm
workbench-fastify-workflow Ready Ready Preview, Comment Jul 27, 2026 7:50pm
workbench-hono-workflow Ready Ready Preview, Comment Jul 27, 2026 7:50pm
workbench-nestjs-workflow Ready Ready Preview, Comment Jul 27, 2026 7:50pm
workbench-nitro-workflow Ready Ready Preview, Comment Jul 27, 2026 7:50pm
workbench-nuxt-workflow Ready Ready Preview, Comment Jul 27, 2026 7:50pm
workbench-sveltekit-workflow Ready Ready Preview, Comment Jul 27, 2026 7:50pm
workbench-tanstack-start-workflow Ready Ready Preview, Comment Jul 27, 2026 7:50pm
workbench-vite-workflow Ready Ready Preview, Comment Jul 27, 2026 7:50pm
workflow-docs Ready Ready Preview, Comment, Open in v0 Jul 27, 2026 7:50pm
workflow-swc-playground Ready Ready Preview, Comment Jul 27, 2026 7:50pm
workflow-tarballs Ready Ready Preview, Comment Jul 27, 2026 7:50pm
workflow-web Ready Ready Preview, Comment Jul 27, 2026 7:50pm

@github-actions

github-actions Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

🧪 E2E Test Results

All tests passed

E2E Test Summary

Summary
Passed Failed Skipped Total
✅ ▲ Vercel Production 1455 0 239 1694
✅ 💻 Local Development 1621 0 227 1848
✅ 📦 Local Production 1621 0 227 1848
✅ 🐘 Local Postgres 1621 0 227 1848
✅ 🪟 Windows 154 0 0 154
✅ 📋 Other 1020 0 212 1232
✅ vercel-multi-region 27 0 0 27
Total 7519 0 1132 8651
Details by Category

✅ ▲ Vercel Production

App Passed Failed Skipped
✅ astro 126 0 28
✅ example 126 0 28
✅ express 126 0 28
✅ fastify 126 0 28
✅ hono 126 0 28
✅ nextjs-turbopack 151 0 3
✅ nextjs-webpack 151 0 3
✅ nitro 126 0 28
✅ nuxt 126 0 28
✅ sveltekit 145 0 9
✅ vite 126 0 28

✅ 💻 Local Development

App Passed Failed Skipped
✅ astro-stable 128 0 26
✅ express-stable 128 0 26
✅ fastify-stable 128 0 26
✅ hono-stable 128 0 26
✅ nextjs-turbopack-canary 135 0 19
✅ nextjs-turbopack-stable 154 0 0
✅ nextjs-webpack-canary 135 0 19
✅ nextjs-webpack-stable 154 0 0
✅ nitro-stable 128 0 26
✅ nuxt-stable 128 0 26
✅ sveltekit-stable 147 0 7
✅ vite-stable 128 0 26

✅ 📦 Local Production

App Passed Failed Skipped
✅ astro-stable 128 0 26
✅ express-stable 128 0 26
✅ fastify-stable 128 0 26
✅ hono-stable 128 0 26
✅ nextjs-turbopack-canary 135 0 19
✅ nextjs-turbopack-stable 154 0 0
✅ nextjs-webpack-canary 135 0 19
✅ nextjs-webpack-stable 154 0 0
✅ nitro-stable 128 0 26
✅ nuxt-stable 128 0 26
✅ sveltekit-stable 147 0 7
✅ vite-stable 128 0 26

✅ 🐘 Local Postgres

App Passed Failed Skipped
✅ astro-stable 128 0 26
✅ express-stable 128 0 26
✅ fastify-stable 128 0 26
✅ hono-stable 128 0 26
✅ nextjs-turbopack-canary 135 0 19
✅ nextjs-turbopack-stable 154 0 0
✅ nextjs-webpack-canary 135 0 19
✅ nextjs-webpack-stable 154 0 0
✅ nitro-stable 128 0 26
✅ nuxt-stable 128 0 26
✅ sveltekit-stable 147 0 7
✅ vite-stable 128 0 26

✅ 🪟 Windows

App Passed Failed Skipped
✅ nextjs-turbopack 154 0 0

✅ 📋 Other

App Passed Failed Skipped
✅ e2e-local-dev-nest-stable 128 0 26
✅ e2e-local-dev-tanstack-start- 128 0 26
✅ e2e-local-postgres-nest-stable 128 0 26
✅ e2e-local-postgres-tanstack-start- 128 0 26
✅ e2e-local-prod-nest-stable 128 0 26
✅ e2e-local-prod-tanstack-start- 128 0 26
✅ e2e-vercel-prod-nest 126 0 28
✅ e2e-vercel-prod-tanstack-start 126 0 28

✅ vercel-multi-region

App Passed Failed Skipped
✅ nextjs-turbopack 27 0 0

📋 View full workflow run

Copilot AI 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.

Pull request overview

Routes sealed-box (encp) envelopes through the core serialization encryption layer by widening the encryption-key surface area from a symmetric-only CryptoKey to a PayloadKey union that can represent either symmetric encryption (encr) or asymmetric sealing targets (encp). This enables cross-run writers to encrypt using only a recipient public key while keeping same-run payloads symmetric for efficiency.

Changes:

  • Introduce PayloadKey = CryptoKey | SealTarget | RunPayloadKeys and implement encp sealing/opening in serialization/encryption.ts.
  • Update one-shot and streaming serialization paths to accept PayloadKey and correctly read/write encp frames/envelopes.
  • Add unit tests covering sealed envelope behavior, capability enforcement, and stream framing properties for encp.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
packages/core/src/serialization/encryption.ts Adds PayloadKey union + SealTarget/RunPayloadKeys variants and encp encrypt/decrypt support alongside existing encr.
packages/core/src/serialization.ts Wires PayloadKey through stream and helper APIs; stream decrypt now supports encp frames with clearer error reporting.
packages/core/src/serialization/step.ts Widen step-mode serialize/deserialize encryption key param to PayloadKey.
packages/core/src/serialization/client.ts Widen client-mode serialize/deserialize encryption key param to PayloadKey.
packages/core/src/serialization/serialization.test.ts Adds tests for encp envelopes, runtime type guards, and capability enforcement.
packages/core/src/serialization.test.ts Adds end-to-end stream sealing (encp) framing/round-trip/tamper and regression tests.
.changeset/encp-payload-key-union.md Declares the @workflow/core minor bump and summarizes the new PayloadKey behavior.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread packages/core/src/serialization.ts Outdated
@TooTallNate
TooTallNate force-pushed the nate/encp-payload-key branch from 8a44694 to 2712e15 Compare July 25, 2026 08:47

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

ai review: Reviewed the PayloadKey routing and sealed stream integration on the current head. The key variants preserve existing symmetric behavior while preventing X25519 public keys from reaching AES-GCM by mistake. The stream sessions correctly amortize one KEM per writer, retain fresh random nonces per frame, bound the read cache, and handle interleaved writers and failed decapsulation. The sole existing inline performance finding is fixed and resolved. The broad Vercel production E2E failures match the unrelated matrix-wide failures on the stack; focused unit, module-boundary, local framework, Windows, and multi-region checks pass.

Adds the plumbing that lets a cross-run writer emit `encp` payloads. The
serialization layer previously had no way to express "seal to this public
key": every consumer expected a symmetric `CryptoKey`, and the encrypt
primitive was unconditionally AES-GCM.

That gap was also a live footgun. A 32-byte X25519 public key is a
structurally valid AES-256 key, so `importKey(pubkey, 'AES-GCM')`
succeeds and silently produces ciphertext nobody can ever open — no
compile error, no runtime error, just unreadable data. Making public keys
reachable only through `sealTo()` turns that mistake from "avoided by
convention" into "unrepresentable".

`PayloadKey` is a widening rather than a replacement, so no existing call
site changes:

  | Variant          | Writes | Reads        | Held by                 |
  | ---------------- | ------ | ------------ | ----------------------- |
  | `CryptoKey`      | encr   | encr         | same-run (legacy shape) |
  | `RunPayloadKeys` | encr   | encr, encp   | the owning run, o11y    |
  | `SealTarget`     | encp   | —            | cross-run writers       |

A run's own payloads deliberately stay symmetric even when the holder
could seal: sealing costs a fresh ECDH and 32 bytes per envelope and buys
nothing when the writer already holds the decryption key.

The variants are branded with `Symbol.for` (not `Symbol()`) because these
values cross the host ↔ workflow VM realm boundary, where only the global
symbol registry is shared.

Both stream directions handle sealed frames, keeping the length header in
the clear so frame boundaries stay findable without a key. Frames keep
per-frame random nonces rather than a counter — a reconnect or a durable
replay restarts the writer, and a counter would repeat `(key, nonce)` and
break AES-GCM catastrophically. Regression tests assert that 100 frames
of identical plaintext produce 100 distinct ciphertexts, and that ten
writer incarnations never share a content key.

Capability shortfalls fail loudly and specifically: opening a sealed
payload with a symmetric key (or a write-only seal target, or nothing)
reports "no run keypair is available" rather than surfacing as a
mysterious auth-tag failure further down.
Sealing each frame independently meant a fresh X25519 keygen + ECDH +
HKDF per chunk — O(frames) crypto for a long stream. As review pointed
out, amortizing the KEM is safe here so long as nonces stay random, which
they already are; the hazard I had been guarding against was counter
nonces specifically, not a long-lived content key.

`createSealSession` performs one encapsulation per writer instance and
reuses the content key, with a fresh random nonce per frame.
`createOpenSession` mirrors it on the read side, caching decapsulation by
ephemeral public key — since every frame from one writer carries the same
key, that is an ECDH per writer rather than per frame.

Both safety properties are preserved and now asserted directly:

- nonces stay random, so sharing a content key cannot repeat
  `(key, nonce)` (100 identical-plaintext frames -> 100 distinct frames)
- a session is scoped to one stream instance, so a reconnect or durable
  replay never inherits a previous content key (10 writer incarnations ->
  10 distinct ephemeral keys)

The envelope layout is byte-identical to one-shot `seal`, so readers
cannot tell which path produced a frame and need no matching session.

Two edge cases the read-side cache introduces, both covered: frames from
two writers interleaved on one stream (eviction on every frame, so
correctness cannot depend on hit rate), and a failed decapsulation
clearing rather than poisoning the entry.
@github-actions

github-actions Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

📊 Workflow Benchmarks

The benchmark run for c748b63 failed. See the run logs for details.

Partial results from the failed run:

commit c748b63 · Mon, 27 Jul 2026 20:08:47 GMT · run logs

Backend: vercel · app: nextjs-turbopack

Metric Scenario Best (ms) P75 (ms) P90 (ms) P99 (ms) Samples
TTFS hook + stream 1526 (+40%) 🔻 1603 🔴 (+30%) 🔻 1649 🔴 (+31%) 🔻 1796 🔴 (+22%) 🔻 30
STSO 1020 steps (1-20) 146 (-19%) 💚 279 🔴 (+1.1%) 319 🔴 (+4.9%) 338 🔴 (-14%) 19
STSO 1020 steps (101-120) 181 (-2.7%) 236 🔴 (-12%) 259 🔴 (-14%) 262 🔴 (-89%) 💚 19
STSO 1020 steps (1001-1020) 484 (+8.3%) 589 🔴 (+14%) 704 🔴 (+31%) 🔻 785 🔴 (+19%) 🔻 19
WO 1020 steps 387291 (+0.7%) 387291 (+0.7%) 387291 (+0.7%) 387291 (+0.7%) 1
SL stream latency 81 (+5.2%) 144 🔴 (+16%) 🔻 163 🔴 (+13%) 231 🔴 (-9.4%) 30
SO stream overhead (text) 106 (+9.3%) 158 (+1.9%) 216 (+23%) 🔻 616 (+211%) 🔻 30
SO stream overhead (structured) 104 (+3.0%) 145 (-14%) 206 (+16%) 🔻 287 (-81%) 💚 30
ℹ️ Metric definitions & methodology

Best/P75/P90/P99 deltas compare against the most recent benchmark run on main at the time of this run. 🔻 flags a delta worse than +15%, 💚 one better than −15%.

Metrics — TTFS: time to first step body (in-deployment start() → first step body, deployment clocks) · STSO: step-to-step overhead (gap between consecutive step bodies) · WO: workflow overhead (whole-run time outside step bodies, in-deployment anchored) · SL: stream latency (in-deployment write → read propagation, readAt - writtenAt) · SO: stream overhead (end-to-end write+consume time beyond the modelled generation window)

Scenarios — step: one trivial no-op step, no stream; no hooks, so the run stays in turbo mode (in-process fast path) · stream: one streaming step; no hooks, so the run stays in turbo mode (in-process fast path) · hook + stream: registers a hook before one step, which exits turbo mode (dispatch path) · 1020 steps: 1020 trivial sequential steps; STSO is measured between consecutive steps in the given step ranges, and WO is the whole-run overhead outside step bodies · stream latency: parallel reader/writer steps on a dedicated stream; SL is the in-deployment write->read propagation (readAt - writtenAt) · stream overhead (text): writer streams 300 variable-length text token deltas paced at 100/s for 3s (a haiku-size LLM's token throughput) while a parallel reader drains the whole stream; SO is the end-to-end write+consume time beyond the 3s generation window (overhead/backpressure) · stream overhead (structured): same workload as stream overhead (text), but each delta is an AI-SDK-style structured object ({ type: 'text-delta', id, text }) instead of a raw string, so the SO gap vs the text scenario is the added serialization cost

🔴 marks a percentile over its target (within target is left unmarked). Targets (p75/p90/p99, ms) — TTFS 200/300/600 · SL 50/60/125 · SO 250/500/1000 · STSO (1-20) 20/30/60 · STSO (101-120) 30/45/90 · STSO (1001-1020) 40/60/120

All metrics are measured from deployment-side timestamps only. Runs are triggered by an in-deployment route that stamps the anchor (clientStart) right before start(), so the CI runner’s request and its path through api.vercel.com sit outside every measured window. TTFS = in-deployment start() → first step body (turbo uses the in-process fast path, non-turbo the dispatch path), and includes the VQS dispatch hop plus any /flow cold start. STSO/WO are measured between step bodies on the deployment. SL is measured inside the workflow (parallel reader/writer steps), so it no longer includes the api.vercel.com read path.

Cold starts are kept in the numbers on purpose — they are part of real bursty-workload latency. The workbench deployment cold-starts the /flow invocation for a large fraction of runs, inflating P75+; the Best column shows the fastest (warm-start) sample for comparison.

@github-actions

Copy link
Copy Markdown
Contributor

No backport to stable for 7a65030 (AI decision).

This is feature work: PR 2 of a 7-PR stack that adds a new PayloadKey union, sealTo()/runPayloadKeys() exports, and a new encp sealed-envelope format to the serialization layer, carrying a minor changeset. It builds on the main-only encp sealed-box primitive from #3093 and adds new API surface rather than fixing a defect on stable. The "footgun" framing describes a hazard that only exists once public keys are introduced, so there is no existing bug on the maintenance line to fix.

To override, re-run the Backport to stable workflow manually via workflow_dispatch and paste this commit SHA into the ref input:

7a6503048acb72bd53e71197339de5cba312f834

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.

3 participants