@cubicecho/better-auth-oidc-pairing
v1.2.1
Published
Pair a better-auth app with an OIDC provider from a setup URL: Dynamic Client Registration (RFC 7591/7592) on top of @better-auth/sso.
Maintainers
Readme
@cubicecho/better-auth-oidc-pairing
Pair a better-auth app with OpenID Connect providers by pasting one setup URL, instead of copying a client id, a secret and a redirect URI into its environment.
https://id.example.com/oidc#setup=<initial access token>&name=heautouThe app reads the issuer's discovery document, registers itself at its registration endpoint (RFC 7591)
and keeps the client as a @better-auth/sso provider,
so sign-in works at once, with no restart. Unpairing deletes the client at the provider (RFC 7592).
- Several providers side by side: one set in the app's environment, kept fixed, and any number paired from setup URLs (five by default).
- Providers on a LAN work. better-auth trusts only public hosts by default, and the plugin trusts each provider's origins for as long as it is paired.
- A sign-in can end in a one-time token the app spends over its own API, so the session never rides in a URL.
Every paired provider can sign in as any address it vouches for, because accounts link by address. Say so on the page where providers are added, and let only the right people pair.
Install
npm install @cubicecho/better-auth-oidc-pairing better-auth @better-auth/ssobetter-auth and @better-auth/sso are peer dependencies, >=1.7.28 <1.8.0. Node 22 or later, ESM only.
Quick start
Save this as server.mjs and run node server.mjs (Node 22.13 or later, for node:sqlite).
import { createServer } from 'node:http';
import { DatabaseSync } from 'node:sqlite';
import { oidcPairingPlugins } from '@cubicecho/better-auth-oidc-pairing';
import { betterAuth } from 'better-auth';
import { getMigrations } from 'better-auth/db/migration';
import { toNodeHandler } from 'better-auth/node';
import { bearer } from 'better-auth/plugins';
const database = new DatabaseSync('app.db');
const auth = betterAuth({
baseURL: 'http://localhost:3000',
secret: 'replace-me-with-32-random-characters-or-more',
database,
plugins: [
bearer(),
...oidcPairingPlugins({
clientName: 'my-app',
// Who may pair, unpair and see issuer URLs: the first account, or anyone while there are none.
canPair: ({ userId }) => {
const owner = database.prepare('SELECT id FROM user ORDER BY createdAt LIMIT 1').get();
return owner === undefined || owner.id === userId;
},
// The provider the operator set in the environment, or null for none.
pinned: null,
// The page that spends the one-time token, and the login page, which reads ?error=.
signedInURL: '/auth/sso',
errorURL: '/login',
}),
],
});
const { runMigrations } = await getMigrations(auth.options);
await runMigrations();
const page = (script) => `<!doctype html><body><script type="module">${script}</script>`;
// One link per provider: a full-page navigation, not a fetch.
const login = page(`
const { providers } = await (await fetch('/api/auth/oidc-pairing/providers')).json();
for (const { providerId, name } of providers) {
const link = document.createElement('a');
link.href = '/api/auth/oidc-pairing/sign-in/' + providerId;
link.textContent = 'Sign in with ' + name;
document.body.append(link);
}`);
// Spends the token once, for the bearer session.
const signedIn = page(`
const token = new URLSearchParams(location.search).get('token');
const response = await fetch('/api/auth/oidc-pairing/verify', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ token }),
});
const session = await response.json();
if (response.ok) localStorage.setItem('session', session.token);
document.body.append(response.ok ? 'Signed in as ' + session.userId : session.message);`);
const handleAuth = toNodeHandler(auth);
createServer((req, res) => {
if (req.url.startsWith('/api/auth/')) return handleAuth(req, res);
res.setHeader('content-type', 'text/html');
res.end(req.url.startsWith('/auth/sso') ? signedIn : login);
}).listen(3000);Then pair a provider with the setup URL it gave you, and sign in at http://localhost:3000/login:
curl http://localhost:3000/api/auth/oidc-pairing/pair \
-H 'content-type: application/json' \
-d '{"setupUrl":"https://id.example.com/oidc#setup=...&name=heautou"}'Documentation
- Install and wire it up
- The environment's provider and starting up
- Options for pairing: who may pair, client metadata, hooks, limits
- Endpoints and GraphQL
- The sign-in
- Errors
- The protocol on its own, without the plugin
- Moving over from genericOAuth
- Common mistakes
- Every export, as
llms.txt - Changelog
