Open History to see the last commit
1import { useEffect, useState } from 'react'
2import { createFileRoute, useRouter } from '@tanstack/react-router'
3import { usePostHog } from '@posthog/react'
4
5import { SiteFooter, SiteNav } from '#/components/site.tsx'
6import { authClient } from '#/lib/auth-client.ts'
7import { posthogIntegrationLogger } from '#/lib/posthog-logger.ts'
8
9export const Route = createFileRoute('/account')({
10 component: Account,
11})
12
13interface KeyRow {
14 id: string
15 name: string | null
16 start: string | null
17 createdAt: string | Date
18 expiresAt: string | Date | null
19 enabled: boolean
20}
21
22const EXPIRY_CHOICES: Array<[label: string, seconds: number | undefined]> = [
23 ['Never expires', undefined],
24 ['30 days', 30 * 86_400],
25 ['90 days', 90 * 86_400],
26 ['1 year', 365 * 86_400],
27]
28
29function Account() {
30 const router = useRouter()
31 const posthog = usePostHog()
32 const { data: session, isPending } = authClient.useSession()
33 const [keys, setKeys] = useState<Array<KeyRow>>([])
34 const [name, setName] = useState('')
35 const [expiry, setExpiry] = useState<string>('')
36 const [createdKey, setCreatedKey] = useState<string | null>(null)
37 const [busy, setBusy] = useState(false)
38 const [error, setError] = useState<string | null>(null)
39
40 const refresh = async () => {
41 const { data } = await authClient.apiKey.list()
42 const rows = Array.isArray(data)
43 ? (data as Array<KeyRow>)
44 : ((data as { apiKeys?: Array<KeyRow> } | null)?.apiKeys ?? [])
45 setKeys(rows)
46 }
47
48 useEffect(() => {
49 if (session) void refresh()
50 }, [session])
51
52 const createKey = async (event: React.FormEvent) => {
53 event.preventDefault()
54 setBusy(true)
55 setError(null)
56 const expiresIn = expiry === '' ? undefined : Number(expiry)
57 const { data, error: createError } = await authClient.apiKey.create({
58 name: name || 'api key',
59 ...(expiresIn !== undefined ? { expiresIn } : {}),
60 })
61 setBusy(false)
62 if (createError) {
63 setError(createError.message ?? 'Could not create the key.')
64 return
65 }
66 setCreatedKey((data as { key: string }).key)
67 posthog.capture('api_key_created', {
68 expires_in_days:
69 expiresIn === undefined ? null : Math.round(expiresIn / 86_400),
70 name_provided: name.trim() !== '',
71 })
72 posthogIntegrationLogger.info(posthog, 'API key operation completed', {
73 action: 'create',
74 expiring: expiresIn !== undefined,
75 status: 'success',
76 })
77 setName('')
78 await refresh()
79 }
80
81 const revokeKey = async (keyId: string) => {
82 setError(null)
83 const { error: deleteError } = await authClient.apiKey.delete({ keyId })
84 if (deleteError) {
85 setError(deleteError.message ?? 'Could not revoke the key.')
86 return
87 }
88 posthog.capture('api_key_revoked', { key_id: keyId })
89 posthogIntegrationLogger.info(posthog, 'API key operation completed', {
90 action: 'revoke',
91 status: 'success',
92 })
93 await refresh()
94 }
95
96 const signOut = async () => {
97 const { error: signOutError } = await authClient.signOut()
98 if (!signOutError) {
99 posthog.capture('user_logged_out')
100 posthog.reset()
101 }
102 await router.invalidate()
103 }
104
105 const inputClasses =
106 'hairline border bg-paper-raised px-3 py-2 font-mono text-sm text-ink outline-none transition-colors focus:border-ink'
107
108 if (isPending) return null
109 if (!session) {
110 return (
111 <div className="min-h-screen text-ink">
112 <SiteNav active="account" />
113 <div className="mx-auto max-w-sm space-y-4 px-5 py-16 text-sm">
114 <h1 className="font-mono text-2xl font-semibold tracking-tight">
115 Account<span className="text-tok-blue">▌</span>
116 </h1>
117 <p className="text-ink-soft">
118 You need to sign in to manage API keys.
119 </p>
120 <a className="press-link" href="/login">
121 Sign in with email →
122 </a>
123 </div>
124 <SiteFooter />
125 </div>
126 )
127 }
128
129 return (
130 <div className="min-h-screen text-ink">
131 <SiteNav active="account" />
132 <div className="mx-auto max-w-2xl space-y-8 px-5 py-14">
133 <header className="space-y-2">
134 <h1 className="font-mono text-2xl font-semibold tracking-tight">
135 Account<span className="text-tok-blue">▌</span>
136 </h1>
137 <p className="text-sm text-ink-soft">
138 Signed in as <span className="font-mono">{session.user.email}</span>{' '}
139 ·{' '}
140 <button
141 type="button"
142 className="press-link"
143 onClick={() => {
144 void signOut()
145 }}
146 >
147 sign out
148 </button>
149 </p>
150 </header>
151
152 <section className="space-y-3">
153 <h2 className="overline-label rule-heavy pb-2 !text-ink">API keys</h2>
154 <p className="text-sm text-ink-soft">
155 Keys unlock 5,000 requests/hour (vs 60/hour anonymous) and webhook
156 subscriptions. Send them as{' '}
157 <code className="bg-paper-raised px-1 text-press-deep">
158 Authorization: Bearer <key>
159 </code>
160 .
161 </p>
162
163 {createdKey ? (
164 <div className="figure space-y-2 p-4 text-sm">
165 <p className="font-medium">
166 Key created — copy it now, it is shown exactly once:
167 </p>
168 <code className="block break-all bg-paper px-2 py-1 text-press-deep">
169 {createdKey}
170 </code>
171 <pre className="overflow-x-auto bg-paper px-2 py-1 font-mono text-xs text-ink-soft">
172 {`curl https://modelschemas.com/v1/agents/me \\\n -H "Authorization: Bearer ${createdKey}"`}
173 </pre>
174 <button
175 type="button"
176 className="press-link font-mono text-xs text-ink-faint"
177 onClick={() => setCreatedKey(null)}
178 >
179 Done, hide it
180 </button>
181 </div>
182 ) : null}
183
184 <form
185 className="flex flex-wrap gap-2"
186 onSubmit={(event) => {
187 void createKey(event)
188 }}
189 >
190 <input
191 className={`${inputClasses} flex-1`}
192 placeholder="Key name (e.g. my laptop)"
193 value={name}
194 onChange={(event) => setName(event.target.value)}
195 />
196 <select
197 className={inputClasses}
198 value={expiry}
199 onChange={(event) => setExpiry(event.target.value)}
200 >
201 {EXPIRY_CHOICES.map(([label, seconds]) => (
202 <option key={label} value={seconds ?? ''}>
203 {label}
204 </option>
205 ))}
206 </select>
207 <button
208 className="border border-ink bg-ink px-4 py-2 font-mono text-sm text-paper transition-colors hover:border-press hover:bg-press disabled:opacity-50"
209 disabled={busy}
210 type="submit"
211 >
212 {busy ? 'Creating…' : 'Create key'}
213 </button>
214 </form>
215
216 {keys.length === 0 ? (
217 <p className="text-sm text-ink-faint">No keys yet.</p>
218 ) : (
219 <ul className="space-y-2">
220 {keys.map((key) => (
221 <li
222 key={key.id}
223 className="figure flex items-center gap-3 px-4 py-2.5 text-sm"
224 >
225 <span className="flex-1">
226 <span className="font-medium">{key.name ?? 'unnamed'}</span>{' '}
227 <code className="font-mono text-xs text-ink-faint">
228 {key.start ?? '…'}…
229 </code>
230 </span>
231 <span className="font-mono text-xs text-ink-faint">
232 {key.expiresAt
233 ? `expires ${new Date(key.expiresAt).toLocaleDateString()}`
234 : 'no expiry'}
235 </span>
236 <button
237 type="button"
238 className="cursor-pointer font-mono text-xs text-tok-red hover:underline"
239 onClick={() => {
240 void revokeKey(key.id)
241 }}
242 >
243 revoke
244 </button>
245 </li>
246 ))}
247 </ul>
248 )}
249 </section>
250
251 {error ? (
252 <p className="font-mono text-sm text-tok-red">{error}</p>
253 ) : null}
254
255 <footer className="font-mono text-xs text-ink-faint">
256 Agents can self-register instead — see{' '}
257 <a className="press-link text-ink-soft" href="/docs">
258 the docs
259 </a>{' '}
260 or{' '}
261 <a
262 className="press-link text-ink-soft"
263 href="/.well-known/agent-configuration"
264 >
265 agent discovery
266 </a>
267 .
268 </footer>
269 </div>
270 <SiteFooter />
271 </div>
272 )
273}