dependabot[bot] 8bbe1646f9 chore(deps-dev): bump the dev group with 7 updates (#100)
Bumps the dev group with 7 updates:

| Package | From | To |
| --- | --- | --- |
| [@better-auth/passkey](https://github.com/better-auth/better-auth/tree/HEAD/packages/passkey) | `1.7.17` | `1.7.21` |
| [@electric-sql/pglite](https://github.com/electric-sql/pglite/tree/HEAD/packages/pglite) | `0.5.15` | `0.5.16` |
| [better-auth](https://github.com/better-auth/better-auth/tree/HEAD/packages/better-auth) | `1.7.17` | `1.7.21` |
| [next](https://github.com/vercel/next.js) | `16.4.5` | `16.4.6` |
| [playwright](https://github.com/microsoft/playwright) | `1.64.1` | `1.65.0` |
| [prettier](https://github.com/prettier/prettier) | `3.9.10` | `3.10.0` |
| [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.72.1` | `8.72.2` |


Updates `@better-auth/passkey` from 1.7.17 to 1.7.21
- [Release notes](https://github.com/better-auth/better-auth/releases)
- [Changelog](https://github.com/better-auth/better-auth/blob/main/packages/passkey/CHANGELOG.md)
- [Commits](https://github.com/better-auth/better-auth/commits/v1.7.21/packages/passkey)

Updates `@electric-sql/pglite` from 0.5.15 to 0.5.16
- [Release notes](https://github.com/electric-sql/pglite/releases)
- [Changelog](https://github.com/electric-sql/electric-pglite/blob/main/packages/pglite/CHANGELOG.md)
- [Commits](https://github.com/electric-sql/pglite/commits/@electric-sql/pglite@0.5.16/packages/pglite)

Updates `better-auth` from 1.7.17 to 1.7.21
- [Release notes](https://github.com/better-auth/better-auth/releases)
- [Changelog](https://github.com/better-auth/better-auth/blob/main/packages/better-auth/CHANGELOG.md)
- [Commits](https://github.com/better-auth/better-auth/commits/v1.7.21/packages/better-auth)

Updates `next` from 16.4.5 to 16.4.6
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/compare/v16.4.5...v16.4.6)

Updates `playwright` from 1.64.1 to 1.65.0
- [Release notes](https://github.com/microsoft/playwright/releases)
- [Commits](https://github.com/microsoft/playwright/compare/v1.64.1...v1.65.0)

Updates `prettier` from 3.9.10 to 3.10.0
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.9.10...3.10.0)

Updates `typescript-eslint` from 8.72.1 to 8.72.2
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.72.2/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: "@better-auth/passkey"
  dependency-version: 1.7.21
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev
- dependency-name: "@electric-sql/pglite"
  dependency-version: 0.5.16
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev
- dependency-name: better-auth
  dependency-version: 1.7.21
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev
- dependency-name: next
  dependency-version: 16.4.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev
- dependency-name: playwright
  dependency-version: 1.65.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev
- dependency-name: prettier
  dependency-version: 3.10.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev
- dependency-name: typescript-eslint
  dependency-version: 8.72.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-15 03:57:19 +01:00
2026-10-02 14:28:10 +02:00

@bitbaum/accountkit

One account for every bitbaum product: the account menu (who is signed in, where to go, how to sign out), and Sign in with OrangeCat (@bitbaum/accountkit/orangecat).

Each product had written its own — Loki's AccountMenu, OrangeCat's UserProfileDropdown — and each had learned half of what the other had. Loki took initials only from the name; OrangeCat never rebuilt a name from the email address; OrangeCat had arrow keys and a 44px target, Loki had neither; Loki's public pages had no menu at all, so a signed-in person could not find sign-out. This is the one menu, with both halves.

It knows nothing about how you sign in. NextAuth, Supabase, better-auth: you pass the person, the places, and a sign-out function.

Install

Use the current verified installation command on the AccountKit package page. Fleet's package registry is the source for the verified artifact and install transport; npm may lag a verified Git release. Release history distinguishes the registration designs shipped in different versions.

dist/ is committed, so the github: install needs no build step and no allowBuilds entry.

Password recovery

SignInForm includes password recovery when signInMethods(env, mail.configured) reports passwordReset. It uses the product's Better Auth client and sends the reset link back to its existing signInPath, preserving the local next path. That page must remain reachable when signed out and must render SignInForm when the reset callback carries token or error=INVALID_TOKEN. The form removes the token from browser history after reading it. Products with a separate reset route can render PasswordRecoveryForm from @bitbaum/accountkit/auth/react.

PasswordRecoveryForm takes a PasswordRecoveryClient: only requestPasswordReset and resetPassword. A Better Auth client satisfies it as is. A product on Auth.js (or any other session system) passes a small adapter object with those two functions, each resolving { error } on failure, and keeps its own users, passwords, roles and sessions. A call that rejects, such as a dropped connection, leaves the form usable with the unavailable message and the typed address kept, so the person can retry.

import type { PasswordRecoveryClient } from "@bitbaum/accountkit/auth/react";
const client: PasswordRecoveryClient = {
  requestPasswordReset: ({ email }) => post("/api/auth/forgot-password", { email }),
  resetPassword: ({ token, newPassword }) =>
    post("/api/auth/reset-password", { token, password: newPassword }),
};

The standard mail adapter is createAuthMailer from @bitbaum/accountkit/auth/mail:

import { createAuthMailer } from "@bitbaum/accountkit/auth/mail";
const mail = createAuthMailer({ site: { title: "Example", url: "https://example.ch" } });

Install its optional peer @bitbaum/mail-kit. The adapter reads deployment configuration lazily, uses the fleet sender and the product's reply address, and supports subject overrides. It rejects malformed or foreign-origin links and never logs a token, address or credential. Configuration still needs a real Resend key and working sender; this adapter does not claim delivery readiness.

The sender must actually deliver account mail: createAuthRuntime({ mail }) calls mail.send("reset", to, url). A deployment with mail.configured=false does not offer recovery and disables its server request handler. A no-op sender does not implement recovery. authLabelsFor(locale) includes recovery words; older product label overrides remain compatible through the English fallback.

The package checks the complete token/callback/reset journey against Postgres, including account-existence parity, expiry, one-time use, session revocation and external-redirect rejection. Its browser suite checks the forms at 320px, 390px and desktop width. Consumers must also verify their own page wiring and delivery.

import "@bitbaum/accountkit/styles.css";
import { AccountMenu } from "@bitbaum/accountkit";

Use

<AccountMenu
  user={{ name: session.user.name, email: session.user.email, image: session.user.image }}
  groups={[{ id: "nav", items: [{ id: "settings", label: "Settings", href: "/settings" }] }]}
  extra={<ThemeToggle />}
  onSignOut={() => signOut({ callbackUrl: "/sign-in" })}
  renderLink={(props) => <Link {...props} />}
/>
  • onSignOut may return a promise. While it runs the row says so; if it rejects, the menu stays open and says sign-out did not complete. A sign-out that fails silently is the one thing this menu must never do.

  • renderLink keeps your router (Next <Link>); the default is a plain <a>.

  • extra is for rows that are not places, such as a theme switch.

  • shown on an item or a group, and extraShown for extra: "always" (the default) or "narrow", shown below 768px only. For a row that repeats a control the header itself carries from that width up, such as a theme toggle that is hidden md:inline-flex in the header: on a phone the menu row is the only way to it, on a desktop it would be the same control twice. The package's stylesheet hides it in a media query, so the server render and the first paint are already right (no width is read in script, nothing flashes), the arrow keys step over a hidden row, and a group whose shown is "narrow", or whose every item's is, goes with its divider.

    groups={[
      { id: "places", items: places },
      { id: "appearance", shown: "narrow", items: [{ id: "theme", label: "Appearance: Auto", onSelect: cycleTheme }] },
    ]}
    
  • accounts and onSwitchAccount list the other accounts this person can become (a second identity, a work account) under who is signed in, and switch on a tap. Each is { id, user, note? }; note says what the account is to the person ("Main account") and leads its second line. Their email is never shown. onSwitchAccount(id) may return a promise: the row says it is switching, and if it rejects the menu stays open and says the switch did not complete, as sign-out does. With no accounts, or no onSwitchAccount, the menu is unchanged. An account may carry waiting, a count of what waits there (unread messages, notifications): it is shown at the end of its row, capped at 99+, and as a dot on the trigger so it is known before the menu is opened.

  • labels translates every string: labels={{ trigger: "Konto: {name}", signOut: "Abmelden" }}.

A static site, or a session on another origin

A site with no accounts of its own (static files) shows the account of the product that holds it. That product answers a small JSON summary with credentialed CORS for the site's origin, at least { "signedIn": false } or { "signedIn": true, "user": { "name", "handle", "image" } }. Three pieces, all from the browser-safe . entry:

  • AccountControl is the header control in all three states: state="loading" is an empty box the trigger's exact size (hidden from assistive technology, not focusable), so nothing moves when the answer arrives; state={null} is one "Sign in" link, the trigger's height, in the same slot; a person is AccountMenu, unchanged, with the rest of the props. The link's text is signIn.label, else labels.signIn, else "Sign in". A javascript: href becomes #.
  • accountSignInHtml({ href, label }) returns byte for byte what AccountControl renders signed out, with href and label escaped, so a page can print the signed-out state without React and mount the control over it later.
  • fetchAccountSummary(url, { signal?, fetch?, timeoutMs? }) is a GET with credentials: "include" and cache: "no-store". It resolves the parsed body when the answer is 2xx JSON with a boolean signedIn, and null on a network or CORS failure, an abort, a timeout, a non-2xx status, a body that is not JSON or one without signedIn, or an injected fetch that resolves to something that is not a response. The promise never rejects, never retries and stores nothing, so the header fails closed to "Sign in". timeoutMs (default 8000; 0, a negative number or Infinity turns it off) bounds the whole read, body included, so a stalled server cannot leave the header loading for ever; it is combined with your signal (AbortSignal.any where the runtime has it, by hand otherwise), and whichever fires first resolves null.
import { useEffect, useState } from "react";
import { AccountControl, accountSignInHtml, fetchAccountSummary } from "@bitbaum/accountkit";

type Summary =
  | { signedIn: false; links: { signIn: string } }
  | { signedIn: true; user: { name: string; handle: string; image: string | null }; links: { signIn: string; signOut: string } };

// Printed into the header by the build, before any script runs:
//   accountSignInHtml({ href: "https://accounts.example/sign-in" })

function Account() {
  const [summary, setSummary] = useState<Summary | null | "loading">("loading");
  useEffect(() => {
    const controller = new AbortController();
    fetchAccountSummary<Summary>("https://accounts.example/api/session", { signal: controller.signal }).then(setSummary);
    return () => controller.abort();
  }, []);
  const state = summary === "loading" ? "loading" : summary?.signedIn ? summary.user : null;
  return (
    <AccountControl
      state={state}
      signIn={{ href: summary && summary !== "loading" ? summary.links.signIn : "https://accounts.example/sign-in" }}
      onSignOut={() => {
        if (summary !== "loading" && summary?.signedIn) location.assign(summary.links.signOut);
      }}
    />
  );
}

returnPath(from, fallback = "/") is exported from . as well (it is the same function ./orangecat exports): it accepts only a same-origin path and refuses protocol-relative paths, backslashes, control characters and absolute URLs.

What is shared, and not configurable

  • The name is never built from the email. No name: @handle. No handle: "Account".
  • Initials come from the name only. No name and no photo: a person glyph.
  • A photo that fails to load falls back to initials, then the glyph.
  • 44px trigger and rows. The panel's width is capped by the screen and it aligns to the trigger's inside edge. Where the trigger is not the last control in its row (a menu button after it), the open panel is measured and moved back inside the screen; where it already fits, it is not moved. It is measured again while open when the window resizes and, without a window resize, when the panel or the row it sits in changes size or a control is added to or removed from that row (a ResizeObserver and a MutationObserver, where the runtime has them). The browser check holds it inside 320 and 390px with a 44px control before or after the trigger, for both align values.
  • Escape closes and returns focus to the trigger, wherever focus was. Arrows, Home and End move between items. A click outside closes.

Theming

Every colour, radius and font is an --acct-* variable. The defaults read @bitbaum/design-tokens at zero specificity, so apps on those tokens match with no work and an app's own :root always wins. An app whose tokens are full colours rather than HSL triplets (Loki's are OKLCH) maps them once:

:root {
  --acct-panel: var(--surface-overlay);
  --acct-fg: var(--text-primary);
  /* … */
}

Accounts (@bitbaum/accountkit/auth)

Every product owns its accounts, and they are the same account system everywhere: email and password, a magic link, passkeys, two-factor codes, the shared bitbaum sign-in and Sign in with OrangeCat (each shown only when configured). Built on better-auth 1.x, so a product writes none of it.

// lib/db/schema.ts — one identical migration in every product
export * from "@bitbaum/accountkit/auth/schema";

// lib/auth.ts
import { createAuthRuntime } from "@bitbaum/accountkit/auth/next";
export const { GET, POST, getSession, requireUser, authStatus, getAuth } = createAuthRuntime({
  site: { url: "https://app.example.ch", title: "Example", slug: "example" },
  mail: { configured, send },            // your mail-kit sender; never log the link
  isDatabaseConfigured: (env) => Boolean(env.DATABASE_URL),
  getDatabase: () => db,                 // Drizzle, built on first use
});

// app/api/auth/[...all]/route.ts
export { GET, POST } from "@/lib/auth";

// lib/auth-client.ts
import { createAuthClient } from "better-auth/react";
import { authClientPlugins } from "@bitbaum/accountkit/auth/client";
export const authClient = createAuthClient({ plugins: authClientPlugins() });

The screens are shared too (@bitbaum/accountkit/auth/react): SignInForm, SignUpForm and AccountPanel. They hold the logic and take the product's words (labels: authLabelsFor(locale) from @bitbaum/accountkit/auth has English, German, French, Italian, Romansh and Russian, so a product keeps no copy of its own; override account.roles if its roles have other names) and look (classes; without them the acct-auth-* classes in styles.css apply, on --acct-* variables):

<SignInForm client={authClient} methods={signInMethods(process.env, mailConfigured)}
  labels={myLabels} classes={{ button: "btn-primary", input: "field" }}
  next="/de/matters" signInPath="/de/sign-in" signUpLink={<Link href="/sign-up">…</Link>} />

A product whose people start from a code it gave them (AOZ's personal codes) passes codeDoor to SignInForm ({ open, label, placeholder, hint, uppercase, param, first }: its words for the code, the query parameter a personal link carries it in), served by the server's domainCredentials; and renders ClaimForm for the first password (proof: { kind: "code", label, prefix, … } for a typed code, { kind: "given", credential } for a claim link the page holds), served by provisioning. Both call through the client's $fetch.

A product whose rows were keyed on an OrangeCat actor id before it had accounts passes legacyIdentityProvider: "orangecat": a person whose first way in was OrangeCat keeps that id as user.actorId, so nothing has to be migrated; everyone else's actorId is their user id.

What is the same everywhere, and not configurable per product: one password rule, MIN_PASSWORD_LENGTH = 1 and MAX_PASSWORD_LENGTH = 128 (exported from @bitbaum/accountkit/auth/password, browser-safe, together with passwordProblem(password); products that keep their own account code import the rule from there), the same in sign-up, reset and the server, with no strength meter, no hint text and no other requirement; a sign-up asks for an email and a password, nothing else; sessions of 14 days; no IP addresses stored; an address is never an identity (a new method joins an account only when the signed-in person links it); provider tokens are never kept; a sign-up cannot choose its role; one rate limiter keyed on the proxy's hop (limitkit), with a stricter bucket for anything that sends mail. signInMethods(env, mailConfigured) says which buttons to show, as booleans, plus signinProviders: the names the shared sign-in (Morulia) publishes at <SIGNIN_ISSUER>/api/providers. Its button reads "Continue with Google, GitHub or Facebook" for exactly those names (signinButtonLabel(labels, names), from withSigninProviders and listOr in every shipped language), and is hidden until the service has answered with at least one. The list is read in the background when the auth instance is created and again at most once a minute; a failed read keeps the last good list.

Needs BETTER_AUTH_SECRET (32+ characters; a product moving off next-auth may keep its AUTH_SECRET) and a database; without them every auth route answers 503 accounts_unavailable instead of crashing. Peer dependencies: better-auth, @better-auth/passkey, drizzle-orm, and next for /auth/next.

Verify

pnpm run verify   # format, lint, types, build, unit + render tests, real-browser checks

The browser checks run the demo at 390px in light and dark: 44px targets, no sideways scroll with the menu open, Escape after a mouse open, arrow keys, outside click, a broken photo, an anonymous account, and a failing sign-out.

Sign in with OrangeCat — @bitbaum/accountkit/orangecat

Nine apps wrote this themselves and each learned something the others had not. This is all of it, once. Server-only, no next-auth import (the types are structural), so it serves Auth.js v5 and next-auth v4.

import { orangecatClient, orangecatProvider, syncOcSession } from "@bitbaum/accountkit/orangecat";

const orangecat = orangecatClient(); // ORANGECAT_OAUTH_CLIENT_ID / _SECRET / _ISSUER, or null

export const { handlers, auth, signIn, signOut } = NextAuth({
  session: { strategy: "jwt" },
  pages: { error: "/auth/error" },
  providers: orangecat ? [orangecatProvider(orangecat)] : [],
  callbacks: {
    jwt: ({ token, account, profile }) => syncOcSession({ token, account, profile }, orangecat),
    session: ({ session, token }) => ({ ...session, actorId: token.actorId }),
  },
});

What is not configurable, and why:

  • client_secret_post and PKCE. OrangeCat's token endpoint accepts only client_secret_post; the Auth.js default is answered with a 400 that reads "client_id is required". PKCE is required even with a secret.
  • profile() has no email. OrangeCat auto-confirms addresses, so email_verified proves nothing. With an email, Auth.js looks a new account up by it and either links (takeover) or refuses. The address rides along as contactEmail, contact data only. The identity is sub (token.actorId), never the email.
  • A revoked grant ends the session. syncOcSession refreshes once the access token expires; invalid_grant drops actorId (read that, never token.sub, as "signed in"); any other failure keeps the session and retries in 60 s. Safe inside jwt() since orangecat#1212 (confidential clients keep their refresh token).

Entry: signIn("orangecat", { redirectTo: returnPath(from) }, authorizationParams({ mode, email, provider })) → prompt=create, login_hint, idp_hint (google, github — the providers OrangeCat has switched on). returnPath accepts only same-origin paths.

Apps with their own user table:

  • withOrangecatIdentity(adapter, store, { keepTokens }) — an OrangeCat sign-in resolves by sub alone; a new sub always creates a new user, stored with its OrangeCat address when free and orangecat-<sub>@users.invalid when taken. Linking an existing account is Auth.js's own path (sign in, then sign in with OrangeCat). keepTokens: true also writes the accounts row (for an app that calls OrangeCat on the person's behalf).
  • resolveOrangecatUser(store, identity) — the same, for a callback (next-auth v4, no adapter). Survives the insert race.
  • decideOrangecatSignIn(input, policy) — the pure rule, with whenEmailTaken / whenNoEmail: "refuse" for an app that prefers to send the person to connect from their profile.
  • mintLinkToken / readLinkToken — evig's "Connect OrangeCat": a 10-minute signed cookie set from inside the session, so the identity that comes back attaches to that account and no other.
  • emailEarnsPromotion(provider) — never ADMIN_EMAILS promotion for an OrangeCat login.
  • mayReceivePasswordReset({ email, hasPassword, orangecatLinked }) — no reset link for an account OrangeCat created, or for a placeholder.

The error screen

import { SignInError } from "@bitbaum/accountkit";

// app/auth/error/page.tsx — Auth.js `pages.error`
<SignInError error={searchParams.error} retry={restartSignIn} retryFields={{ from }} home="/" />

Import @bitbaum/accountkit/styles.css (once, in the root layout or globals) and map the --acct-* variables onto the app's tokens, or the screen renders as bare text — solon shipped exactly that once, and no lint or typecheck can see it. Look at it at 390px before merging.

Try again restarts sign-in (a server action calling signIn("orangecat", …), or a GET route that does). It never goes home, and it never prints the provider's error code. No hooks: renders in a server component.

MIT.

Request-dependent sessions

getSession() is a server-component request API. It reads Next headers before checking deployment readiness and lets framework rendering signals propagate. A build without account secrets must not cache a signed-out page or redirect for all future sessions. Calls outside a request are errors, not signed-out users.

A sign-in link opens wherever the mail app opens it, often another browser or another device than the one where the person asked. When the product's mailer says it can carry a code (codes: true on the AuthMailer; createAuthMailer from @bitbaum/accountkit/auth/mail has it), the same email also carries a six-digit code, and SignInForm offers a field for it under "We sent a link". It is the same method, the address proven by mail: no third party and no key. Ten minutes, three tries, stored hashed, and a second factor applies to it as to every other way in. A product with its own mailer reads extra.code in send(kind, to, url, extra) and sets codes: true; until it does, nothing changes. better-auth's other email-code endpoints (a code on its own, reset, verification, email change) answer 404.

Lightning login

ACCOUNTKIT_LIGHTNING=1 turns on LNURL-auth (LUD-04): a QR code on the sign-in and sign-up cards, and "Add Lightning wallet" in the account panel. The person's wallet signs a one-time challenge with a key it derives for this site and calls /api/auth/lightning/callback; the page, polling /api/auth/sign-in/lightning, is signed in once the signature checks out. The key is the sign-in method (providerId: "lightning"), the person gets a placeholder address, and a second factor applies. Only the browser that showed the code can claim it. authClientPlugins() includes lightningClient().

The product's own mail template

createAuthMailer({ site, render, codes: true }) sends the product's own template (its languages, its HTML) through the shared transport, with the same origin check, and puts the sign-in code in extra.code for the template to print. own: { verify: async (to, url) => sent } replaces one kind of mail with the product's own; resolving false sends the shared one instead.

Second-factor policy

An enabled second factor applies to password, email-link, passkey and OIDC sign-in. The server reuses BetterAuth's native signed challenge, trusted-device validation, attempt limits and expiry. A primary credential alone does not leave an authenticated session while the challenge is pending.

Shared forms complete both JSON twoFactorRedirect responses and app-local ?twoFactor=1 redirects. Custom clients must handle those states and supply their local sign-in screen as errorCallbackURL for email/OIDC callbacks. SignUpForm accepts an optional signInPath for nonstandard route names; standard /sign-up routes infer the sibling /sign-in. Challenge URLs contain no bearer credential.

Password entry

The shared registration form has one password field with a localized show/hide control, preserves paste and password-manager autofill, and asks for no real name. The password reset form uses the same field (one input, the same show/hide control), so sign-up and reset cannot drift. Both forms and the server read the one rule from src/auth/password.ts; there is no other password requirement and no hint text. Passwordless methods keep their existing flow. Products consume this behavior through the package rather than duplicating it.

A product that keeps its own sign-in and its own bcrypt/bcryptjs uses @bitbaum/accountkit/auth/password for the rule (a require build exists for CommonJS backends), @bitbaum/accountkit/auth/password-field for the field and @bitbaum/accountkit/auth/hash for hashing. createPasswordHasher(bcrypt) hashes the SHA-256 of the password, so a long password is not cut at bcrypt's 72 bytes, and still verifies old plain bcrypt hashes; its verify returns rehash: true when a sign-in matched an old hash, and the product then stores hash(password). No one has to reset a password.

When moving those accounts into the shared runtime, pass legacyBcrypt: bcrypt to createAuthRuntime or createAuthInstance and import the existing hashes under the same stable user ids. The runtime then verifies plain bcrypt and $bs1$ hashes as well as native scrypt hashes. New registrations and password resets write native scrypt; reset still revokes existing sessions. Identity and role mapping, migration verification and product journeys remain the consumer's responsibility. This option alone does not migrate any data.

A product that stored its own format instead passes legacyPassword: { matches(hash), verify(password, hash) }. matches claims a stored hash by its shape and is asked first, so it must claim only that product's hashes; verify answers whether the password fits. It works alone or beside legacyBcrypt, and new passwords are native scrypt either way.

Moving a product off Auth.js

A product whose pages call next-auth/react can run on the shared runtime before any page changes. @bitbaum/accountkit/auth/nextauth-compat answers that client protocol (session, csrf, providers, signout, each credentials callback, and signin/<oidc> for every configured OIDC client) from AccountKit:

const compat = createNextAuthCompat({
  runtime: sharedAuth, // createAuthRuntime(...)
  siteUrl: () => process.env.AUTH_URL!,
  signInPath: "/login",
  landing: "/dashboard",
  toSession: async (shared) => productSessionFromRows(shared.user.id),
  credentials: {
    credentials: { name: "Email", resolve: async (form) => ({ email: String(form.get("email")) }) },
  },
});
// app/api/auth/[...nextauth]/route.ts, with the switch on:
export const { GET, POST } = compat.route;

The product supplies only what is its own: the session shape (re-read from its rows on every request), which address each credentials form signs in (or a refusal code such as an account lock), the codes its login page reads, and hooks after a sign-in or a refusal. sharedRuntimeEnabled() (@bitbaum/accountkit/auth/switch) reads the one switch, AUTH_RUNTIME=accountkit. sessionFor(headers) serves a proxy, currentSession() a server component, and sessionIdFor(headers) names the session making a change so the product can keep it while ending the others. AccountKit's own sign-up, reset and password endpoints answer 404 through it, so the product's writers stay the only ones until it adopts AccountKit's screens.

When the product renders SignInForm, SignUpForm and AccountPanel and has retired its own credential writers, it passes screens: "accountkit": every AccountKit endpoint opens (magic link, passkeys, two-factor, recovery, password change), and useSession and signOut on its remaining pages keep answering with the product's own session shape.

accountkit-rehearse-import <import.sql> runs a product's own import SQL against DATABASE_URL in one transaction that always rolls back, and prints only counts. It uses the product's pg or postgres driver. @bitbaum/accountkit/auth/compat-testing gives journey tests a client that speaks what next-auth/react sends and keeps the cookie jar.

A product's own plugins

plugins (both createAuthRuntime and createAuthInstance) mounts a product's own better-auth plugins for its domain, such as organization() for workspaces, after AccountKit's own. They add endpoints and tables; the shared sign-in methods, limits and cookie rules stay AccountKit's. Pass their tables in schema under the plugin's model names (organization, member, invitation), and a session table with any column the plugin adds.

A product served on more than one host (a tenant host beside its platform host) lists the others in site.trustedOrigins, or passes a lookup when its hosts are data. Their requests pass the origin check and keep their own host-only cookies; mail links and passkeys use site.url. A lookup that fails trusts only site.url.

A product's own row for each person

onAccountCreated (both createAuthRuntime and createAuthInstance) is called for every new person, however they came in: password sign-up, an email sign-in link, OrangeCat or another OIDC provider. It runs as each sign-in method is attached; a person created without one (a first email sign-in link) is reported once, as soon as they exist, with providerId: NO_SIGN_IN_METHOD and accountId set to their user id. A product creates its own row there (idempotently) and needs no after-hook on /magic-link/verify.

onAccountDeleted({ userId, email }) is called once a person's account is deleted (the account panel, or any path that deletes the user), so the product removes or anonymises its own row. It runs only after the deletion. A product that must refuse a deletion refuses before it starts, with a plugin before hook on /delete-user (and /delete-user/callback); that stops it before anything is deleted, and onAccountDeleted is not called. A throw in either hook is logged and never blocks the sign-in or undoes the deletion, so a product whose row must go in the same transaction keeps a database trigger.

A product with a duty to keep what an account holds (a clinic keeps medical records for years) passes accountDeletion: false: /delete-user answers 404 and deletes nothing. It gives AccountPanel its own way out as deletion, for example a link to its erasure request, which the panel shows in place of the delete control, beside "Sign out". A product that shows and edits the person's name on its own page passes ownProfile to AccountPanel, which then leaves its Profile section out.

Account tables beside a product's own

A product whose tables already use the standard names (a NextAuth users, accounts, sessions) creates the account tables under a prefix and passes them to the runtime: const tables = createAuthTables("auth_"), then schema: tables (both createAuthRuntime and createAuthInstance). The columns are identical to the standard set; only table and index names change.

Confirming an address never stands in the way

By default a password account signs in the moment it is created, and an existing account signs in whether or not its address was ever confirmed. With mail, every sign-up is also sent a confirmation link; following it sets user.emailVerified. A product that keeps some powers for confirmed addresses (staff, payouts) reads emailVerified on the session itself.

A product that cannot let an unconfirmed address in passes emailConfirmation: "before-sign-in" to createAuthRuntime / createAuthInstance, and the same value to signInMethods(env, mailConfigured, { emailConfirmation }) so its forms say "check your inbox". It takes effect only with mail: without mail the link could never arrive.

UUID ids for a product keyed on uuid

A product whose own rows reference people by a uuid column (evig's users) passes ids: "uuid" (both createAuthRuntime and createAuthInstance). Every id the runtime mints is then a random UUID, so a person AccountKit creates itself, at a first OIDC sign-in or through its own sign-up, can be given the product's row under the same id in onAccountCreated. Imported ids stay as they were; without the option the ids are better-auth's own strings.

Domain credentials during migration

createAuthRuntime and createAuthInstance accept an optional domainCredentials.verify(credential) callback. It returns null for an invalid proof, or { userId, bindSession? } for an existing shared user. This enables POST /api/auth/sign-in/domain with { credential }; use the runtime's POST handler so the shared credential limiter applies. Never accept a user id from the request as the verification result.

bindSession(sessionId) persists product-owned restrictions before the session cookie is set. For example, a staff code of a dual-identity account grants only the staff surface. Store that scope against the shared session id with cascade deletion and read it on every product request. A failed binding revokes the new session. Domain sessions have fixed expiry and cannot enroll credentials, change account security or list other sessions. Show a password/passkey/provider sign-in action before offering account management. An account with an enabled second factor must use another configured primary method; domain proof alone never bypasses MFA. The shared tables require no change for this option.

First passwords and linking a second identity

A product that created people before they had a password (an invitation, a login code) passes provisioning.resolve(credential). It returns null, or { userId, link?, complete?, release? } for the shared user that holds the identity the proof names. This enables POST /api/auth/provision/claim with { credential, email, password, name?, callbackURL? }, rate limited as a credential. Take a single-use proof inside resolve and give it back in release, which runs on every failure after it.

  • A user with no password gets one, under its existing id, at the address typed. An address that cannot receive mail (.invalid) is refused. A verified address is never replaced; the same address keeps its verification, a new one starts unverified.
  • An address that belongs to another account joins this identity to it only on that account's own password, then calls link(targetUserId). Without link the claim is refused. If that account has no password yet (invited, never claimed), the claim is refused with CLAIM_EMAIL_NEEDS_RECOVERY: recovery through its mailbox comes first.
  • An identity that already has a password is refused; sign in or recover.
  • The person is signed in at once (status: "signed_in"); with mail an unverified address also gets its confirmation link. A product that set emailConfirmation: "before-sign-in" gets the link and no session instead (status: "verify_email"); the link signs them in. An account with a second factor is linked but must still sign in (status: "sign_in").

Refusals carry the codes in CLAIM_ERRORS (@bitbaum/accountkit/auth).

A shorter idle limit for some people

sessionLifetime(userId) returns seconds, or nothing for the shared default (14 days). For a person it names, a session idle longer than that is deleted on its next request, an active one slides to now + limit at most once an hour, and the shared 14-day refresh never applies. Products use it where their own rule is stricter, for example staff on 8 hours.

A used password-reset link verifies the address it was sent to, unless the account's address changed after it was sent. Recovery therefore leaves an imported or invited account with a usable sign-in when mail is configured.

S
Description
No description provided
Readme MIT
1.1 MiB
0 Stars 2 Watchers 0 Forks
Languages
TypeScript 53.6%
JavaScript 43.9%
CSS 2.5%