@magicbeansai/magicvault-win32-x64 0.9.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-APACHE 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 [yyyy] [name of copyright owner]
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/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 MagicBeansAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
Binary file
Binary file
Binary file
Binary file
package/bundle.json ADDED
@@ -0,0 +1,82 @@
1
+ {
2
+ "format_version": 1,
3
+ "version": "0.9.0",
4
+ "platform": "win32-x64",
5
+ "files": {
6
+ "bin/magicvault.exe": {
7
+ "sha256": "95e27b5408b5bc10541f5cdf8d5be6d467ada6025ae8fc5142144528ef8d2245",
8
+ "bytes": 9396224,
9
+ "executable": true
10
+ },
11
+ "bin/magicvault-mcp.exe": {
12
+ "sha256": "cad776f2bbb66a5fd6478268620dd4c7ede271d72d28b21b67e7d91cf978abbe",
13
+ "bytes": 4297728,
14
+ "executable": true
15
+ },
16
+ "bin/magicvault-native-host.exe": {
17
+ "sha256": "5d09a5d00f20b54614096b2022f85c7f03b36dc2df09140f74daff578c3529b6",
18
+ "bytes": 2157056,
19
+ "executable": true
20
+ },
21
+ "bin/magicvault-prompt.exe": {
22
+ "sha256": "fea9e6286f3905c9088cbaf0eaa70e2a86a77ff116c85f8cfdc4827c80f963e2",
23
+ "bytes": 4894720,
24
+ "executable": true
25
+ },
26
+ "extension/manifest.json": {
27
+ "sha256": "bcc73a79017ffa7c9e8c73716b6537e0cc2aeeba62786c7414100924b5e3bf51",
28
+ "bytes": 1088,
29
+ "executable": false
30
+ },
31
+ "extension/worker.js": {
32
+ "sha256": "b4b648141545d4ac0357968cf65ed7ceb9b6adb6f81e6fbe19612b95ad352b58",
33
+ "bytes": 22362,
34
+ "executable": false
35
+ },
36
+ "extension/options.html": {
37
+ "sha256": "2e5cdcdeb532697058357d1a01022e668c653bcc106c5e715feeb7caf77821e0",
38
+ "bytes": 5075,
39
+ "executable": false
40
+ },
41
+ "extension/options.js": {
42
+ "sha256": "64410d261bd552029590a85aaf098f0914b768cffdaabafc4286a74b1868c6af",
43
+ "bytes": 9385,
44
+ "executable": false
45
+ },
46
+ "extension/options.css": {
47
+ "sha256": "529df3a87d0985c60068454c32d85363f72fb9bf0628de894b4329830acd9028",
48
+ "bytes": 2359,
49
+ "executable": false
50
+ },
51
+ "extension/fill.js": {
52
+ "sha256": "845eb1f035560e5b97b40d72b4efb400db04cd66e8458bc54b06b542b2924be2",
53
+ "bytes": 3277,
54
+ "executable": false
55
+ },
56
+ "examples/secure-fill.json": {
57
+ "sha256": "9a88d93f6a56f2e91d7b82cbe194f77db2548dd66c045e79e391f536e4a352d3",
58
+ "bytes": 354,
59
+ "executable": false
60
+ },
61
+ "examples/http-profile.json": {
62
+ "sha256": "0ba5f9691a5493e42fe80907f9c4fa9231c550a6c1d3c5cc8e03aa1106fdeac1",
63
+ "bytes": 610,
64
+ "executable": false
65
+ },
66
+ "examples/process-profile.json": {
67
+ "sha256": "d5c8aa6be5a19ee433e819f43ef40078d7b1c101782d2e6fe29449943dfa443a",
68
+ "bytes": 551,
69
+ "executable": false
70
+ },
71
+ "LICENSE-MIT": {
72
+ "sha256": "b224b77c65d9e6598c8ffea5d0aa5412c8e1ab98b37436c0b7c1a68211e015d2",
73
+ "bytes": 1074,
74
+ "executable": false
75
+ },
76
+ "LICENSE-APACHE": {
77
+ "sha256": "a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5",
78
+ "bytes": 10849,
79
+ "executable": false
80
+ }
81
+ }
82
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "label": "Example API request",
3
+ "destination": {
4
+ "kind": "http",
5
+ "config": {
6
+ "url": "https://api.example.com/v1/action",
7
+ "method": "POST",
8
+ "headers": [{
9
+ "name": "Authorization",
10
+ "value": {
11
+ "kind": "credential",
12
+ "credential_ref": "cred_00000000-0000-0000-0000-000000000000",
13
+ "credential_field": "password",
14
+ "prefix": "Bearer "
15
+ }
16
+ }],
17
+ "query": [],
18
+ "body": {"kind": "json", "value": [{"name": "action", "value": {"kind": "literal", "value": "synthetic-demo"}}]},
19
+ "timeout_secs": 15
20
+ }
21
+ }
22
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "label": "Example trusted command",
3
+ "destination": {
4
+ "kind": "process",
5
+ "config": {
6
+ "executable": "/absolute/path/to/trusted-recipient",
7
+ "arguments": [],
8
+ "working_directory": "/absolute/path/to/trusted-work-directory",
9
+ "environment": [{
10
+ "name": "SERVICE_TOKEN",
11
+ "value": {
12
+ "kind": "credential",
13
+ "credential_ref": "cred_00000000-0000-0000-0000-000000000000",
14
+ "credential_field": "password"
15
+ }
16
+ }],
17
+ "stdin": null,
18
+ "timeout_secs": 15
19
+ }
20
+ }
21
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "operation_id": "22222222-2222-4222-8222-222222222222",
3
+ "browser_handle": "33333333-3333-4333-8333-333333333333",
4
+ "target_handle": "44444444-4444-4444-8444-444444444444",
5
+ "fields": [
6
+ {
7
+ "css": "input[name=password]",
8
+ "credential_ref": "cred_11111111-1111-4111-8111-111111111111",
9
+ "credential_field": "password"
10
+ }
11
+ ]
12
+ }
@@ -0,0 +1,59 @@
1
+ function magicvaultFill(expectedOrigin, fields) {
2
+ if (!Array.isArray(fields) || fields.length === 0 || fields.length > 8)
3
+ return {fields: [], error: "invalid_request"};
4
+ const result = fields.map(() => "not_filled");
5
+ const fail = (error) => ({fields: result, error});
6
+ const usable = (node, value) => node instanceof HTMLInputElement &&
7
+ ["text", "password", "email", "tel", "url", "search"].includes(node.type) &&
8
+ !node.disabled && !node.matches(":disabled") && !node.readOnly && node.isConnected &&
9
+ node.getClientRects().length > 0 && getComputedStyle(node).visibility === "visible" &&
10
+ !node.closest("[inert]") && (node.maxLength < 0 || value.length <= node.maxLength);
11
+ try {
12
+ // URL origin alone does not establish a document's security origin (for
13
+ // example, a sandboxed opaque document can retain an HTTPS location).
14
+ if (globalThis.origin !== expectedOrigin || location.origin !== expectedOrigin ||
15
+ document.prerendering || !document.defaultView)
16
+ return fail("stale_target");
17
+ if (!Array.isArray(fields) || fields.length === 0 || fields.length > 8)
18
+ return fail("invalid_request");
19
+ const nodes = [];
20
+ // Resolve and validate every field before writing any material.
21
+ for (const field of fields) {
22
+ if (typeof field.css !== "string" || field.css.length > 512 ||
23
+ typeof field.value !== "string" || field.value.length === 0 || field.value.length > 4096)
24
+ return fail("invalid_request");
25
+ let matches;
26
+ try { matches = document.querySelectorAll(field.css); }
27
+ catch (_) { return fail("unsupported_target"); }
28
+ if (matches.length !== 1) return fail(matches.length ? "ambiguous_target" : "stale_target");
29
+ const node = matches[0];
30
+ if (!usable(node, field.value))
31
+ return fail("unsupported_target");
32
+ if (nodes.includes(node)) return fail("ambiguous_target");
33
+ nodes.push(node);
34
+ }
35
+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set;
36
+ for (let index = 0; index < nodes.length; index++) {
37
+ const node = nodes[index];
38
+ // Earlier input/change handlers may replace or detach a later field.
39
+ const matches = document.querySelectorAll(fields[index].css);
40
+ if (globalThis.origin !== expectedOrigin || location.origin !== expectedOrigin || !node.isConnected ||
41
+ matches.length !== 1 || matches[0] !== node || node.disabled || node.readOnly)
42
+ return fail("stale_target");
43
+ if (!usable(node, fields[index].value)) return fail("unsupported_target");
44
+ // A setter/event exception can follow a write. Never imply rollback.
45
+ result[index] = "uncertain";
46
+ setValue.call(node, fields[index].value);
47
+ node.dispatchEvent(new Event("input", {bubbles: true, composed: true}));
48
+ node.dispatchEvent(new Event("change", {bubbles: true}));
49
+ if (!node.isConnected || node.value !== fields[index].value) return fail("stale_target");
50
+ result[index] = "filled";
51
+ }
52
+ return {fields: result, error: null};
53
+ } catch (_) {
54
+ return fail("unavailable");
55
+ } finally {
56
+ // Best effort lifetime reduction, not a JS heap erasure guarantee.
57
+ for (const field of fields) if (field && typeof field === "object") field.value = "";
58
+ }
59
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "manifest_version": 3,
3
+ "name": "MagicVault — credential fills",
4
+ "version": "0.6.1",
5
+ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz+1KIVs/EvE8w/iSpAJX9nIzfnMlj5kn+q8O/7tHKLLDH/S3OjoAqDBS94CGnUu4HyTufTg34++DVVBsVLpKifIj1Do4gPxeNZX9IlVYvzjpvkjimvT+NDdC4P5JX5ydvgBcmEk+qmMsDtbHW0Afyt+/OnYjzbeMjMz+fbZ4y1IcparR2WR9uQ4pa7CguPnC06ekX0Ek8+f76K2ap7AKuMc4ChFvFwW2ib9NeMOUZxnwFC33YmH40Q38uMZZ7VUe6xvftATeCkI0GUZOFCF2ezxz1KVv1tBR995Bht5UVJw5/bgGoS748nOPtksCDmauURSPHTomNm15Fikjzsb3AQIDAQAB",
6
+ "minimum_chrome_version": "120",
7
+ "description": "Fill approved credential fields without putting values in agent messages. Requires the MagicVault native host.",
8
+ "permissions": ["nativeMessaging", "scripting", "webNavigation", "storage", "alarms"],
9
+ "optional_host_permissions": ["https://*/*", "http://localhost/*", "http://127.0.0.1/*"],
10
+ "background": {"service_worker": "worker.js"},
11
+ "options_page": "options.html",
12
+ "action": {"default_title": "MagicVault setup"},
13
+ "content_security_policy": {"extension_pages": "script-src 'self'; object-src 'none'; base-uri 'none'"}
14
+ }
@@ -0,0 +1,25 @@
1
+ :root { color-scheme: light dark; font: 16px/1.6 system-ui, sans-serif; }
2
+ body { margin: 0; } main { max-width: 760px; margin: 3rem auto; padding: 0 1.5rem 3rem; }
3
+ h1 { font-size: 2rem; } h2 { margin-top: 2rem; font-size: 1.2rem; }
4
+ label { display: block; } input { width: min(90%, 500px); padding: .5rem; margin: .5rem 0; }
5
+ button { padding: .5rem .8rem; margin: .4rem .5rem .4rem 0; cursor: pointer; }
6
+ code, #granted-sites { overflow-wrap: anywhere; } [role=status] { min-height: 1.6em; }
7
+ select { width: min(100%, 550px); padding: .5rem; } button:disabled { cursor: default; }
8
+ h3 { font-size: 1rem; margin-top: 1.5rem; }
9
+ .identity-chip { display: inline-flex; flex-wrap: wrap; align-items: center; gap: .4rem .8rem; max-width: 100%; box-sizing: border-box; padding: .7rem 1rem; border: 1px solid #a5b4fc; border-radius: 1.2rem; background: #eef2ff; color: #312e81; box-shadow: 0 2px 6px rgb(49 46 129 / 10%); }
10
+ .identity-label { font: 600 .75rem/1.5 system-ui, sans-serif; text-transform: uppercase; letter-spacing: .04em; }
11
+ #extension-id { min-width: 0; max-width: 100%; font-size: .95rem; font-weight: 600; user-select: all; cursor: text; }
12
+ #extension-id:focus-visible { outline: 2px solid currentColor; outline-offset: 4px; border-radius: .2rem; }
13
+ .access-summary { display: grid; gap: .25rem; border: 2px solid #64748b; border-radius: .6rem; padding: 1rem; background: #f1f5f9; color: #1e293b; }
14
+ .access-label { font-size: .8rem; font-weight: 600; text-transform: uppercase; letter-spacing: .04em; }
15
+ #access-mode { font-size: 1.25rem; }
16
+ .access-summary[data-state="all"] { border-color: #15803d; background: #f0fdf4; color: #14532d; }
17
+ .access-summary[data-state="selected"] { border-color: #1d4ed8; background: #eff6ff; color: #1e3a8a; }
18
+ .access-summary[data-state="unknown"] { border-color: #a16207; background: #fefce8; color: #713f12; }
19
+ @media (prefers-color-scheme: dark) {
20
+ .identity-chip { border-color: #818cf8; background: #1e1b4b; color: #e0e7ff; }
21
+ .access-summary { background: #1e293b; color: #e2e8f0; border-color: #94a3b8; }
22
+ .access-summary[data-state="all"] { border-color: #4ade80; background: #052e16; color: #dcfce7; }
23
+ .access-summary[data-state="selected"] { border-color: #60a5fa; background: #172554; color: #dbeafe; }
24
+ .access-summary[data-state="unknown"] { border-color: #facc15; background: #422006; color: #fef9c3; }
25
+ }
@@ -0,0 +1,34 @@
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
3
+ <title>MagicVault browser setup</title><link rel="stylesheet" href="options.css"></head>
4
+ <body><main><h1>MagicVault</h1><p>Keep credentials out of agent messages.</p>
5
+ <p>This extension fills approved credential fields. It does not navigate, submit forms, or filter other browser tools’ observations.</p>
6
+ <h2>1. Set up MagicVault</h2><p>Run <code>magicvault setup</code> once to install the native bridge and start MagicVault. This extension connects automatically. No extension ID needs copying for the bundled build. Source builds can use <code>magicvault extension install --host-executable /absolute/path/to/magicvault-native-host</code>.</p>
7
+ <div class="identity-chip"><span class="identity-label">Extension ID</span><code id="extension-id" tabindex="0" aria-label="Installed extension ID"></code></div>
8
+ <h2>2. Choose website access</h2>
9
+ <div id="access-summary" class="access-summary" data-state="checking" role="status" aria-live="polite" aria-atomic="true">
10
+ <span class="access-label">Current browser access</span>
11
+ <strong id="access-mode">Checking browser permissions…</strong>
12
+ <span>Browser permission only. Disabled sites, Chrome site restrictions and credential approvals still apply.</span>
13
+ </div>
14
+ <p>Allow all HTTPS websites once, or grant selected websites individually. Neither choice authorizes a credential: MagicVault still enforces exact page/frame origins, selected fields and native credential approval. The daemon asks each time unless you explicitly choose Always allow for an exact use. Existing installations keep their permissions; no broad access is granted automatically.</p>
15
+ <div><button id="allow-all">Allow all HTTPS websites</button><button id="selected-only">Clear HTTPS access — use selected sites</button></div>
16
+ <p id="permission-status" role="status"></p>
17
+ <p>Clearing HTTPS access removes all HTTPS grants; then allow individual sites below. Local HTTP grants and disabled sites are retained. Broad access increases the extension’s reach if compromised. Chrome can still restrict site access.</p>
18
+ <p>Browser grants: <span id="granted-sites"></span></p>
19
+ <h3>Individual sites and local development</h3>
20
+ <p>Enter an HTTPS origin (for example, <code>https://accounts.example.com</code>), or explicitly allow <code>http://localhost:PORT</code> / <code>http://127.0.0.1:PORT</code> for local development. All-HTTPS access never enables local HTTP. Browser permissions cover the exact host’s paths and ports.</p>
21
+ <label for="origin">Site origin</label><input id="origin" type="url" placeholder="https://accounts.example.com" autocomplete="off">
22
+ <div><button id="allow">Allow site</button><button id="remove">Remove site permission</button><button id="block">Disable site in MagicVault</button></div>
23
+ <h3>Disabled sites</h3>
24
+ <p>Disabled sites are excluded from MagicVault discovery and fills in either mode, including embedded frames. A disabled top-level site also blocks its frames. Entries cover the exact hostname and scheme on all paths and ports; subdomains require separate entries. Up to 256 entries are stored locally, without credentials or browser sync.</p>
25
+ <p>This blocklist does not revoke Chrome’s underlying permission, protect against a compromised extension, or recall an already dispatched fill. Allowing a site does not remove its block.</p>
26
+ <label for="blocked-sites">Disabled sites</label><select id="blocked-sites" size="5"></select>
27
+ <div><button id="unblock">Re-enable selected site</button><button id="refresh-access">Refresh access settings</button></div>
28
+ <p id="block-status" role="status"></p>
29
+ <h2>3. Connection</h2><p>Approve the first native dialog for this profile. Approved profiles reconnect automatically, with a 30-second to 5-minute backoff when MagicVault is unavailable (Chrome may delay retries). Separate profiles keep separate connections. Denial, revoked authorization and conflicting copies of a profile stop retries until you choose Retry / resume. Every credential fill still needs approval.</p>
30
+ <div class="identity-chip"><span class="identity-label">Browser profile ID</span><code id="profile-id" tabindex="0" aria-label="Browser profile ID"></code></div>
31
+ <p>Match this profile ID in the native approval dialog. Pause stops this profile’s automatic connection and survives browser restarts; it does not revoke the remembered approval. To revoke it, use <code>magicvault disconnect-browser --browser-handle HANDLE</code>. New connections get fresh handles; never replay unfinished operations.</p>
32
+ <button id="connect">Retry / resume</button><button id="disconnect">Pause connection</button><button id="refresh">Refresh status</button><p id="status" role="status" aria-live="polite"></p>
33
+ <p>Never paste credentials into this page. Enroll values through MagicVault’s native hidden-input prompts. Websites receive filled values; this is not protection from privileged or unrestricted local software.</p>
34
+ </main><script src="options.js"></script></body></html>
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ const element = id => document.getElementById(id);
3
+ element("extension-id").textContent = chrome.runtime.id;
4
+ let changing = false;
5
+ let refreshRevision = 0;
6
+ let blockRevision = 0;
7
+ let allHttpsEnabled = false;
8
+ const accessButtons = ["allow-all", "selected-only", "allow", "remove", "block", "unblock"];
9
+
10
+ function updateAccessButtons() {
11
+ for (const id of accessButtons) element(id).disabled = changing;
12
+ element("allow-all").disabled = changing || allHttpsEnabled;
13
+ element("allow-all").textContent = allHttpsEnabled ? "All HTTPS websites enabled" : "Allow all HTTPS websites";
14
+ }
15
+
16
+ function siteOrigin() {
17
+ const input = element("origin").value;
18
+ if (input.length > 256) throw new Error("invalid_origin");
19
+ const url = new URL(input);
20
+ if (url.username || url.password || url.search || url.hash || url.pathname !== "/" || url.hostname.includes("*") ||
21
+ !(url.protocol === "https:" || (url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname)))) throw new Error("invalid_origin");
22
+ return url.origin;
23
+ }
24
+
25
+ async function refreshBrowserAccess() {
26
+ const revision = ++refreshRevision;
27
+ try {
28
+ const [all, grants] = await Promise.all([
29
+ chrome.permissions.contains({origins: ["https://*/*"]}),
30
+ chrome.permissions.getAll()
31
+ ]);
32
+ if (revision !== refreshRevision) return;
33
+ allHttpsEnabled = all;
34
+ const origins = grants.origins || [];
35
+ element("access-mode").textContent = all ? "All HTTPS websites enabled" : origins.length ? "Selected websites only" : "No websites allowed yet";
36
+ element("access-summary").dataset.state = all ? "all" : origins.length ? "selected" : "none";
37
+ element("granted-sites").textContent = origins.join(", ") || "No website permissions granted.";
38
+ updateAccessButtons();
39
+ } catch (_) {
40
+ if (revision !== refreshRevision) return;
41
+ allHttpsEnabled = false;
42
+ element("access-mode").textContent = "Browser access could not be verified";
43
+ element("access-summary").dataset.state = "unknown";
44
+ element("granted-sites").textContent = "Browser permissions unavailable. Refresh to check again.";
45
+ updateAccessButtons();
46
+ }
47
+ }
48
+
49
+ async function refreshBlockedSites() {
50
+ const revision = ++blockRevision;
51
+ try {
52
+ const policy = await chrome.runtime.sendMessage({action: "site-policy"});
53
+ if (revision !== blockRevision) return;
54
+ element("blocked-sites").replaceChildren();
55
+ if (!policy?.ok) throw new Error("policy_unavailable");
56
+ for (const site of policy.blockedSites) {
57
+ const option = document.createElement("option");
58
+ option.value = site;
59
+ option.textContent = site;
60
+ element("blocked-sites").append(option);
61
+ }
62
+ element("block-status").textContent = policy.blockedSites.length ? `${policy.blockedSites.length} site(s) disabled in MagicVault.` : "No sites disabled in MagicVault.";
63
+ } catch (_) {
64
+ if (revision === blockRevision) {
65
+ element("blocked-sites").replaceChildren();
66
+ element("block-status").textContent = "Blocklist unavailable. MagicVault refuses fills if its site policy cannot be read.";
67
+ }
68
+ }
69
+ }
70
+
71
+ async function refreshAccess() {
72
+ // Chrome's grant is independent of native connection and blocklist availability.
73
+ // A slow/failed worker must not hide an already confirmed browser permission.
74
+ await Promise.all([refreshBrowserAccess(), refreshBlockedSites()]);
75
+ }
76
+
77
+ async function changeAccess(action) {
78
+ if (changing) return;
79
+ changing = true;
80
+ updateAccessButtons();
81
+ const output = element("permission-status");
82
+ try {
83
+ output.textContent = "Applying change. If Chrome asks for permission, approve or dismiss its prompt.";
84
+ // Call the action before yielding: permission requests require a user gesture.
85
+ output.textContent = await action();
86
+ } catch (_) {
87
+ output.textContent = "Change failed. Use an exact HTTPS origin or supported local HTTP origin; check permissions and refresh before retrying.";
88
+ } finally {
89
+ await refreshAccess();
90
+ changing = false;
91
+ updateAccessButtons();
92
+ }
93
+ }
94
+
95
+ element("allow-all").addEventListener("click", () => changeAccess(async () => {
96
+ const allowed = await chrome.permissions.request({origins: ["https://*/*"]});
97
+ return allowed ? "All HTTPS access granted. Disabled sites and credential approvals still apply. Local HTTP was not enabled." : "All HTTPS access was not granted. Existing settings retained.";
98
+ }));
99
+ element("selected-only").addEventListener("click", () => changeAccess(async () => {
100
+ // Reset HTTPS grants explicitly; do not claim to preserve narrower grants when
101
+ // Chrome removes an overlapping wildcard. Local HTTP grants are independent.
102
+ const origins = (await chrome.permissions.getAll()).origins?.filter(origin => origin.startsWith("https://")) || [];
103
+ if (origins.length && !await chrome.permissions.remove({origins})) throw new Error("permission_denied");
104
+ if (await chrome.permissions.contains({origins: ["https://*/*"]})) throw new Error("permission_denied");
105
+ return "HTTPS grants cleared. Allow individual sites below. Local HTTP grants and disabled sites are unchanged.";
106
+ }));
107
+ element("allow").addEventListener("click", () => changeAccess(async () => {
108
+ const url = new URL(siteOrigin());
109
+ const allowed = await chrome.permissions.request({origins: [`${url.protocol}//${url.hostname}/*`]});
110
+ return allowed ? "Site permission granted. A disabled site stays blocked until re-enabled; exact credential origins still need MagicVault approval." : "Site permission was not granted.";
111
+ }));
112
+ element("remove").addEventListener("click", () => changeAccess(async () => {
113
+ const url = new URL(siteOrigin());
114
+ if (url.protocol === "https:" && await chrome.permissions.contains({origins: ["https://*/*"]})) {
115
+ return "All HTTPS access is enabled. Use Disable site, or clear HTTPS access and allow only selected sites.";
116
+ }
117
+ const origins = [`${url.protocol}//${url.hostname}/*`];
118
+ if (!await chrome.permissions.remove({origins}) || await chrome.permissions.contains({origins})) throw new Error("permission_denied");
119
+ return "Site permission removed. Other grants and disabled sites are unchanged.";
120
+ }));
121
+ async function setBlock(site, blocked) {
122
+ const response = await chrome.runtime.sendMessage({action: "site-block", site, blocked});
123
+ if (!response?.ok) throw new Error("policy_unavailable");
124
+ return blocked ? "Site disabled for MagicVault discovery and fills. Chrome's underlying permission is unchanged; already dispatched fills cannot be recalled." : "Site re-enabled in MagicVault. Browser permission and credential approval are still required.";
125
+ }
126
+ element("block").addEventListener("click", () => changeAccess(() => setBlock(siteOrigin(), true)));
127
+ element("unblock").addEventListener("click", () => changeAccess(() => setBlock(element("blocked-sites").value, false)));
128
+ element("refresh-access").addEventListener("click", refreshAccess);
129
+ chrome.permissions.onAdded.addListener(refreshAccess);
130
+ chrome.permissions.onRemoved.addListener(refreshAccess);
131
+ chrome.storage.onChanged.addListener((changes, area) => {
132
+ if (area === "local" && Object.hasOwn(changes, "sitePolicy")) void refreshAccess();
133
+ if (area === "local" && Object.hasOwn(changes, "connection")) void control("status");
134
+ });
135
+ window.addEventListener("focus", () => { void refreshAccess(); });
136
+ document.addEventListener("visibilitychange", () => {
137
+ if (document.visibilityState === "visible") void refreshAccess();
138
+ });
139
+ async function control(action) {
140
+ const output = document.getElementById("status");
141
+ try {
142
+ const state = await chrome.runtime.sendMessage({action});
143
+ element("profile-id").textContent = state.profile_id || "Not available";
144
+ const reasons = {paused: "Paused by you.", denied: "Browser authorization was denied or revoked.",
145
+ unauthorized: "Pairing is missing or revoked. Check MagicVault setup.", conflict: "Another connection is using this profile identity. Close the copied profile before retrying.",
146
+ capacity: "MagicVault's browser or pairing limit was reached.", unsupported_version: "Update MagicVault and reload the matching extension.",
147
+ storage_unavailable: "Local connection settings could not be saved or read. Reload after fixing storage; no automatic retry.",
148
+ expired: "The connection approval timed out.", cancelled: "Connection approval was cancelled."};
149
+ output.textContent = state.connected ? `Connected. Browser handle: ${state.browser_handle}` : state.connecting ? "Connecting to MagicVault. Approve the native dialog if this is the first connection for this profile." :
150
+ state.paused ? `${reasons[state.reason] || "Connection stopped for safety. Check MagicVault setup."} Choose Retry / resume when ready.` :
151
+ state.retry_at ? `MagicVault is unavailable or busy. Automatic retry after ${new Date(state.retry_at).toLocaleTimeString()} (Chrome may delay it). Run magicvault setup if the native bridge is not installed.` : "Waiting for automatic connection.";
152
+ element("connect").disabled = state.connected || state.connecting;
153
+ } catch (_) { output.textContent = "Connection unavailable. Check the documented setup."; }
154
+ }
155
+ document.getElementById("connect").addEventListener("click", () => control("connect"));
156
+ document.getElementById("disconnect").addEventListener("click", () => control("disconnect"));
157
+ document.getElementById("refresh").addEventListener("click", () => control("status"));
158
+ void refreshAccess();
159
+ void control("status");
@@ -0,0 +1,463 @@
1
+ /* global magicvaultFill */
2
+ "use strict";
3
+ // Packaging copies the fixed function from magicvault-effect/src/fill.js.
4
+ // No remote code, page message receiver, generic evaluate, or enrolled-secret storage.
5
+ // Trusted local storage holds site settings and a profile-pairing capability.
6
+ importScripts("fill.js");
7
+
8
+ const HOST = "ai.magicbeans.magicvault";
9
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
10
+ // Chrome document IDs are opaque tokens, commonly 32 uppercase hex digits,
11
+ // not our daemon's hyphenated UUID handles. Preserve the exact browser value.
12
+ const DOCUMENT_ID = /^(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
13
+ const validDocumentId = value => typeof value === "string" &&
14
+ (value.length === 32 || value.length === 36) && DOCUMENT_ID.test(value);
15
+ let channel = null;
16
+ let generation = 0;
17
+ let browserHandle = null;
18
+ let busy = false;
19
+ let accessRevision = 0;
20
+ let policyWritePending = false;
21
+ const POLICY_KEY = "sitePolicy";
22
+ // A failed storage restriction must deny operations, not crash worker registration.
23
+ const storageReady = chrome.storage.local.setAccessLevel({accessLevel: "TRUSTED_CONTEXTS"})
24
+ .then(() => true, () => false);
25
+ chrome.storage.onChanged.addListener((changes, area) => {
26
+ if (area === "local" && Object.hasOwn(changes, POLICY_KEY)) accessRevision++;
27
+ });
28
+ chrome.permissions.onAdded.addListener(() => { accessRevision++; });
29
+ chrome.permissions.onRemoved.addListener(() => { accessRevision++; });
30
+
31
+ function originOf(value) {
32
+ const url = new URL(value);
33
+ if (url.username || url.password || !(url.protocol === "https:" ||
34
+ (url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname)))) throw new Error("unsupported_target");
35
+ if (url.origin.length > 256) throw new Error("unsupported_target");
36
+ return url.origin;
37
+ }
38
+
39
+ function permissionPattern(origin) {
40
+ const url = new URL(origin);
41
+ return `${url.protocol}//${url.hostname}/*`;
42
+ }
43
+
44
+ function siteKey(value) {
45
+ if (typeof value !== "string" || value.length > 256) throw new Error("invalid_site");
46
+ const url = new URL(value);
47
+ originOf(value);
48
+ if (url.pathname !== "/" || url.search || url.hash || url.hostname.includes("*")) throw new Error("invalid_site");
49
+ // Block the exact hostname on every port, including its DNS trailing-dot alias.
50
+ return `${url.protocol}//${url.hostname.replace(/\.$/, "")}`;
51
+ }
52
+
53
+ async function readSitePolicy() {
54
+ if (!await storageReady) throw new Error("policy_unavailable");
55
+ const stored = (await chrome.storage.local.get(POLICY_KEY))[POLICY_KEY];
56
+ // Existing installations retain their Chrome grants and start with no blocks.
57
+ if (stored === undefined) return {version: 1, blockedSites: []};
58
+ if (!stored || stored.version !== 1 || !Array.isArray(stored.blockedSites) ||
59
+ stored.blockedSites.length > 256 ||
60
+ stored.blockedSites.some(site => siteKey(site) !== site) ||
61
+ new Set(stored.blockedSites).size !== stored.blockedSites.length) throw new Error("policy_unavailable");
62
+ return stored;
63
+ }
64
+
65
+ async function changeSiteBlock(site, blocked) {
66
+ // One writer across setup tabs; do not lose concurrent read/modify/write updates.
67
+ if (policyWritePending || typeof blocked !== "boolean") throw new Error("policy_unavailable");
68
+ const key = siteKey(site);
69
+ policyWritePending = true;
70
+ accessRevision++;
71
+ try {
72
+ const policy = await readSitePolicy();
73
+ const sites = new Set(policy.blockedSites);
74
+ if (blocked) sites.add(key); else sites.delete(key);
75
+ if (sites.size > 256) throw new Error("policy_unavailable");
76
+ const updated = {version: 1, blockedSites: [...sites].sort()};
77
+ await chrome.storage.local.set({[POLICY_KEY]: updated});
78
+ return updated;
79
+ } finally {
80
+ policyWritePending = false;
81
+ accessRevision++;
82
+ }
83
+ }
84
+
85
+ function accessUnchanged(revision) {
86
+ return !policyWritePending && accessRevision === revision;
87
+ }
88
+
89
+ async function permitted(origin, policy) {
90
+ return !policy.blockedSites.includes(siteKey(origin)) &&
91
+ await chrome.permissions.contains({origins: [permissionPattern(origin)]});
92
+ }
93
+
94
+ function active(port, epoch) {
95
+ if (channel !== port || generation !== epoch || !browserHandle) throw new Error("stale_session");
96
+ }
97
+
98
+ const CONNECTION_KEY = "connection";
99
+ const RETRY_ALARM = "magicvault-reconnect";
100
+ const WATCHDOG_ALARM = "magicvault-handshake";
101
+ const NATIVE_VERSION = 2;
102
+ const TRANSIENT = ["busy", "transport_unavailable", "transport_uncertain"];
103
+ const REASONS = ["paused", "denied", "unauthorized", "conflict", "capacity", "unsupported_version",
104
+ "invalid_request", "unavailable", "expired", "cancelled", "persistence_uncertain", "storage_unavailable",
105
+ ...TRANSIENT];
106
+ let connection = null;
107
+ let pausedNow = false;
108
+ let connectionError = null;
109
+ let connectionWork = Promise.resolve();
110
+
111
+ function closeChannel() {
112
+ const old = channel;
113
+ channel = null;
114
+ browserHandle = null;
115
+ generation++;
116
+ busy = false;
117
+ if (old) { try { old.disconnect(); } catch (_) {} }
118
+ }
119
+
120
+ function connectionStatus() {
121
+ return {connected: Boolean(browserHandle), connecting: Boolean(channel) && !browserHandle,
122
+ browser_handle: browserHandle, profile_id: connection?.profile_id || null,
123
+ paused: pausedNow || connection?.mode === "paused", reason: connectionError || connection?.reason || null,
124
+ retry_at: connection?.mode === "enabled" ? connection.retryAt : 0};
125
+ }
126
+
127
+ function transition(work) {
128
+ // A single writer covers startup, alarms, native events and multiple setup tabs.
129
+ connectionWork = connectionWork.then(work).catch(async () => {
130
+ pausedNow = true;
131
+ connectionError = "storage_unavailable";
132
+ closeChannel();
133
+ await Promise.allSettled([chrome.alarms.clear(RETRY_ALARM), chrome.alarms.clear(WATCHDOG_ALARM)]);
134
+ });
135
+ return connectionWork;
136
+ }
137
+
138
+ async function saveConnection() {
139
+ if (!await storageReady || !connection) throw new Error("storage_unavailable");
140
+ await chrome.storage.local.set({[CONNECTION_KEY]: connection});
141
+ }
142
+
143
+ async function stopConnection(reason) {
144
+ closeChannel();
145
+ connection.mode = "paused";
146
+ connection.reason = reason;
147
+ connection.retryAt = 0;
148
+ await saveConnection();
149
+ await chrome.alarms.clear(RETRY_ALARM);
150
+ await chrome.alarms.clear(WATCHDOG_ALARM);
151
+ }
152
+
153
+ async function failedConnection(code) {
154
+ if (pausedNow || connection?.mode === "paused") return;
155
+ closeChannel();
156
+ await chrome.alarms.clear(WATCHDOG_ALARM);
157
+ if (!TRANSIENT.includes(code)) return stopConnection(REASONS.includes(code) ? code : "invalid_request");
158
+ connection.failures = Math.min(connection.failures + 1, 5);
159
+ // MV3 alarms survive worker suspension; Chrome 120's minimum is 30 seconds.
160
+ // Keep the deadline durable so unrelated worker wakeups cannot bypass backoff.
161
+ const delay = Math.min(30 * 2 ** (connection.failures - 1), 300);
162
+ connection.retryAt = Date.now() + (delay + Math.floor(Math.random() * 6)) * 1000;
163
+ connection.reason = code;
164
+ await saveConnection();
165
+ if (!pausedNow && connection.mode === "enabled") {
166
+ await chrome.alarms.create(RETRY_ALARM, {when: connection.retryAt});
167
+ }
168
+ }
169
+
170
+ function failChannel(code, port, epoch) {
171
+ if (channel !== port || generation !== epoch) return;
172
+ closeChannel();
173
+ const closedEpoch = generation;
174
+ void transition(async () => {
175
+ if (generation === closedEpoch) await failedConnection(code);
176
+ });
177
+ }
178
+
179
+ async function connect(manual = false) {
180
+ if (channel || pausedNow || connection?.mode !== "enabled") return;
181
+ if (!manual && connection.retryAt > Date.now()) {
182
+ await chrome.alarms.create(RETRY_ALARM, {when: connection.retryAt});
183
+ return;
184
+ }
185
+ const epoch = ++generation;
186
+ let port;
187
+ try { port = chrome.runtime.connectNative(HOST); }
188
+ catch (_) { return failedConnection("transport_unavailable"); }
189
+ channel = port;
190
+ port.onDisconnect.addListener(() => {
191
+ void chrome.runtime.lastError; // Do not reflect native/browser diagnostics.
192
+ if (channel !== port || generation !== epoch) return;
193
+ failChannel("transport_unavailable", port, epoch);
194
+ });
195
+ port.onMessage.addListener(message => {
196
+ if (channel !== port || epoch !== generation) return;
197
+ if (message?.kind === "error") {
198
+ const code = message.version === NATIVE_VERSION ? message.code : "unsupported_version";
199
+ failChannel(code, port, epoch);
200
+ return;
201
+ }
202
+ if (!browserHandle) {
203
+ if (message?.kind !== "ready" || message.version !== NATIVE_VERSION || !UUID.test(message.browser_handle)) {
204
+ failChannel("unsupported_version", port, epoch);
205
+ return;
206
+ }
207
+ browserHandle = message.browser_handle;
208
+ void transition(async () => {
209
+ if (channel !== port || generation !== epoch) return;
210
+ connection.failures = 0; connection.retryAt = 0; connection.reason = null;
211
+ await saveConnection();
212
+ await chrome.alarms.clear(RETRY_ALARM);
213
+ await chrome.alarms.clear(WATCHDOG_ALARM);
214
+ });
215
+ return;
216
+ }
217
+ if (busy || !UUID.test(message?.request_id) || !message.request ||
218
+ !["targets", "filtered_targets", "fill"].includes(message.request.method)) {
219
+ failChannel("invalid_request", port, epoch); return;
220
+ }
221
+ busy = true;
222
+ handle(message.request, port, epoch).then(result => {
223
+ if (channel === port && generation === epoch) port.postMessage({request_id: message.request_id, result});
224
+ }).catch(() => {
225
+ // Reconnect transport, never replay an operation with uncertain effects.
226
+ if (channel === port && generation === epoch) {
227
+ failChannel("transport_uncertain", port, epoch);
228
+ }
229
+ }).finally(() => { if (generation === epoch) busy = false; });
230
+ });
231
+ try {
232
+ // Profile capability never goes to the options page, agent or website.
233
+ port.postMessage({version: NATIVE_VERSION, profile_id: connection.profile_id,
234
+ capability: connection.capability, manual});
235
+ await chrome.alarms.create(WATCHDOG_ALARM, {delayInMinutes: 4});
236
+ } catch (_) {
237
+ if (channel === port && generation === epoch) await failedConnection("transport_unavailable");
238
+ }
239
+ }
240
+
241
+ async function initializeConnection() {
242
+ if (!await storageReady) throw new Error("storage_unavailable");
243
+ const stored = (await chrome.storage.local.get(CONNECTION_KEY))[CONNECTION_KEY];
244
+ if (stored === undefined) {
245
+ connection = {version: 1, profile_id: crypto.randomUUID(),
246
+ capability: Array.from(crypto.getRandomValues(new Uint8Array(32)), x => x.toString(16).padStart(2, "0")).join(""),
247
+ mode: "enabled", failures: 0, retryAt: 0, reason: null};
248
+ await saveConnection();
249
+ } else {
250
+ if (!stored || stored.version !== 1 || !UUID.test(stored.profile_id) ||
251
+ !/^[0-9a-f]{64}$/.test(stored.capability) || !["enabled", "paused"].includes(stored.mode) ||
252
+ !Number.isInteger(stored.failures) || stored.failures < 0 || stored.failures > 5 ||
253
+ !Number.isSafeInteger(stored.retryAt) || stored.retryAt < 0 ||
254
+ (stored.reason !== null && !REASONS.includes(stored.reason))) throw new Error("storage_unavailable");
255
+ connection = stored;
256
+ // A clock adjustment must not suspend recovery indefinitely.
257
+ connection.retryAt = Math.min(connection.retryAt, Date.now() + 305000);
258
+ }
259
+ await chrome.alarms.clear(WATCHDOG_ALARM);
260
+ if (connection.mode === "paused" || pausedNow) {
261
+ await chrome.alarms.clear(RETRY_ALARM);
262
+ return;
263
+ }
264
+ await connect();
265
+ }
266
+
267
+ async function targets(port, epoch, filter) {
268
+ if (!filter || typeof filter !== "object" || Array.isArray(filter) ||
269
+ Object.keys(filter).some(key => !["top_origin", "tab_id"].includes(key)) ||
270
+ (Object.hasOwn(filter, "top_origin") && typeof filter.top_origin !== "string") ||
271
+ (Object.hasOwn(filter, "tab_id") && (typeof filter.tab_id !== "string" ||
272
+ !/^(?:0|[1-9][0-9]{0,9})$/.test(filter.tab_id)))) return {kind: "error", data: "invalid_request"};
273
+ if (Object.hasOwn(filter, "top_origin")) {
274
+ try { siteKey(filter.top_origin); if (originOf(filter.top_origin) !== filter.top_origin) throw new Error(); }
275
+ catch (_) { return {kind: "error", data: "invalid_request"}; }
276
+ }
277
+ const revision = accessRevision;
278
+ let policy;
279
+ let origins;
280
+ try {
281
+ policy = await readSitePolicy();
282
+ ({origins = []} = await chrome.permissions.getAll());
283
+ }
284
+ catch (_) { return {kind: "error", data: "permission_denied"}; }
285
+ active(port, epoch);
286
+ if (!accessUnchanged(revision)) return {kind: "error", data: "permission_denied"};
287
+ if (!origins.length) return {kind: "targets", data: []};
288
+ // A caller's narrowing is never a grant. Verify it against current Chrome
289
+ // authority before querying even a requested site's tab metadata.
290
+ if (filter.top_origin) {
291
+ const allowed = await permitted(filter.top_origin, policy);
292
+ active(port, epoch);
293
+ if (!accessUnchanged(revision)) return {kind: "error", data: "permission_denied"};
294
+ if (!allowed) return {kind: "targets", data: []};
295
+ origins = [permissionPattern(filter.top_origin)];
296
+ }
297
+ // Host grants allow URL queries without the broad "tabs" permission. Chrome
298
+ // may omit a URL (e.g. after revocation); never fall back to inspecting it.
299
+ // Discarded tabs have no loaded document. Discovery must not wake them.
300
+ const tabs = await chrome.tabs.query({url: origins, discarded: false});
301
+ active(port, epoch);
302
+ // Cache only for this revision/operation, including repeated cross-origin
303
+ // frames. Fills still perform their own fresh, uncached permission checks.
304
+ const permissions = new Map();
305
+ const permittedHere = async origin => {
306
+ if (policy.blockedSites.includes(siteKey(origin))) return false;
307
+ const pattern = permissionPattern(origin);
308
+ if (!permissions.has(pattern)) {
309
+ permissions.set(pattern, await chrome.permissions.contains({origins: [pattern]}));
310
+ }
311
+ return permissions.get(pattern);
312
+ };
313
+ const candidates = [];
314
+ for (const tab of tabs) {
315
+ active(port, epoch);
316
+ if (!accessUnchanged(revision)) return {kind: "error", data: "permission_denied"};
317
+ if (tab.discarded || !Number.isInteger(tab.id) || tab.id < 0 ||
318
+ typeof tab.url !== "string") continue;
319
+ if (filter.tab_id && String(tab.id) !== filter.tab_id) continue;
320
+ let origin;
321
+ try { origin = originOf(tab.url); } catch (_) { continue; }
322
+ // Chrome match patterns ignore ports; the actual origin must still match.
323
+ if (filter.top_origin && origin !== filter.top_origin) continue;
324
+ if (!await permittedHere(origin)) continue;
325
+ active(port, epoch);
326
+ if (!accessUnchanged(revision)) return {kind: "error", data: "permission_denied"};
327
+ candidates.push(tab.id);
328
+ // Bound expensive frame inspection, not the profile's unrelated tab count.
329
+ // Never silently truncate a discovery response to fit the wire budget.
330
+ if (candidates.length > 128) return {kind: "error", data: "capacity"};
331
+ }
332
+ const result = [];
333
+ for (const tabId of candidates) {
334
+ active(port, epoch);
335
+ if (!accessUnchanged(revision)) return {kind: "error", data: "permission_denied"};
336
+ let frames;
337
+ try { frames = await chrome.webNavigation.getAllFrames({tabId}); }
338
+ catch (_) { continue; }
339
+ active(port, epoch);
340
+ if (!accessUnchanged(revision)) return {kind: "error", data: "permission_denied"};
341
+ if (!frames || frames.length > 128) continue;
342
+ const top = frames.find(frame => frame.frameId === 0 && frame.documentLifecycle === "active");
343
+ if (!top || top.errorOccurred || !validDocumentId(top.documentId)) continue;
344
+ let topOrigin;
345
+ try { topOrigin = originOf(top.url); } catch (_) { continue; }
346
+ if (filter.top_origin && topOrigin !== filter.top_origin) continue;
347
+ if (!await permittedHere(topOrigin)) continue;
348
+ for (const frame of frames) {
349
+ active(port, epoch);
350
+ if (!accessUnchanged(revision)) return {kind: "error", data: "permission_denied"};
351
+ if (frame.errorOccurred || frame.documentLifecycle !== "active" || !validDocumentId(frame.documentId)) continue;
352
+ let origin;
353
+ try { origin = originOf(frame.url); } catch (_) { continue; }
354
+ if (!await permittedHere(origin)) continue;
355
+ result.push({tab: String(tabId), frame: String(frame.frameId), document: frame.documentId,
356
+ top_document: top.documentId, origin, top_origin: topOrigin, is_main_frame: frame.frameId === 0});
357
+ if (result.length > 128) return {kind: "error", data: "capacity"};
358
+ }
359
+ }
360
+ active(port, epoch);
361
+ if (!accessUnchanged(revision)) return {kind: "error", data: "permission_denied"};
362
+ return {kind: "targets", data: result};
363
+ }
364
+
365
+ async function fill(params, port, epoch) {
366
+ const fields = params?.fields;
367
+ const target = params?.target;
368
+ if (!Array.isArray(fields) || fields.length === 0 || fields.length > 8 || !target) throw new Error("invalid_request");
369
+ const failed = error => ({kind: "filled", data: {fields: fields.map(() => "not_filled"), error}});
370
+ const uncertain = () => ({kind: "filled", data: {fields: fields.map(() => "uncertain"), error: "transport_uncertain"}});
371
+ try {
372
+ if (!/^[0-9]{1,10}$/.test(target.tab) || !/^[0-9]{1,10}$/.test(target.frame) ||
373
+ !validDocumentId(target.document) || !validDocumentId(target.top_document) ||
374
+ originOf(target.origin) !== target.origin || originOf(target.top_origin) !== target.top_origin ||
375
+ fields.some(field => typeof field.css !== "string" || field.css.length > 512 ||
376
+ typeof field.value !== "string" || field.value.length === 0 || field.value.length > 4096)) return failed("invalid_request");
377
+ const revision = accessRevision;
378
+ let policy;
379
+ try { policy = await readSitePolicy(); } catch (_) { return failed("permission_denied"); }
380
+ if (!accessUnchanged(revision) || !await permitted(target.origin, policy) ||
381
+ !await permitted(target.top_origin, policy)) return failed("permission_denied");
382
+ active(port, epoch);
383
+ const tabId = Number(target.tab);
384
+ const frameId = Number(target.frame);
385
+ const frame = await chrome.webNavigation.getFrame({tabId, frameId, documentId: target.document});
386
+ const top = await chrome.webNavigation.getFrame({tabId, frameId: 0, documentId: target.top_document});
387
+ active(port, epoch);
388
+ if (!frame || !top || frame.errorOccurred || top.errorOccurred ||
389
+ frame.documentLifecycle !== "active" || top.documentLifecycle !== "active" ||
390
+ frame.documentId !== target.document || top.documentId !== target.top_document ||
391
+ originOf(frame.url) !== target.origin || originOf(top.url) !== target.top_origin ||
392
+ target.is_main_frame !== (frameId === 0)) return failed("stale_target");
393
+ // Re-read after asynchronous document checks. Previously discovered handles
394
+ // never bypass a new block or Chrome permission revocation.
395
+ try { policy = await readSitePolicy(); } catch (_) { return failed("permission_denied"); }
396
+ if (!await permitted(target.origin, policy) || !await permitted(target.top_origin, policy) ||
397
+ !accessUnchanged(revision)) return failed("permission_denied");
398
+ active(port, epoch);
399
+ // documentIds, not frameIds: navigation must fail rather than selecting a
400
+ // replacement document between preflight and execution. Isolated world
401
+ // avoids page-overridden JS primitives; the resulting DOM is still shared.
402
+ let results;
403
+ try {
404
+ results = await chrome.scripting.executeScript({target: {tabId, documentIds: [target.document]},
405
+ world: "ISOLATED", func: magicvaultFill, args: [target.origin, fields]});
406
+ } catch (_) { return uncertain(); }
407
+ active(port, epoch);
408
+ if (results.length !== 1 || results[0].documentId !== target.document || results[0].frameId !== frameId) return uncertain();
409
+ const outcome = results[0].result;
410
+ const errors = [null, "invalid_request", "stale_target", "unsupported_target", "ambiguous_target", "unavailable"];
411
+ if (!outcome || !Array.isArray(outcome.fields) || outcome.fields.length !== fields.length ||
412
+ outcome.fields.some(state => !["filled", "not_filled", "uncertain"].includes(state)) || !errors.includes(outcome.error)) return uncertain();
413
+ return {kind: "filled", data: {fields: outcome.fields, error: outcome.error}};
414
+ } catch (_) {
415
+ return failed("stale_target");
416
+ } finally {
417
+ for (const field of fields) if (field && typeof field === "object") field.value = "";
418
+ }
419
+ }
420
+
421
+ async function handle(request, port, epoch) {
422
+ active(port, epoch);
423
+ if (request.method === "targets") return targets(port, epoch, {});
424
+ if (request.method === "filtered_targets") return targets(port, epoch, request.params);
425
+ return fill(request.params, port, epoch);
426
+ }
427
+
428
+ chrome.runtime.onMessage.addListener((message, sender, reply) => {
429
+ // Only our own extension setup page; no content-script or website command
430
+ // path. The setup page never handles credential material.
431
+ if (sender.id !== chrome.runtime.id || sender.url !== chrome.runtime.getURL("options.html")) return false;
432
+ if (message?.action === "site-policy" || message?.action === "site-block") {
433
+ const operation = message.action === "site-policy" ? readSitePolicy() : changeSiteBlock(message.site, message.blocked);
434
+ operation.then(policy => reply({ok: true, blockedSites: policy.blockedSites}),
435
+ () => reply({ok: false}));
436
+ return true;
437
+ }
438
+ if (message?.action === "disconnect") {
439
+ pausedNow = true;
440
+ closeChannel(); // Invalidate in-flight preflight before any asynchronous write.
441
+ transition(() => stopConnection("paused")).then(() => reply(connectionStatus()));
442
+ } else if (message?.action === "connect") {
443
+ pausedNow = false;
444
+ transition(async () => {
445
+ if (!connection || connectionError) throw new Error("storage_unavailable");
446
+ connection.mode = "enabled"; connection.retryAt = 0; connection.failures = 0; connection.reason = null;
447
+ await saveConnection(); await connect(true);
448
+ }).then(() => reply(connectionStatus()));
449
+ } else if (message?.action === "status") {
450
+ connectionWork.then(() => reply(connectionStatus()));
451
+ } else return false;
452
+ return true;
453
+ });
454
+ chrome.action.onClicked.addListener(() => chrome.runtime.openOptionsPage());
455
+ chrome.runtime.onInstalled.addListener(() => chrome.runtime.openOptionsPage());
456
+ chrome.runtime.onStartup.addListener(() => { void transition(() => connect()); });
457
+ chrome.alarms.onAlarm.addListener(alarm => {
458
+ if (alarm.name === RETRY_ALARM) void transition(() => connect());
459
+ else if (alarm.name === WATCHDOG_ALARM) void transition(async () => {
460
+ if (channel && !browserHandle) await failedConnection("expired");
461
+ });
462
+ });
463
+ void transition(initializeConnection);
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "version": "0.9.0",
3
+ "license": "MIT OR Apache-2.0",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/MagicBeansAI/MagicVault.git"
7
+ },
8
+ "engines": {
9
+ "node": ">=22"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "tag": "latest",
14
+ "registry": "https://registry.npmjs.org/"
15
+ },
16
+ "homepage": "https://github.com/MagicBeansAI/MagicVault#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/MagicBeansAI/MagicVault/issues"
19
+ },
20
+ "keywords": [
21
+ "mcp",
22
+ "credentials",
23
+ "vault",
24
+ "agents",
25
+ "typescript",
26
+ "alpha"
27
+ ],
28
+ "name": "@magicbeansai/magicvault-win32-x64",
29
+ "description": "Prebuilt MagicVault executables and browser extension for win32-x64",
30
+ "os": [
31
+ "win32"
32
+ ],
33
+ "cpu": [
34
+ "x64"
35
+ ],
36
+ "files": [
37
+ "bin",
38
+ "extension",
39
+ "examples",
40
+ "bundle.json",
41
+ "LICENSE-MIT",
42
+ "LICENSE-APACHE"
43
+ ]
44
+ }