@velmlabs/unstuck-protocol 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
- # Temporary Holding Version
1
+ # @velmlabs/unstuck-protocol
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The wire protocol shared by the [Unstuck](https://unstuck.sh) engine, viewer and relays: screen frames, JSON-RPC messages and the end-to-end encryption format.
4
+
5
+ You usually don't install this directly: [`@velmlabs/unstuck`](https://www.npmjs.com/package/@velmlabs/unstuck) and `@velmlabs/unstuck-core` depend on it.
6
+
7
+ Docs: https://unstuck.sh/docs · License: Apache-2.0
@@ -0,0 +1,285 @@
1
+ import * as _sinclair_typebox from '@sinclair/typebox';
2
+ import { Static } from '@sinclair/typebox';
3
+
4
+ /** Binary viewer frame: [type u8][width u16 BE][height u16 BE][JPEG bytes]. Width/height are page CSS pixels. */
5
+ declare const FRAME_TYPE_JPEG = 1;
6
+ interface Frame {
7
+ width: number;
8
+ height: number;
9
+ jpeg: Uint8Array;
10
+ }
11
+ declare function encodeFrame(f: Frame): Uint8Array;
12
+ declare function decodeFrame(b: Uint8Array): Frame | null;
13
+
14
+ declare class RpcCallError extends Error {
15
+ readonly code: string;
16
+ constructor(code: string, message: string);
17
+ }
18
+ interface RpcPeer {
19
+ request<T = unknown>(method: string, params?: unknown): Promise<T>;
20
+ notify(method: string, params?: unknown): void;
21
+ handle(method: string, fn: (params: unknown) => unknown): void;
22
+ onNotification(method: string, fn: (params: unknown) => void): void;
23
+ receive(line: string): void;
24
+ close(reason: string): void;
25
+ }
26
+ /** Bidirectional JSON-lines RPC. Transport-agnostic: caller supplies `write` and feeds `receive`. */
27
+ declare function createRpcPeer(write: (line: string) => void): RpcPeer;
28
+
29
+ interface RpcRequest {
30
+ id: number;
31
+ method: string;
32
+ params?: unknown;
33
+ }
34
+ interface RpcError {
35
+ code: string;
36
+ message: string;
37
+ }
38
+ interface RpcResponse {
39
+ id: number;
40
+ result?: unknown;
41
+ error?: RpcError;
42
+ }
43
+ interface RpcNotification {
44
+ method: string;
45
+ params?: unknown;
46
+ }
47
+ declare const PROTOCOL_VERSION = 1;
48
+ /** Method names on the SDK <-> engine JSON-lines channel. */
49
+ declare const Methods: {
50
+ readonly hello: "engine.hello";
51
+ readonly takeover: "takeover";
52
+ readonly shutdown: "shutdown";
53
+ readonly cdpSend: "cdp.send";
54
+ readonly cdpSubscribe: "cdp.subscribe";
55
+ readonly cdpEvent: "cdp.event";
56
+ readonly cdpClosed: "cdp.closed";
57
+ /** The SDK attached a popup the page opened; the engine may now use popupPageId. */
58
+ readonly pagePopup: "page.popup";
59
+ readonly takeoverLink: "takeover.link";
60
+ };
61
+ interface HelloParams {
62
+ sdk: 'ts' | 'py';
63
+ sdkVersion: string;
64
+ protocolVersion: number;
65
+ }
66
+ interface HelloResult {
67
+ engineVersion: string;
68
+ protocolVersion: number;
69
+ }
70
+ interface TakeoverParams {
71
+ pageId: string;
72
+ reason: string;
73
+ timeoutS?: number;
74
+ site?: string;
75
+ /** Ask the human for a 6-digit code delivered with the link (relay spec §5.8). */
76
+ requireCode?: boolean;
77
+ }
78
+ interface CdpSendParams {
79
+ pageId: string;
80
+ method: string;
81
+ params?: object;
82
+ }
83
+ interface CdpSubscribeParams {
84
+ pageId: string;
85
+ events: string[];
86
+ }
87
+ interface CdpEventParams {
88
+ pageId: string;
89
+ method: string;
90
+ params: unknown;
91
+ }
92
+ interface CdpClosedParams {
93
+ pageId: string;
94
+ reason: string;
95
+ }
96
+ interface PagePopupParams {
97
+ pageId: string;
98
+ popupPageId: string;
99
+ }
100
+ interface TakeoverLinkParams {
101
+ sessionId: string;
102
+ pageId: string;
103
+ url: string;
104
+ reason: string;
105
+ expiresAt: number;
106
+ /** The 6-digit code, when the takeover requires one. Never part of the URL. */
107
+ code?: string;
108
+ }
109
+
110
+ type TakeoverStatus = 'resolved' | 'timed_out' | 'cancelled' | 'failed';
111
+ interface TakeoverResult {
112
+ status: TakeoverStatus;
113
+ sessionId: string;
114
+ url: string;
115
+ durationS: number;
116
+ detail?: string;
117
+ }
118
+
119
+ declare const SessionStatusSchema: _sinclair_typebox.TUnion<_sinclair_typebox.TLiteral<string>[]>;
120
+ type SessionStatus = 'created' | 'notifying' | 'waiting' | 'active' | 'resolved' | 'timed_out' | 'cancelled' | 'failed';
121
+ declare const ViewerToEngineSchema: _sinclair_typebox.TUnion<[_sinclair_typebox.TObject<{
122
+ t: _sinclair_typebox.TLiteral<"hello">;
123
+ token: _sinclair_typebox.TString;
124
+ resumeKey: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
125
+ code: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
126
+ }>, _sinclair_typebox.TObject<{
127
+ t: _sinclair_typebox.TLiteral<"mouse">;
128
+ action: _sinclair_typebox.TUnion<[_sinclair_typebox.TLiteral<"down">, _sinclair_typebox.TLiteral<"up">, _sinclair_typebox.TLiteral<"move">]>;
129
+ x: _sinclair_typebox.TNumber;
130
+ y: _sinclair_typebox.TNumber;
131
+ button: _sinclair_typebox.TUnion<[_sinclair_typebox.TLiteral<"left">, _sinclair_typebox.TLiteral<"right">, _sinclair_typebox.TLiteral<"middle">, _sinclair_typebox.TLiteral<"none">]>;
132
+ clickCount: _sinclair_typebox.TNumber;
133
+ modifiers: _sinclair_typebox.TNumber;
134
+ }>, _sinclair_typebox.TObject<{
135
+ t: _sinclair_typebox.TLiteral<"wheel">;
136
+ x: _sinclair_typebox.TNumber;
137
+ y: _sinclair_typebox.TNumber;
138
+ dx: _sinclair_typebox.TNumber;
139
+ dy: _sinclair_typebox.TNumber;
140
+ }>, _sinclair_typebox.TObject<{
141
+ t: _sinclair_typebox.TLiteral<"key">;
142
+ action: _sinclair_typebox.TUnion<[_sinclair_typebox.TLiteral<"down">, _sinclair_typebox.TLiteral<"up">]>;
143
+ key: _sinclair_typebox.TString;
144
+ code: _sinclair_typebox.TString;
145
+ text: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
146
+ modifiers: _sinclair_typebox.TNumber;
147
+ }>, _sinclair_typebox.TObject<{
148
+ t: _sinclair_typebox.TLiteral<"text">;
149
+ text: _sinclair_typebox.TString;
150
+ }>, _sinclair_typebox.TObject<{
151
+ t: _sinclair_typebox.TLiteral<"done">;
152
+ }>, _sinclair_typebox.TObject<{
153
+ t: _sinclair_typebox.TLiteral<"cant_solve">;
154
+ reason: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
155
+ }>, _sinclair_typebox.TObject<{
156
+ t: _sinclair_typebox.TLiteral<"ping">;
157
+ }>]>;
158
+ type ViewerToEngine = Static<typeof ViewerToEngineSchema>;
159
+ type ViewerInput = Extract<ViewerToEngine, {
160
+ t: 'mouse' | 'wheel' | 'key' | 'text';
161
+ }>;
162
+ declare const ViewerErrorCodes: readonly ["token_invalid", "token_used", "expired", "session_closed", "bad_message", "code_required", "code_invalid"];
163
+ type ViewerErrorCode = (typeof ViewerErrorCodes)[number];
164
+ declare const EngineToViewerSchema: _sinclair_typebox.TUnion<[_sinclair_typebox.TObject<{
165
+ t: _sinclair_typebox.TLiteral<"ready">;
166
+ reason: _sinclair_typebox.TString;
167
+ site: _sinclair_typebox.TString;
168
+ expiresAt: _sinclair_typebox.TNumber;
169
+ resumeKey: _sinclair_typebox.TString;
170
+ }>, _sinclair_typebox.TObject<{
171
+ t: _sinclair_typebox.TLiteral<"state">;
172
+ status: _sinclair_typebox.TUnion<_sinclair_typebox.TLiteral<string>[]>;
173
+ }>, _sinclair_typebox.TObject<{
174
+ t: _sinclair_typebox.TLiteral<"error">;
175
+ code: _sinclair_typebox.TUnion<_sinclair_typebox.TLiteral<"token_invalid" | "token_used" | "expired" | "session_closed" | "bad_message" | "code_required" | "code_invalid">[]>;
176
+ message: _sinclair_typebox.TString;
177
+ }>, _sinclair_typebox.TObject<{
178
+ t: _sinclair_typebox.TLiteral<"pong">;
179
+ }>]>;
180
+ type EngineToViewer = {
181
+ t: 'ready';
182
+ reason: string;
183
+ site: string;
184
+ expiresAt: number;
185
+ resumeKey: string;
186
+ } | {
187
+ t: 'state';
188
+ status: SessionStatus;
189
+ } | {
190
+ t: 'error';
191
+ code: ViewerErrorCode;
192
+ message: string;
193
+ } | {
194
+ t: 'pong';
195
+ };
196
+ declare function parseViewerMessage(raw: string): ViewerToEngine | null;
197
+
198
+ declare const RELAY_SUBPROTOCOL = "unstuck-relay.1";
199
+ declare const KEY_SUBPROTOCOL_PREFIX = "key.";
200
+ declare const SESSION_ID_RE: RegExp;
201
+ declare const RELAY_LIMITS: {
202
+ readonly agentPayloadMax: 2097152;
203
+ readonly viewerPayloadMax: 65536;
204
+ readonly viewersPerSession: 4;
205
+ readonly idleMs: 120000;
206
+ readonly heartbeatMs: 30000;
207
+ readonly graceMs: 60000;
208
+ readonly maxExpiryMs: 3600000;
209
+ readonly billableBytes: 4096;
210
+ readonly backpressureBytes: 4194304;
211
+ readonly viewerUpgradesPerMinPerIp: 30;
212
+ readonly agentUpgradesPerMinPerKey: 20;
213
+ };
214
+ declare const RELAY_CLOSE: {
215
+ readonly agentReconnecting: 1012;
216
+ readonly replaced: 4409;
217
+ readonly badMessage: 1003;
218
+ readonly tooBig: 1009;
219
+ /** A refused agent: 4000 + the HTTP status (4401, 4402, 4403, 4429). Clients can't read upgrade statuses. */
220
+ readonly refused: (status: number) => number;
221
+ };
222
+ /** `registered` confirms a hello (first registration or a reconnect); only then is the session live. */
223
+ type RelayToAgent = {
224
+ t: 'open';
225
+ c: number;
226
+ } | {
227
+ t: 'close';
228
+ c: number;
229
+ } | {
230
+ t: 'ping';
231
+ } | {
232
+ t: 'registered';
233
+ };
234
+ type AgentToRelay = {
235
+ t: 'hello';
236
+ expiresAt: number;
237
+ secret: string;
238
+ } | {
239
+ t: 'close';
240
+ c: number;
241
+ code: number;
242
+ } | {
243
+ t: 'pong';
244
+ } | {
245
+ t: 'end';
246
+ } | {
247
+ t: 'event';
248
+ name: string;
249
+ };
250
+ declare const parseRelayToAgent: (raw: string) => RelayToAgent | null;
251
+ declare const parseAgentToRelay: (raw: string) => AgentToRelay | null;
252
+ /** [c: u32 big-endian][payload]: one viewer connection's message on the agent socket. */
253
+ declare function encodeEnvelope(c: number, payload: Uint8Array): Uint8Array;
254
+ declare function decodeEnvelope(b: Uint8Array): {
255
+ c: number;
256
+ payload: Uint8Array;
257
+ } | null;
258
+
259
+ type Direction = 'e2v' | 'v2e';
260
+ /** 32 random bytes: one AES-256-GCM key per takeover session. */
261
+ declare function newE2eKey(): Uint8Array;
262
+ declare function importE2eKey(raw: Uint8Array): Promise<CryptoKey>;
263
+ /** [12-byte random IV][ciphertext + 16-byte tag]; bound to the session and direction. */
264
+ declare function seal(key: CryptoKey, sessionId: string, dir: Direction, plain: Uint8Array): Promise<Uint8Array>;
265
+ /** The plaintext, or null when the message wasn't sealed with this key, session and direction. */
266
+ declare function open(key: CryptoKey, sessionId: string, dir: Direction, sealed: Uint8Array): Promise<Uint8Array | null>;
267
+ declare function b64urlEncode(b: Uint8Array): string;
268
+ declare function b64urlDecode(s: string): Uint8Array | null;
269
+ /** Plaintext JSON messages start with '{'; screen frames start with their type byte (0x01). */
270
+ declare const isJsonPlaintext: (p: Uint8Array) => boolean;
271
+ /**
272
+ * Replay protection (relay spec §5.4): every message on a viewer connection is bound to that connection's random
273
+ * nonce (sent by the engine in a sealed challenge) and carries a sequence number the receiver requires to increase.
274
+ * Format: [seq: u32 big-endian][12-byte IV][ciphertext + tag]; the AAD includes the nonce and the sequence number.
275
+ */
276
+ declare const newConnNonce: () => string;
277
+ declare function sealMsg(key: CryptoKey, sessionId: string, dir: Direction, conn: string, seq: number, plain: Uint8Array): Promise<Uint8Array>;
278
+ /** The sequence number and plaintext, or null when the message isn't from this connection or was tampered with. */
279
+ declare function openMsg(key: CryptoKey, sessionId: string, dir: Direction, conn: string, sealed: Uint8Array): Promise<{
280
+ seq: number;
281
+ plain: Uint8Array;
282
+ } | null>;
283
+
284
+ export { EngineToViewerSchema, FRAME_TYPE_JPEG, KEY_SUBPROTOCOL_PREFIX, Methods, PROTOCOL_VERSION, RELAY_CLOSE, RELAY_LIMITS, RELAY_SUBPROTOCOL, RpcCallError, SESSION_ID_RE, SessionStatusSchema, ViewerErrorCodes, ViewerToEngineSchema, b64urlDecode, b64urlEncode, createRpcPeer, decodeEnvelope, decodeFrame, encodeEnvelope, encodeFrame, importE2eKey, isJsonPlaintext, newConnNonce, newE2eKey, open, openMsg, parseAgentToRelay, parseRelayToAgent, parseViewerMessage, seal, sealMsg };
285
+ export type { AgentToRelay, CdpClosedParams, CdpEventParams, CdpSendParams, CdpSubscribeParams, Direction, EngineToViewer, Frame, HelloParams, HelloResult, PagePopupParams, RelayToAgent, RpcError, RpcNotification, RpcPeer, RpcRequest, RpcResponse, SessionStatus, TakeoverLinkParams, TakeoverParams, TakeoverResult, TakeoverStatus, ViewerErrorCode, ViewerInput, ViewerToEngine };
package/dist/index.js ADDED
@@ -0,0 +1,347 @@
1
+ // src/frame.ts
2
+ var FRAME_TYPE_JPEG = 1;
3
+ var HEADER = 5;
4
+ function checkU16(name, v) {
5
+ if (!Number.isInteger(v) || v < 0 || v > 65535) throw new RangeError(`${name} must be an integer 0..65535, got ${v}`);
6
+ }
7
+ function encodeFrame(f) {
8
+ checkU16("width", f.width);
9
+ checkU16("height", f.height);
10
+ const out = new Uint8Array(HEADER + f.jpeg.length);
11
+ const view = new DataView(out.buffer);
12
+ view.setUint8(0, FRAME_TYPE_JPEG);
13
+ view.setUint16(1, f.width);
14
+ view.setUint16(3, f.height);
15
+ out.set(f.jpeg, HEADER);
16
+ return out;
17
+ }
18
+ function decodeFrame(b) {
19
+ if (b.length < HEADER || b[0] !== FRAME_TYPE_JPEG) return null;
20
+ const view = new DataView(b.buffer, b.byteOffset, b.byteLength);
21
+ return { width: view.getUint16(1), height: view.getUint16(3), jpeg: b.slice(HEADER) };
22
+ }
23
+
24
+ // src/rpc.ts
25
+ var RpcCallError = class extends Error {
26
+ constructor(code, message) {
27
+ super(message);
28
+ this.code = code;
29
+ this.name = "RpcCallError";
30
+ }
31
+ code;
32
+ };
33
+ function createRpcPeer(write) {
34
+ let nextId = 1;
35
+ let closedReason = null;
36
+ const pending = /* @__PURE__ */ new Map();
37
+ const handlers = /* @__PURE__ */ new Map();
38
+ const listeners = /* @__PURE__ */ new Map();
39
+ const send = (msg) => write(JSON.stringify(msg));
40
+ async function onRequest(msg) {
41
+ const fn = handlers.get(msg.method);
42
+ if (!fn) {
43
+ send({ id: msg.id, error: { code: "unknown_method", message: `unknown method ${msg.method}` } });
44
+ return;
45
+ }
46
+ try {
47
+ send({ id: msg.id, result: await fn(msg.params) ?? null });
48
+ } catch (e) {
49
+ const err = e;
50
+ send({ id: msg.id, error: { code: typeof err.code === "string" ? err.code : "handler_error", message: String(err.message ?? e) } });
51
+ }
52
+ }
53
+ return {
54
+ request(method, params) {
55
+ if (closedReason !== null) return Promise.reject(new RpcCallError("closed", closedReason));
56
+ const id = nextId++;
57
+ return new Promise((resolve, reject) => {
58
+ pending.set(id, { resolve, reject });
59
+ send({ id, method, params });
60
+ });
61
+ },
62
+ notify(method, params) {
63
+ send({ method, params });
64
+ },
65
+ handle(method, fn) {
66
+ handlers.set(method, fn);
67
+ },
68
+ onNotification(method, fn) {
69
+ listeners.set(method, [...listeners.get(method) ?? [], fn]);
70
+ },
71
+ receive(line) {
72
+ let msg;
73
+ try {
74
+ msg = JSON.parse(line);
75
+ } catch {
76
+ return;
77
+ }
78
+ if (typeof msg !== "object" || msg === null) return;
79
+ const m = msg;
80
+ if (typeof m.id === "number" && typeof m.method === "string") {
81
+ void onRequest(m);
82
+ } else if (typeof m.id === "number") {
83
+ const p = pending.get(m.id);
84
+ if (!p) return;
85
+ pending.delete(m.id);
86
+ if (m.error) p.reject(new RpcCallError(m.error.code, m.error.message));
87
+ else p.resolve(m.result);
88
+ } else if (typeof m.method === "string") {
89
+ for (const fn of listeners.get(m.method) ?? []) fn(m.params);
90
+ }
91
+ },
92
+ close(reason) {
93
+ closedReason = reason;
94
+ for (const p of pending.values()) p.reject(new RpcCallError("closed", reason));
95
+ pending.clear();
96
+ }
97
+ };
98
+ }
99
+
100
+ // src/rpc-types.ts
101
+ var PROTOCOL_VERSION = 1;
102
+ var Methods = {
103
+ // SDK -> engine requests
104
+ hello: "engine.hello",
105
+ takeover: "takeover",
106
+ shutdown: "shutdown",
107
+ // engine -> SDK requests
108
+ cdpSend: "cdp.send",
109
+ cdpSubscribe: "cdp.subscribe",
110
+ // SDK -> engine notifications
111
+ cdpEvent: "cdp.event",
112
+ cdpClosed: "cdp.closed",
113
+ /** The SDK attached a popup the page opened; the engine may now use popupPageId. */
114
+ pagePopup: "page.popup",
115
+ // engine -> SDK notifications
116
+ takeoverLink: "takeover.link"
117
+ };
118
+
119
+ // src/viewer.ts
120
+ import { Type } from "@sinclair/typebox";
121
+ import { Value } from "@sinclair/typebox/value";
122
+ var SessionStatusSchema = Type.Union(
123
+ ["created", "notifying", "waiting", "active", "resolved", "timed_out", "cancelled", "failed"].map((s) => Type.Literal(s))
124
+ );
125
+ var Num = Type.Number();
126
+ var Lit = (v) => Type.Literal(v);
127
+ var ViewerToEngineSchema = Type.Union([
128
+ Type.Object(
129
+ { t: Lit("hello"), token: Type.String(), resumeKey: Type.Optional(Type.String()), code: Type.Optional(Type.String({ pattern: "^[0-9]{6}$" })) },
130
+ { additionalProperties: false }
131
+ ),
132
+ Type.Object(
133
+ {
134
+ t: Lit("mouse"),
135
+ action: Type.Union([Lit("down"), Lit("up"), Lit("move")]),
136
+ x: Num,
137
+ y: Num,
138
+ button: Type.Union([Lit("left"), Lit("right"), Lit("middle"), Lit("none")]),
139
+ clickCount: Num,
140
+ modifiers: Num
141
+ },
142
+ { additionalProperties: false }
143
+ ),
144
+ Type.Object({ t: Lit("wheel"), x: Num, y: Num, dx: Num, dy: Num }, { additionalProperties: false }),
145
+ Type.Object(
146
+ {
147
+ t: Lit("key"),
148
+ action: Type.Union([Lit("down"), Lit("up")]),
149
+ key: Type.String(),
150
+ code: Type.String(),
151
+ text: Type.Optional(Type.String()),
152
+ modifiers: Num
153
+ },
154
+ { additionalProperties: false }
155
+ ),
156
+ Type.Object({ t: Lit("text"), text: Type.String() }, { additionalProperties: false }),
157
+ Type.Object({ t: Lit("done") }, { additionalProperties: false }),
158
+ Type.Object({ t: Lit("cant_solve"), reason: Type.Optional(Type.String()) }, { additionalProperties: false }),
159
+ Type.Object({ t: Lit("ping") }, { additionalProperties: false })
160
+ ]);
161
+ var ViewerErrorCodes = ["token_invalid", "token_used", "expired", "session_closed", "bad_message", "code_required", "code_invalid"];
162
+ var EngineToViewerSchema = Type.Union([
163
+ Type.Object({ t: Lit("ready"), reason: Type.String(), site: Type.String(), expiresAt: Num, resumeKey: Type.String() }),
164
+ Type.Object({ t: Lit("state"), status: SessionStatusSchema }),
165
+ Type.Object({ t: Lit("error"), code: Type.Union(ViewerErrorCodes.map((c) => Lit(c))), message: Type.String() }),
166
+ Type.Object({ t: Lit("pong") })
167
+ ]);
168
+ function parseViewerMessage(raw) {
169
+ let v;
170
+ try {
171
+ v = JSON.parse(raw);
172
+ } catch {
173
+ return null;
174
+ }
175
+ return Value.Check(ViewerToEngineSchema, v) ? v : null;
176
+ }
177
+
178
+ // src/relay.ts
179
+ import { Type as Type2 } from "@sinclair/typebox";
180
+ import { Value as Value2 } from "@sinclair/typebox/value";
181
+ var RELAY_SUBPROTOCOL = "unstuck-relay.1";
182
+ var KEY_SUBPROTOCOL_PREFIX = "key.";
183
+ var SESSION_ID_RE = /^[A-Za-z0-9_-]{16,64}$/;
184
+ var RELAY_LIMITS = {
185
+ agentPayloadMax: 2097152,
186
+ viewerPayloadMax: 65536,
187
+ viewersPerSession: 4,
188
+ idleMs: 12e4,
189
+ heartbeatMs: 3e4,
190
+ graceMs: 6e4,
191
+ maxExpiryMs: 36e5,
192
+ billableBytes: 4096,
193
+ backpressureBytes: 4194304,
194
+ viewerUpgradesPerMinPerIp: 30,
195
+ agentUpgradesPerMinPerKey: 20
196
+ };
197
+ var RELAY_CLOSE = {
198
+ agentReconnecting: 1012,
199
+ replaced: 4409,
200
+ badMessage: 1003,
201
+ tooBig: 1009,
202
+ /** A refused agent: 4000 + the HTTP status (4401, 4402, 4403, 4429). Clients can't read upgrade statuses. */
203
+ refused: (status) => 4e3 + status
204
+ };
205
+ var C = Type2.Integer({ minimum: 1, maximum: 4294967295 });
206
+ var strict = { additionalProperties: false };
207
+ var RelayToAgentSchema = Type2.Union([
208
+ Type2.Object({ t: Type2.Literal("open"), c: C }, strict),
209
+ Type2.Object({ t: Type2.Literal("close"), c: C }, strict),
210
+ Type2.Object({ t: Type2.Literal("ping") }, strict),
211
+ Type2.Object({ t: Type2.Literal("registered") }, strict)
212
+ ]);
213
+ var AgentToRelaySchema = Type2.Union([
214
+ Type2.Object({ t: Type2.Literal("hello"), expiresAt: Type2.Number(), secret: Type2.String({ minLength: 1, maxLength: 128 }) }, strict),
215
+ Type2.Object({ t: Type2.Literal("close"), c: C, code: Type2.Integer() }, strict),
216
+ Type2.Object({ t: Type2.Literal("pong") }, strict),
217
+ Type2.Object({ t: Type2.Literal("end") }, strict),
218
+ Type2.Object({ t: Type2.Literal("event"), name: Type2.String({ maxLength: 64 }) }, strict)
219
+ ]);
220
+ function parse(schema, raw) {
221
+ let v;
222
+ try {
223
+ v = JSON.parse(raw);
224
+ } catch {
225
+ return null;
226
+ }
227
+ return Value2.Check(schema, v) ? v : null;
228
+ }
229
+ var parseRelayToAgent = (raw) => parse(RelayToAgentSchema, raw);
230
+ var parseAgentToRelay = (raw) => parse(AgentToRelaySchema, raw);
231
+ function encodeEnvelope(c, payload) {
232
+ if (!Number.isInteger(c) || c < 0 || c > 4294967295) throw new RangeError(`connection number out of range: ${c}`);
233
+ const out = new Uint8Array(4 + payload.length);
234
+ new DataView(out.buffer).setUint32(0, c);
235
+ out.set(payload, 4);
236
+ return out;
237
+ }
238
+ function decodeEnvelope(b) {
239
+ if (b.length < 4) return null;
240
+ return { c: new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(0), payload: b.slice(4) };
241
+ }
242
+
243
+ // src/e2e.ts
244
+ var IV_BYTES = 12;
245
+ var TAG_BYTES = 16;
246
+ var enc = new TextEncoder();
247
+ function newE2eKey() {
248
+ return crypto.getRandomValues(new Uint8Array(32));
249
+ }
250
+ function importE2eKey(raw) {
251
+ return crypto.subtle.importKey("raw", new Uint8Array(raw), { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
252
+ }
253
+ var aad = (sessionId, dir) => enc.encode(`unstuck/1|${sessionId}|${dir}`);
254
+ async function seal(key, sessionId, dir, plain) {
255
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
256
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: aad(sessionId, dir) }, key, new Uint8Array(plain)));
257
+ const out = new Uint8Array(IV_BYTES + ct.length);
258
+ out.set(iv);
259
+ out.set(ct, IV_BYTES);
260
+ return out;
261
+ }
262
+ async function open(key, sessionId, dir, sealed) {
263
+ if (sealed.length < IV_BYTES + TAG_BYTES) return null;
264
+ try {
265
+ const pt = await crypto.subtle.decrypt(
266
+ { name: "AES-GCM", iv: sealed.slice(0, IV_BYTES), additionalData: aad(sessionId, dir) },
267
+ key,
268
+ sealed.slice(IV_BYTES)
269
+ );
270
+ return new Uint8Array(pt);
271
+ } catch {
272
+ return null;
273
+ }
274
+ }
275
+ function b64urlEncode(b) {
276
+ let s = "";
277
+ for (const x of b) s += String.fromCharCode(x);
278
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
279
+ }
280
+ function b64urlDecode(s) {
281
+ if (!/^[A-Za-z0-9_-]*$/.test(s)) return null;
282
+ try {
283
+ const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - s.length % 4) % 4));
284
+ return Uint8Array.from(bin, (c) => c.charCodeAt(0));
285
+ } catch {
286
+ return null;
287
+ }
288
+ }
289
+ var isJsonPlaintext = (p) => p[0] === 123;
290
+ var newConnNonce = () => b64urlEncode(crypto.getRandomValues(new Uint8Array(16)));
291
+ var msgAad = (sessionId, dir, conn, seq) => enc.encode(`unstuck/1|${sessionId}|${dir}|${conn}|${seq}`);
292
+ async function sealMsg(key, sessionId, dir, conn, seq, plain) {
293
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
294
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: msgAad(sessionId, dir, conn, seq) }, key, new Uint8Array(plain)));
295
+ const out = new Uint8Array(4 + IV_BYTES + ct.length);
296
+ new DataView(out.buffer).setUint32(0, seq);
297
+ out.set(iv, 4);
298
+ out.set(ct, 4 + IV_BYTES);
299
+ return out;
300
+ }
301
+ async function openMsg(key, sessionId, dir, conn, sealed) {
302
+ if (sealed.length < 4 + IV_BYTES + TAG_BYTES) return null;
303
+ const seq = new DataView(sealed.buffer, sealed.byteOffset, sealed.byteLength).getUint32(0);
304
+ try {
305
+ const pt = await crypto.subtle.decrypt(
306
+ { name: "AES-GCM", iv: sealed.slice(4, 4 + IV_BYTES), additionalData: msgAad(sessionId, dir, conn, seq) },
307
+ key,
308
+ sealed.slice(4 + IV_BYTES)
309
+ );
310
+ return { seq, plain: new Uint8Array(pt) };
311
+ } catch {
312
+ return null;
313
+ }
314
+ }
315
+ export {
316
+ EngineToViewerSchema,
317
+ FRAME_TYPE_JPEG,
318
+ KEY_SUBPROTOCOL_PREFIX,
319
+ Methods,
320
+ PROTOCOL_VERSION,
321
+ RELAY_CLOSE,
322
+ RELAY_LIMITS,
323
+ RELAY_SUBPROTOCOL,
324
+ RpcCallError,
325
+ SESSION_ID_RE,
326
+ SessionStatusSchema,
327
+ ViewerErrorCodes,
328
+ ViewerToEngineSchema,
329
+ b64urlDecode,
330
+ b64urlEncode,
331
+ createRpcPeer,
332
+ decodeEnvelope,
333
+ decodeFrame,
334
+ encodeEnvelope,
335
+ encodeFrame,
336
+ importE2eKey,
337
+ isJsonPlaintext,
338
+ newConnNonce,
339
+ newE2eKey,
340
+ open,
341
+ openMsg,
342
+ parseAgentToRelay,
343
+ parseRelayToAgent,
344
+ parseViewerMessage,
345
+ seal,
346
+ sealMsg
347
+ };
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@velmlabs/unstuck-protocol",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Wire protocol shared by the Unstuck engine, viewer and relays (frames, RPC, end-to-end encryption).",
5
+ "keywords": [
6
+ "ai",
7
+ "agent",
8
+ "browser",
9
+ "captcha",
10
+ "human-in-the-loop",
11
+ "playwright",
12
+ "puppeteer",
13
+ "cdp",
14
+ "mcp"
15
+ ],
16
+ "homepage": "https://unstuck.sh/docs",
17
+ "bugs": {
18
+ "url": "https://github.com/velmlabs/unstuck/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/velmlabs/unstuck.git",
23
+ "directory": "protocol"
24
+ },
25
+ "license": "Apache-2.0",
26
+ "author": "Velm Labs",
27
+ "type": "module",
28
+ "main": "./dist/index.js",
29
+ "types": "./dist/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js",
34
+ "default": "./dist/index.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist"
39
+ ],
40
+ "engines": {
41
+ "node": ">=20"
42
+ },
43
+ "dependencies": {
44
+ "@sinclair/typebox": "~0.34.52"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "scripts": {
50
+ "build": "tsc -p tsconfig.json --noEmit",
51
+ "test": "vitest run --coverage",
52
+ "export-schemas": "tsx scripts/export-schemas.ts",
53
+ "build:dist": "tsup"
54
+ }
6
55
  }