// @ts-check // Share for review: the project's review link. Its local id lives in .hyperframes/review.json; // copies skip .hyperframes, so a duplicate gets its own link, as the backend wants of a fork. import { withProjectShareLock } from "./projectLock.mjs"; import { firstReviewAudience } from "./reviewAudience.mjs"; import { createHmac, randomUUID, timingSafeEqual } from "node:crypto"; import path from "node:path"; import { mkdirInside } from "./storage.mjs"; import { isJsonObject, isNullableSavedId, isOptionalBoolean, isOptionalSavedId, isSavedId, readJsonRecord, SharingStateError, writeJsonAtomic, } from "./storage.mjs"; import { channelSite, journalKey, normalize, signinSites } from "./host.mjs"; 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").ProjectDTO} ProjectDTO */ /** @typedef {import("./types/share.js").ReviewShare} ReviewShare * @typedef {import("./types/share.js").ReviewSpace} ReviewSpace * @typedef {import("./types/share.js").ReviewAccessChange} ReviewAccessChange */ /** Persist studioProjectId/spaceId before sending so a lost reply retries the same project and space; projectId after. * opened marks the first completed share; site/ownerEmail bind the record to its backend/account. * @typedef {{ studioProjectId: string, spaceId: string|null, projectId: string|null, opened: boolean, * site: string, ownerEmail: string|null, removed?: boolean, registration?: * import("./types/reviewWire.js").RegisterProjectRequest | undefined }} ReviewRecord */ /** The sign-in site this run's review calls go to, the channel's own until then. * Ids from another site's server mean nothing here, so each site keeps its own record and never reads another's. * @type {string | null} */ let chosenSite = null; const site = () => chosenSite ?? channelSite(); /** @param {string} now */ export const setReviewSite = (now) => { chosenSite = now; }; /** The channel's own site keeps the original review.json; any other site its own file. * @param {string} projectPath @param {string} [at] */ const recordPath = (projectPath, at = site()) => path.join( projectPath, ".hyperframes", at === channelSite() ? "review.json" : `review-${new URL(at).host}.json`, ); /** The review metadata path for the current sign-in site. @param {string} projectPath */ export const reviewRecordPath = (projectPath) => recordPath(projectPath); /** @param {unknown} value @returns {value is import("./types/reviewWire.js").RegisterProjectRequest} */ function isRegistration(value) { return ( isJsonObject(value) && isSavedId(value.studio_project_id) && isSavedId(value.client_operation_id) && typeof value.title === "string" ); } /** @typedef {{ studioProjectId: string } & * Partial>} SavedIdentity */ /** @param {Record} record @returns {record is Record & SavedIdentity} */ const isSavedIdentity = (record) => isSavedId(record.studioProjectId) && isOptionalSavedId(record.spaceId) && isOptionalSavedId(record.projectId) && isOptionalBoolean(record.opened) && isOptionalBoolean(record.removed) && (!record.opened || isSavedId(record.projectId)); // This is a display hint. Keep ordinary mailbox names, including internationalized ones. /** @param {unknown} value */ function displayOwnerEmail(value) { if (typeof value !== "string" || value.length > 254) return null; const parts = value.split("@"); if (parts.length !== 2) return null; const [local, domain] = parts; const atom = /^[\p{L}\p{M}\p{N}!#$%&'*+/=?^`_{|}~-]+$/u; const label = /^[\p{L}\p{N}](?:[\p{L}\p{M}\p{N}-]{0,61}[\p{L}\p{M}\p{N}])?$/u; return local.length <= 64 && local.split(".").every((part) => atom.test(part)) && domain.split(".").every((part) => label.test(part)) ? value : null; } /** @param {unknown} value @param {string} studioProjectId @param {string} file */ function savedRegistration(value, studioProjectId, file) { if (value == null) return undefined; if (!isRegistration(value) || value.studio_project_id !== studioProjectId) throw new SharingStateError(file); return value; } /** @param {string} projectPath @param {string} [at] @returns {Promise} */ async function readRecord(projectPath, at = site()) { const file = recordPath(projectPath, at); const record = await readJsonRecord(file); if (!record) return null; const { site: madeOn = channelSite() } = record; if (madeOn !== at || !isSavedIdentity(record)) throw new SharingStateError(file); return { studioProjectId: record.studioProjectId, spaceId: record.spaceId ?? null, projectId: record.projectId ?? null, opened: record.opened === true, removed: record.removed === true, registration: savedRegistration(record.registration, record.studioProjectId, file), site: madeOn, ownerEmail: displayOwnerEmail(record.ownerEmail), }; } /** Production, or Dev for any other site. @param {string} at */ const backendName = (at) => (at === channelSite() ? "Production" : "Dev"); /** Not shared here, but shared on another backend: say where, so the person can switch or share again here. * @param {string} projectPath @returns {Promise} */ async function sharedElsewhere(projectPath) { for (const other of signinSites()) { const record = other === site() ? null : await readRecord(projectPath, other); if (record?.opened && record.projectId) return new ReviewFailed(409, `other_backend:${backendName(other)}`); } return null; } /** A space as the wire names it; `has_other_members` only when the server says. * @param {NonNullable | import("./types/reviewWire.js").SpaceDTO} space */ const spaceRefOf = (space) => ({ id: space.space_id, name: space.name, kind: space.kind, ...(typeof space.has_other_members === "boolean" && { hasOtherMembers: space.has_other_members }), }); /** @param {ShareDTO} share @returns {ReviewShare} */ const statusOf = (share) => ({ projectId: share.project_id, url: share.revoked ? null : share.review_url, access: share.access_mode, role: share.default_role, commentsOn: share.comments_enabled, space: share.space ? spaceRefOf(share.space) : null, elsewhere: false, entitlements: share.review_entitlements, ...(share.sharing_state && { sharingState: share.sharing_state }), held: share.moderation_hold === true, ...(takenDown(share) && { takedown: { page: share.authenticated_review_url } }), }); /** A staff takedown: the server refuses a new link and any audience but private until staff lift it. * @param {ShareDTO} share */ export const takenDown = (share) => share.moderation_hold_kind === "takedown"; /** The account's spaces as the server lists them; a server without the route answers 404: none. * @param {ReviewClient} client */ export const listSpaces = (client) => client.spaces().catch((error) => { if (error instanceof ReviewFailed && error.status === 404) return []; throw error; }); /** The workspace Desktop is signed into, where every new link goes: its token is bound there and ignores any other * space. The server marks it `bound`; a server that does not yet marks the one space it lets this token create in, else none. * @param {import("./types/reviewWire.js").SpaceDTO[]} spaces */ function signedInSpace(spaces) { const creatable = spaces.filter((space) => space.can_create_review); return spaces.find((space) => space.bound) ?? (creatable.length === 1 ? creatable[0] : null); } /** Every space the account is in, the signed-in one marked: the later workspace switch lists them; v1 names one. * @param {{ client: ReviewClient }} request @returns {Promise} */ export async function reviewSpaces({ client }) { const spaces = await listSpaces(client); const here = signedInSpace(spaces); return spaces.map((space) => ({ ...spaceRefOf(space), lastUsedAt: space.last_used_at, canCreate: space.can_create_review, signedIn: space === here, entitlements: space.review_entitlements, })); } /** The share as the person sees it: owner routes do not hold a token to its workspace, so a page in another one * than Desktop is signed into works as any other, and is only named (`elsewhere`). A failed list names nothing. * @param {ReviewClient} client @param {ShareDTO} share @returns {Promise} */ export async function shown(client, share) { const bound = (await listSpaces(client).catch(() => [])).find((space) => space.bound); const elsewhere = Boolean(bound && share.space && share.space.space_id !== bound.space_id); return { ...statusOf(share), elsewhere }; } /** An owner route's refusal for a project this app shared: 403 permission_denied is an owner who left its workspace, * a workspace deleted, or Desktop signed into another account (named, when the record knows whose it is); 404 is a * project another account shares now, or the server no longer has. * @param {ReviewClient} client @param {string} [projectPath] */ const ownerRefusal = (client, projectPath) => async (/** @type {unknown} */ error) => { if (!(error instanceof ReviewFailed)) throw error; if (error.reason === "permission_denied") { const [record, now] = await Promise.all([ projectPath ? readRecord(projectPath) : null, client.signedInEmail(), ]); const owner = record?.ownerEmail; const other = owner && now && owner.toLowerCase() !== now.toLowerCase(); throw new ReviewFailed(403, other ? OWNER_SIGNED_OUT + owner : "no_access"); } throw error.status === 404 ? new ReviewFailed(404, "another_account") : error; }; const OWNER_SIGNED_OUT = "owner_signed_out:"; /** The email in an owner_signed_out reason, else null. @param {string} reason */ export const ownerOf = (reason) => reason.startsWith(OWNER_SIGNED_OUT) ? reason.slice(OWNER_SIGNED_OUT.length) : null; /** A line per project: each step runs once the one before it settled; `busy` while one runs or waits. */ export function projectLine() { /** @type {Map>} */ const queues = new Map(); /** @template T @param {string} projectPath @param {() => Promise} run @returns {Promise} */ const inTurn = (projectPath, run) => { const key = normalize(projectPath); const next = (queues.get(key) ?? Promise.resolve()).then(run, run); const settled = next.catch(() => {}); queues.set(key, settled); void settled.then(() => queues.get(key) === settled && queues.delete(key)); return next; }; return { inTurn, busy: (/** @type {string} */ projectPath) => queues.has(normalize(projectPath)), }; } /** One change per project at a time, so two presses never register twice or race a revision. */ const metadataLine = projectLine().inTurn; /** @template T @param {string} projectPath @param {() => Promise} run */ export const oneAtATime = (projectPath, run) => metadataLine(projectPath, () => withProjectShareLock(projectPath, "review", run)); /** Applies the person's choice over whatever else the share holds; a stale revision is read again once. * @param {ReviewClient} client @param {string} id @param {ShareDTO} share * @param {Partial>} change @returns {Promise} */ export async function changeShare(client, id, share, change) { for (let read = share, retried = false; ; retried = true) { const body = { access_mode: read.access_mode, default_role: read.default_role, comments_enabled: read.comments_enabled, ...change, expected_revision: read.revision, }; // Only the workspace's audience may default to Can edit: leaving it hands the new audience Can comment. if (body.access_mode !== "team" && body.default_role === "editor") body.default_role = "commenter"; try { return await client.updateShare(id, body); } catch (error) { const stale = error instanceof ReviewFailed && error.reason === "revision_conflict"; if (retried || !stale) throw error; read = await client.share(id); } } } /** @param {string} projectPath @param {ReviewClient} _client */ async function sharedId(projectPath, _client) { const record = await readRecord(projectPath); if (record?.removed) throw new ReviewFailed(410, "review_project_removed"); if (!record?.opened || !record.projectId) throw (await sharedElsewhere(projectPath)) ?? new ReviewFailed(404, "not_shared"); return record.projectId; } /** The server's id for a project this app finished sharing, else null; the comment feed reads it. * @param {string} projectPath @returns {Promise} */ export async function reviewProjectId(projectPath) { const record = await readRecord(projectPath); return !record?.removed && record?.opened && record.projectId ? record.projectId : null; } /** Which local project each review project was shared from: review project id to its folder. * @param {string[]} paths @returns {Promise>} */ export async function localReviewProjects(paths) { const pairs = await Promise.all(paths.map(async (dir) => [await reviewProjectId(dir), dir])); return Object.fromEntries(pairs.filter(([id]) => id)); } /** The record's ids, for a change of space. @param {string} projectPath */ export const reviewRecord = (projectPath) => readRecord(projectPath); /** Where a change of space waits: beside this backend's record, so one backend never finishes or drops another's. * @param {string} projectPath */ export const reviewSwitchPath = (projectPath) => recordPath(projectPath).replace(/\.json$/, ".switch.json"); /** The host's key over the project's folder and the journal's own text. * @param {Uint8Array} key @param {string} dir @param {object} change */ const sealOf = (key, dir, change) => createHmac("sha256", key) .update(`${normalize(dir)}\0${JSON.stringify(change)}`) .digest(); /** A journal as the kernel writes it: sealed when the host gave a key, so another party's journal can't pass for it. * @template {object} T @param {string} dir @param {T} change */ export function sealedSwitch(dir, change) { const key = journalKey(); return key ? { ...change, seal: sealOf(key, dir, change).toString("hex") } : change; } /** With a host key, the journal without its seal when the seal is that key's over this folder, else null. * @param {string} dir @param {Record} read */ function unsealed(dir, read) { const key = journalKey(); if (!key) return read; const { seal, ...change } = read; if (typeof seal !== "string" || !/^[0-9a-f]{64}$/.test(seal)) return null; return timingSafeEqual(Buffer.from(seal, "hex"), sealOf(key, dir, change)) ? change : null; } /** The change of space waiting in the project; one the host's key did not seal is none. * @param {string} dir @returns {Promise} */ export async function readReviewSwitch(dir) { const file = reviewSwitchPath(dir); const read = await readJsonRecord(file); const change = read && unsealed(dir, read); if (!change) return null; if ( !isSavedId(change.from) || !isSavedId(change.spaceId) || typeof change.space !== "string" || !isNullableSavedId(change.projectId) || (change.id !== undefined && !isSavedId(change.id)) || !isOptionalBoolean(change.opened) || !isOptionalBoolean(change.paused) || (change.opened && !isSavedId(change.projectId)) || !isRegistration(change.body) ) { throw new SharingStateError(file); } return /** @type {import("./reviewSwitch.mjs").Switch} */ (change); } /** @type {Set<(projectPath: string) => void>} */ const rebound = new Set(); /** Called with a project's normalized path once its record names another review project. * @param {(projectPath: string) => void} listener */ export const onRebound = (listener) => void rebound.add(listener); /** Tells every listener that a project's record names another review project now. @param {string} projectPath */ const announceRebound = (projectPath) => { for (const listener of rebound) listener(normalize(projectPath)); }; /** Points the record at another review project, keeping every other field the record holds. * @param {string} projectPath @param {string} projectId @param {string} spaceId */ export async function rebindRecord(projectPath, projectId, spaceId) { const record = await readRecord(projectPath); if (!record) throw new ReviewFailed(404, "not_shared"); if (record.removed) throw new ReviewFailed(410, "review_project_removed"); await writeJsonAtomic(recordPath(projectPath), { ...record, projectId, spaceId, opened: true }); announceRebound(projectPath); } /** Puts a project's record aside, so the next share registers it anew from the signed-in account: a new id and a new * link. The old record stays beside it as review.previous-