Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions docs/site-evidence-adapters.md
Original file line number Diff line number Diff line change
@@ -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.

Expand Down
122 changes: 122 additions & 0 deletions docs/site-selected-publication.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# Unwired exact-selected Sites publication

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.

## 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 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
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/expected artist; 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 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.

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,
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. 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.

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.

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.
113 changes: 113 additions & 0 deletions lib/sites/__tests__/publicationAuthority.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
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", { throwOnError: true });
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");
});

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();
});
Loading
Loading