From 659ac10556376bf2a4320c2ff1d8119adcc3bef0 Mon Sep 17 00:00:00 2001 From: oglassdev <23040613+oglassdev@users.noreply.github.com> Date: Mon, 21 Sep 2026 02:03:00 -0400 Subject: [PATCH 1/2] docs: add MIT license and experimental project disclaimer --- .github/workflows/release.yml | 1 + LICENSE | 21 +++++++++++++++++++++ README.md | 28 ++++++++++++++++------------ apps/web/package.json | 1 + apps/worker/package.json | 1 + package.json | 1 + packages/contracts/package.json | 1 + 7 files changed, 42 insertions(+), 12 deletions(-) create mode 100644 LICENSE diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b2c3a56..74ecaa7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,6 +15,7 @@ jobs: shell: bash run: | mkdir -p release + cp LICENSE release/ for target in linux/amd64 linux/arm64 darwin/amd64 darwin/arm64 windows/amd64 windows/arm64; do os="${target%/*}" arch="${target#*/}" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5b7201e --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 chunkzero contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index c846c8d..fb49f8c 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,12 @@ A Maven repository backed by Cloudflare R2, with a standalone Go publishing clie **Publish through the local proxy. Download directly from the hosted repository.** Maven and Gradle use normal HTTP repository protocols; they never receive R2 credentials. A publication becomes visible only after the entire build succeeds and the Worker validates its artifacts. -## What is implemented +> [!WARNING] +> Experimental and heavily vibe-coded. It works for our current use, but there are rough edges and it has not had a security audit. Expect bugs and breaking changes to the API, CLI, and storage schema. Keep backups of both D1 and R2; don't make this the only copy of artifacts you care about. +> +> See [known limitations](#known-limitations) before deploying your own instance. + +## Features - Release, snapshot, and mixed repositories; public or private visibility. - Atomic publication sessions, immutable releases and timestamped snapshots, concurrent metadata merging, resumable multipart uploads, and failed-build rollback. @@ -16,7 +21,7 @@ A Maven repository backed by Cloudflare R2, with a standalone Go publishing clie - A responsive light/dark console for artifact browsing, path search, dependency snippets, publication history, version deletion, repository settings, members, invitations, service accounts, tokens, usage, and audit history. - Account storage quotas, upload reservations, snapshot retention, abandoned-session expiry, delayed garbage collection, and request rate limits. -## Architecture and upload choice +## How it works | Part | Stack | Responsibility | | --------------------- | ------------------------------------------ | --------------------------------------------------------------------------------------- | @@ -27,12 +32,7 @@ A Maven repository backed by Cloudflare R2, with a standalone Go publishing clie **The Worker handles uploads.** The CLI sends 16 MiB parts to the Worker, which streams them into a private R2 bucket. R2 holds immutable objects; D1 maps published Maven paths to those objects. A Durable Object serializes mutations for each repository, and a D1 transaction publishes all file references and merged metadata together. Readers never see a partially finalized publication. -| Approach | Advantages | Costs | -| ----------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -| Presigned R2 uploads | Artifact bytes bypass Worker execution; useful for very large transfers | Requires S3 signing credentials, grants remain usable until expiry, multipart coordination and final validation are still needed | -| Worker streaming, implemented | Binding-based R2 access, immediate authorization checks, one protocol and deployment surface | More Worker requests; publisher-provided multipart checksums; CPU and D1 limits need capacity planning | - -The part size keeps individual requests below normal Worker request-body limits. Artifact hashing runs in the Go CLI. **Workers Free** deployments must remove `limits.cpu_ms` from their deployment configuration and validate their workload against the CPU, subrequest, and database limits; review [Worker limits](https://developers.cloudflare.com/workers/platform/limits/) and [D1 limits](https://developers.cloudflare.com/d1/platform/limits/) for your workload. Free-tier suitability is not guaranteed by moving hashing off the Worker. A future presigned transport can use the same staging and commit model without changing build configuration. +Artifact hashing runs in the Go CLI. **Workers Free** deployments must remove `limits.cpu_ms` from their deployment configuration. Moving checksums to the CLI does not guarantee that every workload fits the free tier; check the [Worker limits](https://developers.cloudflare.com/workers/platform/limits/) and [D1 limits](https://developers.cloudflare.com/d1/platform/limits/). ## Development @@ -158,7 +158,7 @@ publishing { } ``` -Artifact checksums are publisher-provided declarations. R2 verifies SHA-256 for single-part uploads; multipart uploads are checked for completeness and stored size without the Worker rereading their contents. Sidecars must match the declared hashes, and server-generated metadata is hashed on the Worker. Clients and the Worker must be upgraded together: upload requests require all four hashes. Restart pending publications created by an older client. An identical retry is identified by the declared hashes and size; it never replaces an already published release object. +Artifact checksums are publisher-provided declarations. R2 verifies SHA-256 for single-part uploads; multipart uploads are checked for completeness and stored size without the Worker rereading their contents. Sidecars must match the declared hashes, and server-generated metadata is hashed on the Worker. Upload requests require all four hashes; use matching CLI and Worker versions. An identical retry is identified by the declared hashes and size; it never replaces an already published release object. The proxy answers each upload only after the file is staged remotely. Gradle's HTTP client gives up after 30 seconds by default, so set `systemProp.org.gradle.internal.http.socketTimeout` in `gradle.properties` to cover your largest artifact, as the Gradle example does. Maven's default timeout is long enough. @@ -215,7 +215,7 @@ repositories { } ``` -Absolute URLs map repositories hosted on separate custom domains, such as `https://maven.chunkzero.com/snapshots`. Locally, `http://localhost:5173/` and `http://localhost:5173/snapshots/` serve the default repositories because Vite+ forwards them to the Worker without rewriting the host. +Absolute URLs map repositories hosted on separate custom domains, such as `https://snapshots.example.com`. Locally, `http://localhost:5173/` and `http://localhost:5173/snapshots/` serve the default repositories because Vite+ forwards them to the Worker without rewriting the host. Mappings preserve repository visibility, token scopes, and R2 streaming. Bootstrap repositories are private until an administrator changes their visibility; private consumers still need read credentials. Existing `/maven/{account}/{repository}` URLs continue to work, and publishing still uses the account/repository pair through the CLI. @@ -225,11 +225,15 @@ Relative URLs start with a single slash. Absolute URLs must use HTTPS, except HT The console is served from `/` and routes with a URL hash, for example `/#/default/repositories`, so root mappings and console pages share the origin without ambiguity. Its assets stay under `/console/assets/`, and old `/console/...` bookmarks and `/invite` links redirect to the matching `/#/...` route. `APP_URL` is the console's origin; OAuth callback URLs stay under `/api/auth`. The console displays the first configured mapping for a repository in copyable URLs and dependency snippets, falling back to its canonical URL when no mapping exists. Browser download buttons use the console origin so session credentials work even when a mapping uses another hostname. -## Initial implementation boundaries +## Known limitations - GitHub/OIDC provider redirects and deployed Cloudflare behavior require deployment credentials to validate. Automated checks cover local Cloudflare bindings, Better Auth session validation, real Maven/Gradle interoperability, and browser management flows. - Publication sessions are bounded to 500 uploaded files (including sidecars), 32 artifact IDs, 32 snapshot versions, and a bounded finalization transaction. Split larger builds into separate sessions. POMs and metadata are limited to 1 MiB; ordinary file limits are configurable. The 2 GiB default has not been load-tested on deployed Workers. - Releases and timestamped snapshot files cannot change in place. An identical retry is accepted; adding new files to an existing release requires deleting and republishing the complete version. Non-timestamped snapshots are mutable. Signed repository metadata is rejected because the server regenerates metadata; artifact signatures are preserved but not cryptographically verified. - Version deletion and retention remove references immediately and delay object deletion by an hour for in-flight readers. Quotas measure logical stored content and reservations, not temporary duplicate R2 storage or retained audit/session records. - Console account listings are capped at 200 workspaces; publication and audit history show the latest 100 entries. File browsing uses pagination. Retention and garbage collection run in bounded batches and may take several hourly passes for a backlog. -- Upstream mirrors/proxy caches, virtual repositories, Maven Central promotion, webhooks, download analytics, bulk imports, and a browser OAuth device flow for the CLI are future work. The CLI currently logs in with a console-issued token. +- Upstream mirrors/proxy caches, virtual repositories, Maven Central promotion, webhooks, download analytics, bulk imports, and a browser OAuth device flow for the CLI are not implemented. The CLI logs in with a console-issued token. + +## License + +[MIT](LICENSE). diff --git a/apps/web/package.json b/apps/web/package.json index 39fb2e4..53e3520 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,7 @@ { "name": "@maven-r2/web", "private": true, + "license": "MIT", "type": "module", "scripts": { "dev": "vp dev --host 127.0.0.1", diff --git a/apps/worker/package.json b/apps/worker/package.json index 454d2e3..f7ba661 100644 --- a/apps/worker/package.json +++ b/apps/worker/package.json @@ -1,6 +1,7 @@ { "name": "@maven-r2/worker", "private": true, + "license": "MIT", "type": "module", "scripts": { "dev": "wrangler dev --port 8787", diff --git a/package.json b/package.json index 3363c68..f237922 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,7 @@ { "name": "maven-r2", "private": true, + "license": "MIT", "type": "module", "scripts": { "dev": "pnpm --parallel --filter './apps/*' dev", diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 0ebbae6..9b13218 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,7 @@ { "name": "@maven-r2/contracts", "private": true, + "license": "MIT", "type": "module", "exports": { ".": "./src/index.ts", From 18e899058e043a34614a3ca525b76381c7217f5c Mon Sep 17 00:00:00 2001 From: oglassdev <23040613+oglassdev@users.noreply.github.com> Date: Mon, 21 Sep 2026 02:09:23 -0400 Subject: [PATCH 2/2] docs: focus README on publishing and operating the service --- README.md | 284 +++++++++++++++++++++++------------------------------- 1 file changed, 118 insertions(+), 166 deletions(-) diff --git a/README.md b/README.md index fb49f8c..62b2290 100644 --- a/README.md +++ b/README.md @@ -1,238 +1,190 @@ # Maven R2 -A Maven repository backed by Cloudflare R2, with a standalone Go publishing client and a small web console. +A Maven repository backed by Cloudflare R2, with a Go publishing client and a web console. It supports public and private repositories, releases and snapshots, and scoped access tokens. -**Publish through the local proxy. Download directly from the hosted repository.** Maven and Gradle use normal HTTP repository protocols; they never receive R2 credentials. A publication becomes visible only after the entire build succeeds and the Worker validates its artifacts. +**Publish through the local proxy. Download directly from the hosted repository.** The CLI computes checksums and uploads artifacts through a Cloudflare Worker. A publication becomes visible only after the build succeeds and the service validates it. Maven and Gradle never receive R2 credentials. > [!WARNING] -> Experimental and heavily vibe-coded. It works for our current use, but there are rough edges and it has not had a security audit. Expect bugs and breaking changes to the API, CLI, and storage schema. Keep backups of both D1 and R2; don't make this the only copy of artifacts you care about. -> -> See [known limitations](#known-limitations) before deploying your own instance. +> Experimental and heavily vibe-coded. It works for our current use, but there are rough edges and it has not had a security audit. Expect bugs and breaking changes to the API, CLI, and storage schema. Keep backups of both D1 and R2. Don't make this the only copy of artifacts you care about. -## Features - -- Release, snapshot, and mixed repositories; public or private visibility. -- Atomic publication sessions, immutable releases and timestamped snapshots, concurrent metadata merging, resumable multipart uploads, and failed-build rollback. -- Maven POMs, parent POMs, Gradle module metadata, classifiers, detached signatures, and MD5/SHA-1/SHA-256/SHA-512 sidecars. The Go CLI computes artifact checksums; the server checks supplied sidecars against those declarations and generates checksums for its own metadata. -- Direct downloads with Basic or Bearer token authentication, conditional GET, HEAD, and byte ranges. Public repositories need no credentials. -- Configurable repository URLs, including a release repository at the domain root and snapshots at `/snapshots`, in single- or multiple-workspace instances. -- Single-workspace or multiple-workspace instances, GitHub login, optional OIDC, configurable signups, invitation links, and owner/admin/publisher/reader roles. -- Personal tokens and service-account tokens restricted by repository, path prefix, operation, and expiry. Tokens are stored as hashes and shown once. Revocation, removal of membership, and disabled service accounts take effect on subsequent requests. -- A responsive light/dark console for artifact browsing, path search, dependency snippets, publication history, version deletion, repository settings, members, invitations, service accounts, tokens, usage, and audit history. -- Account storage quotas, upload reservations, snapshot retention, abandoned-session expiry, delayed garbage collection, and request rate limits. - -## How it works - -| Part | Stack | Responsibility | -| --------------------- | ------------------------------------------ | --------------------------------------------------------------------------------------- | -| `cli/`, `internal/` | Go, Kong, generated OpenAPI client | Loopback Maven proxy, local spooling, upload retries, build execution, session recovery | -| `apps/worker/` | Hono, Zod, Better Auth, Drizzle, Workers | Authentication, permissions, publishing API, downloads, maintenance | -| `apps/web/` | React, React Router, TanStack Query, Vite+ | Repository and account console, served as Worker static assets | -| `packages/contracts/` | Zod and OpenAPI | Shared TypeScript schemas and generated Go API contracts | - -**The Worker handles uploads.** The CLI sends 16 MiB parts to the Worker, which streams them into a private R2 bucket. R2 holds immutable objects; D1 maps published Maven paths to those objects. A Durable Object serializes mutations for each repository, and a D1 transaction publishes all file references and merged metadata together. Readers never see a partially finalized publication. - -Artifact hashing runs in the Go CLI. **Workers Free** deployments must remove `limits.cpu_ms` from their deployment configuration. Moving checksums to the CLI does not guarantee that every workload fits the free tier; check the [Worker limits](https://developers.cloudflare.com/workers/platform/limits/) and [D1 limits](https://developers.cloudflare.com/d1/platform/limits/). - -## Development +## Publishing -Install [mise](https://mise.jdx.dev/), then: +Build the CLI from this checkout with Go: ```sh -mise trust -mise install -mise exec -- just setup -cp apps/worker/.dev.vars.example apps/worker/.dev.vars -mise exec -- pnpm db:migrate -mise exec -- just dev +go build -o bin/maven-r2 ./cli ``` -Open **http://localhost:5173/#/**. Vite+ serves the console page at `/` and forwards other paths to the local Worker on port 8787, including mapped repository URLs. Wrangler emulates D1, R2, and Durable Objects locally. The example secrets are for local development only. +Put `bin/maven-r2` on your `PATH`, or use `./bin/maven-r2` in the commands below. Use matching CLI and Worker versions. -Initialize the local instance once: +Create a publishing token in the web console, then save it in a local profile: ```sh -curl --fail-with-body -X POST http://localhost:5173/api/bootstrap \ - -H 'x-bootstrap-token: local-bootstrap-only-replace-before-deploy' +maven-r2 --server https://repo.example.com --profile work login ``` -This creates the default workspace, private `releases` and `snapshots` repositories, and a bootstrap publishing token valid for 24 hours. Save the token from the response. To access the management UI, configure a development GitHub OAuth app in `.dev.vars` and put your numeric GitHub user ID in `ADMIN_GITHUB_IDS` in `wrangler.jsonc`. Its callback URL is `http://localhost:5173/api/auth/callback/github`. +Configure Gradle to publish through the local proxy: + +```kotlin +publishing { + repositories { + maven { + url = uri(providers.environmentVariable("MAVEN_R2_URL").get()) + isAllowInsecureProtocol = true // The proxy listens on loopback only. + credentials { + username = providers.environmentVariable("MAVEN_R2_USERNAME").get() + password = providers.environmentVariable("MAVEN_R2_PASSWORD").get() + } + } + } +} +``` -Commands use the tool versions pinned in `mise.toml`. Activate mise in your shell or prefix them with `mise exec --`. +Run the build through the CLI, using your workspace and repository slugs: ```sh -just format # Vite+ formatting and gofmt -just check # formatting, lint, TypeScript, go vet -just test # Cloudflare-runtime tests and Go race tests -just build # web assets, Worker deployment dry run, bin/maven-r2 -just contracts # regenerate OpenAPI and Go client after contract changes -just ready # all normal release checks -pnpm exec playwright install chromium -just interop # isolated real Maven/Gradle publishing, resolution, and browser checks +maven-r2 --profile work publish --repository default/releases -- ./gradlew publish +maven-r2 --profile work publish --repository default/snapshots -- mvn -s settings.xml deploy ``` -`just interop` starts a temporary local Worker on port 8797, uses separate publishing/consuming Maven caches, seeds a test browser session, and removes its state and server afterward. Screenshots go to `.artifacts/`. It does not contact a deployed repository or test the external OAuth provider. Set `INTEROP_PORT` if necessary. Worker tests invoke Vitest directly for the Cloudflare pool; Vite+ handles frontend builds, formatting, and linting. +The CLI starts the proxy, supplies its URL and temporary credentials to the build, and commits the publication when the command succeeds. Failed builds abort the publication. -## Deploying an instance +For Maven, point both `distributionManagement.repository` and `snapshotRepository` at `${env.MAVEN_R2_URL}`. Their server credentials come from `MAVEN_R2_USERNAME` and `MAVEN_R2_PASSWORD`. Working examples are in [`examples/gradle`](examples/gradle) and [`examples/maven`](examples/maven). -1. Authenticate Wrangler and create a D1 database and a **private** R2 bucket: +Uploads are staged remotely before the proxy responds. For large artifacts, increase `systemProp.org.gradle.internal.http.socketTimeout` in `gradle.properties`, as the Gradle example does. - ```sh - pnpm --filter @maven-r2/worker exec wrangler login - pnpm --filter @maven-r2/worker exec wrangler d1 create maven-r2 - pnpm --filter @maven-r2/worker exec wrangler r2 bucket create maven-r2 - ``` +### CI -2. Update `apps/worker/wrangler.jsonc`: replace the placeholder D1 ID, set `APP_URL` to the final HTTPS origin, configure your Worker domain, and set `ADMIN_GITHUB_IDS` to a comma-separated list of numeric GitHub IDs. Keep the R2 bucket private; all reads must pass through the Worker so repository permissions remain effective. +Set `MAVEN_R2_SERVER` and `MAVEN_R2_TOKEN`, then run the same `publish` command without a profile. Use a service-account token restricted to the repository, artifact path prefix, and publishing operations the project needs. -3. Create a GitHub OAuth app with callback `https://your-origin/api/auth/callback/github`. Set fresh deployment secrets interactively: +If the build also downloads private dependencies, give it a separate read token. The CLI removes `MAVEN_R2_TOKEN` from the build's environment. - ```sh - pnpm --filter @maven-r2/worker exec wrangler secret put BETTER_AUTH_SECRET - pnpm --filter @maven-r2/worker exec wrangler secret put BOOTSTRAP_TOKEN - pnpm --filter @maven-r2/worker exec wrangler secret put GITHUB_CLIENT_ID - pnpm --filter @maven-r2/worker exec wrangler secret put GITHUB_CLIENT_SECRET - ``` +### Recovering a publication - Use independent random secrets of at least 32 bytes for Better Auth and bootstrap. Numeric GitHub IDs, rather than changeable usernames, identify instance administrators. +If finalization fails for a transient reason, the CLI leaves the session open and prints its ID. Retry the commit or discard it: -4. Apply the database migration and deploy the Worker with its web assets: +```sh +maven-r2 --profile work session status SESSION_ID +maven-r2 --profile work session commit SESSION_ID +maven-r2 --profile work session abort SESSION_ID +``` - ```sh - pnpm --filter @maven-r2/worker exec wrangler d1 migrations apply DB --remote - just build - pnpm --filter @maven-r2/worker deploy - ``` +Sessions expire after 24 hours. Use `--keep-on-failure` to preserve a failed build's publication for inspection. -5. Call `POST /api/bootstrap` on your deployed origin with the `x-bootstrap-token` header. Sign in with an administrator's GitHub identity, create the service accounts and scoped tokens you need, and revoke the bootstrap publisher. Delete the bootstrap secret afterward with `wrangler secret delete BOOTSTRAP_TOKEN` in the Worker workspace. +## Downloading -Back up D1 **and** R2 together: D1 contains the published-object references and authorization state. The hourly cron expires abandoned publications, prunes superseded snapshots, and collects unreferenced objects. An R2 lifecycle rule that aborts incomplete multipart uploads provides a backstop for uploads interrupted between R2 creation and recording the upload ID in D1; do not configure object expiration on published objects. +Consumers use the hosted repository directly. They do not need the CLI. -### Instance policy +The default URL mappings expose releases at the origin and snapshots at `/snapshots`: -| Setting | Meaning | -| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------ | -| `INSTANCE_MODE=single` | One default workspace; users can be invited into it. Account creation is disabled. | -| `INSTANCE_MODE=multi` | Multiple independent workspaces share an instance. | -| `SIGNUP_MODE=closed` | Only allowlisted administrators can create new login identities; existing users can still sign in. | -| `SIGNUP_MODE=invite` | New users need an unexpired invitation matching their verified email, or an administrator identity. | -| `SIGNUP_MODE=open` | Anyone supported by a configured identity provider may register. Registration alone does not grant workspace membership. | -| `ALLOW_ACCOUNT_CREATION=true` | In multi mode, signed-in users may create workspaces; otherwise only instance administrators can. | -| `MAX_FILE_BYTES` | Instance upper bound for each artifact; repositories can set a lower limit. Default: 2 GiB. | -| `MAX_ACCOUNT_BYTES` | Default workspace quota. Published files and reserved uploads both count. Default: 10 GiB. | +```kotlin +repositories { + maven("https://repo.example.com") + maven("https://repo.example.com/snapshots") +} +``` -Optional OIDC uses `OIDC_DISCOVERY_URL`, `OIDC_CLIENT_ID`, and `OIDC_CLIENT_SECRET`, with callback `/api/auth/callback/oidc`. GitHub remains the instance-admin identity source. Provider account linking is disabled. Invitation links are copied by an administrator and shared manually; no email delivery service is required. +Repositories start **private**. For private downloads, use Basic authentication with any username and a scoped read token as the password. Public repositories need no credentials. The console supplies repository URLs and dependency snippets. -An **account** is a workspace; a **user** is a login identity. Owners manage other owners, admins manage repositories and ordinary memberships, publishers publish, and readers download. Instance administrators can manage all workspaces, including suspension and quotas. A token's permissions are the intersection of its owner's current role and its scopes. Service accounts are readers or publishers, not administrators. +You can change `vars.REPOSITORY_MAPPINGS` in your deployment configuration. URLs of the form `/maven/{account}/{repository}` also work regardless of the mappings. -A scope such as `com/acme/sdk` matches that namespace and descendants, never `com/acme/sdkevil`. Empty prefixes grant the whole repository. Operations are `read`, `publish:release`, `publish:snapshot`, and `delete`. Private dependency resolution generally needs `read` on the artifact namespace, including its Maven metadata. Publishing-only tokens can submit metadata for their staged artifacts without reading other namespaces. Public visibility intentionally permits anonymous reads regardless of token scopes. +
+Custom repository URLs -## Publishing +Each mapping selects an existing workspace and repository. Relative URLs resolve against `APP_URL`: -Build `bin/maven-r2` with `just build`, or use the platform binaries produced by the release workflow when a `v*` tag is pushed. No release tag is required for development. +```json +"REPOSITORY_MAPPINGS": [ + { "url": "/", "account": "default", "repository": "releases" }, + { "url": "/snapshots", "account": "default", "repository": "snapshots" } +] +``` -Create a token in the console and save it under a named profile: +Absolute HTTPS URLs can use other hostnames. Register those hostnames as Worker custom domains or routes separately. Mappings do not provision DNS or TLS, and they do not change repository visibility. -```sh -maven-r2 --server https://repo.example.com --profile work login -maven-r2 --profile work publish --repository acme/releases -- ./gradlew publish -maven-r2 --profile work publish --repository acme/snapshots -- mvn -s settings.xml deploy -``` +The longest matching path prefix wins. Missing artifacts do not fall back to another repository. Application paths such as `/api`, `/console`, and `/maven` are reserved. -The CLI launches a loopback-only proxy with a random per-run credential, starts the build, and commits after a successful exit. Configure publishing to use the injected `MAVEN_R2_URL`, `MAVEN_R2_USERNAME`, and `MAVEN_R2_PASSWORD`. The remote token is removed from the child's environment. The proxy spools at most four files concurrently to temporary files, computes MD5/SHA-1/SHA-256/SHA-512 in the same pass, uploads resumable parts, and cleans up the spool files. +
-Gradle publishing configuration: +## Deploying an instance -```kotlin -publishing { - repositories { - maven { - url = uri(providers.environmentVariable("MAVEN_R2_URL").get()) - isAllowInsecureProtocol = true // This URL is the local loopback proxy. - credentials { - username = providers.environmentVariable("MAVEN_R2_USERNAME").get() - password = providers.environmentVariable("MAVEN_R2_PASSWORD").get() - } - } - } -} -``` +The service needs a Cloudflare Worker, a D1 database, a private R2 bucket, and a GitHub OAuth app. D1 stores repository metadata and permissions. R2 stores artifact contents. -Artifact checksums are publisher-provided declarations. R2 verifies SHA-256 for single-part uploads; multipart uploads are checked for completeness and stored size without the Worker rereading their contents. Sidecars must match the declared hashes, and server-generated metadata is hashed on the Worker. Upload requests require all four hashes; use matching CLI and Worker versions. An identical retry is identified by the declared hashes and size; it never replaces an already published release object. +Keep production configuration in a private deployment repository that pins a commit of this project. Generate an ignored `apps/worker/wrangler.production.jsonc` beside the supplied `wrangler.jsonc`, using it as a template. Exclude the generated file through the source checkout's `.git/info/exclude`. Keeping the files together preserves the relative source, asset, and migration paths. The commands below assume that generated configuration exists and dependencies are installed. -The proxy answers each upload only after the file is staged remotely. Gradle's HTTP client gives up after 30 seconds by default, so set `systemProp.org.gradle.internal.http.socketTimeout` in `gradle.properties` to cover your largest artifact, as the Gradle example does. Maven's default timeout is long enough. +1. Authenticate Wrangler and create the resources: -For Maven, point both `distributionManagement.repository` and `snapshotRepository` at `${env.MAVEN_R2_URL}`, using a server ID with credentials from those environment variables. Complete multi-module examples are in [`examples/gradle`](examples/gradle) and [`examples/maven`](examples/maven). The Maven example uses the Flatten Maven Plugin to resolve `${revision}` in published POM coordinates. + ```sh + pnpm --filter @maven-r2/worker exec wrangler login + pnpm --filter @maven-r2/worker exec wrangler d1 create maven-r2 + pnpm --filter @maven-r2/worker exec wrangler r2 bucket create maven-r2 + ``` -In CI, set `MAVEN_R2_SERVER` and `MAVEN_R2_TOKEN` as environment variables and run the same `publish` command. Use a service-account token scoped to the repository and namespace being built. Profiles live in the OS user configuration directory with owner-only file permissions on Unix; `MAVEN_R2_CONFIG` overrides the file location. HTTPS is required except for loopback development origins. +2. In your production configuration, set the Cloudflare account ID, D1 ID, bucket name, Worker domain, `APP_URL`, and `ADMIN_GITHUB_IDS`. Administrator IDs are numeric GitHub user IDs. Keep the R2 bucket private with no public domain or r2.dev endpoint. -Failed builds and publications the server rejects during validation abort by default. `--keep-on-failure` preserves them for inspection. A finalization that fails for transient reasons, such as a network or server error, leaves the session open and prints its ID so the validated uploads can be retried: +3. Create a GitHub OAuth app with callback `https://your-origin/api/auth/callback/github`. Set these Worker secrets using `pnpm --filter @maven-r2/worker exec wrangler secret put NAME --config wrangler.production.jsonc`: -```sh -maven-r2 session status SESSION_ID -maven-r2 session commit SESSION_ID -maven-r2 session abort SESSION_ID -``` + - `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` from the OAuth app. + - `BETTER_AUTH_SECRET` and `BOOTSTRAP_TOKEN`, each independently generated with at least 32 random bytes. -`session begin --repository acme/releases` and `serve --session SESSION_ID --env-file local.env` support explicit sessions. Source that environment file with exported variables in the build shell; commit explicitly afterward. The file is removed when `serve` exits. `publish --session SESSION_ID -- COMMAND` can retry an existing build if each previously staged path still has identical content. Rebuilt artifacts with different bytes require a new session. Sessions expire after 24 hours. +4. Build, migrate, and deploy: -## Downloading + ```sh + pnpm --filter @maven-r2/web build + pnpm --filter @maven-r2/worker exec wrangler d1 migrations apply DB --remote --config wrangler.production.jsonc + pnpm --filter @maven-r2/worker exec wrangler deploy --config wrangler.production.jsonc + ``` -Consumers point directly at: +5. Call `POST /api/bootstrap` with the `x-bootstrap-token` header. This creates the default workspace, private release and snapshot repositories, and a temporary publisher token. Sign in through GitHub, create scoped tokens for your projects, and revoke the bootstrap publisher. Delete `BOOTSTRAP_TOKEN` with `wrangler secret delete`, using the same production configuration. -```text -https://repo.example.com/maven/acme/releases -https://repo.example.com/maven/acme/snapshots -``` +The default signup policy is closed. Only configured administrators can register. `SIGNUP_MODE=invite` allows registration with an invitation, and `SIGNUP_MODE=open` allows registration without one. Registration alone does not grant workspace access. -Public repositories need only the URL. For private repositories, use any Basic-auth username and a scoped read token as the password. The web console supplies dependency coordinates and repository snippets. No local proxy is needed for downloads. Configure dependency repositories separately from publishing destinations, including in CI. If the publishing build also downloads private dependencies, supply a separate read credential (for example `MAVEN_R2_READ_TOKEN`); the proxy deliberately removes `MAVEN_R2_TOKEN` from the build environment. +For **Workers Free**, remove `limits.cpu_ms` from the generated configuration. Computing checksums in the CLI does not guarantee that every workload fits the free tier. Check the [Worker limits](https://developers.cloudflare.com/workers/platform/limits/) and [D1 limits](https://developers.cloudflare.com/d1/platform/limits/) against your workload. -### Custom repository URLs +Back up **D1 and R2 together**. Do not add an R2 object-expiration rule for published artifacts. The Worker's scheduled cleanup handles expired publications, snapshot retention, and unreferenced objects. -Set `vars.REPOSITORY_MAPPINGS` in `apps/worker/wrangler.jsonc` to map URLs to existing account/repository slugs. Origin-relative URLs resolve against `APP_URL`, so the default configuration serves the bootstrap repositories from the console origin: +## Development -```json -"REPOSITORY_MAPPINGS": [ - { - "url": "/", - "account": "default", - "repository": "releases" - }, - { - "url": "/snapshots", - "account": "default", - "repository": "snapshots" - } -] +Install [mise](https://mise.jdx.dev/), then run: + +```sh +mise trust +mise install +mise exec -- just setup +cp apps/worker/.dev.vars.example apps/worker/.dev.vars +mise exec -- pnpm db:migrate +mise exec -- just dev ``` -With `APP_URL` set to `https://repo.example.com`, consumers of public repositories can then use: +Open http://localhost:5173. Wrangler emulates the Cloudflare resources locally. Initialize the instance once: -```kotlin -repositories { - maven("https://repo.example.com") - maven("https://repo.example.com/snapshots") -} +```sh +curl --fail-with-body -X POST http://localhost:5173/api/bootstrap \ + -H 'x-bootstrap-token: local-bootstrap-only-replace-before-deploy' ``` -Absolute URLs map repositories hosted on separate custom domains, such as `https://snapshots.example.com`. Locally, `http://localhost:5173/` and `http://localhost:5173/snapshots/` serve the default repositories because Vite+ forwards them to the Worker without rewriting the host. +To sign into the console, configure a development GitHub OAuth app in `.dev.vars` and set `ADMIN_GITHUB_IDS` in the local Wrangler configuration. The callback is `http://localhost:5173/api/auth/callback/github`. The example secrets are for local development only. -Mappings preserve repository visibility, token scopes, and R2 streaming. Bootstrap repositories are private until an administrator changes their visibility; private consumers still need read credentials. Existing `/maven/{account}/{repository}` URLs continue to work, and publishing still uses the account/repository pair through the CLI. +Use `mise exec --` before commands if mise is not active in your shell: -Mappings work in both instance modes. Each URL selects exactly one repository. To serve another account, configure another hostname or path with that account's slugs. Register each hostname as a [Worker custom domain](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/) or Worker route pointing to this Worker; adding a mapping does not provision DNS or TLS. Keep the R2 bucket private. - -Relative URLs start with a single slash. Absolute URLs must use HTTPS, except HTTP on `localhost`, `127.0.0.1`, or `[::1]` for local development. Matching uses the exact origin and the longest matching path prefix at a slash boundary, so `/snapshots` takes precedence over a root mapping. A missing artifact in that repository returns 404 without falling back to another repository. Trailing slashes are optional; duplicate URLs are rejected. `/api`, `/maven`, `/console`, `/health`, `/invite`, `/favicon.ico`, `/robots.txt`, and `/.well-known` are reserved, including their descendants. Nested mappings also reserve their prefixes in the parent mapping; artifacts shadowed by these prefixes remain available at the canonical `/maven/...` URL. +```sh +just format # Format TypeScript and Go +just check # Formatting, lint, type checks, and go vet +just test # Worker and Go tests +just build # Build the web app, Worker, and CLI +just contracts # Regenerate API clients after contract changes +just ready # Check, test, and build +``` -The console is served from `/` and routes with a URL hash, for example `/#/default/repositories`, so root mappings and console pages share the origin without ambiguity. Its assets stay under `/console/assets/`, and old `/console/...` bookmarks and `/invite` links redirect to the matching `/#/...` route. `APP_URL` is the console's origin; OAuth callback URLs stay under `/api/auth`. The console displays the first configured mapping for a repository in copyable URLs and dependency snippets, falling back to its canonical URL when no mapping exists. Browser download buttons use the console origin so session credentials work even when a mapping uses another hostname. +For Maven/Gradle interoperability and browser tests, install Chromium with `pnpm exec playwright install chromium`, then run `just interop`. ## Known limitations -- GitHub/OIDC provider redirects and deployed Cloudflare behavior require deployment credentials to validate. Automated checks cover local Cloudflare bindings, Better Auth session validation, real Maven/Gradle interoperability, and browser management flows. -- Publication sessions are bounded to 500 uploaded files (including sidecars), 32 artifact IDs, 32 snapshot versions, and a bounded finalization transaction. Split larger builds into separate sessions. POMs and metadata are limited to 1 MiB; ordinary file limits are configurable. The 2 GiB default has not been load-tested on deployed Workers. -- Releases and timestamped snapshot files cannot change in place. An identical retry is accepted; adding new files to an existing release requires deleting and republishing the complete version. Non-timestamped snapshots are mutable. Signed repository metadata is rejected because the server regenerates metadata; artifact signatures are preserved but not cryptographically verified. -- Version deletion and retention remove references immediately and delay object deletion by an hour for in-flight readers. Quotas measure logical stored content and reservations, not temporary duplicate R2 storage or retained audit/session records. -- Console account listings are capped at 200 workspaces; publication and audit history show the latest 100 entries. File browsing uses pagination. Retention and garbage collection run in bounded batches and may take several hourly passes for a backlog. -- Upstream mirrors/proxy caches, virtual repositories, Maven Central promotion, webhooks, download analytics, bulk imports, and a browser OAuth device flow for the CLI are not implemented. The CLI logs in with a console-issued token. +- The CLI supplies MD5, SHA-1, SHA-256, and SHA-512 checksums. R2 verifies SHA-256 for single-part uploads. For multipart uploads, the service checks completeness and stored size but trusts the publisher's hashes. Supplied checksum sidecars must match those hashes. +- Releases and timestamped snapshots are immutable. Identical retries are accepted, but changing an existing release requires deleting and republishing the complete version. Artifact signatures are stored without cryptographic verification. +- A publication can contain at most 500 files including sidecars, 32 artifact IDs, and 32 snapshot versions. POMs and metadata are limited to 1 MiB. The default per-file limit is 2 GiB, which has not been load-tested on deployed Workers. +- Storage quotas count published and reserved bytes, not temporary duplicate objects or audit history. Deletion removes references immediately, but object cleanup is delayed by at least an hour. +- Upstream repository mirroring and Maven Central promotion are not implemented. ## License