From d804661675ddd394c956436a7368d79c5f7e7be5 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:20:02 -0500 Subject: [PATCH 1/3] Add unwired exact-selected Sites publication orchestration --- docs/site-selected-publication.md | 109 ++++++ .../__tests__/publicationAuthority.test.ts | 104 ++++++ .../__tests__/selectedPublication.test.ts | 317 ++++++++++++++++++ .../readPaidSiteSubscription.test.ts | 17 + .../__tests__/resolveSiteFanReturnUrl.test.ts | 24 ++ .../fanConnection/hasPaidSiteSubscription.ts | 15 +- .../fanConnection/prepareSiteFanConnection.ts | 8 +- .../fanConnection/readPaidSiteSubscription.ts | 8 + .../fanConnection/resolveSiteFanReturnUrl.ts | 13 + .../authorizeSelectedSitePublication.ts | 40 +++ .../publishSelectedSiteEvidence.ts | 89 +++++ .../resolveSelectedSiteCandidate.ts | 43 +++ .../selectedSitePublicationSchema.ts | 29 ++ .../validateSiteOverrideReceipt.ts | 25 ++ .../validateSitePublicationReceipt.ts | 61 ++++ .../__tests__/publicationRpc.test.ts | 78 +++++ .../callSiteEvidenceRpc.ts | 15 +- .../insertSiteOverrideEvidence.ts | 30 ++ .../publishSiteEvidenceCandidate.ts | 21 ++ 19 files changed, 1025 insertions(+), 21 deletions(-) create mode 100644 docs/site-selected-publication.md create mode 100644 lib/sites/__tests__/publicationAuthority.test.ts create mode 100644 lib/sites/__tests__/selectedPublication.test.ts create mode 100644 lib/sites/fanConnection/__tests__/readPaidSiteSubscription.test.ts create mode 100644 lib/sites/fanConnection/__tests__/resolveSiteFanReturnUrl.test.ts create mode 100644 lib/sites/fanConnection/readPaidSiteSubscription.ts create mode 100644 lib/sites/fanConnection/resolveSiteFanReturnUrl.ts create mode 100644 lib/sites/production/publication/authorizeSelectedSitePublication.ts create mode 100644 lib/sites/production/publication/publishSelectedSiteEvidence.ts create mode 100644 lib/sites/production/publication/resolveSelectedSiteCandidate.ts create mode 100644 lib/sites/production/publication/selectedSitePublicationSchema.ts create mode 100644 lib/sites/production/publication/validateSiteOverrideReceipt.ts create mode 100644 lib/sites/production/publication/validateSitePublicationReceipt.ts create mode 100644 lib/supabase/site_publish_evidence/__tests__/publicationRpc.test.ts create mode 100644 lib/supabase/site_publish_evidence/insertSiteOverrideEvidence.ts create mode 100644 lib/supabase/site_publish_evidence/publishSiteEvidenceCandidate.ts diff --git a/docs/site-selected-publication.md b/docs/site-selected-publication.md new file mode 100644 index 000000000..ce00873e9 --- /dev/null +++ b/docs/site-selected-publication.md @@ -0,0 +1,109 @@ +# Unwired exact-selected Sites publication + +This source extends the evidence adapters from API #1263. It targets the unchanged +**Database #136 proposal**, commit `4caac3cc8a15a47b348109b2fa4f571423d8beb0`. +There is no route, UI, MCP or workflow caller. Existing `processSiteOperation` +publishing remains advisory and unchanged. No migration, schema exposure, runtime +grant, retention activation or publication gate is introduced. + +## Selection and explicit intent + +`publishSelectedSiteEvidence` accepts authenticated server account context and a +stable server operation key separately from its strict input schema. The input +contains expectations: site, owner, artist, revision, candidate digest, explicitly +nullable expected publication evidence pointer, and optional signed generation +token. These values do not grant access. The server reloads and authorizes the site +and resolves the actual draft or signed/current-generation working build. A new +preview under the same revision must still match the selected digest. Missing +`published_evidence_id` metadata is an error, never silently interpreted as null. + +The input chooses either a stored review ID or explicit +`publish-without-passed-review` intent with a nonblank reason. The existing Publish +click/request is not accepted as override intent. No candidate, report, actor, +record timestamp or operation key comes from request-body evidence. There is no +new mandatory artist approval. + +Only after matching selection and authorization does the override branch call the +proposal's create-once capture RPC. It preserves the original candidate and shared +canonical projection/serialization. SQL owns the ID/time; returned identity, +actor, intent and reason are validated. Capture conflicts propagate without +replacement keys. A retained override record can exist even if a later authority +check or publication fails; recording intent does not mean publication succeeded. + +The review branch reads its scoped immutable record and preserves original review +and execution hashes. Both branches run the full existing +`assessSitePublishEvidence` predicate. A failed review never falls back to an +override. The server resolves the selected candidate, checks authority and reads +and assesses the evidence again before `publish_candidate`. The SQL call receives +only actor/owner/site/revision/record ID/selected digest/expected pointer; SQL copies +the stored immutable candidate, not API-supplied replacement bytes. + +## Existing authority and deliberate unsupported transitions + +The current `processSiteOperation` publish branch checks workspace and revision, +uses `readPublishableBuild` for a signed generation, revalidates a saved Context +brief when present, resolves artist attribution, calls `prepareSiteFanConnection` +and rechecks workspace before its legacy publication update. + +The new, unwired path reuses these read/check owners: + +- `authorizeSiteWorkspace` and `readPublishableBuild` for actor/workspace and signed + current-generation resolution, repeated at the final boundary. +- `readSiteContextBrief` for the selected snapshot's saved brief when present, + repeated before publication. This preserves the existing brief-optional source + contract; it does not create new Context evidence or provider analysis. +- Existing artist/workspace association checks (the same organization versus + personal-access distinction used by site creation), plus artist name lookup. +- The existing active-paid-subscription predicate, extracted into + `readPaidSiteSubscription`. The old fan-request helper retains its 30-second + cache; the new path uses fresh reads at both authority passes. The underlying + Stripe reader continues to fail closed to no entitlement on provider errors. +- `getFanOAuthConfig`, `selectFanConfig`, and the extracted shared + `resolveSiteFanReturnUrl` transformation/validator used by existing preparation. + +Two existing side effects cannot safely be included in this proposal: automatic +artist attribution and creating/updating fan configuration. SQL preserves +`artist_id`, so this path requires a nonnull existing artist matching the selected +artist and rejects transitions. It also requires an already enabled fan +configuration for the exact destination; it does not call `updateFanConfig` or +silently claim to have prepared one. These restrictions belong only to this +unwired source, not the existing advisory publish flow. + +## Atomicity and activation gates + +The SQL proposal serializes workspace membership, revision, evidence binding and +publication-pointer CAS. The external paid, Context, artist, fan configuration and +Workflow reads are **not atomically serialized with that transaction**. A changed +selection or pointer observed by the final recheck is rejected, but changes after +that observation are not prevented by API reads. In particular the proposal does +not compare an expected artist ID or the latest mutable Workflow preview inside +SQL. An artist change after the final read can therefore commit before publication; +receipt validation can detect it only after publication has already committed. +Artist/current-generation race handling and exact preview interaction must be +resolved before activation; this source is not complete end-to-end publication +authorization. Pointer CAS also does not solve ABA or order multiple legacy writes +that leave the pointer null; see the proposal protocol. + +Publication receipts are checked for site/owner/artist/revision, evidence ID, +actual published-content digest and unchanged evidence. The site row's raw SQL +`published_at` can contain an offset and is validated accordingly. Evidence +`recordedAt` still uses the proposal's explicit six-fractional-digit UTC-Z format. +A receipt/transport error may occur after SQL committed; it propagates without an +automatic retry, fallback or rekey. Future interaction must resolve ambiguous +outcomes by an authorized read, not assume the site stayed unpublished. + +Required next gates remain separate: reviewed exact-selection/override UI intent, +artist/fan preparation transitions, external authority race policy, approved SQL +release/admission/grants and retention, authoritative pointer availability, +production integration and end-to-end validation. Database #136 remains draft and +proposal-only. Source merge alone does not satisfy any of these gates. + +## Validation scope + +Tests use mocked repository, Stripe, Context, authorization and Workflow +boundaries with the actual candidate identity and complete evidence predicate. +They cover same-revision preview changes, null versus missing pointer, final-boundary +revocation, explicit override capture, mismatched receipts, original report/artifact +digests and RPC argument/error contracts. Existing working-preview, capture, +assessment and fan-configuration tests remain regression checks. No live provider, +DB, browser, native share, fan OAuth or publication execution is claimed. diff --git a/lib/sites/__tests__/publicationAuthority.test.ts b/lib/sites/__tests__/publicationAuthority.test.ts new file mode 100644 index 000000000..81ba4f4c6 --- /dev/null +++ b/lib/sites/__tests__/publicationAuthority.test.ts @@ -0,0 +1,104 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import { authorizeSelectedSitePublication } from "../production/publication/authorizeSelectedSitePublication"; +import { readPaidSiteSubscription } from "../fanConnection/readPaidSiteSubscription"; +import { getFanOAuthConfig } from "../fanConnection/getFanOAuthConfig"; +import { selectFanConfig } from "@/lib/supabase/site_fan_connections/selectFanConfig"; +import { selectAccounts } from "@/lib/supabase/accounts/selectAccounts"; +import { selectArtistOrganizationIds } from "@/lib/supabase/artist_organization_ids/selectArtistOrganizationIds"; +import { checkAccountArtistAccess } from "@/lib/artists/checkAccountArtistAccess"; +import { readSiteContextBrief } from "../production/readSiteContextBrief"; +import type { Site, SiteSnapshot } from "../schema"; +vi.mock("../fanConnection/readPaidSiteSubscription", () => ({ readPaidSiteSubscription: vi.fn() })); +vi.mock("../fanConnection/getFanOAuthConfig", () => ({ getFanOAuthConfig: vi.fn() })); +vi.mock("@/lib/supabase/site_fan_connections/selectFanConfig", () => ({ + selectFanConfig: vi.fn(), +})); +vi.mock("@/lib/supabase/accounts/selectAccounts", () => ({ selectAccounts: vi.fn() })); +vi.mock("@/lib/supabase/artist_organization_ids/selectArtistOrganizationIds", () => ({ + selectArtistOrganizationIds: vi.fn(), +})); +vi.mock("@/lib/artists/checkAccountArtistAccess", () => ({ checkAccountArtistAccess: vi.fn() })); +vi.mock("../production/readSiteContextBrief", () => ({ readSiteContextBrief: vi.fn() })); +const site = { id: "site", owner_id: "workspace", artist_id: "artist" } as Site; +const candidate = { + production: { context: { engine: { briefId: "brief" } } }, +} as unknown as SiteSnapshot; +const authorize = () => + authorizeSelectedSitePublication("actor", { site, candidate }, "https://example.com/site"); +beforeEach(() => { + vi.resetAllMocks(); + vi.mocked(readPaidSiteSubscription).mockResolvedValue(true); + vi.mocked(selectArtistOrganizationIds).mockResolvedValue([ + { organization_id: "workspace" }, + ] as never); + vi.mocked(selectAccounts).mockResolvedValue([{ name: "Artist" }] as never); + vi.mocked(selectFanConfig).mockResolvedValue({ + site_id: "site", + enabled: true, + return_url: "https://example.com/site", + revision: 1, + marketing_text: "Consent", + }); +}); +it("checks the existing brief, workspace artist, fresh paid entitlement, OAuth and prepared fan config", async () => { + await authorize(); + expect(readSiteContextBrief).toHaveBeenCalledWith(site, "actor", "brief"); + expect(readPaidSiteSubscription).toHaveBeenCalledWith("workspace"); + expect(getFanOAuthConfig).toHaveBeenCalledOnce(); +}); +it.each([ + "unpaid", + "missing-artist", + "foreign-artist", + "missing-fan-config", + "changed-destination", + "disabled", + "nameless", +])("rejects %s", async kind => { + let current = site; + if (kind === "unpaid") vi.mocked(readPaidSiteSubscription).mockResolvedValue(false); + if (kind === "missing-artist") current = { ...site, artist_id: null }; + if (kind === "foreign-artist") vi.mocked(selectArtistOrganizationIds).mockResolvedValue([]); + if (kind === "missing-fan-config") vi.mocked(selectFanConfig).mockResolvedValue(null); + if (kind === "changed-destination") + vi.mocked(selectFanConfig).mockResolvedValue({ + site_id: "site", + enabled: true, + return_url: "https://other.test", + revision: 1, + marketing_text: "Consent", + }); + if (kind === "disabled") + vi.mocked(selectFanConfig).mockResolvedValue({ + site_id: "site", + enabled: false, + return_url: "https://example.com/site", + revision: 1, + marketing_text: "Consent", + }); + if (kind === "nameless") vi.mocked(selectAccounts).mockResolvedValue([{ name: " " }] as never); + await expect( + authorizeSelectedSitePublication( + "actor", + { site: current, candidate }, + "https://example.com/site", + ), + ).rejects.toThrow(); +}); +it("allows existing personal artist access but not a workspace bypass", async () => { + vi.mocked(selectArtistOrganizationIds).mockResolvedValue([]); + vi.mocked(checkAccountArtistAccess).mockResolvedValue(true); + await authorizeSelectedSitePublication( + "workspace", + { site, candidate }, + "https://example.com/site", + ); + await expect(authorize()).rejects.toMatchObject({ status: 403 }); +}); +it("propagates context and configuration read errors", async () => { + vi.mocked(readSiteContextBrief).mockRejectedValue(new Error("Context revoked")); + await expect(authorize()).rejects.toThrow("Context revoked"); + vi.mocked(readSiteContextBrief).mockResolvedValue({} as never); + vi.mocked(selectFanConfig).mockRejectedValue(new Error("Unavailable")); + await expect(authorize()).rejects.toThrow("Unavailable"); +}); diff --git a/lib/sites/__tests__/selectedPublication.test.ts b/lib/sites/__tests__/selectedPublication.test.ts new file mode 100644 index 000000000..28aeeb53b --- /dev/null +++ b/lib/sites/__tests__/selectedPublication.test.ts @@ -0,0 +1,317 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import vectors from "./fixtures/site-evidence-digests.json"; +import { publishSelectedSiteEvidence } from "../production/publication/publishSelectedSiteEvidence"; +import { selectSite } from "@/lib/supabase/sites/selectSite"; +import { authorizeSiteWorkspace } from "../authorizeSiteWorkspace"; +import { readPublishableBuild } from "../production/readPublishableBuild"; +import { authorizeSelectedSitePublication } from "../production/publication/authorizeSelectedSitePublication"; +import { selectSitePublishEvidence } from "@/lib/supabase/site_publish_evidence/selectSitePublishEvidence"; +import { insertSiteOverrideEvidence } from "@/lib/supabase/site_publish_evidence/insertSiteOverrideEvidence"; +import { publishSiteEvidenceCandidate } from "@/lib/supabase/site_publish_evidence/publishSiteEvidenceCandidate"; +import { hashSiteEvidence } from "../production/hashSiteEvidence"; +import type { Site, SiteSnapshot } from "../schema"; +vi.mock("@/lib/supabase/sites/selectSite", () => ({ selectSite: vi.fn() })); +vi.mock("../authorizeSiteWorkspace", () => ({ authorizeSiteWorkspace: vi.fn() })); +vi.mock("../production/readPublishableBuild", () => ({ readPublishableBuild: vi.fn() })); +vi.mock("../production/publication/authorizeSelectedSitePublication", () => ({ + authorizeSelectedSitePublication: vi.fn(), +})); +vi.mock("@/lib/supabase/site_publish_evidence/selectSitePublishEvidence", () => ({ + selectSitePublishEvidence: vi.fn(), +})); +vi.mock("@/lib/supabase/site_publish_evidence/insertSiteOverrideEvidence", () => ({ + insertSiteOverrideEvidence: vi.fn(), +})); +vi.mock("@/lib/supabase/site_publish_evidence/publishSiteEvidenceCandidate", () => ({ + publishSiteEvidenceCandidate: vi.fn(), +})); +const actor = "00000000-0000-4000-8000-000000000001"; +const siteId = "00000000-0000-4000-8000-000000000002"; +const ownerId = "00000000-0000-4000-8000-000000000003"; +const evidenceId = "00000000-0000-4000-8000-000000000004"; +const artistId = "00000000-0000-4000-8000-000000000005"; +function fixture() { + const v = structuredClone(vectors.vectors[0]); + const candidate = v.candidate as unknown as SiteSnapshot; + const site = { + id: siteId, + owner_id: ownerId, + artist_id: artistId, + revision: 8, + draft: candidate, + published_evidence_id: null, + } as Site & { published_evidence_id: string | null }; + const record = { + id: evidenceId, + siteId, + ownerId, + revision: 8, + candidateSha256: v.candidateSha256, + recordedByAccountId: actor, + recordedAt: "2026-11-17T00:00:00.000000Z", + kind: "review", + review: v.review, + reviewSha256: v.reviewSha256, + }; + const selection = { + siteId, + ownerId, + artistId, + revision: 8, + candidateSha256: v.candidateSha256, + expectedPublishedEvidenceId: null as string | null, + }; + const request = { selection, evidence: { kind: "review", evidenceId } }; + vi.mocked(selectSite).mockResolvedValue(site); + vi.mocked(selectSitePublishEvidence).mockResolvedValue(record); + const receipt = { + site: { + ...site, + published: candidate, + published_evidence_id: evidenceId, + published_at: "2026-11-17T00:00:01+00:00", + }, + evidence: record, + humanApproval: "not-recorded", + }; + vi.mocked(publishSiteEvidenceCandidate).mockResolvedValue(receipt); + const publish = (raw: unknown = request) => + publishSelectedSiteEvidence({ accountId: actor, operationKey: "run:explicit-publish" }, raw); + return { site, record, request, receipt, publish }; +} +beforeEach(() => vi.resetAllMocks()); +describe("unwired exact selected publication", () => { + it("runs the real assessment and repeats authority before fixed SQL publication", async () => { + const f = fixture(); + expect(await f.publish()).toMatchObject({ humanApproval: "not-recorded" }); + expect(selectSite).toHaveBeenCalledTimes(2); + expect(authorizeSelectedSitePublication).toHaveBeenCalledTimes(2); + expect(selectSitePublishEvidence).toHaveBeenCalledTimes(2); + expect(publishSiteEvidenceCandidate).toHaveBeenCalledWith({ + accountId: actor, + ownerId, + siteId, + revision: 8, + evidenceId, + candidateSha256: f.request.selection.candidateSha256, + expectedPublishedEvidenceId: null, + }); + expect(insertSiteOverrideEvidence).not.toHaveBeenCalled(); + }); + it("records explicit intent only for the already matched authorized candidate", async () => { + const f = fixture(); + const override = { + kind: "override", + intent: "publish-without-passed-review", + reason: "Publish this selected preview", + }; + const record = { ...f.record, ...override }; + delete (record as any).review; + delete (record as any).reviewSha256; + vi.mocked(insertSiteOverrideEvidence).mockResolvedValue(record); + vi.mocked(selectSitePublishEvidence).mockResolvedValue(record); + f.receipt.evidence = record as any; + await f.publish({ selection: f.request.selection, evidence: override }); + expect(insertSiteOverrideEvidence).toHaveBeenCalledWith( + expect.objectContaining({ + accountId: actor, + operationKey: "run:explicit-publish", + candidate: f.site.draft, + intent: override.intent, + reason: override.reason, + }), + ); + }); + it.each(["revision", "digest", "pointer", "owner", "artist", "missing-pointer"])( + "rejects changed %s before capture/write", + async field => { + const f = fixture(); + if (field === "revision") f.site.revision++; + if (field === "digest") f.site.draft!.design.experience!.html += "changed"; + if (field === "pointer") f.site.published_evidence_id = actor; + if (field === "owner") f.site.owner_id = actor; + if (field === "artist") f.site.artist_id = actor; + if (field === "missing-pointer") delete (f.site as any).published_evidence_id; + await expect(f.publish()).rejects.toMatchObject({ status: 409 }); + expect(insertSiteOverrideEvidence).not.toHaveBeenCalled(); + expect(publishSiteEvidenceCandidate).not.toHaveBeenCalled(); + }, + ); + it("rejects implicit legacy Publish input", async () => { + const f = fixture(); + await expect(f.publish({ id: siteId, revision: 8 })).rejects.toThrow(); + expect(selectSite).not.toHaveBeenCalled(); + }); + it.each(["", " ", "\u00a0", "\ufeff"])("rejects empty override reason", async reason => { + const f = fixture(); + await expect( + f.publish({ + selection: f.request.selection, + evidence: { kind: "override", intent: "publish-without-passed-review", reason }, + }), + ).rejects.toThrow(); + expect(insertSiteOverrideEvidence).not.toHaveBeenCalled(); + }); + it("rejects a different same-revision working preview at final recheck", async () => { + const f = fixture(); + const changed = structuredClone(f.site.draft!); + changed.design.experience!.javascript += ";void 1"; + vi.mocked(readPublishableBuild) + .mockResolvedValueOnce(f.site.draft!) + .mockResolvedValueOnce(changed); + await expect( + f.publish({ ...f.request, selection: { ...f.request.selection, generationToken: "signed" } }), + ).rejects.toMatchObject({ status: 409 }); + expect(publishSiteEvidenceCandidate).not.toHaveBeenCalled(); + }); + it.each(["paid", "context", "artist", "workspace", "generation"])( + "does not fallback after final %s revocation", + async kind => { + const f = fixture(); + const error = new Error(kind + " revoked"); + if (kind === "workspace") + vi.mocked(authorizeSiteWorkspace) + .mockResolvedValueOnce(ownerId) + .mockRejectedValueOnce(error); + else if (kind === "generation") + vi.mocked(readPublishableBuild) + .mockResolvedValueOnce(f.site.draft!) + .mockRejectedValueOnce(error); + else + vi.mocked(authorizeSelectedSitePublication) + .mockResolvedValueOnce(undefined) + .mockRejectedValueOnce(error); + await expect( + f.publish( + kind === "generation" + ? { ...f.request, selection: { ...f.request.selection, generationToken: "signed" } } + : f.request, + ), + ).rejects.toThrow("revoked"); + expect(publishSiteEvidenceCandidate).not.toHaveBeenCalled(); + }, + ); + it.each(["failed", "report-hash", "artifact", "foreign-record"])( + "rejects %s using the actual predicate", + async kind => { + const f = fixture(); + if (kind === "failed") { + f.record.review.verdict = "revise"; + f.record.reviewSha256 = hashSiteEvidence(f.record.review); + } + if (kind === "report-hash") f.record.reviewSha256 = "0".repeat(64); + if (kind === "artifact") { + f.record.review.verification.evidence.runnerSha256 = "0".repeat(64); + f.record.reviewSha256 = hashSiteEvidence(f.record.review); + } + if (kind === "foreign-record") f.record.ownerId = actor; + await expect(f.publish()).rejects.toMatchObject({ status: 409 }); + expect(publishSiteEvidenceCandidate).not.toHaveBeenCalled(); + }, + ); + it("propagates SQL conflict once with the original pointer and key", async () => { + const f = fixture(); + vi.mocked(publishSiteEvidenceCandidate).mockRejectedValue(new Error("conflict")); + await expect(f.publish()).rejects.toThrow("conflict"); + expect(publishSiteEvidenceCandidate).toHaveBeenCalledTimes(1); + }); + it("never treats an override from another actor as this actor's intent", async () => { + const f = fixture(); + vi.mocked(insertSiteOverrideEvidence).mockResolvedValue({ + ...f.record, + kind: "override", + intent: "publish-without-passed-review", + reason: "Publish now", + recordedByAccountId: ownerId, + }); + await expect( + f.publish({ + selection: f.request.selection, + evidence: { + kind: "override", + intent: "publish-without-passed-review", + reason: "Publish now", + }, + }), + ).rejects.toMatchObject({ status: 503 }); + expect(publishSiteEvidenceCandidate).not.toHaveBeenCalled(); + }); + it.each(["pointer", "artist", "published", "record"])( + "rejects malformed publication receipt %s without retry", + async field => { + const f = fixture(); + if (field === "pointer") f.receipt.site.published_evidence_id = actor; + if (field === "artist") f.receipt.site.artist_id = actor; + if (field === "published") { + f.receipt.site.published = structuredClone(f.site.draft!); + f.receipt.site.published.design.experience!.html = "changed"; + } + if (field === "record") f.receipt.evidence = { ...f.record, id: actor }; + await expect(f.publish()).rejects.toMatchObject({ status: 503 }); + expect(publishSiteEvidenceCandidate).toHaveBeenCalledTimes(1); + }, + ); +}); + +it("rejects missing trusted actor or invalid server key before reads", async () => { + const f = fixture(); + await expect( + publishSelectedSiteEvidence({ accountId: "", operationKey: "key" }, f.request), + ).rejects.toMatchObject({ status: 401 }); + await expect( + publishSelectedSiteEvidence({ accountId: actor, operationKey: "bad key" }, f.request), + ).rejects.toMatchObject({ status: 400 }); + expect(selectSite).not.toHaveBeenCalled(); +}); +it.each(["accountId", "candidate", "operationKey"])( + "rejects request-body %s authority", + async field => { + const f = fixture(); + await expect(f.publish({ ...f.request, [field]: "injected" })).rejects.toThrow(); + expect(selectSite).not.toHaveBeenCalled(); + }, +); +it("checks authority before recording explicit override intent", async () => { + const f = fixture(); + vi.mocked(authorizeSelectedSitePublication).mockRejectedValue(new Error("Access unavailable")); + await expect( + f.publish({ + selection: f.request.selection, + evidence: { + kind: "override", + intent: "publish-without-passed-review", + reason: "Publish now", + }, + }), + ).rejects.toThrow("Access unavailable"); + expect(insertSiteOverrideEvidence).not.toHaveBeenCalled(); + expect(publishSiteEvidenceCandidate).not.toHaveBeenCalled(); +}); +it("rejects a changed publication pointer at the final boundary", async () => { + const f = fixture(); + vi.mocked(selectSite) + .mockResolvedValueOnce(f.site) + .mockResolvedValueOnce({ ...f.site, published_evidence_id: actor } as Site); + await expect(f.publish()).rejects.toMatchObject({ status: 409 }); + expect(publishSiteEvidenceCandidate).not.toHaveBeenCalled(); +}); +it("propagates final evidence read failures without override or publication", async () => { + const f = fixture(); + vi.mocked(selectSitePublishEvidence) + .mockResolvedValueOnce(f.record) + .mockRejectedValueOnce(new Error("Record unavailable")); + await expect(f.publish()).rejects.toThrow("Record unavailable"); + expect(insertSiteOverrideEvidence).not.toHaveBeenCalled(); + expect(publishSiteEvidenceCandidate).not.toHaveBeenCalled(); +}); +it("does not accept an override record through the review branch", async () => { + const f = fixture(); + vi.mocked(selectSitePublishEvidence).mockResolvedValue({ + ...f.record, + kind: "override", + intent: "publish-without-passed-review", + reason: "Earlier intent", + }); + await expect(f.publish()).rejects.toMatchObject({ status: 409 }); + expect(publishSiteEvidenceCandidate).not.toHaveBeenCalled(); +}); diff --git a/lib/sites/fanConnection/__tests__/readPaidSiteSubscription.test.ts b/lib/sites/fanConnection/__tests__/readPaidSiteSubscription.test.ts new file mode 100644 index 000000000..5ab69acb6 --- /dev/null +++ b/lib/sites/fanConnection/__tests__/readPaidSiteSubscription.test.ts @@ -0,0 +1,17 @@ +import { expect, it, vi } from "vitest"; +import { hasPaidSiteSubscription } from "../hasPaidSiteSubscription"; +import { readPaidSiteSubscription } from "../readPaidSiteSubscription"; +import { getActiveSubscriptions } from "@/lib/stripe/getActiveSubscriptions"; +vi.mock("@/lib/stripe/getActiveSubscriptions", () => ({ getActiveSubscriptions: vi.fn() })); +it("preserves existing fan cache while fresh publication reads observe revocation", async () => { + vi.mocked(getActiveSubscriptions) + .mockResolvedValueOnce([ + { status: "active", items: { data: [{ price: { unit_amount: 100 } }] } }, + ] as never) + .mockResolvedValue([]); + expect(await hasPaidSiteSubscription("fresh-test-owner")).toBe(true); + expect(await hasPaidSiteSubscription("fresh-test-owner")).toBe(true); + expect(getActiveSubscriptions).toHaveBeenCalledTimes(1); + expect(await readPaidSiteSubscription("fresh-test-owner")).toBe(false); + expect(getActiveSubscriptions).toHaveBeenCalledTimes(2); +}); diff --git a/lib/sites/fanConnection/__tests__/resolveSiteFanReturnUrl.test.ts b/lib/sites/fanConnection/__tests__/resolveSiteFanReturnUrl.test.ts new file mode 100644 index 000000000..ea53ca3ef --- /dev/null +++ b/lib/sites/fanConnection/__tests__/resolveSiteFanReturnUrl.test.ts @@ -0,0 +1,24 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { resolveSiteFanReturnUrl } from "../resolveSiteFanReturnUrl"; +afterEach(() => vi.unstubAllEnvs()); +it("prefers explicit destination, then existing configuration, then public site URL", () => { + vi.stubEnv("SITES_PUBLIC_ORIGIN", "https://public.example"); + expect( + resolveSiteFanReturnUrl("site", "https://configured.example", "https://selected.example"), + ).toBe("https://selected.example"); + expect(resolveSiteFanReturnUrl("site", "https://configured.example")).toBe( + "https://configured.example", + ); + expect(resolveSiteFanReturnUrl("site")).toBe("https://public.example/s/site"); +}); +it("retains the default origin", () => { + vi.stubEnv("SITES_PUBLIC_ORIGIN", ""); + expect(resolveSiteFanReturnUrl("site")).toBe("https://app.recoupable.dev/s/site"); +}); +it.each([ + "http://unsafe.example", + "https://user:pass@example.com", + "https://example.com/#fragment", +])("rejects unsafe destination %s", value => { + expect(() => resolveSiteFanReturnUrl("site", undefined, value)).toThrow(); +}); diff --git a/lib/sites/fanConnection/hasPaidSiteSubscription.ts b/lib/sites/fanConnection/hasPaidSiteSubscription.ts index 52cf2a089..1176d89eb 100644 --- a/lib/sites/fanConnection/hasPaidSiteSubscription.ts +++ b/lib/sites/fanConnection/hasPaidSiteSubscription.ts @@ -1,22 +1,11 @@ -import { getActiveSubscriptions } from "@/lib/stripe/getActiveSubscriptions"; +import { readPaidSiteSubscription } from "./readPaidSiteSubscription"; const cache = new Map }>(); /** Coalesce concurrent fan requests; keep billing freshness within 30 seconds per instance. */ export async function hasPaidSiteSubscription(ownerId: string) { const existing = cache.get(ownerId); if (existing && existing.until > Date.now()) return existing.result; if (cache.size >= 1000) cache.delete(cache.keys().next().value!); - const result = getActiveSubscriptions( - ownerId, - subscription => - subscription.status === "active" && - subscription.items.data.some(item => (item.price.unit_amount ?? 0) > 0), - ).then(subscriptions => - subscriptions.some( - subscription => - subscription.status === "active" && - subscription.items.data.some(item => (item.price.unit_amount ?? 0) > 0), - ), - ); + const result = readPaidSiteSubscription(ownerId); cache.set(ownerId, { until: Date.now() + 30000, result }); return result; } diff --git a/lib/sites/fanConnection/prepareSiteFanConnection.ts b/lib/sites/fanConnection/prepareSiteFanConnection.ts index f52b6d5ec..6bf20fdd0 100644 --- a/lib/sites/fanConnection/prepareSiteFanConnection.ts +++ b/lib/sites/fanConnection/prepareSiteFanConnection.ts @@ -3,7 +3,7 @@ import { selectFanConfig } from "@/lib/supabase/site_fan_connections/selectFanCo import { updateFanConfig } from "@/lib/supabase/site_fan_connections/updateFanConfig"; import { hasPaidSiteSubscription } from "./hasPaidSiteSubscription"; import { getFanOAuthConfig } from "./getFanOAuthConfig"; -import { returnUrlSchema } from "./schema"; +import { resolveSiteFanReturnUrl } from "./resolveSiteFanReturnUrl"; import { SiteError } from "../SiteError"; /** Publishing requires a paid workspace and automatically includes Spotify fan connection. */ export async function prepareSiteFanConnection( @@ -22,11 +22,7 @@ export async function prepareSiteFanConnection( "Choose an artist for this site before publishing so Spotify fans are attributed correctly.", ); const config = await selectFanConfig(site.id); - const destination = returnUrlSchema.parse( - returnUrl ?? - config?.return_url ?? - `${process.env.SITES_PUBLIC_ORIGIN || "https://app.recoupable.dev"}/s/${site.id}`, - ); + const destination = resolveSiteFanReturnUrl(site.id, config?.return_url, returnUrl); if (config?.enabled && config.return_url === destination) return "enabled" as const; const [artist] = await selectAccounts(site.artist_id); if (!artist?.name?.trim()) throw new SiteError(400, "Add the artist's name before publishing."); diff --git a/lib/sites/fanConnection/readPaidSiteSubscription.ts b/lib/sites/fanConnection/readPaidSiteSubscription.ts new file mode 100644 index 000000000..d121c479f --- /dev/null +++ b/lib/sites/fanConnection/readPaidSiteSubscription.ts @@ -0,0 +1,8 @@ +import { getActiveSubscriptions } from "@/lib/stripe/getActiveSubscriptions"; +/** Fresh read using the existing paid-site rule; no per-instance fan-request cache. */ +export async function readPaidSiteSubscription(ownerId: string) { + const eligible = (subscription: Awaited>[number]) => + subscription.status === "active" && + subscription.items.data.some(item => (item.price.unit_amount ?? 0) > 0); + return (await getActiveSubscriptions(ownerId, eligible)).some(eligible); +} diff --git a/lib/sites/fanConnection/resolveSiteFanReturnUrl.ts b/lib/sites/fanConnection/resolveSiteFanReturnUrl.ts new file mode 100644 index 000000000..7cd975641 --- /dev/null +++ b/lib/sites/fanConnection/resolveSiteFanReturnUrl.ts @@ -0,0 +1,13 @@ +import { returnUrlSchema } from "./schema"; +/** Shared precedence and validation for preparing or requiring a fan destination. */ +export function resolveSiteFanReturnUrl( + siteId: string, + configuredUrl?: string, + returnUrl?: string, +) { + return returnUrlSchema.parse( + returnUrl ?? + configuredUrl ?? + `${process.env.SITES_PUBLIC_ORIGIN || "https://app.recoupable.dev"}/s/${siteId}`, + ); +} diff --git a/lib/sites/production/publication/authorizeSelectedSitePublication.ts b/lib/sites/production/publication/authorizeSelectedSitePublication.ts new file mode 100644 index 000000000..9e3073635 --- /dev/null +++ b/lib/sites/production/publication/authorizeSelectedSitePublication.ts @@ -0,0 +1,40 @@ +import { selectArtistOrganizationIds } from "@/lib/supabase/artist_organization_ids/selectArtistOrganizationIds"; +import { checkAccountArtistAccess } from "@/lib/artists/checkAccountArtistAccess"; +import { selectAccounts } from "@/lib/supabase/accounts/selectAccounts"; +import { selectFanConfig } from "@/lib/supabase/site_fan_connections/selectFanConfig"; +import { readPaidSiteSubscription } from "../../fanConnection/readPaidSiteSubscription"; +import { getFanOAuthConfig } from "../../fanConnection/getFanOAuthConfig"; +import { resolveSiteFanReturnUrl } from "../../fanConnection/resolveSiteFanReturnUrl"; +import { readSiteContextBrief } from "../readSiteContextBrief"; +import { SiteError } from "../../SiteError"; +import type { Site, SiteSnapshot } from "../../schema"; +/** Read-only authority checks; unsupported artist/configuration writes are rejected. */ +export async function authorizeSelectedSitePublication( + accountId: string, + resolved: { + site: Site; + candidate: SiteSnapshot; + }, + returnUrl?: string, +) { + const { site, candidate } = resolved; + const briefId = candidate.production?.context.engine?.briefId; + if (briefId) await readSiteContextBrief(site, accountId, briefId); + if (!site.artist_id) + throw new SiteError(409, "Artist attribution must be prepared before publication"); + const organizations = await selectArtistOrganizationIds(site.artist_id); + const belongs = organizations?.some(row => row.organization_id === site.owner_id) ?? false; + const personalAccess = + site.owner_id === accountId && (await checkAccountArtistAccess(accountId, site.artist_id)); + if (!belongs && !personalAccess) + throw new SiteError(403, "Artist not available in this workspace"); + if (!(await readPaidSiteSubscription(site.owner_id))) + throw new SiteError(402, "Paid site entitlement unavailable"); + getFanOAuthConfig(); + const config = await selectFanConfig(site.id); + const destination = resolveSiteFanReturnUrl(site.id, config?.return_url, returnUrl); + if (!config?.enabled || config.site_id !== site.id || config.return_url !== destination) + throw new SiteError(409, "Fan connection must already be prepared for this destination"); + const [artist] = await selectAccounts(site.artist_id); + if (!artist?.name?.trim()) throw new SiteError(400, "Add the artist's name before publishing"); +} diff --git a/lib/sites/production/publication/publishSelectedSiteEvidence.ts b/lib/sites/production/publication/publishSelectedSiteEvidence.ts new file mode 100644 index 000000000..b0cfae02b --- /dev/null +++ b/lib/sites/production/publication/publishSelectedSiteEvidence.ts @@ -0,0 +1,89 @@ +import { selectSitePublishEvidence } from "@/lib/supabase/site_publish_evidence/selectSitePublishEvidence"; +import { insertSiteOverrideEvidence } from "@/lib/supabase/site_publish_evidence/insertSiteOverrideEvidence"; +import { publishSiteEvidenceCandidate } from "@/lib/supabase/site_publish_evidence/publishSiteEvidenceCandidate"; +import { SiteError } from "../../SiteError"; +import { assessSitePublishEvidence } from "../assessSitePublishEvidence"; +import { sitePublishEvidenceSchema } from "../sitePublishEvidenceSchema"; +import { selectedSitePublicationSchema } from "./selectedSitePublicationSchema"; +import { resolveSelectedSiteCandidate } from "./resolveSelectedSiteCandidate"; +import { authorizeSelectedSitePublication } from "./authorizeSelectedSitePublication"; +import { validateSiteOverrideReceipt } from "./validateSiteOverrideReceipt"; +import { validateSitePublicationReceipt } from "./validateSitePublicationReceipt"; + +/** UNWIRED. Server identity/key are trusted context, not fields in raw input. + * External authority checks are repeated but are not atomic with the proposed SQL fence. + */ +export async function publishSelectedSiteEvidence( + server: { accountId: string; operationKey: string }, + raw: unknown, +) { + if (!server.accountId) throw new SiteError(401, "Authentication required"); + if (!/^[A-Za-z0-9._:-]{1,128}$/.test(server.operationKey)) + throw new SiteError(400, "Invalid server operation key"); + const input = selectedSitePublicationSchema.parse(raw); + const { selection } = input; + let resolved = await resolveSelectedSiteCandidate(server.accountId, selection); + await authorizeSelectedSitePublication(server.accountId, resolved, input.returnUrl); + let evidenceId: string; + if (input.evidence.kind === "override") { + const captured = await insertSiteOverrideEvidence({ + ...resolved.identity, + accountId: server.accountId, + operationKey: server.operationKey, + candidate: resolved.candidate, + intent: input.evidence.intent, + reason: input.evidence.reason, + }); + evidenceId = validateSiteOverrideReceipt( + captured, + server.accountId, + resolved.identity, + input.evidence.reason, + ).id; + } else evidenceId = input.evidence.evidenceId; + const assess = async () => { + const record = sitePublishEvidenceSchema.parse( + await selectSitePublishEvidence({ + accountId: server.accountId, + ownerId: selection.ownerId, + siteId: selection.siteId, + evidenceId, + }), + ); + if (record.kind !== input.evidence.kind) + throw new SiteError(409, "Evidence kind does not match selected intent"); + if (input.evidence.kind === "override") + validateSiteOverrideReceipt( + record, + server.accountId, + resolved.identity, + input.evidence.reason, + ); + const assessment = await assessSitePublishEvidence( + { siteId: selection.siteId, revision: selection.revision, evidenceId }, + { + accountId: server.accountId, + readCandidate: async () => ({ ...resolved.identity, candidate: resolved.candidate }), + readEvidence: async () => record, + now: Date.now, + }, + ); + if (assessment.status !== "satisfied") + throw new SiteError(409, "Selected evidence is not eligible: " + assessment.reason); + return record; + }; + await assess(); + resolved = await resolveSelectedSiteCandidate(server.accountId, selection); + await authorizeSelectedSitePublication(server.accountId, resolved, input.returnUrl); + const record = await assess(); + const result = await publishSiteEvidenceCandidate({ + accountId: server.accountId, + ownerId: selection.ownerId, + siteId: selection.siteId, + revision: selection.revision, + evidenceId, + candidateSha256: selection.candidateSha256, + expectedPublishedEvidenceId: selection.expectedPublishedEvidenceId, + }); + return validateSitePublicationReceipt(result, selection, record); +} diff --git a/lib/sites/production/publication/resolveSelectedSiteCandidate.ts b/lib/sites/production/publication/resolveSelectedSiteCandidate.ts new file mode 100644 index 000000000..739c7a21a --- /dev/null +++ b/lib/sites/production/publication/resolveSelectedSiteCandidate.ts @@ -0,0 +1,43 @@ +import { z } from "zod"; +import { selectSite } from "@/lib/supabase/sites/selectSite"; +import { authorizeSiteWorkspace } from "../../authorizeSiteWorkspace"; +import { SiteError } from "../../SiteError"; +import { readPublishableBuild } from "../readPublishableBuild"; +import { getSitePublishIdentity } from "../getSitePublishIdentity"; +import type { SitePublicationSelection } from "./selectedSitePublicationSchema"; +/** Selection fields are expectations, never authority or a request-body snapshot. */ +export async function resolveSelectedSiteCandidate( + accountId: string, + selection: SitePublicationSelection, +) { + if (!accountId) throw new SiteError(401, "Authentication required"); + const site = await selectSite(selection.siteId); + if (!site) throw new SiteError(404, "Site not found"); + await authorizeSiteWorkspace(accountId, site.owner_id); + const pointer = z + .uuid() + .nullable() + .safeParse((site as unknown as Record).published_evidence_id); + if ( + !pointer.success || + pointer.data !== selection.expectedPublishedEvidenceId || + site.id !== selection.siteId || + site.owner_id !== selection.ownerId || + site.revision !== selection.revision || + site.artist_id !== selection.artistId + ) + throw new SiteError(409, "Selected site or publication metadata changed or is unavailable"); + const candidate = selection.generationToken + ? await readPublishableBuild(selection.generationToken, site, accountId) + : site.draft; + if (!candidate?.design.experience) throw new SiteError(409, "Selected preview unavailable"); + const identity = getSitePublishIdentity({ + siteId: site.id, + ownerId: site.owner_id, + revision: site.revision, + candidate, + }); + if (identity.candidateSha256 !== selection.candidateSha256) + throw new SiteError(409, "Selected preview changed; select it again before publishing"); + return { site, candidate: structuredClone(candidate), identity }; +} diff --git a/lib/sites/production/publication/selectedSitePublicationSchema.ts b/lib/sites/production/publication/selectedSitePublicationSchema.ts new file mode 100644 index 000000000..0f8eb33fc --- /dev/null +++ b/lib/sites/production/publication/selectedSitePublicationSchema.ts @@ -0,0 +1,29 @@ +import { z } from "zod"; +import { returnUrlSchema } from "../../fanConnection/schema"; +export const selectedSitePublicationSchema = z + .object({ + selection: z + .object({ + siteId: z.uuid(), + ownerId: z.uuid(), + artistId: z.uuid().nullable(), + revision: z.number().int().nonnegative().safe(), + candidateSha256: z.string().regex(/^[a-f0-9]{64}$/), + expectedPublishedEvidenceId: z.uuid().nullable(), + generationToken: z.string().min(1).max(3000).optional(), + }) + .strict(), + evidence: z.discriminatedUnion("kind", [ + z.object({ kind: z.literal("review"), evidenceId: z.uuid() }).strict(), + z + .object({ + kind: z.literal("override"), + intent: z.literal("publish-without-passed-review"), + reason: z.string().trim().min(1).max(2000), + }) + .strict(), + ]), + returnUrl: returnUrlSchema.optional(), + }) + .strict(); +export type SitePublicationSelection = z.infer["selection"]; diff --git a/lib/sites/production/publication/validateSiteOverrideReceipt.ts b/lib/sites/production/publication/validateSiteOverrideReceipt.ts new file mode 100644 index 000000000..f9b8d010f --- /dev/null +++ b/lib/sites/production/publication/validateSiteOverrideReceipt.ts @@ -0,0 +1,25 @@ +import { z } from "zod"; +import { sitePublishEvidenceSchema } from "../sitePublishEvidenceSchema"; +import { SiteError } from "../../SiteError"; +import type { getSitePublishIdentity } from "../getSitePublishIdentity"; +/** Never treat a mismatched create-once receipt as this actor's explicit intent. */ +export function validateSiteOverrideReceipt( + raw: unknown, + accountId: string, + identity: ReturnType, + reason: string, +) { + const parsed = sitePublishEvidenceSchema.safeParse(raw); + if (!parsed.success) throw new SiteError(503, "Invalid override receipt"); + const record = parsed.data; + if ( + record.kind !== "override" || + record.reason !== reason || + record.recordedByAccountId !== accountId || + !z.uuid().safeParse(record.id).success || + Date.parse(record.recordedAt) > Date.now() || + Object.entries(identity).some(([key, value]) => record[key as keyof typeof identity] !== value) + ) + throw new SiteError(503, "Override receipt does not match selected intent"); + return record; +} diff --git a/lib/sites/production/publication/validateSitePublicationReceipt.ts b/lib/sites/production/publication/validateSitePublicationReceipt.ts new file mode 100644 index 000000000..f95b360ef --- /dev/null +++ b/lib/sites/production/publication/validateSitePublicationReceipt.ts @@ -0,0 +1,61 @@ +import { z } from "zod"; +import { sitePublishEvidenceSchema } from "../sitePublishEvidenceSchema"; +import { getSitePublishIdentity } from "../getSitePublishIdentity"; +import { serializeSiteEvidence } from "../serializeSiteEvidence"; +import { SiteError } from "../../SiteError"; +import type { SiteSnapshot } from "../../schema"; +import type { SitePublicationSelection } from "./selectedSitePublicationSchema"; +const receiptSchema = z.object({ + site: z + .object({ + id: z.uuid(), + owner_id: z.uuid(), + artist_id: z.uuid(), + revision: z.number().int().nonnegative(), + published_evidence_id: z.uuid(), + published_at: z.iso.datetime({ offset: true }), + published: z + .object({ + design: z.object({ + experience: z.object({ + html: z.string().min(1), + css: z.string(), + javascript: z.string(), + }), + }), + }) + .passthrough(), + }) + .passthrough(), + evidence: sitePublishEvidenceSchema, + humanApproval: z.literal("not-recorded"), +}); +/** Failure here may follow a committed write. Propagate; never automatically retry/rekey. */ +export function validateSitePublicationReceipt( + raw: unknown, + selection: SitePublicationSelection, + record: z.infer, +) { + const parsed = receiptSchema.safeParse(raw); + if (!parsed.success) throw new SiteError(503, "Invalid publication receipt"); + const { site, evidence } = parsed.data; + // Inspect original JSON, not a Zod-stripped nested design, when checking exact content. + const published = (raw as { site: { published: SiteSnapshot } }).site.published; + const identity = getSitePublishIdentity({ + siteId: site.id, + ownerId: site.owner_id, + revision: site.revision, + candidate: published, + }); + if ( + site.id !== selection.siteId || + site.owner_id !== selection.ownerId || + site.artist_id !== selection.artistId || + site.revision !== selection.revision || + site.published_evidence_id !== record.id || + identity.candidateSha256 !== selection.candidateSha256 || + serializeSiteEvidence(evidence) !== serializeSiteEvidence(record) + ) + throw new SiteError(503, "Publication receipt does not match selection"); + return { ...parsed.data, site: { ...site, published } }; +} diff --git a/lib/supabase/site_publish_evidence/__tests__/publicationRpc.test.ts b/lib/supabase/site_publish_evidence/__tests__/publicationRpc.test.ts new file mode 100644 index 000000000..0ac738da2 --- /dev/null +++ b/lib/supabase/site_publish_evidence/__tests__/publicationRpc.test.ts @@ -0,0 +1,78 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import { insertSiteOverrideEvidence } from "../insertSiteOverrideEvidence"; +import { publishSiteEvidenceCandidate } from "../publishSiteEvidenceCandidate"; +import vectors from "@/lib/sites/__tests__/fixtures/site-evidence-digests.json"; +import type { SiteSnapshot } from "@/lib/sites/schema"; +const { rpc } = vi.hoisted(() => ({ rpc: vi.fn() })); +vi.mock("@/lib/supabase/serverClient", () => ({ default: { schema: () => ({ rpc }) } })); +beforeEach(() => { + vi.clearAllMocks(); + rpc.mockResolvedValue({ data: { id: "receipt" }, error: null }); +}); +it("captures explicit intent with original candidate bytes and no report", async () => { + const v = vectors.vectors[0]; + await insertSiteOverrideEvidence({ + accountId: "actor", + ownerId: "owner", + siteId: "site", + revision: 8, + operationKey: "run:publish", + candidate: v.candidate as unknown as SiteSnapshot, + intent: "publish-without-passed-review", + reason: "Publish now", + }); + expect(rpc).toHaveBeenCalledWith("record_evidence", { + p_actor: "actor", + p_owner: "owner", + p_site: "site", + p_revision: 8, + p_key: "run:publish", + p_candidate: v.candidate, + p_candidate_canonical: v.candidateCanonical, + p_candidate_sha: v.candidateSha256, + p_decision: { + kind: "override", + intent: "publish-without-passed-review", + reason: "Publish now", + }, + p_review_canonical: null, + }); +}); +it.each([null, "pointer"])( + "passes nullable pointer explicitly to the fixed publication RPC", + async expectedPublishedEvidenceId => { + await publishSiteEvidenceCandidate({ + accountId: "actor", + ownerId: "owner", + siteId: "site", + revision: 8, + evidenceId: "record", + candidateSha256: "a".repeat(64), + expectedPublishedEvidenceId, + }); + expect(rpc).toHaveBeenCalledWith("publish_candidate", { + p_actor: "actor", + p_owner: "owner", + p_site: "site", + p_revision: 8, + p_record: "record", + p_candidate_sha: "a".repeat(64), + p_expected_pointer: expectedPublishedEvidenceId, + }); + }, +); +it("propagates publication conflicts without retries", async () => { + rpc.mockResolvedValue({ data: null, error: { code: "40001" } }); + await expect( + publishSiteEvidenceCandidate({ + accountId: "actor", + ownerId: "owner", + siteId: "site", + revision: 8, + evidenceId: "record", + candidateSha256: "a".repeat(64), + expectedPublishedEvidenceId: null, + }), + ).rejects.toMatchObject({ status: 409 }); + expect(rpc).toHaveBeenCalledOnce(); +}); diff --git a/lib/supabase/site_publish_evidence/callSiteEvidenceRpc.ts b/lib/supabase/site_publish_evidence/callSiteEvidenceRpc.ts index c1fc34f99..9485a82bb 100644 --- a/lib/supabase/site_publish_evidence/callSiteEvidenceRpc.ts +++ b/lib/supabase/site_publish_evidence/callSiteEvidenceRpc.ts @@ -11,8 +11,19 @@ type Functions = { p_candidate: SiteSnapshot; p_candidate_canonical: string; p_candidate_sha: string; - p_decision: { kind: "review"; review: unknown; reviewSha256: string }; - p_review_canonical: string; + p_decision: + | { kind: "review"; review: unknown; reviewSha256: string } + | { kind: "override"; intent: "publish-without-passed-review"; reason: string }; + p_review_canonical: string | null; + }; + Returns: unknown; + }; + publish_candidate: { + Args: Scope & { + p_revision: number; + p_record: string; + p_candidate_sha: string; + p_expected_pointer: string | null; }; Returns: unknown; }; diff --git a/lib/supabase/site_publish_evidence/insertSiteOverrideEvidence.ts b/lib/supabase/site_publish_evidence/insertSiteOverrideEvidence.ts new file mode 100644 index 000000000..c9fb0f490 --- /dev/null +++ b/lib/supabase/site_publish_evidence/insertSiteOverrideEvidence.ts @@ -0,0 +1,30 @@ +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"; +/** UNWIRED: only explicit selected intent after server resolution/authorization. */ +export async function insertSiteOverrideEvidence(input: { + accountId: string; + ownerId: string; + siteId: string; + revision: number; + operationKey: string; + candidate: SiteSnapshot; + intent: "publish-without-passed-review"; + reason: string; +}) { + 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: "override", intent: input.intent, reason: input.reason }, + p_review_canonical: null, + }); +} diff --git a/lib/supabase/site_publish_evidence/publishSiteEvidenceCandidate.ts b/lib/supabase/site_publish_evidence/publishSiteEvidenceCandidate.ts new file mode 100644 index 000000000..c59e23c7f --- /dev/null +++ b/lib/supabase/site_publish_evidence/publishSiteEvidenceCandidate.ts @@ -0,0 +1,21 @@ +import { callSiteEvidenceRpc } from "./callSiteEvidenceRpc"; +/** UNWIRED proposal: SQL publishes the immutable record candidate, never supplied bytes. */ +export async function publishSiteEvidenceCandidate(input: { + accountId: string; + ownerId: string; + siteId: string; + revision: number; + evidenceId: string; + candidateSha256: string; + expectedPublishedEvidenceId: string | null; +}) { + return callSiteEvidenceRpc("publish_candidate", { + p_actor: input.accountId, + p_owner: input.ownerId, + p_site: input.siteId, + p_revision: input.revision, + p_record: input.evidenceId, + p_candidate_sha: input.candidateSha256, + p_expected_pointer: input.expectedPublishedEvidenceId, + }); +} From 1f2b819f1e01d3e158829a678cd84799f81274b5 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:31:03 -0500 Subject: [PATCH 2/3] Fence selected artist publication and tighten evidence error handling --- docs/site-selected-publication.md | 37 ++++++++---- .../__tests__/publicationAuthority.test.ts | 11 +++- .../__tests__/selectedPublication.test.ts | 60 ++++++++++++++++++- .../selectedPublicationSchema.test.ts | 21 +++++++ .../readPaidSiteSubscription.test.ts | 10 ++++ .../fanConnection/readPaidSiteSubscription.ts | 17 +++++- .../authorizeSelectedSitePublication.ts | 6 +- .../publishSelectedSiteEvidence.ts | 5 +- .../resolveSelectedSiteCandidate.ts | 2 +- .../selectedSitePublicationSchema.ts | 11 ++-- .../__tests__/getActiveSubscriptions.test.ts | 8 +++ .../getActiveSubscriptionsTestHelpers.ts | 2 +- lib/stripe/getActiveSubscriptions.ts | 2 + .../__tests__/publicationRpc.test.ts | 20 +++++++ .../buildSiteEvidenceRecordArgs.ts | 25 ++++++++ .../callSiteEvidenceRpc.ts | 1 + .../insertSiteOverrideEvidence.ts | 14 +---- .../insertSitePublishEvidence.ts | 12 +--- .../publishSiteEvidenceCandidate.ts | 2 + 19 files changed, 215 insertions(+), 51 deletions(-) create mode 100644 lib/sites/__tests__/selectedPublicationSchema.test.ts create mode 100644 lib/supabase/site_publish_evidence/buildSiteEvidenceRecordArgs.ts diff --git a/docs/site-selected-publication.md b/docs/site-selected-publication.md index ce00873e9..847b5dc38 100644 --- a/docs/site-selected-publication.md +++ b/docs/site-selected-publication.md @@ -1,7 +1,7 @@ # Unwired exact-selected Sites publication This source extends the evidence adapters from API #1263. It targets the unchanged -**Database #136 proposal**, commit `4caac3cc8a15a47b348109b2fa4f571423d8beb0`. +**Database #136 proposal**, commit `afd214aa73dfd70b0f2b860fce90c12ceb23f28b`. There is no route, UI, MCP or workflow caller. Existing `processSiteOperation` publishing remains advisory and unchanged. No migration, schema exposure, runtime grant, retention activation or publication gate is introduced. @@ -15,7 +15,8 @@ nullable expected publication evidence pointer, and optional signed generation token. These values do not grant access. The server reloads and authorizes the site and resolves the actual draft or signed/current-generation working build. A new preview under the same revision must still match the selected digest. Missing -`published_evidence_id` metadata is an error, never silently interpreted as null. +`published_evidence_id` metadata is a 503, never silently interpreted as null. Valid +selection UUIDs are normalized before comparing them with database values. The input chooses either a stored review ID or explicit `publish-without-passed-review` intent with a nonblank reason. The existing Publish @@ -35,7 +36,7 @@ and execution hashes. Both branches run the full existing `assessSitePublishEvidence` predicate. A failed review never falls back to an override. The server resolves the selected candidate, checks authority and reads and assesses the evidence again before `publish_candidate`. The SQL call receives -only actor/owner/site/revision/record ID/selected digest/expected pointer; SQL copies +only actor/owner/site/revision/record ID/selected digest/expected pointer/expected artist; SQL copies the stored immutable candidate, not API-supplied replacement bytes. ## Existing authority and deliberate unsupported transitions @@ -56,8 +57,9 @@ The new, unwired path reuses these read/check owners: personal-access distinction used by site creation), plus artist name lookup. - The existing active-paid-subscription predicate, extracted into `readPaidSiteSubscription`. The old fan-request helper retains its 30-second - cache; the new path uses fresh reads at both authority passes. The underlying - Stripe reader continues to fail closed to no entitlement on provider errors. + cache; the new path uses fresh reads at both authority passes. The new publication path opts into provider-error propagation and reports a + retryable 503 on read failure; an authoritative unpaid result remains 402. Existing + Stripe consumers and cached fan requests keep their prior default behavior. - `getFanOAuthConfig`, `selectFanConfig`, and the extracted shared `resolveSiteFanReturnUrl` transformation/validator used by existing preparation. @@ -71,16 +73,19 @@ unwired source, not the existing advisory publish flow. ## Atomicity and activation gates -The SQL proposal serializes workspace membership, revision, evidence binding and -publication-pointer CAS. The external paid, Context, artist, fan configuration and +The SQL proposal serializes workspace membership, revision, evidence binding, +publication-pointer CAS and expected artist-ID comparison under the same site row +lock. The selected artist is forwarded as `p_expected_artist_id`; a concurrent +artist change before the transaction locks the row conflicts before publication. +SQL uses `IS DISTINCT FROM`, so null matches null, while null/non-null mismatches +conflict. This does not authorize an artist transition; the API still requires an +already attributed artist. The external paid, Context, artist, fan configuration and Workflow reads are **not atomically serialized with that transaction**. A changed selection or pointer observed by the final recheck is rejected, but changes after -that observation are not prevented by API reads. In particular the proposal does -not compare an expected artist ID or the latest mutable Workflow preview inside -SQL. An artist change after the final read can therefore commit before publication; -receipt validation can detect it only after publication has already committed. -Artist/current-generation race handling and exact preview interaction must be -resolved before activation; this source is not complete end-to-end publication +that observation are not prevented by API reads. The expected-artist comparison closes the previously documented artist-ID race; +it does not lock external artist access/name records or the latest mutable +Workflow preview. Current-generation race handling and exact preview interaction +must still be resolved before activation; this source is not complete end-to-end publication authorization. Pointer CAS also does not solve ABA or order multiple legacy writes that leave the pointer null; see the proposal protocol. @@ -107,3 +112,9 @@ revocation, explicit override capture, mismatched receipts, original report/arti digests and RPC argument/error contracts. Existing working-preview, capture, assessment and fan-configuration tests remain regression checks. No live provider, DB, browser, native share, fan OAuth or publication execution is claimed. + +The SQL artist fence is qualified by local PostgreSQL15/17 fixtures, including +a publisher blocked behind an artist writer and a subsequent conflict with all +publication fields unchanged. API mocks prove argument forwarding and one-shot +conflict propagation, not hosted execution. Capture/read signatures and canonical +golden bytes remain compatible with API#1263. diff --git a/lib/sites/__tests__/publicationAuthority.test.ts b/lib/sites/__tests__/publicationAuthority.test.ts index 81ba4f4c6..e32f7d7fa 100644 --- a/lib/sites/__tests__/publicationAuthority.test.ts +++ b/lib/sites/__tests__/publicationAuthority.test.ts @@ -43,7 +43,7 @@ beforeEach(() => { it("checks the existing brief, workspace artist, fresh paid entitlement, OAuth and prepared fan config", async () => { await authorize(); expect(readSiteContextBrief).toHaveBeenCalledWith(site, "actor", "brief"); - expect(readPaidSiteSubscription).toHaveBeenCalledWith("workspace"); + expect(readPaidSiteSubscription).toHaveBeenCalledWith("workspace", { throwOnError: true }); expect(getFanOAuthConfig).toHaveBeenCalledOnce(); }); it.each([ @@ -102,3 +102,12 @@ it("propagates context and configuration read errors", async () => { vi.mocked(selectFanConfig).mockRejectedValue(new Error("Unavailable")); await expect(authorize()).rejects.toThrow("Unavailable"); }); + +it("short-circuits personal artist lookup when existing workspace ownership suffices", async () => { + await authorizeSelectedSitePublication( + "workspace", + { site, candidate }, + "https://example.com/site", + ); + expect(checkAccountArtistAccess).not.toHaveBeenCalled(); +}); diff --git a/lib/sites/__tests__/selectedPublication.test.ts b/lib/sites/__tests__/selectedPublication.test.ts index 28aeeb53b..dd9e0ee0a 100644 --- a/lib/sites/__tests__/selectedPublication.test.ts +++ b/lib/sites/__tests__/selectedPublication.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import vectors from "./fixtures/site-evidence-digests.json"; import { publishSelectedSiteEvidence } from "../production/publication/publishSelectedSiteEvidence"; import { selectSite } from "@/lib/supabase/sites/selectSite"; @@ -79,7 +79,11 @@ function fixture() { publishSelectedSiteEvidence({ accountId: actor, operationKey: "run:explicit-publish" }, raw); return { site, record, request, receipt, publish }; } -beforeEach(() => vi.resetAllMocks()); +beforeEach(() => { + vi.resetAllMocks(); + vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-11-17T12:00:00Z")); +}); +afterEach(() => vi.restoreAllMocks()); describe("unwired exact selected publication", () => { it("runs the real assessment and repeats authority before fixed SQL publication", async () => { const f = fixture(); @@ -95,6 +99,7 @@ describe("unwired exact selected publication", () => { evidenceId, candidateSha256: f.request.selection.candidateSha256, expectedPublishedEvidenceId: null, + expectedArtistId: artistId, }); expect(insertSiteOverrideEvidence).not.toHaveBeenCalled(); }); @@ -132,7 +137,9 @@ describe("unwired exact selected publication", () => { if (field === "owner") f.site.owner_id = actor; if (field === "artist") f.site.artist_id = actor; if (field === "missing-pointer") delete (f.site as any).published_evidence_id; - await expect(f.publish()).rejects.toMatchObject({ status: 409 }); + await expect(f.publish()).rejects.toMatchObject({ + status: field === "missing-pointer" ? 503 : 409, + }); expect(insertSiteOverrideEvidence).not.toHaveBeenCalled(); expect(publishSiteEvidenceCandidate).not.toHaveBeenCalled(); }, @@ -315,3 +322,50 @@ it("does not accept an override record through the review branch", async () => { await expect(f.publish()).rejects.toMatchObject({ status: 409 }); expect(publishSiteEvidenceCandidate).not.toHaveBeenCalled(); }); + +it("forwards the selected artist after final read and propagates an artist SQL conflict once", async () => { + const f = fixture(); + vi.mocked(publishSiteEvidenceCandidate).mockImplementation(async input => { + expect(input.expectedArtistId).toBe(artistId); + f.site.artist_id = ownerId; // Concurrent writer after the API read; SQL owns the atomic fence. + throw Object.assign(new Error("Publication conflict"), { status: 409 }); + }); + await expect(f.publish()).rejects.toMatchObject({ status: 409 }); + expect(publishSiteEvidenceCandidate).toHaveBeenCalledTimes(1); + expect(insertSiteOverrideEvidence).not.toHaveBeenCalled(); +}); + +it("reports malformed stored evidence as unavailable rather than a raw parser error", async () => { + const f = fixture(); + vi.mocked(selectSitePublishEvidence).mockResolvedValue({ kind: "review" }); + await expect(f.publish()).rejects.toMatchObject({ status: 503 }); + expect(publishSiteEvidenceCandidate).not.toHaveBeenCalled(); +}); +it.each(["reason", "future", "id", "identity"])( + "rejects override capture receipt %s before publication", + async failure => { + const f = fixture(); + const record = { + ...f.record, + kind: "override", + intent: "publish-without-passed-review", + reason: "Publish now", + }; + if (failure === "reason") record.reason = "Different intent"; + if (failure === "future") record.recordedAt = "2026-11-18T00:00:00.000000Z"; + if (failure === "id") record.id = "not-a-uuid"; + if (failure === "identity") record.candidateSha256 = "a".repeat(64); + vi.mocked(insertSiteOverrideEvidence).mockResolvedValue(record); + await expect( + f.publish({ + selection: f.request.selection, + evidence: { + kind: "override", + intent: "publish-without-passed-review", + reason: "Publish now", + }, + }), + ).rejects.toMatchObject({ status: 503 }); + expect(publishSiteEvidenceCandidate).not.toHaveBeenCalled(); + }, +); diff --git a/lib/sites/__tests__/selectedPublicationSchema.test.ts b/lib/sites/__tests__/selectedPublicationSchema.test.ts new file mode 100644 index 000000000..db305559e --- /dev/null +++ b/lib/sites/__tests__/selectedPublicationSchema.test.ts @@ -0,0 +1,21 @@ +import { expect, it } from "vitest"; +import { selectedSitePublicationSchema } from "../production/publication/selectedSitePublicationSchema"; +it("normalizes valid mixed-case UUID selection and evidence references", () => { + const uuid = "ABCDEFAB-1234-4ABC-8DEF-123456789ABC"; + const parsed = selectedSitePublicationSchema.parse({ + selection: { + siteId: uuid, + ownerId: uuid, + artistId: uuid, + revision: 1, + candidateSha256: "a".repeat(64), + expectedPublishedEvidenceId: uuid, + }, + evidence: { kind: "review", evidenceId: uuid }, + }); + expect(parsed.selection.siteId).toBe(uuid.toLowerCase()); + expect(parsed.selection.ownerId).toBe(uuid.toLowerCase()); + expect(parsed.selection.artistId).toBe(uuid.toLowerCase()); + expect(parsed.selection.expectedPublishedEvidenceId).toBe(uuid.toLowerCase()); + expect(parsed.evidence).toEqual({ kind: "review", evidenceId: uuid.toLowerCase() }); +}); diff --git a/lib/sites/fanConnection/__tests__/readPaidSiteSubscription.test.ts b/lib/sites/fanConnection/__tests__/readPaidSiteSubscription.test.ts index 5ab69acb6..d9e73bd23 100644 --- a/lib/sites/fanConnection/__tests__/readPaidSiteSubscription.test.ts +++ b/lib/sites/fanConnection/__tests__/readPaidSiteSubscription.test.ts @@ -15,3 +15,13 @@ it("preserves existing fan cache while fresh publication reads observe revocatio expect(await readPaidSiteSubscription("fresh-test-owner")).toBe(false); expect(getActiveSubscriptions).toHaveBeenCalledTimes(2); }); + +it("distinguishes publication entitlement read failures from unpaid results", async () => { + vi.mocked(getActiveSubscriptions).mockRejectedValue(new Error("Stripe unavailable")); + await expect(readPaidSiteSubscription("owner", { throwOnError: true })).rejects.toMatchObject({ + status: 503, + }); + expect(getActiveSubscriptions).toHaveBeenLastCalledWith("owner", expect.any(Function), { + throwOnError: true, + }); +}); diff --git a/lib/sites/fanConnection/readPaidSiteSubscription.ts b/lib/sites/fanConnection/readPaidSiteSubscription.ts index d121c479f..524fcbad6 100644 --- a/lib/sites/fanConnection/readPaidSiteSubscription.ts +++ b/lib/sites/fanConnection/readPaidSiteSubscription.ts @@ -1,8 +1,21 @@ +import { SiteError } from "../SiteError"; import { getActiveSubscriptions } from "@/lib/stripe/getActiveSubscriptions"; /** Fresh read using the existing paid-site rule; no per-instance fan-request cache. */ -export async function readPaidSiteSubscription(ownerId: string) { +export async function readPaidSiteSubscription( + ownerId: string, + options: { throwOnError?: boolean } = {}, +) { const eligible = (subscription: Awaited>[number]) => subscription.status === "active" && subscription.items.data.some(item => (item.price.unit_amount ?? 0) > 0); - return (await getActiveSubscriptions(ownerId, eligible)).some(eligible); + try { + const subscriptions = options.throwOnError + ? await getActiveSubscriptions(ownerId, eligible, { throwOnError: true }) + : await getActiveSubscriptions(ownerId, eligible); + return subscriptions.some(eligible); + } catch (error) { + if (options.throwOnError) + throw new SiteError(503, "Paid site entitlement temporarily unavailable"); + throw error; + } } diff --git a/lib/sites/production/publication/authorizeSelectedSitePublication.ts b/lib/sites/production/publication/authorizeSelectedSitePublication.ts index 9e3073635..f54db9d6f 100644 --- a/lib/sites/production/publication/authorizeSelectedSitePublication.ts +++ b/lib/sites/production/publication/authorizeSelectedSitePublication.ts @@ -25,10 +25,12 @@ export async function authorizeSelectedSitePublication( const organizations = await selectArtistOrganizationIds(site.artist_id); const belongs = organizations?.some(row => row.organization_id === site.owner_id) ?? false; const personalAccess = - site.owner_id === accountId && (await checkAccountArtistAccess(accountId, site.artist_id)); + !belongs && + site.owner_id === accountId && + (await checkAccountArtistAccess(accountId, site.artist_id)); if (!belongs && !personalAccess) throw new SiteError(403, "Artist not available in this workspace"); - if (!(await readPaidSiteSubscription(site.owner_id))) + if (!(await readPaidSiteSubscription(site.owner_id, { throwOnError: true }))) throw new SiteError(402, "Paid site entitlement unavailable"); getFanOAuthConfig(); const config = await selectFanConfig(site.id); diff --git a/lib/sites/production/publication/publishSelectedSiteEvidence.ts b/lib/sites/production/publication/publishSelectedSiteEvidence.ts index b0cfae02b..92afda72e 100644 --- a/lib/sites/production/publication/publishSelectedSiteEvidence.ts +++ b/lib/sites/production/publication/publishSelectedSiteEvidence.ts @@ -42,7 +42,7 @@ export async function publishSelectedSiteEvidence( ).id; } else evidenceId = input.evidence.evidenceId; const assess = async () => { - const record = sitePublishEvidenceSchema.parse( + const parsedRecord = sitePublishEvidenceSchema.safeParse( await selectSitePublishEvidence({ accountId: server.accountId, ownerId: selection.ownerId, @@ -50,6 +50,8 @@ export async function publishSelectedSiteEvidence( evidenceId, }), ); + if (!parsedRecord.success) throw new SiteError(503, "Stored evidence unavailable or invalid"); + const record = parsedRecord.data; if (record.kind !== input.evidence.kind) throw new SiteError(409, "Evidence kind does not match selected intent"); if (input.evidence.kind === "override") @@ -84,6 +86,7 @@ export async function publishSelectedSiteEvidence( evidenceId, candidateSha256: selection.candidateSha256, expectedPublishedEvidenceId: selection.expectedPublishedEvidenceId, + expectedArtistId: selection.artistId, }); return validateSitePublicationReceipt(result, selection, record); } diff --git a/lib/sites/production/publication/resolveSelectedSiteCandidate.ts b/lib/sites/production/publication/resolveSelectedSiteCandidate.ts index 739c7a21a..4ea72aafb 100644 --- a/lib/sites/production/publication/resolveSelectedSiteCandidate.ts +++ b/lib/sites/production/publication/resolveSelectedSiteCandidate.ts @@ -18,8 +18,8 @@ export async function resolveSelectedSiteCandidate( .uuid() .nullable() .safeParse((site as unknown as Record).published_evidence_id); + if (!pointer.success) throw new SiteError(503, "Publication pointer metadata unavailable"); if ( - !pointer.success || pointer.data !== selection.expectedPublishedEvidenceId || site.id !== selection.siteId || site.owner_id !== selection.ownerId || diff --git a/lib/sites/production/publication/selectedSitePublicationSchema.ts b/lib/sites/production/publication/selectedSitePublicationSchema.ts index 0f8eb33fc..277eb3ff7 100644 --- a/lib/sites/production/publication/selectedSitePublicationSchema.ts +++ b/lib/sites/production/publication/selectedSitePublicationSchema.ts @@ -1,20 +1,21 @@ import { z } from "zod"; import { returnUrlSchema } from "../../fanConnection/schema"; +const uuid = z.uuid().transform(value => value.toLowerCase()); export const selectedSitePublicationSchema = z .object({ selection: z .object({ - siteId: z.uuid(), - ownerId: z.uuid(), - artistId: z.uuid().nullable(), + siteId: uuid, + ownerId: uuid, + artistId: uuid.nullable(), revision: z.number().int().nonnegative().safe(), candidateSha256: z.string().regex(/^[a-f0-9]{64}$/), - expectedPublishedEvidenceId: z.uuid().nullable(), + expectedPublishedEvidenceId: uuid.nullable(), generationToken: z.string().min(1).max(3000).optional(), }) .strict(), evidence: z.discriminatedUnion("kind", [ - z.object({ kind: z.literal("review"), evidenceId: z.uuid() }).strict(), + z.object({ kind: z.literal("review"), evidenceId: uuid }).strict(), z .object({ kind: z.literal("override"), diff --git a/lib/stripe/__tests__/getActiveSubscriptions.test.ts b/lib/stripe/__tests__/getActiveSubscriptions.test.ts index e422ff24a..0857f99dc 100644 --- a/lib/stripe/__tests__/getActiveSubscriptions.test.ts +++ b/lib/stripe/__tests__/getActiveSubscriptions.test.ts @@ -81,3 +81,11 @@ describe("getActiveSubscriptions", () => { await expect(getActiveSubscriptions(ACC)).resolves.toEqual([]); }); }); + +it("propagates provider failure only when explicitly requested", async () => { + const failure = new Error("Stripe unavailable"); + list().mockRejectedValue(failure); + await expect(getActiveSubscriptions(ACC, () => true, { throwOnError: true })).rejects.toBe( + failure, + ); +}); diff --git a/lib/stripe/__tests__/getActiveSubscriptionsTestHelpers.ts b/lib/stripe/__tests__/getActiveSubscriptionsTestHelpers.ts index 08e11bb89..719ee7979 100644 --- a/lib/stripe/__tests__/getActiveSubscriptionsTestHelpers.ts +++ b/lib/stripe/__tests__/getActiveSubscriptionsTestHelpers.ts @@ -4,7 +4,7 @@ export function getActiveSubscriptionsTestHelpers() { const testAccountId = "acc-a"; function subscription(id: string, accountId: string): Stripe.Subscription { - return { id, metadata: { accountId } } as Stripe.Subscription; + return { id, metadata: { accountId } } as unknown as Stripe.Subscription; } function subscriptionListPage( diff --git a/lib/stripe/getActiveSubscriptions.ts b/lib/stripe/getActiveSubscriptions.ts index 06c1bb586..05dc97963 100644 --- a/lib/stripe/getActiveSubscriptions.ts +++ b/lib/stripe/getActiveSubscriptions.ts @@ -11,6 +11,7 @@ const PAGE_LIMIT = 100; export const getActiveSubscriptions = async ( accountId: string, eligible: (subscription: Stripe.Subscription) => boolean = () => true, + options: { throwOnError?: boolean } = {}, ) => { try { const now = Math.floor(Date.now() / 1000); @@ -48,6 +49,7 @@ export const getActiveSubscriptions = async ( return activeSubscriptions; } catch (error) { + if (options.throwOnError) throw error; console.error("Error fetching subscriptions:", error); return []; } diff --git a/lib/supabase/site_publish_evidence/__tests__/publicationRpc.test.ts b/lib/supabase/site_publish_evidence/__tests__/publicationRpc.test.ts index 0ac738da2..1332a298f 100644 --- a/lib/supabase/site_publish_evidence/__tests__/publicationRpc.test.ts +++ b/lib/supabase/site_publish_evidence/__tests__/publicationRpc.test.ts @@ -49,6 +49,7 @@ it.each([null, "pointer"])( evidenceId: "record", candidateSha256: "a".repeat(64), expectedPublishedEvidenceId, + expectedArtistId: "artist", }); expect(rpc).toHaveBeenCalledWith("publish_candidate", { p_actor: "actor", @@ -58,6 +59,7 @@ it.each([null, "pointer"])( p_record: "record", p_candidate_sha: "a".repeat(64), p_expected_pointer: expectedPublishedEvidenceId, + p_expected_artist_id: "artist", }); }, ); @@ -72,7 +74,25 @@ it("propagates publication conflicts without retries", async () => { evidenceId: "record", candidateSha256: "a".repeat(64), expectedPublishedEvidenceId: null, + expectedArtistId: null, }), ).rejects.toMatchObject({ status: 409 }); expect(rpc).toHaveBeenCalledOnce(); }); + +it("forwards an explicit null expected artist without omitting the SQL argument", async () => { + await publishSiteEvidenceCandidate({ + accountId: "actor", + ownerId: "owner", + siteId: "site", + revision: 8, + evidenceId: "record", + candidateSha256: "a".repeat(64), + expectedPublishedEvidenceId: null, + expectedArtistId: null, + }); + expect(rpc).toHaveBeenCalledWith( + "publish_candidate", + expect.objectContaining({ p_expected_artist_id: null }), + ); +}); diff --git a/lib/supabase/site_publish_evidence/buildSiteEvidenceRecordArgs.ts b/lib/supabase/site_publish_evidence/buildSiteEvidenceRecordArgs.ts new file mode 100644 index 000000000..0b97686cd --- /dev/null +++ b/lib/supabase/site_publish_evidence/buildSiteEvidenceRecordArgs.ts @@ -0,0 +1,25 @@ +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"; +/** One canonical candidate envelope shared by review and explicit-override capture. */ +export function buildSiteEvidenceRecordArgs(input: { + accountId: string; + ownerId: string; + siteId: string; + revision: number; + operationKey: string; + candidate: SiteSnapshot; +}) { + const content = getSitePublishContent(input.candidate); + return { + 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), + }; +} diff --git a/lib/supabase/site_publish_evidence/callSiteEvidenceRpc.ts b/lib/supabase/site_publish_evidence/callSiteEvidenceRpc.ts index 9485a82bb..223f3c62d 100644 --- a/lib/supabase/site_publish_evidence/callSiteEvidenceRpc.ts +++ b/lib/supabase/site_publish_evidence/callSiteEvidenceRpc.ts @@ -24,6 +24,7 @@ type Functions = { p_record: string; p_candidate_sha: string; p_expected_pointer: string | null; + p_expected_artist_id: string | null; }; Returns: unknown; }; diff --git a/lib/supabase/site_publish_evidence/insertSiteOverrideEvidence.ts b/lib/supabase/site_publish_evidence/insertSiteOverrideEvidence.ts index c9fb0f490..732e4cc9b 100644 --- a/lib/supabase/site_publish_evidence/insertSiteOverrideEvidence.ts +++ b/lib/supabase/site_publish_evidence/insertSiteOverrideEvidence.ts @@ -1,7 +1,5 @@ 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 { buildSiteEvidenceRecordArgs } from "./buildSiteEvidenceRecordArgs"; import type { SiteSnapshot } from "@/lib/sites/schema"; /** UNWIRED: only explicit selected intent after server resolution/authorization. */ export async function insertSiteOverrideEvidence(input: { @@ -14,16 +12,8 @@ export async function insertSiteOverrideEvidence(input: { intent: "publish-without-passed-review"; reason: string; }) { - 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), + ...buildSiteEvidenceRecordArgs(input), p_decision: { kind: "override", intent: input.intent, reason: input.reason }, p_review_canonical: null, }); diff --git a/lib/supabase/site_publish_evidence/insertSitePublishEvidence.ts b/lib/supabase/site_publish_evidence/insertSitePublishEvidence.ts index 5e2eec1e1..59b0a39f5 100644 --- a/lib/supabase/site_publish_evidence/insertSitePublishEvidence.ts +++ b/lib/supabase/site_publish_evidence/insertSitePublishEvidence.ts @@ -1,5 +1,5 @@ import { callSiteEvidenceRpc } from "./callSiteEvidenceRpc"; -import { getSitePublishContent } from "@/lib/sites/production/getSitePublishContent"; +import { buildSiteEvidenceRecordArgs } from "./buildSiteEvidenceRecordArgs"; import { hashSiteEvidence } from "@/lib/sites/production/hashSiteEvidence"; import { serializeSiteEvidence } from "@/lib/sites/production/serializeSiteEvidence"; import type { SiteSnapshot } from "@/lib/sites/schema"; @@ -13,16 +13,8 @@ export async function insertSitePublishEvidence(input: { 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), + ...buildSiteEvidenceRecordArgs(input), p_decision: { kind: "review", review: input.review, diff --git a/lib/supabase/site_publish_evidence/publishSiteEvidenceCandidate.ts b/lib/supabase/site_publish_evidence/publishSiteEvidenceCandidate.ts index c59e23c7f..7386bbf2d 100644 --- a/lib/supabase/site_publish_evidence/publishSiteEvidenceCandidate.ts +++ b/lib/supabase/site_publish_evidence/publishSiteEvidenceCandidate.ts @@ -8,6 +8,7 @@ export async function publishSiteEvidenceCandidate(input: { evidenceId: string; candidateSha256: string; expectedPublishedEvidenceId: string | null; + expectedArtistId: string | null; }) { return callSiteEvidenceRpc("publish_candidate", { p_actor: input.accountId, @@ -17,5 +18,6 @@ export async function publishSiteEvidenceCandidate(input: { p_record: input.evidenceId, p_candidate_sha: input.candidateSha256, p_expected_pointer: input.expectedPublishedEvidenceId, + p_expected_artist_id: input.expectedArtistId, }); } From 97b5d6a800ad2e77091d388911a1d2381b65a932 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:38:19 -0500 Subject: [PATCH 3/3] Preserve entitlement failure diagnostics and align proposal references --- docs/site-evidence-adapters.md | 12 +++++++++--- docs/site-selected-publication.md | 6 ++++-- .../__tests__/readPaidSiteSubscription.test.ts | 6 +++++- lib/sites/fanConnection/readPaidSiteSubscription.ts | 12 +++++------- 4 files changed, 23 insertions(+), 13 deletions(-) diff --git a/docs/site-evidence-adapters.md b/docs/site-evidence-adapters.md index c5d9bf545..104d7e0d0 100644 --- a/docs/site-evidence-adapters.md +++ b/docs/site-evidence-adapters.md @@ -1,8 +1,14 @@ # 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; +These helpers target **proposal-only Database PR136**, current commit +`afd214aa73dfd70b0f2b860fce90c12ceb23f28b` (`proposals/sites-publish-evidence-2094/`). +The original capture/read qualification used `4caac3cc8a15a47b348109b2fa4f571423d8beb0`. +Its successor adds the expected-artist publication fence without changing capture/read +contracts or golden vectors. The separate [unwired publication orchestration](./site-selected-publication.md) +now consumes the scoped reader; no route, workflow or UI invokes the new flow. +The coverage and publication-wrapper exclusions below describe the #1263 +capture/read contribution specifically; the linked orchestration page owns the +subsequent publisher, artist fence and their qualification. 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. diff --git a/docs/site-selected-publication.md b/docs/site-selected-publication.md index 847b5dc38..6c30cd0cb 100644 --- a/docs/site-selected-publication.md +++ b/docs/site-selected-publication.md @@ -1,7 +1,9 @@ # Unwired exact-selected Sites publication -This source extends the evidence adapters from API #1263. It targets the unchanged -**Database #136 proposal**, commit `afd214aa73dfd70b0f2b860fce90c12ceb23f28b`. +This source extends the evidence adapters from API #1263. It targets the revised +**Database #136 proposal**, commit `afd214aa73dfd70b0f2b860fce90c12ceb23f28b`, +which extends `4caac3cc8a15a47b348109b2fa4f571423d8beb0` with the expected-artist +publication fence. Capture/read contracts remain compatible. There is no route, UI, MCP or workflow caller. Existing `processSiteOperation` publishing remains advisory and unchanged. No migration, schema exposure, runtime grant, retention activation or publication gate is introduced. diff --git a/lib/sites/fanConnection/__tests__/readPaidSiteSubscription.test.ts b/lib/sites/fanConnection/__tests__/readPaidSiteSubscription.test.ts index d9e73bd23..ae5ebf565 100644 --- a/lib/sites/fanConnection/__tests__/readPaidSiteSubscription.test.ts +++ b/lib/sites/fanConnection/__tests__/readPaidSiteSubscription.test.ts @@ -17,10 +17,14 @@ it("preserves existing fan cache while fresh publication reads observe revocatio }); it("distinguishes publication entitlement read failures from unpaid results", async () => { - vi.mocked(getActiveSubscriptions).mockRejectedValue(new Error("Stripe unavailable")); + const failure = new Error("Stripe unavailable"); + const logged = vi.spyOn(console, "error").mockImplementation(() => {}); + vi.mocked(getActiveSubscriptions).mockRejectedValue(failure); await expect(readPaidSiteSubscription("owner", { throwOnError: true })).rejects.toMatchObject({ status: 503, }); + expect(logged).toHaveBeenCalledWith("Error checking paid site entitlement:", failure); + logged.mockRestore(); expect(getActiveSubscriptions).toHaveBeenLastCalledWith("owner", expect.any(Function), { throwOnError: true, }); diff --git a/lib/sites/fanConnection/readPaidSiteSubscription.ts b/lib/sites/fanConnection/readPaidSiteSubscription.ts index 524fcbad6..205c7fe6f 100644 --- a/lib/sites/fanConnection/readPaidSiteSubscription.ts +++ b/lib/sites/fanConnection/readPaidSiteSubscription.ts @@ -8,14 +8,12 @@ export async function readPaidSiteSubscription( const eligible = (subscription: Awaited>[number]) => subscription.status === "active" && subscription.items.data.some(item => (item.price.unit_amount ?? 0) > 0); + if (!options.throwOnError) + return (await getActiveSubscriptions(ownerId, eligible)).some(eligible); try { - const subscriptions = options.throwOnError - ? await getActiveSubscriptions(ownerId, eligible, { throwOnError: true }) - : await getActiveSubscriptions(ownerId, eligible); - return subscriptions.some(eligible); + return (await getActiveSubscriptions(ownerId, eligible, { throwOnError: true })).some(eligible); } catch (error) { - if (options.throwOnError) - throw new SiteError(503, "Paid site entitlement temporarily unavailable"); - throw error; + console.error("Error checking paid site entitlement:", error); + throw new SiteError(503, "Paid site entitlement temporarily unavailable"); } }