From 003953c677eddc4deae2c74bb8dc089a69a28306 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sat, 14 Nov 2026 00:18:28 -0800 Subject: [PATCH 1/6] feat(hub): edit registered prototype names Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 1bb10333-1d49-4426-896d-d9a04178b836 --- hub/AGENTS.md | 2 +- hub/docs/architecture.md | 10 +- hub/docs/authentication.md | 2 + hub/docs/frontend.md | 8 +- hub/server/create-app/index.ts | 2 +- .../edit-prototype-metadata/index.ts | 71 +++ hub/server/domains/prototypes/errors.ts | 9 + .../find-prototype-detail/index.ts | 10 +- .../lock-editable-prototype/index.ts | 27 + .../update-prototype-metadata/index.ts | 11 + .../index.ts | 38 ++ hub/server/routes/api/product/types.ts | 7 + .../prototypes/show/get/index.db.test.ts | 1 + .../prototypes/show/patch/index.db.test.ts | 496 ++++++++++++++++++ .../prototypes/show/patch/index.ts | 59 +++ hub/server/routes/index.ts | 7 + 16 files changed, 748 insertions(+), 12 deletions(-) create mode 100644 hub/server/domains/prototypes/edit-prototype-metadata/index.ts create mode 100644 hub/server/domains/prototypes/errors.ts create mode 100644 hub/server/repositories/prototypes/lock-editable-prototype/index.ts create mode 100644 hub/server/repositories/prototypes/update-prototype-metadata/index.ts create mode 100644 hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts create mode 100644 hub/server/routes/api/repositories/prototypes/show/patch/index.ts diff --git a/hub/AGENTS.md b/hub/AGENTS.md index 5381441ee..b3e40702c 100644 --- a/hub/AGENTS.md +++ b/hub/AGENTS.md @@ -10,7 +10,7 @@ Hub is being rebuilt in TypeScript. Read the [root instructions](../AGENTS.md), - [Development](docs/development.md) and [testing](docs/testing-and-operations.md) own local and CI commands. - [Storybook](docs/storybook.md#ui-changes-and-pull-request-evidence) owns presentation coverage, cleanup, and PR screenshots. -Run Node commands from `hub/`, locally or inside the devcontainer. PostgreSQL and Prisma support configured GitHub authentication, administrator enrollment, Hub sessions, and a seeded read-only prototype index; see [authentication](docs/authentication.md). Other prototype APIs and repository-specific permissions are not built. Agree on the design before adding more product models, permissions, deployment choices, or product API routes. +Run Node commands from `hub/`, locally or inside the devcontainer. PostgreSQL and Prisma support configured GitHub authentication, administrator enrollment, Hub sessions, and a seeded prototype index with registered prototype name editing through the API; see [authentication](docs/authentication.md). Other prototype APIs and repository-specific permissions are not built. Agree on the design before adding more product models, permissions, deployment choices, or product API routes. Use `npm run dev:api` to run Hub with local developer sign-in; this is the default choice for trying or testing Hub. Use `npm run dev:api:live` only when the task needs real GitHub or Entra sign-in configured in `.env`. [Development](docs/development.md#start-with-the-real-api) explains both modes. diff --git a/hub/docs/architecture.md b/hub/docs/architecture.md index e3a5aac6a..a72d732f8 100644 --- a/hub/docs/architecture.md +++ b/hub/docs/architecture.md @@ -6,9 +6,9 @@ Hub contributors are rebuilding the app on `build/hub/new` before merging it int The team has chosen TypeScript, Express for the API, React and Vite for the frontend, and Vitest for tests. The old backend and the frontend code that connected to it have been removed rather than rewritten. -The API responds to a health check and gives signed-in members read access to the seeded repository index and prototype details. The frontend connects the retained pages for local exploration. Storybook remains the presentation workbench. +The API responds to a health check and gives signed-in members read access to the seeded repository index and prototype details, plus registered prototype name edits. The frontend connects the retained pages for local exploration. Storybook remains the presentation workbench. -Contributors can use PostgreSQL and Prisma locally or in the devcontainer. The database has a provider-neutral identity transaction foundation with explicit GitHub and single-tenant Microsoft Entra sign-in adapters. A reusable deployment bootstrap secret can enroll a verified provider identity as a Hub administrator. Members can browse a seeded, read-only repository index. The app cannot yet discover real repositories, import Builds, host published previews, edit product data, or support live multi-user reviews. +Contributors can use PostgreSQL and Prisma locally or in the devcontainer. The database has a provider-neutral identity transaction foundation with explicit GitHub and single-tenant Microsoft Entra sign-in adapters. A reusable deployment bootstrap secret can enroll a verified provider identity as a Hub administrator. Members can browse a seeded repository index and edit registered prototype names through the API. The app cannot yet discover real repositories, import Builds, host published previews, or support live multi-user reviews. The [production runtime](deployment.md) serves the built frontend and API and runs both workers in one image. Deployment runs database and job setup separately before starting that image. @@ -20,7 +20,9 @@ API code lives under `server/`. As features are added, route handlers will read The [database guide](database.md) defines the multi-file Prisma schema and shared client in integrations. The health route remains a process check, not a database readiness check. -The [Pino integration](logging.md) writes structured application and HTTP logs to stdout. `createApp()` installs request logging before routes, so new endpoints inherit completion records and server-generated request IDs without explicit logging calls. Authentication routes install their bounded form parsing after origin and rate-limit checks; other routes inherit the shared JSON parser. +The [Pino integration](logging.md) writes structured application and HTTP logs to stdout. `createApp()` installs request logging before routes, so new endpoints inherit completion records and server-generated request IDs without explicit logging calls. Authentication routes install their bounded form parsing after origin and rate-limit checks. Prototype edits check the application origin before bounded JSON parsing, including case and trailing-slash aliases; other routes inherit the shared JSON parser. + +`PATCH /api/repositories/:repositoryId/prototypes/:prototypeId` lets any signed-in member edit a visible registered prototype's name. It trims names, limits them to 255 Unicode characters, and rejects blank names and empty edits. Edits preserve the author and registration time. One transaction locks current session authority and prototype visibility through the write and detail response read, so revocation or lost visibility cannot leave a partial edit. UUID identity and Build relationships remain unchanged. Draft registration, a client editor, description and start-page editing, sharing, and management remain separate work. The API keeps `canEdit: false`. The [background-job foundation](background-jobs.md) uses BullMQ with PostgreSQL and separate on-demand and scheduled worker processes. Setup migrates BullMQ's own schema independently of Prisma. Product processors and schedules are not registered yet. @@ -63,7 +65,7 @@ Imports follow the arrows above. Shared components, hooks, and utilities must no The theme provider wraps routes and their loading and error feedback. -- In real mode, signed-out visitors use the authentication shell. Signed-in members can browse the read-only repository index and open prototype details. Administrators can use `/settings/administrators`, `/settings/sessions`, `/settings/copilot`, and `/settings/audit?scope=hub` through their production APIs without loading provisional product data. +- In real mode, signed-out visitors use the authentication shell. Signed-in members can browse the repository index and open prototype details; the detail editor is not shown yet. Administrators can use `/settings/administrators`, `/settings/sessions`, `/settings/copilot`, and `/settings/audit?scope=hub` through their production APIs without loading provisional product data. - In mock mode, the root reads the simulated session. A nested layout loads the private workspace for signed-in pages. - Route loaders and actions request product data and refresh it after changes. Shareable filters and selections live in the URL. - Product screens keep product-facing copy. API failures remain visible errors. diff --git a/hub/docs/authentication.md b/hub/docs/authentication.md index 251e700f2..8ed3cc185 100644 --- a/hub/docs/authentication.md +++ b/hub/docs/authentication.md @@ -56,6 +56,8 @@ The migration owns the single global revocation row. Its identity and history ar Restoration reads the current revision, locks active provider rows in key order, then share-locks the global revocation row and rechecks the revision before locking membership, assignments, and the session. It checks the revision again before returning authority. Administrator continuation, Copilot changes, and ending all Hub sessions lock provider rows in key order, then lock the global revocation row exclusively before changing state. This serializes mutations with restoration even when bootstrap or administrator authority has no provider row to lock. Those mutations can briefly block restoration and admission. +Prototype name edits acquire provider rows in key order and then share-lock the global revocation row before restoring session authority and locking prototype visibility. They keep those locks through the write and detail read-back. Provider locks can briefly block sign-in, session restoration, and reconciliation; the revocation lock can delay global sign-out. + `GET /api/auth/session` restores the current session and returns its current role plus the membership's provider-neutral presentation identity. `POST /api/auth/session/sign-out` ends it and clears the cookie. Hub does not issue refresh tokens, perform provider logout, or support step-up authentication. ## HTTP boundary diff --git a/hub/docs/frontend.md b/hub/docs/frontend.md index f39d1a0fb..4a1265768 100644 --- a/hub/docs/frontend.md +++ b/hub/docs/frontend.md @@ -1,8 +1,8 @@ # Routed frontend -The Hub frontend uses React Router Framework Mode as a single-page application (SPA) rendered in the browser. In mock mode, it connects the retained pages to local product mocks. In real mode, the repository index, read-only prototype details, administrator roster, and Hub-wide security audit use their production APIs. Creation and branching open the original Copilot app handoff. +The Hub frontend uses React Router Framework Mode as a single-page application (SPA) rendered in the browser. In mock mode, it connects the retained pages to local product mocks. In real mode, the repository index, prototype details, administrator roster, and Hub-wide security audit use their production APIs. Creation and branching open the original Copilot app handoff. -This frontend does not restore the production Hub. Configured GitHub authentication, Hub admission, browser sessions, and a read-only repository index and prototype detail API are available; see [Authentication](authentication.md). The following remain separate backend work: +This frontend does not restore the production Hub. Configured GitHub authentication, Hub admission, browser sessions, a repository index, and a prototype detail API are available; see [Authentication](authentication.md). The following remain separate backend work: - Other product APIs and repository-specific permissions. - External product integrations. @@ -32,7 +32,7 @@ The dataset includes `octocat`, `mona`, additional fictional collaborators, `git In mock mode, the neutral root reads the simulated session. Private pages load their workspace in a separate layout; public shared previews and signed-out pages do not load a private workspace. These provisional product contracts are not adapters for real authentication or authorization. -In real mode, signed-out visitors see the authentication shell without loading provisional session or workspace data. Signed-in members open the first repository or an empty workspace. Administrators can open `/settings/administrators`, `/settings/sessions`, `/settings/copilot`, and `/settings/audit?scope=hub` without loading provisional product workspace data. The sessions page reads current Hub authentication counts, requires explicit confirmation, leaves for fresh authorization through the current session provider, and keeps the signed-out completion result visible after the API ends every Hub session. Sign-in, enrollment, and sign-out forms submit natively to the configured API. Members can search the read-only index, filter it by user, page through 24 prototypes at a time, and open prototype details. The detail API selects the latest successful Build by default; `build` pins another successful Build, and invalid or unavailable selections return 404. Build history and sharing links are unavailable in real mode. Users from other providers are shown by name or login without a GitHub link. Build user metadata may be unknown for older records. Hosted previews and live review remain unavailable, and other real product routes retain explicit API failures. In mock mode, `/` keeps the product entry flow, and `/admin-enrollment` redirects to the mock `/settings/enroll` flow. See [Hub development](development.md) for seed data and access limitations. +In real mode, signed-out visitors see the authentication shell without loading provisional session or workspace data. Signed-in members open the first repository or an empty workspace. Administrators can open `/settings/administrators`, `/settings/sessions`, `/settings/copilot`, and `/settings/audit?scope=hub` without loading provisional product workspace data. The sessions page reads current Hub authentication counts, requires explicit confirmation, leaves for fresh authorization through the current session provider, and keeps the signed-out completion result visible after the API ends every Hub session. Sign-in, enrollment, and sign-out forms submit natively to the configured API. Members can search the index, filter it by user, page through 24 prototypes at a time, and open prototype details. The detail API selects the latest successful Build by default; `build` pins another successful Build, and invalid or unavailable selections return 404. Every signed-in member who can see a registered prototype can `PATCH` its name without changing its author or registration time. Draft registration remains separate work. The real detail page still reports `canEdit: false` and shows no editor. Description and start-page editing, Build history, and sharing links are unavailable in real mode. Users from other providers are shown by name or login without a GitHub link. Build user metadata may be unknown for older records. Hosted previews and live review remain unavailable, and other real product routes retain explicit API failures. In mock mode, `/` keeps the product entry flow, and `/admin-enrollment` redirects to the mock `/settings/enroll` flow. See [Hub development](development.md) for seed data and access limitations. The Build pickers on the prototype and History views list successful, failed, and running Builds with their status. The mock Build history lists all Builds. On these views, successful Builds open the prototype view with `?build=N`; failed and running Builds are plain text because Hub does not store workflow run URLs. The separate share-link picker offers only successful Builds with a preview and keeps selections on the share-links page. @@ -249,7 +249,7 @@ npm run dev:api npm run dev ``` -Run those in separate terminals. `npm run dev:api` uses local developer sign-in; use `npm run dev:api:live` for configured GitHub or Entra sign-in. [Development](development.md#start-with-the-real-api) explains the choice. Real mode proxies `/api` to Express and never starts MSW or falls back to fixtures. Open `/` for sign-in, or `/admin-enrollment` for administrator enrollment. After restoring an administrator session, open `/settings/administrators` for administrator management or `/settings/audit?scope=hub` for Hub-wide security records. Express exposes health, readiness, authentication, administrator-management, security-audit, workspace, repository-index, author-search, and prototype-detail routes. Prototype details are read-only and have no hosted preview yet. Other product routes show explicit API failures until their real endpoints exist. +Run those in separate terminals. `npm run dev:api` uses local developer sign-in; use `npm run dev:api:live` for configured GitHub or Entra sign-in. [Development](development.md#start-with-the-real-api) explains the choice. Real mode proxies `/api` to Express and never starts MSW or falls back to fixtures. Open `/` for sign-in, or `/admin-enrollment` for administrator enrollment. After restoring an administrator session, open `/settings/administrators` for administrator management or `/settings/audit?scope=hub` for Hub-wide security records. Express exposes health, readiness, authentication, administrator-management, security-audit, workspace, repository-index, author-search, and prototype-detail routes, including prototype-detail edits. The real detail page does not show an editor and has no hosted preview yet. Other product routes show explicit API failures until their real endpoints exist. The [authentication guide](authentication.md) owns real sign-in, admission, and session behavior. Those routes and the backend's [telemetry](telemetry.md) and [WebSocket](websockets.md) foundations do not change the provisional mock product contracts. WebSocket upgrades are denied until application access checks are supplied. Mock sign-in and review actions remain local simulations. diff --git a/hub/server/create-app/index.ts b/hub/server/create-app/index.ts index fc6212923..ee3aeb2ab 100644 --- a/hub/server/create-app/index.ts +++ b/hub/server/create-app/index.ts @@ -37,7 +37,7 @@ export function createApp({ authenticationSecurity(), ) app.use( - /^(?!\/api\/copilot-connection(?:\/|$))(?!\/api\/(?:auth|administrators\/authorizations|session-revocation\/authorizations)(?:\/|$)).*/i, + /^(?!\/api\/copilot-connection(?:\/|$))(?!\/api\/(?:auth|administrators\/authorizations|session-revocation\/authorizations)(?:\/|$))(?!\/api\/repositories\/[^/]+\/prototypes\/[^/]+\/?$).*/i, express.json(), ) diff --git a/hub/server/domains/prototypes/edit-prototype-metadata/index.ts b/hub/server/domains/prototypes/edit-prototype-metadata/index.ts new file mode 100644 index 000000000..f8f2185c5 --- /dev/null +++ b/hub/server/domains/prototypes/edit-prototype-metadata/index.ts @@ -0,0 +1,71 @@ +import type { findPrototypeDetail } from "../../../repositories/prototype-index/find-prototype-detail/index.ts" +import type { lockEditablePrototype } from "../../../repositories/prototypes/lock-editable-prototype/index.ts" +import type { updatePrototypeMetadata } from "../../../repositories/prototypes/update-prototype-metadata/index.ts" +import { PrototypeMetadataError } from "../errors.ts" + +type Detail = NonNullable>> + +// Matches the database metadata guard, which also treats NEL as blank. +const space = + "[\\t-\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]" +const edgeSpace = new RegExp(`^${space}+|${space}+$`, "gu") + +export interface PrototypeMetadataChanges { + name?: string | null +} + +export interface PrototypeMetadataRepositories { + restoreSession(sessionDigest: string): Promise<{ userId: string } | null> + lockPrototype(repositoryId: string, prototypeId: string): ReturnType + updatePrototype(id: string, data: Parameters[2]): Promise + findDetail(repositoryId: string, prototypeId: string): Promise +} + +/** Saves metadata without changing the prototype's author or registration. */ +export async function editPrototypeMetadata( + input: { + changes: PrototypeMetadataChanges + prototypeId: string + repositoryId: string + sessionDigest: string + }, + { + runTransaction, + }: { + runTransaction: ( + operation: (repositories: PrototypeMetadataRepositories) => Promise, + ) => Promise + }, +) { + const name = input.changes.name?.replace(edgeSpace, "") + if (!name) throw new PrototypeMetadataError("invalid_input", "Enter a prototype name.") + if (/[\p{Cs}\0]/u.test(name)) { + throw new PrototypeMetadataError( + "invalid_input", + "Remove unsupported characters from the prototype name.", + ) + } + if ([...name].length > 255) { + throw new PrototypeMetadataError( + "invalid_input", + "Use at most 255 characters for the prototype name.", + ) + } + return runTransaction(async (repositories) => { + const viewer = await repositories.restoreSession(input.sessionDigest) + if (!viewer) throw new PrototypeMetadataError("not_signed_in", "Sign in to continue.") + const prototype = await repositories.lockPrototype(input.repositoryId, input.prototypeId) + if (!prototype?.registeredAt) { + throw new PrototypeMetadataError("not_found", "Prototype not found.") + } + + await repositories.updatePrototype(prototype.id, { name }) + const detail = await repositories.findDetail(input.repositoryId, input.prototypeId) + if (!detail) throw new Error("The edited prototype is unavailable.") + const currentViewer = await repositories.restoreSession(input.sessionDigest) + if (!currentViewer || currentViewer.userId !== viewer.userId) { + throw new PrototypeMetadataError("not_signed_in", "Sign in to continue.") + } + return detail + }) +} diff --git a/hub/server/domains/prototypes/errors.ts b/hub/server/domains/prototypes/errors.ts new file mode 100644 index 000000000..2a750de2e --- /dev/null +++ b/hub/server/domains/prototypes/errors.ts @@ -0,0 +1,9 @@ +export class PrototypeMetadataError extends Error { + readonly code: "invalid_input" | "not_found" | "not_signed_in" + + constructor(code: PrototypeMetadataError["code"], message: string) { + super(message) + this.name = "PrototypeMetadataError" + this.code = code + } +} diff --git a/hub/server/repositories/prototype-index/find-prototype-detail/index.ts b/hub/server/repositories/prototype-index/find-prototype-detail/index.ts index 0dfc61047..3f566d9bc 100644 --- a/hub/server/repositories/prototype-index/find-prototype-detail/index.ts +++ b/hub/server/repositories/prototype-index/find-prototype-detail/index.ts @@ -1,9 +1,15 @@ -import type { PrismaClient } from "../../../generated/prisma/client.ts" +import type { Prisma } from "../../../generated/prisma/client.ts" const hiddenBranches = ["replica/install-workflow"] export async function findPrototypeDetail( - database: Pick, + database: { + $transaction( + operation: (transaction: Prisma.TransactionClient) => Promise, + options: { isolationLevel: Prisma.TransactionIsolationLevel }, + ): Promise + repository: Pick + }, repositoryId: string, prototypeId: string, buildNumber?: number, diff --git a/hub/server/repositories/prototypes/lock-editable-prototype/index.ts b/hub/server/repositories/prototypes/lock-editable-prototype/index.ts new file mode 100644 index 000000000..fe4c2002a --- /dev/null +++ b/hub/server/repositories/prototypes/lock-editable-prototype/index.ts @@ -0,0 +1,27 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +/** + * Locks a prototype that the detail page would show. The shared repository + * lock keeps its removal and default branch fixed until the edit commits. + */ +export async function lockEditablePrototype( + database: Pick, + repositoryId: string, + prototypeId: string, +) { + const rows = await database.$queryRaw>` + SELECT + prototype."id", + prototype."registered_at" AS "registeredAt" + FROM "prototypes" prototype + JOIN "repositories" repository ON repository."id" = prototype."repository_id" + WHERE prototype."id" = ${prototypeId}::uuid + AND prototype."repository_id" = ${repositoryId}::uuid + AND repository."removed_at" IS NULL + AND NOT prototype."replica" + AND prototype."branch_name" NOT IN (repository."default_branch", 'replica/install-workflow') + FOR SHARE OF repository + FOR UPDATE OF prototype + ` + return rows[0] ?? null +} diff --git a/hub/server/repositories/prototypes/update-prototype-metadata/index.ts b/hub/server/repositories/prototypes/update-prototype-metadata/index.ts new file mode 100644 index 000000000..2f067753c --- /dev/null +++ b/hub/server/repositories/prototypes/update-prototype-metadata/index.ts @@ -0,0 +1,11 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function updatePrototypeMetadata( + database: Pick, + id: string, + data: { + name: string + }, +) { + return database.prototype.update({ where: { id }, data, select: { id: true } }) +} diff --git a/hub/server/routes/api/product/create-product-route-dependencies/index.ts b/hub/server/routes/api/product/create-product-route-dependencies/index.ts index 8b8651ff2..fbdde613a 100644 --- a/hub/server/routes/api/product/create-product-route-dependencies/index.ts +++ b/hub/server/routes/api/product/create-product-route-dependencies/index.ts @@ -1,8 +1,16 @@ +import { Prisma } from "../../../../generated/prisma/client.ts" +import { restoreHubSession } from "../../../../domains/admission/restore-hub-session/index.ts" +import { runSessionRestoreTransaction } from "../../../../domains/admission/run-session-restore-transaction/index.ts" +import { editPrototypeMetadata } from "../../../../domains/prototypes/edit-prototype-metadata/index.ts" import { prisma } from "../../../../integrations/prisma/index.ts" +import { lockAuthenticationProvidersForSessionAuthority } from "../../../../repositories/authentication-providers/lock-authentication-providers-for-session-authority/index.ts" import { findRepositoryAuthors } from "../../../../repositories/prototype-index/find-repository-authors/index.ts" import { findRepositoryIndex } from "../../../../repositories/prototype-index/find-repository-index/index.ts" import { findPrototypeDetail } from "../../../../repositories/prototype-index/find-prototype-detail/index.ts" import { listRepositories } from "../../../../repositories/prototype-index/list-repositories/index.ts" +import { lockEditablePrototype } from "../../../../repositories/prototypes/lock-editable-prototype/index.ts" +import { updatePrototypeMetadata } from "../../../../repositories/prototypes/update-prototype-metadata/index.ts" +import { lockSessionRevocationState } from "../../../../repositories/session-revocation-states/lock-session-revocation-state/index.ts" import type { ProductRouteDependencies } from "../types.ts" export function createProductRouteDependencies(): ProductRouteDependencies { @@ -14,5 +22,35 @@ export function createProductRouteDependencies(): ProductRouteDependencies { findPrototypeDetail(prisma, repositoryId, prototypeId, buildNumber), findRepositoryAuthors: (repositoryId, filters) => findRepositoryAuthors(prisma, repositoryId, filters), + editPrototypeMetadata: (input) => + editPrototypeMetadata(input, { + runTransaction: (operation) => + prisma.$transaction( + async (transaction) => { + await lockAuthenticationProvidersForSessionAuthority(transaction) + await lockSessionRevocationState(transaction) + // Keep these reads in this transaction so authority and prototype locks remain + // held through the read-back. + const joined = { + $transaction: ( + read: (client: Prisma.TransactionClient) => Promise, + ) => read(transaction), + repository: transaction.repository, + } + return operation({ + restoreSession: (digest) => + restoreHubSession(digest, { + runTransaction: (restore) => runSessionRestoreTransaction(joined, restore), + }), + lockPrototype: (repositoryId, prototypeId) => + lockEditablePrototype(transaction, repositoryId, prototypeId), + updatePrototype: (id, data) => updatePrototypeMetadata(transaction, id, data), + findDetail: (repositoryId, prototypeId) => + findPrototypeDetail(joined, repositoryId, prototypeId), + }) + }, + { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted }, + ), + }), } } diff --git a/hub/server/routes/api/product/types.ts b/hub/server/routes/api/product/types.ts index 5c42a7603..25c2f00b3 100644 --- a/hub/server/routes/api/product/types.ts +++ b/hub/server/routes/api/product/types.ts @@ -1,3 +1,4 @@ +import type { PrototypeMetadataChanges } from "../../../domains/prototypes/edit-prototype-metadata/index.ts" import type { findRepositoryAuthors, RepositoryAuthorsFilters, @@ -24,4 +25,10 @@ export interface ProductRouteDependencies { repositoryId: string, filters: RepositoryAuthorsFilters, ): ReturnType + editPrototypeMetadata(input: { + changes: PrototypeMetadataChanges + prototypeId: string + repositoryId: string + sessionDigest: string + }): Promise>>> } diff --git a/hub/server/routes/api/repositories/prototypes/show/get/index.db.test.ts b/hub/server/routes/api/repositories/prototypes/show/get/index.db.test.ts index 06c1e116b..f19d3cec2 100644 --- a/hub/server/routes/api/repositories/prototypes/show/get/index.db.test.ts +++ b/hub/server/routes/api/repositories/prototypes/show/get/index.db.test.ts @@ -236,6 +236,7 @@ describe("prototype detail API", () => { expect(unregisteredDetail.prototype).toMatchObject({ name: "prototype/unregistered", branchName: "prototype/unregistered", + canEdit: false, }) const deletedResponse = await fetch( diff --git a/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts b/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts new file mode 100644 index 000000000..2567afe8c --- /dev/null +++ b/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts @@ -0,0 +1,496 @@ +import { createHash, randomBytes, randomUUID } from "node:crypto" +import { once } from "node:events" +import { createServer } from "node:http" +import type { AddressInfo } from "node:net" +import pg from "pg" +import { describe, expect, it, onTestFinished, vi } from "vitest" + +import { getDatabaseUrl } from "../../../../../../../test/database/get-database-url" +import { waitForBlockedQuery } from "../../../../../../../test/database/wait-for-blocked-query" +import { waitForDatabaseLock } from "../../../../../../../test/database/wait-for-database-lock" +import { createApp } from "../../../../../../create-app" +import { endAllHubSessions } from "../../../../../../domains/session-revocation/end-all-hub-sessions/index.ts" +import { prisma } from "../../../../../../integrations/prisma" +import { createAuthenticationRouteDependencies } from "../../../../auth/create-authentication-route-dependencies" +import { createProductRouteDependencies } from "../../../../product/create-product-route-dependencies" + +const origin = "http://127.0.0.1:5173" + +async function openServer() { + const authentication = await createAuthenticationRouteDependencies({ + GITHUB_CLIENT_ID: "test-client", + GITHUB_CLIENT_SECRET: "test-secret", + GITHUB_PROVIDER_REVISION: "1", + HUB_APPLICATION_ORIGIN: origin, + HUB_AUTHENTICATION_ENCRYPTION_KEY: randomBytes(32).toString("base64"), + HUB_BOOTSTRAP_SECRET: "test-bootstrap-secret-at-least-32-characters", + }) + const server = createServer( + createApp({ authentication, product: createProductRouteDependencies() }), + ) + server.listen(0, "127.0.0.1") + await once(server, "listening") + onTestFinished( + () => + new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())) + }), + ) + const { port } = server.address() as AddressInfo + return { authentication, url: `http://127.0.0.1:${port}` } +} + +async function createMember(options: { administrator?: boolean; expiresAt?: Date } = {}) { + const provider = await prisma.authenticationProvider.findUniqueOrThrow({ + where: { key: "github" }, + }) + const user = await prisma.user.create({ + data: { profile: { create: { provider: "github", login: randomUUID() } } }, + }) + const identity = await prisma.externalIdentity.create({ + data: { userId: user.id, provider: "github", issuer: "https://github.com", subject: user.id }, + }) + const membership = await prisma.membership.create({ data: { userId: user.id } }) + const assignment = await prisma.membershipAssignment.create({ + data: { + membershipId: membership.id, + externalIdentityId: identity.id, + ...(options.administrator + ? { source: "BOOTSTRAP" as const, role: "ADMINISTRATOR" as const } + : { + providerRevisionId: provider.selectedRevisionId, + providerAssignmentSubject: identity.subject, + source: "AUTHENTICATION_PROVIDER" as const, + role: "MEMBER" as const, + }), + }, + }) + const token = randomUUID() + const session = await prisma.hubSession.create({ + data: { + membershipId: membership.id, + externalIdentityId: identity.id, + providerRevisionId: provider.selectedRevisionId, + digest: createHash("sha256").update(token).digest("hex"), + revocationRevision: 0, + expiresAt: options.expiresAt ?? new Date("2099-01-01T00:00:00Z"), + }, + }) + return { user, membership, assignment, session, token } +} + +async function createPrototype( + serverUrl: string, + branchName: string, + options: { authorId?: string; draft?: boolean; name?: string } = {}, +) { + const repository = await prisma.repository.create({ + data: { nameWithOwner: "team/design", defaultBranch: "main" }, + }) + const prototype = await prisma.prototype.create({ + data: { + repositoryId: repository.id, + branchName, + ...(options.draft + ? {} + : { + authorId: options.authorId, + name: options.name ?? branchName, + registeredAt: new Date("2026-10-01T00:00:00Z"), + }), + }, + }) + const url = `${serverUrl}/api/repositories/${repository.id}/prototypes/${prototype.id}` + return { repository, prototype, url } +} + +function readPrototype(id: string) { + return prisma.prototype.findUniqueOrThrow({ where: { id } }) +} + +function patch(url: string, token: string, body: unknown) { + return fetch(url, { + method: "PATCH", + headers: { origin, cookie: `hub_session=${token}`, "content-type": "application/json" }, + body: JSON.stringify(body), + }) +} + +describe("prototype PATCH API", () => { + it("renames a registered prototype and preserves its author, identity and Builds", async () => { + const server = await openServer() + const first = await createMember() + const second = await createMember() + const { repository, prototype, url } = await createPrototype( + server.url, + "prototype/registered", + { authorId: first.user.id, name: "Original" }, + ) + const build = await prisma.build.create({ + data: { prototypeId: prototype.id, number: 1, state: "successful" }, + }) + await prisma.prototype.update({ + where: { id: prototype.id }, + data: { currentBuildId: build.id }, + }) + const visible = await fetch(url, { headers: { cookie: `hub_session=${first.token}` } }) + expect(visible.status).toBe(200) + + const renamed = await patch(url, first.token, { name: " \u2003Welcome\u00a0 " }) + expect(renamed.status).toBe(200) + expect(await renamed.json()).toMatchObject({ + prototype: { + id: prototype.id, + repositoryId: repository.id, + name: "Welcome", + description: null, + canEdit: false, + }, + selectedBuild: { number: 1, prototypeId: prototype.id }, + }) + const registration = await readPrototype(prototype.id) + expect(registration).toMatchObject({ + authorId: first.user.id, + registeredAt: prototype.registeredAt, + name: "Welcome", + }) + + const updated = await patch(url, second.token, { name: "Renamed" }) + expect(updated.status).toBe(200) + expect(await updated.json()).toMatchObject({ + prototype: { name: "Renamed", description: null }, + }) + expect(await readPrototype(prototype.id)).toMatchObject({ + id: prototype.id, + authorId: first.user.id, + registeredAt: registration.registeredAt, + createdAt: prototype.createdAt, + branchName: prototype.branchName, + currentBuildId: build.id, + }) + expect(await prisma.build.findUniqueOrThrow({ where: { id: build.id } })).toEqual(build) + }) + + it("accepts Unicode name limits and rejects invalid edits without changing a prototype", async () => { + const server = await openServer() + const member = await createMember() + const { prototype, url } = await createPrototype(server.url, "prototype/limits") + + const empty = await patch(url, member.token, {}) + expect(empty.status).toBe(400) + const blankName = await patch(url, member.token, { name: "\u0085\u00a0\u2003 " }) + expect(blankName.status).toBe(400) + const longName = await patch(url, member.token, { name: "😀".repeat(256) }) + expect(longName.status).toBe(400) + expect(await readPrototype(prototype.id)).toEqual(prototype) + + const maximum = await patch(url, member.token, { name: ` ${"😀".repeat(255)} ` }) + expect(maximum.status).toBe(200) + expect(await maximum.json()).toMatchObject({ + prototype: { name: "😀".repeat(255) }, + }) + const saved = await readPrototype(prototype.id) + const blankRegistered = await patch(url, member.token, { name: " " }) + expect(blankRegistered.status).toBe(400) + expect(await readPrototype(prototype.id)).toEqual(saved) + }) + + it("uses detail visibility and preserves unknown first authors on retired branches", async () => { + const server = await openServer() + const member = await createMember() + const repository = await prisma.repository.create({ + data: { nameWithOwner: "team/design", defaultBranch: "trunk" }, + }) + const registeredAt = new Date("2026-10-01T00:00:00Z") + const retired = await prisma.prototype.create({ + data: { + repositoryId: repository.id, + branchName: "prototype/retired", + name: "Retired", + registeredAt, + branchDeletedAt: new Date("2026-10-02T00:00:00Z"), + }, + }) + const retiredUrl = `${server.url}/api/repositories/${repository.id}/prototypes/${retired.id}` + const response = await patch(retiredUrl, member.token, { name: "Edited" }) + expect(response.status).toBe(200) + expect(await readPrototype(retired.id)).toMatchObject({ + authorId: null, + registeredAt, + branchDeletedAt: retired.branchDeletedAt, + }) + const hidden = await prisma.prototype.createManyAndReturn({ + data: [ + { repositoryId: repository.id, branchName: "trunk" }, + { repositoryId: repository.id, branchName: "replica/install-workflow" }, + { repositoryId: repository.id, branchName: "replica/internal", replica: true }, + ], + }) + for (const prototype of hidden) { + const denied = await patch( + `${server.url}/api/repositories/${repository.id}/prototypes/${prototype.id}`, + member.token, + { name: "Changed" }, + ) + expect(denied.status).toBe(404) + expect(await readPrototype(prototype.id)).toEqual(prototype) + } + const other = await prisma.repository.create({ + data: { nameWithOwner: "team/other", defaultBranch: "main" }, + }) + const wrongRepository = await patch( + `${server.url}/api/repositories/${other.id}/prototypes/${retired.id}`, + member.token, + { name: "Wrong repository" }, + ) + expect(wrongRepository.status).toBe(404) + await prisma.repository.update({ + where: { id: repository.id }, + data: { removedAt: new Date() }, + }) + const removedRepository = await patch(retiredUrl, member.token, { + name: "Removed repository", + }) + expect(removedRepository.status).toBe(404) + expect((await readPrototype(retired.id)).name).toBe("Edited") + }) + + it("checks origin before JSON parsing for every Express alias", async () => { + const server = await openServer() + const restore = vi.spyOn(server.authentication.currentSession, "restore") + const path = `/api/repositories/${randomUUID()}/prototypes/${randomUUID()}` + for (const address of [path, `${path.toUpperCase()}/`]) { + const response = await fetch(`${server.url}${address}`, { + method: "PATCH", + headers: { origin: "https://other.example.test", "content-type": "application/json" }, + body: "{", + }) + expect(response.status).toBe(403) + } + expect(restore).not.toHaveBeenCalled() + const malformed = await fetch(`${server.url}${path}`, { + method: "PATCH", + headers: { origin, "content-type": "application/json" }, + body: "{", + }) + expect(malformed.status).toBe(400) + }) + + it("rolls back metadata and repository changes when the prototype becomes unavailable", async () => { + const server = await openServer() + const member = await createMember() + const { prototype, repository, url } = await createPrototype(server.url, "prototype/rollback") + const database = new pg.Client({ connectionString: getDatabaseUrl() }) + await database.connect() + const trigger = `hide_repository_${randomUUID().replaceAll("-", "")}` + try { + await database.query(` + CREATE FUNCTION "${trigger}"() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + UPDATE repositories + SET removed_at = clock_timestamp(), updated_at = clock_timestamp() + WHERE id = NEW.repository_id; + RETURN NEW; + END $$; + CREATE TRIGGER "${trigger}" AFTER UPDATE ON prototypes + FOR EACH ROW EXECUTE FUNCTION "${trigger}"(); + `) + const response = await patch(url, member.token, { name: "Changed" }) + expect(response.status).toBe(500) + expect(await readPrototype(prototype.id)).toEqual(prototype) + expect(await prisma.repository.findUniqueOrThrow({ where: { id: repository.id } })).toEqual( + repository, + ) + } finally { + await database.query( + `DROP TRIGGER IF EXISTS "${trigger}" ON prototypes; DROP FUNCTION IF EXISTS "${trigger}"()`, + ) + await database.end() + } + }) + + it("rejects an edit when its session expires while waiting for the prototype lock", async () => { + const server = await openServer() + const expiresAt = new Date(Date.now() + 3_000) + const member = await createMember({ expiresAt }) + const { prototype, url } = await createPrototype(server.url, "prototype/session-expiry") + const database = new pg.Client({ connectionString: getDatabaseUrl() }) + await database.connect() + let transactionOpen = false + let edit: Promise | null = null + try { + await database.query("BEGIN") + transactionOpen = true + await database.query("SELECT id FROM prototypes WHERE id = $1 FOR UPDATE", [prototype.id]) + edit = patch(url, member.token, { name: "Expired" }) + await waitForDatabaseLock(getDatabaseUrl()) + await new Promise((resolve) => + setTimeout(resolve, Math.max(0, expiresAt.getTime() - Date.now() + 100)), + ) + await database.query("COMMIT") + transactionOpen = false + expect((await edit).status).toBe(401) + expect(await readPrototype(prototype.id)).toEqual(prototype) + } finally { + if (transactionOpen) await database.query("ROLLBACK") + if (edit) await Promise.allSettled([edit]) + await database.end() + } + }) + + it("commits an edit before global session revocation waiting on its lock", async () => { + const server = await openServer() + const member = await createMember() + const { prototype, url } = await createPrototype(server.url, "prototype/session-revocation") + const database = new pg.Client({ connectionString: getDatabaseUrl() }) + const revoker = new pg.Client({ connectionString: getDatabaseUrl() }) + await Promise.all([database.connect(), revoker.connect()]) + let transactionOpen = false + let edit: Promise | null = null + let revisionUpdate: Promise | null = null + try { + await database.query("BEGIN") + transactionOpen = true + await database.query("SELECT id FROM prototypes WHERE id = $1 FOR UPDATE", [prototype.id]) + edit = patch(url, member.token, { name: "Before revocation" }) + await waitForDatabaseLock(getDatabaseUrl()) + revisionUpdate = revoker.query(` + UPDATE session_revocation_states + SET revision = revision + 1, updated_at = clock_timestamp() + WHERE key = 'global' + RETURNING revision + `) + await vi.waitFor(async () => { + const waiting = await database.query<{ blocked: boolean }>( + `SELECT EXISTS ( + SELECT 1 FROM pg_stat_activity + WHERE datname = current_database() + AND wait_event_type = 'Lock' + AND query LIKE '%UPDATE session_revocation_states%' + ) AS blocked`, + ) + expect(waiting.rows[0]?.blocked).toBe(true) + }) + await database.query("COMMIT") + transactionOpen = false + expect((await edit).status).toBe(200) + await revisionUpdate + const saved = await readPrototype(prototype.id) + expect(saved.name).toBe("Before revocation") + expect((await patch(url, member.token, { name: "After revocation" })).status).toBe(401) + expect(await readPrototype(prototype.id)).toEqual(saved) + } finally { + if (transactionOpen) await database.query("ROLLBACK") + if (edit) await Promise.allSettled([edit]) + if (revisionUpdate) await Promise.allSettled([revisionUpdate]) + await Promise.all([database.end(), revoker.end()]) + } + }) + + it("rejects missing sessions and session or assignment revocation after initial authentication", async () => { + const server = await openServer() + const member = await createMember() + const { prototype, url } = await createPrototype(server.url, "prototype/private") + expect((await patch(url, "", { name: "Changed" })).status).toBe(401) + const restore = server.authentication.currentSession.restore.bind( + server.authentication.currentSession, + ) + const restoreSpy = vi.spyOn(server.authentication.currentSession, "restore") + restoreSpy.mockImplementationOnce(async (digest) => { + const current = await restore(digest) + await prisma.hubSession.update({ + where: { id: member.session.id }, + data: { endedAt: new Date() }, + }) + return current + }) + expect((await patch(url, member.token, { name: "Changed" })).status).toBe(401) + expect(await readPrototype(prototype.id)).toEqual(prototype) + + const other = await createMember() + restoreSpy.mockImplementationOnce(async (digest) => { + const current = await restore(digest) + await prisma.membershipAssignment.update({ + where: { id: other.assignment.id }, + data: { lifecycle: "REVOKED" }, + }) + return current + }) + expect((await patch(url, other.token, { name: "Changed" })).status).toBe(401) + expect(await readPrototype(prototype.id)).toEqual(prototype) + }) + + it("does not edit a draft before registration is enabled", async () => { + const server = await openServer() + const member = await createMember() + const { prototype, url } = await createPrototype(server.url, "prototype/draft", { + draft: true, + }) + const denied = await patch(url, member.token, { name: "Must remain a draft" }) + expect(denied.status).toBe(404) + expect(await readPrototype(prototype.id)).toEqual(prototype) + }) + + it("denies an admin edit blocked behind successful session revocation", async () => { + const server = await openServer() + const admin = await createMember({ administrator: true }) + const { prototype, url } = await createPrototype(server.url, "prototype/admin-revocation") + const { revision } = await prisma.sessionRevocationState.findUniqueOrThrow({ + select: { revision: true }, + where: { key: "global" }, + }) + const authorizationId = randomUUID() + await prisma.sensitiveAuthorization.create({ + data: { + actorMembershipId: admin.membership.id, + expiresAt: new Date(Date.now() + 60_000), + externalIdentityId: admin.assignment.externalIdentityId, + hubSessionId: admin.session.id, + id: authorizationId, + operation: "END_ALL_HUB_SESSIONS", + targetMembershipIds: [], + verifiedAt: new Date(), + }, + }) + const viewer = await server.authentication.currentSession.restore( + createHash("sha256").update(admin.token).digest("hex"), + ) + expect(viewer).toMatchObject({ membershipId: admin.membership.id }) + const blocker = new pg.Client({ connectionString: getDatabaseUrl() }) + const inspector = new pg.Client({ connectionString: getDatabaseUrl() }) + await Promise.all([blocker.connect(), inspector.connect()]) + let blockerOpen = false + let revocation: ReturnType | null = null + let edit: Promise | null = null + try { + await blocker.query("BEGIN") + blockerOpen = true + await blocker.query("SELECT id FROM hub_sessions WHERE id = $1 FOR UPDATE", [ + admin.session.id, + ]) + const { pid: blockerPid } = ( + await blocker.query<{ pid: number }>("SELECT pg_backend_pid() AS pid") + ).rows[0]! + revocation = endAllHubSessions(prisma, { + authorizationId, + hubSessionId: admin.session.id, + }) + const revocationPid = await waitForBlockedQuery(inspector, blockerPid, "hub_sessions") + + vi.spyOn(server.authentication.currentSession, "restore").mockResolvedValueOnce(viewer) + edit = patch(url, admin.token, { name: "Must not commit" }) + await waitForBlockedQuery(inspector, revocationPid, "authentication_providers") + + await blocker.query("COMMIT") + blockerOpen = false + await expect(revocation).resolves.toMatchObject({ revision: revision + 1 }) + expect((await edit).status).toBe(401) + expect(await readPrototype(prototype.id)).toEqual(prototype) + } finally { + if (blockerOpen) await blocker.query("ROLLBACK") + if (revocation) await Promise.allSettled([revocation]) + if (edit) await Promise.allSettled([edit]) + await Promise.all([blocker.end(), inspector.end()]) + } + }, 20_000) +}) diff --git a/hub/server/routes/api/repositories/prototypes/show/patch/index.ts b/hub/server/routes/api/repositories/prototypes/show/patch/index.ts new file mode 100644 index 000000000..871fb2260 --- /dev/null +++ b/hub/server/routes/api/repositories/prototypes/show/patch/index.ts @@ -0,0 +1,59 @@ +import type { RequestHandler } from "express" +import { z } from "zod" + +import { hashAuthenticationValue } from "../../../../../../domains/authentication/hash-authentication-value/index.ts" +import { PrototypeMetadataError } from "../../../../../../domains/prototypes/errors.ts" +import { hubSessionCookieName } from "../../../../../../integrations/express/hub-session-cookie-name/index.ts" +import { readCookie } from "../../../../../../integrations/express/read-cookie/index.ts" +import type { CurrentSessionDependencies } from "../../../../auth/types.ts" +import { readProductSession } from "../../../../product/read-product-session/index.ts" +import type { ProductRouteDependencies } from "../../../../product/types.ts" + +const bodySchema = z + .object({ + name: z.string().nullable().optional(), + }) + .strict() + +const errorStatus = { invalid_input: 400, not_found: 404, not_signed_in: 401 } as const + +export function patch( + session: CurrentSessionDependencies, + product: ProductRouteDependencies, +): RequestHandler { + return async (request, response, next) => { + try { + const cookie = readCookie(request, hubSessionCookieName) + if (!cookie || !(await readProductSession(cookie, session))) { + response.status(401).json({ error: "Sign in to continue." }) + return + } + + const repositoryId = z.uuid().safeParse(request.params.repositoryId) + const prototypeId = z.uuid().safeParse(request.params.prototypeId) + if (!repositoryId.success || !prototypeId.success) { + response.status(400).json({ error: "Enter a valid prototype address." }) + return + } + const changes = bodySchema.safeParse(request.body) + if (!changes.success || Object.keys(changes.data).length === 0) { + response.status(400).json({ error: "Send a prototype name." }) + return + } + + const detail = await product.editPrototypeMetadata({ + changes: changes.data, + prototypeId: prototypeId.data, + repositoryId: repositoryId.data, + sessionDigest: hashAuthenticationValue(cookie), + }) + response.json({ ...detail, showPrototypeInfo: false }) + } catch (error) { + if (error instanceof PrototypeMetadataError) { + response.status(errorStatus[error.code]).json({ error: error.message }) + return + } + next(error) + } + } +} diff --git a/hub/server/routes/index.ts b/hub/server/routes/index.ts index 54e667cdd..e4fcfd7b7 100644 --- a/hub/server/routes/index.ts +++ b/hub/server/routes/index.ts @@ -15,6 +15,7 @@ import { get as handleWorkspaceGet } from "./api/workspace/get/index.ts" import { get as handleRepositoryAuthorsGet } from "./api/repositories/authors/get/index.ts" import { get as handleRepositoryGet } from "./api/repositories/show/get/index.ts" import { get as handlePrototypeGet } from "./api/repositories/prototypes/show/get/index.ts" +import { patch as handlePrototypePatch } from "./api/repositories/prototypes/show/patch/index.ts" import { get as handleAdministratorsGet } from "./api/administrators/get/index.ts" import { get as handleAdministratorCandidatesGet } from "./api/administrators/candidates/get/index.ts" import { post as handleAdministratorAuthorizationStartPost } from "./api/administrators/authorizations/start/post/index.ts" @@ -57,6 +58,12 @@ export function routes(app: Express, dependencies: RouteDependencies = {}): void "/api/repositories/:repositoryId/prototypes/:prototypeId", handlePrototypeGet(authentication.currentSession, product), ) + app.patch( + "/api/repositories/:repositoryId/prototypes/:prototypeId", + requireOrigin(authentication.signOut.applicationOrigin), + express.json({ limit: "32kb", strict: true }), + handlePrototypePatch(authentication.currentSession, product), + ) } if (authentication.administrators) { app.get("/api/security-audits", handleSecurityAuditsGet(authentication.administrators)) From ac11ce8681fecaede2b23dff0c01c3ca337963f4 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sat, 14 Nov 2026 00:36:18 -0800 Subject: [PATCH 2/6] test(hub): cover prototype visibility lock Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 1bb10333-1d49-4426-896d-d9a04178b836 --- .../prototypes/show/patch/index.db.test.ts | 66 ++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts b/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts index 2567afe8c..733338a4e 100644 --- a/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts +++ b/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts @@ -9,8 +9,9 @@ import { getDatabaseUrl } from "../../../../../../../test/database/get-database- import { waitForBlockedQuery } from "../../../../../../../test/database/wait-for-blocked-query" import { waitForDatabaseLock } from "../../../../../../../test/database/wait-for-database-lock" import { createApp } from "../../../../../../create-app" -import { endAllHubSessions } from "../../../../../../domains/session-revocation/end-all-hub-sessions/index.ts" +import { endAllHubSessions } from "../../../../../../domains/session-revocation/end-all-hub-sessions" import { prisma } from "../../../../../../integrations/prisma" +import { lockEditablePrototype } from "../../../../../../repositories/prototypes/lock-editable-prototype" import { createAuthenticationRouteDependencies } from "../../../../auth/create-authentication-route-dependencies" import { createProductRouteDependencies } from "../../../../product/create-product-route-dependencies" @@ -309,6 +310,69 @@ describe("prototype PATCH API", () => { } }) + it("holds repository visibility until the edit commits", async () => { + const { repository, prototype } = await createPrototype("", "prototype/visibility") + const database = new pg.Client({ connectionString: getDatabaseUrl() }) + const inspector = new pg.Client({ connectionString: getDatabaseUrl() }) + await Promise.all([database.connect(), inspector.connect()]) + let notifyEditReady!: () => void + const editReady = new Promise((resolve) => { + notifyEditReady = resolve + }) + let releaseEdit!: () => void + const editGate = new Promise((resolve) => { + releaseEdit = resolve + }) + let editPid: number | undefined + let edit: Promise | null = null + let defaultBranchChange: Promise | null = null + try { + edit = prisma.$transaction(async (transaction) => { + expect(await lockEditablePrototype(transaction, repository.id, prototype.id)).toMatchObject( + { id: prototype.id, registeredAt: prototype.registeredAt }, + ) + const [connection] = await transaction.$queryRaw>` + SELECT pg_backend_pid() AS pid + ` + if (!connection) throw new Error("The edit transaction has no PostgreSQL connection.") + editPid = connection.pid + await transaction.prototype.update({ + where: { id: prototype.id }, + data: { name: "Edited" }, + }) + notifyEditReady() + await editGate + }) + await Promise.race([ + editReady, + edit.then(() => { + throw new Error("The edit finished before holding the repository lock.") + }), + ]) + if (editPid === undefined) throw new Error("The edit transaction has no PostgreSQL PID.") + defaultBranchChange = database.query( + `UPDATE repositories + SET default_branch = 'trunk', updated_at = clock_timestamp() + WHERE id = $1`, + [repository.id], + ) + await waitForBlockedQuery(inspector, editPid, "UPDATE repositories") + + releaseEdit() + await edit + await defaultBranchChange + expect(await readPrototype(prototype.id)).toMatchObject({ name: "Edited" }) + expect( + await prisma.repository.findUniqueOrThrow({ where: { id: repository.id } }), + ).toMatchObject({ defaultBranch: "trunk" }) + } finally { + releaseEdit() + if (edit) await Promise.allSettled([edit]) + if (defaultBranchChange) await Promise.allSettled([defaultBranchChange]) + await Promise.all([database.end(), inspector.end()]) + } + }) + it("rejects an edit when its session expires while waiting for the prototype lock", async () => { const server = await openServer() const expiresAt = new Date(Date.now() + 3_000) From 237f7c22bec947b13acc7a894e2b19a613ce7254 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sat, 14 Nov 2026 01:16:11 -0800 Subject: [PATCH 3/6] fix(hub): address prototype name review findings Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 1bb10333-1d49-4426-896d-d9a04178b836 --- hub/docs/architecture.md | 2 +- hub/docs/authentication.md | 2 +- hub/docs/frontend.md | 8 +++- .../edit-prototype-metadata/index.ts | 17 +++++-- .../index.ts | 12 +++++ .../index.ts | 4 +- .../prototypes/show/patch/index.db.test.ts | 46 +++++++++++++++++-- 7 files changed, 78 insertions(+), 13 deletions(-) create mode 100644 hub/server/repositories/authentication-providers/lock-authentication-providers-for-prototype-edit/index.ts diff --git a/hub/docs/architecture.md b/hub/docs/architecture.md index a72d732f8..ba0b583b3 100644 --- a/hub/docs/architecture.md +++ b/hub/docs/architecture.md @@ -22,7 +22,7 @@ The [database guide](database.md) defines the multi-file Prisma schema and share The [Pino integration](logging.md) writes structured application and HTTP logs to stdout. `createApp()` installs request logging before routes, so new endpoints inherit completion records and server-generated request IDs without explicit logging calls. Authentication routes install their bounded form parsing after origin and rate-limit checks. Prototype edits check the application origin before bounded JSON parsing, including case and trailing-slash aliases; other routes inherit the shared JSON parser. -`PATCH /api/repositories/:repositoryId/prototypes/:prototypeId` lets any signed-in member edit a visible registered prototype's name. It trims names, limits them to 255 Unicode characters, and rejects blank names and empty edits. Edits preserve the author and registration time. One transaction locks current session authority and prototype visibility through the write and detail response read, so revocation or lost visibility cannot leave a partial edit. UUID identity and Build relationships remain unchanged. Draft registration, a client editor, description and start-page editing, sharing, and management remain separate work. The API keeps `canEdit: false`. +The [prototype name-edit API](frontend.md#registered-prototype-name-edits) lets signed-in members rename visible registered prototypes. Hub holds session authority and prototype visibility locks through the write and detail read-back. The frontend editor and draft registration remain separate work. The [background-job foundation](background-jobs.md) uses BullMQ with PostgreSQL and separate on-demand and scheduled worker processes. Setup migrates BullMQ's own schema independently of Prisma. Product processors and schedules are not registered yet. diff --git a/hub/docs/authentication.md b/hub/docs/authentication.md index 8ed3cc185..1cb7de89e 100644 --- a/hub/docs/authentication.md +++ b/hub/docs/authentication.md @@ -56,7 +56,7 @@ The migration owns the single global revocation row. Its identity and history ar Restoration reads the current revision, locks active provider rows in key order, then share-locks the global revocation row and rechecks the revision before locking membership, assignments, and the session. It checks the revision again before returning authority. Administrator continuation, Copilot changes, and ending all Hub sessions lock provider rows in key order, then lock the global revocation row exclusively before changing state. This serializes mutations with restoration even when bootstrap or administrator authority has no provider row to lock. Those mutations can briefly block restoration and admission. -Prototype name edits acquire provider rows in key order and then share-lock the global revocation row before restoring session authority and locking prototype visibility. They keep those locks through the write and detail read-back. Provider locks can briefly block sign-in, session restoration, and reconciliation; the revocation lock can delay global sign-out. +Prototype name edits share-lock provider rows in key order and then share-lock the global revocation row before restoring session authority and locking prototype visibility. They keep those locks through the write and detail read-back. Shared provider locks allow sign-in and session restoration to proceed concurrently; provider reconciliation waits for the edit, and the revocation lock can delay global sign-out. `GET /api/auth/session` restores the current session and returns its current role plus the membership's provider-neutral presentation identity. `POST /api/auth/session/sign-out` ends it and clears the cookie. Hub does not issue refresh tokens, perform provider logout, or support step-up authentication. diff --git a/hub/docs/frontend.md b/hub/docs/frontend.md index 4a1265768..a5aa1f9eb 100644 --- a/hub/docs/frontend.md +++ b/hub/docs/frontend.md @@ -191,7 +191,7 @@ These are frontend/mock contracts under [the application contracts](../client/ap | `GET /api/repositories/:repositoryId/authors` | Searchable user choices with a cursor | | `GET /api/repositories/:repositoryId/prototypes/:prototypeId` | Prototype, Build records, and selected successful Build; real mode does not include hosted preview URLs | | `GET /api/repositories/:repositoryId/prototypes/:prototypeId/builds` | Paginated build history | -| `PATCH /api/repositories/:repositoryId/prototypes/:prototypeId` | Updated name/description and prototype data | +| `PATCH /api/repositories/:repositoryId/prototypes/:prototypeId` | Rename a visible, registered prototype | | `/api/repositories/:repositoryId/prototypes/:prototypeId/review-comments` and its comment actions | Review collections, changes, reactions, and read positions | | `GET /api/repositories/:repositoryId/templates` and `/api/repositories/:repositoryId/templates/:templateId` | Template browsing | | `GET /api/repositories/:repositoryId/prototype-management`, `PATCH /api/repositories/:repositoryId/prototype-management/:prototypeId` | Management records and metadata changes | @@ -205,7 +205,11 @@ These are frontend/mock contracts under [the application contracts](../client/ap | `GET /api/settings/workspace`, `/api/settings/public`, `/api/settings/admin-candidates` | Settings records and synthetic page capabilities | | `POST /api/settings/actions` | Explicitly named local actions; administrator role changes return 501 without changing state | -In real mode, Express implements `GET /api/workspace`, `GET /api/repositories/:repositoryId`, its `authors` endpoint, and `GET /api/repositories/:repositoryId/prototypes/:prototypeId`. The workspace lists the viewer and non-removed repositories. The repository index returns 24 eligible prototypes per page. It accepts `q`, `author`, and `page`, and rejects malformed values. Search ignores letter case and matches the prototype name, description, branch, and author login or name. A page past the end shows the last page. Each prototype includes its current Build or, when unset, the chronologically latest Build. The detail endpoint also includes unregistered prototypes and branches that were deleted, but excludes the default branch, replicas, and the reserved installation branch. It chooses the latest successful Build or a requested successful Build number; invalid and unavailable selections return 404. Unknown Build metadata remains null. Preview URLs and screenshots remain null because Hub does not host Builds yet. The authors endpoint lists other users with eligible prototypes, 20 at a time, sorted by login. Its cursor only marks where the last page ended. The [authentication guide](authentication.md) owns the real session routes. +In real mode, Express implements `GET /api/workspace`, `GET /api/repositories/:repositoryId`, its `authors` endpoint, `GET /api/repositories/:repositoryId/prototypes/:prototypeId`, and the [registered prototype name-edit](#registered-prototype-name-edits) `PATCH` endpoint. The workspace lists the viewer and non-removed repositories. The repository index returns 24 eligible prototypes per page. It accepts `q`, `author`, and `page`, and rejects malformed values. Search ignores letter case and matches the prototype name, description, branch, and author login or name. A page past the end shows the last page. Each prototype includes its current Build or, when unset, the chronologically latest Build. The detail endpoint also includes unregistered prototypes and branches that were deleted, but excludes the default branch, replicas, and the reserved installation branch. It chooses the latest successful Build or a requested successful Build number; invalid and unavailable selections return 404. Unknown Build metadata remains null. Preview URLs and screenshots remain null because Hub does not host Builds yet. The authors endpoint lists other users with eligible prototypes, 20 at a time, sorted by login. Its cursor only marks where the last page ended. The [authentication guide](authentication.md) owns the real session routes. + +### Registered prototype name edits + +Any signed-in member can rename a visible, registered prototype with a strict JSON object containing only `name`. Hub checks the configured origin before parsing the bounded body, trims surrounding Unicode whitespace, and rejects blank names, names over 255 Unicode code points, NUL, and unpaired surrogate values. Invalid input returns 400, a wrong origin returns 403, and a missing or expired session returns 401. Drafts, the default branch, replicas, the reserved installation branch, removed repositories, and prototypes requested under another repository return 404. A successful response includes the updated detail while preserving the prototype ID, author, registration time, and Build relationships; `canEdit` remains false. Hub holds session authority and prototype visibility locked through the update and detail read-back. The client editor and draft registration are separate work. Real administrator management does not use the provisional settings contracts: diff --git a/hub/server/domains/prototypes/edit-prototype-metadata/index.ts b/hub/server/domains/prototypes/edit-prototype-metadata/index.ts index f8f2185c5..32d67627b 100644 --- a/hub/server/domains/prototypes/edit-prototype-metadata/index.ts +++ b/hub/server/domains/prototypes/edit-prototype-metadata/index.ts @@ -6,9 +6,15 @@ import { PrototypeMetadataError } from "../errors.ts" type Detail = NonNullable>> // Matches the database metadata guard, which also treats NEL as blank. -const space = - "[\\t-\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]" -const edgeSpace = new RegExp(`^${space}+|${space}+$`, "gu") +const edgeSpace = /^[\t-\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]$/u + +function trimName(value: string) { + let start = 0 + let end = value.length + while (start < end && edgeSpace.test(value.charAt(start))) start += 1 + while (end > start && edgeSpace.test(value.charAt(end - 1))) end -= 1 + return value.slice(start, end) +} export interface PrototypeMetadataChanges { name?: string | null @@ -37,7 +43,10 @@ export async function editPrototypeMetadata( ) => Promise }, ) { - const name = input.changes.name?.replace(edgeSpace, "") + const name = + input.changes.name === null || input.changes.name === undefined + ? undefined + : trimName(input.changes.name) if (!name) throw new PrototypeMetadataError("invalid_input", "Enter a prototype name.") if (/[\p{Cs}\0]/u.test(name)) { throw new PrototypeMetadataError( diff --git a/hub/server/repositories/authentication-providers/lock-authentication-providers-for-prototype-edit/index.ts b/hub/server/repositories/authentication-providers/lock-authentication-providers-for-prototype-edit/index.ts new file mode 100644 index 000000000..591035e13 --- /dev/null +++ b/hub/server/repositories/authentication-providers/lock-authentication-providers-for-prototype-edit/index.ts @@ -0,0 +1,12 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export async function lockAuthenticationProvidersForPrototypeEdit( + database: Pick, +) { + await database.$queryRaw` + SELECT "id" + FROM "authentication_providers" + ORDER BY "key" + FOR SHARE + ` +} diff --git a/hub/server/routes/api/product/create-product-route-dependencies/index.ts b/hub/server/routes/api/product/create-product-route-dependencies/index.ts index fbdde613a..c7af7623d 100644 --- a/hub/server/routes/api/product/create-product-route-dependencies/index.ts +++ b/hub/server/routes/api/product/create-product-route-dependencies/index.ts @@ -3,7 +3,7 @@ import { restoreHubSession } from "../../../../domains/admission/restore-hub-ses import { runSessionRestoreTransaction } from "../../../../domains/admission/run-session-restore-transaction/index.ts" import { editPrototypeMetadata } from "../../../../domains/prototypes/edit-prototype-metadata/index.ts" import { prisma } from "../../../../integrations/prisma/index.ts" -import { lockAuthenticationProvidersForSessionAuthority } from "../../../../repositories/authentication-providers/lock-authentication-providers-for-session-authority/index.ts" +import { lockAuthenticationProvidersForPrototypeEdit } from "../../../../repositories/authentication-providers/lock-authentication-providers-for-prototype-edit/index.ts" import { findRepositoryAuthors } from "../../../../repositories/prototype-index/find-repository-authors/index.ts" import { findRepositoryIndex } from "../../../../repositories/prototype-index/find-repository-index/index.ts" import { findPrototypeDetail } from "../../../../repositories/prototype-index/find-prototype-detail/index.ts" @@ -27,7 +27,7 @@ export function createProductRouteDependencies(): ProductRouteDependencies { runTransaction: (operation) => prisma.$transaction( async (transaction) => { - await lockAuthenticationProvidersForSessionAuthority(transaction) + await lockAuthenticationProvidersForPrototypeEdit(transaction) await lockSessionRevocationState(transaction) // Keep these reads in this transaction so authority and prototype locks remain // held through the read-back. diff --git a/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts b/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts index 733338a4e..972fd85d0 100644 --- a/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts +++ b/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts @@ -11,6 +11,8 @@ import { waitForDatabaseLock } from "../../../../../../../test/database/wait-for import { createApp } from "../../../../../../create-app" import { endAllHubSessions } from "../../../../../../domains/session-revocation/end-all-hub-sessions" import { prisma } from "../../../../../../integrations/prisma" +import { lockAuthenticationProviderForSessionRestore } from "../../../../../../repositories/authentication-providers/lock-authentication-provider-for-session-restore" +import { lockAuthenticationProvidersForPrototypeEdit } from "../../../../../../repositories/authentication-providers/lock-authentication-providers-for-prototype-edit" import { lockEditablePrototype } from "../../../../../../repositories/prototypes/lock-editable-prototype" import { createAuthenticationRouteDependencies } from "../../../../auth/create-authentication-route-dependencies" import { createProductRouteDependencies } from "../../../../product/create-product-route-dependencies" @@ -183,6 +185,10 @@ describe("prototype PATCH API", () => { expect(blankName.status).toBe(400) const longName = await patch(url, member.token, { name: "😀".repeat(256) }) expect(longName.status).toBe(400) + const nulName = await patch(url, member.token, { name: "Invalid\u0000name" }) + expect(nulName.status).toBe(400) + const unpairedSurrogate = await patch(url, member.token, { name: "Invalid\uD800name" }) + expect(unpairedSurrogate.status).toBe(400) expect(await readPrototype(prototype.id)).toEqual(prototype) const maximum = await patch(url, member.token, { name: ` ${"😀".repeat(255)} ` }) @@ -203,6 +209,7 @@ describe("prototype PATCH API", () => { data: { nameWithOwner: "team/design", defaultBranch: "trunk" }, }) const registeredAt = new Date("2026-10-01T00:00:00Z") + const registration = { repositoryId: repository.id, registeredAt } const retired = await prisma.prototype.create({ data: { repositoryId: repository.id, @@ -222,9 +229,8 @@ describe("prototype PATCH API", () => { }) const hidden = await prisma.prototype.createManyAndReturn({ data: [ - { repositoryId: repository.id, branchName: "trunk" }, - { repositoryId: repository.id, branchName: "replica/install-workflow" }, - { repositoryId: repository.id, branchName: "replica/internal", replica: true }, + { ...registration, branchName: "trunk", name: "Default" }, + { ...registration, branchName: "replica/install-workflow", name: "Installation" }, ], }) for (const prototype of hidden) { @@ -373,6 +379,40 @@ describe("prototype PATCH API", () => { } }) + it("allows session restoration to share provider locks", async () => { + await openServer() + let notifyLocksHeld!: () => void + const locksHeld = new Promise((resolve) => { + notifyLocksHeld = resolve + }) + let releaseLocks!: () => void + const lockGate = new Promise((resolve) => { + releaseLocks = resolve + }) + let edit: Promise | null = null + try { + edit = prisma.$transaction(async (transaction) => { + await lockAuthenticationProvidersForPrototypeEdit(transaction) + notifyLocksHeld() + await lockGate + }) + await Promise.race([ + locksHeld, + edit.then(() => { + throw new Error("The transaction finished before holding provider locks.") + }), + ]) + const restoredProvider = await prisma.$transaction(async (transaction) => { + await transaction.$executeRaw`SET LOCAL lock_timeout = '1s'` + return lockAuthenticationProviderForSessionRestore(transaction, "github") + }) + expect(restoredProvider).not.toBeNull() + } finally { + releaseLocks() + if (edit) await Promise.allSettled([edit]) + } + }) + it("rejects an edit when its session expires while waiting for the prototype lock", async () => { const server = await openServer() const expiresAt = new Date(Date.now() + 3_000) From 2153ca96e8fe696bb3a4716bd106a8dba461e717 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sat, 14 Nov 2026 01:25:19 -0800 Subject: [PATCH 4/6] test(hub): stabilize database lock wait checks Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 1bb10333-1d49-4426-896d-d9a04178b836 --- hub/test/database/wait-for-database-lock/index.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/hub/test/database/wait-for-database-lock/index.ts b/hub/test/database/wait-for-database-lock/index.ts index c800a6d57..714cc6e94 100644 --- a/hub/test/database/wait-for-database-lock/index.ts +++ b/hub/test/database/wait-for-database-lock/index.ts @@ -4,7 +4,8 @@ export async function waitForDatabaseLock(databaseUrl: string): Promise { const client = new pg.Client({ connectionString: databaseUrl }) await client.connect() try { - for (let attempt = 0; attempt < 100; attempt += 1) { + const deadline = Date.now() + 5_000 + while (Date.now() < deadline) { const result = await client.query<{ waiting: boolean }>( `SELECT EXISTS ( SELECT 1 @@ -15,9 +16,9 @@ export async function waitForDatabaseLock(databaseUrl: string): Promise { ) AS waiting`, ) if (result.rows[0]?.waiting) return - await new Promise((resolve) => setImmediate(resolve)) + await new Promise((resolve) => setTimeout(resolve, 10)) } - throw new Error("A competing database backend did not enter a lock wait.") + throw new Error("Timed out waiting for a competing database backend to enter a lock wait.") } finally { await client.end() } From fc4395998e0c05811dcd1ad2986ad3211c76b25d Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sat, 14 Nov 2026 01:37:49 -0800 Subject: [PATCH 5/6] docs(hub): distinguish mock and real prototype edits Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 1bb10333-1d49-4426-896d-d9a04178b836 --- hub/docs/frontend.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hub/docs/frontend.md b/hub/docs/frontend.md index a5aa1f9eb..2c2eea8f4 100644 --- a/hub/docs/frontend.md +++ b/hub/docs/frontend.md @@ -191,7 +191,7 @@ These are frontend/mock contracts under [the application contracts](../client/ap | `GET /api/repositories/:repositoryId/authors` | Searchable user choices with a cursor | | `GET /api/repositories/:repositoryId/prototypes/:prototypeId` | Prototype, Build records, and selected successful Build; real mode does not include hosted preview URLs | | `GET /api/repositories/:repositoryId/prototypes/:prototypeId/builds` | Paginated build history | -| `PATCH /api/repositories/:repositoryId/prototypes/:prototypeId` | Rename a visible, registered prototype | +| `PATCH /api/repositories/:repositoryId/prototypes/:prototypeId` | Mock: update a prototype's name and description; both fields are required | | `/api/repositories/:repositoryId/prototypes/:prototypeId/review-comments` and its comment actions | Review collections, changes, reactions, and read positions | | `GET /api/repositories/:repositoryId/templates` and `/api/repositories/:repositoryId/templates/:templateId` | Template browsing | | `GET /api/repositories/:repositoryId/prototype-management`, `PATCH /api/repositories/:repositoryId/prototype-management/:prototypeId` | Management records and metadata changes | @@ -209,7 +209,7 @@ In real mode, Express implements `GET /api/workspace`, `GET /api/repositories/:r ### Registered prototype name edits -Any signed-in member can rename a visible, registered prototype with a strict JSON object containing only `name`. Hub checks the configured origin before parsing the bounded body, trims surrounding Unicode whitespace, and rejects blank names, names over 255 Unicode code points, NUL, and unpaired surrogate values. Invalid input returns 400, a wrong origin returns 403, and a missing or expired session returns 401. Drafts, the default branch, replicas, the reserved installation branch, removed repositories, and prototypes requested under another repository return 404. A successful response includes the updated detail while preserving the prototype ID, author, registration time, and Build relationships; `canEdit` remains false. Hub holds session authority and prototype visibility locked through the update and detail read-back. The client editor and draft registration are separate work. +Unlike the mock contract above, the real endpoint accepts a strict JSON object containing only `name`. Any signed-in member can rename a visible, registered prototype. Hub checks the configured origin before parsing the bounded body, trims surrounding Unicode whitespace, and rejects blank names, names over 255 Unicode code points, NUL, and unpaired surrogate values. Invalid input returns 400, a wrong origin returns 403, and a missing or expired session returns 401. Drafts, the default branch, replicas, the reserved installation branch, removed repositories, and prototypes requested under another repository return 404. A successful response includes the updated detail while preserving the prototype ID, author, registration time, and Build relationships; `canEdit` remains false. Hub holds session authority and prototype visibility locked through the update and detail read-back. The client editor and draft registration are separate work. Real administrator management does not use the provisional settings contracts: From 3b76067af3fc36b4946372806b65c628c945f84b Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sat, 14 Nov 2026 07:08:05 -0800 Subject: [PATCH 6/6] test(hub): refresh lock activity snapshots Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 1bb10333-1d49-4426-896d-d9a04178b836 --- .../api/repositories/prototypes/show/patch/index.db.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts b/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts index 972fd85d0..1b8d54988 100644 --- a/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts +++ b/hub/server/routes/api/repositories/prototypes/show/patch/index.db.test.ts @@ -465,6 +465,8 @@ describe("prototype PATCH API", () => { RETURNING revision `) await vi.waitFor(async () => { + // Refresh activity data while the blocking transaction stays open. + await database.query("SELECT pg_stat_clear_snapshot()") const waiting = await database.query<{ blocked: boolean }>( `SELECT EXISTS ( SELECT 1 FROM pg_stat_activity