diff --git a/packages/cli/src/server/shareRoutes.test.ts b/packages/cli/src/server/shareRoutes.test.ts index 894d33f54b..eddbfac6c6 100644 --- a/packages/cli/src/server/shareRoutes.test.ts +++ b/packages/cli/src/server/shareRoutes.test.ts @@ -190,6 +190,7 @@ it("keeps one server job alive after the request completes and recovers it on re audience: "private", space: "team1", videoOnly: undefined, + confirmedReview: null, }); }); it("returns failed jobs without changing access or retrying automatically", async () => { @@ -264,6 +265,7 @@ it("passes explicit video-only recovery and rejects nonboolean bypass values", a audience: undefined, space: undefined, videoOnly: true, + confirmedReview: null, }), ); }); diff --git a/packages/cli/src/server/shareRoutes.ts b/packages/cli/src/server/shareRoutes.ts index 5d086c8f1b..c5a11ecfb2 100644 --- a/packages/cli/src/server/shareRoutes.ts +++ b/packages/cli/src/server/shareRoutes.ts @@ -270,6 +270,7 @@ function executeAction(sharing: ShareService, input: LocalShareAction) { space: input.space, videoOnly: input.videoOnly, includeSource: input.includeSource, + confirmedReview: input.confirmedReview, }); } diff --git a/packages/cli/src/share/service.test.ts b/packages/cli/src/share/service.test.ts index d24e68fd8a..daf4560446 100644 --- a/packages/cli/src/share/service.test.ts +++ b/packages/cli/src/share/service.test.ts @@ -205,6 +205,36 @@ describe("share operation consent and identity", () => { expect(mocks.create).toHaveBeenCalledWith(expect.objectContaining({ spaceId: "space" })); expect(mocks.add).toHaveBeenCalledWith(expect.objectContaining({ projectId: "project" })); }); + it("carries the confirmed review into a first share's registration", async () => { + mocks.create.mockImplementation(async () => { + mocks.status.mockResolvedValue(shared); + return shared; + }); + mocks.add.mockResolvedValue(null); + + await createShareService("/project").run({ + action: "share", + audience: "public", + confirmedReview: null, + }); + + expect(mocks.create).toHaveBeenCalledWith(expect.objectContaining({ confirmed: null })); + expect(mocks.add).toHaveBeenCalledWith(expect.objectContaining({ projectId: "project" })); + }); + it.each([ + ["a first share confirmed as new, once the record names a review", null, "unopened"], + ["an audience change confirmed for another review", "another", "shared"], + ])("refuses %s before changing anything", async (_, confirmedReview, folder) => { + if (folder === "shared") mocks.status.mockResolvedValue(shared); + else + mocks.record.mockResolvedValue({ projectId: "linked", opened: false, studioProjectId: "s" }); + + await expect( + createShareService("/project").run({ action: "share", audience: "private", confirmedReview }), + ).rejects.toMatchObject({ reason: "review_binding_changed" }); + for (const change of [mocks.render, mocks.create, mocks.setAccess, mocks.add]) + expect(change).not.toHaveBeenCalled(); + }); it("retries an unfinished first share in its saved workspace", async () => { mocks.record.mockResolvedValue({ spaceId: "saved", projectId: "project" }); mocks.spaces.mockResolvedValue([ diff --git a/packages/cli/src/share/service.ts b/packages/cli/src/share/service.ts index 470b97fd6a..ffbbbd688b 100644 --- a/packages/cli/src/share/service.ts +++ b/packages/cli/src/share/service.ts @@ -36,6 +36,7 @@ export interface ShareAction { waitSeconds?: number; videoOnly?: boolean; includeSource?: boolean; + confirmedReview?: string | null; } function linkState(share: ReviewShare | null, ready: boolean, failed: boolean): string { if (!share) return "not_shared"; @@ -130,6 +131,11 @@ function assertUploadProject( if (!id || (expectedId && id !== expectedId)) throw new ReviewFailed(409, "review_binding_changed"); } +function assertConfirmedReview(reviewId: string | null, input: ShareAction) { + if (input.confirmedReview !== undefined && reviewId !== input.confirmedReview) + throw new ReviewFailed(409, "review_binding_changed"); +} +const confirmedId = (input: ShareAction) => input.confirmedReview ?? undefined; function assertExistingIntent(share: ReviewShare | null, input: ShareAction) { if (!share) { if (input.action === "update") throw new ReviewFailed(404, "not_shared"); @@ -266,8 +272,9 @@ export function createShareService( client, spaceId: space, audience: input.audience, + confirmed: input.confirmedReview, }); - assertUploadProject(share, current?.projectId); + assertUploadProject(share, current?.projectId ?? confirmedId(input)); if (share.takedown) throw new ReviewFailed(409, "moderation_hold"); assertExistingIntent(share, { ...input, @@ -294,6 +301,7 @@ export function createShareService( await auth.access(); attempt.authenticated(); let current = await readStatus(dir, client, undefined, attempt.recover); + assertConfirmedReview(current.reviewId, input); if (current.share && input.audience && changesAudience(input, current.share)) { assertExistingIntent(current.share, { ...input, audience: undefined }); const projectId = current.share.projectId; diff --git a/packages/share/src/reviewClient.mjs b/packages/share/src/reviewClient.mjs index d3ef464397..9aac2bbdf7 100644 --- a/packages/share/src/reviewClient.mjs +++ b/packages/share/src/reviewClient.mjs @@ -99,11 +99,20 @@ export function reviewClient({ access, fetchImpl = fetch, signedInEmail = async shareFiles: data?.share_files === true, }; }, - /** Registers into `spaceId`; without one the server uses the caller's default space. + /** Registers into `spaceId`; without one the server uses the caller's default space. `created` is true only for + * a 201: a 200 answers a project that was already bound to this `studio_project_id`. * @param {import("./types/reviewWire.js").RegisterProjectRequest} body @param {string | null} [spaceId] - * @returns {Promise} */ - register: (body, spaceId) => - call("POST", PROJECTS, body, spaceId ? { "x-space-id": spaceId } : {}), + * @returns {Promise} */ + register: async (body, spaceId) => { + const { reply } = await request( + "POST", + PROJECTS, + body, + spaceId ? { "x-space-id": spaceId } : {}, + null, + ); + return { ...(await dataOf(reply, `POST ${PROJECTS}`)), created: reply.status === 201 }; + }, /** @param {string} id @returns {Promise} */ share: (id) => call("GET", `${project(id)}/share`), /** @param {string} id @param {import("./types/reviewWire.js").UpdateProjectShareRequest} body diff --git a/packages/share/src/reviewShare.mjs b/packages/share/src/reviewShare.mjs index 4808a0111d..436c6087ea 100644 --- a/packages/share/src/reviewShare.mjs +++ b/packages/share/src/reviewShare.mjs @@ -21,7 +21,8 @@ import { ReviewFailed } from "./reviewClient.mjs"; import { rename } from "./storage.mjs"; /** @typedef {import("./reviewClient.mjs").ReviewClient} ReviewClient - * @typedef {import("./types/reviewWire.js").ShareDTO} ShareDTO */ + * @typedef {import("./types/reviewWire.js").ShareDTO} ShareDTO + * @typedef {import("./types/reviewWire.js").ProjectDTO} ProjectDTO */ /** @typedef {import("./types/share.js").ReviewShare} ReviewShare * @typedef {import("./types/share.js").ReviewSpace} ReviewSpace @@ -426,13 +427,28 @@ async function registerOnce(client, projectPath, record, title) { client_operation_id: randomUUID(), }; await writeJsonAtomic(recordPath(projectPath), { ...record, registration: body }); + let project; try { - return (await client.register(body, record.spaceId)).project_id; + project = await client.register(body, record.spaceId); } catch (error) { if (!(error instanceof ReviewFailed) || error.reason !== "space_forbidden") throw error; await writeJsonAtomic(recordPath(projectPath), { ...record, spaceId: null }); throw await spaceRefusal(client, record.spaceId, error); } + if (project.created || (record.registration && (await unused(client, project)))) + return project.project_id; + await writeJsonAtomic(recordPath(projectPath), record); + throw new ReviewFailed(409, "review_project_changed"); +} + +/** A first share may only land on a project it made. A server answer of an existing project is a retry after a lost + * reply only when the record already held this registration and the project is as registration left it: private, + * link never turned off, no ready version. Anything else is a review nobody confirmed, so nothing is changed. + * @param {ReviewClient} client @param {ProjectDTO} project */ +async function unused(client, project) { + if (project.latest_ready_version_id) return false; + const share = await readShare(client, project.project_id); + return share.access_mode === "private" && !share.revoked; } /** A space refused at registration. Only one picked before the workspace changed is replaced by the next press; @@ -447,8 +463,10 @@ async function spaceRefusal(client, refused, error) { /** Share's press: the first registers the project into the space given (none: the signed-in one) and opens its link * to that space; a later one reads the link, turning it back on when it was off. A registered project keeps its space. * A host can prepare review content after registration is saved and before the link or its audience changes. + * `confirmed` is the review the person was shown, null for a new one; a record that names another is refused unchanged. * @param {{ projectPath: string, title: string, client: ReviewClient, spaceId?: string | null, audience?: - * import("./types/share.js").AccessMode | undefined, beforeOpen?: (projectId: string) => Promise }} request */ + * import("./types/share.js").AccessMode | undefined, beforeOpen?: (projectId: string) => Promise, + * confirmed?: string | null }} request */ export const shareForReview = ({ projectPath, title, @@ -456,9 +474,10 @@ export const shareForReview = ({ spaceId = null, audience, beforeOpen, + confirmed, }) => oneAtATime(projectPath, async () => { - const read = await recordToShare(client, projectPath, spaceId); + const read = assertConfirmed(await recordToShare(client, projectPath, spaceId), confirmed); const id = read.projectId ?? (await registerOnce(client, projectPath, read, title)); const record = read.projectId ? read @@ -473,6 +492,13 @@ export const shareForReview = ({ ); }); +/** @param {ReviewRecord} record @param {string | null | undefined} confirmed */ +function assertConfirmed(record, confirmed) { + if (confirmed !== undefined && record.projectId !== confirmed) + throw new ReviewFailed(409, "review_project_changed"); + return record; +} + /** Turns a link that was off back on, and opens a first share to the workspace. * @param {ReviewClient} client @param {string} projectPath @param {ReviewRecord} record @param {string} id * @param {ShareDTO} share @param {import("./types/share.js").AccessMode} [audience] */ diff --git a/packages/share/tests/kernel.test.mjs b/packages/share/tests/kernel.test.mjs index 367ad086a1..8b5ee558f8 100644 --- a/packages/share/tests/kernel.test.mjs +++ b/packages/share/tests/kernel.test.mjs @@ -65,7 +65,7 @@ function client() { register: async (value) => { calls++; body.push(value); - return { project_id: "p1" }; + return { project_id: "p1", created: true }; }, signedInEmail: async () => "owner@example.com", share: async () => dto, @@ -336,7 +336,7 @@ for (const fallback of [false, true]) import {realpathSync} from 'node:fs'; import {appendFile} from 'node:fs/promises'; const dir=process.argv[1]; bindShareHost({normalize:realpathSync,channelSite:'https://hyperframes.dev',signinSites:['https://hyperframes.dev']}); const client={ spaces:async()=>[{space_id:'s1',bound:true,can_create_review:true}], signedInEmail:async()=>null, - register:async()=>{await appendFile(dir+'/registrations','registered\\n');await new Promise(r=>setTimeout(r,80));return {project_id:'p1'}}, + register:async()=>{await appendFile(dir+'/registrations','registered\\n');await new Promise(r=>setTimeout(r,80));return {project_id:'p1',created:true}}, share:async()=>({project_id:'p1',review_url:'https://hyperframes.dev/r/t',access_mode:'public',default_role:'commenter',comments_enabled:true,revoked:false})}; await shareForReview({projectPath:dir,title:'Video',client,audience:'public'});`; await Promise.all([success(child(script, [dir])), success(child(script, [dir]))]); @@ -704,3 +704,132 @@ test("change detection still applies a .hyperframesignore it can read", async (t for (const options of [undefined, lenient]) assert.deepEqual([...(await snapshotProject(dir, options)).keys()], ["index.html"]); }); + +test("registration reports whether the server created the project", async () => { + for (const [status, created] of [ + [201, true], + [200, false], + ]) { + const api = reviewClient({ + access: async () => ({ token: "t", heygen: "https://review.test", heygenApi: "" }), + fetchImpl: async () => Response.json({ data: { project_id: "p1" } }, { status }), + }); + const body = { studio_project_id: "s", title: "Video", client_operation_id: "op" }; + assert.deepEqual(await api.register(body, null), { project_id: "p1", created }); + } +}); + +/** One of the signed-in account's existing reviews, answered for any registration of its studio id. */ +function existingReview({ ready = "v1", access = "team", revoked = true, created = false } = {}) { + const writes = []; + const share = { + project_id: "existing", + review_url: null, + access_mode: access, + default_role: "commenter", + comments_enabled: true, + revision: 4, + link_generation: 2, + revoked, + }; + const write = + (name) => + async (...args) => { + writes.push([name, ...args]); + return share; + }; + return { + writes, + registrations: [], + spaces: async () => [{ space_id: "s1", bound: true, can_create_review: true }], + async register(body) { + this.registrations.push(body); + return { project_id: "existing", latest_ready_version_id: ready, created }; + }, + signedInEmail: async () => "owner@example.com", + share: async () => share, + updateShare: write("updateShare"), + linkOn: write("linkOn"), + createExport: write("createExport"), + }; +} +async function recordFolder(t, record) { + const dir = await folder(t); + await mkdir(join(dir, ".hyperframes")); + await writeFile(join(dir, ".hyperframes/review.json"), JSON.stringify(record)); + return dir; +} +const planted = { + studio_project_id: "existing-studio", + title: "Their video", + client_operation_id: "11111111-1111-4111-8111-111111111111", +}; +for (const [name, record, review] of [ + ["only its studio id", { studioProjectId: "existing-studio" }, {}], + [ + "a saved registration, once it has a version", + { studioProjectId: "existing-studio", spaceId: "s1", registration: planted }, + { access: "private", revoked: false }, + ], + [ + "a saved registration, once its audience was set", + { studioProjectId: "existing-studio", spaceId: "s1", registration: planted }, + { ready: null, revoked: false }, + ], + [ + "a saved registration, once its link was turned off", + { studioProjectId: "existing-studio", spaceId: "s1", registration: planted }, + { ready: null, access: "private" }, + ], +]) { + test(`a first share refuses an existing review reached through ${name}`, async (t) => { + const dir = await recordFolder(t, record); + const api = existingReview(review); + await assert.rejects( + shareForReview({ projectPath: dir, title: "Video", client: api, audience: "public" }), + { status: 409, reason: "review_project_changed" }, + ); + assert.equal(api.registrations.length, 1); + assert.deepEqual(api.writes, []); + const after = await reviewRecord(dir); + assert.equal(after.projectId, null); + assert.equal(after.opened, false); + assert.deepEqual(after.registration, record.registration); + }); +} + +test("a retry after a lost registration reply reaches the project it registered", async (t) => { + const dir = await folder(t); + const api = existingReview({ ready: null, access: "private", revoked: false, created: true }); + const register = api.register; + api.register = async function (body) { + const project = await register.call(this, body); + if (this.registrations.length === 1) throw new Error("lost reply"); + return { ...project, created: false }; + }; + await assert.rejects( + shareForReview({ projectPath: dir, title: "Video", client: api, audience: "public" }), + ); + await shareForReview({ projectPath: dir, title: "Video", client: api, audience: "public" }); + assert.deepEqual(api.registrations[0], api.registrations[1]); + assert.equal(api.writes.length, 1); + assert.equal(api.writes[0][0], "updateShare"); + assert.equal(api.writes[0][2].access_mode, "public"); + const after = await reviewRecord(dir); + assert.equal(after.projectId, "existing"); + assert.equal(after.opened, true); +}); + +test("a share confirmed for one review refuses a record that now names another", async (t) => { + const record = { studioProjectId: "studio", projectId: "existing", opened: false }; + for (const confirmed of [null, "another"]) { + const dir = await recordFolder(t, record); + const api = existingReview(); + await assert.rejects( + shareForReview({ projectPath: dir, title: "Video", client: api, confirmed }), + { status: 409, reason: "review_project_changed" }, + ); + assert.deepEqual(api.writes, []); + assert.equal((await reviewRecord(dir)).opened, false); + } +});