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:
bchanot committed 2026-11-02 16:31:50 +01:00
1 parent a79e1f0af7
commit c9ace9aff2
7 files changed
+1126 -6

No files matched your search

+37
View File
@@ -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,
+187
View File
@@ -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) }
}
+329 -5
View File
@@ -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())
}