feat(supabase): auth, profile and roles services; professional columns on profiles; OAuth + TOTP config

- packages/supabase: signIn/signUp/OAuth/reset/updatePassword/signOut wrappers with a closed AuthFailure kind, fetch/update own profile, own platform roles
- migration 20261011100000: practice_name, professional_title, siret (format-checked, column grants); pgTAP 009; database.types regenerated
- config.toml: TOTP enroll/verify on, [auth.external.google|apple] via env(), wildcard redirect URLs
- app config: authProviders (APP_AUTH_PROVIDERS / VITE_AUTH_PROVIDERS), entrypoint env.js, DEPLOY table
- TODO: Step 7 plan
This commit is contained in:
bchanot committed 2026-10-11 23:16:13 +02:00
1 parent c746952d7f
commit b10b227ee9
13 files changed
+427 -10

No files matched your search

+154
View File
@@ -0,0 +1,154 @@
import type { AuthError, Provider, Session, User } from '@supabase/supabase-js'
import type { FaunosteoClient } from './client'
/** OAuth providers the app may offer. Phone and others wait for later steps. */
export type OAuthProvider = Extract<Provider, 'google' | 'apple'>
/**
* Closed set of reasons the UI knows how to phrase. Everything GoTrue reports
* is folded into one of these; the raw message never reaches the screen.
*/
export type AuthFailureKind =
| 'invalid_credentials'
| 'email_not_confirmed'
| 'user_exists'
| 'weak_password'
| 'same_password'
| 'invalid_email'
| 'rate_limited'
| 'link_expired'
| 'session_expired'
| 'provider_disabled'
| 'network'
| 'unknown'
export class AuthFailure extends Error {
readonly kind: AuthFailureKind
constructor(kind: AuthFailureKind, cause?: unknown) {
super(`auth: ${kind}`, { cause })
this.name = 'AuthFailure'
this.kind = kind
}
}
const CODE_TO_KIND: Record<string, AuthFailureKind> = {
invalid_credentials: 'invalid_credentials',
email_not_confirmed: 'email_not_confirmed',
user_already_exists: 'user_exists',
email_exists: 'user_exists',
weak_password: 'weak_password',
same_password: 'same_password',
email_address_invalid: 'invalid_email',
validation_failed: 'invalid_email',
over_request_rate_limit: 'rate_limited',
over_email_send_rate_limit: 'rate_limited',
otp_expired: 'link_expired',
flow_state_not_found: 'link_expired',
flow_state_expired: 'link_expired',
bad_code_verifier: 'link_expired',
session_expired: 'session_expired',
session_not_found: 'session_expired',
refresh_token_not_found: 'session_expired',
provider_disabled: 'provider_disabled',
oauth_provider_not_supported: 'provider_disabled',
email_provider_disabled: 'provider_disabled',
signup_disabled: 'provider_disabled',
}
/** Maps a GoTrue error to a closed kind; code first, HTTP status as fallback. */
export function classifyAuthError(error: AuthError): AuthFailureKind {
const code = (error as { code?: string }).code
if (code && CODE_TO_KIND[code]) return CODE_TO_KIND[code]
if (error.status === 429) return 'rate_limited'
if (error.status === 400 && /invalid login/i.test(error.message)) {
return 'invalid_credentials'
}
if (error.status === undefined || error.status === 0) return 'network'
return 'unknown'
}
function fail(error: AuthError): never {
throw new AuthFailure(classifyAuthError(error), error)
}
export interface EmailPasswordCredentials {
email: string
password: string
}
export interface SignUpInput extends EmailPasswordCredentials {
displayName: string
/** Stored in user metadata; the profile trigger reads it. */
locale: 'fr' | 'en'
/** Absolute URL the confirmation link lands on. */
emailRedirectTo: string
}
export interface SignUpResult {
/** Null while the email is not confirmed (confirmations enabled). */
session: Session | null
user: User | null
}
export async function signInWithPassword(
client: FaunosteoClient,
credentials: EmailPasswordCredentials,
): Promise<Session> {
const { data, error } = await client.auth.signInWithPassword(credentials)
if (error) fail(error)
return data.session
}
export async function signUpWithPassword(
client: FaunosteoClient,
input: SignUpInput,
): Promise<SignUpResult> {
const { data, error } = await client.auth.signUp({
email: input.email,
password: input.password,
options: {
emailRedirectTo: input.emailRedirectTo,
data: { display_name: input.displayName, locale: input.locale },
},
})
if (error) fail(error)
return { session: data.session, user: data.user }
}
/** Starts the redirect flow; the browser leaves the page on success. */
export async function signInWithOAuth(
client: FaunosteoClient,
provider: OAuthProvider,
redirectTo: string,
): Promise<void> {
const { error } = await client.auth.signInWithOAuth({
provider,
options: { redirectTo },
})
if (error) fail(error)
}
export async function sendPasswordReset(
client: FaunosteoClient,
email: string,
redirectTo: string,
): Promise<void> {
const { error } = await client.auth.resetPasswordForEmail(email, {
redirectTo,
})
if (error) fail(error)
}
/** Needs a live session (recovery link or signed-in user). */
export async function updatePassword(
client: FaunosteoClient,
password: string,
): Promise<void> {
const { error } = await client.auth.updateUser({ password })
if (error) fail(error)
}
export async function signOut(client: FaunosteoClient): Promise<void> {
const { error } = await client.auth.signOut()
if (error) fail(error)
}
+9
View File
@@ -306,6 +306,9 @@ export type Database = {
locale: string
phone: string | null
phone_verified_at: string | null
practice_name: string | null
professional_title: string | null
siret: string | null
timezone: string
updated_at: string
}
@@ -320,6 +323,9 @@ export type Database = {
locale?: string
phone?: string | null
phone_verified_at?: string | null
practice_name?: string | null
professional_title?: string | null
siret?: string | null
timezone?: string
updated_at?: string
}
@@ -333,6 +339,9 @@ export type Database = {
locale?: string
phone?: string | null
phone_verified_at?: string | null
practice_name?: string | null
professional_title?: string | null
siret?: string | null
timezone?: string
updated_at?: string
}
+23 -3
View File
@@ -15,12 +15,32 @@ export { Constants } from './database.types'
import type { Enums, Tables } from './database.types'
/** Row of public.profiles. */
export type Profile = Tables<'profiles'>
/** Row of public.profile_roles. */
export type ProfileRole = Tables<'profile_roles'>
export {
AuthFailure,
classifyAuthError,
sendPasswordReset,
signInWithOAuth,
signInWithPassword,
signOut,
signUpWithPassword,
updatePassword,
type AuthFailureKind,
type EmailPasswordCredentials,
type OAuthProvider,
type SignUpInput,
type SignUpResult,
} from './auth'
export {
fetchOwnProfile,
ProfileError,
updateOwnProfile,
type OwnProfilePatch,
type Profile,
} from './profiles'
/** owner | admin | moderator | support. Not a professional status. */
export type PlatformRole = Enums<'platform_role'>
export { fetchOwnPlatformRoles, type PlatformRole } from './platform-roles'
export { publishSheetVersion } from './anatomical-sheets'
/** Row of public.species. */
+18
View File
@@ -0,0 +1,18 @@
import type { FaunosteoClient } from './client'
import type { Enums } from './database.types'
export type PlatformRole = Enums<'platform_role'>
/** Active platform roles of the signed-in user (RLS: own rows, or any as admin). */
export async function fetchOwnPlatformRoles(
client: FaunosteoClient,
userId: string,
): Promise<PlatformRole[]> {
const { data, error } = await client
.from('profile_roles')
.select('role')
.eq('user_id', userId)
.is('revoked_at', null)
if (error) throw new Error(error.message, { cause: error })
return data.map((row) => row.role)
}
+55
View File
@@ -0,0 +1,55 @@
import type { FaunosteoClient } from './client'
import type { Tables, TablesUpdate } from './database.types'
export type Profile = Tables<'profiles'>
/** Columns the signed-in user may change (column grant in the profiles migrations). */
export type OwnProfilePatch = Pick<
TablesUpdate<'profiles'>,
| 'display_name'
| 'first_name'
| 'last_name'
| 'phone'
| 'locale'
| 'timezone'
| 'practice_name'
| 'professional_title'
| 'siret'
>
export class ProfileError extends Error {
readonly code: string | null
constructor(message: string, code: string | null, cause?: unknown) {
super(message, { cause })
this.name = 'ProfileError'
this.code = code
}
}
/** The row RLS lets the user see: their own. Null when the trigger has not run yet. */
export async function fetchOwnProfile(
client: FaunosteoClient,
userId: string,
): Promise<Profile | null> {
const { data, error } = await client
.from('profiles')
.select('*')
.eq('id', userId)
.maybeSingle()
if (error) throw new ProfileError(error.message, error.code, error)
return data
}
export async function updateOwnProfile(
client: FaunosteoClient,
userId: string,
patch: OwnProfilePatch,
): Promise<Profile> {
const { data, error } = await client
.from('profiles')
.update(patch)
.eq('id', userId)
.select('*')
.single()
if (error) throw new ProfileError(error.message, error.code, error)
return data
}