From 3440f914347a065a4e063820622e7e8f79293532 Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:45:02 -0800 Subject: [PATCH 01/13] docs: propose public sharing through Hub exports and an isolated reader Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/adr/0003-public-sharing-export-reader.md | 146 ++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 docs/adr/0003-public-sharing-export-reader.md 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..cde098b14 --- /dev/null +++ b/docs/adr/0003-public-sharing-export-reader.md @@ -0,0 +1,146 @@ +# ADR 0003: Public sharing through Hub exports and an isolated reader + +Status: proposed on November 29, 2026. The Replica maintainers need to confirm the [open decisions](#open-decisions) before Hub integration starts. + +## 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 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 + +Recommended: 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. + +Trade-offs of this choice: + +- 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. +- 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. + +### Request checks + +The reader runs these checks for every request, including assets and `HEAD`: + +- The host and HTTPS scheme match the configured origin. +- 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, time out, and share a 100 MiB in-memory allowance per process. + +Exact files are served first, then a directory's `index.html`. 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`, `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 according to the retention decision. 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; legacy links unchanged | PR 1 contract | +| 3. Terraform and setup wizard | Export storage account and container, reader Container App and identity, container-scoped grants, public hostname, settings on Hub and reader, disabled by default | 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. + +## Open decisions + +| Decision | Recommended default | +| --- | --- | +| Can an active link's expiry be extended? | No. Create a new link. This matches today's rule that deadlines never grow. | +| Password support | Optional per link, set at creation and replaceable or removable later. | +| Copied data after revocation or expiry | Delete the export's files within 24 hours. Keep the Hub record for history. Re-sharing makes a new copy. | +| Viewing during a Hub outage | Yes. The reader needs only storage. Revocations made during an outage wait until Hub returns. | +| Public hostname | A registrable domain separate from Hub's, so public prototypes are never same-site with Hub. | +| Existing `ShareLink` rows | Leave them on the legacy backend unchanged. Do not convert or redirect them to exports. | +| Visible mount path after opening | Accept it; hiding it needs rewriting or rebuilds. | From 864ef4ac6c664a68ef15e6bd45eac131d585f735 Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:51:30 -0800 Subject: [PATCH 02/13] feat(hub): define the public share export contract Add version 1 manifest and policy schemas, exact storage keys, scrypt password hashing, cookie proofs, manifest-only file resolution, a cached share state reader, and bounded Azure Blob and filesystem object readers. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../create-public-share-proof/index.ts | 17 +++ .../create-public-share-state-reader/index.ts | 124 ++++++++++++++++ .../hash-public-share-password/index.ts | 32 +++++ .../public-share-storage-key/index.ts | 13 ++ .../index.ts | 85 +++++++++++ .../resolve-public-share-file/index.ts | 41 ++++++ .../domains/public-share-export/types.ts | 135 ++++++++++++++++++ .../verify-public-share-password/index.ts | 27 ++++ .../index.ts | 48 +++++++ .../index.ts | 47 ++++++ 10 files changed, 569 insertions(+) create mode 100644 hub/server/domains/public-share-export/create-public-share-proof/index.ts create mode 100644 hub/server/domains/public-share-export/create-public-share-state-reader/index.ts create mode 100644 hub/server/domains/public-share-export/hash-public-share-password/index.ts create mode 100644 hub/server/domains/public-share-export/public-share-storage-key/index.ts create mode 100644 hub/server/domains/public-share-export/read-public-share-reader-settings/index.ts create mode 100644 hub/server/domains/public-share-export/resolve-public-share-file/index.ts create mode 100644 hub/server/domains/public-share-export/types.ts create mode 100644 hub/server/domains/public-share-export/verify-public-share-password/index.ts create mode 100644 hub/server/integrations/azure-blob/create-public-share-object-reader/index.ts create mode 100644 hub/server/integrations/filesystem/create-public-share-object-reader/index.ts 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.ts b/hub/server/domains/public-share-export/create-public-share-state-reader/index.ts new file mode 100644 index 000000000..beb5c8418 --- /dev/null +++ b/hub/server/domains/public-share-export/create-public-share-state-reader/index.ts @@ -0,0 +1,124 @@ +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 + 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 + +/** Reads a share's policy and manifest, caching the policy briefly and the manifest until evicted. */ +export function createPublicShareStateReader({ + readObject, + policyCacheMilliseconds = 5_000, + now = Date.now, +}: StateReaderOptions) { + const policies = new Map() + const manifests = new Map() + 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" } + 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: result.data } + } + + // 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 () => { + const loaded = await readJson( + shareId, + "policy", + maximumPublicSharePolicyBytes, + publicSharePolicySchema, + ) + if (loaded.status !== "ok") return loaded + if (loaded.value.shareId !== shareId) return { status: "unavailable" } + policies.delete(shareId) + if (policies.size >= maximumCachedPolicies) policies.delete(policies.keys().next().value!) + policies.set(shareId, { cachedUntil: now() + policyCacheMilliseconds, policy: loaded.value }) + return loaded + }) + } + + 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 } + } + return once(`manifest:${shareId}`, async () => { + const loaded = await readJson( + shareId, + "manifest", + maximumPublicShareManifestBytes, + publicShareManifestSchema, + ) + if (loaded.status !== "ok") return loaded + if (loaded.value.shareId !== shareId) return { status: "unavailable" } + if (manifests.size >= maximumCachedManifests) manifests.delete(manifests.keys().next().value!) + manifests.set(shareId, loaded.value) + return loaded + }) + } + + 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 (policy.value.state !== "active" || Date.parse(policy.value.expiresAt) <= now()) { + 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" } + return { status: "active", manifest: manifest.value, policy: policy.value } + } +} 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..d64a740f9 --- /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 || Buffer.byteLength(password) > 256) { + throw new Error("A share password must contain 1 to 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.ts b/hub/server/domains/public-share-export/read-public-share-reader-settings/index.ts new file mode 100644 index 000000000..b5e32cc00 --- /dev/null +++ b/hub/server/domains/public-share-export/read-public-share-reader-settings/index.ts @@ -0,0 +1,85 @@ +import { z } from "zod" + +type Environment = Readonly> + +export type PublicShareReaderSettings = { + origin: string + trustedProxyHops: number + storage: + | { provider: "filesystem"; directory: string } + | { + provider: "azure" + accountUrl: string + container: string + managedIdentityClientId?: string + } +} + +// The reader must never hold Hub credentials or private storage coordinates. +const forbiddenSetting = + /^(?:HUB_|ARTIFACT_STORAGE_|AZURE_STORAGE_|DATABASE_URL$|TEST_DATABASE_URL$)/ + +/** 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 && forbiddenSetting.test(name)) + .sort() + if (forbidden.length) { + throw new Error( + `The public share reader must not receive Hub settings: ${forbidden.join(", ")}.`, + ) + } + + const origin = environment.PUBLIC_SHARE_ORIGIN ?? "" + const parsed = URL.canParse(origin) ? new URL(origin) : null + if (!parsed || parsed.protocol !== "https:" || parsed.origin !== origin) { + throw new Error( + "PUBLIC_SHARE_ORIGIN must be an exact HTTPS origin, such as https://share.example.net.", + ) + } + + 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 { origin, 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 { + origin, + 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.ts b/hub/server/domains/public-share-export/types.ts new file mode 100644 index 000000000..02176630b --- /dev/null +++ b/hub/server/domains/public-share-export/types.ts @@ -0,0 +1,135 @@ +import { z } from "zod" + +/** Largest served file, matching the largest file a Build may contain. */ +export const maximumPublicShareFileBytes = 100 * 1024 * 1024 +export const maximumPublicShareManifestBytes = 2 * 1024 * 1024 +export const maximumPublicSharePolicyBytes = 4 * 1024 +export const maximumPublicShareFiles = 10_000 +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 + }) +} + +// A mount is the absolute path a Build was compiled for, such as /previews/github/1/2/. +const mountSegment = /^[A-Za-z0-9_~-][A-Za-z0-9._~-]*$/ +const reservedMountRoots = new Set(["s", "health", "__replica-share"]) +const mount = z + .string() + .max(512) + .refine((value) => { + if (!value.startsWith("/") || !value.endsWith("/") || value === "/") return false + const segments = value.slice(1, -1).split("/") + return ( + segments.every((segment) => mountSegment.test(segment)) && + !reservedMountRoots.has(segments[0]!) + ) + }) + +// The entry is a start page inside the mount. Percent escapes are excluded so the reader never +// has to decide whether an encoded segment leaves the mount. +const entrySegment = /^[A-Za-z0-9_~!$&'()*+,;=:@-][A-Za-z0-9._~!$&'()*+,;=:@-]*$/ +const entryPattern = + /^\/([^?#]*)(\?[A-Za-z0-9._~!$&'()*+,;=:@/?-]*)?(#[A-Za-z0-9._~!$&'()*+,;=:@/?-]*)?$/ +const entry = z + .string() + .max(1024) + .refine((value) => { + const path = entryPattern.exec(value)?.[1] + if (path === undefined) return false + return ( + !path || + path + .replace(/\/$/, "") + .split("/") + .every((segment) => entrySegment.test(segment)) + ) + }) + +// 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) <= 2048 && + !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 10,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.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/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" } + } + } +} From ebeba5cad791743be6499c0780ad2f01410fb939 Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:51:34 -0800 Subject: [PATCH 03/13] feat(hub): serve exported shares from an isolated read-only reader The reader opens /s/, checks expiry, revocation and the password on every file and HEAD request, serves exact manifest files with an SPA fallback, and never lists storage or contacts Hub. It refuses to start with Hub settings and is not deployed or enabled. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- hub/docs/README.md | 1 + hub/docs/public-share-reader.md | 56 +++ hub/package.json | 2 + .../express/send-public-share-page/index.ts | 51 +++ .../routes/public-share-reader/index.ts | 335 ++++++++++++++++++ .../start-public-share-reader/index.ts | 35 ++ 6 files changed, 480 insertions(+) create mode 100644 hub/docs/public-share-reader.md create mode 100644 hub/server/integrations/express/send-public-share-page/index.ts create mode 100644 hub/server/routes/public-share-reader/index.ts create mode 100644 hub/server/scripts/start-public-share-reader/index.ts 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..edded94fa --- /dev/null +++ b/hub/docs/public-share-reader.md @@ -0,0 +1,56 @@ +# 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 open decisions. 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 `mount`, start page `entry`, and each package path's `sha256` and `size` | +| `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. + +## What a viewer sees + +1. The viewer opens `https:///s/`. +2. For a password link, the reader asks for the password. Ten wrong attempts within 10 minutes pause that link's password checks on this replica. +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/`. + +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 configured host. +- 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. Directory paths use their `index.html`; 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 read allowance. +- The share is still active after the file read. + +Each replica keeps a policy for up to 5 seconds, 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`, 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 refuses to start when any `HUB_*`, `ARTIFACT_STORAGE_*`, `AZURE_STORAGE_*`, `DATABASE_URL` or `TEST_DATABASE_URL` setting is present, so it cannot receive Hub credentials or private storage coordinates by mistake. + +| Setting | Value | +| --- | --- | +| `PUBLIC_SHARE_ORIGIN` | Exact 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. Serve it on a registrable domain separate from Hub's, so shared prototypes are never same-site with Hub. + +The reader imports only its own modules, 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/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..12b6d6e47 --- /dev/null +++ b/hub/server/integrations/express/send-public-share-page/index.ts @@ -0,0 +1,51 @@ +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}}" +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" | "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 === "busy" + ? '

Too many attempts. Wait a few minutes and try again.

' + : "" + content = + "

Enter the password

This shared prototype is password protected.

" + + message + + `
` + + '' + + '' + + '
' + } + response.setHeader("Content-Security-Policy", pagePolicy) + response.setHeader("Cache-Control", "no-store") + return response + .status(status) + .type("html") + .send( + `Shared prototype
${content}
`, + ) +} 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..bb3a7d0b8 --- /dev/null +++ b/hub/server/routes/public-share-reader/index.ts @@ -0,0 +1,335 @@ +import { timingSafeEqual } from "node:crypto" +import { extname } from "node:path" +import express, { type Request, type Response } from "express" +import { z } from "zod" + +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" + +type ActiveShare = Extract + +const maximumBufferedBytes = 100 * 1024 * 1024 +const minimumReservationBytes = 64 * 1024 +const maximumShareCookies = 8 +const maximumPasswordFailures = 10 +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 origin that serves shares, such as https://share.example.net. */ + origin: string + trustedProxyHops: number + readObject: PublicShareObjectReader + policyCacheMilliseconds?: 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; each is checked in turn. +function readShareCookies(request: Request) { + const found: { shareId: string; proof: string }[] = [] + for (const pair of request.headers.cookie?.split(";") ?? []) { + 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({ + origin, + trustedProxyHops, + readObject, + policyCacheMilliseconds, + now = Date.now, +}: PublicShareReaderOptions) { + const app = express() + const host = new URL(origin).host + const readShare = createPublicShareStateReader({ readObject, policyCacheMilliseconds, now }) + const passwordFailures = new Map() + let passwordChecks = 0 + let bufferedBytes = 0 + + function reserve(byteLength: number) { + const bytes = Math.max(byteLength, minimumReservationBytes) + if (bytes > maximumBufferedBytes - bufferedBytes) return null + bufferedBytes += bytes + let released = false + return () => { + if (released) return + released = true + bufferedBytes -= bytes + } + } + + 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}`]) { + response.cookie(name, proof, { httpOnly: true, secure: true, sameSite: "lax", path, 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 || request.get("host") !== 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)) + + 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 ( + request.get("origin") !== origin || + !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) + const failures = passwordFailures.get(shareId) + if (failures && failures.resetAt <= now()) passwordFailures.delete(shareId) + if ( + (failures && failures.resetAt > now() && failures.count >= maximumPasswordFailures) || + passwordChecks >= maximumConcurrentPasswordChecks + ) { + return sendPublicSharePage(response, 429, { kind: "password", action, error: "busy" }) + } + passwordChecks += 1 + let correct: boolean + try { + correct = await verifyPublicSharePassword(form.data.password, password) + } catch { + return temporarilyUnavailable(response) + } finally { + passwordChecks -= 1 + } + if (!correct) { + const current = passwordFailures.get(shareId) + if (!current && passwordFailures.size >= 10_000) { + passwordFailures.delete(passwordFailures.keys().next().value!) + } + passwordFailures.set(shareId, { + count: (current?.count ?? 0) + 1, + resetAt: current?.resetAt ?? now() + passwordFailureWindow, + }) + return sendPublicSharePage(response, 401, { kind: "password", action, error: "incorrect" }) + } + passwordFailures.delete(shareId) + return openShare(response, state) + }, + ) + + app.get("/{*path}", async (request, response) => { + const document = isDocument(request) + let unavailable = false + let share: { shareId: 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, state } + break + } + } + if (!share) return unavailable ? temporarilyUnavailable(response) : notFound(request, response) + + const { shareId, 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) + + 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() + + const release = reserve(file.size) + if (!release) return temporarilyUnavailable(response) + response.once("close", release) + try { + const stored = await readObject(key, file.size, AbortSignal.timeout(fileReadTimeout)) + if (response.destroyed) return + if (stored.status === "not-found") return notFound(request, response) + if (stored.status !== "ok" || stored.bytes.byteLength !== file.size) { + return temporarilyUnavailable(response) + } + // Revocation or expiry during a slow read stops this response too. + const current = await readShare(shareId) + if (current.status !== "active") return notFound(request, response) + return sendFileHeaders(200).end(stored.bytes) + } catch { + return temporarilyUnavailable(response) + } + }) + + 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.ts b/hub/server/scripts/start-public-share-reader/index.ts new file mode 100644 index 000000000..4a0420f7b --- /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({ + origin: settings.origin, + 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() + }) +} From cff6620e5794ed493cc1012a19890b1c59462513 Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:02:22 -0800 Subject: [PATCH 04/13] fix(hub): bound public share reads and recheck access after waits Share one byte allowance across file, manifest and policy reads, keep a file's reservation until its read and response end, and abort reads on disconnect. Recheck expiry after the manifest loads, the password after file reads and verification, start policy freshness at read time, check the newest share cookies first, and throttle wrong passwords per caller. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/adr/0003-public-sharing-export-reader.md | 7 +- hub/docs/public-share-reader.md | 8 +- .../index.ts | 20 +++++ .../create-public-share-state-reader/index.ts | 79 +++++++++++------ .../routes/public-share-reader/index.ts | 86 ++++++++++++------- 5 files changed, 139 insertions(+), 61 deletions(-) create mode 100644 hub/server/domains/public-share-export/create-public-share-byte-allowance/index.ts diff --git a/docs/adr/0003-public-sharing-export-reader.md b/docs/adr/0003-public-sharing-export-reader.md index cde098b14..1f04d63bd 100644 --- a/docs/adr/0003-public-sharing-export-reader.md +++ b/docs/adr/0003-public-sharing-export-reader.md @@ -101,6 +101,8 @@ Trade-offs of this choice: - 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. @@ -113,7 +115,8 @@ The reader runs these checks for every request, including assets and `HEAD`: - 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, time out, and share a 100 MiB in-memory allowance per process. +- File, manifest and policy reads are size-bounded, time out, and share a 100 MiB in-memory allowance per process. A file's reservation lasts until both its read and its response end. +- Wrong passwords are limited to 10 per caller address and link in 10 minutes, with at most 4 password checks running at once per replica. Exact files are served first, then a directory's `index.html`. An extensionless document navigation falls back to the export's `index.html`. Missing assets return 404. @@ -138,7 +141,7 @@ PR 2 and PR 3 can proceed in parallel after PR 1. Enabling public sharing needs | Decision | Recommended default | | --- | --- | | Can an active link's expiry be extended? | No. Create a new link. This matches today's rule that deadlines never grow. | -| Password support | Optional per link, set at creation and replaceable or removable later. | +| Password support | Optional per link, at least 8 characters, set at creation and replaceable or removable later. Accept the shared-origin exposure above. | | Copied data after revocation or expiry | Delete the export's files within 24 hours. Keep the Hub record for history. Re-sharing makes a new copy. | | Viewing during a Hub outage | Yes. The reader needs only storage. Revocations made during an outage wait until Hub returns. | | Public hostname | A registrable domain separate from Hub's, so public prototypes are never same-site with Hub. | diff --git a/hub/docs/public-share-reader.md b/hub/docs/public-share-reader.md index edded94fa..0008a5ebe 100644 --- a/hub/docs/public-share-reader.md +++ b/hub/docs/public-share-reader.md @@ -17,7 +17,7 @@ A writer copies every file first, then the manifest, then the policy. The share ## What a viewer sees 1. The viewer opens `https:///s/`. -2. For a password link, the reader asks for the password. Ten wrong attempts within 10 minutes pause that link's password checks on this replica. +2. For a password link, the reader asks for the password. After 10 wrong attempts from one address within 10 minutes, that address must wait. Other viewers are not affected. 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/`. @@ -30,10 +30,10 @@ Every page, asset and `HEAD` request passes these checks before the reader retur - The request uses HTTPS on the configured host. - 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. Directory paths use their `index.html`; 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 read allowance. -- The share is still active after the file read. +- The stored file has the recorded size, is at most 100 MiB, and fits the process's 100 MiB read allowance. Policy and manifest reads use the same allowance. +- The share is still active, and its password unchanged, after the file read. -Each replica keeps a policy for up to 5 seconds, so revocation reaches every replica within 5 seconds. Expiry is compared on every request. Bytes already sent cannot be recalled. +The reader checks the newest 8 share cookies the browser sends. 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`, 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. 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-state-reader/index.ts b/hub/server/domains/public-share-export/create-public-share-state-reader/index.ts index beb5c8418..f165e6868 100644 --- 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 @@ -18,6 +18,8 @@ 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 } @@ -25,15 +27,18 @@ 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() + const manifests = new Map() + let cachedManifestBytes = 0 const pending = new Map>>() async function readJson( @@ -41,22 +46,29 @@ export function createPublicShareStateReader({ kind: "manifest" | "policy", maximumBytes: number, schema: z.ZodType, - ): Promise> { + ): Promise> { const key = publicShareStorageKey(shareId, { kind }) if (!key) return { status: "not-found" } - const stored = await readObject(key, maximumBytes, AbortSignal.timeout(storageTimeout)).catch( - () => ({ status: "unavailable" }) as const, - ) - if (stored.status !== "ok") return stored - let parsed: unknown + // Parsing needs about as much memory again as the bytes, so reserve both. + const release = reserve(maximumBytes * 2) + if (!release) return { status: "unavailable" } try { - parsed = JSON.parse(stored.bytes.toString("utf8")) - } catch { - return { status: "unavailable" } + 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() } - const result = schema.safeParse(parsed) - if (!result.success) return { status: "unavailable" } - return { status: "ok", value: result.data } } // Concurrent requests for one share wait for the same storage read. @@ -72,6 +84,8 @@ export function createPublicShareStateReader({ 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", @@ -79,11 +93,12 @@ export function createPublicShareStateReader({ publicSharePolicySchema, ) if (loaded.status !== "ok") return loaded - if (loaded.value.shareId !== shareId) return { status: "unavailable" } + 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: now() + policyCacheMilliseconds, policy: loaded.value }) - return loaded + policies.set(shareId, { cachedUntil, policy }) + return { status: "ok", value: policy } }) } @@ -92,7 +107,7 @@ export function createPublicShareStateReader({ if (cached) { manifests.delete(shareId) manifests.set(shareId, cached) - return { status: "ok", value: cached } + return { status: "ok", value: cached.manifest } } return once(`manifest:${shareId}`, async () => { const loaded = await readJson( @@ -102,23 +117,39 @@ export function createPublicShareStateReader({ publicShareManifestSchema, ) if (loaded.status !== "ok") return loaded - if (loaded.value.shareId !== shareId) return { status: "unavailable" } - if (manifests.size >= maximumCachedManifests) manifests.delete(manifests.keys().next().value!) - manifests.set(shareId, loaded.value) - 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 (policy.value.state !== "active" || Date.parse(policy.value.expiresAt) <= now()) { - return { status: "inactive" } - } + 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 expire while the manifest loads. + if (!isActive(policy.value)) return { status: "inactive" } return { status: "active", manifest: manifest.value, policy: policy.value } } } diff --git a/hub/server/routes/public-share-reader/index.ts b/hub/server/routes/public-share-reader/index.ts index bb3a7d0b8..d48ff64a8 100644 --- a/hub/server/routes/public-share-reader/index.ts +++ b/hub/server/routes/public-share-reader/index.ts @@ -3,6 +3,7 @@ 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" @@ -20,7 +21,6 @@ import { sendPublicSharePage } from "../../integrations/express/send-public-shar type ActiveShare = Extract const maximumBufferedBytes = 100 * 1024 * 1024 -const minimumReservationBytes = 64 * 1024 const maximumShareCookies = 8 const maximumPasswordFailures = 10 const passwordFailureWindow = 10 * 60 * 1000 @@ -80,10 +80,12 @@ function isDocument(request: Request) { return (request.get("accept") ?? "").includes("text/html") } -// The browser sends every share cookie whose path covers the request; each is checked in turn. +// 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 }[] = [] - for (const pair of request.headers.cookie?.split(";") ?? []) { + 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 @@ -124,22 +126,16 @@ export function createPublicShareReader({ }: PublicShareReaderOptions) { const app = express() const host = new URL(origin).host - const readShare = createPublicShareStateReader({ readObject, policyCacheMilliseconds, now }) + // Files, manifests and policies share one allowance so no kind of read can exhaust memory. + const reserve = createPublicShareByteAllowance(maximumBufferedBytes) + const readShare = createPublicShareStateReader({ + readObject, + policyCacheMilliseconds, + reserve, + now, + }) const passwordFailures = new Map() let passwordChecks = 0 - let bufferedBytes = 0 - - function reserve(byteLength: number) { - const bytes = Math.max(byteLength, minimumReservationBytes) - if (bytes > maximumBufferedBytes - bufferedBytes) return null - bufferedBytes += bytes - let released = false - return () => { - if (released) return - released = true - bufferedBytes -= bytes - } - } function notFound(request: Request, response: Response) { if (isDocument(request)) return sendPublicSharePage(response, 404, { kind: "unavailable" }) @@ -226,8 +222,10 @@ export function createPublicShareReader({ } const password = state.policy.password if (!password) return openShare(response, state) - const failures = passwordFailures.get(shareId) - if (failures && failures.resetAt <= now()) passwordFailures.delete(shareId) + // Failures count per caller, so one caller's guesses cannot lock out other viewers. + const caller = `${request.ip ?? ""} ${shareId}` + const failures = passwordFailures.get(caller) + if (failures && failures.resetAt <= now()) passwordFailures.delete(caller) if ( (failures && failures.resetAt > now() && failures.count >= maximumPasswordFailures) || passwordChecks >= maximumConcurrentPasswordChecks @@ -244,25 +242,31 @@ export function createPublicShareReader({ passwordChecks -= 1 } if (!correct) { - const current = passwordFailures.get(shareId) + const current = passwordFailures.get(caller) if (!current && passwordFailures.size >= 10_000) { passwordFailures.delete(passwordFailures.keys().next().value!) } - passwordFailures.set(shareId, { + passwordFailures.set(caller, { count: (current?.count ?? 0) + 1, resetAt: current?.resetAt ?? now() + passwordFailureWindow, }) return sendPublicSharePage(response, 401, { kind: "password", action, error: "incorrect" }) } - passwordFailures.delete(shareId) - return openShare(response, state) + 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) => { const document = isDocument(request) let unavailable = false - let share: { shareId: string; state: ActiveShare } | null = null + 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 @@ -271,13 +275,13 @@ export function createPublicShareReader({ request.path.startsWith(state.manifest.mount) && proofMatches(proof, createPublicShareProof(state.manifest, state.policy)) ) { - share = { shareId, state } + share = { shareId, proof, state } break } } if (!share) return unavailable ? temporarilyUnavailable(response) : notFound(request, response) - const { shareId, state } = share + const { shareId, proof, state } = share let relative: string try { relative = decodeURIComponent(request.path.slice(state.manifest.mount.length)) @@ -306,20 +310,40 @@ export function createPublicShareReader({ const release = reserve(file.size) if (!release) return temporarilyUnavailable(response) - response.once("close", release) + // Keep the reservation until both the read and the response end, so disconnecting cannot + // admit new reads while this one still holds its buffer. + const disconnected = new AbortController() + let reading = true + let closed = false + response.once("close", () => { + closed = true + disconnected.abort() + if (!reading) release() + }) try { - const stored = await readObject(key, file.size, AbortSignal.timeout(fileReadTimeout)) - if (response.destroyed) return + const stored = await readObject( + key, + file.size, + AbortSignal.any([AbortSignal.timeout(fileReadTimeout), disconnected.signal]), + ) + if (closed) return if (stored.status === "not-found") return notFound(request, response) if (stored.status !== "ok" || stored.bytes.byteLength !== file.size) { return temporarilyUnavailable(response) } - // Revocation or expiry during a slow read stops this response too. + // Revocation, expiry or a password change during a slow read stops this response too. const current = await readShare(shareId) - if (current.status !== "active") return notFound(request, 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 (closed) release() } }) From 13de3e3c5681a54f49c7989ca25a53dc5c4234e0 Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:02:23 -0800 Subject: [PATCH 05/13] test(hub): cover the public share reader and export contract Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../index.test.ts | 161 +++++ .../index.test.ts | 42 ++ .../index.test.ts | 53 ++ .../routes/public-share-reader/index.test.ts | 648 ++++++++++++++++++ .../start-public-share-reader/index.test.ts | 64 ++ 5 files changed, 968 insertions(+) create mode 100644 hub/server/domains/public-share-export/create-public-share-state-reader/index.test.ts create mode 100644 hub/server/domains/public-share-export/read-public-share-reader-settings/index.test.ts create mode 100644 hub/server/integrations/azure-blob/create-public-share-object-reader/index.test.ts create mode 100644 hub/server/routes/public-share-reader/index.test.ts create mode 100644 hub/server/scripts/start-public-share-reader/index.test.ts 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..74f516db6 --- /dev/null +++ b/hub/server/domains/public-share-export/create-public-share-state-reader/index.test.ts @@ -0,0 +1,161 @@ +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("treats a link that expires while its manifest loads as inactive", async () => { + const shareId = randomUUID() + let clock = start + const storage = exportStorage(shareId) + const readShare = createPublicShareStateReader({ + readObject: async (key, maximumBytes, signal) => { + const result = await storage(key, maximumBytes, signal) + if (key.endsWith("manifest.json")) clock = start + 60_000 + return result + }, + 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/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..c9c4eb88c --- /dev/null +++ b/hub/server/domains/public-share-export/read-public-share-reader-settings/index.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vitest" + +import { readPublicShareReaderSettings } from "." + +const environment = { + PUBLIC_SHARE_ORIGIN: "https://share.example.net", + 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({ + origin: "https://share.example.net", + trustedProxyHops: 1, + storage: { provider: "filesystem", directory: "/srv/public-shares" }, + }) + }) + + it.each([ + "HUB_SESSION_SECRET", + "DATABASE_URL", + "TEST_DATABASE_URL", + "ARTIFACT_STORAGE_PROVIDER", + "AZURE_STORAGE_CONNECTION_STRING", + ])("refuses to start with the Hub setting %s", (name) => { + expect(() => readPublicShareReaderSettings({ ...environment, [name]: "" })).toThrow(name) + }) + + it.each([ + "http://share.example.net", + "https://share.example.net/", + "https://share.example.net/s", + "share.example.net", + "", + ])("refuses the origin %j", (origin) => { + expect(() => + readPublicShareReaderSettings({ ...environment, PUBLIC_SHARE_ORIGIN: origin }), + ).toThrow("PUBLIC_SHARE_ORIGIN") + }) +}) 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/routes/public-share-reader/index.test.ts b/hub/server/routes/public-share-reader/index.test.ts new file mode 100644 index 000000000..35ab70ca8 --- /dev/null +++ b/hub/server/routes/public-share-reader/index.test.ts @@ -0,0 +1,648 @@ +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 } 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 { createPublicShareFileObjectReader } from "../../integrations/filesystem/create-public-share-object-reader" +import { createPublicShareReader } from "." + +const origin = "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 + +function digest(value: Buffer) { + return createHash("sha256").update(value).digest("hex") +} + +function cookiePair(header: string) { + return header.split(";")[0]! +} + +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 + 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({ + origin, + trustedProxyHops: 1, + readObject, + policyCacheMilliseconds: options.policyCacheMilliseconds, + 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 cookiePair(opened.headers["set-cookie"]![0]!) + } + + return { shareId, mount: shareMount, root, hashes, writePolicy, open } + } + + return { 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?tab=1", 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?tab=1`) + const cookies = opened.headers["set-cookie"]! + expect(cookies).toHaveLength(2) + expect(cookies[0]).toMatch(new RegExp(`;\\s*Path=${mount}(?:;|$)`, "i")) + expect(cookies[1]).toMatch(new RegExp(`;\\s*Path=/s/${shareId}(?:;|$)`, "i")) + for (const cookie of cookies) { + expect(cookie.startsWith(`__Secure-replica-share-${shareId}=open;`)).toBe(true) + expect(cookie).toMatch(/;\s*HttpOnly\b/i) + expect(cookie).toMatch(/;\s*Secure\b/i) + expect(cookie).toMatch(/;\s*SameSite=Lax\b/i) + expect(cookie).toMatch(/;\s*Max-Age=3600\b/i) + expect(cookie).not.toMatch(/;\s*Domain=/i) + } + const cookie = `hub_session=signed-in; ${cookiePair(cookies[0]!)}` + + const page = await request(`${mount}welcome?tab=1`, { 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 own index.html for its slash and extensionless paths", async () => { + const { request, writeShare } = await startReader() + const docs = "Docs" + const { open } = await writeShare({ "index.html": "root", "docs/index.html": docs }) + const cookie = await open() + + for (const path of ["docs/", "docs"]) { + const response = await request(`${mount}${path}`, { headers: assetHeaders(cookie) }) + expect(response.status).toBe(200) + expect(response.body.toString()).toBe(docs) + } + }) + + 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 thousands of files and a large asset", async () => { + const { request, writeShare } = await startReader() + const large = Buffer.alloc(8 * 1024 * 1024, "a") + const extraManifestFiles = Object.fromEntries( + Array.from({ length: 9_998 }, (_, index) => [ + `assets/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 read allowance until an abandoned file read settles", 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(503) + expect(afterDisconnect.status).toBe(503) + expect((await request(`/s/${other.shareId}`)).status).toBe(303) + }) + + 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([ + ["is revoked", () => Promise.resolve({ state: "revoked" })], + [ + "gets a new password", + async () => ({ password: await hashPublicSharePassword("battery staple") }), + ], + ])("does not send a file when the link %s during its read", async (_name, changes) => { + let change: (() => 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 change?.() + return result + }, + }) + const { writePolicy, open } = await writeShare( + { "index.html": "root", "assets/app.js": "x" }, + { password: await hashPublicSharePassword("correct horse") }, + ) + const cookie = await open("correct horse") + const policyChanges = await changes() + change = () => writePolicy(policyChanges) + + const response = await request(`${mount}assets/app.js`, { headers: assetHeaders(cookie) }) + + expect(response.status).toBe(404) + expect(response.body.toString()).not.toBe("x") + }) + + it.each([ + ["is revoked", () => Promise.resolve({ state: "revoked" })], + [ + "gets a new password", + async () => ({ password: await hashPublicSharePassword("battery staple") }), + ], + ])( + "does not open a password link that %s while the password is checked", + async (_name, changes) => { + let change: (() => 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.endsWith("/policy.json") && change) { + const pending = change + change = null + await pending() + } + return result + }, + }) + const { shareId, writePolicy } = await writeShare( + { "index.html": "root" }, + { password: await hashPublicSharePassword("correct horse") }, + ) + const policyChanges = await changes() + change = () => writePolicy(policyChanges) + + 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(`
`) + expect(form.headers["set-cookie"]).toBeUndefined() + const forged = `__Secure-replica-share-${shareId}=open` + expect((await request(asset, { headers: assetHeaders(forged) })).status).toBe(404) + + const crossOrigin = await request(link, { + method: "POST", + headers: passwordHeaders({ origin: "https://attacker.example" }), + body: "password=correct+horse", + }) + expect(crossOrigin.status).toBe(404) + expect(crossOrigin.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() + + const correct = await request(link, { + method: "POST", + headers: passwordHeaders(), + body: "password=correct+horse", + }) + expect(correct.status).toBe(303) + expect(correct.headers.location).toBe(mount) + const cookie = cookiePair(correct.headers["set-cookie"]![0]!) + 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) + + 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 10 failed password attempts in 10 minutes", 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(), + }) + } + for (let failure = 0; failure < 10; failure += 1) { + expect((await attempt("wrong", "203.0.113.1")).status).toBe(401) + } + + 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(limited.status).toBe(429) + expect(limited.headers["set-cookie"]).toBeUndefined() + expect(otherCaller.status).toBe(303) + expect(afterWindow.status).toBe(303) + }) + + it("serves the newest active share of a mount beside revoked ones", async () => { + const { request, writeShare } = await startReader({ policyCacheMilliseconds: 0 }) + const shares = [] + for (let index = 1; index <= 10; index += 1) { + const share = await writeShare({ "index.html": `share ${index}` }) + shares.push({ ...share, cookie: await share.open() }) + } + const active = shares[8]! + for (const share of shares) { + if (share !== active) await share.writePolicy({ state: "revoked" }) + } + + // Browsers list older cookies first. + const all = await request(mount, { + headers: documentHeaders(shares.map(({ cookie }) => cookie).join("; ")), + }) + const revokedOnly = await request(mount, { headers: documentHeaders(shares[9]!.cookie) }) + const activeOnly = await request(mount, { headers: documentHeaders(active.cookie) }) + expect(all.status).toBe(200) + expect(all.body.toString()).toBe("share 9") + expect(revokedOnly.status).toBe(404) + expect(activeOnly.status).toBe(200) + }) + + 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("refuses other hosts, plain HTTP and service worker requests", async () => { + const { request, writeShare } = await startReader() + const { open } = await writeShare({ "index.html": "root", "assets/sw.js": "self.skip()" }) + const cookie = await open() + const asset = `${mount}assets/sw.js` + expect((await request(asset, { headers: assetHeaders(cookie) })).status).toBe(200) + + for (const headers of [ + { host: "hub.example.com" } as Record, + { "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/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..44aea04a7 --- /dev/null +++ b/hub/server/scripts/start-public-share-reader/index.test.ts @@ -0,0 +1,64 @@ +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/", +] +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, 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([]) + }) +}) From 6351841f879c8923f04fc1876f686d36b2e87f97 Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:08:37 -0800 Subject: [PATCH 06/13] fix(hub): keep public share checks fresh under slow and large reads Refresh the policy after a slow manifest load, give policy and manifest reads their own allowance so a large file cannot block its own checks, reissue a reopened share's cookie so it becomes the newest, and return 503 when the post-read check cannot reach storage. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/adr/0003-public-sharing-export-reader.md | 2 +- hub/docs/public-share-reader.md | 4 +- .../index.test.ts | 40 +++-- .../create-public-share-state-reader/index.ts | 9 +- .../routes/public-share-reader/index.test.ts | 165 ++++++++++++------ .../routes/public-share-reader/index.ts | 15 +- 6 files changed, 157 insertions(+), 78 deletions(-) diff --git a/docs/adr/0003-public-sharing-export-reader.md b/docs/adr/0003-public-sharing-export-reader.md index 1f04d63bd..231087ded 100644 --- a/docs/adr/0003-public-sharing-export-reader.md +++ b/docs/adr/0003-public-sharing-export-reader.md @@ -115,7 +115,7 @@ The reader runs these checks for every request, including assets and `HEAD`: - 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, time out, and share a 100 MiB in-memory allowance per process. A file's reservation lasts until both its read and its response end. +- 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 24 MiB one. A file's reservation lasts until both its read and its response end. - Wrong passwords are limited to 10 per caller address and link in 10 minutes, with at most 4 password checks running at once per replica. Exact files are served first, then a directory's `index.html`. An extensionless document navigation falls back to the export's `index.html`. Missing assets return 404. diff --git a/hub/docs/public-share-reader.md b/hub/docs/public-share-reader.md index 0008a5ebe..ef9ffc1e8 100644 --- a/hub/docs/public-share-reader.md +++ b/hub/docs/public-share-reader.md @@ -30,10 +30,10 @@ Every page, asset and `HEAD` request passes these checks before the reader retur - The request uses HTTPS on the configured host. - 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. Directory paths use their `index.html`; 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 read allowance. Policy and manifest reads use the same allowance. +- 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 24 MiB allowance, so a large file cannot block the checks it depends on. - The share is still active, and its password unchanged, after the file read. -The reader checks the newest 8 share cookies the browser sends. 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. +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`, 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. 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 index 74f516db6..231523f66 100644 --- 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 @@ -106,21 +106,31 @@ describe("createPublicShareStateReader()", () => { await expect(readShare(shareId)).resolves.toEqual({ status: "unavailable" }) }) - it("treats a link that expires while its manifest loads as inactive", async () => { - const shareId = randomUUID() - let clock = start - const storage = exportStorage(shareId) - const readShare = createPublicShareStateReader({ - readObject: async (key, maximumBytes, signal) => { - const result = await storage(key, maximumBytes, signal) - if (key.endsWith("manifest.json")) clock = start + 60_000 - return result - }, - now: () => clock, - }) - - await expect(readShare(shareId)).resolves.toEqual({ status: "inactive" }) - }) + 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() 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 index f165e6868..2ddfe6de7 100644 --- 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 @@ -148,8 +148,11 @@ export function createPublicShareStateReader({ // 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 expire while the manifest loads. - if (!isActive(policy.value)) return { status: "inactive" } - return { status: "active", manifest: manifest.value, policy: policy.value } + // 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/routes/public-share-reader/index.test.ts b/hub/server/routes/public-share-reader/index.test.ts index 35ab70ca8..6aaae92a8 100644 --- a/hub/server/routes/public-share-reader/index.test.ts +++ b/hub/server/routes/public-share-reader/index.test.ts @@ -12,14 +12,38 @@ 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://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") } @@ -28,6 +52,11 @@ 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" } } @@ -167,7 +196,7 @@ async function startReader( }) : await request(`/s/${shareId}`, { headers: { "sec-fetch-dest": "document" } }) expect(opened.status).toBe(303) - return cookiePair(opened.headers["set-cookie"]![0]!) + return openedCookie(opened.headers) } return { shareId, mount: shareMount, root, hashes, writePolicy, open } @@ -192,19 +221,25 @@ describe("createPublicShareReader()", () => { }) expect(opened.status).toBe(303) expect(opened.headers.location).toBe(`${mount}welcome?tab=1`) + // Each path's cookie is cleared, then set, so a reopened cookie becomes the newest. const cookies = opened.headers["set-cookie"]! - expect(cookies).toHaveLength(2) - expect(cookies[0]).toMatch(new RegExp(`;\\s*Path=${mount}(?:;|$)`, "i")) - expect(cookies[1]).toMatch(new RegExp(`;\\s*Path=/s/${shareId}(?:;|$)`, "i")) - for (const cookie of cookies) { - expect(cookie.startsWith(`__Secure-replica-share-${shareId}=open;`)).toBe(true) + 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).toMatch(/;\s*Max-Age=3600\b/i) expect(cookie).not.toMatch(/;\s*Domain=/i) } - const cookie = `hub_session=signed-in; ${cookiePair(cookies[0]!)}` + const cookie = `hub_session=signed-in; ${cookiePair(cookies[1]!)}` const page = await request(`${mount}welcome?tab=1`, { headers: documentHeaders(cookie) }) const asset = await request(`${mount}assets/app.js`, { headers: assetHeaders(cookie) }) @@ -315,7 +350,7 @@ describe("createPublicShareReader()", () => { expect(response.body.equals(large)).toBe(true) }) - it("holds the read allowance until an abandoned file read settles", async () => { + 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({ @@ -350,9 +385,32 @@ describe("createPublicShareReader()", () => { expect((await request(asset, { headers: assetHeaders(cookie) })).status).toBe(200), ) - expect(whileReading.status).toBe(503) + expect(whileReading.status).toBe(303) expect(afterDisconnect.status).toBe(503) - expect((await request(`/s/${other.shareId}`)).status).toBe(303) + }) + + 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 () => { @@ -406,64 +464,57 @@ describe("createPublicShareReader()", () => { expect(link.body.toString()).toContain("This shared prototype isn't available") }) - it.each([ - ["is revoked", () => Promise.resolve({ state: "revoked" })], + it.each<[string, (share: { root: string; writePolicy: WritePolicy }) => Promise, number]>([ + ["is revoked", ({ writePolicy }) => writePolicy({ state: "revoked" }), 404], [ "gets a new password", - async () => ({ password: await hashPublicSharePassword("battery staple") }), + async ({ writePolicy }) => + writePolicy({ password: await hashPublicSharePassword("battery staple") }), + 404, ], - ])("does not send a file when the link %s during its read", async (_name, changes) => { - let change: (() => Promise) | null = null + ["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 change?.() + if (key.includes("/files/")) await afterFileRead?.() return result }, }) - const { writePolicy, open } = await writeShare( + const share = await writeShare( { "index.html": "root", "assets/app.js": "x" }, { password: await hashPublicSharePassword("correct horse") }, ) - const cookie = await open("correct horse") - const policyChanges = await changes() - change = () => writePolicy(policyChanges) + 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(404) + expect(response.status).toBe(status) expect(response.body.toString()).not.toBe("x") }) - it.each([ - ["is revoked", () => Promise.resolve({ state: "revoked" })], + it.each<[string, (writePolicy: WritePolicy) => Promise]>([ + ["is revoked", (writePolicy) => writePolicy({ state: "revoked" })], [ "gets a new password", - async () => ({ password: await hashPublicSharePassword("battery staple") }), + async (writePolicy) => + writePolicy({ password: await hashPublicSharePassword("battery staple") }), ], ])( "does not open a password link that %s while the password is checked", - async (_name, changes) => { - let change: (() => 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.endsWith("/policy.json") && change) { - const pending = change - change = null - await pending() - } - return result - }, - }) + async (_name, change) => { + const { request, writeShare } = await startReader({ policyCacheMilliseconds: 0 }) const { shareId, writePolicy } = await writeShare( { "index.html": "root" }, { password: await hashPublicSharePassword("correct horse") }, ) - const policyChanges = await changes() - change = () => writePolicy(policyChanges) + passwordCheck.after = () => change(writePolicy) + onTestFinished(() => { + passwordCheck.after = null + }) const response = await request(`/s/${shareId}`, { method: "POST", @@ -536,7 +587,7 @@ describe("createPublicShareReader()", () => { }) expect(correct.status).toBe(303) expect(correct.headers.location).toBe(mount) - const cookie = cookiePair(correct.headers["set-cookie"]![0]!) + 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) @@ -578,28 +629,38 @@ describe("createPublicShareReader()", () => { expect(afterWindow.status).toBe(303) }) - it("serves the newest active share of a mount beside revoked ones", async () => { + it("serves the newest active share of a mount, including a reopened older one", async () => { const { request, writeShare } = await startReader({ policyCacheMilliseconds: 0 }) - const shares = [] + 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 active = shares[8]! + const [oldest, , , , , , , , newerActive, newest] = shares for (const share of shares) { - if (share !== active) await share.writePolicy({ state: "revoked" }) + 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("; ") } - // Browsers list older cookies first. - const all = await request(mount, { - headers: documentHeaders(shares.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!])), }) - const revokedOnly = await request(mount, { headers: documentHeaders(shares[9]!.cookie) }) - const activeOnly = await request(mount, { headers: documentHeaders(active.cookie) }) + expect(all.status).toBe(200) expect(all.body.toString()).toBe("share 9") expect(revokedOnly.status).toBe(404) - expect(activeOnly.status).toBe(200) + 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 () => { diff --git a/hub/server/routes/public-share-reader/index.ts b/hub/server/routes/public-share-reader/index.ts index d48ff64a8..78b43cf18 100644 --- a/hub/server/routes/public-share-reader/index.ts +++ b/hub/server/routes/public-share-reader/index.ts @@ -20,7 +20,9 @@ import { sendPublicSharePage } from "../../integrations/express/send-public-shar type ActiveShare = Extract -const maximumBufferedBytes = 100 * 1024 * 1024 +const maximumBufferedFileBytes = 100 * 1024 * 1024 +// Separate from files so a large file read cannot block the policy checks it depends on. +const maximumBufferedMetadataBytes = 24 * 1024 * 1024 const maximumShareCookies = 8 const maximumPasswordFailures = 10 const passwordFailureWindow = 10 * 60 * 1000 @@ -126,12 +128,11 @@ export function createPublicShareReader({ }: PublicShareReaderOptions) { const app = express() const host = new URL(origin).host - // Files, manifests and policies share one allowance so no kind of read can exhaust memory. - const reserve = createPublicShareByteAllowance(maximumBufferedBytes) + const reserve = createPublicShareByteAllowance(maximumBufferedFileBytes) const readShare = createPublicShareStateReader({ readObject, policyCacheMilliseconds, - reserve, + reserve: createPublicShareByteAllowance(maximumBufferedMetadataBytes), now, }) const passwordFailures = new Map() @@ -155,7 +156,10 @@ export function createPublicShareReader({ const proof = createPublicShareProof(manifest, policy) const maxAge = Math.min(Date.parse(policy.expiresAt) - now(), maximumPublicShareCookieLifetime) for (const path of [manifest.mount, `/s/${manifest.shareId}`]) { - response.cookie(name, proof, { httpOnly: true, secure: true, sameSite: "lax", path, maxAge }) + 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) @@ -333,6 +337,7 @@ export function createPublicShareReader({ } // 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)) From 4b41f05bd9cb629a31322ad9f5f2acba8182483a Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:57:07 -0800 Subject: [PATCH 07/13] docs: accept public sharing decisions and the generated reader hostname Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/adr/0003-public-sharing-export-reader.md | 48 ++++++++++++------- 1 file changed, 32 insertions(+), 16 deletions(-) diff --git a/docs/adr/0003-public-sharing-export-reader.md b/docs/adr/0003-public-sharing-export-reader.md index 231087ded..0b950cc77 100644 --- a/docs/adr/0003-public-sharing-export-reader.md +++ b/docs/adr/0003-public-sharing-export-reader.md @@ -1,6 +1,6 @@ # ADR 0003: Public sharing through Hub exports and an isolated reader -Status: proposed on November 29, 2026. The Replica maintainers need to confirm the [open decisions](#open-decisions) before Hub integration starts. +Status: accepted on November 29, 2026, with the [policy decisions](#accepted-policy-decisions) recorded below. ## Context @@ -86,7 +86,7 @@ The share is live only once `policy.json` exists, so a viewer never sees a parti ### URL contract -Recommended: an opaque entry that leads into the Build's own mount on the public origin. +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. @@ -97,7 +97,7 @@ Two shares of one Build use two cookies with the same path. Revoking one leaves 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. -Trade-offs of this choice: +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. @@ -107,11 +107,25 @@ Trade-offs of this choice: 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. PR 3 therefore enables public sharing only when Hub uses a custom domain. Production meets this; Hub's cookies there are host-only on `replica.coreai.design`. + ### Request checks The reader runs these checks for every request, including assets and `HEAD`: -- The host and HTTPS scheme match the configured origin. +- 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. @@ -120,11 +134,11 @@ The reader runs these checks for every request, including assets and `HEAD`: Exact files are served first, then a directory's `index.html`. 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`, `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. +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 according to the retention decision. Private Builds and Hub share records are never deleted. +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 @@ -132,18 +146,20 @@ Hub revokes by overwriting `policy.json` with `state: "revoked"` during the user | --- | --- | --- | | 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; legacy links unchanged | PR 1 contract | -| 3. Terraform and setup wizard | Export storage account and container, reader Container App and identity, container-scoped grants, public hostname, settings on Hub and reader, disabled by default | PR 1 start command and settings | +| 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 | 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. -## Open decisions +## Accepted policy decisions + +The Replica maintainers accepted these on November 29, 2026: -| Decision | Recommended default | +| Decision | Result | | --- | --- | -| Can an active link's expiry be extended? | No. Create a new link. This matches today's rule that deadlines never grow. | -| Password support | Optional per link, at least 8 characters, set at creation and replaceable or removable later. Accept the shared-origin exposure above. | -| Copied data after revocation or expiry | Delete the export's files within 24 hours. Keep the Hub record for history. Re-sharing makes a new copy. | -| Viewing during a Hub outage | Yes. The reader needs only storage. Revocations made during an outage wait until Hub returns. | -| Public hostname | A registrable domain separate from Hub's, so public prototypes are never same-site with Hub. | -| Existing `ShareLink` rows | Leave them on the legacy backend unchanged. Do not convert or redirect them to exports. | -| Visible mount path after opening | Accept it; hiding it needs rewriting or rebuilds. | +| 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). | From f2a770fa3cc1931105fd42ad6c037835560edf63 Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:57:07 -0800 Subject: [PATCH 08/13] feat(hub): accept the reader's generated and custom share hostnames Replace PUBLIC_SHARE_ORIGIN with a required PUBLIC_SHARE_GENERATED_ORIGIN and an optional PUBLIC_SHARE_CUSTOM_ORIGIN, so adding a custom domain keeps existing links working. Password forms must come from the host that received them, and share passwords need at least 8 characters. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- hub/docs/public-share-reader.md | 13 +++--- .../hash-public-share-password/index.test.ts | 21 ++++++++++ .../hash-public-share-password/index.ts | 4 +- .../index.test.ts | 25 ++++++++--- .../index.ts | 31 ++++++++++---- .../routes/public-share-reader/index.test.ts | 41 ++++++++++++++----- .../routes/public-share-reader/index.ts | 13 +++--- .../start-public-share-reader/index.ts | 2 +- 8 files changed, 110 insertions(+), 40 deletions(-) create mode 100644 hub/server/domains/public-share-export/hash-public-share-password/index.test.ts diff --git a/hub/docs/public-share-reader.md b/hub/docs/public-share-reader.md index ef9ffc1e8..5ee194034 100644 --- a/hub/docs/public-share-reader.md +++ b/hub/docs/public-share-reader.md @@ -1,6 +1,6 @@ # 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 open decisions. Existing [Build share links](share-links.md) are unchanged. +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 @@ -12,11 +12,11 @@ Hub will write each share as a self-contained copy. The reader only reads these | `shares//manifest.json` | Version 1 index: `shareId`, the Build's `mount`, start page `entry`, and each package path's `sha256` and `size` | | `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. +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/`. +1. The viewer opens `https:///s/`. 2. For a password link, the reader asks for the password. After 10 wrong attempts from one address within 10 minutes, that address must wait. Other viewers are not affected. 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/`. @@ -27,7 +27,7 @@ Only Builds compiled for their mount work. See [private prototype service](build Every page, asset and `HEAD` request passes these checks before the reader returns a file: -- The request uses HTTPS on the configured host. +- 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. Directory paths use their `index.html`; 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 24 MiB allowance, so a large file cannot block the checks it depends on. @@ -43,7 +43,8 @@ The reader refuses to start when any `HUB_*`, `ARTIFACT_STORAGE_*`, `AZURE_STORA | Setting | Value | | --- | --- | -| `PUBLIC_SHARE_ORIGIN` | Exact HTTPS origin, such as `https://share.example.net` | +| `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 | @@ -51,6 +52,6 @@ The reader refuses to start when any `HUB_*`, `ARTIFACT_STORAGE_*`, `AZURE_STORA | `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. Serve it on a registrable domain separate from Hub's, so shared prototypes are never same-site with Hub. +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. Enable the reader only when Hub uses a custom domain, because every generated `azurecontainerapps.io` hostname is the same site; see [public hostname](../../docs/adr/0003-public-sharing-export-reader.md#public-hostname). The reader imports only its own modules, 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/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..37ada9605 --- /dev/null +++ b/hub/server/domains/public-share-export/hash-public-share-password/index.test.ts @@ -0,0 +1,21 @@ +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) + }) + + // Each of these has fewer than 8 characters after normalization but 8 or more UTF-16 units. + 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 index d64a740f9..1b09bb622 100644 --- 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 @@ -8,8 +8,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 || Buffer.byteLength(password) > 256) { - throw new Error("A share password must contain 1 to 256 bytes.") + 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) => 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 index c9c4eb88c..8464231cf 100644 --- 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 @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest" import { readPublicShareReaderSettings } from "." const environment = { - PUBLIC_SHARE_ORIGIN: "https://share.example.net", + 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", @@ -12,12 +12,27 @@ const environment = { describe("readPublicShareReaderSettings()", () => { it("reads the reader's own settings", () => { expect(readPublicShareReaderSettings(environment)).toEqual({ - origin: "https://share.example.net", + origins: ["https://reader.example.azurecontainerapps.io"], trustedProxyHops: 1, storage: { provider: "filesystem", directory: "/srv/public-shares" }, }) }) + 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", @@ -35,8 +50,8 @@ describe("readPublicShareReaderSettings()", () => { "share.example.net", "", ])("refuses the origin %j", (origin) => { - expect(() => - readPublicShareReaderSettings({ ...environment, PUBLIC_SHARE_ORIGIN: origin }), - ).toThrow("PUBLIC_SHARE_ORIGIN") + for (const name of ["PUBLIC_SHARE_GENERATED_ORIGIN", "PUBLIC_SHARE_CUSTOM_ORIGIN"]) { + expect(() => readPublicShareReaderSettings({ ...environment, [name]: origin })).toThrow(name) + } }) }) 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 index b5e32cc00..ef8594f08 100644 --- 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 @@ -3,7 +3,8 @@ import { z } from "zod" type Environment = Readonly> export type PublicShareReaderSettings = { - origin: string + /** The generated origin first, then the optional custom domain's origin. */ + origins: string[] trustedProxyHops: number storage: | { provider: "filesystem"; directory: string } @@ -19,6 +20,14 @@ export type PublicShareReaderSettings = { const forbiddenSetting = /^(?:HUB_|ARTIFACT_STORAGE_|AZURE_STORAGE_|DATABASE_URL$|TEST_DATABASE_URL$)/ +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) @@ -30,12 +39,16 @@ export function readPublicShareReaderSettings(environment: Environment): PublicS ) } - const origin = environment.PUBLIC_SHARE_ORIGIN ?? "" - const parsed = URL.canParse(origin) ? new URL(origin) : null - if (!parsed || parsed.protocol !== "https:" || parsed.origin !== origin) { - throw new Error( - "PUBLIC_SHARE_ORIGIN must be an exact HTTPS origin, such as https://share.example.net.", - ) + // 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) @@ -55,7 +68,7 @@ export function readPublicShareReaderSettings(environment: Environment): PublicS if (!directory?.startsWith("/") || directory.split("/").some((part) => part === "..")) { throw new Error("PUBLIC_SHARE_STORAGE_DIRECTORY must be an absolute directory.") } - return { origin, trustedProxyHops, storage: { provider, directory } } + return { origins, trustedProxyHops, storage: { provider, directory } } } if (provider === "azure") { if (directory !== undefined) { @@ -71,7 +84,7 @@ export function readPublicShareReaderSettings(environment: Environment): PublicS throw new Error("AZURE_CLIENT_ID must be a managed identity client ID.") } return { - origin, + origins, trustedProxyHops, storage: { provider, diff --git a/hub/server/routes/public-share-reader/index.test.ts b/hub/server/routes/public-share-reader/index.test.ts index 6aaae92a8..e3a7db542 100644 --- a/hub/server/routes/public-share-reader/index.test.ts +++ b/hub/server/routes/public-share-reader/index.test.ts @@ -35,7 +35,8 @@ vi.mock( }, ) -const origin = "https://share.example.net" +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 @@ -82,7 +83,7 @@ async function startReader( const fileReader = createPublicShareFileObjectReader(directory) const readObject = vi.fn(options.wrapRead ? options.wrapRead(fileReader) : fileReader) const app = createPublicShareReader({ - origin, + origins: [origin, customOrigin], trustedProxyHops: 1, readObject, policyCacheMilliseconds: options.policyCacheMilliseconds, @@ -563,13 +564,16 @@ describe("createPublicShareReader()", () => { const forged = `__Secure-replica-share-${shareId}=open` expect((await request(asset, { headers: assetHeaders(forged) })).status).toBe(404) - const crossOrigin = await request(link, { - method: "POST", - headers: passwordHeaders({ origin: "https://attacker.example" }), - body: "password=correct+horse", - }) - expect(crossOrigin.status).toBe(404) - expect(crossOrigin.headers["set-cookie"]).toBeUndefined() + // 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", @@ -591,6 +595,12 @@ describe("createPublicShareReader()", () => { 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") }) @@ -677,15 +687,24 @@ describe("createPublicShareReader()", () => { expect(response.body.toString()).not.toContain("second share") }) - it("refuses other hosts, plain HTTP and service worker requests", async () => { + it("serves the generated and custom hostnames and refuses other hosts, plain HTTP and service worker requests", async () => { const { request, writeShare } = await startReader() - const { open } = await writeShare({ "index.html": "root", "assets/sw.js": "self.skip()" }) + 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" }, diff --git a/hub/server/routes/public-share-reader/index.ts b/hub/server/routes/public-share-reader/index.ts index 78b43cf18..b98215d47 100644 --- a/hub/server/routes/public-share-reader/index.ts +++ b/hub/server/routes/public-share-reader/index.ts @@ -68,8 +68,8 @@ const contentTypes: Record = { } interface PublicShareReaderOptions { - /** Exact HTTPS origin that serves shares, such as https://share.example.net. */ - origin: string + /** Exact HTTPS origins that serve shares: the generated hostname and an optional custom one. */ + origins: readonly string[] trustedProxyHops: number readObject: PublicShareObjectReader policyCacheMilliseconds?: number @@ -120,14 +120,14 @@ function temporarilyUnavailable(response: Response) { /** Serves exported shares read-only. It reads only export storage and never contacts Hub. */ export function createPublicShareReader({ - origin, + origins, trustedProxyHops, readObject, policyCacheMilliseconds, now = Date.now, }: PublicShareReaderOptions) { const app = express() - const host = new URL(origin).host + const hosts = new Set(origins.map((origin) => new URL(origin).host)) const reserve = createPublicShareByteAllowance(maximumBufferedFileBytes) const readShare = createPublicShareStateReader({ readObject, @@ -180,7 +180,7 @@ export function createPublicShareReader({ response.setHeader("Cross-Origin-Opener-Policy", "same-origin") response.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=()") response.setHeader("Content-Security-Policy", contentPolicy) - if (!request.secure || request.get("host") !== host) return response.sendStatus(404) + 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) } @@ -206,7 +206,8 @@ export function createPublicShareReader({ "/s/:shareId", (request, response, next) => { if ( - request.get("origin") !== origin || + // 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) ) diff --git a/hub/server/scripts/start-public-share-reader/index.ts b/hub/server/scripts/start-public-share-reader/index.ts index 4a0420f7b..071f384d4 100644 --- a/hub/server/scripts/start-public-share-reader/index.ts +++ b/hub/server/scripts/start-public-share-reader/index.ts @@ -16,7 +16,7 @@ const readObject = await import("../../integrations/azure-blob/create-public-share-object-reader/index.ts") ).createPublicShareBlobObjectReader(settings.storage) const app = createPublicShareReader({ - origin: settings.origin, + origins: settings.origins, trustedProxyHops: settings.trustedProxyHops, readObject, }) From 31a177a326ae2e0b87b1011f8cdc356bee09cd3e Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:12:56 -0800 Subject: [PATCH 09/13] test(hub): cover the public share reader's Azure and refused settings Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../hash-public-share-password/index.test.ts | 3 +- .../index.test.ts | 63 +++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) 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 index 37ada9605..28723b7eb 100644 --- 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 @@ -11,7 +11,8 @@ describe("hashPublicSharePassword()", () => { ).resolves.toBe(true) }) - // Each of these has fewer than 8 characters after normalization but 8 or more UTF-16 units. + // 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) => { 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 index 8464231cf..aec854d92 100644 --- 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 @@ -18,6 +18,69 @@ describe("readPublicShareReaderSettings()", () => { }) }) + 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({ From 8a11bb0a3981bdd154f928bf2b7520bdcc9e12ab Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:42:11 -0800 Subject: [PATCH 10/13] docs: allow a non-production shared-site override for public sharing Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/adr/0003-public-sharing-export-reader.md | 9 ++++++--- hub/docs/public-share-reader.md | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/adr/0003-public-sharing-export-reader.md b/docs/adr/0003-public-sharing-export-reader.md index 0b950cc77..3667ed395 100644 --- a/docs/adr/0003-public-sharing-export-reader.md +++ b/docs/adr/0003-public-sharing-export-reader.md @@ -119,7 +119,9 @@ Public sharing shares no cookies with Hub. In Production, Hub uses `replica.core - 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. PR 3 therefore enables public sharing only when Hub uses a custom domain. Production meets this; Hub's cookies there are host-only on `replica.coreai.design`. +- 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 @@ -145,8 +147,8 @@ Hub revokes by overwriting `policy.json` with `state: "revoked"` during the user | 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; 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 | PR 1 start command and settings | +| 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. @@ -163,3 +165,4 @@ The Replica maintainers accepted these on November 29, 2026: | 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/public-share-reader.md b/hub/docs/public-share-reader.md index 5ee194034..10842c367 100644 --- a/hub/docs/public-share-reader.md +++ b/hub/docs/public-share-reader.md @@ -52,6 +52,6 @@ The reader refuses to start when any `HUB_*`, `ARTIFACT_STORAGE_*`, `AZURE_STORA | `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. Enable the reader only when Hub uses a custom domain, because every generated `azurecontainerapps.io` hostname is the same site; see [public hostname](../../docs/adr/0003-public-sharing-export-reader.md#public-hostname). +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, Node built-ins, Express, zod and the Azure SDK. A test in `server/scripts/start-public-share-reader/` enforces this boundary. From 0a901d7c07807b4719bc27333f976d9f57834a6f Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:58:32 -0800 Subject: [PATCH 11/13] fix(hub): harden the public share reader after review Allow only the reader's own settings, keep the password form's origin, count password attempts before checking them with a 5-attempt cooldown per visitor and replica, release reservations after early disconnects, drop stalled downloads, accept Build-sized manifests and Hub-normalized start pages, redirect slashless directories, and raise dark-mode alert contrast. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/adr/0003-public-sharing-export-reader.md | 8 +- hub/docs/public-share-reader.md | 14 +- .../index.test.ts | 44 ++++- .../index.ts | 35 +++- .../domains/public-share-export/types.test.ts | 39 ++++ .../domains/public-share-export/types.ts | 34 ++-- .../express/send-public-share-page/index.ts | 15 +- .../routes/public-share-reader/index.test.ts | 183 ++++++++++++++++-- .../routes/public-share-reader/index.ts | 88 ++++++--- .../start-public-share-reader/index.test.ts | 4 +- 10 files changed, 375 insertions(+), 89 deletions(-) create mode 100644 hub/server/domains/public-share-export/types.test.ts diff --git a/docs/adr/0003-public-sharing-export-reader.md b/docs/adr/0003-public-sharing-export-reader.md index 3667ed395..b5a3fc003 100644 --- a/docs/adr/0003-public-sharing-export-reader.md +++ b/docs/adr/0003-public-sharing-export-reader.md @@ -44,7 +44,7 @@ flowchart LR | 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 and other public-share modules. A test enforces that import boundary. +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 rule and other public-share modules. A test enforces that import boundary. ### Storage layout and manifest @@ -131,10 +131,10 @@ The reader runs these checks for every request, including assets and `HEAD`: - 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 24 MiB one. A file's reservation lasts until both its read and its response end. -- Wrong passwords are limited to 10 per caller address and link in 10 minutes, with at most 4 password checks running at once per replica. +- 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`. An extensionless document navigation falls back to the export's `index.html`. Missing assets return 404. +Exact files are served first, then a directory's `index.html`; a directory requested without its trailing slash redirects to add it. 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. diff --git a/hub/docs/public-share-reader.md b/hub/docs/public-share-reader.md index 10842c367..951d32c4d 100644 --- a/hub/docs/public-share-reader.md +++ b/hub/docs/public-share-reader.md @@ -9,7 +9,7 @@ Hub will write each share as a self-contained copy. The reader only reads these | 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 `mount`, start page `entry`, and each package path's `sha256` and `size` | +| `shares//manifest.json` | Version 1 index: `shareId`, the Build's `mount`, 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. @@ -17,7 +17,7 @@ A writer copies every file first, then the manifest, then the policy. The share ## What a viewer sees 1. The viewer opens `https:///s/`. -2. For a password link, the reader asks for the password. After 10 wrong attempts from one address within 10 minutes, that address must wait. Other viewers are not affected. +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/`. @@ -29,17 +29,17 @@ Every page, asset and `HEAD` request passes these checks before the reader retur - 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. Directory paths use their `index.html`; 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 24 MiB allowance, so a large file cannot block the checks it depends on. +- 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`, 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. +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 refuses to start when any `HUB_*`, `ARTIFACT_STORAGE_*`, `AZURE_STORAGE_*`, `DATABASE_URL` or `TEST_DATABASE_URL` setting is present, so it cannot receive Hub credentials or private storage coordinates by mistake. +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. For local runs, start it with only these settings, for example with `env -i`, because developer tokens such as `GH_TOKEN` also stop it. | Setting | Value | | --- | --- | @@ -54,4 +54,4 @@ The reader refuses to start when any `HUB_*`, `ARTIFACT_STORAGE_*`, `AZURE_STORA 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, Node built-ins, Express, zod and the Azure SDK. A test in `server/scripts/start-public-share-reader/` enforces this boundary. +The reader imports only its own modules, Hub's dependency-free start-page rule, 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/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 index aec854d92..f10f9c16c 100644 --- 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 @@ -1,3 +1,5 @@ +import { readFileSync } from "node:fs" + import { describe, expect, it } from "vitest" import { readPublicShareReaderSettings } from "." @@ -102,10 +104,39 @@ describe("readPublicShareReaderSettings()", () => { "TEST_DATABASE_URL", "ARTIFACT_STORAGE_PROVIDER", "AZURE_STORAGE_CONNECTION_STRING", - ])("refuses to start with the Hub setting %s", (name) => { + "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/", @@ -117,4 +148,15 @@ describe("readPublicShareReaderSettings()", () => { 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 index ef8594f08..c6f9d286b 100644 --- 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 @@ -16,9 +16,31 @@ export type PublicShareReaderSettings = { } } -// The reader must never hold Hub credentials or private storage coordinates. +// 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 = - /^(?:HUB_|ARTIFACT_STORAGE_|AZURE_STORAGE_|DATABASE_URL$|TEST_DATABASE_URL$)/ + /^(?: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 @@ -31,11 +53,16 @@ function readOrigin(name: string, 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 && forbiddenSetting.test(name)) + .filter( + (name) => + environment[name] !== undefined && + !permittedSettings.has(name) && + forbiddenSetting.test(name), + ) .sort() if (forbidden.length) { throw new Error( - `The public share reader must not receive Hub settings: ${forbidden.join(", ")}.`, + `The public share reader accepts only its own settings; remove ${forbidden.join(", ")}.`, ) } 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..6ccda398a --- /dev/null +++ b/hub/server/domains/public-share-export/types.test.ts @@ -0,0 +1,39 @@ +import { randomUUID } from "node:crypto" +import { describe, expect, it } from "vitest" + +import { maximumDistFiles } from "../build-artifacts/constants" +import { publicShareManifestSchema } from "./types" + +function manifest(changes: { entry?: string; fileCount?: number } = {}) { + const file = { sha256: "a".repeat(64), size: 1 } + return { + version: 1, + shareId: randomUUID(), + 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(["/%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 index 02176630b..96bfe4e3d 100644 --- a/hub/server/domains/public-share-export/types.ts +++ b/hub/server/domains/public-share-export/types.ts @@ -1,10 +1,17 @@ import { z } from "zod" +import { normalizeStartPage } from "../../utils/normalize-start-page/index.ts" + /** Largest served file, matching the largest file a Build may contain. */ export const maximumPublicShareFileBytes = 100 * 1024 * 1024 -export const maximumPublicShareManifestBytes = 2 * 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 maximumPublicShareFiles = 10_000 export const maximumPublicShareCookieLifetime = 30 * 24 * 60 * 60 * 1000 export const publicShareCookiePrefix = "__Secure-replica-share-" export const openPublicShareProof = "open" @@ -39,32 +46,17 @@ const mount = z ) }) -// The entry is a start page inside the mount. Percent escapes are excluded so the reader never -// has to decide whether an encoded segment leaves the mount. -const entrySegment = /^[A-Za-z0-9_~!$&'()*+,;=:@-][A-Za-z0-9._~!$&'()*+,;=:@-]*$/ -const entryPattern = - /^\/([^?#]*)(\?[A-Za-z0-9._~!$&'()*+,;=:@/?-]*)?(#[A-Za-z0-9._~!$&'()*+,;=:@/?-]*)?$/ +// The entry is a start page inside the mount, accepted exactly as Hub normalizes start pages. const entry = z .string() - .max(1024) - .refine((value) => { - const path = entryPattern.exec(value)?.[1] - if (path === undefined) return false - return ( - !path || - path - .replace(/\/$/, "") - .split("/") - .every((segment) => entrySegment.test(segment)) - ) - }) + .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) <= 2048 && + Buffer.byteLength(value) <= maximumPublicSharePathBytes && !value.includes("\\") && value .split("/") @@ -94,7 +86,7 @@ export const publicShareManifestSchema = z .refine( ({ files }) => Object.keys(files).length <= maximumPublicShareFiles && Object.hasOwn(files, "index.html"), - { message: "A manifest lists at most 10,000 files and includes index.html." }, + { message: "A manifest lists at most 2,000 files and includes index.html." }, ) export const publicSharePasswordSchema = z.strictObject({ diff --git a/hub/server/integrations/express/send-public-share-page/index.ts b/hub/server/integrations/express/send-public-share-page/index.ts index 12b6d6e47..b03fe0db6 100644 --- a/hub/server/integrations/express/send-public-share-page/index.ts +++ b/hub/server/integrations/express/send-public-share-page/index.ts @@ -6,7 +6,7 @@ const pageStyle = "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}}" + "@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'", @@ -16,7 +16,8 @@ const pagePolicy = [ ].join("; ") type Page = - { kind: "unavailable" } | { kind: "password"; action: string; error?: "incorrect" | "busy" } + | { 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) { @@ -29,9 +30,11 @@ export function sendPublicSharePage(response: Response, status: number, page: Pa const message = page.error === "incorrect" ? '

That password isn\'t correct.

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

Too many attempts. Wait a few minutes and try again.

' - : "" + : 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 + @@ -41,6 +44,8 @@ export function sendPublicSharePage(response: Response, status: number, page: Pa '' } 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) diff --git a/hub/server/routes/public-share-reader/index.test.ts b/hub/server/routes/public-share-reader/index.test.ts index e3a7db542..203a982ed 100644 --- a/hub/server/routes/public-share-reader/index.test.ts +++ b/hub/server/routes/public-share-reader/index.test.ts @@ -1,7 +1,12 @@ 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 } from "node:http" +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" @@ -73,6 +78,7 @@ function passwordHeaders(headers: Record = {}) { async function startReader( options: { policyCacheMilliseconds?: number + responseIdleMilliseconds?: number now?: () => number wrapRead?: (read: PublicShareObjectReader) => PublicShareObjectReader } = {}, @@ -87,6 +93,7 @@ async function startReader( trustedProxyHops: 1, readObject, policyCacheMilliseconds: options.policyCacheMilliseconds, + responseIdleMilliseconds: options.responseIdleMilliseconds, now: options.now, }) const server = createServer(app).listen(0, "127.0.0.1") @@ -203,7 +210,7 @@ async function startReader( return { shareId, mount: shareMount, root, hashes, writePolicy, open } } - return { request, writeShare, readObject } + return { server, request, writeShare, readObject } } describe("createPublicShareReader()", () => { @@ -214,14 +221,14 @@ describe("createPublicShareReader()", () => { const script = "console.log('shared')" const { shareId } = await writeShare( { "index.html": html, "assets/app.js": script }, - { entry: "/welcome?tab=1", expiresAt: start + hour }, + { 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?tab=1`) + 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) @@ -242,7 +249,9 @@ describe("createPublicShareReader()", () => { } const cookie = `hub_session=signed-in; ${cookiePair(cookies[1]!)}` - const page = await request(`${mount}welcome?tab=1`, { headers: documentHeaders(cookie) }) + 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) @@ -289,16 +298,29 @@ describe("createPublicShareReader()", () => { expect(missingAsset.body.toString()).not.toContain("App shell") }) - it("serves a directory's own index.html for its slash and extensionless paths", async () => { + 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() - for (const path of ["docs/", "docs"]) { - const response = await request(`${mount}${path}`, { headers: assetHeaders(cookie) }) - expect(response.status).toBe(200) - expect(response.body.toString()).toBe(docs) + 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) } }) @@ -329,12 +351,13 @@ describe("createPublicShareReader()", () => { } }) - it("serves a share with thousands of files and a large asset", async () => { + 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: 9_998 }, (_, index) => [ - `assets/chunk-${index}.js`, + Array.from({ length: 1_998 }, (_, index) => [ + `assets/${"a".repeat(2_000)}/chunk-${index}.js`, { sha256: digest(Buffer.from(String(index))), size: 1 }, ]), ) @@ -390,6 +413,95 @@ describe("createPublicShareReader()", () => { 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") @@ -560,6 +672,8 @@ describe("createPublicShareReader()", () => { 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) @@ -583,6 +697,7 @@ describe("createPublicShareReader()", () => { 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", @@ -591,6 +706,7 @@ describe("createPublicShareReader()", () => { }) 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) @@ -610,7 +726,7 @@ describe("createPublicShareReader()", () => { expect(relocked.body.toString()).toContain(``) }) - it("limits one caller to 10 failed password attempts in 10 minutes", async () => { + 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( @@ -624,17 +740,52 @@ describe("createPublicShareReader()", () => { body: new URLSearchParams({ password }).toString(), }) } - for (let failure = 0; failure < 10; failure += 1) { - expect((await attempt("wrong", "203.0.113.1")).status).toBe(401) + 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) }) diff --git a/hub/server/routes/public-share-reader/index.ts b/hub/server/routes/public-share-reader/index.ts index b98215d47..0c327bb7c 100644 --- a/hub/server/routes/public-share-reader/index.ts +++ b/hub/server/routes/public-share-reader/index.ts @@ -22,9 +22,11 @@ type ActiveShare = Extract const maximumBufferedFileBytes = 100 * 1024 * 1024 // Separate from files so a large file read cannot block the policy checks it depends on. -const maximumBufferedMetadataBytes = 24 * 1024 * 1024 +// Room for two of the largest manifests loading at once. +const maximumBufferedMetadataBytes = 40 * 1024 * 1024 const maximumShareCookies = 8 -const maximumPasswordFailures = 10 +// 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 @@ -73,6 +75,8 @@ interface PublicShareReaderOptions { trustedProxyHops: number readObject: PublicShareObjectReader policyCacheMilliseconds?: number + /** A download that makes no progress for this long is dropped, releasing its allowance. */ + responseIdleMilliseconds?: number now?: () => number } @@ -124,6 +128,7 @@ export function createPublicShareReader({ trustedProxyHops, readObject, policyCacheMilliseconds, + responseIdleMilliseconds = 30_000, now = Date.now, }: PublicShareReaderOptions) { const app = express() @@ -227,37 +232,43 @@ export function createPublicShareReader({ } const password = state.policy.password if (!password) return openShare(response, state) - // Failures count per caller, so one caller's guesses cannot lock out other viewers. + // 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}` - const failures = passwordFailures.get(caller) - if (failures && failures.resetAt <= now()) passwordFailures.delete(caller) - if ( - (failures && failures.resetAt > now() && failures.count >= maximumPasswordFailures) || - passwordChecks >= maximumConcurrentPasswordChecks - ) { + 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) { - const current = passwordFailures.get(caller) - if (!current && passwordFailures.size >= 10_000) { - passwordFailures.delete(passwordFailures.keys().next().value!) - } - passwordFailures.set(caller, { - count: (current?.count ?? 0) + 1, - resetAt: current?.resetAt ?? now() + passwordFailureWindow, - }) return sendPublicSharePage(response, 401, { kind: "password", action, error: "incorrect" }) } - passwordFailures.delete(caller) + 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) @@ -269,6 +280,14 @@ export function createPublicShareReader({ ) 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 @@ -296,6 +315,20 @@ export function createPublicShareReader({ 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" @@ -313,25 +346,20 @@ export function createPublicShareReader({ } if (request.method === "HEAD") return sendFileHeaders(200).end() - const release = reserve(file.size) - if (!release) return temporarilyUnavailable(response) + 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. - const disconnected = new AbortController() - let reading = true - let closed = false - response.once("close", () => { - closed = true - disconnected.abort() - if (!reading) release() - }) + 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 (closed) return + 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) @@ -349,7 +377,7 @@ export function createPublicShareReader({ return temporarilyUnavailable(response) } finally { reading = false - if (closed) release() + if (disconnected.signal.aborted) release() } }) diff --git a/hub/server/scripts/start-public-share-reader/index.test.ts b/hub/server/scripts/start-public-share-reader/index.test.ts index 44aea04a7..30688eac0 100644 --- a/hub/server/scripts/start-public-share-reader/index.test.ts +++ b/hub/server/scripts/start-public-share-reader/index.test.ts @@ -12,6 +12,8 @@ const allowedDirectories = [ "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/", ] const allowedPackages = new Set(["express", "zod", "@azure/identity", "@azure/storage-blob"]) const importPattern = /\b(?:from|import)\s*\(?\s*["']([^"']+)["']/g @@ -41,7 +43,7 @@ function readImportGraph() { } describe("start-public-share-reader", () => { - it("reaches only public share modules, Node built-ins and allowed packages", () => { + it("reaches only public share modules, the start-page rule, Node built-ins and allowed packages", () => { const { modules, packages } = readImportGraph() expect(modules).toEqual( From 19b04cd22cd68512248b88a5a4622ebb89c411fc Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:21:22 -0800 Subject: [PATCH 12/13] test(hub): cover password check failures, busy checks and manifest load room Also show a working local run of the public share reader with env -i. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- hub/docs/public-share-reader.md | 13 ++- .../routes/public-share-reader/index.test.ts | 98 +++++++++++++++++++ 2 files changed, 110 insertions(+), 1 deletion(-) diff --git a/hub/docs/public-share-reader.md b/hub/docs/public-share-reader.md index 951d32c4d..ba92fbbaf 100644 --- a/hub/docs/public-share-reader.md +++ b/hub/docs/public-share-reader.md @@ -39,7 +39,18 @@ Responses send a strict content security policy, deny framing, send `X-Robots-Ta ## 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. For local runs, start it with only these settings, for example with `env -i`, because developer tokens such as `GH_TOKEN` also stop it. +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 | | --- | --- | diff --git a/hub/server/routes/public-share-reader/index.test.ts b/hub/server/routes/public-share-reader/index.test.ts index 203a982ed..b166f1d69 100644 --- a/hub/server/routes/public-share-reader/index.test.ts +++ b/hub/server/routes/public-share-reader/index.test.ts @@ -790,6 +790,104 @@ describe("createPublicShareReader()", () => { 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 }[] = [] From 836dea81c21427a7f38e7ae7b6e811ba49e7e2ab Mon Sep 17 00:00:00 2001 From: Will Eastler <32074613+weastler@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:10:28 -0800 Subject: [PATCH 13/13] fix(hub): redirect a slashless public share mount root to its mount Browsers send share cookies only for the slash-terminated mount, and routers with a base path can reload at the mount without its slash. Redirect that exact path by syntax before reading any share, and accept only private prototype mounts in export manifests. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/adr/0003-public-sharing-export-reader.md | 4 ++-- hub/docs/public-share-reader.md | 6 ++--- .../domains/public-share-export/types.test.ts | 13 +++++++++-- .../domains/public-share-export/types.ts | 22 +++++++------------ .../routes/public-share-reader/index.test.ts | 15 +++++++++++++ .../routes/public-share-reader/index.ts | 11 ++++++++++ .../start-public-share-reader/index.test.ts | 1 + 7 files changed, 51 insertions(+), 21 deletions(-) diff --git a/docs/adr/0003-public-sharing-export-reader.md b/docs/adr/0003-public-sharing-export-reader.md index b5a3fc003..525c28881 100644 --- a/docs/adr/0003-public-sharing-export-reader.md +++ b/docs/adr/0003-public-sharing-export-reader.md @@ -44,7 +44,7 @@ flowchart LR | 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 rule and other public-share modules. A test enforces that import boundary. +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 @@ -134,7 +134,7 @@ The reader runs these checks for every request, including assets and `HEAD`: - 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. An extensionless document navigation falls back to the export's `index.html`. Missing assets return 404. +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. diff --git a/hub/docs/public-share-reader.md b/hub/docs/public-share-reader.md index ba92fbbaf..b45759bfa 100644 --- a/hub/docs/public-share-reader.md +++ b/hub/docs/public-share-reader.md @@ -9,7 +9,7 @@ Hub will write each share as a self-contained copy. The reader only reads these | 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 `mount`, start page `entry` (normalized as Hub normalizes start pages), and each package path's `sha256` and `size`, for at most 2,000 files | +| `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. @@ -19,7 +19,7 @@ A writer copies every file first, then the manifest, then the policy. The share 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/`. +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. @@ -65,4 +65,4 @@ The reader listens on `127.0.0.1:3003` and answers only HTTPS requests for its c 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 rule, Node built-ins, Express, zod and the Azure SDK. A test in `server/scripts/start-public-share-reader/` enforces this boundary. +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/server/domains/public-share-export/types.test.ts b/hub/server/domains/public-share-export/types.test.ts index 6ccda398a..317356d77 100644 --- a/hub/server/domains/public-share-export/types.test.ts +++ b/hub/server/domains/public-share-export/types.test.ts @@ -4,12 +4,12 @@ import { describe, expect, it } from "vitest" import { maximumDistFiles } from "../build-artifacts/constants" import { publicShareManifestSchema } from "./types" -function manifest(changes: { entry?: string; fileCount?: number } = {}) { +function manifest(changes: { mount?: string; entry?: string; fileCount?: number } = {}) { const file = { sha256: "a".repeat(64), size: 1 } return { version: 1, shareId: randomUUID(), - mount: "/previews/github/901/1201/", + mount: changes.mount ?? "/previews/github/901/1201/", entry: changes.entry ?? "/", files: Object.fromEntries( Array.from({ length: changes.fileCount ?? 1 }, (_, index) => [ @@ -30,6 +30,15 @@ describe("publicShareManifestSchema", () => { ).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) => { diff --git a/hub/server/domains/public-share-export/types.ts b/hub/server/domains/public-share-export/types.ts index 96bfe4e3d..5be3eb862 100644 --- a/hub/server/domains/public-share-export/types.ts +++ b/hub/server/domains/public-share-export/types.ts @@ -1,6 +1,7 @@ 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 @@ -31,20 +32,13 @@ function base64url(minimumBytes: number, maximumBytes: number) { }) } -// A mount is the absolute path a Build was compiled for, such as /previews/github/1/2/. -const mountSegment = /^[A-Za-z0-9_~-][A-Za-z0-9._~-]*$/ -const reservedMountRoots = new Set(["s", "health", "__replica-share"]) -const mount = z - .string() - .max(512) - .refine((value) => { - if (!value.startsWith("/") || !value.endsWith("/") || value === "/") return false - const segments = value.slice(1, -1).split("/") - return ( - segments.every((segment) => mountSegment.test(segment)) && - !reservedMountRoots.has(segments[0]!) - ) - }) +// 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 diff --git a/hub/server/routes/public-share-reader/index.test.ts b/hub/server/routes/public-share-reader/index.test.ts index b166f1d69..929056abe 100644 --- a/hub/server/routes/public-share-reader/index.test.ts +++ b/hub/server/routes/public-share-reader/index.test.ts @@ -324,6 +324,21 @@ describe("createPublicShareReader()", () => { } }) + 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({ diff --git a/hub/server/routes/public-share-reader/index.ts b/hub/server/routes/public-share-reader/index.ts index 0c327bb7c..df1551130 100644 --- a/hub/server/routes/public-share-reader/index.ts +++ b/hub/server/routes/public-share-reader/index.ts @@ -17,6 +17,7 @@ import { } 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 @@ -194,6 +195,16 @@ export function createPublicShareReader({ 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) diff --git a/hub/server/scripts/start-public-share-reader/index.test.ts b/hub/server/scripts/start-public-share-reader/index.test.ts index 30688eac0..0a731805c 100644 --- a/hub/server/scripts/start-public-share-reader/index.test.ts +++ b/hub/server/scripts/start-public-share-reader/index.test.ts @@ -14,6 +14,7 @@ const allowedDirectories = [ "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