@allbluecn/web-app 0.28.11 → 0.28.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/package.json +5 -5
  2. package/public/dev-gallery.html +19 -0
  3. package/src/__tests__/bench/baselines/format-timestamp.json +44 -0
  4. package/src/__typeprobe__.d.ts +4 -0
  5. package/src/components/harness/extension-panel/panels/terminal/__tests__/terminal-instance.test.tsx +93 -4
  6. package/src/components/harness/extension-panel/panels/terminal/sse-transport.ts +28 -5
  7. package/src/components/harness/extension-panel/panels/terminal/terminal-instance.tsx +53 -10
  8. package/src/components/harness/extension-panel/panels/terminal/transport.ts +10 -3
  9. package/src/components/harness/extension-panel/panels/terminal/ws-transport.ts +13 -2
  10. package/src/components/settings/harness/connectors-card.tsx +5 -0
  11. package/src/dev/gallery-entry.tsx +38 -0
  12. package/src/dev/gallery.tsx +610 -0
  13. package/src/lib/changelog/sdk-versions.ts +3 -3
  14. package/src/paraglide/README.md +1 -1
  15. package/src/paraglide/messages/_index.d.ts +9 -0
  16. package/src/paraglide/messages/_index.js +9 -0
  17. package/src/paraglide/messages/capabilities_webhook.d.ts +16 -0
  18. package/src/paraglide/messages/capabilities_webhook.js +29 -0
  19. package/src/paraglide/messages/capabilities_workflow.d.ts +16 -0
  20. package/src/paraglide/messages/capabilities_workflow.js +29 -0
  21. package/src/paraglide/messages/harness_panel_terminal_exitedrecycled1.d.ts +17 -0
  22. package/src/paraglide/messages/harness_panel_terminal_exitedrecycled1.js +30 -0
  23. package/src/paraglide/messages/harness_panel_terminal_restarted.d.ts +16 -0
  24. package/src/paraglide/messages/harness_panel_terminal_restarted.js +29 -0
  25. package/src/paraglide/messages/settings_harness_connectors_needsauth1.d.ts +17 -0
  26. package/src/paraglide/messages/settings_harness_connectors_needsauth1.js +30 -0
  27. package/src/paraglide/messages/settings_harness_ralphenabled1.d.ts +17 -0
  28. package/src/paraglide/messages/settings_harness_ralphenabled1.js +30 -0
  29. package/src/paraglide/messages/settings_harness_ralphenabled_description1.d.ts +17 -0
  30. package/src/paraglide/messages/settings_harness_ralphenabled_description1.js +30 -0
  31. package/src/paraglide/messages/settings_harness_ralphmaxrounds2.d.ts +17 -0
  32. package/src/paraglide/messages/settings_harness_ralphmaxrounds2.js +30 -0
  33. package/src/paraglide/messages/settings_harness_ralphmaxrounds_description2.d.ts +17 -0
  34. package/src/paraglide/messages/settings_harness_ralphmaxrounds_description2.js +30 -0
  35. package/src/routeTree.gen.ts +21 -0
  36. package/src/routes/api/harness/terminal/$.ts +32 -13
  37. package/src/routes/api/harness/terminal/__tests__/route.test.ts +41 -0
  38. package/src/routes/api/harness/webhook/$token.ts +23 -0
  39. package/src/routes/api/sync/__tests__/bootstrap.test.ts +32 -1
  40. package/src/routes/api/sync/bootstrap.ts +11 -0
  41. package/src/server/ai-gateway/durability/__tests__/sse-resume-frames.test.ts +123 -0
  42. package/src/server/harness/__tests__/agent-terminal-sandbox.test.ts +23 -4
  43. package/src/server/harness/__tests__/agent-terminal.server.test.ts +118 -2
  44. package/src/server/harness/__tests__/credentials.server.test.ts +25 -2
  45. package/src/server/harness/__tests__/host-schedule-worker.test.ts +43 -0
  46. package/src/server/harness/__tests__/runtime-without-providers.test.ts +11 -0
  47. package/src/server/harness/__tests__/sticky-route.test.ts +86 -0
  48. package/src/server/harness/__tests__/terminal-foreground.server.test.ts +80 -0
  49. package/src/server/harness/__tests__/terminal-manager.server.test.ts +75 -1
  50. package/src/server/harness/__tests__/tool-entitlements.test.ts +6 -2
  51. package/src/server/harness/agent-terminal.server.ts +25 -4
  52. package/src/server/harness/agents/__tests__/agent-control.test.ts +1 -0
  53. package/src/server/harness/agents/run-view.server.ts +55 -2
  54. package/src/server/harness/capabilities/__tests__/__snapshots__/matrix.test.ts.snap +92 -0
  55. package/src/server/harness/capabilities/__tests__/execution-plane-denials.test.ts +3 -1
  56. package/src/server/harness/capabilities/__tests__/p3-matrix.test.ts +3 -3
  57. package/src/server/harness/capabilities/__tests__/p5-matrix.test.ts +293 -0
  58. package/src/server/harness/capabilities/__tests__/validate.test.ts +8 -2
  59. package/src/server/harness/capabilities/execution-plane-denials.ts +9 -3
  60. package/src/server/harness/capabilities/manifests/agent-terminal.ts +3 -2
  61. package/src/server/harness/capabilities/manifests/webhook.ts +45 -0
  62. package/src/server/harness/capabilities/manifests/workflow.ts +40 -0
  63. package/src/server/harness/capabilities/registry.ts +4 -0
  64. package/src/server/harness/connectors/__tests__/connector-accounts.test.ts +22 -1
  65. package/src/server/harness/connectors/connector-accounts.server.ts +7 -0
  66. package/src/server/harness/credentials.server.ts +3 -1
  67. package/src/server/harness/define.server.ts +11 -0
  68. package/src/server/harness/mcp/mcp-config.server.ts +3 -1
  69. package/src/server/harness/outbox/outbox-dispatcher.server.ts +9 -0
  70. package/src/server/harness/outbox/outbox-store.server.ts +7 -0
  71. package/src/server/harness/persistence/__tests__/log-store.server.test.ts +4 -1
  72. package/src/server/harness/plugins/__tests__/tool-risk-audit.test.ts +5 -1
  73. package/src/server/harness/plugins/builtin/agent-terminal.plugin.ts +12 -2
  74. package/src/server/harness/providers/contracts.ts +16 -0
  75. package/src/server/harness/schedule/schedule-dispatcher.server.ts +3 -0
  76. package/src/server/harness/search/__tests__/indexer.test.ts +4 -1
  77. package/src/server/harness/search/__tests__/lifecycle.test.ts +4 -1
  78. package/src/server/harness/search/__tests__/search.test.ts +4 -1
  79. package/src/server/harness/sticky-route.server.ts +72 -0
  80. package/src/server/harness/terminal-foreground.server.ts +90 -0
  81. package/src/server/harness/terminal-manager.server.ts +78 -3
  82. package/src/server/harness/tool-entitlements.server.ts +5 -0
  83. package/src/server/harness/webhook/__tests__/body.test.ts +73 -0
  84. package/src/server/harness/webhook/__tests__/payload.test.ts +215 -0
  85. package/src/server/harness/webhook/__tests__/signature.test.ts +170 -0
  86. package/src/server/harness/webhook/__tests__/webhook-dispatcher.test.ts +212 -0
  87. package/src/server/harness/webhook/__tests__/webhook.plugin.test.ts +195 -0
  88. package/src/server/harness/webhook/__tests__/webhook.service.test.ts +354 -0
  89. package/src/server/harness/webhook/body.server.ts +56 -0
  90. package/src/server/harness/webhook/payload.server.ts +169 -0
  91. package/src/server/harness/webhook/signature.server.ts +118 -0
  92. package/src/server/harness/webhook/types.ts +57 -0
  93. package/src/server/harness/webhook/webhook-dispatcher.server.ts +495 -0
  94. package/src/server/harness/webhook/webhook-store.server.ts +115 -0
  95. package/src/server/harness/webhook/webhook.plugin.ts +273 -0
  96. package/src/server/harness/webhook/webhook.service.server.ts +577 -0
  97. package/src/server/harness/worker/__tests__/worker-http.test.ts +8 -1
  98. package/src/server/harness/worker/worker-health.server.ts +4 -1
  99. package/src/server/harness/worker/worker-runtime.server.ts +43 -1
  100. package/src/server/harness/workflow/__tests__/engine.test.ts +195 -0
  101. package/src/server/harness/workflow/__tests__/settings.test.ts +125 -0
  102. package/src/server/harness/workflow/__tests__/validate.test.ts +151 -0
  103. package/src/server/harness/workflow/engine.server.ts +155 -0
  104. package/src/server/harness/workflow/settings.ts +84 -0
  105. package/src/server/harness/workflow/store.server.ts +147 -0
  106. package/src/server/harness/workflow/types.ts +80 -0
  107. package/src/server/harness/workflow/validate.ts +130 -0
  108. package/src/server/harness/workflow/workflow.plugin.ts +261 -0
  109. package/src/server/serverFns/harness/__tests__/fork-thread.test.ts +14 -1
  110. package/src/server/serverFns/harness/fork-thread.ts +17 -0
@@ -0,0 +1,577 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // 入站 webhook 规则服务与接收管线(P5 任务 3,母规格 §6.2/§7/§8)。
6
+ //
7
+ // 分层:
8
+ // - 规则 CRUD:跨会话定义(Prisma 投影,进同步白名单);密钥 AES 加密落
9
+ // secretCipher,明文只在创建/轮换时返回一次(工具结果绝不携带)。
10
+ // - 接收管线 handleWebhookReceive:token → 规则 → 有界 body → 验签 → 事件过滤
11
+ // → repo/owner 白名单 → delivery 唯一键幂等 → 写 outbox → 202。
12
+ // 任何一步失败都在此返回结构化状态码,不把上游 payload 写日志。
13
+ // - 投递(建 root Session)在 webhook-dispatcher.server.ts,由 Worker 驱动。
14
+
15
+ import { randomBytes } from 'node:crypto'
16
+
17
+ import { prisma, Prisma } from '@allbluecn/database'
18
+
19
+ import { auditLog } from '@/server/audit'
20
+ import { decryptApiKey, encryptApiKey } from '@/server/lib/api-key-cipher'
21
+
22
+ import { readBoundedBody } from './body.server'
23
+ import {
24
+ computeEventKey,
25
+ extractEventSummary,
26
+ matchesSubscribedEvents,
27
+ matchesWhitelist,
28
+ parseWebhookPayload,
29
+ } from './payload.server'
30
+ import { verifyWebhookSignature } from './signature.server'
31
+ import {
32
+ cancelPendingWebhookOutbox,
33
+ createWebhookOutbox,
34
+ type WebhookDeliveryPayload,
35
+ } from './webhook-store.server'
36
+ import {
37
+ WEBHOOK_MAX_BODY_BYTES,
38
+ WEBHOOK_SECRET_BYTES,
39
+ WEBHOOK_TOKEN_BYTES,
40
+ type WebhookEventSummary,
41
+ type WebhookProvider,
42
+ type WebhookRuleSummary,
43
+ } from './types'
44
+
45
+ export class WebhookServiceError extends Error {
46
+ readonly code: string
47
+
48
+ constructor(code: string, message: string) {
49
+ super(message)
50
+ this.name = 'WebhookServiceError'
51
+ this.code = code
52
+ }
53
+ }
54
+
55
+ const MAX_NAME_LENGTH = 120
56
+ const MAX_PROMPT_LENGTH = 8_000
57
+ const MAX_WHITELIST_ENTRIES = 50
58
+ const MAX_EVENTS = 50
59
+
60
+ const REPO_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/
61
+ const OWNER_PATTERN = /^[A-Za-z0-9_.-]+$/
62
+ const EVENT_PATTERN = /^[a-z][a-z0-9_]*$/
63
+
64
+ type RuleRow = Prisma.HarnessWebhookRuleGetPayload<object>
65
+
66
+ function generateToken(): string {
67
+ return randomBytes(WEBHOOK_TOKEN_BYTES).toString('base64url')
68
+ }
69
+
70
+ function generateSecret(): string {
71
+ return randomBytes(WEBHOOK_SECRET_BYTES).toString('hex')
72
+ }
73
+
74
+ function secretHintOf(secret: string): string {
75
+ return secret.slice(-4)
76
+ }
77
+
78
+ function stringArrayOrNull(value: Prisma.JsonValue | null): string[] | null {
79
+ if (!Array.isArray(value)) return null
80
+ const entries = value.filter((entry): entry is string => typeof entry === 'string')
81
+ return entries.length > 0 ? entries : null
82
+ }
83
+
84
+ function jsonOrNull(value: readonly string[] | null | undefined): Prisma.InputJsonValue | undefined {
85
+ return value && value.length > 0 ? ([...value] as Prisma.InputJsonValue) : undefined
86
+ }
87
+
88
+ export function toRuleSummary(rule: {
89
+ id: string
90
+ name: string
91
+ provider: string
92
+ status: string
93
+ token: string
94
+ secretHint: string
95
+ /** 密钥密文是否在场(P5 任务 5:跨端同步而来的行为 NULL,须重新录入)。 */
96
+ secretCipher: string | null
97
+ events: Prisma.JsonValue | null
98
+ repoWhitelist: Prisma.JsonValue | null
99
+ ownerWhitelist: Prisma.JsonValue | null
100
+ threadId: string
101
+ lastDeliveryAt: Date | null
102
+ revision: number
103
+ }): WebhookRuleSummary {
104
+ return {
105
+ id: rule.id,
106
+ name: rule.name,
107
+ provider: rule.provider,
108
+ status: rule.status,
109
+ path: `/api/harness/webhook/${rule.token}`,
110
+ secretHint: rule.secretHint,
111
+ hasSecret: rule.secretCipher !== null,
112
+ events: stringArrayOrNull(rule.events),
113
+ repoWhitelist: stringArrayOrNull(rule.repoWhitelist),
114
+ ownerWhitelist: stringArrayOrNull(rule.ownerWhitelist),
115
+ threadId: rule.threadId,
116
+ lastDeliveryAt: rule.lastDeliveryAt,
117
+ revision: rule.revision,
118
+ }
119
+ }
120
+
121
+ function normalizeEvents(events: readonly string[] | null | undefined): string[] | null {
122
+ if (!events || events.length === 0) return null
123
+ const unique = [...new Set(events.map((entry) => entry.trim().toLowerCase()))]
124
+ if (unique.length > MAX_EVENTS) {
125
+ throw new WebhookServiceError('webhook_invalid_input', `At most ${MAX_EVENTS} events allowed`)
126
+ }
127
+ for (const event of unique) {
128
+ if (!EVENT_PATTERN.test(event)) {
129
+ throw new WebhookServiceError('webhook_invalid_input', `Invalid event name: ${event}`)
130
+ }
131
+ }
132
+ return unique
133
+ }
134
+
135
+ function normalizeRepos(repos: readonly string[] | null | undefined): string[] | null {
136
+ if (!repos || repos.length === 0) return null
137
+ const unique = [...new Set(repos.map((entry) => entry.trim()))]
138
+ if (unique.length > MAX_WHITELIST_ENTRIES) {
139
+ throw new WebhookServiceError(
140
+ 'webhook_invalid_input',
141
+ `At most ${MAX_WHITELIST_ENTRIES} repos allowed`,
142
+ )
143
+ }
144
+ for (const repo of unique) {
145
+ if (!REPO_PATTERN.test(repo)) {
146
+ throw new WebhookServiceError('webhook_invalid_input', `Invalid repo: ${repo} (expect owner/repo)`)
147
+ }
148
+ }
149
+ return unique
150
+ }
151
+
152
+ function normalizeOwners(owners: readonly string[] | null | undefined): string[] | null {
153
+ if (!owners || owners.length === 0) return null
154
+ const unique = [...new Set(owners.map((entry) => entry.trim()))]
155
+ if (unique.length > MAX_WHITELIST_ENTRIES) {
156
+ throw new WebhookServiceError(
157
+ 'webhook_invalid_input',
158
+ `At most ${MAX_WHITELIST_ENTRIES} owners allowed`,
159
+ )
160
+ }
161
+ for (const owner of unique) {
162
+ if (!OWNER_PATTERN.test(owner)) {
163
+ throw new WebhookServiceError('webhook_invalid_input', `Invalid owner: ${owner}`)
164
+ }
165
+ }
166
+ return unique
167
+ }
168
+
169
+ /**
170
+ * 安全不变量:repo/owner 白名单至少一个非空。
171
+ * 全空意味着「任意仓库事件都能触发 agent」,等于把端点变成开放触发器——fail-closed 拒绝。
172
+ */
173
+ function assertWhitelistConfigured(
174
+ repos: readonly string[] | null,
175
+ owners: readonly string[] | null,
176
+ ): void {
177
+ if ((repos === null || repos.length === 0) && (owners === null || owners.length === 0)) {
178
+ throw new WebhookServiceError(
179
+ 'webhook_whitelist_required',
180
+ 'At least one of repo_whitelist / owner_whitelist must be non-empty',
181
+ )
182
+ }
183
+ }
184
+
185
+ export async function createWebhookRule(input: {
186
+ userId: string
187
+ threadId: string
188
+ workspaceId?: string | null
189
+ name: string
190
+ prompt: string
191
+ provider?: WebhookProvider
192
+ events?: readonly string[] | null
193
+ repoWhitelist?: readonly string[] | null
194
+ ownerWhitelist?: readonly string[] | null
195
+ executionPlane: 'local' | 'cloud'
196
+ }): Promise<{ rule: RuleRow; secret: string }> {
197
+ const name = input.name.trim()
198
+ const prompt = input.prompt.trim()
199
+ if (!name || name.length > MAX_NAME_LENGTH) {
200
+ throw new WebhookServiceError('webhook_invalid_input', 'Webhook name is required (max 120 chars)')
201
+ }
202
+ if (!prompt || prompt.length > MAX_PROMPT_LENGTH) {
203
+ throw new WebhookServiceError(
204
+ 'webhook_invalid_input',
205
+ `Webhook prompt is required (max ${MAX_PROMPT_LENGTH} chars)`,
206
+ )
207
+ }
208
+ const events = normalizeEvents(input.events)
209
+ const repoWhitelist = normalizeRepos(input.repoWhitelist)
210
+ const ownerWhitelist = normalizeOwners(input.ownerWhitelist)
211
+ assertWhitelistConfigured(repoWhitelist, ownerWhitelist)
212
+
213
+ const secret = generateSecret()
214
+ const secretCipher = encryptApiKey(secret)
215
+ const base = {
216
+ userId: input.userId,
217
+ name,
218
+ provider: input.provider ?? 'github',
219
+ threadId: input.threadId,
220
+ workspaceId: input.workspaceId ?? null,
221
+ prompt,
222
+ secretCipher,
223
+ secretHint: secretHintOf(secret),
224
+ events: jsonOrNull(events),
225
+ repoWhitelist: jsonOrNull(repoWhitelist),
226
+ ownerWhitelist: jsonOrNull(ownerWhitelist),
227
+ executionPlane: input.executionPlane,
228
+ }
229
+
230
+ // token 唯一键冲突概率极低(24 字节随机);重试三次后放弃,不与唯一约束死磕。
231
+ for (let attempt = 0; attempt < 3; attempt += 1) {
232
+ try {
233
+ const rule = await prisma.harnessWebhookRule.create({
234
+ data: { ...base, token: generateToken() },
235
+ })
236
+ return { rule, secret }
237
+ } catch (error) {
238
+ if ((error as { code?: string }).code === 'P2002' && attempt < 2) continue
239
+ throw error
240
+ }
241
+ }
242
+ throw new WebhookServiceError('webhook_token_conflict', 'Failed to allocate a unique token')
243
+ }
244
+
245
+ export async function listWebhookRules(input: {
246
+ userId: string
247
+ threadId?: string
248
+ }): Promise<RuleRow[]> {
249
+ return prisma.harnessWebhookRule.findMany({
250
+ where: {
251
+ userId: input.userId,
252
+ status: { not: 'deleted' },
253
+ ...(input.threadId ? { threadId: input.threadId } : {}),
254
+ },
255
+ orderBy: [{ createdAt: 'asc' }],
256
+ })
257
+ }
258
+
259
+ export async function getWebhookRule(input: {
260
+ userId: string
261
+ id: string
262
+ }): Promise<RuleRow | null> {
263
+ return prisma.harnessWebhookRule.findFirst({
264
+ where: { id: input.id, userId: input.userId, status: { not: 'deleted' } },
265
+ })
266
+ }
267
+
268
+ export async function editWebhookRule(input: {
269
+ userId: string
270
+ id: string
271
+ revision?: number
272
+ status?: 'active' | 'paused'
273
+ name?: string
274
+ prompt?: string
275
+ events?: readonly string[] | null
276
+ repoWhitelist?: readonly string[] | null
277
+ ownerWhitelist?: readonly string[] | null
278
+ }): Promise<RuleRow> {
279
+ const existing = await getWebhookRule({ userId: input.userId, id: input.id })
280
+ if (!existing) {
281
+ throw new WebhookServiceError('webhook_not_found', 'Webhook rule was not found')
282
+ }
283
+ const data: Prisma.HarnessWebhookRuleUpdateManyMutationInput = { revision: { increment: 1 } }
284
+
285
+ if (input.name !== undefined) {
286
+ const name = input.name.trim()
287
+ if (!name || name.length > MAX_NAME_LENGTH) {
288
+ throw new WebhookServiceError('webhook_invalid_input', 'Webhook name is required (max 120 chars)')
289
+ }
290
+ data.name = name
291
+ }
292
+ if (input.prompt !== undefined) {
293
+ const prompt = input.prompt.trim()
294
+ if (!prompt || prompt.length > MAX_PROMPT_LENGTH) {
295
+ throw new WebhookServiceError(
296
+ 'webhook_invalid_input',
297
+ `Webhook prompt is required (max ${MAX_PROMPT_LENGTH} chars)`,
298
+ )
299
+ }
300
+ data.prompt = prompt
301
+ }
302
+ if (input.status !== undefined) data.status = input.status
303
+ if (input.events !== undefined) data.events = jsonOrNull(normalizeEvents(input.events)) ?? Prisma.DbNull
304
+ if (input.repoWhitelist !== undefined) {
305
+ data.repoWhitelist = jsonOrNull(normalizeRepos(input.repoWhitelist)) ?? Prisma.DbNull
306
+ }
307
+ if (input.ownerWhitelist !== undefined) {
308
+ data.ownerWhitelist = jsonOrNull(normalizeOwners(input.ownerWhitelist)) ?? Prisma.DbNull
309
+ }
310
+
311
+ // 改了任一侧白名单后重新校验「至少一个非空」不变量(不能靠改成空来放开)。
312
+ if (input.repoWhitelist !== undefined || input.ownerWhitelist !== undefined) {
313
+ const repos = input.repoWhitelist !== undefined
314
+ ? normalizeRepos(input.repoWhitelist)
315
+ : stringArrayOrNull(existing.repoWhitelist)
316
+ const owners = input.ownerWhitelist !== undefined
317
+ ? normalizeOwners(input.ownerWhitelist)
318
+ : stringArrayOrNull(existing.ownerWhitelist)
319
+ assertWhitelistConfigured(repos, owners)
320
+ }
321
+
322
+ const where: Prisma.HarnessWebhookRuleWhereInput = {
323
+ id: input.id,
324
+ userId: input.userId,
325
+ status: { not: 'deleted' },
326
+ ...(input.revision !== undefined ? { revision: input.revision } : {}),
327
+ }
328
+ const updated = await prisma.harnessWebhookRule.updateMany({ where, data })
329
+ if (updated.count !== 1) {
330
+ throw new WebhookServiceError('webhook_conflict', 'Webhook rule revision conflict')
331
+ }
332
+ const rule = await getWebhookRule({ userId: input.userId, id: input.id })
333
+ if (!rule) throw new WebhookServiceError('webhook_not_found', 'Webhook rule was not found')
334
+ return rule
335
+ }
336
+
337
+ /** 轮换密钥:返回新密钥明文一次(设置页展示后即不可再读)。 */
338
+ export async function rotateWebhookSecret(input: {
339
+ userId: string
340
+ id: string
341
+ revision?: number
342
+ }): Promise<{ rule: RuleRow; secret: string }> {
343
+ const secret = generateSecret()
344
+ const updated = await prisma.harnessWebhookRule.updateMany({
345
+ where: {
346
+ id: input.id,
347
+ userId: input.userId,
348
+ status: { not: 'deleted' },
349
+ ...(input.revision !== undefined ? { revision: input.revision } : {}),
350
+ },
351
+ data: {
352
+ secretCipher: encryptApiKey(secret),
353
+ secretHint: secretHintOf(secret),
354
+ revision: { increment: 1 },
355
+ },
356
+ })
357
+ if (updated.count !== 1) {
358
+ throw new WebhookServiceError('webhook_conflict', 'Webhook rule revision conflict')
359
+ }
360
+ const rule = await getWebhookRule({ userId: input.userId, id: input.id })
361
+ if (!rule) throw new WebhookServiceError('webhook_not_found', 'Webhook rule was not found')
362
+ return { rule, secret }
363
+ }
364
+
365
+ export async function deleteWebhookRule(input: {
366
+ userId: string
367
+ id: string
368
+ revision?: number
369
+ }): Promise<void> {
370
+ await prisma.$transaction(async (tx) => {
371
+ const updated = await tx.harnessWebhookRule.updateMany({
372
+ where: {
373
+ id: input.id,
374
+ userId: input.userId,
375
+ status: { not: 'deleted' },
376
+ ...(input.revision !== undefined ? { revision: input.revision } : {}),
377
+ },
378
+ data: { status: 'deleted', revision: { increment: 1 } },
379
+ })
380
+ if (updated.count !== 1) {
381
+ throw new WebhookServiceError('webhook_conflict', 'Webhook rule revision conflict')
382
+ }
383
+ const deliveries = await tx.harnessWebhookDelivery.findMany({
384
+ where: { ruleId: input.id, userId: input.userId, state: 'pending' },
385
+ select: { id: true },
386
+ })
387
+ await cancelPendingWebhookOutbox(tx, {
388
+ userId: input.userId,
389
+ deliveryIds: deliveries.map((row) => row.id),
390
+ })
391
+ await tx.harnessWebhookDelivery.updateMany({
392
+ where: { ruleId: input.id, userId: input.userId, state: 'pending' },
393
+ data: { state: 'skipped', lastError: 'webhook_rule_removed' },
394
+ })
395
+ })
396
+ }
397
+
398
+ // ---------------------------------------------------------------- 接收管线
399
+
400
+ function jsonResponse(body: unknown, status: number): Response {
401
+ return new Response(JSON.stringify(body), {
402
+ status,
403
+ headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
404
+ })
405
+ }
406
+
407
+ export interface WebhookReceiveDeps {
408
+ now?: number
409
+ audit?: typeof auditLog
410
+ }
411
+
412
+ /**
413
+ * 公开接收端点:无会话鉴权,靠不透明 token + HMAC 验签识别来源。
414
+ *
415
+ * 状态码语义(不回显期望签名、不回显规则是否存在以外信息):
416
+ * 202 受理 / 重复(幂等)/ 事件未订阅
417
+ * 400 payload 非 JSON
418
+ * 401 缺签名 / 签名非法 / 时间戳过期
419
+ * 403 白名单不匹配
420
+ * 404 token 未命中或规则非 active
421
+ * 413 body 超限
422
+ */
423
+ export async function handleWebhookReceive(
424
+ request: Request,
425
+ token: string,
426
+ deps: WebhookReceiveDeps = {},
427
+ ): Promise<Response> {
428
+ const db = prisma
429
+ const nowMs = deps.now ?? Date.now()
430
+ const now = new Date(nowMs)
431
+
432
+ if (!token || token.length < 16 || token.length > 128) {
433
+ return jsonResponse({ error: 'not_found' }, 404)
434
+ }
435
+
436
+ const rule = await db.harnessWebhookRule.findUnique({ where: { token } })
437
+ if (!rule || rule.status !== 'active') {
438
+ return jsonResponse({ error: 'not_found' }, 404)
439
+ }
440
+
441
+ const body = await readBoundedBody(request, WEBHOOK_MAX_BODY_BYTES)
442
+ if (!body.ok) {
443
+ return body.reason === 'too_large'
444
+ ? jsonResponse({ error: 'payload_too_large' }, 413)
445
+ : jsonResponse({ error: 'unreadable_body' }, 400)
446
+ }
447
+
448
+ const secret = decryptApiKey(rule.secretCipher)
449
+ if (!secret) {
450
+ // 密钥不可解密(换加密密钥/数据损坏):拒绝而非放行,且不暴露内部原因。
451
+ return jsonResponse({ error: 'endpoint_unavailable' }, 503)
452
+ }
453
+
454
+ const signature = verifyWebhookSignature({
455
+ secret,
456
+ body: body.bytes,
457
+ headers: request.headers,
458
+ now: nowMs,
459
+ })
460
+ if (!signature.ok) {
461
+ return jsonResponse({ error: 'invalid_signature', reason: signature.reason }, 401)
462
+ }
463
+
464
+ const payload = parseWebhookPayload(body.bytes)
465
+ if (payload === null) {
466
+ return jsonResponse({ error: 'invalid_payload' }, 400)
467
+ }
468
+
469
+ const summary: WebhookEventSummary = extractEventSummary({ headers: request.headers, payload })
470
+
471
+ if (!matchesSubscribedEvents(stringArrayOrNull(rule.events), summary)) {
472
+ // 未订阅的事件是正常过滤,不是错误;不建 delivery,避免表膨胀。
473
+ return jsonResponse({ received: true, ignored: 'event_not_subscribed' }, 202)
474
+ }
475
+
476
+ if (
477
+ !matchesWhitelist({
478
+ repoWhitelist: stringArrayOrNull(rule.repoWhitelist),
479
+ ownerWhitelist: stringArrayOrNull(rule.ownerWhitelist),
480
+ summary,
481
+ })
482
+ ) {
483
+ return jsonResponse({ error: 'repo_not_allowed' }, 403)
484
+ }
485
+
486
+ const eventKey = computeEventKey({ headers: request.headers, body: body.bytes, summary })
487
+ const executionPlane = rule.executionPlane === 'cloud' ? 'cloud' : 'local'
488
+ const outboxPayload: WebhookDeliveryPayload = {
489
+ ruleId: rule.id,
490
+ deliveryId: '',
491
+ threadId: rule.threadId,
492
+ workspaceId: rule.workspaceId,
493
+ name: rule.name,
494
+ provider: rule.provider,
495
+ summary,
496
+ }
497
+
498
+ // 幂等前置检查:上游重投是最常见的重复来源,先查一次避免走事务内的唯一约束异常
499
+ // (P2002 在 Prisma 层会记 error 日志,常态重投不应制造噪音)。并发窗口仍由下面的
500
+ // P2002 兜底。
501
+ const already = await prisma.harnessWebhookDelivery.findUnique({
502
+ where: { ruleId_eventKey: { ruleId: rule.id, eventKey } },
503
+ select: { id: true },
504
+ })
505
+ if (already) {
506
+ return jsonResponse({ received: true, duplicate: true }, 202)
507
+ }
508
+
509
+ let duplicate = false
510
+ await prisma.$transaction(async (tx) => {
511
+ const delivery = await tx.harnessWebhookDelivery.create({
512
+ data: {
513
+ ruleId: rule.id,
514
+ userId: rule.userId,
515
+ executionPlane,
516
+ eventKey,
517
+ eventType: summary.event,
518
+ repo: summary.repo,
519
+ owner: summary.owner,
520
+ summary: summary as unknown as Prisma.InputJsonValue,
521
+ state: 'pending',
522
+ },
523
+ select: { id: true },
524
+ })
525
+ await createWebhookOutbox(tx, {
526
+ userId: rule.userId,
527
+ executionPlane,
528
+ deliveryId: delivery.id,
529
+ payload: { ...outboxPayload, deliveryId: delivery.id },
530
+ nextAttemptAt: now,
531
+ })
532
+ // 规则可能在读取后被暂停/删除:此处不阻断本次已受理的投递——outbox dispatcher
533
+ // 在拉起 Session 前会复查规则状态,非 active 即按 skipped 收尾。
534
+ await tx.harnessWebhookRule.updateMany({
535
+ where: { id: rule.id, userId: rule.userId, status: 'active' },
536
+ data: { lastDeliveryAt: now, lastError: null },
537
+ })
538
+ }).catch((error: unknown) => {
539
+ // (ruleId, eventKey) 唯一冲突 = 上游重投同一事件 → 幂等命中。
540
+ if ((error as { code?: string }).code === 'P2002') {
541
+ duplicate = true
542
+ return
543
+ }
544
+ throw error
545
+ })
546
+
547
+ if (duplicate) {
548
+ // 幂等命中:同一 eventKey 已受理过,返回 202 让上游停止重投。
549
+ return jsonResponse({ received: true, duplicate: true }, 202)
550
+ }
551
+
552
+ // 审计失败不阻断受理(审计是旁路,事件不能因日志写失败被上游重投放大)。
553
+ const audit = deps.audit ?? auditLog
554
+ try {
555
+ await audit({
556
+ workspaceId: rule.workspaceId ?? '',
557
+ userId: rule.userId,
558
+ resourceType: 'harness_webhook',
559
+ resourceId: rule.id,
560
+ action: 'harness.webhook.receive',
561
+ metadata: {
562
+ provider: rule.provider,
563
+ event: summary.event,
564
+ repo: summary.repo,
565
+ owner: summary.owner,
566
+ scheme: signature.scheme,
567
+ },
568
+ })
569
+ } catch (error) {
570
+ console.warn(
571
+ '[webhook] 审计写入失败:',
572
+ error instanceof Error ? error.message : 'unknown',
573
+ )
574
+ }
575
+
576
+ return jsonResponse({ received: true }, 202)
577
+ }
@@ -128,10 +128,17 @@ describe('Harness Worker HTTP ingress', () => {
128
128
  servers.push(server)
129
129
 
130
130
  const response = await fetch(`${server.url}/healthz`)
131
+ const second = await fetch(`${server.url}/healthz`)
131
132
 
132
133
  expect(response.status).toBe(200)
133
- expect(await response.json()).toEqual({
134
+ const firstBody = (await response.json()) as { instanceId: string }
135
+ // 同一实例上重复探测必须给出同一个 instanceId(「变脸」会让运维误判为漂移)
136
+ expect(((await second.json()) as { instanceId: string }).instanceId).toBe(firstBody.instanceId)
137
+ expect(firstBody).toEqual({
134
138
  status: 'ok',
139
+ // P5 任务 8:多实例 sticky 的运维抓手——同一线程反复探测应稳定落在同一 instanceId,
140
+ // 每次都在变说明 ingress 未按 $arg_threadId 哈希(响应头 x-allblue-instance 同源)。
141
+ instanceId: expect.stringMatching(/^.+:\d+$/),
135
142
  plane: 'local',
136
143
  explicitDenials: [],
137
144
  executionProvided: true,
@@ -8,6 +8,7 @@ import {
8
8
  } from '@/server/harness/outbox/outbox-dispatcher.server'
9
9
  import type { ScheduleExecutionPlane } from '@/server/harness/outbox/outbox-store.server'
10
10
  import { resolveExecutionWorld } from '@/server/harness/plane.server'
11
+ import { getInstanceId } from '@/server/harness/sticky-route.server'
11
12
  import {
12
13
  executionPlaneDenialSummaries,
13
14
  type ExecutionPlaneDenialSummary,
@@ -56,5 +57,7 @@ export function createWorkerHealthReader(plane: ScheduleExecutionPlane): () => P
56
57
  }
57
58
 
58
59
  export async function handleWorkerHealthRequest(health: () => Promise<WorkerHealth>): Promise<Response> {
59
- return Response.json({ status: 'ok', ...await health() })
60
+ // instanceId(P5 任务 8):多实例 sticky 的运维抓手——同一粘性键在多实例间反复探测
61
+ // 时应稳定落在同一个 instanceId;若每次都变,说明 ingress 未按 `$arg_threadId` 哈希。
62
+ return Response.json({ status: 'ok', instanceId: getInstanceId(), ...await health() })
60
63
  }
@@ -17,6 +17,7 @@ import {
17
17
  tokenizeMissingSearchDocuments,
18
18
  } from '@/server/harness/search/session-search-lifecycle.server'
19
19
  import { createScheduleDispatcher } from '@/server/harness/schedule/schedule-dispatcher.server'
20
+ import { createWebhookDispatcher } from '@/server/harness/webhook/webhook-dispatcher.server'
20
21
  import { resolveCurrentPlane } from '@/server/harness/schedule/schedule.service.server'
21
22
  import type { ScheduleExecutionPlane } from '@/server/harness/outbox/outbox-store.server'
22
23
  import {
@@ -97,6 +98,7 @@ async function createRuntime(options: StartHarnessWorkerRuntimeOptions): Promise
97
98
  let controller: AbortController | undefined
98
99
  let scheduleController: AbortController | undefined
99
100
  let dispatcher: ReturnType<typeof createScheduleDispatcher> | undefined
101
+ let webhookDispatcher: ReturnType<typeof createWebhookDispatcher> | undefined
100
102
  let timer: ReturnType<typeof setInterval> | undefined
101
103
  let stopping: Promise<void> | undefined
102
104
  let stopped = false
@@ -136,8 +138,46 @@ async function createRuntime(options: StartHarnessWorkerRuntimeOptions): Promise
136
138
  }),
137
139
  })
138
140
  dispatcher = activeDispatcher
141
+ // webhook 投递由同一 Worker 驱动(P5 任务 3):只领 kind='webhook.delivery' 的行,
142
+ // 与 schedule dispatcher 按 kind 隔离;受理已返回 202,这里负责建 root Session。
143
+ const activeWebhookDispatcher = createWebhookDispatcher({
144
+ plane,
145
+ signal: scheduleController.signal,
146
+ submit: async (input) => host.submit({
147
+ harness,
148
+ threadId: input.threadId,
149
+ user: { id: input.userId },
150
+ inputId: input.inputId,
151
+ input: { op: 'prompt', message: input.message },
152
+ }),
153
+ })
154
+ webhookDispatcher = activeWebhookDispatcher
155
+
156
+ // webhook 投递与 schedule 各自串行、互不阻塞:两个 dispatcher 共享 outbox 表但
157
+ // 处理不同 kind,一个慢(host .submit 卡住)不应拖住另一个的 tick 节奏。
158
+ let webhookRunning = false
159
+ let webhookQueue: Promise<void> = Promise.resolve()
160
+ const tickWebhook = (): Promise<void> => {
161
+ if (stopped || webhookRunning) return webhookQueue
162
+ webhookRunning = true
163
+ webhookQueue = (async () => {
164
+ try {
165
+ await activeWebhookDispatcher.tick()
166
+ } catch (error) {
167
+ console.error(
168
+ '[harness] webhook 投递失败:',
169
+ error instanceof Error ? error.message : 'unknown',
170
+ )
171
+ } finally {
172
+ webhookRunning = false
173
+ }
174
+ })()
175
+ return webhookQueue
176
+ }
139
177
 
140
178
  const tick = (): Promise<void> => {
179
+ // webhook 独立排队:即便 schedule tick 正在跑,也不跳过本轮 webhook 领取。
180
+ void tickWebhook()
141
181
  if (stopped || running) return queue
142
182
  running = true
143
183
  queue = (async () => {
@@ -204,7 +244,7 @@ async function createRuntime(options: StartHarnessWorkerRuntimeOptions): Promise
204
244
  const timeoutMs = stopOptions.timeoutMs ?? 30_000
205
245
  let timeout: ReturnType<typeof setTimeout> | undefined
206
246
  const timedOut = await Promise.race([
207
- Promise.allSettled([workerStopping, queue]).then(() => false),
247
+ Promise.allSettled([workerStopping, queue, webhookQueue]).then(() => false),
208
248
  new Promise<true>((resolve) => {
209
249
  timeout = setTimeout(() => resolve(true), timeoutMs)
210
250
  timeout.unref?.()
@@ -213,6 +253,7 @@ async function createRuntime(options: StartHarnessWorkerRuntimeOptions): Promise
213
253
  if (timeout) clearTimeout(timeout)
214
254
  if (timedOut) {
215
255
  dispatcher?.cancel()
256
+ webhookDispatcher?.cancel()
216
257
  scheduleController?.abort()
217
258
  }
218
259
  let failure: unknown
@@ -251,6 +292,7 @@ async function createRuntime(options: StartHarnessWorkerRuntimeOptions): Promise
251
292
  if (timer) clearInterval(timer)
252
293
  if (onSigterm) process.off('SIGTERM', onSigterm)
253
294
  dispatcher?.cancel()
295
+ webhookDispatcher?.cancel()
254
296
  scheduleController?.abort()
255
297
  controller?.abort()
256
298
  try {