@agentmatrix.pro/browser-sdk 0.0.0-stage → 0.1.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/LICENSE +201 -0
- package/README.md +76 -2
- package/dist/index.d.ts +253 -0
- package/dist/index.js +404 -0
- package/package.json +51 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0-rc.1
|
|
4
|
+
|
|
5
|
+
First AgentMatrix browser SDK prerelease, prepared for the official npm `next`
|
|
6
|
+
channel. Requires Platform `0.159.1` with browser control enabled and the calling
|
|
7
|
+
Workspace origin allowed. Real Identity/Guest enablement qualification remains
|
|
8
|
+
pending; installing the package does not enable the server feature or exit Q0.
|
|
9
|
+
|
|
10
|
+
- Keep `BrowserViewer` type-only in built declarations, matching the runtime exports.
|
|
11
|
+
- Refuse attachment after `stopInput()` and enforce the contract's 8192-byte JWT limit before transport.
|
|
12
|
+
- Adopt Platform `0.159.1` error metadata, preserving both Gateway refusals and wrapped Workspace `error.details` responses.
|
|
13
|
+
|
|
14
|
+
- Add human-authorized original-browser status, acquisition and handback with single-attempt transport and an iframe grant helper.
|
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 AgentOS Labs
|
|
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,77 @@
|
|
|
1
|
-
#
|
|
1
|
+
# AgentMatrix browser control
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Human-authorized control of an existing Agent browser. The `0.1.0-rc.1`
|
|
4
|
+
prerelease targets the `next` channel for integration work:
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm install @agentmatrix.pro/browser-sdk@0.1.0-rc.1
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
It requires Platform `0.159.1` with browser control enabled and the calling
|
|
11
|
+
Workspace origin explicitly allowed by its Preview owner. Real Identity/Guest
|
|
12
|
+
enablement qualification remains pending; installing this package does not
|
|
13
|
+
enable browser control on the server.
|
|
14
|
+
|
|
15
|
+
This package uses the current signed-in user's JWT, selected tenant/namespace and
|
|
16
|
+
owned API-key **ID**, plus the Gateway's existing CSRF cookie/header pair. It does
|
|
17
|
+
not accept an API key as human authorization, sign users in, refresh credentials,
|
|
18
|
+
create browsers or establish cross-origin cookie/CORS policy.
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { BrowserControlClient } from "@agentmatrix.pro/browser-sdk";
|
|
22
|
+
|
|
23
|
+
const control = new BrowserControlClient({ baseURL: gatewayOrigin });
|
|
24
|
+
// Take a fresh snapshot from your application's authenticated user/scope owner.
|
|
25
|
+
const context = { userJWT, tenantId, namespaceId, apiKeyId, sessionId, csrfToken };
|
|
26
|
+
const current = await control.get(context);
|
|
27
|
+
if (current.data.allowed_actions.includes("acquire") && current.data.control_id) {
|
|
28
|
+
const result = await control.acquire(context, {
|
|
29
|
+
operation_id: crypto.randomUUID(), // one new explicit user action
|
|
30
|
+
expected_control_id: current.data.control_id,
|
|
31
|
+
expected_revision: current.data.revision,
|
|
32
|
+
});
|
|
33
|
+
if (result.viewer) {
|
|
34
|
+
result.viewer.attach(iframe);
|
|
35
|
+
// Keep this handle in memory. Its deadline is result.viewer.expiresAt.
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`get`, `acquire` and `release` make one HTTP attempt each. They do not retry,
|
|
41
|
+
refresh authentication, generate IDs or poll. Read defaults to a 15-second total
|
|
42
|
+
deadline; mutations default to 200 seconds to cover the server's drain budget.
|
|
43
|
+
Per-call `{ signal, timeoutMs }` bounds headers and the complete response body.
|
|
44
|
+
An injected `fetch` must also make one attempt without hidden refresh/retry.
|
|
45
|
+
|
|
46
|
+
On explicit handback, first call `viewer.stopInput()`. Read a fresh status, then
|
|
47
|
+
call `release(context, { operation_id, expected_control_id, expected_revision,
|
|
48
|
+
lease_id })` using that observation. Retain the iframe while the response is
|
|
49
|
+
202 or state remains revoking: it must receive the Guest's real clear challenge.
|
|
50
|
+
After confirmed Agent handback, call `viewer.dispose()`. When allowed actions
|
|
51
|
+
contain `release`, offer an explicit **Continue handback** action using the latest
|
|
52
|
+
observation and a new user intent. Do not automatically change IDs or resend.
|
|
53
|
+
|
|
54
|
+
`BrowserControlError` contains only a code, optional HTTP status and bounded
|
|
55
|
+
reason. A lost/aborted/timed-out response after dispatch has `replyUnproven: true`;
|
|
56
|
+
read status before offering another action. A known refusal does not clear any
|
|
57
|
+
earlier responsibility. Neither HTTP 202, expiry, iframe closure nor native
|
|
58
|
+
browser closure proves handback. Replay responses never reconstruct a viewer.
|
|
59
|
+
|
|
60
|
+
`BrowserViewer` is a TypeScript interface for a returned handle, not a runtime
|
|
61
|
+
constructor. Obtain it from a fresh `acquire` response; do not use `new` or
|
|
62
|
+
`instanceof`. Calling `stopInput()` before attachment permanently prevents that
|
|
63
|
+
handle from attaching.
|
|
64
|
+
|
|
65
|
+
The viewer helper permits the embedded page's forms, validates both message
|
|
66
|
+
source and exact origin, and burns its token after one delivery. Expiry stops
|
|
67
|
+
input and hides the frame while leaving its cleanup connection alive. Call
|
|
68
|
+
`stopInput()` on stale/unknown status and before handback. On user/tenant/Session
|
|
69
|
+
changes, cancel outstanding calls, discard late replies, and dispose the old
|
|
70
|
+
viewer; the server retains any unresolved responsibility. Never log tokens,
|
|
71
|
+
Preview URLs, page data or form input; do not store a viewer in persistent state.
|
|
72
|
+
Grant serialization/Node inspection is redacted, but application memory and the
|
|
73
|
+
authorized iframe are intentionally within the trusted user's boundary.
|
|
74
|
+
|
|
75
|
+
Ordinary API-key users can only query status through
|
|
76
|
+
`AgentMatrix.sessions.browserControl.get(sessionId)` in the data-plane package.
|
|
77
|
+
No API-key method acquires human control.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
type components = {
|
|
2
|
+
schemas: {
|
|
3
|
+
BrowserControlReadResponse: {
|
|
4
|
+
data: components["schemas"]["BrowserControlStatus"];
|
|
5
|
+
};
|
|
6
|
+
/** @description Safe business projection. It never includes a viewer grant, page data, physical/Worker/envd coordinates or management credentials. A closed original context is not physical release or writer-drain proof. */
|
|
7
|
+
BrowserControlStatus: {
|
|
8
|
+
session_id: string;
|
|
9
|
+
/** @description SM logical control identity, never a physical handle or Guest browser ID. Null before a control slot exists. */
|
|
10
|
+
control_id: string | null;
|
|
11
|
+
/**
|
|
12
|
+
* Format: int64
|
|
13
|
+
* @description SM durable control/intent CAS revision. Upstream observations and action availability still require fresh checks.
|
|
14
|
+
*/
|
|
15
|
+
revision: number;
|
|
16
|
+
state: components["schemas"]["BrowserControlState"];
|
|
17
|
+
lease: components["schemas"]["BrowserControlLease"] | null;
|
|
18
|
+
reason: components["schemas"]["BrowserControlReason"] | null;
|
|
19
|
+
allowed_actions: components["schemas"]["BrowserControlAction"][];
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* @description Contract-first browser lifecycle model; handlers and activation are delivered separately. Business revision is not a Guest revision or a complete-response ETag.
|
|
23
|
+
* @enum {string}
|
|
24
|
+
*/
|
|
25
|
+
BrowserControlState: "unavailable" | "agent" | "acquiring" | "human" | "revoking" | "blocked" | "closed";
|
|
26
|
+
BrowserControlLease: {
|
|
27
|
+
lease_id: string;
|
|
28
|
+
/**
|
|
29
|
+
* Format: date-time
|
|
30
|
+
* @description Conservative server-owned deadline. Expiry revokes human admission; it never returns Agent authority or clears retained debt.
|
|
31
|
+
*/
|
|
32
|
+
expires_at: string;
|
|
33
|
+
};
|
|
34
|
+
/** @enum {string} */
|
|
35
|
+
BrowserControlReason: "browser_control_disabled" | "browser_not_open" | "browser_control_unsupported" | "browser_control_busy" | "browser_control_expired" | "browser_control_revoked" | "browser_control_unproven" | "browser_control_viewer_clear_pending" | "browser_control_binding_changed" | "browser_control_closed" | "browser_control_grant_unavailable";
|
|
36
|
+
/**
|
|
37
|
+
* @description Advisory UI action after fresh authorization; never effect authority.
|
|
38
|
+
* @enum {string}
|
|
39
|
+
*/
|
|
40
|
+
BrowserControlAction: "acquire" | "release";
|
|
41
|
+
GatewayError: {
|
|
42
|
+
/**
|
|
43
|
+
* @example unauthenticated
|
|
44
|
+
* @enum {string}
|
|
45
|
+
*/
|
|
46
|
+
code: "invalid_input" | "unauthenticated" | "permission_denied" | "not_found" | "method_not_allowed" | "conflict" | "rate_limited" | "idempotent_hit" | "invalid_state" | "has_open_turn" | "internal" | "unavailable";
|
|
47
|
+
message: string;
|
|
48
|
+
request_id?: string;
|
|
49
|
+
};
|
|
50
|
+
GatewayOrErrorEnvelope: components["schemas"]["GatewayError"] | components["schemas"]["ErrorEnvelope"];
|
|
51
|
+
ErrorEnvelope: {
|
|
52
|
+
error: {
|
|
53
|
+
/**
|
|
54
|
+
* @example invalid_input
|
|
55
|
+
* @enum {string}
|
|
56
|
+
*/
|
|
57
|
+
code: "invalid_input" | "unauthenticated" | "permission_denied" | "not_found" | "method_not_allowed" | "conflict" | "rate_limited" | "idempotent_hit" | "invalid_state" | "has_open_turn" | "internal" | "unavailable" | "invalid_dependency" | "dependency_not_authorized" | "dependency_validation_limit" | "dependency_unavailable" | "idempotency_conflict" | "version_conflict" | "channel_onboarding_disabled" | "adapter_installation_not_found" | "adapter_installation_suspended" | "adapter_installation_archived" | "binding_not_found" | "binding_conflict" | "binding_idempotency_mismatch" | "binding_limit_exceeded" | "reply_anchor_required" | "observed_tip_required" | "invalid_reply_target" | "stale_observed_tip" | "session_not_active" | "stale_interrupt_target" | "interrupt_not_available" | "invalid_tool_action_target" | "tool_action_not_pending" | "persistent_approval_required" | "persistent_approval_denied" | "persistent_approval_expired" | "persistent_approval_idempotency_mismatch" | "persistent_approval_target_changed" | "inbound_idempotency_mismatch" | "inbound_idempotency_expired" | "subscription_not_found" | "subscription_scope_immutable" | "subscription_disabling" | "subscription_disabled" | "subscription_deprovisioning" | "subscription_deprovisioned" | "subscription_quota_exceeded" | "subscription_cursor_invalid" | "delivery_not_found" | "dlq_item_not_found" | "dlq_generation_not_open" | "dlq_operation_idempotency_mismatch" | "link_authorization_denied" | "link_authorization_expired" | "link_authorization_idempotency_mismatch";
|
|
58
|
+
message: string;
|
|
59
|
+
request_id?: string;
|
|
60
|
+
/** @description Optional non-secret structured error details, such as the current optimistic revision. */
|
|
61
|
+
details?: {
|
|
62
|
+
[key: string]: unknown;
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
/** @description One explicit user intent. Owner, targets, paths, origins, credentials and TTL are derived by trusted owners, never supplied here. Same-operation readback cannot repeat effects or recover a grant. */
|
|
67
|
+
AcquireBrowserControlRequest: {
|
|
68
|
+
operation_id: string;
|
|
69
|
+
expected_control_id: string;
|
|
70
|
+
/** Format: int64 */
|
|
71
|
+
expected_revision: number;
|
|
72
|
+
};
|
|
73
|
+
BrowserControlAcquireResponse: {
|
|
74
|
+
data: components["schemas"]["BrowserControlStatus"];
|
|
75
|
+
viewer_access?: components["schemas"]["BrowserViewerAccess"];
|
|
76
|
+
};
|
|
77
|
+
/** @description Ephemeral successful-acquisition delivery only. Never returned by status/replay/release, logged, persisted or placed in EventLog. Ordinary Preview authorization is independent and cannot replace this human capability. */
|
|
78
|
+
BrowserViewerAccess: {
|
|
79
|
+
/**
|
|
80
|
+
* Format: uri
|
|
81
|
+
* @description Trusted Preview-owner URL. The human token is never placed in this URL; the parent sends it only to the exact iframe origin.
|
|
82
|
+
*/
|
|
83
|
+
url: string;
|
|
84
|
+
/** Format: password */
|
|
85
|
+
token: string;
|
|
86
|
+
/**
|
|
87
|
+
* Format: date-time
|
|
88
|
+
* @description Never later than the business lease or original Guest grant deadline. A caller cannot extend it from receipt time.
|
|
89
|
+
*/
|
|
90
|
+
expires_at: string;
|
|
91
|
+
};
|
|
92
|
+
/** @description Revoke the exact original lease. Missing clear/drain evidence retains revoking/blocked state; release is not Session Archive or original-context destruction. */
|
|
93
|
+
ReleaseBrowserControlRequest: {
|
|
94
|
+
operation_id: string;
|
|
95
|
+
expected_control_id: string;
|
|
96
|
+
/** Format: int64 */
|
|
97
|
+
expected_revision: number;
|
|
98
|
+
lease_id: string;
|
|
99
|
+
};
|
|
100
|
+
/** @enum {string} */
|
|
101
|
+
BrowserControlErrorReason: "browser_control_request_invalid" | "browser_control_human_required" | "browser_control_revision_mismatch" | "browser_control_lease_mismatch" | "browser_control_operation_mismatch" | "browser_control_busy" | "browser_control_unproven" | "browser_control_unsupported" | "browser_control_not_ready" | "browser_control_closed";
|
|
102
|
+
};
|
|
103
|
+
responses: {
|
|
104
|
+
/** @description Aggregate tenant public API rate limit exceeded. */
|
|
105
|
+
TenantRateLimit: {
|
|
106
|
+
headers: {
|
|
107
|
+
/** @description Seconds to wait before retrying. */
|
|
108
|
+
"Retry-After"?: number;
|
|
109
|
+
[name: string]: unknown;
|
|
110
|
+
};
|
|
111
|
+
content: {
|
|
112
|
+
"application/json": components["schemas"]["GatewayError"];
|
|
113
|
+
};
|
|
114
|
+
};
|
|
115
|
+
/** @description Gateway admission can return a flat error; Workspace returns an error envelope with optional error.details.reason from BrowserControlErrorReason. A refusal concerns this request only and does not settle earlier browser responsibility. An unknown result requires status readback, never automatic mutation replay. */
|
|
116
|
+
BrowserControlError: {
|
|
117
|
+
headers: {
|
|
118
|
+
[name: string]: unknown;
|
|
119
|
+
};
|
|
120
|
+
content: {
|
|
121
|
+
"application/json": components["schemas"]["GatewayOrErrorEnvelope"];
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
};
|
|
125
|
+
parameters: {
|
|
126
|
+
/** @description Tenant selected in the User Dashboard resource URL. Identity verifies that the authenticated user has an active membership in this tenant before forwarding to canonical data-plane APIs. */
|
|
127
|
+
WorkspaceTenantId: string;
|
|
128
|
+
/** @example default */
|
|
129
|
+
NamespaceId: string;
|
|
130
|
+
/** @description Canonical Session identifier to reauthorize under the currently selected key. */
|
|
131
|
+
WorkspaceSessionId: string;
|
|
132
|
+
/** @description Current tenant selected by the browser. Gateway resolves active membership and selected-key ownership before signing the private Workspace hop. */
|
|
133
|
+
WorkspaceCurrentTenantIdHeader: string;
|
|
134
|
+
/** @description Current namespace selected by the browser and authorized against the selected key before the Workspace API is called. */
|
|
135
|
+
WorkspaceNamespaceHeader: string;
|
|
136
|
+
/** @description Dashboard-selected user-owned data-plane API key. Required when calling canonical session event append/stream or approved Volume routes with UserJWT. Ignored for direct `ariadra_*` API-key callers. */
|
|
137
|
+
DashboardAPIKeyIdHeader: string;
|
|
138
|
+
/** @description Required on Workspace state-changing requests and must match the readable `ariadra_csrf_token` cookie. Gateway consumes both values; neither reaches the Workspace API. */
|
|
139
|
+
WorkspaceCSRFTokenHeader: string;
|
|
140
|
+
/** @description Required on Gateway-authenticated Workspace state-changing requests and must match `X-CSRF-Token`. Gateway consumes both values; neither reaches the Workspace API. */
|
|
141
|
+
WorkspaceCSRFTokenCookie: string;
|
|
142
|
+
};
|
|
143
|
+
requestBodies: never;
|
|
144
|
+
headers: never;
|
|
145
|
+
pathItems: never;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** Structural DOM types keep Node clients importable without a DOM global or shim. */
|
|
149
|
+
interface BrowserViewerMessage {
|
|
150
|
+
source: unknown;
|
|
151
|
+
origin: string;
|
|
152
|
+
data: unknown;
|
|
153
|
+
}
|
|
154
|
+
interface BrowserViewerWindow {
|
|
155
|
+
addEventListener(type: "message", listener: (event: BrowserViewerMessage) => void): void;
|
|
156
|
+
removeEventListener(type: "message", listener: (event: BrowserViewerMessage) => void): void;
|
|
157
|
+
}
|
|
158
|
+
interface BrowserViewerFrame {
|
|
159
|
+
src: string;
|
|
160
|
+
style: {
|
|
161
|
+
visibility: string;
|
|
162
|
+
};
|
|
163
|
+
contentWindow: {
|
|
164
|
+
postMessage(message: unknown, targetOrigin: string): void;
|
|
165
|
+
} | null;
|
|
166
|
+
ownerDocument: {
|
|
167
|
+
defaultView: BrowserViewerWindow | null;
|
|
168
|
+
};
|
|
169
|
+
setAttribute(name: string, value: string): void;
|
|
170
|
+
removeAttribute(name: string): void;
|
|
171
|
+
blur(): void;
|
|
172
|
+
}
|
|
173
|
+
/** Acquired handle only; no public constructor or runtime BrowserViewer export. */
|
|
174
|
+
interface BrowserViewer {
|
|
175
|
+
readonly expiresAt: string;
|
|
176
|
+
/** Attach once, before the iframe loads. */
|
|
177
|
+
attach(frame: BrowserViewerFrame): void;
|
|
178
|
+
/** Stop local input while retaining the iframe for the Guest's actual clear ACK. */
|
|
179
|
+
stopInput(): void;
|
|
180
|
+
/** Local teardown only; never proof of handback or settled server responsibility. */
|
|
181
|
+
dispose(): void;
|
|
182
|
+
toJSON(): string;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
type BrowserControlStatus = components["schemas"]["BrowserControlStatus"];
|
|
186
|
+
type BrowserControlState = components["schemas"]["BrowserControlState"];
|
|
187
|
+
type BrowserControlAction = components["schemas"]["BrowserControlAction"];
|
|
188
|
+
type BrowserControlReason = components["schemas"]["BrowserControlReason"];
|
|
189
|
+
type BrowserControlErrorReason = components["schemas"]["BrowserControlErrorReason"];
|
|
190
|
+
type AcquireBrowserControlRequest = components["schemas"]["AcquireBrowserControlRequest"];
|
|
191
|
+
type ReleaseBrowserControlRequest = components["schemas"]["ReleaseBrowserControlRequest"];
|
|
192
|
+
/** One current user/context snapshot. Never pass a data-plane API key as userJWT. */
|
|
193
|
+
interface BrowserControlContext {
|
|
194
|
+
userJWT: string;
|
|
195
|
+
tenantId: string;
|
|
196
|
+
namespaceId: string;
|
|
197
|
+
apiKeyId: string;
|
|
198
|
+
sessionId: string;
|
|
199
|
+
}
|
|
200
|
+
interface BrowserControlMutationContext extends BrowserControlContext {
|
|
201
|
+
/** Must match the browser's ariadra_csrf_token cookie on the Gateway origin. */
|
|
202
|
+
csrfToken: string;
|
|
203
|
+
}
|
|
204
|
+
interface BrowserControlRequestOptions {
|
|
205
|
+
signal?: AbortSignal;
|
|
206
|
+
/** Total budget including the complete response body. Defaults to 15s read / 200s mutation. */
|
|
207
|
+
timeoutMs?: number;
|
|
208
|
+
}
|
|
209
|
+
interface BrowserControlResult {
|
|
210
|
+
status: 200 | 202;
|
|
211
|
+
data: BrowserControlStatus;
|
|
212
|
+
replayed: boolean;
|
|
213
|
+
}
|
|
214
|
+
interface BrowserControlAcquisition extends BrowserControlResult {
|
|
215
|
+
status: 200;
|
|
216
|
+
/** Present only on a fresh successful acquisition. Not serializable or reusable. */
|
|
217
|
+
viewer?: BrowserViewer;
|
|
218
|
+
}
|
|
219
|
+
interface BrowserControlClientOptions {
|
|
220
|
+
/** Exact Gateway origin, HTTPS except local development. No implicit hosted default. */
|
|
221
|
+
baseURL: string;
|
|
222
|
+
/** Must implement a single fetch attempt, without authentication refresh or retries. */
|
|
223
|
+
fetch?: typeof globalThis.fetch;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Thin user-authorized client. No cached context, automatic reads, retries, grants or operation IDs. */
|
|
227
|
+
declare class BrowserControlClient {
|
|
228
|
+
#private;
|
|
229
|
+
constructor(options: BrowserControlClientOptions);
|
|
230
|
+
get(context: BrowserControlContext, options?: BrowserControlRequestOptions): Promise<BrowserControlResult>;
|
|
231
|
+
acquire(context: BrowserControlMutationContext, intent: AcquireBrowserControlRequest, options?: BrowserControlRequestOptions): Promise<BrowserControlAcquisition>;
|
|
232
|
+
release(context: BrowserControlMutationContext, intent: ReleaseBrowserControlRequest, options?: BrowserControlRequestOptions): Promise<BrowserControlResult>;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
type BrowserControlFailure = "invalid_input" | "aborted" | "timeout" | "transport_unproven" | "response_unproven" | "refused";
|
|
236
|
+
/**
|
|
237
|
+
* Contains only bounded classifications: no URL, headers, body, token or peer error/cause.
|
|
238
|
+
* A false replyUnproven does not settle a previous lease or operation. No error authorizes a retry.
|
|
239
|
+
*/
|
|
240
|
+
declare class BrowserControlError extends Error {
|
|
241
|
+
readonly code: BrowserControlFailure;
|
|
242
|
+
readonly replyUnproven: boolean;
|
|
243
|
+
readonly status?: number | undefined;
|
|
244
|
+
readonly reason?: BrowserControlErrorReason | undefined;
|
|
245
|
+
readonly name = "BrowserControlError";
|
|
246
|
+
constructor(code: BrowserControlFailure, replyUnproven: boolean, status?: number | undefined, reason?: BrowserControlErrorReason | undefined);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
declare const CONTRACT_VERSION = "0.159.1";
|
|
250
|
+
|
|
251
|
+
declare const BROWSER_SDK_VERSION = "0.1.0-rc.1";
|
|
252
|
+
|
|
253
|
+
export { type AcquireBrowserControlRequest, BROWSER_SDK_VERSION, type BrowserControlAcquisition, type BrowserControlAction, BrowserControlClient, type BrowserControlClientOptions, type BrowserControlContext, BrowserControlError, type BrowserControlErrorReason, type BrowserControlFailure, type BrowserControlMutationContext, type BrowserControlReason, type BrowserControlRequestOptions, type BrowserControlResult, type BrowserControlState, type BrowserControlStatus, type BrowserViewer, type BrowserViewerFrame, type BrowserViewerMessage, type BrowserViewerWindow, CONTRACT_VERSION, type ReleaseBrowserControlRequest };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
// ../../packages/browser-sdk/src/errors.ts
|
|
2
|
+
var BrowserControlError = class extends Error {
|
|
3
|
+
constructor(code, replyUnproven, status, reason) {
|
|
4
|
+
super(`Browser control request failed: ${code}.`);
|
|
5
|
+
this.code = code;
|
|
6
|
+
this.replyUnproven = replyUnproven;
|
|
7
|
+
this.status = status;
|
|
8
|
+
this.reason = reason;
|
|
9
|
+
}
|
|
10
|
+
code;
|
|
11
|
+
replyUnproven;
|
|
12
|
+
status;
|
|
13
|
+
reason;
|
|
14
|
+
name = "BrowserControlError";
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// ../../packages/browser-sdk/src/generated/contract-version.ts
|
|
18
|
+
var CONTRACT_VERSION = "0.159.1";
|
|
19
|
+
|
|
20
|
+
// ../../packages/browser-sdk/src/validation.ts
|
|
21
|
+
var identifier = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
|
|
22
|
+
var reasons = [
|
|
23
|
+
"browser_control_disabled",
|
|
24
|
+
"browser_not_open",
|
|
25
|
+
"browser_control_unsupported",
|
|
26
|
+
"browser_control_busy",
|
|
27
|
+
"browser_control_expired",
|
|
28
|
+
"browser_control_revoked",
|
|
29
|
+
"browser_control_unproven",
|
|
30
|
+
"browser_control_viewer_clear_pending",
|
|
31
|
+
"browser_control_binding_changed",
|
|
32
|
+
"browser_control_closed",
|
|
33
|
+
"browser_control_grant_unavailable"
|
|
34
|
+
];
|
|
35
|
+
var errorReasons = [
|
|
36
|
+
"browser_control_request_invalid",
|
|
37
|
+
"browser_control_human_required",
|
|
38
|
+
"browser_control_revision_mismatch",
|
|
39
|
+
"browser_control_lease_mismatch",
|
|
40
|
+
"browser_control_operation_mismatch",
|
|
41
|
+
"browser_control_busy",
|
|
42
|
+
"browser_control_unproven",
|
|
43
|
+
"browser_control_unsupported",
|
|
44
|
+
"browser_control_not_ready",
|
|
45
|
+
"browser_control_closed"
|
|
46
|
+
];
|
|
47
|
+
var record = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
48
|
+
var id = (v) => typeof v === "string" && identifier.test(v);
|
|
49
|
+
var date = (v) => typeof v === "string" && v.length <= 64 && Number.isFinite(Date.parse(v));
|
|
50
|
+
var keys = (v, allowed) => Object.keys(v).every((k) => allowed.includes(k));
|
|
51
|
+
function invalidInput() {
|
|
52
|
+
throw new BrowserControlError("invalid_input", false);
|
|
53
|
+
}
|
|
54
|
+
function secret(v, max) {
|
|
55
|
+
return typeof v === "string" && v.length > 0 && v.length <= max && /^[\x21-\x7e]+$/.test(v);
|
|
56
|
+
}
|
|
57
|
+
function contextPath(c, mutation) {
|
|
58
|
+
if (!record(c) || !secret(c.userJWT, 8192) || typeof c.tenantId !== "string" || !/^tnt_[0-9A-HJKMNP-TV-Z]{26}$/.test(c.tenantId) || typeof c.apiKeyId !== "string" || !/^ak_[0-9A-HJKMNP-TV-Z]{26}$/.test(c.apiKeyId) || typeof c.namespaceId !== "string" || c.namespaceId.length > 63 || !/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(c.namespaceId) || !id(c.sessionId) || mutation && !secret(c.csrfToken, 8192))
|
|
59
|
+
invalidInput();
|
|
60
|
+
return `/v1/users/me/resources/t/${encodeURIComponent(c.tenantId)}/n/${encodeURIComponent(c.namespaceId)}/sessions/${encodeURIComponent(c.sessionId)}/browser-control`;
|
|
61
|
+
}
|
|
62
|
+
function validateIntent(value, release) {
|
|
63
|
+
if (!record(value) || !keys(value, [
|
|
64
|
+
"operation_id",
|
|
65
|
+
"expected_control_id",
|
|
66
|
+
"expected_revision",
|
|
67
|
+
...release ? ["lease_id"] : []
|
|
68
|
+
]) || !id(value.operation_id) || !id(value.expected_control_id) || !Number.isSafeInteger(value.expected_revision) || value.expected_revision < 1 || release && !id(value.lease_id))
|
|
69
|
+
invalidInput();
|
|
70
|
+
return {
|
|
71
|
+
operation_id: value.operation_id,
|
|
72
|
+
expected_control_id: value.expected_control_id,
|
|
73
|
+
expected_revision: value.expected_revision,
|
|
74
|
+
...release ? { lease_id: value.lease_id } : {}
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function parseReply(value, sessionId, allowGrant) {
|
|
78
|
+
const invalid = () => {
|
|
79
|
+
throw new BrowserControlError("response_unproven", true);
|
|
80
|
+
};
|
|
81
|
+
if (!record(value) || !keys(value, ["data", ...allowGrant ? ["viewer_access"] : []]) || !record(value.data))
|
|
82
|
+
return invalid();
|
|
83
|
+
const s = value.data;
|
|
84
|
+
if (!keys(s, [
|
|
85
|
+
"session_id",
|
|
86
|
+
"control_id",
|
|
87
|
+
"revision",
|
|
88
|
+
"state",
|
|
89
|
+
"lease",
|
|
90
|
+
"reason",
|
|
91
|
+
"allowed_actions"
|
|
92
|
+
]) || s.session_id !== sessionId || !id(s.session_id) || !Number.isSafeInteger(s.revision) || s.revision < 0 || s.control_id !== null && !id(s.control_id) || s.reason !== null && !reasons.includes(s.reason) || !Array.isArray(s.allowed_actions) || s.allowed_actions.length > 1)
|
|
93
|
+
return invalid();
|
|
94
|
+
const lease = s.lease;
|
|
95
|
+
if (lease !== null && (!record(lease) || !keys(lease, ["lease_id", "expires_at"]) || !id(lease.lease_id) || !date(lease.expires_at)))
|
|
96
|
+
return invalid();
|
|
97
|
+
let action;
|
|
98
|
+
switch (s.state) {
|
|
99
|
+
case "unavailable":
|
|
100
|
+
if (lease !== null || s.reason === null || (s.control_id === null ? s.revision !== 0 : s.revision < 1))
|
|
101
|
+
return invalid();
|
|
102
|
+
break;
|
|
103
|
+
case "agent":
|
|
104
|
+
if (lease !== null || s.reason !== null) return invalid();
|
|
105
|
+
action = "acquire";
|
|
106
|
+
break;
|
|
107
|
+
case "acquiring":
|
|
108
|
+
case "human":
|
|
109
|
+
case "revoking":
|
|
110
|
+
if (lease === null || s.state === "human" && s.reason !== null)
|
|
111
|
+
return invalid();
|
|
112
|
+
action = "release";
|
|
113
|
+
break;
|
|
114
|
+
case "blocked":
|
|
115
|
+
case "closed":
|
|
116
|
+
if (s.reason === null) return invalid();
|
|
117
|
+
break;
|
|
118
|
+
default:
|
|
119
|
+
return invalid();
|
|
120
|
+
}
|
|
121
|
+
if (s.state !== "unavailable" && (!id(s.control_id) || s.revision < 1) || s.allowed_actions.some((a) => a !== action))
|
|
122
|
+
return invalid();
|
|
123
|
+
const result = {
|
|
124
|
+
data: s
|
|
125
|
+
};
|
|
126
|
+
if (value.viewer_access !== void 0) {
|
|
127
|
+
const v = value.viewer_access;
|
|
128
|
+
if (!allowGrant || s.state !== "human" || !record(lease) || !record(v) || !keys(v, ["url", "token", "expires_at"]) || typeof v.token !== "string" || !/^[a-f0-9]{64}$/.test(v.token) || !date(v.expires_at) || Date.parse(v.expires_at) > Date.parse(lease.expires_at) || typeof v.url !== "string" || v.url.length > 8192)
|
|
129
|
+
return invalid();
|
|
130
|
+
try {
|
|
131
|
+
const url = new URL(v.url);
|
|
132
|
+
if (!safeURL(url) || url.hash || decodeURIComponent(v.url).includes(v.token))
|
|
133
|
+
return invalid();
|
|
134
|
+
} catch {
|
|
135
|
+
return invalid();
|
|
136
|
+
}
|
|
137
|
+
result.access = v;
|
|
138
|
+
}
|
|
139
|
+
return result;
|
|
140
|
+
}
|
|
141
|
+
function safeURL(url) {
|
|
142
|
+
return !url.username && !url.password && (url.protocol === "https:" || url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname));
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ../../packages/browser-sdk/src/viewer.ts
|
|
146
|
+
var BrowserViewerHandle = class {
|
|
147
|
+
expiresAt;
|
|
148
|
+
#url;
|
|
149
|
+
#token;
|
|
150
|
+
#frame;
|
|
151
|
+
#detach;
|
|
152
|
+
#timer;
|
|
153
|
+
#used = false;
|
|
154
|
+
/** @internal Created only from a validated fresh acquisition reply. */
|
|
155
|
+
constructor(access) {
|
|
156
|
+
this.expiresAt = access.expires_at;
|
|
157
|
+
this.#url = access.url;
|
|
158
|
+
this.#token = access.token;
|
|
159
|
+
}
|
|
160
|
+
/** Attach once, before the iframe loads. Use the exact Workspace origin approved by the deployment. */
|
|
161
|
+
attach(frame) {
|
|
162
|
+
if (this.#used || !frame.ownerDocument.defaultView || Date.parse(this.expiresAt) <= Date.now()) {
|
|
163
|
+
throw new BrowserControlError("invalid_input", false);
|
|
164
|
+
}
|
|
165
|
+
this.#used = true;
|
|
166
|
+
this.#frame = frame;
|
|
167
|
+
const owner = frame.ownerDocument.defaultView;
|
|
168
|
+
const origin = new URL(this.#url).origin;
|
|
169
|
+
const receive = (event) => {
|
|
170
|
+
if (!this.#token || event.source !== frame.contentWindow || event.origin !== origin || !event.data || typeof event.data !== "object" || !("type" in event.data) || event.data.type !== "ariadra-browser-ready")
|
|
171
|
+
return;
|
|
172
|
+
if (Date.now() >= Date.parse(this.expiresAt)) {
|
|
173
|
+
this.stopInput();
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const token = this.#token;
|
|
177
|
+
this.#token = void 0;
|
|
178
|
+
frame.contentWindow?.postMessage(
|
|
179
|
+
{ type: "ariadra-browser-grant", token },
|
|
180
|
+
origin
|
|
181
|
+
);
|
|
182
|
+
};
|
|
183
|
+
owner.addEventListener("message", receive);
|
|
184
|
+
this.#detach = () => owner.removeEventListener("message", receive);
|
|
185
|
+
frame.setAttribute(
|
|
186
|
+
"sandbox",
|
|
187
|
+
"allow-scripts allow-same-origin allow-forms"
|
|
188
|
+
);
|
|
189
|
+
frame.setAttribute("referrerpolicy", "no-referrer");
|
|
190
|
+
frame.removeAttribute("inert");
|
|
191
|
+
frame.style.visibility = "visible";
|
|
192
|
+
this.#timer = setTimeout(
|
|
193
|
+
() => this.stopInput(),
|
|
194
|
+
Math.min(Date.parse(this.expiresAt) - Date.now(), 2147483647)
|
|
195
|
+
);
|
|
196
|
+
frame.src = this.#url;
|
|
197
|
+
this.#url = "";
|
|
198
|
+
}
|
|
199
|
+
/** Call before release, on lost/unknown status, expiry or scope change. Keeps the iframe alive for real clear ACK. */
|
|
200
|
+
stopInput() {
|
|
201
|
+
this.#used = true;
|
|
202
|
+
this.#token = void 0;
|
|
203
|
+
this.#detach?.();
|
|
204
|
+
this.#detach = void 0;
|
|
205
|
+
clearTimeout(this.#timer);
|
|
206
|
+
this.#timer = void 0;
|
|
207
|
+
if (this.#frame) {
|
|
208
|
+
this.#frame.setAttribute("inert", "");
|
|
209
|
+
this.#frame.style.visibility = "hidden";
|
|
210
|
+
this.#frame.blur();
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
/** Local teardown only: never means handback, clear ACK or server debt settlement. */
|
|
214
|
+
dispose() {
|
|
215
|
+
this.stopInput();
|
|
216
|
+
this.#used = true;
|
|
217
|
+
this.#url = "";
|
|
218
|
+
if (this.#frame) this.#frame.src = "about:blank";
|
|
219
|
+
this.#frame = void 0;
|
|
220
|
+
}
|
|
221
|
+
toJSON() {
|
|
222
|
+
return "[REDACTED BrowserViewer]";
|
|
223
|
+
}
|
|
224
|
+
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
225
|
+
return this.toJSON();
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
// ../../packages/browser-sdk/src/client.ts
|
|
230
|
+
var BrowserControlClient = class {
|
|
231
|
+
#origin;
|
|
232
|
+
#fetch;
|
|
233
|
+
constructor(options) {
|
|
234
|
+
try {
|
|
235
|
+
const url = new URL(options.baseURL);
|
|
236
|
+
if (!safeURL(url) || url.origin !== options.baseURL) invalidInput();
|
|
237
|
+
this.#origin = url.origin;
|
|
238
|
+
} catch {
|
|
239
|
+
invalidInput();
|
|
240
|
+
}
|
|
241
|
+
this.#fetch = options.fetch ?? globalThis.fetch;
|
|
242
|
+
if (typeof this.#fetch !== "function") invalidInput();
|
|
243
|
+
}
|
|
244
|
+
async get(context, options = {}) {
|
|
245
|
+
return this.#request("get", context, void 0, options);
|
|
246
|
+
}
|
|
247
|
+
async acquire(context, intent, options = {}) {
|
|
248
|
+
return this.#request(
|
|
249
|
+
"acquire",
|
|
250
|
+
context,
|
|
251
|
+
intent,
|
|
252
|
+
options
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
async release(context, intent, options = {}) {
|
|
256
|
+
return this.#request("release", context, intent, options);
|
|
257
|
+
}
|
|
258
|
+
async #request(action, context, intent, options) {
|
|
259
|
+
const mutation = action !== "get";
|
|
260
|
+
const path = contextPath(context, mutation);
|
|
261
|
+
const frozenIntent = mutation ? validateIntent(intent, action === "release") : void 0;
|
|
262
|
+
const timeoutMs = options.timeoutMs ?? (mutation ? 2e5 : 15e3);
|
|
263
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 3e5)
|
|
264
|
+
invalidInput();
|
|
265
|
+
if (options.signal?.aborted)
|
|
266
|
+
throw new BrowserControlError("aborted", false);
|
|
267
|
+
const sessionId = context.sessionId;
|
|
268
|
+
const headers = new Headers({
|
|
269
|
+
accept: "application/json",
|
|
270
|
+
authorization: `Bearer ${context.userJWT}`,
|
|
271
|
+
"x-ariadra-api-version": CONTRACT_VERSION,
|
|
272
|
+
"x-ariadra-current-tenant-id": context.tenantId,
|
|
273
|
+
"x-ariadra-namespace-id": context.namespaceId,
|
|
274
|
+
"x-ariadra-dashboard-api-key-id": context.apiKeyId
|
|
275
|
+
});
|
|
276
|
+
if (mutation) {
|
|
277
|
+
headers.set("content-type", "application/json");
|
|
278
|
+
headers.set(
|
|
279
|
+
"x-csrf-token",
|
|
280
|
+
context.csrfToken
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
const body = frozenIntent ? JSON.stringify(frozenIntent) : void 0;
|
|
284
|
+
const expectedControl = frozenIntent?.expected_control_id;
|
|
285
|
+
const expectedRevision = frozenIntent?.expected_revision;
|
|
286
|
+
const controller = new AbortController();
|
|
287
|
+
let submitted = false;
|
|
288
|
+
let rejectDeadline = () => {
|
|
289
|
+
};
|
|
290
|
+
const deadline = new Promise((_, reject) => {
|
|
291
|
+
rejectDeadline = reject;
|
|
292
|
+
});
|
|
293
|
+
const stop = (code) => {
|
|
294
|
+
rejectDeadline(new BrowserControlError(code, submitted));
|
|
295
|
+
controller.abort();
|
|
296
|
+
};
|
|
297
|
+
const aborted = () => stop("aborted");
|
|
298
|
+
const timer = setTimeout(() => stop("timeout"), timeoutMs);
|
|
299
|
+
options.signal?.addEventListener("abort", aborted, { once: true });
|
|
300
|
+
const perform = async () => {
|
|
301
|
+
submitted = true;
|
|
302
|
+
let response;
|
|
303
|
+
try {
|
|
304
|
+
const request = {
|
|
305
|
+
method: mutation ? "POST" : "GET",
|
|
306
|
+
headers,
|
|
307
|
+
...body === void 0 ? {} : { body },
|
|
308
|
+
cache: "no-store",
|
|
309
|
+
credentials: "include",
|
|
310
|
+
redirect: "error",
|
|
311
|
+
signal: controller.signal
|
|
312
|
+
};
|
|
313
|
+
response = await this.#fetch(
|
|
314
|
+
`${this.#origin}${path}${mutation ? `/${action}` : ""}`,
|
|
315
|
+
request
|
|
316
|
+
);
|
|
317
|
+
} catch {
|
|
318
|
+
throw new BrowserControlError("transport_unproven", true);
|
|
319
|
+
}
|
|
320
|
+
const allowed = response.status === 200 || action === "release" && response.status === 202;
|
|
321
|
+
let value;
|
|
322
|
+
try {
|
|
323
|
+
value = JSON.parse(await readBody(response, controller.signal));
|
|
324
|
+
} catch {
|
|
325
|
+
throw new BrowserControlError(
|
|
326
|
+
"response_unproven",
|
|
327
|
+
true,
|
|
328
|
+
response.status
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
if (!allowed) {
|
|
332
|
+
const reason = record(value) && record(value.error) && record(value.error.details) ? value.error.details.reason : void 0;
|
|
333
|
+
const known = errorReasons.find((item) => item === reason);
|
|
334
|
+
const refused = [400, 401, 403, 404, 409, 429].includes(
|
|
335
|
+
response.status
|
|
336
|
+
);
|
|
337
|
+
throw new BrowserControlError(
|
|
338
|
+
refused ? "refused" : "response_unproven",
|
|
339
|
+
!refused,
|
|
340
|
+
response.status,
|
|
341
|
+
known
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
const replay = response.headers.get("x-ariadra-idempotent-replay");
|
|
345
|
+
if (replay !== null && replay !== "true" && replay !== "false")
|
|
346
|
+
throw new BrowserControlError("response_unproven", true);
|
|
347
|
+
const reply = parseReply(
|
|
348
|
+
value,
|
|
349
|
+
sessionId,
|
|
350
|
+
action === "acquire" && replay !== "true"
|
|
351
|
+
);
|
|
352
|
+
if (mutation && (reply.data.control_id !== expectedControl || reply.data.revision < expectedRevision)) {
|
|
353
|
+
throw new BrowserControlError("response_unproven", true);
|
|
354
|
+
}
|
|
355
|
+
const result = {
|
|
356
|
+
status: response.status,
|
|
357
|
+
data: reply.data,
|
|
358
|
+
replayed: replay === "true"
|
|
359
|
+
};
|
|
360
|
+
return reply.access ? {
|
|
361
|
+
...result,
|
|
362
|
+
status: 200,
|
|
363
|
+
viewer: new BrowserViewerHandle(reply.access)
|
|
364
|
+
} : result;
|
|
365
|
+
};
|
|
366
|
+
try {
|
|
367
|
+
return await Promise.race([deadline, perform()]);
|
|
368
|
+
} finally {
|
|
369
|
+
clearTimeout(timer);
|
|
370
|
+
options.signal?.removeEventListener("abort", aborted);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
async function readBody(response, signal) {
|
|
375
|
+
if (!response.body) throw new BrowserControlError("response_unproven", true);
|
|
376
|
+
const reader = response.body.getReader();
|
|
377
|
+
const cancel = () => {
|
|
378
|
+
void reader.cancel().catch(() => {
|
|
379
|
+
});
|
|
380
|
+
};
|
|
381
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
382
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
383
|
+
let text = "", bytes = 0;
|
|
384
|
+
try {
|
|
385
|
+
if (signal.aborted) throw new BrowserControlError("aborted", true);
|
|
386
|
+
while (true) {
|
|
387
|
+
const next = await reader.read();
|
|
388
|
+
if (next.done) return text + decoder.decode();
|
|
389
|
+
bytes += next.value.byteLength;
|
|
390
|
+
if (bytes > 65536)
|
|
391
|
+
throw new BrowserControlError("response_unproven", true);
|
|
392
|
+
text += decoder.decode(next.value, { stream: true });
|
|
393
|
+
}
|
|
394
|
+
} finally {
|
|
395
|
+
signal.removeEventListener("abort", cancel);
|
|
396
|
+
cancel();
|
|
397
|
+
reader.releaseLock();
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// src/version.ts
|
|
402
|
+
var BROWSER_SDK_VERSION = "0.1.0-rc.1";
|
|
403
|
+
|
|
404
|
+
export { BROWSER_SDK_VERSION, BrowserControlClient, BrowserControlError, CONTRACT_VERSION };
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentmatrix.pro/browser-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-rc.1",
|
|
4
|
+
"description": "Human-authorized browser control client for AgentMatrix.",
|
|
5
|
+
"homepage": "https://agentmatrix.pro",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"sideEffects": false,
|
|
9
|
+
"engines": {
|
|
10
|
+
"node": ">=18"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"CHANGELOG.md",
|
|
14
|
+
"dist"
|
|
15
|
+
],
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"import": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "tsup --config tsup.config.ts",
|
|
27
|
+
"check": "npm run check:branding && npm run check:exports && npm run check:metadata && npm run check:boundaries && npm run typecheck && npm run build",
|
|
28
|
+
"check:boundaries": "tsx ../../scripts/check-module-boundaries.ts",
|
|
29
|
+
"check:branding": "tsx ../../scripts/check-branding.ts",
|
|
30
|
+
"check:exports": "tsx ../../scripts/gen-publication-exports.ts --check",
|
|
31
|
+
"check:metadata": "tsx ../../scripts/check-package-metadata.ts --package agentmatrix-browser-sdk",
|
|
32
|
+
"clean": "rm -rf dist",
|
|
33
|
+
"gen:exports": "tsx ../../scripts/gen-publication-exports.ts",
|
|
34
|
+
"lint": "biome check .",
|
|
35
|
+
"pack:dry": "npm pack --dry-run",
|
|
36
|
+
"prepack": "npm run check",
|
|
37
|
+
"typecheck": "tsc --project tsconfig.json --noEmit"
|
|
38
|
+
},
|
|
39
|
+
"keywords": [
|
|
40
|
+
"ariadra",
|
|
41
|
+
"sdk",
|
|
42
|
+
"openapi"
|
|
43
|
+
],
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public",
|
|
46
|
+
"registry": "https://registry.npmjs.org/"
|
|
47
|
+
},
|
|
48
|
+
"repository": {
|
|
49
|
+
"type": "git",
|
|
50
|
+
"url": "git+https://github.com/vibengine-ai/ariadra-sdk-typescript.git",
|
|
51
|
+
"directory": "publications/agentmatrix-browser-sdk"
|
|
52
|
+
}
|
|
53
|
+
}
|