diff --git a/docs/adr/0003-public-sharing-export-reader.md b/docs/adr/0003-public-sharing-export-reader.md new file mode 100644 index 000000000..525c28881 --- /dev/null +++ b/docs/adr/0003-public-sharing-export-reader.md @@ -0,0 +1,168 @@ +# ADR 0003: Public sharing through Hub exports and an isolated reader + +Status: accepted on November 29, 2026, with the [policy decisions](#accepted-policy-decisions) recorded below. + +## Context + +A signed-in Hub user can create a public link to one successful Build. Anyone with the link can open that Build without signing in until the link expires or is revoked. + +Today's links ([Build share links](../../hub/docs/share-links.md)) are `ShareLink` rows with a random UUID, a label, an expiry and a revocation tombstone. Hub serves them through the legacy Build-specific preview origin, which needs wildcard DNS and TLS that the Azure reference installation does not provision. Rails used `/share/:public_id` with the same idea and no password. No Rails share data was imported. + +The [private prototype service](../../hub/docs/build-previews.md#private-prototype-service) now serves eligible Builds at `/previews/github///`. These Builds are compiled for that exact path, so they do not work under a different path. + +## Accepted requirements + +- Hub stores share records and writes or revokes exports in a separate public export storage, using a container-scoped managed identity. +- A separate read-only public reader serves exports. It has no access to the Hub database, Hub secrets, private storage, or Hub APIs. +- The same Terraform and setup wizard install both. There is no separate lifecycle API. +- Normal multi-file prototypes with large asset sets work without a second bundle. +- Sharing never deletes or rewrites stored private Builds. + +## Decision + +```mermaid +flowchart LR + user["Hub user"] --> hub["Hub API and worker"] + hub --> db[("Hub database: share records")] + hub -- "reads Build files" --> private[("Private Build storage")] + hub -- "writes and revokes" --> exports[("Public export storage")] + hubId["Hub identity: export contributor"] -.-> exports + viewer["Link viewer"] -- "/s/shareId" --> reader["Public reader"] + reader -- "reads by exact key" --> exports + readerId["Reader identity: read only, no listing"] -.-> exports + reader -. "no route" .-> hub + reader -. "no grant" .-> private + setup["Terraform and setup wizard"] -. "provisions" .-> exports + setup -. "provisions" .-> reader +``` + +### Components and permissions + +| Component | Can do | Cannot do | +| --- | --- | --- | +| Hub API and on-demand worker | Read Build files; create, overwrite and delete objects in the export container | Nothing new outside that container | +| Public export storage | Separate storage account and container; shared keys and anonymous access off | Serve anything without the reader | +| Public reader | Read exact export objects with its own identity | List, write or delete blobs; reach Hub, its database, Key Vault or private storage | + +The reader runs from the Hub image with its own start command, like the private reader, but its modules import only Node built-ins, Express, zod, the Azure SDK, Hub's dependency-free start-page and private-preview address rules, and other public-share modules. A test enforces that import boundary. + +### Storage layout and manifest + +Each share is a self-contained copy. Two shares of one Build are two copies, so revoking or deleting one never affects the other and no reference counting is needed. + +| Object | Written | Purpose | +| --- | --- | --- | +| `shares//files/` | First, create-only | One served `dist/` file, named by its SHA-256 | +| `shares//manifest.json` | After every file | Immutable file index | +| `shares//policy.json` | Last; overwritten for changes | Activation, expiry, password and revocation | + +The share is live only once `policy.json` exists, so a viewer never sees a partial export. + +`manifest.json`, version 1: + +```json +{ + "version": 1, + "shareId": "6f2c…", + "mount": "/previews/github/901/1201/", + "entry": "/", + "files": { "index.html": { "sha256": "…", "size": 812 }, "assets/app.js": { "sha256": "…", "size": 90211 } } +} +``` + +`policy.json`, version 1: + +```json +{ + "version": 1, + "shareId": "6f2c…", + "state": "active", + "expiresAt": "2026-12-06T08:00:00.000Z", + "password": { "algorithm": "scrypt", "cost": 16384, "blockSize": 8, "parallelization": 1, "salt": "…", "hash": "…" } +} +``` + +`state` is `active` or `revoked`. `password` is `null` when the link has none. Hub never stores or exports a plaintext password. + +### URL contract + +Each link is an opaque entry that leads into the Build's own mount on the public origin. + +1. Hub gives out `https:///s/`. The share ID is the existing random `publicId` UUID. +2. The reader checks the policy. For a password link, it asks for the password first. +3. The reader sets a host-only, HTTP-only cookie named `__Secure-replica-share-` with `Path=` and redirects to ``. +4. Every file request under the mount reads the share cookies the browser sent, rechecks each share's policy, and serves from the first active share whose mount matches. + +Two shares of one Build use two cookies with the same path. Revoking one leaves the other working only for viewers who opened the other link. A password link's cookie holds an HMAC keyed by the stored password hash, so changing or removing the password ends existing password sessions. + +Only Builds that the private prototype service can already serve are eligible, because their mount is verified. Hub shows "This Build can't be shared publicly" for every other Build. This rules out automatic rebuilds, response rewriting, framework internals and per-share wildcard DNS. + +Accepted trade-offs: + +- After opening, the address bar shows the mount, which includes the numeric GitHub repository and workflow run IDs. These are not secret, but today's links reveal neither. +- All shares share one origin and its browser storage. A shared prototype's script can read storage of other shares and fetch other shares' files only within a browser that has already opened those shares. The private reader accepts the same trade-off. +- That includes password prompts. A shared prototype's script can open another share's password page in a same-origin window and read a password the viewer types there. A password therefore protects a link from people who only have the URL, not from other prototypes the same viewer opens. +- Same-origin script can also set many share cookies and hide real ones. This only breaks viewing in that browser. +- Public shares open top level. They cannot be framed and do not include Hub's Controls panel or review bridge. + +Rejected alternatives: serving the mount without an entry cannot tell two shares apart and leaks repository identity in the link itself. Accepting only root-relative packages would exclude every current `proto/*` Build. + +### Public hostname + +The reader serves links on its generated Azure Container Apps hostname in every installation, including Production. An installation can add a custom domain later as an optional setup wizard setting. + +- The reader accepts exactly two HTTPS origins: its generated origin and, when configured, the custom one. It refuses every other host. +- Hub builds new links on the custom origin when one is configured, and on the generated origin otherwise. +- Adding a custom domain does not break existing links, because the generated hostname keeps working. + +Public sharing shares no cookies with Hub. In Production, Hub uses `replica.coreai.design` and the private reader uses `preview.replica.coreai.design`, so the reader's generated hostname is a different site from both. Three caveats remain: + +- Links on the generated hostname break if the reader's app or Container Apps environment is recreated without a custom domain. +- `azurecontainerapps.io` is not a public suffix, so browsers treat every generated Container Apps hostname as one site, including apps in other environments and other tenants. Those apps can send same-site requests to the reader and set cookies it receives. The reader serves nothing secret to such requests: responses are same-origin only, and a forged share cookie can open only a passwordless share whose link the sender already has, or hide real cookies in that browser. +- The same applies in reverse to a Hub on its generated hostname: shared prototypes would be same-site with it. By default, Hub and the setup wizard refuse to enable public sharing while Hub uses a generated hostname. Production uses a custom domain, so the default holds there; Hub's cookies are host-only on `replica.coreai.design`. + +A non-production installation, such as Staging, can opt in anyway with `HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE=true`. The setup wizard offers this only for non-production installations and warns about the shared-site trade-off first. The risk is accepted there because a Hub on a generated hostname is already same-site with every Container App, shared or not. Its real protections are its host-only `__Host-` cookies and exact-origin request checks, which sharing does not change. + +### Request checks + +The reader runs these checks for every request, including assets and `HEAD`: + +- The request uses HTTPS on one of the reader's allowed hostnames. +- The share ID, mount and file path are valid; files are read only by manifest key, never by request path, and storage is never listed. +- The policy is `active` and `expiresAt` is in the future, checked again after the file read. +- A password link has a valid cookie proof. +- File, manifest and policy reads are size-bounded and time out. Files share a 100 MiB in-memory allowance per process, and policies and manifests share a separate 40 MiB one. A file's reservation lasts until both its read and its response end, and a stalled download is dropped after 30 seconds without progress. Manifests may list up to 2,000 files, matching a Build's limit. +- Password attempts are limited to 5 per caller address and link in 10 minutes, as a temporary cooldown that never locks or turns off the link, counted before each check, with at most 4 checks running at once. Each replica counts separately, so the limit grows with the number of replicas. A shared count would need the reader to write storage or another service, so the per-replica limit is accepted; passwords need at least 8 characters and scrypt keeps each guess slow. + +Exact files are served first, then a directory's `index.html`; a directory requested without its trailing slash redirects to add it. The mount root without its slash redirects to the mount before any share is read, because share cookies cover only the slash-terminated mount. An extensionless document navigation falls back to the export's `index.html`. Missing assets return 404. + +Responses send a strict content security policy, `X-Robots-Tag: noindex, nofollow, noarchive`, `Referrer-Policy: no-referrer`, `frame-ancestors 'none'` and `Cache-Control: private, no-cache` with a content-hash ETag, so browsers revalidate and policy checks still run. The reader sets only its own share cookies and ignores all others. + +### Revocation + +Hub revokes by overwriting `policy.json` with `state: "revoked"` during the user's request; a worker retries if the write fails and the UI shows the revocation as pending. Each reader replica caches a policy for at most 5 seconds, so revocation reaches every replica within 5 seconds of the write. Expiry is exact because it is compared on each request. Bytes already sent cannot be recalled. A worker then deletes the copied files within 24 hours of revocation or expiry. Private Builds and Hub share records are never deleted. + +## Pull requests + +| PR | Scope | Depends on | +| --- | --- | --- | +| 1. Public reader and export contract | Reader, start command, manifest and policy schemas, storage keys, password hashing, adapters, tests and docs. Not deployed or enabled. | None | +| 2. Hub export and share records | Additive `ShareLink` columns for backend, export state and password flag; export and revoke jobs; share API and **Share links** UI; eligibility message; refusal to enable while Hub's own hostname is a generated `azurecontainerapps.io` one, unless `HUB_PUBLIC_SHARE_ALLOW_SHARED_SITE=true`; legacy links unchanged | PR 1 contract | +| 3. Terraform and setup wizard | Export storage account and container, reader Container App and identity, container-scoped grants, the reader's generated hostname with an optional custom domain setting, settings on Hub and reader, disabled by default and refused while Hub uses a generated hostname; the wizard sets the shared-site override only for non-production installations | PR 1 start command and settings | + +PR 2 and PR 3 can proceed in parallel after PR 1. Enabling public sharing needs all three, plus a non-production end-to-end check with a real framework-built `proto/*` Build. + +## Accepted policy decisions + +The Replica maintainers accepted these on November 29, 2026: + +| Decision | Result | +| --- | --- | +| Extending an active link's expiry | Not allowed. Create a new link. Deadlines never grow. | +| Passwords | Optional per link, at least 8 characters, set at creation and replaceable or removable later. The shared-origin exposure above is accepted. | +| Copied files after revocation or expiry | Deleted within 24 hours. The Hub record stays for history. Sharing again makes a new copy. | +| Viewing during a Hub outage | Active links stay viewable. Revocations made during an outage take effect when Hub can write the policy again. | +| Existing `ShareLink` rows | Left unchanged on the legacy backend. They are not converted or redirected to exports. | +| Mount path in the address bar | Accepted. Hiding it would need response rewriting or rebuilds. | +| Public hostname | The reader's generated Container Apps hostname, with an optional custom domain later. See [public hostname](#public-hostname). | +| Hub on a generated hostname | Sharing is refused by default. Non-production installations, such as Staging, may opt in with an explicit shared-site override. | diff --git a/hub/docs/README.md b/hub/docs/README.md index bb92b0647..114565794 100644 --- a/hub/docs/README.md +++ b/hub/docs/README.md @@ -13,6 +13,7 @@ Hub is being rebuilt. The [Hub overview](../README.md) describes what the baseli - [GitHub Actions Builds](github-actions-builds.md): workflow events, dist and screenshot artifact contracts, and idempotent import. - [Build previews](build-previews.md): authenticated access, isolated Build origins, file behavior, screenshots, and bridge injection. - [Build share links](share-links.md): local and hosted opt-in, Build-pinned public links, revocation, and the separate public preview session. +- [Public share reader](public-share-reader.md): export contract, per-request checks, and runtime settings for the isolated read-only reader. - [Database](database.md): Prisma schema conventions, migrations, and the shared client. - [Authentication and Hub sessions](authentication.md): provider-neutral proof, reusable administrator enrollment, admission, browser sessions, and existing-user administrator management. - [Copilot connection](copilot.md): operator token configuration, fresh administrator authorization, durable connection state, and credential safety. diff --git a/hub/docs/public-share-reader.md b/hub/docs/public-share-reader.md new file mode 100644 index 000000000..b45759bfa --- /dev/null +++ b/hub/docs/public-share-reader.md @@ -0,0 +1,68 @@ +# Public share reader + +The public share reader lets anyone with a share link open one exported Build without signing in. It reads exported files from a separate public export storage and never contacts Hub. Hub does not write exports or give out reader links yet; [ADR 0003](../../docs/adr/0003-public-sharing-export-reader.md) describes the planned integration and its accepted policies. Existing [Build share links](share-links.md) are unchanged. + +## Export contract + +Hub will write each share as a self-contained copy. The reader only reads these objects by exact name and never lists storage. + +| Object | Contents | +| --- | --- | +| `shares//files/` | One served `dist/` file, named by the SHA-256 of its bytes | +| `shares//manifest.json` | Version 1 index: `shareId`, the Build's private prototype `mount` (`/previews/github///`), start page `entry` (normalized as Hub normalizes start pages), and each package path's `sha256` and `size`, for at most 2,000 files | +| `shares//policy.json` | Version 1 policy: `state` (`active` or `revoked`), `expiresAt`, and an optional scrypt `password` hash | + +A writer copies every file first, then the manifest, then the policy. The share stays unavailable until the policy exists. To revoke a share, overwrite its policy with `state: "revoked"`. The schemas live in `server/domains/public-share-export/types.ts`; use `hashPublicSharePassword()` to create a policy's password hash from a password of at least 8 characters. + +## What a viewer sees + +1. The viewer opens `https:///s/`. +2. For a password link, the reader asks for the password. After 5 attempts from one address within 10 minutes, that address must wait for the rest of the 10 minutes. The link keeps working, and other viewers are not affected. Each replica counts separately, so the limit grows with the number of replicas. +3. The reader sets a cookie for the Build's mount and redirects to the start page. +4. The prototype loads from its own mount, for example `/previews/github/901/1201/`. A request for the mount without its final slash, which routers with a base path can produce on reload, redirects to add the slash and keeps the query. The redirect depends only on the path, because the browser sends no share cookie there. + +Only Builds compiled for their mount work. See [private prototype service](build-previews.md#private-prototype-service) for the base-path requirement. + +## Checks on every request + +Every page, asset and `HEAD` request passes these checks before the reader returns a file: + +- The request uses HTTPS on the generated or custom hostname. +- The browser holds a cookie for an active, unexpired share whose mount matches the path. A password link's cookie must match its current password. +- The manifest lists the requested file. A directory path with a trailing slash uses its `index.html`; without the slash, the reader redirects to add it. Extensionless document navigations fall back to the root `index.html`; missing assets return 404. +- The stored file has the recorded size, is at most 100 MiB, and fits the process's 100 MiB file read allowance. Policy and manifest reads use a separate 40 MiB allowance, so a large file cannot block the checks it depends on. A download that makes no progress for 30 seconds is dropped and releases its allowance. +- The share is still active, and its password unchanged, after the file read. + +The reader checks the newest 8 share cookies the browser sends; opening a link makes its cookie the newest. Each replica keeps a policy for up to 5 seconds from when it started reading it, so revocation reaches every replica within 5 seconds. Expiry is compared on every request. Bytes already sent cannot be recalled. + +Responses send a strict content security policy, deny framing, send `X-Robots-Tag: noindex, nofollow, noarchive` and `Referrer-Policy: no-referrer` (`same-origin` on the password page, so its form keeps its origin), and set only the reader's own share cookies. Files use `Cache-Control: private, no-cache` with a content-hash ETag, so browsers revalidate each file and the checks still run. The reader does not support byte ranges, service workers or framing. + +## Runtime settings + +The reader accepts only the settings below and the managed-identity variables Azure sets. It refuses to start when any other setting in a Replica, Hub, GitHub, Entra, Copilot, Azure, artifact storage, private preview or database family is present, or when a setting's name marks it as a secret, token, password, key or connection string. It therefore cannot receive Hub credentials or private storage coordinates by mistake. The Hub image's own fixed settings are allowed. Developer tokens such as `GH_TOKEN` also stop it, so for a local run, start it from `hub/` with only the settings it needs: + +```sh +env -i PATH="$PATH" HOME="$HOME" \ + PUBLIC_SHARE_GENERATED_ORIGIN=https://share.example.net \ + PUBLIC_SHARE_TRUSTED_PROXY_HOPS=1 \ + PUBLIC_SHARE_STORAGE_PROVIDER=filesystem \ + PUBLIC_SHARE_STORAGE_DIRECTORY=/absolute/path/to/exports \ + npm run dev:public-share-reader +``` + +The reader listens on `127.0.0.1:3003` and answers only HTTPS requests for its configured host, so put a local TLS proxy that sets `X-Forwarded-Proto` in front of it. + +| Setting | Value | +| --- | --- | +| `PUBLIC_SHARE_GENERATED_ORIGIN` | The reader's generated HTTPS origin, such as `https://reader.example.azurecontainerapps.io` | +| `PUBLIC_SHARE_CUSTOM_ORIGIN` | Optional custom-domain HTTPS origin, such as `https://share.example.net` | +| `PUBLIC_SHARE_TRUSTED_PROXY_HOPS` | Proxy hops in front of the reader, from 1 to 10 | +| `PUBLIC_SHARE_STORAGE_PROVIDER` | `azure`, or `filesystem` for local development | +| `PUBLIC_SHARE_STORAGE_ACCOUNT`, `PUBLIC_SHARE_STORAGE_CONTAINER` | Azure export storage account and container | +| `AZURE_CLIENT_ID` | Optional user-assigned managed identity client ID | +| `PUBLIC_SHARE_STORAGE_DIRECTORY` | Absolute trusted directory for `filesystem` | +| `PORT`, `HOST` | Defaults to `3003` and `127.0.0.1` | + +Run `npm run start:public-share-reader` from the built image, or `npm run dev:public-share-reader` from source. Give the reader's own managed identity `Storage Blob Data Reader` on the export container only, conditioned to deny listing. Give it no access to Hub's database, Key Vault or private storage. Both origins must be exact HTTPS origins and must differ. Keep the generated origin after adding a custom domain so existing links keep working. Every generated `azurecontainerapps.io` hostname is the same site, so enable sharing only when Hub uses a custom domain, except in a non-production installation that explicitly accepts the shared-site override; see [public hostname](../../docs/adr/0003-public-sharing-export-reader.md#public-hostname). + +The reader imports only its own modules, Hub's dependency-free start-page and private-preview address rules, Node built-ins, Express, zod and the Azure SDK. A test in `server/scripts/start-public-share-reader/` enforces this boundary. diff --git a/hub/package.json b/hub/package.json index 22ea1da16..e9f6a26d8 100644 --- a/hub/package.json +++ b/hub/package.json @@ -54,6 +54,8 @@ "start": "node dist/server/index.js", "start:preview-reader": "node dist/server/scripts/start-private-preview-reader/index.js", "dev:preview-reader": "node server/scripts/start-private-preview-reader/index.ts", + "start:public-share-reader": "node dist/server/scripts/start-public-share-reader/index.js", + "dev:public-share-reader": "node server/scripts/start-public-share-reader/index.ts", "preview": "vite preview --host 127.0.0.1", "extension:assets:check": "node ../.github/extensions/replica-prototype/check-assets/index.mjs", "extension:build": "npm run extension:modules:build && vite build --config vite.prototype-canvas.config.mjs && node script/build-prototype-preview-bridge.mjs", diff --git a/hub/server/domains/public-share-export/create-public-share-byte-allowance/index.ts b/hub/server/domains/public-share-export/create-public-share-byte-allowance/index.ts new file mode 100644 index 000000000..a22f3052a --- /dev/null +++ b/hub/server/domains/public-share-export/create-public-share-byte-allowance/index.ts @@ -0,0 +1,20 @@ +const minimumReservationBytes = 64 * 1024 + +/** + * Bounds bytes held in memory for storage reads. Each reservation covers at least 64 KiB and + * returns null when the allowance is full; its release function is safe to call twice. + */ +export function createPublicShareByteAllowance(maximumBytes: number) { + let reservedBytes = 0 + return function reserve(byteLength: number): (() => void) | null { + const bytes = Math.max(byteLength, minimumReservationBytes) + if (bytes > maximumBytes - reservedBytes) return null + reservedBytes += bytes + let released = false + return () => { + if (released) return + released = true + reservedBytes -= bytes + } + } +} diff --git a/hub/server/domains/public-share-export/create-public-share-proof/index.ts b/hub/server/domains/public-share-export/create-public-share-proof/index.ts new file mode 100644 index 000000000..3e519cce3 --- /dev/null +++ b/hub/server/domains/public-share-export/create-public-share-proof/index.ts @@ -0,0 +1,17 @@ +import { createHmac } from "node:crypto" + +import { openPublicShareProof, type PublicShareManifest, type PublicSharePolicy } from "../types.ts" + +/** + * Returns the cookie value that lets a browser open a share's files. A password link's proof is + * keyed by its stored hash, so changing or removing the password ends existing password sessions. + */ +export function createPublicShareProof( + manifest: Pick, + policy: Pick, +): string { + if (!policy.password) return openPublicShareProof + return createHmac("sha256", Buffer.from(policy.password.hash, "base64url")) + .update(`replica-public-share-v1\n${manifest.shareId}\n${manifest.mount}`) + .digest("base64url") +} diff --git a/hub/server/domains/public-share-export/create-public-share-state-reader/index.test.ts b/hub/server/domains/public-share-export/create-public-share-state-reader/index.test.ts new file mode 100644 index 000000000..231523f66 --- /dev/null +++ b/hub/server/domains/public-share-export/create-public-share-state-reader/index.test.ts @@ -0,0 +1,171 @@ +import { randomUUID } from "node:crypto" +import { describe, expect, it, vi } from "vitest" + +import type { PublicShareObjectReader, PublicShareObjectReadResult } from "../types" +import { createPublicShareStateReader } from "." + +const start = Date.parse("2026-11-29T08:00:00.000Z") + +function stored(value: unknown): PublicShareObjectReadResult { + return { status: "ok", bytes: Buffer.from(JSON.stringify(value)) } +} + +function policy(shareId: string, changes: Record = {}) { + return stored({ + version: 1, + shareId, + state: "active", + expiresAt: new Date(start + 60_000).toISOString(), + password: null, + ...changes, + }) +} + +// Returns an export storage reader for one share, with either object replaced. +function exportStorage( + shareId: string, + objects: { policy?: PublicShareObjectReadResult; manifest?: PublicShareObjectReadResult } = {}, +): PublicShareObjectReader { + const manifest = stored({ + version: 1, + shareId, + mount: "/previews/github/901/1201/", + entry: "/", + files: { "index.html": { sha256: "a".repeat(64), size: 12 } }, + }) + return (key) => + Promise.resolve( + key.endsWith("policy.json") + ? (objects.policy ?? policy(shareId)) + : (objects.manifest ?? manifest), + ) +} + +describe("createPublicShareStateReader()", () => { + it("shares one policy read between concurrent requests until the cache window ends", async () => { + const shareId = randomUUID() + let clock = start + const storage = exportStorage(shareId) + const readObject = vi.fn(async (key, maximumBytes, signal) => { + const result = await storage(key, maximumBytes, signal) + // A slow policy read must not extend the cache window. + if (key.endsWith("policy.json")) clock += 500 + return result + }) + const readShare = createPublicShareStateReader({ + readObject, + policyCacheMilliseconds: 1_000, + now: () => clock, + }) + function policyReads() { + return readObject.mock.calls.filter(([key]) => key === `shares/${shareId}/policy.json`).length + } + + const states = await Promise.all([readShare(shareId), readShare(shareId), readShare(shareId)]) + expect(states.map(({ status }) => status)).toEqual(["active", "active", "active"]) + expect(policyReads()).toBe(1) + + clock = start + 999 + await readShare(shareId) + expect(policyReads()).toBe(1) + + clock = start + 1_000 + await readShare(shareId) + expect(policyReads()).toBe(2) + }) + + it.each<[string, (shareId: string) => PublicShareObjectReadResult]>([ + ["a missing policy", () => ({ status: "not-found" })], + ["a revoked policy", (shareId) => policy(shareId, { state: "revoked" })], + [ + "a policy that expires now", + (shareId) => policy(shareId, { expiresAt: new Date(start).toISOString() }), + ], + ])("treats %s as an inactive link", async (_name, policyFor) => { + const shareId = randomUUID() + const readShare = createPublicShareStateReader({ + readObject: exportStorage(shareId, { policy: policyFor(shareId) }), + now: () => start, + }) + + await expect(readShare(shareId)).resolves.toEqual({ status: "inactive" }) + }) + + it.each<[string, Parameters[1]]>([ + ["unavailable policy storage", { policy: { status: "unavailable" } }], + ["a policy that isn't JSON", { policy: { status: "ok", bytes: Buffer.from("{") } }], + ["a policy for another share", { policy: policy(randomUUID()) }], + ["an active policy without its manifest", { manifest: { status: "not-found" } }], + ])("treats %s as temporarily unavailable", async (_name, objects) => { + const shareId = randomUUID() + const readShare = createPublicShareStateReader({ + readObject: exportStorage(shareId, objects), + now: () => start, + }) + + await expect(readShare(shareId)).resolves.toEqual({ status: "unavailable" }) + }) + + it.each([ + ["expires", 60_000, {}], + ["is revoked after its cached policy goes stale", 5_000, { state: "revoked" }], + ])( + "treats a link that %s while its manifest loads as inactive", + async (_name, delay, changes) => { + const shareId = randomUUID() + let clock = start + let storedPolicy = policy(shareId) + const storage = exportStorage(shareId) + const readShare = createPublicShareStateReader({ + readObject: async (key, maximumBytes, signal) => { + if (key.endsWith("policy.json")) return storedPolicy + const manifest = await storage(key, maximumBytes, signal) + clock += delay + storedPolicy = policy(shareId, changes) + return manifest + }, + policyCacheMilliseconds: 5_000, + now: () => clock, + }) + + await expect(readShare(shareId)).resolves.toEqual({ status: "inactive" }) + }, + ) + + it("reads within the shared byte allowance and is unavailable when it is full", async () => { + const shareId = randomUUID() + const held = new Set() + const reserve = vi.fn<(byteLength: number) => (() => void) | null>(() => { + const reservation = {} + held.add(reservation) + return () => void held.delete(reservation) + }) + const readObject = vi.fn(exportStorage(shareId)) + + await expect( + createPublicShareStateReader({ readObject, reserve, now: () => start })(shareId), + ).resolves.toMatchObject({ status: "active" }) + expect(reserve.mock.calls.map(([byteLength]) => byteLength)).toEqual([ + expect.any(Number), + expect.any(Number), + ]) + reserve.mock.calls.forEach(([byteLength], index) => + expect(byteLength).toBeGreaterThanOrEqual(readObject.mock.calls[index]![1]), + ) + expect(held.size).toBe(0) + + readObject.mockClear() + await expect( + createPublicShareStateReader({ readObject, reserve: () => null, now: () => start })(shareId), + ).resolves.toEqual({ status: "unavailable" }) + expect(readObject).not.toHaveBeenCalled() + }) + + it("treats a storage read that throws as temporarily unavailable", async () => { + const readShare = createPublicShareStateReader({ + readObject: () => Promise.reject(new Error("Storage timed out.")), + }) + + await expect(readShare(randomUUID())).resolves.toEqual({ status: "unavailable" }) + }) +}) diff --git a/hub/server/domains/public-share-export/create-public-share-state-reader/index.ts b/hub/server/domains/public-share-export/create-public-share-state-reader/index.ts new file mode 100644 index 000000000..2ddfe6de7 --- /dev/null +++ b/hub/server/domains/public-share-export/create-public-share-state-reader/index.ts @@ -0,0 +1,158 @@ +import type { z } from "zod" + +import { publicShareStorageKey } from "../public-share-storage-key/index.ts" +import { + maximumPublicShareManifestBytes, + maximumPublicSharePolicyBytes, + publicShareManifestSchema, + publicSharePolicySchema, + type PublicShareManifest, + type PublicShareObjectReader, + type PublicSharePolicy, + type PublicShareState, +} from "../types.ts" + +type Loaded = { status: "ok"; value: T } | { status: "not-found" } | { status: "unavailable" } + +interface StateReaderOptions { + readObject: PublicShareObjectReader + /** How long a replica may keep a policy before reading it again. This bounds revocation delay. */ + policyCacheMilliseconds?: number + /** Shared in-memory allowance for storage reads; a full allowance makes the share unavailable. */ + reserve?: (byteLength: number) => (() => void) | null + now?: () => number +} + +const storageTimeout = 5_000 +const maximumCachedPolicies = 10_000 +// Manifests never change after activation, so a small cache avoids rereading large indexes. +const maximumCachedManifests = 16 +const maximumCachedManifestBytes = 16 * 1024 * 1024 + +/** Reads a share's policy and manifest, caching the policy briefly and the manifest until evicted. */ +export function createPublicShareStateReader({ + readObject, + policyCacheMilliseconds = 5_000, + reserve = () => () => {}, + now = Date.now, +}: StateReaderOptions) { + const policies = new Map() + const manifests = new Map() + let cachedManifestBytes = 0 + const pending = new Map>>() + + async function readJson( + shareId: string, + kind: "manifest" | "policy", + maximumBytes: number, + schema: z.ZodType, + ): Promise> { + const key = publicShareStorageKey(shareId, { kind }) + if (!key) return { status: "not-found" } + // Parsing needs about as much memory again as the bytes, so reserve both. + const release = reserve(maximumBytes * 2) + if (!release) return { status: "unavailable" } + try { + const stored = await readObject(key, maximumBytes, AbortSignal.timeout(storageTimeout)).catch( + () => ({ status: "unavailable" }) as const, + ) + if (stored.status !== "ok") return stored + let parsed: unknown + try { + parsed = JSON.parse(stored.bytes.toString("utf8")) + } catch { + return { status: "unavailable" } + } + const result = schema.safeParse(parsed) + if (!result.success) return { status: "unavailable" } + return { status: "ok", value: { byteLength: stored.bytes.byteLength, value: result.data } } + } finally { + release() + } + } + + // Concurrent requests for one share wait for the same storage read. + function once(key: string, load: () => Promise>): Promise> { + const existing = pending.get(key) as Promise> | undefined + if (existing) return existing + const started = load().finally(() => pending.delete(key)) + pending.set(key, started) + return started + } + + async function readPolicy(shareId: string): Promise> { + const cached = policies.get(shareId) + if (cached && cached.cachedUntil > now()) return { status: "ok", value: cached.policy } + return once(`policy:${shareId}`, async () => { + // Freshness starts before the read, so a slow read cannot extend a revoked policy's life. + const cachedUntil = now() + policyCacheMilliseconds + const loaded = await readJson( + shareId, + "policy", + maximumPublicSharePolicyBytes, + publicSharePolicySchema, + ) + if (loaded.status !== "ok") return loaded + const policy = loaded.value.value + if (policy.shareId !== shareId) return { status: "unavailable" } + policies.delete(shareId) + if (policies.size >= maximumCachedPolicies) policies.delete(policies.keys().next().value!) + policies.set(shareId, { cachedUntil, policy }) + return { status: "ok", value: policy } + }) + } + + async function readManifest(shareId: string): Promise> { + const cached = manifests.get(shareId) + if (cached) { + manifests.delete(shareId) + manifests.set(shareId, cached) + return { status: "ok", value: cached.manifest } + } + return once(`manifest:${shareId}`, async () => { + const loaded = await readJson( + shareId, + "manifest", + maximumPublicShareManifestBytes, + publicShareManifestSchema, + ) + if (loaded.status !== "ok") return loaded + const { byteLength, value: manifest } = loaded.value + if (manifest.shareId !== shareId) return { status: "unavailable" } + while ( + manifests.size && + (manifests.size >= maximumCachedManifests || + cachedManifestBytes + byteLength > maximumCachedManifestBytes) + ) { + const [oldest, entry] = manifests.entries().next().value! + manifests.delete(oldest) + cachedManifestBytes -= entry.byteLength + } + if (byteLength <= maximumCachedManifestBytes) { + manifests.set(shareId, { byteLength, manifest }) + cachedManifestBytes += byteLength + } + return { status: "ok", value: manifest } + }) + } + + function isActive(policy: PublicSharePolicy) { + return policy.state === "active" && Date.parse(policy.expiresAt) > now() + } + + return async function readPublicShare(shareId: string): Promise { + const policy = await readPolicy(shareId) + if (policy.status === "not-found") return { status: "inactive" } + if (policy.status !== "ok") return { status: "unavailable" } + if (!isActive(policy.value)) return { status: "inactive" } + // Hub writes the manifest before activating the policy, so a missing one is a broken export. + const manifest = await readManifest(shareId) + if (manifest.status !== "ok") return { status: "unavailable" } + // The link can be revoked or expire while the manifest loads; this reuses a still-fresh policy. + const current = await readPolicy(shareId) + if (current.status === "not-found") return { status: "inactive" } + if (current.status !== "ok") return { status: "unavailable" } + if (!isActive(current.value)) return { status: "inactive" } + return { status: "active", manifest: manifest.value, policy: current.value } + } +} diff --git a/hub/server/domains/public-share-export/hash-public-share-password/index.test.ts b/hub/server/domains/public-share-export/hash-public-share-password/index.test.ts new file mode 100644 index 000000000..28723b7eb --- /dev/null +++ b/hub/server/domains/public-share-export/hash-public-share-password/index.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest" + +import { verifyPublicSharePassword } from "../verify-public-share-password" +import { hashPublicSharePassword } from "." + +describe("hashPublicSharePassword()", () => { + it("accepts a password of exactly 8 characters, counting each character once", async () => { + const password = "pässwör🙂" + await expect( + verifyPublicSharePassword(password, await hashPublicSharePassword(password)), + ).resolves.toBe(true) + }) + + // The emoji and combining-mark cases have 8 UTF-16 units but fewer than 8 characters; the last + // exceeds the 256-byte maximum. + it.each(["", "seven77", "pässwö🙂", "a\u0308".repeat(4), "a".repeat(257)])( + "refuses the password %j", + async (password) => { + await expect(hashPublicSharePassword(password)).rejects.toThrow("at least 8 characters") + }, + ) +}) diff --git a/hub/server/domains/public-share-export/hash-public-share-password/index.ts b/hub/server/domains/public-share-export/hash-public-share-password/index.ts new file mode 100644 index 000000000..1b09bb622 --- /dev/null +++ b/hub/server/domains/public-share-export/hash-public-share-password/index.ts @@ -0,0 +1,32 @@ +import { randomBytes, scrypt } from "node:crypto" + +import type { PublicSharePassword } from "../types.ts" + +const cost = 16384 +const blockSize = 8 +const parallelization = 1 + +/** Hashes a share password for policy.json. Hub never exports the plaintext. */ +export async function hashPublicSharePassword(password: string): Promise { + if ([...password.normalize("NFC")].length < 8 || Buffer.byteLength(password) > 256) { + throw new Error("A share password must have at least 8 characters and at most 256 bytes.") + } + const salt = randomBytes(16) + const hash = await new Promise((resolve, reject) => + scrypt( + password.normalize("NFC"), + salt, + 32, + { N: cost, r: blockSize, p: parallelization, maxmem: 64 * 1024 * 1024 }, + (error, key) => (error ? reject(error) : resolve(key)), + ), + ) + return { + algorithm: "scrypt", + cost, + blockSize, + parallelization, + salt: salt.toString("base64url"), + hash: hash.toString("base64url"), + } +} diff --git a/hub/server/domains/public-share-export/public-share-storage-key/index.ts b/hub/server/domains/public-share-export/public-share-storage-key/index.ts new file mode 100644 index 000000000..ab14bacfb --- /dev/null +++ b/hub/server/domains/public-share-export/public-share-storage-key/index.ts @@ -0,0 +1,13 @@ +import { publicShareIdPattern, publicShareSha256Pattern } from "../types.ts" + +type PublicShareObject = + { kind: "manifest" } | { kind: "policy" } | { kind: "file"; sha256: string } + +/** Returns the export storage key for one share object, or null for an invalid share or digest. */ +export function publicShareStorageKey(shareId: string, object: PublicShareObject): string | null { + if (!publicShareIdPattern.test(shareId)) return null + if (object.kind === "manifest") return `shares/${shareId}/manifest.json` + if (object.kind === "policy") return `shares/${shareId}/policy.json` + if (!publicShareSha256Pattern.test(object.sha256)) return null + return `shares/${shareId}/files/${object.sha256}` +} diff --git a/hub/server/domains/public-share-export/read-public-share-reader-settings/index.test.ts b/hub/server/domains/public-share-export/read-public-share-reader-settings/index.test.ts new file mode 100644 index 000000000..f10f9c16c --- /dev/null +++ b/hub/server/domains/public-share-export/read-public-share-reader-settings/index.test.ts @@ -0,0 +1,162 @@ +import { readFileSync } from "node:fs" + +import { describe, expect, it } from "vitest" + +import { readPublicShareReaderSettings } from "." + +const environment = { + PUBLIC_SHARE_GENERATED_ORIGIN: "https://reader.example.azurecontainerapps.io", + PUBLIC_SHARE_TRUSTED_PROXY_HOPS: "1", + PUBLIC_SHARE_STORAGE_PROVIDER: "filesystem", + PUBLIC_SHARE_STORAGE_DIRECTORY: "/srv/public-shares", +} + +describe("readPublicShareReaderSettings()", () => { + it("reads the reader's own settings", () => { + expect(readPublicShareReaderSettings(environment)).toEqual({ + origins: ["https://reader.example.azurecontainerapps.io"], + trustedProxyHops: 1, + storage: { provider: "filesystem", directory: "/srv/public-shares" }, + }) + }) + + it("reads Azure export storage with an optional managed identity", () => { + const azure = { + PUBLIC_SHARE_GENERATED_ORIGIN: environment.PUBLIC_SHARE_GENERATED_ORIGIN, + PUBLIC_SHARE_TRUSTED_PROXY_HOPS: "10", + PUBLIC_SHARE_STORAGE_PROVIDER: "azure", + PUBLIC_SHARE_STORAGE_ACCOUNT: "replicashares01", + PUBLIC_SHARE_STORAGE_CONTAINER: "public-share-exports", + } + expect(readPublicShareReaderSettings(azure)).toEqual({ + origins: [environment.PUBLIC_SHARE_GENERATED_ORIGIN], + trustedProxyHops: 10, + storage: { + provider: "azure", + accountUrl: "https://replicashares01.blob.core.windows.net", + container: "public-share-exports", + }, + }) + const clientId = "0b7a3c1e-5f2d-4a8b-9c6e-1d2f3a4b5c6d" + expect( + readPublicShareReaderSettings({ ...azure, AZURE_CLIENT_ID: clientId }).storage, + ).toMatchObject({ managedIdentityClientId: clientId }) + }) + + const azureStorage = { + PUBLIC_SHARE_STORAGE_PROVIDER: "azure", + PUBLIC_SHARE_STORAGE_ACCOUNT: "replicashares01", + PUBLIC_SHARE_STORAGE_CONTAINER: "public-share-exports", + PUBLIC_SHARE_STORAGE_DIRECTORY: undefined, + } + it.each([ + ["no proxy hops", { PUBLIC_SHARE_TRUSTED_PROXY_HOPS: "0" }, "PUBLIC_SHARE_TRUSTED_PROXY_HOPS"], + ["11 proxy hops", { PUBLIC_SHARE_TRUSTED_PROXY_HOPS: "11" }, "PUBLIC_SHARE_TRUSTED_PROXY_HOPS"], + ["no provider", { PUBLIC_SHARE_STORAGE_PROVIDER: undefined }, "PUBLIC_SHARE_STORAGE_PROVIDER"], + ["a relative directory", { PUBLIC_SHARE_STORAGE_DIRECTORY: "srv" }, "absolute directory"], + [ + "Azure settings beside a directory", + { PUBLIC_SHARE_STORAGE_ACCOUNT: "replicashares01" }, + "does not accept Azure settings", + ], + [ + "a directory beside Azure storage", + { ...azureStorage, PUBLIC_SHARE_STORAGE_DIRECTORY: "/srv" }, + "does not accept PUBLIC_SHARE_STORAGE_DIRECTORY", + ], + [ + "an invalid account", + { ...azureStorage, PUBLIC_SHARE_STORAGE_ACCOUNT: "Replica.Shares" }, + "PUBLIC_SHARE_STORAGE_ACCOUNT", + ], + [ + "an invalid container", + { ...azureStorage, PUBLIC_SHARE_STORAGE_CONTAINER: "shares--1" }, + "PUBLIC_SHARE_STORAGE_CONTAINER", + ], + [ + "an invalid managed identity", + { ...azureStorage, AZURE_CLIENT_ID: "not-a-uuid" }, + "AZURE_CLIENT_ID", + ], + ])("refuses %s", (_case, change, message) => { + expect(() => readPublicShareReaderSettings({ ...environment, ...change })).toThrow(message) + }) + + it("adds an optional custom origin after the generated one", () => { + expect( + readPublicShareReaderSettings({ + ...environment, + PUBLIC_SHARE_CUSTOM_ORIGIN: "https://share.example.net", + }).origins, + ).toEqual(["https://reader.example.azurecontainerapps.io", "https://share.example.net"]) + expect(() => + readPublicShareReaderSettings({ + ...environment, + PUBLIC_SHARE_CUSTOM_ORIGIN: environment.PUBLIC_SHARE_GENERATED_ORIGIN, + }), + ).toThrow("must differ") + }) + + it.each([ + "HUB_SESSION_SECRET", + "DATABASE_URL", + "TEST_DATABASE_URL", + "ARTIFACT_STORAGE_PROVIDER", + "AZURE_STORAGE_CONNECTION_STRING", + "GITHUB_APP_PRIVATE_KEY_BASE64", + "GITHUB_CLIENT_SECRET", + "ENTRA_OIDC_CLIENT_SECRET", + "REPLICA_COPILOT_TOKEN", + "AZURE_CLIENT_SECRET", + "PUBLIC_SHARE_ORIGIN", + "SOME_API_TOKEN", + "SIGNING_KEY", + "SESSION_KEYS", + ])("refuses to start with the Hub, unknown or credential setting %s", (name) => { + expect(() => readPublicShareReaderSettings({ ...environment, [name]: "" })).toThrow(name) + }) + + it("starts beside system settings and the variables Azure sets for managed identities", () => { + const system = { + PATH: "/usr/local/bin:/usr/bin", + HOME: "/home/node", + NODE_VERSION: "24.11.0", + CONTAINER_APP_NAME: "replica-share-reader", + KUBERNETES_SERVICE_HOST: "10.0.0.1", + IDENTITY_ENDPOINT: "http://localhost:42356/msi/token", + IDENTITY_HEADER: "identity-header", + MSI_ENDPOINT: "http://localhost:42356/msi/token", + MSI_SECRET: "identity-secret", + PORT: "8080", + HOST: "0.0.0.0", + } + + expect(readPublicShareReaderSettings({ ...environment, ...system })).toEqual( + readPublicShareReaderSettings(environment), + ) + }) + + it.each([ + "http://share.example.net", + "https://share.example.net/", + "https://share.example.net/s", + "share.example.net", + "", + ])("refuses the origin %j", (origin) => { + for (const name of ["PUBLIC_SHARE_GENERATED_ORIGIN", "PUBLIC_SHARE_CUSTOM_ORIGIN"]) { + expect(() => readPublicShareReaderSettings({ ...environment, [name]: origin })).toThrow(name) + } + }) + + it("starts with the settings the Hub image sets for every process", () => { + const dockerfile = readFileSync(new URL("../../../../Dockerfile", import.meta.url), "utf8") + const image = Object.fromEntries( + [...dockerfile.replaceAll("\\\n", " ").matchAll(/^ENV (.+)$/gm)].flatMap(([, line]) => + [...line!.matchAll(/([A-Z_][A-Z0-9_]*)=(\S*)/g)].map(([, name, value]) => [name!, value!]), + ), + ) + expect(Object.keys(image)).toContain("REPLICA_LEARNING_CLI") + expect(() => readPublicShareReaderSettings({ ...image, ...environment })).not.toThrow() + }) +}) diff --git a/hub/server/domains/public-share-export/read-public-share-reader-settings/index.ts b/hub/server/domains/public-share-export/read-public-share-reader-settings/index.ts new file mode 100644 index 000000000..c6f9d286b --- /dev/null +++ b/hub/server/domains/public-share-export/read-public-share-reader-settings/index.ts @@ -0,0 +1,125 @@ +import { z } from "zod" + +type Environment = Readonly> + +export type PublicShareReaderSettings = { + /** The generated origin first, then the optional custom domain's origin. */ + origins: string[] + trustedProxyHops: number + storage: + | { provider: "filesystem"; directory: string } + | { + provider: "azure" + accountUrl: string + container: string + managedIdentityClientId?: string + } +} + +// The reader's own settings, identity variables Azure sets for managed identities, and the Hub +// image's fixed settings. +const permittedSettings = new Set([ + "PUBLIC_SHARE_GENERATED_ORIGIN", + "PUBLIC_SHARE_CUSTOM_ORIGIN", + "PUBLIC_SHARE_TRUSTED_PROXY_HOPS", + "PUBLIC_SHARE_STORAGE_PROVIDER", + "PUBLIC_SHARE_STORAGE_DIRECTORY", + "PUBLIC_SHARE_STORAGE_ACCOUNT", + "PUBLIC_SHARE_STORAGE_CONTAINER", + "AZURE_CLIENT_ID", + "IDENTITY_ENDPOINT", + "IDENTITY_HEADER", + "MSI_ENDPOINT", + "MSI_SECRET", + "PORT", + "HOST", + // Set by the Hub image the reader runs from; it is a file path, not a credential. + "REPLICA_LEARNING_CLI", +]) +// The reader must never hold Hub settings, credentials or private storage coordinates. Any other +// setting in a Replica, Hub, provider or Azure family, or named like a credential, stops startup, +// so a new Hub secret is refused without updating a list. Unrelated system settings are ignored. +const forbiddenSetting = + /^(?:PUBLIC_SHARE_|HUB_|REPLICA_|GITHUB_|ENTRA_|COPILOT_|AZURE_|ARTIFACT_STORAGE_|PRIVATE_PREVIEW_|DATABASE_|TEST_DATABASE_|LOCAL_|DOTENV_)|(?:^|_)(?:SECRETS?|TOKENS?|PASSWORDS?|PASSPHRASE|KEYS?|SALT|CONNECTION_STRING|CREDENTIALS?)(?:_|$)/ + +function readOrigin(name: string, value = "") { + const parsed = URL.canParse(value) ? new URL(value) : null + if (!parsed || parsed.protocol !== "https:" || parsed.origin !== value) { + throw new Error(`${name} must be an exact HTTPS origin, such as https://share.example.net.`) + } + return value +} + +/** Reads the public reader's own settings and refuses to start beside any Hub setting. */ +export function readPublicShareReaderSettings(environment: Environment): PublicShareReaderSettings { + const forbidden = Object.keys(environment) + .filter( + (name) => + environment[name] !== undefined && + !permittedSettings.has(name) && + forbiddenSetting.test(name), + ) + .sort() + if (forbidden.length) { + throw new Error( + `The public share reader accepts only its own settings; remove ${forbidden.join(", ")}.`, + ) + } + + // Links keep working on the generated hostname after a custom domain is added. + const origins = [ + readOrigin("PUBLIC_SHARE_GENERATED_ORIGIN", environment.PUBLIC_SHARE_GENERATED_ORIGIN), + ] + if (environment.PUBLIC_SHARE_CUSTOM_ORIGIN !== undefined) { + const custom = readOrigin("PUBLIC_SHARE_CUSTOM_ORIGIN", environment.PUBLIC_SHARE_CUSTOM_ORIGIN) + if (custom === origins[0]) { + throw new Error("PUBLIC_SHARE_CUSTOM_ORIGIN must differ from PUBLIC_SHARE_GENERATED_ORIGIN.") + } + origins.push(custom) + } + + const trustedProxyHops = Number(environment.PUBLIC_SHARE_TRUSTED_PROXY_HOPS) + if (!Number.isInteger(trustedProxyHops) || trustedProxyHops < 1 || trustedProxyHops > 10) { + throw new Error("PUBLIC_SHARE_TRUSTED_PROXY_HOPS must be an integer between 1 and 10.") + } + + const provider = environment.PUBLIC_SHARE_STORAGE_PROVIDER + const directory = environment.PUBLIC_SHARE_STORAGE_DIRECTORY + const account = environment.PUBLIC_SHARE_STORAGE_ACCOUNT + const container = environment.PUBLIC_SHARE_STORAGE_CONTAINER + const clientId = environment.AZURE_CLIENT_ID + if (provider === "filesystem") { + if (account !== undefined || container !== undefined || clientId !== undefined) { + throw new Error("Filesystem public share storage does not accept Azure settings.") + } + if (!directory?.startsWith("/") || directory.split("/").some((part) => part === "..")) { + throw new Error("PUBLIC_SHARE_STORAGE_DIRECTORY must be an absolute directory.") + } + return { origins, trustedProxyHops, storage: { provider, directory } } + } + if (provider === "azure") { + if (directory !== undefined) { + throw new Error("Azure public share storage does not accept PUBLIC_SHARE_STORAGE_DIRECTORY.") + } + if (!account || !/^[a-z0-9]{3,24}$/.test(account)) { + throw new Error("PUBLIC_SHARE_STORAGE_ACCOUNT must be a storage account name.") + } + if (!container || !/^(?!.*--)[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(container)) { + throw new Error("PUBLIC_SHARE_STORAGE_CONTAINER must be a blob container name.") + } + if (clientId !== undefined && !z.uuid().safeParse(clientId).success) { + throw new Error("AZURE_CLIENT_ID must be a managed identity client ID.") + } + return { + origins, + trustedProxyHops, + storage: { + provider, + accountUrl: `https://${account}.blob.core.windows.net`, + container, + ...(clientId ? { managedIdentityClientId: clientId } : {}), + }, + } + } + throw new Error("PUBLIC_SHARE_STORAGE_PROVIDER must be azure or filesystem.") +} diff --git a/hub/server/domains/public-share-export/resolve-public-share-file/index.ts b/hub/server/domains/public-share-export/resolve-public-share-file/index.ts new file mode 100644 index 000000000..b50825f1b --- /dev/null +++ b/hub/server/domains/public-share-export/resolve-public-share-file/index.ts @@ -0,0 +1,41 @@ +import type { PublicShareManifest } from "../types.ts" + +interface PublicShareFile { + path: string + sha256: string + size: number +} + +/** + * Finds the exported file for a decoded path below the share's mount. Directory paths use their + * index.html. A document navigation to a missing extensionless route falls back to the export's + * index.html; a missing asset does not. + */ +export function resolvePublicShareFile( + manifest: Pick, + relativePath: string, + documentNavigation: boolean, +): PublicShareFile | null { + const directory = relativePath === "" || relativePath.endsWith("/") + const path = directory ? `${relativePath}index.html` : relativePath + if ( + path.includes("\\") || + path + .split("/") + .some( + (segment) => + segment === "" || segment === "." || segment === ".." || /[\p{Cc}\p{Cs}]/u.test(segment), + ) + ) + return null + const extensionless = !relativePath.replace(/\/$/, "").split("/").at(-1)?.includes(".") + const candidates = [path] + if (!directory && extensionless) candidates.push(`${path}/index.html`) + if (documentNavigation && extensionless) candidates.push("index.html") + for (const candidate of candidates) { + if (Object.hasOwn(manifest.files, candidate)) { + return { path: candidate, ...manifest.files[candidate]! } + } + } + return null +} diff --git a/hub/server/domains/public-share-export/types.test.ts b/hub/server/domains/public-share-export/types.test.ts new file mode 100644 index 000000000..317356d77 --- /dev/null +++ b/hub/server/domains/public-share-export/types.test.ts @@ -0,0 +1,48 @@ +import { randomUUID } from "node:crypto" +import { describe, expect, it } from "vitest" + +import { maximumDistFiles } from "../build-artifacts/constants" +import { publicShareManifestSchema } from "./types" + +function manifest(changes: { mount?: string; entry?: string; fileCount?: number } = {}) { + const file = { sha256: "a".repeat(64), size: 1 } + return { + version: 1, + shareId: randomUUID(), + mount: changes.mount ?? "/previews/github/901/1201/", + entry: changes.entry ?? "/", + files: Object.fromEntries( + Array.from({ length: changes.fileCount ?? 1 }, (_, index) => [ + index ? `assets/chunk-${index}.js` : "index.html", + file, + ]), + ), + } +} + +describe("publicShareManifestSchema", () => { + it("accepts as many files as a Build may contain and refuses more", () => { + expect( + publicShareManifestSchema.safeParse(manifest({ fileCount: maximumDistFiles })).success, + ).toBe(true) + expect( + publicShareManifestSchema.safeParse(manifest({ fileCount: maximumDistFiles + 1 })).success, + ).toBe(false) + }) + + it.each([ + "/previews/github/901/1201", + "/previews/github/0901/1201/", + "/previews/github/901/1201/extra/", + "/s/", + ])("refuses the mount %j, which is not one Build's private prototype path", (mount) => { + expect(publicShareManifestSchema.safeParse(manifest({ mount })).success).toBe(false) + }) + + it.each(["/%2e%2e/x", "//evil", "welcome"])( + "refuses the entry %j, which Hub would not keep as a start page", + (entry) => { + expect(publicShareManifestSchema.safeParse(manifest({ entry })).success).toBe(false) + }, + ) +}) diff --git a/hub/server/domains/public-share-export/types.ts b/hub/server/domains/public-share-export/types.ts new file mode 100644 index 000000000..5be3eb862 --- /dev/null +++ b/hub/server/domains/public-share-export/types.ts @@ -0,0 +1,121 @@ +import { z } from "zod" + +import { normalizeStartPage } from "../../utils/normalize-start-page/index.ts" +import { privatePreviewAddress } from "../../utils/private-preview-address/index.ts" + +/** Largest served file, matching the largest file a Build may contain. */ +export const maximumPublicShareFileBytes = 100 * 1024 * 1024 +// Matches a Build's dist limits: at most 2,000 files with package paths of up to 2,048 bytes. +export const maximumPublicShareFiles = 2_000 +const maximumPublicSharePathBytes = 2_048 +// Each entry needs at most twice its path (JSON escapes quotes) plus about 100 bytes of digest, +// size and punctuation. +export const maximumPublicShareManifestBytes = + maximumPublicShareFiles * (2 * maximumPublicSharePathBytes + 128) + 4 * 1024 +export const maximumPublicSharePolicyBytes = 4 * 1024 +export const maximumPublicShareCookieLifetime = 30 * 24 * 60 * 60 * 1000 +export const publicShareCookiePrefix = "__Secure-replica-share-" +export const openPublicShareProof = "open" + +// Hub creates share IDs with randomUUID(), which returns lowercase version 4 UUIDs. +export const publicShareIdPattern = + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ +export const publicShareSha256Pattern = /^[0-9a-f]{64}$/ + +function base64url(minimumBytes: number, maximumBytes: number) { + return z + .string() + .regex(/^[A-Za-z0-9_-]+$/) + .refine((value) => { + const length = Buffer.from(value, "base64url").byteLength + return length >= minimumBytes && length <= maximumBytes + }) +} + +// Only Builds the private prototype service can serve are exported, so a mount is always that +// service's path for one Build, such as /previews/github/1/2/. +const mount = z.string().refine((value) => { + const [, repositoryId = "", runId = ""] = + /^\/previews\/github\/([^/]+)\/([^/]+)\/$/.exec(value) ?? [] + return privatePreviewAddress(repositoryId, runId)?.mount === value +}) + +// The entry is a start page inside the mount, accepted exactly as Hub normalizes start pages. +const entry = z + .string() + .refine((value) => value.startsWith("/") && normalizeStartPage(value) === value) + +// Paths are relative to the Build's dist directory, such as index.html or assets/app.js. +const filePath = z + .string() + .refine( + (value) => + Buffer.byteLength(value) <= maximumPublicSharePathBytes && + !value.includes("\\") && + value + .split("/") + .every( + (segment) => + segment !== "" && + segment !== "." && + segment !== ".." && + !/[\p{Cc}\p{Cs}]/u.test(segment), + ), + ) + +export const publicShareManifestSchema = z + .strictObject({ + version: z.literal(1), + shareId: z.string().regex(publicShareIdPattern), + mount, + entry, + files: z.record( + filePath, + z.strictObject({ + sha256: z.string().regex(publicShareSha256Pattern), + size: z.number().int().min(0).max(maximumPublicShareFileBytes), + }), + ), + }) + .refine( + ({ files }) => + Object.keys(files).length <= maximumPublicShareFiles && Object.hasOwn(files, "index.html"), + { message: "A manifest lists at most 2,000 files and includes index.html." }, + ) + +export const publicSharePasswordSchema = z.strictObject({ + algorithm: z.literal("scrypt"), + // Bounded so one verification uses at most 32 MiB of memory. + cost: z.union([z.literal(16384), z.literal(32768)]), + blockSize: z.literal(8), + parallelization: z.literal(1), + salt: base64url(16, 64), + hash: base64url(32, 32), +}) + +export const publicSharePolicySchema = z.strictObject({ + version: z.literal(1), + shareId: z.string().regex(publicShareIdPattern), + state: z.enum(["active", "revoked"]), + expiresAt: z.iso.datetime(), + password: publicSharePasswordSchema.nullable(), +}) + +export type PublicShareManifest = z.infer +export type PublicSharePolicy = z.infer +export type PublicSharePassword = z.infer + +export type PublicShareObjectReadResult = + { status: "ok"; bytes: Buffer } | { status: "not-found" } | { status: "unavailable" } + +/** Reads one export object by exact key. Objects larger than maximumBytes are unavailable. */ +export type PublicShareObjectReader = ( + key: string, + maximumBytes: number, + signal: AbortSignal, +) => Promise + +export type PublicShareState = + | { status: "active"; manifest: PublicShareManifest; policy: PublicSharePolicy } + | { status: "inactive" } + | { status: "unavailable" } diff --git a/hub/server/domains/public-share-export/verify-public-share-password/index.ts b/hub/server/domains/public-share-export/verify-public-share-password/index.ts new file mode 100644 index 000000000..35091d011 --- /dev/null +++ b/hub/server/domains/public-share-export/verify-public-share-password/index.ts @@ -0,0 +1,27 @@ +import { scrypt, timingSafeEqual } from "node:crypto" + +import type { PublicSharePassword } from "../types.ts" + +/** Checks a submitted password against the hash in a share's policy. */ +export async function verifyPublicSharePassword( + password: string, + stored: PublicSharePassword, +): Promise { + if (!password || Buffer.byteLength(password) > 256) return false + const expected = Buffer.from(stored.hash, "base64url") + const actual = await new Promise((resolve, reject) => + scrypt( + password.normalize("NFC"), + Buffer.from(stored.salt, "base64url"), + expected.byteLength, + { + N: stored.cost, + r: stored.blockSize, + p: stored.parallelization, + maxmem: 64 * 1024 * 1024, + }, + (error, key) => (error ? reject(error) : resolve(key)), + ), + ) + return timingSafeEqual(actual, expected) +} diff --git a/hub/server/integrations/azure-blob/create-public-share-object-reader/index.test.ts b/hub/server/integrations/azure-blob/create-public-share-object-reader/index.test.ts new file mode 100644 index 000000000..a6e804ceb --- /dev/null +++ b/hub/server/integrations/azure-blob/create-public-share-object-reader/index.test.ts @@ -0,0 +1,53 @@ +import { Readable } from "node:stream" +import { describe, expect, it, vi } from "vitest" + +import { createPublicShareBlobObjectReader } from "." + +const { download } = vi.hoisted(() => ({ download: vi.fn() })) +vi.mock("@azure/storage-blob", () => ({ + BlobServiceClient: class { + getContainerClient() { + return { getBlockBlobClient: () => ({ download }) } + } + }, +})) + +const settings = { accountUrl: "https://example.blob.core.windows.net", container: "shares" } + +describe("createPublicShareBlobObjectReader()", () => { + it.each([ + ["BlobNotFound", "not-found"], + ["AuthorizationPermissionMismatch", "unavailable"], + ])("returns %s as %s", async (errorCode, status) => { + download.mockRejectedValueOnce({ statusCode: 404, details: { errorCode } }) + const read = createPublicShareBlobObjectReader(settings) + + await expect(read("shares/key", 12, AbortSignal.timeout(1000))).resolves.toEqual({ status }) + }) + + it("reads a blob up to the maximum size and refuses a larger or overlong one", async () => { + const read = createPublicShareBlobObjectReader(settings) + download.mockResolvedValueOnce({ + contentLength: 5, + readableStreamBody: Readable.from([Buffer.from("he"), Buffer.from("llo")]), + }) + const larger = Readable.from([Buffer.from("hello!")]) + download.mockResolvedValueOnce({ contentLength: 6, readableStreamBody: larger }) + download.mockResolvedValueOnce({ + contentLength: 5, + readableStreamBody: Readable.from([Buffer.from("hello"), Buffer.from("!")]), + }) + + await expect(read("shares/key", 5, AbortSignal.timeout(1000))).resolves.toEqual({ + status: "ok", + bytes: Buffer.from("hello"), + }) + await expect(read("shares/key", 5, AbortSignal.timeout(1000))).resolves.toEqual({ + status: "unavailable", + }) + expect(larger.destroyed).toBe(true) + await expect(read("shares/key", 5, AbortSignal.timeout(1000))).resolves.toEqual({ + status: "unavailable", + }) + }) +}) diff --git a/hub/server/integrations/azure-blob/create-public-share-object-reader/index.ts b/hub/server/integrations/azure-blob/create-public-share-object-reader/index.ts new file mode 100644 index 000000000..d2ef1c315 --- /dev/null +++ b/hub/server/integrations/azure-blob/create-public-share-object-reader/index.ts @@ -0,0 +1,48 @@ +import { ManagedIdentityCredential } from "@azure/identity" +import { BlobServiceClient } from "@azure/storage-blob" + +type ReadResult = + { status: "ok"; bytes: Buffer } | { status: "not-found" } | { status: "unavailable" } + +/** Reads public export objects by exact name with the reader's read-only managed identity. */ +export function createPublicShareBlobObjectReader(settings: { + accountUrl: string + container: string + managedIdentityClientId?: string +}) { + const identity = settings.managedIdentityClientId + ? new ManagedIdentityCredential({ clientId: settings.managedIdentityClientId }) + : new ManagedIdentityCredential() + const container = new BlobServiceClient(settings.accountUrl, identity).getContainerClient( + settings.container, + ) + return async (key: string, maximumBytes: number, signal: AbortSignal): Promise => { + try { + const response = await container + .getBlockBlobClient(key) + .download(0, undefined, { abortSignal: signal }) + const stream = response.readableStreamBody + if (!stream) return { status: "unavailable" } + try { + const length = response.contentLength + if (length === undefined || length > maximumBytes) return { status: "unavailable" } + const bytes = Buffer.alloc(length) + let offset = 0 + for await (const chunk of stream) { + signal.throwIfAborted() + const part = Buffer.from(chunk as Uint8Array) + if (offset + part.byteLength > length) return { status: "unavailable" } + part.copy(bytes, offset) + offset += part.byteLength + } + if (offset !== length) return { status: "unavailable" } + return { status: "ok", bytes } + } finally { + stream.destroy() + } + } catch (error) { + const code = (error as { details?: { errorCode?: string } } | null)?.details?.errorCode + return code === "BlobNotFound" ? { status: "not-found" } : { status: "unavailable" } + } + } +} diff --git a/hub/server/integrations/express/send-public-share-page/index.ts b/hub/server/integrations/express/send-public-share-page/index.ts new file mode 100644 index 000000000..b03fe0db6 --- /dev/null +++ b/hub/server/integrations/express/send-public-share-page/index.ts @@ -0,0 +1,56 @@ +import type { Response } from "express" + +const pageStyle = + "body{margin:0;min-height:100vh;display:grid;place-items:center;font:16px/1.5 system-ui,sans-serif;color:#1f2328;background:#f6f8fa}" + + "main{max-width:24rem;padding:2rem;background:#fff;border:1px solid #d1d9e0;border-radius:12px}" + + "h1{margin:0 0 .5rem;font-size:1.25rem}p{margin:0 0 1rem}label{display:block;font-weight:600}" + + "input{box-sizing:border-box;width:100%;margin:.25rem 0 1rem;padding:.5rem;font:inherit}" + + "button{padding:.5rem 1rem;font:inherit}[role=alert]{color:#d1242f}" + + "@media (prefers-color-scheme:dark){body{color:#f0f6fc;background:#0d1117}main{background:#151b23;border-color:#3d444d}[role=alert]{color:#ff7b72}}" +const pagePolicy = [ + "default-src 'none'", + "style-src 'unsafe-inline'", + "form-action 'self'", + "frame-ancestors 'none'", + "base-uri 'none'", +].join("; ") + +type Page = + | { kind: "unavailable" } + | { kind: "password"; action: string; error?: "incorrect" | "throttled" | "busy" } + +/** Sends one of the public reader's own pages. None of them include share or Hub details. */ +export function sendPublicSharePage(response: Response, status: number, page: Page) { + let content: string + if (page.kind === "unavailable") { + content = + "

This shared prototype isn't available

" + + "

The link may have expired or been turned off. Ask the person who shared it for a new link.

" + } else { + const message = + page.error === "incorrect" + ? '

That password isn\'t correct.

' + : page.error === "throttled" + ? '

Too many attempts. Wait 10 minutes and try again, or ask the person who shared it for the password.

' + : page.error === "busy" + ? '

This page is busy. Try again in a moment.

' + : "" + content = + "

Enter the password

This shared prototype is password protected.

" + + message + + `
` + + '' + + '' + + '
' + } + response.setHeader("Content-Security-Policy", pagePolicy) + // Browsers send Origin: null for a form posted under no-referrer, which fails the origin check. + if (page.kind === "password") response.setHeader("Referrer-Policy", "same-origin") + response.setHeader("Cache-Control", "no-store") + return response + .status(status) + .type("html") + .send( + `Shared prototype
${content}
`, + ) +} diff --git a/hub/server/integrations/filesystem/create-public-share-object-reader/index.ts b/hub/server/integrations/filesystem/create-public-share-object-reader/index.ts new file mode 100644 index 000000000..370f6f866 --- /dev/null +++ b/hub/server/integrations/filesystem/create-public-share-object-reader/index.ts @@ -0,0 +1,47 @@ +import { constants } from "node:fs" +import { open, realpath } from "node:fs/promises" +import { dirname, join } from "node:path" + +type ReadResult = + { status: "ok"; bytes: Buffer } | { status: "not-found" } | { status: "unavailable" } + +const keyPattern = + /^shares\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/(?:manifest\.json|policy\.json|files\/[0-9a-f]{64})$/ + +/** + * Reads public export objects from a local directory, for development and tests. The directory + * must be trusted; the reader refuses symbolic links inside it but does not pin its ancestors. + */ +export function createPublicShareFileObjectReader(directory: string) { + return async (key: string, maximumBytes: number, signal: AbortSignal): Promise => { + if (!keyPattern.test(key)) return { status: "unavailable" } + try { + signal.throwIfAborted() + const root = await realpath(directory) + const parent = join(root, dirname(key)) + if ((await realpath(parent)) !== parent) return { status: "unavailable" } + const handle = await open( + join(parent, key.slice(key.lastIndexOf("/") + 1)), + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ) + try { + const stat = await handle.stat() + if (!stat.isFile() || stat.size > maximumBytes) return { status: "unavailable" } + const bytes = Buffer.alloc(stat.size) + let offset = 0 + while (offset < bytes.byteLength) { + signal.throwIfAborted() + const { bytesRead } = await handle.read(bytes, offset, bytes.byteLength - offset, offset) + if (!bytesRead) return { status: "unavailable" } + offset += bytesRead + } + return { status: "ok", bytes } + } finally { + await handle.close() + } + } catch (error) { + const code = error instanceof Error && "code" in error ? error.code : null + return code === "ENOENT" ? { status: "not-found" } : { status: "unavailable" } + } + } +} diff --git a/hub/server/routes/public-share-reader/index.test.ts b/hub/server/routes/public-share-reader/index.test.ts new file mode 100644 index 000000000..929056abe --- /dev/null +++ b/hub/server/routes/public-share-reader/index.test.ts @@ -0,0 +1,992 @@ +import { createHash, randomUUID } from "node:crypto" +import { once } from "node:events" +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises" +import { + createServer, + request as httpRequest, + type IncomingHttpHeaders, + type IncomingMessage, +} from "node:http" +import type { AddressInfo } from "node:net" +import { join } from "node:path" +import { fileURLToPath } from "node:url" +import { describe, expect, it, onTestFinished, vi } from "vitest" + +import { hashPublicSharePassword } from "../../domains/public-share-export/hash-public-share-password" +import type { + PublicShareObjectReader, + PublicSharePassword, +} from "../../domains/public-share-export/types" +import type { verifyPublicSharePassword } from "../../domains/public-share-export/verify-public-share-password" +import { createPublicShareFileObjectReader } from "../../integrations/filesystem/create-public-share-object-reader" +import { createPublicShareReader } from "." + +const passwordCheck = vi.hoisted(() => ({ after: null as (() => Promise) | null })) +vi.mock( + "../../domains/public-share-export/verify-public-share-password", + async (importOriginal) => { + const actual = await importOriginal<{ + verifyPublicSharePassword: typeof verifyPublicSharePassword + }>() + return { + verifyPublicSharePassword: async ( + ...input: Parameters + ) => { + const correct = await actual.verifyPublicSharePassword(...input) + await passwordCheck.after?.() + return correct + }, + } + }, +) + +const origin = "https://reader.example.azurecontainerapps.io" +const customOrigin = "https://share.example.net" +const mount = "/previews/github/901/1201/" +const storageParent = fileURLToPath(new URL("../../../.local/test-public-shares/", import.meta.url)) +const hour = 60 * 60 * 1000 + +type WritePolicy = Awaited< + ReturnType>["writeShare"]> +>["writePolicy"] + +function digest(value: Buffer) { + return createHash("sha256").update(value).digest("hex") +} + +function cookiePair(header: string) { + return header.split(";")[0]! +} + +// Opening sends a clearing cookie before each new one; this returns the first new one. +function openedCookie(headers: IncomingHttpHeaders) { + return cookiePair(headers["set-cookie"]!.find((header) => /;\s*Max-Age=/i.test(header))!) +} + +function documentHeaders(cookie: string) { + return { cookie, "sec-fetch-dest": "document", "sec-fetch-mode": "navigate" } +} + +function assetHeaders(cookie: string) { + return { cookie, "sec-fetch-dest": "script", "sec-fetch-mode": "no-cors" } +} + +function passwordHeaders(headers: Record = {}) { + return { origin, "content-type": "application/x-www-form-urlencoded", ...headers } +} + +async function startReader( + options: { + policyCacheMilliseconds?: number + responseIdleMilliseconds?: number + now?: () => number + wrapRead?: (read: PublicShareObjectReader) => PublicShareObjectReader + } = {}, +) { + await mkdir(storageParent, { recursive: true }) + const directory = await mkdtemp(join(storageParent, "reader-")) + onTestFinished(() => rm(directory, { recursive: true, force: true })) + const fileReader = createPublicShareFileObjectReader(directory) + const readObject = vi.fn(options.wrapRead ? options.wrapRead(fileReader) : fileReader) + const app = createPublicShareReader({ + origins: [origin, customOrigin], + trustedProxyHops: 1, + readObject, + policyCacheMilliseconds: options.policyCacheMilliseconds, + responseIdleMilliseconds: options.responseIdleMilliseconds, + now: options.now, + }) + const server = createServer(app).listen(0, "127.0.0.1") + await once(server, "listening") + onTestFinished(() => new Promise((resolve) => server.close(() => resolve()))) + const { port } = server.address() as AddressInfo + const clock = options.now ?? Date.now + + function request( + path: string, + options: { + method?: string + headers?: Record + body?: string + signal?: AbortSignal + } = {}, + ) { + return new Promise<{ status: number; headers: IncomingHttpHeaders; body: Buffer }>( + (resolve, reject) => { + const outgoing = httpRequest( + { + host: "127.0.0.1", + port, + path, + method: options.method, + signal: options.signal, + headers: { + host: new URL(origin).host, + "x-forwarded-proto": "https", + ...options.headers, + }, + }, + (response) => { + const chunks: Buffer[] = [] + response.on("data", (chunk: Buffer) => chunks.push(chunk)) + response.on("error", reject) + response.on("end", () => + resolve({ + status: response.statusCode!, + headers: response.headers, + body: Buffer.concat(chunks), + }), + ) + }, + ) + outgoing.on("error", reject) + outgoing.end(options.body) + }, + ) + } + + // Writes an export in the order Hub does: files, then the manifest, then the activating policy. + async function writeShare( + files: Record, + share: { + mount?: string + entry?: string + password?: PublicSharePassword | null + expiresAt?: number + extraManifestFiles?: Record + } = {}, + ) { + const shareId = randomUUID() + const root = join(directory, "shares", shareId) + await mkdir(join(root, "files"), { recursive: true }) + const manifestFiles: Record = { + ...share.extraManifestFiles, + } + const hashes: Record = {} + for (const [path, content] of Object.entries(files)) { + const bytes = Buffer.from(content) + const sha256 = digest(bytes) + await writeFile(join(root, "files", sha256), bytes) + manifestFiles[path] = { sha256, size: bytes.byteLength } + hashes[path] = sha256 + } + const shareMount = share.mount ?? mount + await writeFile( + join(root, "manifest.json"), + JSON.stringify({ + version: 1, + shareId, + mount: shareMount, + entry: share.entry ?? "/", + files: manifestFiles, + }), + ) + let policy = { + version: 1, + shareId, + state: "active", + expiresAt: new Date(share.expiresAt ?? clock() + hour).toISOString(), + password: share.password ?? null, + } + async function writePolicy(changes: Partial) { + policy = { ...policy, ...changes } + await writeFile(join(root, "policy.json"), JSON.stringify(policy)) + } + await writePolicy({}) + + // Opens the link, submitting the password when one is given. + async function open(password?: string) { + const opened = password + ? await request(`/s/${shareId}`, { + method: "POST", + headers: passwordHeaders(), + body: new URLSearchParams({ password }).toString(), + }) + : await request(`/s/${shareId}`, { headers: { "sec-fetch-dest": "document" } }) + expect(opened.status).toBe(303) + return openedCookie(opened.headers) + } + + return { shareId, mount: shareMount, root, hashes, writePolicy, open } + } + + return { server, request, writeShare, readObject } +} + +describe("createPublicShareReader()", () => { + it("opens a link with share-only cookies and serves its files with strict headers", async () => { + const start = Date.parse("2026-11-29T08:00:00.000Z") + const { request, writeShare } = await startReader({ now: () => start }) + const html = "Shared" + const script = "console.log('shared')" + const { shareId } = await writeShare( + { "index.html": html, "assets/app.js": script }, + { entry: "/welcome%20back/100%25?tab=first#/details", expiresAt: start + hour }, + ) + + const opened = await request(`/s/${shareId}`, { + headers: { "sec-fetch-dest": "document", cookie: "hub_session=signed-in" }, + }) + expect(opened.status).toBe(303) + expect(opened.headers.location).toBe(`${mount}welcome%20back/100%25?tab=first#/details`) + // Each path's cookie is cleared, then set, so a reopened cookie becomes the newest. + const cookies = opened.headers["set-cookie"]! + expect(cookies).toHaveLength(4) + for (const [index, path] of [mount, mount, `/s/${shareId}`, `/s/${shareId}`].entries()) { + const cookie = cookies[index]! + const cleared = index % 2 === 0 + expect(cookie.startsWith(`__Secure-replica-share-${shareId}=${cleared ? "" : "open"};`)).toBe( + true, + ) + expect(cookie).toMatch(new RegExp(`;\\s*Path=${path}(?:;|$)`, "i")) + expect(cookie).toMatch( + cleared ? /;\s*Expires=Thu, 01 Jan 1970 00:00:00 GMT\b/i : /;\s*Max-Age=3600\b/i, + ) + expect(cookie).toMatch(/;\s*HttpOnly\b/i) + expect(cookie).toMatch(/;\s*Secure\b/i) + expect(cookie).toMatch(/;\s*SameSite=Lax\b/i) + expect(cookie).not.toMatch(/;\s*Domain=/i) + } + const cookie = `hub_session=signed-in; ${cookiePair(cookies[1]!)}` + + const page = await request(`${mount}welcome%20back/100%25?tab=first`, { + headers: documentHeaders(cookie), + }) + const asset = await request(`${mount}assets/app.js`, { headers: assetHeaders(cookie) }) + expect(page.status).toBe(200) + expect(page.body.toString()).toBe(html) + expect(page.headers["content-type"]).toBe("text/html; charset=utf-8") + expect(asset.status).toBe(200) + expect(asset.body.toString()).toBe(script) + expect(asset.headers["content-type"]).toBe("text/javascript; charset=utf-8") + for (const response of [opened, page, asset]) { + expect(response.headers["content-security-policy"]).toContain("frame-ancestors 'none'") + expect(response.headers["content-security-policy"]).toContain("default-src 'none'") + expect(response.headers["x-robots-tag"]).toContain("noindex") + expect(response.headers["referrer-policy"]).toBe("no-referrer") + expect(response.headers["x-content-type-options"]).toBe("nosniff") + } + for (const response of [page, asset]) { + expect(response.headers["set-cookie"]).toBeUndefined() + expect(response.headers["cache-control"]).toBe("private, no-cache") + } + }) + + it("falls back to index.html only for extensionless document navigations", async () => { + const { request, writeShare } = await startReader() + const html = "App shell" + const { open } = await writeShare({ "index.html": html, "assets/app.js": "app()" }) + const cookie = await open() + + const navigation = await request(`${mount}projects/42`, { headers: documentHeaders(cookie) }) + const acceptNavigation = await request(`${mount}projects/42`, { + headers: { cookie, accept: "text/html,application/xhtml+xml" }, + }) + const dataFetch = await request(`${mount}projects/42`, { + headers: { cookie, "sec-fetch-dest": "empty", accept: "text/html" }, + }) + const missingAsset = await request(`${mount}assets/missing.js`, { + headers: documentHeaders(cookie), + }) + + expect(navigation.status).toBe(200) + expect(navigation.body.toString()).toBe(html) + expect(acceptNavigation.status).toBe(200) + expect(acceptNavigation.body.toString()).toBe(html) + expect(dataFetch.status).toBe(404) + expect(missingAsset.status).toBe(404) + expect(missingAsset.body.toString()).not.toContain("App shell") + }) + + it("serves a directory's index.html at its slash path and redirects its slashless path", async () => { + const { request, writeShare } = await startReader() + const docs = "Docs" + const { open } = await writeShare({ "index.html": "root", "docs/index.html": docs }) + const cookie = await open() + + const withSlash = await request(`${mount}docs/`, { headers: documentHeaders(cookie) }) + const withoutSlash = await request(`${mount}docs?x=1`, { headers: documentHeaders(cookie) }) + + expect(withSlash.status).toBe(200) + expect(withSlash.body.toString()).toBe(docs) + expect(withoutSlash.status).toBe(302) + expect(withoutSlash.headers.location).toBe(`${mount}docs/?x=1`) + + // An encoded slash is not a literal one for relative URLs, and an absolute-form request + // target must not move the redirect to another host. + for (const [path, location] of [ + [`${mount}docs%2F`, `${mount}docs/`], + [`http://evil.example${mount}docs?x=1`, `${mount}docs/?x=1`], + ] as const) { + const response = await request(path, { headers: documentHeaders(cookie) }) + expect(response.status, path).toBe(302) + expect(response.headers.location, path).toBe(location) + } + }) + + it("adds the slash to a slashless mount root before reading any share", async () => { + const { request, readObject } = await startReader() + const root = mount.slice(0, -1) + + // Browsers send no share cookie here, because each cookie's path ends with the slash. + for (const path of [`${root}?tab=1&x=%2F`, `http://evil.example${root}?tab=1&x=%2F`]) { + const response = await request(path, { headers: { "sec-fetch-dest": "document" } }) + expect(response.status, path).toBe(302) + expect(response.headers.location, path).toBe(`${mount}?tab=1&x=%2F`) + } + expect((await request(root, { method: "HEAD" })).headers.location).toBe(mount) + expect((await request("/previews/github/0901/1201")).status).toBe(404) + expect(readObject).not.toHaveBeenCalled() + }) + + it("serves only files listed in an opened share's manifest", async () => { + const { request, writeShare } = await startReader() + const { shareId, hashes, open } = await writeShare({ + "index.html": "root", + "assets/app.js": "app()", + }) + const sha256 = hashes["assets/app.js"]! + + const unopened = await request(`${mount}assets/app.js`, { headers: assetHeaders("") }) + expect(unopened.status).toBe(404) + + const cookie = await open() + for (const path of [ + `${mount}assets/`, + `${mount}${sha256}`, + `${mount}files/${sha256}`, + `${mount}%2e%2e/%2e%2e/%2e%2e/%2e%2e/shares/${shareId}/manifest.json`, + `/shares/${shareId}/manifest.json`, + `/shares/${shareId}/policy.json`, + `/shares/${shareId}/files/${sha256}`, + ]) { + const response = await request(path, { headers: assetHeaders(cookie) }) + expect(response.status, path).toBe(404) + expect(response.body.toString(), path).not.toContain(shareId) + } + }) + + it("serves a share with 2,000 long file paths and a large asset", async () => { + const { request, writeShare } = await startReader() + const large = Buffer.alloc(8 * 1024 * 1024, "a") + // Paths near the 2,048-byte limit make the manifest about 4 MiB. + const extraManifestFiles = Object.fromEntries( + Array.from({ length: 1_998 }, (_, index) => [ + `assets/${"a".repeat(2_000)}/chunk-${index}.js`, + { sha256: digest(Buffer.from(String(index))), size: 1 }, + ]), + ) + const { open } = await writeShare( + { "index.html": "root", "assets/large.bin": large }, + { extraManifestFiles }, + ) + const cookie = await open() + + const response = await request(`${mount}assets/large.bin`, { headers: assetHeaders(cookie) }) + + expect(response.status).toBe(200) + expect(response.headers["content-length"]).toBe(String(large.byteLength)) + expect(response.body.equals(large)).toBe(true) + }) + + it("holds the file allowance until an abandoned read settles without blocking other links", async () => { + const largeSha = digest(Buffer.from("large")) + let largeRead: { signal: AbortSignal; settle: () => void } | null = null + const { request, writeShare } = await startReader({ + wrapRead: (read) => (key, maximumBytes, signal) => { + if (!key.endsWith(largeSha)) return read(key, maximumBytes, signal) + return new Promise((resolve) => { + largeRead = { signal, settle: () => resolve({ status: "unavailable" }) } + }) + }, + }) + const { open } = await writeShare( + { "index.html": "root", "assets/app.js": "app()" }, + { extraManifestFiles: { "assets/large.bin": { sha256: largeSha, size: 100 * 1024 * 1024 } } }, + ) + const other = await writeShare({ "index.html": "other" }) + const cookie = await open() + const asset = `${mount}assets/app.js` + const client = new AbortController() + + const abandoned = request(`${mount}assets/large.bin`, { + headers: assetHeaders(cookie), + signal: client.signal, + }).catch(() => null) + await vi.waitFor(() => expect(largeRead).not.toBeNull()) + const whileReading = await request(`/s/${other.shareId}`) + client.abort() + await abandoned + await vi.waitFor(() => expect(largeRead!.signal.aborted).toBe(true)) + const afterDisconnect = await request(asset, { headers: assetHeaders(cookie) }) + largeRead!.settle() + await vi.waitFor(async () => + expect((await request(asset, { headers: assetHeaders(cookie) })).status).toBe(200), + ) + + expect(whileReading.status).toBe(303) + expect(afterDisconnect.status).toBe(503) + }) + + it("does not hold the file allowance for a client that leaves while the link loads", async () => { + let heldPolicy: (() => void) | null = null + let holdNextPolicy = false + const { server, request, writeShare } = await startReader({ + policyCacheMilliseconds: 0, + wrapRead: (read) => async (key, maximumBytes, signal) => { + if (!holdNextPolicy || !key.endsWith("policy.json")) return read(key, maximumBytes, signal) + holdNextPolicy = false + await new Promise((resolve) => (heldPolicy = resolve)) + return read(key, maximumBytes, signal) + }, + }) + const { open } = await writeShare( + { "index.html": "root", "assets/app.js": "app()" }, + { + extraManifestFiles: { + "assets/large.bin": { sha256: digest(Buffer.from("large")), size: 100 * 1024 * 1024 }, + }, + }, + ) + const cookie = await open() + let left = false + server.once("request", (_request, response) => response.once("close", () => (left = true))) + const client = new AbortController() + + holdNextPolicy = true + const abandoned = request(`${mount}assets/large.bin`, { + headers: assetHeaders(cookie), + signal: client.signal, + }).catch(() => null) + await vi.waitFor(() => expect(heldPolicy).not.toBeNull()) + client.abort() + await abandoned + await vi.waitFor(() => expect(left).toBe(true)) + heldPolicy!() + + await vi.waitFor(async () => + expect( + (await request(`${mount}assets/app.js`, { headers: assetHeaders(cookie) })).status, + ).toBe(200), + ) + }) + + it("drops a file response that stops making progress and releases its allowance", async () => { + const large = Buffer.alloc(64 * 1024 * 1024, "a") + const largeSha = digest(large) + const { server, request, writeShare } = await startReader({ + responseIdleMilliseconds: 200, + wrapRead: (read) => (key, maximumBytes, signal) => { + if (!key.endsWith(largeSha)) return read(key, maximumBytes, signal) + return Promise.resolve({ status: "ok", bytes: large }) + }, + }) + const { open } = await writeShare( + { "index.html": "root" }, + { extraManifestFiles: { "assets/large.bin": { sha256: largeSha, size: large.byteLength } } }, + ) + const cookie = await open() + const path = `${mount}assets/large.bin` + const client = new AbortController() + onTestFinished(() => client.abort()) + + // The client never reads the body, so the server's writes stall once socket buffers fill. + const stalled = httpRequest({ + host: "127.0.0.1", + port: (server.address() as AddressInfo).port, + path, + signal: client.signal, + headers: { + host: new URL(origin).host, + "x-forwarded-proto": "https", + ...assetHeaders(cookie), + }, + }) + stalled.on("error", () => {}) + stalled.end() + const [stalledResponse] = (await once(stalled, "response")) as [IncomingMessage] + expect(stalledResponse.statusCode).toBe(200) + + await vi.waitFor( + async () => { + const response = await request(path, { headers: assetHeaders(cookie) }) + expect(response.status).toBe(200) + expect(response.body.byteLength).toBe(large.byteLength) + }, + { timeout: 3_000 }, + ) + }) + + it("serves a 100 MiB file whose read outlasts the policy cache", async () => { + let clock = Date.parse("2026-11-29T08:00:00.000Z") + const large = Buffer.alloc(100 * 1024 * 1024, "a") + const largeSha = digest(large) + const { request, writeShare } = await startReader({ + now: () => clock, + wrapRead: (read) => (key, maximumBytes, signal) => { + if (!key.endsWith(largeSha)) return read(key, maximumBytes, signal) + clock += 10_000 + return Promise.resolve({ status: "ok", bytes: large }) + }, + }) + const { open } = await writeShare( + { "index.html": "root" }, + { extraManifestFiles: { "assets/large.bin": { sha256: largeSha, size: large.byteLength } } }, + ) + const cookie = await open() + + const response = await request(`${mount}assets/large.bin`, { headers: assetHeaders(cookie) }) + + expect(response.status).toBe(200) + expect(response.body.byteLength).toBe(large.byteLength) + }) + + it("revalidates and answers HEAD from the manifest without reading the file", async () => { + const { request, writeShare, readObject } = await startReader() + const script = "app()" + const { hashes, open } = await writeShare({ "index.html": "root", "assets/app.js": script }) + const cookie = await open() + const entityTag = `"${hashes["assets/app.js"]}"` + + const head = await request(`${mount}assets/app.js`, { + method: "HEAD", + headers: assetHeaders(cookie), + }) + const revalidated = await request(`${mount}assets/app.js`, { + headers: { ...assetHeaders(cookie), "if-none-match": entityTag }, + }) + + expect(head.status).toBe(200) + expect(head.headers["content-length"]).toBe(String(Buffer.byteLength(script))) + expect(head.headers.etag).toBe(entityTag) + expect(revalidated.status).toBe(304) + expect(revalidated.body.byteLength).toBe(0) + expect(readObject.mock.calls.map(([key]) => key)).not.toContainEqual( + expect.stringContaining("/files/"), + ) + }) + + it("stops GET, HEAD and revalidation as soon as the link is revoked", async () => { + const { request, writeShare } = await startReader({ policyCacheMilliseconds: 0 }) + const { shareId, hashes, writePolicy, open } = await writeShare({ + "index.html": "root", + "assets/app.js": "app()", + }) + const cookie = await open() + const asset = `${mount}assets/app.js` + expect((await request(asset, { headers: assetHeaders(cookie) })).status).toBe(200) + + await writePolicy({ state: "revoked" }) + + const get = await request(asset, { headers: assetHeaders(cookie) }) + const head = await request(asset, { method: "HEAD", headers: assetHeaders(cookie) }) + const revalidated = await request(asset, { + headers: { ...assetHeaders(cookie), "if-none-match": `"${hashes["assets/app.js"]}"` }, + }) + const link = await request(`/s/${shareId}`, { headers: documentHeaders(cookie) }) + expect(get.status).toBe(404) + expect(head.status).toBe(404) + expect(revalidated.status).toBe(404) + expect(link.status).toBe(404) + expect(link.headers["set-cookie"]).toBeUndefined() + expect(link.body.toString()).toContain("This shared prototype isn't available") + }) + + it.each<[string, (share: { root: string; writePolicy: WritePolicy }) => Promise, number]>([ + ["is revoked", ({ writePolicy }) => writePolicy({ state: "revoked" }), 404], + [ + "gets a new password", + async ({ writePolicy }) => + writePolicy({ password: await hashPublicSharePassword("battery staple") }), + 404, + ], + ["can't be read", ({ root }) => writeFile(join(root, "policy.json"), "{"), 503], + ])("does not send a file when the link %s during its read", async (_name, change, status) => { + let afterFileRead: (() => Promise) | null = null + const { request, writeShare } = await startReader({ + policyCacheMilliseconds: 0, + wrapRead: (read) => async (key, maximumBytes, signal) => { + const result = await read(key, maximumBytes, signal) + if (key.includes("/files/")) await afterFileRead?.() + return result + }, + }) + const share = await writeShare( + { "index.html": "root", "assets/app.js": "x" }, + { password: await hashPublicSharePassword("correct horse") }, + ) + const cookie = await share.open("correct horse") + afterFileRead = () => change(share) + + const response = await request(`${mount}assets/app.js`, { headers: assetHeaders(cookie) }) + + expect(response.status).toBe(status) + expect(response.body.toString()).not.toBe("x") + }) + + it.each<[string, (writePolicy: WritePolicy) => Promise]>([ + ["is revoked", (writePolicy) => writePolicy({ state: "revoked" })], + [ + "gets a new password", + async (writePolicy) => + writePolicy({ password: await hashPublicSharePassword("battery staple") }), + ], + ])( + "does not open a password link that %s while the password is checked", + async (_name, change) => { + const { request, writeShare } = await startReader({ policyCacheMilliseconds: 0 }) + const { shareId, writePolicy } = await writeShare( + { "index.html": "root" }, + { password: await hashPublicSharePassword("correct horse") }, + ) + passwordCheck.after = () => change(writePolicy) + onTestFinished(() => { + passwordCheck.after = null + }) + + const response = await request(`/s/${shareId}`, { + method: "POST", + headers: passwordHeaders(), + body: "password=correct+horse", + }) + + expect(response.status).toBe(404) + expect(response.headers["set-cookie"]).toBeUndefined() + }, + ) + + it("stops GET and HEAD at expiry even while the policy is cached", async () => { + let clock = Date.parse("2026-11-29T08:00:00.000Z") + const { request, writeShare } = await startReader({ now: () => clock }) + const { shareId, open } = await writeShare( + { "index.html": "root", "assets/app.js": "app()" }, + { expiresAt: clock + 1_000 }, + ) + const cookie = await open() + const asset = `${mount}assets/app.js` + expect((await request(asset, { headers: assetHeaders(cookie) })).status).toBe(200) + + clock += 1_000 + + expect((await request(asset, { headers: assetHeaders(cookie) })).status).toBe(404) + expect((await request(asset, { method: "HEAD", headers: assetHeaders(cookie) })).status).toBe( + 404, + ) + expect((await request(`/s/${shareId}`)).status).toBe(404) + }) + + it("opens a password link only for the current password from the share origin", async () => { + const { request, writeShare } = await startReader({ policyCacheMilliseconds: 0 }) + const { shareId, writePolicy } = await writeShare( + { "index.html": "root", "assets/app.js": "app()" }, + { password: await hashPublicSharePassword("correct horse") }, + ) + const link = `/s/${shareId}` + const asset = `${mount}assets/app.js` + + const form = await request(link, { headers: { "sec-fetch-dest": "document" } }) + expect(form.status).toBe(200) + expect(form.body.toString()).toContain(`
`) + // Under no-referrer, browsers post the form with Origin: null, which the origin check refuses. + expect(form.headers["referrer-policy"]).toBe("same-origin") + expect(form.headers["set-cookie"]).toBeUndefined() + const forged = `__Secure-replica-share-${shareId}=open` + expect((await request(asset, { headers: assetHeaders(forged) })).status).toBe(404) + + // The other allowed hostname is still a different origin for the form. + for (const crossOrigin of ["https://attacker.example", customOrigin]) { + const posted = await request(link, { + method: "POST", + headers: passwordHeaders({ origin: crossOrigin }), + body: "password=correct+horse", + }) + expect(posted.status, crossOrigin).toBe(404) + expect(posted.headers["set-cookie"]).toBeUndefined() + } + + const wrong = await request(link, { + method: "POST", + headers: passwordHeaders(), + body: "password=wrong", + }) + expect(wrong.status).toBe(401) + expect(wrong.body.toString()).toContain("That password isn't correct.") + expect(wrong.headers["set-cookie"]).toBeUndefined() + expect(wrong.headers["referrer-policy"]).toBe("same-origin") + + const correct = await request(link, { + method: "POST", + headers: passwordHeaders(), + body: "password=correct+horse", + }) + expect(correct.status).toBe(303) + expect(correct.headers.location).toBe(mount) + expect(correct.headers["referrer-policy"]).toBe("no-referrer") + const cookie = openedCookie(correct.headers) + expect(cookie).not.toBe(forged) + expect((await request(asset, { headers: assetHeaders(cookie) })).status).toBe(200) + expect((await request(link, { headers: documentHeaders(cookie) })).status).toBe(303) + const onCustomHost = await request(link, { + method: "POST", + headers: passwordHeaders({ origin: customOrigin, host: new URL(customOrigin).host }), + body: "password=correct+horse", + }) + expect(onCustomHost.status).toBe(303) + + await writePolicy({ password: await hashPublicSharePassword("battery staple") }) + + expect((await request(asset, { headers: assetHeaders(cookie) })).status).toBe(404) + const relocked = await request(link, { headers: documentHeaders(cookie) }) + expect(relocked.status).toBe(200) + expect(relocked.body.toString()).toContain(``) + }) + + it("limits one caller to 5 password attempts in 10 minutes, even when they arrive together", async () => { + let clock = Date.parse("2026-11-29T08:00:00.000Z") + const { request, writeShare } = await startReader({ now: () => clock }) + const { shareId } = await writeShare( + { "index.html": "root" }, + { password: await hashPublicSharePassword("correct horse"), expiresAt: clock + hour }, + ) + function attempt(password: string, address: string) { + return request(`/s/${shareId}`, { + method: "POST", + headers: passwordHeaders({ "x-forwarded-for": address }), + body: new URLSearchParams({ password }).toString(), + }) + } + async function fail(times: number) { + for (let failure = 0; failure < times; failure += 1) { + expect((await attempt("wrong", "203.0.113.1")).status).toBe(401) + } + } + await fail(4) + // The correct password clears earlier failures. + expect((await attempt("correct horse", "203.0.113.1")).status).toBe(303) + await fail(4) + + // Three guesses stay below the concurrent check limit, so only the attempt count refuses them. + let verified = 0 + let refused = 0 + let finishChecks!: () => void + const checksHeld = new Promise((resolve) => (finishChecks = resolve)) + passwordCheck.after = () => { + verified += 1 + return checksHeld + } + onTestFinished(() => { + finishChecks() + passwordCheck.after = null + }) + const together = Array.from({ length: 3 }, async () => { + const response = await attempt("wrong", "203.0.113.1") + if (response.status === 429) refused += 1 + return response + }) + await vi.waitFor(() => expect(verified + refused).toBe(3)) + finishChecks() + const togetherStatuses = (await Promise.all(together)).map(({ status }) => status) + passwordCheck.after = null + + const limited = await attempt("correct horse", "203.0.113.1") + const otherCaller = await attempt("correct horse", "203.0.113.2") + clock += 10 * 60 * 1000 + const afterWindow = await attempt("correct horse", "203.0.113.1") + + expect(verified).toBe(1) + expect(togetherStatuses.sort()).toEqual([401, 429, 429]) + expect(limited.status).toBe(429) + expect(limited.headers["set-cookie"]).toBeUndefined() + expect(limited.headers["referrer-policy"]).toBe("same-origin") + expect(limited.body.toString()).toContain( + "Too many attempts. Wait 10 minutes and try again, or ask the person who shared it for the password.", + ) + expect(otherCaller.status).toBe(303) + expect(afterWindow.status).toBe(303) + }) + + it("does not count a password check that fails to run against the caller", async () => { + const { request, writeShare } = await startReader() + const { shareId } = await writeShare( + { "index.html": "root" }, + { password: await hashPublicSharePassword("correct horse") }, + ) + function attempt() { + return request(`/s/${shareId}`, { + method: "POST", + headers: passwordHeaders({ "x-forwarded-for": "203.0.113.1" }), + body: "password=wrong", + }) + } + for (let failure = 0; failure < 4; failure += 1) expect((await attempt()).status).toBe(401) + + passwordCheck.after = () => Promise.reject(new Error("scrypt failed")) + onTestFinished(() => { + passwordCheck.after = null + }) + const failedCheck = await attempt() + passwordCheck.after = null + + expect(failedCheck.status).toBe(503) + expect((await attempt()).status).toBe(401) + expect((await attempt()).status).toBe(429) + }) + + it("asks a visitor to retry while 4 password checks are already running", async () => { + const { request, writeShare } = await startReader() + const { shareId } = await writeShare( + { "index.html": "root" }, + { password: await hashPublicSharePassword("correct horse") }, + ) + function attempt(address: string) { + return request(`/s/${shareId}`, { + method: "POST", + headers: passwordHeaders({ "x-forwarded-for": address }), + body: "password=wrong", + }) + } + let running = 0 + let finishChecks!: () => void + const checksHeld = new Promise((resolve) => (finishChecks = resolve)) + passwordCheck.after = () => { + running += 1 + return checksHeld + } + onTestFinished(() => { + finishChecks() + passwordCheck.after = null + }) + + // Each check comes from a different address, so only the concurrency limit applies. + const held = ["1", "2", "3", "4"].map((host) => attempt(`203.0.113.${host}`)) + await vi.waitFor(() => expect(running).toBe(4)) + const busy = await attempt("203.0.113.5") + finishChecks() + passwordCheck.after = null + const heldStatuses = (await Promise.all(held)).map(({ status }) => status) + + expect(busy.status).toBe(429) + expect(busy.body.toString()).toContain("This page is busy. Try again in a moment.") + expect(busy.body.toString()).not.toContain("Too many attempts") + expect(heldStatuses).toEqual([401, 401, 401, 401]) + expect((await attempt("203.0.113.5")).status).toBe(401) + }) + + it("loads two of the largest manifests at once and refuses a third until one finishes", async () => { + let holding = true + const held: (() => void)[] = [] + const { request, writeShare } = await startReader({ + wrapRead: (read) => async (key, maximumBytes, signal) => { + if (holding && key.endsWith("manifest.json")) { + await new Promise((resolve) => held.push(resolve)) + } + return read(key, maximumBytes, signal) + }, + }) + const shares = [ + await writeShare({ "index.html": "one" }), + await writeShare({ "index.html": "two" }), + await writeShare({ "index.html": "three" }), + ] + + const first = request(`/s/${shares[0]!.shareId}`) + const second = request(`/s/${shares[1]!.shareId}`) + await vi.waitFor(() => expect(held).toHaveLength(2)) + const third = await request(`/s/${shares[2]!.shareId}`) + holding = false + held.forEach((resolve) => resolve()) + + // Each manifest read reserves room for the largest possible manifest, about 16 MiB. + expect(third.status).toBe(503) + expect((await first).status).toBe(303) + expect((await second).status).toBe(303) + expect((await request(`/s/${shares[2]!.shareId}`)).status).toBe(303) + }) + + it("serves the newest active share of a mount, including a reopened older one", async () => { + const { request, writeShare } = await startReader({ policyCacheMilliseconds: 0 }) + const shares: { shareId: string; cookie: string; writePolicy: WritePolicy }[] = [] + for (let index = 1; index <= 10; index += 1) { + const share = await writeShare({ "index.html": `share ${index}` }) + shares.push({ ...share, cookie: await share.open() }) + } + const [oldest, , , , , , , , newerActive, newest] = shares + for (const share of shares) { + if (share !== oldest && share !== newerActive) await share.writePolicy({ state: "revoked" }) + } + // Browsers list older cookies first and give a deleted then recreated cookie a new age. + function header(list: typeof shares) { + return list.map(({ cookie }) => cookie).join("; ") + } + + const all = await request(mount, { headers: documentHeaders(header(shares)) }) + const revokedOnly = await request(mount, { headers: documentHeaders(newest!.cookie) }) + const reopened = await request(`/s/${oldest!.shareId}`) + const afterReopen = await request(mount, { + headers: documentHeaders(header([...shares.slice(1), oldest!])), + }) + + expect(all.status).toBe(200) + expect(all.body.toString()).toBe("share 9") + expect(revokedOnly.status).toBe(404) + expect(reopened.headers["set-cookie"]!.slice(0, 2).map(cookiePair)).toEqual([ + `__Secure-replica-share-${oldest!.shareId}=`, + oldest!.cookie, + ]) + expect(afterReopen.status).toBe(200) + expect(afterReopen.body.toString()).toBe("share 1") + }) + + it("does not let one share's cookie open another share's mount", async () => { + const { request, writeShare } = await startReader() + const first = await writeShare({ "index.html": "first share" }) + await writeShare({ "index.html": "second share" }, { mount: "/previews/github/902/1301/" }) + const cookie = await first.open() + + const response = await request("/previews/github/902/1301/", { + headers: documentHeaders(cookie), + }) + + expect(response.status).toBe(404) + expect(response.body.toString()).not.toContain("second share") + }) + + it("serves the generated and custom hostnames and refuses other hosts, plain HTTP and service worker requests", async () => { + const { request, writeShare } = await startReader() + const { shareId, open } = await writeShare({ + "index.html": "root", + "assets/sw.js": "self.skip()", + }) + const cookie = await open() + const asset = `${mount}assets/sw.js` + const customHost = { host: new URL(customOrigin).host } + expect((await request(asset, { headers: assetHeaders(cookie) })).status).toBe(200) + expect( + (await request(asset, { headers: { ...assetHeaders(cookie), ...customHost } })).status, + ).toBe(200) + expect((await request(`/s/${shareId}`, { headers: customHost })).status).toBe(303) + + for (const headers of [ + { host: "hub.example.com" } as Record, + { host: "other.example.azurecontainerapps.io" }, + { "x-forwarded-proto": "http" }, + { "service-worker": "script" }, + { "sec-fetch-dest": "serviceworker" }, + ]) { + const response = await request(asset, { headers: { ...assetHeaders(cookie), ...headers } }) + expect(response.status, JSON.stringify(headers)).toBe(404) + } + }) + + it("reports a stored file whose size differs from its manifest as unavailable", async () => { + const { request, writeShare } = await startReader() + const { root, hashes, open } = await writeShare({ "index.html": "root", "assets/app.js": "x" }) + await writeFile(join(root, "files", hashes["assets/app.js"]!), "a much longer replacement") + const cookie = await open() + + const response = await request(`${mount}assets/app.js`, { headers: assetHeaders(cookie) }) + + expect(response.status).toBe(503) + expect(response.body.toString()).not.toContain("replacement") + }) +}) diff --git a/hub/server/routes/public-share-reader/index.ts b/hub/server/routes/public-share-reader/index.ts new file mode 100644 index 000000000..df1551130 --- /dev/null +++ b/hub/server/routes/public-share-reader/index.ts @@ -0,0 +1,404 @@ +import { timingSafeEqual } from "node:crypto" +import { extname } from "node:path" +import express, { type Request, type Response } from "express" +import { z } from "zod" + +import { createPublicShareByteAllowance } from "../../domains/public-share-export/create-public-share-byte-allowance/index.ts" +import { createPublicShareProof } from "../../domains/public-share-export/create-public-share-proof/index.ts" +import { createPublicShareStateReader } from "../../domains/public-share-export/create-public-share-state-reader/index.ts" +import { publicShareStorageKey } from "../../domains/public-share-export/public-share-storage-key/index.ts" +import { resolvePublicShareFile } from "../../domains/public-share-export/resolve-public-share-file/index.ts" +import { + maximumPublicShareCookieLifetime, + publicShareCookiePrefix, + publicShareIdPattern, + type PublicShareObjectReader, + type PublicShareState, +} from "../../domains/public-share-export/types.ts" +import { verifyPublicSharePassword } from "../../domains/public-share-export/verify-public-share-password/index.ts" +import { sendPublicSharePage } from "../../integrations/express/send-public-share-page/index.ts" +import { privatePreviewAddress } from "../../utils/private-preview-address/index.ts" + +type ActiveShare = Extract + +const maximumBufferedFileBytes = 100 * 1024 * 1024 +// Separate from files so a large file read cannot block the policy checks it depends on. +// Room for two of the largest manifests loading at once. +const maximumBufferedMetadataBytes = 40 * 1024 * 1024 +const maximumShareCookies = 8 +// A temporary cooldown per visitor and link; it never locks or turns off the link. +const maximumPasswordFailures = 5 +const passwordFailureWindow = 10 * 60 * 1000 +const maximumConcurrentPasswordChecks = 4 +const fileReadTimeout = 15_000 +const passwordForm = z.strictObject({ password: z.string().max(256) }) +const contentPolicy = [ + "default-src 'none'", + "script-src 'self' 'unsafe-inline'", + "style-src 'self' 'unsafe-inline'", + "img-src 'self' data: blob:", + "media-src 'self' blob:", + "font-src 'self' data:", + "connect-src 'self'", + "worker-src 'none'", + "frame-ancestors 'none'", + "form-action 'none'", + "base-uri 'none'", +].join("; ") +const contentTypes: Record = { + ".avif": "image/avif", + ".css": "text/css; charset=utf-8", + ".gif": "image/gif", + ".html": "text/html; charset=utf-8", + ".ico": "image/x-icon", + ".jpeg": "image/jpeg", + ".jpg": "image/jpeg", + ".js": "text/javascript; charset=utf-8", + ".json": "application/json; charset=utf-8", + ".mjs": "text/javascript; charset=utf-8", + ".mp3": "audio/mpeg", + ".mp4": "video/mp4", + ".otf": "font/otf", + ".png": "image/png", + ".svg": "image/svg+xml", + ".ttf": "font/ttf", + ".txt": "text/plain; charset=utf-8", + ".wasm": "application/wasm", + ".webm": "video/webm", + ".webp": "image/webp", + ".woff": "font/woff", + ".woff2": "font/woff2", +} + +interface PublicShareReaderOptions { + /** Exact HTTPS origins that serve shares: the generated hostname and an optional custom one. */ + origins: readonly string[] + trustedProxyHops: number + readObject: PublicShareObjectReader + policyCacheMilliseconds?: number + /** A download that makes no progress for this long is dropped, releasing its allowance. */ + responseIdleMilliseconds?: number + now?: () => number +} + +function isDocument(request: Request) { + const destination = request.get("sec-fetch-dest") + if (destination !== undefined) return destination === "document" + return (request.get("accept") ?? "").includes("text/html") +} + +// The browser sends every share cookie whose path covers the request. Browsers list older cookies +// first, so checking the newest few keeps a just-opened link usable beside revoked ones. +function readShareCookies(request: Request) { + const found: { shareId: string; proof: string }[] = [] + const pairs = request.headers.cookie?.split(";") ?? [] + for (const pair of pairs.reverse()) { + const separator = pair.indexOf("=") + const name = separator < 0 ? "" : pair.slice(0, separator).trim() + if (!name.startsWith(publicShareCookiePrefix)) continue + const shareId = name.slice(publicShareCookiePrefix.length) + const proof = pair.slice(separator + 1).trim() + if (!publicShareIdPattern.test(shareId) || proof.length > 128) continue + found.push({ shareId, proof }) + if (found.length >= maximumShareCookies) break + } + return found +} + +function proofMatches(actual: string, expected: string) { + const left = Buffer.from(actual) + const right = Buffer.from(expected) + return left.byteLength === right.byteLength && timingSafeEqual(left, right) +} + +function matchesEntityTag(header: string | undefined, entityTag: string) { + if (!header) return false + return header + .split(",") + .map((value) => value.trim().replace(/^W\//, "")) + .some((value) => value === "*" || value === entityTag) +} + +function temporarilyUnavailable(response: Response) { + return response.status(503).type("text").send("This shared prototype is temporarily unavailable.") +} + +/** Serves exported shares read-only. It reads only export storage and never contacts Hub. */ +export function createPublicShareReader({ + origins, + trustedProxyHops, + readObject, + policyCacheMilliseconds, + responseIdleMilliseconds = 30_000, + now = Date.now, +}: PublicShareReaderOptions) { + const app = express() + const hosts = new Set(origins.map((origin) => new URL(origin).host)) + const reserve = createPublicShareByteAllowance(maximumBufferedFileBytes) + const readShare = createPublicShareStateReader({ + readObject, + policyCacheMilliseconds, + reserve: createPublicShareByteAllowance(maximumBufferedMetadataBytes), + now, + }) + const passwordFailures = new Map() + let passwordChecks = 0 + + function notFound(request: Request, response: Response) { + if (isDocument(request)) return sendPublicSharePage(response, 404, { kind: "unavailable" }) + return response.sendStatus(404) + } + + function hasProof(request: Request, { manifest, policy }: ActiveShare) { + const expected = createPublicShareProof(manifest, policy) + return readShareCookies(request).some( + ({ shareId, proof }) => shareId === manifest.shareId && proofMatches(proof, expected), + ) + } + + // Sets the share cookie for its mount and for its entry link, then opens the start page. + function openShare(response: Response, { manifest, policy }: ActiveShare) { + const name = `${publicShareCookiePrefix}${manifest.shareId}` + const proof = createPublicShareProof(manifest, policy) + const maxAge = Math.min(Date.parse(policy.expiresAt) - now(), maximumPublicShareCookieLifetime) + for (const path of [manifest.mount, `/s/${manifest.shareId}`]) { + const options = { httpOnly: true, secure: true, sameSite: "lax", path } as const + // Browsers keep a replaced cookie's original age; deleting it first makes this the newest. + response.clearCookie(name, options) + response.cookie(name, proof, { ...options, maxAge }) + } + return response + .status(303) + .location(`${manifest.mount}${manifest.entry.slice(1)}`) + .end() + } + + app.disable("x-powered-by") + app.disable("etag") + app.set("trust proxy", trustedProxyHops) + app.use((request, response, next) => { + response.setHeader("Cache-Control", "no-store") + response.setHeader("Referrer-Policy", "no-referrer") + response.setHeader("X-Content-Type-Options", "nosniff") + response.setHeader("X-Frame-Options", "DENY") + response.setHeader("X-Robots-Tag", "noindex, nofollow, noarchive") + response.setHeader("Cross-Origin-Resource-Policy", "same-origin") + response.setHeader("Cross-Origin-Opener-Policy", "same-origin") + response.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=()") + response.setHeader("Content-Security-Policy", contentPolicy) + if (!request.secure || !hosts.has(request.get("host") ?? "")) return response.sendStatus(404) + if (request.get("service-worker") || request.get("sec-fetch-dest") === "serviceworker") { + return response.sendStatus(404) + } + next() + }) + + app.get("/health", (_request, response) => response.sendStatus(204)) + + // Share cookies cover only the slash-terminated mount, and routers that use a basename can show + // the mount without its slash. Add the slash from the path alone, before reading any share. + app.get("/previews/github/:repositoryId/:runId", (request, response, next) => { + const address = privatePreviewAddress(request.params.repositoryId, request.params.runId) + if (!address || request.path !== address.mount.slice(0, -1)) return next() + const separator = request.originalUrl.indexOf("?") + const query = separator < 0 ? "" : request.originalUrl.slice(separator) + return response.status(302).location(`${address.mount}${query}`).end() + }) + + app.get("/s/:shareId", async (request, response) => { + const { shareId } = request.params + if (!publicShareIdPattern.test(shareId)) return notFound(request, response) + const state = await readShare(shareId) + if (state.status === "unavailable") return temporarilyUnavailable(response) + if (state.status === "inactive") + return sendPublicSharePage(response, 404, { kind: "unavailable" }) + if (state.policy.password && !hasProof(request, state)) { + return sendPublicSharePage(response, 200, { kind: "password", action: `/s/${shareId}` }) + } + return openShare(response, state) + }) + + app.post( + "/s/:shareId", + (request, response, next) => { + if ( + // The form must come from the same allowed host that received it. + request.get("origin") !== `https://${request.get("host")}` || + !request.is("application/x-www-form-urlencoded") || + !publicShareIdPattern.test(request.params.shareId) + ) + return response.sendStatus(404) + next() + }, + express.urlencoded({ extended: false, limit: "1kb", parameterLimit: 1, inflate: false }), + async (request, response) => { + const { shareId } = request.params + const action = `/s/${shareId}` + const form = passwordForm.safeParse(request.body) + if (!form.success) return response.sendStatus(400) + const state = await readShare(shareId) + if (state.status === "unavailable") return temporarilyUnavailable(response) + if (state.status === "inactive") { + return sendPublicSharePage(response, 404, { kind: "unavailable" }) + } + const password = state.policy.password + if (!password) return openShare(response, state) + // Attempts count per caller, so one caller's guesses cannot lock out other viewers. Each + // attempt is counted before its check, so concurrent guesses cannot exceed the limit. + // Each replica keeps its own count. + const caller = `${request.ip ?? ""} ${shareId}` + let attempts = passwordFailures.get(caller) + if (attempts && attempts.resetAt <= now()) { + passwordFailures.delete(caller) + attempts = undefined + } + if (attempts && attempts.count >= maximumPasswordFailures) { + return sendPublicSharePage(response, 429, { kind: "password", action, error: "throttled" }) + } + if (passwordChecks >= maximumConcurrentPasswordChecks) { + return sendPublicSharePage(response, 429, { kind: "password", action, error: "busy" }) + } + if (!attempts) { + if (passwordFailures.size >= 10_000) { + passwordFailures.delete(passwordFailures.keys().next().value!) + } + attempts = { count: 0, resetAt: now() + passwordFailureWindow } + passwordFailures.set(caller, attempts) + } + attempts.count += 1 + passwordChecks += 1 + let correct: boolean + try { + correct = await verifyPublicSharePassword(form.data.password, password) + } catch { + attempts.count -= 1 + return temporarilyUnavailable(response) + } finally { + passwordChecks -= 1 + } + if (!correct) { + return sendPublicSharePage(response, 401, { kind: "password", action, error: "incorrect" }) + } + if (passwordFailures.get(caller) === attempts) passwordFailures.delete(caller) + // The link can be revoked, expire or change password while the hash is checked. + const current = await readShare(shareId) + if (current.status === "unavailable") return temporarilyUnavailable(response) + if (current.status === "inactive" || current.policy.password?.hash !== password.hash) { + return sendPublicSharePage(response, 404, { kind: "unavailable" }) + } + return openShare(response, current) + }, + ) + + app.get("/{*path}", async (request, response) => { + // Track disconnects from the start, so one during the metadata reads below is not missed. + const disconnected = new AbortController() + let release: (() => void) | null = null + let reading = false + response.once("close", () => { + disconnected.abort() + if (!reading) release?.() + }) + const document = isDocument(request) + let unavailable = false + let share: { shareId: string; proof: string; state: ActiveShare } | null = null + for (const { shareId, proof } of readShareCookies(request)) { + const state = await readShare(shareId) + if (state.status === "unavailable") unavailable = true + if ( + state.status === "active" && + request.path.startsWith(state.manifest.mount) && + proofMatches(proof, createPublicShareProof(state.manifest, state.policy)) + ) { + share = { shareId, proof, state } + break + } + } + if (!share) return unavailable ? temporarilyUnavailable(response) : notFound(request, response) + + const { shareId, proof, state } = share + let relative: string + try { + relative = decodeURIComponent(request.path.slice(state.manifest.mount.length)) + } catch { + return notFound(request, response) + } + const file = resolvePublicShareFile(state.manifest, relative, document) + const key = file && publicShareStorageKey(shareId, { kind: "file", sha256: file.sha256 }) + if (!file || !key) return notFound(request, response) + // A directory requested without a literal trailing slash would resolve its relative URLs one + // level up. Build the redirect from the path alone, never from an absolute-form request target. + const directoryIndex = + relative !== "" && + file.path === (relative.endsWith("/") ? `${relative}index.html` : `${relative}/index.html`) + if (directoryIndex && !request.path.endsWith("/")) { + const query = request.originalUrl.includes("?") + ? request.originalUrl.slice(request.originalUrl.indexOf("?")) + : "" + return response + .status(302) + .location(`${request.path.replace(/%2f$/i, "")}/${query}`) + .end() + } + + const entityTag = `"${file.sha256}"` + const contentType = contentTypes[extname(file.path).toLowerCase()] ?? "application/octet-stream" + const size = file.size + // Browsers revalidate every file, so each reuse still passes the policy checks above. + function sendFileHeaders(status: number) { + response.setHeader("Cache-Control", "private, no-cache") + response.setHeader("ETag", entityTag) + response.type(contentType) + if (status === 200) response.setHeader("Content-Length", size) + return response.status(status) + } + if (matchesEntityTag(request.get("if-none-match"), entityTag)) { + return sendFileHeaders(304).end() + } + if (request.method === "HEAD") return sendFileHeaders(200).end() + + if (disconnected.signal.aborted) return + // Keep the reservation until both the read and the response end, so disconnecting cannot + // admit new reads while this one still holds its buffer. + release = reserve(file.size) + if (!release) return temporarilyUnavailable(response) + response.setTimeout(responseIdleMilliseconds, () => response.destroy()) + reading = true + try { + const stored = await readObject( + key, + file.size, + AbortSignal.any([AbortSignal.timeout(fileReadTimeout), disconnected.signal]), + ) + if (disconnected.signal.aborted) return + if (stored.status === "not-found") return notFound(request, response) + if (stored.status !== "ok" || stored.bytes.byteLength !== file.size) { + return temporarilyUnavailable(response) + } + // Revocation, expiry or a password change during a slow read stops this response too. + const current = await readShare(shareId) + if (current.status === "unavailable") return temporarilyUnavailable(response) + if ( + current.status !== "active" || + !proofMatches(proof, createPublicShareProof(current.manifest, current.policy)) + ) + return notFound(request, response) + return sendFileHeaders(200).end(stored.bytes) + } catch { + return temporarilyUnavailable(response) + } finally { + reading = false + if (disconnected.signal.aborted) release() + } + }) + + app.use((request, response) => notFound(request, response)) + app.use((error: unknown, _request: Request, response: Response, next: express.NextFunction) => { + if (response.headersSent) return next(error) + const status = + typeof error === "object" && error !== null && "status" in error ? error.status : null + if (status === 400 || status === 413 || status === 415) return response.sendStatus(status) + return temporarilyUnavailable(response) + }) + return app +} diff --git a/hub/server/scripts/start-public-share-reader/index.test.ts b/hub/server/scripts/start-public-share-reader/index.test.ts new file mode 100644 index 000000000..0a731805c --- /dev/null +++ b/hub/server/scripts/start-public-share-reader/index.test.ts @@ -0,0 +1,67 @@ +import { readFileSync } from "node:fs" +import { dirname, relative, resolve } from "node:path" +import { fileURLToPath } from "node:url" +import { describe, expect, it } from "vitest" + +const hubRoot = fileURLToPath(new URL("../../../", import.meta.url)) +const entry = resolve(hubRoot, "server/scripts/start-public-share-reader/index.ts") +const allowedDirectories = [ + "server/domains/public-share-export/", + "server/routes/public-share-reader/", + "server/integrations/azure-blob/create-public-share-object-reader/", + "server/integrations/filesystem/create-public-share-object-reader/", + "server/integrations/express/send-public-share-page/", + "server/scripts/start-public-share-reader/", + // A dependency-free utility, shared so exported start pages match Hub's rule exactly. + "server/utils/normalize-start-page/", + "server/utils/private-preview-address/", +] +const allowedPackages = new Set(["express", "zod", "@azure/identity", "@azure/storage-blob"]) +const importPattern = /\b(?:from|import)\s*\(?\s*["']([^"']+)["']/g + +// Follows static and dynamic imports from the start script without running it. +function readImportGraph() { + const modules = new Set() + const packages = new Set() + const pending = [entry] + while (pending.length) { + const file = pending.pop()! + if (modules.has(file)) continue + modules.add(file) + for (const [, specifier] of readFileSync(file, "utf8").matchAll(importPattern)) { + if (!specifier!.startsWith(".")) { + packages.add(specifier!) + continue + } + const target = resolve(dirname(file), specifier!) + pending.push(target.endsWith(".ts") ? target : resolve(target, "index.ts")) + } + } + return { + modules: [...modules].map((file) => relative(hubRoot, file)), + packages: [...packages], + } +} + +describe("start-public-share-reader", () => { + it("reaches only public share modules, the start-page rule, Node built-ins and allowed packages", () => { + const { modules, packages } = readImportGraph() + + expect(modules).toEqual( + expect.arrayContaining([ + "server/routes/public-share-reader/index.ts", + "server/integrations/azure-blob/create-public-share-object-reader/index.ts", + ]), + ) + expect( + modules.filter( + (module) => + module.endsWith(".test.ts") || + !allowedDirectories.some((directory) => module.startsWith(directory)), + ), + ).toEqual([]) + expect( + packages.filter((name) => !name.startsWith("node:") && !allowedPackages.has(name)), + ).toEqual([]) + }) +}) diff --git a/hub/server/scripts/start-public-share-reader/index.ts b/hub/server/scripts/start-public-share-reader/index.ts new file mode 100644 index 000000000..071f384d4 --- /dev/null +++ b/hub/server/scripts/start-public-share-reader/index.ts @@ -0,0 +1,35 @@ +import { createServer } from "node:http" + +import { readPublicShareReaderSettings } from "../../domains/public-share-export/read-public-share-reader-settings/index.ts" +import { createPublicShareFileObjectReader } from "../../integrations/filesystem/create-public-share-object-reader/index.ts" +import { createPublicShareReader } from "../../routes/public-share-reader/index.ts" + +const settings = readPublicShareReaderSettings(process.env) +const port = Number(process.env.PORT ?? 3003) +if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error("PORT must be an integer between 1 and 65535.") +} +const readObject = + settings.storage.provider === "filesystem" + ? createPublicShareFileObjectReader(settings.storage.directory) + : ( + await import("../../integrations/azure-blob/create-public-share-object-reader/index.ts") + ).createPublicShareBlobObjectReader(settings.storage) +const app = createPublicShareReader({ + origins: settings.origins, + trustedProxyHops: settings.trustedProxyHops, + readObject, +}) +const server = createServer({ headersTimeout: 10_000, requestTimeout: 30_000 }, app) +// Container liveness can use a TCP probe; HTTP routes require the HTTPS ingress host. +server.listen(port, process.env.HOST ?? "127.0.0.1") +server.on("error", () => { + console.error("Public share reader could not listen.") + process.exitCode = 1 +}) +for (const signal of ["SIGINT", "SIGTERM"] as const) { + process.once(signal, () => { + server.close() + setTimeout(() => server.closeAllConnections(), 15_000).unref() + }) +}