Authentication
NukeBase provides a built-in cookie-based authentication system. When you configure
authPath: ["users"]
in your domain setup, authentication endpoints are automatically available and cookies are handled
seamlessly.
How it works:
- Configure
authPath: ["users"]in your domain setup - Use the built-in authentication endpoints from your client
- Server automatically sets HTTP cookies (uid, token)
- WebSocket connections automatically use these cookies
- User information populates the
adminobject for security rules
What's in core, and what's an extension
Configuring authPath turns on the parts of authentication that every sign-in method needs, regardless of how the user proved who they are:
- Session validation —
checkAuthreads theuid/tokencookies on every request and WebSocket upgrade, and populatesadmin. - POST /logout — revokes the active session and closes any WebSocket connections opened with it; the next parked account, if any, becomes active. Also signs out one parked account or every account — see Several accounts in one browser.
- POST /accounts and POST /switch — list the accounts signed in on this browser, and move between them.
- The session frame — the first message on every WebSocket says who the socket is, which is what
client.authreads. issueSession(uid, admin, opts)— the one function that mints a browser session, used by every extension; see below if you write your own sign-in route.- Hourly token cleanup — expired entries are swept from
auth.tokensautomatically.
The endpoints that create a session are opt-in extensions you mount from app.js. Pick the one that matches how you want people to sign in — or mount more than one; they all mint the same session cookies and share the same user records.
| Extension | Adds | Needs |
|---|---|---|
extensions/auth |
POST /login, POST /changepassword |
Nothing — username + password, hashed with argon2id |
extensions/easy-login |
POST /auth/email, GET /auth/callback, POST /auth/me |
Nothing — passwordless email links delivered by NukeBase's hosted mail service |
extensions/magic-link |
POST /magic-link, POST /magic-signup, GET /magiclink |
Your own Mailgun API key, sending domain and sender address |
const nukebase = addDomain({ authPath: ["users"] });
// Enables /login and /changepassword.
// (/createuser ships commented out — accounts are created by the email flows.)
// Omit this and your app is passwordless — /logout and session
// validation keep working either way.
require("./extensions/auth")({
app: nukebase.app,
authPath: nukebase.authPath,
get, set, update, remove, query, generateRequestId, hashToken, issueSession,
sessionTokenTtlMs: 24 * 60 * 60 * 1000 // optional, default 24h
});
Not mounted means not routed. If extensions/auth isn't mounted, a POST /login falls through to the static handler and returns 404 — the client SDK's login() will fail on JSON parsing rather than telling you the endpoint is missing. Same for createUser(), changePassword() and magicLink().
Authentication Endpoints
The endpoints below are provided by the extensions in the table above.
Available Endpoints:
- POST /login - Login with username/password, or resume session via cookies (can also upgrade a demo account that has not yet set credentials by providing username/password — the username must not already be taken, and the password must be 8–128 characters). Requires the
authextension. - POST /createuser — currently disabled. The route is commented out in
extensions/auth.js: account creation is email-only. UsePOST /auth/email(easy-login) orPOST /magic-signup(magic-link) instead, both of which create the account on first sign-in. The SDK'screateUser()will get a 404 until you uncomment it. - POST /magic-signup - Create a passwordless account (email only; body
{ email }). The server emails a magic-link sign-in; the account is created when the link is clicked, which is what proves the address belongs to the person signing up. The user is NOT logged in by this call. Requires the magic-link extension. - POST /logout - Revoke the active session; the next parked account takes over, or the browser is anonymous. Body
{ uid }signs out one parked account,{ all: true }every account. Built into the engine — always available onceauthPathis set, no extension required. - POST /accounts / POST /switch
{ uid }- The accounts signed in on this browser, and switching between them. Built into the engine — see Several accounts in one browser. - POST /changepassword - Change user password (requires an active password-backed session). Requires the
authextension. - POST /auth/email - Email a sign-in link using NukeBase's hosted mail service — no email provider of your own. Requires the easy-login extension.
- GET /auth/callback?code=... - Landing URL for an easy-login link. Serves a small page that finishes the sign-in with POST /auth/callback
{ code }, which verifies the code, finds or creates the account, sets the session cookies and answers{ status, location }; the page then goes tolocation. The extra step is a same-origin request, so the browser sends the cookies of the account it is already signed in as (they areSameSite=Strict, and a link clicked in a webmail tab arrives without them) and that account is parked rather than replaced. - POST /auth/me - Returns
{ email }for the current session, or{ email: null }. Requires the easy-login extension. - POST /magic-link - Email a one-time sign-in link to an existing account (15-minute expiry). See Magic Link Authentication.
- GET /magiclink?token=... - Public landing URL the magic-link email points to. Serves a small page that finishes the sign-in with POST /magiclink
{ token }, which validates the token, sets the session cookies and answers{ status, location }; the page then goes toredirectPath(configured when mounting the extension).
Cookies set on success: all auth endpoints that establish a session set two cookies — uid and token — with attributes HttpOnly; Secure; SameSite=Strict; Path=/ and a Max-Age equal to the session's life (24 hours by default, backed by a server-side hashed token). A third cookie, accounts, with the same attributes, holds the sessions of the other accounts signed in on the browser — see Several accounts in one browser. /logout sets Max-Age=0 on whatever it clears.
Because Secure is required, the cookies will not be set over plain http://. Use https:// in production and http://localhost in development (browsers exempt localhost from the Secure requirement).
Built-in security — you don't need to add these yourself:
- Rate limiting: 5 attempts per 60-second window per client IP on
/login,/magic-link,/magic-signupand/auth/email(each extension keeps its own budget). A successful login clears the limiter for that IP. - Argon2 password hashing: passwords are stored as argon2id hashes. Plaintext passwords from legacy data are auto-migrated on first successful login.
- SHA-256 hashed session tokens: the cookie holds the raw token, but only its SHA-256 hash is stored under
auth.tokens. A leak of the database does not leak usable session tokens. - Hourly token cleanup: a background job sweeps expired entries from
auth.tokens; each extension sweeps its own rate-limit map every five minutes. No manual housekeeping is required. - Username enumeration resistance:
/magic-linkreturns the same response whether or not the address corresponds to an existing account.
Username and password format constraints:
- Username (
/login): matches/^[a-z0-9_.]{1,32}$/— lowercase letters, digits, underscore and dot, up to 32 characters. No@, so a password-login username is a handle, not an email address. - Password: 8–128 characters, enforced on
/changepassword. - Email (the passwordless flows): a normal address pattern —
+, uppercase and long domains are all accepted. Addresses are lowercased before lookup, and stored underauth.emailrather thanauth.username.
The two identity fields are separate. Password login looks a user up by auth.username; both email flows look them up by auth.email. A user created by an email flow has no username and cannot sign in through /login, and vice versa — unless you populate both fields yourself.
Behind a reverse proxy? Nothing to configure. The engine decides whether to believe x-real-ip / x-forwarded-for from where the connection actually came from: a Unix socket or a private/loopback peer means a proxy you put there and the header is honored; a public peer address means the open internet and the header is ignored in favour of the peer. A client on a public port therefore cannot rotate headers to reset its own login budget. See Environment Variables for the TRUST_PROXY override, which exists only for unusual topologies.
Login
Use the /login endpoint to login with a username and password. If valid auth cookies are already on the request, the session is resumed automatically — no DB lookup against the password. The endpoint can also upgrade a demo account: if the cookie-session belongs to an account that has no username and no password yet (i.e. a true demo account that has never been upgraded), passing (username, password) attaches credentials to that same UID. The username must not belong to any other account (the call answers "That username is taken"), since password login finds a user by username. Once an account has a username or password, this upgrade path is no longer available — subsequent calls just resume the existing session.
// Import and destructure the methods you need
import createClient from './sdkmod.js';
const { login } = await createClient();
// Login with username and password
const result = await login("username", "password");
if (result && result.status === "Success") {
console.log('Authenticated as:', result.username);
}
// Resume session (if cookies are already set)
const result2 = await login();
if (result2 && result2.status === "Success") {
console.log('Session resumed:', result2.uid);
}
// Upgrade a demo account to a full account
// Preconditions: valid demo cookies AND the account currently has
// no username and no password set. After the first upgrade, calling
// login(...) again just resumes the existing session — it will not
// overwrite the username/password.
const result3 = await login("newUsername", "newPassword");
if (result3 && result3.status === "Success") {
console.log('Demo account upgraded:', result3.username);
}
Create Account
/createuser is commented out in extensions/auth.js as shipped, so everything in this section is inert until you uncomment it. Accounts are created by the email flows instead — /auth/email or /magic-signup — both of which create the user on first sign-in with no separate signup step.
If you re-enable it, /createuser supports:
- No arguments — creates a demo (anonymous) account and immediately logs the user in.
- Username + password — creates a full account and immediately logs the user in.
Both modes fail with "Already signed in, logout first" if the caller already has a valid session cookie. For passwordless (email-only) signup, use POST /magic-signup instead — see Magic Link Authentication.
import createClient from './sdkmod.js';
const { createUser } = await createClient();
// Create a demo/anonymous account (no credentials) — logs in immediately
const result = await createUser();
if (result && result.status === "Success") {
console.log('Demo account created:', result.uid);
}
// Create a full account with username and password — logs in immediately
const result2 = await createUser("myUsername", "myPassword");
if (result2 && result2.status === "Success") {
console.log('Account created:', result2.username);
}
// Note: Fails if already signed in - logout first
// For passwordless signup, use POST /magic-signup instead
Logout
Sign the active account out. If another account is signed in on this browser it becomes the active one; otherwise the browser is anonymous. The SDK reconnects by itself:
import createClient from './sdkmod.js';
const client = await createClient();
const result = await client.logout();
if (result && result.status === "Success") {
console.log('Signed out; now acting as', result.active); // the next account's uid, or null
}
// One parked account, or everything signed in on this browser:
await client.auth.logout({ uid: "someOtherUid" });
await client.auth.logout({ all: true });
Several accounts in one browser
A browser can be signed in to more than one account at once. Exactly one is active — the one the uid and token cookies name, the one every request and socket acts as — and the others are parked in a third HttpOnly cookie, accounts, as their own uid and session token. A parked session is an ordinary entry in that user's auth.tokens, with its own expiry; the cookie is only where the browser keeps the raw token. Nothing about how identity is checked changes, which is why rules, sockets, the file store and the CLI need no knowledge of it.
Signing in while an account is active adds the new account and parks the old one — through every sign-in method, because every one of them mints the session through the engine's issueSession. Switching needs no password or link: the parked token is the proof.
const client = await createClient();
// Who am I? Known as soon as createClient resolves (the socket's first frame).
console.log(client.auth.uid); // "p90h…" or null
client.auth.onAuth((me) => render(me)); // now, and on every change
// Everyone signed in on this browser, the active one first. Never the tokens.
const { accounts } = await client.auth.accounts();
// [{ uid, email, username, active: true }, { uid, email, username, active: false }, …]
// Make a parked account the active one. The socket reconnects as it,
// every other tab of this app follows, and the page cache is emptied.
await client.auth.switch(accounts[1].uid);
// Sign the active account out: the next parked one takes over.
await client.auth.logout();
// Sign one parked account out, leaving the active one alone:
await client.auth.logout({ uid });
// Everything, in one go:
await client.auth.logout({ all: true });
What a switch or sign-out does on the client, besides reconnecting: every other open tab of the app on this browser reconnects too (over a BroadcastChannel), so no tab keeps acting as the old account; the service worker's page cache is emptied, because it is keyed by URL alone and a page one account saw must not be shown to the next (the following loads refill it); and with offline mode on, the cache that belongs to the new account is opened — see one cache per account.
Writing your own sign-in route? Mint the session with issueSession(uid, admin, opts) from the engine API rather than setting cookies yourself. It writes the token and its Signed-in devices record, parks the account the browser already holds, and hands back the cookies: const s = await issueSession(uid, req.admin, { ttlMs }); s.setCookies(res); — call setCookies inside the same cork as writeStatus/end, or before res.send on a postWithBody route. On a raw route, call checkAuth(req, res) before any await and pass the result as admin. Options: ttlMs (session life), maxAgeSeconds (cookie life, default the session's), kind (the devices record's, default "web"), ua. sessionAccounts(admin) returns what /accounts would, and revokeSession(uid, token) ends one.
Limits and safety. At most eight parked accounts (ACCOUNTS_MAX), oldest out first. The wallet is pruned on every read: a parked session that expired or was revoked elsewhere simply disappears from accounts(). A /switch to a uid the wallet holds no live token for is refused, so a forged cookie cannot reach an account. Signing in again to an account that is already parked replaces and revokes its parked session. A socket opened as the old account keeps that identity until it reconnects, which the SDK does on its own; revoking a session (sign-out) closes its sockets at once. Every cookie stays HttpOnly; Secure; SameSite=Strict, so a stolen cookie jar is the same class of risk as before, multiplied by the accounts in it — keep sessions short where that matters.
Change Password
Allow authenticated users to change their password:
import createClient from './sdkmod.js';
const { changePassword } = await createClient();
const result = await changePassword("newPassword123");
if (result && result.status === "Success") {
console.log('Password changed successfully');
} else {
console.log('Failed to change password');
}
Easy Login — passwordless email, no mail provider
The easy-login extension gives you passwordless email sign-in without setting up SendGrid, Mailgun or any provider of your own. NukeBase delivers the sign-in emails on your behalf (billed to your project) and tells your server which address clicked the link. Everything else stays yours: the accounts live under your authPath, and the sessions are your app's sessions.
const nukebase = addDomain({ authPath: ["users"] });
require("./extensions/easy-login")({
app: nukebase.app,
authPath: nukebase.authPath,
get, set, query, generateRequestId, hashToken, issueSession, checkAuth,
redirectPath: "/dashboard", // optional, default "/"
brandName: "Acme", // optional, shown in the email
sessionTokenTtlMs: 24 * 60 * 60 * 1000 // optional, default 24h
});
// 1. Ask for a link
const r = await fetch("/auth/email", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: "matt@example.com" })
});
const { status, message } = await r.json();
// Always the same generic response, whether or not the account exists
// 2. The user clicks the link in their inbox. It lands on
// /auth/callback?code=..., a page that posts the code back to
// /auth/callback; that creates the account if it's new, sets the
// session cookies, and the page goes on to redirectPath.
// 3. Anywhere after that:
const me = await (await fetch("/auth/me", { method: "POST" })).json();
// → { email: "matt@example.com", uid: "…" } or { email: null, uid: null }
// (or simply client.auth.current — the SDK already knows)
// 4. Sign out with the core endpoint
await client.auth.logout();
// A second address signed in from the same browser is ADDED, not swapped in:
// client.auth.accounts() lists both and client.auth.switch(uid) moves between them.
Credentials come from the "nukebase" section of package.json (api, uid, project, mailKey), written when the project was created. Projects created before 2.1 carry the same values in sys/config.json, read when package.json has no section. The mailKey is a scoped NukeBase token that can only send sign-in emails for this project — it is not a mail-provider key, and it is fixed for the project's life (it is never rotated, so the copy in package.json always matches the server's). If any of the four is missing, the extension still mounts but /auth/email returns { status: "Failed", message: "Login not configured" } and logs a warning at startup.
Custom domains just work. The redirect target is built from the Host the request actually arrived on, so a user signing in from your custom domain lands back on it rather than the *.nukebase.com subdomain. NukeBase re-validates that host against the project's known domains, so a spoofed Host header cannot be used as a redirect target.
New addresses create accounts. /auth/callback finds the user by email or creates one — there is no separate signup step. Rate limited to 5 emails per 60-second window per IP, and the response to /auth/email is identical whether or not the address exists, so it cannot be used to enumerate users.
Sending from your own domain
With a custom domain connected, your app's emails can come from it instead of from nukebase.com: Idaho Weed Control <support@yourdomain.com>. Set it up with nukebase domain email or the Email Sending button on the dashboard, then add the two DNS records it shows (SPF and DKIM). The setup is only the domain: once it is verified, any address on it can send. Your code picks the sender name, the address and the Reply-To on each email (sendEmail's from and replyTo, or loginEmail.from for sign-in emails). Left out, the address is support@ and the sender name is your brandName.
- Send from the domain itself or from
mail.yourdomain.com. The domain itself is best when it has no email yet. If you already use email on it (Google Workspace, Outlook), choosemail.: your existing records are not touched. Either way the From address isname@yourdomain.com(orname@mail.yourdomain.comwhen the domain's DMARC record asks for strict alignment). - Sending only. No MX record is added, so the domain's inbox, if it has one, is unaffected. Replies reach you through the Reply-To address.
- One SPF record per name. If the domain already has one, you are shown that record with the mail provider merged in, to replace it. Adding a second one would break email from the domain.
- Until the records verify, and if a send from your domain ever fails, emails keep going out from nukebase.com as before. Records are re-checked every 10 minutes for a week; an unverified setup is then removed. Removing the custom domain removes the sending domain too.
nukebase domain email # choose, add the records, wait for verification
nukebase domain email --sub # choose mail.yourdomain.com without being asked
nukebase domain email # again: status, records
nukebase domain email remove # back to nukebase.com
Customising the sign-in email
Pass loginEmail to easy-login to reword and style the sign-in email. Every field is optional and plain text (no HTML); {{brand}} in any of them becomes your brandName. The sign-in button always points at NukeBase's link: you can change how the email looks, never where it goes.
require("./extensions/easy-login")({
// ...the usual options...
brandName: "Acme",
loginEmail: {
subject: "Your {{brand}} sign-in link", // up to 150 characters
heading: "Welcome back to {{brand}}", // 120
message: "Tap the button to sign in.", // 600, new lines kept
buttonText: "Open Acme", // 40
footer: "Questions? Just reply to this email.", // 300
brandColor: "#4361ee", // hex colour of the button
logoUrl: "https://acme.com/logo.png", // https only
from: "login" // sender name before the @ (custom domain only)
}
});
sendEmail — any email from your app
Once your custom domain is set up for sending (above), easy-login also gives you sendEmail for everything else: reminders, receipts, notifications. It is sent from your own domain, to any address.
const { sendEmail } = require("./extensions/easy-login")({ /* ... */ });
const r = await sendEmail({
from: "Idaho Weed Control <support>", // sender name and the part before the @; optional
to: "customer@example.com", // one address per call
subject: "Your booking is confirmed",
html: "<p>See you Tuesday at 3pm.</p>", // html, text, or both
text: "See you Tuesday at 3pm.",
replyTo: "you@gmail.com" // optional: where replies go
});
// r = { ok: true, id } or { ok: false, error: "..." } — it never throws
- You pick the sender on each email; the domain is always yours.
fromsets the sender name and the part before the @:"Idaho Weed Control <support>","John <john>", or just"billing". The domain is your verified sending domain. Without a name, the sender name is easy-login'sbrandName; without an address, it issupport@.replyTois per email too. - Limits: up to 100 emails a day per app on every plan (resetting at midnight UTC), and 120 a minute. Sign-in emails do not count toward them.
- Plain text is made for you. Give only
htmland a plain-text version is generated from it (spam filters prefer both); givetextto write your own. - Needs a verified sending domain. Without one every call answers
{ ok: false, error: "Set up email sending on your custom domain first…" }. Projects without a custom domain keep easy-login's sign-in emails only. - Price: $0.01 per email from your credit, the same as a sign-in email.
- Bounces and spam reports are watched. Over the last 7 days, bounces above 5% or spam complaints above 0.1% bring a warning by email and on the dashboard; above 10% or 0.3%,
sendEmailis paused until support lifts it. Sign-in emails are never paused, so your users can always sign in. - Addresses that bounced, complained or unsubscribed are refused with an error saying so, rather than silently dropped.
- Recent emails. The dashboard's Recent emails button on the project lists the last 200 emails sent from your domain (sign-in emails included) with what happened to each: delivered, retrying, bounced (with the receiving server's reason), marked as spam, or unsubscribed. Kept for 30 days; address and subject only, never the body. The
idsendEmailreturns is the same email. - Send only to people who signed up for your app and expect the email. Lists bought or copied from elsewhere are what get sending paused.
What emails cost
Every email, sign-in or sendEmail, is $0.01 from your credit; no plan includes a bundle. Accounts created before this change keep the monthly allowance per app their plan had (Free 100, Launch 300, Scale 1,500) until they change plan. With no credit left, emails are refused with 402 Payment Required until you add funds.
Magic Link Authentication
Use this instead of easy-login when you want to send the emails yourself — your own Mailgun account, your own sending domain, your own sender address.
NukeBase has built-in passwordless sign-in via emailed one-time links. Two endpoints power the flow, and account creation can also bootstrap into it.
Setup requirement: Magic-link authentication is an optional extension that requires a Mailgun account. Mount it in your app.js after addDomain():
const nukebase = addDomain({ authPath: ["users"] });
// Mount magic-link extension
require("./extensions/magic-link")({
app: nukebase.app,
authPath: nukebase.authPath,
query, set, generateRequestId, hashToken,
mailgunKey: "key-your-mailgun-api-key",
mailgunDomain: "mg.yourdomain.com",
fromEmail: "noreply@yourdomain.com",
domain: "https://your-app.nukebase.com",
redirectPath: "/dashboard", // optional, default "/"
errorRedirect: "/", // optional, default "/"
ttlMs: 15 * 60 * 1000, // optional, token expiry (default 15 min)
sessionTokenTtlMs: 24*60*60*1000, // optional, session length (default 24h)
cookieMaxAgeSeconds: 86400, // optional, cookie Max-Age (default 86400)
brandName: "Acme", // optional, email subject and heading (default "Sign in")
brandColor: "#4361ee", // optional, button colour
fromName: "Acme", // optional, display name on From (default brandName)
supportEmail: "help@acme.com" // optional, shown in the email footer
});
Without this extension mounted, the /magic-link, /magic-signup, and /magiclink endpoints will not exist. The extension requires mailgunKey, mailgunDomain, fromEmail and domain — it throws on startup if any are missing.
POST /magic-link — request a sign-in link for an existing account
const r = await fetch("/magic-link", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: "matt@example.com" })
});
const { status, message } = await r.json();
// status === "Success" whether or not the address exists (anti-enumeration)
Body: { email: string }. The address is lowercased and must be an ordinary email address — up to 254 characters, local part up to 64, no quotes or whitespace; + tags, hyphenated domains and long TLDs are all accepted. The response is the same regardless of whether the account exists, so a bad actor cannot use this endpoint to enumerate users. The IP-based rate limiter applies (5 / 60s).
GET /magiclink?token=... — consume a sign-in link
This is the URL that the email points at; users don't call it from code. It answers with a small "Signing you in…" page, whose script posts the token to POST /magiclink { token } on the same origin. On a valid, unexpired token that request:
- Mints a session through
issueSession(a 32-byte token whose SHA-256 hash is stored underusers.<uid>.auth.tokens, 24-hour expiry by default), parking any other account this browser is signed in as, - Sets the
uidandtokencookies (HttpOnly; Secure; SameSite=Strict), - Answers
{ status: "Success", location }, and the page goes to${domain}${redirectPath}(both configured when mounting the extension).
Why the extra step: the session cookies are SameSite=Strict, so a link clicked in a webmail tab (another site) arrives without them. A sign-in minted on that request could not see the account the browser was already signed in as, and would replace it instead of parking it. The page's request is same-origin and carries the cookies. Scanners that prefetch links do not run the script, so they no longer spend the token either.
Tokens are single-use (deleted on consumption) and expire 15 minutes after issue. An invalid or expired token sends the page to errorRedirect?error=invalid_or_expired, a missing token to ?error=missing_token; a relative errorRedirect is taken from the site root.
Passwordless account creation via /magic-signup
Use the /magic-signup endpoint to create an account that exists only for magic-link sign-in. The server sends a sign-in link and creates the account only when that link is clicked — so nobody can register an address they don't control. The response does not log the user in; they have to click the link in their email. This endpoint is provided by the magic-link extension.
// Email-only signup via /magic-signup — user must click the link in their inbox
const r = await fetch("/magic-signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: "matt@example.com" })
});
const result = await r.json();
// result.status === "Success", result.message tells the user to check email
// A taken address answers status "Failed", "An account with that email already exists"
// (no uid / token returned here — the session is established by /magiclink)
Using Authentication in Security Rules
Once authenticated, the admin object is available in your security rules:
// In your rules.js
module.exports = {
"users": {
"$userId": {
// Only the user themselves can edit
"write": "admin.uid == $userId",
// Don't grant read at $userId — it would cascade and expose "private".
// Split the data into public/private subnodes and grant read on each.
"public": { "read": "true" }, // Anyone can read public profile
"private": { "read": "admin.uid == $userId" } // Only the user
}
},
"adminPanel": {
// Only users with admin role can access
"read": "admin.claims.role == 'admin'",
"write": "admin.claims.role == 'admin'"
}
};
Security Notes:
- Use HTTPS in production — the auth cookies are
Secure-flagged and will not be set over plain HTTP (browsers exemptlocalhostfor development). - Rate limiting on
/login,/magic-link,/magic-signupand/auth/emailis built in (5 attempts per 60-second window per client IP). The client IP is derived from the connection's peer address, so it is already correct behind a reverse proxy and cannot be spoofed by a directly-exposed client — no configuration needed. - Expired session tokens are swept automatically every hour — no cleanup script needed.
- Passwords are hashed with argon2id; session tokens are SHA-256 hashed before storage. Legacy plaintext passwords auto-upgrade on first successful login.
generateRequestId(bytes)usescrypto.randomBytesand returns a hex string. Defaults to 8 bytes (16 hex chars); session tokens use 32 bytes (64 hex chars).
Custom Claims
Custom claims let you attach arbitrary data (roles, permissions, plan tiers, etc.) to a user's auth record. Claims are available in security rules and callable functions via admin.claims.
// Set all claims at once
set(["users", uid, "auth", "claims"], { role: "admin", plan: "pro" });
// Update or add a single claim
update(["users", uid, "auth", "claims"], { role: "editor" });
// Remove a single claim
remove(["users", uid, "auth", "claims", "role"]);
module.exports = {
"adminPanel": {
"read": "admin.claims.role == 'admin'",
"write": "admin.claims.role == 'admin'"
},
"premiumContent": {
"read": "admin.claims.plan == 'pro'"
}
};
Claim changes reach open connections. A connected user's claims are re-read every time their session is checked: on every message they send, and every 30 seconds for a connection that only listens. So removing a role takes effect on their next request, and within 30 seconds for their live subscriptions — no reconnect needed. To cut someone off immediately (a ban, a forced sign-out), call disconnectUser(uid) from app.js; revoking their session tokens alone is picked up within the same 30 seconds. Users without any claims will have admin.claims default to an empty object {}.
Database Structure for Authentication
The authentication system expects user data to be structured like this:
"users": {
"ML96SDE5": { // Unique user UID (hex, generated by generateRequestId)
"auth": {
"username": "matt123", // Lowercased username/email (optional for demo accounts)
"password": "$argon2id$v=19$m=65536,...", // argon2id hash — never plaintext
"tokens": {
// Keys are SHA-256 hashes of the raw session token (the cookie value).
// Values are expiration timestamps in ms since epoch.
"8f3a...e21c": 1748357368415,
"b12d...07ff": 1748357670935
},
"claims": { // Optional custom claims (free-form object)
"role": "admin",
"plan": "pro"
}
}
}
}
What's actually stored vs. what the cookie holds:
- Password: stored as an
argon2idhash. A legacy plaintext value will be auto-upgraded to a hash on the next successful login. - Session tokens: the cookie holds the raw 32-byte hex token; the database stores only its SHA-256 hash as the key under
auth.tokens. You cannot reconstruct a valid cookie from the database alone. - Don't try to read tokens out of
auth.tokensat runtime — they're hashes, not the values you'd put back into a cookie.
Token cleanup is automatic. A background sweep runs hourly and removes any auth.tokens entries whose expiry has passed; the extensions sweep their in-memory rate-limit maps every five minutes. You don't need to schedule your own cleanup.