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

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,21 @@ 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
+ url: 'https://example.com/hooks/orders', // The address the webhook is set to in Swell.
125
+ });
126
+ // webhook.event is the event the body carries.
127
+ ```
128
+
114
129
  ## Components
115
130
 
116
131
  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.
@@ -136,10 +151,11 @@ export default function ColorPicker({ value, setValue, readonly }: ComponentProp
136
151
  | `params` | Configuration from the place that uses the component |
137
152
  | `settings` | The app's public settings |
138
153
  | `locale`, `readonly` | Display locale and read-only state |
154
+ | `theme` | The host's color theme, `'light'` or `'dark'`, re-rendered when it changes. The frame sets it as `data-theme` and `color-scheme` on its root from its start, so CSS can follow it with `:root[data-theme="dark"]` |
139
155
  | `setValidity(error)` | Report a validation error, or `null` when valid |
140
156
  | `fetch` | Like `fetch`, but requests to the app's own origin (app functions, `/app-api`) carry a platform token when the host provides one, so they receive a verified `Swell-Context` with `surface` |
141
157
  | `call(name, data)` | Calls a host action and resolves with its result; payment components get `createIntent` and `getIntent` |
142
- | `on(event, handler)` | Handle a host event. Only the first handler registered for an event runs; its return value, or the error it throws, answers the host's `emit` |
158
+ | `on(event, handler)` | Handle a host event. Returns a function that removes the handler. Every handler of the event runs, in the order registered, each after the previous one settles; the first error thrown answers the host's `emit`, otherwise the last result other than `undefined` does. A handler registered again, as an effect does on a re-render, moves to the end, so keep steps that depend on each other in one handler. One removed while the event runs is skipped, and one registered meanwhile runs from the next event |
143
159
 
144
160
  ### Payment components
145
161
 
@@ -155,7 +171,7 @@ export const config = {
155
171
  };
156
172
 
157
173
  export default function Card({ call, on, context }: ComponentProps<never, PaymentContext>) {
158
- // Register in an effect: the frame runs only the first handler registered for an event, and `on` returns the unsubscribe
174
+ // Register in an effect, whose cleanup (the function `on` returns) removes the handler of the previous render
159
175
  useEffect(() => on('submit', async (): Promise<PaymentSubmitResult> => {
160
176
  const intent = await call<{ id: string }>('createIntent', { amount: context.cart.capture_total });
161
177
  return { billing: { intent } };
@@ -201,8 +217,8 @@ badge.unmount();
201
217
  | --- | --- |
202
218
  | `ready` | Resolves when the component has mounted in its frame. Rejects when the app or component cannot be loaded, when the frame page does not start within 10 seconds of loading, when the props cannot be sent, or when you unmount first |
203
219
  | `on(event, handler)` | Listen to `change` (new value), `validity` (error or `null`) and `error` (load, start, token and component failures, including the ones that reject `ready`). Returns a function that removes the listener; other event names are ignored |
204
- | `update(input)` | Re-render with new `value`, `context`, `params`, `readonly` or `locale`. Updates made before the component list loads are kept |
205
- | `emit(event, data)` | Waits for `ready`, then resolves with the result of the component's first `on` handler for the event, or rejects with its error |
220
+ | `update(input)` | Re-render with new `value`, `context`, `params`, `readonly`, `locale` or `theme`. Updates made before the component list loads are kept |
221
+ | `emit(event, data)` | Waits for `ready`, then resolves with the last result other than `undefined` of the component's `on` handlers for the event, or rejects with the first error one throws |
206
222
  | `focus()` | Moves keyboard focus to the component's first control, for example when your form focuses its first invalid field. During overlay, to the component's modal |
207
223
  | `unmount()` | Removes the frame. Before the component list loads, it cancels the mount; `ready` and pending `emit` calls reject |
208
224
 
@@ -212,7 +228,7 @@ Props and event data must be structured-cloneable. Props that cannot be cloned f
212
228
 
213
229
  Hosts that have their own session, like the Swell admin, pass `getToken: (app) => Promise<{ token, expires }>`. The token is refreshed a minute before it expires; if a refresh fails, the component keeps the current token and the host retries. Without `getToken` the frame gets no token, and `props.fetch` sends requests without a token header.
214
230
 
215
- The frame is an iframe inside the target element, so it behaves like any element of your page: it takes part in the layout, your popovers, sticky bars and dialogs stack over it, scrolling containers clip it, and Tab and Shift+Tab move into it and on to the neighbouring elements. Tab skips a component whose frame has not started yet, failed to start or reported an error before it rendered. The target's height follows the component's content. Do not move the target in the DOM while the component is mounted: browsers reload a moved iframe, so the component would start again with the current props.
231
+ The frame is an iframe inside the target element, so it behaves like any element of your page: it takes part in the layout, your popovers, sticky bars and dialogs stack over it, scrolling containers clip it, and Tab and Shift+Tab move into it and on to the neighbouring elements. Tab skips a component whose frame has not started yet, failed to start or reported an error before it rendered. The target's height follows the component's content from the frame's first report on, and is then at least 1px so that a modal opened from an empty component can still cover the viewport. Do not move the target in the DOM while the component is mounted: browsers reload a moved iframe, so the component would start again with the current props.
216
232
 
217
233
  When a component opens a modal (a payment SDK's 3D Secure challenge, a QR code), its frame covers the viewport until the modal closes. The frame enters the browser's top layer (the Popover API), so z-index, `transform`, `opacity` and `overflow` on the target's ancestors cannot confine it; in browsers without the Popover API it is a fixed box with the highest z-index, which a transformed or filtered ancestor still confines. Meanwhile the rest of your page is `inert` and does not scroll, and keyboard focus moves into the modal.
218
234
 
@@ -328,6 +344,33 @@ For server integrations, construct `SwellBackendAPI` with explicit credentials a
328
344
  `createStorefrontClient` with explicit public configuration. These clients do not
329
345
  require an HTTP request or a store user.
330
346
 
347
+ ### Webhook options
348
+
349
+ `verifySwellWebhook(headers, body, { url, env?, appId?, storeId? })` returns the webhook or
350
+ throws if verification fails. Pass `appId`, `storeId` or both from trusted configuration:
351
+ `appId` accepts only webhooks of apps with that id, and `storeId` only the webhooks of
352
+ that store. Without either it throws, since any Swell store can send a signed webhook to
353
+ any address. An app id is unique to its developer and store, so another developer's
354
+ private app can have yours: check `storeId` against the stores your app is installed in
355
+ before acting for one.
356
+
357
+ `url` is the address the webhook is set to in Swell: a string, a `URL`, or an object
358
+ with its `href`, such as Next's `request.nextUrl`. The signature
359
+ names the endpoint Swell sent the request to, so a request that one endpoint of a store
360
+ received and sent on to another is refused there. Pass the address from your
361
+ configuration. The request URL serves only where the platform routes requests to your
362
+ endpoint strictly by its host; never build it from the `Host` or `X-Forwarded-*` headers,
363
+ which the sender sets. The same address written another way, with an upper-case host, a
364
+ default port or a fragment, matches; its path and query must be the same.
365
+
366
+ It reads the same configuration as the request context. `SWELL_VERIFY_HEADERS=false`
367
+ also turns off webhook verification, so while it is set anyone can send a webhook your
368
+ endpoint accepts.
369
+
370
+ Swell retries a delivery that fails, and a signature stays valid for five minutes, so
371
+ one event can arrive more than once. Skip an `eventId` you have already handled. Order
372
+ webhooks, which an order's checkout calls as it runs, carry no `eventId` or `webhookId`.
373
+
331
374
  ### Store users
332
375
 
333
376
  `requireStoreUser(context)` returns `{ userId, storeId }` or throws `SwellError` with
@@ -351,6 +394,7 @@ error handling; `message` is for people and may change.
351
394
  when the payload is null or absent, in `body`.
352
395
  - Header verification uses 401 / `invalid_swell_context` for absent, malformed, expired
353
396
  or rejected tokens, and 503 / `swell_jwks_unavailable` for key-service failures.
397
+ Webhook verification uses 401 / `invalid_swell_webhook` and the same 503.
354
398
  - Backend/storefront network errors remain native. Local configuration errors may be
355
399
  ordinary `Error` instances; not every failure is a `SwellError`.
356
400
 
@@ -44,6 +44,20 @@ export function startComponentFrame(options = {}) {
44
44
  document.body.appendChild(root);
45
45
  }
46
46
  const target = root;
47
+ // The frame shows the theme from its start: the host puts it in the frame's URL, which keeps the current one
48
+ // for a reload
49
+ let rootTheme;
50
+ const showTheme = (theme) => {
51
+ if (theme === rootTheme)
52
+ return;
53
+ rootTheme = theme;
54
+ document.documentElement.dataset.theme = theme;
55
+ document.documentElement.style.colorScheme = theme;
56
+ const url = new URL(win.location.href);
57
+ url.searchParams.set('theme', theme);
58
+ win.history.replaceState(win.history.state, '', url.href);
59
+ };
60
+ showTheme(params.get('theme') === 'dark' ? 'dark' : 'light');
47
61
  const importModule = options.importModule ?? ((url) => import(/* webpackIgnore: true */ /* @vite-ignore */ url));
48
62
  let props = null;
49
63
  let token = null;
@@ -101,10 +115,19 @@ export function startComponentFrame(options = {}) {
101
115
  },
102
116
  };
103
117
  const componentProps = () => ({ ...props, ...callbacks });
118
+ // A host before themes sends none: its pages are light
119
+ const applyTheme = () => {
120
+ if (!props)
121
+ return;
122
+ props = { ...props, theme: props.theme === 'dark' ? 'dark' : 'light' };
123
+ showTheme(props.theme);
124
+ };
125
+ // At least 1px, so a modal opened from an empty component has an area: in a frame without height a modal has
126
+ // none either, and overlay could not tell it from an empty fixed container
104
127
  const reportHeight = () => {
105
128
  if (overlay)
106
129
  return;
107
- const height = Math.ceil(target.getBoundingClientRect().height);
130
+ const height = Math.max(1, Math.ceil(target.getBoundingClientRect().height));
108
131
  if (height !== lastHeight) {
109
132
  lastHeight = height;
110
133
  post({ type: 'resize', height });
@@ -189,6 +212,7 @@ export function startComponentFrame(options = {}) {
189
212
  case 'init':
190
213
  actions = Array.isArray(message.actions) ? message.actions.filter(name => typeof name === 'string') : [];
191
214
  props = message.props;
215
+ applyTheme();
192
216
  token = message.token;
193
217
  if (!mounting) {
194
218
  mounting = mount();
@@ -212,15 +236,25 @@ export function startComponentFrame(options = {}) {
212
236
  if (!props)
213
237
  return;
214
238
  props = { ...props, ...message.props };
239
+ applyTheme();
215
240
  await module?.update(target, componentProps());
216
241
  return;
217
242
  case 'token':
218
243
  token = message.token;
219
244
  return;
220
245
  case 'event': {
221
- const [handler] = handlers.get(message.name) ?? [];
246
+ // The handlers registered when the event arrived, in order, each after the previous one settles; one
247
+ // removed meanwhile, as a re-render's effect cleanup does, no longer runs
222
248
  try {
223
- post({ type: 'result', call: message.call, result: handler ? await handler(message.data) : undefined });
249
+ let result;
250
+ for (const handler of handlers.get(message.name) ?? []) {
251
+ if (!handlers.get(message.name)?.includes(handler))
252
+ continue;
253
+ const value = await handler(message.data);
254
+ if (value !== undefined)
255
+ result = value;
256
+ }
257
+ post({ type: 'result', call: message.call, result });
224
258
  }
225
259
  catch (error) {
226
260
  post({ type: 'result', call: message.call, error: errorMessage(error) });
@@ -247,5 +281,5 @@ export function startComponentFrame(options = {}) {
247
281
  if (message)
248
282
  handle(message).catch(fail);
249
283
  });
250
- post({ type: 'hello' });
284
+ post({ type: 'hello', themes: true });
251
285
  }
@@ -19,8 +19,9 @@ export interface ComponentHandle<TValue = unknown> {
19
19
  /** Re-renders the component with new data. */
20
20
  update(input: ComponentInput<TValue>): void;
21
21
  /**
22
- * Sends an event to the component and resolves with its handler's result. Rejects when the frame
23
- * does not start in time, reports an error (final) or is unmounted.
22
+ * Sends an event to the component and resolves with the last result other than `undefined` of its
23
+ * handlers for the event, or rejects with the first error one throws. Also rejects when the frame does
24
+ * not start in time, reports an error (final) or is unmounted.
24
25
  */
25
26
  emit<T = unknown>(event: string, data?: unknown): Promise<T>;
26
27
  /**
@@ -19,8 +19,9 @@ export interface ComponentHandle<TValue = unknown> {
19
19
  /** Re-renders the component with new data. */
20
20
  update(input: ComponentInput<TValue>): void;
21
21
  /**
22
- * Sends an event to the component and resolves with its handler's result. Rejects when the frame
23
- * does not start in time, reports an error (final) or is unmounted.
22
+ * Sends an event to the component and resolves with the last result other than `undefined` of its
23
+ * handlers for the event, or rejects with the first error one throws. Also rejects when the frame does
24
+ * not start in time, reports an error (final) or is unmounted.
24
25
  */
25
26
  emit<T = unknown>(event: string, data?: unknown): Promise<T>;
26
27
  /**
@@ -6,14 +6,16 @@ const RETRY_MS = 10_000;
6
6
  const MAX_RETRY_MS = 5 * 60_000;
7
7
  const MAX_TIMEOUT = 2 ** 31 - 1;
8
8
  const START_MS = 10_000;
9
- const INPUT_KEYS = ['value', 'context', 'params', 'readonly', 'locale'];
9
+ const INPUT_KEYS = ['value', 'context', 'params', 'readonly', 'locale', 'theme'];
10
10
  export const toError = (error) => (error instanceof Error ? error : new Error(String(error)));
11
+ /** The theme a host shows: dark, or light for anything else. */
12
+ const toTheme = (theme) => (theme === 'dark' ? 'dark' : 'light');
11
13
  /** The props a handle update changes: only the keys the host passed. */
12
14
  export function pickInput(input) {
13
15
  const changed = {};
14
16
  for (const key of INPUT_KEYS) {
15
17
  if (key in input)
16
- Object.assign(changed, { [key]: input[key] });
18
+ Object.assign(changed, { [key]: key === 'theme' ? toTheme(input.theme) : input[key] });
17
19
  }
18
20
  return changed;
19
21
  }
@@ -72,7 +74,10 @@ export function embedComponent(placeholder, options) {
72
74
  const props = {
73
75
  value: options.value, context: options.context ?? {}, params: options.params ?? {},
74
76
  settings: options.settings ?? {}, locale: options.locale ?? 'en', readonly: options.readonly ?? false,
77
+ theme: toTheme(options.theme),
75
78
  };
79
+ // The frame shows the theme from its start, before the host's init reaches it
80
+ url.searchParams.set('theme', props.theme);
76
81
  const { on, notify } = createListeners();
77
82
  const pending = new Map();
78
83
  let calls = 0;
@@ -105,6 +110,10 @@ export function embedComponent(placeholder, options) {
105
110
  pending.clear();
106
111
  };
107
112
  const placed = placeFrame(placeholder, url.href, options.title ?? 'App component', rect => send({ type: 'rect', rect }));
113
+ // A frame whose scheme differs from its element's gets an opaque background. A frame runtime that shows the theme
114
+ // sets it on its root and says so in its hello; until then, and for an older one, both keep the normal scheme
115
+ placed.iframe.style.colorScheme = 'normal';
116
+ let showsTheme = false;
108
117
  // A Tab stop only while the frame runs: from its first hello until it fails to start, or reports an error
109
118
  // before it rendered, so Tab skips a frame that shows an error page
110
119
  placed.iframe.tabIndex = -1;
@@ -185,6 +194,8 @@ export function embedComponent(placeholder, options) {
185
194
  switch (message.type) {
186
195
  case 'hello':
187
196
  clearTimeout(startTimer);
197
+ showsTheme = Boolean(message.themes);
198
+ placed.iframe.style.colorScheme = showsTheme ? props.theme : 'normal';
188
199
  if (greeted) {
189
200
  // The frame reloaded: its new runtime starts without overlay and cannot answer earlier events
190
201
  placed.setOverlay(false);
@@ -277,6 +288,8 @@ export function embedComponent(placeholder, options) {
277
288
  update(input) {
278
289
  const changed = pickInput(input);
279
290
  Object.assign(props, changed);
291
+ if (changed.theme && showsTheme)
292
+ placed.iframe.style.colorScheme = changed.theme;
280
293
  send({ type: 'update', props: changed });
281
294
  },
282
295
  async emit(name, data) {
@@ -3,7 +3,7 @@
3
3
  const IN_FLOW = {
4
4
  display: 'block', position: 'static', inset: 'auto', margin: '0', padding: '0', border: '0',
5
5
  width: '100%', height: '100%', 'max-width': 'none', 'max-height': 'none', overflow: 'visible',
6
- background: 'transparent', 'color-scheme': 'normal', 'z-index': 'auto',
6
+ background: 'transparent', 'z-index': 'auto',
7
7
  };
8
8
  // The z-index only matters without the Popover API: the top layer is above every z-index
9
9
  const COVER = { position: 'fixed', inset: '0px', width: '100vw', height: '100vh', 'z-index': '2147483647' };
@@ -20,6 +20,7 @@ export interface WireProps {
20
20
  settings: Record<string, unknown>;
21
21
  locale: string;
22
22
  readonly: boolean;
23
+ theme: 'light' | 'dark';
23
24
  }
24
25
  export type HostMessage = {
25
26
  type: 'init';
@@ -50,6 +51,7 @@ export type HostMessage = {
50
51
  };
51
52
  export type FrameMessage = {
52
53
  type: 'hello';
54
+ themes?: boolean;
53
55
  } | {
54
56
  type: 'ready';
55
57
  } | {
@@ -20,6 +20,7 @@ export interface WireProps {
20
20
  settings: Record<string, unknown>;
21
21
  locale: string;
22
22
  readonly: boolean;
23
+ theme: 'light' | 'dark';
23
24
  }
24
25
  export type HostMessage = {
25
26
  type: 'init';
@@ -50,6 +51,7 @@ export type HostMessage = {
50
51
  };
51
52
  export type FrameMessage = {
52
53
  type: 'hello';
54
+ themes?: boolean;
53
55
  } | {
54
56
  type: 'ready';
55
57
  } | {
@@ -11,12 +11,20 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
11
11
  readonly settings: Readonly<Record<string, unknown>>;
12
12
  readonly locale: string;
13
13
  readonly readonly: boolean;
14
+ /**
15
+ * The host's color theme. The frame also sets it as `data-theme` and `color-scheme` on its root element, so CSS
16
+ * can follow it with `:root[data-theme="dark"]`. `'light'` when the host passes none.
17
+ */
18
+ readonly theme: ComponentTheme;
14
19
  setValidity(error: string | null): void;
15
20
  /** fetch that adds the component token to requests to the frame's own origin. */
16
21
  readonly fetch: typeof fetch;
17
22
  /**
18
- * Handles a host event. Only the first handler registered for an event runs, and its result
19
- * (or thrown error) answers the host's `emit`; later handlers for the same event are not called.
23
+ * Handles a host event. Every handler registered for the event runs, in the order registered, each after the
24
+ * previous one settles. The first error thrown answers the host's `emit` and the later handlers do not run;
25
+ * otherwise `emit` resolves with the last result other than `undefined`. A handler registered again, as an effect
26
+ * does on a re-render, moves to the end, so keep steps that depend on each other in one handler. One removed while
27
+ * the event runs is skipped, and one registered meanwhile runs from the next event.
20
28
  */
21
29
  on(event: string, handler: (data: unknown) => unknown): () => void;
22
30
  /**
@@ -25,6 +33,7 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
25
33
  */
26
34
  call<T = unknown>(name: string, data?: unknown): Promise<T>;
27
35
  }
36
+ export type ComponentTheme = 'light' | 'dark';
28
37
  /** Optional static metadata a component file exports as `config`. */
29
38
  export interface ComponentConfig {
30
39
  readonly description?: string;
@@ -51,6 +60,8 @@ export interface ComponentInput<TValue = unknown, TContext = Record<string, unkn
51
60
  params?: Record<string, unknown>;
52
61
  readonly?: boolean;
53
62
  locale?: string;
63
+ /** The host's color theme, light by default. Update it when the host switches. */
64
+ theme?: ComponentTheme;
54
65
  }
55
66
  /** Short-lived platform token. `expires` is in epoch seconds. */
56
67
  export interface ComponentToken {
@@ -11,12 +11,20 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
11
11
  readonly settings: Readonly<Record<string, unknown>>;
12
12
  readonly locale: string;
13
13
  readonly readonly: boolean;
14
+ /**
15
+ * The host's color theme. The frame also sets it as `data-theme` and `color-scheme` on its root element, so CSS
16
+ * can follow it with `:root[data-theme="dark"]`. `'light'` when the host passes none.
17
+ */
18
+ readonly theme: ComponentTheme;
14
19
  setValidity(error: string | null): void;
15
20
  /** fetch that adds the component token to requests to the frame's own origin. */
16
21
  readonly fetch: typeof fetch;
17
22
  /**
18
- * Handles a host event. Only the first handler registered for an event runs, and its result
19
- * (or thrown error) answers the host's `emit`; later handlers for the same event are not called.
23
+ * Handles a host event. Every handler registered for the event runs, in the order registered, each after the
24
+ * previous one settles. The first error thrown answers the host's `emit` and the later handlers do not run;
25
+ * otherwise `emit` resolves with the last result other than `undefined`. A handler registered again, as an effect
26
+ * does on a re-render, moves to the end, so keep steps that depend on each other in one handler. One removed while
27
+ * the event runs is skipped, and one registered meanwhile runs from the next event.
20
28
  */
21
29
  on(event: string, handler: (data: unknown) => unknown): () => void;
22
30
  /**
@@ -25,6 +33,7 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
25
33
  */
26
34
  call<T = unknown>(name: string, data?: unknown): Promise<T>;
27
35
  }
36
+ export type ComponentTheme = 'light' | 'dark';
28
37
  /** Optional static metadata a component file exports as `config`. */
29
38
  export interface ComponentConfig {
30
39
  readonly description?: string;
@@ -51,6 +60,8 @@ export interface ComponentInput<TValue = unknown, TContext = Record<string, unkn
51
60
  params?: Record<string, unknown>;
52
61
  readonly?: boolean;
53
62
  locale?: string;
63
+ /** The host's color theme, light by default. Update it when the host switches. */
64
+ theme?: ComponentTheme;
54
65
  }
55
66
  /** Short-lived platform token. `expires` is in epoch seconds. */
56
67
  export interface ComponentToken {
@@ -1,4 +1,4 @@
1
- export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentToken, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.cjs';
1
+ export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentTheme, ComponentToken, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.cjs';
2
2
  export { createComponents } from './components-client.cjs';
3
3
  export type { Components, ComponentsOptions, MountOptions, NamedMountOptions, PlaceComponent, TargetMountOptions, TargetHandle } from './components-client.cjs';
4
4
  export type { ComponentHandle } from './components-host.cjs';
@@ -1,4 +1,4 @@
1
- export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentToken, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.js';
1
+ export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentTheme, ComponentToken, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.js';
2
2
  export { createComponents } from './components-client.js';
3
3
  export type { Components, ComponentsOptions, MountOptions, NamedMountOptions, PlaceComponent, TargetMountOptions, TargetHandle } from './components-client.js';
4
4
  export type { ComponentHandle } from './components-host.js';
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.9";
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.9";
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.9';
@@ -0,0 +1,38 @@
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
+ * The address the webhook is set to in Swell, from your configuration. Refuses a request Swell signed for another
12
+ * endpoint. The request URL serves only where the platform routes requests to your endpoint strictly by its host;
13
+ * never build it from the Host or X-Forwarded-* headers, which the sender sets. A string, a URL, or an object with
14
+ * the URL's href, such as Next's request.nextUrl.
15
+ */
16
+ url: string | {
17
+ readonly href: string;
18
+ };
19
+ }
20
+ /** A webhook request Swell sent, with its event. */
21
+ export interface SwellWebhook {
22
+ readonly storeId: string;
23
+ readonly environmentId?: string;
24
+ /** Set for an app's webhook: the id in the app's swell.json. */
25
+ readonly appId?: string;
26
+ readonly webhookId?: string;
27
+ readonly eventId?: string;
28
+ /** The event, as the body sent it. */
29
+ readonly event: Readonly<Record<string, unknown>>;
30
+ /** False only when trusted runtime configuration explicitly disables verification. */
31
+ readonly signatureVerified: boolean;
32
+ }
33
+ /**
34
+ * Verifies the Swell-Signature of a webhook request and reads its event. The
35
+ * body must be the bytes the request carried, before any parsing. Uses ES256
36
+ * and the same pinned JWKS endpoint as verifySwellContext.
37
+ */
38
+ export declare function verifySwellWebhook(headers: HeaderReader, body: string | ArrayBuffer | ArrayBufferView, options: VerifySwellWebhookOptions): Promise<SwellWebhook>;
@@ -0,0 +1,38 @@
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
+ * The address the webhook is set to in Swell, from your configuration. Refuses a request Swell signed for another
12
+ * endpoint. The request URL serves only where the platform routes requests to your endpoint strictly by its host;
13
+ * never build it from the Host or X-Forwarded-* headers, which the sender sets. A string, a URL, or an object with
14
+ * the URL's href, such as Next's request.nextUrl.
15
+ */
16
+ url: string | {
17
+ readonly href: string;
18
+ };
19
+ }
20
+ /** A webhook request Swell sent, with its event. */
21
+ export interface SwellWebhook {
22
+ readonly storeId: string;
23
+ readonly environmentId?: string;
24
+ /** Set for an app's webhook: the id in the app's swell.json. */
25
+ readonly appId?: string;
26
+ readonly webhookId?: string;
27
+ readonly eventId?: string;
28
+ /** The event, as the body sent it. */
29
+ readonly event: Readonly<Record<string, unknown>>;
30
+ /** False only when trusted runtime configuration explicitly disables verification. */
31
+ readonly signatureVerified: boolean;
32
+ }
33
+ /**
34
+ * Verifies the Swell-Signature of a webhook request and reads its event. The
35
+ * body must be the bytes the request carried, before any parsing. Uses ES256
36
+ * and the same pinned JWKS endpoint as verifySwellContext.
37
+ */
38
+ export declare function verifySwellWebhook(headers: HeaderReader, body: string | ArrayBuffer | ArrayBufferView, options: VerifySwellWebhookOptions): Promise<SwellWebhook>;
@@ -0,0 +1,135 @@
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
+ // The same address written either way, such as with an upper-case host, a default port or a fragment, is one endpoint.
24
+ // An object is read by its href: a URL of another realm, or one like Next's request.nextUrl, is not a URL instance
25
+ function endpointOf(value) {
26
+ const href = typeof value === 'string' ? value : value?.href;
27
+ if (typeof href !== 'string')
28
+ return undefined;
29
+ try {
30
+ const { origin, pathname, search } = new URL(href);
31
+ return `${origin}${pathname}${search}`;
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ }
37
+ async function sha256(body) {
38
+ const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', body));
39
+ return btoa(String.fromCharCode(...hash)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
40
+ }
41
+ /**
42
+ * Verifies the Swell-Signature of a webhook request and reads its event. The
43
+ * body must be the bytes the request carried, before any parsing. Uses ES256
44
+ * and the same pinned JWKS endpoint as verifySwellContext.
45
+ */
46
+ export async function verifySwellWebhook(headers, body, options) {
47
+ // A JavaScript caller can leave out the options, and gets told what they need
48
+ options = options ?? {};
49
+ const runtime = globalThis;
50
+ const env = options.env ?? runtime.process?.env ?? {};
51
+ const verify = env.SWELL_VERIFY_HEADERS !== 'false';
52
+ const jwksUrl = validateUrl(env.SWELL_HEADERS_JWKS_URL ?? 'https://keys.swell.store/jwks.json', 'SWELL_HEADERS_JWKS_URL');
53
+ for (const field of ['appId', 'storeId']) {
54
+ if (options[field] !== undefined)
55
+ requireString(options[field], field);
56
+ }
57
+ // A signature proves that Swell sent the request, not whose webhook it is:
58
+ // any store can point a webhook at any address
59
+ if (options.appId === undefined && options.storeId === undefined) {
60
+ throw new Error('verifySwellWebhook needs options.appId or options.storeId');
61
+ }
62
+ // Any endpoint a store's webhooks go to receives signed requests, and could pass one on to another
63
+ if (options.url === undefined)
64
+ throw new Error('verifySwellWebhook needs options.url, the address the webhook is set to');
65
+ const url = endpointOf(options.url);
66
+ if (url === undefined)
67
+ throw new Error('Invalid url: expected an absolute URL');
68
+ // A parsed body no longer has the bytes the signature covers
69
+ if (typeof body !== 'string' && !(body instanceof ArrayBuffer) && !ArrayBuffer.isView(body)) {
70
+ throw new TypeError('verifySwellWebhook needs the body as the request carried it, a string or bytes');
71
+ }
72
+ const bytes = typeof body === 'string' ? new TextEncoder().encode(body)
73
+ : body instanceof ArrayBuffer ? new Uint8Array(body)
74
+ : new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
75
+ const token = headers.get('Swell-Signature');
76
+ if (!token || token.length > 16_384)
77
+ throw invalidWebhook();
78
+ let payload;
79
+ let header;
80
+ let signature;
81
+ const parts = token.split('.');
82
+ try {
83
+ if (parts.length !== 3)
84
+ throw invalidWebhook();
85
+ header = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(decode(parts[0])));
86
+ payload = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(decode(parts[1])));
87
+ object(header);
88
+ object(payload);
89
+ signature = decode(parts[2]);
90
+ if (header.alg !== 'ES256' || header.typ !== SIGNATURE_TYPE || typeof header.kid !== 'string' || !header.kid ||
91
+ header.crit !== undefined || header.b64 !== undefined || signature.length !== 64)
92
+ throw invalidWebhook();
93
+ }
94
+ catch {
95
+ throw invalidWebhook();
96
+ }
97
+ if (verify) {
98
+ const key = await getVerificationKey(jwksUrl, header.kid, 'invalid_swell_webhook');
99
+ if (!await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, signature, new TextEncoder().encode(`${parts[0]}.${parts[1]}`)))
100
+ throw invalidWebhook();
101
+ }
102
+ try {
103
+ const now = Date.now() / 1000;
104
+ // The issuer controls signature lifetime; allow five seconds for clock skew.
105
+ if (typeof payload.iat !== 'number' || !Number.isFinite(payload.iat) || payload.iat > now + 5 ||
106
+ typeof payload.exp !== 'number' || !Number.isFinite(payload.exp) || payload.exp <= now - 5 ||
107
+ payload.exp <= payload.iat)
108
+ throw invalidWebhook();
109
+ requireString(payload.store_id, 'store_id');
110
+ requireString(payload.body_sha256, 'body_sha256');
111
+ const appId = optionalString(payload.app_id, 'app_id');
112
+ if ((options.storeId !== undefined && payload.store_id !== options.storeId) ||
113
+ (options.appId !== undefined && appId !== options.appId))
114
+ throw invalidWebhook();
115
+ // Signatures Swell made before it named the endpoint have no aud
116
+ if (payload.aud !== undefined && endpointOf(payload.aud) !== url)
117
+ throw invalidWebhook();
118
+ if (payload.body_sha256 !== await sha256(bytes))
119
+ throw invalidWebhook();
120
+ const event = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
121
+ object(event);
122
+ return Object.freeze({
123
+ storeId: payload.store_id,
124
+ environmentId: optionalString(payload.environment_id, 'environment_id'),
125
+ appId,
126
+ webhookId: optionalString(payload.webhook_id, 'webhook_id'),
127
+ eventId: optionalString(payload.event_id, 'event_id'),
128
+ event: Object.freeze(event),
129
+ signatureVerified: verify,
130
+ });
131
+ }
132
+ catch {
133
+ throw invalidWebhook();
134
+ }
135
+ }
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.9",
4
4
  "description": "Server SDK for Swell apps.",
5
5
  "type": "module",
6
6
  "license": "MIT",