The admin
Sign-in
Protect the admin with Google or email sign-in, and decide who gets in.
@mortar-kit/auth protects the admin. Sign-in methods (Google, an emailed link or code, or your own) prove who someone is. Your authorize function then decides whether they may in, and as which user. A signed cookie keeps them signed in.
It runs on the server only: import it from middleware and server functions, never from client code.
Set it up
The quickest way is authFromEnv, which reads its settings from environment variables:
// src/server/auth.ts
import { authFromEnv } from '@mortar-kit/auth';
import { createJsonFileStore } from '@mortar-kit/core/server';
export const auth = authFromEnv({ store: createJsonFileStore({ dir: '.data' }), siteName: 'My site' });
| Variable | What it does |
|---|---|
MORTAR_AUTH_SECRET |
Signs the session cookie: at least 32 characters (openssl rand -base64 32). Comma-separate several to rotate keys. |
MORTAR_ADMINS |
Addresses and *@domains that may always sign in, comma-separated. With authorize, they get in as well as whoever it accepts. |
GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET |
Turn on Sign in with Google. |
RESEND_API_KEY, MORTAR_EMAIL_FROM |
Send sign-in emails through Resend, from that address. |
MORTAR_BASE_URL |
The public origin, behind a proxy. |
Email sign-in needs store (where pending sign-ins wait) and a mailer: Resend from the variables above, or your own mailer option. In development (Vite's dev server), a missing secret falls back to a fixed one, [email protected] may sign in, and emails print to the console. A production build never falls back: it refuses to start without a secret, someone who may sign in, and at least one way to sign in. With your own authorize, the development admin isn't added: set MORTAR_ADMINS for that. authorize is asked first, so someone it accepts gets your user; someone only in MORTAR_ADMINS gets { email, name? }. Every option of createAuth can be passed too, and wins over the environment.
By hand
createAuth takes everything explicitly:
import { allowEmails, createAuth, email, google } from '@mortar-kit/auth';
import { createJsonFileStore } from '@mortar-kit/core/server';
export const auth = createAuth({
methods: [
google({ clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET! }),
email({ mailer, store: createJsonFileStore({ dir: '.data' }) }),
],
authorize: allowEmails(['[email protected]', '*@example.com']),
secret: process.env.MORTAR_AUTH_SECRET!,
});
methods is a list: the sign-in page offers each, in order. secret signs the session cookie: at least 32 characters, from the environment. Pass several to rotate keys; the first signs and all are accepted.
Who may sign in
authorize gets the identity a method verified ({ email, name?, method }) and returns your user, or null to refuse. Look users up however you like:
async authorize({ identity }) {
const admin = await db.admins.find(identity.email);
return admin ? { email: admin.email, name: admin.name } : null;
}
It runs when someone signs in and again on every guarded request, so removing someone takes effect at once. Keep it to one quick lookup, and return plain JSON, since the user reaches the admin in the browser. allowEmails([...]) is a ready-made one for a fixed list of addresses and *@domains.
To manage who may sign in from the admin itself, keep them in a collection of your own and use allowMembers:
export const members = defineCollection({
name: 'members',
label: 'Members',
fields: { email: fields.text({ label: 'Email', required: true }), name: fields.text({ label: 'Name' }) },
});
authFromEnv({ store, authorize: allowMembers({ content, collection: 'members' }) });
It lets in anyone whose address (the email field; emailField to change it) is in a document of the collection, and uses its name field as their name. Deleting the document locks them out at once.
To give users roles, add a field and name it in fields: the user gets it as stored.
authorize: allowMembers({ content, collection: 'members', fields: ['role'] }),
// ada is { email: '[email protected]', name: 'Ada', role: 'owner' }
Who may change what
Signed-in editors can change everything by default. To limit that, pass canWrite to createContentServer. It gets each write with the user authorize returned and answers true or false:
export const server = createContentServer({
content,
auth,
// Only owners change who may sign in.
canWrite: ({ user, collection }) => collection !== 'members' || user.role === 'owner',
});
Besides user, it gets action (the function called: save, remove, move, or one of the asset functions such as uploadAsset), collection (undefined for asset writes), id (the document's id, an asset's key or a folder's id) and, for save, the doc itself. For document writes it also gets stored, the document as stored now (null when a save creates it). A refused write throws a 403 Response, "Not allowed", which the admin shows where the save failed.
A collection can have its own rule, scoped to its documents. createContentServer checks it after the server's, and both must allow:
export const projects = defineCollection({
name: 'projects',
fields: { title: fields.text({ label: 'Title' }), lead: fields.text({ label: 'Lead (email)' }) },
// Editors change only the projects they lead, and can't hand them to someone else.
canWrite: ({ user, stored, doc }) =>
user.role === 'owner' || ((!stored || stored.fields.lead === user.email) && (!doc || doc.fields.lead === user.email)),
});
It gets user, action (save, remove or move), id, stored and, for a save, doc as sent (not validated yet). Check both stored and doc on a save, or an editor could take over a document by changing its owner field.
Guard the routes
createMiddleware is the middleware a Mortar site needs, in one function. Put it in start.middleware:
// src/middleware.ts (vite.config: solid({ start: { middleware: './src/middleware.ts' } }))
import { createMiddleware } from '@mortar-kit/auth';
import { auth } from './server/auth.ts';
import { blobs } from './server/blobs.ts';
export default createMiddleware({
auth,
blobs,
sitemap: { content, collections, origin: process.env.MORTAR_BASE_URL },
robots: true,
});
For each request, in order:
- Rate limit: posts to the sign-in routes are limited per client, 10 every 10 minutes by default (
rateLimit: { max, window }in seconds, orfalse). Asking for a code and trying one count separately, so someone who asked a few times can still type the code they got. Clients are told apart byX-Forwarded-FororX-Real-IP, which a proxy in front of the server sets. Without a proxy, passclientKey(request): a FetchRequestdoesn't carry the client's address. Requests with no key aren't limited, because one shared bucket would let anyone lock every editor out. - Auth:
auth.handleanswers the sign-in routes (under/admin/auth) and sends signed-out visits to/adminand below to the sign-in page. - Sitemap and robots.txt: with
sitemap,GET /sitemap.xmlanswers withsitemap()over those collections (its options too:include,extra,lastmod).origindefaults to the request's, so set it behind a proxy.robots: trueanswers/robots.txt, keeping crawlers out of/adminand pointing them at the sitemap; a string is your own file. - Uploads: with
blobs, files are served at the pathblobs.url('')gives (e.g./uploads/), throughserveBlob. - Pages: HTML responses get a Content-Security-Policy,
script-src 'nonce-…' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'self', with a fresh nonce per request that the render puts on its scripts. Pass your own policy as a string ({nonce}is replaced), orcsp: false. On the dev server there is none by default, since Vite's dev scripts carry no nonce (csp: trueturns it on anyway). UseuseRenderedPage()to put the nonce on scripts of your own. An authored server entry must passcontext.noncetorenderToStream; the generated one does.
Every response also gets X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin and X-Frame-Options: SAMEORIGIN, unless it set them itself. headers adds yours ({ 'Permissions-Policy': 'camera=()' }), null drops one of the defaults, and headers: false adds none.
To add your own steps, give start.middleware an array: [createMiddleware({ auth, blobs }), yours].
Middleware can't tell which server-function calls come from the admin, so every function that writes checks for itself. Pass auth to createContentServer and its writes do. For server functions of your own, auth.require returns the user, or throws a 401 (or a 403 for a cross-site call):
'use server';
export async function saveDoc(collection: string, doc: Doc) {
await auth.require(getRequestEvent()!.request);
return content.save(collection, doc);
}
The sign-in page
Mount <SignIn> from @mortar-kit/admin at /admin/sign-in. Give it auth.methods (from a server function) and the page's search parameters, which carry its state: an email sent, an emailed link, an error. It's plain forms, so it works without JavaScript. Pass the signed-in user to <Admin user={...}> to show them at the foot of the rail, with Sign out.
Create an OAuth client of type "Web application" in the Google Cloud console and add https://your-site/admin/auth/google/callback as a redirect URI. hostedDomain: 'example.com' accepts only that Workspace domain. Only verified addresses get through.
One email carries a 6-digit code and a link, so it works both on the device that asked and on a phone. Codes and links work once, expire after 15 minutes and allow five tries. The page says "check your email" whether or not the address may sign in, and sends nothing to addresses authorize refuses.
Email goes through a Mailer. resendMailer({ apiKey, from }) sends through Resend (authFromEnv uses it when RESEND_API_KEY is set). Any other provider is one send function:
const mailer: Mailer = {
async send(message) {
await postmark.sendEmail({ From: '[email protected]', To: message.to, Subject: message.subject, TextBody: message.text, HtmlBody: message.html });
},
};
consoleMailer() prints emails to the server console instead, for development. Pending sign-ins (hashes only) go in any ContentStore, under the reserved collection mortar-auth-tokens. With the JSON-file store, keep them outside your content and git.
Behind a proxy
Set baseUrl: 'https://example.com' when the server sees a different origin than visitors do, so redirect URIs, email links and the same-origin check use the public one.
Your own method
A method is { id, label, input, start, callback }. start handles the sign-in form's post (redirect to a provider, send something). callback handles the return and resolves to { identity }; createAuth does the rest (asks authorize, sets the cookie). Its context signs state (ctx.sealer), builds URLs and fails back to the sign-in page.