@critical-path/core 0.25.0 → 0.27.0
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/CHANGELOG.md +52 -0
- package/README.md +25 -0
- package/dist/domain/authorization.d.ts +23 -0
- package/dist/domain/authorization.d.ts.map +1 -0
- package/dist/domain/authorization.js +62 -0
- package/dist/domain/authorization.js.map +1 -0
- package/dist/domain/entities.d.ts +2 -2
- package/dist/domain/entities.d.ts.map +1 -1
- package/dist/domain/entities.js.map +1 -1
- package/dist/domain/errors.d.ts +6 -0
- package/dist/domain/errors.d.ts.map +1 -1
- package/dist/domain/errors.js +9 -0
- package/dist/domain/errors.js.map +1 -1
- package/dist/domain/events.d.ts +5 -0
- package/dist/domain/events.d.ts.map +1 -1
- package/dist/domain/events.js +34 -0
- package/dist/domain/events.js.map +1 -1
- package/dist/domain/index.d.ts +1 -0
- package/dist/domain/index.d.ts.map +1 -1
- package/dist/domain/index.js +1 -0
- package/dist/domain/index.js.map +1 -1
- package/dist/engine/authorization.test.d.ts +2 -0
- package/dist/engine/authorization.test.d.ts.map +1 -0
- package/dist/engine/authorization.test.js +150 -0
- package/dist/engine/authorization.test.js.map +1 -0
- package/dist/engine/index.d.ts +65 -3
- package/dist/engine/index.d.ts.map +1 -1
- package/dist/engine/index.js +404 -104
- package/dist/engine/index.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/schemas/index.d.ts +131 -54
- package/dist/schemas/index.d.ts.map +1 -1
- package/dist/schemas/index.js +18 -1
- package/dist/schemas/index.js.map +1 -1
- package/dist/schemas/schemas.test.js +1 -0
- package/dist/schemas/schemas.test.js.map +1 -1
- package/dist/store/firebase.d.ts +3 -0
- package/dist/store/firebase.d.ts.map +1 -1
- package/dist/store/firebase.js +21 -0
- package/dist/store/firebase.js.map +1 -1
- package/dist/store/firebase.test.js +17 -0
- package/dist/store/firebase.test.js.map +1 -1
- package/dist/store/index.d.ts +6 -0
- package/dist/store/index.d.ts.map +1 -1
- package/dist/store/index.js +14 -0
- package/dist/store/index.js.map +1 -1
- package/dist/store/sqlite.d.ts +4 -0
- package/dist/store/sqlite.d.ts.map +1 -1
- package/dist/store/sqlite.js +62 -17
- package/dist/store/sqlite.js.map +1 -1
- package/dist/types/index.d.ts +61 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/webhooks/dispatcher.d.ts +80 -0
- package/dist/webhooks/dispatcher.d.ts.map +1 -0
- package/dist/webhooks/dispatcher.js +133 -0
- package/dist/webhooks/dispatcher.js.map +1 -0
- package/dist/webhooks/index.d.ts +3 -0
- package/dist/webhooks/index.d.ts.map +1 -0
- package/dist/webhooks/index.js +3 -0
- package/dist/webhooks/index.js.map +1 -0
- package/dist/webhooks/signature.d.ts +28 -0
- package/dist/webhooks/signature.d.ts.map +1 -0
- package/dist/webhooks/signature.js +42 -0
- package/dist/webhooks/signature.js.map +1 -0
- package/dist/webhooks/webhooks.test.d.ts +2 -0
- package/dist/webhooks/webhooks.test.d.ts.map +1 -0
- package/dist/webhooks/webhooks.test.js +153 -0
- package/dist/webhooks/webhooks.test.js.map +1 -0
- package/package.json +1 -1
- package/src/domain/authorization.ts +82 -0
- package/src/domain/entities.ts +2 -1
- package/src/domain/errors.ts +10 -0
- package/src/domain/events.ts +42 -3
- package/src/domain/index.ts +1 -0
- package/src/engine/authorization.test.ts +191 -0
- package/src/engine/index.ts +419 -108
- package/src/index.ts +1 -0
- package/src/schemas/index.ts +22 -1
- package/src/schemas/schemas.test.ts +9 -5
- package/src/store/firebase.test.ts +20 -0
- package/src/store/firebase.ts +22 -0
- package/src/store/index.ts +19 -0
- package/src/store/sqlite.ts +74 -13
- package/src/types/index.ts +81 -29
- package/src/webhooks/dispatcher.ts +190 -0
- package/src/webhooks/index.ts +2 -0
- package/src/webhooks/signature.ts +57 -0
- package/src/webhooks/webhooks.test.ts +200 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import type { Webhook } from '../types/index.js';
|
|
2
|
+
import type { DomainEvent } from '../domain/events.js';
|
|
3
|
+
import { signWebhookPayload } from './signature.js';
|
|
4
|
+
|
|
5
|
+
/** One attempt to deliver one event to one webhook. Serializable, so durable queues can store it. */
|
|
6
|
+
export interface WebhookDeliveryJob {
|
|
7
|
+
/** Stable per event and webhook (`<eventId>:<webhookId>`); sent as `X-CriticalPath-Delivery`. */
|
|
8
|
+
id: string;
|
|
9
|
+
webhookId: string;
|
|
10
|
+
url: string;
|
|
11
|
+
secret?: string;
|
|
12
|
+
event: string;
|
|
13
|
+
/** JSON body, signed as-is. */
|
|
14
|
+
body: string;
|
|
15
|
+
/** 1-based attempt number. */
|
|
16
|
+
attempt: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Schedules delivery jobs. The default `InProcessWebhookQueue` keeps jobs in memory (lost on
|
|
21
|
+
* restart). A durable queue persists `job` and, when `delayMs` has passed, calls
|
|
22
|
+
* `engine.webhooks.deliver(job)` from a worker.
|
|
23
|
+
*/
|
|
24
|
+
export interface WebhookDeliveryQueue {
|
|
25
|
+
enqueue(job: WebhookDeliveryJob, delayMs: number): void | Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface WebhookDeliveryOptions {
|
|
29
|
+
/** Custom queue (e.g. backed by a database or job runner). Default: in-process timers. */
|
|
30
|
+
queue?: WebhookDeliveryQueue;
|
|
31
|
+
/** Fetch implementation. Default: global `fetch`. */
|
|
32
|
+
fetch?: typeof fetch;
|
|
33
|
+
/** Per-attempt timeout. Default 10 000 ms. */
|
|
34
|
+
timeoutMs?: number;
|
|
35
|
+
/** Attempts before giving up. Default 5. */
|
|
36
|
+
maxAttempts?: number;
|
|
37
|
+
/** First retry delay; doubles each attempt. Default 1 000 ms. */
|
|
38
|
+
retryBaseDelayMs?: number;
|
|
39
|
+
/**
|
|
40
|
+
* Allow webhook URLs that point at localhost or private network addresses. Default `false`,
|
|
41
|
+
* which blocks literal private hosts to reduce SSRF risk (DNS-based tricks are not detected).
|
|
42
|
+
*/
|
|
43
|
+
allowPrivateUrls?: boolean;
|
|
44
|
+
onDelivered?: (job: WebhookDeliveryJob, status: number) => void;
|
|
45
|
+
/** Called after the final failed attempt. Default: `console.warn`. */
|
|
46
|
+
onDeliveryFailed?: (job: WebhookDeliveryJob, error: unknown) => void;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface WebhookSource {
|
|
50
|
+
listWebhooks(): Promise<Webhook[]>;
|
|
51
|
+
/** The tenant an event belongs to; only webhooks with the same `tenantId` receive it. */
|
|
52
|
+
resolveTenant(event: DomainEvent): Promise<string | undefined>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Default queue: runs jobs on timers in this process. Timers do not keep the process alive. */
|
|
56
|
+
export class InProcessWebhookQueue implements WebhookDeliveryQueue {
|
|
57
|
+
private outstanding = 0;
|
|
58
|
+
private waiters: Array<() => void> = [];
|
|
59
|
+
|
|
60
|
+
constructor(private readonly run: (job: WebhookDeliveryJob) => Promise<void>) {}
|
|
61
|
+
|
|
62
|
+
enqueue(job: WebhookDeliveryJob, delayMs: number): void {
|
|
63
|
+
this.outstanding++;
|
|
64
|
+
const timer = setTimeout(async () => {
|
|
65
|
+
try {
|
|
66
|
+
await this.run(job);
|
|
67
|
+
} finally {
|
|
68
|
+
this.outstanding--;
|
|
69
|
+
if (this.outstanding === 0) this.waiters.splice(0).forEach((resolve) => resolve());
|
|
70
|
+
}
|
|
71
|
+
}, delayMs);
|
|
72
|
+
(timer as { unref?: () => void }).unref?.();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Resolves when no deliveries (including scheduled retries) are pending. */
|
|
76
|
+
idle(): Promise<void> {
|
|
77
|
+
return this.outstanding === 0 ? Promise.resolve() : new Promise((resolve) => this.waiters.push(resolve));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const PRIVATE_HOST = /^(localhost|.*\.localhost|.*\.internal|127\.\d+\.\d+\.\d+|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|169\.254\.\d+\.\d+|0\.0\.0\.0|\[::1?\]|\[f[cd][0-9a-f]*:.*\]|\[fe80:.*\])$/i;
|
|
82
|
+
|
|
83
|
+
/** Throws if `url` is not an acceptable webhook target. */
|
|
84
|
+
export function assertWebhookUrl(url: string, allowPrivateUrls = false): void {
|
|
85
|
+
let parsed: URL;
|
|
86
|
+
try {
|
|
87
|
+
parsed = new URL(url);
|
|
88
|
+
} catch {
|
|
89
|
+
throw new Error(`Invalid webhook URL "${url}".`);
|
|
90
|
+
}
|
|
91
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
|
92
|
+
throw new Error('Webhook URLs must use http or https.');
|
|
93
|
+
}
|
|
94
|
+
if (!allowPrivateUrls && PRIVATE_HOST.test(parsed.hostname)) {
|
|
95
|
+
throw new Error(`Webhook URL host "${parsed.hostname}" is a private or local address. Set webhookDelivery.allowPrivateUrls to allow it.`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Turns domain events into signed webhook deliveries with timeouts and exponential-backoff retries.
|
|
101
|
+
* Subscribed to the engine's event bus, so every published event is deliverable.
|
|
102
|
+
*/
|
|
103
|
+
export class WebhookDispatcher {
|
|
104
|
+
private readonly queue: WebhookDeliveryQueue;
|
|
105
|
+
private readonly fetchImpl: typeof fetch;
|
|
106
|
+
private cache?: Promise<Webhook[]>;
|
|
107
|
+
|
|
108
|
+
constructor(
|
|
109
|
+
private readonly source: WebhookSource,
|
|
110
|
+
private readonly options: WebhookDeliveryOptions = {}
|
|
111
|
+
) {
|
|
112
|
+
this.queue = options.queue ?? new InProcessWebhookQueue((job) => this.deliver(job));
|
|
113
|
+
this.fetchImpl = options.fetch ?? ((...args) => fetch(...args));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Drops cached webhooks; call after creating, updating or deleting one. */
|
|
117
|
+
invalidate(): void {
|
|
118
|
+
this.cache = undefined;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Resolves when the default in-process queue has nothing pending. */
|
|
122
|
+
idle(): Promise<void> {
|
|
123
|
+
return this.queue instanceof InProcessWebhookQueue ? this.queue.idle() : Promise.resolve();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async handle(event: DomainEvent): Promise<void> {
|
|
127
|
+
this.cache ??= this.source.listWebhooks().catch((err) => {
|
|
128
|
+
this.cache = undefined;
|
|
129
|
+
throw err;
|
|
130
|
+
});
|
|
131
|
+
const subscribed = (await this.cache).filter(
|
|
132
|
+
(w) => w.active && (w.events.includes('*') || w.events.includes(event.name as Webhook['events'][number]))
|
|
133
|
+
);
|
|
134
|
+
if (subscribed.length === 0) return;
|
|
135
|
+
|
|
136
|
+
const tenantId = await this.source.resolveTenant(event);
|
|
137
|
+
const targets = subscribed.filter((w) => w.tenantId === tenantId);
|
|
138
|
+
if (targets.length === 0) return;
|
|
139
|
+
|
|
140
|
+
const body = JSON.stringify({
|
|
141
|
+
id: event.id,
|
|
142
|
+
event: event.name,
|
|
143
|
+
occurredAt: event.occurredAt,
|
|
144
|
+
...(tenantId ? { tenantId } : {}),
|
|
145
|
+
data: event.payload
|
|
146
|
+
});
|
|
147
|
+
for (const webhook of targets) {
|
|
148
|
+
await this.queue.enqueue(
|
|
149
|
+
{ id: `${event.id}:${webhook.id}`, webhookId: webhook.id, url: webhook.url, secret: webhook.secret, event: event.name, body, attempt: 1 },
|
|
150
|
+
0
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Makes one delivery attempt, scheduling a retry (or reporting failure) if it does not succeed. */
|
|
156
|
+
async deliver(job: WebhookDeliveryJob): Promise<void> {
|
|
157
|
+
const maxAttempts = this.options.maxAttempts ?? 5;
|
|
158
|
+
try {
|
|
159
|
+
assertWebhookUrl(job.url, this.options.allowPrivateUrls);
|
|
160
|
+
const timestamp = Math.floor(Date.now() / 1000);
|
|
161
|
+
const headers: Record<string, string> = {
|
|
162
|
+
'Content-Type': 'application/json',
|
|
163
|
+
'User-Agent': 'CriticalPath-Webhooks/1',
|
|
164
|
+
'X-CriticalPath-Event': job.event,
|
|
165
|
+
'X-CriticalPath-Delivery': job.id,
|
|
166
|
+
'X-CriticalPath-Timestamp': String(timestamp)
|
|
167
|
+
};
|
|
168
|
+
if (job.secret) {
|
|
169
|
+
headers['X-CriticalPath-Signature'] = await signWebhookPayload({ secret: job.secret, body: job.body, timestamp });
|
|
170
|
+
}
|
|
171
|
+
const response = await this.fetchImpl(job.url, {
|
|
172
|
+
method: 'POST',
|
|
173
|
+
headers,
|
|
174
|
+
body: job.body,
|
|
175
|
+
signal: AbortSignal.timeout(this.options.timeoutMs ?? 10_000)
|
|
176
|
+
});
|
|
177
|
+
if (!response.ok) throw new Error(`Webhook responded with HTTP ${response.status}`);
|
|
178
|
+
this.options.onDelivered?.(job, response.status);
|
|
179
|
+
} catch (error) {
|
|
180
|
+
if (job.attempt < maxAttempts) {
|
|
181
|
+
const delay = (this.options.retryBaseDelayMs ?? 1_000) * 2 ** (job.attempt - 1);
|
|
182
|
+
await this.queue.enqueue({ ...job, attempt: job.attempt + 1 }, delay);
|
|
183
|
+
} else if (this.options.onDeliveryFailed) {
|
|
184
|
+
this.options.onDeliveryFailed(job, error);
|
|
185
|
+
} else {
|
|
186
|
+
console.warn(`[CriticalPath Webhooks] Giving up on delivery ${job.id} to ${job.url} after ${job.attempt} attempts:`, error);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Webhook signing (HMAC-SHA256 over `"<timestamp>.<body>"`) using Web Crypto, so it works in
|
|
3
|
+
* Node, edge runtimes and browsers alike.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const encoder = new TextEncoder();
|
|
7
|
+
|
|
8
|
+
async function hmacHex(secret: string, message: string): Promise<string> {
|
|
9
|
+
const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, [
|
|
10
|
+
'sign'
|
|
11
|
+
]);
|
|
12
|
+
const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(message));
|
|
13
|
+
return Array.from(new Uint8Array(signature), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function constantTimeEqual(a: string, b: string): boolean {
|
|
17
|
+
if (a.length !== b.length) return false;
|
|
18
|
+
let diff = 0;
|
|
19
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
20
|
+
return diff === 0;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Returns the `X-CriticalPath-Signature` header value: `sha256=<hex>`. */
|
|
24
|
+
export async function signWebhookPayload(input: { secret: string; body: string; timestamp: number }): Promise<string> {
|
|
25
|
+
return `sha256=${await hmacHex(input.secret, `${input.timestamp}.${input.body}`)}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface VerifyWebhookSignatureInput {
|
|
29
|
+
secret: string;
|
|
30
|
+
/** The raw request body, exactly as received. */
|
|
31
|
+
body: string;
|
|
32
|
+
/** `X-CriticalPath-Timestamp` header (Unix seconds). */
|
|
33
|
+
timestamp: string | number;
|
|
34
|
+
/** `X-CriticalPath-Signature` header. */
|
|
35
|
+
signature: string;
|
|
36
|
+
/** Reject deliveries older or newer than this many seconds (replay protection). Default 300. */
|
|
37
|
+
toleranceSeconds?: number;
|
|
38
|
+
/** Current time in milliseconds, for tests. */
|
|
39
|
+
now?: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Verifies a delivery in a webhook receiver. */
|
|
43
|
+
export async function verifyWebhookSignature(input: VerifyWebhookSignatureInput): Promise<boolean> {
|
|
44
|
+
const timestamp = Number(input.timestamp);
|
|
45
|
+
if (!Number.isFinite(timestamp)) return false;
|
|
46
|
+
const tolerance = input.toleranceSeconds ?? 300;
|
|
47
|
+
const nowSeconds = Math.floor((input.now ?? Date.now()) / 1000);
|
|
48
|
+
if (Math.abs(nowSeconds - timestamp) > tolerance) return false;
|
|
49
|
+
const expected = await signWebhookPayload({ secret: input.secret, body: input.body, timestamp });
|
|
50
|
+
return constantTimeEqual(expected, input.signature);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Generates a random signing secret (`whsec_` + 64 hex characters). */
|
|
54
|
+
export function generateWebhookSecret(): string {
|
|
55
|
+
const bytes = crypto.getRandomValues(new Uint8Array(32));
|
|
56
|
+
return `whsec_${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}`;
|
|
57
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
CriticalPathEngine,
|
|
4
|
+
SQLiteStore,
|
|
5
|
+
createRolePolicy,
|
|
6
|
+
ForbiddenError,
|
|
7
|
+
ValidationError,
|
|
8
|
+
signWebhookPayload,
|
|
9
|
+
verifyWebhookSignature,
|
|
10
|
+
type WebhookDeliveryOptions
|
|
11
|
+
} from '../index.js';
|
|
12
|
+
|
|
13
|
+
interface Captured {
|
|
14
|
+
url: string;
|
|
15
|
+
headers: Record<string, string>;
|
|
16
|
+
body: any;
|
|
17
|
+
rawBody: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Engine whose webhook deliveries are captured instead of sent. `respond` decides each status. */
|
|
21
|
+
function engineWithCapture(options: WebhookDeliveryOptions & { respond?: (n: number) => number } = {}, config = {}) {
|
|
22
|
+
const deliveries: Captured[] = [];
|
|
23
|
+
const fetchMock = (async (url: string, init: RequestInit) => {
|
|
24
|
+
const rawBody = init.body as string;
|
|
25
|
+
deliveries.push({ url, headers: init.headers as Record<string, string>, body: JSON.parse(rawBody), rawBody });
|
|
26
|
+
return new Response(null, { status: options.respond?.(deliveries.length) ?? 200 });
|
|
27
|
+
}) as unknown as typeof fetch;
|
|
28
|
+
const engine = new CriticalPathEngine({
|
|
29
|
+
...config,
|
|
30
|
+
webhookDelivery: { retryBaseDelayMs: 1, ...options, fetch: options.fetch ?? fetchMock }
|
|
31
|
+
});
|
|
32
|
+
return { engine, deliveries };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
describe('webhook signatures', () => {
|
|
36
|
+
it('signs and verifies, rejecting tampering and stale timestamps', async () => {
|
|
37
|
+
const timestamp = Math.floor(Date.now() / 1000);
|
|
38
|
+
const signature = await signWebhookPayload({ secret: 's3cret', body: '{"a":1}', timestamp });
|
|
39
|
+
|
|
40
|
+
expect(await verifyWebhookSignature({ secret: 's3cret', body: '{"a":1}', timestamp, signature })).toBe(true);
|
|
41
|
+
expect(await verifyWebhookSignature({ secret: 's3cret', body: '{"a":2}', timestamp, signature })).toBe(false);
|
|
42
|
+
expect(await verifyWebhookSignature({ secret: 'other', body: '{"a":1}', timestamp, signature })).toBe(false);
|
|
43
|
+
expect(
|
|
44
|
+
await verifyWebhookSignature({ secret: 's3cret', body: '{"a":1}', timestamp, signature, now: (timestamp + 3600) * 1000 })
|
|
45
|
+
).toBe(false);
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe('webhook delivery', () => {
|
|
50
|
+
it('delivers signed domain events to subscribed webhooks', async () => {
|
|
51
|
+
const { engine, deliveries } = engineWithCapture();
|
|
52
|
+
const { secret } = await engine.createWebhook({ name: 'CI', url: 'https://hooks.example.com/cp', events: ['task.created'] });
|
|
53
|
+
const project = await engine.createProject({ name: 'Hooks' });
|
|
54
|
+
const task = await engine.createTask({ projectId: project.id, title: 'Ship it' });
|
|
55
|
+
await engine.webhooks.idle();
|
|
56
|
+
|
|
57
|
+
expect(deliveries).toHaveLength(1);
|
|
58
|
+
const [delivery] = deliveries;
|
|
59
|
+
expect(delivery.headers['X-CriticalPath-Event']).toBe('task.created');
|
|
60
|
+
expect(delivery.body.data.task.id).toBe(task.id);
|
|
61
|
+
expect(
|
|
62
|
+
await verifyWebhookSignature({
|
|
63
|
+
secret,
|
|
64
|
+
body: delivery.rawBody,
|
|
65
|
+
timestamp: delivery.headers['X-CriticalPath-Timestamp'],
|
|
66
|
+
signature: delivery.headers['X-CriticalPath-Signature']
|
|
67
|
+
})
|
|
68
|
+
).toBe(true);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('supports wildcard subscriptions and skips inactive webhooks', async () => {
|
|
72
|
+
const { engine, deliveries } = engineWithCapture();
|
|
73
|
+
await engine.createWebhook({ name: 'All', url: 'https://hooks.example.com/all', events: ['*'] });
|
|
74
|
+
const off = await engine.createWebhook({ name: 'Off', url: 'https://hooks.example.com/off', events: ['*'] });
|
|
75
|
+
await engine.updateWebhook(off.webhook.id, { active: false });
|
|
76
|
+
|
|
77
|
+
const project = await engine.createProject({ name: 'Wild' });
|
|
78
|
+
await engine.createTask({ projectId: project.id, title: 'T' });
|
|
79
|
+
await engine.webhooks.idle();
|
|
80
|
+
|
|
81
|
+
expect(deliveries.map((d) => d.body.event)).toEqual(['project.created', 'task.created']);
|
|
82
|
+
expect(deliveries.every((d) => d.url.endsWith('/all'))).toBe(true);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('retries failed deliveries with backoff, then reports the final failure', async () => {
|
|
86
|
+
const failures: string[] = [];
|
|
87
|
+
const { engine, deliveries } = engineWithCapture({
|
|
88
|
+
maxAttempts: 3,
|
|
89
|
+
respond: () => 500,
|
|
90
|
+
onDeliveryFailed: (job) => failures.push(job.id)
|
|
91
|
+
});
|
|
92
|
+
await engine.createWebhook({ name: 'Flaky', url: 'https://hooks.example.com/flaky', events: ['project.created'] });
|
|
93
|
+
await engine.createProject({ name: 'Retry' });
|
|
94
|
+
await engine.webhooks.idle();
|
|
95
|
+
|
|
96
|
+
expect(deliveries).toHaveLength(3);
|
|
97
|
+
expect(new Set(deliveries.map((d) => d.headers['X-CriticalPath-Delivery'])).size).toBe(1);
|
|
98
|
+
expect(failures).toHaveLength(1);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('stops retrying once a delivery succeeds', async () => {
|
|
102
|
+
const { engine, deliveries } = engineWithCapture({ respond: (n) => (n < 3 ? 503 : 200) });
|
|
103
|
+
await engine.createWebhook({ name: 'Eventually', url: 'https://hooks.example.com/ok', events: ['project.created'] });
|
|
104
|
+
await engine.createProject({ name: 'Recover' });
|
|
105
|
+
await engine.webhooks.idle();
|
|
106
|
+
expect(deliveries).toHaveLength(3);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('times out hung receivers', async () => {
|
|
110
|
+
const failures: unknown[] = [];
|
|
111
|
+
const hanging = ((_url: string, init: RequestInit) =>
|
|
112
|
+
new Promise((_resolve, reject) => init.signal!.addEventListener('abort', () => reject(init.signal!.reason)))) as unknown as typeof fetch;
|
|
113
|
+
const { engine } = engineWithCapture({ fetch: hanging, timeoutMs: 10, maxAttempts: 1, onDeliveryFailed: (_job, err) => failures.push(err) });
|
|
114
|
+
await engine.createWebhook({ name: 'Slow', url: 'https://hooks.example.com/slow', events: ['project.created'] });
|
|
115
|
+
await engine.createProject({ name: 'Timeout' });
|
|
116
|
+
await engine.webhooks.idle();
|
|
117
|
+
expect(failures).toHaveLength(1);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it('routes events only to webhooks in the same tenant, including deletions', async () => {
|
|
121
|
+
const { engine, deliveries } = engineWithCapture();
|
|
122
|
+
const acme = engine.withActor({ userId: 'a', tenantId: 'acme' });
|
|
123
|
+
const globex = engine.withActor({ userId: 'g', tenantId: 'globex' });
|
|
124
|
+
await acme.createWebhook({ name: 'Acme', url: 'https://hooks.example.com/acme', events: ['*'] });
|
|
125
|
+
await globex.createWebhook({ name: 'Globex', url: 'https://hooks.example.com/globex', events: ['*'] });
|
|
126
|
+
|
|
127
|
+
const project = await acme.createProject({ name: 'Acme only' });
|
|
128
|
+
await acme.createTask({ projectId: project.id, title: 'T' });
|
|
129
|
+
await acme.deleteProject(project.id);
|
|
130
|
+
await engine.webhooks.idle();
|
|
131
|
+
|
|
132
|
+
expect(deliveries.length).toBeGreaterThan(0);
|
|
133
|
+
expect(deliveries.every((d) => d.url.endsWith('/acme'))).toBe(true);
|
|
134
|
+
expect(deliveries.every((d) => d.body.tenantId === 'acme')).toBe(true);
|
|
135
|
+
expect(deliveries.map((d) => d.body.event)).toContain('project.deleted');
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('delivers to static webhooks from config', async () => {
|
|
139
|
+
const { engine, deliveries } = engineWithCapture(
|
|
140
|
+
{},
|
|
141
|
+
{ webhooks: [{ name: 'Static', url: 'https://hooks.example.com/static', events: ['project.created'], active: true }] }
|
|
142
|
+
);
|
|
143
|
+
await engine.createProject({ name: 'Configured' });
|
|
144
|
+
await engine.webhooks.idle();
|
|
145
|
+
expect(deliveries).toHaveLength(1);
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
describe('webhook management', () => {
|
|
150
|
+
it('returns the secret once and redacts it from reads', async () => {
|
|
151
|
+
const { engine } = engineWithCapture();
|
|
152
|
+
const created = await engine.createWebhook({ name: 'Mine', url: 'https://hooks.example.com/x', events: ['*'] });
|
|
153
|
+
expect(created.secret).toMatch(/^whsec_[0-9a-f]{64}$/);
|
|
154
|
+
expect(created.webhook).not.toHaveProperty('secret');
|
|
155
|
+
expect(created.webhook.hasSecret).toBe(true);
|
|
156
|
+
|
|
157
|
+
const [listed] = await engine.getWebhooks();
|
|
158
|
+
expect(listed).not.toHaveProperty('secret');
|
|
159
|
+
expect(await engine.deleteWebhook(created.webhook.id)).toBe(true);
|
|
160
|
+
expect(await engine.getWebhooks()).toHaveLength(0);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it('rejects non-http and private URLs unless private URLs are allowed', async () => {
|
|
164
|
+
const { engine } = engineWithCapture();
|
|
165
|
+
await expect(engine.createWebhook({ name: 'x', url: 'ftp://hooks.example.com', events: ['*'] })).rejects.toThrow(ValidationError);
|
|
166
|
+
await expect(engine.createWebhook({ name: 'x', url: 'http://169.254.169.254/latest', events: ['*'] })).rejects.toThrow(/private/);
|
|
167
|
+
await expect(engine.createWebhook({ name: 'x', url: 'http://localhost:3000/hook', events: ['*'] })).rejects.toThrow(/private/);
|
|
168
|
+
|
|
169
|
+
const { engine: dev } = engineWithCapture({ allowPrivateUrls: true });
|
|
170
|
+
await expect(dev.createWebhook({ name: 'x', url: 'http://localhost:3000/hook', events: ['*'] })).resolves.toBeDefined();
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it('requires workspace.manage under a role policy and scopes webhooks by tenant', async () => {
|
|
174
|
+
const { engine } = engineWithCapture({}, { authorize: createRolePolicy() });
|
|
175
|
+
const member = engine.withActor({ userId: 'm', tenantId: 'acme' });
|
|
176
|
+
const admin = engine.withActor({ userId: 'root', tenantId: 'acme', roles: ['admin'] });
|
|
177
|
+
const otherAdmin = engine.withActor({ userId: 'root2', tenantId: 'globex', roles: ['admin'] });
|
|
178
|
+
|
|
179
|
+
await expect(member.createWebhook({ name: 'x', url: 'https://hooks.example.com/x', events: ['*'] })).rejects.toThrow(ForbiddenError);
|
|
180
|
+
const { webhook } = await admin.createWebhook({ name: 'Acme', url: 'https://hooks.example.com/acme', events: ['*'] });
|
|
181
|
+
expect(webhook.tenantId).toBe('acme');
|
|
182
|
+
expect(await otherAdmin.getWebhooks()).toHaveLength(0);
|
|
183
|
+
expect(await otherAdmin.deleteWebhook(webhook.id)).toBe(false);
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it('persists webhooks in SQLiteStore', async () => {
|
|
187
|
+
const engine = new CriticalPathEngine({ store: new SQLiteStore({ filename: ':memory:' }) });
|
|
188
|
+
const { webhook } = await engine.withActor({ userId: 'a', tenantId: 'acme' }).createWebhook({
|
|
189
|
+
name: 'Stored',
|
|
190
|
+
url: 'https://hooks.example.com/s',
|
|
191
|
+
events: ['task.created']
|
|
192
|
+
});
|
|
193
|
+
await engine.updateWebhook(webhook.id, { events: ['*'], name: 'Renamed' });
|
|
194
|
+
|
|
195
|
+
const stored = await engine.store.getWebhook(webhook.id);
|
|
196
|
+
expect(stored).toMatchObject({ name: 'Renamed', events: ['*'], tenantId: 'acme', active: true });
|
|
197
|
+
expect(stored?.secret).toMatch(/^whsec_/);
|
|
198
|
+
expect(await engine.deleteWebhook(webhook.id)).toBe(true);
|
|
199
|
+
});
|
|
200
|
+
});
|
package/tsconfig.tsbuildinfo
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"root":["./src/deliverables.test.ts","./src/index.test.ts","./src/index.ts","./src/status.test.ts","./src/task-state.test.ts","./src/use-case-validation.test.ts","./src/domain/calendar.test.ts","./src/domain/calendar.ts","./src/domain/cpm.test.ts","./src/domain/cpm.ts","./src/domain/custom-fields.ts","./src/domain/ddd.test.ts","./src/domain/entities.ts","./src/domain/errors.ts","./src/domain/events.ts","./src/domain/graph.ts","./src/domain/index.ts","./src/domain/ladder.test.ts","./src/domain/ladder.ts","./src/domain/metrics.test.ts","./src/domain/metrics.ts","./src/domain/task-duration.test.ts","./src/domain/workload.test.ts","./src/domain/workload.ts","./src/engine/actor.test.ts","./src/engine/index.ts","./src/plugins/index.ts","./src/schemas/index.ts","./src/schemas/schemas.test.ts","./src/storage/file-storage.ts","./src/storage/firebase-storage.ts","./src/storage/index.ts","./src/storage/s3.ts","./src/storage/storage.test.ts","./src/store/firebase.test.ts","./src/store/firebase.ts","./src/store/index.ts","./src/store/sqlite.test.ts","./src/store/sqlite.ts","./src/types/index.ts","./src/utils/fractional-index.test.ts","./src/utils/fractional-index.ts","./src/utils/index.ts","./src/utils/key.test.ts","./src/utils/key.ts","./src/utils/mentions.test.ts","./src/utils/mentions.ts","./src/utils/status.ts","./src/utils/workflow.ts"],"version":"5.9.3"}
|
|
1
|
+
{"root":["./src/deliverables.test.ts","./src/index.test.ts","./src/index.ts","./src/status.test.ts","./src/task-state.test.ts","./src/use-case-validation.test.ts","./src/domain/authorization.ts","./src/domain/calendar.test.ts","./src/domain/calendar.ts","./src/domain/cpm.test.ts","./src/domain/cpm.ts","./src/domain/custom-fields.ts","./src/domain/ddd.test.ts","./src/domain/entities.ts","./src/domain/errors.ts","./src/domain/events.ts","./src/domain/graph.ts","./src/domain/index.ts","./src/domain/ladder.test.ts","./src/domain/ladder.ts","./src/domain/metrics.test.ts","./src/domain/metrics.ts","./src/domain/task-duration.test.ts","./src/domain/workload.test.ts","./src/domain/workload.ts","./src/engine/actor.test.ts","./src/engine/authorization.test.ts","./src/engine/index.ts","./src/plugins/index.ts","./src/schemas/index.ts","./src/schemas/schemas.test.ts","./src/storage/file-storage.ts","./src/storage/firebase-storage.ts","./src/storage/index.ts","./src/storage/s3.ts","./src/storage/storage.test.ts","./src/store/firebase.test.ts","./src/store/firebase.ts","./src/store/index.ts","./src/store/sqlite.test.ts","./src/store/sqlite.ts","./src/types/index.ts","./src/utils/fractional-index.test.ts","./src/utils/fractional-index.ts","./src/utils/index.ts","./src/utils/key.test.ts","./src/utils/key.ts","./src/utils/mentions.test.ts","./src/utils/mentions.ts","./src/utils/status.ts","./src/utils/workflow.ts","./src/webhooks/dispatcher.ts","./src/webhooks/index.ts","./src/webhooks/signature.ts","./src/webhooks/webhooks.test.ts"],"version":"5.9.3"}
|