Skip to content

[reference] Single-use artifactIds, web-standard core, direct uploads — reclaim and uploadUnit deleted - #62

Draft
morepriyam wants to merge 9 commits into
mainfrom
feat/grounding
Draft

morepriyam wants to merge 9 commits into
mainfrom
feat/grounding

Conversation

@morepriyam

@morepriyam morepriyam commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator

Why the diff is large (8,679+ / 2,504− over 75 files): most of it isn't library logic — 1,752 lines are example lockfiles, tests and scripts are +2,763 / −927, examples are +714 / −436 (Hono, Workers, Fastify, Meteor demos), and docs are +711 / −122 (PROTOCOL/README/OPERATIONS/CHANGELOG). The reviewable src/ core is +2,653 / −998 over 21 files; the genuinely new surfaces inside it are web.ts, lib/direct-upload.ts, lib/tus-request.ts and storage/sidecar.ts, and the storage adapters are net deletions after the tombstone commit. Reviewing commit-by-commit (9 logical commits) is much smaller than the flat diff.

What this PR is

The grounding pass for pulsevault. It adds two surfaces the library was missing — a runtime-portable core and a presigned direct-upload data plane — and then deletes the machinery that existed to paper over a contract that was wrong.

The point of the PR is that contract: artifactIds are single-use — including through a delete.

The simplification

reserveUpload is a plain atomic create on both adapters — a temp-file + hard-link on local (atomic and exclusive, so a crash mid-write can't leave debris under the real name), IfNoneMatch: "*" on S3/R2. The first reservation of an id wins, and every later create for that id answers a stable 409, whether the previous attempt finished, is still in flight, died halfway, or was deleted.

That last clause is the final commit, and it is what lets the rest of the storage layer be simple. remove() — the artifact DELETE route, TUS termination, retention, validation-failure cleanup — deletes the bytes and rewrites the sidecar as a "deleted" tombstone. Readers see 404; a create for the id still 409s. An id is spent forever. Because an id's identity can never change, every stale handle is harmless by construction: a stale presigned PUT lands on bytes nothing will ever serve, a stale cache entry describes an id nothing can re-reserve, and a cancel that races a finish can only ever un-serve.

Deleted with it:

  • The reclaim state machine — staleness grace windows, datastore-liveness probes, the S3 IfMatch claim dance, local reclaim sweeps, and the reclaimGraceMs option on both adapters. Reclaim existed so a client could retry a crashed create under the same id; a client that mints a fresh id per attempt never needs it.
  • Every defense that existed only because remove() used to free the id: the per-reservation objectSuffix object keys for direct uploads, the deletion-epoch cache guard, the generation gate on the post-terminate sweep, the fresh sidecar re-read on every byte accessor (one direct complete did five sidecar GETs), the ordered "sidecar last" delete choreography, and the local adapter's per-artifact lock. None of them had a test that would fail if removed.
  • The degraded check-then-write mode on S3. The boot-time probe (two PUTs of a throwaway key, the 412/409 required — the thing that catches backends which accept If-None-Match and silently ignore it) now refuses a backend that fails it instead of falling back behind a console.warn. The fallback reopened the exact race the single-use contract exists to close.
  • PROTOCOL.md §4.2.1's client-side 409-derive-resume recovery. The deterministic tus id scheme is demoted to an internal detail — clients MUST NOT construct upload URLs from it. Single-use ids constrain creates, not resumption: an upload the client can still name (it holds the Location from its own create) stays resumable per §4.2.
  • uploadUnit — the per-clip "segment" strategy carried no information the beat manifest doesn't. Gone from the Fastify plugin, the core, the web handler, buildUploadLink, and GET /capabilities; PROTOCOL §8 now defines the single upload set. Passing it is a TypeError at boot on every surface.
  • The tus finish hook's per-request kind/checksum cache with a storage fallback — it reads storage once (getMetadata) — and its two silent "should not happen" early returns, which left a finished upload unfinalized with nothing in the logs. They are loud 500s now.
  • The "cleanup failed → 500" branches after a validation rejection. A 422 no longer promises the id is freed for a corrected retry, because nothing is ever freed; the client mints a fresh id, which §4.2.1 already required.

Kept on purpose: the per-artifact lock on direct-upload complete (a client retrying a lost response genuinely races itself — Pulse's client does exactly that), and the four sidecar getters on the storage contract (public API; removing them was churn with no behavior gain).

Abandoned reservations are freed of their bytes by TUS DELETE or by operator retention (reservedAt-keyed sweep plus bucket lifecycle rules) — never by a contested create, and never of their id. The retention sweep runs on S3/R2 too via listArtifactIds(); tombstones are a few hundred bytes, are listed, and read as absent through getMetadata.

Pulse's single-shot uploader (mieweb/pulse#207) is the reference client.

What's new

  • The . export is now the framework-agnostic core, not the Fastify plugin. Fastify moves to /fastify (the /core alias is kept, and the fastify peer dep is now optional).
  • A web-standard core (Request → Response) in web.ts, so the library runs on Workers, Hono, and Deno — with runnable Hono and Workers demos.
  • PROTOCOL §9 direct-upload profile — a presigned PUT data plane with re-grants, sharing the artifactId space and the single-use rule with TUS creates. Stated plainly in the spec: a direct upload is one PUT, retryable from zero, not resumable mid-file; TUS stays the default.
  • One authorize decision for every surface. authorizeTusRequest / authorizeArtifactRequest in lib/tus-request.ts own the phase derivation, the preflight bypass, the §5.2 unresolvable-id rule, the rejection mapping and the event; both cores only render the result. (The two hand-mirrored copies had already drifted: the OPTIONS-preflight bypass had landed in web.ts only.)

Commit by commit

  1. fix(storage) — POST_TERMINATE sidecar sweep, shared sidecar module, R2 auto-config, cache-resurrection fixes
  2. feat! — entry-point flip: . is the core, Fastify at /fastify
  3. feat — web-standard core + §9 direct-upload profile; Hono + Workers examples
  4. feat! — remove uploadUnit
  5. fix — security/correctness hardening: grant fencing, mint-time re-grant revalidation, storage-truth cross-instance reads, body caps, nosniff, constant-time worker token verification
  6. feat! — single-use artifactIds (reclaim deleted)
  7. fix — post-review hardening: strict tus-id parse, fail-closed sidecar parsing, presignPut requires an exact size match, supportsDirectUpload requires the full §9 surface
  8. fix — review round: the shared authorize decision, AWS's 409 ConditionalRequestConflict mapping, the boot-time conditional-write probe, Fastify body parity, de-duplication
  9. feat! — tombstones (above): remove() tombstones instead of freeing; the defenses that existed only for un-burn deleted; conditional writes required on S3; the tus finish hook reads storage and fails loudly

Commit 9 supersedes parts of 5 and 8 (grant fencing by key, deletion epochs, the degraded mode). They are kept for history.

Follow-ups, deliberately not in this PR: (a) the tus-DELETE sidecar sweep runs after the 204 is on the wire; PROTOCOL words it as if synchronous. (b) markReady/complete conditional writes on S3 — #63. S3's markReady is still an unconditional put; under tombstones the worst case of that race is a "ready" sidecar over missing bytes, which the presigned redirect reports as 404.

Validation

  • npm run build (tsc) clean
  • npm test — 165/165, covering both adapters, the web core, and every demo's contract suite. The termination, direct-upload, plugin and S3 suites now assert the tombstone contract (DELETE → 404, then a fresh create is 409; a 422 leaves the id spent; a backend that fails the conditional-write probe is refused).
  • npm run e2e — boots the auth demo and drives a real TUS upload with HEAD-based resume and token checks: green
  • Pulse's cross-repo integration suite runs green against this build ([reference] Single-shot uploads and a direct-upload transport — segments and cross-run resume deleted pulse#207, 182/182)

Version is unchanged at 0.3.0; these changes sit under ## [Unreleased] in CHANGELOG.md, with each breaking change called out — including the tombstone semantics of remove() and the conditional-write requirement.

Comment thread .github/workflows/ci.yml Fixed
@morepriyam morepriyam changed the title Runtime-portable core, presigned direct-upload profile, storage fixes, PR CI Runtime-portable core, presigned direct uploads, uploadUnit removal, storage fixes (0.4.0) Sep 16, 2026
@morepriyam
morepriyam marked this pull request as ready for review September 16, 2026 23:41
Copilot AI lite review requested due to automatic review settings September 16, 2026 23:41

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

🟡 Changes recommended

Unresolved critical and moderate findings remain across direct uploads, runtime handling, storage reclamation, and packaging.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

PulseVault 0.4.0 makes the upload core runtime-portable, adds presigned direct uploads, removes uploadUnit, and consolidates storage and protocol handling.

Changes:

  • Adds framework-agnostic Node/web handlers and runtime demos.
  • Adds direct-upload authorization, presigning, completion, and re-grant flows.
  • Fixes storage lifecycle behavior and updates packaging, documentation, tests, and CI.
File summaries
File Reviewed changes
web.js Legacy web entry fallback
web.d.ts Web entry type declarations
test/web-handler.test.mjs Web-handler protocol coverage
test/termination-and-reclaim.test.mjs Cleanup and reclaim regression coverage
test/s3-storage.test.mjs S3 storage behavior coverage
test/plugin.test.mjs Fastify plugin coverage
test/mock-s3.mjs Mock S3 behavior and conditional writes
test/local-storage-path-safety.test.mjs Local path safety coverage
test/http-adapter.test.mjs Node HTTP adapter coverage
test/helpers.mjs Shared test-server helpers
test/fail-closed.test.mjs Fail-closed validation coverage
test/direct-upload.test.mjs Direct-upload integration coverage
test/deeplinks.test.mjs Deeplink behavior coverage
test/artifact-name.test.mjs Artifact naming coverage
test/artifact-kinds.test.mjs Artifact-kind validation coverage
src/storage/types.ts Expanded storage contracts and metadata types
src/storage/sidecar.ts Shared sidecar schema and cache logic
src/storage/local.ts Local storage lifecycle and reclaim behavior
src/routes/pulsevault.ts Fastify routes and response schemas
src/lib/upload-metadata.ts Shared upload metadata parsing
src/lib/tus-request.ts Shared TUS request interpretation
src/lib/pulsevaultTus.ts TUS lifecycle and termination cleanup
src/lib/options.ts Storage and server options
src/lib/magic.ts File-type validation
src/lib/finalize.ts Shared upload finalization
src/lib/errors.ts Shared HTTP error helpers
src/lib/direct-upload.ts Direct-upload authorization and completion
src/lib/deeplinks.ts Deeplink generation
src/lib/checksum.ts Checksum handling
src/lib/capability-token.ts Capability-token handling
src/lib/capabilities.ts Capability discovery payload
src/fastify.ts Fastify adapter
src/core.ts Framework-agnostic Node handler
scripts/web-ready-migrate.mjs Web-ready migration tooling
scripts/e2e-tus.mjs End-to-end TUS client flow
PROTOCOL.md Direct-upload and upload-set protocol
package.json Package exports and dependencies
package-lock.json Locked dependency graph
OPERATIONS.md Operational guidance
fastify.js Legacy Fastify resolver
fastify.d.ts Fastify resolver types
examples/workers-demo/wrangler.toml Workers deployment configuration
examples/workers-demo/src/worker.mjs Workers direct-upload control plane
examples/workers-demo/package.json Workers example metadata
examples/meteor-demo/server/main.js Meteor server integration
examples/meteor-demo/private/index.html Meteor example UI
examples/meteor-demo/package-lock.json Meteor example dependencies
examples/meteor-demo/.env.example Meteor environment template
examples/hono-demo/server.mjs Hono runtime integration
examples/hono-demo/package.json Hono example metadata
examples/hono-demo/package-lock.json Hono example dependencies
examples/hono-demo/.gitignore Hono example ignore rules
examples/fastify-demo/server.mjs Fastify example integration
examples/fastify-demo/public/index.html Fastify example UI
examples/fastify-demo/.env.example Fastify environment template
examples/fastify-auth-demo/server.mjs Authenticated Fastify integration
examples/fastify-auth-demo/public/index.html Authenticated example UI
examples/fastify-auth-demo/compose.yaml Authenticated example services
examples/fastify-auth-demo/.env.example Authenticated environment template
examples/express-demo/server.mjs Express integration
examples/express-demo/package.json Express example metadata
examples/express-demo/package-lock.json Express example dependencies
CHANGELOG.md Release and migration notes
.github/workflows/ci.yml Node matrix and package validation CI
Review details

Files not reviewed (4)

  • examples/express-demo/package-lock.json: Generated file
  • examples/hono-demo/package-lock.json: Generated file
  • examples/meteor-demo/package-lock.json: Generated file
  • examples/workers-demo/package-lock.json: Generated file

Suppressed comments (16)

examples/fastify-auth-demo/server.mjs:37

  • This migration uses the updated package subpath, but examples/fastify-auth-demo/package-lock.json still records the old ../.. package metadata (0.1.2, Node >=20, and no range-parser). Because the example is installed with npm ci, the stale lock can produce a fresh environment without the runtime graph required by the new package. Regenerate the example lockfile from the current root package.
import pulseVault, {
  createLocalStorage,
  createMp4Sniffer,
  createChecksumValidator,
  buildUploadLink,
  issueCapabilityToken,
  verifyCapabilityToken,
  createCapabilityAuthorize,
} from "@mieweb/pulsevault/fastify";

examples/fastify-demo/server.mjs:24

  • This import now depends on the root package's updated runtime graph, but examples/fastify-demo/package-lock.json still embeds the old ../.. package metadata (0.1.2, Node >=20, and no range-parser). Release/deploy flows use npm ci, so a clean demo install can omit the package's runtime dependency and fail when the Fastify entry eagerly loads the web/core graph. Regenerate this example lockfile from the current root package.
import pulseVault, { createLocalStorage, buildUploadLink, ensureWebReady } from "@mieweb/pulsevault/fastify";

examples/workers-demo/src/worker.mjs:138

  • The request passed to aws4fetch.sign() contains no Content-Type or Content-Length headers. Returning those values in the JSON response does not bind them into the SigV4 query signature, so the presigned PUT does not enforce the declared payload shape (the completion check only catches size later). Pass the exact headers into the Request being signed and reuse them in the response.
  const signed = await r2Client(env).sign(new Request(url, { method }), {
    aws: { signQuery: true },

examples/workers-demo/src/worker.mjs:199

  • Every existing reservation is rejected here, including an incomplete reservation with the same kind, extension, and size. That violates §9.1's required re-grant behavior: a client that loses or outlives its grant receives a permanent 409 instead of a fresh URL. Read the existing metadata, return a new presign with status 200 for the same shape, and reserve-conflict only for ready or mismatched reservations.
  if (await readMeta(env, artifactId)) return fail(409, `artifactId ${artifactId} already has an upload`);

examples/workers-demo/src/worker.mjs:202

  • This read-then-write reservation is not atomic: two concurrent requests can both observe no sidecar, both write the same artifact key, and both return 201 grants. That breaks the protocol's artifactId collision rule and can hand two clients authority over one object. Use an R2 conditional create (If-None-Match/onlyIf) and map the precondition failure to 409, while keeping the same-shape re-grant path separate.
  if (await readMeta(env, artifactId)) return fail(409, `artifactId ${artifactId} already has an upload`);

  const key = `${kind}/${artifactId}${ext}`;
  await writeMeta(env, artifactId, {

examples/workers-demo/src/worker.mjs:179

  • request.json() buffers the entire client body before any validation, but this public direct-upload endpoint only needs a few hundred bytes. A large or chunked request can consume the Worker isolate's memory; the package web handler already applies a 64 KiB cap for this exact path. Cap the body while reading before parsing JSON.
    body = await request.json();

examples/workers-demo/src/worker.mjs:265

  • This unmatched-prefix 404 is a plain response without the required Protocol-Version header. Protocol §2/§7 requires the header on every response, including errors; return the versioned JSON error shape used elsewhere.
    if (!p.startsWith(`${PREFIX}/`)) return new Response("Not Found", { status: 404 });

examples/workers-demo/src/worker.mjs:183

  • A valid JSON body of null reaches this line and throws TypeError on body.artifactId, producing an unhandled 500 instead of the required 400 invalid-body response (the package implementation rejects non-object bodies explicitly). Validate that the parsed value is a non-null, non-array object before reading its fields.
  const artifactId = String(body.artifactId ?? "").trim();

examples/workers-demo/src/worker.mjs:272

  • The artifact route only handles GET, but PROTOCOL.md §6.2 requires every server to expose DELETE /artifacts/:artifactId as well. Without it, direct-upload reservations and finalized objects cannot be removed through the protocol, and the demo cannot provide the documented cleanup semantics.
    const artifact = sub.match(/^\/artifacts\/([^/]+)$/);
    if (artifact && request.method === "GET") return handleArtifactGet(request, env, artifact[1]);

src/lib/direct-upload.ts:36

  • The runtime/type guard only requires createDirectUpload and headObjectSize, but directUploadCreate's re-grant path and every completion call also depend on getMetadata. A custom adapter can therefore pass this check, be advertised as direct-upload capable, and then return 404 on completion because metadata is unavailable. Make the direct-upload contract require metadata lookup and include it in this capability check.
    src/storage/local.ts:322
  • The second eviction does not close the full in-flight-read race: loadMeta() can miss the cache and start readSidecar() before deletion, then finish after this eviction and call metaCache.set() with stale metadata. A later lookup can still treat the deleted artifact as present (and S3 can issue a dead redirect). Use an epoch/generation or per-artifact synchronization so reads started before remove() cannot repopulate the cache afterward.
    src/storage/local.ts:157
  • fs.access() can fail with EACCES/EPERM or other I/O errors, but this catch treats every failure as “no datastore state.” An aged sidecar can therefore be reclaimed and overwritten while live TUS state is merely unreadable, while the original storage error is hidden. Only treat ENOENT as absent and rethrow other errors.
    src/storage/s3.ts:512
  • This adapter has the same remaining invalidation race: a loadMeta() read that began before deletion can complete after this final delete() and reinsert the old sidecar. Subsequent resolves may return a presigned URL for an artifact that has already been removed. Add generation-based invalidation or per-artifact locking around cache fills and removal.
    src/web.ts:323
  • With combine: true, range-parser can still return multiple disjoint ranges, but this branch silently selects only the first and sends a single-range 206 without a multipart response. That does not represent the requested byte ranges; only enter the single-range path when parsed.length === 1, otherwise ignore the header and serve the full 200 (or implement multipart ranges).
    src/web.ts:337
  • A valid zero-byte TUS artifact leaves end === -1, and createReadStream(..., { end: -1 }) is an invalid stream range; HEAD works, but GET can fail instead of returning an empty artifact. Handle size === 0 after the range/HEAD handling and return an empty body with the existing headers.
    src/web.ts:26
  • Although filesystem imports are lazy below, these eager runtime imports load @tus/server/node:async_hooks through pulsevaultTus.js and node:path through direct-upload.js. As a result, importing this module still fails to bundle or load in filesystem-less edge runtimes, contradicting the documented edge/serverless surface. Move Node/TUS dependencies behind a lazy path or provide an edge-safe direct-only entry point.
  • Files reviewed: 61/68 changed files
  • Comments generated: 15
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/storage/local.ts Resolved
Comment thread src/core.ts Resolved
Comment thread src/lib/capabilities.ts Resolved
Comment thread src/routes/pulsevault.ts Resolved
Comment thread src/web.ts Resolved
Comment thread src/web.ts Resolved
Copilot AI review requested due to automatic review settings September 16, 2026 23:52

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

🟡 Changes recommended

Unresolved critical and moderate findings remain in the Workers example, direct-upload and storage concurrency paths, web handling, and dependency lockfiles.

Get a fresh assessment by requesting another Copilot review.

Review details

Files not reviewed (4)

  • examples/express-demo/package-lock.json: Generated file
  • examples/hono-demo/package-lock.json: Generated file
  • examples/meteor-demo/package-lock.json: Generated file
  • examples/workers-demo/package-lock.json: Generated file

Suppressed comments (22)

Previously missed (2) — in code that hasn't changed since the last review.

examples/workers-demo/src/worker.mjs:272

  • The artifact route only handles GET, but PROTOCOL.md §6.2 requires every server to expose DELETE for artifacts. Without a DELETE path, clients cannot cancel/clean up direct-upload reservations or remove completed objects in this control-plane demo.
    src/storage/sidecar.ts:103
  • JSON.parse can successfully return null; the next parsed.ext access then throws instead of returning null as promised for malformed sidecars. A sidecar containing the valid JSON text null can therefore break reserve/reclaim and metadata reads in both adapters rather than being treated as debris.

examples/hono-demo/package-lock.json:31

  • The ../.. package entry in this lockfile still records range-parser under devDependencies and omits it from dependencies, while the root package now imports it at runtime. A fresh npm ci for hono-demo therefore can leave range-parser out and make @mieweb/pulsevault/web fail at import time; regenerate this entry from the root package metadata.
    examples/workers-demo/src/worker.mjs:202
  • The read-then-write reservation is not atomic. Two concurrent requests can both observe no metadata and both write the sidecar, returning two 201 grants for the same artifactId, contrary to the shared collision rules; use R2 conditional creation or an external coordination primitive.
  if (await readMeta(env, artifactId)) return fail(409, `artifactId ${artifactId} already has an upload`);

  const key = `${kind}/${artifactId}${ext}`;
  await writeMeta(env, artifactId, {

examples/workers-demo/src/worker.mjs:96

  • This verifier accepts a signed payload with missing or non-numeric iat/exp (the comparisons with undefined or null are false), and it also accepts payloads without the documented kid. That is weaker than the package token verifier and allows malformed signed tokens to bypass the required time/claim checks; validate the claims' object shape and field types before comparing them.
  const now = Math.floor(Date.now() / 1000);
  if (typeof claims.artifactId !== "string") return null;
  if (claims.iat > now + 30 || claims.exp < now - 30) return null;
  if (claims.issuer !== env.PV_ISSUER) return null;

examples/workers-demo/src/worker.mjs:273

  • This example advertises the direct-upload profile as a PROTOCOL-compatible server, but the router has no DELETE /artifacts/:id required by §6.2 and no TUS routes, even though §9.1 explicitly requires servers supporting direct uploads to continue supporting TUS. Clients cannot cancel/recover through the advertised protocol. Either implement those required routes or clearly mark this as a partial control-plane example rather than a full protocol server.
    const complete = sub.match(/^\/direct-uploads\/([^/]+)\/complete$/);
    if (complete && request.method === "POST") return handleDirectComplete(request, env, complete[1]);
    const artifact = sub.match(/^\/artifacts\/([^/]+)$/);
    if (artifact && request.method === "GET") return handleArtifactGet(request, env, artifact[1]);
    return new Response("Not Found", { status: 404 });

examples/workers-demo/src/worker.mjs:265

  • The out-of-prefix fallback returns a plain-text 404 without Protocol-Version, but protocol errors must use { ok: false, error: string } and every response must carry the protocol version. This makes an ordinary client route mistake non-conformant; use the existing JSON error helper for this branch.
    if (!p.startsWith(`${PREFIX}/`)) return new Response("Not Found", { status: 404 });

examples/workers-demo/src/worker.mjs:273

  • Unknown routes take this plain-text 404 path, which omits both the required JSON error shape and Protocol-Version. Return the standard fail(404, ...) response so clients can handle errors uniformly.
    return new Response("Not Found", { status: 404 });

package.json:99

  • Changing the root runtime dependency set here also requires regenerating the ../.. entries in the existing Fastify demo lockfiles. examples/fastify-demo/package-lock.json and examples/fastify-auth-demo/package-lock.json still describe the old root package (0.1.2, Node >=20) and omit runtime range-parser, so npm ci in those demos is not installing the package state this PR builds.
    src/core.ts:606
  • decodeURIComponent can throw for a request such as /direct-uploads/%E0%A4/complete. This call is outside the handler's error boundary, so the raw core rejects its handler promise instead of returning the documented 400 for an invalid artifact id. Catch malformed path encoding (or avoid decoding a value that must be a UUID) before dispatching.
    src/lib/capabilities.ts:35
  • Capabilities are advertised when only createDirectUpload exists, but every direct-upload request is gated by supportsDirectUpload, which also requires headObjectSize. A custom adapter can therefore advertise directUpload: { enabled: true } and still return 501 for both create and complete; test both required methods here.
    src/lib/direct-upload.ts:178
  • The re-grant check treats any incomplete reservation with the same kind and extension as a direct-upload reservation when expectedSize is absent. TUS reservations intentionally leave that field unset, so a retry of POST /direct-uploads can mint a PUT URL over an in-flight TUS artifact and let the direct path take it over; only reservations carrying the matching direct-upload size should enter this branch.
    src/lib/direct-upload.ts:283
  • This endpoint also accepts TUS reservations because it only checks expectedSize when comparing sizes. A caller can invoke .../complete for an uploading TUS artifact, have its partial object pass headObjectSize, and mark that artifact ready without the TUS upload reaching its declared length; reject non-direct reservations before the ready/HEAD/finalize path.
    src/lib/direct-upload.ts:276
  • The pre-check is not sufficient for the documented idempotency guarantee under concurrent complete requests: two requests can both read meta.ready === false, both pass the HEAD check, and both run onUploadComplete and the complete event. A lost response followed by an overlapping retry can therefore duplicate consumer work; completion needs an atomic per-artifact claim/transition, not only a read-before-finalize check.
    src/lib/direct-upload.ts:36
  • The public direct-upload capability predicate only requires create and head methods, but completion immediately depends on getMetadata, failed verification must use remove, and the documented re-grant path depends on presignPut. A custom adapter can therefore pass this check, advertise direct uploads, and then return 404 or fail to clean up/re-grant. Make those operations part of the required direct-upload contract and predicate, or reject adapters that lack them.
    src/lib/pulsevaultTus.ts:233
  • The termination listener deliberately schedules cleanup after the 204 has already been sent. A client that immediately retries POST /upload with the same artifactId can therefore hit the still-present sidecar and receive 409 even though DELETE succeeded; the regression test has to poll for cleanup before recreating. If DELETE promises to free the id, await cleanup before acknowledging termination or coordinate reserve with the pending cleanup.
    src/storage/local.ts:259
  • When an aged sidecar is reclaimed, both callers can observe existing as stale with no datastore state and then both execute this unconditional overwrite. That reopens the two-winners race for simultaneous retries after the grace period, despite the comment and tests preserving atomicity for fresh sidecars; reclamation must itself use an atomic create/claim operation.
    src/storage/local.ts:322
  • A second eviction does not fully close the cache-resurrection race: a read that started before the deletes can finish its sidecar read after this eviction and call metaCache.set, leaving a deleted artifact cached again. Use a per-key generation/invalidation check (or serialize reads with remove) so in-flight loads cannot publish metadata after deletion.
    src/storage/s3.ts:512
  • The post-delete eviction has the same remaining race here: an already-started loadMeta can receive the old sidecar after this delete and repopulate the cache after this line runs. A generation check or per-artifact read/delete coordination is needed; evicting twice alone is not a complete invalidation barrier.
    src/web.ts:467
  • The artifact route has the same uncaught decode path: malformed percent-encoding in /artifacts/:id throws before handleArtifactGet can convert the request to a response. Fetch handlers should return a 400 for this invalid request rather than reject the handler promise and delegate an arbitrary 500 to the host framework.
    src/web.ts:457
  • Malformed percent-encoding in /direct-uploads/%E0%A4/complete throws here and is caught as an internal failure, producing a plain-text 500. This is client input for a UUID path and should be rejected as a JSON 400, not reported as a server error; catch the decode separately or avoid decoding this UUID-only parameter.
    src/web.ts:145
  • All responses produced through this helper are text/plain, but PROTOCOL §5.3 requires error responses to be JSON { "ok": false, "error": string }. This affects unmatched routes, malformed URLs, and internal failures on the new web surface, so clients cannot reliably parse errors even though normal validation errors use the required shape. Return the standard JSON error body here.
  • Files reviewed: 61/68 changed files
  • Comments generated: 3
  • Review effort level: Lite

Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread src/storage/s3.ts Resolved
Comment thread src/web.ts Resolved
Copilot AI review requested due to automatic review settings September 17, 2026 00:19

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

🟡 Changes recommended

Unresolved critical and moderate issues remain in the direct-upload, Worker, web, and storage paths.

Get a fresh assessment by requesting another Copilot review.

Review details

Files not reviewed (6)

  • examples/express-demo/package-lock.json: Generated file
  • examples/fastify-auth-demo/package-lock.json: Generated file
  • examples/fastify-demo/package-lock.json: Generated file
  • examples/hono-demo/package-lock.json: Generated file
  • examples/meteor-demo/package-lock.json: Generated file
  • examples/workers-demo/package-lock.json: Generated file

Suppressed comments (13)

examples/workers-demo/src/worker.mjs:219

  • This rejects every existing reservation, but §9.1 requires a same-shape incomplete direct reservation to return 200 with a fresh grant. After an app restart or an expired URL, a client hitting this Worker gets a permanent 409 instead of the required retry/re-grant behavior. Compare the existing metadata's incomplete status, kind, extension, and size, then call presign for the existing key when the shape matches.
  // §9.1 re-grant: an incomplete reservation with the SAME shape gets a fresh
  // presigned URL (the client lost the response or let the grant expire) — a

examples/workers-demo/src/worker.mjs:298

  • The Worker advertises directUpload but returns 501 for every TUS route, while PROTOCOL.md §9 explicitly requires servers supporting this profile to continue serving TUS. A compliant client cannot distinguish this intentional control-plane-only deployment from a broken server. Either delegate TUS to a data-plane service or expose/document a distinct non-conforming capability for this demo.
  const server = `${origin}${PREFIX}`;
  const link = `pulsecam://?v=1&artifactId=${artifactId}&server=${encodeURIComponent(server)}&token=${encodeURIComponent(token)}`;
  return json(200, { artifactId, link });
}

examples/workers-demo/src/worker.mjs:200

  • If the JSON body is the valid JSON literal null, request.json() succeeds and this property access throws, producing an uncaught 500 instead of the protocol's 400 invalid-body response. Reject non-null JSON objects before reading artifactId.
  const artifactId = String(body.artifactId ?? '').trim();
  if (!UUID_RE.test(artifactId)) return fail(400, '`artifactId` must be a valid UUID');
  const kind = KINDS.includes(body.kind) ? body.kind : 'video';

examples/workers-demo/src/worker.mjs:213

  • This validates String(body.relatedTo) but stores the original value. A JSON array such as ["<uuid>"] stringifies to a UUID, passes the check, and is then persisted as a non-string relatedTo, so authorization and metadata semantics diverge from the core implementation. Validate the actual value as a string and store that normalized string.
  const relatedTo = UUID_RE.test(String(body.relatedTo ?? '')) ? body.relatedTo : undefined;

examples/workers-demo/src/worker.mjs:232

  • The reservation is written before presign runs. If R2 credential/signing setup fails, the handler throws after creating the sidecar, so subsequent retries hit the existing-reservation conflict and the artifact cannot self-heal (this demo has no reclaim path). Wrap presigning and delete the metadata reservation when the initial grant cannot be minted.
  // (already completed, or different size/kind/ext) is a real conflict.
  const existing = await readMeta(env, artifactId);
  if (existing) {
    const sameShape =
      existing.status !== 'ready' &&
      existing.kind === kind &&
      existing.ext === ext &&
      existing.expectedSize === size;
    if (!sameShape) return fail(409, `artifactId ${artifactId} already has an upload`);
  }

  const key = `${kind}/${artifactId}${ext}`;

src/lib/capabilities.ts:44

  • validateMaxUploadSize and the public options allow Infinity for an uncapped deployment, but returning it here makes JSON.stringify emit null. /capabilities therefore violates PROTOCOL.md §2's required integer maxUploadSize, and clients cannot reliably enforce the advertised limit. Define a wire-safe representation and update the protocol/client contract, or reject Infinity for protocol-facing handlers.
    src/lib/direct-upload.ts:171
  • If createDirectUpload reserves the sidecar and then presigning fails, this 500 path leaves the reservation behind. The next identical request receives a conflict and only becomes retryable after the reclaim grace period, even though no usable grant was returned. Clean up the reservation on an initial grant failure (without removing an existing reservation in the re-grant branch).
    src/lib/direct-upload.ts:42
  • This predicate advertises the §9 profile for a custom adapter that implements createDirectUpload, headObjectSize, and getMetadata but has no presignPut. Such an adapter can create and complete the first upload, but a same-shape retry falls through regrantDirectUpload and returns 409 instead of the required fresh 200 grant. Require the re-grant operation in the capability contract/predicate, or provide an equivalent fallback, before advertising directUpload.
    src/routes/pulsevault.ts:215
  • This Fastify schema requires artifactId, so a direct-upload request using the legacy videoid/projectid aliases is rejected before it reaches the shared normalizeUploadMetadata path; the Node and web surfaces accept those aliases. Align the schema with the shared alias rule (for example, allow any one of the three fields) or remove alias support consistently.
    src/routes/pulsevault.ts:231
  • The Fastify/OpenAPI schema lists only error responses for direct-upload creation; it omits the normal 201 success and the new same-shape re-grant 200 success. Generated API documentation therefore describes every successful direct-upload response as undocumented, and does not expose the required re-grant contract. Add response schemas/descriptions for both statuses.
    src/storage/s3.ts:357
  • Direct-upload reservations have no <artifact>.info datastore object, so this check classifies every incomplete direct upload as stale once reclaimGraceMs elapses. A retry after the 15-minute grant expires (or a delayed complete) can overwrite the sidecar/delete the existing object and return 201 instead of the required same-shape 200 re-grant. Keep expectedSize reservations out of this TUS debris check, or otherwise make reclaim profile-aware, so they reach the re-grant path.
    src/storage/sidecar.ts:145
  • The new reclaimGraceMs option is used without validation. A negative value makes every uploading sidecar immediately stale, so concurrent creates can both reclaim and win; NaN can make debris unreclaimable forever. Reject non-finite or negative grace values at adapter construction (while allowing 0 if immediate reclaim is intentional).
    src/web.ts:196
  • The web surface makes OPTIONS a patch because only POST is considered create. An authorized client probing TUS capabilities at /upload therefore has no artifact id and receives 403 before handleWeb can return the required OPTIONS response. Bypass authorization for OPTIONS or model it as a separate non-upload phase.
  • Files reviewed: 66/75 changed files
  • Comments generated: 15
  • Review effort level: Lite

Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/web.ts Resolved
Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread src/storage/s3.ts Resolved
Comment thread src/web.ts Resolved
Copilot AI review requested due to automatic review settings September 17, 2026 00:38

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

🟡 Changes recommended

Blocking concurrency, protocol, and security findings remain unresolved.

Get a fresh assessment by requesting another Copilot review.

Review details

Files not reviewed (6)

  • examples/express-demo/package-lock.json: Generated file
  • examples/fastify-auth-demo/package-lock.json: Generated file
  • examples/fastify-demo/package-lock.json: Generated file
  • examples/hono-demo/package-lock.json: Generated file
  • examples/meteor-demo/package-lock.json: Generated file
  • examples/workers-demo/package-lock.json: Generated file

Suppressed comments (13)

examples/workers-demo/src/worker.mjs:153

  • This helper signs only the method and URL, but the response advertises Content-Type and exact Content-Length as required upload headers. Because those headers are absent from the Request passed to aws4fetch, they are not part of the SigV4 signed request, so a bearer grant can PUT a different content type or byte count (and the Worker only checks size at completion). Pass the returned headers into the request being signed, including on the direct-upload call site.
  const signed = await r2Client(env).sign(new Request(url, { method }), {
    aws: { signQuery: true },

examples/workers-demo/src/worker.mjs:225

  • The readMeta check and the later writeMeta are not an atomic reservation. Two simultaneous creates for a new artifactId can both observe no sidecar, both write, and both return 201, violating §9's shared collision rules and allowing one grant to overwrite the other's reservation. Use an R2 conditional create (or another per-id atomic coordination mechanism) before advertising this as the same reservation protocol.
  const existing = await readMeta(env, artifactId);
  if (existing) {
    const sameShape =
      existing.status !== 'ready' &&

examples/workers-demo/src/worker.mjs:315

  • This explicit TUS-unavailable response omits the required Protocol-Version header. PROTOCOL.md §2 requires every response other than the capabilities response to carry that version, so a client receiving this 501 cannot reliably interpret the control-plane contract; use the same header as json() here.
      return new Response('TUS is not available on this control plane — direct uploads only', {
        status: 501,
      });

examples/workers-demo/src/worker.mjs:199

  • A valid JSON null body reaches this line and throws when body.artifactId is evaluated, producing an uncaught Worker error instead of the specified 400 invalid-body response. Check that the parsed value is a non-null object before reading its fields.
  const artifactId = String(body.artifactId ?? '').trim();
  if (!UUID_RE.test(artifactId)) return fail(400, '`artifactId` must be a valid UUID');

examples/workers-demo/src/worker.mjs:150

  • This constructs a virtual-hosted bucket.account.r2.cloudflarestorage.com URL. The package's R2 configuration uses the account endpoint with path-style addressing (https://<account>.r2.cloudflarestorage.com/<bucket>/<key>; forcePathStyle defaults to true because R2 needs it), so these presigned PUT/GET URLs target the wrong R2 endpoint and will fail before the upload reaches the bucket.
async function presign(env, method, key, ttl = PRESIGN_TTL) {
  const url = new URL(
    `https://${env.R2_BUCKET_NAME}.${env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com/${key}`,
  );

examples/workers-demo/src/worker.mjs:129

  • The query-string fallback is accepted for every method, allowing the bearer used for direct-upload create/complete to be sent as ?token= and exposed in proxy logs or browser history. Per §5.1, query tokens are the playback GET fallback; require the Authorization header for POSTs (as the package authorize helper does).
  const token = /^Bearer /i.test(header)
    ? header.slice('Bearer '.length)
    : (url.searchParams.get('token') ?? '');
  if (!token) return fail(401, 'Missing capability token');

examples/workers-demo/src/worker.mjs:324

  • This Worker has no DELETE /pulsevault/artifacts/:id branch, so it does not implement the mandatory artifact cleanup route from §6.2; clients cannot delete a ready artifact or clean up an abandoned object through the documented API. Add a token-authorized delete that removes both the data object and its metadata sidecar.
    const artifact = sub.match(/^\/artifacts\/([^/]+)$/);
    if (artifact && request.method === 'GET') return handleArtifactGet(request, env, artifact[1]);
    return new Response('Not Found', { status: 404 });

src/lib/direct-upload.ts:264

  • This authorization uses cached metadata, while the completion lock later re-reads fresh metadata without re-authorizing it. After another S3 instance deletes and re-creates the same artifactId, a token valid for the old reservation's relatedTo can pass here and complete the new reservation. Authorize against the same fresh metadata that is finalized, or re-check authorization after that fresh read.
    src/lib/direct-upload.ts:285
  • This ready shortcut runs before the TUS/direct profile check below, so a completed TUS upload returns 200 from /direct-uploads/:id/complete even though it never had a direct reservation. The code and §9 require the profiles not to cross; reject TUS-owned ids before accepting the idempotent-ready response, while retaining the shortcut for ready direct uploads.
    src/lib/finalize.ts:100
  • This observer is awaited after markReady and onUploadComplete without an error boundary. If an audit/metrics hook throws, the artifact is already ready but the upload endpoint returns 500; clients may retry a supposedly failed completion while the documented completion sequence has already run. Treat event-hook failures as logged/isolated, or define an explicit retry/idempotency contract for this hook.
    src/storage/s3.ts:551
  • A concurrent reserveUpload can reclaim the stale sidecar and write a new reservation before these deletes complete. The unconditional deletes can then remove the new sidecar or object, losing the replacement upload. Add per-artifact coordination or generation-aware conditional deletes before allowing re-reservation during cleanup.
    src/web.ts:3
  • This static import pulls in pulsevaultTus.ts, which evaluates node:async_hooks, node:path, and @tus/server at module load. Filesystem-less V8 isolates cannot resolve that Node/TUS stack, so importing @mieweb/pulsevault/web fails even for an S3/R2 direct-upload-only deployment; lazily importing only node:fs/node:stream below does not make this entry point edge-loadable. Split or lazy-load the TUS implementation so direct-only edge consumers can load the web handler.
    src/web.ts:346
  • For a valid zero-byte local artifact, size - 1 is -1, and createReadStream rejects the { start: 0, end: -1 } range. The web handler therefore turns a successful empty TUS upload into a 500 instead of returning an empty 200/206 response; short-circuit empty files before creating the Node stream.
  • Files reviewed: 66/75 changed files
  • Comments generated: 2
  • Review effort level: Lite

Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/storage/local.ts Resolved
Copilot AI review requested due to automatic review settings September 17, 2026 00:46

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

🟡 Changes recommended

Unresolved critical and moderate findings affect direct-upload safety, storage cleanup/reclaim, and web-runtime portability.

Get a fresh assessment by requesting another Copilot review.

Review details

Files not reviewed (6)

  • examples/express-demo/package-lock.json: Generated file
  • examples/fastify-auth-demo/package-lock.json: Generated file
  • examples/fastify-demo/package-lock.json: Generated file
  • examples/hono-demo/package-lock.json: Generated file
  • examples/meteor-demo/package-lock.json: Generated file
  • examples/workers-demo/package-lock.json: Generated file

Suppressed comments (13)

OPERATIONS.md:294

  • The retention example says reservedAt is absent on sidecars written before v0.3, but the changelog describes this field as introduced by this release targeting v0.4. Operators upgrading from v0.3 would therefore be given the wrong compatibility note. Change the version reference to v0.4 (or say "before this release").
  // reservedAt is absent on sidecars written before v0.3; treat those as old.

examples/workers-demo/src/worker.mjs:324

  • The Worker never registers DELETE /pulsevault/artifacts/:id; it falls through to the generic 404. PROTOCOL §6.2 requires DELETE, and the direct-upload profile still needs it to cancel a reservation or remove completed/abandoned objects, so clients cannot clean up storage through this server. Add an authorized delete that removes both the final object and metadata.
    const artifact = sub.match(/^\/artifacts\/([^/]+)$/);
    if (artifact && request.method === 'GET') return handleArtifactGet(request, env, artifact[1]);
    return new Response('Not Found', { status: 404 });

examples/workers-demo/src/worker.mjs:315

  • The TUS-unavailable response omits Protocol-Version, even though the protocol requires that header on every response and the other JSON helpers add it. A client probing /upload cannot reliably interpret this 501 response; include Protocol-Version: 1 here.
      return new Response('TUS is not available on this control plane — direct uploads only', {
        status: 501,
      });

examples/workers-demo/src/worker.mjs:199

  • Valid JSON values such as null or a number reach body.artifactId and throw instead of producing the documented 400 response. This also accepts only artifactId, while protocol v1 requires servers to continue accepting the videoid/projectid aliases. Validate an object body and apply the shared alias precedence before reading the id.
  const artifactId = String(body.artifactId ?? '').trim();
  if (!UUID_RE.test(artifactId)) return fail(400, '`artifactId` must be a valid UUID');

examples/workers-demo/src/worker.mjs:249

  • This grant also points at the deterministic final key and remains a reusable PUT credential after handleDirectComplete marks the sidecar ready. A holder can replay it with a different same-sized payload, while the ready fast path returns 200 without revalidating the object, so the served artifact can be overwritten without a new authorization. Use a one-time conditional write or a reservation-generation/staging key before publishing the artifact.
  const uploadUrl = await presign(env, 'PUT', key);
  return json(existing ? 200 : 201, {
    ok: true,
    artifactId,
    uploadUrl,

src/lib/direct-upload.ts:353

  • If storage.remove fails here, returning 422 tells the client the artifactId is immediately reusable even though the sidecar/object may still exist; the next create then returns 409 and the rejected bytes remain. Treat cleanup failure as a server error (or retry/confirm cleanup) instead of advertising a successful fail-closed cleanup required by §9.2.
    src/storage/local.ts:334
  • This final cache eviction still has a race: a loadMeta that started before the deletes can finish reading the sidecar after this metaCache.delete() and then call set(), resurrecting metadata for the deleted artifact. Use per-artifact synchronization or a generation/tombstone check when inserting cache results.
    src/storage/s3.ts:513
  • When If-None-Match is unsupported, this fallback overwrites a stale direct-upload sidecar after conflictingUpload returns false, but unlike the conditional-claim branch it never deletes the old final object. A previous direct PUT can therefore remain at the same key and complete can HEAD it (if its size matches) and mark the new reservation ready without a new PUT. Preserve the stale metadata/object cleanup in this degraded path before reusing the id, or reject direct reclaims when conditional writes are unavailable.
    src/storage/s3.ts:69
  • presignTtlSeconds is also the default TTL for direct-upload PUT grants (presignPut uses the same presignTtl value), not only for playback redirects. This option’s type documentation is misleading for operators configuring grant expiry and reclaim behavior.
    src/storage/s3.ts:585
  • The post-delete eviction does not fully close the race: a loadMeta that began before the deletes can finish reading the sidecar after this metaCache.delete() and then insert the old metadata. A later S3 resolve can consequently return a redirect for the deleted artifact. Use per-artifact synchronization or a generation/tombstone check on cache insertion.
    src/storage/s3.ts:705
  • The presigned PUT is reusable against the deterministic final key until its TTL expires. After complete marks the artifact ready—or after stale-sidecar reclaim deletes the old object—the old URL can PUT a different same-sized payload, and completion only checks size and the current sidecar, so the finalized artifact can be overwritten without a new authorization. Bind the grant to a one-time conditional write or a reservation-generation/staging key that is atomically published on completion.
    src/web.ts:346
  • size can be zero for a valid TUS upload, but this computes end = -1 and passes { start: 0, end: -1 } to createReadStream, which throws instead of serving a 200 empty body (HEAD happens to work). Handle the zero-length case before creating the stream.
    src/web.ts:6
  • Although the filesystem stream imports are lazy, this static import pulls @tus/server and pulsevaultTus.ts (which imports node:async_hooks/node:path) into the web module's load graph; tus-request.ts also has a runtime import of that module. Importing @mieweb/pulsevault/web therefore fails on filesystem-less edge runtimes before a handler can use an S3/R2 adapter, contrary to the portability contract. Keep the TUS-only graph behind a lazy import and move shared URL parsing/context dependencies to an edge-neutral module.
  • Files reviewed: 66/75 changed files
  • Comments generated: 8
  • Review effort level: Lite

Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/lib/pulsevaultTus.ts Resolved
Comment thread src/storage/local.ts Resolved
Comment thread src/storage/local.ts Resolved
Comment thread src/storage/s3.ts Resolved
Copilot AI review requested due to automatic review settings September 17, 2026 01:48

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

🟡 Changes recommended

Unresolved critical and moderate findings remain in direct-upload, Workers, protocol, adapter, and storage lifecycle paths.

Get a fresh assessment by requesting another Copilot review.

Review details

Files not reviewed (6)

  • examples/express-demo/package-lock.json: Generated file
  • examples/fastify-auth-demo/package-lock.json: Generated file
  • examples/fastify-demo/package-lock.json: Generated file
  • examples/hono-demo/package-lock.json: Generated file
  • examples/meteor-demo/package-lock.json: Generated file
  • examples/workers-demo/package-lock.json: Generated file

Suppressed comments (10)

examples/workers-demo/src/worker.mjs:255

  • A valid JSON null body makes body.artifactId throw before the direct-upload 400 validation, so the Worker returns an uncaught 500 instead of the protocol's invalid-body response. Reject non-object/null bodies immediately after parsing, as the Node and web handlers do.
}

examples/workers-demo/src/worker.mjs:252

  • request.json() buffers the entire unauthenticated direct-create body before any validation. Unlike the package web handler's 64 KiB cap, a deployed Worker can be made to allocate up to the platform request limit per request with an oversized JSON body. Read the body with a content-length and streaming cap before parsing.
    minSupportedVersion: 1,
    maxSupportedVersion: 1,
    kinds: KINDS,
    allowedExtensions: ALLOWED,
    maxUploadSize: MAX_UPLOAD,

examples/workers-demo/src/worker.mjs:345

  • This unconditional metadata write is based on an earlier reservation read and head check. A DELETE followed by a new reservation can install a different suffix between those operations; the stale completion then overwrites the current sidecar as ready and playback can point at the old or missing key, defeating the documented grant fencing. Update the metadata with a generation/ETag precondition before marking it ready.

  const key = dataKey(artifactId, meta);

examples/workers-demo/src/worker.mjs:184

  • The direct grant returns Content-Type and exact Content-Length, but this aws4fetch request signs only the method and URL; those headers are added later in grantResponse and are not part of the signature. A holder can therefore PUT a different payload/type and only be rejected after the object has consumed storage and bandwidth. Include the returned PUT headers in the signed Request, matching the S3 adapter's presign behavior.
 * are signed into the URL — they land in `X-Amz-SignedHeaders`, so R2 rejects
 * a PUT whose headers don't match the grant. (`Content-Length` is a
 * fetch-forbidden header that runtimes may strip before signing, so the

src/core.ts:610

  • After the route checks fall through, the core emits its own 404 without Protocol-Version; the malformed-request 400 branch has the same omission. These are protocol responses, so PROTOCOL §2/§7's requirement that every response carry the version header is not met for these errors. Stamp the header on both fallback writes before sending them.
    src/lib/capabilities.ts:42
  • maxUploadSize is allowed to be Infinity by the public options, but JSON.stringify(Infinity) serializes this field as null. /capabilities therefore violates PROTOCOL §2's required integer field (and can fail the Fastify response schema) whenever an operator uses the documented no-cap setting; reject that setting or define a valid finite wire representation.
    src/lib/direct-upload.ts:263
  • This lookup supplies the authorization context and the ready short-circuit, but it uses the adapter cache. On shared S3 storage, another instance can delete and recreate the same ID after this instance cached the old metadata; a token scoped to the old relatedTo can then authorize the new reservation, or an old ready bit can return 200 without checking current state. Read metadata with { fresh: true } before authorization and retain the locked fresh read below.
    src/lib/direct-upload.ts:43
  • This predicate advertises the §9 profile for adapters that only provide createDirectUpload/headObjectSize/getMetadata. The implementation's re-grant path also requires presignPut, and mismatch/validation cleanup relies on remove; a partial adapter therefore advertises direct uploads but returns 409 on same-shape retries and cannot free a rejected reservation. Make those capabilities required for the advertised profile, or stop advertising it until they exist.
    src/routes/pulsevault.ts:348
  • Fastify validates these schemas before the route handler runs, so invalid direct-upload JSON/UUIDs receive Fastify's default validation response without the handler's Protocol-Version header (and without the documented { ok, error } body). That violates the protocol response invariant; add a plugin-scoped validation/error hook or let the shared core own these validation failures. The artifact route schemas have the same lifecycle issue.
    src/routes/pulsevault.ts:291
  • The Fastify adapter passes authorize into a core instance whose TUS/artifact handlers receive request.raw; consequently the shared core invokes authorize, validatePayload, and onUploadComplete with the raw IncomingMessage, and stores pulseVault only there. Fastify consumers are documented to receive the actual FastifyRequest (including custom auth decorators and request.pulseVault), so this refactor breaks those hooks for TUS and artifact GET/DELETE. Carry the wrapper separately for hook/context calls while keeping the raw request for transport I/O.
  • Files reviewed: 66/75 changed files
  • Comments generated: 11
  • Review effort level: Lite

Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/lib/tus-request.ts Resolved
Comment thread src/storage/s3.ts Resolved
Comment thread src/storage/s3.ts Resolved
Comment thread src/storage/s3.ts Resolved
Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/storage/s3.ts Resolved

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

🟡 Changes recommended

Unresolved critical and moderate issues require changes before approval.

Get a fresh assessment by requesting another Copilot review.

Review details

Files not reviewed (6)

  • examples/express-demo/package-lock.json: Generated file
  • examples/fastify-auth-demo/package-lock.json: Generated file
  • examples/fastify-demo/package-lock.json: Generated file
  • examples/hono-demo/package-lock.json: Generated file
  • examples/meteor-demo/package-lock.json: Generated file
  • examples/workers-demo/package-lock.json: Generated file

Suppressed comments (15)

Previously missed (6) — in code that hasn't changed since the last review.

examples/workers-demo/src/worker.mjs:264

  • A valid JSON null body reaches this line and throws while reading body.artifactId, so the Worker returns an uncaught 500 instead of the protocol's 400 for an invalid create body. Add the same object/null guard as the package handler before accessing fields.
    src/lib/direct-upload.ts:55
  • The capability predicate does not require presignPut(), even though the same-shape re-grant path calls it and the protocol requires a repeated create to return a fresh URL. A custom adapter with only createDirectUpload, headObjectSize, and getMetadata will advertise directUpload: { enabled: true }, successfully create once, then return 409 instead of the required 200 after a lost/expired grant. Include presignPut in the capability contract and predicate.
    src/storage/local.ts:306
  • A malformed sidecar makes existing null, so this reclaim path overwrites only .pulsevault/<id>.json and never removes the old TUS datastore .json or bytes. If that corrupt sidecar came from a crash while an older upload had datastore state, the next @tus/file-store create can still collide with the stale state (or reuse its offset/tail), contradicting the claim that malformed debris is safely reclaimable. Recover the old storage key before sweeping, or fail closed instead of treating it as safe to overwrite.
    src/storage/s3.ts:462
  • A ready entry in this per-process cache is treated as an unconditional conflict, so an S3 instance that cached an artifact before another instance deleted it will reject every later create for that artifactId until cache eviction. The following fresh check already provides the collision decision and the conditional write closes the race; do not short-circuit from the cached ready state.
    src/storage/s3.ts:529
  • When readSidecarWithEtag returns a malformed sidecar, stale.meta is null; this branch then replaces the sidecar but skips deleteArtifactObject, leaving any old data object and TUS .info object behind. A subsequent create can still collide with or inherit that stale datastore state, so malformed debris is not actually reclaimed. Recover the prior key before replacement or do not claim malformed sidecars are safe to overwrite.
    src/storage/s3.ts:560
  • resolve() uses the unversioned per-process metadata cache, so a second S3 instance can cache an uploading sidecar and continue returning 404 after the first instance marks it ready (or cache ready and redirect to a deleted/replaced key). There is no TTL or cross-instance invalidation, so this is not a transient race in a horizontally scaled deployment. Read storage truth for resolution or add a correctness-preserving cache version/expiry strategy.

examples/workers-demo/src/worker.mjs:355

  • This unconditional metadata write is not fenced to the reservation that was read above. If this complete request is delayed while the reservation is deleted and the artifactId is re-created, it can overwrite the new reservation's sidecar with the old reservation marked ready (and point playback at the old key), defeating the §9 grant-fencing/reuse guarantees. Update the sidecar conditionally against the reservation generation/ETag, and reject or retry when it changed.
      422,

examples/workers-demo/src/worker.mjs:376

  • The delete path reads meta, then deletes metaKey(artifactId) without checking that the same reservation is still current. A delayed DELETE can therefore remove a newly re-created reservation after the old reservation was replaced, leaving the fresh grant unusable. Delete the sidecar conditionally on the generation/ETag that was read, not by unconditional key deletion.
  const meta = await readMeta(env, artifactId);

examples/workers-demo/src/worker.mjs:400

  • This Worker advertises directUpload enabled but deliberately returns 501 for every TUS request, while PROTOCOL.md section 9.1 requires a server that supports the direct profile to still support TUS. A client selecting the advertised capability can therefore receive a non-conforming server; this also conflicts with describing the demo as a from-spec control plane. Either implement or host TUS alongside it, or expose and document this as a separate direct-only capability rather than the section 9 profile.
    if (p === '/deeplinks' && request.method === 'GET') return handleDeeplink(request, env);
    if (!p.startsWith(`${PREFIX}/`)) return new Response('Not Found', { status: 404 });
    const sub = p.slice(PREFIX.length);
    if (sub === '/capabilities' && request.method === 'GET') return handleCapabilities();

src/lib/tus-request.ts:3

  • tus-request.ts imports artifactIdFromUploadId from pulsevaultTus.ts at module scope. Because web.ts imports this helper eagerly, loading @mieweb/pulsevault/web also evaluates @tus/server and the node:async_hooks/node:path imports before the documented lazy TUS boundary, so edge runtimes without Node built-ins cannot even load the handler for capabilities or direct uploads. Move this parser to a runtime-neutral module and import it from both paths.
    src/routes/pulsevault.ts:348
  • Fastify performs this JSON schema validation before the handler runs. Malformed JSON, an invalid UUID, or an invalid size therefore gets Fastify's default error response, which lacks both Protocol-Version and the required { ok: false, error } shape; the header/body mapping below only applies after validation succeeds. Attach a validation-error handler for these routes or route validation through the core's protocol error mapper.
    src/routes/pulsevault.ts:349
  • These data-level calls are not wrapped in the core's try/catch response mapping. A storage failure or consumer hook exception can reject the handler, so Fastify emits its default 500 response without Protocol-Version and without the protocol error shape, unlike the raw Node/web paths. Catch and map failures through the same fail-closed protocol response before returning the Fastify reply.
    src/storage/s3.ts:543
  • The unsupported-conditional-write branch overwrites an aged sidecar but never deletes the old reservation's object. Direct reservations use unique object suffixes, so each reclaim in this degraded mode leaves unreachable bucket bytes; retain the stale metadata and sweep its data key as the conditional reclaim branch does.
    src/storage/s3.ts:581
  • This ready transition is based only on the artifactId and the sidecar currently read here. A direct completion that captured an older reservation can reach this write after DELETE/re-create and mark the newer reservation ready without its bytes. Carry a reservation identity/object suffix through finalization and condition the write on that identity.
    src/storage/sidecar.ts:124
  • JSON.parse('null') is valid JSON but produces null, so the property access below throws instead of returning the documented null for malformed sidecar content. Both adapters call this parser on their read/reclaim paths, turning corrupt sidecar debris into a 500 rather than allowing the reclaim logic to handle it. Reject non-object parsed values before reading ext.
  • Files reviewed: 66/75 changed files
  • Comments generated: 6
  • Review effort level: Lite

Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread scripts/e2e-tus.mjs Resolved
Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/lib/pulsevaultTus.ts Resolved
Comment thread src/storage/s3.ts Resolved
Copilot AI review requested due to automatic review settings September 17, 2026 02:23

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

🟡 Changes recommended

Unresolved critical and moderate issues remain in direct-upload/storage concurrency, authorization, packaging, and runtime examples.

Get a fresh assessment by requesting another Copilot review.

Review details

Files not reviewed (6)

  • examples/express-demo/package-lock.json: Generated file
  • examples/fastify-auth-demo/package-lock.json: Generated file
  • examples/fastify-demo/package-lock.json: Generated file
  • examples/hono-demo/package-lock.json: Generated file
  • examples/meteor-demo/package-lock.json: Generated file
  • examples/workers-demo/package-lock.json: Generated file

Suppressed comments (19)

Previously missed (2) — in code that hasn't changed since the last review.

examples/workers-demo/src/worker.mjs:265

  • JSON null is valid JSON and request.json() returns it, but dereferencing body.artifactId throws and the Worker returns an unhandled 500 instead of §9's 400 invalid-body response. Validate that body is a non-null object before reading fields.
    OPERATIONS.md:295
  • reservedAt is introduced by this release's reclaim change, while the current package is 0.3.x and the PR targets 0.4.0. Saying sidecars without it were written before v0.3 is inaccurate and could mislead operators about which backups need the fallback treatment; this should refer to pre-0.4 sidecars (or simply pre-reservedAt sidecars).

OPERATIONS.md:282

  • For direct reservations, the adapter deliberately uses max(reclaimGraceMs, presignTtlSeconds * 1000) so an unexpired presigned PUT cannot be reclaimed. With the documented default 900-second presign TTL, the artifactId is not freed after 60 seconds as this note implies; document the effective direct-upload grace (15 minutes by default, or the configured presign TTL).
> **Direct uploads (PROTOCOL.md §9).** A direct-upload reservation whose
> `complete` never arrives leaves an `"uploading"` sidecar plus (possibly) a
> stored object the client PUT but never confirmed. The abandoned-upload
> cutoff below covers the sidecar; on S3/R2 also add a bucket lifecycle rule
> for unconfirmed objects, and rely on the built-in reserve debris-reclaim
> (`reclaimGraceMs`, default 60 s) to free the artifactId for a retried
> create.

README.md:799

  • This says a direct reservation is freed according to reclaimGraceMs, but direct sidecars are intentionally protected until the presigned grant expires: the effective age is max(reclaimGraceMs, presignTtlSeconds * 1000). With the defaults, that is 15 minutes rather than 60 seconds. Please document the direct-upload effective grace here so operators do not expect an early re-grant.
  *Direct* uploads that `PUT` but never `complete` leave a full object at the
  reservation's key with its sidecar stuck at `"uploading"` — the reservation
  itself is freed by debris-reclaim (`reclaimGraceMs`), but if the client
  never returns, only a prefix-scoped expiry rule (or your own

package.json:17

  • This breaking entry-point change is still published as package version 0.3.0 in package.json (and the committed lockfile metadata), although the PR targets 0.4.0. Publishing this tree would expose the new API under the old version, so semver consumers would not be warned about the Fastify import break. Bump the root package to 0.4.0 and regenerate the root-package entries in the five local-demo lockfiles before release.
    src/core.ts:260
  • The !artifactId && phase === 'patch' guard also receives OPTIONS, because handleTus maps every non-POST method to patch. With authorize configured, an OPTIONS request therefore gets 403 before @tus/server can return the TUS capability response. Treat OPTIONS as collection-level discovery and bypass artifact authorization while retaining auth for HEAD/PATCH/DELETE.
    src/lib/capabilities.ts:43
  • validateMaxUploadSize explicitly permits Infinity for no cap, but JSON serialization turns maxUploadSize: Infinity into null. That makes /capabilities violate PROTOCOL §2's required integer and the Fastify response schema's number, so clients cannot distinguish an unlimited deployment from a malformed response. Define and document a wire representation for no cap (updating the schema/spec as needed) or serialize a finite sentinel consistently.
    src/lib/direct-upload.ts:346
  • After the request is authorized against the pre-lock meta, this re-read only checks fresh.ready; it does not verify that fresh is the same reservation. A DELETE/recreate (or reclaim/re-reserve) between these reads lets a request authorized for the old relatedTo finalize the new reservation, and can also return the idempotent 200 for an unrelated incomplete reservation. Compare a reservation generation/key and re-authorize current metadata before calling completeUnlocked.
    src/lib/direct-upload.ts:326
  • The profile-crossing guard is after the meta.ready fast path, so calling /direct-uploads/:id/complete for an already-ready TUS artifact (whose sidecar has no expectedSize) returns a false-success 200 instead of the documented TUS 409. Check expectedSize before the ready/idempotency branch so only direct reservations can be completed through this endpoint.
    src/lib/direct-upload.ts:403
  • The protocol promises that a size mismatch frees the reservation and makes the id immediately retryable, but this catches and only logs a failed/absent storage.remove before still returning 422. If the delete is temporarily unavailable (or a custom direct-capable adapter omits remove), the wrong object and uploading sidecar remain while the client is told cleanup succeeded, leaving retries 409-poisoned. Treat cleanup failure as a server error/retryable completion failure and require cleanup support for the direct-upload capability.
    src/lib/direct-upload.ts:55
  • The direct profile promises a 200 fresh grant for a same-shape retry, but this capability predicate does not require the presignPut method that regrantDirectUpload needs. A custom adapter can satisfy this guard, advertise directUpload, and then return 409 for every re-grant. Make the re-grant primitive part of the direct-capable contract and capability check, or change the advertised profile contract.
    src/lib/direct-upload.ts:411
  • For direct uploads the actual S3 object key includes the reservation's objectSuffix via dataKey, but this passes the unsuffixed TUS-style key to both validatePayload and onUploadComplete. Hooks that use ctx.uploadId to locate or correlate the stored object receive an identifier that does not exist for the direct upload; pass the actual reservation key or define a separate direct-upload key contract.
    src/lib/pulsevaultTus.ts:236
  • The generation check relies on millisecond timestamps and only skips when reservedAt > terminatedAt. A reservation created after the TUS DELETE but within the same Date.now() tick can have an equal timestamp, pass this condition, and then be removed by the asynchronous termination sweep. Use an unambiguous reservation generation/identity captured for the terminated upload (or otherwise make the cleanup ordering atomic) rather than treating timestamps as a strict generation token.
    src/routes/pulsevault.ts:215
  • normalizeUploadMetadata/parseUploadKind intentionally default an absent or unknown kind to video, so Node/web direct create accepts a value such as kind: "future-kind" as video. This Fastify-only enum rejects the same request before the shared logic runs, making the advertised surfaces inconsistent. Either remove this schema-level enum or make the shared normalizer reject unknown kinds consistently.
    src/routes/pulsevault.ts:219
  • The shared direct-upload normalizer accepts the legacy videoid/projectid aliases, but this Fastify schema requires artifactId before the shared implementation runs. Consequently Fastify rejects alias-based requests that the Node and web surfaces accept, defeating the single alias-precedence rule; allow the aliases in this schema (or remove alias support consistently from every surface).
    src/storage/local.ts:247
  • A fresh read that finds no sidecar returns without evicting the existing cache entry. In a shared-storage deployment, another instance can delete the sidecar; this instance then observes absence via getMetadata(..., { fresh: true }) but a later non-fresh resolve can still use the old cached ready metadata and serve the deleted artifact. Invalidate the cache/epoch when the sidecar is absent.
    src/storage/s3.ts:543
  • When conditional writes are unsupported, a stale uploading sidecar has already passed conflictingUpload; this fallback overwrites only the sidecar. Unlike the conditional reclaim branch above, it never removes the stale reservation's data key, so abandoned direct grants leave their suffixed objects orphaned (and stale TUS bytes are not swept). Reuse the stale-object cleanup before the unconditional write.
    src/storage/s3.ts:433
  • A fresh read that finds no sidecar returns without evicting the existing cache entry. In a shared-storage deployment, another instance can delete the sidecar; this instance then observes absence via getMetadata(..., { fresh: true }) but a later non-fresh resolve can still use the old cached ready metadata and serve the deleted artifact. Invalidate the cache/epoch when the sidecar is absent.
    src/web.ts:215
  • OPTIONS is routed into this branch but is classified as patch; with authorize configured it has no artifact id, so the next guard returns 403 before @tus/server can return the TUS capability response. OPTIONS is the collection-level discovery request, not an artifact lifecycle operation; bypass artifact authorization for it while retaining auth for HEAD/PATCH/DELETE.
  • Files reviewed: 66/75 changed files
  • Comments generated: 6
  • Review effort level: Lite

Comment thread examples/meteor-demo/server/main.js Resolved
Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread examples/workers-demo/src/worker.mjs Resolved
Comment thread src/lib/finalize.ts Resolved
Comment thread src/storage/s3.ts Resolved
Comment thread src/storage/s3.ts Resolved
…den R2

TUS DELETE now sweeps the adapter's own sidecar via POST_TERMINATE (a
cancelled artifactId no longer stays 409-reserved). Both adapters share
one sidecar module (schema, parsing, cache, collision error) instead of
hand-mirrored copies. Cloudflare R2 is auto-configured (equal part
sizes, no object tagging) and remove() can no longer resurrect deleted
artifacts in the metadata cache.
…s an adapter

`@mieweb/pulsevault` is now the framework-agnostic core; the Fastify
plugin moves to `@mieweb/pulsevault/fastify` (one-line import change).
The legacy `/core` subpath stays as an alias of `.` indefinitely.
… plane)

`createPulseVaultWebHandler` serves the whole protocol as a WHATWG
Request -> Response handler (Hono/Bun/Deno/Workers). New PROTOCOL.md §9
direct-upload profile: authorize + reserve + presigned PUT, then a
verify-and-finalize complete step sharing the exact TUS validation
sequence. Re-grants re-arm incomplete same-shape reservations. New
Hono and Cloudflare Workers examples; S3/R2 deployment-caveats docs;
retention sample on the public metadata API.
A pulse uploads as one set: the video plus its related artifacts under a
single session token. The per-clip segment strategy carried no
information the beat manifest doesn't, so it is removed from the plugin,
core, web handler, link builder, capabilities, and PROTOCOL.md §8.
Review-driven pass over both adapters, the web core, and the demos:
grant fencing via per-reservation object keys, mint-time re-grant
revalidation anchored to the session relation, storage-truth reads for
cross-instance decisions, deletion-epoch metadata caches, generation-
gated terminate cleanup, per-artifact serialization in local storage,
64 KiB direct-upload body cap, nosniff artifact serving, constant-time
worker token verification, express-demo rate limits, and least-privilege
CI tokens.
`reserveUpload` is now a plain atomic create on both adapters: the first
reservation of an id wins and every later create answers a stable 409 —
whether the previous attempt finished, is in flight, or died halfway.
The reclaim state machine (staleness grace, datastore-liveness probes,
the S3 IfMatch claim dance, local reclaim sweeps) and the
`reclaimGraceMs` option are deleted. Abandoned reservations are freed by
TUS DELETE or operator retention, never by a contested create — which
removes every reclaim race by construction.

PROTOCOL.md §4.2.1 is rewritten: ids are single-use, clients mint a
fresh id per attempt, and the deterministic tus id scheme is demoted to
an internal detail (the client-side 409-derive-resume recovery is
withdrawn). Docs and tests follow; the meteor demo now awaits
storage.initialize(), and the workers demo restricts the ?token= query
fallback to GET requests.
Copilot AI review requested due to automatic review settings September 17, 2026 04:51

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

🟡 Changes recommended

Unresolved critical and moderate issues remain in reservation fencing, cleanup safety, protocol handling, and direct-upload correctness.

Get a fresh assessment by requesting another Copilot review.

Review details

Files not reviewed (6)

  • examples/express-demo/package-lock.json: Generated file
  • examples/fastify-auth-demo/package-lock.json: Generated file
  • examples/fastify-demo/package-lock.json: Generated file
  • examples/hono-demo/package-lock.json: Generated file
  • examples/meteor-demo/package-lock.json: Generated file
  • examples/workers-demo/package-lock.json: Generated file

Suppressed comments (22)

CHANGELOG.md:16

  • The PR description still presents aged crash-debris reclaim via reclaimGraceMs (and describes deterministic-ID URL recovery as a stable contract), but this final branch explicitly removes reclaim and says clients must not derive upload URLs. Please reconcile the PR description with this release behavior before approval; otherwise consumers will expect retry semantics that are no longer implemented.
- **Breaking: artifactIds are single-use — in-band debris reclaim is gone.**
  `reserveUpload` is now a plain atomic create: the first reservation of an
  artifactId wins and every later create for the same id answers `409`,
  whether the previous attempt finished, is in flight, or died halfway. The
  reclaim state machine that tried to tell crash debris from live uploads

OPERATIONS.md:299

  • The retention decision is made from one metadata snapshot, but remove(artifactId) deletes whatever reservation exists when it runs. If a concurrent TUS DELETE frees this id and a new attempt reserves it between these two calls, this stale retention pass can delete the fresh reservation. Add a compare-by-reservation generation/timestamp delete operation, or recheck the metadata under the adapter's deletion lock before removing.
    await storage.remove(artifactId);

examples/workers-demo/src/worker.mjs:359

  • The key is selected from the initial meta, then the object is headed and the metadata is later written as ready without checking that the reservation is still the same. If this id is deleted and re-reserved between those awaits, the stale request can mark the later reservation ready while retaining the old objectSuffix, allowing superseded grant bytes to be served and violating §9 grant fencing. Re-read and conditionally update the exact reservation generation before publishing or deleting.
  const key = dataKey(artifactId, meta);
  const head = await env.BUCKET.head(key);
  if (!head) return fail(409, 'No uploaded object found — PUT the bytes to the upload URL first');
  if (meta.expectedSize !== undefined && head.size !== meta.expectedSize) {
    await env.BUCKET.delete([key, metaKey(artifactId)]);

examples/workers-demo/src/worker.mjs:270

  • A malformed JSON body (null) reaches body.artifactId and throws, so this documented direct-upload endpoint returns a 500 instead of the required 400 invalid-body response. Validate that the parsed value is a non-null JSON object before reading its fields.
  const artifactId = String(body.artifactId ?? '').trim();

examples/workers-demo/src/worker.mjs:310

  • grantResponse signs from a metadata snapshot after sameShape() was checked, but it never re-reads or conditionally fences that snapshot. If another request completes the reservation in this gap, a retry can receive a PUT URL for an already-ready object; if the ID is replaced, it can grant against a stale generation. Re-read immediately before signing and reject unless the same reservation generation is still uploading.
  const grantResponse = async (meta, statusCode) =>
    json(statusCode, {
      ok: true,
      artifactId,
      uploadUrl: await presign(env, 'PUT', dataKey(artifactId, meta), {
        'content-type': CONTENT_TYPES[ext] ?? 'application/octet-stream',
      }),

package.json:98

  • The root package-lock.json does not mirror this manifest's peerDependenciesMeta.fastify.optional: true (its root package entry has only peerDependencies), while the linked demo lockfiles do. Regenerate the root lockfile as part of this package metadata change so npm ci and the published metadata stay consistent.
    src/lib/capabilities.ts:42
  • maxUploadSize is allowed to be Infinity by validateMaxUploadSize and the public options docs, but JSON serialization turns this field into null. That violates the capabilities contract, which requires an integer, and makes no-cap deployments ambiguous to clients. Define and document a wire-safe representation for an uncapped limit (or reject Infinity before building the payload) instead of passing the non-finite number through unchanged.
    src/lib/direct-upload.ts:385
  • headObjectSize(artifactId) performs another fresh metadata lookup instead of checking the reservation represented by meta; finalization and mismatch cleanup then operate by bare artifactId as well. A cross-instance delete/re-reserve between these awaits can make an old completion validate/mark the new reservation, or make its 422 cleanup delete the new reservation, despite authorization for the old metadata. Carry an immutable reservation generation/object key through head, validation, mark-ready, and cleanup with a compare-and-swap.
    src/lib/direct-upload.ts:320
  • This idempotent 200 path is outside the per-artifact completion lock. If another request or instance deletes the ready reservation and re-creates the same artifactId between the initial fresh read and this branch, the response reports success for the new uploading reservation without checking its object or generation. Make the ready decision inside the same generation-bound completion operation.
    src/lib/direct-upload.ts:413
  • The shared finalize contract documents uploadId as the datastore id or the object key for direct uploads, but this constructs the unsuffixed TUS-style key. Direct S3 grants actually write to kind/<artifactId>.<objectSuffix><ext>; validators or onUploadComplete consumers that use uploadId to locate the object will target a key that does not exist. Pass the current reservation's real object key through the adapter/finalize input (while keeping TUS ids unchanged).
    src/lib/direct-upload.ts:393
  • The documented size-mismatch path promises to wipe the reservation so the id is immediately retryable, but a failed storage.remove() is swallowed and the endpoint still returns 422. In that case the sidecar remains reserved and the next create gets 409, so the response falsely reports a recoverable state; surface cleanup failure as a server error (or otherwise make cleanup durable) instead of claiming the reservation was wiped.
    src/lib/direct-upload.ts:55
  • The direct-upload capability check also omits remove, even though the §9 failure paths call it to wipe a wrong-sized or invalid reservation and promise that the id becomes retryable. A custom adapter with the three checked methods but no remove is advertised as direct-capable, then silently leaves the sidecar/object and returns 422/4xx with a permanently conflicted id. Require the cleanup operation in the direct contract/predicate or reject the profile before advertising it.
    src/lib/finalize.ts:72
  • The shared finalizer also returns the validation error after swallowing a failed storage.remove(), even though its contract says every 4xx validation rejection deletes the sidecar and bytes for a safe retry. A transient delete failure therefore leaves the artifactId reserved while the client receives a retryable-looking 422; propagate a server failure or otherwise guarantee/report cleanup failure before returning the 4xx.
    src/routes/pulsevault.ts:365
  • Unlike the raw Node and web handlers, these Fastify direct-upload routes do not catch rejected core operations. Backend failures, onArtifactEvent errors, or a storage read failure can reject directUploadComplete, so Fastify emits its default 500 response without the protocol error shape/Protocol-Version header (and may expose the thrown message). Route the data-level call through the same fail-closed HTTP mapping used by the other surfaces.
    src/routes/pulsevault.ts:353
  • This Fastify create route also lets a rejected core promise escape to Fastify's default error handler. For example, a storage/getMetadata or consumer-event failure during re-grant can produce a framework 500 without the JSON error contract and Protocol-Version header, unlike the raw Node/web paths; use the shared fail-closed mapping around this call as well.
    src/routes/pulsevault.ts:353
  • Fastify validates directUploadCreateSchema before entering this handler, so malformed bodies rejected by the schema never pass through the .header('Protocol-Version', ...) chain. Those new protocol responses use Fastify's default validation error (without the required version header/error shape); add a route/plugin-level error hook that stamps and normalizes validation failures, or avoid relying on pre-handler schema errors for the wire contract.
    src/routes/pulsevault.ts:365
  • The complete route has the same pre-handler validation gap: an invalid artifactId or body can be rejected by directUploadCompleteSchema before this callback runs, so the response bypasses the protocol-version/error shaping used by the core. Ensure Fastify validation errors for this route are stamped and normalized at the plugin level.
    src/storage/local.ts:227
  • The PR description still says crash debris is reclaimed after reclaimGraceMs, but this change deliberately removes that behavior: the implementation keeps every existing sidecar conflicted and the current CHANGELOG/PROTOCOL require a fresh artifactId or operator retention. Please reconcile the PR description (and release notes) with the final single-use reservation contract so consumers do not rely on a retry path this version does not provide.
    src/storage/s3.ts:608
  • The mint-time fence does not actually reject a TUS reservation: when expectedSize is undefined, (meta.expectedSize !== undefined && meta.expectedSize !== size) is false. If a direct-upload regrant loses a remove/re-reserve race to a TUS create, it can issue a PUT grant for the TUS base key and overwrite that upload's bytes, contrary to the cross-profile isolation described above. Require meta.expectedSize === size for every presigned direct grant.
    src/storage/s3.ts:445
  • This unconditional sidecar write can publish stale metadata: on S3, a DELETE followed by a new reservation can replace the sidecar between the earlier read and this write, after which the old upload's completion marks the new reservation ready. Use an ETag/conditional write or carry a reservation generation and reject stale markReady calls.
    src/storage/sidecar.ts:125
  • This treats every non-uploading status as ready, so a corrupted or unknown status value is fail-open and can make an incomplete artifact resolvable. Keep the legacy missing-status case as ready, but reject any explicit status other than uploading or ready so malformed sidecars remain hidden rather than being served.
    src/web.ts:446
  • An OPTIONS /upload preflight is routed into handleTus, whose authorization phase treats every non-POST request as a patch and requires an artifact id. With an authorize hook, browser preflights have no upload URL/id (or bearer token) and are rejected 403 before @tus/server can return its TUS capabilities, so authenticated web clients cannot start uploads cross-origin. Bypass artifact authorization for OPTIONS and let the TUS handler answer the preflight.
  • Files reviewed: 66/75 changed files
  • Comments generated: 8
  • Review effort level: Lite

Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/lib/finalize.ts Resolved
Comment thread src/lib/tus-request.ts Resolved
Comment thread src/storage/local.ts Resolved
Comment thread src/storage/local.ts Resolved
Comment thread src/storage/s3.ts Resolved
Comment thread src/lib/direct-upload.ts Resolved
Comment thread src/lib/pulsevaultTus.ts Resolved
…s, ordered removes, honest §9 contract

- artifactIdFromUploadId rejects ids with extra path segments (authorization
  and the datastore can no longer disagree about which key a request names)
- parseSidecar fails closed on an unknown explicit status instead of serving it
- local remove() deletes bytes/datastore state first and the sidecar LAST,
  matching the S3 adapter, so a new reservation can't be clobbered mid-remove
- the degraded (IfNoneMatch-unsupported) S3 fallback checks object EXISTENCE,
  not parsed metadata — a malformed sidecar no longer un-burns its id
- presignPut requires expectedSize === size: a TUS re-creation under the same
  id can never be armed with a direct PUT grant
- supportsDirectUpload requires the full §9 surface (presignPut, remove) so a
  partial adapter can't advertise a profile it can't complete; failed cleanup
  after a rejected upload now surfaces as 500 (the id was NOT freed), never a
  retryable-looking 4xx
- OPTIONS preflights bypass artifact authorization (tus capabilities/CORS)
- capabilities: maxUploadSize Infinity serializes as an explicit null (wire-
  documented); Fastify routes answer schema/handler failures in the protocol
  error shape with Protocol-Version stamped
- workers demo: non-object JSON bodies get a 400, not a field-access 500
Copilot AI review requested due to automatic review settings September 17, 2026 05:20

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@morepriyam morepriyam changed the title Runtime-portable core, presigned direct uploads, uploadUnit removal, storage fixes (0.4.0) Single-use artifactIds, web-standard core, direct uploads — reclaim and uploadUnit deleted Sep 17, 2026
…clearable debris

Review round on the single-use model. Bugs:

- the OPTIONS-preflight bypass had landed only in the web core; the Node core
  (and so the Fastify plugin) still classified a browser CORS preflight as an
  in-flight `patch`, failed to resolve an id from `/upload`, and 403'd whenever
  `authorize` was set — every browser tus client blocked at the preflight. The
  TUS and artifact authorize decisions now live once in lib/tus-request.ts
  (authorizeTusRequest / authorizeArtifactRequest); both cores only render the
  result. HEAD /artifacts/:id on the Node core answers like GET, headers only.
- AWS answers two CONCURRENT `If-None-Match: *` writes to one key with 409
  ConditionalRequestConflict, not 412; the adapter mapped only 412, so a racing
  duplicate create was a tus 500 with the SDK message in the body.
- conditional-write support is decided once by a boot-time probe (two PUTs of a
  throwaway key, the 412/409 required). That is what catches backends which
  accept the header and silently ignore it — they never hit the old per-request
  501 branch and would have overwritten a finished artifact's sidecar on every
  collision with no signal.
- a corrupt sidecar was a permanently burned id: absent for readers, so DELETE
  404'd and the retention sweep skipped it, while reserve kept 409ing. remove()
  now clears an existing-but-unparseable sidecar; the local reserve writes the
  sidecar whole to a temp file and hard-links it into place (atomic AND
  exclusive), so a crash mid-write can't leave debris under the real name.
- the re-grant identity check is one fresh read in the adapter: presignPut takes
  the full expected identity (size/kind/ext/relatedTo) and compares every field
  at mint time. The core's separate same-shape read — which a remove + re-reserve
  could race — is gone.
- complete decides "is this a TUS reservation" under its lock, on the serialized
  re-read, not on the pre-lock snapshot.
- the S3 byte readers behind validatePayload read the sidecar fresh — a rival
  instance may have re-reserved the id under a new per-reservation key, and
  validating (then wiping) the wrong object turned a good upload into a 500.
- Fastify parity: the Ajv body schema for POST /direct-uploads rejected bodies
  the core accepts (aliases, case-folded kind, non-UUID relatedTo); it is
  documentation only now. A body-less complete under Content-Type:
  application/json was a 400 from Fastify's parser where the other cores return
  200; the plugin scopes a tolerant one.
- the presigner leaves content-type unsigned by default; it is named signable,
  so a grant pins the declared type as documented.
- the removed `uploadUnit` option is a TypeError at boot on every surface.
- listArtifactIds() on the S3 adapter (paginated ListObjectsV2 over the metadata
  prefix) — the retention sweep single-use ids lean on could not run on S3/R2.

De-duplicated: the adapters' loadMeta + five getters + the ArtifactMetadata
projection (createSidecarReader in sidecar.ts), the grant type spelled eight
times (DirectUploadGrant), extractAuthzMessage / pulseVaultError inlined in the
direct-upload module and the Fastify error handler, the duck-typed
regrantDirectUpload wrapper and the `?.` calls on an already-narrowed storage,
pulsevaultTus's private copy of resolveStorageKind, the JSON body cap (one
constant, also the Fastify bodyLimit), the double cache eviction in remove(),
the write-only tus-context fields, and the unused createDirectUpload options.
Copilot AI review requested due to automatic review settings September 17, 2026 13:21

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

`remove()` no longer frees an artifactId. It deletes the bytes and
rewrites the sidecar as `status: "deleted"`: readers see 404, and a later
create for the id still answers 409. DELETE /artifacts, TUS termination,
retention, and validation-failure cleanup all go through it.

That one rule made a whole layer of defenses unnecessary, and they are
gone: the per-reservation `objectSuffix` object keys for direct uploads
(a stale presigned PUT now lands on bytes nothing will ever serve), the
deletion-epoch cache guard, the generation gate on the POST_TERMINATE
sweep, the `{ fresh: true }` re-read on every byte accessor, the ordered
"sidecar last" delete choreography, the local adapter's per-artifact
lock, and the cleanup-failed-becomes-500 branches (a 422 no longer
promises the id is freed; the client mints a fresh one, which PROTOCOL
§4.2.1 already required).

S3-compatible backends must now honor `If-None-Match`: the boot probe
refuses a backend that rejects or silently ignores conditional writes
instead of degrading to check-then-write behind a warning. The degraded
mode reopened the exact race the single-use contract exists to close.

The tus finish hook reads kind and checksum from storage (one
`getMetadata`) instead of a per-request AsyncLocalStorage cache with a
storage fallback, and a missing context or unparseable upload id there is
a loud 500 rather than a silent skip that left a finished upload
unserved.

Kept on purpose: the per-artifact lock on direct-upload `complete` (a
client retrying a lost response races itself), and the four sidecar
getters on the storage contract (public API).

PROTOCOL §4.2.1, §6.2 and §9, OPERATIONS, README and CHANGELOG are
rewritten for the new contract; the thirteen tests that pinned "id
reusable after delete" and the degraded write mode now assert the
tombstone and the refusal.
Copilot AI review requested due to automatic review settings September 17, 2026 14:30

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@morepriyam
morepriyam marked this pull request as draft September 21, 2026 16:08
@morepriyam morepriyam changed the title Single-use artifactIds, web-standard core, direct uploads — reclaim and uploadUnit deleted [reference] Single-use artifactIds, web-standard core, direct uploads — reclaim and uploadUnit deleted Sep 21, 2026
@morepriyam

Copy link
Copy Markdown
Collaborator Author

Reference only — not for merge.

This grounding PR stays open as a reference implementation. Its meaningful pieces are being extracted into focused issues, each landed by its own small PR as a fix. Please don't review this one for merge; review the extracted PRs instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Ready

Development

Successfully merging this pull request may close these issues.

3 participants