@base44-preview/platform 0.2.0-pr.313.e5d2766 → 0.2.0-pr.319.0f5c92a
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/README.md +58 -2
- package/dist/{modules → client/modules}/builder-socket.js +5 -2
- package/dist/server/errors.d.ts +53 -0
- package/dist/server/errors.js +56 -0
- package/dist/server/errors.types.d.ts +54 -0
- package/dist/server/errors.types.js +1 -0
- package/dist/server/index.d.ts +6 -0
- package/dist/server/index.js +3 -0
- package/dist/server/modules/webhooks-signature.d.ts +11 -0
- package/dist/server/modules/webhooks-signature.js +65 -0
- package/dist/server/modules/webhooks.d.ts +3 -0
- package/dist/server/modules/webhooks.events.generated.d.ts +174 -0
- package/dist/server/modules/webhooks.events.generated.js +3 -0
- package/dist/server/modules/webhooks.js +77 -0
- package/dist/server/modules/webhooks.types.d.ts +182 -0
- package/dist/server/modules/webhooks.types.js +1 -0
- package/dist/server/server-url.d.ts +2 -0
- package/dist/server/server-url.js +8 -0
- package/dist/server/server.d.ts +33 -0
- package/dist/server/server.js +41 -0
- package/dist/server/server.types.d.ts +30 -0
- package/dist/server/server.types.js +1 -0
- package/package.json +22 -7
- /package/dist/{client.d.ts → client/client.d.ts} +0 -0
- /package/dist/{client.js → client/client.js} +0 -0
- /package/dist/{client.types.d.ts → client/client.types.d.ts} +0 -0
- /package/dist/{client.types.js → client/client.types.js} +0 -0
- /package/dist/{errors.d.ts → client/errors.d.ts} +0 -0
- /package/dist/{errors.js → client/errors.js} +0 -0
- /package/dist/{errors.types.d.ts → client/errors.types.d.ts} +0 -0
- /package/dist/{errors.types.js → client/errors.types.js} +0 -0
- /package/dist/{index.d.ts → client/index.d.ts} +0 -0
- /package/dist/{index.js → client/index.js} +0 -0
- /package/dist/{modules → client/modules}/builder-protocol.d.ts +0 -0
- /package/dist/{modules → client/modules}/builder-protocol.js +0 -0
- /package/dist/{modules → client/modules}/builder-socket.d.ts +0 -0
- /package/dist/{modules → client/modules}/builder-subscription.d.ts +0 -0
- /package/dist/{modules → client/modules}/builder-subscription.js +0 -0
- /package/dist/{modules → client/modules}/builder.d.ts +0 -0
- /package/dist/{modules → client/modules}/builder.events.generated.d.ts +0 -0
- /package/dist/{modules → client/modules}/builder.events.generated.js +0 -0
- /package/dist/{modules → client/modules}/builder.events.types.d.ts +0 -0
- /package/dist/{modules → client/modules}/builder.events.types.js +0 -0
- /package/dist/{modules → client/modules}/builder.js +0 -0
- /package/dist/{modules → client/modules}/builder.types.d.ts +0 -0
- /package/dist/{modules → client/modules}/builder.types.js +0 -0
package/README.md
CHANGED
|
@@ -33,6 +33,61 @@ subscription.unsubscribe();
|
|
|
33
33
|
builder.close();
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
+
## Receiving webhooks (server)
|
|
37
|
+
|
|
38
|
+
`@base44/platform/server` verifies Base44 outbound webhooks and answers the endpoint
|
|
39
|
+
activation challenge. It uses WebCrypto only (Node 20+, Deno, Bun, Workers, edge runtimes) and
|
|
40
|
+
makes no network calls: pass your workspace's public keys (`whpk_…`) to each call that verifies.
|
|
41
|
+
|
|
42
|
+
The simplest route is `createHandler`. It reads the raw body, verifies it, answers the
|
|
43
|
+
activation challenge and picks the status code: 400 for a delivery that fails verification,
|
|
44
|
+
500 when your keys are misconfigured or a callback throws (Base44 retries), 204 otherwise,
|
|
45
|
+
including for event types you have no handler for.
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { createPlatformServer } from "@base44/platform/server";
|
|
49
|
+
|
|
50
|
+
const platform = createPlatformServer({
|
|
51
|
+
serverUrl: "https://base44.app",
|
|
52
|
+
apiKey: process.env.BASE44_API_KEY!,
|
|
53
|
+
});
|
|
54
|
+
const publicKeys = process.env.BASE44_WEBHOOK_PUBLIC_KEYS!; // two keys during a rotation
|
|
55
|
+
|
|
56
|
+
export const POST = platform.webhooks.createHandler({
|
|
57
|
+
publicKeys,
|
|
58
|
+
on: {
|
|
59
|
+
"app.deleted.v1": async event => forget(event.data.app_id), // event is narrowed per type
|
|
60
|
+
},
|
|
61
|
+
onEvent: event => log(event.type), // every event, before its handler
|
|
62
|
+
onSuccess: event => {}, // return a Response to replace the 204
|
|
63
|
+
onError: (error, event) => report(error), // return a Response to replace the 400/500
|
|
64
|
+
});
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
For full control, verify and dispatch yourself:
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
export async function POST(request: Request) {
|
|
71
|
+
const rawBody = await request.text(); // exactly as received
|
|
72
|
+
let event;
|
|
73
|
+
try {
|
|
74
|
+
event = await platform.webhooks.verifyEvent(rawBody, request.headers, { publicKeys });
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (error instanceof WebhookVerificationError) return new Response(null, { status: 400 });
|
|
77
|
+
throw error; // missing/malformed keys: a 500, so Base44 retries
|
|
78
|
+
}
|
|
79
|
+
switch (event.type) {
|
|
80
|
+
case "webhook.test.v1": return Response.json({ challenge: event.data.challenge }); // activates the endpoint
|
|
81
|
+
case "app.deleted.v1": await forget(event.data.app_id); break;
|
|
82
|
+
}
|
|
83
|
+
return new Response(null, { status: 204 });
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Delivery is at least once with no ordering guarantee: deduplicate on `event.id`, and answer
|
|
88
|
+
2xx to event types you do not handle. Event types are generated from the schemas published at
|
|
89
|
+
`https://base44.com/webhooks/schemas`; run `npm run generate:webhooks` to refresh them.
|
|
90
|
+
|
|
36
91
|
## Sessions
|
|
37
92
|
|
|
38
93
|
`/api/builder-socket-session` is your backend's route, not an SDK endpoint. It opens a
|
|
@@ -124,7 +179,7 @@ redaction of generated prose or user content.
|
|
|
124
179
|
## Event types
|
|
125
180
|
|
|
126
181
|
The socket protocol is defined by the service's AsyncAPI document, committed as
|
|
127
|
-
`asyncapi.json`. `src/modules/builder.events.generated.ts` is generated from it with
|
|
182
|
+
`asyncapi.json`. `src/client/modules/builder.events.generated.ts` is generated from it with
|
|
128
183
|
`json-schema-to-typescript`: one type per schema, named after the backend model
|
|
129
184
|
(`Message`, `StatusObject`, `QueueState`, one `*Call` per tool, one `*Approval` per
|
|
130
185
|
guard), plus `ServerEventMap` and `ClientMessageMap`. Never edit it by hand.
|
|
@@ -147,7 +202,8 @@ Every exported shape and field has JSDoc. `npm run docs` validates it into `docs
|
|
|
147
202
|
`npm run create-docs` runs the app SDK's TypeDoc and Mintlify pipeline for this package,
|
|
148
203
|
and `npm run copy-docs-local -- --target <mintlify-docs>` copies the result into
|
|
149
204
|
`developers/references/platform-sdk/docs`. The pipeline's config for this package lives
|
|
150
|
-
in `scripts/mintlify-post-processing
|
|
205
|
+
in `scripts/mintlify-post-processing/`, including `reference.ts`, the docs-only entry that combines
|
|
206
|
+
the client and server entrypoints into one reference. The Socket messages page is built in mintlify-docs from
|
|
151
207
|
the service's AsyncAPI document, not here.
|
|
152
208
|
|
|
153
209
|
`PlatformSocketError` extends `Error` with `code` and optional `appId`. Original
|
|
@@ -123,8 +123,11 @@ export class BuilderSocket {
|
|
|
123
123
|
socket.on(name, (raw) => this.roomNotice(code, raw));
|
|
124
124
|
for (const name of eventNames)
|
|
125
125
|
socket.on(name, (raw) => this.appEvent(name, raw));
|
|
126
|
-
|
|
127
|
-
|
|
126
|
+
// An unknown event with no app room (a future session-wide event) has nowhere to go: ignore it.
|
|
127
|
+
socket.onAny((name, raw) => {
|
|
128
|
+
if (isUnknownEvent(name) && appFromRoom(raw === null || raw === void 0 ? void 0 : raw.room))
|
|
129
|
+
this.appEvent(name, raw);
|
|
130
|
+
});
|
|
128
131
|
socket.connect();
|
|
129
132
|
}
|
|
130
133
|
appEvent(name, raw) {
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { WebhookConfigurationErrorCode, WebhookVerificationErrorCode } from "./errors.types.js";
|
|
2
|
+
/**
|
|
3
|
+
* The error the SDK reports when a webhook delivery can't be trusted.
|
|
4
|
+
*
|
|
5
|
+
* You don't create it. The [`verifyEvent()`](/developers/references/platform-sdk/docs/interfaces/webhooks#verifyevent) method rejects with
|
|
6
|
+
* it, and [`createHandler()`](/developers/references/platform-sdk/docs/interfaces/webhooks#createhandler) answers it with a 400 and passes it
|
|
7
|
+
* to your `onError`. Check `code` to see what happened, then look the code up below.
|
|
8
|
+
*
|
|
9
|
+
* The error never carries the request body or its signature.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```typescript
|
|
13
|
+
* // Refuse a delivery that doesn't verify
|
|
14
|
+
* try {
|
|
15
|
+
* const event = await platform.webhooks.verifyEvent(rawBody, request.headers, { publicKeys });
|
|
16
|
+
* } catch (error) {
|
|
17
|
+
* if (error instanceof WebhookVerificationError) {
|
|
18
|
+
* return Response.json({ error: error.code }, { status: 400 });
|
|
19
|
+
* }
|
|
20
|
+
* throw error;
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export declare class WebhookVerificationError extends Error {
|
|
25
|
+
/** What happened. One of the [verification error codes](#webhookverificationerrorcode). */
|
|
26
|
+
readonly code: WebhookVerificationErrorCode;
|
|
27
|
+
/** @internal */
|
|
28
|
+
constructor(code: WebhookVerificationErrorCode);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The error the SDK reports when the public keys you passed can't be used, so no delivery can be verified.
|
|
32
|
+
*
|
|
33
|
+
* You don't create it. The [`verifyEvent()`](/developers/references/platform-sdk/docs/interfaces/webhooks#verifyevent) method rejects with
|
|
34
|
+
* it, and [`createHandler()`](/developers/references/platform-sdk/docs/interfaces/webhooks#createhandler) answers it with a 500 and passes it
|
|
35
|
+
* to your `onError`. Fix the keys, and Base44's retries then succeed.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```typescript
|
|
39
|
+
* // Log a misconfigured deployment, and let it answer 500
|
|
40
|
+
* export const POST = platform.webhooks.createHandler({
|
|
41
|
+
* publicKeys: process.env.BASE44_WEBHOOK_PUBLIC_KEYS,
|
|
42
|
+
* onError(error) {
|
|
43
|
+
* if (error instanceof WebhookConfigurationError) console.error('Check BASE44_WEBHOOK_PUBLIC_KEYS', error.code);
|
|
44
|
+
* },
|
|
45
|
+
* });
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export declare class WebhookConfigurationError extends Error {
|
|
49
|
+
/** What's wrong with the keys. One of the [configuration error codes](#webhookconfigurationerrorcode). */
|
|
50
|
+
readonly code: WebhookConfigurationErrorCode;
|
|
51
|
+
/** @internal */
|
|
52
|
+
constructor(code: WebhookConfigurationErrorCode, detail: string);
|
|
53
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The error the SDK reports when a webhook delivery can't be trusted.
|
|
3
|
+
*
|
|
4
|
+
* You don't create it. The [`verifyEvent()`](/developers/references/platform-sdk/docs/interfaces/webhooks#verifyevent) method rejects with
|
|
5
|
+
* it, and [`createHandler()`](/developers/references/platform-sdk/docs/interfaces/webhooks#createhandler) answers it with a 400 and passes it
|
|
6
|
+
* to your `onError`. Check `code` to see what happened, then look the code up below.
|
|
7
|
+
*
|
|
8
|
+
* The error never carries the request body or its signature.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* // Refuse a delivery that doesn't verify
|
|
13
|
+
* try {
|
|
14
|
+
* const event = await platform.webhooks.verifyEvent(rawBody, request.headers, { publicKeys });
|
|
15
|
+
* } catch (error) {
|
|
16
|
+
* if (error instanceof WebhookVerificationError) {
|
|
17
|
+
* return Response.json({ error: error.code }, { status: 400 });
|
|
18
|
+
* }
|
|
19
|
+
* throw error;
|
|
20
|
+
* }
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
export class WebhookVerificationError extends Error {
|
|
24
|
+
/** @internal */
|
|
25
|
+
constructor(code) {
|
|
26
|
+
super(`Webhook verification failed: ${code}`);
|
|
27
|
+
this.name = "WebhookVerificationError";
|
|
28
|
+
this.code = code;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The error the SDK reports when the public keys you passed can't be used, so no delivery can be verified.
|
|
33
|
+
*
|
|
34
|
+
* You don't create it. The [`verifyEvent()`](/developers/references/platform-sdk/docs/interfaces/webhooks#verifyevent) method rejects with
|
|
35
|
+
* it, and [`createHandler()`](/developers/references/platform-sdk/docs/interfaces/webhooks#createhandler) answers it with a 500 and passes it
|
|
36
|
+
* to your `onError`. Fix the keys, and Base44's retries then succeed.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```typescript
|
|
40
|
+
* // Log a misconfigured deployment, and let it answer 500
|
|
41
|
+
* export const POST = platform.webhooks.createHandler({
|
|
42
|
+
* publicKeys: process.env.BASE44_WEBHOOK_PUBLIC_KEYS,
|
|
43
|
+
* onError(error) {
|
|
44
|
+
* if (error instanceof WebhookConfigurationError) console.error('Check BASE44_WEBHOOK_PUBLIC_KEYS', error.code);
|
|
45
|
+
* },
|
|
46
|
+
* });
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
export class WebhookConfigurationError extends Error {
|
|
50
|
+
/** @internal */
|
|
51
|
+
constructor(code, detail) {
|
|
52
|
+
super(`Webhook configuration: ${detail}`);
|
|
53
|
+
this.name = "WebhookConfigurationError";
|
|
54
|
+
this.code = code;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codes of errors for a delivery that can't be trusted. Answer these with a 400. Base44 treats the
|
|
3
|
+
* request as failed and retries it, and a genuine delivery verifies on the retry.
|
|
4
|
+
*/
|
|
5
|
+
export type WebhookVerificationErrorCode =
|
|
6
|
+
/**
|
|
7
|
+
* The request is missing one of the `webhook-id`, `webhook-timestamp` or `webhook-signature` headers.
|
|
8
|
+
*
|
|
9
|
+
* Check that a proxy in front of your endpoint forwards all request headers.
|
|
10
|
+
*/
|
|
11
|
+
"missing_headers"
|
|
12
|
+
/**
|
|
13
|
+
* The `webhook-timestamp` header is more than `toleranceSeconds` (300 by default) away from your server's clock, or isn't a number.
|
|
14
|
+
*
|
|
15
|
+
* Check your server's clock. A replayed old delivery fails this way too.
|
|
16
|
+
*/
|
|
17
|
+
| "timestamp_outside_tolerance"
|
|
18
|
+
/**
|
|
19
|
+
* The `webhook-signature` header has no signature in the `v1a` scheme Base44 uses.
|
|
20
|
+
*
|
|
21
|
+
* The request didn't come from Base44, or a proxy rewrote the header.
|
|
22
|
+
*/
|
|
23
|
+
| "no_signature_entries"
|
|
24
|
+
/**
|
|
25
|
+
* No signature matches any of your public keys.
|
|
26
|
+
*
|
|
27
|
+
* Check that you pass the request body exactly as received. Parsing the JSON and serializing it again
|
|
28
|
+
* changes the bytes. Also check that your public keys belong to the workspace that sends the webhook.
|
|
29
|
+
*/
|
|
30
|
+
| "signature_mismatch"
|
|
31
|
+
/**
|
|
32
|
+
* The signature is valid, but the body isn't a JSON event.
|
|
33
|
+
*
|
|
34
|
+
* This shouldn't happen with deliveries from Base44.
|
|
35
|
+
*/
|
|
36
|
+
| "invalid_payload";
|
|
37
|
+
/**
|
|
38
|
+
* Codes of errors that stop verification before it starts, because the public keys you passed can't
|
|
39
|
+
* be used. They're about your deployment, not the request, so let them surface as a 500. Base44 then
|
|
40
|
+
* retries the delivery, and it succeeds once you fix the keys.
|
|
41
|
+
*/
|
|
42
|
+
export type WebhookConfigurationErrorCode =
|
|
43
|
+
/**
|
|
44
|
+
* No public keys were passed, for example because an environment variable is unset.
|
|
45
|
+
*
|
|
46
|
+
* Pass your workspace's public keys to `verifyEvent()` or `createHandler()`.
|
|
47
|
+
*/
|
|
48
|
+
"missing_public_keys"
|
|
49
|
+
/**
|
|
50
|
+
* A public key isn't a base64-encoded 32-byte Ed25519 key, with or without the `whpk_` prefix.
|
|
51
|
+
*
|
|
52
|
+
* Copy the key again. A truncated key fails this way.
|
|
53
|
+
*/
|
|
54
|
+
| "invalid_public_key";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Server platform modules, authenticated with a workspace API key. */
|
|
2
|
+
export { createPlatformServer } from "./server.js";
|
|
3
|
+
export { WebhookConfigurationError, WebhookVerificationError } from "./errors.js";
|
|
4
|
+
export type { WebhookConfigurationErrorCode, WebhookVerificationErrorCode } from "./errors.types.js";
|
|
5
|
+
export type { PlatformServer, PlatformServerOptions } from "./server.types.js";
|
|
6
|
+
export type { AppCreatedV1Data, AppDeletedV1Data, AppPublishedV1Data, AppRestoredV1Data, AppUnpublishedV1Data, CloudEvent, CreateHandlerOptions, DeliveredWebhookEvent, VerifyEventOptions, WebhookEventHandlers, WebhookEvent, WebhookEventMap, WebhookEventType, WebhookHeaders, WebhookPublicKeys, WebhooksModule, WebhookTestV1Data, } from "./modules/webhooks.types.js";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { WebhookHeaders, WebhookPublicKeys } from "./webhooks.types.js";
|
|
2
|
+
/** Split the configured keys into raw 32-byte Ed25519 keys. A truncated paste throws: a wrong key reads as every event being forged. */
|
|
3
|
+
export declare function parsePublicKeys(keys: WebhookPublicKeys | undefined): Uint8Array[];
|
|
4
|
+
export declare function importPublicKey(raw: Uint8Array): Promise<CryptoKey>;
|
|
5
|
+
/** Read one header from a `Headers` or a Node-style object. */
|
|
6
|
+
export declare function readHeader(headers: WebhookHeaders, name: string, separator?: string): string | null;
|
|
7
|
+
/** The `v1a,<base64>` entries of a `webhook-signature` header, decoded. */
|
|
8
|
+
export declare function parseSignatures(header: string): Uint8Array[];
|
|
9
|
+
/** The signed bytes: `<id>.<timestamp>.<raw body>`. */
|
|
10
|
+
export declare function signedPayload(id: string, timestamp: string, body: string | Uint8Array): Uint8Array;
|
|
11
|
+
export declare function anySignatureVerifies(keys: CryptoKey[], signatures: Uint8Array[], payload: Uint8Array): Promise<boolean>;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { WebhookConfigurationError } from "../errors.js";
|
|
2
|
+
const SIGNATURE_SCHEME = "v1a";
|
|
3
|
+
const encoder = new TextEncoder();
|
|
4
|
+
/** Standard base64 to bytes, or `null` when it is not valid base64. */
|
|
5
|
+
function decodeBase64(value) {
|
|
6
|
+
try {
|
|
7
|
+
const binary = atob(value);
|
|
8
|
+
return Uint8Array.from(binary, char => char.charCodeAt(0));
|
|
9
|
+
}
|
|
10
|
+
catch (_a) {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** Split the configured keys into raw 32-byte Ed25519 keys. A truncated paste throws: a wrong key reads as every event being forged. */
|
|
15
|
+
export function parsePublicKeys(keys) {
|
|
16
|
+
const entries = (Array.isArray(keys) ? keys : (keys !== null && keys !== void 0 ? keys : "").split(/[\s,]+/)).map(key => key.trim()).filter(Boolean);
|
|
17
|
+
if (entries.length === 0)
|
|
18
|
+
throw new WebhookConfigurationError("missing_public_keys", "no public keys were provided");
|
|
19
|
+
return entries.map(entry => {
|
|
20
|
+
const raw = decodeBase64(entry.replace(/^whpk_/, ""));
|
|
21
|
+
if (!raw || raw.length !== 32) {
|
|
22
|
+
throw new WebhookConfigurationError("invalid_public_key", "a public key is not a base64-encoded 32-byte Ed25519 key");
|
|
23
|
+
}
|
|
24
|
+
return raw;
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
export function importPublicKey(raw) {
|
|
28
|
+
return crypto.subtle.importKey("raw", raw, "Ed25519", false, ["verify"]);
|
|
29
|
+
}
|
|
30
|
+
/** Read one header from a `Headers` or a Node-style object. */
|
|
31
|
+
export function readHeader(headers, name, separator = ", ") {
|
|
32
|
+
if (typeof headers.get === "function")
|
|
33
|
+
return headers.get(name);
|
|
34
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
35
|
+
if (key.toLowerCase() === name && value !== undefined)
|
|
36
|
+
return Array.isArray(value) ? value.join(separator) : value;
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
/** The `v1a,<base64>` entries of a `webhook-signature` header, decoded. */
|
|
41
|
+
export function parseSignatures(header) {
|
|
42
|
+
return header
|
|
43
|
+
.split(" ")
|
|
44
|
+
.filter(entry => entry.startsWith(`${SIGNATURE_SCHEME},`))
|
|
45
|
+
.map(entry => decodeBase64(entry.slice(SIGNATURE_SCHEME.length + 1)))
|
|
46
|
+
.filter((signature) => signature !== null);
|
|
47
|
+
}
|
|
48
|
+
/** The signed bytes: `<id>.<timestamp>.<raw body>`. */
|
|
49
|
+
export function signedPayload(id, timestamp, body) {
|
|
50
|
+
const prefix = encoder.encode(`${id}.${timestamp}.`);
|
|
51
|
+
const bytes = typeof body === "string" ? encoder.encode(body) : body;
|
|
52
|
+
const payload = new Uint8Array(prefix.length + bytes.length);
|
|
53
|
+
payload.set(prefix);
|
|
54
|
+
payload.set(bytes, prefix.length);
|
|
55
|
+
return payload;
|
|
56
|
+
}
|
|
57
|
+
export async function anySignatureVerifies(keys, signatures, payload) {
|
|
58
|
+
for (const key of keys) {
|
|
59
|
+
for (const signature of signatures) {
|
|
60
|
+
if (await crypto.subtle.verify("Ed25519", key, signature, payload))
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `data` object of `app.created.v1`. An app was created.
|
|
3
|
+
*/
|
|
4
|
+
export interface AppCreatedV1Data {
|
|
5
|
+
/**
|
|
6
|
+
* The app the event is about.
|
|
7
|
+
*/
|
|
8
|
+
app_id: string;
|
|
9
|
+
/**
|
|
10
|
+
* The workspace the app belongs to.
|
|
11
|
+
*/
|
|
12
|
+
workspace_id: string;
|
|
13
|
+
/**
|
|
14
|
+
* Opaque platform id of the app's current owner.
|
|
15
|
+
*/
|
|
16
|
+
owner_id: string;
|
|
17
|
+
/**
|
|
18
|
+
* Your own handle for the owner: the `service_external_id` you gave when you created that service user. Absent when the owner is not a service user.
|
|
19
|
+
*/
|
|
20
|
+
owner_service_external_id?: string;
|
|
21
|
+
/**
|
|
22
|
+
* The kind of app. New values arrive as a new event version.
|
|
23
|
+
*/
|
|
24
|
+
app_type: "imported_app" | "user_agent" | "user_app" | "user_game";
|
|
25
|
+
/**
|
|
26
|
+
* When the app was created (UTC).
|
|
27
|
+
*/
|
|
28
|
+
created_at: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The `data` object of `app.published.v1`. An app version was published.
|
|
32
|
+
*/
|
|
33
|
+
export interface AppPublishedV1Data {
|
|
34
|
+
/**
|
|
35
|
+
* The app the event is about.
|
|
36
|
+
*/
|
|
37
|
+
app_id: string;
|
|
38
|
+
/**
|
|
39
|
+
* The workspace the app belongs to.
|
|
40
|
+
*/
|
|
41
|
+
workspace_id: string;
|
|
42
|
+
/**
|
|
43
|
+
* Opaque platform id of the app's current owner.
|
|
44
|
+
*/
|
|
45
|
+
owner_id: string;
|
|
46
|
+
/**
|
|
47
|
+
* Your own handle for the owner: the `service_external_id` you gave when you created that service user. Absent when the owner is not a service user.
|
|
48
|
+
*/
|
|
49
|
+
owner_service_external_id?: string;
|
|
50
|
+
/**
|
|
51
|
+
* Id of the version now live.
|
|
52
|
+
*/
|
|
53
|
+
published_version: string;
|
|
54
|
+
/**
|
|
55
|
+
* When the version went live (UTC).
|
|
56
|
+
*/
|
|
57
|
+
published_at: string;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The `data` object of `app.unpublished.v1`. An app was taken offline.
|
|
61
|
+
*/
|
|
62
|
+
export interface AppUnpublishedV1Data {
|
|
63
|
+
/**
|
|
64
|
+
* The app the event is about.
|
|
65
|
+
*/
|
|
66
|
+
app_id: string;
|
|
67
|
+
/**
|
|
68
|
+
* The workspace the app belongs to.
|
|
69
|
+
*/
|
|
70
|
+
workspace_id: string;
|
|
71
|
+
/**
|
|
72
|
+
* Opaque platform id of the app's current owner.
|
|
73
|
+
*/
|
|
74
|
+
owner_id: string;
|
|
75
|
+
/**
|
|
76
|
+
* Your own handle for the owner: the `service_external_id` you gave when you created that service user. Absent when the owner is not a service user.
|
|
77
|
+
*/
|
|
78
|
+
owner_service_external_id?: string;
|
|
79
|
+
/**
|
|
80
|
+
* When the app was taken offline (UTC).
|
|
81
|
+
*/
|
|
82
|
+
unpublished_at: string;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Tombstone identifiers only.
|
|
86
|
+
*
|
|
87
|
+
* Deletion is **not** erasure: the app moves to trash and is self-serve
|
|
88
|
+
* restorable for 30 days, with unbounded restore through support. A receiver
|
|
89
|
+
* that purges on this event will be wrong for every restored app, which is why
|
|
90
|
+
* ``app.restored.v1`` exists and why this is documented as a trash signal.
|
|
91
|
+
*/
|
|
92
|
+
export interface AppDeletedV1Data {
|
|
93
|
+
/**
|
|
94
|
+
* The app the event is about.
|
|
95
|
+
*/
|
|
96
|
+
app_id: string;
|
|
97
|
+
/**
|
|
98
|
+
* The workspace the app belongs to.
|
|
99
|
+
*/
|
|
100
|
+
workspace_id: string;
|
|
101
|
+
/**
|
|
102
|
+
* Opaque platform id of the app's current owner.
|
|
103
|
+
*/
|
|
104
|
+
owner_id: string;
|
|
105
|
+
/**
|
|
106
|
+
* Your own handle for the owner: the `service_external_id` you gave when you created that service user. Absent when the owner is not a service user.
|
|
107
|
+
*/
|
|
108
|
+
owner_service_external_id?: string;
|
|
109
|
+
/**
|
|
110
|
+
* When the app was moved to trash (UTC). It can still be restored.
|
|
111
|
+
*/
|
|
112
|
+
deleted_at: string;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* The `data` object of `app.restored.v1`. An app was restored from trash.
|
|
116
|
+
*/
|
|
117
|
+
export interface AppRestoredV1Data {
|
|
118
|
+
/**
|
|
119
|
+
* The app the event is about.
|
|
120
|
+
*/
|
|
121
|
+
app_id: string;
|
|
122
|
+
/**
|
|
123
|
+
* The workspace the app belongs to.
|
|
124
|
+
*/
|
|
125
|
+
workspace_id: string;
|
|
126
|
+
/**
|
|
127
|
+
* Opaque platform id of the app's current owner.
|
|
128
|
+
*/
|
|
129
|
+
owner_id: string;
|
|
130
|
+
/**
|
|
131
|
+
* Your own handle for the owner: the `service_external_id` you gave when you created that service user. Absent when the owner is not a service user.
|
|
132
|
+
*/
|
|
133
|
+
owner_service_external_id?: string;
|
|
134
|
+
/**
|
|
135
|
+
* When the app was restored (UTC).
|
|
136
|
+
*/
|
|
137
|
+
restored_at: string;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Carries no domain data — its only job is to be verifiable and echoed.
|
|
141
|
+
*/
|
|
142
|
+
export interface WebhookTestV1Data {
|
|
143
|
+
/**
|
|
144
|
+
* The endpoint being activated.
|
|
145
|
+
*/
|
|
146
|
+
endpoint_id: string;
|
|
147
|
+
/**
|
|
148
|
+
* The workspace the endpoint belongs to.
|
|
149
|
+
*/
|
|
150
|
+
workspace_id: string;
|
|
151
|
+
/**
|
|
152
|
+
* When the test was sent (UTC).
|
|
153
|
+
*/
|
|
154
|
+
sent_at: string;
|
|
155
|
+
/**
|
|
156
|
+
* Return this value in your response body to activate the endpoint.
|
|
157
|
+
*/
|
|
158
|
+
challenge: string;
|
|
159
|
+
}
|
|
160
|
+
/** Every event type Base44 sends, mapped to the shape of its `data` object. */
|
|
161
|
+
export interface WebhookEventMap {
|
|
162
|
+
/** An app was created. */
|
|
163
|
+
"app.created.v1": AppCreatedV1Data;
|
|
164
|
+
/** An app version was published. */
|
|
165
|
+
"app.published.v1": AppPublishedV1Data;
|
|
166
|
+
/** An app was taken offline. */
|
|
167
|
+
"app.unpublished.v1": AppUnpublishedV1Data;
|
|
168
|
+
/** Tombstone identifiers only. */
|
|
169
|
+
"app.deleted.v1": AppDeletedV1Data;
|
|
170
|
+
/** An app was restored from trash. */
|
|
171
|
+
"app.restored.v1": AppRestoredV1Data;
|
|
172
|
+
/** Carries no domain data — its only job is to be verifiable and echoed. */
|
|
173
|
+
"webhook.test.v1": WebhookTestV1Data;
|
|
174
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { WebhookConfigurationError, WebhookVerificationError } from "../errors.js";
|
|
2
|
+
import { anySignatureVerifies, importPublicKey, parsePublicKeys, parseSignatures, readHeader, signedPayload } from "./webhooks-signature.js";
|
|
3
|
+
const DEFAULT_TOLERANCE_SECONDS = 300;
|
|
4
|
+
/** Webhook receiving utilities. Verification is local: no network calls, no timers. */
|
|
5
|
+
export function createWebhooks() {
|
|
6
|
+
// Imported keys are cached by their wire form so a pinned key is imported once.
|
|
7
|
+
const imported = new Map();
|
|
8
|
+
const keysFor = (publicKeys) => Promise.all(parsePublicKeys(publicKeys).map(raw => {
|
|
9
|
+
const id = raw.join(",");
|
|
10
|
+
if (!imported.has(id))
|
|
11
|
+
imported.set(id, importPublicKey(raw));
|
|
12
|
+
return imported.get(id);
|
|
13
|
+
}));
|
|
14
|
+
const verifyEvent = async (body, headers, verifyOptions) => {
|
|
15
|
+
var _a;
|
|
16
|
+
// Configuration problems surface first, whatever the request looks like: a missing key is ours to fix.
|
|
17
|
+
const keys = await keysFor(verifyOptions === null || verifyOptions === void 0 ? void 0 : verifyOptions.publicKeys);
|
|
18
|
+
const id = readHeader(headers, "webhook-id");
|
|
19
|
+
const timestamp = readHeader(headers, "webhook-timestamp");
|
|
20
|
+
const signature = readHeader(headers, "webhook-signature", " ");
|
|
21
|
+
if (!id || !timestamp || !signature)
|
|
22
|
+
throw new WebhookVerificationError("missing_headers");
|
|
23
|
+
// Negated so a non-numeric timestamp (NaN) is refused too.
|
|
24
|
+
if (!(Math.abs(Date.now() / 1000 - Number(timestamp)) <= ((_a = verifyOptions === null || verifyOptions === void 0 ? void 0 : verifyOptions.toleranceSeconds) !== null && _a !== void 0 ? _a : DEFAULT_TOLERANCE_SECONDS))) {
|
|
25
|
+
throw new WebhookVerificationError("timestamp_outside_tolerance");
|
|
26
|
+
}
|
|
27
|
+
const signatures = parseSignatures(signature);
|
|
28
|
+
if (signatures.length === 0)
|
|
29
|
+
throw new WebhookVerificationError("no_signature_entries");
|
|
30
|
+
if (!(await anySignatureVerifies(keys, signatures, signedPayload(id, timestamp, body)))) {
|
|
31
|
+
throw new WebhookVerificationError("signature_mismatch");
|
|
32
|
+
}
|
|
33
|
+
// Only now is the body trusted enough to parse.
|
|
34
|
+
let event;
|
|
35
|
+
try {
|
|
36
|
+
event = JSON.parse(typeof body === "string" ? body : new TextDecoder().decode(body));
|
|
37
|
+
}
|
|
38
|
+
catch (_b) {
|
|
39
|
+
throw new WebhookVerificationError("invalid_payload");
|
|
40
|
+
}
|
|
41
|
+
const { type, id: eventId, data } = (event !== null && event !== void 0 ? event : {});
|
|
42
|
+
if (typeof type !== "string" || typeof eventId !== "string" || typeof data !== "object" || data === null) {
|
|
43
|
+
throw new WebhookVerificationError("invalid_payload");
|
|
44
|
+
}
|
|
45
|
+
return event;
|
|
46
|
+
};
|
|
47
|
+
return {
|
|
48
|
+
verifyEvent,
|
|
49
|
+
createHandler({ on = {}, onEvent, onSuccess, onError, ...verifyOptions }) {
|
|
50
|
+
const fail = async (error, status, event) => {
|
|
51
|
+
var _a;
|
|
52
|
+
return (_a = (await (onError === null || onError === void 0 ? void 0 : onError(error, event)))) !== null && _a !== void 0 ? _a : Response.json({ error: error instanceof WebhookVerificationError ? error.code : error instanceof WebhookConfigurationError ? "receiver_misconfigured" : "handler_failed" }, { status });
|
|
53
|
+
};
|
|
54
|
+
return async (request) => {
|
|
55
|
+
var _a, _b;
|
|
56
|
+
let event;
|
|
57
|
+
try {
|
|
58
|
+
event = await verifyEvent(new Uint8Array(await request.arrayBuffer()), request.headers, verifyOptions);
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
return fail(error, error instanceof WebhookVerificationError ? 400 : 500);
|
|
62
|
+
}
|
|
63
|
+
// Activation probe: echo the challenge, only after the signature verified. Never reaches your callbacks.
|
|
64
|
+
if (event.type === "webhook.test.v1")
|
|
65
|
+
return Response.json({ challenge: event.data.challenge });
|
|
66
|
+
try {
|
|
67
|
+
await (onEvent === null || onEvent === void 0 ? void 0 : onEvent(event));
|
|
68
|
+
await ((_a = on[event.type]) === null || _a === void 0 ? void 0 : _a.call(on, event));
|
|
69
|
+
return (_b = (await (onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(event)))) !== null && _b !== void 0 ? _b : new Response(null, { status: 204 });
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
return fail(error, 500, event);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import type { WebhookEventMap, WebhookTestV1Data } from "./webhooks.events.generated.js";
|
|
2
|
+
export type * from "./webhooks.events.generated.js";
|
|
3
|
+
/** Name of a webhook event, such as `app.deleted.v1`. The version is part of the name. */
|
|
4
|
+
export type WebhookEventType = keyof WebhookEventMap;
|
|
5
|
+
/** The CloudEvents 1.0 envelope every webhook arrives in. Its `data` depends on `type`. */
|
|
6
|
+
export interface CloudEvent<TType extends string, TData> {
|
|
7
|
+
/** CloudEvents version. Always `1.0`. */
|
|
8
|
+
specversion: "1.0";
|
|
9
|
+
/** Unique event ID, starting with `evt_`. A redelivery keeps the same ID, so use it to skip events you already handled. */
|
|
10
|
+
id: string;
|
|
11
|
+
/** URL of the workspace the event happened in. */
|
|
12
|
+
source: string;
|
|
13
|
+
/** Event type, including its version. */
|
|
14
|
+
type: TType;
|
|
15
|
+
/** The resource the event is about, such as `apps/<app ID>`. */
|
|
16
|
+
subject: string;
|
|
17
|
+
/** When the event happened, as an RFC 3339 timestamp in UTC. */
|
|
18
|
+
time: string;
|
|
19
|
+
/** Content type of `data`. Always `application/json`. */
|
|
20
|
+
datacontenttype: string;
|
|
21
|
+
/** URL of the JSON Schema that describes `data`. */
|
|
22
|
+
dataschema: string;
|
|
23
|
+
/** W3C trace context, when the event was produced inside a trace. */
|
|
24
|
+
traceparent?: string;
|
|
25
|
+
/** W3C trace state, when the event was produced inside a trace. */
|
|
26
|
+
tracestate?: string;
|
|
27
|
+
/** Kind of actor that caused the event. */
|
|
28
|
+
authtype: string;
|
|
29
|
+
/** ID of the actor that caused the event. */
|
|
30
|
+
authid: string;
|
|
31
|
+
/** The event's payload. Its shape depends on `type`. */
|
|
32
|
+
data: TData;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* A verified webhook event.
|
|
36
|
+
*
|
|
37
|
+
* Check `type` to narrow `data` to that event's payload. Base44 can add event types later, so give a
|
|
38
|
+
* `switch` a default branch that still answers 2xx. A non-2xx answer makes Base44 retry the delivery.
|
|
39
|
+
*/
|
|
40
|
+
export type WebhookEvent = {
|
|
41
|
+
[K in WebhookEventType]: CloudEvent<K, WebhookEventMap[K]>;
|
|
42
|
+
}[WebhookEventType];
|
|
43
|
+
/** Request headers, as a fetch `Headers` object or a Node.js-style object. Header names are case-insensitive. */
|
|
44
|
+
export type WebhookHeaders = Headers | Record<string, string | string[] | undefined>;
|
|
45
|
+
/** One Ed25519 public key, starting with `whpk_`, or several in an array or separated by commas or whitespace. */
|
|
46
|
+
export type WebhookPublicKeys = string | string[];
|
|
47
|
+
/** Options for {@linkcode WebhooksModule.verifyEvent | verifyEvent()}. */
|
|
48
|
+
export interface VerifyEventOptions {
|
|
49
|
+
/**
|
|
50
|
+
* Your workspace's public keys.
|
|
51
|
+
*
|
|
52
|
+
* Pass both the old and the new key while a key rotation is in progress. Missing or malformed keys
|
|
53
|
+
* reject with `WebhookConfigurationError`.
|
|
54
|
+
*/
|
|
55
|
+
publicKeys: WebhookPublicKeys;
|
|
56
|
+
/** How far, in seconds, a delivery's timestamp can be from your server's clock. Defaults to `300`. */
|
|
57
|
+
toleranceSeconds?: number;
|
|
58
|
+
}
|
|
59
|
+
/** An event your callbacks receive. Every event except the `webhook.test.v1` activation probe, which the handler answers itself. */
|
|
60
|
+
export type DeliveredWebhookEvent = Exclude<WebhookEvent, CloudEvent<"webhook.test.v1", WebhookTestV1Data>>;
|
|
61
|
+
/** Handlers keyed by event type. Each handler receives the event narrowed to its type. */
|
|
62
|
+
export type WebhookEventHandlers = {
|
|
63
|
+
[K in DeliveredWebhookEvent["type"]]?: (event: Extract<DeliveredWebhookEvent, {
|
|
64
|
+
type: K;
|
|
65
|
+
}>) => unknown;
|
|
66
|
+
};
|
|
67
|
+
/** Options for {@linkcode WebhooksModule.createHandler | createHandler()}. Every callback can be async. */
|
|
68
|
+
export interface CreateHandlerOptions extends VerifyEventOptions {
|
|
69
|
+
/** Handlers keyed by event type. Events without a handler are still answered 2xx, so Base44 doesn't retry them. */
|
|
70
|
+
on?: WebhookEventHandlers;
|
|
71
|
+
/** Called for every verified event, before its handler in `on`. */
|
|
72
|
+
onEvent?: (event: DeliveredWebhookEvent) => unknown;
|
|
73
|
+
/**
|
|
74
|
+
* Called after `onEvent` and the event's handler finish without throwing.
|
|
75
|
+
*
|
|
76
|
+
* Return a `Response` to replace the default empty 204.
|
|
77
|
+
*/
|
|
78
|
+
onSuccess?: (event: DeliveredWebhookEvent) => Response | void | Promise<Response | void>;
|
|
79
|
+
/**
|
|
80
|
+
* Called when a delivery fails.
|
|
81
|
+
*
|
|
82
|
+
* The handler answers a `WebhookVerificationError` with a 400. It answers a `WebhookConfigurationError`,
|
|
83
|
+
* or anything a callback throws, with a 500 so Base44 retries. The `event` argument is set when the
|
|
84
|
+
* delivery verified and a callback failed. Return a `Response` to replace the default answer.
|
|
85
|
+
*/
|
|
86
|
+
onError?: (error: unknown, event?: DeliveredWebhookEvent) => Response | void | Promise<Response | void>;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Webhooks module for receiving the events Base44 sends to your server.
|
|
90
|
+
*
|
|
91
|
+
* Base44 sends a signed event to your endpoint when something happens in your workspace:
|
|
92
|
+
* - An app is created, published, unpublished, moved to trash or restored.
|
|
93
|
+
* - Base44 tests a new endpoint before activating it.
|
|
94
|
+
*
|
|
95
|
+
* The module verifies each delivery's signature with your workspace's public keys, and gives you
|
|
96
|
+
* the event with its payload typed. It runs on Node.js 20 and later and on edge runtimes, and makes
|
|
97
|
+
* no network requests.
|
|
98
|
+
*
|
|
99
|
+
* Use {@linkcode createHandler | createHandler()} for a ready-made route handler, or
|
|
100
|
+
* {@linkcode verifyEvent | verifyEvent()} to handle the request yourself. Base44 delivers each event at
|
|
101
|
+
* least once and in no guaranteed order, so skip events whose `id` you already handled.
|
|
102
|
+
*/
|
|
103
|
+
export interface WebhooksModule {
|
|
104
|
+
/**
|
|
105
|
+
* Verifies a delivery and returns its event.
|
|
106
|
+
*
|
|
107
|
+
* Pass the request body exactly as received, before any JSON parsing, because the signature covers
|
|
108
|
+
* its exact bytes. Nothing is parsed until the signature checks out.
|
|
109
|
+
*
|
|
110
|
+
* To activate a new endpoint, answer the `webhook.test.v1` event with
|
|
111
|
+
* `{ "challenge": event.data.challenge }` within 5 seconds. Answer every other event with a 2xx.
|
|
112
|
+
*
|
|
113
|
+
* @param body - The raw request body, as text or bytes.
|
|
114
|
+
* @param headers - The request headers.
|
|
115
|
+
* @param options - Verification options, including your public keys.
|
|
116
|
+
* @returns Promise resolving to the verified event.
|
|
117
|
+
* @throws {WebhookVerificationError} When the delivery can't be trusted. Answer with a 400.
|
|
118
|
+
* @throws {WebhookConfigurationError} When the public keys are missing or malformed. Let it surface as a 500.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* ```typescript
|
|
122
|
+
* // Verify the request and handle each event type
|
|
123
|
+
* export async function POST(request) {
|
|
124
|
+
* const rawBody = await request.text();
|
|
125
|
+
* let event;
|
|
126
|
+
* try {
|
|
127
|
+
* event = await platform.webhooks.verifyEvent(rawBody, request.headers, {
|
|
128
|
+
* publicKeys: process.env.BASE44_WEBHOOK_PUBLIC_KEYS,
|
|
129
|
+
* });
|
|
130
|
+
* } catch (error) {
|
|
131
|
+
* if (error instanceof WebhookVerificationError) return new Response(null, { status: 400 });
|
|
132
|
+
* throw error;
|
|
133
|
+
* }
|
|
134
|
+
*
|
|
135
|
+
* switch (event.type) {
|
|
136
|
+
* case 'webhook.test.v1':
|
|
137
|
+
* return Response.json({ challenge: event.data.challenge });
|
|
138
|
+
* case 'app.deleted.v1':
|
|
139
|
+
* await removeApp(event.data.app_id);
|
|
140
|
+
* break;
|
|
141
|
+
* }
|
|
142
|
+
* return new Response(null, { status: 204 });
|
|
143
|
+
* }
|
|
144
|
+
* ```
|
|
145
|
+
*/
|
|
146
|
+
verifyEvent(body: string | Uint8Array, headers: WebhookHeaders, options: VerifyEventOptions): Promise<WebhookEvent>;
|
|
147
|
+
/**
|
|
148
|
+
* Creates a route handler that verifies deliveries and calls your handlers.
|
|
149
|
+
*
|
|
150
|
+
* The handler takes a fetch `Request` and returns a `Response`, so it works as a Next.js route
|
|
151
|
+
* handler and in Hono, Cloudflare Workers, Deno and Bun. For each request it reads the raw body,
|
|
152
|
+
* verifies it, answers the activation probe itself, and then calls `onEvent`, the event's handler in
|
|
153
|
+
* `on`, and `onSuccess`, in that order.
|
|
154
|
+
*
|
|
155
|
+
* It answers with:
|
|
156
|
+
* - 204 when the event was handled, including events with no handler.
|
|
157
|
+
* - 400 when the delivery doesn't verify.
|
|
158
|
+
* - 500 when the public keys are misconfigured or a callback throws. Base44 then retries.
|
|
159
|
+
*
|
|
160
|
+
* Base44 can deliver the same event more than once, so make your handlers safe to run twice for the
|
|
161
|
+
* same `event.id`.
|
|
162
|
+
*
|
|
163
|
+
* @param options - Your public keys, handlers and callbacks.
|
|
164
|
+
* @returns A function that takes a `Request` and resolves to the `Response` to send.
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* ```typescript
|
|
168
|
+
* // Handle app events in a Next.js route
|
|
169
|
+
* export const POST = platform.webhooks.createHandler({
|
|
170
|
+
* publicKeys: process.env.BASE44_WEBHOOK_PUBLIC_KEYS,
|
|
171
|
+
* on: {
|
|
172
|
+
* 'app.deleted.v1': async (event) => removeApp(event.data.app_id),
|
|
173
|
+
* 'app.published.v1': async (event) => refreshApp(event.data.app_id),
|
|
174
|
+
* },
|
|
175
|
+
* onError(error, event) {
|
|
176
|
+
* console.error('Webhook failed', event?.id, error);
|
|
177
|
+
* },
|
|
178
|
+
* });
|
|
179
|
+
* ```
|
|
180
|
+
*/
|
|
181
|
+
createHandler(options: CreateHandlerOptions): (request: Request) => Promise<Response>;
|
|
182
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Validate a platform origin and return it normalized. Used by the server entrypoint. */
|
|
2
|
+
export function normalizeServerUrl(serverUrl) {
|
|
3
|
+
const url = new URL(serverUrl);
|
|
4
|
+
if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
|
|
5
|
+
throw new TypeError("serverUrl must be an HTTP(S) origin without credentials, path, query or fragment");
|
|
6
|
+
}
|
|
7
|
+
return url.origin;
|
|
8
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { PlatformServer, PlatformServerOptions } from "./server.types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Creates a platform server client.
|
|
4
|
+
*
|
|
5
|
+
* This is the entry point of the Platform SDK on your backend. Import it from
|
|
6
|
+
* `@base44/platform/server`. The client gives your server access to the platform's server modules,
|
|
7
|
+
* such as [`webhooks`](/developers/references/platform-sdk/docs/interfaces/webhooks). Creating it
|
|
8
|
+
* makes no network requests.
|
|
9
|
+
*
|
|
10
|
+
* @param options - Configuration object for the client.
|
|
11
|
+
* @returns A configured server client with access to the platform's server modules.
|
|
12
|
+
* @throws {TypeError} When `serverUrl` isn't an HTTP or HTTPS origin, or `apiKey` is empty.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```typescript
|
|
16
|
+
* // Create a server client on your backend
|
|
17
|
+
* import { createPlatformServer } from '@base44/platform/server';
|
|
18
|
+
*
|
|
19
|
+
* const platform = createPlatformServer({
|
|
20
|
+
* serverUrl: 'https://base44.app',
|
|
21
|
+
* apiKey: process.env.BASE44_API_KEY,
|
|
22
|
+
* });
|
|
23
|
+
*
|
|
24
|
+
* // Use the client to receive webhooks
|
|
25
|
+
* export const POST = platform.webhooks.createHandler({
|
|
26
|
+
* publicKeys: process.env.BASE44_WEBHOOK_PUBLIC_KEYS,
|
|
27
|
+
* on: {
|
|
28
|
+
* 'app.deleted.v1': async (event) => removeApp(event.data.app_id),
|
|
29
|
+
* },
|
|
30
|
+
* });
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export declare function createPlatformServer(options: PlatformServerOptions): PlatformServer;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { normalizeServerUrl } from "./server-url.js";
|
|
2
|
+
import { createWebhooks } from "./modules/webhooks.js";
|
|
3
|
+
/**
|
|
4
|
+
* Creates a platform server client.
|
|
5
|
+
*
|
|
6
|
+
* This is the entry point of the Platform SDK on your backend. Import it from
|
|
7
|
+
* `@base44/platform/server`. The client gives your server access to the platform's server modules,
|
|
8
|
+
* such as [`webhooks`](/developers/references/platform-sdk/docs/interfaces/webhooks). Creating it
|
|
9
|
+
* makes no network requests.
|
|
10
|
+
*
|
|
11
|
+
* @param options - Configuration object for the client.
|
|
12
|
+
* @returns A configured server client with access to the platform's server modules.
|
|
13
|
+
* @throws {TypeError} When `serverUrl` isn't an HTTP or HTTPS origin, or `apiKey` is empty.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```typescript
|
|
17
|
+
* // Create a server client on your backend
|
|
18
|
+
* import { createPlatformServer } from '@base44/platform/server';
|
|
19
|
+
*
|
|
20
|
+
* const platform = createPlatformServer({
|
|
21
|
+
* serverUrl: 'https://base44.app',
|
|
22
|
+
* apiKey: process.env.BASE44_API_KEY,
|
|
23
|
+
* });
|
|
24
|
+
*
|
|
25
|
+
* // Use the client to receive webhooks
|
|
26
|
+
* export const POST = platform.webhooks.createHandler({
|
|
27
|
+
* publicKeys: process.env.BASE44_WEBHOOK_PUBLIC_KEYS,
|
|
28
|
+
* on: {
|
|
29
|
+
* 'app.deleted.v1': async (event) => removeApp(event.data.app_id),
|
|
30
|
+
* },
|
|
31
|
+
* });
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export function createPlatformServer(options) {
|
|
35
|
+
if (!options.apiKey)
|
|
36
|
+
throw new TypeError("apiKey is required");
|
|
37
|
+
normalizeServerUrl(options.serverUrl);
|
|
38
|
+
return Object.freeze({
|
|
39
|
+
webhooks: Object.freeze(createWebhooks()),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { WebhooksModule } from "./modules/webhooks.types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Options for {@linkcode createPlatformServer | createPlatformServer()}.
|
|
4
|
+
*
|
|
5
|
+
* The server client runs on your backend and holds your workspace API key. Never pass these options
|
|
6
|
+
* to code that runs in the browser.
|
|
7
|
+
*/
|
|
8
|
+
export interface PlatformServerOptions {
|
|
9
|
+
/**
|
|
10
|
+
* Origin of the Base44 API, such as `https://base44.app`.
|
|
11
|
+
*
|
|
12
|
+
* It must be an origin with no path, query, fragment, or credentials.
|
|
13
|
+
*/
|
|
14
|
+
serverUrl: string;
|
|
15
|
+
/**
|
|
16
|
+
* Your workspace API key.
|
|
17
|
+
*
|
|
18
|
+
* Keep it on your server. The browser client never needs it.
|
|
19
|
+
*/
|
|
20
|
+
apiKey: string;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The platform server client.
|
|
24
|
+
*
|
|
25
|
+
* Provides access to the platform's server modules.
|
|
26
|
+
*/
|
|
27
|
+
export interface PlatformServer {
|
|
28
|
+
/** [Webhooks module](/developers/references/platform-sdk/docs/interfaces/webhooks) for receiving the events Base44 sends to your server. */
|
|
29
|
+
readonly webhooks: WebhooksModule;
|
|
30
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,17 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@base44-preview/platform",
|
|
3
|
-
"version": "0.2.0-pr.
|
|
4
|
-
"description": "
|
|
5
|
-
"main": "dist/index.js",
|
|
6
|
-
"types": "dist/index.d.ts",
|
|
3
|
+
"version": "0.2.0-pr.319.0f5c92a",
|
|
4
|
+
"description": "Client and server SDK for building on the Base44 platform",
|
|
5
|
+
"main": "dist/client/index.js",
|
|
6
|
+
"types": "dist/client/index.d.ts",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"exports": {
|
|
9
9
|
".": {
|
|
10
|
-
"types": "./dist/index.d.ts",
|
|
11
|
-
"default": "./dist/index.js"
|
|
10
|
+
"types": "./dist/client/index.d.ts",
|
|
11
|
+
"default": "./dist/client/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./server": {
|
|
14
|
+
"types": "./dist/server/index.d.ts",
|
|
15
|
+
"default": "./dist/server/index.js"
|
|
12
16
|
},
|
|
13
17
|
"./package.json": "./package.json"
|
|
14
18
|
},
|
|
19
|
+
"typesVersions": {
|
|
20
|
+
"*": {
|
|
21
|
+
"server": [
|
|
22
|
+
"dist/server/index.d.ts"
|
|
23
|
+
]
|
|
24
|
+
}
|
|
25
|
+
},
|
|
15
26
|
"files": [
|
|
16
27
|
"dist"
|
|
17
28
|
],
|
|
@@ -33,7 +44,8 @@
|
|
|
33
44
|
"create-docs-local": "npm run create-docs && npm run copy-docs-local",
|
|
34
45
|
"copy-docs-local": "node ../sdk/scripts/mintlify-post-processing/copy-to-local-docs.js --package-dir .",
|
|
35
46
|
"create-docs:generate": "node -e \"fs.rmSync('docs',{recursive:true,force:true})\" && typedoc --options typedoc.mintlify.json",
|
|
36
|
-
"create-docs:process": "node ../sdk/scripts/mintlify-post-processing/file-processing/file-processing.js --package-dir ."
|
|
47
|
+
"create-docs:process": "node ../sdk/scripts/mintlify-post-processing/file-processing/file-processing.js --package-dir .",
|
|
48
|
+
"generate:webhooks": "node scripts/generate-webhook-types.mjs"
|
|
37
49
|
},
|
|
38
50
|
"dependencies": {
|
|
39
51
|
"socket.io-client": "^4.8.3"
|
|
@@ -56,5 +68,8 @@
|
|
|
56
68
|
"homepage": "https://github.com/base44/javascript-sdk/tree/main/packages/platform#readme",
|
|
57
69
|
"devDependencies": {
|
|
58
70
|
"json-schema-to-typescript": "16.0.0"
|
|
71
|
+
},
|
|
72
|
+
"engines": {
|
|
73
|
+
"node": ">=20"
|
|
59
74
|
}
|
|
60
75
|
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|