// Production deploy job sync_hosted_auth_signups: applies three private.settings switches to // the hosted Supabase Auth through the Management API (GET/PATCH /v1/projects/{ref}/config/auth): // SUPABASE_HOSTED_GOTRUE_NEW_SIGNUPS_ENABLED new sign-ups (disable_signup, inverted) // SUPABASE_HOSTED_GOTRUE_EMAIL_PROVIDER_ENABLED Email provider (external_email_enabled) // SUPABASE_HOSTED_GOTRUE_SAML_ENABLED SAML (saml_enabled) // Each switch takes the same values and is handled on its own: // skip_dont_read not read from the Management API // skip log the current value, change nothing // true / false turn it on / off, only with an Owner or Administrator token // Missing or unknown value: one warning, that switch is left alone. // One read of private.settings, one GET of the auth config (only when a switch needs it), and // at most one PATCH holding only the fields that need changing. // // The logs are public. Never log a response body (GET /config/auth holds Auth secrets), // the token, or the user behind it. Problems are `::warning::` lines with the HTTP status // only. It never fails a deploy: main never throws and the CLI always exits 0. import process from 'node:process' type AuthKey = 'disable_signup' | 'external_email_enabled' | 'saml_enabled' type Value = 'skip' | 'true' | 'false' interface Field { setting: string key: AuthKey label: string // true when the auth config field means "off" (disable_signup: true = sign-ups off) inverted: boolean } export const FIELDS: readonly Field[] = [ { setting: 'SUPABASE_HOSTED_GOTRUE_NEW_SIGNUPS_ENABLED', key: 'disable_signup', label: 'sign-ups', inverted: true }, { setting: 'SUPABASE_HOSTED_GOTRUE_EMAIL_PROVIDER_ENABLED', key: 'external_email_enabled', label: 'Email provider', inverted: false }, { setting: 'SUPABASE_HOSTED_GOTRUE_SAML_ENABLED', key: 'saml_enabled', label: 'SAML', inverted: false }, ] export const SETTING_NAMES = FIELDS.map(f => f.setting) const API = 'https://api.supabase.com' const REQUEST_TIMEOUT_MS = 20_000 const ADMIN_ROLES = new Set(['owner', 'administrator']) const VALUES = new Set(['skip', 'true', 'false']) export interface Deps { env: Record fetch: typeof fetch // One read of private.settings: the value of each of SETTING_NAMES that exists. readSettings: (databaseUrl: string) => Promise> log: (line: string) => void } class Stop extends Error {} const state = (enabled: boolean): string => enabled ? 'enabled' : 'disabled' export async function main(deps: Deps): Promise { const token = deps.env.SUPABASE_TOKEN?.trim() const ref = deps.env.SUPABASE_PROJECT_ID_PROD?.trim() const info = (message: string): void => { deps.log(`hosted-auth-signups: ${message}`) } const warn = (message: string): void => { deps.log(`::warning::hosted-auth-signups: ${message}`) } const stop = (message: string): never => { warn(message) throw new Stop() } async function call(method: 'GET' | 'PATCH', path: string, what: string, body?: unknown): Promise { let res: Response try { res = await deps.fetch(`${API}${path}`, { method, headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), }) } catch (error) { return stop(`${what} failed (${errorName(error)})`) } if (!res.ok) stop(`${what} failed (HTTP ${res.status})`) return res } async function readJson(res: Response, what: string): Promise { try { return await res.json() as T } catch { return stop(`${what} returned an unreadable response`) } } async function readRole(): Promise { try { const profile = await readJson<{ gotrue_id?: string }>(await call('GET', '/v1/profile', 'GET /v1/profile'), 'GET /v1/profile') const project = await readJson<{ organization_slug?: string }>(await call('GET', `/v1/projects/${ref}`, 'GET /v1/projects/{ref}'), 'GET /v1/projects/{ref}') if (!project.organization_slug) return 'unknown' const members = await readJson<{ user_id?: string, role_name?: string }[]>( await call('GET', `/v1/organizations/${encodeURIComponent(project.organization_slug)}/members`, 'GET /v1/organizations/{slug}/members'), 'GET /v1/organizations/{slug}/members', ) const member = Array.isArray(members) && profile.gotrue_id ? members.find(m => m.user_id === profile.gotrue_id) : undefined return member?.role_name ?? 'not a member' } catch (error) { if (error instanceof Stop) return 'unknown' throw error } } // Whether each field is on, keyed by setting name. Keeps only these booleans: the rest of // the response is Auth secrets. async function readEnabled(): Promise> { const config = await readJson> | null>(await call('GET', `/v1/projects/${ref}/config/auth`, 'GET /config/auth'), 'GET /config/auth') const enabled = new Map() for (const field of FIELDS) { const raw = config?.[field.key] if (typeof raw === 'boolean') enabled.set(field.setting, field.inverted ? !raw : raw) } return enabled } // The switches that need the Management API, after warning about missing or unknown ones. function parseSettings(values: Record): { field: Field, value: Value }[] { const active: { field: Field, value: Value }[] = [] for (const field of FIELDS) { const value = values[field.setting]?.trim() if (value === undefined) warn(`${field.setting} is missing from private.settings, left alone`) else if (value === 'skip_dont_read') info(`${field.setting}=skip_dont_read, not read`) else if (!VALUES.has(value)) warn(`${field.setting} has an unknown value (expected skip_dont_read, skip, true or false), left alone`) else active.push({ field, value: value as Value }) } return active } try { const databaseUrl = deps.env.DATABASE_URL_PROD?.trim() if (!databaseUrl) stop('DATABASE_URL_PROD is not set, nothing done') let values: Record try { values = await deps.readSettings(databaseUrl!) } catch (error) { return stop(`reading private.settings failed (${errorName(error)}), nothing done`) } const active = parseSettings(values) if (active.length === 0) return info('no Management API call') if (!token) stop('SUPABASE_TOKEN is not set, nothing done') if (!ref) stop('SUPABASE_PROJECT_ID_PROD is not set, nothing done') const role = await readRole() info(`Management API token role: ${role}`) const before = await readEnabled() const writes: { field: Field, value: Value, enabled: boolean }[] = [] for (const { field, value } of active) { const enabled = before.get(field.setting) if (enabled === undefined) { warn(`GET /config/auth has no ${field.key}, ${field.setting} left alone`) continue } info(`hosted Auth ${field.label}: ${state(enabled)}`) if (value === 'skip') info(`${field.setting}=skip, nothing changed`) else writes.push({ field, value, enabled }) } if (writes.length === 0) return if (!ADMIN_ROLES.has(role.toLowerCase())) stop(`${writes.map(w => `${w.field.setting}=${w.value}`).join(', ')} needs an Owner or Administrator token (role: ${role}), nothing changed`) const changes = writes.filter(w => w.enabled !== (w.value === 'true')) for (const w of writes.filter(w => !changes.includes(w))) info(`${w.field.setting}=${w.value}, already set, nothing changed`) if (changes.length === 0) return const body = Object.fromEntries(changes.map(c => [c.field.key, c.field.inverted ? c.value === 'false' : c.value === 'true'])) await call('PATCH', `/v1/projects/${ref}/config/auth`, 'PATCH /config/auth', body) const after = await readEnabled() for (const c of changes) { const want = c.value === 'true' if (after.get(c.field.setting) !== want) warn(`PATCH /config/auth succeeded but ${c.field.label} is not ${state(want)}`) else info(`hosted Auth ${c.field.label} changed to ${state(want)}`) } } catch (error) { if (!(error instanceof Stop)) warn(`unexpected error (${errorName(error)}), nothing more done`) } } function errorName(error: unknown): string { return error instanceof Error ? error.name : 'unknown error' } async function readSettingsFromDb(databaseUrl: string): Promise> { // Imported here so a load failure is caught by main instead of failing the job. const { connectScriptDb } = await import('./script_db.ts') const client = await connectScriptDb(databaseUrl) try { const { rows } = await client.query<{ name: string, value: string | null }>('SELECT name, value FROM private.settings WHERE name = ANY($1)', [SETTING_NAMES]) return Object.fromEntries(rows.map(r => [r.name, r.value])) } finally { await client.end() } } if (import.meta.main) { main({ env: process.env, fetch: globalThis.fetch, readSettings: readSettingsFromDb, log: line => console.log(line) }) .catch(() => console.log('::warning::hosted-auth-signups: unexpected error, nothing more done')) .finally(() => process.exit(0)) }