Repository navigation
[reference] Single-use artifactIds, web-standard core, direct uploads — reclaim and uploadUnit deleted - #62
morepriyam wants to merge 9 commits into
Conversation
There was a problem hiding this comment.
🟡 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.jsonstill records the old../..package metadata (0.1.2, Node>=20, and norange-parser). Because the example is installed withnpm 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.jsonstill embeds the old../..package metadata (0.1.2, Node>=20, and norange-parser). Release/deploy flows usenpm 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 noContent-TypeorContent-Lengthheaders. 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
201grants. 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-Versionheader. 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
nullreaches this line and throwsTypeErroronbody.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 exposeDELETE /artifacts/:artifactIdas 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
createDirectUploadandheadObjectSize, butdirectUploadCreate's re-grant path and every completion call also depend ongetMetadata. 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 startreadSidecar()before deletion, then finish after this eviction and callmetaCache.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 beforeremove()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 finaldelete()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-parsercan still return multiple disjoint ranges, but this branch silently selects only the first and sends a single-range206without a multipart response. That does not represent the requested byte ranges; only enter the single-range path whenparsed.length === 1, otherwise ignore the header and serve the full200(or implement multipart ranges).
src/web.ts:337 - A valid zero-byte TUS artifact leaves
end === -1, andcreateReadStream(..., { end: -1 })is an invalid stream range;HEADworks, butGETcan fail instead of returning an empty artifact. Handlesize === 0after 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_hooksthroughpulsevaultTus.jsandnode:paththroughdirect-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.
There was a problem hiding this comment.
🟡 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.parsecan successfully returnnull; the nextparsed.extaccess then throws instead of returningnullas promised for malformed sidecars. A sidecar containing the valid JSON textnullcan 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 recordsrange-parserunderdevDependenciesand omits it fromdependencies, while the root package now imports it at runtime. A freshnpm ciforhono-demotherefore can leaverange-parserout and make@mieweb/pulsevault/webfail 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 withundefinedornullare false), and it also accepts payloads without the documentedkid. 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/:idrequired 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 standardfail(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.jsonandexamples/fastify-auth-demo/package-lock.jsonstill describe the old root package (0.1.2, Node>=20) and omit runtimerange-parser, sonpm ciin those demos is not installing the package state this PR builds.
src/core.ts:606 decodeURIComponentcan 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
createDirectUploadexists, but every direct-upload request is gated bysupportsDirectUpload, which also requiresheadObjectSize. A custom adapter can therefore advertisedirectUpload: { 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
expectedSizeis absent. TUS reservations intentionally leave that field unset, so a retry ofPOST /direct-uploadscan 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
expectedSizewhen comparing sizes. A caller can invoke.../completefor an uploading TUS artifact, have its partial object passheadObjectSize, 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 runonUploadCompleteand 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 useremove, and the documented re-grant path depends onpresignPut. 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 /uploadwith 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
existingas 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
loadMetacan 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/:idthrows beforehandleArtifactGetcan 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/completethrows 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
There was a problem hiding this comment.
🟡 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
200with a fresh grant. After an app restart or an expired URL, a client hitting this Worker gets a permanent409instead of the required retry/re-grant behavior. Compare the existing metadata's incomplete status, kind, extension, and size, then callpresignfor 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
directUploadbut returns501for 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 readingartifactId.
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-stringrelatedTo, 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
presignruns. 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
validateMaxUploadSizeand the public options allowInfinityfor an uncapped deployment, but returning it here makesJSON.stringifyemitnull./capabilitiestherefore violates PROTOCOL.md §2's required integermaxUploadSize, and clients cannot reliably enforce the advertised limit. Define a wire-safe representation and update the protocol/client contract, or rejectInfinityfor protocol-facing handlers.
src/lib/direct-upload.ts:171- If
createDirectUploadreserves 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, andgetMetadatabut has nopresignPut. Such an adapter can create and complete the first upload, but a same-shape retry falls throughregrantDirectUploadand 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 advertisingdirectUpload.
src/routes/pulsevault.ts:215 - This Fastify schema requires
artifactId, so a direct-upload request using the legacyvideoid/projectidaliases is rejected before it reaches the sharednormalizeUploadMetadatapath; 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
201success and the new same-shape re-grant200success. 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>.infodatastore object, so this check classifies every incomplete direct upload as stale oncereclaimGraceMselapses. 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. KeepexpectedSizereservations 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
reclaimGraceMsoption is used without validation. A negative value makes every uploading sidecar immediately stale, so concurrent creates can both reclaim and win;NaNcan make debris unreclaimable forever. Reject non-finite or negative grace values at adapter construction (while allowing0if immediate reclaim is intentional).
src/web.ts:196 - The web surface makes
OPTIONSa patch because onlyPOSTis considered create. An authorized client probing TUS capabilities at/uploadtherefore has no artifact id and receives 403 beforehandleWebcan 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
There was a problem hiding this comment.
🟡 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-Typeand exactContent-Lengthas required upload headers. Because those headers are absent from theRequestpassed toaws4fetch, 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
readMetacheck and the laterwriteMetaare 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-Versionheader.PROTOCOL.md §2requires 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 asjson()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
nullbody reaches this line and throws whenbody.artifactIdis 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.comURL. The package's R2 configuration uses the account endpoint with path-style addressing (https://<account>.r2.cloudflarestorage.com/<bucket>/<key>;forcePathStyledefaults 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/:idbranch, 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
relatedTocan 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/completeeven 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
markReadyandonUploadCompletewithout 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
reserveUploadcan 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 evaluatesnode:async_hooks,node:path, and@tus/serverat module load. Filesystem-less V8 isolates cannot resolve that Node/TUS stack, so importing@mieweb/pulsevault/webfails even for an S3/R2 direct-upload-only deployment; lazily importing onlynode:fs/node:streambelow 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 - 1is-1, andcreateReadStreamrejects 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
There was a problem hiding this comment.
🟡 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
reservedAtis 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/uploadcannot reliably interpret this 501 response; includeProtocol-Version: 1here.
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
nullor a number reachbody.artifactIdand throw instead of producing the documented 400 response. This also accepts onlyartifactId, while protocol v1 requires servers to continue accepting thevideoid/projectidaliases. 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
handleDirectCompletemarks 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.removefails 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
loadMetathat started before the deletes can finish reading the sidecar after thismetaCache.delete()and then callset(), 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-Matchis unsupported, this fallback overwrites a stale direct-upload sidecar afterconflictingUploadreturns 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 andcompletecan 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 presignTtlSecondsis also the default TTL for direct-upload PUT grants (presignPutuses the samepresignTtlvalue), 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
loadMetathat began before the deletes can finish reading the sidecar after thismetaCache.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
completemarks 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 sizecan be zero for a valid TUS upload, but this computesend = -1and passes{ start: 0, end: -1 }tocreateReadStream, 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/serverandpulsevaultTus.ts(which importsnode:async_hooks/node:path) into the web module's load graph;tus-request.tsalso has a runtime import of that module. Importing@mieweb/pulsevault/webtherefore 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
There was a problem hiding this comment.
🟡 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
nullbody makesbody.artifactIdthrow 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
readyand 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-Typeand exactContent-Length, but thisaws4fetchrequest signs only the method and URL; those headers are added later ingrantResponseand 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 maxUploadSizeis allowed to beInfinityby the public options, butJSON.stringify(Infinity)serializes this field asnull./capabilitiestherefore 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
relatedTocan then authorize the new reservation, or an oldreadybit 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 requirespresignPut, and mismatch/validation cleanup relies onremove; 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-Versionheader (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
authorizeinto a core instance whose TUS/artifact handlers receiverequest.raw; consequently the shared core invokesauthorize,validatePayload, andonUploadCompletewith the rawIncomingMessage, and storespulseVaultonly there. Fastify consumers are documented to receive the actualFastifyRequest(including custom auth decorators andrequest.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
There was a problem hiding this comment.
🟡 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
nullbody reaches this line and throws while readingbody.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 onlycreateDirectUpload,headObjectSize, andgetMetadatawill advertisedirectUpload: { enabled: true }, successfully create once, then return 409 instead of the required 200 after a lost/expired grant. IncludepresignPutin the capability contract and predicate.
src/storage/local.ts:306 - A malformed sidecar makes
existingnull, so this reclaim path overwrites only.pulsevault/<id>.jsonand never removes the old TUS datastore.jsonor bytes. If that corrupt sidecar came from a crash while an older upload had datastore state, the next@tus/file-storecreate 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
readyentry 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 cachedreadystate.
src/storage/s3.ts:529 - When
readSidecarWithEtagreturns a malformed sidecar,stale.metais null; this branch then replaces the sidecar but skipsdeleteArtifactObject, leaving any old data object and TUS.infoobject 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 anuploadingsidecar and continue returning 404 after the first instance marks it ready (or cachereadyand 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 deletesmetaKey(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.tsimportsartifactIdFromUploadIdfrompulsevaultTus.tsat module scope. Becauseweb.tsimports this helper eagerly, loading@mieweb/pulsevault/webalso evaluates@tus/serverand thenode:async_hooks/node:pathimports 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
sizetherefore gets Fastify's default error response, which lacks bothProtocol-Versionand 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/catchresponse mapping. A storage failure or consumer hook exception can reject the handler, so Fastify emits its default 500 response withoutProtocol-Versionand 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 producesnull, so the property access below throws instead of returning the documentednullfor 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 readingext.
- Files reviewed: 66/75 changed files
- Comments generated: 6
- Review effort level: Lite
There was a problem hiding this comment.
🟡 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
nullis valid JSON andrequest.json()returns it, but dereferencingbody.artifactIdthrows and the Worker returns an unhandled 500 instead of §9's 400 invalid-body response. Validate thatbodyis a non-null object before reading fields.
OPERATIONS.md:295 reservedAtis 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-reservedAtsidecars).
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 ismax(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.0inpackage.json(and the committed lockfile metadata), although the PR targets0.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 to0.4.0and regenerate the root-package entries in the five local-demo lockfiles before release.
src/core.ts:260 - The
!artifactId && phase === 'patch'guard also receivesOPTIONS, becausehandleTusmaps every non-POST method topatch. Withauthorizeconfigured, an OPTIONS request therefore gets 403 before@tus/servercan 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 validateMaxUploadSizeexplicitly permitsInfinityfor no cap, but JSON serialization turnsmaxUploadSize: Infinityintonull. That makes/capabilitiesviolate PROTOCOL §2's required integer and the Fastify response schema'snumber, 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 checksfresh.ready; it does not verify thatfreshis the same reservation. A DELETE/recreate (or reclaim/re-reserve) between these reads lets a request authorized for the oldrelatedTofinalize 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 callingcompleteUnlocked.
src/lib/direct-upload.ts:326 - The profile-crossing guard is after the
meta.readyfast path, so calling/direct-uploads/:id/completefor an already-ready TUS artifact (whose sidecar has noexpectedSize) returns a false-success200instead of the documented TUS409. CheckexpectedSizebefore 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.removebefore still returning422. If the delete is temporarily unavailable (or a custom direct-capable adapter omitsremove), the wrong object anduploadingsidecar 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
presignPutmethod thatregrantDirectUploadneeds. A custom adapter can satisfy this guard, advertisedirectUpload, 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
objectSuffixviadataKey, but this passes the unsuffixed TUS-style key to bothvalidatePayloadandonUploadComplete. Hooks that usectx.uploadIdto 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 sameDate.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/parseUploadKindintentionally default an absent or unknown kind tovideo, so Node/web direct create accepts a value such askind: "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/projectidaliases, but this Fastify schema requiresartifactIdbefore 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-freshresolvecan 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-freshresolvecan 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 OPTIONSis routed into this branch but is classified aspatch; withauthorizeconfigured it has no artifact id, so the next guard returns 403 before@tus/servercan 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
…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.
2e288b0 to
865f6e5
Compare
There was a problem hiding this comment.
🟡 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 oldobjectSuffix, 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) reachesbody.artifactIdand 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
grantResponsesigns from a metadata snapshot aftersameShape()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.jsondoes not mirror this manifest'speerDependenciesMeta.fastify.optional: true(its root package entry has onlypeerDependencies), while the linked demo lockfiles do. Regenerate the root lockfile as part of this package metadata change sonpm ciand the published metadata stay consistent.
src/lib/capabilities.ts:42 maxUploadSizeis allowed to beInfinitybyvalidateMaxUploadSizeand the public options docs, but JSON serialization turns this field intonull. 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 rejectInfinitybefore building the payload) instead of passing the non-finite number through unchanged.
src/lib/direct-upload.ts:385headObjectSize(artifactId)performs another fresh metadata lookup instead of checking the reservation represented bymeta; 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
200path 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
uploadIdas the datastore id or the object key for direct uploads, but this constructs the unsuffixed TUS-style key. Direct S3 grants actually write tokind/<artifactId>.<objectSuffix><ext>; validators oronUploadCompleteconsumers that useuploadIdto 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 noremoveis 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,
onArtifactEventerrors, or a storage read failure can rejectdirectUploadComplete, so Fastify emits its default 500 response without the protocol error shape/Protocol-Versionheader (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-Versionheader, unlike the raw Node/web paths; use the shared fail-closed mapping around this call as well.
src/routes/pulsevault.ts:353 - Fastify validates
directUploadCreateSchemabefore 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
artifactIdor body can be rejected bydirectUploadCompleteSchemabefore 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
expectedSizeisundefined,(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. Requiremeta.expectedSize === sizefor 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 stalemarkReadycalls.
src/storage/sidecar.ts:125 - This treats every non-
uploadingstatus asready, 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 thanuploadingorreadyso malformed sidecars remain hidden rather than being served.
src/web.ts:446 - An
OPTIONS /uploadpreflight is routed intohandleTus, whose authorization phase treats every non-POST request as apatchand requires an artifact id. With anauthorizehook, browser preflights have no upload URL/id (or bearer token) and are rejected 403 before@tus/servercan 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
…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
…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.
`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.
|
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. |
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
reserveUploadis 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 artifactDELETEroute, TUS termination, retention, validation-failure cleanup — deletes the bytes and rewrites the sidecar as a"deleted"tombstone. Readers see404; a create for the id still409s. 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:
IfMatchclaim dance, local reclaim sweeps, and thereclaimGraceMsoption 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.remove()used to free the id: the per-reservationobjectSuffixobject 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 directcompletedid 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.If-None-Matchand silently ignore it) now refuses a backend that fails it instead of falling back behind aconsole.warn. The fallback reopened the exact race the single-use contract exists to close.Locationfrom 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, andGET /capabilities; PROTOCOL §8 now defines the single upload set. Passing it is aTypeErrorat boot on every surface.kind/checksumcache 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 loud500s now.422no 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
DELETEor 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 vialistArtifactIds(); tombstones are a few hundred bytes, are listed, and read as absent throughgetMetadata.Pulse's single-shot uploader (mieweb/pulse#207) is the reference client.
What's new
.export is now the framework-agnostic core, not the Fastify plugin. Fastify moves to/fastify(the/corealias is kept, and thefastifypeer dep is now optional).Request → Response) inweb.ts, so the library runs on Workers, Hono, and Deno — with runnable Hono and Workers demos.authorizeTusRequest/authorizeArtifactRequestinlib/tus-request.tsown 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 inweb.tsonly.)Commit by commit
fix(storage)— POST_TERMINATE sidecar sweep, shared sidecar module, R2 auto-config, cache-resurrection fixesfeat!— entry-point flip:.is the core, Fastify at/fastifyfeat— web-standard core + §9 direct-upload profile; Hono + Workers examplesfeat!— removeuploadUnitfix— security/correctness hardening: grant fencing, mint-time re-grant revalidation, storage-truth cross-instance reads, body caps, nosniff, constant-time worker token verificationfeat!— single-use artifactIds (reclaim deleted)fix— post-review hardening: strict tus-id parse, fail-closed sidecar parsing,presignPutrequires an exact size match,supportsDirectUploadrequires the full §9 surfacefix— review round: the shared authorize decision, AWS's409 ConditionalRequestConflictmapping, the boot-time conditional-write probe, Fastify body parity, de-duplicationfeat!— 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 loudlyCommit 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-
DELETEsidecar sweep runs after the 204 is on the wire; PROTOCOL words it as if synchronous. (b)markReady/completeconditional writes on S3 — #63. S3'smarkReadyis 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) cleannpm 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: greenVersion is unchanged at
0.3.0; these changes sit under## [Unreleased]in CHANGELOG.md, with each breaking change called out — including the tombstone semantics ofremove()and the conditional-write requirement.