@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,354 @@
1
+ // @vitest-environment node
2
+
3
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'
4
+ import { prisma } from '@allbluecn/database'
5
+
6
+ import { computeHmacHex } from '../signature.server'
7
+ import {
8
+ createWebhookRule,
9
+ deleteWebhookRule,
10
+ editWebhookRule,
11
+ getWebhookRule,
12
+ handleWebhookReceive,
13
+ listWebhookRules,
14
+ rotateWebhookSecret,
15
+ toRuleSummary,
16
+ WebhookServiceError,
17
+ } from '../webhook.service.server'
18
+ import { OUTBOX_KIND_WEBHOOK } from '../../outbox/outbox-store.server'
19
+ import { WEBHOOK_MAX_BODY_BYTES } from '../types'
20
+
21
+ const hasDb = !!process.env.DATABASE_URL
22
+ const MARKER = `vitest-webhook-${process.pid}`
23
+ const USER_A = `${MARKER}-a`
24
+ const USER_B = `${MARKER}-b`
25
+ const THREAD_A = `${MARKER}-thread-a`
26
+ const THREAD_A2 = `${MARKER}-thread-a2`
27
+ const THREAD_B = `${MARKER}-thread-b`
28
+ const NOW = Date.parse('2026-11-28T12:00:00.000Z')
29
+
30
+ const noopAudit = (async () => {}) as unknown as typeof import('@/server/audit').auditLog
31
+
32
+ const PUSH_PAYLOAD = {
33
+ ref: 'refs/heads/main',
34
+ repository: {
35
+ full_name: 'acme/app',
36
+ html_url: 'https://github.com/acme/app',
37
+ owner: { login: 'acme' },
38
+ },
39
+ head_commit: { message: 'fix: build' },
40
+ sender: { login: 'octocat' },
41
+ }
42
+
43
+ const encoder = new TextEncoder()
44
+
45
+ function signedRequest(input: {
46
+ body: string
47
+ secret: string
48
+ event?: string
49
+ deliveryId?: string
50
+ signatureOverride?: string
51
+ }): Request {
52
+ const bytes = encoder.encode(input.body)
53
+ const signature = input.signatureOverride ?? `sha256=${computeHmacHex(input.secret, bytes)}`
54
+ return new Request('http://localhost/api/harness/webhook/token', {
55
+ method: 'POST',
56
+ body: input.body,
57
+ headers: {
58
+ 'content-type': 'application/json',
59
+ 'x-hub-signature-256': signature,
60
+ 'x-github-event': input.event ?? 'push',
61
+ ...(input.deliveryId ? { 'x-github-delivery': input.deliveryId } : {}),
62
+ },
63
+ })
64
+ }
65
+
66
+ async function cleanup(): Promise<void> {
67
+ if (!hasDb) return
68
+ const userIds = [USER_A, USER_B]
69
+ await prisma.harnessOutbox.deleteMany({ where: { userId: { in: userIds } } })
70
+ await prisma.harnessWebhookDelivery.deleteMany({ where: { userId: { in: userIds } } })
71
+ await prisma.harnessWebhookRule.deleteMany({ where: { userId: { in: userIds } } })
72
+ await prisma.chatThread.deleteMany({
73
+ where: { id: { in: [THREAD_A, THREAD_A2, THREAD_B] } },
74
+ })
75
+ await prisma.user.deleteMany({ where: { id: { in: userIds } } })
76
+ }
77
+
78
+ beforeAll(async () => {
79
+ if (!hasDb) return
80
+ await cleanup()
81
+ await prisma.user.createMany({
82
+ data: [
83
+ { id: USER_A, email: `${MARKER}-a@example.com`, username: `${MARKER}-a`, password: 'test' },
84
+ { id: USER_B, email: `${MARKER}-b@example.com`, username: `${MARKER}-b`, password: 'test' },
85
+ ],
86
+ })
87
+ await prisma.chatThread.createMany({
88
+ data: [
89
+ { id: THREAD_A, userId: USER_A, engine: 'local', localCwd: '/tmp' },
90
+ { id: THREAD_A2, userId: USER_A, engine: 'local', localCwd: '/tmp' },
91
+ { id: THREAD_B, userId: USER_B, engine: 'local', localCwd: '/tmp' },
92
+ ],
93
+ })
94
+ })
95
+
96
+ afterAll(cleanup)
97
+
98
+ beforeEach(async () => {
99
+ if (!hasDb) return
100
+ await prisma.harnessOutbox.deleteMany({ where: { userId: { in: [USER_A, USER_B] } } })
101
+ await prisma.harnessWebhookDelivery.deleteMany({ where: { userId: { in: [USER_A, USER_B] } } })
102
+ await prisma.harnessWebhookRule.deleteMany({ where: { userId: { in: [USER_A, USER_B] } } })
103
+ })
104
+
105
+ afterEach(() => {})
106
+
107
+ async function seedRule(overrides: Partial<Parameters<typeof createWebhookRule>[0]> = {}) {
108
+ return createWebhookRule({
109
+ userId: USER_A,
110
+ threadId: THREAD_A,
111
+ name: 'Build watcher',
112
+ prompt: 'inspect the failure',
113
+ repoWhitelist: ['acme/app'],
114
+ executionPlane: 'local',
115
+ ...overrides,
116
+ })
117
+ }
118
+
119
+ describe.skipIf(!hasDb)('webhook 规则服务', () => {
120
+ it('创建时返回一次性明文密钥,落库只存密文与末 4 位', async () => {
121
+ const { rule, secret } = await seedRule()
122
+ expect(secret).toHaveLength(64)
123
+ expect(rule.secretCipher).not.toBe(secret)
124
+ expect(rule.secretCipher).not.toContain(secret)
125
+ expect(rule.secretHint).toBe(secret.slice(-4))
126
+
127
+ const summary = toRuleSummary(rule)
128
+ expect(summary.path).toBe(`/api/harness/webhook/${rule.token}`)
129
+ expect(summary.hasSecret).toBe(true)
130
+ expect(JSON.stringify(summary)).not.toContain(secret)
131
+ expect(JSON.stringify(summary)).not.toContain(rule.secretCipher)
132
+ })
133
+
134
+ it('跨端同步而来的规则(密钥不在本机)标 hasSecret=false 且端点 fail-closed', async () => {
135
+ const { rule } = await seedRule()
136
+ // 模拟 sync 下行:定义可见、secretCipher 为 NULL(密钥永不跨端)。
137
+ const synced = await prisma.harnessWebhookRule.update({
138
+ where: { id: rule.id },
139
+ data: { secretCipher: null },
140
+ })
141
+ expect(synced.secretCipher).toBeNull()
142
+
143
+ const summary = toRuleSummary(synced)
144
+ expect(summary.hasSecret).toBe(false)
145
+ expect(summary.secretHint).toBe(rule.secretHint)
146
+
147
+ const listed = await listWebhookRules({ userId: USER_A, threadId: THREAD_A })
148
+ const listedSummary = toRuleSummary(listed.find((entry) => entry.id === rule.id)!)
149
+ expect(listedSummary.hasSecret).toBe(false)
150
+
151
+ const response = await handleWebhookReceive(
152
+ signedRequest({ body: JSON.stringify(PUSH_PAYLOAD), secret: 'whatever-secret' }),
153
+ rule.token,
154
+ { now: NOW, audit: noopAudit },
155
+ )
156
+ // 没有密钥就不能验签:503 而非 401,避免把「未配置」误报成「签名错」。
157
+ expect(response.status).toBe(503)
158
+ })
159
+
160
+ it('未配置任何白名单直接拒绝(fail-closed)', async () => {
161
+ await expect(seedRule({ repoWhitelist: undefined, ownerWhitelist: undefined }))
162
+ .rejects.toBeInstanceOf(WebhookServiceError)
163
+ })
164
+
165
+ it('轮换密钥后旧密钥失效、新密钥生效', async () => {
166
+ const { rule, secret: oldSecret } = await seedRule()
167
+ const rotated = await rotateWebhookSecret({ userId: USER_A, id: rule.id })
168
+ expect(rotated.secret).not.toBe(oldSecret)
169
+ expect(rotated.rule.secretHint).toBe(rotated.secret.slice(-4))
170
+
171
+ const stale = await handleWebhookReceive(
172
+ signedRequest({ body: JSON.stringify(PUSH_PAYLOAD), secret: oldSecret }),
173
+ rule.token,
174
+ { now: NOW, audit: noopAudit },
175
+ )
176
+ expect(stale.status).toBe(401)
177
+
178
+ const fresh = await handleWebhookReceive(
179
+ signedRequest({ body: JSON.stringify(PUSH_PAYLOAD), secret: rotated.secret }),
180
+ rule.token,
181
+ { now: NOW, audit: noopAudit },
182
+ )
183
+ expect(fresh.status).toBe(202)
184
+ })
185
+
186
+ it('列表按线程过滤,删除后不可见', async () => {
187
+ const { rule } = await seedRule()
188
+ await seedRule({ threadId: THREAD_A2, repoWhitelist: ['acme/other'] })
189
+ expect(await listWebhookRules({ userId: USER_A, threadId: THREAD_A })).toHaveLength(1)
190
+
191
+ await deleteWebhookRule({ userId: USER_A, id: rule.id })
192
+ expect(await getWebhookRule({ userId: USER_A, id: rule.id })).toBeNull()
193
+ })
194
+
195
+ it('白名单改成空被拒绝(不允许通过编辑放开)', async () => {
196
+ const { rule } = await seedRule()
197
+ await expect(
198
+ editWebhookRule({
199
+ userId: USER_A,
200
+ id: rule.id,
201
+ revision: rule.revision,
202
+ repoWhitelist: [],
203
+ ownerWhitelist: [],
204
+ }),
205
+ ).rejects.toBeInstanceOf(WebhookServiceError)
206
+ })
207
+
208
+ it('暂停后接收端点返回 404(不泄露存在性)', async () => {
209
+ const { rule, secret } = await seedRule()
210
+ await editWebhookRule({ userId: USER_A, id: rule.id, revision: rule.revision, status: 'paused' })
211
+ const response = await handleWebhookReceive(
212
+ signedRequest({ body: JSON.stringify(PUSH_PAYLOAD), secret }),
213
+ rule.token,
214
+ { now: NOW, audit: noopAudit },
215
+ )
216
+ expect(response.status).toBe(404)
217
+ })
218
+ })
219
+
220
+ describe.skipIf(!hasDb)('接收管线', () => {
221
+ it('验签通过 → 202 + delivery + outbox(kind=webhook.delivery)', async () => {
222
+ const { rule, secret } = await seedRule()
223
+ const body = JSON.stringify(PUSH_PAYLOAD)
224
+ const response = await handleWebhookReceive(
225
+ signedRequest({ body, secret, deliveryId: 'delivery-1' }),
226
+ rule.token,
227
+ { now: NOW, audit: noopAudit },
228
+ )
229
+ expect(response.status).toBe(202)
230
+ expect(await response.json()).toEqual({ received: true })
231
+
232
+ const delivery = await prisma.harnessWebhookDelivery.findFirst({
233
+ where: { ruleId: rule.id },
234
+ })
235
+ expect(delivery).toMatchObject({
236
+ eventKey: 'github:delivery-1',
237
+ eventType: 'push',
238
+ repo: 'acme/app',
239
+ owner: 'acme',
240
+ state: 'pending',
241
+ })
242
+
243
+ const outbox = await prisma.harnessOutbox.findFirst({ where: { userId: USER_A } })
244
+ expect(outbox).toMatchObject({
245
+ kind: OUTBOX_KIND_WEBHOOK,
246
+ state: 'pending',
247
+ inputId: `webhook:${delivery!.id}`,
248
+ })
249
+ // 密钥不进任何落库投影
250
+ const serialized = JSON.stringify({ delivery, outbox })
251
+ expect(serialized).not.toContain(secret)
252
+ })
253
+
254
+ it('同一事件重投幂等:202 duplicate,delivery 与 outbox 各只有一行', async () => {
255
+ const { rule, secret } = await seedRule()
256
+ const body = JSON.stringify(PUSH_PAYLOAD)
257
+ const first = await handleWebhookReceive(
258
+ signedRequest({ body, secret, deliveryId: 'delivery-dup' }),
259
+ rule.token,
260
+ { now: NOW, audit: noopAudit },
261
+ )
262
+ const second = await handleWebhookReceive(
263
+ signedRequest({ body, secret, deliveryId: 'delivery-dup' }),
264
+ rule.token,
265
+ { now: NOW, audit: noopAudit },
266
+ )
267
+ expect(first.status).toBe(202)
268
+ expect(second.status).toBe(202)
269
+ expect(await second.json()).toEqual({ received: true, duplicate: true })
270
+
271
+ expect(await prisma.harnessWebhookDelivery.count({ where: { ruleId: rule.id } })).toBe(1)
272
+ expect(await prisma.harnessOutbox.count({ where: { userId: USER_A } })).toBe(1)
273
+ })
274
+
275
+ it('非法签名 401 且不产生任何投递', async () => {
276
+ const { rule, secret } = await seedRule()
277
+ const response = await handleWebhookReceive(
278
+ signedRequest({ body: JSON.stringify(PUSH_PAYLOAD), secret, signatureOverride: `sha256=${'0'.repeat(64)}` }),
279
+ rule.token,
280
+ { now: NOW, audit: noopAudit },
281
+ )
282
+ expect(response.status).toBe(401)
283
+ expect(await prisma.harnessWebhookDelivery.count({ where: { ruleId: rule.id } })).toBe(0)
284
+ expect(await prisma.harnessOutbox.count({ where: { userId: USER_A } })).toBe(0)
285
+ })
286
+
287
+ it('白名单外 repo 返回 403', async () => {
288
+ const { rule, secret } = await seedRule()
289
+ const otherRepo = { ...PUSH_PAYLOAD, repository: { ...PUSH_PAYLOAD.repository, full_name: 'evil/app' } }
290
+ const response = await handleWebhookReceive(
291
+ signedRequest({ body: JSON.stringify(otherRepo), secret }),
292
+ rule.token,
293
+ { now: NOW, audit: noopAudit },
294
+ )
295
+ expect(response.status).toBe(403)
296
+ expect(await prisma.harnessWebhookDelivery.count({ where: { ruleId: rule.id } })).toBe(0)
297
+ })
298
+
299
+ it('未订阅事件返回 202 ignored 且不建 delivery', async () => {
300
+ const { rule, secret } = await seedRule({ events: ['pull_request'] })
301
+ const response = await handleWebhookReceive(
302
+ signedRequest({ body: JSON.stringify(PUSH_PAYLOAD), secret, event: 'push' }),
303
+ rule.token,
304
+ { now: NOW, audit: noopAudit },
305
+ )
306
+ expect(response.status).toBe(202)
307
+ expect(await response.json()).toEqual({ received: true, ignored: 'event_not_subscribed' })
308
+ expect(await prisma.harnessWebhookDelivery.count({ where: { ruleId: rule.id } })).toBe(0)
309
+ })
310
+
311
+ it('body 超限 413', async () => {
312
+ const { rule, secret } = await seedRule()
313
+ const huge = '{"padding":"' + 'x'.repeat(WEBHOOK_MAX_BODY_BYTES) + '"}'
314
+ const response = await handleWebhookReceive(
315
+ signedRequest({ body: huge, secret }),
316
+ rule.token,
317
+ { now: NOW, audit: noopAudit },
318
+ )
319
+ expect(response.status).toBe(413)
320
+ })
321
+
322
+ it('非 JSON 400', async () => {
323
+ const { rule, secret } = await seedRule()
324
+ const response = await handleWebhookReceive(
325
+ signedRequest({ body: 'not-json', secret }),
326
+ rule.token,
327
+ { now: NOW, audit: noopAudit },
328
+ )
329
+ expect(response.status).toBe(400)
330
+ })
331
+
332
+ it('未知 token 404', async () => {
333
+ const response = await handleWebhookReceive(
334
+ signedRequest({ body: JSON.stringify(PUSH_PAYLOAD), secret: 'a'.repeat(64) }),
335
+ 'unknown-token-abcdefghijklmnop',
336
+ { now: NOW, audit: noopAudit },
337
+ )
338
+ expect(response.status).toBe(404)
339
+ })
340
+
341
+ it('他用户的规则 token 不会串到本用户(按 token 精确命中)', async () => {
342
+ const { rule, secret } = await seedRule()
343
+ const foreign = await seedRule({ userId: USER_B, threadId: THREAD_B })
344
+ expect(foreign.rule.token).not.toBe(rule.token)
345
+
346
+ const response = await handleWebhookReceive(
347
+ signedRequest({ body: JSON.stringify(PUSH_PAYLOAD), secret }),
348
+ foreign.rule.token,
349
+ { now: NOW, audit: noopAudit },
350
+ )
351
+ // foreign 规则的密钥与之不同 → 验签失败
352
+ expect(response.status).toBe(401)
353
+ })
354
+ })
@@ -0,0 +1,56 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+
5
+ // 入站 webhook raw body 有界摄取(P5 任务 3)。
6
+ // 两层防线:先看 Content-Length 预检(不读 body 直接拒),再流式累计(防伪造/缺失
7
+ // Content-Length 的超大 chunked body)。任一超限即取消读取,不把整个 body 读进内存。
8
+
9
+ import { WEBHOOK_MAX_BODY_BYTES } from './types'
10
+
11
+ export type BodyReadResult =
12
+ | { ok: true; bytes: Uint8Array }
13
+ | { ok: false; reason: 'too_large' | 'unreadable' }
14
+
15
+ export async function readBoundedBody(
16
+ request: Request,
17
+ limit: number = WEBHOOK_MAX_BODY_BYTES,
18
+ ): Promise<BodyReadResult> {
19
+ const declared = request.headers.get('content-length')
20
+ if (declared !== null) {
21
+ const length = Number(declared)
22
+ if (!Number.isFinite(length) || length < 0) return { ok: false, reason: 'unreadable' }
23
+ if (length > limit) return { ok: false, reason: 'too_large' }
24
+ }
25
+
26
+ const stream = request.body
27
+ if (stream === null) return { ok: true, bytes: new Uint8Array(0) }
28
+
29
+ const reader = stream.getReader()
30
+ const chunks: Uint8Array[] = []
31
+ let total = 0
32
+ try {
33
+ for (;;) {
34
+ const { done, value } = await reader.read()
35
+ if (done) break
36
+ if (!value) continue
37
+ total += value.byteLength
38
+ if (total > limit) {
39
+ await reader.cancel().catch(() => undefined)
40
+ return { ok: false, reason: 'too_large' }
41
+ }
42
+ chunks.push(value)
43
+ }
44
+ } catch {
45
+ await reader.cancel().catch(() => undefined)
46
+ return { ok: false, reason: 'unreadable' }
47
+ }
48
+
49
+ const bytes = new Uint8Array(total)
50
+ let offset = 0
51
+ for (const chunk of chunks) {
52
+ bytes.set(chunk, offset)
53
+ offset += chunk.byteLength
54
+ }
55
+ return { ok: true, bytes }
56
+ }
@@ -0,0 +1,169 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+
5
+ // 入站 webhook 的纯函数层:事件摘要提取、去重键、白名单/订阅匹配、prompt 渲染。
6
+ // 全为确定函数,接收管线只做 I/O 编排,便于逐条单测(计划任务 3 测试项 ③④)。
7
+
8
+ import { createHash } from 'node:crypto'
9
+
10
+ import {
11
+ GITHUB_DELIVERY_HEADER,
12
+ GITHUB_EVENT_HEADER,
13
+ TIMESTAMPED_TIMESTAMP_HEADER,
14
+ } from './signature.server'
15
+ import type { WebhookEventSummary } from './types'
16
+
17
+ const MAX_TITLE_LENGTH = 200
18
+
19
+ function asRecord(value: unknown): Record<string, unknown> | null {
20
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
21
+ ? (value as Record<string, unknown>)
22
+ : null
23
+ }
24
+
25
+ function asString(value: unknown): string | null {
26
+ return typeof value === 'string' && value.length > 0 ? value : null
27
+ }
28
+
29
+ function truncated(value: string | null): string | null {
30
+ if (value === null) return null
31
+ return value.length <= MAX_TITLE_LENGTH ? value : `${value.slice(0, MAX_TITLE_LENGTH)}…`
32
+ }
33
+
34
+ function nested(value: unknown, ...path: string[]): unknown {
35
+ let current: unknown = value
36
+ for (const key of path) {
37
+ const record = asRecord(current)
38
+ if (!record) return null
39
+ current = record[key]
40
+ }
41
+ return current
42
+ }
43
+
44
+ /**
45
+ * 从 GitHub 事件体提取有界摘要。非 GitHub 形状时各字段退化为 null,不抛错
46
+ * (未知 provider 的事件仍可投递,只是上下文更少)。
47
+ */
48
+ export function extractEventSummary(input: {
49
+ headers: Headers
50
+ payload: unknown
51
+ }): WebhookEventSummary {
52
+ const event = input.headers.get(GITHUB_EVENT_HEADER)?.trim() || 'unknown'
53
+ const pullRequest = nested(input.payload, 'pull_request')
54
+ const issue = nested(input.payload, 'issue')
55
+ const repository = nested(input.payload, 'repository')
56
+
57
+ return {
58
+ event,
59
+ action: truncated(asString(nested(input.payload, 'action'))),
60
+ repo: truncated(asString(nested(repository, 'full_name'))),
61
+ owner: truncated(
62
+ asString(nested(repository, 'owner', 'login'))
63
+ ?? asString(nested(repository, 'owner', 'name')),
64
+ ),
65
+ ref: truncated(
66
+ asString(nested(input.payload, 'ref'))
67
+ ?? asString(nested(pullRequest, 'head', 'ref')),
68
+ ),
69
+ title: truncated(
70
+ asString(nested(pullRequest, 'title'))
71
+ ?? asString(nested(issue, 'title'))
72
+ ?? firstLine(asString(nested(input.payload, 'head_commit', 'message'))),
73
+ ),
74
+ url: truncated(
75
+ asString(nested(pullRequest, 'html_url'))
76
+ ?? asString(nested(issue, 'html_url'))
77
+ ?? asString(nested(input.payload, 'compare'))
78
+ ?? asString(nested(repository, 'html_url')),
79
+ ),
80
+ actor: truncated(asString(nested(input.payload, 'sender', 'login'))),
81
+ }
82
+ }
83
+
84
+ function firstLine(value: string | null): string | null {
85
+ if (value === null) return null
86
+ const line = value.split('\n', 1)[0]?.trim()
87
+ return line && line.length > 0 ? line : null
88
+ }
89
+
90
+ /**
91
+ * 去重键:
92
+ * 1. GitHub 优先用投递 guid(`X-GitHub-Delivery`,上游重投时不变);
93
+ * 2. 带时间戳方案用 `timestamp + body 摘要`(同窗口重放命中唯一键);
94
+ * 3. 兜底用整段 body 摘要(同 body 重投同样去重)。
95
+ */
96
+ export function computeEventKey(input: {
97
+ headers: Headers
98
+ body: Uint8Array
99
+ summary: WebhookEventSummary
100
+ }): string {
101
+ const delivery = input.headers.get(GITHUB_DELIVERY_HEADER)?.trim()
102
+ if (delivery) return `github:${delivery}`
103
+ const digest = createHash('sha256').update(input.body).digest('hex')
104
+ const timestamp = input.headers.get(TIMESTAMPED_TIMESTAMP_HEADER)?.trim()
105
+ if (timestamp && /^\d{1,12}$/.test(timestamp)) {
106
+ return `${input.summary.event}:${timestamp}:${digest.slice(0, 16)}`
107
+ }
108
+ return `${input.summary.event}:${digest.slice(0, 32)}`
109
+ }
110
+
111
+ /** 事件订阅匹配:events 为 null 表示全部订阅。 */
112
+ export function matchesSubscribedEvents(
113
+ events: readonly string[] | null,
114
+ summary: WebhookEventSummary,
115
+ ): boolean {
116
+ if (events === null || events.length === 0) return true
117
+ return events.includes(summary.event)
118
+ }
119
+
120
+ /**
121
+ * repo/owner 白名单匹配(精确匹配,大小写不敏感——GitHub owner/repo 大小写不敏感)。
122
+ * 两个白名单都为 null 视为「未配置」→ 不匹配(fail-closed:规则创建时已强制至少一个)。
123
+ */
124
+ export function matchesWhitelist(input: {
125
+ repoWhitelist: readonly string[] | null
126
+ ownerWhitelist: readonly string[] | null
127
+ summary: Pick<WebhookEventSummary, 'repo' | 'owner'>
128
+ }): boolean {
129
+ const repo = input.summary.repo?.toLowerCase() ?? null
130
+ const owner = input.summary.owner?.toLowerCase() ?? null
131
+ const repos = input.repoWhitelist?.map((entry) => entry.toLowerCase()) ?? null
132
+ const owners = input.ownerWhitelist?.map((entry) => entry.toLowerCase()) ?? null
133
+
134
+ if (repos !== null && repos.length > 0 && repo !== null && repos.includes(repo)) return true
135
+ if (owners !== null && owners.length > 0 && owner !== null && owners.includes(owner)) return true
136
+ return false
137
+ }
138
+
139
+ /**
140
+ * 投递给 agent 的 prompt:固定格式头 + 规则 prompt。
141
+ * 头只含有界摘要字段(无 payload 全文、无签名、无密钥)。
142
+ */
143
+ export function renderWebhookPrompt(input: {
144
+ name: string
145
+ provider: string
146
+ prompt: string
147
+ summary: WebhookEventSummary
148
+ }): string {
149
+ const lines = [`[webhook] ${input.provider} ${input.summary.event} · ${input.name}`]
150
+ if (input.summary.repo) lines.push(`repo: ${input.summary.repo}`)
151
+ if (input.summary.action) lines.push(`action: ${input.summary.action}`)
152
+ if (input.summary.ref) lines.push(`ref: ${input.summary.ref}`)
153
+ if (input.summary.actor) lines.push(`actor: ${input.summary.actor}`)
154
+ if (input.summary.title) lines.push(`title: ${input.summary.title}`)
155
+ if (input.summary.url) lines.push(`url: ${input.summary.url}`)
156
+ lines.push('', input.prompt)
157
+ return lines.join('\n')
158
+ }
159
+
160
+ /** 解析 JSON body;非对象或解析失败返回 null(接收管线据此 400)。 */
161
+ export function parseWebhookPayload(body: Uint8Array): unknown | null {
162
+ try {
163
+ const text = new TextDecoder('utf-8', { fatal: false }).decode(body)
164
+ const parsed: unknown = JSON.parse(text)
165
+ return parsed
166
+ } catch {
167
+ return null
168
+ }
169
+ }
@@ -0,0 +1,118 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+
5
+ // 入站 webhook 签名校验(P5 任务 3,母规格 §6.2)。
6
+ //
7
+ // 两种方案并存,按头选择:
8
+ // 1. **GitHub**:`X-Hub-Signature-256: sha256=<hex>`,HMAC-SHA256(secret, rawBody)。
9
+ // GitHub 不带时间戳,重放由投递 guid(`X-GitHub-Delivery`)的唯一键去重承担。
10
+ // 2. **带时间戳**(generic):`X-AllBlue-Timestamp: <unix 秒>` +
11
+ // `X-AllBlue-Signature: v1=<hex>`,签名体 `${timestamp}.${rawBody}`,窗口 ±5 分钟。
12
+ // 时间戳参与签名:窗口内篡改时间戳无法通过验签。
13
+ //
14
+ // 一律 timingSafeEqual 比较;任何格式异常按 invalid 处理,不回显期望值。
15
+
16
+ import { createHmac, timingSafeEqual } from 'node:crypto'
17
+
18
+ import { WEBHOOK_REPLAY_WINDOW_MS } from './types'
19
+
20
+ export const GITHUB_SIGNATURE_HEADER = 'x-hub-signature-256'
21
+ export const GITHUB_EVENT_HEADER = 'x-github-event'
22
+ export const GITHUB_DELIVERY_HEADER = 'x-github-delivery'
23
+ export const TIMESTAMPED_SIGNATURE_HEADER = 'x-allblue-signature'
24
+ export const TIMESTAMPED_TIMESTAMP_HEADER = 'x-allblue-timestamp'
25
+
26
+ export type SignatureScheme = 'github' | 'timestamped'
27
+
28
+ export type SignatureCheck =
29
+ | { ok: true; scheme: SignatureScheme }
30
+ | {
31
+ ok: false
32
+ reason: 'missing_signature' | 'invalid_signature' | 'stale_timestamp' | 'bad_timestamp'
33
+ }
34
+
35
+ function hmacHex(secret: string, chunks: readonly Uint8Array[]): string {
36
+ const hmac = createHmac('sha256', secret)
37
+ for (const chunk of chunks) hmac.update(chunk)
38
+ return hmac.digest('hex')
39
+ }
40
+
41
+ /** HMAC-SHA256(secret, body) 的小写 hex(GitHub 方案)。 */
42
+ export function computeHmacHex(secret: string, body: Uint8Array): string {
43
+ return hmacHex(secret, [body])
44
+ }
45
+
46
+ /** 带时间戳签名:HMAC-SHA256(secret, `${timestamp}.${body}`) 的小写 hex。 */
47
+ export function computeTimestampedSignature(
48
+ secret: string,
49
+ timestamp: string,
50
+ body: Uint8Array,
51
+ ): string {
52
+ return hmacHex(secret, [Buffer.from(`${timestamp}.`, 'utf8'), body])
53
+ }
54
+
55
+ /** 去掉可选的 `sha256=` / `v1=` 前缀,返回小写 hex;格式非法返回 null。 */
56
+ function normalizeHexSignature(raw: string, prefixes: readonly string[]): string | null {
57
+ let value = raw.trim()
58
+ for (const prefix of prefixes) {
59
+ if (value.startsWith(prefix)) {
60
+ value = value.slice(prefix.length)
61
+ break
62
+ }
63
+ }
64
+ if (value.length !== 64 || !/^[0-9a-fA-F]{64}$/.test(value)) return null
65
+ return value.toLowerCase()
66
+ }
67
+
68
+ function safeEqualHex(expectedHex: string, actualHex: string): boolean {
69
+ const expected = Buffer.from(expectedHex, 'hex')
70
+ const actual = Buffer.from(actualHex, 'hex')
71
+ if (expected.length !== actual.length) return false
72
+ return timingSafeEqual(expected, actual)
73
+ }
74
+
75
+ /**
76
+ * 按请求头选择方案并验签。
77
+ *
78
+ * `now` 可注入,便于测试重放窗口边界。
79
+ */
80
+ export function verifyWebhookSignature(input: {
81
+ secret: string
82
+ body: Uint8Array
83
+ headers: Headers
84
+ now?: number
85
+ }): SignatureCheck {
86
+ const githubRaw = input.headers.get(GITHUB_SIGNATURE_HEADER)
87
+ if (githubRaw !== null) {
88
+ const provided = normalizeHexSignature(githubRaw, ['sha256='])
89
+ if (!provided) return { ok: false, reason: 'invalid_signature' }
90
+ const expected = computeHmacHex(input.secret, input.body)
91
+ return safeEqualHex(expected, provided)
92
+ ? { ok: true, scheme: 'github' }
93
+ : { ok: false, reason: 'invalid_signature' }
94
+ }
95
+
96
+ const timestamp = input.headers.get(TIMESTAMPED_TIMESTAMP_HEADER)
97
+ const signature = input.headers.get(TIMESTAMPED_SIGNATURE_HEADER)
98
+ if (timestamp === null && signature === null) {
99
+ return { ok: false, reason: 'missing_signature' }
100
+ }
101
+ if (timestamp === null || signature === null) {
102
+ return { ok: false, reason: 'missing_signature' }
103
+ }
104
+ if (!/^\d{1,12}$/.test(timestamp.trim())) {
105
+ return { ok: false, reason: 'bad_timestamp' }
106
+ }
107
+ const timestampMs = Number(timestamp.trim()) * 1000
108
+ const now = input.now ?? Date.now()
109
+ if (Math.abs(now - timestampMs) > WEBHOOK_REPLAY_WINDOW_MS) {
110
+ return { ok: false, reason: 'stale_timestamp' }
111
+ }
112
+ const provided = normalizeHexSignature(signature, ['v1='])
113
+ if (!provided) return { ok: false, reason: 'invalid_signature' }
114
+ const expected = computeTimestampedSignature(input.secret, timestamp.trim(), input.body)
115
+ return safeEqualHex(expected, provided)
116
+ ? { ok: true, scheme: 'timestamped' }
117
+ : { ok: false, reason: 'invalid_signature' }
118
+ }