Files
opencode-manager/backend/src/auth/index.ts
T
Chris Scott f8e4cfe136 feat(device-pairing): pair phones and browsers with a QR code
Settings -> Account gets "Connect a device", a paired-devices list, and a
remote access headers editor, so the mobile app and other browsers can sign
in without typing a password and pass a reverse proxy such as Cloudflare
Access.

- one-time pairing codes (3 min TTL) minted by a Better Auth plugin and
  redeemed into a new session that records the device name
- POST /api/device-pairing/links builds the ocm://link app link with the
  stored headers as h= parameters and a browser /pair link; plain-HTTP and
  loopback origins are blocked or warned about
- remote access headers are stored encrypted, returned by name only, and
  validated (8 headers, 512-char values, 1800 encoded characters, reserved
  transport names blocked); a Cloudflare Access service token preset fills
  CF-Access-Client-Id and CF-Access-Client-Secret
- login offers "Sign in with QR code" and /pair redeems a scanned code,
  returning to the login redirect target
- revoking a device deletes its session, closes its live connections and
  removes its push subscriptions; the current session cannot be revoked
2026-10-24 19:26:21 -04:00

139 lines
3.7 KiB
TypeScript

import { betterAuth } from 'better-auth'
import { APIError } from 'better-auth/api'
import { passkey } from '@better-auth/passkey'
import { Database } from 'bun:sqlite'
import { ENV, getTrustedOrigins } from '@opencode-manager/shared/config/env'
import { AUTH_COOKIE_PREFIX } from './cookies'
import { AUTH_SOCKET_IP_HEADER } from './client-ip'
import { devicePairing } from './device-pairing'
import { closeSessionConnections } from '../services/session-connections'
import { deletePushSubscriptionsForSession } from '../db/push-subscriptions'
export type AuthInstance = ReturnType<typeof createAuth>
export function isAdminConfigured(): boolean {
return !!(ENV.AUTH.ADMIN_EMAIL && ENV.AUTH.ADMIN_PASSWORD)
}
export function createAuth(db: Database) {
const socialProviders: Record<string, { clientId: string; clientSecret: string }> = {}
if (ENV.AUTH.GITHUB_CLIENT_ID && ENV.AUTH.GITHUB_CLIENT_SECRET) {
socialProviders.github = {
clientId: ENV.AUTH.GITHUB_CLIENT_ID,
clientSecret: ENV.AUTH.GITHUB_CLIENT_SECRET,
}
}
if (ENV.AUTH.GOOGLE_CLIENT_ID && ENV.AUTH.GOOGLE_CLIENT_SECRET) {
socialProviders.google = {
clientId: ENV.AUTH.GOOGLE_CLIENT_ID,
clientSecret: ENV.AUTH.GOOGLE_CLIENT_SECRET,
}
}
if (ENV.AUTH.DISCORD_CLIENT_ID && ENV.AUTH.DISCORD_CLIENT_SECRET) {
socialProviders.discord = {
clientId: ENV.AUTH.DISCORD_CLIENT_ID,
clientSecret: ENV.AUTH.DISCORD_CLIENT_SECRET,
}
}
const trustedOrigins = getTrustedOrigins()
const baseURL = trustedOrigins[0] || `http://localhost:${ENV.SERVER.PORT}`
const auth = betterAuth({
baseURL,
basePath: '/api/auth',
database: db,
secret: ENV.AUTH.SECRET,
trustedOrigins,
emailAndPassword: {
enabled: true,
minPasswordLength: 8,
maxPasswordLength: 128,
autoSignIn: true,
},
socialProviders: Object.keys(socialProviders).length > 0 ? socialProviders : undefined,
databaseHooks: {
session: {
delete: {
after: async (session) => {
closeSessionConnections(session.id)
},
},
},
user: {
create: {
before: async (user, context) => {
if (isAdminConfigured() && (context?.request || user.email.toLowerCase() !== ENV.AUTH.ADMIN_EMAIL!.toLowerCase())) {
throw new APIError('FORBIDDEN', { message: 'Registration is disabled' })
}
},
},
},
},
plugins: [
passkey({
rpID: ENV.AUTH.PASSKEY_RP_ID,
rpName: ENV.AUTH.PASSKEY_RP_NAME,
origin: ENV.AUTH.PASSKEY_ORIGIN,
authenticatorSelection: {
residentKey: 'required',
userVerification: 'required',
},
}),
devicePairing({
onDeviceRevoked: (sessionId) => deletePushSubscriptionsForSession(db, sessionId),
}),
],
session: {
expiresIn: 60 * 60 * 24 * 7,
updateAge: 60 * 60 * 24,
},
user: {
additionalFields: {
role: {
type: 'string',
required: false,
defaultValue: 'user',
input: false,
},
},
},
advanced: {
cookiePrefix: AUTH_COOKIE_PREFIX,
useSecureCookies: ENV.AUTH.SECURE_COOKIES,
ipAddress: {
ipAddressHeaders: [AUTH_SOCKET_IP_HEADER],
},
},
})
return auth
}
export type Session = {
session: {
id: string
userId: string
token: string
expiresAt: Date
createdAt: Date
updatedAt: Date
ipAddress?: string | null
userAgent?: string | null
deviceName?: string | null
}
user: {
id: string
name: string
email: string
emailVerified: boolean
image?: string | null
createdAt: Date
updatedAt: Date
role?: string
}
}