feat(supabase): sheet drawing register, upload, confirm accessors and save answer

This commit is contained in:
bchanot committed 2026-11-04 11:57:22 +01:00
1 parent cfd49c7b5b
commit f7e7bf4ee1
4 files changed
+334

No files matched your search

@@ -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<FaunosteoClient> {
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<Database>(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<FaunosteoClient> {
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<unknown>) {
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')
})
})
@@ -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<unknown>) {
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 <sha256>.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' }))
})
})