@libo11y/webext 0.0.0-stage → 0.3.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,227 @@
1
- # Temporary Holding Version
1
+ # @libo11y/webext
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The libo11y Manifest V3 extension platform for TypeScript. It builds on
4
+ [`@libo11y/web`](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/web).
5
+ `setupWorker()` runs in the extension's service worker. The browser can
6
+ stop the worker at any time, so the worker stores every batch in IndexedDB
7
+ before it sends it, and it drains the queue on every wake.
8
+ `setupContentScript()` runs in content scripts and extension pages. Those
9
+ contexts never post to the collector. They forward their batches to the
10
+ worker by runtime messaging. Trace context crosses with every traced
11
+ message, and consent is one state for the whole extension.
12
+
13
+ It has no RUM features. Those belong to `@libo11y/rum`, whose
14
+ `@libo11y/rum/webext` entry point builds on this package.
15
+
16
+ ```sh
17
+ npm install @libo11y/webext
18
+ ```
19
+
20
+ ## Quick start
21
+
22
+ `manifest.json`:
23
+
24
+ ```json
25
+ {
26
+ "manifest_version": 3,
27
+ "name": "Clipper",
28
+ "version": "1.4.0",
29
+ "background": { "service_worker": "worker.js", "type": "module" },
30
+ "content_scripts": [{ "matches": ["https://*/*"], "js": ["content.js"] }],
31
+ "permissions": ["storage"],
32
+ "host_permissions": ["https://otlp.example.com/*"]
33
+ }
34
+ ```
35
+
36
+ `worker.ts`:
37
+
38
+ ```ts
39
+ import { setupWorker } from "@libo11y/webext";
40
+
41
+ // At the top level, without a top-level await, so it runs on every wake.
42
+ const telemetry = setupWorker({
43
+ serviceName: "clipper",
44
+ environment: "production",
45
+ endpoint: "https://otlp.example.com",
46
+ });
47
+
48
+ telemetry.then((t) =>
49
+ t.onMessage(async () => {
50
+ // Runs in the sender's trace context, so spans started here are its children.
51
+ t.logger.info("clip received");
52
+ return { saved: true };
53
+ }),
54
+ );
55
+ ```
56
+
57
+ `content.ts`:
58
+
59
+ ```ts
60
+ import { setupContentScript } from "@libo11y/webext";
61
+
62
+ const telemetry = setupContentScript({ serviceName: "clipper", environment: "production" });
63
+
64
+ document.addEventListener("click", async () => {
65
+ const t = await telemetry;
66
+ await t.sendMessage({ kind: "clip", url: location.href });
67
+ });
68
+ ```
69
+
70
+ Neither script uses a top-level `await`, and neither does the package's
71
+ test extension. Bundle each entry point for the browser. The package's own test extension
72
+ in `browser/fixture-extension` bundles its worker, content script and page
73
+ with `Bun.build` and `target: "browser"`.
74
+
75
+ The `storage` permission holds the shared consent state. Without it, each
76
+ context keeps its own state and content scripts start `pending`. The
77
+ collector's origin belongs in `host_permissions`.
78
+
79
+ ## The service worker
80
+
81
+ Call `setupWorker` at the top level of the worker script, so it runs on
82
+ every wake. It registers its message listener before its first `await`, so
83
+ the message that woke the worker reaches it. Batches that arrive before the
84
+ telemetry is ready are answered once it is.
85
+
86
+ `setupWorker` takes core's `TelemetryOptions` and the
87
+ [`@libo11y/web` export options](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/web#endpoints-and-cors):
88
+ `endpoint`, the per-signal endpoints, `headers`, `env`, `transport` and
89
+ `userAgent`. It differs from the page `setup` in these ways:
90
+
91
+ - Every batch is put in the IndexedDB queue, leased, before its first
92
+ attempt. It is removed after a success or a fatal error and rescheduled
93
+ after a retryable one.
94
+ - Requests are always normal `fetch` requests, gzip-compressed when
95
+ `compression` allows. The worker has no `sendBeacon` and no unload mode.
96
+ - The span and log batch delays default to 1000 ms and the metric export
97
+ interval to 15000 ms, because the worker can stop at any time.
98
+ `OTEL_BSP_SCHEDULE_DELAY`, `OTEL_BLRP_SCHEDULE_DELAY` and
99
+ `OTEL_METRIC_EXPORT_INTERVAL` in `env` override them.
100
+ - `serviceVersion` defaults to the manifest's `version`.
101
+ - The console sink defaults to off.
102
+ - `setupWorker` rejects when there is no `chrome.runtime`.
103
+
104
+ | Worker option | Default | Effect |
105
+ | ----------------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
106
+ | `consent` | `{}` | the initial state and the privacy signals, as in `@libo11y/web`. A stored state beats `initial` |
107
+ | `fetch` | `true` | client spans for the worker's own `fetch` calls. Pass `false` to turn them off, or `{ propagateTo, ignoreUrls }` to configure them |
108
+ | `acceptForwarded` | `true` | accept export batches from content scripts and extension pages |
109
+ | `contextManager` | `createContextManager()` | as in `@libo11y/web` |
110
+
111
+ The worker accepts export messages only from its own extension's contexts,
112
+ whose `sender.id` equals `chrome.runtime.id`. It re-reads the stored
113
+ consent before it accepts each batch, so a grant or revoke in another
114
+ context counts before the storage change event reaches the worker.
115
+
116
+ `telemetry.sendTabMessage(tabId, payload)` sends a traced message to a
117
+ tab's content script through `chrome.tabs.sendMessage`. It rejects where
118
+ `chrome.tabs` is unavailable.
119
+
120
+ ## Content scripts and extension pages
121
+
122
+ `setupContentScript` takes core's `TelemetryOptions`, `env`, `userAgent`,
123
+ `contextManager` and `instrumentations`. It has no endpoint options. Every
124
+ signal's batches go to the worker as export messages, and the worker posts
125
+ the body to the collector unchanged.
126
+
127
+ ```mermaid
128
+ sequenceDiagram
129
+ participant content_script
130
+ participant worker
131
+ participant indexeddb_queue
132
+ participant collector
133
+ content_script->>worker: export message (OTLP JSON body)
134
+ worker->>indexeddb_queue: put batch
135
+ worker-->>content_script: export reply (ok)
136
+ worker->>indexeddb_queue: claim due batches
137
+ worker->>collector: POST /v1/<signal>
138
+ worker->>indexeddb_queue: remove sent batches
139
+ ```
140
+
141
+ The worker replies once the batch is in its queue. It refuses the batch
142
+ when consent is not granted, when the message is malformed, or when the
143
+ queue refuses it. The content script drops a refused batch and reports it
144
+ through diag. No reply, a rejected `sendMessage`, or no answer within
145
+ 10 seconds is retried from a memory queue in the content script.
146
+
147
+ | `instrumentations` option | Default | Effect |
148
+ | --------------------------- | -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
149
+ | `fetch`, `xhr` | `true` | client spans for this context's own requests. A content script runs in an isolated world, so it does not see the page's requests |
150
+ | `documentLoad` | `false` in a content script, `true` in an extension page | the `documentLoad` span. A content script's document is the page's |
151
+ | `propagateTo`, `ignoreUrls` | `[]` | as in `@libo11y/web` |
152
+
153
+ An extension page is a context whose protocol is `chrome-extension:`,
154
+ `moz-extension:` or `safari-web-extension:`. Both kinds of context flush
155
+ when their document is hidden.
156
+
157
+ ## Consent
158
+
159
+ Consent is one state for the whole extension, stored in
160
+ `chrome.storage.local` under `libo11y.consent`. The worker reads it on every
161
+ wake, and a stored state beats `consent.initial`. When nothing is stored
162
+ yet, the worker stores a `granted` or `denied` initial state for the
163
+ content scripts to read. A content script starts from the stored state, or
164
+ `pending` when none is stored.
165
+
166
+ Every context writes its changes to storage and applies changes from other
167
+ contexts. `grant()` and `revoke()` in any context change consent for the
168
+ whole extension. A revoke anywhere clears the worker's IndexedDB queue and
169
+ each context's buffers, as `revoke()` does on a page. A stored state never
170
+ moves back to `pending`.
171
+
172
+ The worker's `consent` options decide the privacy signals for the whole
173
+ extension. When a respected DNT or GPC signal refuses a stored grant, from
174
+ a content script or an earlier wake, the worker stores `denied` in its
175
+ place. Every context then revokes, so the signals deny everywhere.
176
+
177
+ ## Traced messaging
178
+
179
+ Both handles have `sendMessage(payload)` and `onMessage(listener)`.
180
+ `sendMessage` wraps the payload with the active trace context and resolves
181
+ with the listener's result. It rejects with the listener's error message,
182
+ or when no traced listener answered. `onMessage` runs the listener inside
183
+ the sender's context, so spans it starts are children of the sender's
184
+ active span. A returned promise is awaited, and its value is the reply.
185
+ `onMessage` returns a function that removes the listener.
186
+
187
+ Payloads cross `chrome.runtime.sendMessage`, so they must survive the
188
+ browser's JSON serialization of runtime messages.
189
+
190
+ ## The message protocol
191
+
192
+ Every libo11y message is a plain JSON object with `libo11y: 1`
193
+ (`PROTOCOL_VERSION`). libo11y listeners ignore every other message, and
194
+ other listeners in the extension keep working. Do not send messages with a
195
+ `libo11y` field of your own.
196
+
197
+ | `type` | From | Fields | Meaning |
198
+ | -------------- | ---------------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------- |
199
+ | `export` | content script or page | `signal` (`traces`, `metrics` or `logs`), `body` | one OTLP/HTTP JSON request body for the worker to queue and send |
200
+ | `export-reply` | worker | `ok`, `reason` when refused | the batch is queued, or the reason it was refused |
201
+ | `traced` | any context | `carrier`, `payload` | an application message with `traceparent`, and `tracestate` and `baggage` when present |
202
+ | `traced-reply` | the listener's context | `ok`, `result` or `error` | the listener's result, or its error message |
203
+
204
+ ## Known limitations
205
+
206
+ - The test suites load the extension in Chromium only. `getChrome()` falls
207
+ back to `globalThis.browser` where `chrome` is absent, and no other
208
+ browser is tested.
209
+ - A content script's retry queue is in memory. Batches it could not hand
210
+ to the worker are lost when the page closes.
211
+ - Only the worker reads DNT and GPC, through its `consent` options. A
212
+ content script's `grant()` returns `"granted"` even when the worker's
213
+ signals will refuse it. It records until the worker's refusal comes back
214
+ through storage, and the worker refuses those batches.
215
+ - Delivery from the worker's queue is at least once. A worker stopped after
216
+ its request reached the collector, but before it removed the batch, sends
217
+ the batch again on the next wake. The worker is the only user of its
218
+ queue, so a new wake releases every lease the stopped one held and sends
219
+ those batches at once, without waiting for the leases to run out.
220
+ - `onMessage` needs the handle, so a traced listener is added only after
221
+ `setupContentScript` resolves. A traced message that reaches a content
222
+ script before then is not answered by it. The worker holds up to 100
223
+ traced messages from its own extension that arrive before its listeners
224
+ exist. It replays them one task after `setupWorker` resolves, to the
225
+ listeners added by then, so add the worker's listeners in the first
226
+ `then` of `setupWorker`.
227
+ - The worker has no XHR and no document-load span.
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Contract, frozen by the L4 scaffold. Owned by WP5.
3
+ *
4
+ * The slice of the extension API libo11y uses, typed by hand so the package needs no @types/chrome
5
+ * and tests can pass a fake. Chrome and Firefox both expose it as `chrome` in Manifest V3, with
6
+ * promise-returning methods.
7
+ */
8
+ /** Who sent a runtime message. */
9
+ export interface MessageSenderLike {
10
+ /** The sending extension's ID. */
11
+ readonly id?: string;
12
+ /** The sending tab, for a content script. */
13
+ readonly tab?: {
14
+ readonly id?: number;
15
+ };
16
+ readonly frameId?: number;
17
+ readonly url?: string;
18
+ readonly origin?: string;
19
+ }
20
+ /** A runtime.onMessage listener: return true to answer asynchronously through sendResponse. */
21
+ export type RuntimeMessageListener = (message: unknown, sender: MessageSenderLike, sendResponse: (response?: unknown) => void) => boolean | undefined;
22
+ /** A storage area change, as storage.onChanged reports it. */
23
+ export interface StorageChangeLike {
24
+ readonly oldValue?: unknown;
25
+ readonly newValue?: unknown;
26
+ }
27
+ /** An extension event. */
28
+ export interface ExtensionEvent<L> {
29
+ addListener(listener: L): void;
30
+ removeListener(listener: L): void;
31
+ }
32
+ /** The extension API slice. */
33
+ export interface ChromeLike {
34
+ readonly runtime: {
35
+ readonly id: string;
36
+ getManifest(): {
37
+ readonly name: string;
38
+ readonly version: string;
39
+ };
40
+ sendMessage(message: unknown): Promise<unknown>;
41
+ readonly onMessage: ExtensionEvent<RuntimeMessageListener>;
42
+ };
43
+ /** Absent in content scripts. */
44
+ readonly tabs?: {
45
+ sendMessage(tabId: number, message: unknown): Promise<unknown>;
46
+ };
47
+ /** Needs the "storage" permission. */
48
+ readonly storage?: {
49
+ readonly local: {
50
+ get(key: string): Promise<Record<string, unknown>>;
51
+ set(items: Record<string, unknown>): Promise<void>;
52
+ };
53
+ readonly onChanged: ExtensionEvent<(changes: Record<string, StorageChangeLike>, areaName: string) => void>;
54
+ };
55
+ }
56
+ /** globalThis.chrome, else globalThis.browser, else undefined. */
57
+ export declare function getChrome(): ChromeLike | undefined;
package/dist/chrome.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Contract, frozen by the L4 scaffold. Owned by WP5.
3
+ *
4
+ * The slice of the extension API libo11y uses, typed by hand so the package needs no @types/chrome
5
+ * and tests can pass a fake. Chrome and Firefox both expose it as `chrome` in Manifest V3, with
6
+ * promise-returning methods.
7
+ */
8
+ /** globalThis.chrome, else globalThis.browser, else undefined. */
9
+ export function getChrome() {
10
+ const g = globalThis;
11
+ return g.chrome?.runtime !== undefined
12
+ ? g.chrome
13
+ : g.browser?.runtime !== undefined
14
+ ? g.browser
15
+ : undefined;
16
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * WP5 (webext). One consent state for the whole extension, in chrome.storage.local.
3
+ */
4
+ import type { ConsentController, ConsentState } from "@libo11y/web/internal";
5
+ import type { ChromeLike } from "./chrome.ts";
6
+ /** The chrome.storage.local key. */
7
+ export declare const CONSENT_STORAGE_KEY = "libo11y.consent";
8
+ /** The stored state, or undefined when none is stored, storage is unavailable or the value is malformed. */
9
+ export declare function readStoredConsent(chrome: ChromeLike): Promise<ConsentState | undefined>;
10
+ /** A running sync between a controller and storage. */
11
+ export interface ConsentSync {
12
+ /** Stops syncing both ways. Idempotent. */
13
+ readonly stop: () => void;
14
+ /**
15
+ * Re-reads the stored state and applies it now, resolving once applied. For a decision that
16
+ * must not wait for storage.onChanged, such as accepting a batch just after a grant elsewhere.
17
+ */
18
+ readonly refresh: () => Promise<void>;
19
+ }
20
+ /**
21
+ * Keeps controller and storage in step: every controller change is written, and a storage change
22
+ * from another context is applied with grant() or revoke() when it differs (so a revoke anywhere
23
+ * clears this context's queues). Returns the running sync.
24
+ *
25
+ * A storage change is a signal to re-read the stored state rather than a value to apply, because
26
+ * storage operations run in order: the echo of an earlier write of this context can arrive after a
27
+ * later change here, and the re-read then returns the later state. "pending" is never applied,
28
+ * because consent has no way back to it. The stored state is also read once at the start, to
29
+ * catch a change between readStoredConsent and this call.
30
+ *
31
+ * Privacy signals deny everywhere: when a stored "granted" cannot be applied because this
32
+ * controller respects a privacy signal (DNT or GPC) that is set, "denied" is written back, and
33
+ * every other context then revokes. So a grant in a content script, whose controller reads no
34
+ * signals, is undone extension-wide when the worker's signals refuse it, as is a stored grant the
35
+ * worker finds when it wakes.
36
+ */
37
+ export declare function syncConsent(controller: ConsentController, chrome: ChromeLike): ConsentSync;
@@ -0,0 +1,97 @@
1
+ import { diag } from "@opentelemetry/api";
2
+ /** The chrome.storage.local key. */
3
+ export const CONSENT_STORAGE_KEY = "libo11y.consent";
4
+ function isConsentState(v) {
5
+ return v === "pending" || v === "granted" || v === "denied";
6
+ }
7
+ /** The stored state, or undefined when none is stored, storage is unavailable or the value is malformed. */
8
+ export async function readStoredConsent(chrome) {
9
+ if (chrome.storage === undefined)
10
+ return undefined;
11
+ try {
12
+ const items = await chrome.storage.local.get(CONSENT_STORAGE_KEY);
13
+ const value = items[CONSENT_STORAGE_KEY];
14
+ return isConsentState(value) ? value : undefined;
15
+ }
16
+ catch (err) {
17
+ diag.warn("o11y: reading the stored consent", err);
18
+ return undefined;
19
+ }
20
+ }
21
+ /**
22
+ * Keeps controller and storage in step: every controller change is written, and a storage change
23
+ * from another context is applied with grant() or revoke() when it differs (so a revoke anywhere
24
+ * clears this context's queues). Returns the running sync.
25
+ *
26
+ * A storage change is a signal to re-read the stored state rather than a value to apply, because
27
+ * storage operations run in order: the echo of an earlier write of this context can arrive after a
28
+ * later change here, and the re-read then returns the later state. "pending" is never applied,
29
+ * because consent has no way back to it. The stored state is also read once at the start, to
30
+ * catch a change between readStoredConsent and this call.
31
+ *
32
+ * Privacy signals deny everywhere: when a stored "granted" cannot be applied because this
33
+ * controller respects a privacy signal (DNT or GPC) that is set, "denied" is written back, and
34
+ * every other context then revokes. So a grant in a content script, whose controller reads no
35
+ * signals, is undone extension-wide when the worker's signals refuse it, as is a stored grant the
36
+ * worker finds when it wakes.
37
+ */
38
+ export function syncConsent(controller, chrome) {
39
+ const storage = chrome.storage;
40
+ if (storage === undefined)
41
+ return { stop: () => { }, refresh: async () => { } };
42
+ let stopped = false;
43
+ let applying = false;
44
+ const write = (state) => {
45
+ storage.local.set({ [CONSENT_STORAGE_KEY]: state }).catch((err) => {
46
+ diag.warn("o11y: storing the consent state", err);
47
+ });
48
+ };
49
+ const apply = (stored) => {
50
+ if (stopped || stored === undefined || stored === "pending")
51
+ return;
52
+ const consent = controller.consent;
53
+ if (stored === consent.state())
54
+ return;
55
+ applying = true;
56
+ try {
57
+ if (stored === "granted")
58
+ consent.grant();
59
+ else
60
+ void consent.revoke();
61
+ }
62
+ finally {
63
+ applying = false;
64
+ }
65
+ // A respected privacy signal refused the grant: store the refusal, so every context denies.
66
+ if (stored === "granted" && consent.state() !== "granted")
67
+ write(consent.state());
68
+ };
69
+ const refresh = () => readStoredConsent(chrome)
70
+ .then(apply)
71
+ .catch((err) => {
72
+ diag.warn("o11y: applying the stored consent", err);
73
+ });
74
+ const reconcile = () => {
75
+ void refresh();
76
+ };
77
+ const unsubscribe = controller.consent.subscribe((state) => {
78
+ if (stopped || applying)
79
+ return;
80
+ write(state);
81
+ });
82
+ const onChanged = (changes, areaName) => {
83
+ if (areaName !== "local" || !Object.hasOwn(changes, CONSENT_STORAGE_KEY))
84
+ return;
85
+ reconcile();
86
+ };
87
+ storage.onChanged.addListener(onChanged);
88
+ reconcile();
89
+ const stop = () => {
90
+ if (stopped)
91
+ return;
92
+ stopped = true;
93
+ unsubscribe();
94
+ storage.onChanged.removeListener(onChanged);
95
+ };
96
+ return { stop, refresh };
97
+ }