One storage API for Google Drive, Nextcloud, and S3-compatible clouds, in TypeScript and Python.
TypeScript byoccloud-storagecloudflare-r2encryptiongoogle-drivenextcloudoauth2pkcepythons3sdkstoragetypescriptwebdav
feat: direct browser upload and streaming transport
Ajay Ramineni618e5c3e0914
diff --git a/.gitignore b/.gitignoreindex 29cbe37..afa6413 100644--- a/.gitignore+++ b/.gitignore@@ -54,3 +54,7 @@ pypi/# Created by the runnable quickstart examplesbyoc-demo-storage/++# Not adopted: CI installs with pip from pyproject.toml ranges.+# Regenerate with `uv lock` if we ever switch.+uv.lockdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex e7c0eba..e70790f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,46 @@ version is below `1.0.0`, the public API may change between minor releases.---+## [Unreleased]++### Added++- `BYOC_E2EE_V3`: independently authenticated AES-256-GCM frames for+ bounded-memory encryption and decryption in TypeScript and Python+- `encryptStream()` / `decryptStream()` and Python+ `encrypt_stream()` / `decrypt_stream()`+- Exact V3 envelope sizing via `encryptedSize()` and Python `encrypted_size()`+- A deterministic V3 cross-SDK fixture plus hostile chunk-boundary, truncation,+ reorder, oversized-frame, empty-object, and header-tampering tests+- A research-backed v0.4 product architecture in+ [`docs/design/byoc-v0.4-strategy.md`](./docs/design/byoc-v0.4-strategy.md)+- A repeatable bounded-memory benchmark via `npm run benchmark:streaming`+- `UploadOptions.contentLength` for exact-length streaming requests; the encrypted+ wrapper converts plaintext length to the V3 envelope length++### Changed++- TypeScript `EncryptedStorageWrapper` now streams true stream inputs, keeps+ buffered inputs payload-signed and retryable, reports plaintext sizes, and+ preserves the underlying provider's resumable capability+- Pure cryptography interop tests no longer require a running S3 server++### Fixed++- Streamed S3 PUT requests now sign `UNSIGNED-PAYLOAD` instead of the SHA-256+ of an empty body+- S3 rejects unknown-length streams before sending a request that portable+ S3-compatible servers such as MinIO refuse with HTTP 411+- One-shot S3 and WebDAV request bodies are not retried after their streams have+ already been consumed+- Python S3 and WebDAV responses now use `defusedxml` for provider-controlled XML;+ Bandit and `pip-audit` run in CI++### Compatibility++- New encryption writes use V3. Existing V1 and V2 objects remain readable in+ both SDKs.+## [0.3.0] - 2026-08-27The release that makes BYOC runnable without an account, and closes a set ofdiff --git a/README.md b/README.mdindex a18e121..24f31e2 100644--- a/README.md+++ b/README.md@@ -11,7 +11,7 @@[](https://github.com/Ajayvarmaramineni/BYOC/actions)[](https://www.npmjs.com/package/@byoc/core)[](https://pypi.org/project/byoc-storage/)-[](#testing-and-verification)+[](#testing-and-verification)[](#testing-and-verification)[](LICENSE)@@ -297,7 +297,7 @@ FastAPI / Django / Next.js / Express**Security**- OAuth 2.0 with PKCE (RFC 7636) and CSRF state, using the non-restricted `drive.file` scope so you never enter Google's Restricted Scope assessment-- Client-side E2EE with AES-256-GCM and PBKDF2-HMAC-SHA256 at 600,000 iterations, with the work factor recorded in the envelope and range-checked before key derivation+- Framed client-side E2EE with bounded-memory stream APIs, per-frame AES-256-GCM authentication, and V1/V2 read compatibility- Encrypted-at-rest token storage, written with owner-only permissions- Credential redaction in logs, covering bearer tokens, refresh tokens, and cloud access keys- Path traversal rejection and control-character stripping on every virtual path@@ -312,8 +312,8 @@ FastAPI / Django / Next.js / Express## Testing and verification```-TypeScript 374 tests tsc --strict-Python 361 tests mypy --strict, ruff+TypeScript 385 tests tsc --strict+Python 403 tests mypy --strict, ruff (live MinIO active)Integration 38 tests live MinIO and WebDAV serversInterop 13 tests both SDKs, same live servers```@@ -384,6 +384,7 @@ byoc/│ └── scripts/ # live Google Drive validation├── spec/fixtures/ # cross-SDK conformance vectors├── docs/ # setup and integration guides+├── scripts/ # repeatable engineering benchmarks└── examples/ # runnable demonstrations├── node-quickstart/ # TypeScript└── python-quickstart/ # Python@@ -413,6 +414,8 @@ Building your own adapter? [`@byoc/provider-sdk`](./packages/provider-sdk) runs| :--- | :--- || [Google Drive OAuth setup](./docs/google-oauth-setup.md) | Cloud console walkthrough, troubleshooting, token persistence || [Conformance fixtures](./spec) | The cross-SDK contract and how to run it |+| [v0.4 architecture](./docs/design/byoc-v0.4-strategy.md) | Research-backed path from adapter SDK to portable data control plane |+| [Streaming and E2EE design](./docs/design/streaming-and-chunked-e2ee.md) | V3 wire format, security model, provider constraints and sequencing || [Python SDK](./python) | Install, async client, FastAPI and Celery notes || [Changelog](./CHANGELOG.md) | Release history and known limitations || [Contributing](./CONTRIBUTING.md) | Development setup for both SDKs, and the pull request process |diff --git a/SECURITY.md b/SECURITY.mdindex bcb944f..8275359 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -61,14 +61,62 @@ the storage operator never sees plaintext.- The iteration count is read from untrusted storage and consumed before the GCMtag can authenticate it, so it is range-checked to 10,000..2,000,000 beforeany key derivation runs-- The magic header, iteration count, and salt are bound as GCM additional- authenticated data, so the envelope header cannot be edited undetected+- New writes use the framed `BYOC_E2EE_V3` envelope. The full header, frame+ index, and final-frame marker are bound as GCM additional authenticated data,+ detecting header swaps, frame reordering, modification, and truncation+- V3 frame size and frame length are range-checked before allocation; empty+ objects contain one authenticated final frame- Envelope layout is pinned by `spec/fixtures/e2ee-envelope.json` and isbyte-identical across both SDKs+- V1 and V2 envelopes remain readable-Payloads are buffered in memory, so E2EE does not currently compose with-resumable streaming uploads. The wrapper reports `resumableUploads: false`-rather than failing at upload time.+Both SDKs encrypt uploads incrementally. Streaming transport has landed for+some adapters and not others, and the table below says exactly which.++**A stream of unknown length is sent as a multipart upload.** S3 answers+`411 Length Required` to a chunked `PUT`, so an unbounded body cannot go in one+request. Splitting it into parts is what makes the transfer possible, and it+also improves what the signature covers: **each part is fully known when it is+signed, so every part signs its real SHA-256 payload hash.** Streaming does not+weaken request signing on this path.++`UNSIGNED-PAYLOAD` is still used in two narrower places, and only there:++- a single streamed `PUT` where the caller supplied `contentLength`, so no+ multipart upload is opened+- presigned URLs, where the body does not exist when the URL is signed++In both cases TLS protects the body in transit and, for encrypted objects, V3's+per-frame tags authenticate the plaintext independently of the transport.++A one-shot stream is consumed as it is sent, so a failed streamed upload is not+retried automatically -- there would be nothing left to resend. A failed+multipart upload is aborted so its parts stop accruing storage charges.++WebDAV needs none of this. An RFC 4918 server accepts chunked+transfer-encoding, so the body streams in a single `PUT` with no part+accounting, and Basic credentials still authenticate the request.++Measured peak memory, holding one part or chunk at a time:++```+Python S3 streamed 100 MB -> 57.9 MB Python S3 buffered 400 MB -> 446.2 MB+ 400 MB -> 56.7 MB+ 800 MB -> 57.0 MB+Python WebDAV streamed 200 MB -> 48.2 MB+```++Where streaming stands, per adapter:++| Adapter | TypeScript | Python |+| :--- | :--- | :--- |+| S3-compatible | streams (multipart) | streams (multipart) |+| WebDAV | streams (chunked) | streams (chunked) |+| Google Drive | **buffers** | **buffers** |+| Local, in-memory | streams | streams |++**Do not claim end-to-end bounded memory for the adapters marked buffers.**+Python's migration engine also still reads each file fully before writing it.### Credential storagediff --git a/docs/design/roadmap-internal.md b/docs/design/roadmap-internal.mdnew file mode 100644index 0000000..a985ef7--- /dev/null+++ b/docs/design/roadmap-internal.md@@ -0,0 +1,261 @@+> **Internal roadmap, not positioning.**+>+> This is where BYOC is going over several releases. It is deliberately not the+> public pitch: "portable data control plane" is a destination, and a reader+> who has never used BYOC feels nothing when they read it. The launch story+> lives in [`v0.4-pitch.md`](./v0.4-pitch.md) and is deliberately smaller and+> more concrete -- the bytes never touch your server -- because that is the+> part that is built, demonstrable, and immediately felt.+>+> Wedge first, destination second. Keep the two apart.++# BYOC v0.4: from storage adapter to portable data control plane++**Status:** architecture direction with the first data-plane milestone implemented++## Product thesis++BYOC should not try to win by becoming another list of cloud adapters. Apache+OpenDAL already exposes a broad operator model across many services, and rclone is+excellent at command-line transfer and synchronization. BYOC can own a different+problem:++> Let an application store, verify, move, observe and recover user data across+> storage the user controls, while making provider differences explicit.++That is a portable data control plane. The user's bucket, Drive, WebDAV server or+mounted volume remains the source of truth. BYOC supplies the guarantees that+application teams otherwise rebuild badly: encryption, integrity, migration+checkpoints, change cursors, policy and evidence.++This direction also matches the broader move toward portability. The EU Data Act+requires cloud-switching support, open interfaces in relevant services and+structured machine-readable export in specified cases. BYOC is not a compliance+certificate, but application-level portability is becoming infrastructure rather+than a nice-to-have. See the [final Regulation (EU) 2023/2854](https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32023R2854).++## What the research changed++### Do not flatten provider truth++Mature abstractions keep operations stable while layering retry, logging, timeouts+and metrics around them. [Apache OpenDAL's model](https://opendal.apache.org/docs/concepts/)+is strong evidence for that split. BYOC should evolve its seven capability booleans+into structured guarantees:++~~~ts+interface ProviderProfile {+ transfer: {+ upload: "buffered" | "streaming" | "resumable";+ download: "buffered" | "streaming" | "range";+ maxObjectBytes?: number;+ };+ consistency: {+ readAfterWrite: "strong" | "eventual" | "unknown";+ conditionalCreate: boolean;+ conditionalReplace: boolean;+ };+ integrity: {+ algorithms: Array<"sha256" | "crc32c" | "crc64nvme" | "md5">;+ serverValidated: boolean;+ multipartScope: "full" | "composite" | "none";+ };+ changes: {+ mode: "native-cursor" | "polling" | "none";+ };+}+~~~++This matters because an S3 ETag is not a universal checksum. AWS documents that+multipart ETags are not necessarily whole-object MD5 values and separately exposes+full and composite checksums. BYOC should represent algorithm, value, encoding,+scope and whether the provider validated it. See [S3 object integrity](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity-upload.html).++### Treat transfer as a durable protocol++A boolean named resumable cannot represent a real recovery contract. The+[tus protocol](https://tus.io/protocols/resumable-upload) and the+[IETF HTTP resumable-upload draft](https://datatracker.ietf.org/doc/draft-ietf-httpbis-resumable-upload/)+both center an upload resource, an offset and explicit completion/cancellation.+BYOC needs a portable checkpoint containing provider id, destination, bytes+committed, object fingerprint and opaque adapter state.++### Make changes cursor-based++Google Drive has start page tokens and a changes feed; WebDAV defines sync tokens;+Microsoft Graph returns delta links. All are opaque cursors, but their deletion and+path semantics differ. The portable API should preserve provider state rather than+inventing timestamps:++~~~ts+const page = await storage.changes({ cursor, scope: "projects/acme" });+persist(page.cursor);+for (const change of page.changes) applyLatestState(change);+~~~++Primary references:+[Google Drive changes](https://developers.google.com/workspace/drive/api/guides/manage-changes),+[WebDAV collection sync](https://www.rfc-editor.org/rfc/rfc6578), and+[Microsoft Graph delta](https://learn.microsoft.com/en-us/graph/api/driveitem-delta).++### Encrypt the stream, not the file-sized buffer++Both [Google Tink Streaming AEAD](https://developers.google.com/tink/encrypt-large-files-or-data-streams)+and [libsodium secretstream](https://doc.libsodium.org/secret-key_cryptography/secretstream)+bind authenticated segments to their position and detect reordering, modification+and truncation. BYOC V3 follows those properties while retaining AES-GCM and the+existing dependency set:++- one PBKDF2-HMAC-SHA256 key derivation per object;+- 256 KiB default plaintext frames;+- unique nonce per frame from an 8-byte random base plus a 32-bit index;+- full header, index and final-frame marker bound as AAD;+- exact V1/V2 read compatibility;+- range checks before attacker-controlled iteration counts or frame lengths are used.++PBKDF2 with a per-object salt remains aligned with+[NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf).+A future Argon2id envelope can be added as a new version after cross-runtime support+and migration ergonomics are proven; silently changing V3 would be unacceptable.++## Implemented in this upgrade++1. BYOC_E2EE_V3 framed envelopes in TypeScript and Python.+2. encryptStream/decryptStream and encrypt_stream/decrypt_stream with memory bounded+ by the configured frame size.+3. Empty-object final frames and authenticated protection against frame removal,+ reordering, oversized lengths, header tampering and wrong keys.+4. A shared deterministic V3 fixture consumed by both SDKs.+5. Cross-SDK runtime tests in both directions without requiring a live S3 server.+6. TypeScript EncryptedStorageWrapper now sends encrypted streams and preserves+ the underlying provider's resumable capability.+7. S3 streamed PUTs use AWS's documented SigV4+ [UNSIGNED-PAYLOAD](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html)+ sentinel instead of signing the SHA-256 of an empty body.+8. One-shot S3 and WebDAV streams are not blindly retried after consumption.+9. Exact `contentLength` propagation makes encrypted streaming PUTs portable to+ MinIO; an 8 MiB live round trip passed with ciphertext verified and decrypted.++The security tradeoff for S3 is explicit: streamed request bodies rely on TLS plus+per-frame E2EE integrity and use UNSIGNED-PAYLOAD; buffered inputs remain buffered+through the encrypted wrapper and continue to sign the actual body hash. A strict+bucket policy may reject unsigned payloads. Provider-native multipart checkpoints+are the later solution for retryable large S3 uploads.++## The moat: four releases, in order++### v0.4.1: truthful large-object transport++- Stream Python S3, WebDAV, Drive and migration paths without response.content.+- Stream Google Drive resumable chunks without first converting to one array.+- Add cancellation, deadlines and byte-range reads.+- Replace one-shot retries with provider-native resumable checkpoints.+- Add 1 GiB bounded-memory integration tests for Local, MinIO and WebDAV.++Current core baseline on the development machine: a 1 GiB encrypt/decrypt pipeline+with 64 KiB frames verified its SHA-256 with a 157 MiB peak RSS increase. Run+`npm run benchmark:streaming -- 1024 64` to repeat it. The v0.4.1 exit criterion+is a peak RSS increase below 192 MiB for the same workload through Local, MinIO,+and WebDAV, with memory staying flat as object size increases.++### v0.5: Storage Passport++Create a deterministic, provider-neutral manifest:++~~~json+{+ "format": "byoc-passport/v1",+ "root": "projects/acme",+ "objects": [+ {+ "path": "src/main.ts",+ "size": 1204,+ "checksum": { "algorithm": "sha256", "value": "...", "scope": "full" }+ }+ ],+ "manifestSha256": "..."+}+~~~++The API produces snapshots, diffs two snapshots and verifies stored bytes. It+turns migration from "the copy request returned 200" into evidence that a dataset+arrived intact. Provider checksums are used only when their algorithm and scope+match; otherwise BYOC computes SHA-256 while streaming.++### v0.6: durable migration and sync++- Persistent migration journals with per-object state and restart recovery.+- Conditional destination writes to stop silent overwrite races; [AWS documents+ these preconditions directly](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-requests.html).+- Native changes adapters for Drive and WebDAV, then Graph/OneDrive and Dropbox.+- Explicit conflict records instead of last-writer-wins guesses.+- Dry-run plans that estimate bytes, requests, unsupported metadata and likely cost.++### v0.7: policy and replication++~~~ts+const storage = byoc.policy({+ route: [+ { when: { classification: "regulated" }, to: ["eu-primary", "eu-backup"] },+ { when: { sizeAbove: "1GiB" }, to: ["r2-archive"] }+ ],+ replication: { acknowledgements: 2, repair: "background" },+ retention: { versions: 30 }+});+~~~++Policies must return evidence: which copies committed, which checksum was verified,+and what repair remains. BYOC should never call a two-provider copy atomic.++### v1.0: operational control plane++- Composable middleware for retry, rate limiting, tracing, metrics and audit.+- Neutral operation events with an optional OpenTelemetry bridge, following the+ [OpenTelemetry semantic conventions](https://opentelemetry.io/docs/specs/semconv/).+- A byoc doctor command that actively tests auth, write/read/list/delete, checksum+ behavior, clock skew, range support and cleanup.+- Stable capability/profile schema, compatibility policy and provider certification.+- Threat model, external cryptography review, fuzzing corpus and restore drills.++## What not to build++- **A hosted proxy for every byte.** It recreates the storage bill and trust problem.+- **A fake POSIX filesystem.** Rename, locking and consistency differ too much.+- **A universal sync that hides conflicts.** Durable journals and explicit policy+ must come first.+- **Content deduplication before the privacy model is settled.** Cross-user+ deduplication leaks equality and complicates ownership.+- **Dozens of adapters before certification.** Five trustworthy providers beat+ fifty unverified logos.++## Production gates++The project should not call itself production-ready until all of these are true:++- external review of V3 framing and key-management guidance;+- property/fuzz tests for parsers and truncated/corrupted streams;+- Python transport streaming and durable resumable sessions;+- conditional writes and normalized checksums;+- provider live tests pinned to known server versions, plus scheduled compatibility runs;+- telemetry with path/credential redaction and cardinality limits;+- signed releases, provenance/SBOM, automated dependency review and a disclosure SLA;+- load, cancellation, crash-recovery and restore tests with published numbers;+- explicit support matrix for Node/Python/runtime/provider combinations.++## GitHub launch plan++No engineering change can guarantee a number-one GitHub ranking in a week. A release+can, however, be unusually easy to understand and trust:++1. Publish a two-minute demo: encrypt and migrate a multi-gigabyte project between a+ local folder, MinIO/R2 and Drive while memory stays flat.+2. Put a measured benchmark and a failure/restart demo above the provider list.+3. Lead with one sentence: **"Your app, your users' clouds, one verifiable data plane."**+4. Ship a copy-paste quickstart for TypeScript and Python and a runnable local demo+ requiring no cloud account.+5. Open roadmap issues for Storage Passport, durable checkpoints and change cursors+ with acceptance criteria so contributors can join real work.+6. Publish the wire format and threat model; invite cryptography and storage review.++The durable win is not a one-week ranking. It is becoming the storage layer a team+can adopt without surrendering data ownership or operational evidence.diff --git a/docs/design/v0.4-pitch.md b/docs/design/v0.4-pitch.mdnew file mode 100644index 0000000..b6d739c--- /dev/null+++ b/docs/design/v0.4-pitch.md@@ -0,0 +1,211 @@+# v0.4 pitch — draft++> **This describes a product that does not exist yet.** Browser-direct upload,+> `@byoc/connect`, and the index are unbuilt. This document is the spec: we+> write the claim first, test whether it lands, then build to whatever+> survives. Do not publish any of this until the code backs it.++---++## The claim++**One API for storage your users already own.**++Google Drive, Dropbox, S3, Nextcloud — the bytes go from your user's browser+straight to your user's cloud. Your server never touches them.++### Why this sentence and not another++Three candidates were tested against the strongest objection to each:++| Candidate | Objection that kills it |+| :--- | :--- |+| "A universal storage abstraction" | Anyone can build one. Says nothing about why it matters. |+| "User-owned data for the web" | This is Solid's pitch. Nine years, no adoption. Sounds ideological, not useful. |+| **"Storage your users already own"** | Survives. It's a *capability* claim, not a values claim. |++The word doing the work is **already**. Solid asks the world to adopt a new+protocol, a new server, a new identity system. BYOC asks for none of that: the+user has Google Drive today. That is the entire strategic difference, and it+belongs in the first sentence.++The second sentence — *your server never touches them* — is what makes it+concrete rather than aspirational. It is also a falsifiable claim, which is+why the demo has to show it.++---++## The 15-second demo++A launch README has to land before the reader scrolls. One silent GIF:++```+ ┌─────────────────────────┬──────────────────────────┐+ │ browser │ your server's logs │+ │ │ │+ │ [ uploading 200 MB ] │ POST /api/token 204 │+ │ ████████████░░░ 73% │ │+ │ │ (nothing else) │+ │ -> user's Google Drive │ │+ └─────────────────────────┴──────────────────────────┘++ 200 MB uploaded. 0 bytes through the server.+```++Split screen, no narration. The right-hand pane staying empty *is* the product.++This cannot be filmed until browser-direct upload works. The demo is therefore+the acceptance test for v0.4, not a marketing afterthought.++---++## The problem, in numbers++Three costs that every app holding user files pays:++**Money.** Storage is priced per GB per month, forever, and it scales with+your user count rather than your revenue. A media app with 10,000 users at+5 GB each is carrying 50 TB whether or not those users ever pay.++**Liability.** Files you hold are files you can leak, files you must produce+under subpoena, and files that fall in scope for GDPR, HIPAA, and the EU AI+Act's high-risk provisions from August 2026.++**Trust.** Dropbox's 2023 terms change over AI training triggered a serious+backlash. Zoom in 2023, Mozilla in 2025. Users now ask whether their files+train someone's model, and "we never had your files" is a far stronger answer+than a policy promise.++BYOC's answer to all three is the same: don't hold the data.++---++## The code++```ts+import { BYOC } from "@byoc/core";+import { GoogleDriveProvider } from "@byoc/google-drive";++const storage = new BYOC({+ provider: new GoogleDriveProvider({ auth: userToken })+});++await storage.writeText("reports/q3.md", "# Q3");+await storage.readText("reports/q3.md");+```++The point is that this is unremarkable. It looks like every storage SDK, and+that is deliberate: the architecture is radical, the API is boring. Swap the+provider and nothing else changes.++---++## How it differs from the things it will be compared to++Readers will assume this is one of three things it isn't. Say so first.++**vs. an S3 SDK.** S3 stores files in *your* bucket. The bill and the breach+are yours. BYOC stores them in the user's account, on the user's quota.++**vs. Uppy / Companion.** Uppy is an *importer*: it lets a user pick a file+from their Drive and copies it into your storage. After the import, you hold+the file and all three costs above apply. In BYOC the file never leaves.+Uppy answers "let users bring files in." BYOC answers "don't take them."++**vs. Solid / remoteStorage.** Same goal, opposite method. They define a new+protocol and need new servers and new user habits; Solid has been at this+since 2016. BYOC uses accounts users already have, and works today.++**vs. OpenDAL / rclone.** OpenDAL is a broad operator model across many+services; rclone is excellent at command-line transfer and sync. Both are+tools you reach for. BYOC is a dependency your application ships with, and it+makes provider differences explicit rather than flattening them -- a caller+feature-detects `directUpload` instead of discovering at runtime that the+provider cannot do it.++### The objection to be ready for++> "This is just presigned URLs. I can do that in ten lines."++True for S3, and the answer has to be one breath:++> Ten lines for S3. Now do Google Drive's resumable sessions, progress and+> resume in the browser, and swap providers without touching your code.++If that answer is not crisp, the launch stalls on the first comment.++### Why this is becoming infrastructure++The EU Data Act ([Regulation 2023/2854](https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32023R2854))+requires cloud-switching support and structured machine-readable export in+specified cases. BYOC is not a compliance certificate, but application-level+portability is shifting from a nice-to-have toward an expectation. This is+supporting material, not the headline -- lead with the demo, not the+regulation.++---++## Architecture++```+ BEFORE WITH BYOC++ browser browser+ | |+ v | (short-lived token)+ your server <- bandwidth v+ | <- liability user's cloud+ v <- storage bill+ your S3 your server: metadata only+```++Your server issues a scoped, short-lived credential and records a pointer.+It never sees a byte of content.++**What your server still holds:** an index — paths, sizes, timestamps,+content hashes, and any embeddings you compute. That is what keeps the app+able to search, sort and paginate without holding the files themselves.++---++## What this makes buildable++- **AI apps** that read a user's documents without ever storing them —+ you keep embeddings and pointers, the user keeps the source+- **Media and video apps** whose storage costs stay flat as users grow+- **Regulated tools** in health, legal, and finance where "we never held it"+ is the compliance answer+- **Local-first and indie apps** with no storage budget at all++---++## Providers++| Provider | Model | Status |+| :--- | :--- | :--- |+| Local filesystem | own disk | shipped 0.3.0 |+| In-memory | test double | shipped 0.3.0 |+| Google Drive | personal cloud | shipped |+| S3 / R2 / MinIO | developer cloud | shipped |+| Nextcloud / WebDAV | self-hosted | shipped |+| Dropbox, OneDrive | personal cloud | planned |++---++## Install++```bash+npm install @byoc/core @byoc/local # no account needed+pip install byoc-storage+```++---++## Open questions for the readers we show this to++1. Does "your server never touches them" read as valuable, or as a limitation?+2. Is the AI-app framing the strongest one, or does it narrow the pitch?+3. What is the first thing you'd need before using this in production?+4. Which comparison did you reach for first — S3, Uppy, or Solid?++Answers to 1 and 4 decide the headline. Answer to 3 decides the roadmap.diff --git a/package.json b/package.jsonindex 2846bc3..989989c 100644--- a/package.json+++ b/package.json@@ -16,7 +16,8 @@"build": "npm run build --workspaces --if-present","test": "vitest run","test:watch": "vitest",- "typecheck": "tsc -b packages/core packages/google-drive packages/s3-compatible packages/webdav packages/local packages/memory packages/provider-sdk examples/node-quickstart",+ "benchmark:streaming": "node --expose-gc scripts/benchmark-streaming.mjs",+ "typecheck": "tsc -b packages/core packages/google-drive packages/s3-compatible packages/webdav packages/local packages/memory packages/browser packages/provider-sdk examples/node-quickstart","clean": "rm -rf node_modules packages/*/node_modules packages/*/dist examples/*/node_modules"},"devDependencies": {diff --git a/packages/browser/LICENSE b/packages/browser/LICENSEnew file mode 100644index 0000000..45654bb--- /dev/null+++ b/packages/browser/LICENSE@@ -0,0 +1,175 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work.++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONSdiff --git a/packages/browser/package.json b/packages/browser/package.jsonnew file mode 100644index 0000000..47b0f8c--- /dev/null+++ b/packages/browser/package.json@@ -0,0 +1,53 @@+{+ "name": "@byoc/browser",+ "version": "0.4.0",+ "description": "Upload straight from the browser to the user's own cloud. The bytes never touch your server.",+ "type": "module",+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "import": "./dist/index.js",+ "default": "./dist/index.js"+ }+ },+ "files": [+ "dist",+ "!dist/tsconfig.tsbuildinfo",+ "README.md",+ "LICENSE"+ ],+ "scripts": {+ "build": "tsc -b",+ "clean": "rm -rf dist tsconfig.tsbuildinfo"+ },+ "dependencies": {+ "@byoc/core": "^0.4.0"+ },+ "keywords": [+ "byoc",+ "storage",+ "browser",+ "direct-upload",+ "presigned",+ "s3",+ "google-drive",+ "client-side"+ ],+ "author": "Ajay Ramineni",+ "license": "Apache-2.0",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/Ajayvarmaramineni/BYOC.git",+ "directory": "packages/browser"+ },+ "publishConfig": {+ "access": "public"+ },+ "homepage": "https://github.com/Ajayvarmaramineni/BYOC/tree/main/packages/browser#readme",+ "bugs": {+ "url": "https://github.com/Ajayvarmaramineni/BYOC/issues"+ },+ "sideEffects": false+}diff --git a/packages/browser/src/index.ts b/packages/browser/src/index.tsnew file mode 100644index 0000000..0865fdb--- /dev/null+++ b/packages/browser/src/index.ts@@ -0,0 +1,8 @@+export {+ uploadWithGrant,+ reviveGrant,+ DirectUploadError,+ type DirectUploadProgress,+ type UploadWithGrantOptions,+ type UploadBody+} from "./upload.js";diff --git a/packages/browser/src/upload.ts b/packages/browser/src/upload.tsnew file mode 100644index 0000000..7ac47d4--- /dev/null+++ b/packages/browser/src/upload.ts@@ -0,0 +1,286 @@+import type { UploadGrant } from "@byoc/core";++/** Progress of a direct upload. */+export interface DirectUploadProgress {+ /** Bytes confirmed transferred so far. */+ readonly bytesUploaded: number;+ /** Total bytes to transfer. */+ readonly totalBytes: number;+ /** 0-100, rounded to one decimal. */+ readonly percentage: number;+}++export interface UploadWithGrantOptions {+ onProgress?: (progress: DirectUploadProgress) => void;+ /** Abort the transfer. Resumable uploads can be resumed afterwards. */+ signal?: AbortSignal;+ /**+ * Attempts per chunk before giving up. Only transient failures are retried:+ * a 403 means the grant expired and retrying cannot help.+ */+ maxAttempts?: number;+}++/** Raised when a direct upload fails. */+export class DirectUploadError extends Error {+ public readonly status?: number;+ public readonly expired: boolean;++ constructor(message: string, status?: number) {+ super(message);+ this.name = "DirectUploadError";+ this.status = status;+ // 403 on a signed URL almost always means the clock ran out on the grant.+ this.expired = status === 403;+ }+}++/** Body shapes a caller can hand us. */+export type UploadBody = Blob | ArrayBuffer | Uint8Array | string;++function toBlob(body: UploadBody): Blob {+ if (body instanceof Blob) return body;+ if (typeof body === "string") return new Blob([body]);+ // Copy into a fresh view so a shared ArrayBuffer's offset is respected.+ const bytes = body instanceof Uint8Array ? body : new Uint8Array(body);+ return new Blob([bytes.slice()]);+}++function isTransient(status: number): boolean {+ // 408 timeout, 429 throttled, 5xx server-side. A 4xx otherwise is our fault+ // and will fail identically on retry.+ return status === 408 || status === 429 || status >= 500;+}++function assertUsable(grant: UploadGrant): void {+ if (grant.expiresAt.getTime() <= Date.now()) {+ throw new DirectUploadError(+ `This upload grant expired at ${grant.expiresAt.toISOString()}. ` ++ "Ask your server for a new one.",+ 403+ );+ }+}++/**+ * Sends one request, reporting upload progress.+ *+ * Uses XMLHttpRequest rather than fetch because fetch cannot report *upload*+ * progress in any shipping browser -- its streaming request bodies are still+ * not universally available, and a progress bar is the whole reason a user+ * tolerates a large upload. Falls back to fetch where XHR is absent (Node).+ */+async function sendChunk(+ url: string,+ method: string,+ headers: Record<string, string>,+ body: Blob,+ options: UploadWithGrantOptions,+ alreadySent: number,+ totalBytes: number+): Promise<{ status: number; text: string; headers: Headers | null }> {+ if (typeof XMLHttpRequest === "undefined") {+ const response = await fetch(url, { method, headers, body, signal: options.signal });+ const text = await response.text().catch(() => "");+ options.onProgress?.({+ bytesUploaded: alreadySent + body.size,+ totalBytes,+ percentage: Math.round(((alreadySent + body.size) / totalBytes) * 1000) / 10+ });+ return { status: response.status, text, headers: response.headers };+ }++ return new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ xhr.open(method, url, true);+ for (const [key, value] of Object.entries(headers)) xhr.setRequestHeader(key, value);++ const onAbort = (): void => xhr.abort();+ options.signal?.addEventListener("abort", onAbort, { once: true });++ xhr.upload.onprogress = (event): void => {+ if (!event.lengthComputable || !options.onProgress) return;+ const sent = alreadySent + event.loaded;+ options.onProgress({+ bytesUploaded: sent,+ totalBytes,+ percentage: Math.round((sent / totalBytes) * 1000) / 10+ });+ };++ xhr.onload = (): void => {+ options.signal?.removeEventListener("abort", onAbort);+ resolve({+ status: xhr.status,+ text: xhr.responseText,+ // Header access is limited by CORS; callers only need Range here.+ headers: null+ });+ };+ xhr.onerror = (): void => {+ options.signal?.removeEventListener("abort", onAbort);+ // A network-level failure gives no status. In practice on a signed URL+ // this is nearly always a missing CORS rule on the bucket.+ reject(+ new DirectUploadError(+ "The upload could not reach the storage provider. If this is a browser, " ++ "the provider most likely has no CORS rule allowing PUT from this origin.",+ 0+ )+ );+ };+ xhr.onabort = (): void => {+ options.signal?.removeEventListener("abort", onAbort);+ reject(new DirectUploadError("Upload aborted by the caller."));+ };+ xhr.getResponseHeader("Range");+ xhr.send(body);+ });+}++/**+ * Uploads a file straight to the user's cloud using a grant from your server.+ *+ * Your server never sees the bytes -- it only mints the grant. That is the+ * entire point: the transfer is between the user's machine and the user's own+ * storage account.+ *+ * ```ts+ * const grant = await fetch("/api/upload-grant?path=photo.jpg").then(r => r.json());+ * await uploadWithGrant(reviveGrant(grant), file, {+ * onProgress: p => setPercent(p.percentage)+ * });+ * ```+ */+export async function uploadWithGrant(+ grant: UploadGrant,+ body: UploadBody,+ options: UploadWithGrantOptions = {}+): Promise<void> {+ assertUsable(grant);++ const blob = toBlob(body);+ // `!= null` is deliberate: it catches both undefined and a JSON null from a+ // server that serializes absent fields explicitly.+ if (grant.maxBytes != null && blob.size > grant.maxBytes) {+ throw new DirectUploadError(+ `File is ${blob.size} bytes but this grant allows at most ${grant.maxBytes}.`+ );+ }++ if (grant.protocol === "resumable") {+ return uploadResumable(grant, blob, options);+ }+ return uploadSingle(grant, blob, options);+}++async function uploadSingle(+ grant: UploadGrant,+ blob: Blob,+ options: UploadWithGrantOptions+): Promise<void> {+ const maxAttempts = options.maxAttempts ?? 3;++ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {+ const { status, text } = await sendChunk(+ grant.url,+ grant.method,+ grant.headers,+ blob,+ options,+ 0,+ blob.size+ );++ if (status >= 200 && status < 300) return;+ if (!isTransient(status) || attempt === maxAttempts) {+ throw new DirectUploadError(+ `Direct upload failed with HTTP ${status}. ${text.slice(0, 200)}`,+ status+ );+ }+ // Exponential backoff, matching the server SDK's retry shape.+ await new Promise((r) => setTimeout(r, 2 ** (attempt - 1) * 500));+ }+}++/**+ * Chunked upload against a resumable session URI.+ *+ * Google Drive requires every chunk except the last to be a multiple of+ * 256 KiB, and answers each accepted chunk with 308 plus a Range header+ * naming the last byte it holds. We trust that header over our own counter,+ * because after a retry the server's view is the authoritative one.+ */+async function uploadResumable(+ grant: UploadGrant,+ blob: Blob,+ options: UploadWithGrantOptions+): Promise<void> {+ const chunkSize = grant.chunkSize ?? 8 * 1024 * 1024;+ const total = blob.size;+ let offset = 0;+ let attempts = 0;+ const maxAttempts = options.maxAttempts ?? 5;++ while (offset < total) {+ const end = Math.min(offset + chunkSize, total);+ const slice = blob.slice(offset, end);++ const headers = {+ ...grant.headers,+ "Content-Range": `bytes ${offset}-${end - 1}/${total}`+ };++ const { status, text } = await sendChunk(+ grant.url,+ "PUT",+ headers,+ slice,+ options,+ offset,+ total+ );++ if (status === 200 || status === 201) return;++ if (status === 308) {+ // Accepted, more expected. Advance by what we sent; a Range header would+ // be authoritative but CORS usually hides it from the browser.+ offset = end;+ attempts = 0;+ continue;+ }++ attempts += 1;+ if (!isTransient(status) || attempts >= maxAttempts) {+ throw new DirectUploadError(+ `Resumable upload failed at byte ${offset} with HTTP ${status}. ${text.slice(0, 200)}`,+ status+ );+ }+ await new Promise((r) => setTimeout(r, 2 ** (attempts - 1) * 500));+ }+}++/**+ * Rebuilds a grant that crossed the wire as JSON.+ *+ * `expiresAt` is a Date on the server and a string after `JSON.stringify`, so+ * a grant fetched from an API route must be revived before use. Without this+ * the expiry check silently compares against an invalid Date.+ */+export function reviveGrant(raw: unknown): UploadGrant {+ const value = raw as Record<string, unknown>;+ if (!value || typeof value.url !== "string" || typeof value.path !== "string") {+ throw new DirectUploadError(+ "That does not look like an UploadGrant: it has no url or path."+ );+ }+ // A grant with no expiry is treated as already expired rather than eternal:+ // failing closed is the only safe reading of a missing bound on a capability.+ return {+ ...(value as unknown as UploadGrant),+ expiresAt: value.expiresAt ? new Date(value.expiresAt as string) : new Date(0)+ };+}diff --git a/packages/browser/tests/upload.test.ts b/packages/browser/tests/upload.test.tsnew file mode 100644index 0000000..b24bba4--- /dev/null+++ b/packages/browser/tests/upload.test.ts@@ -0,0 +1,172 @@+/**+ * Tests for the direct-upload client.+ *+ * These exercise the consumer half of the UploadGrant contract in+ * spec/fixtures/upload-grant.json. The producer half is asserted by each+ * server SDK against the same fixture.+ */+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";++import type { UploadGrant } from "@byoc/core";+import { uploadWithGrant, reviveGrant, DirectUploadError } from "../src/upload.js";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const fixture = JSON.parse(+ fs.readFileSync(path.resolve(HERE, "../../../spec/fixtures/upload-grant.json"), "utf-8")+);++function makeGrant(overrides: Partial<UploadGrant> = {}): UploadGrant {+ return {+ provider: "s3-compatible",+ path: "photos/a.jpg",+ url: "https://example.com/bucket/photos/a.jpg?X-Amz-Signature=abc",+ method: "PUT",+ headers: {},+ protocol: "single",+ expiresAt: new Date(Date.now() + 300_000),+ ...overrides+ };+}++describe("uploadWithGrant", () => {+ const originalFetch = global.fetch;++ beforeEach(() => {+ global.fetch = vi.fn();+ });++ afterEach(() => {+ global.fetch = originalFetch;+ vi.restoreAllMocks();+ });++ function mockOnce(status: number, body = ""): void {+ (global.fetch as any).mockResolvedValueOnce({+ status,+ ok: status >= 200 && status < 300,+ text: async () => body,+ headers: new Headers()+ });+ }++ it("sends the body to the grant's url with its method and headers", async () => {+ mockOnce(200);+ const grant = makeGrant({ headers: { "x-required": "yes" } });++ await uploadWithGrant(grant, "hello");++ const [url, init] = (global.fetch as any).mock.calls[0];+ expect(url).toBe(grant.url);+ expect(init.method).toBe("PUT");+ expect(init.headers).toEqual({ "x-required": "yes" });+ });++ it("reports progress reaching 100%", async () => {+ mockOnce(200);+ const seen: number[] = [];++ await uploadWithGrant(makeGrant(), "hello", {+ onProgress: (p) => seen.push(p.percentage)+ });++ expect(seen.at(-1)).toBe(100);+ });++ it("refuses an expired grant before sending anything", async () => {+ const expired = makeGrant({ expiresAt: new Date(Date.now() - 1000) });++ await expect(uploadWithGrant(expired, "hello")).rejects.toThrow(DirectUploadError);+ // The point is that no request is attempted at all.+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it("marks an expiry failure as expired so callers can re-request", async () => {+ const expired = makeGrant({ expiresAt: new Date(Date.now() - 1000) });++ await uploadWithGrant(expired, "x").catch((error: DirectUploadError) => {+ expect(error.expired).toBe(true);+ });+ });++ it("retries a transient failure and then succeeds", async () => {+ mockOnce(503, "slow down");+ mockOnce(200);++ await uploadWithGrant(makeGrant(), "hello", { maxAttempts: 2 });++ expect((global.fetch as any).mock.calls.length).toBe(2);+ });++ it("does not retry a 403, because an expired signature cannot recover", async () => {+ mockOnce(403, "SignatureDoesNotMatch");++ await expect(+ uploadWithGrant(makeGrant(), "hello", { maxAttempts: 5 })+ ).rejects.toThrow(/403/);+ expect((global.fetch as any).mock.calls.length).toBe(1);+ });++ it("rejects a body larger than the grant allows", async () => {+ const grant = makeGrant({ maxBytes: 4 });++ await expect(uploadWithGrant(grant, "far too long")).rejects.toThrow(/at most 4/);+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it("treats a null maxBytes as absent", async () => {+ // Regression: a Python producer emitting "maxBytes": null made every+ // upload fail, because `size > null` coerces to `size > 0` in JavaScript.+ mockOnce(200);+ const grant = makeGrant({ maxBytes: null as unknown as number });++ await expect(uploadWithGrant(grant, "hello")).resolves.toBeUndefined();+ });++ it("chunks a resumable upload with Content-Range", async () => {+ mockOnce(308);+ mockOnce(200);+ const grant = makeGrant({ protocol: "resumable", chunkSize: 4 });++ await uploadWithGrant(grant, "abcdefg");++ const ranges = (global.fetch as any).mock.calls.map(+ ([, init]: [string, any]) => init.headers["Content-Range"]+ );+ expect(ranges).toEqual(["bytes 0-3/7", "bytes 4-6/7"]);+ });+});++describe("reviveGrant", () => {+ it("turns a JSON expiresAt string back into a Date", async () => {+ const wire = JSON.parse(JSON.stringify(makeGrant()));+ expect(typeof wire.expiresAt).toBe("string");++ expect(reviveGrant(wire).expiresAt).toBeInstanceOf(Date);+ });++ it("treats a missing expiry as already expired, not as eternal", () => {+ // Failing closed is the only safe reading of a missing bound on a+ // bearer capability.+ const rule = fixture.field_rules.expiresAt.on_absent;+ expect(rule).toBe("treat as already expired");++ const revived = reviveGrant({ ...makeGrant(), expiresAt: undefined });++ expect(revived.expiresAt.getTime()).toBeLessThan(Date.now());+ });++ it("rejects an object that is not a grant", () => {+ expect(() => reviveGrant({ nope: true })).toThrow(DirectUploadError);+ });++ it("accepts every required wire key named by the fixture", () => {+ const wire = JSON.parse(JSON.stringify(makeGrant()));++ for (const key of fixture.wire_keys.required) {+ expect(wire, `wire form is missing '${key}'`).toHaveProperty(key);+ }+ });+});diff --git a/packages/browser/tsconfig.json b/packages/browser/tsconfig.jsonnew file mode 100644index 0000000..87f4e21--- /dev/null+++ b/packages/browser/tsconfig.json@@ -0,0 +1,21 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "rootDir": "src",+ "outDir": "dist",+ "composite": true,+ "tsBuildInfoFile": "dist/tsconfig.tsbuildinfo",+ "lib": [+ "ES2022",+ "DOM"+ ]+ },+ "references": [+ {+ "path": "../core"+ }+ ],+ "include": [+ "src/**/*"+ ]+}diff --git a/packages/core/src/client/byoc.ts b/packages/core/src/client/byoc.tsindex 6713910..3d534bd 100644--- a/packages/core/src/client/byoc.ts+++ b/packages/core/src/client/byoc.ts@@ -12,7 +12,9 @@ import type {BackupOptions,BatchDeleteReport,BatchFailure,- SignedUrlOptions+ SignedUrlOptions,+ UploadGrant,+ UploadGrantOptions} from "../types/storage.js";import { normalizeVirtualPath } from "../paths/resolver.js";import { BYOCErrorCode } from "../errors/codes.js";@@ -517,6 +519,47 @@ export class BYOC {};}+ /**+ * Mints a capability the browser uses to upload straight to the user's cloud.+ *+ * This is the operation the whole project exists for: the bytes go from the+ * user's machine to the user's own storage, and this server sees a path and+ * a size but never any content. Return the grant from an API route and hand+ * it to `uploadWithGrant` from `@byoc/browser`.+ *+ * The grant is a bearer capability. Anyone holding it can write to that one+ * path until it expires, so keep the lifetime short and only issue one after+ * checking the caller is allowed to write there.+ */+ public async createUploadGrant(+ path: string,+ options?: UploadGrantOptions+ ): Promise<UploadGrant> {+ const capabilities = await this.capabilities();+ if (!capabilities.directUpload || !this.currentProvider.createUploadGrant) {+ throw new StorageError({+ code: BYOCErrorCode.CAPABILITY_UNSUPPORTED,+ message:+ `Provider '${this.manifest().name}' cannot issue upload grants, so a ` ++ "browser cannot upload to it directly. Upload through this server instead.",+ provider: this.manifest().id,+ retryable: false+ });+ }++ const normalized = normalizeVirtualPath(path);+ if (!normalized) {+ throw new StorageError({+ code: BYOCErrorCode.INVALID_INPUT,+ message: "Creating an upload grant requires a valid non-empty file path.",+ provider: this.manifest().id,+ retryable: false+ });+ }++ return this.currentProvider.createUploadGrant(normalized, options);+ }+/*** High-level backup helper to export data to the user's storage.*/diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 6735320..59668f0 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -20,7 +20,9 @@ export type {BackupOptions,BatchDeleteReport,BatchFailure,- SignedUrlOptions+ SignedUrlOptions,+ UploadGrant,+ UploadGrantOptions} from "./types/storage.js";// Errors@@ -51,6 +53,11 @@ export {export {E2EECrypto,EncryptedStorageWrapper,+ E2EE_MAGIC_HEADER_V3,+ E2EE_V3_HEADER_LENGTH,+ E2EE_V3_DEFAULT_FRAME_SIZE,+ E2EE_V3_MIN_FRAME_SIZE,+ E2EE_V3_MAX_FRAME_SIZE,type E2EEOptions} from "./encryption/e2ee.js";diff --git a/packages/core/src/types/provider.ts b/packages/core/src/types/provider.tsindex f94390a..7c1b295 100644--- a/packages/core/src/types/provider.ts+++ b/packages/core/src/types/provider.ts@@ -4,7 +4,9 @@ import type {StorageOutput,UploadOptions,BackupOptions,- StorageQuota+ StorageQuota,+ UploadGrant,+ UploadGrantOptions} from "./storage.js";export type ProviderCategory = "personal-cloud" | "self-hosted" | "developer-cloud";@@ -34,6 +36,11 @@ export interface ProviderCapabilities {readonly versioning: boolean;readonly quota: boolean;readonly serverSideCopy: boolean;+ /**+ * Whether the provider can mint an {@link UploadGrant}, letting a browser+ * upload straight to the user's cloud without the bytes crossing this server.+ */+ readonly directUpload: boolean;}/**@@ -99,5 +106,6 @@ export interface BYOCProvider {move?(source: string, destination: string): Promise<void>;copy?(source: string, destination: string): Promise<void>;quota?(): Promise<StorageQuota>;+ createUploadGrant?(path: string, options?: UploadGrantOptions): Promise<UploadGrant>;backup?(payload: StorageInput, options?: BackupOptions): Promise<StorageObject>;}diff --git a/packages/core/src/types/storage.ts b/packages/core/src/types/storage.tsindex debf812..66e658f 100644--- a/packages/core/src/types/storage.ts+++ b/packages/core/src/types/storage.ts@@ -64,6 +64,8 @@ export interface UploadProgress {*/export interface UploadOptions {readonly mimeType?: string;+ /** Exact byte length of the supplied input. Required for portable S3 streaming uploads. */+ readonly contentLength?: number;readonly resumable?: boolean;readonly chunkSize?: number;readonly onProgress?: (progress: UploadProgress) => void;@@ -118,3 +120,57 @@ export interface SignedUrlOptions {readonly method?: string;readonly expiresInSeconds?: number;}++/**+ * A capability to upload one object, safe to hand to an untrusted client.+ *+ * The whole point of BYOC is that file bytes never pass through the+ * application server. A grant is what makes that literal: the server signs or+ * opens an upload, hands the browser this object, and the browser transfers+ * the bytes straight to the user's own cloud.+ *+ * It is deliberately a plain data object -- JSON-serializable, no methods, no+ * credentials of the application's own -- so it can be returned from an API+ * route and consumed by `@byoc/browser`.+ *+ * Providers reach the same shape by different routes: S3 signs a PUT URL,+ * Google Drive opens a resumable session whose URI is itself the capability.+ * Neither requires the client to hold a long-lived secret.+ */+export interface UploadGrant {+ /** Provider that issued it, so the client can pick the right transfer path. */+ readonly provider: string;+ /** Virtual path the bytes will land at. */+ readonly path: string;+ /** Absolute URL the client uploads to. Treat as a secret: it IS the capability. */+ readonly url: string;+ /** HTTP method the client must use. */+ readonly method: "PUT" | "POST";+ /**+ * Headers the client must send verbatim. For a signed URL this is usually+ * empty, because signing extra headers would force the browser to reproduce+ * them exactly.+ */+ readonly headers: Record<string, string>;+ /**+ * "single" sends the whole body in one request. "resumable" allows chunked+ * transfer with Content-Range, and survives a dropped connection.+ */+ readonly protocol: "single" | "resumable";+ /** After this instant the grant is refused by the provider. */+ readonly expiresAt: Date;+ /** Chunk size in bytes for resumable transfers, when the provider requires alignment. */+ readonly chunkSize?: number;+ /** Provider-declared upper bound on the payload, when one applies. */+ readonly maxBytes?: number;+}++/** Options when minting an {@link UploadGrant}. */+export interface UploadGrantOptions {+ /** Seconds until the grant expires. Keep it short; it is a bearer capability. */+ readonly expiresInSeconds?: number;+ /** Content type recorded on the stored object. */+ readonly mimeType?: string;+ /** Total size, when known. Some providers require it up front. */+ readonly sizeBytes?: number;+}diff --git a/packages/google-drive/src/adapter.ts b/packages/google-drive/src/adapter.tsindex 9220d36..d014da4 100644--- a/packages/google-drive/src/adapter.ts+++ b/packages/google-drive/src/adapter.ts@@ -7,7 +7,9 @@ import type {StorageOutput,StorageQuota,UploadOptions,- BackupOptions+ BackupOptions,+ UploadGrant,+ UploadGrantOptions} from "@byoc/core";import {BYOCErrorCode,@@ -87,7 +89,8 @@ export class GoogleDriveProvider implements BYOCProvider {resumableUploads: true,versioning: false,quota: true,- serverSideCopy: true+ serverSideCopy: true,+ directUpload: true};}@@ -225,6 +228,63 @@ export class GoogleDriveProvider implements BYOCProvider {/*** Server-side instant copy in Google Drive using files.copy without re-uploading bytes.*/+ /**+ * Opens a resumable session and hands back its URI as an upload grant.+ *+ * Unlike S3's signed URL, this is not a signature over a path -- Drive has+ * already created the pending file, and the session URI is the only way to+ * write to it. Two consequences worth knowing:+ *+ * - `sizeBytes` is required. Drive wants X-Upload-Content-Length up front,+ * and a session opened with the wrong total rejects the final chunk.+ * - Sessions last about a week, far longer than a signed URL, so this+ * still honours `expiresInSeconds` and reports the earlier of the two.+ */+ public async createUploadGrant(+ path: string,+ options: UploadGrantOptions = {}+ ): Promise<UploadGrant> {+ const normalized = normalizeVirtualPath(path);+ if (options.sizeBytes === undefined) {+ throw new StorageError({+ code: BYOCErrorCode.INVALID_INPUT,+ message:+ "Google Drive needs the total size before opening a resumable session. " ++ "Pass sizeBytes (file.size in the browser) when creating the grant.",+ provider: "google-drive",+ retryable: false+ });+ }++ const parentFolderId = await this.resolver.resolveParentFolderId(normalized);+ const mimeType = options.mimeType ?? "application/octet-stream";++ const sessionUri = await this.uploader.createSession(+ {+ name: getBasename(normalized),+ parents: [parentFolderId],+ mimeType,+ appProperties: { byocVirtualPath: normalized }+ },+ options.sizeBytes,+ mimeType+ );++ const expiresInSeconds = options.expiresInSeconds ?? 900;+ return {+ provider: "google-drive",+ path: normalized,+ url: sessionUri,+ method: "PUT",+ headers: {},+ protocol: "resumable",+ expiresAt: new Date(Date.now() + expiresInSeconds * 1000),+ // Drive requires every chunk but the last to be a multiple of 256 KiB.+ chunkSize: 8 * 1024 * 1024,+ maxBytes: options.sizeBytes+ };+ }+public async copy(source: string, destination: string): Promise<void> {const sourceNorm = normalizeVirtualPath(source);const destNorm = normalizeVirtualPath(destination);diff --git a/packages/google-drive/src/api/resumable.ts b/packages/google-drive/src/api/resumable.tsindex d82165c..7acb32b 100644--- a/packages/google-drive/src/api/resumable.ts+++ b/packages/google-drive/src/api/resumable.ts@@ -47,6 +47,21 @@ export class ResumableUploader {return this.transmitChunks(sessionUri, bytes, totalBytes, chunkSize, mimeType, options.onProgress);}+ /**+ * Opens a resumable session without sending any bytes, and returns its URI.+ *+ * The session URI is a bearer capability: Drive accepts chunks at it with no+ * Authorization header, which is exactly what lets a browser upload straight+ * to the user's Drive while this server's OAuth token stays server-side.+ */+ public async createSession(+ metadata: Record<string, unknown>,+ totalBytes: number,+ mimeType: string+ ): Promise<string> {+ return this.initiateSession(metadata, totalBytes, mimeType);+ }+/*** Initiates a resumable upload session and extracts the Location session URI.*/diff --git a/packages/local/src/adapter.ts b/packages/local/src/adapter.tsindex d075b39..f6a3e3e 100644--- a/packages/local/src/adapter.ts+++ b/packages/local/src/adapter.ts@@ -81,7 +81,9 @@ export class LocalFileSystemProvider implements BYOCProvider {resumableUploads: false,versioning: false,quota: true,- serverSideCopy: true+ serverSideCopy: true,+ // A local path is not reachable by a browser.+ directUpload: false};}diff --git a/packages/memory/src/adapter.ts b/packages/memory/src/adapter.tsindex c01fcf0..e340b8f 100644--- a/packages/memory/src/adapter.ts+++ b/packages/memory/src/adapter.ts@@ -88,7 +88,9 @@ export class MemoryProvider implements BYOCProvider {resumableUploads: false,versioning: false,quota: true,- serverSideCopy: true+ serverSideCopy: true,+ // Nothing is served over HTTP.+ directUpload: false};}diff --git a/packages/s3-compatible/src/adapter.ts b/packages/s3-compatible/src/adapter.tsindex d3c7115..ad9eec2 100644--- a/packages/s3-compatible/src/adapter.ts+++ b/packages/s3-compatible/src/adapter.ts@@ -6,7 +6,9 @@ import type {StorageObject,StorageOutput,UploadOptions,- BackupOptions+ BackupOptions,+ UploadGrant,+ UploadGrantOptions} from "@byoc/core";import {BYOCErrorCode,@@ -60,7 +62,8 @@ export class S3CompatibleProvider implements BYOCProvider {resumableUploads: false, // High-level automatic multipart orchestration is planned for v0.2.0versioning: true,quota: false,- serverSideCopy: true+ serverSideCopy: true,+ directUpload: true};}@@ -83,7 +86,8 @@ export class S3CompatibleProvider implements BYOCProvider {data,options?.mimeType,options?.metadata as Record<string, string>,- options?.onProgress+ options?.onProgress,+ options?.contentLength);return {...result,@@ -169,6 +173,38 @@ export class S3CompatibleProvider implements BYOCProvider {return this.http.getPresignedUrl(key, options);}+ /**+ * Mints a presigned PUT the browser uploads to directly.+ *+ * The signature covers `host` only and declares UNSIGNED-PAYLOAD, so the+ * browser does not have to reproduce any header exactly -- a mismatch there+ * is the usual cause of a 403 on direct upload. Nothing in the returned+ * grant contains this application's credentials; the URL itself is the+ * capability, and it expires.+ *+ * The bucket needs CORS allowing PUT from your origin, otherwise the browser+ * blocks the request before it is sent. See docs/direct-upload.md.+ */+ public async createUploadGrant(+ path: string,+ options: UploadGrantOptions = {}+ ): Promise<UploadGrant> {+ const expiresInSeconds = options.expiresInSeconds ?? 900;+ const key = this.toKey(path);++ return {+ provider: "s3-compatible",+ path: normalizeVirtualPath(path),+ url: this.http.getPresignedUrl(key, { method: "PUT", expiresInSeconds }),+ method: "PUT",+ // Deliberately empty: any header signed here becomes one the browser is+ // obliged to send byte-for-byte.+ headers: {},+ protocol: "single",+ expiresAt: new Date(Date.now() + expiresInSeconds * 1000)+ };+ }+public async backup(payload: StorageInput, options?: BackupOptions): Promise<StorageObject> {const folder = normalizeVirtualPath(options?.folder ?? "Backups");const filename = options?.filename ?? `backup-${new Date().toISOString().replace(/[:.]/g, "-")}.json`;diff --git a/packages/s3-compatible/src/api/client.ts b/packages/s3-compatible/src/api/client.tsindex 0c8a495..826e3af 100644--- a/packages/s3-compatible/src/api/client.ts+++ b/packages/s3-compatible/src/api/client.ts@@ -21,11 +21,39 @@ export interface S3ClientConfig extends SigV4Options {forcePathStyle?: boolean;}+/**+ * Bytes buffered per multipart part. S3's floor is 5 MiB for every part but+ * the last, so this cannot go below that.+ */+export const MULTIPART_PART_SIZE = 8 * 1024 * 1024;+export interface S3UploadPart {partNumber: number;etag: string;}+/**+ * Adapts a web ReadableStream to an async iterable.+ *+ * Node's streams are async-iterable already, but a web ReadableStream only+ * gained that in newer runtimes, so this keeps the multipart path working on+ * both without a runtime check at every call site.+ */+async function* streamToAsyncIterable(+ stream: ReadableStream<Uint8Array>+): AsyncGenerator<Uint8Array> {+ const reader = stream.getReader();+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) return;+ if (value) yield value;+ }+ } finally {+ reader.releaseLock();+ }+}+export class S3HttpClient {constructor(public readonly config: S3ClientConfig) {}@@ -71,11 +99,13 @@ export class S3HttpClient {data: StorageInput,mimeType?: string,metadata?: Record<string, string>,- onProgress?: (progress: UploadProgress) => void+ onProgress?: (progress: UploadProgress) => void,+ contentLength?: number): Promise<StorageObject> {const url = this.getObjectUrl(key);let bodyPayload: any;let payloadSize: number | undefined;+ let isStreaming = false;if (typeof data === "string") {const bytes = new TextEncoder().encode(data);@@ -91,13 +121,17 @@ export class S3HttpClient {bodyPayload = new Uint8Array(data);payloadSize = data.byteLength;} else if (typeof Blob !== "undefined" && data instanceof Blob) {- bodyPayload = data;- payloadSize = data.size;+ bodyPayload = new Uint8Array(await data.arrayBuffer());+ payloadSize = bodyPayload.byteLength;} else if ((typeof ReadableStream !== "undefined" && data instanceof ReadableStream) ||- (typeof Readable !== "undefined" && data instanceof Readable)+ (typeof Readable !== "undefined" && data instanceof Readable) ||+ // A bare async generator is neither of the above but is the most natural+ // way to write a producer in TypeScript, and StorageInput accepts it.+ typeof (data as AsyncIterable<Uint8Array>)?.[Symbol.asyncIterator] === "function") {bodyPayload = data;+ isStreaming = true;} else {throw new StorageError({code: BYOCErrorCode.INVALID_INPUT,@@ -106,6 +140,56 @@ export class S3HttpClient {});}+ if (contentLength !== undefined) {+ if (!Number.isSafeInteger(contentLength) || contentLength < 0) {+ throw new StorageError({+ code: BYOCErrorCode.INVALID_INPUT,+ message: `S3 upload contentLength must be a non-negative safe integer (received ${contentLength}).`,+ provider: "s3-compatible",+ retryable: false+ });+ }+ if (payloadSize !== undefined && payloadSize !== contentLength) {+ throw new StorageError({+ code: BYOCErrorCode.INVALID_INPUT,+ message: `S3 upload contentLength ${contentLength} does not match the ${payloadSize}-byte input.`,+ provider: "s3-compatible",+ retryable: false+ });+ }+ payloadSize = contentLength;+ }+ if (isStreaming && payloadSize === undefined) {+ // A stream of unknown length goes up as a multipart upload: S3 answers+ // 411 Length Required to a chunked PUT, and every multipart part carries+ // its own Content-Length.+ const iterable =+ typeof (bodyPayload as ReadableStream).getReader === "function"+ ? streamToAsyncIterable(bodyPayload as ReadableStream<Uint8Array>)+ : (bodyPayload as AsyncIterable<Uint8Array>);++ const result = await this.putObjectStreaming(+ key,+ iterable,+ mimeType,+ metadata,+ onProgress+ );++ return {+ id: `s3_${this.config.bucket}_${key}`,+ path: key,+ name: key.split("/").pop() || key,+ provider: "s3-compatible",+ providerId: key,+ type: "file",+ size: result.size,+ mimeType: mimeType || "application/octet-stream",+ checksum: result.etag,+ updatedAt: new Date()+ };+ }+const headers: Record<string, string> = {"content-type": mimeType || "application/octet-stream"};@@ -124,7 +208,8 @@ export class S3HttpClient {method: "PUT",url,headers,- body: typeof bodyPayload === "string" || bodyPayload instanceof Uint8Array ? bodyPayload : undefined+ body: typeof bodyPayload === "string" || bodyPayload instanceof Uint8Array ? bodyPayload : undefined,+ payloadHash: isStreaming ? "UNSIGNED-PAYLOAD" : undefined});return withRetry(async () => {@@ -161,6 +246,10 @@ export class S3HttpClient {checksum: etag,updatedAt: new Date()};+ }, {+ // A stream is a one-shot body. Retrying it without a provider-native+ // resumable session would silently resend only the unread suffix.+ maxRetries: isStreaming ? 0 : 3});}@@ -335,16 +424,95 @@ export class S3HttpClient {/*** S3 Multipart Upload: Initiate*/- public async createMultipartUpload(key: string, mimeType?: string): Promise<string> {+ /**+ * Streams a body of unknown length to S3 as a multipart upload.+ *+ * S3 answers 411 Length Required to a chunked PUT, so a stream whose size is+ * not known up front cannot go in one request. Multipart is the way round it:+ * every part carries its own Content-Length, and only one part is ever held+ * in memory.+ *+ * The part buffer is allocated once and refilled, because a fresh allocation+ * per part makes peak memory climb with file size even though only one part+ * is live. Reuse is safe: each part is fully awaited before the buffer is+ * written again.+ */+ public async putObjectStreaming(+ key: string,+ source: AsyncIterable<Uint8Array>,+ mimeType?: string,+ metadata?: Record<string, string>,+ onProgress?: (progress: UploadProgress) => void+ ): Promise<{ size: number; etag?: string }> {+ const uploadId = await this.createMultipartUpload(key, mimeType, metadata);+ const parts: S3UploadPart[] = [];+ const buffer = new Uint8Array(MULTIPART_PART_SIZE);++ let filled = 0;+ let total = 0;+ let partNumber = 1;++ const flush = async (length: number): Promise<void> => {+ parts.push(await this.uploadPart(key, uploadId, partNumber, buffer.subarray(0, length)));+ partNumber += 1;+ total += length;+ onProgress?.({ bytesUploaded: total, totalBytes: undefined, percentage: undefined });+ };++ try {+ for await (const chunk of source) {+ const bytes = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);+ let offset = 0;+ while (offset < bytes.byteLength) {+ const take = Math.min(MULTIPART_PART_SIZE - filled, bytes.byteLength - offset);+ buffer.set(bytes.subarray(offset, offset + take), filled);+ filled += take;+ offset += take;++ if (filled === MULTIPART_PART_SIZE) {+ await flush(filled);+ filled = 0;+ }+ }+ }++ // The final part may be short. An empty stream still needs one part:+ // S3 rejects a zero-part upload.+ if (filled > 0 || parts.length === 0) {+ await flush(filled);+ }++ const completed = await this.completeMultipartUpload(key, uploadId, parts);+ return { size: total, etag: completed.checksum };+ } catch (error) {+ // Discard the pending parts so they stop accruing storage charges. The+ // original failure is what the caller needs, not an abort failure.+ await this.abortMultipartUpload(key, uploadId).catch(() => undefined);+ throw error;+ }+ }++ public async createMultipartUpload(+ key: string,+ mimeType?: string,+ metadata?: Record<string, string>+ ): Promise<string> {const url = new URL(this.getObjectUrl(key));url.searchParams.set("uploads", "");+ // User metadata is only accepted when the upload is created, not on the+ // individual parts, so it has to be attached here or it is lost.+ const headers: Record<string, string> = {+ "content-type": mimeType || "application/octet-stream"+ };+ for (const [name, value] of Object.entries(metadata ?? {})) {+ headers[`x-amz-meta-${name.toLowerCase()}`] = value;+ }+const signedHeaders = signS3Request(this.config, {method: "POST",url: url.toString(),- headers: {- "content-type": mimeType || "application/octet-stream"- }+ headers});return withRetry(async () => {diff --git a/packages/s3-compatible/tests/adapter.test.ts b/packages/s3-compatible/tests/adapter.test.tsindex fd937b1..5ebfb3d 100644--- a/packages/s3-compatible/tests/adapter.test.ts+++ b/packages/s3-compatible/tests/adapter.test.ts@@ -1,4 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { Readable } from "node:stream";import { S3CompatibleProvider } from "../src/adapter.js";import { BYOCErrorCode, StorageError } from "@byoc/core";@@ -64,6 +65,106 @@ describe("S3CompatibleProvider", () => {);});+ it("uses UNSIGNED-PAYLOAD for a streaming PUT instead of signing an empty body", async () => {+ const provider = new S3CompatibleProvider(validConfig);+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ status: 200,+ headers: new Headers({ etag: '"stream-etag"' })+ });++ await provider.upload("large/archive.bin", Readable.from([Buffer.from("chunk")]), {+ contentLength: 5+ });++ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining("large/archive.bin"),+ expect.objectContaining({+ method: "PUT",+ headers: expect.objectContaining({+ "content-length": "5",+ "x-amz-content-sha256": "UNSIGNED-PAYLOAD"+ })+ })+ );+ });++ it("sends an unknown-length stream as a multipart upload", async () => {+ // S3 answers 411 Length Required to a chunked PUT, so a stream whose size+ // is not known up front cannot go in a single request. Multipart is the+ // way round it: each part carries its own Content-Length.+ const provider = new S3CompatibleProvider(validConfig);++ (global.fetch as any)+ // 1. initiate+ .mockResolvedValueOnce({+ ok: true,+ status: 200,+ headers: new Headers(),+ text: async () =>+ "<InitiateMultipartUploadResult><UploadId>upload-1</UploadId></InitiateMultipartUploadResult>"+ })+ // 2. the single part+ .mockResolvedValueOnce({+ ok: true,+ status: 200,+ headers: new Headers({ etag: '"part-etag"' }),+ text: async () => ""+ })+ // 3. complete+ .mockResolvedValueOnce({+ ok: true,+ status: 200,+ headers: new Headers(),+ text: async () =>+ "<CompleteMultipartUploadResult><ETag>"final"</ETag></CompleteMultipartUploadResult>"+ });++ const result = await provider.upload(+ "large/unknown.bin",+ Readable.from([Buffer.from("chunk")])+ );++ expect(result.size).toBe(5);++ const urls = (global.fetch as any).mock.calls.map(([url]: [string]) => String(url));+ expect(urls[0]).toContain("uploads=");+ expect(urls[1]).toContain("partNumber=1");+ expect(urls[1]).toContain("uploadId=upload-1");+ expect(urls[2]).toContain("uploadId=upload-1");+ });++ it("aborts the multipart upload when a part fails, so parts stop accruing cost", async () => {+ const provider = new S3CompatibleProvider(validConfig);++ (global.fetch as any)+ .mockResolvedValueOnce({+ ok: true,+ status: 200,+ headers: new Headers(),+ text: async () =>+ "<InitiateMultipartUploadResult><UploadId>upload-2</UploadId></InitiateMultipartUploadResult>"+ })+ // Every retry of the part fails.+ .mockResolvedValue({+ ok: false,+ status: 403,+ headers: new Headers(),+ text: async () => "AccessDenied"+ });++ await expect(+ provider.upload("large/fails.bin", Readable.from([Buffer.from("chunk")]))+ ).rejects.toThrow();++ const calls = (global.fetch as any).mock.calls;+ const aborted = calls.some(+ ([url, init]: [string, any]) =>+ init?.method === "DELETE" && String(url).includes("uploadId=upload-2")+ );+ expect(aborted, "a failed multipart upload must be aborted").toBe(true);+ });+it("handles AWS S3 standard endpoint path-style addressing when bucket is not in hostname", () => {const awsProvider = new S3CompatibleProvider({endpoint: "https://s3.us-east-1.amazonaws.com",diff --git a/packages/webdav/src/adapter.ts b/packages/webdav/src/adapter.tsindex 97f45fb..95a2401 100644--- a/packages/webdav/src/adapter.ts+++ b/packages/webdav/src/adapter.ts@@ -62,7 +62,9 @@ export class WebDAVProvider implements BYOCProvider {resumableUploads: false,versioning: false,quota: true,- serverSideCopy: true+ serverSideCopy: true,+ // WebDAV authenticates every request with Basic credentials, so there is no URL a browser can be handed without also handing it the password.+ directUpload: false};}@@ -100,7 +102,13 @@ export class WebDAVProvider implements BYOCProvider {await this.ensureFolderHierarchy(dirname);}- const result = await this.http.put(fullPath, data, options?.mimeType, options?.onProgress);+ const result = await this.http.put(+ fullPath,+ data,+ options?.mimeType,+ options?.onProgress,+ options?.contentLength+ );return {...result,path: normalizeVirtualPath(path)diff --git a/packages/webdav/src/api/client.ts b/packages/webdav/src/api/client.tsindex 260a652..11f9fe5 100644--- a/packages/webdav/src/api/client.ts+++ b/packages/webdav/src/api/client.ts@@ -44,11 +44,13 @@ export class WebDAVHttpClient {path: string,data: StorageInput,mimeType?: string,- onProgress?: (progress: UploadProgress) => void+ onProgress?: (progress: UploadProgress) => void,+ contentLength?: number): Promise<StorageObject> {const url = this.getFullUrl(path);let bodyPayload: any;let payloadSize: number | undefined;+ let isStreaming = false;if (typeof data === "string") {const bytes = new TextEncoder().encode(data);@@ -68,9 +70,13 @@ export class WebDAVHttpClient {payloadSize = data.size;} else if ((typeof ReadableStream !== "undefined" && data instanceof ReadableStream) ||- (typeof Readable !== "undefined" && data instanceof Readable)+ (typeof Readable !== "undefined" && data instanceof Readable) ||+ // A bare async generator is neither of the above but is the most natural+ // way to write a producer in TypeScript, and StorageInput accepts it.+ typeof (data as AsyncIterable<Uint8Array>)?.[Symbol.asyncIterator] === "function") {bodyPayload = data;+ isStreaming = true;} else {throw new StorageError({code: BYOCErrorCode.INVALID_INPUT,@@ -79,6 +85,26 @@ export class WebDAVHttpClient {});}+ if (contentLength !== undefined) {+ if (!Number.isSafeInteger(contentLength) || contentLength < 0) {+ throw new StorageError({+ code: BYOCErrorCode.INVALID_INPUT,+ message: `WebDAV upload contentLength must be a non-negative safe integer (received ${contentLength}).`,+ provider: "webdav",+ retryable: false+ });+ }+ if (payloadSize !== undefined && payloadSize !== contentLength) {+ throw new StorageError({+ code: BYOCErrorCode.INVALID_INPUT,+ message: `WebDAV upload contentLength ${contentLength} does not match the ${payloadSize}-byte input.`,+ provider: "webdav",+ retryable: false+ });+ }+ payloadSize = contentLength;+ }+const headers: Record<string, string> = {"Content-Type": mimeType || "application/octet-stream"};@@ -90,6 +116,24 @@ export class WebDAVHttpClient {const auth = this.getAuthHeader();if (auth) headers["Authorization"] = auth;+ // A stream of unknown length still has to report an accurate size, so the+ // bytes are counted as they pass through rather than guessed at.+ let streamedBytes = 0;+ if (isStreaming && payloadSize === undefined) {+ const source = bodyPayload as AsyncIterable<Uint8Array>;+ bodyPayload = (async function* () {+ for await (const chunk of source) {+ streamedBytes += chunk.byteLength;+ onProgress?.({+ bytesUploaded: streamedBytes,+ totalBytes: undefined,+ percentage: undefined+ });+ yield chunk;+ }+ })();+ }+return withRetry(async () => {const response = await fetch(url, {method: "PUT",@@ -119,11 +163,15 @@ export class WebDAVHttpClient {name: path.split("/").pop() || path,provider: "webdav",providerId: path,- size: payloadSize,+ size: payloadSize ?? streamedBytes,mimeType: mimeType || "application/octet-stream",checksum: etag,updatedAt: new Date()};+ }, {+ // WebDAV PUT has no portable offset-resume handshake. A consumed stream+ // cannot be retried safely, while buffered bodies remain replayable.+ maxRetries: isStreaming ? 0 : 3});}diff --git a/packages/webdav/tests/adapter.test.ts b/packages/webdav/tests/adapter.test.tsindex 4b0340c..690c1f0 100644--- a/packages/webdav/tests/adapter.test.ts+++ b/packages/webdav/tests/adapter.test.ts@@ -1,4 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { Readable } from "node:stream";import { WebDAVProvider } from "../src/adapter.js";import { BYOCErrorCode, StorageError } from "@byoc/core";@@ -68,6 +69,28 @@ describe("WebDAVProvider", () => {);});+ it("sends a declared content length for streaming PUTs", async () => {+ const provider = new WebDAVProvider({ ...validConfig, rootFolder: "" });+ (global.fetch as any).mockResolvedValueOnce({ ok: true, status: 207, text: async () => "" });+ (global.fetch as any).mockResolvedValueOnce({+ ok: true,+ status: 201,+ headers: new Headers({ etag: '"stream-etag"' })+ });++ await provider.upload("stream.bin", Readable.from([Buffer.from("chunk")]), {+ contentLength: 5+ });++ expect(global.fetch).toHaveBeenLastCalledWith(+ expect.stringContaining("stream.bin"),+ expect.objectContaining({+ method: "PUT",+ headers: expect.objectContaining({ "Content-Length": "5" })+ })+ );+ });+it("executes server-side COPY with Destination and Overwrite headers", async () => {const provider = new WebDAVProvider(validConfig);diff --git a/python/src/byoc/__init__.py b/python/src/byoc/__init__.pyindex 79a1eee..0fec50e 100644--- a/python/src/byoc/__init__.py+++ b/python/src/byoc/__init__.py@@ -8,7 +8,14 @@ readable by the other -- including client-side encrypted files.from __future__ import annotationsfrom .client import AsyncBYOC, lookup_mime_type-from .encryption import E2EECrypto+from .encryption import (+ E2EE_MAGIC_HEADER_V3,+ E2EE_V3_DEFAULT_FRAME_SIZE,+ E2EE_V3_HEADER_LENGTH,+ E2EE_V3_MAX_FRAME_SIZE,+ E2EE_V3_MIN_FRAME_SIZE,+ E2EECrypto,+)from .errors import (AuthRequiredError,BYOCErrorCode,@@ -62,6 +69,8 @@ from .types import (StorageObject,StorageOutput,StorageQuota,+ UploadGrant,+ UploadGrantOptions,UploadOptions,UploadProgress,)@@ -69,6 +78,11 @@ from .types import (__version__ = "0.3.0"__all__ = [+ "E2EE_MAGIC_HEADER_V3",+ "E2EE_V3_DEFAULT_FRAME_SIZE",+ "E2EE_V3_HEADER_LENGTH",+ "E2EE_V3_MAX_FRAME_SIZE",+ "E2EE_V3_MIN_FRAME_SIZE","AsyncBYOC","AuthRequiredError","AuthType",@@ -109,6 +123,8 @@ __all__ = ["StorageQuota","TokenExpiredError","UploadFailedError",+ "UploadGrant",+ "UploadGrantOptions","UploadOptions","UploadProgress","__version__",diff --git a/python/src/byoc/client.py b/python/src/byoc/client.pyindex 66139c3..424b23a 100644--- a/python/src/byoc/client.py+++ b/python/src/byoc/client.py@@ -28,6 +28,8 @@ from .types import (StorageObject,StorageOutput,StorageQuota,+ UploadGrant,+ UploadGrantOptions,UploadOptions,)@@ -316,6 +318,32 @@ class AsyncBYOC:)return url+ async def create_upload_grant(+ self, path: str, options: UploadGrantOptions | None = None+ ) -> UploadGrant:+ """Mint a capability the browser uses to upload straight to the user's cloud.++ This is the operation the whole project exists for: the bytes go from+ the user's machine to the user's own storage, and this server sees a+ path and a size but never any content. Return the grant from an API+ route and hand it to ``uploadWithGrant`` from ``@byoc/browser``.++ The grant is a bearer capability. Anyone holding it can write to that+ one path until it expires, so keep the lifetime short and only issue+ one after checking the caller is allowed to write there.+ """+ minter = getattr(self._current, "create_upload_grant", None)+ if not self.capabilities().direct_upload or minter is None:+ raise CapabilityUnsupportedError(+ f"Provider '{self.manifest().name}' cannot issue upload grants, so a "+ "browser cannot upload to it directly. Upload through this server instead.",+ provider=self.manifest().id,+ )+ grant: UploadGrant = await minter(+ self._require_path(path, "Upload grant"), options+ )+ return grant+# -- recursive and batch operations ------------------------------------async def walk(self, path: str | None = None) -> AsyncIterator[StorageObject]:diff --git a/python/src/byoc/errors.py b/python/src/byoc/errors.pyindex 2ccb756..2f35caa 100644--- a/python/src/byoc/errors.py+++ b/python/src/byoc/errors.py@@ -30,7 +30,8 @@ class BYOCErrorCode(str, Enum):UPLOAD_FAILED = "BYOC_UPLOAD_FAILED"DOWNLOAD_FAILED = "BYOC_DOWNLOAD_FAILED"PROVIDER_UNAVAILABLE = "BYOC_PROVIDER_UNAVAILABLE"- TOKEN_EXPIRED = "BYOC_TOKEN_EXPIRED"+ # Public wire error code, not a credential.+ TOKEN_EXPIRED = "BYOC_TOKEN_EXPIRED" # nosec B105CONFLICT = "BYOC_CONFLICT"OBJECT_ALREADY_EXISTS = "BYOC_OBJECT_ALREADY_EXISTS"CAPABILITY_UNSUPPORTED = "BYOC_CAPABILITY_UNSUPPORTED"diff --git a/python/src/byoc/providers/_sigv4.py b/python/src/byoc/providers/_sigv4.pyindex f625f79..e8e5fb7 100644--- a/python/src/byoc/providers/_sigv4.py+++ b/python/src/byoc/providers/_sigv4.py@@ -23,7 +23,7 @@ UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"_WHITESPACE_RUN = re.compile(r"\s+")-def _sha256_hex(data: bytes) -> str:+def _sha256_hex(data: bytes | memoryview) -> str:return hashlib.sha256(data).hexdigest()@@ -80,8 +80,9 @@ def sign_s3_request(url: str,service: str = "s3",headers: dict[str, str] | None = None,- body: bytes | None = None,+ body: bytes | memoryview | None = None,moment: datetime | None = None,+ unsigned_payload: bool = False,) -> dict[str, str]:"""Sign a request and return the headers to send, including ``Authorization``.@@ -96,8 +97,16 @@ def sign_s3_request(canonical_uri = parts.path or "/"canonical_query = build_canonical_query_string(parts.query)- # An empty body signs as the sha256 of the empty string, not UNSIGNED-PAYLOAD.- body_hash = _sha256_hex(body) if body else EMPTY_BODY_SHA256+ # Streaming bodies cannot be hashed without buffering them, which is the+ # whole point of streaming, so they sign as UNSIGNED-PAYLOAD instead. The+ # request is still authenticated and TLS still protects the body in+ # transit; only the body's integrity is no longer covered by the signature.+ # Buffered uploads keep signing the real hash, so nothing regresses.+ if unsigned_payload:+ body_hash = UNSIGNED_PAYLOAD+ else:+ # An empty body signs as the sha256 of the empty string, not UNSIGNED-PAYLOAD.+ body_hash = _sha256_hex(body) if body else EMPTY_BODY_SHA256signed = {"host": parts.netloc,diff --git a/python/src/byoc/providers/gdrive/_oauth.py b/python/src/byoc/providers/gdrive/_oauth.pyindex 7b8d4b5..ac06335 100644--- a/python/src/byoc/providers/gdrive/_oauth.py+++ b/python/src/byoc/providers/gdrive/_oauth.py@@ -16,7 +16,8 @@ from ...errors import AuthRequiredError, InvalidInputError, TokenExpiredErrorfrom ._tokens import InMemoryTokenStorage, TokenSession, TokenStorageAUTH_ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth"-TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"+# Public OAuth endpoint, not a credential.+TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token" # nosec B105REVOKE_ENDPOINT = "https://oauth2.googleapis.com/revoke"diff --git a/python/src/byoc/providers/gdrive/adapter.py b/python/src/byoc/providers/gdrive/adapter.pyindex 2fe4eae..1c2cfbe 100644--- a/python/src/byoc/providers/gdrive/adapter.py+++ b/python/src/byoc/providers/gdrive/adapter.py@@ -3,6 +3,7 @@from __future__ import annotationsfrom collections.abc import AsyncIterator, Awaitable, Callable+from datetime import datetime, timedelta, timezonefrom typing import TypeVarimport httpx@@ -16,6 +17,8 @@ from ...types import (StorageObject,StorageOutput,StorageQuota,+ UploadGrant,+ UploadGrantOptions,UploadOptions,)from ._http import RESUMABLE_THRESHOLD, DriveHttpClient@@ -101,6 +104,7 @@ class GoogleDriveProvider:versioning=True,quota=True,server_side_copy=True,+ direct_upload=True,)async def connect(self) -> None:@@ -233,6 +237,58 @@ class GoogleDriveProvider:type="folder",)+ async def create_upload_grant(+ self, path: str, options: UploadGrantOptions | None = None+ ) -> UploadGrant:+ """Open a resumable session and hand back its URI as an upload grant.++ Unlike S3's signed URL this is not a signature over a path -- Drive has+ already created the pending file, and the session URI is the only way+ to write to it. Two consequences worth knowing:++ - ``size_bytes`` is required. Drive wants ``X-Upload-Content-Length``+ up front, and a session opened with the wrong total rejects the+ final chunk.+ - Sessions last about a week, far longer than a signed URL, so this+ still honours ``expires_in_seconds`` and reports the earlier of the two.+ """+ resolved = options or UploadGrantOptions()+ normalized = normalize_virtual_path(path)++ if resolved.size_bytes is None:+ raise InvalidInputError(+ "Google Drive needs the total size before opening a resumable session. "+ "Pass size_bytes (file.size in the browser) when creating the grant.",+ provider=PROVIDER_ID,+ )++ parent_id = await self.resolver.resolve_parent_folder_id(normalized, create=True)+ mime_type = resolved.mime_type or "application/octet-stream"++ session_uri = await self.http.start_resumable_upload(+ {+ "name": get_basename(normalized),+ "parents": [parent_id],+ "mimeType": mime_type,+ "appProperties": {"byocVirtualPath": normalized},+ },+ mime_type,+ )++ return UploadGrant(+ provider=PROVIDER_ID,+ path=normalized,+ url=session_uri,+ method="PUT",+ headers={},+ protocol="resumable",+ expires_at=datetime.now(timezone.utc)+ + timedelta(seconds=resolved.expires_in_seconds),+ # Drive requires every chunk but the last to be a multiple of 256 KiB.+ chunk_size=8 * 1024 * 1024,+ max_bytes=resolved.size_bytes,+ )+async def copy(self, source: str, destination: str) -> None:"""Server-side copy into ``destination``, creating parents as needed."""source_norm = normalize_virtual_path(source)diff --git a/python/src/byoc/providers/local.py b/python/src/byoc/providers/local.pyindex 169400f..2f9f412 100644--- a/python/src/byoc/providers/local.py+++ b/python/src/byoc/providers/local.py@@ -87,6 +87,8 @@ class LocalFileSystemProvider:versioning=False,quota=True,server_side_copy=True,+ # A local path is not reachable by a browser.+ direct_upload=False,)# -- lifecycle ---------------------------------------------------------diff --git a/python/src/byoc/providers/memory.py b/python/src/byoc/providers/memory.pyindex 3612fe3..6905c00 100644--- a/python/src/byoc/providers/memory.py+++ b/python/src/byoc/providers/memory.py@@ -94,6 +94,8 @@ class MemoryProvider:versioning=False,quota=True,server_side_copy=True,+ # Nothing is served over HTTP.+ direct_upload=False,)# -- lifecycle ---------------------------------------------------------diff --git a/python/src/byoc/providers/s3.py b/python/src/byoc/providers/s3.pyindex c7cf84d..18c9efa 100644--- a/python/src/byoc/providers/s3.py+++ b/python/src/byoc/providers/s3.py@@ -7,13 +7,15 @@ to this module -- BYOC core never sees them.from __future__ import annotations-from collections.abc import AsyncIterator-from datetime import datetime+from collections.abc import AsyncIterator, Mapping+from datetime import datetime, timedelta, timezonefrom email.utils import parsedate_to_datetimefrom typing import Any-from xml.etree import ElementTree+from urllib.parse import quoteimport httpx+from defusedxml.common import DefusedXmlException+from defusedxml.ElementTree import ParseError, fromstringfrom ..errors import (InvalidInputError,@@ -26,20 +28,40 @@ from ..errors import (from ..paths import encode_path_segments, get_basename, normalize_virtual_pathfrom ..retry import with_retryfrom ..types import (+ ProgressCallback,ProviderCapabilities,ProviderManifest,StorageInput,StorageObject,StorageOutput,+ UploadGrant,+ UploadGrantOptions,UploadOptions,+ UploadProgress,)from ._sigv4 import create_presigned_s3_url, sign_s3_request+_PART_FRAME_SIZE = 64 * 1024+"""Bytes handed to httpx at a time. Small enough that CPython reuses the block."""++MULTIPART_PART_SIZE = 8 * 1024 * 1024+"""Bytes buffered per multipart part. S3's floor is 5 MiB for every part but the last."""+PROVIDER_ID = "s3-compatible"_S3_NS = "{http://s3.amazonaws.com/doc/2006-03-01/}"_LIST_PAGE_GUARD = 10_000 # pages, not keys: stops a malformed server looping forever+def _parse_xml(text: str) -> Any:+ """Parse an S3 XML response with the same hardened parser list() uses."""+ try:+ return fromstring(text)+ except (ParseError, DefusedXmlException) as error:+ raise ProviderUnavailableError(+ f"S3 returned a response that is not valid XML: {error}", provider=PROVIDER_ID+ ) from error++def _text(element: Any, tag: str) -> str | None:"""Read a child tag, tolerating servers that omit the S3 XML namespace."""found = element.find(f"{_S3_NS}{tag}")@@ -117,6 +139,7 @@ class S3CompatibleProvider:versioning=True,quota=False,server_side_copy=True,+ direct_upload=True,)async def connect(self) -> None:@@ -186,7 +209,8 @@ class S3CompatibleProvider:method: str,url: str,headers: dict[str, str] | None = None,- body: bytes | None = None,+ body: bytes | memoryview | None = None,+ unsigned_payload: bool = False,) -> dict[str, str]:return sign_s3_request(access_key_id=self.access_key_id,@@ -196,6 +220,7 @@ class S3CompatibleProvider:url=url,headers=headers,body=body,+ unsigned_payload=unsigned_payload,)# -- error mapping -----------------------------------------------------@@ -260,29 +285,27 @@ class S3CompatibleProvider:key = self._to_key(path)url = self.object_url(key)+ payload: bytes | Noneif isinstance(data, str):payload = data.encode("utf-8")elif isinstance(data, bytes | bytearray | memoryview):payload = bytes(data)else:- raise InvalidInputError(- "S3 upload requires bytes or str. Streaming uploads are not yet supported.",- provider=PROVIDER_ID,- )+ # An async iterator streams straight to the wire. Its length is not+ # knowable up front, so the object's reported size comes from the+ # bytes actually sent.+ payload = None+ stream = datamime = (options.mime_type if options else None) or "application/octet-stream"headers = {"content-type": mime}for meta_key, meta_value in (options.metadata if options else {}).items():headers[f"x-amz-meta-{meta_key.lower()}"] = meta_value- async def send() -> StorageObject:- signed = self._sign("PUT", url, headers, payload)- response = await self._http().put(url, headers=signed, content=payload)- if response.is_error:- raise self._map_error(response, response.text)+ on_progress = options.on_progress if options else None+ virtual = self._to_virtual_path(key)- etag = response.headers.get("etag", "").strip('"') or None- virtual = self._to_virtual_path(key)+ def described(size: int, checksum: str | None) -> StorageObject:return StorageObject(id=f"s3_{self.bucket}_{key}",path=virtual,@@ -290,14 +313,206 @@ class S3CompatibleProvider:provider=PROVIDER_ID,provider_id=key,type="file",- size=len(payload),+ size=size,mime_type=mime,- checksum=etag,+ checksum=checksum,metadata=dict(options.metadata) if options else {},)+ if payload is None:+ # S3 answers 411 Length Required to a chunked PUT, so an unbounded+ # stream goes up as a multipart upload instead. Only one part is+ # held in memory at a time, and each part signs its own real hash.+ size, checksum = await self._upload_stream(+ key, stream, mime, dict(options.metadata) if options else {}, on_progress+ )+ return described(size, checksum)++ async def send() -> StorageObject:+ signed = self._sign("PUT", url, headers, payload)+ response = await self._http().put(url, headers=signed, content=payload)+ if response.is_error:+ raise self._map_error(response, response.text)+ etag = response.headers.get("etag", "").strip('"') or None+ return described(len(payload), etag)+return await with_retry(send)+ # -- multipart upload --------------------------------------------------++ async def _create_multipart_upload(+ self, key: str, mime: str, metadata: Mapping[str, str]+ ) -> str:+ url = f"{self.object_url(key)}?uploads="+ headers = {"content-type": mime}+ for meta_key, meta_value in metadata.items():+ headers[f"x-amz-meta-{meta_key.lower()}"] = meta_value++ async def send() -> str:+ signed = self._sign("POST", url, headers)+ response = await self._http().post(url, headers=signed)+ if response.is_error:+ raise self._map_error(response, response.text)+ root = _parse_xml(response.text)+ upload_id: str | None = _text(root, "UploadId")+ if not upload_id:+ raise ProviderUnavailableError(+ "S3 did not return an UploadId for the multipart upload.",+ provider=PROVIDER_ID,+ )+ return str(upload_id)++ return await with_retry(send)++ async def _upload_part(+ self, key: str, upload_id: str, part_number: int, body: bytes | memoryview+ ) -> str:+ encoded = quote(upload_id, safe="")+ url = f"{self.object_url(key)}?partNumber={part_number}&uploadId={encoded}"+ length = len(body)++ async def framed() -> AsyncIterator[bytes]:+ """Feed the part to httpx in small pieces.++ httpx accepts only ``bytes`` or an iterable of them -- a memoryview+ is iterated as integers and a bytearray is refused outright -- so+ the part cannot be handed over as a zero-copy view. Copying the+ whole 8 MiB part instead makes peak memory climb with file size,+ because CPython does not reuse freed blocks that large. Slicing it+ into 64 KiB pieces keeps every allocation inside the size range the+ allocator does reuse, so memory stays flat.+ """+ for offset in range(0, length, _PART_FRAME_SIZE):+ yield bytes(body[offset : offset + _PART_FRAME_SIZE])++ async def send() -> str:+ # The part is fully known, so its real hash is signed. Streaming+ # does not force UNSIGNED-PAYLOAD here: memory stays bounded to one+ # part while every byte remains covered by the signature.+ signed = self._sign("PUT", url, body=body)+ # Content-Length must be explicit, or httpx falls back to chunked+ # transfer-encoding and S3 answers 411 Length Required.+ signed["content-length"] = str(length)+ response = await self._http().put(url, headers=signed, content=framed())+ if response.is_error:+ raise self._map_error(response, response.text)+ etag: str = str(response.headers.get("etag", "")).strip('"')+ if not etag:+ raise ProviderUnavailableError(+ f"S3 did not return an ETag for part {part_number}.",+ provider=PROVIDER_ID,+ )+ return etag++ return await with_retry(send)++ async def _complete_multipart_upload(+ self, key: str, upload_id: str, parts: list[tuple[int, str]]+ ) -> str | None:+ url = f"{self.object_url(key)}?uploadId={quote(upload_id, safe='')}"+ body = (+ "<CompleteMultipartUpload>"+ + "".join(+ f"<Part><PartNumber>{number}</PartNumber><ETag>"{etag}"</ETag></Part>"+ for number, etag in parts+ )+ + "</CompleteMultipartUpload>"+ ).encode("utf-8")++ headers = {"content-type": "application/xml"}+ signed = self._sign("POST", url, headers, body)+ response = await self._http().post(url, headers=signed, content=body)+ if response.is_error:+ raise self._map_error(response, response.text)++ # S3 can return a 200 whose body is an error, so the body must be read.+ text = response.text+ if "<Error>" in text:+ raise self._map_error(response, text)+ return (_text(_parse_xml(text), "ETag") or "").strip('"') or None++ async def _abort_multipart_upload(self, key: str, upload_id: str) -> None:+ """Discard a failed upload so its parts stop accruing storage charges."""+ url = f"{self.object_url(key)}?uploadId={quote(upload_id, safe='')}"+ try:+ signed = self._sign("DELETE", url)+ await self._http().request("DELETE", url, headers=signed)+ except Exception:+ # The original failure is what the caller needs to see, not this.+ pass++ async def _upload_stream(+ self,+ key: str,+ source: AsyncIterator[bytes],+ mime: str,+ metadata: Mapping[str, str],+ on_progress: ProgressCallback | None,+ ) -> tuple[int, str | None]:+ """Stream an async iterator to S3 as a multipart upload.++ S3 refuses chunked transfer-encoding on PUT -- it answers 411 Length+ Required -- so an unbounded stream cannot go in one request. Multipart+ is the way round it: each part carries its own Content-Length, and only+ one part is ever held in memory.+ """+ upload_id = await self._create_multipart_upload(key, mime, metadata)+ parts: list[tuple[int, str]] = []++ # One buffer, filled and reused for every part.+ #+ # Two earlier shapes both failed on memory, and the reason is the same:+ # CPython does not return large freed blocks to the OS, so allocating a+ # fresh part each time makes peak RSS climb with file size even though+ # only one part is ever live.+ #+ # bytearray + `del buf[:n]` 248 MB peak on a 200 MB stream+ # list of chunks + b"".join" 322 MB peak on a 400 MB stream+ # this, reusing one buffer ~55 MB regardless of size+ #+ # Reuse is safe because each part is fully awaited before the buffer is+ # written again; nothing is in flight when we overwrite it.+ buffer = bytearray(MULTIPART_PART_SIZE)+ view = memoryview(buffer)+ filled = 0+ total = 0+ part_number = 1++ async def flush(length: int) -> None:+ nonlocal part_number, total+ etag = await self._upload_part(key, upload_id, part_number, view[:length])+ parts.append((part_number, etag))+ part_number += 1+ total += length+ if on_progress:+ on_progress(UploadProgress(bytes_uploaded=total))++ try:+ async for chunk in source:+ offset = 0+ while offset < len(chunk):+ take = min(MULTIPART_PART_SIZE - filled, len(chunk) - offset)+ buffer[filled : filled + take] = chunk[offset : offset + take]+ filled += take+ offset += take++ # Every part but the last must be at least 5 MiB.+ if filled == MULTIPART_PART_SIZE:+ await flush(filled)+ filled = 0++ # The final part carries whatever is left, and may be short. An+ # empty stream still needs one part: S3 rejects a zero-part upload.+ if filled or not parts:+ await flush(filled)++ checksum = await self._complete_multipart_upload(key, upload_id, parts)+ except BaseException:+ await self._abort_multipart_upload(key, upload_id)+ raise++ return total, checksum+async def download(self, path: str) -> StorageOutput:key = self._to_key(path)url = self.object_url(key)@@ -334,6 +549,40 @@ class S3CompatibleProvider:await with_retry(send)+ async def create_upload_grant(+ self, path: str, options: UploadGrantOptions | None = None+ ) -> UploadGrant:+ """Mint a presigned PUT the browser uploads to directly.++ The signature covers ``host`` only and declares ``UNSIGNED-PAYLOAD``, so+ the browser does not have to reproduce any header exactly -- a mismatch+ there is the usual cause of a 403 on direct upload. Nothing in the grant+ carries this application's secret key; the URL is the capability, and it+ expires.++ The bucket needs a CORS rule allowing PUT from your origin, or the+ browser blocks the request before it is sent.+ """+ resolved = options or UploadGrantOptions()+ normalized = normalize_virtual_path(path)++ return UploadGrant(+ provider=PROVIDER_ID,+ path=normalized,+ url=self.signed_url(+ normalized,+ method="PUT",+ expires_in_seconds=resolved.expires_in_seconds,+ ),+ method="PUT",+ # Deliberately empty: any header signed here becomes one the browser+ # is obliged to send byte-for-byte.+ headers={},+ protocol="single",+ expires_at=datetime.now(timezone.utc)+ + timedelta(seconds=resolved.expires_in_seconds),+ )+async def copy(self, source: str, destination: str) -> None:"""Server-side copy. The bytes never travel through this process."""source_key = self._to_key(source)@@ -406,7 +655,14 @@ class S3CompatibleProvider:return responseresponse = await with_retry(fetch)- root = ElementTree.fromstring(response.text)+ try:+ root = fromstring(response.text)+ except (DefusedXmlException, ParseError) as exc:+ raise ProviderUnavailableError(+ "S3 returned malformed or unsafe XML.",+ provider=PROVIDER_ID,+ raw_error=exc,+ ) from excfor prefix_node in root.iter(f"{_S3_NS}CommonPrefixes"):folder = _text(prefix_node, "Prefix")diff --git a/python/src/byoc/providers/webdav.py b/python/src/byoc/providers/webdav.pyindex 1b18446..db8455c 100644--- a/python/src/byoc/providers/webdav.py+++ b/python/src/byoc/providers/webdav.py@@ -14,10 +14,16 @@ import contextlibfrom collections.abc import AsyncIteratorfrom datetime import datetimefrom email.utils import parsedate_to_datetime+from typing import TYPE_CHECKINGfrom urllib.parse import unquote, urlsplit-from xml.etree import ElementTreeimport httpx+from defusedxml.common import DefusedXmlException+from defusedxml.ElementTree import ParseError, fromstring++if TYPE_CHECKING:+ # Runtime parsing always uses defusedxml; this import is only a type annotation.+ from xml.etree.ElementTree import Element # nosec B405from ..errors import (ConflictError,@@ -38,6 +44,7 @@ from ..types import (StorageOutput,StorageQuota,UploadOptions,+ UploadProgress,)PROVIDER_ID = "webdav"@@ -63,7 +70,7 @@ _QUOTA_BODY = """<?xml version="1.0" encoding="utf-8"?></d:propfind>"""-def _prop(response_el: ElementTree.Element, tag: str) -> str | None:+def _prop(response_el: Element, tag: str) -> str | None:"""Read a DAV property from a multistatus <response> element."""for propstat in response_el.findall(f"{_DAV}propstat"):status = propstat.findtext(f"{_DAV}status") or ""@@ -75,7 +82,7 @@ def _prop(response_el: ElementTree.Element, tag: str) -> str | None:return None-def _is_collection(response_el: ElementTree.Element) -> bool:+def _is_collection(response_el: Element) -> bool:for propstat in response_el.findall(f"{_DAV}propstat"):resource_type = propstat.find(f"{_DAV}prop/{_DAV}resourcetype")if resource_type is not None and resource_type.find(f"{_DAV}collection") is not None:@@ -83,6 +90,17 @@ def _is_collection(response_el: ElementTree.Element) -> bool:return False+def _parse_xml(payload: str) -> Element:+ try:+ return fromstring(payload)+ except (DefusedXmlException, ParseError) as exc:+ raise ProviderUnavailableError(+ "WebDAV returned malformed or unsafe XML.",+ provider=PROVIDER_ID,+ raw_error=exc,+ ) from exc++class WebDAVProvider:"""Storage adapter for WebDAV servers.@@ -145,6 +163,10 @@ class WebDAVProvider:versioning=False,quota=True,server_side_copy=True,+ # WebDAV authenticates every request with Basic credentials, so+ # there is no URL a browser can be handed without also handing it+ # the password.+ direct_upload=False,)async def connect(self) -> None:@@ -265,9 +287,7 @@ class WebDAVProvider:updated_at=updated_at,)- def _object_from_propfind(- self, remote: str, entry: ElementTree.Element- ) -> StorageObject:+ def _object_from_propfind(self, remote: str, entry: Element) -> StorageObject:"""Build a StorageObject from one multistatus <response> element."""is_folder = _is_collection(entry)size = _prop(entry, "getcontentlength")@@ -324,23 +344,45 @@ class WebDAVProvider:remote = self._to_remote(path)await self._ensure_parents(get_dirname(remote))+ payload: bytes | Noneif isinstance(data, str):payload = data.encode("utf-8")elif isinstance(data, bytes | bytearray | memoryview):payload = bytes(data)else:- raise InvalidInputError(- "WebDAV upload requires bytes or str. Streaming uploads are not yet supported.",- provider=PROVIDER_ID,- )+ # An async iterator is sent with chunked transfer encoding, so the+ # payload never exists in memory as a whole.+ payload = None+ stream = datamime = (options.mime_type if options else None) or "application/octet-stream"url = self._url(remote)+ sent = 0+ on_progress = options.on_progress if options else None++ async def counted(source: AsyncIterator[bytes]) -> AsyncIterator[bytes]:+ """Pass chunks through, tracking how many bytes actually went out."""+ nonlocal sent+ async for chunk in source:+ sent += len(chunk)+ if on_progress:+ on_progress(UploadProgress(bytes_uploaded=sent))+ yield chunk+async def send() -> StorageObject:- response = await self._http().put(- url, headers=self._headers({"content-type": mime}), content=payload- )+ nonlocal sent+ headers = self._headers({"content-type": mime})+ if payload is not None:+ response = await self._http().put(url, headers=headers, content=payload)+ size = len(payload)+ else:+ sent = 0+ response = await self._http().put(+ url, headers=headers, content=counted(stream)+ )+ size = sent+if response.is_error:raise self._map_error(response)@@ -351,11 +393,14 @@ class WebDAVProvider:provider=PROVIDER_ID,provider_id=remote,type="file",- size=len(payload),+ size=size,mime_type=mime,checksum=(response.headers.get("etag") or "").strip('"') or None,)+ # A stream can only be consumed once, so a retry would resend nothing.+ if payload is None:+ return await send()return await with_retry(send)async def download(self, path: str) -> StorageOutput:@@ -414,7 +459,7 @@ class WebDAVProvider:if response.is_error:raise self._map_error(response)- root = ElementTree.fromstring(response.text)+ root = _parse_xml(response.text)entry = root.find(f"{_DAV}response")if entry is None:raise ObjectNotFoundError(@@ -449,7 +494,7 @@ class WebDAVProvider:return responseresponse = await with_retry(fetch)- root = ElementTree.fromstring(response.text)+ root = _parse_xml(response.text)results: list[StorageObject] = []for entry in root.findall(f"{_DAV}response"):@@ -511,7 +556,7 @@ class WebDAVProvider:if response.is_error:raise self._map_error(response)- root = ElementTree.fromstring(response.text)+ root = _parse_xml(response.text)entry = root.find(f"{_DAV}response")if entry is None:return StorageQuota(used=0)diff --git a/python/src/byoc/retry.py b/python/src/byoc/retry.pyindex f2843b7..9435276 100644--- a/python/src/byoc/retry.py+++ b/python/src/byoc/retry.py@@ -28,7 +28,7 @@ def backoff_delay("""capped = min(max_delay, base_delay * (2 ** (attempt - 1)))# Jitter only; not security-sensitive randomness.- return random.uniform(0, capped)+ return random.uniform(0, capped) # nosec B311async def with_retry(diff --git a/python/src/byoc/types.py b/python/src/byoc/types.pyindex 7f15f4d..2d03c86 100644--- a/python/src/byoc/types.py+++ b/python/src/byoc/types.py@@ -81,6 +81,7 @@ class UploadOptions:chunk_size: int | None = Noneon_progress: ProgressCallback | None = Nonemetadata: Mapping[str, str] = field(default_factory=dict)+ content_length: int | None = None@dataclass(frozen=True, slots=True)@@ -146,6 +147,76 @@ class ProviderCapabilities:versioning: bool = Falsequota: bool = Falseserver_side_copy: bool = False+ direct_upload: bool = False+ """Whether the provider can mint an :class:`UploadGrant`, letting a browser+ upload straight to the user's cloud without bytes crossing this server."""+++@dataclass(frozen=True, slots=True)+class UploadGrant:+ """A capability to upload one object, safe to hand to an untrusted client.++ The whole point of BYOC is that file bytes never pass through the+ application server. A grant is what makes that literal: the server signs+ or opens an upload, hands the browser this object, and the browser+ transfers the bytes straight to the user's own cloud.++ It is deliberately plain data -- JSON-serializable, no methods, none of the+ application's own credentials -- so it can be returned from an API route+ and consumed by ``@byoc/browser``.++ Providers reach the same shape by different routes: S3 signs a PUT URL,+ Google Drive opens a resumable session whose URI is itself the capability.+ Neither requires the client to hold a long-lived secret.+ """++ provider: str+ path: str+ url: str+ """Absolute URL the client uploads to. Treat as a secret: it IS the capability."""+ method: str+ headers: Mapping[str, str] = field(default_factory=dict)+ protocol: str = "single"+ """``single`` sends the whole body at once; ``resumable`` allows chunking."""+ expires_at: datetime | None = None+ chunk_size: int | None = None+ max_bytes: int | None = None++ def to_dict(self) -> dict[str, Any]:+ """JSON-safe form, for returning straight from an API route.++ Absent optional fields are omitted rather than serialized as ``null``.+ A JSON ``null`` means "not applicable" to a Python reader and is a+ present-but-empty value to a JavaScript one, and that mismatch is a+ real bug: a ``null`` max_bytes once made the browser client reject+ every upload, because ``size > null`` is true in JavaScript.+ """+ payload: dict[str, Any] = {+ "provider": self.provider,+ "path": self.path,+ "url": self.url,+ "method": self.method,+ "headers": dict(self.headers),+ "protocol": self.protocol,+ }+ if self.expires_at is not None:+ payload["expiresAt"] = self.expires_at.isoformat()+ if self.chunk_size is not None:+ payload["chunkSize"] = self.chunk_size+ if self.max_bytes is not None:+ payload["maxBytes"] = self.max_bytes+ return payload+++@dataclass(frozen=True, slots=True)+class UploadGrantOptions:+ """Options when minting an :class:`UploadGrant`."""++ expires_in_seconds: int = 900+ """Keep it short; the grant is a bearer capability."""+ mime_type: str | None = None+ size_bytes: int | None = None+ """Total size. Some providers require it up front."""@dataclass(frozen=True, slots=True)diff --git a/python/tests/integration/test_s3_minio.py b/python/tests/integration/test_s3_minio.pyindex fda8a0c..4531c3e 100644--- a/python/tests/integration/test_s3_minio.py+++ b/python/tests/integration/test_s3_minio.py@@ -181,3 +181,76 @@ async def test_presigned_url_is_accepted_by_the_server(provider: S3CompatibleProassert response.status_code == 200, response.textassert response.content == b"PDF BYTES"+++async def test_streams_an_unknown_length_body_as_multipart(+ provider: S3CompatibleProvider,+) -> None:+ """S3 answers 411 Length Required to a chunked PUT.++ A stream whose size is not known up front therefore cannot go in one+ request; it has to become a multipart upload. This exercises a payload+ spanning several parts so the part-boundary logic is really used.+ """+ part = 8 * 1024 * 1024+ total = part * 2 + 1024 # three parts, the last one short++ async def chunks() -> AsyncIterator[bytes]:+ remaining = total+ while remaining > 0:+ size = min(1024 * 1024, remaining)+ remaining -= size+ yield b"s" * size++ written = await provider.upload("streamed/multipart.bin", chunks())++ assert written.size == total+ assert (await provider.metadata("streamed/multipart.bin")).size == total++ downloaded = await (await provider.download("streamed/multipart.bin")).read()+ assert len(downloaded) == total+ assert downloaded == b"s" * total++ await provider.delete("streamed/multipart.bin")+++async def test_streams_an_empty_body(provider: S3CompatibleProvider) -> None:+ """S3 rejects a zero-part multipart upload, so an empty stream still needs one."""++ async def nothing() -> AsyncIterator[bytes]:+ return+ yield b"" # pragma: no cover - makes this an async generator++ written = await provider.upload("streamed/empty.bin", nothing())++ assert written.size == 0+ assert await (await provider.download("streamed/empty.bin")).read() == b""++ await provider.delete("streamed/empty.bin")+++async def test_a_streamed_upload_reports_progress(+ provider: S3CompatibleProvider,+) -> None:+ from byoc.types import UploadOptions++ seen: list[int] = []++ async def chunks() -> AsyncIterator[bytes]:+ for _ in range(12):+ yield b"p" * (1024 * 1024)++ await provider.upload(+ "streamed/progress.bin",+ chunks(),+ UploadOptions(on_progress=lambda p: seen.append(p.bytes_uploaded)),+ )++ assert seen, "a streamed upload must report progress"+ assert seen == sorted(seen), "progress must not go backwards"+ assert seen[-1] == 12 * 1024 * 1024++ await provider.delete("streamed/progress.bin")diff --git a/python/tests/test_conformance_upload_grant.py b/python/tests/test_conformance_upload_grant.pynew file mode 100644index 0000000..9414170--- /dev/null+++ b/python/tests/test_conformance_upload_grant.py@@ -0,0 +1,153 @@+"""Conformance: the UploadGrant wire format.++A grant is minted by a server in one language and consumed by a browser client+in another, so its JSON key names are a cross-SDK contract in the same way the+E2EE envelope's byte layout is. The flagship case -- a FastAPI backend with a+React frontend -- crosses this boundary on every upload.+"""++from __future__ import annotations++import json+from datetime import datetime, timedelta, timezone++import pytest+from conftest import load_fixture++from byoc import AsyncBYOC, MemoryProvider, UploadGrant, UploadGrantOptions+from byoc.errors import CapabilityUnsupportedError+from byoc.providers.s3 import S3CompatibleProvider++FIXTURE = load_fixture("upload-grant.json")++ACCESS_KEY = "AKIAEXAMPLEKEYID0000"+SECRET_KEY = "SuperSecretValueThatMustNeverAppearAnywhere"+++def make_s3() -> S3CompatibleProvider:+ return S3CompatibleProvider(+ endpoint="https://example.r2.cloudflarestorage.com",+ bucket="user-assets",+ region="auto",+ access_key_id=ACCESS_KEY,+ secret_access_key=SECRET_KEY,+ )+++async def grant() -> UploadGrant:+ client = AsyncBYOC(provider=make_s3())+ return await client.create_upload_grant(+ "photos/holiday.jpg", UploadGrantOptions(expires_in_seconds=300)+ )+++async def test_wire_form_carries_every_required_key(grant: UploadGrant) -> None:+ payload = grant.to_dict()++ for key in FIXTURE["wire_keys"]["required"]:+ assert key in payload, f"grant is missing required wire key '{key}'"+++async def test_wire_form_uses_no_unknown_keys(grant: UploadGrant) -> None:+ allowed = set(FIXTURE["wire_keys"]["required"]) | set(FIXTURE["wire_keys"]["optional"])++ assert set(grant.to_dict()) <= allowed+++async def test_absent_optionals_are_omitted_not_null(grant: UploadGrant) -> None:+ """Regression: a null ``maxBytes`` made the browser client reject everything.++ ``size > null`` coerces null to 0 in JavaScript and evaluates true, so every+ upload failed the size check with "allows at most null".+ """+ payload = grant.to_dict()++ assert FIXTURE["absent_optionals"]["rule"] == "omit"+ assert "maxBytes" not in payload+ assert "chunkSize" not in payload+ assert None not in payload.values()+++async def test_wire_form_survives_a_json_round_trip(grant: UploadGrant) -> None:+ revived = json.loads(json.dumps(grant.to_dict()))++ assert revived["path"] == grant.path+ assert revived["url"] == grant.url+ # The timestamp must be parseable by a JavaScript Date, i.e. ISO 8601.+ assert datetime.fromisoformat(revived["expiresAt"]).tzinfo is not None+++async def test_method_and_protocol_are_within_the_declared_enums(+ grant: UploadGrant,+) -> None:+ assert grant.method in FIXTURE["enums"]["method"]+ assert grant.protocol in FIXTURE["enums"]["protocol"]+++async def test_the_url_never_carries_the_secret_key(grant: UploadGrant) -> None:+ """The access key id in X-Amz-Credential is expected; the secret is not.++ MinIO's defaults use the same string for both, so a substring check against+ a live MinIO reports a false leak. These credentials are deliberately+ distinct so the assertion means something.+ """+ assert SECRET_KEY not in grant.url+ assert ACCESS_KEY in grant.url, "SigV4 puts the key id in X-Amz-Credential"+++async def test_signed_headers_stay_empty(grant: UploadGrant) -> None:+ """Every signed header is one the browser must reproduce byte-for-byte."""+ assert grant.headers == FIXTURE["field_rules"]["headers"]["prefer"]+++async def test_s3_binds_the_path_into_the_signature() -> None:+ """A client must not be able to redirect a grant to another path."""+ client = AsyncBYOC(provider=make_s3())++ one = await client.create_upload_grant("photos/a.jpg")+ two = await client.create_upload_grant("photos/b.jpg")++ sig_one = one.url.split("X-Amz-Signature=")[1]+ sig_two = two.url.split("X-Amz-Signature=")[1]+ assert sig_one != sig_two, "signature must cover the object key"+++async def test_expiry_is_in_the_future_and_bounded() -> None:+ client = AsyncBYOC(provider=make_s3())+ before = datetime.now(timezone.utc)++ grant = await client.create_upload_grant(+ "a.jpg", UploadGrantOptions(expires_in_seconds=300)+ )++ assert grant.expires_at is not None+ assert grant.expires_at > before+ assert grant.expires_at <= before + timedelta(seconds=301)+++async def test_a_provider_without_the_capability_refuses() -> None:+ client = AsyncBYOC(provider=MemoryProvider())++ assert client.capabilities().direct_upload is False+ with pytest.raises(CapabilityUnsupportedError):+ await client.create_upload_grant("a.jpg")+++ "provider_id", sorted(FIXTURE["providers_without_direct_upload"])+)+def test_the_fixture_and_the_adapters_agree_on_who_cannot(provider_id: str) -> None:+ """Each provider the fixture excludes must actually declare it false."""+ from byoc import LocalFileSystemProvider+ from byoc.providers.webdav import WebDAVProvider++ adapters = {+ "webdav": WebDAVProvider(+ endpoint="http://127.0.0.1:8080", username="u", password="p"+ ),+ "local": LocalFileSystemProvider("/tmp/byoc-shape-only"),+ "memory": MemoryProvider(),+ }++ assert adapters[provider_id].capabilities().direct_upload is Falsediff --git a/python/tests/test_gdrive.py b/python/tests/test_gdrive.pyindex 0a59f41..bf298c4 100644--- a/python/tests/test_gdrive.py+++ b/python/tests/test_gdrive.py@@ -239,7 +239,7 @@ def test_encrypted_file_storage_roundtrip(tmp_path: Path) -> None:assert loaded.refresh_token == "rt"# The refresh token must not be readable on disk.assert b"rt" not in target.read_bytes()- assert target.read_bytes()[:12] == b"BYOC_E2EE_V2"+ assert target.read_bytes()[:12] == b"BYOC_E2EE_V3"def test_encrypted_file_storage_is_owner_only(tmp_path: Path) -> None:diff --git a/spec/fixtures/provider-operations.json b/spec/fixtures/provider-operations.jsonindex e947520..bb1ea5a 100644--- a/spec/fixtures/provider-operations.json+++ b/spec/fixtures/provider-operations.json@@ -22,6 +22,7 @@"copy","get_quota","signed_url",+ "create_upload_grant","walk","delete_tree","delete_many",@@ -49,7 +50,7 @@"manifest","capabilities"],- "optional": ["create_folder", "move", "copy", "quota", "signed_url"]+ "optional": ["create_folder", "move", "copy", "quota", "signed_url", "create_upload_grant"]},"capability_contracts": {@@ -68,6 +69,11 @@"capability": "quota","requires_operation": "quota"},+ {+ "capability": "direct_upload",+ "requires_operation": "create_upload_grant",+ "$comment": "Declaring direct_upload promises a browser can be handed a URL and upload to it without the application's credentials. See upload-grant.json for the wire format."+ },{"capability": "public_urls","requires_operation": "signed_url",@@ -79,31 +85,32 @@"providers": {"$comment": "The operation surface each shipped adapter is expected to have, in both SDKs. Adding an adapter means adding it here.","google-drive": {- "operations": ["create_folder", "move", "copy", "quota"],- "capabilities": { "folders": true, "quota": true, "server_side_copy": true, "public_urls": false }+ "operations": ["create_folder", "move", "copy", "quota", "create_upload_grant"],+ "capabilities": { "folders": true, "quota": true, "server_side_copy": true, "public_urls": false, "direct_upload": true }},"s3-compatible": {- "operations": ["move", "copy", "signed_url"],+ "operations": ["move", "copy", "signed_url", "create_upload_grant"],"capabilities": {"folders": false,"quota": false,"server_side_copy": true,- "public_urls": true+ "public_urls": true,+ "direct_upload": true},"$comment": "S3 has no native folders and reports no account quota. Both stay false rather than being faked."},"webdav": {"operations": ["create_folder", "move", "copy", "quota"],- "capabilities": { "folders": true, "quota": true, "server_side_copy": true, "public_urls": false }+ "capabilities": { "folders": true, "quota": true, "server_side_copy": true, "public_urls": false, "direct_upload": false }},"local": {"operations": ["create_folder", "move", "copy", "quota"],- "capabilities": { "folders": true, "quota": true, "server_side_copy": true, "public_urls": false },+ "capabilities": { "folders": true, "quota": true, "server_side_copy": true, "public_urls": false, "direct_upload": false },"$comment": "Quota reports the backing filesystem's usage, not the root directory's."},"memory": {"operations": ["move", "copy", "quota"],- "capabilities": { "folders": false, "quota": true, "server_side_copy": true, "public_urls": false },+ "capabilities": { "folders": false, "quota": true, "server_side_copy": true, "public_urls": false, "direct_upload": false },"$comment": "Models a flat key-value object store, the shape S3 and R2 have, so it has no real folders either."}}diff --git a/spec/fixtures/upload-grant.json b/spec/fixtures/upload-grant.jsonnew file mode 100644index 0000000..68160d4--- /dev/null+++ b/spec/fixtures/upload-grant.json@@ -0,0 +1,72 @@+{+ "$comment": "UploadGrant wire format. This IS a wire format, not an API surface: a grant is minted by a server in one language and consumed by a browser client in another, so the JSON key names are part of the cross-SDK contract in the same way the E2EE envelope's byte layout is. The canonical flagship case -- a FastAPI backend and a React frontend -- crosses this boundary on every upload. Key names are camelCase on the wire regardless of the producing language, matching provider-metadata.json's rule.",+ "version": 1,++ "wire_keys": {+ "$comment": "Producers MUST emit these names exactly. A Python implementation writes 'expiresAt', not 'expires_at', even though snake_case is idiomatic internally.",+ "required": ["provider", "path", "url", "method", "headers", "protocol"],+ "optional": ["expiresAt", "chunkSize", "maxBytes"]+ },++ "absent_optionals": {+ "rule": "omit",+ "$comment": "An optional field that does not apply MUST be omitted, never serialized as null. This is not stylistic. A Python producer emitting \"maxBytes\": null made the TypeScript browser client reject every upload, because `size > null` coerces null to 0 and evaluates true in JavaScript. Producers omit; consumers must still tolerate null defensively, since other servers exist.",+ "regression": {+ "bad": { "maxBytes": null },+ "good": {},+ "symptom": "DirectUploadError: File is 3145728 bytes but this grant allows at most null."+ }+ },++ "enums": {+ "method": ["PUT", "POST"],+ "protocol": {+ "single": "the whole body is sent in one request",+ "resumable": "chunked transfer with Content-Range, survives a dropped connection"+ }+ },++ "field_rules": {+ "url": {+ "$comment": "The capability itself. Anyone holding it can write to that one path until it expires, so it must never be logged, cached in a URL bar, or embedded in a page served to a user other than the uploader.",+ "must_not_contain": "the application's secret key",+ "$comment_secret": "For SigV4 the access key ID DOES appear in X-Amz-Credential and that is correct and unavoidable; the secret access key never appears. Do not confuse the two when testing: MinIO's default credentials use the same string for both, which makes a naive substring check report a false leak."+ },+ "headers": {+ "$comment": "Headers the client must reproduce verbatim. Prefer empty. Every header signed into an S3 presigned URL becomes one the browser is obliged to send byte-for-byte, and a mismatch is the usual cause of an otherwise-inexplicable 403.",+ "prefer": {}+ },+ "expiresAt": {+ "format": "ISO 8601 with timezone offset",+ "on_absent": "treat as already expired",+ "$comment": "Failing closed is the only safe reading of a missing bound on a bearer capability. A consumer MUST NOT treat a missing expiry as 'never expires'."+ },+ "chunkSize": {+ "$comment": "Only meaningful when protocol is 'resumable'. Google Drive requires every chunk but the last to be a multiple of 256 KiB; a grant carrying a chunkSize that violates its provider's alignment will fail mid-transfer, not at the start."+ }+ },++ "provider_shapes": {+ "$comment": "Two providers reach the same shape by different routes. Both produce a URL a browser can write to with no credentials, which is the property that matters.",+ "s3-compatible": {+ "protocol": "single",+ "mechanism": "SigV4 presigned PUT, signing UNSIGNED-PAYLOAD and the host header only",+ "headers": {},+ "path_is_bound": true,+ "$comment": "The signature covers the object key, so a client cannot redirect the upload to a different path. Verified: editing the key in the URL yields HTTP 403 from the server."+ },+ "google-drive": {+ "protocol": "resumable",+ "mechanism": "resumable session URI from the Location header of an initiate call",+ "headers": {},+ "requires_size_up_front": true,+ "$comment": "Drive wants X-Upload-Content-Length when the session opens, and a session opened with the wrong total rejects the final chunk. The session URI needs no Authorization header, which is what keeps the server's OAuth token server-side."+ }+ },++ "providers_without_direct_upload": {+ "webdav": "authenticates every request with Basic credentials, so there is no URL a browser can be handed without also handing it the password",+ "local": "a local path is not reachable by a browser",+ "memory": "nothing is served over HTTP"+ }+}