From 2d42e91fbe8077b90659ffba96e3c120e6ada073 Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:23:30 +0700 Subject: [PATCH] feat(doop): close proof and land_proposal policy rule, inert (CHE-9672) verifyLanding rebuilds the close proof from Multica and the sent bytes. assertWritable gains land_proposal, which needs a proof only verifyLanding can make. No caller yet (S3b); DOOP_LANDING stays off. --- server/landingProof.ts | 216 ++++++++++++++++++ server/pageState.ts | 4 +- server/writePolicy.ts | 33 +++ tests/landingProof.test.ts | 455 +++++++++++++++++++++++++++++++++++++ 4 files changed, 706 insertions(+), 2 deletions(-) create mode 100644 server/landingProof.ts create mode 100644 tests/landingProof.test.ts diff --git a/server/landingProof.ts b/server/landingProof.ts new file mode 100644 index 000000000..8f267b31e --- /dev/null +++ b/server/landingProof.ts @@ -0,0 +1,216 @@ +import { createHash } from 'node:crypto' +import { PolicyRefused } from './policyRefused.ts' + +/** + * CHE-9672 (A5 landing S3c): the close proof. `verifyLanding` rebuilds, from Multica and from the bytes the + * caller sent, the facts that make a landing legitimate, and returns a `LandingProof` only when all of them + * hold. `assertWritable`'s `land_proposal` rule accepts nothing else. Inert: no route calls it yet (S3b). + * + * The Multica reads sit behind `LandingMultica`, so this file guesses no REST path and imports nothing from + * the checklist module (S3a). The proof is a server-side value: `isLandingProof` knows only objects this + * module made, so a proof-shaped object from input, a spread or a JSON round trip is not one. + */ + +/** What S3a's `trustedChecklist` returns: the record the watcher keeps on the topic issue. */ +export type TrustedChecklist = { + link: { canvas: string; topic: string } + decisionId: string + /** the `Lock pin: …` line */ + pin: string + recordCommentId: string +} + +export interface LandingMultica { + /** `DOOP_LANDING_WATCHER_ID`; unset means no proof can be made */ + readonly watcherId: string | undefined + /** S3a. Its refusals carry a `code`, which passes through. */ + trustedChecklist(issueId: string): Promise + /** `GET /api/decisions/:id` */ + decision(id: string): Promise + /** the workspace member list: `{ user_id, role }[]` */ + members(workspaceId: string): Promise +} + +export type LandingFrame = { frameId: string; html: string; contentSha256: string } + +export type LandingRequest = { + canvasId: string + topicIssueId: string + sourcePageId: string + /** the source page's name, as the server resolved it (the checklist link names the topic) */ + sourcePageName: string + closeDecisionId: string + /** the `Lock pin: …` line */ + pin: string + /** the exact bytes of LOCK.json */ + lockJson: string + frames: LandingFrame[] +} + +declare const landingBrand: unique symbol + +export type LandingProof = Readonly<{ + projectId: string + issueId: string + canvasId: string + sourcePageId: string + sourcePageName: string + decisionId: string + recordCommentId: string + pin: string + watcherId: string + frames: readonly { frameId: string; contentSha256: string }[] +}> & { readonly [landingBrand]: true } + +const issued = new WeakSet() + +/** Whether `value` was returned by `verifyLanding` in this process. */ +export const isLandingProof = (value: unknown): value is LandingProof => + typeof value === 'object' && value !== null && issued.has(value) + +const OP = 'land_proposal' +const refuse = (code: string, reason: string): never => { + throw new PolicyRefused(OP, reason, code) +} +const sha256 = (text: string) => createHash('sha256').update(text).digest('hex') +const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value) +const text = (value: unknown): string | undefined => (typeof value === 'string' && value ? value : undefined) + +/** A Multica read that failed or came back malformed: nothing is proven. */ +const unavailable = (what: string): never => refuse('proof_unavailable', `${what} unavailable`) + +async function read(what: string, call: () => Promise): Promise { + try { + return await call() + } catch (error) { + if (error instanceof PolicyRefused) throw error + return unavailable(what) + } +} + +/** The options of a decision: a JSON array, or the base64 JSON the list endpoint sends. */ +function optionLabels(options: unknown): (string | undefined)[] { + let list = options + if (typeof options === 'string') { + try { + list = JSON.parse(Buffer.from(options, 'base64').toString('utf8')) + } catch { + return unavailable('decision options') + } + } + if (!Array.isArray(list)) return unavailable('decision options') + return list.map((option) => (isRecord(option) ? text(option.label) : typeof option === 'string' ? option : undefined)) +} + +function checkDecision(decision: unknown, req: LandingRequest, watcherId: string) { + if (!isRecord(decision)) return unavailable('decision') + if (decision.id !== undefined && decision.id !== req.closeDecisionId) + refuse('decision_mismatch', 'Multica returned another decision') + if (decision.kind !== 'decision') refuse('decision_kind', 'the close record is not a decision') + const answer = decision.answer + if (decision.status !== 'answered' || !isRecord(answer)) + refuse('decision_not_answered', 'the decision is not answered') + const given = answer as Record + if (decision.withdrawn_at) refuse('decision_withdrawn', 'the decision was withdrawn') + if (decision.authority !== 'human') refuse('decision_not_human', 'the decision does not need a human') + if (decision.asking_agent_id !== watcherId) + refuse('decision_not_watcher', 'the decision was not asked by the watcher') + if (decision.issue_id !== req.topicIssueId) refuse('decision_wrong_issue', 'the decision is on another issue') + const index = given.chosen_option_index + const label = typeof index === 'number' ? optionLabels(decision.options)[index] : undefined + if (label !== 'close' || given.content_snapshot !== 'close') refuse('decision_not_close', 'the answer is not close') + if (given.disclaimed_at) refuse('decision_disclaimed', 'the answer was disclaimed') + const humanId = text(decision.human_user_id) + if (!humanId || given.answered_by_user_id !== humanId) + refuse('decision_answerer', 'the decision was not answered by its human') + const projectId = text(decision.project_id) + const workspaceId = text(decision.workspace_id) + if (!projectId || !workspaceId) return unavailable('decision project') + return { projectId, workspaceId, humanId, ask: typeof decision.ask === 'string' ? decision.ask : '' } +} + +function checkPinLine(ask: string, pin: string): void { + const lines = ask.split(/\r?\n/).filter((line) => line.trim().startsWith('Lock pin:')) + if (lines.length === 0) refuse('pin_line_missing', 'the decision text has no pin line') + if (lines.length > 1) refuse('pin_line_ambiguous', 'the decision text has more than one pin line') + if (lines[0]?.trim() !== pin) refuse('pin_line_mismatch', 'the decision pin line is not the record pin') +} + +function checkLock(req: LandingRequest): void { + const manifest = /\bmanifest=([0-9a-f]{64})\b/.exec(req.pin)?.[1] + if (!manifest || sha256(req.lockJson) !== manifest) + refuse('manifest_mismatch', 'LOCK.json is not the pinned manifest') + let lock: unknown + try { + lock = JSON.parse(req.lockJson) + } catch { + return refuse('lock_invalid', 'LOCK.json is not JSON') + } + if (!isRecord(lock) || !Array.isArray(lock.screens)) return refuse('lock_invalid', 'LOCK.json has no screens') + if (lock.canvas_or_project_id !== req.canvasId) refuse('lock_mismatch', 'LOCK.json names another canvas') + if (lock.page_id !== req.sourcePageId) refuse('lock_mismatch', 'LOCK.json names another page') + const entries = new Map() + for (const screen of lock.screens as unknown[]) { + const frameId = isRecord(screen) ? text(screen.frame_id) : undefined + if (!frameId || entries.has(frameId)) return refuse('lock_invalid', 'LOCK.json has a bad or repeated frame id') + entries.set(frameId, (screen as Record).content_sha256) + } + const sent = new Set(req.frames.map((frame) => frame.frameId)) + if (sent.size !== req.frames.length || sent.size !== entries.size || [...sent].some((id) => !entries.has(id))) + refuse('lock_mismatch', 'LOCK.json frames are not the frames sent') + for (const frame of req.frames) + if (entries.get(frame.frameId) !== frame.contentSha256 || sha256(frame.html) !== frame.contentSha256) + refuse('frame_hash_mismatch', `frame ${frame.frameId} does not hash to its LOCK.json entry`) +} + +/** + * Throws a `PolicyRefused` (op `land_proposal`, a code per failed check) unless the request is a legitimate + * landing: the trusted checklist names this decision, pin, canvas and topic; the decision is an answered, + * undisclaimed, human `close` asked by the watcher on the topic issue, answered by its human, who is an owner; + * its text holds exactly the record pin; and the sent LOCK.json and frames match the pin. + */ +export async function verifyLanding(req: LandingRequest, multica: LandingMultica): Promise { + const watcherId = text(multica.watcherId) + if (!watcherId) return unavailable('the landing watcher setting') + + let checklist: TrustedChecklist + try { + checklist = await multica.trustedChecklist(req.topicIssueId) + } catch (error) { + const code = isRecord(error) ? text(error.code) : undefined + if (code) refuse(code, error instanceof Error ? error.message : 'the checklist was refused') + return unavailable('the checklist') + } + if (checklist.decisionId !== req.closeDecisionId) + refuse('decision_mismatch', 'the request names a decision the record does not') + if (checklist.pin !== req.pin) refuse('pin_mismatch', 'the request pin is not the record pin') + if (checklist.link.canvas !== req.canvasId || checklist.link.topic !== req.sourcePageName) + refuse('link_mismatch', 'the record link names another canvas or topic') + + const decision = await read('the decision', () => multica.decision(req.closeDecisionId)) + const { projectId, workspaceId, humanId, ask } = checkDecision(decision, req, watcherId) + + const members = await read('the member list', () => multica.members(workspaceId)) + if (!Array.isArray(members)) return unavailable('the member list') + if (!members.some((member) => isRecord(member) && member.user_id === humanId && member.role === 'owner')) + refuse('answerer_not_owner', 'the decision human is not an owner') + + checkPinLine(ask, req.pin) + checkLock(req) + + const proof = Object.freeze({ + projectId, + issueId: req.topicIssueId, + canvasId: req.canvasId, + sourcePageId: req.sourcePageId, + sourcePageName: req.sourcePageName, + decisionId: req.closeDecisionId, + recordCommentId: checklist.recordCommentId, + pin: req.pin, + watcherId, + frames: Object.freeze(req.frames.map(({ frameId, contentSha256 }) => ({ frameId, contentSha256 }))), + }) as unknown as LandingProof + issued.add(proof) + return proof +} diff --git a/server/pageState.ts b/server/pageState.ts index 7f5d01110..126f9dc27 100644 --- a/server/pageState.ts +++ b/server/pageState.ts @@ -42,8 +42,8 @@ export function refuseFinishedFrame(canvas: Canvas, frame: Frame, op = 'update_f throw new PageFinishedError(op, finishedPageName(canvas, frame)) } -/** Ops the freeze covers: frame writes. `lock_frame` and `unlock_frame` stay open. */ -const FROZEN_OPS: ReadonlySet = new Set(['create_frame', 'update_frame', 'delete_frame']) +/** Ops the freeze covers: frame writes, and a landing (its `pageIds` is the destination). `lock_frame` and `unlock_frame` stay open. */ +const FROZEN_OPS: ReadonlySet = new Set(['create_frame', 'update_frame', 'delete_frame', 'land_proposal']) /** * The page rule of `assertWritable`, run right after the lock rules and for every context. `lockOnly` diff --git a/server/writePolicy.ts b/server/writePolicy.ts index 00dcaf134..4d21807c3 100644 --- a/server/writePolicy.ts +++ b/server/writePolicy.ts @@ -1,5 +1,6 @@ import { canvasPages, framePageId } from '../shared/pages.ts' import { checkReconGate, isReconHtml, reconRefusal } from './reconGuard.ts' +import { isLandingProof, type LandingProof } from './landingProof.ts' import { assertPageRules } from './pageState.ts' import { FrameLockedError, PolicyRefused } from './policyRefused.ts' import type { Actor, Canvas, CanvasPageInfo, Frame } from '../shared/types.ts' @@ -25,6 +26,8 @@ export type WriteContext = { origin?: 'mcp' | 'sync' /** account erasure only (`erasureContext`): may delete a canvas that still holds a locked frame */ erasure?: boolean + /** `land_proposal` only: the proof `verifyLanding` made. A server-side value, never parsed from input. */ + landing?: LandingProof } export type WriteOp = @@ -38,12 +41,15 @@ export type WriteOp = | 'lock_frame' | 'unlock_frame' | 'set_page_state' + | 'land_proposal' export type WriteTarget = { canvas: Canvas frame?: Frame /** the page the write lands on (frame page, destination page, source page) */ pageIds?: string[] + /** land_proposal: the page the proposal comes from (its Finished state is not checked; `pageIds` is the destination) */ + sourcePageId?: string /** set_pages: the list being saved */ nextPages?: CanvasPageInfo[] /** create_frame: the HTML the new frame starts with (the recon frame itself is exempt from G2) */ @@ -127,6 +133,7 @@ const OPS: ReadonlySet = new Set([ 'lock_frame', 'unlock_frame', 'set_page_state', + 'land_proposal', ]) function assertLockRules(ctx: WriteContext, op: WriteOp, target: WriteTarget): void { @@ -168,11 +175,37 @@ export function assertWritable(ctx: WriteContext, op: WriteOp, target: WriteTarg if (!OPS.has(op)) throw new PolicyRefused(op, 'unknown operation') assertLockRules(ctx, op, target) assertPageRules(op, target) + if (op === 'land_proposal') return assertLanding(ctx, target) if (ctx.kind !== 'agent') return assertBinding(ctx, op, target) if (op === 'create_frame') assertRecon(ctx, target) } +/** + * A landing (CHE-9672): the one write a taskless agent may make on a bound canvas, and only with a + * `LandingProof` from `verifyLanding`. The proof, not the actor, is the authority, so every kind of context + * needs it and `assertBinding` is not asked. It must be for this canvas and project, the source page must be + * the proof's topic (bound to its issue when bound at all), and the destination is the ledger page alone. + */ +function assertLanding(ctx: WriteContext, target: WriteTarget): void { + const op = 'land_proposal' + const proof = ctx.landing + if (!isLandingProof(proof)) throw new PolicyRefused(op, 'a landing needs a proof from verifyLanding') + const { canvas } = target + if (!canvas.projectId || canvas.projectId !== proof.projectId) + throw new PolicyRefused(op, 'canvas is not bound to the proof project') + if (canvas.id !== proof.canvasId) throw new PolicyRefused(op, 'the proof is for another canvas') + const pages = canvasPages(canvas) + const source = pages.find((page) => page.id === target.sourcePageId) + if (!source || source.id !== proof.sourcePageId || source.name !== proof.sourcePageName) + throw new PolicyRefused(op, 'source page is not the proof topic') + if (source.issueId && source.issueId !== proof.issueId) + throw new PolicyRefused(op, 'source page is bound to another issue') + const ledger = pages.find((page) => page.ledger) + if (!ledger || target.pageIds?.length !== 1 || target.pageIds[0] !== ledger.id) + throw new PolicyRefused(op, 'a landing goes to the ledger page only') +} + /** * G2: a design frame on a page bound to an issue waits for a complete, confirmed, locked recon. The * recon frame is exempt, so it can be made first. Fail closed: a throw anywhere inside is a refusal. diff --git a/tests/landingProof.test.ts b/tests/landingProof.test.ts new file mode 100644 index 000000000..2cc3b3cd8 --- /dev/null +++ b/tests/landingProof.test.ts @@ -0,0 +1,455 @@ +import { createHash } from 'node:crypto' +import { describe, expect, it, vi, type Mock } from 'vitest' +import { + verifyLanding, + type LandingMultica, + type LandingProof, + type LandingRequest, + type TrustedChecklist, +} from '../server/landingProof.ts' +import { PageFinishedError } from '../server/pageState.ts' +import { assertWritable, PolicyRefused, type WriteContext, type WriteTarget } from '../server/writePolicy.ts' +import type { Canvas } from '../shared/types.ts' + +/* CHE-9672 (A5 landing S3c): verifyLanding rebuilds the close proof from Multica and the sent bytes, and + `land_proposal` is a write op whose policy rule needs a proof that only verifyLanding makes. Inert: no + caller yet (S3b). Multica is a fake; the trusted checklist is S3a's interface, injected. */ + +const sha = (text: string) => createHash('sha256').update(text).digest('hex') + +const WATCHER = 'watcher-agent' +const OWNER = 'owner-user' +const ISSUE = 'topic-issue' +const PROJECT = 'proj-a' +const CANVAS = 'canvas-1' +const SOURCE_PAGE = 'che-5478' +const TOPIC = 'Lifecycle UI' +const DECISION = 'decision-1' +const WORKSPACE = 'ws-1' + +const htmlA = '

frame a

' +const htmlB = '

frame b

' +const lockOf = (over: Record = {}) => + JSON.stringify({ + provider: 'doop', + canvas_or_project_id: CANVAS, + page_id: SOURCE_PAGE, + screens: [ + { screen: 'A', frame_id: 'fa', file: 'a.html', content_sha256: sha(htmlA) }, + { screen: 'B', frame_id: 'fb', file: 'b.html', content_sha256: sha(htmlB) }, + ], + ...over, + }) +const pinOf = (lockJson: string) => + `Lock pin: repo=cheese-work/doop pr=39 sha=${'a'.repeat(40)} path=design/lifecycle-ui/approved/LOCK.json manifest=${sha(lockJson)} canvas=${CANVAS} page=${SOURCE_PAGE}` + +type World = { + req: LandingRequest + checklist: TrustedChecklist + decision: Record + members: Record[] + watcherId: string | undefined + multica: LandingMultica + trusted: Mock +} + +function world(over: { lockJson?: string; pin?: string } = {}): World { + const lockJson = over.lockJson ?? lockOf() + const pin = over.pin ?? pinOf(lockJson) + const w: Omit & { multica?: LandingMultica; trusted?: World['trusted'] } = { + req: { + canvasId: CANVAS, + topicIssueId: ISSUE, + sourcePageId: SOURCE_PAGE, + sourcePageName: TOPIC, + closeDecisionId: DECISION, + pin, + lockJson, + frames: [ + { frameId: 'fa', html: htmlA, contentSha256: sha(htmlA) }, + { frameId: 'fb', html: htmlB, contentSha256: sha(htmlB) }, + ], + } satisfies LandingRequest, + checklist: { + link: { canvas: CANVAS, topic: TOPIC }, + decisionId: DECISION, + pin, + recordCommentId: 'comment-1', + } satisfies TrustedChecklist, + decision: { + id: DECISION, + kind: 'decision', + status: 'answered', + authority: 'human', + asking_agent_id: WATCHER, + issue_id: ISSUE, + project_id: PROJECT, + workspace_id: WORKSPACE, + human_user_id: OWNER, + withdrawn_at: null, + ask: `Close the proposal?\n\n${pin}\n\nMore text.`, + options: [{ label: 'close' }, { label: 'keep open' }], + answer: { + answered_by_user_id: OWNER, + chosen_option_index: 0, + content_snapshot: 'close', + disclaimed_at: null, + }, + } as Record, + members: [ + { user_id: OWNER, role: 'owner' }, + { user_id: 'someone', role: 'member' }, + ] as Record[], + watcherId: WATCHER as string | undefined, + } + w.trusted = vi.fn(async () => w.checklist) + /* one object, mutated by the tests: the fake reads it live, so no copy is returned */ + w.multica = { + get watcherId() { + return w.watcherId + }, + trustedChecklist: w.trusted, + decision: async () => w.decision, + members: async () => w.members, + } + return w as World +} + +const refused = async (w: World) => { + try { + await verifyLanding(w.req, w.multica) + } catch (error) { + return (error as { code?: string }).code + } + return 'accepted' +} + +describe('verifyLanding', () => { + it('accepts the valid case and returns the proof ids', async () => { + const w = world() + const proof = await verifyLanding(w.req, w.multica) + expect(proof).toMatchObject({ + canvasId: CANVAS, + projectId: PROJECT, + issueId: ISSUE, + decisionId: DECISION, + recordCommentId: 'comment-1', + watcherId: WATCHER, + sourcePageName: TOPIC, + }) + expect(proof.pin).toBe(w.req.pin) + expect(proof.frames).toEqual([ + { frameId: 'fa', contentSha256: sha(htmlA) }, + { frameId: 'fb', contentSha256: sha(htmlB) }, + ]) + expect(w.trusted).toHaveBeenCalledWith(ISSUE) + }) + + it('settings unset: proof_unavailable, and Multica is not asked', async () => { + const w = world() + w.watcherId = undefined + expect(await refused(w)).toBe('proof_unavailable') + expect(w.trusted).not.toHaveBeenCalled() + }) + + it('passes a trustedChecklist refusal through with its code', async () => { + const w = world() + w.trusted.mockRejectedValueOnce(Object.assign(new Error('x'), { code: 'watcher_mismatch' })) + expect(await refused(w)).toBe('watcher_mismatch') + }) + + it('maps a transport failure to proof_unavailable', async () => { + const a = world() + a.trusted.mockRejectedValueOnce(new Error('boom')) + expect(await refused(a)).toBe('proof_unavailable') + const b = world() + b.multica.decision = async () => { + throw new Error('500') + } + expect(await refused(b)).toBe('proof_unavailable') + const c = world() + c.multica.members = async () => { + throw new Error('500') + } + expect(await refused(c)).toBe('proof_unavailable') + }) + + it('an unrelated owner close on the same issue refuses: the request names another decision', async () => { + const w = world() + w.req = { ...w.req, closeDecisionId: 'decision-other' } + w.decision = { ...w.decision, id: 'decision-other' } + expect(await refused(w)).toBe('decision_mismatch') + }) + + it('a superseded checklist answered close refuses: the record now names a newer decision', async () => { + const w = world() + w.checklist = { ...w.checklist, decisionId: 'decision-newer' } + expect(await refused(w)).toBe('decision_mismatch') + }) + + it('a pin that is not the record pin refuses', async () => { + const w = world() + w.req = { ...w.req, pin: w.req.pin.replace('pr=39', 'pr=40') } + expect(await refused(w)).toBe('pin_mismatch') + }) + + it('the link must name the request canvas and the source page name', async () => { + const a = world() + a.checklist = { ...a.checklist, link: { ...a.checklist.link, canvas: 'canvas-2' } } + expect(await refused(a)).toBe('link_mismatch') + const b = world() + b.checklist = { ...b.checklist, link: { ...b.checklist.link, topic: 'Other topic' } } + expect(await refused(b)).toBe('link_mismatch') + }) + + const decisionCases: [string, (d: Record) => Record, string][] = [ + ['kind is not decision', (d) => ({ ...d, kind: 'approval' }), 'decision_kind'], + ['status is open', (d) => ({ ...d, status: 'open' }), 'decision_not_answered'], + ['no answer', (d) => ({ ...d, answer: null }), 'decision_not_answered'], + ['withdrawn', (d) => ({ ...d, withdrawn_at: '2026-11-26T00:00:00Z' }), 'decision_withdrawn'], + ['authority is not human', (d) => ({ ...d, authority: 'agent' }), 'decision_not_human'], + ['asked by another agent', (d) => ({ ...d, asking_agent_id: 'agent-x' }), 'decision_not_watcher'], + ['on another issue', (d) => ({ ...d, issue_id: 'other-issue' }), 'decision_wrong_issue'], + [ + 'chosen option is not close', + (d) => ({ ...d, answer: { ...(d.answer as object), chosen_option_index: 1, content_snapshot: 'keep open' } }), + 'decision_not_close', + ], + [ + 'content snapshot differs from the chosen label', + (d) => ({ ...d, answer: { ...(d.answer as object), content_snapshot: 'Close' } }), + 'decision_not_close', + ], + [ + 'text-only answer (no chosen option)', + (d) => ({ ...d, answer: { ...(d.answer as object), chosen_option_index: null } }), + 'decision_not_close', + ], + [ + 'disclaimed', + (d) => ({ ...d, answer: { ...(d.answer as object), disclaimed_at: '2026-11-26T00:00:00Z' } }), + 'decision_disclaimed', + ], + [ + 'answered by a user who is not the human', + (d) => ({ ...d, answer: { ...(d.answer as object), answered_by_user_id: 'someone' } }), + 'decision_answerer', + ], + ] + for (const [name, change, code] of decisionCases) + it(`decision ${name} -> ${code}`, async () => { + const w = world() + w.decision = change(w.decision) + expect(await refused(w)).toBe(code) + }) + + it('the human must be an owner in the member list', async () => { + const a = world() + a.members = [{ user_id: OWNER, role: 'admin' }] + expect(await refused(a)).toBe('answerer_not_owner') + const b = world() + b.members = [{ user_id: 'someone', role: 'owner' }] + expect(await refused(b)).toBe('answerer_not_owner') + }) + + it('options may arrive base64-encoded, as the list endpoint sends them', async () => { + const w = world() + w.decision = { ...w.decision, options: Buffer.from(JSON.stringify([{ label: 'close' }])).toString('base64') } + expect(await refused(w)).toBe('accepted') + }) + + it('exactly one pin line in the decision text, equal to the record pin', async () => { + const none = world() + none.decision = { ...none.decision, ask: 'Close the proposal?' } + expect(await refused(none)).toBe('pin_line_missing') + const two = world() + two.decision = { ...two.decision, ask: `${two.req.pin}\n${two.req.pin}` } + expect(await refused(two)).toBe('pin_line_ambiguous') + const other = world() + other.decision = { ...other.decision, ask: other.req.pin.replace('pr=39', 'pr=41') } + expect(await refused(other)).toBe('pin_line_mismatch') + }) + + it('the sent LOCK.json must hash to the pin manifest', async () => { + const w = world() + w.req = { ...w.req, lockJson: `${w.req.lockJson}\n` } + expect(await refused(w)).toBe('manifest_mismatch') + }) + + it('LOCK.json canvas, page and frame set must equal the request', async () => { + const cases: Record = { + canvas: lockOf({ canvas_or_project_id: 'canvas-9' }), + page: lockOf({ page_id: 'other-page' }), + missing: lockOf({ screens: [{ frame_id: 'fa', file: 'a', content_sha256: sha(htmlA) }] }), + extra: lockOf({ + screens: [ + { frame_id: 'fa', file: 'a', content_sha256: sha(htmlA) }, + { frame_id: 'fb', file: 'b', content_sha256: sha(htmlB) }, + { frame_id: 'fc', file: 'c', content_sha256: sha('c') }, + ], + }), + } + for (const [name, lockJson] of Object.entries(cases)) { + const w = world({ lockJson }) + expect(await refused(w), name).toBe('lock_mismatch') + } + const notJson = world({ lockJson: 'not json' }) + expect(await refused(notJson)).toBe('lock_invalid') + }) + + it('a repeated frame id in the request refuses', async () => { + const w = world() + w.req = { ...w.req, frames: [...w.req.frames, w.req.frames[0]!] } + expect(await refused(w)).toBe('lock_mismatch') + }) + + it('each frame hash must equal its LOCK.json entry and the SHA256 of its html', async () => { + const entry = world() + entry.req = { + ...entry.req, + frames: [{ ...entry.req.frames[0]!, contentSha256: sha('x') }, entry.req.frames[1]!], + } + expect(await refused(entry)).toBe('frame_hash_mismatch') + const bytes = world() + bytes.req = { ...bytes.req, frames: [{ ...bytes.req.frames[0]!, html: '

changed

' }, bytes.req.frames[1]!] } + expect(await refused(bytes)).toBe('frame_hash_mismatch') + }) +}) + +/* ---- the land_proposal rule of assertWritable ---- */ + +const LEDGER = 'ledger' +function canvasOf(over: { projectId?: string | undefined; pages?: Canvas['pages']; id?: string } = {}): Canvas { + return { + id: over.id ?? CANVAS, + name: 'c', + ownerId: 'u', + projectId: 'projectId' in over ? over.projectId : PROJECT, + pages: over.pages ?? [ + { id: LEDGER, name: 'Ledger', ledger: true }, + { id: SOURCE_PAGE, name: TOPIC, issueId: ISSUE }, + ], + frames: [], + } as unknown as Canvas +} +const proofOf = async (): Promise => { + const w = world() + return verifyLanding(w.req, w.multica) +} +const target = (canvas: Canvas, over: Partial = {}): WriteTarget => ({ + canvas, + sourcePageId: SOURCE_PAGE, + pageIds: [LEDGER], + ...over, +}) +const sys: WriteContext = { kind: 'system' } +const taskless: WriteContext = { kind: 'agent', origin: 'mcp' } + +describe('assertWritable land_proposal', () => { + it('refuses without a LandingProof, for every kind of context', async () => { + const canvas = canvasOf() + for (const ctx of [sys, taskless, { kind: 'user', userId: 'u' } as WriteContext]) + expect(() => assertWritable(ctx, 'land_proposal', target(canvas))).toThrow(PolicyRefused) + }) + + it('refuses a proof-shaped object that verifyLanding did not make', async () => { + const real = await proofOf() + const forged = { ...real } as LandingProof + expect(() => assertWritable({ ...sys, landing: forged }, 'land_proposal', target(canvasOf()))).toThrow( + PolicyRefused, + ) + }) + + it('passes with a proof: system context and a taskless MCP agent on a bound canvas', async () => { + const landing = await proofOf() + const canvas = canvasOf() + expect(() => assertWritable({ ...sys, landing }, 'land_proposal', target(canvas))).not.toThrow() + expect(() => assertWritable({ ...taskless, landing }, 'land_proposal', target(canvas))).not.toThrow() + }) + + it('refuses a proof from another project, or for another canvas', async () => { + const landing = await proofOf() + expect(() => + assertWritable({ ...taskless, landing }, 'land_proposal', target(canvasOf({ projectId: 'proj-b' }))), + ).toThrow(PolicyRefused) + expect(() => + assertWritable({ ...taskless, landing }, 'land_proposal', target(canvasOf({ projectId: undefined }))), + ).toThrow(PolicyRefused) + expect(() => + assertWritable({ ...taskless, landing }, 'land_proposal', target(canvasOf({ id: 'canvas-2' }))), + ).toThrow(PolicyRefused) + }) + + it('refuses a source page bound to another issue; an unbound source page passes', async () => { + const landing = await proofOf() + const bound = canvasOf({ + pages: [ + { id: LEDGER, name: 'Ledger', ledger: true }, + { id: SOURCE_PAGE, name: TOPIC, issueId: 'other-issue' }, + ], + }) + expect(() => assertWritable({ ...taskless, landing }, 'land_proposal', target(bound))).toThrow(PolicyRefused) + const unbound = canvasOf({ + pages: [ + { id: LEDGER, name: 'Ledger', ledger: true }, + { id: SOURCE_PAGE, name: TOPIC }, + ], + }) + expect(() => assertWritable({ ...taskless, landing }, 'land_proposal', target(unbound))).not.toThrow() + }) + + it('refuses a source page that is missing or is not the proof topic', async () => { + const landing = await proofOf() + const canvas = canvasOf() + expect(() => + assertWritable({ ...taskless, landing }, 'land_proposal', target(canvas, { sourcePageId: 'nope' })), + ).toThrow(PolicyRefused) + const renamed = canvasOf({ + pages: [ + { id: LEDGER, name: 'Ledger', ledger: true }, + { id: SOURCE_PAGE, name: 'Another name', issueId: ISSUE }, + ], + }) + expect(() => assertWritable({ ...taskless, landing }, 'land_proposal', target(renamed))).toThrow(PolicyRefused) + }) + + it('the destination is the current ledger page only', async () => { + const landing = await proofOf() + const canvas = canvasOf() + expect(() => + assertWritable({ ...taskless, landing }, 'land_proposal', target(canvas, { pageIds: [SOURCE_PAGE] })), + ).toThrow(PolicyRefused) + expect(() => assertWritable({ ...taskless, landing }, 'land_proposal', target(canvas, { pageIds: [] }))).toThrow( + PolicyRefused, + ) + const noLedger = canvasOf({ pages: [{ id: SOURCE_PAGE, name: TOPIC, issueId: ISSUE }] }) + expect(() => + assertWritable({ ...taskless, landing }, 'land_proposal', target(noLedger, { pageIds: [SOURCE_PAGE] })), + ).toThrow(PolicyRefused) + }) + + it('the page rule runs first: a Finished ledger page is refused with page_finished', async () => { + const landing = await proofOf() + const canvas = canvasOf({ + pages: [ + { id: LEDGER, name: 'Ledger', ledger: true, finished: { at: 1, by: 'u' } }, + { id: SOURCE_PAGE, name: TOPIC, issueId: ISSUE }, + ], + }) + expect(() => assertWritable({ ...sys, landing }, 'land_proposal', target(canvas))).toThrow(PageFinishedError) + }) + + it('the lock rule runs first: a locked frame in the target is refused', async () => { + const landing = await proofOf() + const frame = { id: 'f1', name: 'f1', locked: true } as unknown as NonNullable + expect(() => assertWritable({ ...sys, landing }, 'land_proposal', target(canvasOf(), { frame }))).toThrow(/locked/) + }) + + it('the same taskless context still cannot create a frame on the bound canvas', async () => { + const landing = await proofOf() + const canvas = canvasOf() + expect(() => + assertWritable({ ...taskless, landing }, 'create_frame', { canvas, pageIds: [LEDGER], html: '

' }), + ).toThrow(/no Multica task/) + }) +})