Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

auth.ts

157 lines5.9 KB

1import { betterAuth } from 'better-auth'
2import { bearer, emailOTP } from 'better-auth/plugins'
3import { apiKey } from '@better-auth/api-key'
4import { drizzleAdapter } from 'better-auth/adapters/drizzle'
5import { agentAuth } from '@better-auth/agent-auth'
6import { createFromOpenAPI, fromOpenAPI } from '@better-auth/agent-auth/openapi'
7import type { BetterAuthPlugin } from 'better-auth'
8import type { Capability } from '@better-auth/agent-auth'
9​
10import type { Db } from '#/db/index.ts'
11import * as schema from '#/db/schema.ts'
12import { openApiDocument } from '#/server/openapi.ts'
13​
14/** Capabilities never exposed to agents (admin surface). */
15const EXCLUDED_CAPABILITIES = new Set([
16 'syncProvider',
17 'extractFalPricing',
18 'exportCatalog',
19])
20​
21/**
22 * The public (approval-free) capability set. This is also the EXACT set an
23 * API-key principal may satisfy: API keys are the low-friction fallback for
24 * public operations and must never satisfy a privileged capability — if a
25 * capability with approvalStrength !== 'none' is ever added, keep it out of
26 * this list (see requireAgent's capability check).
27 */
28export function publicCapabilityNames(): Array<string> {
29 const derived = fromOpenAPI(
30 openApiDocument as unknown as Parameters<typeof fromOpenAPI>[0],
31 )
32 .map((capability) => capability.name)
33 .filter((name) => !EXCLUDED_CAPABILITIES.has(name))
34 return [...derived, 'manage_subscriptions']
36​
37export interface CreateAuthOptions {
38 secret?: string
39 /** Delivers sign-in OTPs (task 9.2). Injectable so tests capture codes;
40 * defaults to a structured console line. */
41 sendOtp?: (data: { email: string; otp: string }) => Promise<void>
42 /** Absolute origin used for capability execution self-calls + JWT audiences. */
43 baseUrl?: string
44 extraPlugins?: Array<BetterAuthPlugin>
45 /** Test hook: fetch used by the capability execute proxy. */
46 capabilityFetch?: typeof globalThis.fetch
48​
49function buildAgentAuthConfig(options?: CreateAuthOptions) {
50 const baseUrl = options?.baseUrl ?? 'http://localhost:3000'
51 const fromSpec = createFromOpenAPI(
52 // `as const` document → readonly arrays; the helper wants mutable.
53 openApiDocument as unknown as Parameters<typeof createFromOpenAPI>[0],
54 {
55 baseUrl,
56 fetch: options?.capabilityFetch,
57 // Reads + validate are public data: grant without human approval so
58 // the autonomous (no-human) path is friction-free.
59 approvalStrength: 'none',
60 },
61 )
62​
63 const capabilities: Array<Capability> = [
64 ...(fromSpec.capabilities ?? []).filter(
65 (capability) => !EXCLUDED_CAPABILITIES.has(capability.name),
66 ),
67 // Hand-declared: webhook subscription management (Phase 6 endpoints).
68 {
69 name: 'manage_subscriptions',
70 description:
71 'Create, list, and delete webhook subscriptions for model/schema change events.',
72 approvalStrength: 'none',
73 input: {
74 type: 'object',
75 properties: {
76 action: { type: 'string', enum: ['create', 'list', 'delete'] },
77 url: { type: 'string' },
78 events: { type: 'array', items: { type: 'string' } },
79 provider: { type: 'string' },
80 subscriptionId: { type: 'string' },
81 },
82 required: ['action'],
83 },
84 },
85 ]
86​
87 return {
88 ...fromSpec,
89 providerName: 'modelschemas',
90 providerDescription:
91 'Live AI model schema service: per-endpoint request/response JSON Schemas and model metadata for monitored providers.',
92 // Autonomous (no human in the loop) is the primary path; delegated mode
93 // + approvals stay enabled but no current capability requires them.
94 modes: ['autonomous', 'delegated'] as Array<'autonomous' | 'delegated'>,
95 capabilities,
96 // Hosts that register without an explicit capability list get the full
97 // public set. Must be the FILTERED list — deriving from the spec would
98 // include excluded admin ops (syncProvider, extractFalPricing,
99 // exportCatalog) and 400 every registration.
100 defaultHostCapabilities: capabilities.map((capability) => capability.name),
101 // Open agent signup: unknown hosts may self-register with inline keys.
102 allowDynamicHostRegistration: true,
103 // Autonomous agents have no human owner; execute under a virtual
104 // identity (reads are public — this is identity plumbing, not access).
105 resolveAutonomousUser: ({
106 agentId,
107 hostName,
108 }: {
109 agentId: string
110 hostName: string | null
111 }) => ({
112 id: `agent:${agentId}`,
113 name: hostName ?? 'autonomous-agent',
114 email: `${agentId}@agents.modelschemas.invalid`,
115 }),
116 }
118​
119// Factory rather than a singleton: the D1-backed db only exists per-request
120// in Workers. The runtime instance lives in src/server/auth.ts; the better-auth
121// CLI loads this factory through scripts/better-auth-config.ts instead, so this
122// file must not import `cloudflare:workers` — and must not import
123// `better-auth/tanstack-start` either (its vite-resolved subpath imports break
124// outside the TanStack build; the runtime passes it via `extraPlugins`).
125export function createAuth(db: Db, options?: CreateAuthOptions) {
126 return betterAuth({
127 database: drizzleAdapter(db, { provider: 'sqlite', schema }),
128 secret: options?.secret,
129 baseURL: options?.baseUrl,
130 // Email/password backs delegated-mode approvals and the later dashboard.
131 emailAndPassword: {
132 enabled: true,
133 },
134 plugins: [
135 agentAuth(buildAgentAuthConfig(options)),
136 apiKey(),
137 bearer(),
138 // Human sign-in (task 9.2): email OTP, 6 digits, 5-minute expiry.
139 emailOTP({
140 otpLength: 6,
141 expiresIn: 300,
142 sendVerificationOTP: async ({ email, otp }) => {
143 if (options?.sendOtp) {
144 await options.sendOtp({ email, otp })
145 return
146 }
147 console.log(
148 JSON.stringify({ job: 'email', mode: 'dev-log', to: email, otp }),
149 )
150 },
151 }),
152 ...(options?.extraPlugins ?? []),
153 ],
154 })
156​
157export type Auth = ReturnType<typeof createAuth>