From f7e7bf4ee10c2674278e43a430cdba73780533bd Mon Sep 17 00:00:00 2001 From: bchanot Date: Wed, 4 Nov 2026 11:57:22 +0100 Subject: [PATCH] feat(supabase): sheet drawing register, upload, confirm accessors and save answer --- packages/supabase/src/index.ts | 6 + packages/supabase/src/sheets.ts | 88 +++++++++++++ .../sandbox/sheet-editor-assets.sandbox.ts | 121 ++++++++++++++++++ packages/supabase/tests/sheet-assets.test.ts | 119 +++++++++++++++++ 4 files changed, 334 insertions(+) create mode 100644 packages/supabase/tests/sandbox/sheet-editor-assets.sandbox.ts create mode 100644 packages/supabase/tests/sheet-assets.test.ts diff --git a/packages/supabase/src/index.ts b/packages/supabase/src/index.ts index e79509ce..ea8fc160 100644 --- a/packages/supabase/src/index.ts +++ b/packages/supabase/src/index.ts @@ -69,6 +69,12 @@ export { getOfficialSheetAdmin, listSheetVersions, downloadSheetDrawing, + registerSheetAsset, + listSheetAssets, + uploadSheetDrawing, + confirmSheetAssetUpload, + parseSaveAnswer, + type SheetAssetRow, listOwnCatalogGrants, type CatalogAccount, type CatalogGrant, diff --git a/packages/supabase/src/sheets.ts b/packages/supabase/src/sheets.ts index f88a9965..dbc8d850 100644 --- a/packages/supabase/src/sheets.ts +++ b/packages/supabase/src/sheets.ts @@ -93,6 +93,7 @@ export const SHEET_FAILURE_KINDS = [ // uploads and working copy 'upload_missing', 'size_mismatch', + 'upload.pending_other', 'asset.referenced', 'working_copy.source_invalid', 'working_copy.exists', @@ -257,6 +258,13 @@ export async function saveSheetDraft( return data } +/** The save answer `{ revision }` (M5): a positive integer, else `unavailable`. */ +export function parseSaveAnswer(value: unknown): { revision: number } { + const answer = z.object({ revision: z.number().int().positive() }).safeParse(value) + if (!answer.success) throw new SheetFailure('unavailable', answer.error) + return { revision: answer.data.revision } +} + export async function submitSheetReview( client: FaunosteoClient, args: { version_id: string; expected_revision: number; note?: string }, @@ -532,6 +540,7 @@ const DRAWING_BUCKET = 'anatomical-sheet-assets' interface StorageLikeError { name?: string status?: number + statusCode?: string code?: string } @@ -563,3 +572,82 @@ export async function downloadSheetDrawing( if (error || !data) throw new SheetFailure(classifyDrawingError(error), error) return new Uint8Array(await data.arrayBuffer()) } + +// --- Drawing upload (editor, aal2; §9.2-§9.3) -------------------------------- +/** Registers a drawing of a sheet; the row of the same hash is returned when it exists. */ +export async function registerSheetAsset( + client: FaunosteoClient, + args: { sheet_id: string; sha256: string; byte_size: number; file_name: string }, +): Promise { + const { data, error, status } = await client.rpc('register_sheet_asset', args) + if (error) failSheet(error, status) + return data +} + +export interface SheetAssetRow { + id: string + sha256: string + byte_size: number + uploaded_at: string | null +} + +/** The drawing rows of a sheet the caller can see; `uploaded_at` null is a pending row. */ +export async function listSheetAssets( + client: FaunosteoClient, + sheetId: string, +): Promise { + if (!UUID_PATTERN.test(sheetId)) throw new SheetFailure('not_found') + const { data, error, status } = await client + .from('anatomical_sheet_assets') + .select('id, sha256, byte_size, uploaded_at') + .eq('sheet_id', sheetId) + if (error) failSheet(error, status) + return data ?? [] +} + +/** The Storage code of a refusal: HTTP status, or body `statusCode` behind an HTTP 400 (LRN-113). */ +function storageCode(error: StorageLikeError): string { + const bodyCode = error.status === 400 ? error.statusCode : undefined + return bodyCode ?? String(error.status) +} + +/** + * Uploads `.svg` without upsert. `present`: the object is already + * there (409). A policy refusal (403: a pending row of another account) is + * `upload.pending_other`; the caller then confirms once. The bytes are the + * core's `stored`; no check here. + */ +export async function uploadSheetDrawing( + client: FaunosteoClient, + sha256: string, + bytes: Uint8Array, +): Promise<'uploaded' | 'present'> { + if (!SHA256_PATTERN.test(sha256)) throw new SheetFailure('invalid_input') + const { error } = await client.storage + .from(DRAWING_BUCKET) + .upload(`${sha256}.svg`, bytes, { contentType: 'image/svg+xml', upsert: false }) + if (!error) return 'uploaded' + const code = storageCode(error) + if (code === '409') return 'present' + if (code === '403') throw new SheetFailure('upload.pending_other', error) + throw new SheetFailure(classifyUploadError(error), error) +} + +function classifyUploadError(error: StorageLikeError): SheetFailureKind { + if (error.name === 'StorageUnknownError') return 'network' + if (error.code === 'InvalidJWT' || error.status === 401) return 'session_expired' + if (error.status === 429) return 'rate_limited' + return 'unavailable' +} + +/** Confirms the upload of a registered drawing (`upload_missing`, `size_mismatch`). */ +export async function confirmSheetAssetUpload( + client: FaunosteoClient, + assetId: string, +): Promise { + const { data, error, status } = await client.rpc('confirm_sheet_asset_upload', { + asset_id: assetId, + }) + if (error) failSheet(error, status) + return data +} diff --git a/packages/supabase/tests/sandbox/sheet-editor-assets.sandbox.ts b/packages/supabase/tests/sandbox/sheet-editor-assets.sandbox.ts new file mode 100644 index 00000000..f06fae71 --- /dev/null +++ b/packages/supabase/tests/sandbox/sheet-editor-assets.sandbox.ts @@ -0,0 +1,121 @@ +/** + * The V1-2.6 drawing accessors through real supabase-js against the throwaway + * stack: register, list, upload, confirm, the confirmed hash registered again + * (nothing to upload), and a second editor meeting a pending row of the first + * (`upload.pending_other`, then `upload_missing` on its confirm). Bytes are + * unique per run, so it runs again on the same stack. Run through + * `pnpm db:sandbox test tests/sandbox/sheet-editor-assets.sandbox.ts`. + */ +import { randomUUID } from 'node:crypto' +import { createClient } from '@supabase/supabase-js' +import { + SheetFailure, + confirmSheetAssetUpload, + createOfficialSheet, + enrollTotp, + listSheetAssets, + registerSheetAsset, + uploadSheetDrawing, + verifyTotp, + type Database, + type FaunosteoClient, +} from '../../src' +import { PASSWORD, confirmedAccount, sql, stack, type Account } from './stack' +import { drawing, sha256, sheetDoc } from './sheet-fixtures' +import { totpCode } from './totp' + +const BASE = 'http://sandbox.faunosteo.invalid' + +/** The browser client of the app, its requests replayed on the sandbox ports. */ +async function editorClient(account: Account): Promise { + const mapped: typeof fetch = (input, init) => { + const url = String(input instanceof Request ? input.url : input) + .replace(`${BASE}/auth/v1`, stack.authUrl) + .replace(`${BASE}/rest/v1`, stack.restUrl) + .replace(`${BASE}/storage/v1`, stack.storageUrl) + return fetch(url, init) + } + const client = createClient(BASE, stack.anonKey, { + auth: { persistSession: false, autoRefreshToken: false }, + global: { fetch: mapped }, + }) + const { error } = await client.auth.signInWithPassword({ email: account.email, password: PASSWORD }) + if (error) throw error + const enrolment = await enrollTotp(client, 'device') + await verifyTotp(client, enrolment.factorId, totpCode(enrolment.secret)) + return client +} + +const created: string[] = [] + +async function editor(tag: string): Promise { + const a = await confirmedAccount(tag) + created.push(a.id) + await sql(`select private.assign_platform_role(null, '${a.id}', 'admin')`) + await sql(`insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by) + values ('${a.id}', 'sheet_editor', 'sandbox', 'sandbox', '${a.id}')`) + return editorClient(a) +} + +async function kindOf(promise: Promise) { + try { + await promise + return 'no failure' + } catch (error) { + return error instanceof SheetFailure ? error.kind : `other: ${String(error)}` + } +} + +afterAll(async () => { + if (created.length === 0) return + const ids = created.map((id) => `'${id}'`).join(', ') + await sql(`begin; + set local session_replication_role = replica; + delete from public.anatomical_catalog_grants where user_id in (${ids}); + set local session_replication_role = origin; + delete from auth.users where id in (${ids}); + commit;`) +}) + +describe('drawing accessors on real Storage and PostgREST', () => { + let first: FaunosteoClient + let second: FaunosteoClient + let sheetId: string + + beforeAll(async () => { + first = await editor('assets-first') + second = await editor('assets-second') + sheetId = await createOfficialSheet(first, `sb-${randomUUID().slice(0, 12)}`, sheetDoc(null) as never) + }) + + const register = (client: FaunosteoClient, bytes: Buffer) => + registerSheetAsset(client, { sheet_id: sheetId, sha256: sha256(bytes), byte_size: bytes.length, file_name: 'd.svg' }) + + it('registers, uploads, confirms, then finds the confirmed hash without uploading', async () => { + const bytes = drawing() + const id = await register(first, bytes) + expect(await listSheetAssets(first, sheetId)).toContainEqual({ + id, sha256: sha256(bytes), byte_size: bytes.length, uploaded_at: null, + }) + expect(await uploadSheetDrawing(first, sha256(bytes), new Uint8Array(bytes))).toBe('uploaded') + expect(await uploadSheetDrawing(first, sha256(bytes), new Uint8Array(bytes))).toBe('present') + expect(await confirmSheetAssetUpload(first, id)).toBe(id) + const row = (await listSheetAssets(first, sheetId)).find((r) => r.id === id) + expect(row?.uploaded_at).toEqual(expect.any(String)) + + expect(await register(first, bytes)).toBe(id) + expect((await listSheetAssets(first, sheetId)).find((r) => r.id === id)?.uploaded_at).toBe(row?.uploaded_at) + }) + + it('refuses a second editor on a pending row of the first, with its own statusCode', async () => { + const bytes = drawing() + const id = await register(first, bytes) + expect(await register(second, bytes)).toBe(id) + expect(await kindOf(uploadSheetDrawing(second, sha256(bytes), new Uint8Array(bytes)))) + .toBe('upload.pending_other') + const refusal = await uploadSheetDrawing(second, sha256(bytes), new Uint8Array(bytes)).catch((e) => e) + const cause = refusal.cause as { status?: number; statusCode?: string } + expect({ status: cause.status, statusCode: cause.statusCode }).toEqual({ status: 400, statusCode: '403' }) + expect(await kindOf(confirmSheetAssetUpload(second, id))).toBe('upload_missing') + }) +}) diff --git a/packages/supabase/tests/sheet-assets.test.ts b/packages/supabase/tests/sheet-assets.test.ts new file mode 100644 index 00000000..fc295d54 --- /dev/null +++ b/packages/supabase/tests/sheet-assets.test.ts @@ -0,0 +1,119 @@ +import { + SheetFailure, + confirmSheetAssetUpload, + listSheetAssets, + parseSaveAnswer, + registerSheetAsset, + uploadSheetDrawing, + type FaunosteoClient, +} from '../src' + +/** + * Call shapes and failure folding of the drawing accessors (V1-2.6 Lot B). The + * same functions run against real Storage and PostgREST in + * tests/sandbox/sheet-editor-assets.sandbox.ts. + */ +const SHEET = '22222222-2222-4222-8222-222222222222' +const SHA = 'b'.repeat(64) + +function stub(answers: { rpc?: unknown; rows?: unknown; upload?: unknown } = {}) { + const calls: unknown[][] = [] + const settle = (error: unknown, data: unknown = null) => ({ data, error: error ?? null, status: error ? 400 : 200 }) + const chain = { select: () => chain, eq: () => chain, then: (r: (v: unknown) => unknown) => r(settle(null, answers.rows ?? [])) } + const client = { + from: (table: string) => (calls.push(['from', table]), chain), + rpc: async (name: string, args: unknown) => (calls.push([name, args]), settle(answers.rpc, 'id-1')), + storage: { + from: (bucket: string) => ({ + upload: async (path: string, body: unknown, options: unknown) => ( + calls.push(['upload', bucket, path, body, options]), { data: null, error: answers.upload ?? null } + ), + }), + }, + } as unknown as FaunosteoClient + return { client, calls } +} + +async function kindOf(promise: Promise) { + try { + await promise + return 'no failure' + } catch (error) { + return error instanceof SheetFailure ? error.kind : `other: ${String(error)}` + } +} + +describe('uploadSheetDrawing', () => { + const bytes = new Uint8Array([1, 2, 3]) + const failing = (error: unknown) => stub({ upload: error }).client + + it('uploads .svg as image/svg+xml, never upserting', async () => { + const { client, calls } = stub() + expect(await uploadSheetDrawing(client, SHA, bytes)).toBe('uploaded') + expect(calls).toEqual([ + ['upload', 'anatomical-sheet-assets', `${SHA}.svg`, bytes, { contentType: 'image/svg+xml', upsert: false }], + ]) + }) + + it('reads an existing object on HTTP 409 or HTTP 400 with body statusCode "409"', async () => { + for (const error of [ + { name: 'StorageApiError', status: 409, statusCode: '409' }, + { name: 'StorageApiError', status: 400, statusCode: '409' }, + ]) + expect(await uploadSheetDrawing(failing(error), SHA, bytes)).toBe('present') + }) + + it('reads a policy refusal on HTTP 403 or HTTP 400 with body statusCode "403"', async () => { + for (const error of [ + { name: 'StorageApiError', status: 403, statusCode: '403' }, + { name: 'StorageApiError', status: 400, statusCode: '403' }, + ]) + expect(await kindOf(uploadSheetDrawing(failing(error), SHA, bytes))).toBe('upload.pending_other') + }) + + it('keeps any other refusal apart and a bad hash out of the network', async () => { + const kind = (error: unknown) => kindOf(uploadSheetDrawing(failing(error), SHA, bytes)) + expect(await kind({ name: 'StorageApiError', status: 400, statusCode: '404' })).toBe('unavailable') + expect(await kind({ name: 'StorageApiError', status: 401 })).toBe('session_expired') + expect(await kind({ name: 'StorageApiError', status: 429 })).toBe('rate_limited') + expect(await kind({ name: 'StorageUnknownError' })).toBe('network') + const { client, calls } = stub() + expect(await kindOf(uploadSheetDrawing(client, 'xyz', bytes))).toBe('invalid_input') + expect(calls).toEqual([]) + }) +}) + +describe('register, list, confirm', () => { + it('registers with the RPC arguments and answers the asset id', async () => { + const { client, calls } = stub() + const args = { sheet_id: SHEET, sha256: SHA, byte_size: 12, file_name: 'd.svg' } + expect(await registerSheetAsset(client, args)).toBe('id-1') + expect(calls).toEqual([['register_sheet_asset', args]]) + }) + + it('folds server kinds through the existing reader', async () => { + const refused = stub({ rpc: { code: 'P0001', message: 'upload_missing' } }).client + expect(await kindOf(confirmSheetAssetUpload(refused, SHEET))).toBe('upload_missing') + expect(await kindOf(registerSheetAsset(stub({ rpc: { code: '42501', message: 'rights.capability' } }).client, + { sheet_id: SHEET, sha256: SHA, byte_size: 1, file_name: 'd.svg' }))).toBe('rights.capability') + }) + + it('lists the rows of a sheet and refuses a malformed id', async () => { + const rows = [{ id: 'a', sha256: SHA, byte_size: 3, uploaded_at: null }] + const { client, calls } = stub({ rows }) + expect(await listSheetAssets(client, SHEET)).toEqual(rows) + expect(calls).toEqual([['from', 'anatomical_sheet_assets']]) + expect(await kindOf(listSheetAssets(client, 'nope'))).toBe('not_found') + }) +}) + +describe('parseSaveAnswer', () => { + it('reads a positive integer revision', () => { + expect(parseSaveAnswer({ revision: 4 })).toEqual({ revision: 4 }) + }) + + it('answers unavailable for anything else', () => { + for (const value of [null, 4, {}, { revision: 0 }, { revision: -1 }, { revision: 1.5 }, { revision: '2' }]) + expect(() => parseSaveAnswer(value)).toThrow(expect.objectContaining({ kind: 'unavailable' })) + }) +})