@inglorious/supabase
v0.14.0
Published
Supabase integration for Inglorious Web, and helpers for Supabase Edge Functions.
Maintainers
Readme
@inglorious/supabase
Supabase integration for Inglorious Web.
- Realtime:
realtimeSourcetells entities that a table changed, so thatwithLiveReloadreloads them. - CAPTCHA:
createCaptchagives Supabase Auth the Turnstile tokens its CAPTCHA protection asks for. See CAPTCHA. - Edge Functions:
@inglorious/supabase/edgehas the helpers every function needs, from CORS to the caller's identity and sending email. See Edge Functions. - Secrets:
inglorious-supabasesets the linked project's function secrets fromsupabase/functions/.env, and its Vault secrets. See Secrets.
Install
pnpm add @inglorious/supabase @inglorious/web @supabase/supabase-jsRealtime
import { realtimeSource } from "@inglorious/supabase"
import { createClient } from "@supabase/supabase-js"
import { withLiveReload } from "@inglorious/web/decorators/with-live-reload"
export const supabase = createClient(url, publishableKey)
const live = realtimeSource(supabase)
const types = {
MessageList: [
MessageList,
withLiveReload({ source: live, tables: ["messages"] }),
],
}Each table must be in the supabase_realtime publication:
alter publication supabase_realtime add table public.messages;What it takes care of
Realtime is easy to get subtly wrong. realtimeSource handles these cases:
- One channel per table, shared by every entity that reads it, and closed with the last of them.
- Restored sessions. A channel joins only once the client's saved session is restored. One that joins while the session is still being restored, as a channel opened at boot does, joins as anonymous and stays that way. It still receives deletes, which skip RLS, but no inserts or updates.
- Dropped connections. When a channel joins again after losing its connection, it tells its subscribers, because whatever changed in between was missed.
Signing in and out later needs nothing: the client hands every channel the new token itself.
It says that a table changed, not how. Under RLS, a delete carries only the row's primary key, so matching changes to rows on screen is fragile. Reloading what the entity shows is not.
Options
realtimeSource(client, { schema }): schema defaults to "public".
Reaching a local backend from a phone
On a phone, 127.0.0.1 is the phone itself. backendUrl gives the backend's address as the page can reach it: when the app comes from a computer's dev server over the network, as with cap run --live-reload or vite --host, a local Supabase is reached at that computer's address. A hosted backend is left alone.
import { backendUrl } from "@inglorious/supabase"
import { createClient } from "@supabase/supabase-js"
export const supabase = createClient(
backendUrl(import.meta.env.VITE_SUPABASE_URL),
import.meta.env.VITE_SUPABASE_ANON_KEY,
)backendUrl(url, pageHost): pageHost defaults to location.hostname.
Network errors
isNetworkError(error) tells a call that never reached the server from one the server refused. Each client reports it differently: PostgREST returns { message: "TypeError: Failed to fetch" } (worded differently in every browser), Functions throws FunctionsFetchError, Auth AuthRetryableFetchError, and Storage wraps the failure in originalError.
import { isNetworkError } from "@inglorious/supabase"
const { data, error } = await supabase.from("messages").select()
if (error) throw isNetworkError(error) ? new Error("errors.offline") : errorPair it with the NetworkStatus sensor of @inglorious/web to tell people they are offline, and with withLiveReload, which reloads what is on screen when the connection comes back.
Sign-in
supabaseAuth is the adapter of createAuth from @inglorious/web/auth, over Supabase Auth: passwords, codes sent by email, password resets, and erasing the account through an Edge Function.
import { createCaptcha, supabaseAuth } from "@inglorious/supabase"
const captcha = createCaptcha({
siteKey: import.meta.env.VITE_TURNSTILE_SITE_KEY,
element: "captcha",
})
export const authAdapter = supabaseAuth(supabase, { captcha })What it takes care of
- Codes: sign-up confirmations, sign-in codes and password resets all take the 6-digit
{{ .Token }}of Supabase's email templates. Put it in the Confirm signup, Magic Link and Reset Password templates. - CAPTCHA: with
captcha, every call that signs in or sends an email carries a Turnstile token, and the challenge of the next step starts as soon as the email check knows it. Without a site key, no CAPTCHA is asked. - Links:
verifyLinksigns in with an email's{{ .TokenHash }}, for templates that offer a link next to the code. - The session:
onSessionChangereads the session after every Auth event, so a late event never brings back a session that is gone. A session restored from storage is checked with the server before its user is reported: if the account was erased since, on another device or by resetting a local backend, the app signs out instead of sending requests nobody can answer. Offline, the session stays. A session that can't be read, as when the Keychain or Keystore fails while the app starts, reports nothing, so the app is neither signed in nor out, and is read again shortly, waiting longer each time. - Errors:
errorCodeturns Supabase's error codes into the keyscreateAuthexpects, network failures and CAPTCHA refusals included.
Options
captcha: fromcreateCaptcha.accountExistsFunction: an Edge Function answering{ exists }for{ email }, so the screen skips straight to the password or to the new account. Rate-limit it: it tells anyone whether an email has an account.codeCreatesAccount: whether a sign-in code sent to an unknown email creates the account. Defaults totrue;falseleaves new accounts to sign-up, such as when it asks for a name or for the terms to be accepted.eraseFunction: the Edge Function that erases the caller's account. Defaults to"erase-account".
Erasing accounts
eraseUser from @inglorious/supabase/edge deletes a user and their files, with a client holding the service role key:
import {
currentUser,
env,
eraseUser,
json,
serve,
} from "npm:@inglorious/supabase@^0.13.0/edge"
import { createClient } from "npm:@supabase/supabase-js@2"
serve(async (req) => {
const db = createClient(env("SUPABASE_URL"), env("SUPABASE_SERVICE_ROLE_KEY"))
const user = await currentUser(db, req)
if (!user) return json({ error: "Not signed in" }, 401)
await eraseUser(db, user.id, { buckets: ["avatars"] })
return json({ erased: true })
})It empties the folder named after the user's id in each bucket, subfolders included, then deletes the user. Their rows go with them through on delete cascade foreign keys to auth.users.
Native app updates
supabaseNativeUpdate(client) is the adapter of createNativeUpdate from @inglorious/web/native/update: it reads each platform's minimum build from a table, so a release becomes mandatory with one update in the SQL editor, without a deploy.
create table public.app_versions (
platform text primary key check (platform in ('ios', 'android')),
min_build integer not null check (min_build >= 1),
store_url text
);
alter table public.app_versions enable row level security;
create policy "Anyone reads the minimum app versions"
on public.app_versions for select to anon, authenticated
using (true);
insert into public.app_versions (platform, min_build) values ('ios', 1), ('android', 1);import { supabaseNativeUpdate } from "@inglorious/supabase"
import { createNativeUpdate } from "@inglorious/web/native/update"
const NativeUpdate = createNativeUpdate({
adapter: supabaseNativeUpdate(supabase),
})update public.app_versions set min_build = 7 where platform = 'android';Raise a platform's minimum only once its new build is live in that store. Options: table (default "app_versions") and timeoutMs (default 10 seconds).
Live updates
@inglorious/supabase/live-update publishes the web code of a Capacitor app for createLiveUpdate from @inglorious/web/native/live-update. It runs in Node, from a release script.
import {
generateLiveUpdateKeys,
publishLiveUpdate,
} from "@inglorious/supabase/live-update"
const { privateKey, publicKey } = generateLiveUpdateKeys()
const manifest = await publishLiveUpdate({
dist: "dist",
release: Math.floor(Date.now() / 1000),
minBuild: 3,
privateKey,
projectUrl: "https://<ref>.supabase.co",
serviceKey,
})publishLiveUpdate zips dist, signs the zip the way @capawesome/capacitor-live-update checks it (RSA with SHA-256, base64), and uploads it to bundles/<release>.zip in a public bucket, live-updates by default, then manifest.json. Then it deletes all but the newest two zips (keepBundles changes how many): the manifest points only to the latest, and a bundle that fails rolls back to the app's own code, never to an older one. The previous zip stays for a device still downloading it. A failed cleanup only warns, since the update is out by then. packLiveUpdate does the zipping and signing alone. Keep the private key off the build server: whoever holds it can change the installed apps. The public key goes in the plugin's Capacitor config as publicKey.
liveUpdateManifestUrl(projectUrl), from the main entry, is the manifest's URL for the app.
The inglorious-live-update command
The same, ready to use from package.json:
{
"scripts": {
"build:release": "inglorious-live-update build",
"live:keys": "inglorious-live-update keys",
"live:release": "inglorious-live-update release"
},
"liveUpdate": { "minBuild": 1 }
}keyswrites the private key to~/.config/<package name>/live-update.pem, or toLIVE_UPDATE_PRIVATE_KEY, and the public key tolive-update.pub.pemin the project.buildrunsvite buildwith the values in.envover.env.local, stamped asVITE_LIVE_UPDATE_RELEASE: the time, in seconds. Use it for store builds too, so a store build never goes back to an older bundle.releasebuildsHEADfrom a clean git worktree, so uncommitted changes never ship, and publishes it for builds fromliveUpdate.minBuildup. It takes the project and its service role key from the Supabase CLI aftersupabase link, or fromSUPABASE_URLandSUPABASE_SERVICE_ROLE_KEY.release --on-push, in a pre-push hook, reads the refs git pushes on stdin and publishes only whenmaingets commits that touch the app: notdocs/,landing/,supabase/,.changeset/,.github/or Markdown alone. Without a key it says so and lets the push through.
printf '%s\n' "$(cat)" | pnpm exec inglorious-live-update release --on-pushCAPTCHA
With CAPTCHA protection on (Authentication → Attack Protection, provider Turnstile, with the widget's secret key), Supabase Auth refuses a signup, password login, magic link or confirmation resend without a valid token. createCaptcha makes those tokens:
import { createCaptcha, isCaptchaError } from "@inglorious/supabase"
const captcha = createCaptcha({
siteKey: import.meta.env.VITE_TURNSTILE_SITE_KEY,
element: "captcha",
language: () => currentLocale(),
})
// Once the login form shows:
captcha.prepare("login")
// On submit:
const { error } = await supabase.auth.signInWithPassword({
email,
password,
options: { captchaToken: await captcha.token("login") },
})
if (isCaptchaError(error)) showError("errors.captcha")element is where the widget goes, or its id, such as <div id="captcha"></div> under the form. Keep it on the page across the form's steps. The widget only shows when Turnstile needs the person to act; otherwise it solves the challenge out of sight.
What it takes care of
- Single use. A token works once, so each
token(action)gets a new one, and each widget is removed once it answers. - Waiting. A challenge takes a moment.
prepare(action)starts it while the person types;token(action)then uses that token if it is for the same action and younger than Turnstile's five minutes, and otherwise makes a new one. - The script. Cloudflare's script loads on the first token, once per page.
- No site key. Without one, as on a local stack, it loads nothing and every token is
undefined, which Supabase Auth accepts while CAPTCHA protection is off.
isCaptchaError(error) is true for the widget's own CaptchaError, whose code is Turnstile's, and for Supabase Auth refusing the token with captcha_failed.
Turning it on
Turn on CAPTCHA protection only once every client sends tokens: apps in the stores built without the site key can no longer sign in or sign up from then on, though sessions already open carry on.
- The content security policy needs
https://challenges.cloudflare.cominscript-srcandframe-src. - The widget's hostnames in Cloudflare need the site's domain, plus
localhostfor Capacitor apps, which run there.
Secrets
The inglorious-supabase command sets a linked project's secrets (after supabase link), with the Supabase CLI, version 3 or later:
{
"scripts": {
"secrets:push": "inglorious-supabase secrets",
"vault:push": "inglorious-supabase vault"
}
}inglorious-supabase secretssets the Edge Function secrets insupabase/functions/.env, then reads back the fingerprints Supabase keeps of them and printsokorDIFFfor each, failing on a difference. Name some to set only those:inglorious-supabase secrets FCM_SERVICE_ACCOUNT.inglorious-supabase vaultstoresproject_urland the legacyservice_role_keyin Vault, for SQL that calls Edge Functions withpg_net, such as a trigger that sends a push. The key comes from the Supabase CLI's login, so it is never written down.
Both write the values to a private temporary file for the Supabase CLI, never to its arguments, and delete it afterwards. Running either is the confirmation the CLI asks for before it changes a hosted project: they pass it --yes.
Edge Functions
@inglorious/supabase/edge is for functions running on Supabase's Deno runtime. It imports nothing, supabase-js included, so a function pays only for what it uses:
import {
currentUser,
env,
json,
serve,
} from "npm:@inglorious/supabase@^0.13.0/edge"
import { createClient } from "npm:@supabase/supabase-js@2"
const admin = () =>
createClient(env("SUPABASE_URL"), env("SUPABASE_SERVICE_ROLE_KEY"))
serve(
async (req) => {
const user = await currentUser(admin(), req)
if (!user) return json({ error: "Not signed in" }, 401)
return json({ id: user.id })
},
{ fallbackError: "Could not load the profile" },
)serve(handler, { fallbackError })andhandle(handler, options): answer the CORS preflight, and turn a thrown error into{ error }with status 500 and CORS headers, so the browser reads the message instead of a CORS failure.servecallsDeno.serve;handlereturns the wrapped handler, for tests.json(body, status, headers): a JSON response with CORS headers.env(name): an environment variable that must be set. It throws, naming it, when it is not.currentUser(client, req): the signed-in caller, from their access token and never from the body. Pass a client with the service role key.callerRole(req)andbearerToken(req): the token'sroleclaim, such as"service_role"for a call from the database, and the token itself. The role is read without checking the signature, which the platform checks before the function runs unlessverify_jwtis off. Only the legacy JWT keys carry a role;sb_secret_keys do not.upstreamError(service, res): an error for a failed call to another API, with the first 200 characters of its answer.clientIp(req): the caller's IP address, for limits per address, ornull. It reads Cloudflare'scf-connecting-ip, which fronts hosted Supabase, before the firstx-forwarded-forentry, which the caller writes: a limit keyed on that entry is one anyone can skip.isLocalStack(url): whetherSUPABASE_URLis the local stack's, to skip outside services in development.
sendEmail(email, { apiKey, from }) sends one email through Resend; sendEmails(emails, { apiKey, from }) sends up to 100 in a single request, so a rate limit never splits them: they go out or fail together. Either throws an EmailError whose status is Resend's, where 429 means the rate or daily limit was reached. An email is { to, subject, text, html, headers }; headers can carry List-Unsubscribe.
import {
env,
isLocalStack,
sendEmail,
} from "npm:@inglorious/supabase@^0.13.0/edge"
if (!isLocalStack(env("SUPABASE_URL"))) {
await sendEmail(
{ to: "[email protected]", subject: "Welcome", text: "Hello!" },
{ apiKey: env("RESEND_API_KEY"), from: "App <[email protected]>" },
)
}