// @ts-check // Review requests run on the host so the browser never receives the account bearer. import { randomUUID } from "node:crypto"; import { rejectedGrantRequest } from "./grantRefusal.mjs"; import { signedInRequest } from "./host.mjs"; import { shareOpenCalls } from "./reviewOpenCalls.mjs"; /** @typedef {import("./types/reviewWire.js").ShareDTO} ShareDTO @typedef {import("./types/reviewWire.js").ProjectDTO} ProjectDTO * @typedef {import("./types/reviewWire.js").ExportDTO} ExportDTO */ const TIMEOUT_MS = 30_000; const PROJECTS = "/v1/hyperframes/review-projects"; const SPACES = "/v1/hyperframes/review-spaces"; /** A refused or failed call: the HTTP status (0 when the server was never reached) and the server's reason. */ export class ReviewFailed extends Error { /** @param {number} status @param {string} reason @param {number} [currentRevision] @param {number} [retryAfterMs] * @param {import("./types/reviewWire.js").ErrorEnvelope["data"]} [details] */ constructor(status, reason, currentRevision, retryAfterMs, details) { super(`review ${status} ${reason}`); this.status = status; this.reason = reason; this.currentRevision = currentRevision; this.retryAfterMs = retryAfterMs; this.details = details; } } /** The answer's data; null for a 204. A refusal throws with the server's status and reason. * @param {Response} reply @param {string} what @returns {Promise} */ async function dataOf(reply, what) { if (reply.status === 204) return null; const payload = await reply.json().catch(() => null); if (reply.ok) return payload?.data ?? null; /** @type {import("./types/reviewWire.js").ErrorEnvelope["data"] | undefined} */ const data = payload?.data; throw responseFailure(reply, what, data); } /** @param {Response} reply @param {string} what @param {import("./types/reviewWire.js").ErrorEnvelope["data"] | undefined} data */ function responseFailure(reply, what, data) { if (process.env.HF_DEBUG_SHARE === "1") console.error(`[review] ${what} refused:`, reply.status, data?.reason); const retryAfter = Number(reply.headers.get("retry-after") ?? NaN); return new ReviewFailed( reply.status, data?.reason ?? "", data?.current_revision, retryAfter >= 0 ? retryAfter * 1000 : undefined, data, ); } /** The server's own "no" to the sharing read: signed out, not allowed, or no such route. */ export const SHARING_REFUSALS = [401, 403, 404]; /** @param {{ access: import("./types/access.js").ApiAccess, fetchImpl?: typeof fetch, * signedInEmail?: () => Promise }} deps */ export function reviewClient({ access, fetchImpl = fetch, signedInEmail = async () => null }) { const request = signedInRequest({ access, fetchImpl, timeoutMs: TIMEOUT_MS, tag: "review", offline: () => new ReviewFailed(0, "offline"), signedOut: () => new ReviewFailed(401, "login_required"), }); /** @param {string} method @param {string} route @param {unknown} [body] @param {Record} [headers] * @param {number[] | null} [answers] @returns {Promise} */ const call = async (method, route, body, headers = {}, answers = null) => dataOf((await request(method, route, body, headers, answers)).reply, `${method} ${route}`); /** A call on a share token's route, logged as `what`: the token opens the share to anyone holding it. * @param {string} what @param {string} method @param {string} route @param {unknown} [body] * @returns {Promise} */ const tokenCall = async (what, method, route, body) => dataOf((await request(method, route, body, {}, null, what)).reply, what); const project = (/** @type {string} */ id) => `${PROJECTS}/${encodeURIComponent(id)}`; return { /** The signed-in account's email, null when unknown; the record keeps it as the project's owner. */ signedInEmail, /** The spaces this account can share into, personal first. * @returns {Promise} */ spaces: async () => { const items = (await call("GET", SPACES))?.items; // An answer without a list is not "no spaces": sharing then would pick a workspace nobody chose. if (!Array.isArray(items)) throw new ReviewFailed(502, "malformed_spaces"); return items; }, /** The server's per-account flags on review-spaces, each on only for `true`: `hyperframes-review-version-sharing` * and `hyperframes-review-share-files`. One read answers both. * @returns {Promise<{ versionSharing: boolean, shareFiles: boolean }>} */ reviewFlags: async () => { const data = await call("GET", SPACES, undefined, {}, SHARING_REFUSALS); if (!Array.isArray(data?.items)) throw new ReviewFailed(502, "malformed_spaces"); return { versionSharing: data?.version_sharing === true, shareFiles: data?.share_files === true, }; }, /** Registers into `spaceId`; without one the server uses the caller's default space. * @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 } : {}), /** @param {string} id @returns {Promise} */ share: (id) => call("GET", `${project(id)}/share`), /** @param {string} id @param {import("./types/reviewWire.js").UpdateProjectShareRequest} body * @returns {Promise} */ updateShare: (id, body) => call("PATCH", `${project(id)}/share`, body), /** @param {string} id @param {import("./types/reviewWire.js").ProjectOperationRequest} body @returns {Promise} */ linkOn: (id, body) => call("POST", `${project(id)}/share`, body), /** @param {string} id @returns {Promise} */ linkOff: (id) => call("DELETE", `${project(id)}/share`), /** @param {string} id @returns {Promise} */ project: (id) => call("GET", project(id)), /** @param {string} id @returns {Promise<{frames: unknown[]}>} */ storyboard: (id) => call("GET", `/v1/hyperframes/projects/${encodeURIComponent(id)}/storyboard`), /** @param {string} id @param {string} compositionId @returns {Promise<{composition_id: string}>} */ bindComposition: (id, compositionId) => call("PUT", `${project(id)}/composition`, { composition_id: compositionId }), /** One page of the project's comments, every state. @param {string} id @param {URLSearchParams} query * @returns {Promise} */ feedback: (id, query) => call("GET", `${project(id)}/feedback?${query}`), /** A new version from a local MP4. A body factory runs after sign-in on each attempt. * @param {string} id @param {ExportRequest | (() => Promise)} body @returns {Promise} */ createExport: (id, body) => call("POST", `${project(id)}/exports`, body), /** @param {string} id @param {string} videoId @returns {Promise} */ readExport: (id, videoId) => call("GET", `${project(id)}/exports/${encodeURIComponent(videoId)}`), /** The upload is in storage: start processing. @param {string} id @param {string} videoId * @returns {Promise} */ completeExport: (id, videoId) => call("POST", `${project(id)}/exports/${encodeURIComponent(videoId)}/complete`), /** Attaches the synced snapshot to a version that has none; the same one again is a no-op, another is refused * with 409 `snapshot_already_attached`. @param {string} id @param {string} versionId * @param {import("./types/reviewWire.js").SnapshotRef} snapshot @returns {Promise} */ attachSnapshot: (id, versionId, snapshot) => call("PUT", `${project(id)}/versions/${encodeURIComponent(versionId)}/snapshot`, snapshot), ...shareOpenCalls(tokenCall), ...managementClient(call, project, access), ...threadWrites(call, project), }; } /** The owner's writes on one thread. @param {(method: string, route: string, body?: unknown) => Promise} call * @param {(id: string) => string} project */ function threadWrites(call, project) { const thread = (/** @type {string} */ id, /** @type {string} */ rootId) => `${project(id)}/comments/${encodeURIComponent(rootId)}`; return { /** Accept, dismiss, reopen or resolve a thread. @param {string} id @param {string} rootId * @param {{ action: import("./types/review.js").ReviewAction, expected_status_revision: number }} body */ setStatus: (id, rootId, body) => call("PATCH", `${thread(id, rootId)}/status`, body), /** @param {string} id @param {string} rootId * @param {{ client_operation_id: string, body: string, attachment_ids: string[] }} body */ reply: (id, rootId, body) => call("POST", `${thread(id, rootId)}/replies`, body), }; } /** An invite to an email whose grant was revoked: the server takes the row back only at its revision with a fresh * operation ID, here the conflict's revision. Null for any other refusal, or one the same revision already got. * @param {unknown} error @param {import("./types/reviewWire.js").CreateGrantRequest} body * @returns {import("./types/reviewWire.js").CreateGrantRequest | null} */ function regrantOf(error, body) { if (!(error instanceof ReviewFailed) || error.reason !== "revision_conflict") return null; if (typeof error.currentRevision !== "number") return null; // A current revision of 0 is no row at all, which the server asks for as no revision. const revision = error.currentRevision || null; if (revision === body.expected_revision) return null; return { ...body, client_operation_id: randomUUID(), expected_revision: revision }; } /** Grants listed with their revoked rows, whose revisions let a re-invite go straight out as the re-grant; a server * that ignores `include_revoked` lists none, and the re-invite meets `revision_conflict` first. A re-grant is kept as * its invitation's retry, sent again as itself until an answer or a refusal `rejectedGrantRequest` calls final. * @param {(method: string, route: string, body?: unknown) => Promise} call @param {(id: string) => string} project * @param {import("./types/access.js").ApiAccess} access */ function grantCalls(call, project, access) { /** Re-grants awaiting a final answer, by site, account, project and the operation the window sent. * @type {Map} */ const sent = new Map(); /** The revision of each revoked grant the last list read, by site, account and project, then email. * @type {Map>} */ const revoked = new Map(); /** @param {string} id */ const scopeOf = async (id) => { // expected: signed out, the call itself refuses as login_required; the scope is only a key. const who = await access().catch(() => null); return [who?.heygen ?? "", who?.owner ?? "", id].join("\n"); }; /** @param {string} route @param {string} key @param {import("./types/reviewWire.js").CreateGrantRequest} body */ const settle = async (route, key, body) => { try { const answer = await call("POST", route, body); sent.delete(key); return answer; } catch (error) { if (rejectedGrantRequest(error)) sent.delete(key); throw error; } }; /** @param {string} route @param {string} key @param {import("./types/reviewWire.js").CreateGrantRequest} body */ const regranting = (route, key, body) => { sent.set(key, { email: body.email, regrant: body }); return settle(route, key, body); }; /** @param {string} scope @param {string} email */ const forgetEarlierInvites = (scope, email) => { for (const [other, kept] of sent) if (other.startsWith(`${scope}\n`) && kept.email === email) sent.delete(other); }; return { /** The project's live grants. @param {string} id * @returns {Promise<{items: import("./types/reviewWire.js").AccessGrantDTO[]}>} */ grants: async (id) => { const scope = await scopeOf(id); const items = await everyGrant(call, `${project(id)}/access-grants`); revoked.set( scope, new Map( items.filter((grant) => grant.revoked_at).map((grant) => [grant.email, grant.revision]), ), ); return { items: items.filter((grant) => !grant.revoked_at) }; }, /** @param {string} id @param {import("./types/reviewWire.js").CreateGrantRequest} body * @returns {Promise} */ createGrant: async (id, body) => { const route = `${project(id)}/access-grants`; const scope = await scopeOf(id); const key = `${scope}\n${body.client_operation_id}`; const retained = sent.get(key); if (retained) return settle(route, key, retained.regrant); forgetEarlierInvites(scope, body.email); const known = body.expected_revision === null ? revoked.get(scope)?.get(body.email) : undefined; revoked.get(scope)?.delete(body.email); const first = known === undefined ? body : { ...body, client_operation_id: randomUUID(), expected_revision: known }; try { return await (first === body ? call("POST", route, body) : regranting(route, key, first)); } catch (error) { const regrant = regrantOf(error, first); if (!regrant) throw error; return regranting(route, key, regrant); } }, }; } /** Every page of a grant list, revoked rows included where the server lists them. * @param {(method: string, route: string) => Promise} call @param {string} route * @returns {Promise} */ async function everyGrant(call, route) { const items = []; const cursors = new Set(); let cursor = null; do { const query = new URLSearchParams({ include_revoked: "true", ...(cursor ? { cursor } : {}) }); const page = await call("GET", `${route}?${query}`); items.push(...page.items); cursor = page.next_cursor; if (cursor && (cursors.has(cursor) || cursors.size >= 1000)) throw new ReviewFailed(502, "malformed_grant_pagination"); cursors.add(cursor); } while (cursor); return items; } /** @typedef {ReturnType} ReviewClient * @typedef {import("./types/reviewWire.js").ExportRequest} ExportRequest */ /** @param {(method: string, route: string, body?: unknown, headers?: Record) => Promise} call * @param {(id: string) => string} project @param {import("./types/access.js").ApiAccess} access */ function managementClient(call, project, access) { return { /** @param {string} id @param {{ title: string, expected_title: string }} body * @returns {Promise<{title: string}>} */ updateTitle: (id, body) => call("PATCH", project(id), body), /** @param {string} spaceId @param {string | null} [cursor] @returns * {Promise} */ listProjects: (spaceId, cursor = null) => call("GET", `${PROJECTS}?${new URLSearchParams(cursor ? { cursor } : {})}`, undefined, { "x-space-id": spaceId, }), /** @param {string} id @returns {Promise} */ removeProject: (id) => call("DELETE", project(id)), ...grantCalls(call, project, access), /** @param {string} id @param {string} grantId @param {{role: import("./types/reviewWire.js").AccessGrantDTO["role"], * expected_revision: number}} body @returns {Promise} */ updateGrant: (id, grantId, body) => call("PATCH", `${project(id)}/access-grants/${encodeURIComponent(grantId)}`, body), /** @param {string} id @param {string} grantId @returns {Promise} */ revokeGrant: (id, grantId) => call("DELETE", `${project(id)}/access-grants/${encodeURIComponent(grantId)}`), }; }