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

auth.ts

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