@ignite-ember/extension-bridge 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +303 -2
  4. package/dist/bridge.d.ts +33 -0
  5. package/dist/bridge.d.ts.map +1 -0
  6. package/dist/bridge.js +92 -0
  7. package/dist/bridge.js.map +1 -0
  8. package/dist/channel.d.ts +26 -0
  9. package/dist/channel.d.ts.map +1 -0
  10. package/dist/channel.js +36 -0
  11. package/dist/channel.js.map +1 -0
  12. package/dist/contract.d.ts +110 -0
  13. package/dist/contract.d.ts.map +1 -0
  14. package/dist/contract.js +9 -0
  15. package/dist/contract.js.map +1 -0
  16. package/dist/correlator.d.ts +37 -0
  17. package/dist/correlator.d.ts.map +1 -0
  18. package/dist/correlator.js +67 -0
  19. package/dist/correlator.js.map +1 -0
  20. package/dist/guestBridge.d.ts +63 -0
  21. package/dist/guestBridge.d.ts.map +1 -0
  22. package/dist/guestBridge.js +156 -0
  23. package/dist/guestBridge.js.map +1 -0
  24. package/dist/hostModel.d.ts +155 -0
  25. package/dist/hostModel.d.ts.map +1 -0
  26. package/dist/hostModel.generated.d.ts +1870 -0
  27. package/dist/hostModel.generated.d.ts.map +1 -0
  28. package/dist/hostModel.generated.js +1241 -0
  29. package/dist/hostModel.generated.js.map +1 -0
  30. package/dist/hostModel.js +168 -0
  31. package/dist/hostModel.js.map +1 -0
  32. package/dist/index.d.ts +12 -0
  33. package/dist/index.d.ts.map +1 -0
  34. package/dist/index.js +12 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/protocol.d.ts +338 -0
  37. package/dist/protocol.d.ts.map +1 -0
  38. package/dist/protocol.js +135 -0
  39. package/dist/protocol.js.map +1 -0
  40. package/dist/service.d.ts +143 -0
  41. package/dist/service.d.ts.map +1 -0
  42. package/dist/service.js +179 -0
  43. package/dist/service.js.map +1 -0
  44. package/dist/signals.d.ts +21 -0
  45. package/dist/signals.d.ts.map +1 -0
  46. package/dist/signals.js +52 -0
  47. package/dist/signals.js.map +1 -0
  48. package/dist/tokens.d.ts +95 -0
  49. package/dist/tokens.d.ts.map +1 -0
  50. package/dist/tokens.js +158 -0
  51. package/dist/tokens.js.map +1 -0
  52. package/dist/watchers.d.ts +12 -0
  53. package/dist/watchers.d.ts.map +1 -0
  54. package/dist/watchers.js +18 -0
  55. package/dist/watchers.js.map +1 -0
  56. package/package.json +53 -4
  57. package/src/bridge.ts +112 -0
  58. package/src/channel.ts +48 -0
  59. package/src/contract.ts +130 -0
  60. package/src/correlator.ts +81 -0
  61. package/src/guestBridge.ts +261 -0
  62. package/src/hostModel.generated.ts +2649 -0
  63. package/src/hostModel.ts +209 -0
  64. package/src/index.ts +11 -0
  65. package/src/protocol.ts +475 -0
  66. package/src/service.ts +253 -0
  67. package/src/signals.ts +65 -0
  68. package/src/tokens.ts +165 -0
  69. package/src/watchers.ts +18 -0
package/src/service.ts ADDED
@@ -0,0 +1,253 @@
1
+ /**
2
+ * `bridge.service`: the extension's own service, from its page, as the
3
+ * signed-in person.
4
+ *
5
+ * const notes = await bridge.service.fetch("/v1/notes");
6
+ * const room = await bridge.service.websocket("/v1/rooms/runbook");
7
+ *
8
+ * The page talks to its service directly — the host is for host things.
9
+ * What the host does is the one thing a page cannot: trade the person's
10
+ * igni session for a ten-minute token whose audience is **this
11
+ * extension's service and nothing else**. The page asks for "my token";
12
+ * igni decides whose service that is, from which extension the frame
13
+ * is. The same exchange the extension's process uses (`ext.service`),
14
+ * and the same cache.
15
+ *
16
+ * The token never leaves for anywhere but the service: `fetch` and
17
+ * `websocket` refuse a path that resolves to another origin, so a page
18
+ * cannot hand it to an egress host by accident. The frame's CSP admits
19
+ * the service's origin (`https`/`wss`) and the hosts the manifest
20
+ * declared in `permissions.egress`, and nothing else.
21
+ *
22
+ * `fetch` is a cross-origin call from igni's window. It sends the token
23
+ * and never credentials (`credentials: "omit"`); the service answers it
24
+ * because its route takes a person's token (igni-service's `BearerCors`,
25
+ * which every service gets from `igni.install`).
26
+ */
27
+
28
+ /** Why `bridge.service` could not do what was asked. */
29
+ export class ServiceError extends Error {
30
+ constructor(
31
+ /**
32
+ * `no_service` (none a page may reach), `refused` (igni gave no
33
+ * token — nobody signed in, say), `other_origin`, `closed`, `failed`.
34
+ */
35
+ readonly code: string,
36
+ message: string,
37
+ ) {
38
+ super(message);
39
+ this.name = "ServiceError";
40
+ }
41
+ }
42
+
43
+ /** What the host hands back for one token request. */
44
+ export interface IssuedToken {
45
+ /** The bearer token itself. */
46
+ token: string;
47
+ /** Seconds it has left. */
48
+ expiresIn: number;
49
+ }
50
+
51
+ /** How a socket says who it is, once it is open. */
52
+ export interface ServiceSocketOptions {
53
+ /**
54
+ * The first frame, carrying the token. A browser's WebSocket cannot
55
+ * set an `Authorization` header, and a token in the URL ends up in
56
+ * access logs, so the token goes in the first frame. The default is
57
+ * `{"type": "auth", "token": …}` — what igni's services read (the
58
+ * Artifacts document room, for one).
59
+ */
60
+ authFrame?: (token: string) => string;
61
+ /** Sub-protocols, passed to the WebSocket as they are. */
62
+ protocols?: string | string[];
63
+ }
64
+
65
+ /** `bridge.service`, as a page uses it. */
66
+ export interface ServiceBridge {
67
+ /**
68
+ * The service's URL, or `null` when this extension has none a page
69
+ * may reach — then every other member rejects with `no_service`.
70
+ */
71
+ readonly url: string | null;
72
+ /**
73
+ * A bearer token for the service. Kept until shortly before it
74
+ * expires and fetched again then; concurrent asks share one fetch.
75
+ */
76
+ token(): Promise<string>;
77
+ /**
78
+ * `fetch` against the service, with the token. `path` is relative
79
+ * to {@link url}. A `401` fetches a new token and is sent once more.
80
+ */
81
+ fetch(path: string, init?: RequestInit): Promise<Response>;
82
+ /**
83
+ * A WebSocket to `path` on the service (`https` → `wss`), resolved
84
+ * once it is open and has said who it is (see
85
+ * {@link ServiceSocketOptions.authFrame}).
86
+ */
87
+ websocket(path: string, options?: ServiceSocketOptions): Promise<WebSocket>;
88
+ }
89
+
90
+ /** Fetch a new token when the held one has less than this left. */
91
+ export const RENEW_BEFORE_MS = 60_000;
92
+
93
+ /** The default first frame: `{"type": "auth", "token": …}`. */
94
+ export function authMessage(token: string): string {
95
+ return JSON.stringify({ type: "auth", token });
96
+ }
97
+
98
+ /** `bridge.service`'s implementation; the bridge builds one per frame. */
99
+ export class ServiceLink implements ServiceBridge {
100
+ /** The token this link is holding, and when it stops being valid. */
101
+ private held: { token: string; expiresAt: number } | null = null;
102
+ /** The fetch in flight, so two asks share one request to the host. */
103
+ private fetching: Promise<string> | null = null;
104
+
105
+ /**
106
+ * One link, for one frame.
107
+ *
108
+ * @param url — the service's URL, or `null` when there is none.
109
+ * @param ask — how a token is asked of the host.
110
+ * @param env — what the browser is asked for, when it is not this one.
111
+ */
112
+ constructor(
113
+ readonly url: string | null,
114
+ private readonly ask: () => Promise<IssuedToken>,
115
+ private readonly env: {
116
+ now?: () => number;
117
+ fetch?: typeof fetch;
118
+ WebSocket?: typeof WebSocket;
119
+ } = {},
120
+ ) {}
121
+
122
+ /**
123
+ * A bearer token for the service.
124
+ *
125
+ * @returns — the token, fetched if it is not held or is nearly spent.
126
+ */
127
+ token(): Promise<string> {
128
+ return this.fresh(false);
129
+ }
130
+
131
+ /**
132
+ * `fetch` against the service, with the token.
133
+ *
134
+ * @param path — where to go, relative to the service's URL.
135
+ * @param init — what to send, as `fetch` takes it.
136
+ * @returns — the service's answer.
137
+ */
138
+ async fetch(path: string, init: RequestInit = {}): Promise<Response> {
139
+ const target = this.resolve(path, false);
140
+ const send = async (token: string) => {
141
+ const headers = new Headers(init.headers);
142
+ headers.set("Authorization", `Bearer ${token}`);
143
+ const doFetch = this.env.fetch ?? globalThis.fetch.bind(globalThis);
144
+ // The token and nothing else: no cookies, whatever the caller
145
+ // asked, so the service's own website sessions never ride along.
146
+ return doFetch(target, { ...init, headers, credentials: "omit" });
147
+ };
148
+ const first = await send(await this.fresh(false));
149
+ if (first.status !== 401) return first;
150
+ // Revoked or expired early: one new token, one more try.
151
+ return send(await this.fresh(true));
152
+ }
153
+
154
+ /**
155
+ * A socket to the service, with the token in the first frame.
156
+ *
157
+ * @param path — where to open it, relative to the service's URL.
158
+ * @param options — how the socket says who it is.
159
+ * @returns — the open socket.
160
+ */
161
+ async websocket(
162
+ path: string,
163
+ options: ServiceSocketOptions = {},
164
+ ): Promise<WebSocket> {
165
+ const target = this.resolve(path, true);
166
+ const token = await this.fresh(false);
167
+ const Socket = this.env.WebSocket ?? globalThis.WebSocket;
168
+ const frame = (options.authFrame ?? authMessage)(token);
169
+ return new Promise<WebSocket>((resolve, reject) => {
170
+ const socket = new Socket(target, options.protocols);
171
+ const opened = () => {
172
+ socket.removeEventListener("open", opened);
173
+ socket.removeEventListener("close", failed);
174
+ socket.send(frame);
175
+ resolve(socket);
176
+ };
177
+ const failed = () => {
178
+ socket.removeEventListener("open", opened);
179
+ socket.removeEventListener("close", failed);
180
+ reject(
181
+ new ServiceError("closed", `the service closed ${path} before it opened`),
182
+ );
183
+ };
184
+ socket.addEventListener("open", opened);
185
+ // `error` is always followed by `close`; one rejection is enough.
186
+ socket.addEventListener("close", failed);
187
+ });
188
+ }
189
+
190
+ /**
191
+ * A token that is worth handing out: the held one if it has time
192
+ * left, a new one otherwise.
193
+ *
194
+ * @param force — fetch a new one even when the held one is good.
195
+ * @returns — the token.
196
+ */
197
+ private async fresh(force: boolean): Promise<string> {
198
+ if (this.url === null) {
199
+ throw new ServiceError(
200
+ "no_service",
201
+ "this extension has no service its page may reach",
202
+ );
203
+ }
204
+ const now = (this.env.now ?? Date.now)();
205
+ if (!force && this.held && this.held.expiresAt - now > RENEW_BEFORE_MS) {
206
+ return this.held.token;
207
+ }
208
+ if (this.fetching) return this.fetching;
209
+ this.fetching = this.ask()
210
+ .then((issued) => {
211
+ this.held = {
212
+ token: issued.token,
213
+ expiresAt: (this.env.now ?? Date.now)() + issued.expiresIn * 1000,
214
+ };
215
+ return issued.token;
216
+ })
217
+ .finally(() => {
218
+ this.fetching = null;
219
+ });
220
+ return this.fetching;
221
+ }
222
+
223
+ /** `path` on the service, or a refusal if it is anywhere else. */
224
+ private resolve(path: string, socket: boolean): string {
225
+ if (this.url === null) {
226
+ throw new ServiceError(
227
+ "no_service",
228
+ "this extension has no service its page may reach",
229
+ );
230
+ }
231
+ const base = new URL(this.url);
232
+ const joined = new URL(
233
+ `${base.pathname.replace(/\/$/, "")}/${path.replace(/^\//, "")}`,
234
+ base,
235
+ );
236
+ // Something like `//elsewhere.example/x` or a full URL would land
237
+ // on another origin, and the token goes only to the service.
238
+ if (
239
+ /^[a-z][a-z0-9+.-]*:/i.test(path) ||
240
+ path.startsWith("//") ||
241
+ joined.origin !== base.origin
242
+ ) {
243
+ throw new ServiceError(
244
+ "other_origin",
245
+ `'${path}' is not on this extension's service; its token goes nowhere else`,
246
+ );
247
+ }
248
+ if (socket) {
249
+ joined.protocol = joined.protocol === "https:" ? "wss:" : "ws:";
250
+ }
251
+ return joined.toString();
252
+ }
253
+ }
package/src/signals.ts ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The host signals a page handles: `bridge.on(signal, fn)`.
3
+ *
4
+ * The first handler of a signal subscribes to it; removing the last one
5
+ * unsubscribes. A refused subscription is reported, not swallowed: to
6
+ * the handler's `onRefused` when it gave one, to the console otherwise.
7
+ */
8
+
9
+ import type { HostError, Signal } from "./hostModel.js";
10
+ import type { HostSignalMessage } from "./protocol.js";
11
+
12
+ /** Asks the host to start or stop sending one signal. */
13
+ export type SignalRequest = (
14
+ op: "subscribe" | "unsubscribe",
15
+ signal: string,
16
+ ) => Promise<unknown>;
17
+
18
+ export class SignalSubscriptions {
19
+ private readonly handlers = new Map<string, Set<(value: unknown) => void>>();
20
+
21
+ constructor(private readonly request: SignalRequest) {}
22
+
23
+ on<T>(
24
+ signal: Signal<T>,
25
+ fn: (value: T) => void,
26
+ onRefused?: (error: HostError) => void,
27
+ ): () => void {
28
+ const wire = signal.name;
29
+ let handlers = this.handlers.get(wire);
30
+ if (handlers === undefined) {
31
+ handlers = new Set();
32
+ this.handlers.set(wire, handlers);
33
+ this.request("subscribe", wire).catch((error: HostError) => {
34
+ if (onRefused) onRefused(error);
35
+ else
36
+ console.warn(
37
+ `igni bridge: subscribing to ${wire} failed: ${error.message}`,
38
+ );
39
+ });
40
+ }
41
+ const handler = fn as (value: unknown) => void;
42
+ handlers.add(handler);
43
+ return () => this.off(wire, handler);
44
+ }
45
+
46
+ /** Hand a signal the host sent to everything handling it. */
47
+ deliver(message: HostSignalMessage): void {
48
+ const handlers = this.handlers.get(message.signal);
49
+ if (handlers === undefined) return;
50
+ for (const fn of handlers) fn(message.value);
51
+ }
52
+
53
+ private off(wire: string, handler: (value: unknown) => void): void {
54
+ const current = this.handlers.get(wire);
55
+ if (current === undefined) return;
56
+ current.delete(handler);
57
+ if (current.size > 0) return;
58
+ this.handlers.delete(wire);
59
+ this.request("unsubscribe", wire).catch((error: HostError) => {
60
+ console.warn(
61
+ `igni bridge: unsubscribing from ${wire} failed: ${error.message}`,
62
+ );
63
+ });
64
+ }
65
+ }
package/src/tokens.ts ADDED
@@ -0,0 +1,165 @@
1
+ /**
2
+ * The design tokens an extension may rely on, and how they travel.
3
+ *
4
+ * An extension's page is a different origin, so it cannot read this
5
+ * app's stylesheet — and the CSP on its own origin would block
6
+ * fetching one. So the values are **pushed**, over the bridge, at
7
+ * handshake and again whenever they change.
8
+ *
9
+ * Pushed rather than copied into the package on purpose. A static
10
+ * copy is a second description of the theme, and a second description
11
+ * drifts: `theme.css` defines these across forty-five blocks — a
12
+ * ``:root``, a light override, and a ``prefers-color-scheme`` block
13
+ * per feature. Anything duplicating that is wrong within a release.
14
+ * This reads the live computed values instead, so an extension
15
+ * follows dark mode, light mode, and whatever a group's policy pack
16
+ * has branded, without knowing any of those exist.
17
+ *
18
+ * **This list is the floor.** A token named here is one an extension
19
+ * may build against, and removing or repurposing one is a breaking
20
+ * change under the compatibility policy. A token *not* named here is
21
+ * ours to change freely — which is why the list is curated rather
22
+ * than "every custom property in the stylesheet". Layout internals
23
+ * like ``--rail-width`` and ``--crumb-row-h`` are deliberately absent:
24
+ * they describe this app's chrome, and an extension that positioned
25
+ * itself against them would break the first time we moved something.
26
+ */
27
+
28
+ /**
29
+ * Published tokens, by what they are for.
30
+ *
31
+ * Grouped because the groups are how an author reads them: pick a
32
+ * surface, pick the text that goes on it, pick a tone for the
33
+ * meaning. Names match the app's own so a reader moving between the
34
+ * two is not translating.
35
+ */
36
+ export const PUBLISHED_TOKENS = {
37
+ /** Surfaces, back to front. */
38
+ surface: ["--bg", "--bg-inset", "--bg-surface", "--bg-raised"],
39
+ /** Text, in descending prominence. */
40
+ text: ["--fg", "--fg-muted", "--fg-faint"],
41
+ /** Lines between things. */
42
+ line: ["--border", "--border-soft"],
43
+ /** Meaning. ``*-text`` variants are the contrast-safe ones for type. */
44
+ tone: [
45
+ "--success",
46
+ "--warning",
47
+ "--danger",
48
+ "--danger-text",
49
+ "--accent-blue",
50
+ "--accent-blue-text",
51
+ "--accent-green-text",
52
+ "--accent-orange-text",
53
+ "--accent-red-text",
54
+ ],
55
+ /** The product's own colour. Use sparingly; it means igni. */
56
+ brand: [
57
+ "--igni-orange",
58
+ "--igni-orange-hover",
59
+ "--igni-red",
60
+ "--igni-gradient",
61
+ ],
62
+ /** Shape. */
63
+ form: [
64
+ "--radius-sm",
65
+ "--radius",
66
+ "--radius-lg",
67
+ "--radius-pill",
68
+ "--radius-circle",
69
+ "--font-ui",
70
+ "--font-mono",
71
+ "--shadow-pop",
72
+ ],
73
+ /**
74
+ * The type scale. Nine steps, by role rather than by ratio.
75
+ *
76
+ * It replaced twenty-two hardcoded sizes that included every
77
+ * half-step from 9px to 15px — 11.5px, 12px and 12.5px between
78
+ * them accounted for 272 declarations, which is one size written
79
+ * three ways. Build against the role, not the pixel.
80
+ */
81
+ type: [
82
+ "--text-2xs",
83
+ "--text-xs",
84
+ "--text-sm",
85
+ "--text-md",
86
+ "--text-lg",
87
+ "--text-xl",
88
+ "--text-2xl",
89
+ "--text-3xl",
90
+ "--text-4xl",
91
+ ],
92
+ /**
93
+ * The spacing scale. Published so an extension's layout sits on the
94
+ * same rhythm as the app around it rather than next to it.
95
+ *
96
+ * These steps are the ones igni already used — they were written as
97
+ * literals in three hundred and seventy-five places, which is why
98
+ * adopting them changed nothing on screen.
99
+ */
100
+ space: [
101
+ "--space-1",
102
+ "--space-2",
103
+ "--space-3",
104
+ "--space-4",
105
+ "--space-5",
106
+ "--space-6",
107
+ "--space-7",
108
+ "--space-8",
109
+ "--space-10",
110
+ "--space-12",
111
+ "--space-16",
112
+ ],
113
+ } as const;
114
+
115
+ /**
116
+ * Every published token name, flat.
117
+ *
118
+ * Derived rather than listed. A second list would be a second place
119
+ * to forget — and the groups above are an object literal, where a
120
+ * repeated key silently keeps only the last one. That happened: the
121
+ * type scale was added as `text`, which was already the foreground
122
+ * colours, and `--fg` disappeared without a word.
123
+ */
124
+ export const TOKEN_NAMES: readonly string[] =
125
+ Object.values(PUBLISHED_TOKENS).flat();
126
+
127
+ /** Token name → current value. */
128
+ export type ThemeTokens = Record<string, string>;
129
+
130
+ /**
131
+ * Read the published tokens as they are right now.
132
+ *
133
+ * Computed values, not declared ones: a token defined in a media
134
+ * query or overridden by a `data-theme` attribute resolves here to
135
+ * what the user is actually looking at, which is the only answer
136
+ * worth sending.
137
+ */
138
+ export function readThemeTokens(
139
+ root: Element = document.documentElement,
140
+ ): ThemeTokens {
141
+ const computed = getComputedStyle(root);
142
+ const out: ThemeTokens = {};
143
+ for (const name of TOKEN_NAMES) {
144
+ const value = computed.getPropertyValue(name).trim();
145
+ // A token the host has not defined is omitted rather than sent
146
+ // empty: the guest's stylesheet carries a fallback for each, and
147
+ // an empty string would override it with nothing.
148
+ if (value) out[name] = value;
149
+ }
150
+ return out;
151
+ }
152
+
153
+ /**
154
+ * Apply tokens inside the extension's own document.
155
+ *
156
+ * Called by the guest bridge. Separate from reading them so the two
157
+ * halves can be tested without a frame between them.
158
+ */
159
+ export function applyThemeTokens(tokens: ThemeTokens, root: HTMLElement): void {
160
+ for (const [name, value] of Object.entries(tokens)) {
161
+ // Only published names, even though the host is trusted: a typo
162
+ // on our side should not silently define something in theirs.
163
+ if (TOKEN_NAMES.includes(name)) root.style.setProperty(name, value);
164
+ }
165
+ }
@@ -0,0 +1,18 @@
1
+ /** Functions following one value: added, removed, and told of a change. */
2
+ export class Watchers<T> {
3
+ private readonly fns = new Set<(value: T) => void>();
4
+
5
+ /**
6
+ * Follow the value. Returns an unsubscribe, which answers whether it
7
+ * stopped anything: true the first time, false after.
8
+ */
9
+ add(fn: (value: T) => void): () => void {
10
+ this.fns.add(fn);
11
+ return () => this.fns.delete(fn);
12
+ }
13
+
14
+ /** Tell every watcher the value is now `value`. */
15
+ emit(value: T): void {
16
+ for (const fn of this.fns) fn(value);
17
+ }
18
+ }