@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.
- package/package.json +5 -5
- package/public/dev-gallery.html +19 -0
- package/src/__tests__/bench/baselines/format-timestamp.json +44 -0
- package/src/__typeprobe__.d.ts +4 -0
- package/src/components/harness/extension-panel/panels/terminal/__tests__/terminal-instance.test.tsx +93 -4
- package/src/components/harness/extension-panel/panels/terminal/sse-transport.ts +28 -5
- package/src/components/harness/extension-panel/panels/terminal/terminal-instance.tsx +53 -10
- package/src/components/harness/extension-panel/panels/terminal/transport.ts +10 -3
- package/src/components/harness/extension-panel/panels/terminal/ws-transport.ts +13 -2
- package/src/components/settings/harness/connectors-card.tsx +5 -0
- package/src/components/story/detail/story-detail-toolbar/associated-attachments-panel.tsx +2 -1
- package/src/dev/gallery-entry.tsx +38 -0
- package/src/dev/gallery.tsx +610 -0
- package/src/lib/changelog/sdk-versions.ts +4 -4
- package/src/lib/session.ts +10 -0
- package/src/paraglide/README.md +1 -1
- package/src/paraglide/messages/_index.d.ts +9 -0
- package/src/paraglide/messages/_index.js +9 -0
- package/src/paraglide/messages/capabilities_webhook.d.ts +16 -0
- package/src/paraglide/messages/capabilities_webhook.js +29 -0
- package/src/paraglide/messages/capabilities_workflow.d.ts +16 -0
- package/src/paraglide/messages/capabilities_workflow.js +29 -0
- package/src/paraglide/messages/harness_panel_terminal_exitedrecycled1.d.ts +17 -0
- package/src/paraglide/messages/harness_panel_terminal_exitedrecycled1.js +30 -0
- package/src/paraglide/messages/harness_panel_terminal_restarted.d.ts +16 -0
- package/src/paraglide/messages/harness_panel_terminal_restarted.js +29 -0
- package/src/paraglide/messages/settings_harness_connectors_needsauth1.d.ts +17 -0
- package/src/paraglide/messages/settings_harness_connectors_needsauth1.js +30 -0
- package/src/paraglide/messages/settings_harness_ralphenabled1.d.ts +17 -0
- package/src/paraglide/messages/settings_harness_ralphenabled1.js +30 -0
- package/src/paraglide/messages/settings_harness_ralphenabled_description1.d.ts +17 -0
- package/src/paraglide/messages/settings_harness_ralphenabled_description1.js +30 -0
- package/src/paraglide/messages/settings_harness_ralphmaxrounds2.d.ts +17 -0
- package/src/paraglide/messages/settings_harness_ralphmaxrounds2.js +30 -0
- package/src/paraglide/messages/settings_harness_ralphmaxrounds_description2.d.ts +17 -0
- package/src/paraglide/messages/settings_harness_ralphmaxrounds_description2.js +30 -0
- package/src/routeTree.gen.ts +21 -0
- package/src/routes/api/auth/desktop-callback.ts +9 -0
- package/src/routes/api/chat.ts +8 -1
- package/src/routes/api/harness/browser/proxy.ts +41 -12
- package/src/routes/api/harness/terminal/$.ts +32 -13
- package/src/routes/api/harness/terminal/__tests__/route.test.ts +41 -0
- package/src/routes/api/harness/webhook/$token.ts +23 -0
- package/src/routes/api/sync/__tests__/bootstrap.test.ts +32 -1
- package/src/routes/api/sync/bootstrap.ts +11 -0
- package/src/server/ai-gateway/adapter.ts +7 -3
- package/src/server/ai-gateway/connectivity-check.ts +3 -2
- package/src/server/ai-gateway/durability/__tests__/sse-resume-frames.test.ts +123 -0
- package/src/server/ai-gateway/embedding.ts +3 -2
- package/src/server/ai-gateway/model-fetch.ts +3 -2
- package/src/server/ai-gateway/sandbox/__tests__/provider.test.ts +12 -1
- package/src/server/ai-gateway/sandbox/policy.ts +27 -1
- package/src/server/ai-gateway/sandbox/provider.ts +10 -0
- package/src/server/ai-gateway/tools/definitions.ts +1 -1
- package/src/server/ai-gateway/tools/server.ts +4 -2
- package/src/server/harness/__tests__/agent-terminal-sandbox.test.ts +23 -4
- package/src/server/harness/__tests__/agent-terminal.server.test.ts +118 -2
- package/src/server/harness/__tests__/credentials.server.test.ts +25 -2
- package/src/server/harness/__tests__/host-schedule-worker.test.ts +43 -0
- package/src/server/harness/__tests__/runtime-without-providers.test.ts +11 -0
- package/src/server/harness/__tests__/sticky-route.test.ts +86 -0
- package/src/server/harness/__tests__/terminal-foreground.server.test.ts +80 -0
- package/src/server/harness/__tests__/terminal-manager.server.test.ts +75 -1
- package/src/server/harness/__tests__/tool-entitlements.test.ts +6 -2
- package/src/server/harness/agent-terminal.server.ts +25 -4
- package/src/server/harness/agents/__tests__/agent-control.test.ts +1 -0
- package/src/server/harness/agents/run-view.server.ts +55 -2
- package/src/server/harness/capabilities/__tests__/__snapshots__/matrix.test.ts.snap +92 -0
- package/src/server/harness/capabilities/__tests__/execution-plane-denials.test.ts +3 -1
- package/src/server/harness/capabilities/__tests__/p3-matrix.test.ts +3 -3
- package/src/server/harness/capabilities/__tests__/p5-matrix.test.ts +293 -0
- package/src/server/harness/capabilities/__tests__/validate.test.ts +8 -2
- package/src/server/harness/capabilities/execution-plane-denials.ts +9 -3
- package/src/server/harness/capabilities/manifests/agent-terminal.ts +3 -2
- package/src/server/harness/capabilities/manifests/webhook.ts +45 -0
- package/src/server/harness/capabilities/manifests/workflow.ts +40 -0
- package/src/server/harness/capabilities/registry.ts +4 -0
- package/src/server/harness/connectors/__tests__/connector-accounts.test.ts +22 -1
- package/src/server/harness/connectors/connector-accounts.server.ts +7 -0
- package/src/server/harness/credentials.server.ts +3 -1
- package/src/server/harness/define.server.ts +11 -0
- package/src/server/harness/mcp/mcp-config.server.ts +3 -1
- package/src/server/harness/outbox/outbox-dispatcher.server.ts +9 -0
- package/src/server/harness/outbox/outbox-store.server.ts +7 -0
- package/src/server/harness/persistence/__tests__/log-store.server.test.ts +4 -1
- package/src/server/harness/plugins/__tests__/tool-risk-audit.test.ts +5 -1
- package/src/server/harness/plugins/builtin/agent-terminal.plugin.ts +12 -2
- package/src/server/harness/providers/contracts.ts +16 -0
- package/src/server/harness/schedule/schedule-dispatcher.server.ts +3 -0
- package/src/server/harness/search/__tests__/indexer.test.ts +4 -1
- package/src/server/harness/search/__tests__/lifecycle.test.ts +4 -1
- package/src/server/harness/search/__tests__/search.test.ts +4 -1
- package/src/server/harness/sticky-route.server.ts +72 -0
- package/src/server/harness/terminal-foreground.server.ts +90 -0
- package/src/server/harness/terminal-manager.server.ts +78 -3
- package/src/server/harness/tool-entitlements.server.ts +5 -0
- package/src/server/harness/webhook/__tests__/body.test.ts +73 -0
- package/src/server/harness/webhook/__tests__/payload.test.ts +215 -0
- package/src/server/harness/webhook/__tests__/signature.test.ts +170 -0
- package/src/server/harness/webhook/__tests__/webhook-dispatcher.test.ts +212 -0
- package/src/server/harness/webhook/__tests__/webhook.plugin.test.ts +195 -0
- package/src/server/harness/webhook/__tests__/webhook.service.test.ts +354 -0
- package/src/server/harness/webhook/body.server.ts +56 -0
- package/src/server/harness/webhook/payload.server.ts +169 -0
- package/src/server/harness/webhook/signature.server.ts +118 -0
- package/src/server/harness/webhook/types.ts +57 -0
- package/src/server/harness/webhook/webhook-dispatcher.server.ts +495 -0
- package/src/server/harness/webhook/webhook-store.server.ts +115 -0
- package/src/server/harness/webhook/webhook.plugin.ts +273 -0
- package/src/server/harness/webhook/webhook.service.server.ts +577 -0
- package/src/server/harness/worker/__tests__/worker-http.test.ts +8 -1
- package/src/server/harness/worker/worker-health.server.ts +4 -1
- package/src/server/harness/worker/worker-runtime.server.ts +43 -1
- package/src/server/harness/workflow/__tests__/engine.test.ts +195 -0
- package/src/server/harness/workflow/__tests__/settings.test.ts +125 -0
- package/src/server/harness/workflow/__tests__/validate.test.ts +151 -0
- package/src/server/harness/workflow/engine.server.ts +155 -0
- package/src/server/harness/workflow/settings.ts +84 -0
- package/src/server/harness/workflow/store.server.ts +147 -0
- package/src/server/harness/workflow/types.ts +80 -0
- package/src/server/harness/workflow/validate.ts +130 -0
- package/src/server/harness/workflow/workflow.plugin.ts +261 -0
- package/src/server/knowledge/search-scope.ts +8 -1
- package/src/server/middlewares/security-headers.ts +1 -0
- package/src/server/serverFns/__tests__/link-preview.test.ts +2 -2
- package/src/server/serverFns/collab.ts +4 -0
- package/src/server/serverFns/design/versions.ts +6 -0
- package/src/server/serverFns/harness/__tests__/fork-thread.test.ts +14 -1
- package/src/server/serverFns/harness/fork-thread.ts +17 -0
- package/src/server/serverFns/story/link-preview.ts +3 -2
- package/src/server-entry.ts +13 -1
- package/src/start.ts +15 -1
- package/vite.shared.ts +0 -13
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// @vitest-environment node
|
|
2
|
+
|
|
3
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
4
|
+
|
|
5
|
+
const service = vi.hoisted(() => ({
|
|
6
|
+
createWebhookRule: vi.fn(),
|
|
7
|
+
listWebhookRules: vi.fn(),
|
|
8
|
+
getWebhookRule: vi.fn(),
|
|
9
|
+
editWebhookRule: vi.fn(),
|
|
10
|
+
deleteWebhookRule: vi.fn(),
|
|
11
|
+
}))
|
|
12
|
+
|
|
13
|
+
vi.mock('../webhook.service.server', async (importOriginal) => {
|
|
14
|
+
const actual = await importOriginal<typeof import('../webhook.service.server')>()
|
|
15
|
+
return { ...actual, ...service }
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
import { createWebhookPlugin, webhookTools } from '../webhook.plugin'
|
|
19
|
+
import { WebhookServiceError } from '../webhook.service.server'
|
|
20
|
+
import { webhookManifest } from '../../capabilities/manifests/webhook'
|
|
21
|
+
|
|
22
|
+
const scheduler = { id: 'scheduler', available: true }
|
|
23
|
+
|
|
24
|
+
type WebhookTool = (typeof webhookTools)[number]
|
|
25
|
+
type ExecutableWebhookTool = WebhookTool & { execute: NonNullable<WebhookTool['execute']> }
|
|
26
|
+
|
|
27
|
+
function tool(name: string): ExecutableWebhookTool {
|
|
28
|
+
const found = webhookTools.find((candidate) => candidate.name === name)
|
|
29
|
+
if (!found?.execute) throw new Error(`Missing executable tool ${name}`)
|
|
30
|
+
return found as ExecutableWebhookTool
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function context(overrides: Record<string, unknown> = {}) {
|
|
34
|
+
return {
|
|
35
|
+
context: {
|
|
36
|
+
userId: 'forged-user',
|
|
37
|
+
threadId: 'forged-thread',
|
|
38
|
+
run: { userId: 'forged-run-user', threadId: 'thread-1', user: { id: 'user-1' } },
|
|
39
|
+
...overrides,
|
|
40
|
+
},
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const SECRET_CIPHER = 'encrypted-secret-that-must-never-leak'
|
|
45
|
+
|
|
46
|
+
const ruleRow = {
|
|
47
|
+
id: 'webhook-1',
|
|
48
|
+
userId: 'user-1',
|
|
49
|
+
token: 'tok_abcdefghijklmnopqrstuvwxyz012345',
|
|
50
|
+
name: 'Build watcher',
|
|
51
|
+
provider: 'github',
|
|
52
|
+
threadId: 'thread-1',
|
|
53
|
+
workspaceId: null,
|
|
54
|
+
prompt: 'secret prompt that must not leave the server',
|
|
55
|
+
secretCipher: SECRET_CIPHER,
|
|
56
|
+
secretHint: 'ab12',
|
|
57
|
+
events: ['push'],
|
|
58
|
+
repoWhitelist: ['acme/app'],
|
|
59
|
+
ownerWhitelist: null,
|
|
60
|
+
status: 'active',
|
|
61
|
+
executionPlane: 'local',
|
|
62
|
+
lastDeliveryAt: null,
|
|
63
|
+
lastError: null,
|
|
64
|
+
revision: 0,
|
|
65
|
+
createdAt: new Date('2026-11-28T00:00:00.000Z'),
|
|
66
|
+
updatedAt: new Date('2026-11-28T00:00:00.000Z'),
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
beforeEach(() => {
|
|
70
|
+
vi.clearAllMocks()
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
describe('webhook 工具登记与 schema', () => {
|
|
74
|
+
it('五工具名与 manifest 严格一致', () => {
|
|
75
|
+
expect(webhookTools.map((entry) => entry.name)).toEqual([
|
|
76
|
+
'webhook_create',
|
|
77
|
+
'webhook_list',
|
|
78
|
+
'webhook_view',
|
|
79
|
+
'webhook_edit',
|
|
80
|
+
'webhook_delete',
|
|
81
|
+
])
|
|
82
|
+
expect(webhookManifest.tools.map((entry) => entry.name)).toEqual(
|
|
83
|
+
webhookTools.map((entry) => entry.name),
|
|
84
|
+
)
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
it('缺少 scheduler Provider 时整体缺席(无半成品接口)', () => {
|
|
88
|
+
expect(createWebhookPlugin(null)).toBeNull()
|
|
89
|
+
expect(createWebhookPlugin({ available: false })).toBeNull()
|
|
90
|
+
expect(createWebhookPlugin(scheduler)?.name).toBe('allblue/webhook')
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
it('create 必须至少提供一个白名单(fail-closed)', () => {
|
|
94
|
+
const schema = tool('webhook_create').inputSchema
|
|
95
|
+
expect(schema.safeParse({ name: 'n', prompt: 'p' }).success).toBe(false)
|
|
96
|
+
expect(schema.safeParse({ name: 'n', prompt: 'p', repo_whitelist: [] }).success).toBe(false)
|
|
97
|
+
expect(schema.safeParse({ name: 'n', prompt: 'p', owner_whitelist: [] }).success).toBe(false)
|
|
98
|
+
expect(schema.safeParse({ name: 'n', prompt: 'p', repo_whitelist: ['acme/app'] }).success).toBe(true)
|
|
99
|
+
expect(schema.safeParse({ name: 'n', prompt: 'p', owner_whitelist: ['acme'] }).success).toBe(true)
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
it('create 拒绝非法 repo 格式、空 prompt 与超长名', () => {
|
|
103
|
+
const schema = tool('webhook_create').inputSchema
|
|
104
|
+
expect(schema.safeParse({ name: 'n', prompt: 'p', repo_whitelist: ['no-slash'] }).success).toBe(false)
|
|
105
|
+
expect(schema.safeParse({ name: 'n', prompt: ' ', repo_whitelist: ['a/b'] }).success).toBe(false)
|
|
106
|
+
expect(schema.safeParse({ name: 'x'.repeat(121), prompt: 'p', repo_whitelist: ['a/b'] }).success).toBe(false)
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
it('edit 必须至少改一个字段', () => {
|
|
110
|
+
const schema = tool('webhook_edit').inputSchema
|
|
111
|
+
expect(schema.safeParse({ id: 'webhook-1' }).success).toBe(false)
|
|
112
|
+
expect(schema.safeParse({ id: 'webhook-1', status: 'paused' }).success).toBe(true)
|
|
113
|
+
expect(schema.safeParse({ id: 'webhook-1', name: 'renamed' }).success).toBe(true)
|
|
114
|
+
})
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
describe('webhook 工具行为', () => {
|
|
118
|
+
it('create 用受信 run 身份与线程,结果零密钥', async () => {
|
|
119
|
+
service.createWebhookRule.mockResolvedValue({ rule: ruleRow, secret: 'plain-secret-never-returned' })
|
|
120
|
+
|
|
121
|
+
const result = await tool('webhook_create').execute({
|
|
122
|
+
name: 'Build watcher',
|
|
123
|
+
prompt: 'do it',
|
|
124
|
+
repo_whitelist: ['acme/app'],
|
|
125
|
+
events: ['push'],
|
|
126
|
+
}, context())
|
|
127
|
+
|
|
128
|
+
expect(service.createWebhookRule).toHaveBeenCalledWith(expect.objectContaining({
|
|
129
|
+
userId: 'user-1',
|
|
130
|
+
threadId: 'thread-1',
|
|
131
|
+
name: 'Build watcher',
|
|
132
|
+
prompt: 'do it',
|
|
133
|
+
repoWhitelist: ['acme/app'],
|
|
134
|
+
events: ['push'],
|
|
135
|
+
executionPlane: 'local',
|
|
136
|
+
}))
|
|
137
|
+
|
|
138
|
+
const serialized = JSON.stringify(result)
|
|
139
|
+
expect(serialized).not.toContain(SECRET_CIPHER)
|
|
140
|
+
expect(serialized).not.toContain('plain-secret-never-returned')
|
|
141
|
+
expect(serialized).not.toContain('secret prompt that must not leave the server')
|
|
142
|
+
expect(result).toMatchObject({
|
|
143
|
+
id: 'webhook-1',
|
|
144
|
+
path: '/api/harness/webhook/tok_abcdefghijklmnopqrstuvwxyz012345',
|
|
145
|
+
secretHint: 'ab12',
|
|
146
|
+
hasSecret: true,
|
|
147
|
+
})
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
it('同步而来的规则在工具结果中标记 hasSecret=false(引导重新录入)', async () => {
|
|
151
|
+
service.listWebhookRules.mockResolvedValue([{ ...ruleRow, secretCipher: null }])
|
|
152
|
+
const result = await tool('webhook_list').execute({}, context())
|
|
153
|
+
expect(result).toEqual({
|
|
154
|
+
webhooks: [expect.objectContaining({ id: 'webhook-1', hasSecret: false, secretHint: 'ab12' })],
|
|
155
|
+
})
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
it('list 只返回当前线程的规则投影', async () => {
|
|
159
|
+
service.listWebhookRules.mockResolvedValue([ruleRow])
|
|
160
|
+
const result = await tool('webhook_list').execute({}, context())
|
|
161
|
+
expect(service.listWebhookRules).toHaveBeenCalledWith({ userId: 'user-1', threadId: 'thread-1' })
|
|
162
|
+
expect(result).toEqual({ webhooks: [expect.objectContaining({ id: 'webhook-1' })] })
|
|
163
|
+
expect(JSON.stringify(result)).not.toContain(SECRET_CIPHER)
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
it('view 跨线程规则按 not_found 拒绝', async () => {
|
|
167
|
+
service.getWebhookRule.mockResolvedValue({ ...ruleRow, threadId: 'other-thread' })
|
|
168
|
+
const result = await tool('webhook_view').execute({ id: 'webhook-1' }, context())
|
|
169
|
+
expect(result).toEqual({
|
|
170
|
+
code: 'webhook_not_found',
|
|
171
|
+
message: 'Webhook rule was not found for this thread',
|
|
172
|
+
})
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
it('service 抛出的领域错误映射为 {code,message} 而非 500', async () => {
|
|
176
|
+
service.getWebhookRule.mockResolvedValue(ruleRow)
|
|
177
|
+
service.editWebhookRule.mockRejectedValue(
|
|
178
|
+
new WebhookServiceError('webhook_conflict', 'Webhook rule revision conflict'),
|
|
179
|
+
)
|
|
180
|
+
const result = await tool('webhook_edit').execute({ id: 'webhook-1', name: 'renamed' }, context())
|
|
181
|
+
expect(result).toEqual({ code: 'webhook_conflict', message: 'Webhook rule revision conflict' })
|
|
182
|
+
})
|
|
183
|
+
|
|
184
|
+
it('delete 先校验归属再删除,返回删除前投影', async () => {
|
|
185
|
+
service.getWebhookRule.mockResolvedValue(ruleRow)
|
|
186
|
+
service.deleteWebhookRule.mockResolvedValue(undefined)
|
|
187
|
+
const result = await tool('webhook_delete').execute({ id: 'webhook-1' }, context())
|
|
188
|
+
expect(service.deleteWebhookRule).toHaveBeenCalledWith({
|
|
189
|
+
userId: 'user-1',
|
|
190
|
+
id: 'webhook-1',
|
|
191
|
+
revision: 0,
|
|
192
|
+
})
|
|
193
|
+
expect(result).toMatchObject({ id: 'webhook-1', status: 'active' })
|
|
194
|
+
})
|
|
195
|
+
})
|
|
@@ -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
|
+
}
|