Files
faunosteo/packages/supabase/src/auth.ts
T
bchanot b10b227ee9 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
2026-10-11 23:16:13 +02:00

155 lines
4.5 KiB
TypeScript

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)
}