@tryagentkey/runtime 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/NOTICE +2 -0
- package/README.md +52 -2
- package/index.mjs +226 -0
- package/package.json +23 -4
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/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
-
#
|
|
1
|
+
# AgentKey runtime (no extension)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Use AgentKey from the browser your agent already runs. No extension, no hosted browser.
|
|
4
|
+
Base URL: `https://agentkey.waiwiser.com/api/public/agentkey-api`
|
|
5
|
+
|
|
6
|
+
## 0. Ask AgentKey first
|
|
7
|
+
```js
|
|
8
|
+
const g = await AgentKeyRuntime.guide({agentToken, goal: {origin: 'https://news.ycombinator.com', site_name: 'Hacker News'}})
|
|
9
|
+
// g.path, g.next_action, g.next_call, g.blockers — using your live state
|
|
10
|
+
```
|
|
11
|
+
`POST /v1/guide` with `{environment: {browser: 'automation'|'extension'|'none', can_run_code}, goal: {origin, site_name, signin_url?}}`. `GET /v1` describes every route. Every error carries a `help` object with the fix; `RuntimeError.help` exposes it.
|
|
12
|
+
|
|
13
|
+
## 1. Enroll once
|
|
14
|
+
```js
|
|
15
|
+
import {AgentKeyRuntime, exportRuntimeKey} from '@tryagentkey/runtime'
|
|
16
|
+
const {runtime, key, approvalURL} = await AgentKeyRuntime.enroll({agentToken, agentId, label: 'My agent browser',
|
|
17
|
+
onSession: s => secretStore.save('session', s)})
|
|
18
|
+
await secretStore.save('key', await exportRuntimeKey(key))
|
|
19
|
+
// Send approvalURL to the owner ("here is your link"). They compare the key and tap Trust.
|
|
20
|
+
await runtime.waitUntilEnabled()
|
|
21
|
+
```
|
|
22
|
+
API: `POST /v1/executor/pairings` (agent token, code hash only) -> `POST /v1/executor/redeem` (code + your public key, returns a session sealed to your key) -> `GET /v1/executor/self` until enabled. Code-based pairing from the owner page also works: skip `pairings` and redeem the owner's code.
|
|
23
|
+
|
|
24
|
+
## 2. Ask for a login (agent token, unchanged)
|
|
25
|
+
`POST /v1/requests` -> send link -> `POST /v1/grants/<id>/use` -> operation queued.
|
|
26
|
+
For an exact page: `runtime.registerTarget({origin})` then `POST /v2/target-requests` with the target id.
|
|
27
|
+
|
|
28
|
+
## 3. Fill in your existing page
|
|
29
|
+
```js
|
|
30
|
+
for (const op of await runtime.pending()) await runtime.fillOperation(op.operation_id, page, {verify: p => p.locator('text=Sign out').isVisible()})
|
|
31
|
+
```
|
|
32
|
+
Fails closed when the page origin differs or the form is ambiguous. Reports exactly one outcome. A submitted form without `verify` is `unknown`, never proof of login. Never retry an uncertain submission.
|
|
33
|
+
|
|
34
|
+
## Executor routes (executor session token)
|
|
35
|
+
`GET self`, `POST heartbeat`, `GET pending`, `GET operations/<id>` (no ciphertext), `POST operations/<id>/claim`, `POST target-operations/<id>/claim`, `POST operations/<id>/complete {completed|failed|unknown}`, `POST target-support`, `POST targets`, `POST session/refresh`. All under `/v1/executor/`.
|
|
36
|
+
|
|
37
|
+
Owner disabling the runtime stops new claims; poll `self()` and stop when it returns nothing.
|
|
38
|
+
|
|
39
|
+
## Agent-created login proposals (0.1.1)
|
|
40
|
+
|
|
41
|
+
An enrolled executor hosting an open Glove session can stage an encrypted login proposal for its owner. The session binds the owner, requesting agent, and executor. These methods do not create a website account by themselves, approve a grant, or import a login into an owner vault.
|
|
42
|
+
|
|
43
|
+
- `ownerRecipientKey(sessionId)` fetches the session owner's published recipient key.
|
|
44
|
+
- `proposeCreatedLogin({sessionId, agentId, origin, username, title, password})` seals the credential to that key and stages a proposal. `agentId` must match the agent bound to the session. `origin` must be an exact HTTPS origin. It returns a proposal identifier and state, not the password.
|
|
45
|
+
- `proposalStatus(proposalId, sessionId)` reads its state.
|
|
46
|
+
- `confirmLoginProposal(proposalId, sessionId)` records confirmed account creation. Call only after the website outcome is verified.
|
|
47
|
+
- `markLoginProposalUncertain(proposalId, sessionId)` preserves an uncertain outcome for owner recovery. Do not blindly repeat signup.
|
|
48
|
+
- `retractLoginProposal(proposalId, sessionId)` retracts a staged proposal when appropriate.
|
|
49
|
+
- `proposeLogin({sessionId, origin, recipientKeyId, ciphertext})` is the lower-level staging method for an already sealed envelope.
|
|
50
|
+
|
|
51
|
+
The exported `sealAgentLogin(login, scope, recipientPublicKeyB64)` helper uses an ephemeral X25519 key, HKDF-SHA256, and AES-256-GCM with the owner, agent, recipient-key identifier, and origin bound into authenticated data. The owner's recipient private key is needed to open the result. Server-side authorization and state checks still apply.
|
|
52
|
+
|
|
53
|
+
This runtime handles plaintext within the trusted executor process while sealing. Do not put a real password in a model prompt, tool result, log, or source file. A caller that passes a password string directly already has access to that string; this API alone does not hide it from that caller. Owner-vault import, backup, and device notification delivery are separate workflows and are not proved by staging or confirming a proposal.
|
package/index.mjs
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// AgentKey runtime for an agent's own existing browser, with no extension.
|
|
2
|
+
// Runs in the agent's runtime process beside its already-open browser
|
|
3
|
+
// (Playwright/Puppeteer page objects the agent already holds). It never
|
|
4
|
+
// launches a browser, opens a context or exports cookies. The private key and
|
|
5
|
+
// opened credentials stay in this process; nothing here logs or returns them.
|
|
6
|
+
import {webcrypto as crypto} from 'node:crypto';
|
|
7
|
+
const enc=new TextEncoder(),dec=new TextDecoder();
|
|
8
|
+
const b64e=u=>Buffer.from(u).toString('base64'),b64d=s=>new Uint8Array(Buffer.from(s,'base64'));
|
|
9
|
+
const UUID=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;
|
|
10
|
+
const NAMES=['ownerID','requestID','agentID','executorID','executorKeyID','itemID'];
|
|
11
|
+
const ALPHA='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
|
12
|
+
export class RuntimeError extends Error{constructor(code,help){super(code);this.code=code;if(help)this.help=help;}}
|
|
13
|
+
|
|
14
|
+
export async function generateRuntimeKey(){
|
|
15
|
+
const pair=await crypto.subtle.generateKey({name:'X25519'},true,['deriveBits']);
|
|
16
|
+
return {privateKey:pair.privateKey,publicKeyB64:b64e(new Uint8Array(await crypto.subtle.exportKey('raw',pair.publicKey)))};
|
|
17
|
+
}
|
|
18
|
+
// Persist with exportRuntimeKey into the runtime's own secret store; never log it.
|
|
19
|
+
export async function exportRuntimeKey(key){return {jwk:await crypto.subtle.exportKey('jwk',key.privateKey),publicKeyB64:key.publicKeyB64};}
|
|
20
|
+
export async function importRuntimeKey({jwk,publicKeyB64}){return {privateKey:await crypto.subtle.importKey('jwk',jwk,{name:'X25519'},true,['deriveBits']),publicKeyB64};}
|
|
21
|
+
|
|
22
|
+
async function aesKey(privateKey,ephemeralB64,info){
|
|
23
|
+
const eph=await crypto.subtle.importKey('raw',b64d(ephemeralB64),{name:'X25519'},false,[]);
|
|
24
|
+
const shared=new Uint8Array(await crypto.subtle.deriveBits({name:'X25519',public:eph},privateKey,256));
|
|
25
|
+
const hk=await crypto.subtle.importKey('raw',shared,{name:'HKDF'},false,['deriveKey']);
|
|
26
|
+
return crypto.subtle.deriveKey({name:'HKDF',hash:'SHA-256',salt:enc.encode('AgentKey.executor.v1'),info},hk,{name:'AES-GCM',length:256},false,['decrypt']);
|
|
27
|
+
}
|
|
28
|
+
async function openSealed(e,privateKey,binding){
|
|
29
|
+
const k=await aesKey(privateKey,e.ephemeralPublicKey,binding),c=b64d(e.sealed);
|
|
30
|
+
if(c.length<28)throw new RuntimeError('invalid_envelope');
|
|
31
|
+
try{return JSON.parse(dec.decode(await crypto.subtle.decrypt({name:'AES-GCM',iv:c.slice(0,12),additionalData:binding},k,c.slice(12))));}catch{throw new RuntimeError('scope_mismatch');}
|
|
32
|
+
}
|
|
33
|
+
export async function openSessionEnvelope(encoded,pairingId,key){
|
|
34
|
+
const binding=enc.encode(['AgentKey.deviceSession.v1',pairingId.toLowerCase(),key.publicKeyB64].join('\n'));
|
|
35
|
+
const e=JSON.parse(dec.decode(b64d(encoded)));if(!e||e.version!==1)throw new RuntimeError('invalid_envelope');
|
|
36
|
+
const p=await openSealed(e,key.privateKey,binding);
|
|
37
|
+
if(p?.pairing_id!==pairingId||typeof p.access_token!=='string'||typeof p.refresh_token!=='string')throw new RuntimeError('invalid_envelope');
|
|
38
|
+
return {access_token:p.access_token,refresh_token:p.refresh_token,expires_at:p.expires_at??0};
|
|
39
|
+
}
|
|
40
|
+
function validOrigin(o){try{const u=new URL(o);return u.protocol==='https:'&&u.origin===o;}catch{return false;}}
|
|
41
|
+
function targetBinding(s,now){
|
|
42
|
+
const t=s.deliveryTarget;if(t===undefined)return [];
|
|
43
|
+
if(!t||t.version!==2||!/^[a-f0-9]{32}$/.test(t.targetID)||!/^[A-Za-z0-9+/]{43}=$/.test(t.executorPublicKey)||t.origin!==s.origin||!Number.isSafeInteger(t.expiresAt)||t.expiresAt<=now||t.expiresAt>now+300000||s.maxUses!==1)throw new RuntimeError('scope_mismatch');
|
|
44
|
+
return ['AgentKey.deliveryTarget.v2',t.targetID,t.executorPublicKey,t.origin,String(t.expiresAt)];
|
|
45
|
+
}
|
|
46
|
+
export function scopeBinding(s,now=Date.now()){
|
|
47
|
+
if(!s||typeof s!=='object'||Array.isArray(s))throw new RuntimeError('scope_mismatch');
|
|
48
|
+
if(s.auxOrigins!==undefined&&(!Array.isArray(s.auxOrigins)||s.auxOrigins.length>4||s.auxOrigins.some(o=>!validOrigin(o))))throw new RuntimeError('scope_mismatch');
|
|
49
|
+
const auxOrigins=s.auxOrigins===undefined?[]:[...new Set(s.auxOrigins)].sort();
|
|
50
|
+
if(Object.hasOwn(s,'standingGrantID')){
|
|
51
|
+
const names=['ownerID','standingGrantID','agentID','executorID','executorKeyID','itemID'];
|
|
52
|
+
for(const n of names)if(typeof s[n]!=='string'||!UUID.test(s[n]))throw new RuntimeError('scope_mismatch');
|
|
53
|
+
if(!Number.isSafeInteger(s.itemVersion)||s.itemVersion<1||s.action!=='credential.fill'||!validOrigin(s.origin)||s.requestID!==undefined||s.expiresAt!==undefined||s.maxUses!==undefined||s.deliveryTarget!==undefined)throw new RuntimeError('scope_mismatch');
|
|
54
|
+
return enc.encode(['AgentKey.standing-envelope.v1',...names.map(n=>s[n].toLowerCase()),String(s.itemVersion),s.origin,s.action,...auxOrigins].join('\n'));
|
|
55
|
+
}
|
|
56
|
+
for(const n of NAMES)if(typeof s[n]!=='string'||!UUID.test(s[n]))throw new RuntimeError('scope_mismatch');
|
|
57
|
+
if(s.action!=='credential.fill'||!validOrigin(s.origin)||!Number.isSafeInteger(s.itemVersion)||!Number.isSafeInteger(s.expiresAt)||!Number.isSafeInteger(s.maxUses)||s.maxUses<1||s.maxUses>3)throw new RuntimeError('scope_mismatch');
|
|
58
|
+
if(now/1000>=s.expiresAt)throw new RuntimeError('inactive_grant');
|
|
59
|
+
const aux=s.auxOrigins===undefined?[]:[...new Set(s.auxOrigins)].sort();
|
|
60
|
+
if(aux.some(o=>!validOrigin(o))||aux.length>4)throw new RuntimeError('scope_mismatch');
|
|
61
|
+
return enc.encode([s.deliveryTarget?'AgentKey.envelope.v2':'AgentKey.envelope.v1',...NAMES.map(n=>s[n].toLowerCase()),String(s.itemVersion),s.origin,s.action,String(s.expiresAt),String(s.maxUses),...aux,...targetBinding(s,now)].join('\n'));
|
|
62
|
+
}
|
|
63
|
+
export async function openGrantEnvelope(encoded,scope,key){
|
|
64
|
+
const binding=scopeBinding(scope);
|
|
65
|
+
if(typeof encoded!=='string'||encoded.length>65536)throw new RuntimeError('invalid_envelope');
|
|
66
|
+
const e=JSON.parse(dec.decode(b64d(encoded)));if(!e||e.version!==(scope.deliveryTarget?2:1))throw new RuntimeError('invalid_envelope');
|
|
67
|
+
const p=await openSealed(e,key.privateKey,binding);
|
|
68
|
+
if(!p?.scope||!Buffer.from(scopeBinding(p.scope)).equals(Buffer.from(binding))||typeof p.username!=='string'||typeof p.password!=='string'||p.session!==undefined)throw new RuntimeError('scope_mismatch');
|
|
69
|
+
return {username:p.username,password:p.password};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Agent-created login envelope (AgentKey.agent-login.v1): byte-compatible
|
|
73
|
+
// port of apps/mobile/src/crypto.ts sealAgentLogin. Sealed to the owner's
|
|
74
|
+
// published recipient key; only the owner's private key opens it.
|
|
75
|
+
function agentLoginBinding(s){return enc.encode(['AgentKey.agent-login.v1',s.ownerID.toLowerCase(),s.agentID.toLowerCase(),s.recipientKeyID.toLowerCase(),s.origin].join('\n'));}
|
|
76
|
+
function agentLoginWire(s){return {ownerID:s.ownerID.toUpperCase(),agentID:s.agentID.toUpperCase(),recipientKeyID:s.recipientKeyID.toUpperCase(),origin:s.origin};}
|
|
77
|
+
export async function sealAgentLogin(login,scope,recipientPublicKeyB64){
|
|
78
|
+
if(!scope||!UUID.test(scope.ownerID)||!UUID.test(scope.agentID)||!UUID.test(scope.recipientKeyID)||!validOrigin(scope.origin))throw new RuntimeError('invalid_request');
|
|
79
|
+
if(!login||typeof login.title!=='string'||typeof login.username!=='string'||typeof login.password!=='string'||!login.password)throw new RuntimeError('invalid_request');
|
|
80
|
+
const recipient=await crypto.subtle.importKey('raw',b64d(recipientPublicKeyB64),{name:'X25519'},false,[]);
|
|
81
|
+
const eph=await crypto.subtle.generateKey({name:'X25519'},false,['deriveBits']);
|
|
82
|
+
const shared=await crypto.subtle.deriveBits({name:'X25519',public:recipient},eph.privateKey,256);
|
|
83
|
+
const binding=agentLoginBinding(scope);
|
|
84
|
+
const hk=await crypto.subtle.importKey('raw',shared,{name:'HKDF'},false,['deriveKey']);
|
|
85
|
+
const key=await crypto.subtle.deriveKey({name:'HKDF',hash:'SHA-256',salt:enc.encode('AgentKey.agent-login.v1'),info:binding},hk,{name:'AES-GCM',length:256},false,['encrypt']);
|
|
86
|
+
const plain=enc.encode(JSON.stringify({scope:agentLoginWire(scope),title:login.title,username:login.username,password:login.password}));
|
|
87
|
+
if(plain.length>15000)throw new RuntimeError('invalid_request');
|
|
88
|
+
const iv=crypto.getRandomValues(new Uint8Array(12));
|
|
89
|
+
const ct=new Uint8Array(await crypto.subtle.encrypt({name:'AES-GCM',iv,additionalData:binding},key,plain));
|
|
90
|
+
const sealed=new Uint8Array(12+ct.length);sealed.set(iv);sealed.set(ct,12);
|
|
91
|
+
const pub=await crypto.subtle.exportKey('raw',eph.publicKey);
|
|
92
|
+
return b64e(enc.encode(JSON.stringify({version:1,scope:agentLoginWire(scope),ephemeralPublicKey:b64e(new Uint8Array(pub)),sealed:b64e(sealed)})));
|
|
93
|
+
}
|
|
94
|
+
export class AgentKeyRuntime{
|
|
95
|
+
constructor({baseURL='https://agentkey.waiwiser.com/api/public/agentkey-api',key,session,onSession,fetchImpl=fetch}){Object.assign(this,{baseURL,key,session,onSession,fetchImpl});}
|
|
96
|
+
async #call(method,path,body,bearer){
|
|
97
|
+
const r=await this.fetchImpl(this.baseURL+path,{method,headers:{...(bearer?{Authorization:'Bearer '+bearer}:{}),...(body?{'Content-Type':'application/json'}:{})},body:body?JSON.stringify(body):undefined,redirect:'error',signal:AbortSignal.timeout(15000)});
|
|
98
|
+
const j=await r.json().catch(()=>({}));if(!r.ok)throw new RuntimeError(j.code||'request_failed',j.help);return j;
|
|
99
|
+
}
|
|
100
|
+
// Ask AgentKey for the fastest path and the next exact call. Guidance only:
|
|
101
|
+
// it grants nothing, and owner approval still gates every login.
|
|
102
|
+
static async guide({baseURL='https://agentkey.waiwiser.com/api/public/agentkey-api',agentToken,agentId,goal,environment={browser:'automation',can_run_code:true},fetchImpl=fetch}={}){
|
|
103
|
+
const r=await fetchImpl(baseURL+'/v1/guide',{method:'POST',headers:{'Content-Type':'application/json',...(agentToken?{Authorization:'Bearer '+agentToken}:{})},body:JSON.stringify({environment,...(goal?{goal}:{}),...(agentId?{agent_id:agentId}:{})})});
|
|
104
|
+
const j=await r.json().catch(()=>({}));if(!r.ok)throw new RuntimeError(j.code||'request_failed',j.help);return j;
|
|
105
|
+
}
|
|
106
|
+
async guide(){return AgentKeyRuntime.guide({baseURL:this.baseURL,agentToken:await this.#token(),fetchImpl:this.fetchImpl});}
|
|
107
|
+
// Enroll a fresh runtime with the agent's own requester token. Returns the
|
|
108
|
+
// owner approval link; the runtime stays disabled until the owner enables it.
|
|
109
|
+
static async enroll({baseURL,agentToken,agentId,label,key,fetchImpl=fetch,onSession}){
|
|
110
|
+
key??=await generateRuntimeKey();
|
|
111
|
+
const rt=new AgentKeyRuntime({baseURL,key,fetchImpl,onSession});
|
|
112
|
+
const code=Array.from(crypto.getRandomValues(new Uint8Array(8)),b=>ALPHA[b%36]).join('');
|
|
113
|
+
const hash=Buffer.from(await crypto.subtle.digest('SHA-256',enc.encode(code))).toString('hex');
|
|
114
|
+
const p=await rt.#call('POST','/v1/executor/pairings',{agent_id:agentId,code_hash:hash,...(label?{label}:{})},agentToken);
|
|
115
|
+
const red=await rt.#call('POST','/v1/executor/redeem',{code,public_key:key.publicKeyB64});
|
|
116
|
+
rt.session=await openSessionEnvelope(red.sealed_session,red.pairing_id,key);await onSession?.(rt.session);
|
|
117
|
+
return {runtime:rt,key,approvalURL:p.approval_url,pairingId:p.pairing_id};
|
|
118
|
+
}
|
|
119
|
+
#refreshing=null;
|
|
120
|
+
#sessionUnsaved=false;
|
|
121
|
+
async #token(){
|
|
122
|
+
if(!this.session)throw new RuntimeError('not_enrolled');
|
|
123
|
+
if(this.#refreshing)await this.#refreshing;
|
|
124
|
+
else if(this.#sessionUnsaved||(this.session.expires_at&&this.session.expires_at*1000<Date.now()+60000)){
|
|
125
|
+
this.#refreshing??=(async()=>{
|
|
126
|
+
if(!this.#sessionUnsaved){this.session=await this.#call('POST','/v1/executor/session/refresh',{refresh_token:this.session.refresh_token});this.#sessionUnsaved=true;}
|
|
127
|
+
await this.onSession?.(this.session);this.#sessionUnsaved=false;
|
|
128
|
+
})().finally(()=>{this.#refreshing=null;});
|
|
129
|
+
await this.#refreshing;
|
|
130
|
+
}
|
|
131
|
+
return this.session.access_token;
|
|
132
|
+
}
|
|
133
|
+
async self(){const {executors}=await this.#call('GET','/v1/executor/self',null,await this.#token());return executors.filter(e=>e.enabled&&e.public_key===this.key.publicKeyB64);}
|
|
134
|
+
async enrollment(){const rows=await this.self();if(rows.length!==1)throw new RuntimeError('executor_not_enabled');return rows[0];}
|
|
135
|
+
async waitUntilEnabled({timeoutMs=600000,intervalMs=3000}={}){const end=Date.now()+timeoutMs;for(;;){const rows=await this.self();if(rows.length===1)return rows[0];if(Date.now()>end)throw new RuntimeError('owner_approval_pending');await new Promise(r=>setTimeout(r,intervalMs));}}
|
|
136
|
+
async heartbeat(){return (await this.#call('POST','/v1/executor/heartbeat',{public_key:this.key.publicKeyB64},await this.#token())).recorded;}
|
|
137
|
+
async pending(){return (await this.#call('GET','/v1/executor/pending',null,await this.#token())).operations;}
|
|
138
|
+
async preview(id){return this.#call('GET','/v1/executor/operations/'+id,null,await this.#token());}
|
|
139
|
+
async complete(id,outcome){return this.#call('POST','/v1/executor/operations/'+id+'/complete',{outcome},await this.#token());}
|
|
140
|
+
async registerTarget({origin,targetId,ttlMs=300000}){
|
|
141
|
+
const e=await this.enrollment();targetId??=Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString('hex');
|
|
142
|
+
const r=await this.#call('POST','/v1/executor/targets',{executor_id:e.executor_id,key_id:e.key_id,target_id:targetId,origin,expires_epoch_ms:Date.now()+Math.min(ttlMs,300000)},await this.#token());
|
|
143
|
+
return {targetId,executorId:e.executor_id,target:r.target};
|
|
144
|
+
}
|
|
145
|
+
// Glove host calls (packages/agentkey-glove). The glove host is this same
|
|
146
|
+
// owner-trusted runtime; it only ever follows the agent's own commands.
|
|
147
|
+
async gloveHost({executorId,connectURL,capacity}){return this.#call('POST','/v1/executor/glove/host',{executor_id:executorId,connect_url:connectURL,capacity},await this.#token());}
|
|
148
|
+
async gloveRedeem({executorId,ticket}){return this.#call('POST','/v1/executor/glove/redeem',{executor_id:executorId,ticket},await this.#token());}
|
|
149
|
+
async gloveHeartbeat({executorId,sessions}){return (await this.#call('POST','/v1/executor/glove/heartbeat',{executor_id:executorId,sessions},await this.#token())).open;}
|
|
150
|
+
async gloveClose({executorId,sessionId,reason}){return this.#call('POST','/v1/executor/glove/sessions/'+sessionId+'/close',{executor_id:executorId,reason},await this.#token());}
|
|
151
|
+
// Claim one operation and fill it into the agent's EXISTING page. Fails
|
|
152
|
+
// closed unless the page's current origin exactly matches the grant origin.
|
|
153
|
+
// Reports exactly one outcome; a submitted form is reported as 'unknown'
|
|
154
|
+
// unless verify() confirms the signed-in state.
|
|
155
|
+
// Agent-created logins (glove signup-and-save). The runtime seals to the
|
|
156
|
+
// owner's current recipient key; the server only ever stores ciphertext.
|
|
157
|
+
// Executor-scoped proposal lifecycle. Every call is bound to the glove
|
|
158
|
+
// session the runtime is hosting: the server derives owner and agent from
|
|
159
|
+
// the session's immutable binding, so a caller can never name them.
|
|
160
|
+
async ownerRecipientKey(sessionId){
|
|
161
|
+
if(!UUID.test(sessionId))throw new RuntimeError('invalid_request');
|
|
162
|
+
const r=await this.#call('POST','/v1/executor/glove/proposals/key',{session_id:sessionId},await this.#token());
|
|
163
|
+
if(!r||!UUID.test(r.owner_id)||!UUID.test(r.agent_id)||!UUID.test(r.recipient_key_id)||typeof r.public_key!=='string'||r.public_key.length!==44)throw new RuntimeError('invalid_response');
|
|
164
|
+
return {ownerId:r.owner_id,agentId:r.agent_id,keyId:r.recipient_key_id,publicKey:r.public_key};
|
|
165
|
+
}
|
|
166
|
+
async proposeLogin({sessionId,origin,recipientKeyId,ciphertext}){
|
|
167
|
+
if(!UUID.test(sessionId)||!UUID.test(recipientKeyId)||!validOrigin(origin)||typeof ciphertext!=='string'||ciphertext.length<100||ciphertext.length>40000)throw new RuntimeError('invalid_request');
|
|
168
|
+
const r=await this.#call('POST','/v1/executor/glove/proposals',{session_id:sessionId,origin,recipient_key_id:recipientKeyId,ciphertext},await this.#token());
|
|
169
|
+
if(!r||!UUID.test(r.proposal_id)||typeof r.state!=='string')throw new RuntimeError('invalid_response');
|
|
170
|
+
return {proposalId:r.proposal_id,status:r.state};
|
|
171
|
+
}
|
|
172
|
+
async proposalStatus(id,sessionId){if(!UUID.test(id)||!UUID.test(sessionId))throw new RuntimeError('invalid_request');const r=await this.#call('POST','/v1/executor/glove/proposals/'+id+'/status',{session_id:sessionId},await this.#token());if(!r||typeof r.state!=='string')throw new RuntimeError('invalid_response');return r.state;}
|
|
173
|
+
async markLoginProposalUncertain(id,sessionId){if(!UUID.test(id)||!UUID.test(sessionId))throw new RuntimeError('invalid_request');return this.#call('POST','/v1/executor/glove/proposals/'+id+'/uncertain',{session_id:sessionId},await this.#token());}
|
|
174
|
+
async confirmLoginProposal(id,sessionId){if(!UUID.test(id)||!UUID.test(sessionId))throw new RuntimeError('invalid_request');return this.#call('POST','/v1/executor/glove/proposals/'+id+'/confirm',{session_id:sessionId},await this.#token());}
|
|
175
|
+
async retractLoginProposal(id,sessionId){if(!UUID.test(id)||!UUID.test(sessionId))throw new RuntimeError('invalid_request');return this.#call('POST','/v1/executor/glove/proposals/'+id+'/retract',{session_id:sessionId},await this.#token());}
|
|
176
|
+
// Seal a generated signup credential to the owner and stage it BEFORE the
|
|
177
|
+
// signup is committed. agentId must be the agent the session was redeemed
|
|
178
|
+
// for; the owner verifies the sealed scope against the proposal row, so a
|
|
179
|
+
// wrong agent id fails closed at import. Returns the durable proposal id;
|
|
180
|
+
// the credential itself is never returned, logged or sent anywhere else.
|
|
181
|
+
async proposeCreatedLogin({sessionId,agentId,origin,username,title,password}){
|
|
182
|
+
if(!UUID.test(sessionId)||!UUID.test(agentId))throw new RuntimeError('invalid_request');
|
|
183
|
+
if(typeof username!=='string'||username.length>200)throw new RuntimeError('invalid_request');
|
|
184
|
+
if(title!==undefined&&(typeof title!=='string'||title.length>120))throw new RuntimeError('invalid_request');
|
|
185
|
+
const k=await this.ownerRecipientKey(sessionId);
|
|
186
|
+
if(k.agentId.toLowerCase()!==agentId.toLowerCase())throw new RuntimeError('scope_mismatch');
|
|
187
|
+
const ciphertext=await sealAgentLogin({title:title??'',username,password},{ownerID:k.ownerId,agentID:agentId,recipientKeyID:k.keyId,origin},k.publicKey);
|
|
188
|
+
return this.proposeLogin({sessionId,origin,recipientKeyId:k.keyId,ciphertext});
|
|
189
|
+
}
|
|
190
|
+
async fillOperation(operationId,page,{usernameSelector='input[autocomplete="username"],input[type="email"],input[name*="user" i],input[name*="email" i]',passwordSelector='input[type="password"]',submit=true,verify,targetBound=false,gloveSessionId,onSecret}={}){
|
|
191
|
+
if(!UUID.test(operationId)||(gloveSessionId!==undefined&&(!UUID.test(gloveSessionId)||targetBound)))throw new RuntimeError('invalid_request');
|
|
192
|
+
if(verify!==undefined&&typeof verify!=='function')throw new RuntimeError('invalid_verification');
|
|
193
|
+
const pageOrigin=new URL(page.url()).origin;
|
|
194
|
+
const claim=await this.#call('POST','/v1/executor/'+(targetBound?'target-operations/':'operations/')+operationId+'/claim',gloveSessionId?{glove_session_id:gloveSessionId}:{},await this.#token());
|
|
195
|
+
let cred,outcome='failed',submitted=false,verification='not_requested',failure=null;
|
|
196
|
+
try{
|
|
197
|
+
if(claim.scope.origin!==pageOrigin||new URL(page.url()).origin!==pageOrigin)throw new RuntimeError('page_origin_mismatch');
|
|
198
|
+
if(gloveSessionId&&claim.glove_session_id!==gloveSessionId)throw new RuntimeError('glove_session_mismatch');
|
|
199
|
+
cred=await openGrantEnvelope(claim.encoded,claim.scope,this.key);
|
|
200
|
+
// Host-only sink for output redaction. Never returned, logged or accepted
|
|
201
|
+
// from a wire command. It remains in this same credential process.
|
|
202
|
+
onSecret?.(cred.password);
|
|
203
|
+
const pw=page.locator(passwordSelector);if(await pw.count()!==1)throw new RuntimeError('login_form_ambiguous');
|
|
204
|
+
const user=page.locator(usernameSelector);const uc=await user.count();if(uc>1)throw new RuntimeError('login_form_ambiguous');
|
|
205
|
+
if(uc===1)await user.first().fill(cred.username);
|
|
206
|
+
await pw.fill(cred.password);
|
|
207
|
+
cred=null;
|
|
208
|
+
if(submit){
|
|
209
|
+
submitted=true; // Set before dispatch: a timeout may still have submitted.
|
|
210
|
+
await pw.press('Enter');
|
|
211
|
+
if(verify){verification=(await verify(page))?'matched':'not_matched';outcome=verification==='matched'?'completed':'unknown';}
|
|
212
|
+
else outcome='unknown';
|
|
213
|
+
}else outcome='completed';
|
|
214
|
+
}catch(e){
|
|
215
|
+
failure=e;
|
|
216
|
+
outcome=submitted?'unknown':'failed';
|
|
217
|
+
if(submitted&&verify)verification='unconfirmed';
|
|
218
|
+
}finally{cred=null;}
|
|
219
|
+
// Exactly one completion attempt. Never retry an uncertain submission or
|
|
220
|
+
// convert a verifier/navigation error after submission into a failed login.
|
|
221
|
+
await this.complete(operationId,outcome);
|
|
222
|
+
if(failure&&!submitted)throw failure;
|
|
223
|
+
return {operation_id:operationId,outcome,submitted,verification,...(failure?{code:'submission_unconfirmed'}:{})};
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tryagentkey/runtime",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"author": "AgentKey, Inc.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "index.mjs",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./index.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"index.mjs",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE",
|
|
14
|
+
"NOTICE"
|
|
15
|
+
],
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=22"
|
|
18
|
+
},
|
|
19
|
+
"license": "Apache-2.0",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/edan-ais/agentkey.git",
|
|
23
|
+
"directory": "packages/agentkey-runtime"
|
|
24
|
+
}
|
|
25
|
+
}
|