From 91c2b246801522a6fb3867b44987c20f57b6ea50 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:49:05 -0500 Subject: [PATCH] Add unwired Sites evidence capture and assessment adapters --- docs/site-evidence-adapters.md | 93 ++++++ lib/sites/__tests__/evidenceAdapters.test.ts | 284 ++++++++++++++++++ .../fixtures/site-evidence-digests.json | 201 +++++++++++++ .../production/assessSitePublishEvidence.ts | 22 +- .../assessStoredSitePublishEvidence.ts | 33 ++ .../production/captureSavedSiteReview.ts | 82 +++++ lib/sites/production/getSitePublishContent.ts | 10 + .../production/getSitePublishIdentity.ts | 8 +- lib/sites/production/hashSiteEvidence.ts | 17 +- lib/sites/production/serializeSiteEvidence.ts | 14 + .../production/sitePublishEvidenceSchema.ts | 19 ++ .../__tests__/evidenceRpc.test.ts | 74 +++++ .../callSiteEvidenceRpc.ts | 47 +++ .../insertSitePublishEvidence.ts | 33 ++ .../selectSitePublishEvidence.ts | 15 + 15 files changed, 912 insertions(+), 40 deletions(-) create mode 100644 docs/site-evidence-adapters.md create mode 100644 lib/sites/__tests__/evidenceAdapters.test.ts create mode 100644 lib/sites/__tests__/fixtures/site-evidence-digests.json create mode 100644 lib/sites/production/assessStoredSitePublishEvidence.ts create mode 100644 lib/sites/production/captureSavedSiteReview.ts create mode 100644 lib/sites/production/getSitePublishContent.ts create mode 100644 lib/sites/production/serializeSiteEvidence.ts create mode 100644 lib/sites/production/sitePublishEvidenceSchema.ts create mode 100644 lib/supabase/site_publish_evidence/__tests__/evidenceRpc.test.ts create mode 100644 lib/supabase/site_publish_evidence/callSiteEvidenceRpc.ts create mode 100644 lib/supabase/site_publish_evidence/insertSitePublishEvidence.ts create mode 100644 lib/supabase/site_publish_evidence/selectSitePublishEvidence.ts diff --git a/docs/site-evidence-adapters.md b/docs/site-evidence-adapters.md new file mode 100644 index 000000000..c5d9bf545 --- /dev/null +++ b/docs/site-evidence-adapters.md @@ -0,0 +1,93 @@ +# Unwired Sites evidence adapters + +These helpers target **proposal-only Database PR136**, commit +`4caac3cc8a15a47b348109b2fa4f571423d8beb0` (`proposals/sites-publish-evidence-2094/`). +They have no route, workflow, UI or publishing caller. The proposal remains draft; +this source does not deploy a migration, expose a PostgREST schema, grant execution, +activate retention, add storage or change the advisory working-preview behavior. + +## Capture and assessment + +`captureSavedSiteReview` accepts authenticated server account context, the actual +**returned final-save Site**, and a stable server execution operation key. It reloads +the site, uses `authorizeSiteWorkspace`, checks owner/site/revision and the complete +saved draft, and selects the final saved review. It never guesses `revision + 1`, +uses an earlier successful report, fabricates a receipt or retries with another key. +The SQL function owns the create-once ID and timestamp. Exact retries return that +original receipt; advanced revisions or different payloads/actors conflict. Returned +metadata and the original report are checked before reporting capture success. + +The extracted serializer retains the old `hashSiteEvidence` implementation byte for +byte. Capture and identity share one candidate projection excluding only +`production.reviews` and `production.status`. The committed golden vectors originate +from the proposal's actual API fixture (API `9fb18d85`); tests compare canonical +strings and hashes, including Unicode keys and JavaScript number formatting. +PostgreSQL JSONB text is never substituted for those canonical strings. + +The original review is retained, including failed reviews. Original execution +hashes are compared with the shared render-artifact builder when present; a pass +without execution evidence is rejected. Capture never rewrites execution hashes +to make a report pass. A stored report is not automatically a passing assessment. + +`assessStoredSitePublishEvidence` independently reloads and authorizes the site, +resolves its draft or the existing signed/current-generation working-build reader, +then reads a record scoped by actor, owner, site and record ID. SQL returns an +assessment record, **not the candidate**. The existing `assessSitePublishEvidence` +predicate checks the actual resolved snapshot, report and rendered-artifact hashes. +A failed read/access check propagates; it cannot become an automatic override. +There is no override capture or publication RPC wrapper in this change. + +## Limits before activation + +These are source adapters, not proof of hosted database admission or end-to-end +publication. The proposed schema has no default runtime admission; missing schema, +permission or transport failures remain failures. Only helpers under +`lib/supabase/site_publish_evidence` call its proposed RPCs. Generated database types +and deployment configuration are unchanged. + +The read is an assessment at a point in time, not a publication lock. A future +publisher must repeat all existing paid/account/context/artist checks and use the +separately reviewed atomic SQL publication fence. `authorizeSiteWorkspace` plus the +signed generation reader is not the full generation/publish authorization chain. +Artist transitions, selected-preview interaction and explicit override interaction +remain unresolved activation work. SQL ownership/membership fences cannot by +themselves complete these product access requirements. A future final-save caller +must supply the trusted final assembled report; no public request may supply this +object or actor. No human approval is inferred or newly required here. + +## SQL contract seams and local test scope + +The 26 proposal tests below remain **SQL-fixture evidence** on PG15/17. API tests use +mocked repository/RPC boundaries and the actual predicate; they do not prove SQL +locking, ACLs, deployment, browser execution or provider execution. Publication-only +seams intentionally have no API write adapter. The inherited prerequisite test is +separate from these 26 tests. + +| Proposal test suffix | API boundary / verification | +| --- | --- | +| original_identity_time_and_payload_retry | Capture preserves the returned ID/time and stable key on retries; unexpected receipt fields rejected. | +| parallel_capture_returns_one_original_record | Each capture issues one RPC, with no local identity/store; actual concurrent uniqueness is SQL-only. | +| roles_owner_and_scoped_read | Existing workspace authorization precedes actor/owner/site/record-scoped read. | +| revocation_blocks_capture_retry_read_and_publish | Authorization errors stop capture/read; RPC 42501 propagates; publication absent. | +| execute_privilege_revocation | RPC 42501 propagates without fallback. | +| publication_uses_stored_candidate_without_advancing_revision | No publication RPC; assessment uses separately resolved current candidate. | +| conflicts_leave_publication_unchanged | 40001/23505 propagate once; no publish side effect. | +| concurrent_publications_have_one_pointer_winner | No publication wrapper; pointer/transaction concurrency remains SQL-only. | +| failed_or_malformed_reports_cannot_publish_even_direct_sql | Actual predicate rejects malformed/failed/blocked/viewports/opening/direction reports. | +| override_requires_explicit_intent_and_same_actor | Existing predicate tests explicit intent/current actor; no override capture. | +| digest_mismatch_and_original_report_are_not_rewritten | Capture rejects source/journey/runner drift; actual predicate rejects report/digest drift. | +| legacy_clear_unpublish_and_pointer_forgery | No pointer/legacy publication write in adapters; existing publish regressions unchanged. | +| delete_retention_and_immutable_guards | No delete/update/retention adapter; missing site/record fails closed. | +| broad_defaults_do_not_leak_table_column_or_helper_access | RPC tests assert only exact named entry points; actual grants remain SQL-only. | +| shadow_objects_do_not_redirect_definers | Explicit fixed schema/RPC names; actual SQL search-path isolation remains SQL-only. | +| actor_null_missing_site_and_advanced_revision_retry | No-auth/missing-site/stale-revision tests; no record lookup on stale draft. | +| parallel_different_payload_same_key_has_one_winner | Conflict errors propagate without rekey/retry; concurrency remains SQL-only. | +| legacy_same_bytes_artist_timestamp_and_insert_pointer_guards | No publication/pointer API; artist transition remains an explicit activation gap. | +| failed_write_is_atomic_and_other_sites_survive_retention | Unavailable/conflict RPC responses and transport errors propagate once; SQL atomicity/retention remains SQL-only. | +| membership_revocation_waits_for_authorized_transaction | Existing auth plus SQL actor arguments; held-lock behavior remains SQL-only. | +| actual_api_digest_vectors_survive_jsonb_storage | Exact original canonical vectors checked against shared extracted serializer/hash. | +| capture_binds_returned_final_save_revision_not_claim_revision | Capture sends returned revision verbatim and rejects current revision drift. | +| draft_write_waiting_after_publish_preserves_live_pointer | No draft/publication writes; waiting/locking remains SQL-only. | +| owner_transition_cannot_orphan_retained_evidence | Reloaded owner mismatch rejected; SQL owner guard remains SQL-only. | +| nonspace_whitespace_is_not_explicit_override_reason | Actual predicate rejects NBSP, EM SPACE and BOM-only reasons. | +| corrupt_record_kind_is_not_eligible_for_direct_publication | Actual predicate rejects unknown kind; no publication fallback. | diff --git a/lib/sites/__tests__/evidenceAdapters.test.ts b/lib/sites/__tests__/evidenceAdapters.test.ts new file mode 100644 index 000000000..3ddf7e393 --- /dev/null +++ b/lib/sites/__tests__/evidenceAdapters.test.ts @@ -0,0 +1,284 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import vectors from "./fixtures/site-evidence-digests.json"; +import type { Site, SiteSnapshot } from "../schema"; +import { serializeSiteEvidence } from "../production/serializeSiteEvidence"; +import { getSitePublishContent } from "../production/getSitePublishContent"; +import { hashSiteEvidence } from "../production/hashSiteEvidence"; +import { captureSavedSiteReview } from "../production/captureSavedSiteReview"; +import { assessStoredSitePublishEvidence } from "../production/assessStoredSitePublishEvidence"; +import { selectSite } from "@/lib/supabase/sites/selectSite"; +import { authorizeSiteWorkspace } from "../authorizeSiteWorkspace"; +import { readPublishableBuild } from "../production/readPublishableBuild"; +import { insertSitePublishEvidence } from "@/lib/supabase/site_publish_evidence/insertSitePublishEvidence"; +import { selectSitePublishEvidence } from "@/lib/supabase/site_publish_evidence/selectSitePublishEvidence"; +vi.mock("@/lib/supabase/sites/selectSite", () => ({ selectSite: vi.fn() })); +vi.mock("../authorizeSiteWorkspace", () => ({ authorizeSiteWorkspace: vi.fn() })); +vi.mock("../production/readPublishableBuild", () => ({ readPublishableBuild: vi.fn() })); +vi.mock("@/lib/supabase/site_publish_evidence/insertSitePublishEvidence", () => ({ + insertSitePublishEvidence: vi.fn(), +})); +vi.mock("@/lib/supabase/site_publish_evidence/selectSitePublishEvidence", () => ({ + selectSitePublishEvidence: vi.fn(), +})); +const actor = "00000000-0000-4000-8000-000000000001"; +const siteId = "00000000-0000-4000-8000-000000000002"; +const owner = "00000000-0000-4000-8000-000000000003"; +const evidenceId = "00000000-0000-4000-8000-000000000004"; +function fixture() { + const vector = structuredClone(vectors.vectors[0]); + const candidate = vector.candidate as unknown as SiteSnapshot; + candidate.production!.reviews = [vector.review as never]; + const site = { id: siteId, owner_id: owner, revision: 8, draft: candidate } as Site; + const record = { + id: evidenceId, + siteId, + ownerId: owner, + revision: 8, + candidateSha256: vector.candidateSha256, + recordedByAccountId: actor, + recordedAt: "2026-11-17T00:00:00.000000Z", + kind: "review", + review: vector.review, + reviewSha256: vector.reviewSha256, + }; + vi.mocked(selectSite).mockResolvedValue(structuredClone(site)); + vi.mocked(authorizeSiteWorkspace).mockResolvedValue(owner); + vi.mocked(insertSitePublishEvidence).mockResolvedValue(record); + vi.mocked(selectSitePublishEvidence).mockResolvedValue(record); + return { + site, + record, + capture: () => + captureSavedSiteReview({ accountId: actor, savedSite: site, operationKey: "run:final-save" }), + assess: (generationToken?: string) => + assessStoredSitePublishEvidence(actor, { siteId, revision: 8, evidenceId, generationToken }), + }; +} +beforeEach(() => vi.resetAllMocks()); +describe("original canonical byte contract", () => { + it.each(vectors.vectors)("preserves $name golden bytes and hashes", vector => { + const content = getSitePublishContent(vector.candidate as unknown as SiteSnapshot); + expect(serializeSiteEvidence(content)).toBe(vector.candidateCanonical); + expect(hashSiteEvidence(content)).toBe(vector.candidateSha256); + expect(serializeSiteEvidence(vector.review)).toBe(vector.reviewCanonical); + expect(hashSiteEvidence(vector.review)).toBe(vector.reviewSha256); + }); +}); +describe("unwired final-save capture", () => { + it("uses the returned save revision and original report; DB owns ID/time", async () => { + const f = fixture(); + expect(await f.capture()).toEqual(f.record); + expect(authorizeSiteWorkspace).toHaveBeenCalledWith(actor, owner); + expect(insertSitePublishEvidence).toHaveBeenCalledWith( + expect.objectContaining({ + accountId: actor, + ownerId: owner, + siteId, + revision: 8, + operationKey: "run:final-save", + candidate: f.site.draft, + review: f.record.review, + }), + ); + expect(insertSitePublishEvidence).toHaveBeenCalledTimes(1); + }); + it.each(["revision", "owner", "site", "candidate"])( + "rejects changed current %s before persistence", + async field => { + const f = fixture(); + const current = structuredClone(f.site); + if (field === "revision") current.revision++; + if (field === "owner") current.owner_id = actor; + if (field === "site") current.id = actor; + if (field === "candidate") current.draft!.design.experience!.html += "changed"; + vi.mocked(selectSite).mockResolvedValue(current); + await expect(f.capture()).rejects.toMatchObject({ status: 409 }); + expect(insertSitePublishEvidence).not.toHaveBeenCalled(); + }, + ); + it.each(["sourceSha256", "journeySha256", "runnerSha256"])( + "never launders stale %s", + async key => { + const f = fixture(); + Object.assign(f.site.draft!.production!.reviews[0].verification!.evidence!, { + [key]: "0".repeat(64), + }); + vi.mocked(selectSite).mockResolvedValue(structuredClone(f.site)); + await expect(f.capture()).rejects.toMatchObject({ status: 409 }); + expect(insertSitePublishEvidence).not.toHaveBeenCalled(); + }, + ); + it("does not reuse an older report when the final report is missing", async () => { + const f = fixture(); + f.site.draft!.production!.reviews = []; + vi.mocked(selectSite).mockResolvedValue(f.site); + await expect(f.capture()).rejects.toMatchObject({ status: 409 }); + }); + it("rejects a pass without execution metadata", async () => { + const f = fixture(); + delete f.site.draft!.production!.reviews[0].verification; + vi.mocked(selectSite).mockResolvedValue(f.site); + await expect(f.capture()).rejects.toMatchObject({ status: 409 }); + }); + it("retains a failed report without inventing verification", async () => { + const f = fixture(); + const failed = { verdict: "revise", summary: "Failed", issues: [] }; + f.site.draft!.production!.reviews = [failed as never]; + vi.mocked(selectSite).mockResolvedValue(f.site); + Object.assign(f.record, { review: failed, reviewSha256: hashSiteEvidence(failed) }); + expect(await f.capture()).toEqual(f.record); + expect(insertSitePublishEvidence).toHaveBeenCalledWith( + expect.objectContaining({ review: failed }), + ); + }); + it.each(["", "contains spaces", "x".repeat(129)])( + "rejects invalid operation key %s", + async operationKey => { + const f = fixture(); + await expect( + captureSavedSiteReview({ accountId: actor, savedSite: f.site, operationKey }), + ).rejects.toMatchObject({ status: 400 }); + expect(insertSitePublishEvidence).not.toHaveBeenCalled(); + }, + ); + it("propagates a create-once conflict without retry/new key", async () => { + const f = fixture(); + const failure = new Error("Conflict"); + vi.mocked(insertSitePublishEvidence).mockRejectedValue(failure); + await expect(f.capture()).rejects.toBe(failure); + expect(insertSitePublishEvidence).toHaveBeenCalledTimes(1); + }); + it.each(["recordedByAccountId", "candidateSha256", "reviewSha256", "revision"])( + "rejects unexpected returned %s", + async key => { + const f = fixture(); + Object.assign(f.record, { [key]: key === "revision" ? 7 : owner }); + await expect(f.capture()).rejects.toMatchObject({ status: 503 }); + }, + ); +}); +describe("authorized stored assessment", () => { + it("reads scoped SQL record and uses the actual predicate", async () => { + const f = fixture(); + expect(await f.assess()).toMatchObject({ status: "satisfied", humanApproval: "not-recorded" }); + expect(selectSitePublishEvidence).toHaveBeenCalledWith({ + accountId: actor, + ownerId: owner, + siteId, + evidenceId, + }); + }); + it("resolves the signed working build, not a candidate in the record", async () => { + const f = fixture(); + const candidate = structuredClone(f.site.draft!); + candidate.design.experience!.javascript = "changed"; + vi.mocked(readPublishableBuild).mockResolvedValue(candidate); + expect(await f.assess("signed-token")).toMatchObject({ + status: "unsatisfied", + reason: "candidate-mismatch", + }); + expect(readPublishableBuild).toHaveBeenCalledWith( + "signed-token", + expect.objectContaining({ id: siteId }), + actor, + ); + }); + it("rejects a stale revision before the record read", async () => { + const f = fixture(); + vi.mocked(selectSite).mockResolvedValue({ ...f.site, revision: 9 }); + expect(await f.assess()).toMatchObject({ status: "unsatisfied", reason: "revision-mismatch" }); + expect(selectSitePublishEvidence).not.toHaveBeenCalled(); + }); + it("does not convert access denial into an override", async () => { + const f = fixture(); + vi.mocked(authorizeSiteWorkspace).mockRejectedValue(new Error("Denied")); + await expect(f.assess()).rejects.toThrow("Denied"); + expect(selectSitePublishEvidence).not.toHaveBeenCalled(); + }); + it("does not read without authentication", async () => { + fixture(); + expect( + await assessStoredSitePublishEvidence("", { siteId, revision: 8, evidenceId }), + ).toMatchObject({ status: "unsatisfied", reason: "authentication-required" }); + expect(selectSite).not.toHaveBeenCalled(); + }); + it("propagates record unavailability", async () => { + const f = fixture(); + vi.mocked(selectSitePublishEvidence).mockRejectedValue(new Error("Unavailable")); + await expect(f.assess()).rejects.toThrow("Unavailable"); + }); +}); + +describe("capture and read boundary failures", () => { + it("preserves the original create-once receipt on exact repeated capture", async () => { + const f = fixture(); + expect(await f.capture()).toEqual(await f.capture()); + expect(insertSitePublishEvidence).toHaveBeenNthCalledWith( + 2, + vi.mocked(insertSitePublishEvidence).mock.calls[0][0], + ); + }); + it("rejects unauthenticated capture before any read or write", async () => { + const f = fixture(); + await expect( + captureSavedSiteReview({ accountId: "", savedSite: f.site, operationKey: "save" }), + ).rejects.toMatchObject({ status: 401 }); + expect(selectSite).not.toHaveBeenCalled(); + expect(insertSitePublishEvidence).not.toHaveBeenCalled(); + }); + it.each(["capture", "assessment"])("does not invent a missing site during %s", async mode => { + const f = fixture(); + vi.mocked(selectSite).mockResolvedValue(null); + await expect(mode === "capture" ? f.capture() : f.assess()).rejects.toMatchObject({ + status: 404, + }); + expect(insertSitePublishEvidence).not.toHaveBeenCalled(); + expect(selectSitePublishEvidence).not.toHaveBeenCalled(); + }); + it("propagates capture membership revocation before persistence", async () => { + const f = fixture(); + vi.mocked(authorizeSiteWorkspace).mockRejectedValue(new Error("Revoked")); + await expect(f.capture()).rejects.toThrow("Revoked"); + expect(insertSitePublishEvidence).not.toHaveBeenCalled(); + }); + it("does not silently fall back from an inaccessible signed generation", async () => { + const f = fixture(); + vi.mocked(readPublishableBuild).mockRejectedValue(new Error("Expired generation")); + await expect(f.assess("expired")).rejects.toThrow("Expired generation"); + expect(selectSitePublishEvidence).not.toHaveBeenCalled(); + }); + it.each([null, {}, { kind: "unknown" }])("rejects malformed stored records", async value => { + const f = fixture(); + vi.mocked(selectSitePublishEvidence).mockResolvedValue(value); + expect(await f.assess()).toMatchObject({ + status: "unsatisfied", + reason: "missing-or-invalid-record", + }); + }); + it.each(["\u00a0", "\u2003", "\ufeff"])( + "does not accept whitespace-only override intent", + async reason => { + const f = fixture(); + vi.mocked(selectSitePublishEvidence).mockResolvedValue({ + ...f.record, + kind: "override", + intent: "publish-without-passed-review", + reason, + }); + expect(await f.assess()).toMatchObject({ status: "unsatisfied" }); + }, + ); + it("rejects changed candidate bytes under the same revision on read", async () => { + const f = fixture(); + f.site.draft!.design.experience!.css = "body{color:red}"; + vi.mocked(selectSite).mockResolvedValue(f.site); + expect(await f.assess()).toMatchObject({ status: "unsatisfied", reason: "candidate-mismatch" }); + }); + it("returns failed report assessment without a write or automatic override", async () => { + const f = fixture(); + f.record.review.verdict = "revise"; + f.record.reviewSha256 = hashSiteEvidence(f.record.review); + expect(await f.assess()).toMatchObject({ status: "unsatisfied", reason: "report-not-passed" }); + expect(insertSitePublishEvidence).not.toHaveBeenCalled(); + }); +}); diff --git a/lib/sites/__tests__/fixtures/site-evidence-digests.json b/lib/sites/__tests__/fixtures/site-evidence-digests.json new file mode 100644 index 000000000..b90907542 --- /dev/null +++ b/lib/sites/__tests__/fixtures/site-evidence-digests.json @@ -0,0 +1,201 @@ +{ + "apiCommit": "9fb18d854e927777886c5cd7ed1b2a165a9c669c", + "sourceHashes": { + "getSitePublishIdentity.ts": "fafcaffc8b51333b7a320328c7d53eba26de8ed406f49284e88da8025bff1798", + "hashSiteEvidence.ts": "6482f20729a762e027d94f4d5c695349171ae51a0a1899a73d388af5cde09f95", + "prepareSiteRenderArtifacts.ts": "da8a025de2db179436b9b5c87a91dcc178aeca26dcffddc907359a8e11e52964", + "assessSitePublishEvidence.ts": "610956438219d0ac680b13672e1e90ae4c393de914c74597b2ffe51e755849e1" + }, + "vectors": [ + { + "name": "ordinary", + "candidate": { + "name": "Synthetic preview", + "releaseUrl": "", + "assets": [], + "design": { + "experience": { + "html": "", + "css": "", + "javascript": "void 0" + } + }, + "production": { + "version": 1, + "context": {}, + "direction": {}, + "reviews": [], + "status": "reviewed" + } + }, + "candidateCanonical": "{\"assets\":[],\"design\":{\"experience\":{\"css\":\"\",\"html\":\"\",\"javascript\":\"void 0\"}},\"name\":\"Synthetic preview\",\"production\":{\"context\":{},\"direction\":{},\"version\":1},\"releaseUrl\":\"\"}", + "candidateSha256": "0cc032b80c00a8c7df33a00b4d0e7abebe0a6d426782b057bac7054f0d96f3b5", + "review": { + "verdict": "pass", + "issues": [], + "summary": "Synthetic; no browser ran", + "verification": { + "scope": "generated-experience", + "humanApproval": "not-recorded", + "nativeShareDelivery": "not-tested", + "spotifyAuthentication": "not-tested", + "evidence": { + "sourceSha256": "f98f88337fb5d5efea7189422ba066c1763e346f070394f65011f32b5241960b", + "journeySha256": "011538573b0cf47b60781ebf7fa8ad487332208fd8eb71495acb524a72ad16da", + "runnerSha256": "b924d0dd2f120b580b7273f11535d3aded08df4741a192c7764200f88b5f1294" + }, + "journey": { + "releaseConnection": "A concrete release connection", + "evidence": [ + "Synthetic" + ], + "motivation": "A concrete motivation for participation", + "payoff": "A concrete payoff from participation", + "capabilities": [ + "browser-interaction" + ], + "steps": [ + { + "action": "click", + "target": "Start", + "value": "", + "expected": "", + "checkpoint": "participate" + }, + { + "action": "click", + "target": "Start", + "value": "", + "expected": "", + "checkpoint": "result" + }, + { + "action": "click", + "target": "Start", + "value": "", + "expected": "", + "checkpoint": "delivery" + } + ] + }, + "viewports": [ + { + "name": "mobile", + "journeyPassed": true, + "errors": [], + "overflow": false + }, + { + "name": "desktop", + "journeyPassed": true, + "errors": [], + "overflow": false + } + ] + } + }, + "reviewCanonical": "{\"issues\":[],\"summary\":\"Synthetic; no browser ran\",\"verdict\":\"pass\",\"verification\":{\"evidence\":{\"journeySha256\":\"011538573b0cf47b60781ebf7fa8ad487332208fd8eb71495acb524a72ad16da\",\"runnerSha256\":\"b924d0dd2f120b580b7273f11535d3aded08df4741a192c7764200f88b5f1294\",\"sourceSha256\":\"f98f88337fb5d5efea7189422ba066c1763e346f070394f65011f32b5241960b\"},\"humanApproval\":\"not-recorded\",\"journey\":{\"capabilities\":[\"browser-interaction\"],\"evidence\":[\"Synthetic\"],\"motivation\":\"A concrete motivation for participation\",\"payoff\":\"A concrete payoff from participation\",\"releaseConnection\":\"A concrete release connection\",\"steps\":[{\"action\":\"click\",\"checkpoint\":\"participate\",\"expected\":\"\",\"target\":\"Start\",\"value\":\"\"},{\"action\":\"click\",\"checkpoint\":\"result\",\"expected\":\"\",\"target\":\"Start\",\"value\":\"\"},{\"action\":\"click\",\"checkpoint\":\"delivery\",\"expected\":\"\",\"target\":\"Start\",\"value\":\"\"}]},\"nativeShareDelivery\":\"not-tested\",\"scope\":\"generated-experience\",\"spotifyAuthentication\":\"not-tested\",\"viewports\":[{\"errors\":[],\"journeyPassed\":true,\"name\":\"mobile\",\"overflow\":false},{\"errors\":[],\"journeyPassed\":true,\"name\":\"desktop\",\"overflow\":false}]}}", + "reviewSha256": "0fa29ee1a6ce36eab359f50ecec75f8ee86727d1aedfad61781241cf9376448b" + }, + { + "name": "unicode-and-numbers", + "candidate": { + "name": "Synthetic preview", + "releaseUrl": "", + "assets": [], + "design": { + "experience": { + "html": "", + "css": "", + "javascript": "void 0" + } + }, + "production": { + "version": 1, + "context": { + "𐀀": 1, + "": 2, + "numbers": [ + 0, + 1e+21, + 1e-7, + 1.5 + ], + "text": "🎵 café" + }, + "direction": {}, + "reviews": [], + "status": "reviewed" + } + }, + "candidateCanonical": "{\"assets\":[],\"design\":{\"experience\":{\"css\":\"\",\"html\":\"\",\"javascript\":\"void 0\"}},\"name\":\"Synthetic preview\",\"production\":{\"context\":{\"numbers\":[0,1e+21,1e-7,1.5],\"text\":\"🎵 café\",\"𐀀\":1,\"\":2},\"direction\":{},\"version\":1},\"releaseUrl\":\"\"}", + "candidateSha256": "543df88ccfb1714a8a28836065d2749e34492bc0caaf921a5a04a8528ab16740", + "review": { + "verdict": "pass", + "issues": [], + "summary": "Synthetic; no browser ran", + "verification": { + "scope": "generated-experience", + "humanApproval": "not-recorded", + "nativeShareDelivery": "not-tested", + "spotifyAuthentication": "not-tested", + "evidence": { + "sourceSha256": "f98f88337fb5d5efea7189422ba066c1763e346f070394f65011f32b5241960b", + "journeySha256": "011538573b0cf47b60781ebf7fa8ad487332208fd8eb71495acb524a72ad16da", + "runnerSha256": "b924d0dd2f120b580b7273f11535d3aded08df4741a192c7764200f88b5f1294" + }, + "journey": { + "releaseConnection": "A concrete release connection", + "evidence": [ + "Synthetic" + ], + "motivation": "A concrete motivation for participation", + "payoff": "A concrete payoff from participation", + "capabilities": [ + "browser-interaction" + ], + "steps": [ + { + "action": "click", + "target": "Start", + "value": "", + "expected": "", + "checkpoint": "participate" + }, + { + "action": "click", + "target": "Start", + "value": "", + "expected": "", + "checkpoint": "result" + }, + { + "action": "click", + "target": "Start", + "value": "", + "expected": "", + "checkpoint": "delivery" + } + ] + }, + "viewports": [ + { + "name": "mobile", + "journeyPassed": true, + "errors": [], + "overflow": false + }, + { + "name": "desktop", + "journeyPassed": true, + "errors": [], + "overflow": false + } + ] + } + }, + "reviewCanonical": "{\"issues\":[],\"summary\":\"Synthetic; no browser ran\",\"verdict\":\"pass\",\"verification\":{\"evidence\":{\"journeySha256\":\"011538573b0cf47b60781ebf7fa8ad487332208fd8eb71495acb524a72ad16da\",\"runnerSha256\":\"b924d0dd2f120b580b7273f11535d3aded08df4741a192c7764200f88b5f1294\",\"sourceSha256\":\"f98f88337fb5d5efea7189422ba066c1763e346f070394f65011f32b5241960b\"},\"humanApproval\":\"not-recorded\",\"journey\":{\"capabilities\":[\"browser-interaction\"],\"evidence\":[\"Synthetic\"],\"motivation\":\"A concrete motivation for participation\",\"payoff\":\"A concrete payoff from participation\",\"releaseConnection\":\"A concrete release connection\",\"steps\":[{\"action\":\"click\",\"checkpoint\":\"participate\",\"expected\":\"\",\"target\":\"Start\",\"value\":\"\"},{\"action\":\"click\",\"checkpoint\":\"result\",\"expected\":\"\",\"target\":\"Start\",\"value\":\"\"},{\"action\":\"click\",\"checkpoint\":\"delivery\",\"expected\":\"\",\"target\":\"Start\",\"value\":\"\"}]},\"nativeShareDelivery\":\"not-tested\",\"scope\":\"generated-experience\",\"spotifyAuthentication\":\"not-tested\",\"viewports\":[{\"errors\":[],\"journeyPassed\":true,\"name\":\"mobile\",\"overflow\":false},{\"errors\":[],\"journeyPassed\":true,\"name\":\"desktop\",\"overflow\":false}]}}", + "reviewSha256": "0fa29ee1a6ce36eab359f50ecec75f8ee86727d1aedfad61781241cf9376448b" + } + ] +} diff --git a/lib/sites/production/assessSitePublishEvidence.ts b/lib/sites/production/assessSitePublishEvidence.ts index a7d54c030..b315213f6 100644 --- a/lib/sites/production/assessSitePublishEvidence.ts +++ b/lib/sites/production/assessSitePublishEvidence.ts @@ -6,16 +6,9 @@ import { prepareSiteRenderArtifacts } from "./prepareSiteRenderArtifacts"; import { reviewSchema } from "./schema"; import { openingReviewSchema } from "./openingReviewSchema"; +import { sitePublishEvidenceSchema } from "./sitePublishEvidenceSchema"; + const hash = z.string().regex(/^[a-f0-9]{64}$/); -const recordSchema = z.object({ - id: z.string().min(1), - siteId: z.string().min(1), - ownerId: z.string().min(1), - revision: z.number().int().nonnegative().safe(), - candidateSha256: hash, - recordedByAccountId: z.string().min(1), - recordedAt: z.string().datetime(), -}); const verificationSchema = z.object({ scope: z.literal("generated-experience"), humanApproval: z.literal("not-recorded"), @@ -37,15 +30,6 @@ const verificationSchema = z.object({ .extend({ verdict: z.literal("pass"), issues: z.array(z.unknown()).length(0) }) .optional(), }); -const evidenceSchema = z.discriminatedUnion("kind", [ - recordSchema.extend({ kind: z.literal("review"), review: z.unknown(), reviewSha256: hash }), - recordSchema.extend({ - kind: z.literal("override"), - intent: z.literal("publish-without-passed-review"), - reason: z.string().trim().min(1).max(2000), - }), -]); - /** UNWIRED evidence assessment, not publication authorization. * Adapters MUST read authoritative persisted records, authorize the authenticated account * using authorizeSiteWorkspace, and resolve the actual draft/signed working-build candidate. @@ -83,7 +67,7 @@ export async function assessSitePublishEvidence( return unsatisfied("revision-mismatch"); if (!current.candidate.design.experience) return unsatisfied("missing-experience"); const identity = getSitePublishIdentity(current); - const parsed = evidenceSchema.safeParse( + const parsed = sitePublishEvidenceSchema.safeParse( await server.readEvidence({ evidenceId: request.evidenceId, siteId: current.siteId, diff --git a/lib/sites/production/assessStoredSitePublishEvidence.ts b/lib/sites/production/assessStoredSitePublishEvidence.ts new file mode 100644 index 000000000..fe996b70f --- /dev/null +++ b/lib/sites/production/assessStoredSitePublishEvidence.ts @@ -0,0 +1,33 @@ +import { selectSite } from "@/lib/supabase/sites/selectSite"; +import { selectSitePublishEvidence } from "@/lib/supabase/site_publish_evidence/selectSitePublishEvidence"; +import { authorizeSiteWorkspace } from "../authorizeSiteWorkspace"; +import { SiteError } from "../SiteError"; +import { assessSitePublishEvidence } from "./assessSitePublishEvidence"; +import { readPublishableBuild } from "./readPublishableBuild"; + +/** UNWIRED assessment only. Full publish/artist/context authorization remains separate. */ +export async function assessStoredSitePublishEvidence( + accountId: string, + request: { + siteId: string; + revision: number; + evidenceId: string; + generationToken?: string; + }, +) { + return assessSitePublishEvidence(request, { + accountId, + readCandidate: async ({ siteId }) => { + const site = await selectSite(siteId); + if (!site) throw new SiteError(404, "Site not found"); + await authorizeSiteWorkspace(accountId, site.owner_id); + const candidate = request.generationToken + ? await readPublishableBuild(request.generationToken, site, accountId) + : site.draft; + if (!candidate) throw new SiteError(409, "Site candidate unavailable"); + return { siteId: site.id, ownerId: site.owner_id, revision: site.revision, candidate }; + }, + readEvidence: scope => selectSitePublishEvidence({ ...scope, accountId }), + now: Date.now, + }); +} diff --git a/lib/sites/production/captureSavedSiteReview.ts b/lib/sites/production/captureSavedSiteReview.ts new file mode 100644 index 000000000..6ca641cbf --- /dev/null +++ b/lib/sites/production/captureSavedSiteReview.ts @@ -0,0 +1,82 @@ +import { z } from "zod"; +import { selectSite } from "@/lib/supabase/sites/selectSite"; +import { insertSitePublishEvidence } from "@/lib/supabase/site_publish_evidence/insertSitePublishEvidence"; +import { authorizeSiteWorkspace } from "../authorizeSiteWorkspace"; +import { SiteError } from "../SiteError"; +import type { Site } from "../schema"; +import { getSitePublishIdentity } from "./getSitePublishIdentity"; +import { hashSiteEvidence } from "./hashSiteEvidence"; +import { serializeSiteEvidence } from "./serializeSiteEvidence"; +import { prepareSiteRenderArtifacts } from "./prepareSiteRenderArtifacts"; +import { sitePublishEvidenceSchema } from "./sitePublishEvidenceSchema"; + +/** UNWIRED. savedSite MUST be the trusted final save return, never request-body state. + * Retains failed reports; does not authorize publication or capture an implicit override. + */ +export async function captureSavedSiteReview(input: { + accountId: string; + savedSite: Site; + operationKey: string; +}) { + if (!input.accountId) throw new SiteError(401, "Authentication required"); + if (!/^[A-Za-z0-9._:-]{1,128}$/.test(input.operationKey)) + throw new SiteError(400, "Invalid evidence operation key"); + const saved = structuredClone(input.savedSite); + const current = await selectSite(saved.id); + if (!current) throw new SiteError(404, "Site not found"); + await authorizeSiteWorkspace(input.accountId, current.owner_id); + if ( + current.id !== saved.id || + current.owner_id !== saved.owner_id || + current.revision !== saved.revision || + !Number.isSafeInteger(saved.revision) || + saved.revision < 0 || + serializeSiteEvidence(current.draft) !== serializeSiteEvidence(saved.draft) + ) + throw new SiteError(409, "Saved site no longer matches the current draft"); + const candidate = saved.draft; + const review = candidate?.production?.reviews.at(-1); + if (!candidate?.design.experience || !review || typeof review !== "object") + throw new SiteError(409, "Final saved review unavailable"); + const verification = review.verification; + if (verification?.journey && verification.evidence) { + const actual = prepareSiteRenderArtifacts(candidate, verification.journey).evidence; + if ( + Object.entries(actual).some( + ([key, value]) => verification.evidence![key as keyof typeof actual] !== value, + ) + ) + throw new SiteError(409, "Saved report execution artifacts do not match"); + } else if (review.verdict === "pass") { + throw new SiteError(409, "Passed report is missing execution evidence"); + } + const identity = getSitePublishIdentity({ + siteId: saved.id, + ownerId: saved.owner_id, + revision: saved.revision, + candidate, + }); + const raw = await insertSitePublishEvidence({ + ...identity, + accountId: input.accountId, + operationKey: input.operationKey, + candidate, + review, + }); + const parsed = sitePublishEvidenceSchema.safeParse(raw); + if (!parsed.success) throw new SiteError(503, "Invalid stored evidence response"); + const record = parsed.data; + if ( + !z.uuid().safeParse(record.id).success || + record.kind !== "review" || + Object.entries(identity).some( + ([key, value]) => record[key as keyof typeof identity] !== value, + ) || + record.recordedByAccountId !== input.accountId || + Date.parse(record.recordedAt) > Date.now() || + record.reviewSha256 !== hashSiteEvidence(review) || + serializeSiteEvidence(record.review) !== serializeSiteEvidence(review) + ) + throw new SiteError(503, "Stored evidence does not match capture"); + return record; +} diff --git a/lib/sites/production/getSitePublishContent.ts b/lib/sites/production/getSitePublishContent.ts new file mode 100644 index 000000000..0565d5974 --- /dev/null +++ b/lib/sites/production/getSitePublishContent.ts @@ -0,0 +1,10 @@ +import type { SiteSnapshot } from "../schema"; +/** Exclude only review history and derived status from the publication identity. */ +export function getSitePublishContent(candidate: SiteSnapshot) { + const content = structuredClone(candidate); + if (content.production) { + const { reviews: _reviews, status: _status, ...production } = content.production; + return { ...content, production }; + } + return content; +} diff --git a/lib/sites/production/getSitePublishIdentity.ts b/lib/sites/production/getSitePublishIdentity.ts index 72767966e..e4621bab3 100644 --- a/lib/sites/production/getSitePublishIdentity.ts +++ b/lib/sites/production/getSitePublishIdentity.ts @@ -1,3 +1,4 @@ +import { getSitePublishContent } from "./getSitePublishContent"; import { hashSiteEvidence } from "./hashSiteEvidence"; import type { SiteSnapshot } from "../schema"; @@ -9,10 +10,5 @@ export type SitePublishCandidate = { }; /** Bind publication content, excluding only review history and its derived status. */ export function getSitePublishIdentity({ candidate, ...identity }: SitePublishCandidate) { - const content = structuredClone(candidate); - if (content.production) { - const { reviews: _reviews, status: _status, ...production } = content.production; - return { ...identity, candidateSha256: hashSiteEvidence({ ...content, production }) }; - } - return { ...identity, candidateSha256: hashSiteEvidence(content) }; + return { ...identity, candidateSha256: hashSiteEvidence(getSitePublishContent(candidate)) }; } diff --git a/lib/sites/production/hashSiteEvidence.ts b/lib/sites/production/hashSiteEvidence.ts index a5f7a9754..d40f0e432 100644 --- a/lib/sites/production/hashSiteEvidence.ts +++ b/lib/sites/production/hashSiteEvidence.ts @@ -1,18 +1,5 @@ import { createHash } from "node:crypto"; - -/** Stable digest of JSON evidence, including after a JSONB object-key reorder. */ +import { serializeSiteEvidence } from "./serializeSiteEvidence"; export function hashSiteEvidence(value: unknown): string { - const canonical = (item: unknown): unknown => { - if (Array.isArray(item)) return item.map(canonical); - if (item && typeof item === "object") - return Object.fromEntries( - Object.entries(item) - .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) - .map(([key, child]) => [key, canonical(child)]), - ); - return item; - }; - return createHash("sha256") - .update(JSON.stringify(canonical(value))) - .digest("hex"); + return createHash("sha256").update(serializeSiteEvidence(value)).digest("hex"); } diff --git a/lib/sites/production/serializeSiteEvidence.ts b/lib/sites/production/serializeSiteEvidence.ts new file mode 100644 index 000000000..af23be21e --- /dev/null +++ b/lib/sites/production/serializeSiteEvidence.ts @@ -0,0 +1,14 @@ +/** Exact historical hashSiteEvidence serialization; not PostgreSQL JSONB text. */ +export function serializeSiteEvidence(value: unknown): string { + const canonical = (item: unknown): unknown => { + if (Array.isArray(item)) return item.map(canonical); + if (item && typeof item === "object") + return Object.fromEntries( + Object.entries(item) + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([key, child]) => [key, canonical(child)]), + ); + return item; + }; + return JSON.stringify(canonical(value)); +} diff --git a/lib/sites/production/sitePublishEvidenceSchema.ts b/lib/sites/production/sitePublishEvidenceSchema.ts new file mode 100644 index 000000000..44dd125b4 --- /dev/null +++ b/lib/sites/production/sitePublishEvidenceSchema.ts @@ -0,0 +1,19 @@ +import { z } from "zod"; +const hash = z.string().regex(/^[a-f0-9]{64}$/); +const recordSchema = z.object({ + id: z.string().min(1), + siteId: z.string().min(1), + ownerId: z.string().min(1), + revision: z.number().int().nonnegative().safe(), + candidateSha256: hash, + recordedByAccountId: z.string().min(1), + recordedAt: z.string().datetime(), +}); +export const sitePublishEvidenceSchema = z.discriminatedUnion("kind", [ + recordSchema.extend({ kind: z.literal("review"), review: z.unknown(), reviewSha256: hash }), + recordSchema.extend({ + kind: z.literal("override"), + intent: z.literal("publish-without-passed-review"), + reason: z.string().trim().min(1).max(2000), + }), +]); diff --git a/lib/supabase/site_publish_evidence/__tests__/evidenceRpc.test.ts b/lib/supabase/site_publish_evidence/__tests__/evidenceRpc.test.ts new file mode 100644 index 000000000..228310292 --- /dev/null +++ b/lib/supabase/site_publish_evidence/__tests__/evidenceRpc.test.ts @@ -0,0 +1,74 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import { insertSitePublishEvidence } from "../insertSitePublishEvidence"; +import { selectSitePublishEvidence } from "../selectSitePublishEvidence"; +import vectors from "@/lib/sites/__tests__/fixtures/site-evidence-digests.json"; +import type { SiteSnapshot } from "@/lib/sites/schema"; +const { rpc, schema } = vi.hoisted(() => { + const rpc = vi.fn(); + return { rpc, schema: vi.fn(() => ({ rpc })) }; +}); +vi.mock("@/lib/supabase/serverClient", () => ({ default: { schema } })); +const vector = vectors.vectors[0]; +const input = { + accountId: "actor", + ownerId: "owner", + siteId: "site", + revision: 8, + operationKey: "run:save", + candidate: vector.candidate as unknown as SiteSnapshot, + review: vector.review, +}; +beforeEach(() => { + vi.clearAllMocks(); + rpc.mockResolvedValue({ data: { id: "db-record" }, error: null }); +}); +it("passes only the exact proposal capture contract with original canonical bytes", async () => { + expect(await insertSitePublishEvidence(input)).toEqual({ id: "db-record" }); + expect(schema).toHaveBeenCalledWith("sites_evidence_proposal"); + expect(rpc).toHaveBeenCalledWith("record_evidence", { + p_actor: "actor", + p_owner: "owner", + p_site: "site", + p_revision: 8, + p_key: "run:save", + p_candidate: vector.candidate, + p_candidate_canonical: vector.candidateCanonical, + p_candidate_sha: vector.candidateSha256, + p_decision: { kind: "review", review: vector.review, reviewSha256: vector.reviewSha256 }, + p_review_canonical: vector.reviewCanonical, + }); +}); +it("scopes reads by authenticated actor, current owner, site and record", async () => { + await selectSitePublishEvidence({ + accountId: "actor", + ownerId: "owner", + siteId: "site", + evidenceId: "record", + }); + expect(rpc).toHaveBeenCalledWith("read_evidence", { + p_actor: "actor", + p_owner: "owner", + p_site: "site", + p_record: "record", + }); +}); +it.each([ + ["40001", 409], + ["23505", 409], + ["42501", 403], + ["PGRST106", 503], + ["P0001", 503], +])("propagates SQL %s as %s without retry", async (code, status) => { + rpc.mockResolvedValue({ data: null, error: { code, message: "private SQL details" } }); + await expect(insertSitePublishEvidence(input)).rejects.toMatchObject({ status }); + expect(rpc).toHaveBeenCalledTimes(1); +}); +it("fails closed on missing data", async () => { + rpc.mockResolvedValue({ data: null, error: null }); + await expect(insertSitePublishEvidence(input)).rejects.toMatchObject({ status: 503 }); +}); +it("propagates transport failure without a second operation", async () => { + rpc.mockRejectedValue(new Error("transport failed")); + await expect(insertSitePublishEvidence(input)).rejects.toThrow("transport failed"); + expect(rpc).toHaveBeenCalledTimes(1); +}); diff --git a/lib/supabase/site_publish_evidence/callSiteEvidenceRpc.ts b/lib/supabase/site_publish_evidence/callSiteEvidenceRpc.ts new file mode 100644 index 000000000..c1fc34f99 --- /dev/null +++ b/lib/supabase/site_publish_evidence/callSiteEvidenceRpc.ts @@ -0,0 +1,47 @@ +import type { SupabaseClient } from "@supabase/supabase-js"; +import supabase from "@/lib/supabase/serverClient"; +import { SiteError } from "@/lib/sites/SiteError"; +import type { SiteSnapshot } from "@/lib/sites/schema"; +type Scope = { p_actor: string; p_owner: string; p_site: string }; +type Functions = { + record_evidence: { + Args: Scope & { + p_revision: number; + p_key: string; + p_candidate: SiteSnapshot; + p_candidate_canonical: string; + p_candidate_sha: string; + p_decision: { kind: "review"; review: unknown; reviewSha256: string }; + p_review_canonical: string; + }; + Returns: unknown; + }; + read_evidence: { Args: Scope & { p_record: string }; Returns: unknown }; +}; +type Schema = { Tables: Record; Views: Record; Functions: Functions }; +type ProposedDatabase = { public: Schema; sites_evidence_proposal: Schema }; +/** UNWIRED proposal-only RPCs. No schema exposure, grants or fallback are installed here. */ +export async function callSiteEvidenceRpc( + name: T, + args: Functions[T]["Args"], +) { + const client = supabase as unknown as SupabaseClient; + const { data, error } = await client.schema("sites_evidence_proposal").rpc(name, args); + if (error) { + const status = ["40001", "23505"].includes(error.code) + ? 409 + : error.code === "42501" + ? 403 + : 503; + throw new SiteError( + status, + status === 409 + ? "Site evidence conflict" + : status === 403 + ? "Site evidence access denied" + : "Site evidence unavailable", + ); + } + if (data == null) throw new SiteError(503, "Site evidence unavailable"); + return data; +} diff --git a/lib/supabase/site_publish_evidence/insertSitePublishEvidence.ts b/lib/supabase/site_publish_evidence/insertSitePublishEvidence.ts new file mode 100644 index 000000000..5e2eec1e1 --- /dev/null +++ b/lib/supabase/site_publish_evidence/insertSitePublishEvidence.ts @@ -0,0 +1,33 @@ +import { callSiteEvidenceRpc } from "./callSiteEvidenceRpc"; +import { getSitePublishContent } from "@/lib/sites/production/getSitePublishContent"; +import { hashSiteEvidence } from "@/lib/sites/production/hashSiteEvidence"; +import { serializeSiteEvidence } from "@/lib/sites/production/serializeSiteEvidence"; +import type { SiteSnapshot } from "@/lib/sites/schema"; +/** Capture only server-resolved review inputs. SQL owns create-once identity and time. */ +export async function insertSitePublishEvidence(input: { + accountId: string; + ownerId: string; + siteId: string; + revision: number; + operationKey: string; + candidate: SiteSnapshot; + review: unknown; +}) { + const content = getSitePublishContent(input.candidate); + return callSiteEvidenceRpc("record_evidence", { + p_actor: input.accountId, + p_owner: input.ownerId, + p_site: input.siteId, + p_revision: input.revision, + p_key: input.operationKey, + p_candidate: input.candidate, + p_candidate_canonical: serializeSiteEvidence(content), + p_candidate_sha: hashSiteEvidence(content), + p_decision: { + kind: "review", + review: input.review, + reviewSha256: hashSiteEvidence(input.review), + }, + p_review_canonical: serializeSiteEvidence(input.review), + }); +} diff --git a/lib/supabase/site_publish_evidence/selectSitePublishEvidence.ts b/lib/supabase/site_publish_evidence/selectSitePublishEvidence.ts new file mode 100644 index 000000000..737b8f663 --- /dev/null +++ b/lib/supabase/site_publish_evidence/selectSitePublishEvidence.ts @@ -0,0 +1,15 @@ +import { callSiteEvidenceRpc } from "./callSiteEvidenceRpc"; +/** The returned record is evidence, never the authoritative candidate snapshot. */ +export async function selectSitePublishEvidence(input: { + accountId: string; + ownerId: string; + siteId: string; + evidenceId: string; +}) { + return callSiteEvidenceRpc("read_evidence", { + p_actor: input.accountId, + p_owner: input.ownerId, + p_site: input.siteId, + p_record: input.evidenceId, + }); +}