Open History to see the last commit
1/**
2 * Webhook subscriptions CRUD (PLAN.md task 6.1). Authenticated via
3 * requireAgent (capability: manage_subscriptions). Secrets are generated
4 * server-side and returned exactly once; list responses never echo them.
5 */
6import { and, count, eq } from 'drizzle-orm'
7
8import type { Db } from '#/db/index.ts'
9import { halGet } from '#/server/hal.ts'
10import { changeTypes, subscriptions, user } from '#/db/schema.ts'
11import type { Principal } from '#/server/require-agent.ts'
12
13const MAX_SUBSCRIPTIONS_PER_OWNER = 10
14
15export interface CreateSubscriptionBody {
16 url: string
17 events: Array<string>
18 provider?: string
19}
20
21/**
22 * SSRF guard for webhook destinations: only public https hosts. Literal
23 * loopback/private/link-local addresses and internal-looking names are
24 * rejected at registration; delivery additionally refuses to follow
25 * redirects. Residual risk (DNS rebinding to edge-internal space) is
26 * accepted: Workers fetch has no privileged network position and workerd
27 * exposes no resolver to re-check A records at delivery time.
28 */
29export function isForbiddenWebhookHost(hostname: string): boolean {
30 const host = hostname.toLowerCase().replace(/\.$/, '')
31 if (
32 host === 'localhost' ||
33 host.endsWith('.localhost') ||
34 host.endsWith('.local') ||
35 host.endsWith('.internal') ||
36 host === ''
37 ) {
38 return true
39 }
40 const bare = host.replace(/^\[|\]$/g, '')
41 if (
42 bare === '::' ||
43 bare === '::1' ||
44 bare.startsWith('fe80:') ||
45 bare.startsWith('fc') ||
46 bare.startsWith('fd')
47 ) {
48 return true
49 }
50 const ipv4 = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(bare)
51 if (ipv4) {
52 const a = Number(ipv4[1])
53 const b = Number(ipv4[2])
54 if (a === 0 || a === 127 || a === 10) return true
55 if (a === 169 && b === 254) return true
56 if (a === 172 && b >= 16 && b <= 31) return true
57 if (a === 192 && b === 168) return true
58 }
59 return false
60}
61
62export function parseCreateSubscriptionBody(
63 raw: unknown,
64): CreateSubscriptionBody | null {
65 if (typeof raw !== 'object' || raw === null) return null
66 const body = raw as Record<string, unknown>
67 if (typeof body.url !== 'string') return null
68 let parsed: URL
69 try {
70 parsed = new URL(body.url)
71 } catch {
72 return null
73 }
74 if (parsed.protocol !== 'https:') return null
75 if (isForbiddenWebhookHost(parsed.hostname)) return null
76 if (
77 !Array.isArray(body.events) ||
78 body.events.length === 0 ||
79 !body.events.every(
80 (event) =>
81 typeof event === 'string' &&
82 (changeTypes as ReadonlyArray<string>).includes(event),
83 )
84 ) {
85 return null
86 }
87 if (body.provider !== undefined && typeof body.provider !== 'string') {
88 return null
89 }
90 return {
91 url: body.url,
92 events: body.events as Array<string>,
93 provider: body.provider,
94 }
95}
96
97/**
98 * The subscriptions.agent_id column FKs user.id. Autonomous agents run
99 * under a virtual identity that has no user row — materialise it on first
100 * write so FK integrity holds.
101 */
102async function ensureOwnerUser(db: Db, principal: Principal): Promise<string> {
103 const ownerId =
104 principal.kind === 'api-key'
105 ? principal.userId
106 : (principal.userId ?? `agent:${principal.agentId}`)
107 const existing = await db.query.user.findFirst({
108 where: eq(user.id, ownerId),
109 columns: { id: true },
110 })
111 if (!existing) {
112 const now = new Date()
113 await db.insert(user).values({
114 id: ownerId,
115 name: principal.name ?? 'autonomous-agent',
116 email: `${ownerId.replace(/[^a-zA-Z0-9]+/g, '-')}@agents.modelschemas.invalid`,
117 createdAt: now,
118 updatedAt: now,
119 })
120 }
121 return ownerId
122}
123
124function generateSecret(): string {
125 const bytes = new Uint8Array(32)
126 crypto.getRandomValues(bytes)
127 return `whsec_${[...bytes].map((b) => b.toString(16).padStart(2, '0')).join('')}`
128}
129
130type SubscriptionRow = typeof subscriptions.$inferSelect
131
132function toApiSubscription(row: SubscriptionRow) {
133 return {
134 id: row.id,
135 url: row.url,
136 events: row.events,
137 provider: row.providerFilter,
138 active: row.active,
139 createdAt: row.createdAt,
140 }
141}
142
143export type SubscriptionsOutcome<T> =
144 | { ok: true; result: T }
145 | { ok: false; status: number; code: string; message: string }
146
147export async function createSubscription(
148 db: Db,
149 principal: Principal,
150 body: CreateSubscriptionBody,
151 now = Math.floor(Date.now() / 1000),
152): Promise<
153 SubscriptionsOutcome<
154 ReturnType<typeof toApiSubscription> & { secret: string }
155 >
156> {
157 if (body.provider) {
158 const provider = await db.query.providers.findFirst({
159 where: (providers, { eq: equals }) =>
160 equals(providers.id, body.provider ?? ''),
161 columns: { id: true },
162 })
163 if (!provider) {
164 return {
165 ok: false,
166 status: 404,
167 code: 'unknown_provider',
168 message: `Unknown provider '${body.provider}'. See GET /v1/providers.`,
169 }
170 }
171 }
172
173 const ownerId = await ensureOwnerUser(db, principal)
174 const countRows = await db
175 .select({ n: count() })
176 .from(subscriptions)
177 .where(eq(subscriptions.agentId, ownerId))
178 const existing = countRows[0]?.n ?? 0
179 if (existing >= MAX_SUBSCRIPTIONS_PER_OWNER) {
180 return {
181 ok: false,
182 status: 409,
183 code: 'subscription_limit',
184 message: `Limit of ${String(MAX_SUBSCRIPTIONS_PER_OWNER)} subscriptions reached. Delete one first (GET /v1/subscriptions).`,
185 }
186 }
187
188 const secret = generateSecret()
189 const row: typeof subscriptions.$inferInsert = {
190 id: crypto.randomUUID(),
191 agentId: ownerId,
192 url: body.url,
193 secret,
194 events: body.events,
195 providerFilter: body.provider ?? null,
196 active: true,
197 createdAt: now,
198 }
199 await db.insert(subscriptions).values(row)
200 return {
201 ok: true,
202 result: {
203 ...toApiSubscription({ ...row, active: true } as SubscriptionRow),
204 secret,
205 },
206 }
207}
208
209export async function listSubscriptions(db: Db, principal: Principal) {
210 const ownerId =
211 principal.kind === 'api-key'
212 ? principal.userId
213 : (principal.userId ?? `agent:${principal.agentId}`)
214 const rows = await db
215 .select()
216 .from(subscriptions)
217 .where(eq(subscriptions.agentId, ownerId))
218 .orderBy(subscriptions.createdAt)
219 return {
220 count: rows.length,
221 subscriptions: rows.map(toApiSubscription),
222 _links: {
223 self: halGet('/v1/subscriptions'),
224 changes: halGet('/v1/changes'),
225 },
226 }
227}
228
229export async function deleteSubscription(
230 db: Db,
231 principal: Principal,
232 id: string,
233): Promise<SubscriptionsOutcome<{ deleted: string }>> {
234 const ownerId =
235 principal.kind === 'api-key'
236 ? principal.userId
237 : (principal.userId ?? `agent:${principal.agentId}`)
238 const existing = await db.query.subscriptions.findFirst({
239 where: and(eq(subscriptions.id, id), eq(subscriptions.agentId, ownerId)),
240 columns: { id: true },
241 })
242 if (!existing) {
243 return {
244 ok: false,
245 status: 404,
246 code: 'unknown_subscription',
247 message: `No subscription '${id}' for this account. List yours at GET /v1/subscriptions.`,
248 }
249 }
250 await db.delete(subscriptions).where(eq(subscriptions.id, id))
251 return { ok: true, result: { deleted: id } }
252}