/lunora:lunora-setup-authfrom Lunora
Adds authentication to a Lunora app using better-auth with D1 storage. Covers email/password, OAuth (Clerk, Auth0), magic link, email OTP, auth UI screens, and gating functions on ctx.auth.userId. Also supports external identity providers via @lunora/jwt-auth.
Ships in Lunora. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
The auth registry item is built on @lunora/auth, a thin wrapper over
better-auth. Users and sessions are stored in D1.
Lunora's SessionDO is a separate TTL'd token store that @lunora/auth never
calls, so don't wire it for auth. If you need auth state in a Durable Object
instead of D1, use LunoraAuthDO / .auth({ namespace, internalSecret }).
If the project has no Lunora backend yet, start with lunora-quickstart.
If the app's users sign in through Clerk, WorkOS AuthKit, Auth0, Supabase or any
OIDC issuer, and that provider should keep owning the session, don't add the
auth item. Verify the provider's JWT instead with @lunora/jwt-auth:
lunora init --auth=clerk # new project: or workos | auth0 (wires everything below)
lunora registry add auth-clerk-jwt # existing project: or auth-workos-jwt | auth-auth0-jwt
import { clerk } from "@lunora/jwt-auth"; // workos, auth0, supabase, jwtIdentityResolver
import { memoizeIdentity } from "lunorash/runtime";
defineApp<Env>()
.shard((env) => env.SHARD)
.extend((env) => ({
resolveIdentity: memoizeIdentity(clerk({ publishableKey: env.CLERK_PUBLISHABLE_KEY ?? "", authorizedParties: env.CLERK_AUTHORIZED_PARTIES ?? "" })),
}))
.build();
On the client, create the LunoraClient with authTokenOnUpgrade: true and,
once signed in, call setAuthTokenProvider(client, getToken, { subject: userId })
from lunorash/client. It refreshes before exp and on onTokenExpired; map
the provider's "signed out" error (WorkOS LoginRequiredError, Auth0
login_required) to null. authTokenOnUpgrade is what authenticates
live-query sockets: the browser offers the bearer as a Sec-WebSocket-Protocol
entry. Without it, a WorkOS or Auth0 socket, or a cross-origin Clerk one, is
anonymous.
Org claims arrive as orgId with the org role (orgRole for Clerk, role /
orgRoles for WorkOS); no preset sets the app-wide roles RLS reads, since
any Clerk user can create an organization and be its admin. Check the org role
together with orgId in a policy. CLERK_AUTHORIZED_PARTIES is required.
Full guide:
/docs/concepts/external-auth, with runnable apps in examples/clerk-auth and
examples/workos-auth.
The rest of this skill covers the better-auth path.
lunora add auth # asks for the provider and D1 database name
lunora add auth --provider clerk --db my-app-db # non-interactive (auth | clerk | auth0)
lunora registry add auth # low-level: writes placeholder names
Then run pnpm install. The item does the following:
@lunora/auth, @lunora/mail and @lunora/server to package.json.lunora/auth/index.ts into the project. The project owns this file and can edit it. It exports buildAuth(env), getAuth(env) (memoized per isolate) and mountAuth(env, request), which routes /api/auth/* and returns undefined for any other path. The scaffold turns on email/password with requireEmailVerification: true and sends verification and reset mail through @lunora/mail. It also adds the uiConfig() plugin.DB binding to wrangler.jsonc. The database_id is a placeholder.BETTER_AUTH_SECRET, BETTER_AUTH_URL and MAIL_FROM to .dev.vars.| Var | Secret | Notes |
|---|---|---|
BETTER_AUTH_SECRET | yes | At least 32 chars (openssl rand -base64 32). Production: wrangler secret put. |
BETTER_AUTH_URL | no | Public base URL. better-auth uses it for callbacks and cookies. |
MAIL_FROM | no | Sender for verification and reset mail. |
wrangler d1 create my-app-db # paste the returned id into the DB binding
lunora doctor # flags a placeholder database_id
Don't declare the better-auth tables (user, session, account,
verification) in lunora/schema.ts. better-auth owns them in D1. In dev the
schema is auto-applied on the first /api/auth/* request. For production,
pre-apply it with compileMigrationsSql(auth.options) piped to
wrangler d1 execute <db> --remote --file -. The item README has the script.
Re-run that migration after adding a plugin that brings its own tables, such as
organization or twoFactor.
There are two parts. /api/auth/* has to reach better-auth. resolveIdentity
has to turn the session cookie into ctx.auth. If resolveIdentity is missing,
sign-in still works but ctx.auth.userId stays null in every function.
Through the generated defineApp builder. This is the default for
templates. .auth() does both parts: it builds the instance lazily, runs
ensureMigrated, dispatches /api/auth/* and sets resolveIdentity. A
Vite-first app ("main": "virtual:lunora/worker") has no entry file, so chain
the call in the lunora.config.ts app hook. A hand-written entry
(src/server.ts) chains it on defineApp() directly:
// lunora.config.ts
import type { AppBuilder, LunoraConfig } from "./lunora/_generated/app";
// Move the object `buildAuth` passes to `createAuth` (minus `database`; the
// builder supplies the D1 adapter) into an exported `authOptions(env)` in
// lunora/auth/index.ts, and have `buildAuth` spread it too.
import { authOptions } from "./lunora/auth/index.js";
interface Env {
BETTER_AUTH_SECRET: string;
BETTER_AUTH_URL: string;
DB: D1Database;
}
export default {
target: "cloudflare",
app: (app: AppBuilder<Env>): AppBuilder<Env> =>
app.auth({
d1: (env) => env.DB,
options: (env) => authOptions(env),
}),
} satisfies LunoraConfig<Env>;
Reuse the scaffold's options rather than retyping a subset: a hand-written
{ emailAndPassword: { enabled: true } } drops requireEmailVerification,
sendResetPassword and sendVerificationEmail, so users sign in unverified and
no verification or reset mail goes out.
.auth() appears on the builder only after codegen sees @lunora/auth
installed, so run lunora codegen first.
Hand-rolled createWorker entry. Call the scaffolded mountAuth first in
fetch, then hand every other request to the Lunora worker, which resolves the
identity:
import type { AuthEnv } from "../../lunora/auth/index.js";
import { getAuth, mountAuth } from "../../lunora/auth/index.js";
const worker = createWorker({
resolveIdentity: async (req, env) => {
const session = await getAuth(env as AuthEnv).api.getSession({ headers: req.headers });
return session?.user ? { userId: session.user.id } : null;
},
// …
});
export default {
async fetch(request: Request, env: AuthEnv, ctx: ExecutionContext): Promise<Response> {
const authResponse = await mountAuth(env, request);
if (authResponse) return authResponse;
return worker.fetch(request, env, ctx); // RPC, WebSocket, everything else
},
};
Each of these items requires the base auth item and installs it if it is
missing:
lunora add auth-clerk # Clerk OIDC (genericOAuth): CLERK_CLIENT_ID / _SECRET / CLERK_ISSUER_URL
lunora add auth-auth0 # Auth0 OIDC: AUTH0_CLIENT_ID / _SECRET / AUTH0_DOMAIN
lunora add auth-magic-link # passwordless link, sent via @lunora/mail
lunora add auth-otp # email one-time code, sent via @lunora/mail
lunora add auth-emails # styled React templates for the auth mails (renderEmail)
lunora add auth-ui # copy-in screens; framework auto-detected (no React Native port)
The provider items copy a file into lunora/auth/ but don't register it
anywhere. Add the plugin to the plugins array yourself, in buildAuth or in
.auth({ options }). For example, plugins: [uiConfig(), clerk(env)] with
import { clerk } from "./clerk.js". The other exports are auth0,
magicLinkPlugin and emailOtpPlugin. The OAuth callback URL is
<BETTER_AUTH_URL>/api/auth/oauth2/callback/<clerk|auth0>.
import { LunoraError } from "lunorash/server";
import { mutation, v } from "#lunora/_generated/server.js";
export const createDocument = mutation.input({ title: v.string() }).mutation(async ({ ctx, args: { title } }) => {
if (!ctx.auth.userId) {
throw new LunoraError("UNAUTHORIZED", "not signed in");
}
return ctx.db.insert("documents", { ownerId: ctx.auth.userId, title, createdAt: Date.now() });
});
ctx.auth.getIdentity() returns the full session claims, such as email and
name. For org or role checks, compose withAuthPlugins(auth) and call the
better-auth server API.
The default is a better-auth cookie session. LunoraClient needs no token,
so don't call setToken / setAuthToken for it. Sign in with the better-auth
client. Build that client with createLunoraAuthClient, which installs
lunoraSessionSync(). That plugin tells every open LunoraClient, including
ones in other tabs, to re-resolve the session after sign-in or sign-out. Without
it, live queries keep serving the previous user's rows. If you call
createAuthClient yourself, add lunoraSessionSync() to its plugins.
import { createLunoraAuthClient } from "@lunora/auth/plugins/client";
import { Authenticated, AuthLoading, Unauthenticated, useAuth } from "@lunora/react";
import { createAuthClient } from "better-auth/react";
export const authClient = createLunoraAuthClient(createAuthClient);
function Account({ email, password }: { email: string; password: string }) {
const { user } = useAuth(); // { setToken, status, token, user }
return (
<>
<AuthLoading>…</AuthLoading>
<Authenticated>
<span>Signed in as {user?.email}</span>
<button type="button" onClick={() => authClient.signOut()}>
Sign out
</button>
</Authenticated>
<Unauthenticated>
<button type="button" onClick={() => authClient.signIn.email({ email, password })}>
Sign in
</button>
</Unauthenticated>
</>
);
}
A client plugin toggle such as { plugins: { twoFactor: true } } only adds
the client half. Register the matching server plugin (twoFactor() from
@lunora/auth/plugins) in buildAuth's plugins too, or its endpoints don't
exist.
setToken is only for bearer-token setups, such as React Native or a JWT from
an external IdP.
Branch on status, not on user === null. status takes one of four values:
"unauthenticated", "loading", "authenticated" or "unreachable". The gates
in @lunora/vue, @lunora/solid, @lunora/svelte and @lunora/angular use the
same four. "unreachable" means a credential is held but the session endpoint
failed, for example on an offline reload. The gates treat it as authenticated,
yet user can still be null at that point. A UI that reads that null as
"signed out" shows a signed-in user the signed-out screen. The full contract is
documented on AuthStatus in @lunora/client/auth.
requireEmailVerification: true, so the user has to open the verification link first. In dev, that link is in the Studio Mail tab.MAIL_FROM, the scaffold throws rather than logging the link. Auth links are bearer credentials, so this is intentional. Production needs lunora add email (the SEND_EMAIL binding) or RESEND_API_KEY, plus a verified sender domain. See lunora-setup-mail.requireOwner throw UNAUTHORIZED until resolveIdentity is wired (Step 3).lunora doctor. It should report no placeholder database_id.lunora dev. Sign up, open the verification link from the Studio Mail tab, then sign in.ctx.auth.userId. It should return the user's id, not null.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
15 skills in this plugin
/lunoraRoutes general Lunora requests to the right Lunora skill and gives the shared mental model (codegen loop, generated `api`/`internal` references, review commands, add-on capabilities, the `@lunora/mcp` server). Use when the user asks which Lunora skill to use, gives an underspecified task in a project with a `lunora/` directory or `lunorash`/`@lunora/*` dependencies, asks to review or audit Lunora code, asks about an add-on without its own skill (queues, workflows, agents, AI, flags, payments, notifications), or wants to expose a deployment to an AI agent over MCP./lunora-cloudflare-auditAudits a Lunora app for Cloudflare cost and reliability risk before launch or after a surprise bill. Chains the read-only `lunora doctor`, `lunora advisor` and `lunora insights` signals, then traces what they cannot see — retry and fan-out loops, cron cadence, public routes that reach a metered product (Workers AI, Browser, Containers, Vectorize, R2, D1), preview environments with paid bindings, and missing usage alerts (`lunora cloudflare alerts`). Reports each finding with the billing meter it moves, the smallest fix, and how to verify. Use when the user asks to "audit before launch", "what could blow up our Cloudflare bill", "why did the bill spike", "is this safe to put on the public internet", or "review our cron / queue / AI / workflow cost". For a slow query or OCC conflict use `lunora-performance-audit`; for a failing deploy use `lunora-deploy`./lunora-create-packageBuilds a reusable Lunora capability, either as a registry item that `lunora add` / `lunora registry add` copies into an app's `lunora/`, or as a publishable `@lunora/*` workspace package in the Lunora monorepo. Use when the user wants to package schema + functions + wrangler bindings + env vars for other apps, add or edit an item under `registry/<name>/` (`registry.json`), run `vis generate lunora-package`, or wire a new `ctx.*` capability into codegen./lunora-deployDeploys a Lunora app to Cloudflare Workers + Durable Objects and gets wrangler.jsonc, remote resources and secrets to line up. Covers `lunora deploy` (and `--env`, `--dry-run`, `--migrate`), isolated per-PR previews (`lunora preview deploy | list | delete`), the `lunora doctor` / `lunora verify` / `lunora prepare` preflights, Durable Object bindings (SHARD, SHARD_REGISTRY, SCHEDULER), the `DB` D1 binding and its placeholder id, R2 buckets, production secrets (`lunora env push`, `wrangler secret put`) versus `.dev.vars`, the schema-drift gate, the architecture diff, and rollback with `lunora cloudflare deployments`. Use when the user asks to "deploy", "ship to production", "set up a staging environment", wire CI deploys, or when a deploy fails on a binding, a placeholder `database_id`, an unexported Durable Object class, a missing secret, or "schema drift gate blocked deploy"./lunora-functionsAuthoring rules for Lunora schema and server functions under `lunora/` — `defineSchema`/`defineTable`, `v.*` validators, the generated `query`/`mutation`/`action` builders (and `internal*`), indexes and `withIndex`, the `ctx.db` API, pagination, `ctx.db.related`, opt-in `ctx.*` capabilities, topics, modules, services, and `httpAction`. Use when writing or reviewing files in `lunora/` (`schema.ts`, function files, `http.ts`, `queues.ts`), when asked to "add a query/mutation/action", "add an index", "call one function from another", or "add a webhook endpoint", or when `lunora codegen` reports an error in a function./lunora-migration-helperPlans and runs Lunora schema and data migrations with the widen → migrate → narrow pattern. Covers online data migrations (`defineMigration` in `lunora/migrations.ts`, `lunora migrate create | up | down | status`), what the pre-deploy schema-drift gate treats as breaking and how a migration covers it, `.global()` table DDL on D1 (`lunora migrate generate`) and Hyperdrive, moving a dataset with `lunora migrate d1-to-hyperdrive` (and back with `hyperdrive-to-d1`), and re-keying a `.shardBy()` table. Use when the user wants to make a field required, rename or drop a field or table, change a field's type, add a unique index to a populated table, backfill data, switch a table between root / `.shardBy()` / `.global()`, or when `lunora deploy` reports "schema drift gate blocked".npx claudepluginhub anolilab/lunora --plugin lunoraOther plugins' skills for the same job