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

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 +364 -2
  4. package/dist/bridge.d.ts +37 -0
  5. package/dist/bridge.d.ts.map +1 -0
  6. package/dist/bridge.js +96 -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 +137 -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 +75 -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 +159 -0
  25. package/dist/hostModel.d.ts.map +1 -0
  26. package/dist/hostModel.generated.d.ts +2373 -0
  27. package/dist/hostModel.generated.d.ts.map +1 -0
  28. package/dist/hostModel.generated.js +1746 -0
  29. package/dist/hostModel.generated.js.map +1 -0
  30. package/dist/hostModel.js +172 -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 +348 -0
  37. package/dist/protocol.d.ts.map +1 -0
  38. package/dist/protocol.js +145 -0
  39. package/dist/protocol.js.map +1 -0
  40. package/dist/service.d.ts +168 -0
  41. package/dist/service.d.ts.map +1 -0
  42. package/dist/service.js +196 -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 +101 -0
  49. package/dist/tokens.d.ts.map +1 -0
  50. package/dist/tokens.js +164 -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 +116 -0
  58. package/src/channel.ts +48 -0
  59. package/src/contract.ts +157 -0
  60. package/src/correlator.ts +88 -0
  61. package/src/guestBridge.ts +261 -0
  62. package/src/hostModel.generated.ts +3155 -0
  63. package/src/hostModel.ts +213 -0
  64. package/src/index.ts +11 -0
  65. package/src/protocol.ts +485 -0
  66. package/src/service.ts +278 -0
  67. package/src/signals.ts +65 -0
  68. package/src/tokens.ts +171 -0
  69. package/src/watchers.ts +18 -0
@@ -0,0 +1,145 @@
1
+ /**
2
+ * What crosses the gap between the host app and an extension's frame.
3
+ *
4
+ * One envelope type, versioned, with the host and the guest reading
5
+ * the same definition. The guest half of this file is the part that
6
+ * becomes a published package when somebody outside this repository
7
+ * writes an extension; until then both sides import it from here, so
8
+ * there is one description of the wire rather than two that agree
9
+ * until they don't.
10
+ *
11
+ * The frame is the untrusted party. Everything the host accepts from
12
+ * it is checked — the origin it came from, the window it came from,
13
+ * the nonce it was issued, and whether the method is one this
14
+ * extension was granted. None of those checks live in the guest.
15
+ */
16
+ /** Bumped only for a change the other side cannot ignore. */
17
+ export const BRIDGE_VERSION = 1;
18
+ const HOST_OPS = new Set(["get", "set", "call", "subscribe", "unsubscribe"]);
19
+ /**
20
+ * Is this a message from a guest, shaped the way we require?
21
+ *
22
+ * Written as a narrowing guard rather than a schema check because the
23
+ * host has to answer this about `unknown` arriving from a frame, and
24
+ * the answer has to be "no" for everything that is not exactly right.
25
+ * A message that fails here is dropped without a reply: a guest that
26
+ * can tell malformed from unauthorised has learned something.
27
+ *
28
+ * @param data — the message as it arrived, in whatever shape it is.
29
+ */
30
+ export function isGuestMessage(data) {
31
+ if (typeof data !== "object" || data === null)
32
+ return false;
33
+ const m = data;
34
+ if (m.igni !== BRIDGE_VERSION)
35
+ return false;
36
+ if (typeof m.nonce !== "string" || m.nonce.length === 0)
37
+ return false;
38
+ switch (m.kind) {
39
+ case "call":
40
+ return (typeof m.id === "string" &&
41
+ m.id.length > 0 &&
42
+ typeof m.method === "string" &&
43
+ m.method.length > 0 &&
44
+ typeof m.args === "object" &&
45
+ m.args !== null &&
46
+ !Array.isArray(m.args));
47
+ case "navigate":
48
+ return typeof m.to === "string" && m.to.length > 0;
49
+ case "location":
50
+ // Every value a string, checked rather than assumed: this goes
51
+ // into the host's own URL, and a guest is the untrusted party.
52
+ return (typeof m.state === "object" &&
53
+ m.state !== null &&
54
+ !Array.isArray(m.state) &&
55
+ Object.values(m.state).every((value) => typeof value === "string"));
56
+ case "close":
57
+ return true;
58
+ case "service-token":
59
+ return typeof m.id === "string" && m.id.length > 0;
60
+ case "host":
61
+ return (typeof m.id === "string" &&
62
+ m.id.length > 0 &&
63
+ typeof m.op === "string" &&
64
+ HOST_OPS.has(m.op) &&
65
+ typeof m.path === "string" &&
66
+ (m.window === undefined ||
67
+ m.window === null ||
68
+ typeof m.window === "string") &&
69
+ (m.session === undefined ||
70
+ m.session === null ||
71
+ typeof m.session === "string") &&
72
+ (m.params === undefined ||
73
+ (typeof m.params === "object" &&
74
+ m.params !== null &&
75
+ !Array.isArray(m.params))) &&
76
+ (m.signals === undefined ||
77
+ (Array.isArray(m.signals) &&
78
+ m.signals.every((one) => typeof one === "string"))));
79
+ default:
80
+ return false;
81
+ }
82
+ }
83
+ /**
84
+ * Is this a message from the host, shaped the way the guest requires?
85
+ *
86
+ * @param data — the message as it arrived, in whatever shape it is.
87
+ */
88
+ export function isHostMessage(data) {
89
+ if (typeof data !== "object" || data === null)
90
+ return false;
91
+ const m = data;
92
+ if (m.igni !== BRIDGE_VERSION)
93
+ return false;
94
+ switch (m.kind) {
95
+ case "hello":
96
+ return (typeof m.nonce === "string" &&
97
+ typeof m.extensionId === "string" &&
98
+ typeof m.theme === "string" &&
99
+ typeof m.params === "object" &&
100
+ m.params !== null &&
101
+ (m.settings === undefined || (typeof m.settings === "object" && m.settings !== null)) &&
102
+ (m.serviceUrl === undefined || m.serviceUrl === null || typeof m.serviceUrl === "string") &&
103
+ typeof m.tokens === "object" &&
104
+ m.tokens !== null);
105
+ case "theme":
106
+ return (typeof m.theme === "string" &&
107
+ typeof m.tokens === "object" &&
108
+ m.tokens !== null);
109
+ case "params":
110
+ return (typeof m.params === "object" &&
111
+ m.params !== null &&
112
+ !Array.isArray(m.params));
113
+ case "result":
114
+ return typeof m.id === "string" && typeof m.ok === "boolean";
115
+ case "host-reply":
116
+ return typeof m.id === "string" && typeof m.ok === "boolean";
117
+ case "service-token-reply":
118
+ return (typeof m.id === "string" &&
119
+ typeof m.ok === "boolean" &&
120
+ (m.token === undefined || typeof m.token === "string") &&
121
+ (m.expiresIn === undefined || typeof m.expiresIn === "number"));
122
+ case "signal":
123
+ return typeof m.signal === "string" && m.signal.length > 0;
124
+ default:
125
+ return false;
126
+ }
127
+ }
128
+ /**
129
+ * May this extension call this method?
130
+ *
131
+ * Exact names, or a `*`-suffixed prefix. No regular expressions and no
132
+ * `*` anywhere but the end: a permission list is read by whoever
133
+ * approves an install, and a pattern language it cannot be read in is
134
+ * a permission nobody actually granted.
135
+ *
136
+ * @param method — the method the extension wants to call.
137
+ * @param allow — the methods it was granted, as exact names or as
138
+ * `*`-suffixed prefixes.
139
+ */
140
+ export function methodAllowed(method, allow) {
141
+ return allow.some((pattern) => pattern.endsWith("*")
142
+ ? method.startsWith(pattern.slice(0, -1))
143
+ : method === pattern);
144
+ }
145
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/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zC,CAAC,CAAC,MAAM,KAAK,OAAO,CACvB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,168 @@
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
+ /** Why `bridge.service` could not do what was asked. */
28
+ export declare class ServiceError extends Error {
29
+ /**
30
+ * `no_service` (none a page may reach), `refused` (igni gave no
31
+ * token — nobody signed in, say), `other_origin`, `closed`, `failed`.
32
+ */
33
+ readonly code: string;
34
+ /**
35
+ * Why the service could not do what was asked.
36
+ *
37
+ * @param code — why it failed: `no_service`, `refused`,
38
+ * `other_origin`, `closed` or `failed`.
39
+ * @param message — a sentence for a person to read.
40
+ */
41
+ constructor(
42
+ /**
43
+ * `no_service` (none a page may reach), `refused` (igni gave no
44
+ * token — nobody signed in, say), `other_origin`, `closed`, `failed`.
45
+ */
46
+ code: string, message: string);
47
+ }
48
+ /** What the host hands back for one token request. */
49
+ export interface IssuedToken {
50
+ /** The bearer token itself. */
51
+ token: string;
52
+ /** Seconds it has left. */
53
+ expiresIn: number;
54
+ }
55
+ /** How a socket says who it is, once it is open. */
56
+ export interface ServiceSocketOptions {
57
+ /**
58
+ * The first frame, carrying the token. A browser's WebSocket cannot
59
+ * set an `Authorization` header, and a token in the URL ends up in
60
+ * access logs, so the token goes in the first frame. The default is
61
+ * `{"type": "auth", "token": …}` — what igni's services read (the
62
+ * Artifacts document room, for one).
63
+ */
64
+ authFrame?: (token: string) => string;
65
+ /** Sub-protocols, passed to the WebSocket as they are. */
66
+ protocols?: string | string[];
67
+ }
68
+ /** `bridge.service`, as a page uses it. */
69
+ export interface ServiceBridge {
70
+ /**
71
+ * The service's URL, or `null` when this extension has none a page
72
+ * may reach — then every other member rejects with `no_service`.
73
+ */
74
+ readonly url: string | null;
75
+ /**
76
+ * A bearer token for the service. Kept until shortly before it
77
+ * expires and fetched again then; concurrent asks share one fetch.
78
+ */
79
+ token(): Promise<string>;
80
+ /**
81
+ * `fetch` against the service, with the token. `path` is relative
82
+ * to {@link url}. A `401` fetches a new token and is sent once more.
83
+ *
84
+ * @param path — where to go, relative to the service's URL.
85
+ * @param init — what to send, as `fetch` takes it.
86
+ */
87
+ fetch(path: string, init?: RequestInit): Promise<Response>;
88
+ /**
89
+ * A WebSocket to `path` on the service (`https` → `wss`), resolved
90
+ * once it is open and has said who it is (see
91
+ * {@link ServiceSocketOptions.authFrame}).
92
+ *
93
+ * @param path — where to open the socket, relative to the service's
94
+ * URL.
95
+ * @param options — how the socket says who it is: the first frame,
96
+ * and the sub-protocols.
97
+ */
98
+ websocket(path: string, options?: ServiceSocketOptions): Promise<WebSocket>;
99
+ }
100
+ /** Fetch a new token when the held one has less than this left. */
101
+ export declare const RENEW_BEFORE_MS = 60000;
102
+ /**
103
+ * The default first frame: `{"type": "auth", "token": …}`.
104
+ *
105
+ * @param token — the bearer token the frame carries.
106
+ */
107
+ export declare function authMessage(token: string): string;
108
+ /** `bridge.service`'s implementation; the bridge builds one per frame. */
109
+ export declare class ServiceLink implements ServiceBridge {
110
+ readonly url: string | null;
111
+ private readonly ask;
112
+ private readonly env;
113
+ /** The token this link is holding, and when it stops being valid. */
114
+ private held;
115
+ /** The fetch in flight, so two asks share one request to the host. */
116
+ private fetching;
117
+ /**
118
+ * One link, for one frame.
119
+ *
120
+ * @param url — the service's URL, or `null` when there is none.
121
+ * @param ask — how a token is asked of the host.
122
+ * @param env — what the browser is asked for, when it is not this one.
123
+ */
124
+ constructor(url: string | null, ask: () => Promise<IssuedToken>, env?: {
125
+ now?: () => number;
126
+ fetch?: typeof fetch;
127
+ WebSocket?: typeof WebSocket;
128
+ });
129
+ /**
130
+ * A bearer token for the service.
131
+ *
132
+ * @returns — the token, fetched if it is not held or is nearly spent.
133
+ */
134
+ token(): Promise<string>;
135
+ /**
136
+ * `fetch` against the service, with the token.
137
+ *
138
+ * @param path — where to go, relative to the service's URL.
139
+ * @param init — what to send, as `fetch` takes it.
140
+ * @returns — the service's answer.
141
+ */
142
+ fetch(path: string, init?: RequestInit): Promise<Response>;
143
+ /**
144
+ * A socket to the service, with the token in the first frame.
145
+ *
146
+ * @param path — where to open it, relative to the service's URL.
147
+ * @param options — how the socket says who it is.
148
+ * @returns — the open socket.
149
+ */
150
+ websocket(path: string, options?: ServiceSocketOptions): Promise<WebSocket>;
151
+ /**
152
+ * A token that is worth handing out: the held one if it has time
153
+ * left, a new one otherwise.
154
+ *
155
+ * @param force — fetch a new one even when the held one is good.
156
+ * @returns — the token.
157
+ */
158
+ private fresh;
159
+ /**
160
+ * `path` on the service, or a refusal if it is anywhere else.
161
+ *
162
+ * @param path — the path on the service, relative to its URL.
163
+ * @param socket — whether the path is opened as a socket, which turns
164
+ * `https` into `wss`.
165
+ */
166
+ private resolve;
167
+ }
168
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,wDAAwD;AACxD,q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AqE;IACrE,OAAO,CAAC,IAAI,CAAqD;IACjE,sEAAsE;IACtE,OAAO,CAAC,QAAQ,CAAgC;IAEhD;;;;;;OAMG;gBAEQ,GAAG,EAAE,MAAM,GAAG,IAAI,EACV,GAAG,EAAE,MAAM,OAAO,CAAC,WAAW,CAAC,EAC/B,GAAG,GAAE;QACpB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;QACnB,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;QACrB,SAAS,CAAC,EAAE,OAAO,SAAS,CAAC;KACzB;IAGR;;;;OAIG;IACH,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC;IAIxB;;;;;;OAMG;IACG,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,WAAgB,GAAG,OAAO,CAAC,QAAQ,CAAC;IAgBpE;;;;;;OAMG;IACG,SAAS,CACb,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,SAAS,CAAC;IA0BrB;;;;;;OAMG;YACW,KAAK;IA0BnB;;;;;;OAMG;IACH,OAAO,CAAC,OAAO;CA6BhB"}
@@ -0,0 +1,196 @@
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
+ /** Why `bridge.service` could not do what was asked. */
28
+ export class ServiceError extends Error {
29
+ code;
30
+ /**
31
+ * Why the service could not do what was asked.
32
+ *
33
+ * @param code — why it failed: `no_service`, `refused`,
34
+ * `other_origin`, `closed` or `failed`.
35
+ * @param message — a sentence for a person to read.
36
+ */
37
+ constructor(
38
+ /**
39
+ * `no_service` (none a page may reach), `refused` (igni gave no
40
+ * token — nobody signed in, say), `other_origin`, `closed`, `failed`.
41
+ */
42
+ code, message) {
43
+ super(message);
44
+ this.code = code;
45
+ this.name = "ServiceError";
46
+ }
47
+ }
48
+ /** Fetch a new token when the held one has less than this left. */
49
+ export const RENEW_BEFORE_MS = 60_000;
50
+ /**
51
+ * The default first frame: `{"type": "auth", "token": …}`.
52
+ *
53
+ * @param token — the bearer token the frame carries.
54
+ */
55
+ export function authMessage(token) {
56
+ return JSON.stringify({ type: "auth", token });
57
+ }
58
+ /** `bridge.service`'s implementation; the bridge builds one per frame. */
59
+ export class ServiceLink {
60
+ url;
61
+ ask;
62
+ env;
63
+ /** The token this link is holding, and when it stops being valid. */
64
+ held = null;
65
+ /** The fetch in flight, so two asks share one request to the host. */
66
+ fetching = null;
67
+ /**
68
+ * One link, for one frame.
69
+ *
70
+ * @param url — the service's URL, or `null` when there is none.
71
+ * @param ask — how a token is asked of the host.
72
+ * @param env — what the browser is asked for, when it is not this one.
73
+ */
74
+ constructor(url, ask, env = {}) {
75
+ this.url = url;
76
+ this.ask = ask;
77
+ this.env = env;
78
+ }
79
+ /**
80
+ * A bearer token for the service.
81
+ *
82
+ * @returns — the token, fetched if it is not held or is nearly spent.
83
+ */
84
+ token() {
85
+ return this.fresh(false);
86
+ }
87
+ /**
88
+ * `fetch` against the service, with the token.
89
+ *
90
+ * @param path — where to go, relative to the service's URL.
91
+ * @param init — what to send, as `fetch` takes it.
92
+ * @returns — the service's answer.
93
+ */
94
+ async fetch(path, init = {}) {
95
+ const target = this.resolve(path, false);
96
+ const send = async (token) => {
97
+ const headers = new Headers(init.headers);
98
+ headers.set("Authorization", `Bearer ${token}`);
99
+ const doFetch = this.env.fetch ?? globalThis.fetch.bind(globalThis);
100
+ // The token and nothing else: no cookies, whatever the caller
101
+ // asked, so the service's own website sessions never ride along.
102
+ return doFetch(target, { ...init, headers, credentials: "omit" });
103
+ };
104
+ const first = await send(await this.fresh(false));
105
+ if (first.status !== 401)
106
+ return first;
107
+ // Revoked or expired early: one new token, one more try.
108
+ return send(await this.fresh(true));
109
+ }
110
+ /**
111
+ * A socket to the service, with the token in the first frame.
112
+ *
113
+ * @param path — where to open it, relative to the service's URL.
114
+ * @param options — how the socket says who it is.
115
+ * @returns — the open socket.
116
+ */
117
+ async websocket(path, options = {}) {
118
+ const target = this.resolve(path, true);
119
+ const token = await this.fresh(false);
120
+ const Socket = this.env.WebSocket ?? globalThis.WebSocket;
121
+ const frame = (options.authFrame ?? authMessage)(token);
122
+ return new Promise((resolve, reject) => {
123
+ const socket = new Socket(target, options.protocols);
124
+ const opened = () => {
125
+ socket.removeEventListener("open", opened);
126
+ socket.removeEventListener("close", failed);
127
+ socket.send(frame);
128
+ resolve(socket);
129
+ };
130
+ const failed = () => {
131
+ socket.removeEventListener("open", opened);
132
+ socket.removeEventListener("close", failed);
133
+ reject(new ServiceError("closed", `the service closed ${path} before it opened`));
134
+ };
135
+ socket.addEventListener("open", opened);
136
+ // `error` is always followed by `close`; one rejection is enough.
137
+ socket.addEventListener("close", failed);
138
+ });
139
+ }
140
+ /**
141
+ * A token that is worth handing out: the held one if it has time
142
+ * left, a new one otherwise.
143
+ *
144
+ * @param force — fetch a new one even when the held one is good.
145
+ * @returns — the token.
146
+ */
147
+ async fresh(force) {
148
+ if (this.url === null) {
149
+ throw new ServiceError("no_service", "this extension has no service its page may reach");
150
+ }
151
+ const now = (this.env.now ?? Date.now)();
152
+ if (!force && this.held && this.held.expiresAt - now > RENEW_BEFORE_MS) {
153
+ return this.held.token;
154
+ }
155
+ if (this.fetching)
156
+ return this.fetching;
157
+ this.fetching = this.ask()
158
+ .then((issued) => {
159
+ this.held = {
160
+ token: issued.token,
161
+ expiresAt: (this.env.now ?? Date.now)() + issued.expiresIn * 1000,
162
+ };
163
+ return issued.token;
164
+ })
165
+ .finally(() => {
166
+ this.fetching = null;
167
+ });
168
+ return this.fetching;
169
+ }
170
+ /**
171
+ * `path` on the service, or a refusal if it is anywhere else.
172
+ *
173
+ * @param path — the path on the service, relative to its URL.
174
+ * @param socket — whether the path is opened as a socket, which turns
175
+ * `https` into `wss`.
176
+ */
177
+ resolve(path, socket) {
178
+ if (this.url === null) {
179
+ throw new ServiceError("no_service", "this extension has no service its page may reach");
180
+ }
181
+ const base = new URL(this.url);
182
+ const joined = new URL(`${base.pathname.replace(/\/$/, "")}/${path.replace(/^\//, "")}`, base);
183
+ // Something like `//elsewhere.example/x` or a full URL would land
184
+ // on another origin, and the token goes only to the service.
185
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path) ||
186
+ path.startsWith("//") ||
187
+ joined.origin !== base.origin) {
188
+ throw new ServiceError("other_origin", `'${path}' is not on this extension's service; its token goes nowhere else`);
189
+ }
190
+ if (socket) {
191
+ joined.protocol = joined.protocol === "https:" ? "wss:" : "ws:";
192
+ }
193
+ return joined.toString();
194
+ }
195
+ }
196
+ //# sourceMappingURL=service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.js","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,wDAAwD;AACxD,MAAM,OAAO,YAAa,SAAQ,KAAK;IAa1B;IAZX;;;;;;OAMG;IACH;IACE;;;OAGG;IACM,IAAY,EACrB,OAAe;QAEf,KAAK,CAAC,OAAO,CAAC,CAAC;QAHN,SAAI,GAAJ,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AAO,MAAM,CAAC,KAAK,CAAC;QACtB,CAAC,CAAC;aACD,OAAO,CAAC,GAAG,EAAE;YACZ,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACvB,CAAC,CAAC,CAAC;QACL,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED;;;;;;OAMG;IACK,OAAO,CAAC,IAAY,EAAE,MAAe;QAC3C,IAAI,IAAI,CAAC,GAAG,KAAK,IAAI,EAAE,CAAC;YACtB,MAAM,IAAI,YAAY,CACpB,YAAY,EACZ,kDAAkD,CACnD,CAAC;QACJ,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC/B,MAAM,MAAM,GAAG,IAAI,GAAG,CACpB,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,EAChE,IAAI,CACL,CAAC;QACF,kEAAkE;QAClE,6DAA6D;QAC7D,IACE,sBAAsB,CAAC,IAAI,CAAC,IAAI,CAAC;YACjC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;YACrB,MAAM,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,EAC7B,CAAC;YACD,MAAM,IAAI,YAAY,CACpB,cAAc,EACd,IAAI,IAAI,mEAAmE,CAC5E,CAAC;QACJ,CAAC;QACD,IAAI,MAAM,EAAE,CAAC;YACX,MAAM,CAAC,QAAQ,GAAG,MAAM,CAAC,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC;QAClE,CAAC;QACD,OAAO,MAAM,CAAC,QAAQ,EAAE,CAAC;IAC3B,CAAC;CACF"}
@@ -0,0 +1,21 @@
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
+ import type { HostError, Signal } from "./hostModel.js";
9
+ import type { HostSignalMessage } from "./protocol.js";
10
+ /** Asks the host to start or stop sending one signal. */
11
+ export type SignalRequest = (op: "subscribe" | "unsubscribe", signal: string) => Promise<unknown>;
12
+ export declare class SignalSubscriptions {
13
+ private readonly request;
14
+ private readonly handlers;
15
+ constructor(request: SignalRequest);
16
+ on<T>(signal: Signal<T>, fn: (value: T) => void, onRefused?: (error: HostError) => void): () => void;
17
+ /** Hand a signal the host sent to everything handling it. */
18
+ deliver(message: HostSignalMessage): void;
19
+ private off;
20
+ }
21
+ //# sourceMappingURL=signals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signals.d.ts","sourceRoot":"","sources":["../src/signals.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAEvD,yDAAyD;AACzD,MAAM,MAAM,aAAa,GAAG,CAC1B,EAAE,EAAE,WAAW,GAAG,aAAa,EAC/B,MAAM,EAAE,MAAM,KACX,OAAO,CAAC,OAAO,CAAC,CAAC;AAEtB,qBAAa,mBAAmB;IAGlB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAFpC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAoD;gBAEhD,OAAO,EAAE,aAAa;IAEnD,EAAE,CAAC,CAAC,EACF,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,EACjB,EAAE,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,IAAI,EACtB,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI,GACrC,MAAM,IAAI;IAmBb,6DAA6D;IAC7D,OAAO,CAAC,OAAO,EAAE,iBAAiB,GAAG,IAAI;IAMzC,OAAO,CAAC,GAAG;CAYZ"}
@@ -0,0 +1,52 @@
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
+ export class SignalSubscriptions {
9
+ request;
10
+ handlers = new Map();
11
+ constructor(request) {
12
+ this.request = request;
13
+ }
14
+ on(signal, fn, onRefused) {
15
+ const wire = signal.name;
16
+ let handlers = this.handlers.get(wire);
17
+ if (handlers === undefined) {
18
+ handlers = new Set();
19
+ this.handlers.set(wire, handlers);
20
+ this.request("subscribe", wire).catch((error) => {
21
+ if (onRefused)
22
+ onRefused(error);
23
+ else
24
+ console.warn(`igni bridge: subscribing to ${wire} failed: ${error.message}`);
25
+ });
26
+ }
27
+ const handler = fn;
28
+ handlers.add(handler);
29
+ return () => this.off(wire, handler);
30
+ }
31
+ /** Hand a signal the host sent to everything handling it. */
32
+ deliver(message) {
33
+ const handlers = this.handlers.get(message.signal);
34
+ if (handlers === undefined)
35
+ return;
36
+ for (const fn of handlers)
37
+ fn(message.value);
38
+ }
39
+ off(wire, handler) {
40
+ const current = this.handlers.get(wire);
41
+ if (current === undefined)
42
+ return;
43
+ current.delete(handler);
44
+ if (current.size > 0)
45
+ return;
46
+ this.handlers.delete(wire);
47
+ this.request("unsubscribe", wire).catch((error) => {
48
+ console.warn(`igni bridge: unsubscribing from ${wire} failed: ${error.message}`);
49
+ });
50
+ }
51
+ }
52
+ //# sourceMappingURL=signals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signals.js","sourceRoot":"","sources":["../src/signals.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAWH,MAAM,OAAO,mBAAmB;IAGD;IAFZ,QAAQ,GAAG,IAAI,GAAG,EAAyC,CAAC;IAE7E,YAA6B,OAAsB;QAAtB,YAAO,GAAP,OAAO,CAAe;IAAG,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