feat(supabase): MFA, species, rights, admin and catalogue access layer (V1-2.5 D)
mfa.ts (closed kinds, TOTP list incl. unverified, enrol, verify, unenrol, assurance); sheets.ts wrappers for species, working copy, account lookup, M7 reads, versions list, drawing download, own grants, with shape parsers. Unit 148, sandbox sheets-admin 5/5 x2.
This commit is contained in:
1 parent
a79e1f0af7
commit
c9ace9aff2
7 files changed
+1126
-6
No files matched your search
@@ -58,8 +58,45 @@ export {
|
||||
publishSheetVersion,
|
||||
getSheetVersion,
|
||||
listOfficialCatalog,
|
||||
lookupCatalogAccount,
|
||||
listCatalogSpecies,
|
||||
createSpecies,
|
||||
updateInactiveSpecies,
|
||||
activateSpecies,
|
||||
renameSpecies,
|
||||
createSheetWorkingCopy,
|
||||
listOfficialSheetsAdmin,
|
||||
getOfficialSheetAdmin,
|
||||
listSheetVersions,
|
||||
downloadSheetDrawing,
|
||||
listOwnCatalogGrants,
|
||||
type CatalogAccount,
|
||||
type CatalogGrant,
|
||||
type CatalogSpecies,
|
||||
type CatalogVersionItem,
|
||||
type OfficialSheetAdmin,
|
||||
type OfficialSheetAdminSummary,
|
||||
type OwnCatalogGrant,
|
||||
type SheetAdminPerson,
|
||||
type SheetAdminRound,
|
||||
type SheetAdminVersion,
|
||||
type SheetFailureKind,
|
||||
} from './sheets'
|
||||
export {
|
||||
MFA_FAILURE_KINDS,
|
||||
MfaFailure,
|
||||
classifyMfaError,
|
||||
listTotpFactors,
|
||||
enrollTotp,
|
||||
verifyTotp,
|
||||
unenrollFactor,
|
||||
assuranceLevel,
|
||||
type AssuranceLevel,
|
||||
type AssuranceState,
|
||||
type MfaFailureKind,
|
||||
type TotpEnrolment,
|
||||
type TotpFactor,
|
||||
} from './mfa'
|
||||
export {
|
||||
ASSET_FAILURE_KINDS,
|
||||
ASSET_OWNER_COLUMNS,
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
import type { FaunosteoClient } from './client'
|
||||
|
||||
/**
|
||||
* TOTP factors of the signed-in account (V1-2.5, contract
|
||||
* docs/development/V1-2_ANATOMICAL_SHEETS.md §5.6, §5.7): list, enrol,
|
||||
* challenge and verify, remove, and the session's assurance level. GoTrue is
|
||||
* the only authority: its `aal2` requirements (a second factor or the removal
|
||||
* of a verified one from `aal1`, docs/development/IDENTITY.md §4.1) come back
|
||||
* as the closed kind `aal2_required`, never worked around here. Every GoTrue
|
||||
* answer is folded into one kind the UI phrases (`mfa.failure.<kind>`); the
|
||||
* raw message never reaches the screen.
|
||||
*/
|
||||
|
||||
export const MFA_FAILURE_KINDS = [
|
||||
'aal2_required',
|
||||
'invalid_code',
|
||||
'factor_not_found',
|
||||
'challenge_expired',
|
||||
'too_many_factors',
|
||||
'name_taken',
|
||||
'rate_limited',
|
||||
'session_expired',
|
||||
'network',
|
||||
'unavailable',
|
||||
] as const
|
||||
export type MfaFailureKind = (typeof MFA_FAILURE_KINDS)[number]
|
||||
|
||||
export class MfaFailure extends Error {
|
||||
readonly kind: MfaFailureKind
|
||||
constructor(kind: MfaFailureKind, cause?: unknown) {
|
||||
super(`mfa: ${kind}`, { cause })
|
||||
this.name = 'MfaFailure'
|
||||
this.kind = kind
|
||||
}
|
||||
}
|
||||
|
||||
/** GoTrue v2.197.0 error codes (auth-js `ErrorCode`) and their kinds. */
|
||||
const CODE_TO_KIND: Record<string, MfaFailureKind> = {
|
||||
insufficient_aal: 'aal2_required',
|
||||
mfa_verification_failed: 'invalid_code',
|
||||
mfa_verification_rejected: 'invalid_code',
|
||||
mfa_factor_not_found: 'factor_not_found',
|
||||
mfa_challenge_expired: 'challenge_expired',
|
||||
// The challenge was made from another address: a new one is needed.
|
||||
mfa_ip_address_mismatch: 'challenge_expired',
|
||||
too_many_enrolled_mfa_factors: 'too_many_factors',
|
||||
mfa_factor_name_conflict: 'name_taken',
|
||||
over_request_rate_limit: 'rate_limited',
|
||||
session_not_found: 'session_expired',
|
||||
session_expired: 'session_expired',
|
||||
refresh_token_not_found: 'session_expired',
|
||||
refresh_token_already_used: 'session_expired',
|
||||
bad_jwt: 'session_expired',
|
||||
no_authorization: 'session_expired',
|
||||
}
|
||||
|
||||
interface AuthLikeError {
|
||||
name?: string
|
||||
code?: string
|
||||
status?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a GoTrue answer to a closed kind: code first, then the client's own
|
||||
* error classes and the HTTP status. Fails closed to `unavailable` (TOTP
|
||||
* disabled on the server, an unexpected code).
|
||||
*/
|
||||
export function classifyMfaError(error: unknown): MfaFailureKind {
|
||||
if (error instanceof MfaFailure) return error.kind
|
||||
if (error instanceof TypeError) return 'network'
|
||||
const e = (error ?? {}) as AuthLikeError
|
||||
if (e.code && CODE_TO_KIND[e.code]) return CODE_TO_KIND[e.code]
|
||||
if (e.name === 'AuthSessionMissingError') return 'session_expired'
|
||||
if (e.name === 'AuthRetryableFetchError') return 'network'
|
||||
if (e.status === 429) return 'rate_limited'
|
||||
return 'unavailable'
|
||||
}
|
||||
|
||||
function fail(error: unknown): never {
|
||||
throw new MfaFailure(classifyMfaError(error), error)
|
||||
}
|
||||
|
||||
export interface TotpFactor {
|
||||
id: string
|
||||
friendlyName: string | null
|
||||
status: 'verified' | 'unverified'
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Every TOTP factor of the account, unverified ones included. supabase-js
|
||||
* `listFactors` keeps only verified factors in its `totp` list; its `all`
|
||||
* list is the user's `factors` from `getUser()` (a request to GoTrue, so the
|
||||
* list is current), which is what is read here.
|
||||
*/
|
||||
export async function listTotpFactors(
|
||||
client: FaunosteoClient,
|
||||
): Promise<TotpFactor[]> {
|
||||
const { data, error } = await client.auth.mfa.listFactors()
|
||||
if (error) fail(error)
|
||||
return data.all
|
||||
.filter((factor) => factor.factor_type === 'totp')
|
||||
.map((factor) => ({
|
||||
id: factor.id,
|
||||
friendlyName: factor.friendly_name || null,
|
||||
status: factor.status === 'verified' ? 'verified' : 'unverified',
|
||||
createdAt: factor.created_at,
|
||||
}))
|
||||
}
|
||||
|
||||
export interface TotpEnrolment {
|
||||
factorId: string
|
||||
/** The QR code as an SVG data URI (`data:image/svg+xml;utf-8,…`), as supabase-js builds it. */
|
||||
qrCode: string
|
||||
/**
|
||||
* The shared secret, shown once beside the QR code. Never stored, logged
|
||||
* or sent anywhere by the app: GoTrue keeps it, the user's authenticator
|
||||
* holds it, and it is gone when the enrolment screen closes.
|
||||
*/
|
||||
secret: string
|
||||
/** The otpauth:// URI the QR code encodes; same secrecy as `secret`. */
|
||||
uri: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A new, unverified TOTP factor. From `aal1` GoTrue allows it only while the
|
||||
* account has no verified factor (`aal2_required` otherwise).
|
||||
*/
|
||||
export async function enrollTotp(
|
||||
client: FaunosteoClient,
|
||||
friendlyName: string,
|
||||
): Promise<TotpEnrolment> {
|
||||
const { data, error } = await client.auth.mfa.enroll({
|
||||
factorType: 'totp',
|
||||
friendlyName,
|
||||
})
|
||||
if (error) fail(error)
|
||||
return {
|
||||
factorId: data.id,
|
||||
qrCode: data.totp.qr_code,
|
||||
secret: data.totp.secret,
|
||||
uri: data.totp.uri,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Challenges the factor and verifies the code in one step. On success the
|
||||
* client's session is upgraded to `aal2` (GoTrue drops the account's other
|
||||
* `aal1` sessions, IDENTITY.md §4.1).
|
||||
*/
|
||||
export async function verifyTotp(
|
||||
client: FaunosteoClient,
|
||||
factorId: string,
|
||||
code: string,
|
||||
): Promise<void> {
|
||||
const { error } = await client.auth.mfa.challengeAndVerify({ factorId, code })
|
||||
if (error) fail(error)
|
||||
}
|
||||
|
||||
/** Removes a factor; a verified one needs an `aal2` session (`aal2_required`). */
|
||||
export async function unenrollFactor(
|
||||
client: FaunosteoClient,
|
||||
factorId: string,
|
||||
): Promise<void> {
|
||||
const { error } = await client.auth.mfa.unenroll({ factorId })
|
||||
if (error) fail(error)
|
||||
}
|
||||
|
||||
export type AssuranceLevel = 'aal1' | 'aal2'
|
||||
|
||||
export interface AssuranceState {
|
||||
/** The level of the current access token; null without a session. */
|
||||
current: AssuranceLevel | null
|
||||
/** `aal2` once the account holds a verified factor (from the session's user, no request). */
|
||||
next: AssuranceLevel | null
|
||||
}
|
||||
|
||||
/** The session's assurance level. A hint for the screens: the server checks the token itself. */
|
||||
export async function assuranceLevel(
|
||||
client: FaunosteoClient,
|
||||
): Promise<AssuranceState> {
|
||||
const { data, error } = await client.auth.mfa.getAuthenticatorAssuranceLevel()
|
||||
if (error) fail(error)
|
||||
const level = (value: string | null): AssuranceLevel | null =>
|
||||
value === 'aal1' || value === 'aal2' ? value : null
|
||||
return { current: level(data.currentLevel), next: level(data.nextLevel) }
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { z } from 'zod'
|
||||
import type { FaunosteoClient } from './client'
|
||||
import type { Json } from './database.types'
|
||||
import { Constants, type Enums, type Json } from './database.types'
|
||||
import { UUID_PATTERN } from './records'
|
||||
|
||||
/**
|
||||
* Access layer for the official anatomical-sheet workflow (V1-2.1, M4/M5):
|
||||
@@ -12,8 +14,10 @@ import type { Json } from './database.types'
|
||||
* decide; the former client publication gate is gone (publication takes a
|
||||
* review id only).
|
||||
*
|
||||
* The screens that call these wrappers arrive in V1-2.5 onward; V1-2.1 ships
|
||||
* the access layer and its types only.
|
||||
* V1-2.1 shipped the workflow wrappers; V1-2.5 adds the administration reads
|
||||
* (M7), species, working copy, account lookup and the catalogue reads, with
|
||||
* shallow parsers of the JSON answers: a shape outside the contract is
|
||||
* `unavailable`, the business rules stay the server's.
|
||||
*/
|
||||
|
||||
/** Every closed failure the sheet RPCs raise (contract §6.5, §6.7, §5.2, §5.7). */
|
||||
@@ -141,6 +145,19 @@ export function failSheet(error: unknown, status?: number): never {
|
||||
throw new SheetFailure(classifySheetError(error, status), error)
|
||||
}
|
||||
|
||||
/** The RPC answer checked against its contract; a different shape is `unavailable`. */
|
||||
function parseSheetAnswer<T>(schema: z.ZodType<T>, data: unknown): T {
|
||||
const result = schema.safeParse(data)
|
||||
if (!result.success) throw new SheetFailure('unavailable', result.error)
|
||||
return result.data
|
||||
}
|
||||
|
||||
const { Enums: E } = Constants.public
|
||||
const LocalizedSchema = z.object({ fr: z.string(), en: z.string() })
|
||||
/** An account as the admin answers name it (M7 `sheet_admin_person`). */
|
||||
const PersonSchema = z.object({ user_id: z.string(), display_name: z.string().nullable() })
|
||||
export type SheetAdminPerson = z.infer<typeof PersonSchema>
|
||||
|
||||
// --- Rights (owner, aal2) --------------------------------------------------
|
||||
export async function grantCatalogRight(
|
||||
client: FaunosteoClient,
|
||||
@@ -170,12 +187,56 @@ export async function revokeCatalogRight(
|
||||
return data
|
||||
}
|
||||
|
||||
export async function listCatalogGrants(client: FaunosteoClient): Promise<Json> {
|
||||
const CatalogGrantSchema = z.object({
|
||||
id: z.string(),
|
||||
user_id: z.string(),
|
||||
display_name: z.string().nullable(),
|
||||
email: z.string().nullable(),
|
||||
kind: z.enum(E.catalog_grant_kind),
|
||||
reason: z.string(),
|
||||
verification_note: z.string().nullable(),
|
||||
granted_by: z.string(),
|
||||
granted_by_name: z.string().nullable(),
|
||||
granted_at: z.string(),
|
||||
expires_at: z.string().nullable(),
|
||||
revoked_at: z.string().nullable(),
|
||||
revoked_by: z.string().nullable(),
|
||||
revocation_reason: z.string().nullable(),
|
||||
/** `expiring`: within 30 days (server clock). */
|
||||
state: z.enum(['active', 'expiring', 'expired', 'revoked']),
|
||||
/** The right is in force now (grant_active: account confirmed and active, factor where needed). */
|
||||
effective: z.boolean(),
|
||||
})
|
||||
export type CatalogGrant = z.infer<typeof CatalogGrantSchema>
|
||||
|
||||
/** Every grant with its holder, state and reasons (owner, aal2). */
|
||||
export async function listCatalogGrants(client: FaunosteoClient): Promise<CatalogGrant[]> {
|
||||
const { data, error, status } = await client.rpc('list_catalog_grants')
|
||||
if (error) failSheet(error, status)
|
||||
return data
|
||||
return parseSheetAnswer(z.array(CatalogGrantSchema), data)
|
||||
}
|
||||
|
||||
const CatalogAccountSchema = z.object({
|
||||
user_id: z.string(),
|
||||
display_name: z.string().nullable(),
|
||||
active: z.boolean(),
|
||||
email_confirmed: z.boolean(),
|
||||
verified_totp: z.boolean(),
|
||||
platform_roles: z.array(z.enum(E.platform_role)),
|
||||
})
|
||||
export type CatalogAccount = z.infer<typeof CatalogAccountSchema>
|
||||
|
||||
/** The account a right is granted to, by e-mail (owner, aal2); an unknown address is `not_found`. */
|
||||
export async function lookupCatalogAccount(
|
||||
client: FaunosteoClient,
|
||||
email: string,
|
||||
): Promise<CatalogAccount> {
|
||||
const { data, error, status } = await client.rpc('lookup_catalog_account', { email })
|
||||
if (error) failSheet(error, status)
|
||||
return parseSheetAnswer(CatalogAccountSchema, data)
|
||||
}
|
||||
|
||||
|
||||
// --- Sheets, drafts, review, publication -----------------------------------
|
||||
export async function createOfficialSheet(
|
||||
client: FaunosteoClient,
|
||||
@@ -235,3 +296,266 @@ export async function listOfficialCatalog(client: FaunosteoClient): Promise<Json
|
||||
if (error) failSheet(error, status)
|
||||
return data
|
||||
}
|
||||
|
||||
// --- Species (contract §7.2) -----------------------------------------------
|
||||
const CatalogSpeciesSchema = z.object({
|
||||
id: z.string(),
|
||||
name_fr: z.string(),
|
||||
name_en: z.string(),
|
||||
sort_order: z.number(),
|
||||
active: z.boolean(),
|
||||
})
|
||||
export type CatalogSpecies = z.infer<typeof CatalogSpeciesSchema>
|
||||
|
||||
/** Active and inactive species (capability holders or the owner, aal2). */
|
||||
export async function listCatalogSpecies(client: FaunosteoClient): Promise<CatalogSpecies[]> {
|
||||
const { data, error, status } = await client.rpc('list_catalog_species')
|
||||
if (error) failSheet(error, status)
|
||||
return parseSheetAnswer(z.array(CatalogSpeciesSchema), data)
|
||||
}
|
||||
|
||||
/** A new species, always inactive (sheet_editor, aal2). Resolves with its id. */
|
||||
export async function createSpecies(
|
||||
client: FaunosteoClient,
|
||||
args: { id: string; name_fr: string; name_en: string; sort_order?: number },
|
||||
): Promise<string> {
|
||||
const { data, error, status } = await client.rpc('create_species', args)
|
||||
if (error) failSheet(error, status)
|
||||
return data
|
||||
}
|
||||
|
||||
/** Names and order of an inactive species (sheet_editor, aal2). */
|
||||
export async function updateInactiveSpecies(
|
||||
client: FaunosteoClient,
|
||||
args: { id: string; name_fr: string; name_en: string; sort_order: number },
|
||||
): Promise<string> {
|
||||
const { data, error, status } = await client.rpc('update_inactive_species', args)
|
||||
if (error) failSheet(error, status)
|
||||
return data
|
||||
}
|
||||
|
||||
/** Owner, aal2. */
|
||||
export async function activateSpecies(client: FaunosteoClient, id: string): Promise<string> {
|
||||
const { data, error, status } = await client.rpc('activate_species', { id })
|
||||
if (error) failSheet(error, status)
|
||||
return data
|
||||
}
|
||||
|
||||
/** Names of an active species (owner, aal2). */
|
||||
export async function renameSpecies(
|
||||
client: FaunosteoClient,
|
||||
args: { id: string; name_fr: string; name_en: string },
|
||||
): Promise<string> {
|
||||
const { data, error, status } = await client.rpc('rename_species', args)
|
||||
if (error) failSheet(error, status)
|
||||
return data
|
||||
}
|
||||
|
||||
// --- Working copy of the historical sheet (§14.3) --------------------------
|
||||
/** A new official sheet drafted from a historical version (sheet_editor, aal2). Resolves with the sheet id. */
|
||||
export async function createSheetWorkingCopy(
|
||||
client: FaunosteoClient,
|
||||
sourceVersionId: string,
|
||||
slug: string,
|
||||
): Promise<string> {
|
||||
const { data, error, status } = await client.rpc('create_sheet_working_copy', {
|
||||
source_version_id: sourceVersionId,
|
||||
slug,
|
||||
})
|
||||
if (error) failSheet(error, status)
|
||||
return data
|
||||
}
|
||||
|
||||
// --- Administration reads (M7, capability holders at aal2) ------------------
|
||||
const VersionStatusSchema = z.enum(E.sheet_version_status)
|
||||
const RoundStatusSchema = z.enum(E.sheet_round_status)
|
||||
|
||||
const OfficialSheetAdminSummarySchema = z.object({
|
||||
sheet_id: z.string(),
|
||||
species_id: z.string(),
|
||||
slug: z.string(),
|
||||
status: z.enum(E.sheet_status),
|
||||
archived_at: z.string().nullable(),
|
||||
created_at: z.string(),
|
||||
updated_at: z.string(),
|
||||
name: LocalizedSchema,
|
||||
historical: z.boolean(),
|
||||
working_copy: z.boolean(),
|
||||
/** Set on the historical sheet only: a working copy is active (the single slot of §14.3). */
|
||||
working_copy_active: z.boolean().nullable(),
|
||||
latest_version: z
|
||||
.object({
|
||||
version_id: z.string(),
|
||||
version_number: z.number(),
|
||||
status: VersionStatusSchema,
|
||||
revision: z.number(),
|
||||
})
|
||||
.nullable(),
|
||||
current_version: z
|
||||
.object({ version_id: z.string(), version_number: z.number(), published_at: z.string().nullable() })
|
||||
.nullable(),
|
||||
draft_version: z
|
||||
.object({ version_id: z.string(), version_number: z.number(), revision: z.number() })
|
||||
.nullable(),
|
||||
version_statuses: z.array(VersionStatusSchema),
|
||||
open_rounds: z.number(),
|
||||
latest_round: z
|
||||
.object({
|
||||
review_id: z.string(),
|
||||
version_number: z.number(),
|
||||
round: z.number(),
|
||||
status: RoundStatusSchema,
|
||||
submitted_at: z.string().nullable(),
|
||||
})
|
||||
.nullable(),
|
||||
})
|
||||
export type OfficialSheetAdminSummary = z.infer<typeof OfficialSheetAdminSummarySchema>
|
||||
|
||||
const SheetAdminVersionSchema = z.object({
|
||||
version_id: z.string(),
|
||||
version_number: z.number(),
|
||||
status: VersionStatusSchema,
|
||||
revision: z.number(),
|
||||
change_note: z.string().nullable(),
|
||||
created_at: z.string(),
|
||||
published_at: z.string().nullable(),
|
||||
deprecated_at: z.string().nullable(),
|
||||
source_version_number: z.number().nullable(),
|
||||
authors: z.array(PersonSchema),
|
||||
})
|
||||
export type SheetAdminVersion = z.infer<typeof SheetAdminVersionSchema>
|
||||
|
||||
const SheetAdminRoundSchema = z.object({
|
||||
review_id: z.string(),
|
||||
version_id: z.string(),
|
||||
version_number: z.number(),
|
||||
round: z.number(),
|
||||
revision: z.number(),
|
||||
status: RoundStatusSchema,
|
||||
submitted_by: PersonSchema.nullable(),
|
||||
submitted_at: z.string().nullable(),
|
||||
verified_at: z.string().nullable(),
|
||||
failure_outcome: z.enum(E.sheet_verification_outcome).nullable(),
|
||||
failure_code: z.string().nullable(),
|
||||
decided_by: PersonSchema.nullable(),
|
||||
decided_at: z.string().nullable(),
|
||||
withdrawn_at: z.string().nullable(),
|
||||
})
|
||||
export type SheetAdminRound = z.infer<typeof SheetAdminRoundSchema>
|
||||
|
||||
const OfficialSheetAdminSchema = OfficialSheetAdminSummarySchema.extend({
|
||||
working_copy_source: z.object({ version_id: z.string(), version_number: z.number() }).nullable(),
|
||||
versions: z.array(SheetAdminVersionSchema),
|
||||
rounds: z.array(SheetAdminRoundSchema),
|
||||
})
|
||||
export type OfficialSheetAdmin = z.infer<typeof OfficialSheetAdminSchema>
|
||||
|
||||
/** Every official sheet that is not deleted, one summary each. */
|
||||
export async function listOfficialSheetsAdmin(
|
||||
client: FaunosteoClient,
|
||||
): Promise<OfficialSheetAdminSummary[]> {
|
||||
const { data, error, status } = await client.rpc('list_official_sheets_admin')
|
||||
if (error) failSheet(error, status)
|
||||
return parseSheetAnswer(z.array(OfficialSheetAdminSummarySchema), data)
|
||||
}
|
||||
|
||||
/** One sheet's overview: summary, versions and rounds. Unknown and forbidden ids are `not_found`. */
|
||||
export async function getOfficialSheetAdmin(
|
||||
client: FaunosteoClient,
|
||||
sheetId: string,
|
||||
): Promise<OfficialSheetAdmin> {
|
||||
if (!UUID_PATTERN.test(sheetId)) throw new SheetFailure('not_found')
|
||||
const { data, error, status } = await client.rpc('get_official_sheet_admin', { sheet_id: sheetId })
|
||||
if (error) failSheet(error, status)
|
||||
return parseSheetAnswer(OfficialSheetAdminSchema, data)
|
||||
}
|
||||
|
||||
// --- Catalogue reads (readers, any assurance level) --------------------------
|
||||
export interface CatalogVersionItem {
|
||||
id: string
|
||||
version_number: number
|
||||
status: 'published' | 'deprecated'
|
||||
published_at: string | null
|
||||
deprecated_at: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* The published and deprecated versions of a sheet, newest first, through
|
||||
* the reader column grants of M4 and their RLS policy. An unknown or
|
||||
* unreadable sheet answers an empty list.
|
||||
*/
|
||||
export async function listSheetVersions(
|
||||
client: FaunosteoClient,
|
||||
sheetId: string,
|
||||
): Promise<CatalogVersionItem[]> {
|
||||
if (!UUID_PATTERN.test(sheetId)) throw new SheetFailure('not_found')
|
||||
const { data, error, status } = await client
|
||||
.from('anatomical_sheet_versions')
|
||||
.select('id, version_number, status, published_at, deprecated_at')
|
||||
.eq('sheet_id', sheetId)
|
||||
.in('status', ['published', 'deprecated'])
|
||||
.order('version_number', { ascending: false })
|
||||
if (error) failSheet(error, status)
|
||||
return (data ?? []) as CatalogVersionItem[]
|
||||
}
|
||||
|
||||
export interface OwnCatalogGrant {
|
||||
kind: Enums<'catalog_grant_kind'>
|
||||
expires_at: string | null
|
||||
revoked_at: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* The caller's own grant rows (the grants policy shows every account its
|
||||
* own), for the navigation hint of §5.3 only: never a control, the server
|
||||
* decides on every read.
|
||||
*/
|
||||
export async function listOwnCatalogGrants(
|
||||
client: FaunosteoClient,
|
||||
userId: string,
|
||||
): Promise<OwnCatalogGrant[]> {
|
||||
const { data, error, status } = await client
|
||||
.from('anatomical_catalog_grants')
|
||||
.select('kind:grant_kind, expires_at, revoked_at')
|
||||
.eq('user_id', userId)
|
||||
if (error) failSheet(error, status)
|
||||
return data ?? []
|
||||
}
|
||||
|
||||
const SHA256_PATTERN = /^[0-9a-f]{64}$/
|
||||
const DRAWING_BUCKET = 'anatomical-sheet-assets'
|
||||
|
||||
interface StorageLikeError {
|
||||
name?: string
|
||||
status?: number
|
||||
code?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds a Storage answer: a missing object and a refused one are the same
|
||||
* `not_found` (Storage answers 400 or 404 for both); a request that never got
|
||||
* an answer is `network`.
|
||||
*/
|
||||
function classifyDrawingError(error: unknown): SheetFailureKind {
|
||||
const e = (error ?? {}) as StorageLikeError
|
||||
if (e.name === 'StorageUnknownError') return 'network'
|
||||
if (e.code === 'InvalidJWT' || e.status === 401) return 'session_expired'
|
||||
if (e.status === 429) return 'rate_limited'
|
||||
if (e.status === 400 || e.status === 404) return 'not_found'
|
||||
return 'unavailable'
|
||||
}
|
||||
|
||||
/**
|
||||
* The bytes of one sheet drawing (`<sha256>.svg`) under the Storage read
|
||||
* policy (§9.4). A malformed hash is refused before any request. The bytes
|
||||
* are untrusted: the core checks the hash and reads the SVG.
|
||||
*/
|
||||
export async function downloadSheetDrawing(
|
||||
client: FaunosteoClient,
|
||||
sha256: string,
|
||||
): Promise<Uint8Array> {
|
||||
if (!SHA256_PATTERN.test(sha256)) throw new SheetFailure('invalid_input')
|
||||
const { data, error } = await client.storage.from(DRAWING_BUCKET).download(`${sha256}.svg`)
|
||||
if (error || !data) throw new SheetFailure(classifyDrawingError(error), error)
|
||||
return new Uint8Array(await data.arrayBuffer())
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import {
|
||||
MfaFailure,
|
||||
assuranceLevel,
|
||||
classifyMfaError,
|
||||
enrollTotp,
|
||||
listTotpFactors,
|
||||
unenrollFactor,
|
||||
verifyTotp,
|
||||
type FaunosteoClient,
|
||||
} from '../src'
|
||||
|
||||
/**
|
||||
* TOTP wrappers over supabase-js `auth.mfa`: call shapes, the factor list
|
||||
* (unverified factors included) and the closed failure kinds. The same
|
||||
* functions run against real GoTrue in tests/sandbox/sheets-admin.sandbox.ts.
|
||||
*/
|
||||
type Result = { data?: unknown; error?: unknown }
|
||||
|
||||
function stubMfa(results: Record<string, Result> = {}) {
|
||||
const calls: Array<[string, unknown]> = []
|
||||
const method = (name: string) => async (params?: unknown) => {
|
||||
calls.push([name, params])
|
||||
return { data: results[name]?.data ?? null, error: results[name]?.error ?? null }
|
||||
}
|
||||
const client = {
|
||||
auth: {
|
||||
mfa: {
|
||||
listFactors: method('listFactors'),
|
||||
enroll: method('enroll'),
|
||||
challengeAndVerify: method('challengeAndVerify'),
|
||||
unenroll: method('unenroll'),
|
||||
getAuthenticatorAssuranceLevel: method('getAuthenticatorAssuranceLevel'),
|
||||
},
|
||||
},
|
||||
} as unknown as FaunosteoClient
|
||||
return { client, calls }
|
||||
}
|
||||
|
||||
async function kindOf(promise: Promise<unknown>) {
|
||||
try {
|
||||
await promise
|
||||
return 'no failure'
|
||||
} catch (error) {
|
||||
return error instanceof MfaFailure ? error.kind : `other: ${String(error)}`
|
||||
}
|
||||
}
|
||||
|
||||
const factor = (id: string, status: string, type = 'totp', name?: string) => ({
|
||||
id, factor_type: type, status, friendly_name: name, created_at: `2026-11-0${id}T10:00:00Z`, updated_at: 'u',
|
||||
})
|
||||
|
||||
describe('classifyMfaError', () => {
|
||||
it('maps the GoTrue codes to the closed kinds', () => {
|
||||
expect(classifyMfaError({ code: 'insufficient_aal', status: 403 })).toBe('aal2_required')
|
||||
expect(classifyMfaError({ code: 'mfa_verification_failed', status: 422 })).toBe('invalid_code')
|
||||
expect(classifyMfaError({ code: 'mfa_verification_rejected', status: 422 })).toBe('invalid_code')
|
||||
expect(classifyMfaError({ code: 'mfa_factor_not_found', status: 404 })).toBe('factor_not_found')
|
||||
expect(classifyMfaError({ code: 'mfa_challenge_expired', status: 422 })).toBe('challenge_expired')
|
||||
expect(classifyMfaError({ code: 'too_many_enrolled_mfa_factors', status: 422 })).toBe('too_many_factors')
|
||||
expect(classifyMfaError({ code: 'mfa_factor_name_conflict', status: 422 })).toBe('name_taken')
|
||||
expect(classifyMfaError({ code: 'over_request_rate_limit', status: 429 })).toBe('rate_limited')
|
||||
expect(classifyMfaError({ code: 'session_not_found', status: 403 })).toBe('session_expired')
|
||||
expect(classifyMfaError({ code: 'bad_jwt', status: 401 })).toBe('session_expired')
|
||||
})
|
||||
|
||||
it('reads the client error classes, then the status, and fails closed', () => {
|
||||
expect(classifyMfaError({ name: 'AuthSessionMissingError', status: 400 })).toBe('session_expired')
|
||||
expect(classifyMfaError({ name: 'AuthRetryableFetchError', status: 0 })).toBe('network')
|
||||
expect(classifyMfaError(new TypeError('fetch failed'))).toBe('network')
|
||||
expect(classifyMfaError({ status: 429 })).toBe('rate_limited')
|
||||
expect(classifyMfaError({ code: 'mfa_totp_enroll_not_enabled', status: 422 })).toBe('unavailable')
|
||||
expect(classifyMfaError({ code: 'unexpected_failure', status: 500 })).toBe('unavailable')
|
||||
expect(classifyMfaError(undefined)).toBe('unavailable')
|
||||
expect(classifyMfaError(new MfaFailure('invalid_code'))).toBe('invalid_code')
|
||||
})
|
||||
})
|
||||
|
||||
describe('TOTP wrappers', () => {
|
||||
it('lists every TOTP factor, unverified ones included, and no other type', async () => {
|
||||
const all = [factor('1', 'verified', 'totp', 'Phone'), factor('2', 'unverified'), factor('3', 'verified', 'phone')]
|
||||
const { client } = stubMfa({ listFactors: { data: { all, totp: [all[0]] } } })
|
||||
expect(await listTotpFactors(client)).toEqual([
|
||||
{ id: '1', friendlyName: 'Phone', status: 'verified', createdAt: '2026-11-01T10:00:00Z' },
|
||||
{ id: '2', friendlyName: null, status: 'unverified', createdAt: '2026-11-02T10:00:00Z' },
|
||||
])
|
||||
})
|
||||
|
||||
it('enrols a TOTP factor and hands back the QR code, secret and URI', async () => {
|
||||
const totp = { qr_code: 'data:image/svg+xml;utf-8,<svg/>', secret: 'S', uri: 'otpauth://totp/x' }
|
||||
const { client, calls } = stubMfa({ enroll: { data: { id: 'f1', type: 'totp', totp } } })
|
||||
expect(await enrollTotp(client, 'Phone')).toEqual({
|
||||
factorId: 'f1', qrCode: totp.qr_code, secret: 'S', uri: totp.uri,
|
||||
})
|
||||
expect(calls).toEqual([['enroll', { factorType: 'totp', friendlyName: 'Phone' }]])
|
||||
})
|
||||
|
||||
it('verifies with one challenge and removes a factor by id', async () => {
|
||||
const { client, calls } = stubMfa({ challengeAndVerify: { data: {} }, unenroll: { data: { id: 'f1' } } })
|
||||
await verifyTotp(client, 'f1', '123456')
|
||||
await unenrollFactor(client, 'f1')
|
||||
expect(calls).toEqual([
|
||||
['challengeAndVerify', { factorId: 'f1', code: '123456' }],
|
||||
['unenroll', { factorId: 'f1' }],
|
||||
])
|
||||
})
|
||||
|
||||
it('answers the assurance levels, null without a session', async () => {
|
||||
const level = (currentLevel: unknown, nextLevel: unknown) =>
|
||||
stubMfa({ getAuthenticatorAssuranceLevel: { data: { currentLevel, nextLevel, currentAuthenticationMethods: [] } } })
|
||||
.client
|
||||
expect(await assuranceLevel(level('aal1', 'aal2'))).toEqual({ current: 'aal1', next: 'aal2' })
|
||||
expect(await assuranceLevel(level(null, null))).toEqual({ current: null, next: null })
|
||||
expect(await assuranceLevel(level('aal3', 'aal2'))).toEqual({ current: null, next: 'aal2' })
|
||||
})
|
||||
|
||||
it('throws the closed kind of a GoTrue refusal', async () => {
|
||||
const refused = (name: string, code: string) => stubMfa({ [name]: { error: { code, status: 403 } } }).client
|
||||
expect(await kindOf(enrollTotp(refused('enroll', 'insufficient_aal'), 'x'))).toBe('aal2_required')
|
||||
expect(await kindOf(verifyTotp(refused('challengeAndVerify', 'mfa_verification_failed'), 'f', '000000')))
|
||||
.toBe('invalid_code')
|
||||
expect(await kindOf(unenrollFactor(refused('unenroll', 'insufficient_aal'), 'f'))).toBe('aal2_required')
|
||||
expect(await kindOf(listTotpFactors(refused('listFactors', 'session_not_found')))).toBe('session_expired')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* The V1-2.5 access layer through real supabase-js against the throwaway
|
||||
* stack (real GoTrue v2.197.0, PostgREST, Storage, PostgreSQL): the TOTP
|
||||
* wrappers (enrol, verify to aal2, the aal1 refusals of IDENTITY.md §4.1,
|
||||
* removal), the M7 admin reads at aal2 and their aal1 refusal, species
|
||||
* creation by an editor, the account lookup by the owner, the catalogue
|
||||
* reads. Run through `pnpm db:sandbox test tests/sandbox/sheets-admin.sandbox.ts`;
|
||||
* the accounts and the species it creates are removed afterwards, so it runs
|
||||
* again on the same stack.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import {
|
||||
MfaFailure,
|
||||
SheetFailure,
|
||||
assuranceLevel,
|
||||
createSheetWorkingCopy,
|
||||
createSpecies,
|
||||
downloadSheetDrawing,
|
||||
enrollTotp,
|
||||
getOfficialSheetAdmin,
|
||||
listCatalogGrants,
|
||||
listCatalogSpecies,
|
||||
listOfficialSheetsAdmin,
|
||||
listOwnCatalogGrants,
|
||||
listSheetVersions,
|
||||
listTotpFactors,
|
||||
lookupCatalogAccount,
|
||||
unenrollFactor,
|
||||
updateInactiveSpecies,
|
||||
verifyTotp,
|
||||
type Database,
|
||||
type FaunosteoClient,
|
||||
} from '../../src'
|
||||
import { PASSWORD, confirmedAccount, sql, stack, type Account } from './stack'
|
||||
import { totpCode } from './totp'
|
||||
|
||||
const BASE = 'http://sandbox.faunosteo.invalid'
|
||||
const HISTORICAL = '503dc301-a8b1-50d4-9e44-0919b2fc2916'
|
||||
|
||||
/** The browser client of the app, its requests replayed on the sandbox ports. */
|
||||
function browserClient(): 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)
|
||||
}
|
||||
return createClient<Database>(BASE, stack.anonKey, {
|
||||
auth: { persistSession: false, autoRefreshToken: false },
|
||||
global: { fetch: mapped },
|
||||
})
|
||||
}
|
||||
|
||||
/** A new password session of the account: always aal1. */
|
||||
async function signedIn(account: Account): Promise<FaunosteoClient> {
|
||||
const client = browserClient()
|
||||
const { error } = await client.auth.signInWithPassword({ email: account.email, password: PASSWORD })
|
||||
if (error) throw error
|
||||
return client
|
||||
}
|
||||
|
||||
/** Enrols and verifies a TOTP factor through the wrappers; the client ends at aal2. */
|
||||
async function stepUp(client: FaunosteoClient, name = 'device') {
|
||||
const enrolment = await enrollTotp(client, name)
|
||||
await verifyTotp(client, enrolment.factorId, totpCode(enrolment.secret))
|
||||
return enrolment
|
||||
}
|
||||
|
||||
async function kindOf(promise: Promise<unknown>) {
|
||||
try {
|
||||
await promise
|
||||
return 'no failure'
|
||||
} catch (error) {
|
||||
if (error instanceof SheetFailure || error instanceof MfaFailure) return error.kind
|
||||
return `other: ${String(error)}`
|
||||
}
|
||||
}
|
||||
|
||||
/** A code of the same length that is not the current one. */
|
||||
const wrongCode = (secret: string) =>
|
||||
totpCode(secret).replace(/.$/, (digit) => String((Number(digit) + 5) % 10))
|
||||
|
||||
const created: string[] = []
|
||||
const species: string[] = []
|
||||
|
||||
async function account(tag: string, role: 'owner' | 'admin' | null = null): Promise<Account> {
|
||||
const a = await confirmedAccount(tag)
|
||||
created.push(a.id)
|
||||
if (role) await sql(`select private.assign_platform_role(null, '${a.id}', '${role}')`)
|
||||
return a
|
||||
}
|
||||
|
||||
afterAll(async () => {
|
||||
if (species.length > 0)
|
||||
await sql(`delete from public.species where id in (${species.map((id) => `'${id}'`).join(', ')})`)
|
||||
if (created.length === 0) return
|
||||
const ids = created.map((id) => `'${id}'`).join(', ')
|
||||
// Grants are never deleted by design (guard trigger): the run's own rows are
|
||||
// removed with the triggers off for this transaction only, then the accounts.
|
||||
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('TOTP wrappers on real GoTrue', () => {
|
||||
it('enrols, verifies to aal2, refuses the aal1 changes, removes', async () => {
|
||||
const a = await account('admin-mfa')
|
||||
const client = await signedIn(a)
|
||||
expect(await assuranceLevel(client)).toEqual({ current: 'aal1', next: 'aal1' })
|
||||
|
||||
const enrolment = await enrollTotp(client, 'Phone')
|
||||
expect(enrolment.qrCode.startsWith('data:image/svg+xml;utf-8,')).toBe(true)
|
||||
expect(enrolment.uri.startsWith('otpauth://totp/')).toBe(true)
|
||||
// supabase-js keeps unverified factors out of `totp`: the wrapper still lists them.
|
||||
expect(await listTotpFactors(client)).toEqual([
|
||||
expect.objectContaining({ id: enrolment.factorId, friendlyName: 'Phone', status: 'unverified' }),
|
||||
])
|
||||
|
||||
expect(await kindOf(verifyTotp(client, enrolment.factorId, wrongCode(enrolment.secret)))).toBe('invalid_code')
|
||||
await verifyTotp(client, enrolment.factorId, totpCode(enrolment.secret))
|
||||
expect(await assuranceLevel(client)).toEqual({ current: 'aal2', next: 'aal2' })
|
||||
expect((await listTotpFactors(client)).map((f) => f.status)).toEqual(['verified'])
|
||||
|
||||
// A new password session is aal1: no second factor, no removal of the verified one.
|
||||
const aal1 = await signedIn(a)
|
||||
expect(await assuranceLevel(aal1)).toEqual({ current: 'aal1', next: 'aal2' })
|
||||
expect(await kindOf(enrollTotp(aal1, 'Second'))).toBe('aal2_required')
|
||||
expect(await kindOf(unenrollFactor(aal1, enrolment.factorId))).toBe('aal2_required')
|
||||
expect(await kindOf(unenrollFactor(client, randomUUID()))).toBe('factor_not_found')
|
||||
|
||||
await unenrollFactor(client, enrolment.factorId)
|
||||
expect(await listTotpFactors(client)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('administration reads, species and account lookup', () => {
|
||||
let editor: Account
|
||||
let editorAal2: FaunosteoClient
|
||||
|
||||
beforeAll(async () => {
|
||||
editor = await account('admin-editor', 'admin')
|
||||
await sql(`insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, verification_note, granted_by)
|
||||
values ('${editor.id}', 'sheet_editor', 'sandbox', 'sandbox', '${editor.id}')`)
|
||||
editorAal2 = await signedIn(editor)
|
||||
await stepUp(editorAal2)
|
||||
})
|
||||
|
||||
it('an editor reads the admin list and an overview at aal2, refused at aal1', async () => {
|
||||
const sheets = await listOfficialSheetsAdmin(editorAal2)
|
||||
expect(sheets.find((s) => s.sheet_id === HISTORICAL)).toMatchObject({ historical: true, working_copy: false })
|
||||
const overview = await getOfficialSheetAdmin(editorAal2, HISTORICAL)
|
||||
expect(overview.versions.length).toBeGreaterThan(0)
|
||||
expect(await kindOf(getOfficialSheetAdmin(editorAal2, randomUUID()))).toBe('not_found')
|
||||
|
||||
const aal1 = await signedIn(editor)
|
||||
expect(await kindOf(listOfficialSheetsAdmin(aal1))).toBe('rights.mfa')
|
||||
expect(await kindOf(getOfficialSheetAdmin(aal1, HISTORICAL))).toBe('rights.mfa')
|
||||
// The navigation hint reads the own rows at any level.
|
||||
expect(await listOwnCatalogGrants(aal1, editor.id)).toEqual([
|
||||
{ kind: 'sheet_editor', expires_at: null, revoked_at: null },
|
||||
])
|
||||
})
|
||||
|
||||
it('an editor creates an inactive species and edits it', async () => {
|
||||
const id = `sbx-${randomUUID().slice(0, 8)}`
|
||||
species.push(id)
|
||||
expect(await createSpecies(editorAal2, { id, name_fr: 'Essai', name_en: 'Trial' })).toBe(id)
|
||||
expect(await updateInactiveSpecies(editorAal2, { id, name_fr: 'Essai 2', name_en: 'Trial 2', sort_order: 900 }))
|
||||
.toBe(id)
|
||||
expect((await listCatalogSpecies(editorAal2)).find((s) => s.id === id)).toEqual({
|
||||
id, name_fr: 'Essai 2', name_en: 'Trial 2', sort_order: 900, active: false,
|
||||
})
|
||||
expect(await kindOf(createSpecies(editorAal2, { id, name_fr: 'X', name_en: 'X' }))).toBe('species.exists')
|
||||
})
|
||||
|
||||
it('the working copy and the catalogue reads answer their closed kinds', async () => {
|
||||
const source = await sql(`select id from public.anatomical_sheet_versions where sheet_id = '${HISTORICAL}'
|
||||
order by version_number limit 1`)
|
||||
expect(['working_copy.exists', 'working_copy.assets_missing'])
|
||||
.toContain(await kindOf(createSheetWorkingCopy(editorAal2, source, `wc-${randomUUID().slice(0, 8)}`)))
|
||||
const versions = await listSheetVersions(editorAal2, HISTORICAL)
|
||||
expect(versions.every((v) => v.status === 'published' || v.status === 'deprecated')).toBe(true)
|
||||
expect(await kindOf(downloadSheetDrawing(editorAal2, 'f'.repeat(64)))).toBe('not_found')
|
||||
})
|
||||
|
||||
it('the owner looks an account up at aal2, refused at aal1', async () => {
|
||||
const owner = await account('admin-owner', 'owner')
|
||||
const ownerAal2 = await signedIn(owner)
|
||||
await stepUp(ownerAal2)
|
||||
expect(await lookupCatalogAccount(ownerAal2, editor.email.toUpperCase())).toEqual({
|
||||
user_id: editor.id,
|
||||
display_name: expect.any(String),
|
||||
active: true,
|
||||
email_confirmed: true,
|
||||
verified_totp: true,
|
||||
platform_roles: ['admin'],
|
||||
})
|
||||
expect(await kindOf(lookupCatalogAccount(ownerAal2, `none-${randomUUID()}@sandbox.local`))).toBe('not_found')
|
||||
expect((await listCatalogGrants(ownerAal2)).find((g) => g.user_id === editor.id)).toMatchObject({
|
||||
kind: 'sheet_editor', state: 'active', effective: true,
|
||||
})
|
||||
expect(await kindOf(lookupCatalogAccount(await signedIn(owner), editor.email))).toBe('rights.mfa')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,238 @@
|
||||
import {
|
||||
SheetFailure,
|
||||
activateSpecies,
|
||||
createSheetWorkingCopy,
|
||||
createSpecies,
|
||||
downloadSheetDrawing,
|
||||
getOfficialSheetAdmin,
|
||||
listCatalogGrants,
|
||||
listCatalogSpecies,
|
||||
listOfficialSheetsAdmin,
|
||||
listOwnCatalogGrants,
|
||||
listSheetVersions,
|
||||
lookupCatalogAccount,
|
||||
renameSpecies,
|
||||
updateInactiveSpecies,
|
||||
type FaunosteoClient,
|
||||
} from '../src'
|
||||
|
||||
/**
|
||||
* Call shapes, answer parsers and closed failure kinds of the V1-2.5 sheet
|
||||
* access layer. The argument names are checked by the compiler against the
|
||||
* generated types; the RPC bodies by the sheet pgTAP files under supabase/tests; the
|
||||
* same functions run against real PostgREST, GoTrue and Storage in
|
||||
* tests/sandbox/sheets-admin.sandbox.ts.
|
||||
*/
|
||||
type Answer = { data?: unknown; error?: unknown; status?: number }
|
||||
|
||||
function stubClient(answers: { rpc?: Answer; select?: Answer; download?: Answer } = {}) {
|
||||
const rpcCalls: Array<[string, Record<string, unknown> | undefined]> = []
|
||||
const query: Record<string, unknown> = {}
|
||||
const downloads: Array<[string, string]> = []
|
||||
const settle = (a: Answer = {}) => ({
|
||||
data: a.data ?? null,
|
||||
error: a.error ?? null,
|
||||
status: a.status ?? (a.error ? 400 : 200),
|
||||
})
|
||||
const chain = {
|
||||
select: (cols: string) => ((query.select = cols), chain),
|
||||
eq: (col: string, value: unknown) => ((query[`eq:${col}`] = value), chain),
|
||||
in: (col: string, values: unknown) => ((query[`in:${col}`] = values), chain),
|
||||
order: (col: string, opts: unknown) => ((query[`order:${col}`] = opts), chain),
|
||||
then: (resolve: (value: unknown) => unknown) => resolve(settle(answers.select)),
|
||||
}
|
||||
const client = {
|
||||
from: (table: string) => ((query.table = table), chain),
|
||||
rpc: async (name: string, args?: Record<string, unknown>) => {
|
||||
rpcCalls.push([name, args])
|
||||
return settle(answers.rpc)
|
||||
},
|
||||
storage: {
|
||||
from: (bucket: string) => ({
|
||||
download: async (path: string) => {
|
||||
downloads.push([bucket, path])
|
||||
return { data: answers.download?.data ?? null, error: answers.download?.error ?? null }
|
||||
},
|
||||
}),
|
||||
},
|
||||
} as unknown as FaunosteoClient
|
||||
return { client, rpcCalls, query, downloads }
|
||||
}
|
||||
|
||||
async function kindOf(promise: Promise<unknown>) {
|
||||
try {
|
||||
await promise
|
||||
return 'no failure'
|
||||
} catch (error) {
|
||||
return error instanceof SheetFailure ? error.kind : `other: ${String(error)}`
|
||||
}
|
||||
}
|
||||
|
||||
const SHEET = '22222222-2222-4222-8222-222222222222'
|
||||
const VERSION = '33333333-3333-4333-8333-333333333333'
|
||||
const SHA = 'a'.repeat(64)
|
||||
|
||||
const person = { user_id: SHEET, display_name: 'Marie' }
|
||||
const summary = {
|
||||
sheet_id: SHEET,
|
||||
species_id: 'equine',
|
||||
slug: 'cheval',
|
||||
status: 'active',
|
||||
archived_at: null,
|
||||
created_at: '2026-11-02T10:00:00Z',
|
||||
updated_at: '2026-11-02T10:00:00Z',
|
||||
name: { fr: 'Cheval', en: 'Horse' },
|
||||
historical: true,
|
||||
working_copy: false,
|
||||
working_copy_active: false,
|
||||
latest_version: { version_id: VERSION, version_number: 2, status: 'draft', revision: 3 },
|
||||
current_version: { version_id: VERSION, version_number: 1, published_at: '2026-11-01T10:00:00Z' },
|
||||
draft_version: { version_id: VERSION, version_number: 2, revision: 3 },
|
||||
version_statuses: ['draft', 'published'],
|
||||
open_rounds: 0,
|
||||
latest_round: null,
|
||||
}
|
||||
const overview = {
|
||||
...summary,
|
||||
working_copy_source: null,
|
||||
versions: [{
|
||||
version_id: VERSION, version_number: 1, status: 'published', revision: 1, change_note: null,
|
||||
created_at: '2026-11-01T09:00:00Z', published_at: '2026-11-01T10:00:00Z', deprecated_at: null,
|
||||
source_version_number: null, authors: [person],
|
||||
}],
|
||||
rounds: [{
|
||||
review_id: VERSION, version_id: VERSION, version_number: 1, round: 1, revision: 1, status: 'approved',
|
||||
submitted_by: person, submitted_at: '2026-11-01T09:30:00Z', verified_at: '2026-11-01T09:31:00Z',
|
||||
failure_outcome: null, failure_code: null, decided_by: person, decided_at: '2026-11-01T09:40:00Z',
|
||||
withdrawn_at: null,
|
||||
}],
|
||||
}
|
||||
const grant = {
|
||||
id: VERSION, user_id: SHEET, display_name: 'Marie', email: 'marie@example.org', kind: 'sheet_editor',
|
||||
reason: 'r', verification_note: 'n', granted_by: SHEET, granted_by_name: 'Owner',
|
||||
granted_at: '2026-11-01T09:00:00Z', expires_at: null, revoked_at: null, revoked_by: null,
|
||||
revocation_reason: null, state: 'active', effective: true,
|
||||
}
|
||||
|
||||
describe('sheet admin wrappers: argument mapping', () => {
|
||||
it('names the RPC arguments as the migrations do', async () => {
|
||||
const { client, rpcCalls } = stubClient({ rpc: { data: 'ok' } })
|
||||
await createSpecies(client, { id: 'feline', name_fr: 'Chat', name_en: 'Cat' })
|
||||
await updateInactiveSpecies(client, { id: 'feline', name_fr: 'Chat', name_en: 'Cat', sort_order: 5 })
|
||||
await activateSpecies(client, 'feline')
|
||||
await renameSpecies(client, { id: 'feline', name_fr: 'Félin', name_en: 'Feline' })
|
||||
await createSheetWorkingCopy(client, VERSION, 'cheval-v2')
|
||||
expect(rpcCalls).toEqual([
|
||||
['create_species', { id: 'feline', name_fr: 'Chat', name_en: 'Cat' }],
|
||||
['update_inactive_species', { id: 'feline', name_fr: 'Chat', name_en: 'Cat', sort_order: 5 }],
|
||||
['activate_species', { id: 'feline' }],
|
||||
['rename_species', { id: 'feline', name_fr: 'Félin', name_en: 'Feline' }],
|
||||
['create_sheet_working_copy', { source_version_id: VERSION, slug: 'cheval-v2' }],
|
||||
])
|
||||
})
|
||||
|
||||
it('reads the published and deprecated versions of one sheet, newest first', async () => {
|
||||
const rows = [{ id: VERSION, version_number: 1, status: 'published', published_at: 'x', deprecated_at: null }]
|
||||
const { client, query } = stubClient({ select: { data: rows } })
|
||||
expect(await listSheetVersions(client, SHEET)).toEqual(rows)
|
||||
expect(query).toEqual({
|
||||
table: 'anatomical_sheet_versions',
|
||||
select: 'id, version_number, status, published_at, deprecated_at',
|
||||
[`eq:sheet_id`]: SHEET,
|
||||
[`in:status`]: ['published', 'deprecated'],
|
||||
[`order:version_number`]: { ascending: false },
|
||||
})
|
||||
})
|
||||
|
||||
it("reads the caller's own grant rows for the navigation hint", async () => {
|
||||
const rows = [{ kind: 'catalog_reader', expires_at: null, revoked_at: null }]
|
||||
const { client, query } = stubClient({ select: { data: rows } })
|
||||
expect(await listOwnCatalogGrants(client, SHEET)).toEqual(rows)
|
||||
expect(query).toEqual({
|
||||
table: 'anatomical_catalog_grants',
|
||||
select: 'kind:grant_kind, expires_at, revoked_at',
|
||||
[`eq:user_id`]: SHEET,
|
||||
})
|
||||
})
|
||||
|
||||
it('answers a malformed id as unknown without a request', async () => {
|
||||
const { client, rpcCalls, query } = stubClient()
|
||||
expect(await kindOf(getOfficialSheetAdmin(client, 'nope'))).toBe('not_found')
|
||||
expect(await kindOf(listSheetVersions(client, `${SHEET}'`))).toBe('not_found')
|
||||
expect(rpcCalls).toEqual([])
|
||||
expect(query).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe('sheet admin wrappers: answers', () => {
|
||||
it('parses the admin list and the overview', async () => {
|
||||
expect(await listOfficialSheetsAdmin(stubClient({ rpc: { data: [summary] } }).client)).toEqual([summary])
|
||||
const { client, rpcCalls } = stubClient({ rpc: { data: overview } })
|
||||
expect(await getOfficialSheetAdmin(client, SHEET)).toEqual(overview)
|
||||
expect(rpcCalls).toEqual([['get_official_sheet_admin', { sheet_id: SHEET }]])
|
||||
})
|
||||
|
||||
it('parses grants, the account lookup and the species', async () => {
|
||||
expect(await listCatalogGrants(stubClient({ rpc: { data: [grant] } }).client)).toEqual([grant])
|
||||
const account = {
|
||||
user_id: SHEET, display_name: 'Marie', active: true, email_confirmed: true, verified_totp: false,
|
||||
platform_roles: ['owner'],
|
||||
}
|
||||
const lookup = stubClient({ rpc: { data: account } })
|
||||
expect(await lookupCatalogAccount(lookup.client, 'marie@example.org')).toEqual(account)
|
||||
expect(lookup.rpcCalls).toEqual([['lookup_catalog_account', { email: 'marie@example.org' }]])
|
||||
const species = [{ id: 'equine', name_fr: 'Cheval', name_en: 'Horse', sort_order: 10, active: true }]
|
||||
expect(await listCatalogSpecies(stubClient({ rpc: { data: species } }).client)).toEqual(species)
|
||||
})
|
||||
|
||||
it('refuses an answer outside the contract as unavailable', async () => {
|
||||
const answer = (data: unknown) => stubClient({ rpc: { data } }).client
|
||||
expect(await kindOf(listOfficialSheetsAdmin(answer({ sheets: [] })))).toBe('unavailable')
|
||||
expect(await kindOf(listOfficialSheetsAdmin(answer([{ ...summary, status: 'gone' }])))).toBe('unavailable')
|
||||
expect(await kindOf(getOfficialSheetAdmin(answer(summary), SHEET))).toBe('unavailable')
|
||||
expect(await kindOf(listCatalogGrants(answer([{ ...grant, state: 'paused' }])))).toBe('unavailable')
|
||||
expect(await kindOf(lookupCatalogAccount(answer(null), 'a@b.c'))).toBe('unavailable')
|
||||
expect(await kindOf(listCatalogSpecies(answer([{ id: 'x' }])))).toBe('unavailable')
|
||||
})
|
||||
|
||||
it('folds the server refusals into their kinds', async () => {
|
||||
const refused = (message: string, code = '42501') =>
|
||||
stubClient({ rpc: { error: { code, message }, status: 403 } }).client
|
||||
expect(await kindOf(listOfficialSheetsAdmin(refused('rights.mfa')))).toBe('rights.mfa')
|
||||
expect(await kindOf(getOfficialSheetAdmin(refused('not_found'), SHEET))).toBe('not_found')
|
||||
expect(await kindOf(lookupCatalogAccount(refused('rights.owner'), 'a@b.c'))).toBe('rights.owner')
|
||||
expect(await kindOf(createSpecies(refused('species.exists', 'P0001'), { id: 'x', name_fr: 'X', name_en: 'X' })))
|
||||
.toBe('species.exists')
|
||||
expect(await kindOf(createSheetWorkingCopy(refused('working_copy.exists', 'P0001'), VERSION, 's')))
|
||||
.toBe('working_copy.exists')
|
||||
const expired = stubClient({ select: { error: { code: 'PGRST301', message: 'JWT expired' }, status: 401 } })
|
||||
expect(await kindOf(listSheetVersions(expired.client, SHEET))).toBe('session_expired')
|
||||
})
|
||||
})
|
||||
|
||||
describe('downloadSheetDrawing', () => {
|
||||
it('downloads <sha256>.svg from the sheet bucket and answers its bytes', async () => {
|
||||
const bytes = new TextEncoder().encode('<svg/>')
|
||||
const { client, downloads } = stubClient({ download: { data: new Blob([bytes]) } })
|
||||
expect(await downloadSheetDrawing(client, SHA)).toEqual(bytes)
|
||||
expect(downloads).toEqual([['anatomical-sheet-assets', `${SHA}.svg`]])
|
||||
})
|
||||
|
||||
it('refuses a malformed hash before any request', async () => {
|
||||
const { client, downloads } = stubClient()
|
||||
for (const sha of ['', 'A'.repeat(64), 'a'.repeat(63), `${'a'.repeat(64)}/x`, '../x'])
|
||||
expect(await kindOf(downloadSheetDrawing(client, sha))).toBe('invalid_input')
|
||||
expect(downloads).toEqual([])
|
||||
})
|
||||
|
||||
it('folds Storage refusals: a missing object and a refused one are the same not_found', async () => {
|
||||
const failing = (error: unknown) => stubClient({ download: { error } }).client
|
||||
expect(await kindOf(downloadSheetDrawing(failing({ name: 'StorageApiError', status: 400, code: 'NoSuchKey' }), SHA)))
|
||||
.toBe('not_found')
|
||||
expect(await kindOf(downloadSheetDrawing(failing({ name: 'StorageApiError', status: 404 }), SHA))).toBe('not_found')
|
||||
expect(await kindOf(downloadSheetDrawing(failing({ name: 'StorageApiError', status: 400, code: 'InvalidJWT' }), SHA)))
|
||||
.toBe('session_expired')
|
||||
expect(await kindOf(downloadSheetDrawing(failing({ name: 'StorageUnknownError' }), SHA))).toBe('network')
|
||||
expect(await kindOf(downloadSheetDrawing(failing({ name: 'StorageApiError', status: 500 }), SHA))).toBe('unavailable')
|
||||
})
|
||||
})
|
||||
@@ -5,13 +5,14 @@ import { migrationsDir } from './db/harness'
|
||||
|
||||
/**
|
||||
* The closed failure kinds of the sheet workflow (V1-2.1). The census reads
|
||||
* every closed code M4 and M5 raise (`raise exception '<code>'`, a lowercase
|
||||
* every closed code M4, M5 and M7 raise (`raise exception '<code>'`, a lowercase
|
||||
* dotted word; free-text messages are not codes) so a code added on the server
|
||||
* can never reach a page as `unavailable` for want of a kind.
|
||||
*/
|
||||
const SHEET_MIGRATIONS = [
|
||||
'20261028100000_sheet_access_hardening.sql',
|
||||
'20261028110000_sheet_review_workflow.sql',
|
||||
'20261102100000_sheet_admin_reads.sql',
|
||||
]
|
||||
|
||||
async function raisedCodes(): Promise<string[]> {
|
||||
|
||||
Reference in new issue
Block a user