@haatlabs-core/extension-kit 0.0.0-stage → 0.10.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Haatlabs
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,55 @@
1
- # Temporary Holding Version
1
+ # @haatlabs-core/extension-kit
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 browser side of an extension's panel (Manifest V3): the `PanelEnv` of
4
+ `@haatlabs-core/extension-ui` for a Chrome or Edge side panel, the service worker's setup, and the
5
+ key an app's own connect page hands the extension.
6
+
7
+ ## Install
8
+
9
+ pnpm add @haatlabs-core/extension-kit
10
+
11
+ ## Use
12
+
13
+ - `createChromePanelEnv()`: the active tab (once the person clicked the icon there, or
14
+ allowed every site), tab changes in the panel's own window, downloads (a file made in parts
15
+ is saved as one), JSON read from inside the page as the page would, and the page's scripts
16
+ and globals.
17
+ - `openSidePanelOnIconClick()`, in the service worker: the toolbar icon opens the side panel.
18
+ - Sign-in through the app's own connect page: `startConnect(webOrigin)` opens
19
+ `<webOrigin>/connect/extension?extension=<id>`; `listenForConnections({ <app>: <webOrigin> })`
20
+ in the service worker keeps the key that page sends (`<app>.connected`), only from that
21
+ origin; `createAuthStore(app)` reads, keeps and forgets it in local storage (never synced).
22
+
23
+ For an extension of an app with its own backend (not built on the platform):
24
+
25
+ - `fillFields(tabId, [{ selector, value }])` fills a page's form in the page's own world, so
26
+ React and Vue forms keep the values (a `<select>` by its value or its text), and returns
27
+ `{ filled, missing }`: show what was missing, never skip it. `copyText(text)` copies.
28
+ - `SiteAdapter`: one site's form as data (`matches` as Chrome match patterns, the `anchor`
29
+ field, and `fields(data, page)`); `matchAdapter(url, adapters)` picks the page's.
30
+ - `installFillButton({ adapters, label, onFill })`, in a content script: a button beside the
31
+ form's first field once it appears.
32
+ - `startOAuthPkce({ authorizeUrl, tokenUrl, clientId, scopes })` signs in through
33
+ `chrome.identity` with OAuth 2 and PKCE (S256, `state` checked) and returns
34
+ `{ accessToken, refreshToken, expiresAt }`; `refreshOAuth(grant, tokenUrl, clientId)` renews
35
+ it in its last minute. `createAuthStore` keeps either kind of grant.
36
+
37
+ Chrome, Edge, Firefox and Safari from one code base:
38
+
39
+ - `browserName()` (`chromium`, `firefox`, `safari`, from the scheme of the extension's own pages) and `extensionApi()` (`browser` where there
40
+ is one, else `chrome`). `createChromePanelEnv` works in each: Firefox and Safari answer
41
+ `chrome.*` too.
42
+ - `openPanelOnIconClick()`, in the background script: Chromium's side panel, Firefox's sidebar;
43
+ on Safari the panel is the action's popup.
44
+ - `manifestFor(browser, base, { geckoId })` writes each browser's manifest from one Chromium
45
+ base: Firefox gets `sidebar_action`, a background script and `browser_specific_settings`;
46
+ Safari a popup and no `identity` permission.
47
+ - `startOAuthPkce` signs in with `chrome.identity` or `browser.identity`; on Safari, which has
48
+ none, through a tab to the app's own page (`safariRedirectUri`), which hands the answer back
49
+ with `browser.runtime.sendMessage`.
50
+
51
+ The manifest needs the `sidePanel`, `scripting`, `downloads`, `storage` and `activeTab`
52
+ permissions, `optional_host_permissions: ["https://*/*"]`, and the app's web origin in
53
+ `externally_connectable`.
54
+
55
+ The package is for the browser only: its code runs in an extension, through a bundler.
package/dist/auth.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import type { OAuthGrant } from './oauth.js';
2
+ /**
3
+ * What lets the extension call the app for a person, and whose account it is: the key the
4
+ * app's connect page handed over, or OAuth tokens (`startOAuthPkce`).
5
+ */
6
+ export type StoredAuth = {
7
+ key: string;
8
+ organizationName: string;
9
+ } | {
10
+ oauth: OAuthGrant;
11
+ organizationName: string;
12
+ };
13
+ export interface AuthStore {
14
+ get(): Promise<StoredAuth | null>;
15
+ set(auth: StoredAuth): Promise<void>;
16
+ clear(): Promise<void>;
17
+ /** Calls back when the key is kept or forgotten (in any of the extension's pages). */
18
+ onChange(listener: () => void): () => void;
19
+ }
20
+ /** One app's key, in the extension's local storage (never synced, never shown). */
21
+ export declare function createAuthStore(app: string): AuthStore;
22
+ /** Opens the app's connect page, naming this extension; the page hands the key back. */
23
+ export declare function startConnect(webOrigin: string): void;
24
+ /**
25
+ * In the service worker: keeps the key an app's own connect page hands over
26
+ * (`<app>.connected`), and only from that app's own web origin. Anything else is refused.
27
+ */
28
+ export declare function listenForConnections(webOrigins: Record<string, string>): void;
package/dist/auth.js ADDED
@@ -0,0 +1,69 @@
1
+ const isGrant = (value) => {
2
+ const grant = value;
3
+ return (typeof grant?.accessToken === 'string' &&
4
+ typeof grant.refreshToken === 'string' &&
5
+ typeof grant.expiresAt === 'number');
6
+ };
7
+ const storageKey = (app) => `auth:${app}`;
8
+ /** One app's key, in the extension's local storage (never synced, never shown). */
9
+ export function createAuthStore(app) {
10
+ const key = storageKey(app);
11
+ return {
12
+ async get() {
13
+ const found = (await chrome.storage.local.get(key))[key];
14
+ if (typeof found?.organizationName !== 'string')
15
+ return null;
16
+ if (typeof found.key === 'string') {
17
+ return { key: found.key, organizationName: found.organizationName };
18
+ }
19
+ if (isGrant(found.oauth)) {
20
+ return { oauth: found.oauth, organizationName: found.organizationName };
21
+ }
22
+ return null;
23
+ },
24
+ async set(auth) {
25
+ await chrome.storage.local.set({ [key]: auth });
26
+ },
27
+ async clear() {
28
+ await chrome.storage.local.remove(key);
29
+ },
30
+ onChange(listener) {
31
+ const onChanged = (changes, area) => {
32
+ if (area === 'local' && key in changes)
33
+ listener();
34
+ };
35
+ chrome.storage.onChanged.addListener(onChanged);
36
+ return () => chrome.storage.onChanged.removeListener(onChanged);
37
+ },
38
+ };
39
+ }
40
+ /** Opens the app's connect page, naming this extension; the page hands the key back. */
41
+ export function startConnect(webOrigin) {
42
+ void chrome.tabs.create({
43
+ url: `${webOrigin}/connect/extension?extension=${chrome.runtime.id}`,
44
+ });
45
+ }
46
+ /**
47
+ * In the service worker: keeps the key an app's own connect page hands over
48
+ * (`<app>.connected`), and only from that app's own web origin. Anything else is refused.
49
+ */
50
+ export function listenForConnections(webOrigins) {
51
+ chrome.runtime.onMessageExternal.addListener((message, sender, reply) => {
52
+ const { type, key, organizationName } = (message ?? {});
53
+ const app = typeof type === 'string' ? type.replace(/\.connected$/, '') : '';
54
+ const fromItsPage = typeof type === 'string' &&
55
+ type.endsWith('.connected') &&
56
+ webOrigins[app] !== undefined &&
57
+ sender.origin === webOrigins[app];
58
+ if (!fromItsPage || typeof key !== 'string' || typeof organizationName !== 'string') {
59
+ reply({ ok: false });
60
+ return false;
61
+ }
62
+ void createAuthStore(app)
63
+ .set({ key, organizationName })
64
+ .then(() => reply({ ok: true }));
65
+ // The reply comes after the key is kept.
66
+ return true;
67
+ });
68
+ }
69
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AASA,MAAM,OAAO,GAAG,CAAC,KAAc,EAAuB,EAAE;IACtD,MAAM,KAAK,GAAG,KAAwC,CAAC;IACvD,OAAO,CACL,OAAO,KAAK,EAAE,WAAW,KAAK,QAAQ;QACtC,OAAO,KAAK,CAAC,YAAY,KAAK,QAAQ;QACtC,OAAO,KAAK,CAAC,SAAS,KAAK,QAAQ,CACpC,CAAC;AACJ,CAAC,CAAC;AAUF,MAAM,UAAU,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,QAAQ,GAAG,EAAE,CAAC;AAElD,mFAAmF;AACnF,MAAM,UAAU,eAAe,CAAC,GAAW;IACzC,MAAM,GAAG,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC;IAC5B,OAAO;QACL,KAAK,CAAC,GAAG;YACP,MAAM,KAAK,GAAG,CAAC,MAAM,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CACqB,CAAC;YAC7E,IAAI,OAAO,KAAK,EAAE,gBA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,CAAC,OAAO,CAAC,EAAE,EAAE;KACrE,CAAC,CAAC;AACL,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAAC,UAAkC;IACrE,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,WAAW,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE;QACtE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,gBAAgB,EAAE,GAAG,CAAC,OAAO,IAAI,EAAE,CAA4B,CAAC;QACnF,MAAM,GAAG,GAAG,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7E,MAAM,WAAW,GACf,OAAO,IAAI,KAAK,QAAQ;YACxB,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC;YAC3B,UAAU,CAAC,GAAG,CAAC,KAAK,SAAS;YAC7B,MAAM,CAAC,MAAM,KAAK,UAAU,CAAC,GAAG,CAAC,CAAC;QACpC,IAAI,CAAC,WAAW,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,OAAO,gBAAgB,KAAK,QAAQ,EAAE,CAAC;YACpF,KAAK,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;YACrB,OAAO,KAAK,CAAC;QACf,CAAC;QACD,KAAK,eAAe,CAAC,GAAG,CAAC;aACtB,GAAG,CAAC,EAAE,GAAG,EAAE,gBAAgB,EAAE,CAAC;aAC9B,IAAI,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QACnC,yCAAyC;QACzC,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,2 @@
1
+ /** In the service worker: the toolbar icon opens the side panel (and grants activeTab there). */
2
+ export declare function openSidePanelOnIconClick(): void;
@@ -0,0 +1,6 @@
1
+ import { openPanelOnIconClick } from './panel.js';
2
+ /** In the service worker: the toolbar icon opens the side panel (and grants activeTab there). */
3
+ export function openSidePanelOnIconClick() {
4
+ openPanelOnIconClick();
5
+ }
6
+ //# sourceMappingURL=background.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"background.js","sourceRoot":"","sources":["../src/background.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAElD,iGAAiG;AACjG,MAAM,UAAU,wBAAwB;IACtC,oBAAoB,EAAE,CAAC;AACzB,CAAC"}
@@ -0,0 +1,12 @@
1
+ /** The browsers an extension made with the kit runs in. Edge is Chromium. */
2
+ export type BrowserName = 'chromium' | 'firefox' | 'safari';
3
+ type Api = typeof chrome;
4
+ /**
5
+ * Which browser this is, from the address of the extension's own pages: `chrome-extension:`
6
+ * (Chrome, Edge), `moz-extension:` (Firefox) or `safari-web-extension:`. Not from the `browser`
7
+ * global, which webextension-polyfill also defines in Chrome.
8
+ */
9
+ export declare function browserName(): BrowserName;
10
+ /** The extension API: `browser` where there is one, else `chrome`; the same calls in each. */
11
+ export declare function extensionApi(): Api;
12
+ export {};
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Which browser this is, from the address of the extension's own pages: `chrome-extension:`
3
+ * (Chrome, Edge), `moz-extension:` (Firefox) or `safari-web-extension:`. Not from the `browser`
4
+ * global, which webextension-polyfill also defines in Chrome.
5
+ */
6
+ export function browserName() {
7
+ const scheme = extensionApi().runtime.getURL('').split(':')[0];
8
+ if (scheme === 'moz-extension')
9
+ return 'firefox';
10
+ if (scheme === 'safari-web-extension')
11
+ return 'safari';
12
+ return 'chromium';
13
+ }
14
+ /** The extension API: `browser` where there is one, else `chrome`; the same calls in each. */
15
+ export function extensionApi() {
16
+ const { browser, chrome: chromeApi } = globalThis;
17
+ const api = browser ?? chromeApi;
18
+ if (!api)
19
+ throw new Error('Not running in a browser extension');
20
+ return api;
21
+ }
22
+ //# sourceMappingURL=browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser.js","sourceRoot":"","sources":["../src/browser.ts"],"names":[],"mappings":"AAKA;;;;GAIG;AACH,MAAM,UAAU,WAAW;IACzB,MAAM,MAAM,GAAG,YAAY,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/D,IAAI,MAAM,KAAK,eAAe;QAAE,OAAO,SAAS,CAAC;IACjD,IAAI,MAAM,KAAK,sBAAsB;QAAE,OAAO,QAAQ,CAAC;IACvD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,8FAA8F;AAC9F,MAAM,UAAU,YAAY;IAC1B,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,UAA6C,CAAC;IACrF,MAAM,GAAG,GAAG,OAAO,IAAI,SAAS,CAAC;IACjC,IAAI,CAAC,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IAChE,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { PanelEnv } from '@haatlabs-core/extension-ui';
2
+ /** A panel's environment in a Chrome (or Edge) side panel. */
3
+ export declare function createChromePanelEnv(): PanelEnv;
@@ -0,0 +1,91 @@
1
+ import { chromePageReader } from './page-fetch.js';
2
+ function addressInPage() {
3
+ return location.href;
4
+ }
5
+ /** In the page (its JavaScript world): its scripts, and which of `names` it defines. */
6
+ function factsInPage(names) {
7
+ const scripts = Array.from(document.scripts, (script) => script.src).filter(Boolean);
8
+ const loaded = performance
9
+ .getEntriesByType('resource')
10
+ .filter((entry) => entry.initiatorType === 'script')
11
+ .map((entry) => entry.name);
12
+ const page = window;
13
+ return {
14
+ scriptSrcs: [...new Set([...scripts, ...loaded])],
15
+ globals: names.filter((name) => page[name] !== undefined),
16
+ };
17
+ }
18
+ async function pageFacts(tabId, globals) {
19
+ const [result] = await chrome.scripting.executeScript({
20
+ target: { tabId },
21
+ world: 'MAIN',
22
+ func: factsInPage,
23
+ args: [[...globals]],
24
+ });
25
+ return result?.result ?? { scriptSrcs: [], globals: [] };
26
+ }
27
+ /**
28
+ * Saves through Chrome's downloads, from an object URL freed once the download has it. A
29
+ * file made in parts (a zip's chunks) becomes one Blob without being joined in memory first.
30
+ */
31
+ async function download(data, fileName, type) {
32
+ const parts = (typeof data === 'string' || data instanceof Uint8Array ? [data] : data);
33
+ const url = URL.createObjectURL(new Blob(parts, { type }));
34
+ try {
35
+ await chrome.downloads.download({ url, filename: fileName, saveAs: false });
36
+ }
37
+ finally {
38
+ setTimeout(() => URL.revokeObjectURL(url), 60_000);
39
+ }
40
+ }
41
+ /** A panel's environment in a Chrome (or Edge) side panel. */
42
+ export function createChromePanelEnv() {
43
+ return {
44
+ async activeTab() {
45
+ const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
46
+ if (tab?.id === undefined)
47
+ return null;
48
+ try {
49
+ // Reading the page's own address proves the panel may read the page.
50
+ const [result] = await chrome.scripting.executeScript({
51
+ target: { tabId: tab.id },
52
+ func: addressInPage,
53
+ });
54
+ const url = result?.result;
55
+ if (typeof url !== 'string' || !URL.canParse(url))
56
+ return null;
57
+ return { tabId: tab.id, url, host: new URL(url).host };
58
+ }
59
+ catch {
60
+ // No access to this tab: the icon was not clicked here, nor every site allowed.
61
+ return null;
62
+ }
63
+ },
64
+ requestAccess: () => chrome.permissions.request({ origins: ['https://*/*'] }),
65
+ onTabChange(listener) {
66
+ // Only the panel's own window counts: its active tab, once that has loaded.
67
+ let windowId;
68
+ void chrome.windows.getCurrent().then((current) => {
69
+ windowId = current.id;
70
+ });
71
+ const onActivated = (info) => {
72
+ if (info.windowId === windowId)
73
+ listener();
74
+ };
75
+ const onUpdated = (_id, change, tab) => {
76
+ if (change.status === 'complete' && tab.active && tab.windowId === windowId)
77
+ listener();
78
+ };
79
+ chrome.tabs.onActivated.addListener(onActivated);
80
+ chrome.tabs.onUpdated.addListener(onUpdated);
81
+ return () => {
82
+ chrome.tabs.onActivated.removeListener(onActivated);
83
+ chrome.tabs.onUpdated.removeListener(onUpdated);
84
+ };
85
+ },
86
+ download,
87
+ reader: chromePageReader,
88
+ pageFacts,
89
+ };
90
+ }
91
+ //# sourceMappingURL=chrome-env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chrome-env.js","sourceRoot":"","sources":["../src/chrome-env.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnD,SAAS,aAAa;IACpB,OAAO,QAAQ,CAAC,IAAI,CAAC;AACvB,CAAC;AAED,wFAAwF;AACxF,SAAS,WAAW,CAAC,KAAe;IAClC,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACrF,MAAM,MAAM,GAAG,WAAW;SACvB,gBAAgB,CAAC,UAAU,CAAC;SAC5B,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAE,KAAmC,CAAC,aAAa,KAAK,QAAQ,CAAC;SAClF,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC9B,MAAM,IAAI,GAAG,MAA4C,CAAC;IAC1D,OAAO;QACL,UAAU,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,MAAM,CAAC,CAAC,CAAC;QACjD,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,SAAS,CAAC;KAC1D,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,SAAS,CAAC,KAAa,EAAE,OAA0B;IAChE,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,MAAM,CAAC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Q,KAAK,QAAQ;oBAAE,QAAQ,EAAE,CAAC;YAC1F,CAAC,CAAC;YACF,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,WAAW,CAAC,WAAW,CAAC,CAAC;YACjD,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;YAC7C,OAAO,GAAG,EAAE;gBACV,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC;gBACpD,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;YAClD,CAAC,CAAC;QACJ,CAAC;QACD,QAAQ;QACR,MAAM,EAAE,gBAAgB;QACxB,SAAS;KACV,CAAC;AACJ,CAAC"}
@@ -0,0 +1,13 @@
1
+ import type { SiteAdapter } from './site-adapter.js';
2
+ /**
3
+ * In a content script: a small button beside the form's first field on a page an adapter
4
+ * covers, put there once the field appears (checkouts draw their forms late). A click calls
5
+ * back with the adapter; the extension then asks what to fill and fills it. Returns the stop.
6
+ */
7
+ export declare function installFillButton<T>(options: {
8
+ adapters: readonly SiteAdapter<T>[];
9
+ label: string;
10
+ onFill: (adapter: SiteAdapter<T>) => void;
11
+ /** The page's address; this page's own by default. */
12
+ url?: string;
13
+ }): () => void;
@@ -0,0 +1,33 @@
1
+ import { matchAdapter } from './site-adapter.js';
2
+ /**
3
+ * In a content script: a small button beside the form's first field on a page an adapter
4
+ * covers, put there once the field appears (checkouts draw their forms late). A click calls
5
+ * back with the adapter; the extension then asks what to fill and fills it. Returns the stop.
6
+ */
7
+ export function installFillButton(options) {
8
+ const adapter = matchAdapter(options.url ?? location.href, options.adapters);
9
+ if (!adapter)
10
+ return () => undefined;
11
+ let button = null;
12
+ const place = () => {
13
+ if (button?.isConnected)
14
+ return;
15
+ const anchor = document.querySelector(adapter.anchor);
16
+ if (!anchor)
17
+ return;
18
+ button = document.createElement('button');
19
+ button.type = 'button';
20
+ button.className = 'haatlabs-fill-button';
21
+ button.textContent = options.label;
22
+ button.addEventListener('click', () => options.onFill(adapter));
23
+ anchor.after(button);
24
+ };
25
+ const observer = new MutationObserver(place);
26
+ observer.observe(document.documentElement, { childList: true, subtree: true });
27
+ place();
28
+ return () => {
29
+ observer.disconnect();
30
+ button?.remove();
31
+ };
32
+ }
33
+ //# sourceMappingURL=fill-button.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fill-button.js","sourceRoot":"","sources":["../src/fill-button.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGjD;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAI,OAMpC;IACC,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC,GAAG,IAAI,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;IAC7E,IAAI,CAAC,OAAO;QAAE,OAAO,GAAG,EAAE,CAAC,SAAS,CAAC;IACrC,IAAI,MAAM,GAA6B,IAAI,CAAC;IAC5C,MAAM,KAAK,GAAG,GAAG,EAAE;QACjB,IAAI,MAAM,EAAE,WAAW;YAAE,OAAO;QAChC,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACtD,IAAI,CAAC,MAAM;YAAE,OAAO;QACpB,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAC1C,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC;QACvB,MAAM,CAAC,SAAS,GAAG,sBAAsB,CAAC;QAC1C,MAAM,CAAC,WAAW,GAAG,OAAO,CAAC,KAAK,CAAC;QACnC,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;QAChE,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACvB,CAAC,CAAC;IACF,MAAM,QAAQ,GAAG,IAAI,gBAAgB,CAAC,KAAK,CAAC,CAAC;IAC7C,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,eAAe,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IAC/E,KAAK,EAAE,CAAC;IACR,OAAO,GAAG,EAAE;QACV,QAAQ,CAAC,UAAU,EAAE,CAAC;QACtB,MAAM,EAAE,MAAM,EAAE,CAAC;IACnB,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,17 @@
1
+ export { openSidePanelOnIconClick } from './background.js';
2
+ export { createChromePanelEnv } from './chrome-env.js';
3
+ export { chromePageReader } from './page-fetch.js';
4
+ export { createAuthStore, listenForConnections, startConnect } from './auth.js';
5
+ export type { AuthStore, StoredAuth } from './auth.js';
6
+ export { copyText, fillFields } from './page-actions.js';
7
+ export type { FieldValue, FillResult } from './page-actions.js';
8
+ export { matchAdapter, matchesPattern } from './site-adapter.js';
9
+ export type { SiteAdapter } from './site-adapter.js';
10
+ export { installFillButton } from './fill-button.js';
11
+ export { refreshOAuth, startOAuthPkce } from './oauth.js';
12
+ export type { OAuthGrant, OAuthOptions } from './oauth.js';
13
+ export { browserName, extensionApi } from './browser.js';
14
+ export type { BrowserName } from './browser.js';
15
+ export { openPanelOnIconClick } from './panel.js';
16
+ export { manifestFor } from './manifest.js';
17
+ export type { Manifest } from './manifest.js';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ // The browser side of an extension's panel: the panel's environment, the service worker's
2
+ // setup, and the key an app's connect page hands over.
3
+ export { openSidePanelOnIconClick } from './background.js';
4
+ export { createChromePanelEnv } from './chrome-env.js';
5
+ export { chromePageReader } from './page-fetch.js';
6
+ export { createAuthStore, listenForConnections, startConnect } from './auth.js';
7
+ export { copyText, fillFields } from './page-actions.js';
8
+ export { matchAdapter, matchesPattern } from './site-adapter.js';
9
+ export { installFillButton } from './fill-button.js';
10
+ export { refreshOAuth, startOAuthPkce } from './oauth.js';
11
+ export { browserName, extensionApi } from './browser.js';
12
+ export { openPanelOnIconClick } from './panel.js';
13
+ export { manifestFor } from './manifest.js';
14
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAC1F,uDAAuD;AACvD,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEhF,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAE1D,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEzD,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { BrowserName } from './browser.js';
2
+ /** A Manifest V3 manifest, as JSON. */
3
+ export type Manifest = Record<string, unknown> & {
4
+ permissions?: string[];
5
+ side_panel?: {
6
+ default_path: string;
7
+ };
8
+ background?: {
9
+ service_worker?: string;
10
+ scripts?: string[];
11
+ type?: string;
12
+ };
13
+ action?: Record<string, unknown>;
14
+ };
15
+ /**
16
+ * One base manifest (Chromium's: `side_panel`, a `service_worker`) as each browser takes it.
17
+ * Firefox: the panel is a sidebar, the background a script, and the add-on has its own id.
18
+ * Safari: the panel is the action's popup.
19
+ */
20
+ export declare function manifestFor(browser: BrowserName, base: Manifest, options?: {
21
+ geckoId?: string;
22
+ firefoxMinVersion?: string;
23
+ }): Manifest;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * One base manifest (Chromium's: `side_panel`, a `service_worker`) as each browser takes it.
3
+ * Firefox: the panel is a sidebar, the background a script, and the add-on has its own id.
4
+ * Safari: the panel is the action's popup.
5
+ */
6
+ export function manifestFor(browser, base, options = {}) {
7
+ if (browser === 'chromium')
8
+ return base;
9
+ const { side_panel: panel, ...rest } = structuredClone(base);
10
+ const permissions = (rest.permissions ?? []).filter((name) => name !== 'sidePanel');
11
+ if (browser === 'firefox') {
12
+ if (!options.geckoId)
13
+ throw new Error('A Firefox manifest needs geckoId, the add-on id');
14
+ const worker = rest.background?.service_worker;
15
+ return {
16
+ ...rest,
17
+ permissions,
18
+ ...(panel
19
+ ? { sidebar_action: { default_panel: panel.default_path, default_title: base.name } }
20
+ : {}),
21
+ ...(worker ? { background: { scripts: [worker], type: rest.background?.type } } : {}),
22
+ browser_specific_settings: {
23
+ gecko: { id: options.geckoId, strict_min_version: options.firefoxMinVersion ?? '128.0' },
24
+ },
25
+ };
26
+ }
27
+ // Safari has no identity API: sign-in goes through a tab (startOAuthPkce's safariRedirectUri).
28
+ return {
29
+ ...rest,
30
+ permissions: permissions.filter((name) => name !== 'identity'),
31
+ ...(panel ? { action: { ...rest.action, default_popup: panel.default_path } } : {}),
32
+ };
33
+ }
34
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manifest.js","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAUA;;;;GAIG;AACH,MAAM,UAAU,WAAW,CACzB,OAAoB,EACpB,IAAc,EACd,UAA4D,EAAE;IAE9D,IAAI,OAAO,KAAK,UAAU;QAAE,OAAO,IAAI,CAAC;IACxC,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,GAAG,eAA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C;KACpF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,35 @@
1
+ /** An OAuth sign-in's tokens, and when the access token stops working (ms since the epoch). */
2
+ export interface OAuthGrant {
3
+ accessToken: string;
4
+ refreshToken: string;
5
+ expiresAt: number;
6
+ }
7
+ export interface OAuthOptions {
8
+ /** The app's authorization endpoint, where the person signs in and approves. */
9
+ authorizeUrl: string;
10
+ tokenUrl: string;
11
+ /** The extension's public client (no secret): PKCE proves it is the one that asked. */
12
+ clientId: string;
13
+ scopes: string[];
14
+ /**
15
+ * Safari only, which has no identity API: the app's own https page the sign-in returns to.
16
+ * That page sends `{ type: 'oauth.callback', url: location.href }` to the extension with
17
+ * `browser.runtime.sendMessage(<extension id>, …)`; its origin must be in the manifest's
18
+ * `externally_connectable`.
19
+ */
20
+ safariRedirectUri?: string;
21
+ }
22
+ /**
23
+ * Signs in to the app through the browser's sign-in window (`chrome.identity`), with OAuth 2
24
+ * and PKCE (S256): the person approves on the app's own page, and the code that comes back is
25
+ * exchanged for tokens. A changed `state` (an answer to someone else's request) is refused.
26
+ */
27
+ export declare function startOAuthPkce(options: OAuthOptions): Promise<OAuthGrant>;
28
+ /**
29
+ * The grant to use now: the same one while its access token has more than `marginMs` (a
30
+ * minute) left, else a new one from its refresh token.
31
+ */
32
+ export declare function refreshOAuth(grant: OAuthGrant, tokenUrl: string, clientId: string, options?: {
33
+ now?: number;
34
+ marginMs?: number;
35
+ }): Promise<OAuthGrant>;
package/dist/oauth.js ADDED
@@ -0,0 +1,109 @@
1
+ import { browserName, extensionApi } from './browser.js';
2
+ const SAFARI_SIGN_IN_MS = 10 * 60_000;
3
+ /** Safari: the authorize page in a tab, and the answer the app's page sends back. */
4
+ function signInInTab(url, redirectUri) {
5
+ const api = extensionApi();
6
+ const origin = new URL(redirectUri).origin;
7
+ return new Promise((resolve, reject) => {
8
+ let tabId;
9
+ const done = (finish) => {
10
+ clearTimeout(timer);
11
+ api.runtime.onMessageExternal.removeListener(listener);
12
+ if (tabId !== undefined)
13
+ void api.tabs.remove(tabId).catch(() => undefined);
14
+ finish();
15
+ };
16
+ const listener = (message, sender) => {
17
+ const { type, url: answered } = (message ?? {});
18
+ if (sender.origin !== origin || type !== 'oauth.callback' || typeof answered !== 'string')
19
+ return;
20
+ if (!answered.startsWith(redirectUri))
21
+ return;
22
+ done(() => resolve(answered));
23
+ };
24
+ const timer = setTimeout(() => done(() => reject(new Error('The sign-in was not finished in time'))), SAFARI_SIGN_IN_MS);
25
+ api.runtime.onMessageExternal.addListener(listener);
26
+ void api.tabs.create({ url }).then((tab) => {
27
+ tabId = tab.id;
28
+ }, (error) => done(() => reject(error instanceof Error ? error : new Error(String(error)))));
29
+ });
30
+ }
31
+ const base64url = (bytes) => btoa(String.fromCharCode(...bytes))
32
+ .replace(/\+/g, '-')
33
+ .replace(/\//g, '_')
34
+ .replace(/=+$/, '');
35
+ const randomText = (bytes) => base64url(crypto.getRandomValues(new Uint8Array(bytes)));
36
+ async function tokens(tokenUrl, body, now) {
37
+ const response = await fetch(tokenUrl, {
38
+ method: 'POST',
39
+ headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
40
+ body: new URLSearchParams(body).toString(),
41
+ });
42
+ const answer = (await response.json().catch(() => ({})));
43
+ if (!response.ok || typeof answer.access_token !== 'string') {
44
+ throw new Error(`The sign-in was refused (${String(answer.error ?? response.status)})`);
45
+ }
46
+ return {
47
+ accessToken: answer.access_token,
48
+ refreshToken: typeof answer.refresh_token === 'string' ? answer.refresh_token : (body.refresh_token ?? ''),
49
+ expiresAt: now + Number(answer.expires_in ?? 0) * 1000,
50
+ };
51
+ }
52
+ /**
53
+ * Signs in to the app through the browser's sign-in window (`chrome.identity`), with OAuth 2
54
+ * and PKCE (S256): the person approves on the app's own page, and the code that comes back is
55
+ * exchanged for tokens. A changed `state` (an answer to someone else's request) is refused.
56
+ */
57
+ export async function startOAuthPkce(options) {
58
+ const verifier = randomText(48);
59
+ const challenge = base64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
60
+ const state = randomText(16);
61
+ const safari = browserName() === 'safari';
62
+ if (safari && !options.safariRedirectUri) {
63
+ throw new Error('On Safari the sign-in needs safariRedirectUri, the app page it returns to');
64
+ }
65
+ const redirectUri = safari
66
+ ? options.safariRedirectUri
67
+ : extensionApi().identity.getRedirectURL();
68
+ const url = new URL(options.authorizeUrl);
69
+ url.search = new URLSearchParams({
70
+ response_type: 'code',
71
+ client_id: options.clientId,
72
+ redirect_uri: redirectUri,
73
+ scope: options.scopes.join(' '),
74
+ state,
75
+ code_challenge: challenge,
76
+ code_challenge_method: 'S256',
77
+ }).toString();
78
+ const answered = safari
79
+ ? await signInInTab(url.toString(), redirectUri)
80
+ : await extensionApi().identity.launchWebAuthFlow({ url: url.toString(), interactive: true });
81
+ if (!answered)
82
+ throw new Error('The sign-in window was closed');
83
+ const back = new URL(answered).searchParams;
84
+ if (back.get('error'))
85
+ throw new Error(`The sign-in was not approved (${back.get('error')})`);
86
+ if (back.get('state') !== state)
87
+ throw new Error('The sign-in answer has another state: refused');
88
+ const code = back.get('code');
89
+ if (!code)
90
+ throw new Error('The sign-in answer has no code');
91
+ return tokens(options.tokenUrl, {
92
+ grant_type: 'authorization_code',
93
+ code,
94
+ redirect_uri: redirectUri,
95
+ client_id: options.clientId,
96
+ code_verifier: verifier,
97
+ }, Date.now());
98
+ }
99
+ /**
100
+ * The grant to use now: the same one while its access token has more than `marginMs` (a
101
+ * minute) left, else a new one from its refresh token.
102
+ */
103
+ export async function refreshOAuth(grant, tokenUrl, clientId, options = {}) {
104
+ const now = options.now ?? Date.now();
105
+ if (grant.expiresAt - now > (options.marginMs ?? 60_000))
106
+ return grant;
107
+ return tokens(tokenUrl, { grant_type: 'refresh_token', refresh_token: grant.refreshToken, client_id: clientId }, now);
108
+ }
109
+ //# sourceMappingURL=oauth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth.js","sourceRoot":"","sources":["../src/oauth.ts"],"names":[],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I,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC9B,IAAI,CAAC,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IAC7D,OAAO,MAAM,CACX,OAAO,CAAC,QAAQ,EAChB;QACE,UAAU,EAAE,oBAAoB;QAChC,IAAI;QACJ,YAAY,EAAE,WAAW;QACzB,SAAS,EAAE,OAAO,CAAC,QAAQ;QAC3B,aAAa,EAAE,QAAQ;KACxB,EACD,IAAI,CAAC,GAAG,EAAE,CACX,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,KAAiB,EACjB,QAAgB,EAChB,QAAgB,EAChB,UAA+C,EAAE;IAEjD,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;IACtC,IAAI,KAAK,CAAC,SAAS,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,QAAQ,IAAI,MAAM,CAAC;QAAE,OAAO,KAAK,CAAC;IACvE,OAAO,MAAM,CACX,QAAQ,EACR,EAAE,UAAU,EAAE,eAAe,EAAE,aAAa,EAAE,KAAK,CAAC,YAAY,EAAE,SAAS,EAAE,QAAQ,EAAE,EACvF,GAAG,CACJ,CAAC;AACJ,CAAC"}
@@ -0,0 +1,17 @@
1
+ /** A form field, by its CSS selector, and the value to give it. */
2
+ export interface FieldValue {
3
+ selector: string;
4
+ value: string;
5
+ }
6
+ /** Which fields took their value, and which were not there or would not take it. */
7
+ export interface FillResult {
8
+ filled: string[];
9
+ missing: string[];
10
+ }
11
+ /**
12
+ * Fills a page's form fields, in the page's own world, so the page's framework keeps the values.
13
+ * The fields it could not find or fill are listed: show them, never skip them silently.
14
+ */
15
+ export declare function fillFields(tabId: number, fields: FieldValue[]): Promise<FillResult>;
16
+ /** Puts text on the clipboard, from the panel. */
17
+ export declare function copyText(text: string): Promise<void>;
@@ -0,0 +1,68 @@
1
+ // Runs inside the page (chrome.scripting serialises it), so it uses nothing from outside its
2
+ // own body. Values are set through the element's own value setter and followed by input and
3
+ // change events: what a person's typing does, so React's and Vue's forms keep them.
4
+ function fillInPage(fields) {
5
+ const filled = [];
6
+ const missing = [];
7
+ const set = (element, proto, value) => {
8
+ const setter = Object.getOwnPropertyDescriptor(proto, 'value')?.set;
9
+ if (setter)
10
+ setter.call(element, value);
11
+ else
12
+ element.value = value;
13
+ element.dispatchEvent(new Event('input', { bubbles: true }));
14
+ element.dispatchEvent(new Event('change', { bubbles: true }));
15
+ };
16
+ for (const { selector, value } of fields) {
17
+ const element = document.querySelector(selector);
18
+ if (element instanceof HTMLSelectElement) {
19
+ const options = Array.from(element.options);
20
+ const wanted = value.trim().toLowerCase();
21
+ const option = options.find((each) => each.value === value) ??
22
+ options.find((each) => each.text.trim().toLowerCase() === wanted);
23
+ if (!option) {
24
+ missing.push(selector);
25
+ continue;
26
+ }
27
+ set(element, HTMLSelectElement.prototype, option.value);
28
+ }
29
+ else if (element instanceof HTMLInputElement) {
30
+ set(element, HTMLInputElement.prototype, value);
31
+ }
32
+ else if (element instanceof HTMLTextAreaElement) {
33
+ set(element, HTMLTextAreaElement.prototype, value);
34
+ }
35
+ else {
36
+ missing.push(selector);
37
+ continue;
38
+ }
39
+ // Read back: a field the page changed again, or would not take, is reported, not hidden.
40
+ const now = element.value;
41
+ if (element instanceof HTMLSelectElement ? now !== '' : now === value)
42
+ filled.push(selector);
43
+ else
44
+ missing.push(selector);
45
+ }
46
+ return { filled, missing };
47
+ }
48
+ /**
49
+ * Fills a page's form fields, in the page's own world, so the page's framework keeps the values.
50
+ * The fields it could not find or fill are listed: show them, never skip them silently.
51
+ */
52
+ export async function fillFields(tabId, fields) {
53
+ const [result] = await chrome.scripting.executeScript({
54
+ target: { tabId },
55
+ world: 'MAIN',
56
+ func: fillInPage,
57
+ args: [fields],
58
+ });
59
+ return (result?.result ?? {
60
+ filled: [],
61
+ missing: fields.map((f) => f.selector),
62
+ });
63
+ }
64
+ /** Puts text on the clipboard, from the panel. */
65
+ export async function copyText(text) {
66
+ await navigator.clipboard.writeText(text);
67
+ }
68
+ //# sourceMappingURL=page-actions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"page-actions.js","sourceRoot":"","sources":["../src/page-actions.ts"],"names":[],"mappings":"AAYA,6FAA6F;AAC7F,4FAA4F;AAC5F,oFAAoF;AACpF,SAAS,UAAU,CAAC,MAAoB;IACtC,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,MAAM,OAAO,GAAa,EAAE,CAAC;IAC7B,MAAM,GAAG,GAAG,CAAC,OAAoB,EAAE,KAAa,EAAE,KAAa,EAAE,EAAE;QACjE,MAAM,MAAM,GAAG,MAAM,CAAC,wBAAwB,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,GAAG,CAAC;QACpE,IAAI,MAAM;YAAE,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;;YAClC,OAA4B,CAAC,KAAK,GAAG,KAAK,CAAC;QACjD,OAAO,CAAC,aAAa,CAAC,IAAI,KAAK,CAAC,OAAO,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QAC7D,OAAO,CAAC,aAAa,CAAC,IAAI,KAAK,CAAC,QAAQ,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IAChE,CAAC,CAAC;IACF,KAAK,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,MAAM,EAAE,CAAC;QACzC,MAAM,OAAO,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QACjD,IAAI,OAAO,YAAY,iBAAiB,EAAE,CAAC;YACzC,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;YAC5C,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;YAC1C,MAAM,MA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,CAAC,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,aAAa,CAAC;QACpD,MAAM,EAAE,EAAE,KAAK,EAAE;QACjB,KAAK,EAAE,MAAM;QACb,IAAI,EAAE,UAAU;QAChB,IAAI,EAAE,CAAC,MAAM,CAAC;KACf,CAAC,CAAC;IACH,OAAO,CACJ,MAAM,EAAE,MAAiC,IAAI;QAC5C,MAAM,EAAE,EAAE;QACV,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC;KACvC,CACF,CAAC;AACJ,CAAC;AAED,kDAAkD;AAClD,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAC,IAAY;IACzC,MAAM,SAAS,CAAC,SAAS,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;AAC5C,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { PageReader } from '@haatlabs-core/extension-ui';
2
+ /** Reads the site open in a tab, from inside that tab, as its own pages would. */
3
+ export declare function chromePageReader(tabId: number): PageReader;
@@ -0,0 +1,32 @@
1
+ // This runs inside the page's tab (chrome.scripting serialises it), so it uses nothing from
2
+ // outside its own body.
3
+ async function fetchInPage(path) {
4
+ try {
5
+ const response = await fetch(path, {
6
+ credentials: 'omit',
7
+ headers: { accept: 'application/json' },
8
+ });
9
+ const type = response.headers.get('content-type') ?? '';
10
+ if (response.ok && type.includes('json')) {
11
+ return { ok: true, status: response.status, json: await response.json() };
12
+ }
13
+ return { ok: false, status: response.status, html: type.includes('html') };
14
+ }
15
+ catch {
16
+ return { ok: false, status: 0, html: false };
17
+ }
18
+ }
19
+ /** Reads the site open in a tab, from inside that tab, as its own pages would. */
20
+ export function chromePageReader(tabId) {
21
+ return {
22
+ async json(path) {
23
+ const [result] = await chrome.scripting.executeScript({
24
+ target: { tabId },
25
+ func: fetchInPage,
26
+ args: [path],
27
+ });
28
+ return result?.result ?? { ok: false, status: 0, html: false };
29
+ },
30
+ };
31
+ }
32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,CAAC;aACb,CAAC,CAAC;YACH,OAAQ,MAAM,EAAE,MAAiC,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;QAC7F,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * In the service worker (background script): the toolbar icon opens the panel. Chromium's
3
+ * side panel, Firefox's sidebar; Safari shows the panel as the action's popup (manifestFor
4
+ * sets it), so there is nothing to do there.
5
+ */
6
+ export declare function openPanelOnIconClick(): void;
package/dist/panel.js ADDED
@@ -0,0 +1,20 @@
1
+ import { browserName, extensionApi } from './browser.js';
2
+ /**
3
+ * In the service worker (background script): the toolbar icon opens the panel. Chromium's
4
+ * side panel, Firefox's sidebar; Safari shows the panel as the action's popup (manifestFor
5
+ * sets it), so there is nothing to do there.
6
+ */
7
+ export function openPanelOnIconClick() {
8
+ const browser = browserName();
9
+ if (browser === 'chromium') {
10
+ chrome.runtime.onInstalled.addListener(() => {
11
+ void chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
12
+ });
13
+ }
14
+ else if (browser === 'firefox') {
15
+ const api = extensionApi();
16
+ // toggle() must run in the click's own handler, as a user action, with nothing awaited first.
17
+ api.action.onClicked.addListener(() => void api.sidebarAction.toggle());
18
+ }
19
+ }
20
+ //# sourceMappingURL=panel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"panel.js","sourceRoot":"","sources":["../src/panel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEzD;;;;GAIG;AACH,MAAM,UAAU,oBAAoB;IAClC,MAAM,OAAO,GAAG,WAAW,EAAE,CAAC;IAC9B,IAAI,OAAO,KAAK,UAAU,EAAE,CAAC;QAC3B,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,WAAW,CAAC,GAAG,EAAE;YAC1C,KAAK,MAAM,CAAC,SAAS,CAAC,gBAAgB,CAAC,EAAE,sBAAsB,EAAE,IAAI,EAAE,CAAC,CAAC;QAC3E,CAAC,CAAC,CAAC;IACL,CAAC;SAAM,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QACjC,MAAM,GAAG,GAAG,YAAY,EAGvB,CAAC;QACF,8FAA8F;QAC9F,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC,KAAK,GAAG,CAAC,aAAa,CAAC,MAAM,EAAE,CAAC,CAAC;IAC1E,CAAC;AACH,CAAC"}
@@ -0,0 +1,19 @@
1
+ import type { FieldValue } from './page-actions.js';
2
+ /**
3
+ * One site's form: which pages it is on, where an in-page button goes, and which field gets
4
+ * which value. Plain data and selectors, so a site's redesign is a change of selectors.
5
+ */
6
+ export interface SiteAdapter<T> {
7
+ id: string;
8
+ /** Chrome match patterns: `https://*.amazon.com/a/addresses/*`. */
9
+ matches: string[];
10
+ /** The field an in-page button sits beside. */
11
+ anchor: string;
12
+ fields(data: T, page: {
13
+ url: string;
14
+ }): FieldValue[];
15
+ }
16
+ /** Whether a URL is one a Chrome match pattern (scheme, host, path) covers. */
17
+ export declare function matchesPattern(pattern: string, url: string): boolean;
18
+ /** The adapter whose patterns cover the page, or null. */
19
+ export declare function matchAdapter<T>(url: string, adapters: readonly SiteAdapter<T>[]): SiteAdapter<T> | null;
@@ -0,0 +1,25 @@
1
+ const escape = (text) => text.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
2
+ /** Whether a URL is one a Chrome match pattern (scheme, host, path) covers. */
3
+ export function matchesPattern(pattern, url) {
4
+ const parts = /^(\*|https?):\/\/([^/]+)(\/.*)$/.exec(pattern);
5
+ if (!parts || !URL.canParse(url))
6
+ return false;
7
+ const [, scheme, host, path] = parts;
8
+ const page = new URL(url);
9
+ if (scheme === '*' ? !['http:', 'https:'].includes(page.protocol) : page.protocol !== `${scheme}:`)
10
+ return false;
11
+ const hostRe = host === '*'
12
+ ? /^.+$/
13
+ : host.startsWith('*.')
14
+ ? new RegExp(`^(?:[^.]+\\.)*${escape(host.slice(2))}$`)
15
+ : new RegExp(`^${escape(host)}$`);
16
+ if (!hostRe.test(page.hostname))
17
+ return false;
18
+ return new RegExp(`^${escape(path).replace(/\*/g, '.*')}$`).test(page.pathname + page.search);
19
+ }
20
+ /** The adapter whose patterns cover the page, or null. */
21
+ export function matchAdapter(url, adapters) {
22
+ return (adapters.find((adapter) => adapter.matches.some((pattern) => matchesPattern(pattern, url))) ??
23
+ null);
24
+ }
25
+ //# sourceMappingURL=site-adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"site-adapter.js","sourceRoot":"","sources":["../src/site-adapter.ts"],"names":[],"mappings":"AAeA,MAAM,MAAM,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,oBAAoB,EAAE,MAAM,CAAC,CAAC;AAE5E,+EAA+E;AAC/E,MAAM,UAAU,cAAc,CAAC,OAAe,EAAE,GAAW;IACzD,MAAM,KAAK,GAAG,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC9D,IAAI,CAAC,KAAK,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,KAAK,CAAC;IAC/C,MAAM,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,KAAoD,CAAC;IACpF,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;IAC1B,IACE,MAAM,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,KAAK,GAAG,MAAM,GAAG;QAE9F,OAAO,KAAK,CAAC;IACf,MAAM,MAAM,GACV,IAAI,KAAK,GAAG;QACV,CAAC,CAAC,MAAM;QACR,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;YACrB,CAAC,CAAC,IAAI,MAAM,CAAC,iBAAiB,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;YACvD,CAAC,CAAC,IAAI,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACxC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9C,OAAO,IAAI,MAAM,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;AAChG,CAAC;AAED,0DAA0D;AAC1D,MAAM,UAAU,YAAY,CAC1B,GAAW,EACX,QAAmC;IAEnC,OAAO,CACL,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,cAAc,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;QAC3F,IAAI,CACL,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@haatlabs-core/extension-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.10.0",
4
+ "description": "The browser side of an extension's panel: the active tab, page reads, downloads, sign-in keys.",
5
+ "keywords": [
6
+ "haatlabs",
7
+ "browser-extension",
8
+ "chrome"
9
+ ],
10
+ "homepage": "https://haatlabs.shop/docs/packages/extension-kit/",
11
+ "license": "Apache-2.0",
12
+ "type": "module",
13
+ "engines": {
14
+ "node": ">=24"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/Haatlabs/haatlabs-platform.git",
19
+ "directory": "packages/extension-kit"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "registry": "https://registry.npmjs.org"
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js",
32
+ "default": "./dist/index.js"
33
+ }
34
+ },
35
+ "haatlabs": {
36
+ "runtime": "browser"
37
+ },
38
+ "dependencies": {
39
+ "@haatlabs-core/extension-ui": "0.10.0"
40
+ },
41
+ "devDependencies": {
42
+ "@testing-library/dom": "^10.4.2",
43
+ "@testing-library/react": "^16.3.3",
44
+ "@types/chrome": "^0.3.5",
45
+ "@types/react": "^19.3.0",
46
+ "@types/react-dom": "^19.3.0",
47
+ "jsdom": "^30.1.2",
48
+ "react": "^18.3.1",
49
+ "react-dom": "^18.3.1",
50
+ "@haatlabs-core/tsconfig": "0.10.0",
51
+ "@haatlabs-core/vitest-config": "0.10.0"
52
+ },
53
+ "scripts": {
54
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
55
+ "typecheck": "tsc --noEmit",
56
+ "test": "vitest run --typecheck",
57
+ "check:package": "publint --strict && attw --pack . --profile esm-only"
58
+ },
59
+ "platformRegistry": "npm"
60
+ }