pcific 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +50 -2
- package/dist/SKILL.md +127 -0
- package/dist/api/catalog.js +637 -0
- package/dist/api/run.js +960 -0
- package/dist/api/search.js +171 -0
- package/dist/api/shortcuts.js +799 -0
- package/dist/bin.js +648 -0
- package/dist/commands/auth.js +513 -0
- package/dist/commands/doctor.js +410 -0
- package/dist/commands/init.js +306 -0
- package/dist/commands/sync.js +214 -0
- package/dist/detect.js +214 -0
- package/dist/env.js +339 -0
- package/dist/goLive.js +629 -0
- package/dist/keyLink.js +305 -0
- package/dist/mcp/server.js +206 -0
- package/dist/mcp/tools.js +689 -0
- package/dist/python/template.js +793 -0
- package/dist/schema/discover.js +324 -0
- package/dist/schema/helpers.js +396 -0
- package/dist/schema/prismaToJsonSchema.js +197 -0
- package/dist/schema/push.js +570 -0
- package/dist/schema/tsToJsonSchema.js +405 -0
- package/dist/schema/zodToJsonSchema.js +442 -0
- package/dist/templates/openapi.json +1 -0
- package/dist/templates/sdk/auth.ts +139 -0
- package/dist/templates/sdk/client.ts +1059 -0
- package/dist/templates/sdk/errors.ts +76 -0
- package/dist/templates/sdk/generated-types.ts +5746 -0
- package/dist/templates/sdk/http.ts +359 -0
- package/dist/templates/sdk/index.ts +84 -0
- package/dist/templates/sdk/json.ts +24 -0
- package/dist/templates/sdk/kit.ts +516 -0
- package/dist/templates/sdk/multipart.ts +99 -0
- package/dist/templates/sdk/sse.ts +131 -0
- package/dist/templates/sdk/verify.ts +766 -0
- package/dist/templates/sdk-js/auth.d.ts +20 -0
- package/dist/templates/sdk-js/auth.js +85 -0
- package/dist/templates/sdk-js/client.d.ts +324 -0
- package/dist/templates/sdk-js/client.js +607 -0
- package/dist/templates/sdk-js/errors.d.ts +51 -0
- package/dist/templates/sdk-js/errors.js +48 -0
- package/dist/templates/sdk-js/generated-types.d.ts +5736 -0
- package/dist/templates/sdk-js/generated-types.js +5 -0
- package/dist/templates/sdk-js/http.d.ts +50 -0
- package/dist/templates/sdk-js/http.js +263 -0
- package/dist/templates/sdk-js/index.d.ts +9 -0
- package/dist/templates/sdk-js/index.js +7 -0
- package/dist/templates/sdk-js/json.d.ts +11 -0
- package/dist/templates/sdk-js/json.js +16 -0
- package/dist/templates/sdk-js/kit.d.ts +220 -0
- package/dist/templates/sdk-js/kit.js +208 -0
- package/dist/templates/sdk-js/multipart.d.ts +23 -0
- package/dist/templates/sdk-js/multipart.js +61 -0
- package/dist/templates/sdk-js/sse.d.ts +12 -0
- package/dist/templates/sdk-js/sse.js +99 -0
- package/dist/templates/sdk-js/verify.d.ts +114 -0
- package/dist/templates/sdk-js/verify.js +506 -0
- package/dist/templates.js +925 -0
- package/dist/ui.js +399 -0
- package/dist/webhooks/events.js +171 -0
- package/dist/webhooks/listen.js +772 -0
- package/package.json +32 -4
|
@@ -0,0 +1,772 @@
|
|
|
1
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { BaseUrlError, DEFAULT_BASE_URL, normalizeBaseUrl, readMergedEnv, redactSecrets, } from "../api/run.js";
|
|
4
|
+
import { buildSampleWebhookEvent, isWebhookEventType, signWebhookPayload, WEBHOOK_EVENT_TYPES, } from "./events.js";
|
|
5
|
+
const LOCALHOST_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
|
|
6
|
+
const TTY_SHORTCUTS = new Map([
|
|
7
|
+
["d", "dispute_pack.ready"],
|
|
8
|
+
["s", "safeguard.review_finished"],
|
|
9
|
+
["o", "orbit.finished"],
|
|
10
|
+
["m", "message_check.flagged"],
|
|
11
|
+
]);
|
|
12
|
+
function isJsonString(value) {
|
|
13
|
+
return typeof value === "string";
|
|
14
|
+
}
|
|
15
|
+
function isJsonBoolean(value) {
|
|
16
|
+
return typeof value === "boolean";
|
|
17
|
+
}
|
|
18
|
+
function isJsonObject(value) {
|
|
19
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
function parseJsonValue(text) {
|
|
22
|
+
// SAFETY: JSON.parse returns only JSON primitives, arrays, or plain objects matching WebhookJsonValue.
|
|
23
|
+
return JSON.parse(text);
|
|
24
|
+
}
|
|
25
|
+
function isAddressInfo(address) {
|
|
26
|
+
return address !== null && typeof address === "object";
|
|
27
|
+
}
|
|
28
|
+
export function generateLocalWebhookSecret() {
|
|
29
|
+
return `whsec_local_${randomBytes(24).toString("hex")}`;
|
|
30
|
+
}
|
|
31
|
+
export function validateForwardUrl(rawUrl, allowRemote) {
|
|
32
|
+
let parsed;
|
|
33
|
+
try {
|
|
34
|
+
parsed = new URL(rawUrl);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return {
|
|
38
|
+
code: "INVALID_FORWARD_URL",
|
|
39
|
+
error: `Invalid --forward URL "${rawUrl}".`,
|
|
40
|
+
tryThis: "Provide a full http:// or https:// address such as --forward http://127.0.0.1:3000/api/webhooks/pcific.",
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
44
|
+
return {
|
|
45
|
+
code: "INVALID_FORWARD_URL",
|
|
46
|
+
error: `Unsupported protocol "${parsed.protocol}" in --forward URL.`,
|
|
47
|
+
tryThis: "Use an http:// or https:// URL such as http://127.0.0.1:3000/api/webhooks/pcific.",
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
const host = parsed.hostname.toLowerCase();
|
|
51
|
+
if (!allowRemote && !LOCALHOST_HOSTS.has(host)) {
|
|
52
|
+
return {
|
|
53
|
+
code: "REMOTE_FORWARD_BLOCKED",
|
|
54
|
+
error: `Refusing to forward local test webhooks to non-localhost host "${parsed.hostname}" without --allow-remote.`,
|
|
55
|
+
tryThis: "Use a localhost / 127.0.0.1 / ::1 URL, or pass --allow-remote explicitly if you intend to send to a remote host.",
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
return { url: parsed };
|
|
59
|
+
}
|
|
60
|
+
export async function deliverSignedWebhook(options) {
|
|
61
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
62
|
+
const rawBody = JSON.stringify(options.event);
|
|
63
|
+
const signature = signWebhookPayload(rawBody, options.secret);
|
|
64
|
+
const start = Date.now();
|
|
65
|
+
try {
|
|
66
|
+
const response = await fetchFn(options.forwardUrl, {
|
|
67
|
+
method: "POST",
|
|
68
|
+
redirect: "manual",
|
|
69
|
+
headers: {
|
|
70
|
+
"Content-Type": "application/json",
|
|
71
|
+
"User-Agent": "PCIFIC-Webhooks/1",
|
|
72
|
+
"PCIFIC-Event-Id": options.event.id,
|
|
73
|
+
"PCIFIC-Signature": signature,
|
|
74
|
+
},
|
|
75
|
+
body: rawBody,
|
|
76
|
+
});
|
|
77
|
+
const responseBody = redactSecrets(await response.text());
|
|
78
|
+
const latencyMs = Date.now() - start;
|
|
79
|
+
return {
|
|
80
|
+
ok: response.ok,
|
|
81
|
+
eventId: options.event.id,
|
|
82
|
+
eventType: options.event.type,
|
|
83
|
+
forwardUrl: options.forwardUrl,
|
|
84
|
+
signature,
|
|
85
|
+
status: response.status,
|
|
86
|
+
latencyMs,
|
|
87
|
+
responseBody,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
const latencyMs = Date.now() - start;
|
|
92
|
+
return {
|
|
93
|
+
ok: false,
|
|
94
|
+
eventId: options.event.id,
|
|
95
|
+
eventType: options.event.type,
|
|
96
|
+
forwardUrl: options.forwardUrl,
|
|
97
|
+
signature,
|
|
98
|
+
status: 0,
|
|
99
|
+
latencyMs,
|
|
100
|
+
responseBody: "",
|
|
101
|
+
error: redactSecrets(error instanceof Error ? error.message : String(error)),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function readRequestBody(req, maxBytes = 1024 * 1024) {
|
|
106
|
+
return new Promise((resolve, reject) => {
|
|
107
|
+
const chunks = [];
|
|
108
|
+
let total = 0;
|
|
109
|
+
req.on("data", (chunk) => {
|
|
110
|
+
total += chunk.length;
|
|
111
|
+
if (total > maxBytes) {
|
|
112
|
+
reject(new Error("Request body exceeds 1 MiB limit."));
|
|
113
|
+
req.destroy();
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
chunks.push(chunk);
|
|
117
|
+
});
|
|
118
|
+
req.on("end", () => {
|
|
119
|
+
resolve(Buffer.concat(chunks).toString("utf8"));
|
|
120
|
+
});
|
|
121
|
+
req.on("error", reject);
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
function sendJson(res, status, body) {
|
|
125
|
+
const text = JSON.stringify(body);
|
|
126
|
+
res.writeHead(status, {
|
|
127
|
+
"Content-Type": "application/json",
|
|
128
|
+
"Content-Length": Buffer.byteLength(text),
|
|
129
|
+
});
|
|
130
|
+
res.end(text);
|
|
131
|
+
}
|
|
132
|
+
export async function startWebhookListener(options) {
|
|
133
|
+
const check = validateForwardUrl(options.forwardUrl, Boolean(options.allowRemote));
|
|
134
|
+
if (check.error) {
|
|
135
|
+
throw new Error(check.error);
|
|
136
|
+
}
|
|
137
|
+
const secret = options.secret ?? generateLocalWebhookSecret();
|
|
138
|
+
const port = options.port ?? 4242;
|
|
139
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
140
|
+
const deliver = async (eventType, customBody) => {
|
|
141
|
+
const baseEvent = buildSampleWebhookEvent(eventType, {
|
|
142
|
+
marketplaceId: options.marketplaceId,
|
|
143
|
+
test: true,
|
|
144
|
+
});
|
|
145
|
+
const event = customBody
|
|
146
|
+
? {
|
|
147
|
+
id: isJsonString(customBody.id) ? customBody.id : baseEvent.id,
|
|
148
|
+
type: eventType,
|
|
149
|
+
createdAt: isJsonString(customBody.createdAt)
|
|
150
|
+
? customBody.createdAt
|
|
151
|
+
: baseEvent.createdAt,
|
|
152
|
+
marketplaceId: isJsonString(customBody.marketplaceId)
|
|
153
|
+
? customBody.marketplaceId
|
|
154
|
+
: baseEvent.marketplaceId,
|
|
155
|
+
test: isJsonBoolean(customBody.test) ? customBody.test : true,
|
|
156
|
+
data: isJsonObject(customBody.data) ? customBody.data : baseEvent.data,
|
|
157
|
+
}
|
|
158
|
+
: baseEvent;
|
|
159
|
+
const report = await deliverSignedWebhook({
|
|
160
|
+
forwardUrl: options.forwardUrl,
|
|
161
|
+
secret,
|
|
162
|
+
event,
|
|
163
|
+
fetch: fetchFn,
|
|
164
|
+
});
|
|
165
|
+
options.onDelivery?.(report);
|
|
166
|
+
return report;
|
|
167
|
+
};
|
|
168
|
+
const server = createServer(async (req, res) => {
|
|
169
|
+
const method = req.method ?? "GET";
|
|
170
|
+
const parsedUrl = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
171
|
+
if (method === "GET" && parsedUrl.pathname === "/health") {
|
|
172
|
+
sendJson(res, 200, {
|
|
173
|
+
ok: true,
|
|
174
|
+
forwardUrl: options.forwardUrl,
|
|
175
|
+
events: [...WEBHOOK_EVENT_TYPES],
|
|
176
|
+
});
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (method !== "POST") {
|
|
180
|
+
sendJson(res, 405, {
|
|
181
|
+
code: "METHOD_NOT_ALLOWED",
|
|
182
|
+
error: `Expected POST /trigger/<eventType> or POST /, received ${method}.`,
|
|
183
|
+
tryThis: "Send POST /trigger/safeguard.review_finished to forward a signed sample webhook.",
|
|
184
|
+
});
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
let rawBody = "";
|
|
188
|
+
try {
|
|
189
|
+
rawBody = await readRequestBody(req);
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
sendJson(res, 413, {
|
|
193
|
+
code: "BODY_TOO_LARGE",
|
|
194
|
+
error: error instanceof Error ? error.message : String(error),
|
|
195
|
+
tryThis: "Send a webhook payload smaller than 1 MiB.",
|
|
196
|
+
});
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
let customBody;
|
|
200
|
+
if (rawBody.trim().length > 0) {
|
|
201
|
+
try {
|
|
202
|
+
const parsed = parseJsonValue(rawBody);
|
|
203
|
+
if (!isJsonObject(parsed)) {
|
|
204
|
+
sendJson(res, 400, {
|
|
205
|
+
code: "INVALID_JSON",
|
|
206
|
+
error: "Request body must be a JSON object.",
|
|
207
|
+
tryThis: "Send an empty body or a JSON object overriding sample event fields.",
|
|
208
|
+
});
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
customBody = parsed;
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
sendJson(res, 400, {
|
|
215
|
+
code: "INVALID_JSON",
|
|
216
|
+
error: "Request body is not valid JSON.",
|
|
217
|
+
tryThis: "Fix the JSON syntax or omit the body to use the default sample event.",
|
|
218
|
+
});
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
let eventTypeName = "";
|
|
223
|
+
if (parsedUrl.pathname.startsWith("/trigger/")) {
|
|
224
|
+
eventTypeName = decodeURIComponent(parsedUrl.pathname.slice("/trigger/".length));
|
|
225
|
+
}
|
|
226
|
+
else if (parsedUrl.pathname === "/") {
|
|
227
|
+
const fromQuery = parsedUrl.searchParams.get("event") ?? parsedUrl.searchParams.get("type");
|
|
228
|
+
const fromBody = customBody && isJsonString(customBody.type) ? customBody.type : undefined;
|
|
229
|
+
eventTypeName = fromQuery ?? fromBody ?? "";
|
|
230
|
+
}
|
|
231
|
+
else {
|
|
232
|
+
sendJson(res, 404, {
|
|
233
|
+
code: "NOT_FOUND",
|
|
234
|
+
error: `Unknown path "${parsedUrl.pathname}".`,
|
|
235
|
+
tryThis: 'Send POST /trigger/<eventType> or POST / with {"type": "<eventType>"}.',
|
|
236
|
+
});
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (!isWebhookEventType(eventTypeName)) {
|
|
240
|
+
sendJson(res, 400, {
|
|
241
|
+
code: "WEBHOOK_EVENT_INVALID",
|
|
242
|
+
error: eventTypeName
|
|
243
|
+
? `Unsupported webhook event "${eventTypeName}".`
|
|
244
|
+
: "Missing webhook event type.",
|
|
245
|
+
tryThis: `Choose one of: ${WEBHOOK_EVENT_TYPES.join(", ")}.`,
|
|
246
|
+
});
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
const report = await deliver(eventTypeName, customBody);
|
|
250
|
+
const responsePayload = {
|
|
251
|
+
delivered: report.ok,
|
|
252
|
+
eventId: report.eventId,
|
|
253
|
+
eventType: report.eventType,
|
|
254
|
+
status: report.status,
|
|
255
|
+
latencyMs: report.latencyMs,
|
|
256
|
+
signature: report.signature,
|
|
257
|
+
responseBody: report.responseBody,
|
|
258
|
+
};
|
|
259
|
+
if (report.error) {
|
|
260
|
+
responsePayload.error = report.error;
|
|
261
|
+
}
|
|
262
|
+
sendJson(res, report.ok ? 200 : 502, responsePayload);
|
|
263
|
+
});
|
|
264
|
+
await new Promise((resolve, reject) => {
|
|
265
|
+
server.once("error", reject);
|
|
266
|
+
server.listen(port, "127.0.0.1", () => {
|
|
267
|
+
server.off("error", reject);
|
|
268
|
+
resolve();
|
|
269
|
+
});
|
|
270
|
+
});
|
|
271
|
+
const addr = server.address();
|
|
272
|
+
if (!isAddressInfo(addr)) {
|
|
273
|
+
throw new Error("Expected TCP AddressInfo from local webhook listener.");
|
|
274
|
+
}
|
|
275
|
+
const boundPort = addr.port;
|
|
276
|
+
return {
|
|
277
|
+
url: `http://127.0.0.1:${boundPort}`,
|
|
278
|
+
port: boundPort,
|
|
279
|
+
secret,
|
|
280
|
+
forwardUrl: options.forwardUrl,
|
|
281
|
+
server,
|
|
282
|
+
deliver,
|
|
283
|
+
close: () => new Promise((resolve, reject) => {
|
|
284
|
+
server.close((error) => {
|
|
285
|
+
if (error)
|
|
286
|
+
reject(error);
|
|
287
|
+
else
|
|
288
|
+
resolve();
|
|
289
|
+
});
|
|
290
|
+
}),
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
function isWritableStreamSink(sink) {
|
|
294
|
+
return "write" in sink;
|
|
295
|
+
}
|
|
296
|
+
function createLineWriter(sink, fallback, redact) {
|
|
297
|
+
if (sink && !isWritableStreamSink(sink)) {
|
|
298
|
+
return (line) => {
|
|
299
|
+
sink(redact ? redactSecrets(line) : line);
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
const stream = sink ?? fallback;
|
|
303
|
+
return (line) => {
|
|
304
|
+
stream.write(`${redact ? redactSecrets(line) : line}\n`);
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
function readWebhookFlagValue(args, index, flag, tryThis) {
|
|
308
|
+
const token = args[index];
|
|
309
|
+
if (token.startsWith(`${flag}=`)) {
|
|
310
|
+
const value = token.slice(flag.length + 1);
|
|
311
|
+
if (!value) {
|
|
312
|
+
return { ok: false, error: `Missing value for ${flag}.`, tryThis };
|
|
313
|
+
}
|
|
314
|
+
return { ok: true, value, nextIndex: index };
|
|
315
|
+
}
|
|
316
|
+
const next = args[index + 1];
|
|
317
|
+
if (!next || next.startsWith("-")) {
|
|
318
|
+
return { ok: false, error: `Missing value for ${flag}.`, tryThis };
|
|
319
|
+
}
|
|
320
|
+
return { ok: true, value: next, nextIndex: index + 1 };
|
|
321
|
+
}
|
|
322
|
+
function parseWebhookArgs(args, options) {
|
|
323
|
+
const wantsJson = Boolean(options.json) || args.includes("--json");
|
|
324
|
+
const parsed = {
|
|
325
|
+
subcommand: "help",
|
|
326
|
+
allowRemote: false,
|
|
327
|
+
plain: Boolean(options.plain),
|
|
328
|
+
json: wantsJson,
|
|
329
|
+
help: false,
|
|
330
|
+
};
|
|
331
|
+
const positionals = [];
|
|
332
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
333
|
+
const arg = args[index];
|
|
334
|
+
if (arg === "--help" || arg === "-h") {
|
|
335
|
+
parsed.help = true;
|
|
336
|
+
}
|
|
337
|
+
else if (arg === "--allow-remote") {
|
|
338
|
+
parsed.allowRemote = true;
|
|
339
|
+
}
|
|
340
|
+
else if (arg === "--plain") {
|
|
341
|
+
parsed.plain = true;
|
|
342
|
+
}
|
|
343
|
+
else if (arg === "--json") {
|
|
344
|
+
parsed.json = true;
|
|
345
|
+
}
|
|
346
|
+
else if (arg === "--forward" || arg.startsWith("--forward=")) {
|
|
347
|
+
const read = readWebhookFlagValue(args, index, "--forward", "Pass a receiver URL, for example --forward http://127.0.0.1:3000/api/webhooks/pcific.");
|
|
348
|
+
if (!read.ok) {
|
|
349
|
+
return { ok: false, code: "MISSING_FLAG_VALUE", error: read.error, tryThis: read.tryThis, json: wantsJson };
|
|
350
|
+
}
|
|
351
|
+
parsed.forward = read.value;
|
|
352
|
+
index = read.nextIndex;
|
|
353
|
+
}
|
|
354
|
+
else if (arg === "--port" || arg.startsWith("--port=")) {
|
|
355
|
+
const read = readWebhookFlagValue(args, index, "--port", "Pass a port number between 0 and 65535, for example --port 4242.");
|
|
356
|
+
if (!read.ok) {
|
|
357
|
+
return { ok: false, code: "MISSING_FLAG_VALUE", error: read.error, tryThis: read.tryThis, json: wantsJson };
|
|
358
|
+
}
|
|
359
|
+
const portValue = Number(read.value);
|
|
360
|
+
if (!Number.isInteger(portValue) || portValue < 0 || portValue > 65535) {
|
|
361
|
+
return {
|
|
362
|
+
ok: false,
|
|
363
|
+
code: "INVALID_PORT",
|
|
364
|
+
error: `Invalid --port value "${read.value}".`,
|
|
365
|
+
tryThis: "Pass a whole port number between 0 and 65535, for example --port 4242.",
|
|
366
|
+
json: wantsJson,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
parsed.port = portValue;
|
|
370
|
+
index = read.nextIndex;
|
|
371
|
+
}
|
|
372
|
+
else if (arg === "--secret" || arg.startsWith("--secret=")) {
|
|
373
|
+
const read = readWebhookFlagValue(args, index, "--secret", "Pass a webhook signing secret, for example --secret whsec_... or set PCIFIC_WEBHOOK_SECRET.");
|
|
374
|
+
if (!read.ok) {
|
|
375
|
+
return { ok: false, code: "MISSING_FLAG_VALUE", error: read.error, tryThis: read.tryThis, json: wantsJson };
|
|
376
|
+
}
|
|
377
|
+
parsed.secret = read.value;
|
|
378
|
+
index = read.nextIndex;
|
|
379
|
+
}
|
|
380
|
+
else if (arg === "--marketplace-id" || arg.startsWith("--marketplace-id=")) {
|
|
381
|
+
const read = readWebhookFlagValue(args, index, "--marketplace-id", "Pass a shop ID, for example --marketplace-id <shop-id>.");
|
|
382
|
+
if (!read.ok) {
|
|
383
|
+
return { ok: false, code: "MISSING_FLAG_VALUE", error: read.error, tryThis: read.tryThis, json: wantsJson };
|
|
384
|
+
}
|
|
385
|
+
parsed.marketplaceId = read.value;
|
|
386
|
+
index = read.nextIndex;
|
|
387
|
+
}
|
|
388
|
+
else if (arg === "--base-url" || arg.startsWith("--base-url=")) {
|
|
389
|
+
const read = readWebhookFlagValue(args, index, "--base-url", `Pass an http:// or https:// URL, for example --base-url ${DEFAULT_BASE_URL}.`);
|
|
390
|
+
if (!read.ok) {
|
|
391
|
+
return { ok: false, code: "MISSING_FLAG_VALUE", error: read.error, tryThis: read.tryThis, json: wantsJson };
|
|
392
|
+
}
|
|
393
|
+
parsed.baseUrl = read.value;
|
|
394
|
+
index = read.nextIndex;
|
|
395
|
+
}
|
|
396
|
+
else if (arg.startsWith("-")) {
|
|
397
|
+
return {
|
|
398
|
+
ok: false,
|
|
399
|
+
code: "UNKNOWN_FLAG",
|
|
400
|
+
error: `Unknown flag "${arg}" for pcific webhooks.`,
|
|
401
|
+
tryThis: "Run pcific webhooks --help to see supported options.",
|
|
402
|
+
json: wantsJson,
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
else {
|
|
406
|
+
positionals.push(arg);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
if (positionals.length > 0) {
|
|
410
|
+
parsed.subcommand = positionals[0];
|
|
411
|
+
}
|
|
412
|
+
if (positionals.length > 1) {
|
|
413
|
+
parsed.eventType = positionals[1];
|
|
414
|
+
}
|
|
415
|
+
return { ok: true, parsed };
|
|
416
|
+
}
|
|
417
|
+
function emitWebhookError(out, err, asJson, payload) {
|
|
418
|
+
const cleanError = redactSecrets(payload.error);
|
|
419
|
+
const cleanTryThis = redactSecrets(payload.tryThis);
|
|
420
|
+
if (asJson) {
|
|
421
|
+
const jsonPayload = {
|
|
422
|
+
ok: false,
|
|
423
|
+
code: payload.code,
|
|
424
|
+
error: cleanError,
|
|
425
|
+
tryThis: cleanTryThis,
|
|
426
|
+
};
|
|
427
|
+
if (payload.status !== undefined)
|
|
428
|
+
jsonPayload.status = payload.status;
|
|
429
|
+
if (payload.eventTypes !== undefined)
|
|
430
|
+
jsonPayload.eventTypes = payload.eventTypes;
|
|
431
|
+
out(JSON.stringify(jsonPayload, null, 2));
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
err(cleanError);
|
|
435
|
+
err(`Next: ${cleanTryThis}`);
|
|
436
|
+
}
|
|
437
|
+
function printUsage(out) {
|
|
438
|
+
out("Usage:");
|
|
439
|
+
out(" pcific webhooks listen --forward <url> [--port <port>] [--secret <secret>] [--allow-remote] [--plain] [--json]");
|
|
440
|
+
out(" pcific webhooks trigger <eventType> --forward <url> [--secret <secret>] [--marketplace-id <id>] [--allow-remote] [--plain] [--json]");
|
|
441
|
+
out(" pcific webhooks list [--plain] [--json]");
|
|
442
|
+
}
|
|
443
|
+
function formatDeliveryLine(report) {
|
|
444
|
+
const statusLabel = report.status > 0 ? `HTTP ${report.status}` : "NETWORK_ERROR";
|
|
445
|
+
const summary = report.error
|
|
446
|
+
? report.error
|
|
447
|
+
: report.responseBody.trim().slice(0, 120) || "(empty body)";
|
|
448
|
+
return `[${report.ok ? "OK" : "FAIL"}] ${report.eventType} -> ${statusLabel} (${report.latencyMs}ms) id=${report.eventId} body=${summary}`;
|
|
449
|
+
}
|
|
450
|
+
function enableRawMode(stdin, enabled) {
|
|
451
|
+
if (stdin.isTTY && stdin.setRawMode) {
|
|
452
|
+
stdin.setRawMode(enabled);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
export async function runWebhooksCommand(args, options = {}) {
|
|
456
|
+
const cwd = options.cwd ?? process.cwd();
|
|
457
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
458
|
+
const out = createLineWriter(options.stdout, process.stdout, true);
|
|
459
|
+
const outRaw = createLineWriter(options.stdout, process.stdout, false);
|
|
460
|
+
const err = createLineWriter(options.stderr, process.stderr, true);
|
|
461
|
+
const parsedResult = parseWebhookArgs(args, options);
|
|
462
|
+
if (!parsedResult.ok) {
|
|
463
|
+
emitWebhookError(out, err, parsedResult.json, {
|
|
464
|
+
code: parsedResult.code,
|
|
465
|
+
error: parsedResult.error,
|
|
466
|
+
tryThis: parsedResult.tryThis,
|
|
467
|
+
});
|
|
468
|
+
return 1;
|
|
469
|
+
}
|
|
470
|
+
const parsed = parsedResult.parsed;
|
|
471
|
+
if (parsed.help || parsed.subcommand === "help") {
|
|
472
|
+
printUsage(out);
|
|
473
|
+
return 0;
|
|
474
|
+
}
|
|
475
|
+
const env = readMergedEnv(cwd, options.env);
|
|
476
|
+
if (parsed.subcommand === "trigger") {
|
|
477
|
+
if (!parsed.eventType || !isWebhookEventType(parsed.eventType)) {
|
|
478
|
+
const msg = parsed.eventType
|
|
479
|
+
? `Unsupported webhook event "${parsed.eventType}".`
|
|
480
|
+
: "Missing webhook event type.";
|
|
481
|
+
emitWebhookError(out, err, parsed.json, {
|
|
482
|
+
code: "WEBHOOK_EVENT_INVALID",
|
|
483
|
+
error: msg,
|
|
484
|
+
tryThis: `Choose one of: ${WEBHOOK_EVENT_TYPES.join(", ")}.`,
|
|
485
|
+
eventTypes: WEBHOOK_EVENT_TYPES,
|
|
486
|
+
});
|
|
487
|
+
return 1;
|
|
488
|
+
}
|
|
489
|
+
if (!parsed.forward) {
|
|
490
|
+
emitWebhookError(out, err, parsed.json, {
|
|
491
|
+
code: "MISSING_REQUIRED_FLAG",
|
|
492
|
+
error: "Missing required flag --forward <url>.",
|
|
493
|
+
tryThis: "Pass --forward http://127.0.0.1:3000/api/webhooks/pcific (your local webhook receiver URL).",
|
|
494
|
+
});
|
|
495
|
+
return 1;
|
|
496
|
+
}
|
|
497
|
+
const urlCheck = validateForwardUrl(parsed.forward, parsed.allowRemote);
|
|
498
|
+
if (urlCheck.error) {
|
|
499
|
+
emitWebhookError(out, err, parsed.json, {
|
|
500
|
+
code: urlCheck.code ?? "INVALID_FORWARD_URL",
|
|
501
|
+
error: urlCheck.error,
|
|
502
|
+
tryThis: urlCheck.tryThis ??
|
|
503
|
+
"Pass a valid http:// or https:// localhost URL to --forward.",
|
|
504
|
+
});
|
|
505
|
+
return 1;
|
|
506
|
+
}
|
|
507
|
+
const secret = parsed.secret ?? (env.get("PCIFIC_WEBHOOK_SECRET")?.trim() || generateLocalWebhookSecret());
|
|
508
|
+
const marketplaceId = parsed.marketplaceId ?? (env.get("PCIFIC_MARKETPLACE_ID")?.trim() || undefined);
|
|
509
|
+
const event = buildSampleWebhookEvent(parsed.eventType, {
|
|
510
|
+
marketplaceId,
|
|
511
|
+
test: true,
|
|
512
|
+
eventId: randomUUID(),
|
|
513
|
+
});
|
|
514
|
+
const report = await deliverSignedWebhook({
|
|
515
|
+
forwardUrl: parsed.forward,
|
|
516
|
+
secret,
|
|
517
|
+
event,
|
|
518
|
+
fetch: fetchFn,
|
|
519
|
+
});
|
|
520
|
+
if (parsed.json) {
|
|
521
|
+
out(JSON.stringify(report, null, 2));
|
|
522
|
+
}
|
|
523
|
+
else {
|
|
524
|
+
out(`Event: ${report.eventType} (${report.eventId})`);
|
|
525
|
+
out(`Target: ${report.forwardUrl}`);
|
|
526
|
+
out(`PCIFIC-Signature: ${report.signature}`);
|
|
527
|
+
out(formatDeliveryLine(report));
|
|
528
|
+
}
|
|
529
|
+
return report.ok ? 0 : 1;
|
|
530
|
+
}
|
|
531
|
+
if (parsed.subcommand === "list") {
|
|
532
|
+
const testKey = env.get("PCIFIC_TEST_KEY")?.trim();
|
|
533
|
+
if (testKey && testKey.startsWith("pcific_live_")) {
|
|
534
|
+
emitWebhookError(out, err, parsed.json, {
|
|
535
|
+
code: "LIVE_KEY_REFUSED",
|
|
536
|
+
error: "Refusing to run webhooks list with a live API key (pcific_live_***).",
|
|
537
|
+
tryThis: "Set PCIFIC_TEST_KEY to a test key (pcific_test_...) in your environment or .env file.",
|
|
538
|
+
});
|
|
539
|
+
return 1;
|
|
540
|
+
}
|
|
541
|
+
if (!testKey) {
|
|
542
|
+
if (env.get("PCIFIC_LIVE_KEY")?.trim()) {
|
|
543
|
+
emitWebhookError(out, err, parsed.json, {
|
|
544
|
+
code: "LIVE_KEY_REFUSED",
|
|
545
|
+
error: "PCIFIC_TEST_KEY is not set, and webhooks list never uses PCIFIC_LIVE_KEY.",
|
|
546
|
+
tryThis: "Set PCIFIC_TEST_KEY to a test key (pcific_test_...) in your environment or .env file.",
|
|
547
|
+
});
|
|
548
|
+
return 1;
|
|
549
|
+
}
|
|
550
|
+
emitWebhookError(out, err, parsed.json, {
|
|
551
|
+
code: "MISSING_TEST_KEY",
|
|
552
|
+
error: "Missing PCIFIC_TEST_KEY.",
|
|
553
|
+
tryThis: "Set PCIFIC_TEST_KEY in your environment or .env file to a test key (pcific_test_...) or run `npx pcific init`.",
|
|
554
|
+
});
|
|
555
|
+
return 1;
|
|
556
|
+
}
|
|
557
|
+
let baseUrl;
|
|
558
|
+
try {
|
|
559
|
+
baseUrl = normalizeBaseUrl(parsed.baseUrl ?? options.baseUrl ?? env.get("PCIFIC_BASE_URL")?.trim() ?? DEFAULT_BASE_URL);
|
|
560
|
+
}
|
|
561
|
+
catch (error) {
|
|
562
|
+
if (error instanceof BaseUrlError) {
|
|
563
|
+
emitWebhookError(out, err, parsed.json, {
|
|
564
|
+
code: error.code,
|
|
565
|
+
error: error.message,
|
|
566
|
+
tryThis: error.tryThis,
|
|
567
|
+
});
|
|
568
|
+
return 1;
|
|
569
|
+
}
|
|
570
|
+
throw error;
|
|
571
|
+
}
|
|
572
|
+
const marketplaceId = parsed.marketplaceId ?? (env.get("PCIFIC_MARKETPLACE_ID")?.trim() || undefined);
|
|
573
|
+
const url = new URL(`${baseUrl}/api/v1/webhooks`);
|
|
574
|
+
if (marketplaceId) {
|
|
575
|
+
url.searchParams.set("marketplaceId", marketplaceId);
|
|
576
|
+
}
|
|
577
|
+
let response;
|
|
578
|
+
try {
|
|
579
|
+
response = await fetchFn(url.toString(), {
|
|
580
|
+
method: "GET",
|
|
581
|
+
headers: {
|
|
582
|
+
Authorization: `Bearer ${testKey}`,
|
|
583
|
+
Accept: "application/json",
|
|
584
|
+
},
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
catch (error) {
|
|
588
|
+
const msg = `Failed to reach ${url.toString()}: ${error instanceof Error ? error.message : String(error)}`;
|
|
589
|
+
emitWebhookError(out, err, parsed.json, {
|
|
590
|
+
code: "NETWORK_ERROR",
|
|
591
|
+
error: msg,
|
|
592
|
+
tryThis: `Check your network connection and base URL (${baseUrl}), then retry.`,
|
|
593
|
+
});
|
|
594
|
+
return 1;
|
|
595
|
+
}
|
|
596
|
+
const rawText = await response.text();
|
|
597
|
+
let payload = {};
|
|
598
|
+
try {
|
|
599
|
+
const decoded = parseJsonValue(rawText);
|
|
600
|
+
payload = isJsonObject(decoded) ? decoded : { raw: rawText };
|
|
601
|
+
}
|
|
602
|
+
catch {
|
|
603
|
+
payload = { raw: rawText };
|
|
604
|
+
}
|
|
605
|
+
if (!response.ok) {
|
|
606
|
+
const errorText = isJsonString(payload.error)
|
|
607
|
+
? payload.error
|
|
608
|
+
: `HTTP ${response.status}: ${rawText || "Request failed."}`;
|
|
609
|
+
const tryThisText = isJsonString(payload.tryThis)
|
|
610
|
+
? payload.tryThis
|
|
611
|
+
: "Check your API key permissions (`webhooks`) and base URL, then retry.";
|
|
612
|
+
const codeText = isJsonString(payload.code) ? payload.code : `HTTP_${response.status}`;
|
|
613
|
+
emitWebhookError(out, err, parsed.json, {
|
|
614
|
+
code: codeText,
|
|
615
|
+
error: `${codeText}: ${errorText}`,
|
|
616
|
+
tryThis: tryThisText,
|
|
617
|
+
status: response.status,
|
|
618
|
+
});
|
|
619
|
+
return 1;
|
|
620
|
+
}
|
|
621
|
+
if (parsed.json) {
|
|
622
|
+
out(JSON.stringify(payload, null, 2));
|
|
623
|
+
return 0;
|
|
624
|
+
}
|
|
625
|
+
const rawEndpoints = Array.isArray(payload.endpoints) ? payload.endpoints : [];
|
|
626
|
+
const endpoints = rawEndpoints.filter(isJsonObject);
|
|
627
|
+
const testEndpoints = endpoints.filter((ep) => ep.test === true);
|
|
628
|
+
const liveCount = endpoints.length - testEndpoints.length;
|
|
629
|
+
const rawEventTypes = Array.isArray(payload.eventTypes) ? payload.eventTypes : [];
|
|
630
|
+
const eventTypes = rawEventTypes.length > 0
|
|
631
|
+
? rawEventTypes.filter(isJsonString)
|
|
632
|
+
: [...WEBHOOK_EVENT_TYPES];
|
|
633
|
+
if (testEndpoints.length === 0) {
|
|
634
|
+
out("No test webhook endpoints configured.");
|
|
635
|
+
}
|
|
636
|
+
else {
|
|
637
|
+
out(`Configured test webhook endpoints (${testEndpoints.length}):`);
|
|
638
|
+
for (const ep of testEndpoints) {
|
|
639
|
+
const epEvents = Array.isArray(ep.events)
|
|
640
|
+
? ep.events.filter(isJsonString).join(", ")
|
|
641
|
+
: "";
|
|
642
|
+
const epId = isJsonString(ep.id) ? ep.id : "";
|
|
643
|
+
const epUrl = isJsonString(ep.url) ? ep.url : "";
|
|
644
|
+
out(` - ${epId}: ${epUrl} [${epEvents}]`);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
if (liveCount > 0) {
|
|
648
|
+
out(`(${liveCount} live endpoint${liveCount === 1 ? "" : "s"} also configured on the dashboard)`);
|
|
649
|
+
}
|
|
650
|
+
out(`Supported events (${eventTypes.length}): ${eventTypes.join(", ")}`);
|
|
651
|
+
return 0;
|
|
652
|
+
}
|
|
653
|
+
if (parsed.subcommand === "listen") {
|
|
654
|
+
if (!parsed.forward) {
|
|
655
|
+
emitWebhookError(out, err, parsed.json, {
|
|
656
|
+
code: "MISSING_REQUIRED_FLAG",
|
|
657
|
+
error: "Missing required flag --forward <url>.",
|
|
658
|
+
tryThis: "Pass --forward http://127.0.0.1:3000/api/webhooks/pcific (your local webhook receiver URL).",
|
|
659
|
+
});
|
|
660
|
+
return 1;
|
|
661
|
+
}
|
|
662
|
+
const urlCheck = validateForwardUrl(parsed.forward, parsed.allowRemote);
|
|
663
|
+
if (urlCheck.error) {
|
|
664
|
+
emitWebhookError(out, err, parsed.json, {
|
|
665
|
+
code: urlCheck.code ?? "INVALID_FORWARD_URL",
|
|
666
|
+
error: urlCheck.error,
|
|
667
|
+
tryThis: urlCheck.tryThis ??
|
|
668
|
+
"Pass a valid http:// or https:// localhost URL to --forward.",
|
|
669
|
+
});
|
|
670
|
+
return 1;
|
|
671
|
+
}
|
|
672
|
+
const port = parsed.port ?? 4242;
|
|
673
|
+
const configuredSecret = parsed.secret ?? (env.get("PCIFIC_WEBHOOK_SECRET")?.trim() || undefined);
|
|
674
|
+
const secretWasGenerated = !configuredSecret;
|
|
675
|
+
const secret = configuredSecret ?? generateLocalWebhookSecret();
|
|
676
|
+
const marketplaceId = parsed.marketplaceId ?? (env.get("PCIFIC_MARKETPLACE_ID")?.trim() || undefined);
|
|
677
|
+
let handle;
|
|
678
|
+
try {
|
|
679
|
+
handle = await startWebhookListener({
|
|
680
|
+
forwardUrl: parsed.forward,
|
|
681
|
+
port,
|
|
682
|
+
secret,
|
|
683
|
+
marketplaceId,
|
|
684
|
+
allowRemote: parsed.allowRemote,
|
|
685
|
+
fetch: fetchFn,
|
|
686
|
+
onDelivery: (report) => {
|
|
687
|
+
if (parsed.json) {
|
|
688
|
+
out(JSON.stringify(report));
|
|
689
|
+
}
|
|
690
|
+
else {
|
|
691
|
+
out(formatDeliveryLine(report));
|
|
692
|
+
}
|
|
693
|
+
},
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
catch (error) {
|
|
697
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
698
|
+
emitWebhookError(out, err, parsed.json, {
|
|
699
|
+
code: "LISTENER_START_FAILED",
|
|
700
|
+
error: msg,
|
|
701
|
+
tryThis: "Check that the port is free (or pass --port 0) and that --forward is valid.",
|
|
702
|
+
});
|
|
703
|
+
return 1;
|
|
704
|
+
}
|
|
705
|
+
const displayedSecret = secretWasGenerated ? handle.secret : "[configured]";
|
|
706
|
+
if (parsed.json) {
|
|
707
|
+
const startPayload = JSON.stringify({
|
|
708
|
+
listening: true,
|
|
709
|
+
url: handle.url,
|
|
710
|
+
port: handle.port,
|
|
711
|
+
forwardUrl: handle.forwardUrl,
|
|
712
|
+
secret: displayedSecret,
|
|
713
|
+
});
|
|
714
|
+
if (secretWasGenerated) {
|
|
715
|
+
outRaw(startPayload);
|
|
716
|
+
}
|
|
717
|
+
else {
|
|
718
|
+
out(startPayload);
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
else {
|
|
722
|
+
out(`PCIFIC local webhook listener running on ${handle.url}`);
|
|
723
|
+
out(`Forwarding signed events to: ${handle.forwardUrl}`);
|
|
724
|
+
if (secretWasGenerated) {
|
|
725
|
+
outRaw(`Local signing secret (put in .env as PCIFIC_WEBHOOK_SECRET): ${handle.secret}`);
|
|
726
|
+
}
|
|
727
|
+
else {
|
|
728
|
+
out("Local signing secret: [configured]");
|
|
729
|
+
}
|
|
730
|
+
out(`Trigger via HTTP: POST ${handle.url}/trigger/<eventType>`);
|
|
731
|
+
out("Shortcuts (TTY): [d] dispute_pack.ready [s] safeguard.review_finished [o] orbit.finished [m] message_check.flagged [q] quit");
|
|
732
|
+
}
|
|
733
|
+
const stdin = options.stdin ?? process.stdin;
|
|
734
|
+
return new Promise((resolve) => {
|
|
735
|
+
let closed = false;
|
|
736
|
+
const shutdown = () => {
|
|
737
|
+
if (closed)
|
|
738
|
+
return;
|
|
739
|
+
closed = true;
|
|
740
|
+
enableRawMode(stdin, false);
|
|
741
|
+
stdin.pause();
|
|
742
|
+
process.off("SIGINT", shutdown);
|
|
743
|
+
process.off("SIGTERM", shutdown);
|
|
744
|
+
void handle.close().finally(() => resolve(0));
|
|
745
|
+
};
|
|
746
|
+
process.once("SIGINT", shutdown);
|
|
747
|
+
process.once("SIGTERM", shutdown);
|
|
748
|
+
if (stdin.isTTY) {
|
|
749
|
+
enableRawMode(stdin, true);
|
|
750
|
+
stdin.resume();
|
|
751
|
+
stdin.setEncoding("utf8");
|
|
752
|
+
stdin.on("data", (chunk) => {
|
|
753
|
+
const key = chunk.toLowerCase();
|
|
754
|
+
if (key === "q" || key === "\u0003") {
|
|
755
|
+
shutdown();
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
const eventType = TTY_SHORTCUTS.get(key);
|
|
759
|
+
if (eventType) {
|
|
760
|
+
void handle.deliver(eventType);
|
|
761
|
+
}
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
emitWebhookError(out, err, parsed.json, {
|
|
767
|
+
code: "UNKNOWN_SUBCOMMAND",
|
|
768
|
+
error: `Unknown webhooks subcommand "${parsed.subcommand}". Expected "listen", "trigger", or "list".`,
|
|
769
|
+
tryThis: 'Run "pcific webhooks listen", "pcific webhooks trigger", "pcific webhooks list", or "pcific webhooks --help".',
|
|
770
|
+
});
|
|
771
|
+
return 1;
|
|
772
|
+
}
|