@swell/apps-sdk 2.0.0-alpha.7 → 2.0.0-alpha.8

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 CHANGED
@@ -31,7 +31,7 @@ store user access. Use the same pattern for Swell-hosted and self-hosted fronten
31
31
  import { verifySwellContext } from '@swell/apps-sdk';
32
32
 
33
33
  const context = await verifySwellContext(request.headers, {
34
- appId: 'my-app', // Your app's configured slug.
34
+ appId: 'my_app', // The id in your app's swell.json.
35
35
  });
36
36
  ```
37
37
 
@@ -111,6 +111,20 @@ const storeUser = requireStoreUser(context); // { userId, storeId }, or a 401 Sw
111
111
  const optional = context.storeUser; // null for a visitor; no exception needed.
112
112
  ```
113
113
 
114
+ ### Webhooks
115
+
116
+ Swell signs each webhook request it sends. Verify the request against the body it
117
+ arrived with before acting on its event:
118
+
119
+ ```ts
120
+ import { verifySwellWebhook } from '@swell/apps-sdk';
121
+
122
+ const webhook = await verifySwellWebhook(request.headers, await request.text(), {
123
+ appId: 'my_app', // The id in your app's swell.json.
124
+ });
125
+ // webhook.event is the event the body carries.
126
+ ```
127
+
114
128
  ## Components
115
129
 
116
130
  App components are small UI bundles from an app's `components/` folder. Swell renders each one in an isolated iframe on the app installation's origin, so app code never runs in the host page. `@swell/apps-sdk/components` is browser code and is only bundled when you import it.
@@ -328,6 +342,24 @@ For server integrations, construct `SwellBackendAPI` with explicit credentials a
328
342
  `createStorefrontClient` with explicit public configuration. These clients do not
329
343
  require an HTTP request or a store user.
330
344
 
345
+ ### Webhook options
346
+
347
+ `verifySwellWebhook(headers, body, { env?, appId?, storeId? })` returns the webhook or
348
+ throws if verification fails. Pass `appId`, `storeId` or both from trusted configuration:
349
+ `appId` accepts only webhooks of apps with that id, and `storeId` only the webhooks of
350
+ that store. Without either it throws, since any Swell store can send a signed webhook to
351
+ any address. An app id is unique to its developer and store, so another developer's
352
+ private app can have yours: check `storeId` against the stores your app is installed in
353
+ before acting for one.
354
+
355
+ It reads the same configuration as the request context. `SWELL_VERIFY_HEADERS=false`
356
+ also turns off webhook verification, so while it is set anyone can send a webhook your
357
+ endpoint accepts.
358
+
359
+ Swell retries a delivery that fails, and a signature stays valid for five minutes, so
360
+ one event can arrive more than once. Skip an `eventId` you have already handled. Order
361
+ webhooks, which an order's checkout calls as it runs, carry no `eventId` or `webhookId`.
362
+
331
363
  ### Store users
332
364
 
333
365
  `requireStoreUser(context)` returns `{ userId, storeId }` or throws `SwellError` with
@@ -351,6 +383,7 @@ error handling; `message` is for people and may change.
351
383
  when the payload is null or absent, in `body`.
352
384
  - Header verification uses 401 / `invalid_swell_context` for absent, malformed, expired
353
385
  or rejected tokens, and 503 / `swell_jwks_unavailable` for key-service failures.
386
+ Webhook verification uses 401 / `invalid_swell_webhook` and the same 503.
354
387
  - Backend/storefront network errors remain native. Local configuration errors may be
355
388
  ordinary `Error` instances; not every failure is a `SwellError`.
356
389
 
package/dist/index.d.cts CHANGED
@@ -3,6 +3,8 @@ export { getStorefrontConfig } from './context.cjs';
3
3
  export type { HeaderReader } from './context.cjs';
4
4
  export { verifySwellContext } from './request-context.cjs';
5
5
  export type { SwellRequestContext, SwellHeadersEnv, SwellSurface, VerifySwellContextOptions } from './request-context.cjs';
6
+ export { verifySwellWebhook } from './webhook.cjs';
7
+ export type { SwellWebhook, VerifySwellWebhookOptions } from './webhook.cjs';
6
8
  export { SwellBackendAPI } from './backend.cjs';
7
9
  export type { BackendOptions, SwellCollection, SwellData, TransactionOperation, TransactionOptions } from './backend.cjs';
8
10
  export { SwellError } from './error.cjs';
package/dist/index.d.ts CHANGED
@@ -3,6 +3,8 @@ export { getStorefrontConfig } from './context.js';
3
3
  export type { HeaderReader } from './context.js';
4
4
  export { verifySwellContext } from './request-context.js';
5
5
  export type { SwellRequestContext, SwellHeadersEnv, SwellSurface, VerifySwellContextOptions } from './request-context.js';
6
+ export { verifySwellWebhook } from './webhook.js';
7
+ export type { SwellWebhook, VerifySwellWebhookOptions } from './webhook.js';
6
8
  export { SwellBackendAPI } from './backend.js';
7
9
  export type { BackendOptions, SwellCollection, SwellData, TransactionOperation, TransactionOptions } from './backend.js';
8
10
  export { SwellError } from './error.js';
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import './guard.js';
2
2
  export { getStorefrontConfig } from './context.js';
3
3
  export { verifySwellContext } from './request-context.js';
4
+ export { verifySwellWebhook } from './webhook.js';
4
5
  export { SwellBackendAPI } from './backend.js';
5
6
  export { SwellError } from './error.js';
6
7
  export { requireStoreUser } from './store-user.js';
package/dist/jwks.d.cts CHANGED
@@ -1 +1 @@
1
- export declare function getVerificationKey(url: string, kid: string): Promise<CryptoKey>;
1
+ export declare function getVerificationKey(url: string, kid: string, code?: string): Promise<CryptoKey>;
package/dist/jwks.d.ts CHANGED
@@ -1 +1 @@
1
- export declare function getVerificationKey(url: string, kid: string): Promise<CryptoKey>;
1
+ export declare function getVerificationKey(url: string, kid: string, code?: string): Promise<CryptoKey>;
package/dist/jwks.js CHANGED
@@ -34,7 +34,7 @@ async function refresh(url, entry) {
34
34
  throw entry.error;
35
35
  }
36
36
  }
37
- export async function getVerificationKey(url, kid) {
37
+ export async function getVerificationKey(url, kid, code = 'invalid_swell_context') {
38
38
  let entry = keySets.get(url);
39
39
  if (!entry) {
40
40
  if (keySets.size >= MAX_URLS)
@@ -65,6 +65,6 @@ export async function getVerificationKey(url, kid) {
65
65
  }
66
66
  const key = entry.keys.get(kid);
67
67
  if (!key)
68
- throw new SwellError('Unknown Swell signing key', { status: 401, code: 'invalid_swell_context' });
68
+ throw new SwellError('Unknown Swell signing key', { status: 401, code });
69
69
  return key;
70
70
  }
@@ -1 +1 @@
1
- export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.7";
1
+ export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.8";
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.7";
1
+ export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.8";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // Replaced with the package version by the build.
2
- export const USER_AGENT = 'swell-apps-sdk/2.0.0-alpha.7';
2
+ export const USER_AGENT = 'swell-apps-sdk/2.0.0-alpha.8';
@@ -0,0 +1,29 @@
1
+ import type { HeaderReader } from './context.cjs';
2
+ import type { SwellHeadersEnv } from './request-context.cjs';
3
+ export interface VerifySwellWebhookOptions {
4
+ /** Explicit Worker bindings or server configuration. Omit to read process.env when available. */
5
+ env?: SwellHeadersEnv;
6
+ /** Expected sender from trusted configuration, never incoming headers. Pass this or `appId`. */
7
+ storeId?: string;
8
+ /** The id in swell.json of the app the webhook must belong to. Pass this or `storeId`. */
9
+ appId?: string;
10
+ }
11
+ /** A webhook request Swell sent, with its event. */
12
+ export interface SwellWebhook {
13
+ readonly storeId: string;
14
+ readonly environmentId?: string;
15
+ /** Set for an app's webhook: the id in the app's swell.json. */
16
+ readonly appId?: string;
17
+ readonly webhookId?: string;
18
+ readonly eventId?: string;
19
+ /** The event, as the body sent it. */
20
+ readonly event: Readonly<Record<string, unknown>>;
21
+ /** False only when trusted runtime configuration explicitly disables verification. */
22
+ readonly signatureVerified: boolean;
23
+ }
24
+ /**
25
+ * Verifies the Swell-Signature of a webhook request and reads its event. The
26
+ * body must be the bytes the request carried, before any parsing. Uses ES256
27
+ * and the same pinned JWKS endpoint as verifySwellContext.
28
+ */
29
+ export declare function verifySwellWebhook(headers: HeaderReader, body: string | ArrayBuffer | ArrayBufferView, options?: VerifySwellWebhookOptions): Promise<SwellWebhook>;
@@ -0,0 +1,29 @@
1
+ import type { HeaderReader } from './context.js';
2
+ import type { SwellHeadersEnv } from './request-context.js';
3
+ export interface VerifySwellWebhookOptions {
4
+ /** Explicit Worker bindings or server configuration. Omit to read process.env when available. */
5
+ env?: SwellHeadersEnv;
6
+ /** Expected sender from trusted configuration, never incoming headers. Pass this or `appId`. */
7
+ storeId?: string;
8
+ /** The id in swell.json of the app the webhook must belong to. Pass this or `storeId`. */
9
+ appId?: string;
10
+ }
11
+ /** A webhook request Swell sent, with its event. */
12
+ export interface SwellWebhook {
13
+ readonly storeId: string;
14
+ readonly environmentId?: string;
15
+ /** Set for an app's webhook: the id in the app's swell.json. */
16
+ readonly appId?: string;
17
+ readonly webhookId?: string;
18
+ readonly eventId?: string;
19
+ /** The event, as the body sent it. */
20
+ readonly event: Readonly<Record<string, unknown>>;
21
+ /** False only when trusted runtime configuration explicitly disables verification. */
22
+ readonly signatureVerified: boolean;
23
+ }
24
+ /**
25
+ * Verifies the Swell-Signature of a webhook request and reads its event. The
26
+ * body must be the bytes the request carried, before any parsing. Uses ES256
27
+ * and the same pinned JWKS endpoint as verifySwellContext.
28
+ */
29
+ export declare function verifySwellWebhook(headers: HeaderReader, body: string | ArrayBuffer | ArrayBufferView, options?: VerifySwellWebhookOptions): Promise<SwellWebhook>;
@@ -0,0 +1,110 @@
1
+ import { requireString, validateUrl } from './context.js';
2
+ import { SwellError } from './error.js';
3
+ import { getVerificationKey } from './jwks.js';
4
+ const SIGNATURE_TYPE = 'swell-webhook+jwt';
5
+ function invalidWebhook() {
6
+ return new SwellError('Missing or invalid Swell webhook signature', { status: 401, code: 'invalid_swell_webhook' });
7
+ }
8
+ function decode(value) {
9
+ if (!/^[A-Za-z0-9_-]+$/.test(value))
10
+ throw invalidWebhook();
11
+ return Uint8Array.from(atob(value.replace(/-/g, '+').replace(/_/g, '/')), char => char.charCodeAt(0));
12
+ }
13
+ function object(value) {
14
+ if (!value || typeof value !== 'object' || Array.isArray(value))
15
+ throw invalidWebhook();
16
+ }
17
+ function optionalString(value, field) {
18
+ if (value == null)
19
+ return undefined;
20
+ requireString(value, field);
21
+ return value;
22
+ }
23
+ async function sha256(body) {
24
+ const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', body));
25
+ return btoa(String.fromCharCode(...hash)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
26
+ }
27
+ /**
28
+ * Verifies the Swell-Signature of a webhook request and reads its event. The
29
+ * body must be the bytes the request carried, before any parsing. Uses ES256
30
+ * and the same pinned JWKS endpoint as verifySwellContext.
31
+ */
32
+ export async function verifySwellWebhook(headers, body, options = {}) {
33
+ const runtime = globalThis;
34
+ const env = options.env ?? runtime.process?.env ?? {};
35
+ const verify = env.SWELL_VERIFY_HEADERS !== 'false';
36
+ const jwksUrl = validateUrl(env.SWELL_HEADERS_JWKS_URL ?? 'https://keys.swell.store/jwks.json', 'SWELL_HEADERS_JWKS_URL');
37
+ for (const field of ['appId', 'storeId']) {
38
+ if (options[field] !== undefined)
39
+ requireString(options[field], field);
40
+ }
41
+ // A signature proves that Swell sent the request, not whose webhook it is:
42
+ // any store can point a webhook at any address
43
+ if (options.appId === undefined && options.storeId === undefined) {
44
+ throw new Error('verifySwellWebhook needs options.appId or options.storeId');
45
+ }
46
+ // A parsed body no longer has the bytes the signature covers
47
+ if (typeof body !== 'string' && !(body instanceof ArrayBuffer) && !ArrayBuffer.isView(body)) {
48
+ throw new TypeError('verifySwellWebhook needs the body as the request carried it, a string or bytes');
49
+ }
50
+ const bytes = typeof body === 'string' ? new TextEncoder().encode(body)
51
+ : body instanceof ArrayBuffer ? new Uint8Array(body)
52
+ : new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
53
+ const token = headers.get('Swell-Signature');
54
+ if (!token || token.length > 16_384)
55
+ throw invalidWebhook();
56
+ let payload;
57
+ let header;
58
+ let signature;
59
+ const parts = token.split('.');
60
+ try {
61
+ if (parts.length !== 3)
62
+ throw invalidWebhook();
63
+ header = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(decode(parts[0])));
64
+ payload = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(decode(parts[1])));
65
+ object(header);
66
+ object(payload);
67
+ signature = decode(parts[2]);
68
+ if (header.alg !== 'ES256' || header.typ !== SIGNATURE_TYPE || typeof header.kid !== 'string' || !header.kid ||
69
+ header.crit !== undefined || header.b64 !== undefined || signature.length !== 64)
70
+ throw invalidWebhook();
71
+ }
72
+ catch {
73
+ throw invalidWebhook();
74
+ }
75
+ if (verify) {
76
+ const key = await getVerificationKey(jwksUrl, header.kid, 'invalid_swell_webhook');
77
+ if (!await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, signature, new TextEncoder().encode(`${parts[0]}.${parts[1]}`)))
78
+ throw invalidWebhook();
79
+ }
80
+ try {
81
+ const now = Date.now() / 1000;
82
+ // The issuer controls signature lifetime; allow five seconds for clock skew.
83
+ if (typeof payload.iat !== 'number' || !Number.isFinite(payload.iat) || payload.iat > now + 5 ||
84
+ typeof payload.exp !== 'number' || !Number.isFinite(payload.exp) || payload.exp <= now - 5 ||
85
+ payload.exp <= payload.iat)
86
+ throw invalidWebhook();
87
+ requireString(payload.store_id, 'store_id');
88
+ requireString(payload.body_sha256, 'body_sha256');
89
+ const appId = optionalString(payload.app_id, 'app_id');
90
+ if ((options.storeId !== undefined && payload.store_id !== options.storeId) ||
91
+ (options.appId !== undefined && appId !== options.appId))
92
+ throw invalidWebhook();
93
+ if (payload.body_sha256 !== await sha256(bytes))
94
+ throw invalidWebhook();
95
+ const event = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
96
+ object(event);
97
+ return Object.freeze({
98
+ storeId: payload.store_id,
99
+ environmentId: optionalString(payload.environment_id, 'environment_id'),
100
+ appId,
101
+ webhookId: optionalString(payload.webhook_id, 'webhook_id'),
102
+ eventId: optionalString(payload.event_id, 'event_id'),
103
+ event: Object.freeze(event),
104
+ signatureVerified: verify,
105
+ });
106
+ }
107
+ catch {
108
+ throw invalidWebhook();
109
+ }
110
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swell/apps-sdk",
3
- "version": "2.0.0-alpha.7",
3
+ "version": "2.0.0-alpha.8",
4
4
  "description": "Server SDK for Swell apps.",
5
5
  "type": "module",
6
6
  "license": "MIT",