@commmerce/app-bridge 0.0.0-stage → 1.0.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +17 -0
- package/README.md +79 -2
- package/dist/app-bridge.js +1 -0
- package/dist/client.d.ts +82 -0
- package/dist/client.js +223 -0
- package/dist/host.d.ts +52 -0
- package/dist/host.js +156 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/protocol.d.ts +206 -0
- package/dist/protocol.js +114 -0
- package/dist/reference-host.d.ts +20 -0
- package/dist/reference-host.js +108 -0
- package/dist/session-token.d.ts +50 -0
- package/dist/session-token.js +93 -0
- package/package.json +48 -4
package/dist/host.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { PROTOCOL, PROTOCOL_VERSION, AppBridgeError, isMessage, normalizeOrigin, } from './protocol.js';
|
|
2
|
+
const str = (v, max) => typeof v === 'string' && v.trim().length > 0 && v.length <= max;
|
|
3
|
+
const optStr = (v, max) => v === undefined || str(v, max);
|
|
4
|
+
const optBool = (v) => v === undefined || typeof v === 'boolean';
|
|
5
|
+
/**
|
|
6
|
+
* True for a path that stays inside the app: starts with one `/`, has no `\\` (browsers read `/\\host` as
|
|
7
|
+
* `//host`) and no control characters, and resolves to the same origin as its base.
|
|
8
|
+
*/
|
|
9
|
+
export function isAppPath(v) {
|
|
10
|
+
if (typeof v !== 'string' || v.length === 0 || v.length > 2000)
|
|
11
|
+
return false;
|
|
12
|
+
if (!v.startsWith('/') || v.startsWith('//') || v.includes('\\') || /[\u0000-\u001f\u007f]/.test(v))
|
|
13
|
+
return false;
|
|
14
|
+
try {
|
|
15
|
+
return new URL(v, 'https://app-bridge.invalid').origin === 'https://app-bridge.invalid';
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** Returns an error message if the payload is wrong for its type, else null. */
|
|
22
|
+
export function validatePayload(type, p) {
|
|
23
|
+
switch (type) {
|
|
24
|
+
case 'ready': return optStr(p.apiKey, 200) ? null : 'apiKey must be a string';
|
|
25
|
+
case 'toast.show':
|
|
26
|
+
if (!str(p.message, 200))
|
|
27
|
+
return 'message must be 1–200 characters';
|
|
28
|
+
if (p.tone !== undefined && !['default', 'success', 'critical'].includes(p.tone))
|
|
29
|
+
return 'tone must be default, success or critical';
|
|
30
|
+
if (p.duration !== undefined && !(typeof p.duration === 'number' && p.duration >= 2000 && p.duration <= 10000))
|
|
31
|
+
return 'duration must be 2000–10000 ms';
|
|
32
|
+
return null;
|
|
33
|
+
case 'modal.open': {
|
|
34
|
+
if (!str(p.title, 100) || !str(p.message, 1000))
|
|
35
|
+
return 'title (1–100) and message (1–1000 characters) are required';
|
|
36
|
+
const pa = p.primaryAction;
|
|
37
|
+
const sa = p.secondaryAction;
|
|
38
|
+
if (pa !== undefined && !(pa && str(pa.label, 40) && optBool(pa.destructive)))
|
|
39
|
+
return 'primaryAction needs a label (1–40 characters)';
|
|
40
|
+
if (sa !== undefined && !(sa && str(sa.label, 40)))
|
|
41
|
+
return 'secondaryAction needs a label (1–40 characters)';
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
case 'navigate':
|
|
45
|
+
if (!isAppPath(p.path))
|
|
46
|
+
return 'path must be a path inside the app, starting with a single / (no \\, no control characters)';
|
|
47
|
+
return optBool(p.replace) ? null : 'replace must be a boolean';
|
|
48
|
+
case 'frame.resize':
|
|
49
|
+
return typeof p.height === 'number' && Number.isFinite(p.height) && p.height >= 0 && p.height <= 100000
|
|
50
|
+
? null : 'height must be a number of pixels, 0–100000';
|
|
51
|
+
case 'saveBar.show':
|
|
52
|
+
return optStr(p.message, 100) && optStr(p.saveLabel, 40) && optStr(p.discardLabel, 40) && optBool(p.loading)
|
|
53
|
+
? null : 'message (≤100), saveLabel and discardLabel (≤40) must be strings; loading a boolean';
|
|
54
|
+
case 'resourcePicker.open':
|
|
55
|
+
if (!['product', 'customer', 'collection'].includes(p.type))
|
|
56
|
+
return 'type must be product, customer or collection';
|
|
57
|
+
return optBool(p.multiple) ? null : 'multiple must be a boolean';
|
|
58
|
+
default: return null;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** Admin side: answers App Bridge requests from the app in `iframe`. */
|
|
62
|
+
export function createHost(config) {
|
|
63
|
+
const appOrigin = normalizeOrigin(config.appOrigin, 'appOrigin');
|
|
64
|
+
const { iframe, handlers } = config;
|
|
65
|
+
let connected = false;
|
|
66
|
+
let destroyed = false;
|
|
67
|
+
const post = (msg) => {
|
|
68
|
+
if (!destroyed)
|
|
69
|
+
iframe.contentWindow?.postMessage({ protocol: PROTOCOL, version: PROTOCOL_VERSION, ...msg }, appOrigin);
|
|
70
|
+
};
|
|
71
|
+
const fail = (id, code, message) => post({ kind: 'response', id, ok: false, error: { code, message } });
|
|
72
|
+
const run = (type, p) => {
|
|
73
|
+
const need = (h) => { if (!h)
|
|
74
|
+
throw new AppBridgeError('not-supported', `This admin does not support "${type}"`); };
|
|
75
|
+
switch (type) {
|
|
76
|
+
case 'ready':
|
|
77
|
+
if (config.apiKey && p.apiKey !== config.apiKey)
|
|
78
|
+
throw new AppBridgeError('failed', 'API key does not match this app');
|
|
79
|
+
connected = true;
|
|
80
|
+
return { version: PROTOCOL_VERSION, theme: config.info?.theme ?? 'light', locale: config.info?.locale ?? 'en-IN' };
|
|
81
|
+
case 'toast.show':
|
|
82
|
+
need(handlers.toast);
|
|
83
|
+
return handlers.toast(p);
|
|
84
|
+
case 'modal.open':
|
|
85
|
+
need(handlers.modal);
|
|
86
|
+
return handlers.modal(p);
|
|
87
|
+
case 'navigate':
|
|
88
|
+
need(handlers.navigate);
|
|
89
|
+
return handlers.navigate(p);
|
|
90
|
+
case 'saveBar.show':
|
|
91
|
+
need(handlers.saveBar);
|
|
92
|
+
return handlers.saveBar(p);
|
|
93
|
+
case 'saveBar.hide':
|
|
94
|
+
need(handlers.saveBar);
|
|
95
|
+
return handlers.saveBar(null);
|
|
96
|
+
case 'resourcePicker.open':
|
|
97
|
+
need(handlers.resourcePicker);
|
|
98
|
+
return handlers.resourcePicker(p);
|
|
99
|
+
case 'loading.start':
|
|
100
|
+
need(handlers.loading);
|
|
101
|
+
return handlers.loading(true);
|
|
102
|
+
case 'loading.stop':
|
|
103
|
+
need(handlers.loading);
|
|
104
|
+
return handlers.loading(false);
|
|
105
|
+
case 'sessionToken.get':
|
|
106
|
+
need(handlers.sessionToken);
|
|
107
|
+
return handlers.sessionToken();
|
|
108
|
+
case 'frame.resize':
|
|
109
|
+
if (handlers.resize)
|
|
110
|
+
return handlers.resize(p);
|
|
111
|
+
iframe.style.blockSize = `${Math.ceil(p.height)}px`;
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
const KNOWN = ['ready', 'toast.show', 'modal.open', 'navigate', 'saveBar.show', 'saveBar.hide',
|
|
116
|
+
'resourcePicker.open', 'loading.start', 'loading.stop', 'sessionToken.get', 'frame.resize'];
|
|
117
|
+
const onMessage = async (event) => {
|
|
118
|
+
if (!isMessage(event.data))
|
|
119
|
+
return config.onReject?.('not an App Bridge message', event);
|
|
120
|
+
if (!iframe.contentWindow || event.source !== iframe.contentWindow)
|
|
121
|
+
return config.onReject?.('not from the app frame', event);
|
|
122
|
+
if (event.origin !== appOrigin)
|
|
123
|
+
return config.onReject?.(`origin ${event.origin} is not ${appOrigin}`, event);
|
|
124
|
+
const msg = event.data;
|
|
125
|
+
if (msg.kind !== 'request' || typeof msg.id !== 'string')
|
|
126
|
+
return config.onReject?.('not a request', event);
|
|
127
|
+
const { id, type } = msg;
|
|
128
|
+
if (msg.version !== PROTOCOL_VERSION)
|
|
129
|
+
return fail(id, 'unsupported-version', `This admin speaks App Bridge version ${PROTOCOL_VERSION}`);
|
|
130
|
+
if (!KNOWN.includes(type))
|
|
131
|
+
return fail(id, 'unknown-type', `Unknown request "${String(type)}"`);
|
|
132
|
+
if (type !== 'ready' && !connected)
|
|
133
|
+
return fail(id, 'not-ready', 'Send "ready" first');
|
|
134
|
+
const payload = msg.payload && typeof msg.payload === 'object' ? msg.payload : {};
|
|
135
|
+
const invalid = validatePayload(type, payload);
|
|
136
|
+
if (invalid)
|
|
137
|
+
return fail(id, 'invalid-payload', invalid);
|
|
138
|
+
try {
|
|
139
|
+
const result = await run(type, payload);
|
|
140
|
+
post({ kind: 'response', id, ok: true, ...(result === undefined ? {} : { result }) });
|
|
141
|
+
}
|
|
142
|
+
catch (e) {
|
|
143
|
+
if (e instanceof AppBridgeError)
|
|
144
|
+
fail(id, e.code, e.message);
|
|
145
|
+
else
|
|
146
|
+
fail(id, 'failed', e instanceof Error ? e.message : 'The admin could not complete the request');
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
window.addEventListener('message', onMessage);
|
|
150
|
+
return {
|
|
151
|
+
send(type, payload) { if (connected)
|
|
152
|
+
post({ kind: 'event', type, payload }); },
|
|
153
|
+
get connected() { return connected; },
|
|
154
|
+
destroy() { destroyed = true; connected = false; window.removeEventListener('message', onMessage); },
|
|
155
|
+
};
|
|
156
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export * from './protocol.js';
|
|
2
|
+
export { createApp, type App, type AppConfig } from './client.js';
|
|
3
|
+
export { createHost, validatePayload, isAppPath, type Host, type HostConfig, type HostHandlers } from './host.js';
|
|
4
|
+
export { createReferenceHost, type ReferenceHostConfig } from './reference-host.js';
|
|
5
|
+
export { signSessionToken, verifySessionToken, decodeClaims, SessionTokenError, type SessionTokenClaims, type VerifyOptions, type SessionTokenErrorCode, } from './session-token.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export * from './protocol.js';
|
|
2
|
+
export { createApp } from './client.js';
|
|
3
|
+
export { createHost, validatePayload, isAppPath } from './host.js';
|
|
4
|
+
export { createReferenceHost } from './reference-host.js';
|
|
5
|
+
export { signSessionToken, verifySessionToken, decodeClaims, SessionTokenError, } from './session-token.js';
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The App Bridge wire protocol: plain objects sent with `postMessage` between the Commmerce admin (host)
|
|
3
|
+
* and an app running in an iframe inside it. Every message carries `protocol` and `version`, so either
|
|
4
|
+
* side can ignore traffic that is not App Bridge and refuse a version it does not speak.
|
|
5
|
+
*
|
|
6
|
+
* - request (app → host): `{ protocol, version, kind: 'request', id, type, payload }`
|
|
7
|
+
* - response (host → app): `{ protocol, version, kind: 'response', id, ok, result? , error? }`
|
|
8
|
+
* - event (host → app): `{ protocol, version, kind: 'event', type, payload }`
|
|
9
|
+
*/
|
|
10
|
+
export declare const PROTOCOL = "commmerce-app-bridge";
|
|
11
|
+
/** Major protocol version. A host answers a request with a different version with `unsupported-version`. */
|
|
12
|
+
export declare const PROTOCOL_VERSION = 1;
|
|
13
|
+
export type ToastTone = 'default' | 'success' | 'critical';
|
|
14
|
+
export interface ToastOptions {
|
|
15
|
+
/** `default`, `success` or `critical`. */
|
|
16
|
+
tone?: ToastTone;
|
|
17
|
+
/** How long it stays, in ms (2000–10000). Default 5000. */
|
|
18
|
+
duration?: number;
|
|
19
|
+
}
|
|
20
|
+
export interface ModalOptions {
|
|
21
|
+
title: string;
|
|
22
|
+
message: string;
|
|
23
|
+
/** The main action, e.g. `{ label: 'Delete product', destructive: true }`. */
|
|
24
|
+
primaryAction?: {
|
|
25
|
+
label: string;
|
|
26
|
+
destructive?: boolean;
|
|
27
|
+
};
|
|
28
|
+
/** Usually `{ label: 'Cancel' }`. */
|
|
29
|
+
secondaryAction?: {
|
|
30
|
+
label: string;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** How an admin-level modal was closed. */
|
|
34
|
+
export type ModalResult = 'primary' | 'secondary' | 'close';
|
|
35
|
+
export interface SaveBarOptions {
|
|
36
|
+
/** Default "Unsaved changes". */
|
|
37
|
+
message?: string;
|
|
38
|
+
saveLabel?: string;
|
|
39
|
+
discardLabel?: string;
|
|
40
|
+
/** Show the save button as busy. */
|
|
41
|
+
loading?: boolean;
|
|
42
|
+
}
|
|
43
|
+
export type ResourceType = 'product' | 'customer' | 'collection';
|
|
44
|
+
export interface ResourcePickerOptions {
|
|
45
|
+
type: ResourceType;
|
|
46
|
+
/** Allow choosing more than one. Default false. */
|
|
47
|
+
multiple?: boolean;
|
|
48
|
+
}
|
|
49
|
+
export interface PickedResource {
|
|
50
|
+
id: string;
|
|
51
|
+
title: string;
|
|
52
|
+
}
|
|
53
|
+
export interface NavigateOptions {
|
|
54
|
+
/** Replace the current admin history entry instead of adding one. */
|
|
55
|
+
replace?: boolean;
|
|
56
|
+
}
|
|
57
|
+
/** What the host tells the app when it connects. */
|
|
58
|
+
export interface HostInfo {
|
|
59
|
+
/** The protocol version the host speaks. */
|
|
60
|
+
version: number;
|
|
61
|
+
/** The admin's current theme. Follow it with `data-cm-theme`. */
|
|
62
|
+
theme: 'light' | 'dark';
|
|
63
|
+
/** BCP 47 locale of the staff member, e.g. `en-IN`. */
|
|
64
|
+
locale: string;
|
|
65
|
+
}
|
|
66
|
+
/** Every request an app can make, with its payload and result. */
|
|
67
|
+
export interface RequestMap {
|
|
68
|
+
'ready': {
|
|
69
|
+
payload: {
|
|
70
|
+
apiKey?: string;
|
|
71
|
+
};
|
|
72
|
+
result: HostInfo;
|
|
73
|
+
};
|
|
74
|
+
'toast.show': {
|
|
75
|
+
payload: {
|
|
76
|
+
message: string;
|
|
77
|
+
} & ToastOptions;
|
|
78
|
+
result: void;
|
|
79
|
+
};
|
|
80
|
+
'modal.open': {
|
|
81
|
+
payload: ModalOptions;
|
|
82
|
+
result: ModalResult;
|
|
83
|
+
};
|
|
84
|
+
'navigate': {
|
|
85
|
+
payload: {
|
|
86
|
+
path: string;
|
|
87
|
+
} & NavigateOptions;
|
|
88
|
+
result: void;
|
|
89
|
+
};
|
|
90
|
+
'saveBar.show': {
|
|
91
|
+
payload: SaveBarOptions;
|
|
92
|
+
result: void;
|
|
93
|
+
};
|
|
94
|
+
'saveBar.hide': {
|
|
95
|
+
payload: Record<string, never>;
|
|
96
|
+
result: void;
|
|
97
|
+
};
|
|
98
|
+
'resourcePicker.open': {
|
|
99
|
+
payload: ResourcePickerOptions;
|
|
100
|
+
result: PickedResource[] | null;
|
|
101
|
+
};
|
|
102
|
+
'loading.start': {
|
|
103
|
+
payload: Record<string, never>;
|
|
104
|
+
result: void;
|
|
105
|
+
};
|
|
106
|
+
'loading.stop': {
|
|
107
|
+
payload: Record<string, never>;
|
|
108
|
+
result: void;
|
|
109
|
+
};
|
|
110
|
+
'sessionToken.get': {
|
|
111
|
+
payload: Record<string, never>;
|
|
112
|
+
result: string;
|
|
113
|
+
};
|
|
114
|
+
/** The app's content height in CSS pixels, so the admin can size the frame (added in 1.0.0-rc.2, still protocol v1). */
|
|
115
|
+
'frame.resize': {
|
|
116
|
+
payload: {
|
|
117
|
+
height: number;
|
|
118
|
+
};
|
|
119
|
+
result: void;
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
export type RequestType = keyof RequestMap;
|
|
123
|
+
/** Events the host sends to the app. */
|
|
124
|
+
export interface EventMap {
|
|
125
|
+
/** Save pressed on the admin save bar. */
|
|
126
|
+
'saveBar.save': Record<string, never>;
|
|
127
|
+
/** Discard pressed on the admin save bar. */
|
|
128
|
+
'saveBar.discard': Record<string, never>;
|
|
129
|
+
/** The admin theme changed. */
|
|
130
|
+
'theme.change': {
|
|
131
|
+
theme: 'light' | 'dark';
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
export type EventType = keyof EventMap;
|
|
135
|
+
export interface RequestMessage<T extends RequestType = RequestType> {
|
|
136
|
+
protocol: typeof PROTOCOL;
|
|
137
|
+
version: number;
|
|
138
|
+
kind: 'request';
|
|
139
|
+
id: string;
|
|
140
|
+
type: T;
|
|
141
|
+
payload: RequestMap[T]['payload'];
|
|
142
|
+
}
|
|
143
|
+
export interface ResponseMessage {
|
|
144
|
+
protocol: typeof PROTOCOL;
|
|
145
|
+
version: number;
|
|
146
|
+
kind: 'response';
|
|
147
|
+
id: string;
|
|
148
|
+
ok: boolean;
|
|
149
|
+
result?: unknown;
|
|
150
|
+
error?: {
|
|
151
|
+
code: ErrorCode;
|
|
152
|
+
message: string;
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
export interface EventMessage<T extends EventType = EventType> {
|
|
156
|
+
protocol: typeof PROTOCOL;
|
|
157
|
+
version: number;
|
|
158
|
+
kind: 'event';
|
|
159
|
+
type: T;
|
|
160
|
+
payload: EventMap[T];
|
|
161
|
+
}
|
|
162
|
+
export type Message = RequestMessage | ResponseMessage | EventMessage;
|
|
163
|
+
export type ErrorCode = 'unsupported-version' | 'unknown-type' | 'invalid-payload' | 'not-supported' | 'not-ready' | 'failed' | 'timeout';
|
|
164
|
+
/** A request the host refused or could not complete. */
|
|
165
|
+
export declare class AppBridgeError extends Error {
|
|
166
|
+
code: ErrorCode;
|
|
167
|
+
constructor(code: ErrorCode, message: string);
|
|
168
|
+
}
|
|
169
|
+
/** True for anything shaped like an App Bridge message (any version). */
|
|
170
|
+
export declare function isMessage(data: unknown): data is Message;
|
|
171
|
+
/** Normalises an origin (`https://app.example.com/path` → `https://app.example.com`). Refuses `*`, `null` and wildcards. */
|
|
172
|
+
export declare function normalizeOrigin(origin: string, what: string): string;
|
|
173
|
+
/**
|
|
174
|
+
* An admin origin pattern such as `https://*.commmerce.com`: every admin on a subdomain of one domain.
|
|
175
|
+
* Made by `parseOriginPattern`; `scheme` is `https:` or `http:`, `port` is `''` for the scheme's default port.
|
|
176
|
+
*/
|
|
177
|
+
export interface OriginPattern {
|
|
178
|
+
scheme: 'https:' | 'http:';
|
|
179
|
+
/** The domain after `*.`, lower case, e.g. `commmerce.com`. */
|
|
180
|
+
domain: string;
|
|
181
|
+
port: string;
|
|
182
|
+
/** The pattern as given. */
|
|
183
|
+
source: string;
|
|
184
|
+
}
|
|
185
|
+
/** True if `value` is meant as a pattern (it contains `*`). Check it with `parseOriginPattern`. */
|
|
186
|
+
export declare function isOriginPattern(value: string): boolean;
|
|
187
|
+
/**
|
|
188
|
+
* Parses an origin pattern: `scheme://*.domain` or `scheme://*.domain:port`, scheme `https` or `http`.
|
|
189
|
+
* Only one leading `*.` label is allowed, the domain needs at least one dot (`*.com` is refused; `*.localhost`
|
|
190
|
+
* is allowed for local development, because it only ever reaches this computer), and there is no path. Throws
|
|
191
|
+
* `TypeError` otherwise.
|
|
192
|
+
*/
|
|
193
|
+
export declare function parseOriginPattern(pattern: string, what?: string): OriginPattern;
|
|
194
|
+
/**
|
|
195
|
+
* True if `origin` (e.g. `https://admin.commmerce.com`) matches `pattern` (e.g. `https://*.commmerce.com`):
|
|
196
|
+
* the same scheme and port, and a host name that ends with `.` + the domain with at least one valid label before
|
|
197
|
+
* it, at any depth. The bare domain, look-alikes (`evilcommmerce.com`, `commmerce.com.evil.com`), other schemes,
|
|
198
|
+
* other ports and IP addresses never match. `origin` must be an origin and nothing more (no path, no trailing `/`,
|
|
199
|
+
* no user name, no default port written out); letter case is ignored.
|
|
200
|
+
*/
|
|
201
|
+
export declare function matchesOriginPattern(pattern: string | OriginPattern, origin: string): boolean;
|
|
202
|
+
/**
|
|
203
|
+
* Checks `origin` against what your settings allow: an exact origin (compared exactly, as before) or a pattern
|
|
204
|
+
* such as `https://*.commmerce.com` (see `matchesOriginPattern`). Throws `TypeError` for an invalid pattern.
|
|
205
|
+
*/
|
|
206
|
+
export declare function matchesOrigin(allowed: string, origin: string): boolean;
|
package/dist/protocol.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The App Bridge wire protocol: plain objects sent with `postMessage` between the Commmerce admin (host)
|
|
3
|
+
* and an app running in an iframe inside it. Every message carries `protocol` and `version`, so either
|
|
4
|
+
* side can ignore traffic that is not App Bridge and refuse a version it does not speak.
|
|
5
|
+
*
|
|
6
|
+
* - request (app → host): `{ protocol, version, kind: 'request', id, type, payload }`
|
|
7
|
+
* - response (host → app): `{ protocol, version, kind: 'response', id, ok, result? , error? }`
|
|
8
|
+
* - event (host → app): `{ protocol, version, kind: 'event', type, payload }`
|
|
9
|
+
*/
|
|
10
|
+
export const PROTOCOL = 'commmerce-app-bridge';
|
|
11
|
+
/** Major protocol version. A host answers a request with a different version with `unsupported-version`. */
|
|
12
|
+
export const PROTOCOL_VERSION = 1;
|
|
13
|
+
/** A request the host refused or could not complete. */
|
|
14
|
+
export class AppBridgeError extends Error {
|
|
15
|
+
constructor(code, message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = 'AppBridgeError';
|
|
18
|
+
this.code = code;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** True for anything shaped like an App Bridge message (any version). */
|
|
22
|
+
export function isMessage(data) {
|
|
23
|
+
if (!data || typeof data !== 'object')
|
|
24
|
+
return false;
|
|
25
|
+
const m = data;
|
|
26
|
+
return m.protocol === PROTOCOL && typeof m.version === 'number'
|
|
27
|
+
&& (m.kind === 'request' || m.kind === 'response' || m.kind === 'event');
|
|
28
|
+
}
|
|
29
|
+
/** Normalises an origin (`https://app.example.com/path` → `https://app.example.com`). Refuses `*`, `null` and wildcards. */
|
|
30
|
+
export function normalizeOrigin(origin, what) {
|
|
31
|
+
if (!origin || origin === '*' || origin === 'null')
|
|
32
|
+
throw new TypeError(`App Bridge: ${what} must be an exact origin such as https://app.example.com, not "${origin}"`);
|
|
33
|
+
// `new URL('https://*.example.com')` parses, but no real origin contains `*`: say so instead of never matching.
|
|
34
|
+
if (String(origin).includes('*'))
|
|
35
|
+
throw new TypeError(`App Bridge: ${what} must be an exact origin such as https://app.example.com, not the pattern "${origin}"`);
|
|
36
|
+
const o = new URL(origin).origin;
|
|
37
|
+
if (o === 'null')
|
|
38
|
+
throw new TypeError(`App Bridge: ${what} "${origin}" has no origin`);
|
|
39
|
+
return o;
|
|
40
|
+
}
|
|
41
|
+
/** One DNS label: letters, digits and hyphens, 1–63 characters, not starting or ending with a hyphen. */
|
|
42
|
+
const LABEL = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/;
|
|
43
|
+
const DEFAULT_PORT = { 'https:': '443', 'http:': '80' };
|
|
44
|
+
/** True if `value` is meant as a pattern (it contains `*`). Check it with `parseOriginPattern`. */
|
|
45
|
+
export function isOriginPattern(value) {
|
|
46
|
+
return typeof value === 'string' && value.includes('*');
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Parses an origin pattern: `scheme://*.domain` or `scheme://*.domain:port`, scheme `https` or `http`.
|
|
50
|
+
* Only one leading `*.` label is allowed, the domain needs at least one dot (`*.com` is refused; `*.localhost`
|
|
51
|
+
* is allowed for local development, because it only ever reaches this computer), and there is no path. Throws
|
|
52
|
+
* `TypeError` otherwise.
|
|
53
|
+
*/
|
|
54
|
+
export function parseOriginPattern(pattern, what = 'origin pattern') {
|
|
55
|
+
const fail = (why) => new TypeError(`App Bridge: ${what} "${pattern}" is not a valid origin pattern: ${why}. `
|
|
56
|
+
+ 'Use an exact origin such as https://admin.example.com, or a pattern such as https://*.commmerce.com');
|
|
57
|
+
const m = /^(https?):\/\/\*\.([^:/?#]*)(?::(\d{1,5}))?$/i.exec(String(pattern));
|
|
58
|
+
if (!m)
|
|
59
|
+
throw fail('it must be https://*.domain or http://*.domain, with an optional :port and nothing else');
|
|
60
|
+
const scheme = `${m[1].toLowerCase()}:`;
|
|
61
|
+
const domain = m[2].toLowerCase();
|
|
62
|
+
const labels = domain.split('.');
|
|
63
|
+
if (domain.length > 253 || !labels.every((l) => LABEL.test(l)))
|
|
64
|
+
throw fail('the part after "*." must be a domain name (letters, digits, hyphens and dots)');
|
|
65
|
+
if (labels.length < 2 && domain !== 'localhost')
|
|
66
|
+
throw fail('the domain after "*." needs at least one dot, e.g. *.commmerce.com');
|
|
67
|
+
if (/^(\d+|0x[0-9a-f]*)$/.test(labels[labels.length - 1]))
|
|
68
|
+
throw fail('IP addresses cannot have a wildcard');
|
|
69
|
+
let port = '';
|
|
70
|
+
if (m[3] !== undefined) {
|
|
71
|
+
const n = Number(m[3]);
|
|
72
|
+
if (n < 1 || n > 65535)
|
|
73
|
+
throw fail('the port must be 1 to 65535');
|
|
74
|
+
port = String(n) === DEFAULT_PORT[scheme] ? '' : String(n);
|
|
75
|
+
}
|
|
76
|
+
return { scheme, domain, port, source: String(pattern) };
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* True if `origin` (e.g. `https://admin.commmerce.com`) matches `pattern` (e.g. `https://*.commmerce.com`):
|
|
80
|
+
* the same scheme and port, and a host name that ends with `.` + the domain with at least one valid label before
|
|
81
|
+
* it, at any depth. The bare domain, look-alikes (`evilcommmerce.com`, `commmerce.com.evil.com`), other schemes,
|
|
82
|
+
* other ports and IP addresses never match. `origin` must be an origin and nothing more (no path, no trailing `/`,
|
|
83
|
+
* no user name, no default port written out); letter case is ignored.
|
|
84
|
+
*/
|
|
85
|
+
export function matchesOriginPattern(pattern, origin) {
|
|
86
|
+
const p = typeof pattern === 'string' ? parseOriginPattern(pattern) : pattern;
|
|
87
|
+
if (typeof origin !== 'string' || !origin)
|
|
88
|
+
return false;
|
|
89
|
+
let u;
|
|
90
|
+
try {
|
|
91
|
+
u = new URL(origin);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
if (u.origin === 'null' || u.origin !== origin.toLowerCase())
|
|
97
|
+
return false;
|
|
98
|
+
if (u.protocol !== p.scheme || u.port !== p.port)
|
|
99
|
+
return false;
|
|
100
|
+
const suffix = `.${p.domain}`;
|
|
101
|
+
if (!u.hostname.endsWith(suffix))
|
|
102
|
+
return false;
|
|
103
|
+
const sub = u.hostname.slice(0, -suffix.length);
|
|
104
|
+
return sub.length > 0 && sub.split('.').every((l) => LABEL.test(l));
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Checks `origin` against what your settings allow: an exact origin (compared exactly, as before) or a pattern
|
|
108
|
+
* such as `https://*.commmerce.com` (see `matchesOriginPattern`). Throws `TypeError` for an invalid pattern.
|
|
109
|
+
*/
|
|
110
|
+
export function matchesOrigin(allowed, origin) {
|
|
111
|
+
if (isOriginPattern(allowed))
|
|
112
|
+
return matchesOriginPattern(parseOriginPattern(allowed, 'allowed origin'), origin);
|
|
113
|
+
return typeof origin === 'string' && origin === allowed;
|
|
114
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type Host, type HostConfig } from './host.js';
|
|
2
|
+
import type { PickedResource, ResourcePickerOptions } from './protocol.js';
|
|
3
|
+
/**
|
|
4
|
+
* A reference admin-side implementation, built from Commmerce UI components (`cm-toast`, `cm-progress-bar`,
|
|
5
|
+
* `cm-modal`, `cm-save-bar`, `cm-button`, `cm-checkbox`, `cm-radio-group`): load `@commmerce/ui` and `@commmerce/tokens` on the page first.
|
|
6
|
+
* The Commmerce admin uses its own wiring; this shows how each request should look and behave, and is what
|
|
7
|
+
* the docs example runs.
|
|
8
|
+
*/
|
|
9
|
+
export interface ReferenceHostConfig extends Omit<HostConfig, 'handlers'> {
|
|
10
|
+
/** Where toasts, modals, the save bar and the loading bar are added. Default `document.body`. */
|
|
11
|
+
root?: HTMLElement;
|
|
12
|
+
/** Update the admin's address. Default: `history.pushState` / `replaceState` with `#<path>`. */
|
|
13
|
+
navigate?: (path: string, replace: boolean) => void;
|
|
14
|
+
/** The candidates the resource picker lists. Without it, the picker answers `not-supported`. */
|
|
15
|
+
resources?: (type: ResourcePickerOptions['type']) => Promise<PickedResource[]> | PickedResource[];
|
|
16
|
+
/** Fetch a session token from the admin's backend. Without it, `getSessionToken` answers `not-supported`. */
|
|
17
|
+
sessionToken?: () => Promise<string>;
|
|
18
|
+
}
|
|
19
|
+
/** Connects the app in `iframe` to admin-level UI made from Commmerce UI components. */
|
|
20
|
+
export declare function createReferenceHost(config: ReferenceHostConfig): Host;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { createHost } from './host.js';
|
|
2
|
+
const TYPE_NAMES = { product: 'products', customer: 'customers', collection: 'collections' };
|
|
3
|
+
function el(tag, attrs = {}, text) {
|
|
4
|
+
const e = document.createElement(tag);
|
|
5
|
+
for (const [k, v] of Object.entries(attrs))
|
|
6
|
+
if (v !== false)
|
|
7
|
+
e.setAttribute(k, v === true ? '' : v);
|
|
8
|
+
if (text !== undefined)
|
|
9
|
+
e.textContent = text; // app strings are always text, never HTML
|
|
10
|
+
return e;
|
|
11
|
+
}
|
|
12
|
+
/** Shows `modal` and resolves with how it closed. */
|
|
13
|
+
function runModal(root, heading, body, actions) {
|
|
14
|
+
return new Promise((resolve) => {
|
|
15
|
+
const modal = el('cm-modal', { heading });
|
|
16
|
+
modal.append(body);
|
|
17
|
+
let value = 'close';
|
|
18
|
+
for (const a of actions) {
|
|
19
|
+
const b = el('cm-button', { slot: 'footer', variant: a.primary ? 'primary' : 'secondary' }, a.label);
|
|
20
|
+
b.addEventListener('click', () => { value = a.value; modal.close(); });
|
|
21
|
+
modal.append(b);
|
|
22
|
+
}
|
|
23
|
+
modal.addEventListener('cm-closed', () => { modal.remove(); resolve(value); });
|
|
24
|
+
root.append(modal);
|
|
25
|
+
modal.show();
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** Connects the app in `iframe` to admin-level UI made from Commmerce UI components. */
|
|
29
|
+
export function createReferenceHost(config) {
|
|
30
|
+
const root = config.root ?? document.body;
|
|
31
|
+
let host;
|
|
32
|
+
// Toasts: a cm-toast-region (a polite status region, bottom centre) holding cm-toasts.
|
|
33
|
+
const toasts = el('cm-toast-region', { 'data-app-bridge': 'toasts', max: '1' });
|
|
34
|
+
// The loading bar: an indeterminate cm-progress-bar along the top edge.
|
|
35
|
+
const bar = el('cm-progress-bar', { label: 'Loading', 'label-hidden': true, size: 'small', hidden: true, 'data-app-bridge': 'loading' });
|
|
36
|
+
bar.style.cssText = 'position:fixed;inset-block-start:0;inset-inline:0;z-index:1000';
|
|
37
|
+
const saveBar = el('cm-save-bar', { 'data-app-bridge': 'save-bar' });
|
|
38
|
+
saveBar.addEventListener('cm-save', (e) => { e.preventDefault(); host.send('saveBar.save', {}); });
|
|
39
|
+
saveBar.addEventListener('cm-discard', (e) => { e.preventDefault(); host.send('saveBar.discard', {}); });
|
|
40
|
+
root.append(toasts, bar, saveBar);
|
|
41
|
+
const handlers = {
|
|
42
|
+
toast({ message, tone = 'default', duration = 5000 }) {
|
|
43
|
+
const t = el('cm-toast', { 'data-tone': tone });
|
|
44
|
+
t.message = message; // a property, rendered as text: app strings never become HTML
|
|
45
|
+
t.tone = tone === 'critical' ? 'critical' : 'default';
|
|
46
|
+
t.duration = duration;
|
|
47
|
+
toasts.add(t);
|
|
48
|
+
},
|
|
49
|
+
async modal({ title, message, primaryAction, secondaryAction }) {
|
|
50
|
+
const actions = [];
|
|
51
|
+
if (secondaryAction)
|
|
52
|
+
actions.push({ label: secondaryAction.label, value: 'secondary' });
|
|
53
|
+
if (primaryAction)
|
|
54
|
+
actions.push({ label: primaryAction.label, value: 'primary', primary: true });
|
|
55
|
+
return await runModal(root, title, el('p', {}, message), actions);
|
|
56
|
+
},
|
|
57
|
+
navigate({ path, replace }) {
|
|
58
|
+
if (config.navigate)
|
|
59
|
+
return config.navigate(path, !!replace);
|
|
60
|
+
const url = `${location.pathname}${location.search}#${path}`;
|
|
61
|
+
if (replace)
|
|
62
|
+
history.replaceState(history.state, '', url);
|
|
63
|
+
else
|
|
64
|
+
history.pushState(history.state, '', url);
|
|
65
|
+
},
|
|
66
|
+
saveBar(options) {
|
|
67
|
+
if (!options) {
|
|
68
|
+
saveBar.open = false;
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
saveBar.message = options.message ?? 'Unsaved changes';
|
|
72
|
+
if (options.saveLabel)
|
|
73
|
+
saveBar.saveLabel = options.saveLabel;
|
|
74
|
+
if (options.discardLabel)
|
|
75
|
+
saveBar.discardLabel = options.discardLabel;
|
|
76
|
+
saveBar.loading = !!options.loading;
|
|
77
|
+
saveBar.open = true;
|
|
78
|
+
},
|
|
79
|
+
loading(on) { bar.hidden = !on; },
|
|
80
|
+
};
|
|
81
|
+
if (config.resources) {
|
|
82
|
+
const resources = config.resources;
|
|
83
|
+
handlers.resourcePicker = async ({ type, multiple }) => {
|
|
84
|
+
const items = await resources(type);
|
|
85
|
+
const list = el(multiple ? 'div' : 'cm-radio-group', multiple ? {} : { label: `Choose ${type}` });
|
|
86
|
+
list.style.cssText = 'display:grid;gap:var(--cm-space-10,10px)';
|
|
87
|
+
for (const item of items)
|
|
88
|
+
list.append(el(multiple ? 'cm-checkbox' : 'cm-radio', { label: item.title, value: item.id }));
|
|
89
|
+
const choice = await runModal(root, `Select ${TYPE_NAMES[type]}`, list, [
|
|
90
|
+
{ label: 'Cancel', value: 'secondary' }, { label: 'Select', value: 'primary', primary: true }
|
|
91
|
+
]);
|
|
92
|
+
if (choice !== 'primary')
|
|
93
|
+
return null;
|
|
94
|
+
const chosen = [...list.querySelectorAll('cm-checkbox, cm-radio')]
|
|
95
|
+
.filter((c) => c.checked).map((c) => c.value);
|
|
96
|
+
return items.filter((i) => chosen.includes(i.id));
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
if (config.sessionToken)
|
|
100
|
+
handlers.sessionToken = config.sessionToken;
|
|
101
|
+
host = createHost({ ...config, handlers });
|
|
102
|
+
const destroy = host.destroy;
|
|
103
|
+
return Object.assign(Object.create(null), {
|
|
104
|
+
send: host.send,
|
|
105
|
+
get connected() { return host.connected; },
|
|
106
|
+
destroy() { destroy(); toasts.remove(); bar.remove(); saveBar.remove(); },
|
|
107
|
+
});
|
|
108
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** The claims in every session token. */
|
|
2
|
+
export interface SessionTokenClaims {
|
|
3
|
+
/** Issuer: the origin of the admin that signed it, e.g. `https://admin.commmerce.com`. */
|
|
4
|
+
iss: string;
|
|
5
|
+
/** Destination: the store's address (origin), e.g. `https://preprod.commmerce.com`. Use it to find the store's data. */
|
|
6
|
+
dest: string;
|
|
7
|
+
/** Audience: your app's API key. Reject tokens for any other app. */
|
|
8
|
+
aud: string;
|
|
9
|
+
/** Subject: the staff member's id in that store. */
|
|
10
|
+
sub: string;
|
|
11
|
+
/** Expiry, seconds since the epoch. Tokens live 60 seconds. */
|
|
12
|
+
exp: number;
|
|
13
|
+
/** Not before, seconds since the epoch. */
|
|
14
|
+
nbf: number;
|
|
15
|
+
/** Issued at, seconds since the epoch. */
|
|
16
|
+
iat: number;
|
|
17
|
+
/** Unique token id; reject a `jti` you have already seen if you need replay protection. */
|
|
18
|
+
jti: string;
|
|
19
|
+
/** The admin session id; stays the same while the staff member is signed in. */
|
|
20
|
+
sid: string;
|
|
21
|
+
}
|
|
22
|
+
export interface VerifyOptions {
|
|
23
|
+
/** Your app's API key. Required: the token's `aud` must match. */
|
|
24
|
+
audience: string;
|
|
25
|
+
/**
|
|
26
|
+
* The admin's origin from your app settings; the token's `iss` must match. An exact origin
|
|
27
|
+
* (`https://admin.example.com`, compared exactly) or a pattern (`https://*.commmerce.com`: any admin on a
|
|
28
|
+
* subdomain, see `matchesOriginPattern`). Optional for compatibility, but always pass it.
|
|
29
|
+
*/
|
|
30
|
+
issuer?: string;
|
|
31
|
+
/** Allowed clock difference, in seconds. Default 5. */
|
|
32
|
+
clockTolerance?: number;
|
|
33
|
+
/** Current time in seconds (for tests). Default now. */
|
|
34
|
+
now?: number;
|
|
35
|
+
}
|
|
36
|
+
export type SessionTokenErrorCode = 'malformed' | 'algorithm' | 'signature' | 'expired' | 'not-yet-valid' | 'audience' | 'issuer';
|
|
37
|
+
/** Why a token was refused. Answer the request with 401. */
|
|
38
|
+
export declare class SessionTokenError extends Error {
|
|
39
|
+
code: SessionTokenErrorCode;
|
|
40
|
+
constructor(code: SessionTokenErrorCode, message: string);
|
|
41
|
+
}
|
|
42
|
+
/** Signs a session token. Fills `iat`, `nbf`, `exp` (60 s) and `jti` if they are missing. Server-side only. */
|
|
43
|
+
export declare function signSessionToken(claims: Omit<SessionTokenClaims, 'iat' | 'nbf' | 'exp' | 'jti'> & Partial<SessionTokenClaims>, secret: string): Promise<string>;
|
|
44
|
+
/** Reads a token's claims WITHOUT checking it. Never trust the result; use `verifySessionToken` on your server. */
|
|
45
|
+
export declare function decodeClaims(token: string): Partial<SessionTokenClaims>;
|
|
46
|
+
/**
|
|
47
|
+
* Verifies a session token on your backend: HS256 only (other algorithms, including `none`, are refused),
|
|
48
|
+
* the signature, `exp`, `nbf`, `aud` and optionally `iss`. Returns the claims, or throws `SessionTokenError`.
|
|
49
|
+
*/
|
|
50
|
+
export declare function verifySessionToken(token: string, secret: string, options: VerifyOptions): Promise<SessionTokenClaims>;
|