@allbluecn/web-app 0.28.11 → 0.28.13

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 (133) 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/components/story/detail/story-detail-toolbar/associated-attachments-panel.tsx +2 -1
  12. package/src/dev/gallery-entry.tsx +38 -0
  13. package/src/dev/gallery.tsx +610 -0
  14. package/src/lib/changelog/sdk-versions.ts +4 -4
  15. package/src/lib/session.ts +10 -0
  16. package/src/paraglide/README.md +1 -1
  17. package/src/paraglide/messages/_index.d.ts +9 -0
  18. package/src/paraglide/messages/_index.js +9 -0
  19. package/src/paraglide/messages/capabilities_webhook.d.ts +16 -0
  20. package/src/paraglide/messages/capabilities_webhook.js +29 -0
  21. package/src/paraglide/messages/capabilities_workflow.d.ts +16 -0
  22. package/src/paraglide/messages/capabilities_workflow.js +29 -0
  23. package/src/paraglide/messages/harness_panel_terminal_exitedrecycled1.d.ts +17 -0
  24. package/src/paraglide/messages/harness_panel_terminal_exitedrecycled1.js +30 -0
  25. package/src/paraglide/messages/harness_panel_terminal_restarted.d.ts +16 -0
  26. package/src/paraglide/messages/harness_panel_terminal_restarted.js +29 -0
  27. package/src/paraglide/messages/settings_harness_connectors_needsauth1.d.ts +17 -0
  28. package/src/paraglide/messages/settings_harness_connectors_needsauth1.js +30 -0
  29. package/src/paraglide/messages/settings_harness_ralphenabled1.d.ts +17 -0
  30. package/src/paraglide/messages/settings_harness_ralphenabled1.js +30 -0
  31. package/src/paraglide/messages/settings_harness_ralphenabled_description1.d.ts +17 -0
  32. package/src/paraglide/messages/settings_harness_ralphenabled_description1.js +30 -0
  33. package/src/paraglide/messages/settings_harness_ralphmaxrounds2.d.ts +17 -0
  34. package/src/paraglide/messages/settings_harness_ralphmaxrounds2.js +30 -0
  35. package/src/paraglide/messages/settings_harness_ralphmaxrounds_description2.d.ts +17 -0
  36. package/src/paraglide/messages/settings_harness_ralphmaxrounds_description2.js +30 -0
  37. package/src/routeTree.gen.ts +21 -0
  38. package/src/routes/api/auth/desktop-callback.ts +9 -0
  39. package/src/routes/api/chat.ts +8 -1
  40. package/src/routes/api/harness/browser/proxy.ts +41 -12
  41. package/src/routes/api/harness/terminal/$.ts +32 -13
  42. package/src/routes/api/harness/terminal/__tests__/route.test.ts +41 -0
  43. package/src/routes/api/harness/webhook/$token.ts +23 -0
  44. package/src/routes/api/sync/__tests__/bootstrap.test.ts +32 -1
  45. package/src/routes/api/sync/bootstrap.ts +11 -0
  46. package/src/server/ai-gateway/adapter.ts +7 -3
  47. package/src/server/ai-gateway/connectivity-check.ts +3 -2
  48. package/src/server/ai-gateway/durability/__tests__/sse-resume-frames.test.ts +123 -0
  49. package/src/server/ai-gateway/embedding.ts +3 -2
  50. package/src/server/ai-gateway/model-fetch.ts +3 -2
  51. package/src/server/ai-gateway/sandbox/__tests__/provider.test.ts +12 -1
  52. package/src/server/ai-gateway/sandbox/policy.ts +27 -1
  53. package/src/server/ai-gateway/sandbox/provider.ts +10 -0
  54. package/src/server/ai-gateway/tools/definitions.ts +1 -1
  55. package/src/server/ai-gateway/tools/server.ts +4 -2
  56. package/src/server/harness/__tests__/agent-terminal-sandbox.test.ts +23 -4
  57. package/src/server/harness/__tests__/agent-terminal.server.test.ts +118 -2
  58. package/src/server/harness/__tests__/credentials.server.test.ts +25 -2
  59. package/src/server/harness/__tests__/host-schedule-worker.test.ts +43 -0
  60. package/src/server/harness/__tests__/runtime-without-providers.test.ts +11 -0
  61. package/src/server/harness/__tests__/sticky-route.test.ts +86 -0
  62. package/src/server/harness/__tests__/terminal-foreground.server.test.ts +80 -0
  63. package/src/server/harness/__tests__/terminal-manager.server.test.ts +75 -1
  64. package/src/server/harness/__tests__/tool-entitlements.test.ts +6 -2
  65. package/src/server/harness/agent-terminal.server.ts +25 -4
  66. package/src/server/harness/agents/__tests__/agent-control.test.ts +1 -0
  67. package/src/server/harness/agents/run-view.server.ts +55 -2
  68. package/src/server/harness/capabilities/__tests__/__snapshots__/matrix.test.ts.snap +92 -0
  69. package/src/server/harness/capabilities/__tests__/execution-plane-denials.test.ts +3 -1
  70. package/src/server/harness/capabilities/__tests__/p3-matrix.test.ts +3 -3
  71. package/src/server/harness/capabilities/__tests__/p5-matrix.test.ts +293 -0
  72. package/src/server/harness/capabilities/__tests__/validate.test.ts +8 -2
  73. package/src/server/harness/capabilities/execution-plane-denials.ts +9 -3
  74. package/src/server/harness/capabilities/manifests/agent-terminal.ts +3 -2
  75. package/src/server/harness/capabilities/manifests/webhook.ts +45 -0
  76. package/src/server/harness/capabilities/manifests/workflow.ts +40 -0
  77. package/src/server/harness/capabilities/registry.ts +4 -0
  78. package/src/server/harness/connectors/__tests__/connector-accounts.test.ts +22 -1
  79. package/src/server/harness/connectors/connector-accounts.server.ts +7 -0
  80. package/src/server/harness/credentials.server.ts +3 -1
  81. package/src/server/harness/define.server.ts +11 -0
  82. package/src/server/harness/mcp/mcp-config.server.ts +3 -1
  83. package/src/server/harness/outbox/outbox-dispatcher.server.ts +9 -0
  84. package/src/server/harness/outbox/outbox-store.server.ts +7 -0
  85. package/src/server/harness/persistence/__tests__/log-store.server.test.ts +4 -1
  86. package/src/server/harness/plugins/__tests__/tool-risk-audit.test.ts +5 -1
  87. package/src/server/harness/plugins/builtin/agent-terminal.plugin.ts +12 -2
  88. package/src/server/harness/providers/contracts.ts +16 -0
  89. package/src/server/harness/schedule/schedule-dispatcher.server.ts +3 -0
  90. package/src/server/harness/search/__tests__/indexer.test.ts +4 -1
  91. package/src/server/harness/search/__tests__/lifecycle.test.ts +4 -1
  92. package/src/server/harness/search/__tests__/search.test.ts +4 -1
  93. package/src/server/harness/sticky-route.server.ts +72 -0
  94. package/src/server/harness/terminal-foreground.server.ts +90 -0
  95. package/src/server/harness/terminal-manager.server.ts +78 -3
  96. package/src/server/harness/tool-entitlements.server.ts +5 -0
  97. package/src/server/harness/webhook/__tests__/body.test.ts +73 -0
  98. package/src/server/harness/webhook/__tests__/payload.test.ts +215 -0
  99. package/src/server/harness/webhook/__tests__/signature.test.ts +170 -0
  100. package/src/server/harness/webhook/__tests__/webhook-dispatcher.test.ts +212 -0
  101. package/src/server/harness/webhook/__tests__/webhook.plugin.test.ts +195 -0
  102. package/src/server/harness/webhook/__tests__/webhook.service.test.ts +354 -0
  103. package/src/server/harness/webhook/body.server.ts +56 -0
  104. package/src/server/harness/webhook/payload.server.ts +169 -0
  105. package/src/server/harness/webhook/signature.server.ts +118 -0
  106. package/src/server/harness/webhook/types.ts +57 -0
  107. package/src/server/harness/webhook/webhook-dispatcher.server.ts +495 -0
  108. package/src/server/harness/webhook/webhook-store.server.ts +115 -0
  109. package/src/server/harness/webhook/webhook.plugin.ts +273 -0
  110. package/src/server/harness/webhook/webhook.service.server.ts +577 -0
  111. package/src/server/harness/worker/__tests__/worker-http.test.ts +8 -1
  112. package/src/server/harness/worker/worker-health.server.ts +4 -1
  113. package/src/server/harness/worker/worker-runtime.server.ts +43 -1
  114. package/src/server/harness/workflow/__tests__/engine.test.ts +195 -0
  115. package/src/server/harness/workflow/__tests__/settings.test.ts +125 -0
  116. package/src/server/harness/workflow/__tests__/validate.test.ts +151 -0
  117. package/src/server/harness/workflow/engine.server.ts +155 -0
  118. package/src/server/harness/workflow/settings.ts +84 -0
  119. package/src/server/harness/workflow/store.server.ts +147 -0
  120. package/src/server/harness/workflow/types.ts +80 -0
  121. package/src/server/harness/workflow/validate.ts +130 -0
  122. package/src/server/harness/workflow/workflow.plugin.ts +261 -0
  123. package/src/server/knowledge/search-scope.ts +8 -1
  124. package/src/server/middlewares/security-headers.ts +1 -0
  125. package/src/server/serverFns/__tests__/link-preview.test.ts +2 -2
  126. package/src/server/serverFns/collab.ts +4 -0
  127. package/src/server/serverFns/design/versions.ts +6 -0
  128. package/src/server/serverFns/harness/__tests__/fork-thread.test.ts +14 -1
  129. package/src/server/serverFns/harness/fork-thread.ts +17 -0
  130. package/src/server/serverFns/story/link-preview.ts +3 -2
  131. package/src/server-entry.ts +13 -1
  132. package/src/start.ts +15 -1
  133. package/vite.shared.ts +0 -13
@@ -0,0 +1,215 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import {
4
+ computeEventKey,
5
+ extractEventSummary,
6
+ matchesSubscribedEvents,
7
+ matchesWhitelist,
8
+ parseWebhookPayload,
9
+ renderWebhookPrompt,
10
+ } from '../payload.server'
11
+
12
+ const encoder = new TextEncoder()
13
+
14
+ function headers(entries: Record<string, string>): Headers {
15
+ return new Headers(entries)
16
+ }
17
+
18
+ const PUSH_PAYLOAD = {
19
+ ref: 'refs/heads/main',
20
+ compare: 'https://github.com/acme/app/compare/a...b',
21
+ head_commit: { message: 'fix: broken build\n\nlong body' },
22
+ repository: {
23
+ full_name: 'acme/app',
24
+ html_url: 'https://github.com/acme/app',
25
+ owner: { login: 'acme' },
26
+ },
27
+ sender: { login: 'octocat' },
28
+ }
29
+
30
+ const PR_PAYLOAD = {
31
+ action: 'opened',
32
+ pull_request: {
33
+ title: 'Add webhook support',
34
+ html_url: 'https://github.com/acme/app/pull/1',
35
+ head: { ref: 'feat/webhook' },
36
+ },
37
+ repository: {
38
+ full_name: 'Acme/App',
39
+ owner: { login: 'Acme' },
40
+ },
41
+ sender: { login: 'octocat' },
42
+ }
43
+
44
+ describe('事件摘要提取', () => {
45
+ it('push 事件提取 repo/owner/ref/首行提交信息/compare url', () => {
46
+ const summary = extractEventSummary({ headers: headers({ 'x-github-event': 'push' }), payload: PUSH_PAYLOAD })
47
+ expect(summary.event).toBe('push')
48
+ expect(summary.repo).toBe('acme/app')
49
+ expect(summary.owner).toBe('acme')
50
+ expect(summary.ref).toBe('refs/heads/main')
51
+ expect(summary.title).toBe('fix: broken build')
52
+ expect(summary.url).toBe('https://github.com/acme/app/compare/a...b')
53
+ expect(summary.actor).toBe('octocat')
54
+ })
55
+
56
+ it('pull_request 事件优先取 PR 标题与 head ref', () => {
57
+ const summary = extractEventSummary({
58
+ headers: headers({ 'x-github-event': 'pull_request' }),
59
+ payload: PR_PAYLOAD,
60
+ })
61
+ expect(summary.action).toBe('opened')
62
+ expect(summary.title).toBe('Add webhook support')
63
+ expect(summary.ref).toBe('feat/webhook')
64
+ expect(summary.url).toBe('https://github.com/acme/app/pull/1')
65
+ })
66
+
67
+ it('未知/非 GitHub 形状退化为 null 而不抛错', () => {
68
+ const summary = extractEventSummary({ headers: new Headers(), payload: { hello: 'world' } })
69
+ expect(summary.event).toBe('unknown')
70
+ expect(summary.repo).toBeNull()
71
+ expect(summary.title).toBeNull()
72
+ expect(summary.actor).toBeNull()
73
+ })
74
+
75
+ it('超长标题被截断(有界摘要)', () => {
76
+ const longTitle = 'x'.repeat(500)
77
+ const summary = extractEventSummary({
78
+ headers: headers({ 'x-github-event': 'pull_request' }),
79
+ payload: { pull_request: { title: longTitle } },
80
+ })
81
+ expect(summary.title?.length).toBeLessThanOrEqual(201)
82
+ expect(summary.title?.endsWith('…')).toBe(true)
83
+ })
84
+ })
85
+
86
+ describe('去重键', () => {
87
+ const summary = extractEventSummary({ headers: headers({ 'x-github-event': 'push' }), payload: PUSH_PAYLOAD })
88
+ const body = encoder.encode(JSON.stringify(PUSH_PAYLOAD))
89
+
90
+ it('优先用 GitHub 投递 guid', () => {
91
+ const key = computeEventKey({
92
+ headers: headers({ 'x-github-delivery': '72d3162e-cc78-11e3-81ab-4c9367dc0958' }),
93
+ body,
94
+ summary,
95
+ })
96
+ expect(key).toBe('github:72d3162e-cc78-11e3-81ab-4c9367dc0958')
97
+ })
98
+
99
+ it('无 guid 时用 timestamp + body 摘要(同窗口重放命中同一键)', () => {
100
+ const args = {
101
+ headers: headers({ 'x-allblue-timestamp': '1795800000' }),
102
+ body,
103
+ summary,
104
+ }
105
+ const first = computeEventKey(args)
106
+ const second = computeEventKey(args)
107
+ expect(first).toBe(second)
108
+ expect(first.startsWith('push:1795800000:')).toBe(true)
109
+ })
110
+
111
+ it('无 guid 无时间戳时退化为 body 摘要', () => {
112
+ const first = computeEventKey({ headers: new Headers(), body, summary })
113
+ const second = computeEventKey({ headers: new Headers(), body, summary })
114
+ expect(first).toBe(second)
115
+ expect(first.startsWith('push:')).toBe(true)
116
+ expect(first.split(':')[1]).toHaveLength(32)
117
+ })
118
+
119
+ it('body 不同则键不同(不是恒定值)', () => {
120
+ const other = encoder.encode(JSON.stringify({ ...PUSH_PAYLOAD, ref: 'refs/heads/dev' }))
121
+ expect(computeEventKey({ headers: new Headers(), body, summary }))
122
+ .not.toBe(computeEventKey({ headers: new Headers(), body: other, summary }))
123
+ })
124
+ })
125
+
126
+ describe('事件订阅匹配', () => {
127
+ const summary = extractEventSummary({ headers: headers({ 'x-github-event': 'push' }), payload: PUSH_PAYLOAD })
128
+
129
+ it('events 为 null 或空 → 全部订阅', () => {
130
+ expect(matchesSubscribedEvents(null, summary)).toBe(true)
131
+ expect(matchesSubscribedEvents([], summary)).toBe(true)
132
+ })
133
+
134
+ it('命中订阅 → true;未命中 → false', () => {
135
+ expect(matchesSubscribedEvents(['push', 'pull_request'], summary)).toBe(true)
136
+ expect(matchesSubscribedEvents(['issues'], summary)).toBe(false)
137
+ })
138
+ })
139
+
140
+ describe('repo/owner 白名单', () => {
141
+ const summary = extractEventSummary({
142
+ headers: headers({ 'x-github-event': 'pull_request' }),
143
+ payload: PR_PAYLOAD,
144
+ })
145
+
146
+ it('repo 精确命中(大小写不敏感)', () => {
147
+ expect(
148
+ matchesWhitelist({ repoWhitelist: ['acme/app'], ownerWhitelist: null, summary }),
149
+ ).toBe(true)
150
+ })
151
+
152
+ it('owner 命中即可(无需逐个列 repo)', () => {
153
+ expect(
154
+ matchesWhitelist({ repoWhitelist: null, ownerWhitelist: ['ACME'], summary }),
155
+ ).toBe(true)
156
+ })
157
+
158
+ it('都不命中 → false(跨仓库事件被拒)', () => {
159
+ expect(
160
+ matchesWhitelist({ repoWhitelist: ['other/app'], ownerWhitelist: ['other'], summary }),
161
+ ).toBe(false)
162
+ })
163
+
164
+ it('两个白名单都空 → fail-closed 拒绝', () => {
165
+ expect(matchesWhitelist({ repoWhitelist: null, ownerWhitelist: null, summary })).toBe(false)
166
+ expect(matchesWhitelist({ repoWhitelist: [], ownerWhitelist: [], summary })).toBe(false)
167
+ })
168
+
169
+ it('事件里没有 repo/owner 时不因空匹配放行', () => {
170
+ const anonymous = extractEventSummary({ headers: new Headers(), payload: {} })
171
+ expect(matchesWhitelist({ repoWhitelist: ['acme/app'], ownerWhitelist: null, summary: anonymous }))
172
+ .toBe(false)
173
+ })
174
+ })
175
+
176
+ describe('prompt 渲染', () => {
177
+ const summary = extractEventSummary({ headers: headers({ 'x-github-event': 'push' }), payload: PUSH_PAYLOAD })
178
+
179
+ it('首行标识事件与规则名,后续只含有界摘要字段', () => {
180
+ const prompt = renderWebhookPrompt({
181
+ name: 'build watcher',
182
+ provider: 'github',
183
+ prompt: '检查构建失败原因并修复',
184
+ summary,
185
+ })
186
+ expect(prompt.split('\n')[0]).toBe('[webhook] github push · build watcher')
187
+ expect(prompt).toContain('repo: acme/app')
188
+ expect(prompt).toContain('ref: refs/heads/main')
189
+ expect(prompt).toContain('actor: octocat')
190
+ expect(prompt.trim().endsWith('检查构建失败原因并修复')).toBe(true)
191
+ })
192
+
193
+ it('不包含 payload 全文(不把整段事件体塞进 log)', () => {
194
+ const prompt = renderWebhookPrompt({
195
+ name: 'n',
196
+ provider: 'github',
197
+ prompt: 'p',
198
+ summary,
199
+ })
200
+ expect(prompt).not.toContain('"repository"')
201
+ expect(prompt).not.toContain('head_commit')
202
+ expect(prompt.length).toBeLessThan(1_000)
203
+ })
204
+ })
205
+
206
+ describe('payload 解析', () => {
207
+ it('合法 JSON 返回对象', () => {
208
+ expect(parseWebhookPayload(encoder.encode('{"a":1}'))).toEqual({ a: 1 })
209
+ })
210
+
211
+ it('非法 JSON 返回 null(接收管线据此 400)', () => {
212
+ expect(parseWebhookPayload(encoder.encode('not json'))).toBeNull()
213
+ expect(parseWebhookPayload(new Uint8Array(0))).toBeNull()
214
+ })
215
+ })
@@ -0,0 +1,170 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import {
4
+ computeHmacHex,
5
+ computeTimestampedSignature,
6
+ verifyWebhookSignature,
7
+ } from '../signature.server'
8
+ import { WEBHOOK_REPLAY_WINDOW_MS } from '../types'
9
+
10
+ const SECRET = 'a'.repeat(64)
11
+ const BODY = new TextEncoder().encode('{"action":"opened","repository":{"full_name":"acme/app"}}')
12
+ const NOW = Date.parse('2026-11-28T12:00:00.000Z')
13
+
14
+ function githubHeaders(signature: string): Headers {
15
+ return new Headers({ 'x-hub-signature-256': signature })
16
+ }
17
+
18
+ function timestampedHeaders(input: {
19
+ timestamp: string
20
+ signature: string
21
+ }): Headers {
22
+ return new Headers({
23
+ 'x-allblue-timestamp': input.timestamp,
24
+ 'x-allblue-signature': input.signature,
25
+ })
26
+ }
27
+
28
+ describe('GitHub 方案验签', () => {
29
+ it('正确签名(sha256= 前缀)通过', () => {
30
+ const signature = `sha256=${computeHmacHex(SECRET, BODY)}`
31
+ expect(verifyWebhookSignature({ secret: SECRET, body: BODY, headers: githubHeaders(signature), now: NOW }))
32
+ .toEqual({ ok: true, scheme: 'github' })
33
+ })
34
+
35
+ it('裸 hex 与大小写 hex 同样通过(兼容上游实现差异)', () => {
36
+ const hex = computeHmacHex(SECRET, BODY)
37
+ expect(
38
+ verifyWebhookSignature({ secret: SECRET, body: BODY, headers: githubHeaders(hex), now: NOW }).ok,
39
+ ).toBe(true)
40
+ expect(
41
+ verifyWebhookSignature({
42
+ secret: SECRET,
43
+ body: BODY,
44
+ headers: githubHeaders(`sha256=${hex.toUpperCase()}`),
45
+ now: NOW,
46
+ }).ok,
47
+ ).toBe(true)
48
+ })
49
+
50
+ it('错误密钥被拒', () => {
51
+ const signature = `sha256=${computeHmacHex('b'.repeat(64), BODY)}`
52
+ expect(verifyWebhookSignature({ secret: SECRET, body: BODY, headers: githubHeaders(signature), now: NOW }))
53
+ .toEqual({ ok: false, reason: 'invalid_signature' })
54
+ })
55
+
56
+ it('body 被篡改被拒(同一签名不覆盖改后 body)', () => {
57
+ const signature = `sha256=${computeHmacHex(SECRET, BODY)}`
58
+ const tampered = new TextEncoder().encode('{"action":"closed"}')
59
+ expect(
60
+ verifyWebhookSignature({ secret: SECRET, body: tampered, headers: githubHeaders(signature), now: NOW }),
61
+ ).toEqual({ ok: false, reason: 'invalid_signature' })
62
+ })
63
+
64
+ it('长度不足/非 hex 的签名被拒', () => {
65
+ expect(
66
+ verifyWebhookSignature({ secret: SECRET, body: BODY, headers: githubHeaders('sha256=abc'), now: NOW }),
67
+ ).toEqual({ ok: false, reason: 'invalid_signature' })
68
+ expect(
69
+ verifyWebhookSignature({
70
+ secret: SECRET,
71
+ body: BODY,
72
+ headers: githubHeaders(`sha256=${'z'.repeat(64)}`),
73
+ now: NOW,
74
+ }),
75
+ ).toEqual({ ok: false, reason: 'invalid_signature' })
76
+ })
77
+ })
78
+
79
+ describe('带时间戳方案验签', () => {
80
+ const timestamp = String(Math.floor(NOW / 1000))
81
+
82
+ it('窗口内正确签名通过(v1= 前缀)', () => {
83
+ const signature = `v1=${computeTimestampedSignature(SECRET, timestamp, BODY)}`
84
+ expect(
85
+ verifyWebhookSignature({
86
+ secret: SECRET,
87
+ body: BODY,
88
+ headers: timestampedHeaders({ timestamp, signature }),
89
+ now: NOW,
90
+ }),
91
+ ).toEqual({ ok: true, scheme: 'timestamped' })
92
+ })
93
+
94
+ it('窗口外被拒(重放窗口生效)', () => {
95
+ const signature = `v1=${computeTimestampedSignature(SECRET, timestamp, BODY)}`
96
+ expect(
97
+ verifyWebhookSignature({
98
+ secret: SECRET,
99
+ body: BODY,
100
+ headers: timestampedHeaders({ timestamp, signature }),
101
+ now: NOW + WEBHOOK_REPLAY_WINDOW_MS + 1_000,
102
+ }),
103
+ ).toEqual({ ok: false, reason: 'stale_timestamp' })
104
+ })
105
+
106
+ it('窗口边界内仍通过(±窗口容差)', () => {
107
+ const signature = `v1=${computeTimestampedSignature(SECRET, timestamp, BODY)}`
108
+ expect(
109
+ verifyWebhookSignature({
110
+ secret: SECRET,
111
+ body: BODY,
112
+ headers: timestampedHeaders({ timestamp, signature }),
113
+ now: NOW - (WEBHOOK_REPLAY_WINDOW_MS - 1_000),
114
+ }).ok,
115
+ ).toBe(true)
116
+ })
117
+
118
+ it('时间戳被改到另一窗口内但签名未同步 → 被拒', () => {
119
+ const signature = `v1=${computeTimestampedSignature(SECRET, timestamp, BODY)}`
120
+ const shifted = String(Number(timestamp) + 1)
121
+ expect(
122
+ verifyWebhookSignature({
123
+ secret: SECRET,
124
+ body: BODY,
125
+ headers: timestampedHeaders({ timestamp: shifted, signature }),
126
+ now: NOW,
127
+ }),
128
+ ).toEqual({ ok: false, reason: 'invalid_signature' })
129
+ })
130
+
131
+ it('非数字时间戳 → bad_timestamp', () => {
132
+ const signature = `v1=${computeTimestampedSignature(SECRET, 'abc', BODY)}`
133
+ expect(
134
+ verifyWebhookSignature({
135
+ secret: SECRET,
136
+ body: BODY,
137
+ headers: timestampedHeaders({ timestamp: 'abc', signature }),
138
+ now: NOW,
139
+ }),
140
+ ).toEqual({ ok: false, reason: 'bad_timestamp' })
141
+ })
142
+ })
143
+
144
+ describe('签名头缺失', () => {
145
+ it('完全没有签名头 → missing_signature', () => {
146
+ expect(
147
+ verifyWebhookSignature({ secret: SECRET, body: BODY, headers: new Headers(), now: NOW }),
148
+ ).toEqual({ ok: false, reason: 'missing_signature' })
149
+ })
150
+
151
+ it('只有时间戳没有签名(或反之)→ missing_signature', () => {
152
+ const timestamp = String(Math.floor(NOW / 1000))
153
+ expect(
154
+ verifyWebhookSignature({
155
+ secret: SECRET,
156
+ body: BODY,
157
+ headers: new Headers({ 'x-allblue-timestamp': timestamp }),
158
+ now: NOW,
159
+ }),
160
+ ).toEqual({ ok: false, reason: 'missing_signature' })
161
+ expect(
162
+ verifyWebhookSignature({
163
+ secret: SECRET,
164
+ body: BODY,
165
+ headers: new Headers({ 'x-allblue-signature': `v1=${'0'.repeat(64)}` }),
166
+ now: NOW,
167
+ }),
168
+ ).toEqual({ ok: false, reason: 'missing_signature' })
169
+ })
170
+ })
@@ -0,0 +1,212 @@
1
+ // @vitest-environment node
2
+
3
+ import { beforeAll, beforeEach, afterAll, describe, expect, it } from 'vitest'
4
+ import { prisma } from '@allbluecn/database'
5
+
6
+ import { createWebhookDispatcher } from '../webhook-dispatcher.server'
7
+ import { createWebhookRule, editWebhookRule } from '../webhook.service.server'
8
+ import { createWebhookOutbox } from '../webhook-store.server'
9
+ import { OUTBOX_KIND_SCHEDULE, OUTBOX_KIND_WEBHOOK } from '../../outbox/outbox-store.server'
10
+ import type { ScheduleReceipt, ScheduleSubmitInput } from '../../schedule/schedule-dispatcher.server'
11
+ import type { WebhookEventSummary } from '../types'
12
+
13
+ const hasDb = !!process.env.DATABASE_URL
14
+ const MARKER = `vitest-webhook-dispatch-${process.pid}`
15
+ const USER_A = `${MARKER}-a`
16
+ const THREAD_A = `${MARKER}-thread-a`
17
+ const NOW = Date.parse('2026-11-28T12:00:00.000Z')
18
+
19
+ const SUMMARY: WebhookEventSummary = {
20
+ event: 'push',
21
+ action: null,
22
+ repo: 'acme/app',
23
+ owner: 'acme',
24
+ ref: 'refs/heads/main',
25
+ title: 'fix: build',
26
+ url: 'https://github.com/acme/app/compare/a...b',
27
+ actor: 'octocat',
28
+ }
29
+
30
+ async function cleanup(): Promise<void> {
31
+ if (!hasDb) return
32
+ const userIds = [USER_A]
33
+ await prisma.harnessOutbox.deleteMany({ where: { userId: { in: userIds } } })
34
+ await prisma.harnessWebhookDelivery.deleteMany({ where: { userId: { in: userIds } } })
35
+ await prisma.harnessWebhookRule.deleteMany({ where: { userId: { in: userIds } } })
36
+ await prisma.chatThread.deleteMany({ where: { id: THREAD_A } })
37
+ await prisma.user.deleteMany({ where: { id: { in: userIds } } })
38
+ }
39
+
40
+ beforeAll(async () => {
41
+ if (!hasDb) return
42
+ await cleanup()
43
+ await prisma.user.create({
44
+ data: { id: USER_A, email: `${MARKER}-a@example.com`, username: `${MARKER}-a`, password: 'test' },
45
+ })
46
+ await prisma.chatThread.create({
47
+ data: { id: THREAD_A, userId: USER_A, engine: 'local', localCwd: '/tmp' },
48
+ })
49
+ })
50
+
51
+ afterAll(cleanup)
52
+
53
+ beforeEach(async () => {
54
+ if (!hasDb) return
55
+ await prisma.harnessOutbox.deleteMany({ where: { userId: USER_A } })
56
+ await prisma.harnessWebhookDelivery.deleteMany({ where: { userId: USER_A } })
57
+ await prisma.harnessWebhookRule.deleteMany({ where: { userId: USER_A } })
58
+ })
59
+
60
+ async function seedDelivery(input: { prompt?: string } = {}) {
61
+ const { rule } = await createWebhookRule({
62
+ userId: USER_A,
63
+ threadId: THREAD_A,
64
+ name: 'Build watcher',
65
+ prompt: input.prompt ?? 'inspect the failure',
66
+ repoWhitelist: ['acme/app'],
67
+ executionPlane: 'local',
68
+ })
69
+ const delivery = await prisma.harnessWebhookDelivery.create({
70
+ data: {
71
+ ruleId: rule.id,
72
+ userId: USER_A,
73
+ executionPlane: 'local',
74
+ eventKey: `github:${MARKER}-delivery`,
75
+ eventType: 'push',
76
+ repo: 'acme/app',
77
+ owner: 'acme',
78
+ summary: SUMMARY as unknown as object,
79
+ state: 'pending',
80
+ },
81
+ })
82
+ await prisma.$transaction(async (tx) => {
83
+ await createWebhookOutbox(tx, {
84
+ userId: USER_A,
85
+ executionPlane: 'local',
86
+ deliveryId: delivery.id,
87
+ payload: {
88
+ ruleId: rule.id,
89
+ deliveryId: delivery.id,
90
+ threadId: THREAD_A,
91
+ workspaceId: null,
92
+ name: rule.name,
93
+ provider: rule.provider,
94
+ summary: SUMMARY,
95
+ },
96
+ nextAttemptAt: new Date(NOW - 1_000),
97
+ })
98
+ })
99
+ return { rule, delivery }
100
+ }
101
+
102
+ function fakeSubmit(result?: Partial<ScheduleReceipt>) {
103
+ const calls: ScheduleSubmitInput[] = []
104
+ const submit = async (input: ScheduleSubmitInput): Promise<ScheduleReceipt> => {
105
+ calls.push(input)
106
+ return (result ?? { inputId: input.inputId, status: 'accepted' }) as ScheduleReceipt
107
+ }
108
+ return { submit, calls }
109
+ }
110
+
111
+ describe.skipIf(!hasDb)('webhook 投递 dispatcher', () => {
112
+ it('领取 webhook.delivery → 在该线程发起 root Session → 标记 delivered', async () => {
113
+ const { delivery } = await seedDelivery()
114
+ const { submit, calls } = fakeSubmit()
115
+
116
+ const dispatcher = createWebhookDispatcher({
117
+ userId: USER_A,
118
+ plane: 'local',
119
+ now: () => NOW,
120
+ submit,
121
+ })
122
+ const result = await dispatcher.tick()
123
+ expect(result).toMatchObject({ claimed: 1, delivered: 1 })
124
+
125
+ expect(calls).toHaveLength(1)
126
+ expect(calls[0]).toMatchObject({
127
+ userId: USER_A,
128
+ threadId: THREAD_A,
129
+ inputId: `webhook:${delivery.id}`,
130
+ })
131
+ expect(calls[0].message.split('\n')[0]).toBe('[webhook] github push · Build watcher')
132
+ expect(calls[0].message).toContain('repo: acme/app')
133
+ expect(calls[0].message.trim().endsWith('inspect the failure')).toBe(true)
134
+
135
+ const after = await prisma.harnessWebhookDelivery.findUniqueOrThrow({ where: { id: delivery.id } })
136
+ expect(after.state).toBe('delivered')
137
+ expect(after.deliveredAt).not.toBeNull()
138
+
139
+ const outbox = await prisma.harnessOutbox.findFirstOrThrow({ where: { userId: USER_A } })
140
+ expect(outbox.state).toBe('done')
141
+ })
142
+
143
+ it('重复 tick 不重复投递(delivery 已 delivered 即 skip)', async () => {
144
+ await seedDelivery()
145
+ const { submit, calls } = fakeSubmit()
146
+ const dispatcher = createWebhookDispatcher({ userId: USER_A, plane: 'local', now: () => NOW, submit })
147
+
148
+ await dispatcher.tick()
149
+ const second = await dispatcher.tick()
150
+
151
+ expect(calls).toHaveLength(1)
152
+ expect(second.claimed).toBe(0)
153
+ })
154
+
155
+ it('submit 失败按可重试处理:delivery 回 pending,outbox 留待下次', async () => {
156
+ const { delivery } = await seedDelivery()
157
+ const submit = async (): Promise<ScheduleReceipt> => {
158
+ throw new Error('host_unavailable')
159
+ }
160
+ const dispatcher = createWebhookDispatcher({ userId: USER_A, plane: 'local', now: () => NOW, submit })
161
+ const result = await dispatcher.tick()
162
+ expect(result.retried).toBe(1)
163
+
164
+ const after = await prisma.harnessWebhookDelivery.findUniqueOrThrow({ where: { id: delivery.id } })
165
+ expect(after.state).toBe('pending')
166
+ expect(after.lastError).toBe('host_unavailable')
167
+
168
+ const outbox = await prisma.harnessOutbox.findFirstOrThrow({ where: { userId: USER_A } })
169
+ expect(outbox.state).toBe('pending')
170
+ expect(outbox.attempt).toBe(1)
171
+ })
172
+
173
+ it('规则暂停后按 skipped 收尾且不调 submit', async () => {
174
+ const { rule, delivery } = await seedDelivery()
175
+ await editWebhookRule({ userId: USER_A, id: rule.id, revision: rule.revision, status: 'paused' })
176
+ const { submit, calls } = fakeSubmit()
177
+
178
+ const dispatcher = createWebhookDispatcher({ userId: USER_A, plane: 'local', now: () => NOW, submit })
179
+ const result = await dispatcher.tick()
180
+ expect(calls).toHaveLength(0)
181
+ expect(result.skipped).toBe(1)
182
+
183
+ const after = await prisma.harnessWebhookDelivery.findUniqueOrThrow({ where: { id: delivery.id } })
184
+ expect(after.state).toBe('skipped')
185
+ expect(after.lastError).toBe('rule_paused')
186
+ })
187
+
188
+ it('不领取 schedule.wake 行(kind 隔离)', async () => {
189
+ await prisma.harnessOutbox.create({
190
+ data: {
191
+ userId: USER_A,
192
+ executionPlane: 'local',
193
+ kind: OUTBOX_KIND_SCHEDULE,
194
+ inputId: `schedule:${MARKER}-occ`,
195
+ idempotencyKey: `schedule:${MARKER}-occ`,
196
+ payload: { scheduleId: 'x', occurrenceId: 'occ', threadId: THREAD_A },
197
+ nextAttemptAt: new Date(NOW - 1_000),
198
+ },
199
+ })
200
+ const { submit, calls } = fakeSubmit()
201
+ const dispatcher = createWebhookDispatcher({ userId: USER_A, plane: 'local', now: () => NOW, submit })
202
+ const result = await dispatcher.tick()
203
+ expect(result.claimed).toBe(0)
204
+ expect(calls).toHaveLength(0)
205
+
206
+ const scheduleRow = await prisma.harnessOutbox.findFirstOrThrow({
207
+ where: { userId: USER_A, kind: OUTBOX_KIND_SCHEDULE },
208
+ })
209
+ expect(scheduleRow.state).toBe('pending')
210
+ expect(await prisma.harnessOutbox.count({ where: { userId: USER_A, kind: OUTBOX_KIND_WEBHOOK } })).toBe(0)
211
+ })
212
+ })