@asecret/cli 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/CHANGELOG.md +16 -0
- package/LICENSE +21 -0
- package/README.md +72 -2
- package/bin/asecret-mcp.js +4 -0
- package/bin/asecret.js +12 -0
- package/core/spec/0.2/messages.schema.json +751 -0
- package/core/src/agent-crypto.js +191 -0
- package/core/src/agent.js +237 -0
- package/core/src/assistant-instructions.js +64 -0
- package/core/src/authorization.js +266 -0
- package/core/src/credentials.js +149 -0
- package/core/src/host-login.js +110 -0
- package/core/src/mcp-tools.js +130 -0
- package/core/src/wire.js +76 -0
- package/package.json +68 -4
- package/skill/SKILL.md +66 -0
- package/src/agents.js +140 -0
- package/src/api.js +188 -0
- package/src/commands.js +864 -0
- package/src/config.js +76 -0
- package/src/core.d.ts +55 -0
- package/src/core.js +19 -0
- package/src/errors.js +11 -0
- package/src/main.js +520 -0
- package/src/mcp.js +107 -0
- package/src/output.js +93 -0
- package/src/server.js +242 -0
- package/src/storage.js +137 -0
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// Use on the agent host. Keep the returned finish function in private host state.
|
|
2
|
+
function providerOrigin(value) {
|
|
3
|
+
const url = new URL(value);
|
|
4
|
+
if (url.protocol !== 'https:' || url.href !== url.origin + '/')
|
|
5
|
+
throw new Error('Choose a server HTTPS origin');
|
|
6
|
+
return url.origin;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function endpoint(value, origin) {
|
|
10
|
+
const url = new URL(value);
|
|
11
|
+
if (url.origin !== origin || url.username || url.password || url.hash)
|
|
12
|
+
throw new Error('Unexpected authorization endpoint');
|
|
13
|
+
return url;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function callbackURL(input) {
|
|
17
|
+
const url = new URL(input);
|
|
18
|
+
const loopback = url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname);
|
|
19
|
+
if ((!loopback && url.protocol !== 'https:') || url.username || url.password || url.hash || url.search) {
|
|
20
|
+
throw new Error('Register an HTTPS or loopback callback without query parameters');
|
|
21
|
+
}
|
|
22
|
+
return url;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function base64url(bytes) {
|
|
26
|
+
return btoa(String.fromCharCode(...bytes))
|
|
27
|
+
.replaceAll('+', '-')
|
|
28
|
+
.replaceAll('/', '_')
|
|
29
|
+
.replaceAll('=', '');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function responseJSON(fetcher, url, options) {
|
|
33
|
+
const response = await fetcher(url, {
|
|
34
|
+
...options,
|
|
35
|
+
redirect: 'error',
|
|
36
|
+
credentials: 'omit',
|
|
37
|
+
signal: AbortSignal.timeout(15000),
|
|
38
|
+
});
|
|
39
|
+
if (!response.ok || response.headers.get('content-type')?.split(';')[0] !== 'application/json') {
|
|
40
|
+
throw new Error('Server authorization service unavailable');
|
|
41
|
+
}
|
|
42
|
+
const reader = response.body.getReader();
|
|
43
|
+
const decoder = new TextDecoder();
|
|
44
|
+
let bytes = 0,
|
|
45
|
+
text = '';
|
|
46
|
+
try {
|
|
47
|
+
for (;;) {
|
|
48
|
+
const { done, value } = await reader.read();
|
|
49
|
+
if (done) break;
|
|
50
|
+
bytes += value.byteLength;
|
|
51
|
+
if (bytes > 65536) {
|
|
52
|
+
await reader.cancel();
|
|
53
|
+
throw new Error('Oversized authorization response');
|
|
54
|
+
}
|
|
55
|
+
text += decoder.decode(value, { stream: true });
|
|
56
|
+
}
|
|
57
|
+
} finally {
|
|
58
|
+
reader.releaseLock();
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
return JSON.parse(text + decoder.decode());
|
|
62
|
+
} catch {
|
|
63
|
+
throw Error('Invalid JSON from the server authorization service');
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function validateAgentName(name) {
|
|
68
|
+
if (
|
|
69
|
+
typeof name !== 'string' ||
|
|
70
|
+
!name ||
|
|
71
|
+
name.length > 80 ||
|
|
72
|
+
name.trim() !== name ||
|
|
73
|
+
/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(name)
|
|
74
|
+
)
|
|
75
|
+
throw Error('Choose an agent name of 1 to 80 visible characters.');
|
|
76
|
+
return name;
|
|
77
|
+
}
|
|
78
|
+
async function serverMetadata(origin, fetcher) {
|
|
79
|
+
const metadata = await responseJSON(fetcher, origin + '/.well-known/oauth-authorization-server');
|
|
80
|
+
if (
|
|
81
|
+
metadata?.issuer !== origin ||
|
|
82
|
+
!Array.isArray(metadata.code_challenge_methods_supported) ||
|
|
83
|
+
!metadata.code_challenge_methods_supported.includes('S256')
|
|
84
|
+
)
|
|
85
|
+
throw Error('Incompatible authorization server');
|
|
86
|
+
return metadata;
|
|
87
|
+
}
|
|
88
|
+
function supportsRenewal(metadata) {
|
|
89
|
+
return (
|
|
90
|
+
Array.isArray(metadata.grant_types_supported) &&
|
|
91
|
+
metadata.grant_types_supported.includes('refresh_token') &&
|
|
92
|
+
Array.isArray(metadata.scopes_supported) &&
|
|
93
|
+
metadata.scopes_supported.includes('offline_access')
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function registerAgentClient(
|
|
98
|
+
serverOrigin,
|
|
99
|
+
{ name, redirectUri, persistent = true, fetcher = fetch },
|
|
100
|
+
) {
|
|
101
|
+
const origin = providerOrigin(serverOrigin);
|
|
102
|
+
validateAgentName(name);
|
|
103
|
+
const callback = callbackURL(redirectUri);
|
|
104
|
+
if (
|
|
105
|
+
callback.href !== redirectUri ||
|
|
106
|
+
redirectUri.includes('?') ||
|
|
107
|
+
redirectUri.includes('#') ||
|
|
108
|
+
(callback.protocol === 'http:' && !callback.port)
|
|
109
|
+
)
|
|
110
|
+
throw Error('Choose an exact HTTPS or loopback callback with a loopback port.');
|
|
111
|
+
const metadata = await serverMetadata(origin, fetcher);
|
|
112
|
+
if (!metadata.registration_endpoint) {
|
|
113
|
+
const error = Error(
|
|
114
|
+
'This server requires a registered client ID and callback. Configure the issued client ID and exact return address.',
|
|
115
|
+
);
|
|
116
|
+
error.code = 'registration_unavailable';
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
const registration = endpoint(metadata.registration_endpoint, origin),
|
|
120
|
+
ongoing = persistent && supportsRenewal(metadata);
|
|
121
|
+
const result = await responseJSON(fetcher, registration, {
|
|
122
|
+
method: 'POST',
|
|
123
|
+
headers: { 'content-type': 'application/json' },
|
|
124
|
+
body: JSON.stringify({
|
|
125
|
+
client_name: name,
|
|
126
|
+
redirect_uris: [redirectUri],
|
|
127
|
+
token_endpoint_auth_method: 'none',
|
|
128
|
+
grant_types: ongoing ? ['authorization_code', 'refresh_token'] : ['authorization_code'],
|
|
129
|
+
response_types: ['code'],
|
|
130
|
+
scope: ongoing ? 'asecret.request offline_access' : 'asecret.request',
|
|
131
|
+
}),
|
|
132
|
+
});
|
|
133
|
+
if (
|
|
134
|
+
typeof result?.client_id !== 'string' ||
|
|
135
|
+
!result.client_id ||
|
|
136
|
+
result.client_id.length > 1024 ||
|
|
137
|
+
/[\p{Cc}\p{Cf}]/u.test(result.client_id) ||
|
|
138
|
+
result.token_endpoint_auth_method !== 'none' ||
|
|
139
|
+
['client_secret', 'access_token', 'refresh_token'].some((key) => Object.hasOwn(result, key)) ||
|
|
140
|
+
!Array.isArray(result.redirect_uris) ||
|
|
141
|
+
result.redirect_uris.length !== 1 ||
|
|
142
|
+
result.redirect_uris[0] !== redirectUri
|
|
143
|
+
)
|
|
144
|
+
throw Error('Unexpected public-client registration.');
|
|
145
|
+
return result.client_id;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export async function beginAgentConnection(
|
|
149
|
+
serverOrigin,
|
|
150
|
+
{ clientId, redirectUri, fetcher = fetch, persistent = true, resource },
|
|
151
|
+
) {
|
|
152
|
+
const origin = providerOrigin(serverOrigin);
|
|
153
|
+
if (
|
|
154
|
+
resource !== undefined &&
|
|
155
|
+
(typeof resource !== 'string' || endpoint(resource, origin).href !== resource)
|
|
156
|
+
)
|
|
157
|
+
throw new Error('Invalid protected resource');
|
|
158
|
+
const callback = callbackURL(redirectUri);
|
|
159
|
+
if (typeof clientId !== 'string' || !clientId)
|
|
160
|
+
throw new Error('A registered agent client ID is required');
|
|
161
|
+
const metadata = await serverMetadata(origin, fetcher);
|
|
162
|
+
const authorization = endpoint(metadata.authorization_endpoint, origin);
|
|
163
|
+
const token = endpoint(metadata.token_endpoint, origin);
|
|
164
|
+
const verifier = base64url(crypto.getRandomValues(new Uint8Array(48)));
|
|
165
|
+
const state = base64url(crypto.getRandomValues(new Uint8Array(32)));
|
|
166
|
+
const challenge = base64url(
|
|
167
|
+
new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))),
|
|
168
|
+
);
|
|
169
|
+
const parameters = {
|
|
170
|
+
...(resource ? { resource } : {}),
|
|
171
|
+
response_type: 'code',
|
|
172
|
+
client_id: clientId,
|
|
173
|
+
redirect_uri: redirectUri,
|
|
174
|
+
state,
|
|
175
|
+
code_challenge_method: 'S256',
|
|
176
|
+
code_challenge: challenge,
|
|
177
|
+
};
|
|
178
|
+
if (persistent && supportsRenewal(metadata)) parameters.scope = 'asecret.request offline_access';
|
|
179
|
+
for (const [key, value] of Object.entries(parameters)) authorization.searchParams.set(key, value);
|
|
180
|
+
let consumed = false;
|
|
181
|
+
const deadline = Date.now() + 300000;
|
|
182
|
+
async function finish(callbackAddress) {
|
|
183
|
+
const received = new URL(callbackAddress);
|
|
184
|
+
if (
|
|
185
|
+
consumed ||
|
|
186
|
+
Date.now() >= deadline ||
|
|
187
|
+
received.origin !== callback.origin ||
|
|
188
|
+
received.pathname !== callback.pathname ||
|
|
189
|
+
received.username ||
|
|
190
|
+
received.password ||
|
|
191
|
+
received.hash ||
|
|
192
|
+
received.searchParams.getAll('state').length !== 1 ||
|
|
193
|
+
received.searchParams.get('state') !== state
|
|
194
|
+
)
|
|
195
|
+
throw new Error('Invalid or expired server return');
|
|
196
|
+
consumed = true;
|
|
197
|
+
if (received.searchParams.has('error')) throw new Error('Server connection was declined');
|
|
198
|
+
const codes = received.searchParams.getAll('code');
|
|
199
|
+
if (codes.length !== 1 || !codes[0]) throw new Error('Missing authorization code');
|
|
200
|
+
const form = new URLSearchParams({
|
|
201
|
+
...(resource ? { resource } : {}),
|
|
202
|
+
grant_type: 'authorization_code',
|
|
203
|
+
client_id: clientId,
|
|
204
|
+
redirect_uri: redirectUri,
|
|
205
|
+
code: codes[0],
|
|
206
|
+
code_verifier: verifier,
|
|
207
|
+
});
|
|
208
|
+
const value = await responseJSON(fetcher, token, { method: 'POST', body: form });
|
|
209
|
+
return hostGrant(value, origin, clientId, resource);
|
|
210
|
+
}
|
|
211
|
+
return { authorizationURL: authorization.href, finish };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function hostGrant(value, origin, clientId, resource) {
|
|
215
|
+
if (
|
|
216
|
+
value.token_type?.toLowerCase() !== 'bearer' ||
|
|
217
|
+
typeof value.access_token !== 'string' ||
|
|
218
|
+
!value.access_token.length ||
|
|
219
|
+
typeof value.connection_id !== 'string' ||
|
|
220
|
+
!value.connection_id.length ||
|
|
221
|
+
!Number.isSafeInteger(value.expires_in) ||
|
|
222
|
+
value.expires_in <= 0 ||
|
|
223
|
+
!Number.isSafeInteger(Date.now() + value.expires_in * 1000)
|
|
224
|
+
)
|
|
225
|
+
throw new Error('Invalid token response');
|
|
226
|
+
return {
|
|
227
|
+
origin,
|
|
228
|
+
clientId,
|
|
229
|
+
...(resource ? { resource } : {}),
|
|
230
|
+
...(typeof value.refresh_token === 'string' && value.refresh_token
|
|
231
|
+
? { refreshToken: value.refresh_token }
|
|
232
|
+
: {}),
|
|
233
|
+
accessToken: value.access_token,
|
|
234
|
+
connectionId: value.connection_id,
|
|
235
|
+
expiresAt: Date.now() + 1000 * value.expires_in,
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
export async function renewAgentConnection(grant, { fetcher = fetch, beforeExchange } = {}) {
|
|
239
|
+
const origin = providerOrigin(grant.origin);
|
|
240
|
+
if (!grant.clientId || !grant.refreshToken || !grant.connectionId)
|
|
241
|
+
throw new Error('This host connection requires pairing');
|
|
242
|
+
const metadata = await responseJSON(fetcher, origin + '/.well-known/oauth-authorization-server');
|
|
243
|
+
if (metadata.issuer !== origin || !metadata.grant_types_supported?.includes('refresh_token'))
|
|
244
|
+
throw new Error('Server does not support connection renewal');
|
|
245
|
+
const tokenEndpoint = endpoint(metadata.token_endpoint, origin);
|
|
246
|
+
if (grant.resource && endpoint(grant.resource, origin).href !== grant.resource)
|
|
247
|
+
throw new Error('Invalid protected resource');
|
|
248
|
+
await beforeExchange?.();
|
|
249
|
+
const response = await responseJSON(fetcher, tokenEndpoint, {
|
|
250
|
+
method: 'POST',
|
|
251
|
+
body: new URLSearchParams({
|
|
252
|
+
...(grant.resource ? { resource: grant.resource } : {}),
|
|
253
|
+
grant_type: 'refresh_token',
|
|
254
|
+
client_id: grant.clientId,
|
|
255
|
+
refresh_token: grant.refreshToken,
|
|
256
|
+
}),
|
|
257
|
+
});
|
|
258
|
+
const next = hostGrant(response, origin, grant.clientId, grant.resource);
|
|
259
|
+
if (
|
|
260
|
+
next.connectionId !== grant.connectionId ||
|
|
261
|
+
!next.refreshToken ||
|
|
262
|
+
next.refreshToken === grant.refreshToken
|
|
263
|
+
)
|
|
264
|
+
throw new Error('Invalid renewed host credential');
|
|
265
|
+
return next;
|
|
266
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { dirname } from 'node:path';
|
|
2
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { open, readFile, link, rename, unlink, mkdir } from 'node:fs/promises';
|
|
5
|
+
import { setTimeout as wait } from 'node:timers/promises';
|
|
6
|
+
import { renewAgentConnection } from './authorization.js';
|
|
7
|
+
|
|
8
|
+
export async function readCredential(file, origin) {
|
|
9
|
+
let text;
|
|
10
|
+
try {
|
|
11
|
+
text = await readFile(file, 'utf8');
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (error.code === 'ENOENT') return null;
|
|
14
|
+
throw error;
|
|
15
|
+
}
|
|
16
|
+
const value = JSON.parse(text);
|
|
17
|
+
if (value.origin !== origin || typeof value.accessToken !== 'string' || !value.accessToken)
|
|
18
|
+
throw new Error('Credential belongs to another server or is incomplete');
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function atomicWrite(file, value, create = false) {
|
|
23
|
+
const tmp = file + '.' + randomUUID() + '.new';
|
|
24
|
+
const output = await open(tmp, 'wx', 0o600);
|
|
25
|
+
try {
|
|
26
|
+
try {
|
|
27
|
+
await output.writeFile(JSON.stringify(value));
|
|
28
|
+
await output.sync();
|
|
29
|
+
} finally {
|
|
30
|
+
await output.close();
|
|
31
|
+
}
|
|
32
|
+
if (create) await link(tmp, file);
|
|
33
|
+
else await rename(tmp, file);
|
|
34
|
+
} finally {
|
|
35
|
+
await unlink(tmp).catch((error) => {
|
|
36
|
+
if (error.code !== 'ENOENT') throw error;
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// SQLite releases its process lock if the host exits mid-renewal. This companion file contains no credentials.
|
|
42
|
+
async function withCredentialLock(file, work) {
|
|
43
|
+
const guard = new DatabaseSync(file + '.lock.sqlite');
|
|
44
|
+
const until = Date.now() + 40000;
|
|
45
|
+
try {
|
|
46
|
+
for (;;) {
|
|
47
|
+
try {
|
|
48
|
+
guard.exec('BEGIN IMMEDIATE');
|
|
49
|
+
break;
|
|
50
|
+
} catch (error) {
|
|
51
|
+
if (error.errcode !== 5 || Date.now() >= until) throw error;
|
|
52
|
+
await wait(40);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return await work();
|
|
56
|
+
} finally {
|
|
57
|
+
guard.close();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function saveCredential(file, grant, previous = null) {
|
|
62
|
+
return withCredentialLock(file, async () => {
|
|
63
|
+
const found = await readCredential(file, grant.origin);
|
|
64
|
+
if ((found?.accessToken ?? null) !== (previous?.accessToken ?? null))
|
|
65
|
+
throw new Error('Host connection changed during pairing');
|
|
66
|
+
await atomicWrite(file, grant, !found);
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function usableCredential(
|
|
71
|
+
file,
|
|
72
|
+
origin,
|
|
73
|
+
{ renew = renewAgentConnection, expectedClient } = {},
|
|
74
|
+
) {
|
|
75
|
+
async function read() {
|
|
76
|
+
const stored = await readCredential(file, origin);
|
|
77
|
+
if (stored && expectedClient !== undefined && (!expectedClient || stored.clientId !== expectedClient))
|
|
78
|
+
throw Error('Choose the credential file for this agent.');
|
|
79
|
+
return stored;
|
|
80
|
+
}
|
|
81
|
+
function due(value) {
|
|
82
|
+
return value?.refreshToken && value.expiresAt <= Date.now() + 30000;
|
|
83
|
+
}
|
|
84
|
+
const session = await read();
|
|
85
|
+
if (!due(session)) return session;
|
|
86
|
+
return withCredentialLock(file, async () => {
|
|
87
|
+
const current = await read();
|
|
88
|
+
if (!due(current)) return current;
|
|
89
|
+
const pending = { ...current, expiresAt: 0 };
|
|
90
|
+
delete pending.refreshToken;
|
|
91
|
+
// A crash or lost response must never replay a consumed refresh token.
|
|
92
|
+
const next = await renew(current, { beforeExchange: () => atomicWrite(file, pending) });
|
|
93
|
+
await atomicWrite(file, next);
|
|
94
|
+
return next;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function localRegistration(file, origin, name, create) {
|
|
99
|
+
const path = file + '.client.json';
|
|
100
|
+
async function read() {
|
|
101
|
+
let raw;
|
|
102
|
+
try {
|
|
103
|
+
raw = await readFile(path, 'utf8');
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (error.code === 'ENOENT') return null;
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
const cached = JSON.parse(raw);
|
|
109
|
+
if (
|
|
110
|
+
cached?.origin !== origin ||
|
|
111
|
+
cached.name !== name ||
|
|
112
|
+
typeof cached.clientId !== 'string' ||
|
|
113
|
+
!cached.clientId ||
|
|
114
|
+
typeof cached.redirectUri !== 'string'
|
|
115
|
+
)
|
|
116
|
+
throw Error(
|
|
117
|
+
'This credential file belongs to a different agent. Choose a separate file for this name and server.',
|
|
118
|
+
);
|
|
119
|
+
return cached;
|
|
120
|
+
}
|
|
121
|
+
const existing = await read();
|
|
122
|
+
if (existing || !create) return existing;
|
|
123
|
+
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
|
|
124
|
+
return withCredentialLock(file, async () => {
|
|
125
|
+
const current = await read();
|
|
126
|
+
if (current) return current;
|
|
127
|
+
if (await readCredential(file, origin))
|
|
128
|
+
throw Error(
|
|
129
|
+
'This credential file already belongs to a registered agent. Choose a separate file.',
|
|
130
|
+
);
|
|
131
|
+
const registered = { origin, name, ...(await create()) };
|
|
132
|
+
await atomicWrite(path, registered, true);
|
|
133
|
+
return registered;
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export async function clearDisconnectedCredential(file, session, { requireSameToken = false } = {}) {
|
|
138
|
+
return withCredentialLock(file, async () => {
|
|
139
|
+
const current = await readCredential(file, session.origin);
|
|
140
|
+
if (!current) return true;
|
|
141
|
+
if (
|
|
142
|
+
current.connectionId !== session.connectionId ||
|
|
143
|
+
(requireSameToken && current.accessToken !== session.accessToken)
|
|
144
|
+
)
|
|
145
|
+
return false;
|
|
146
|
+
await unlink(file);
|
|
147
|
+
return true;
|
|
148
|
+
});
|
|
149
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { once } from 'node:events';
|
|
3
|
+
import { beginAgentConnection, registerAgentClient, validateAgentName } from './authorization.js';
|
|
4
|
+
import { localRegistration } from './credentials.js';
|
|
5
|
+
|
|
6
|
+
export function loopbackCallback(address) {
|
|
7
|
+
const url = new URL(address);
|
|
8
|
+
if (
|
|
9
|
+
url.protocol !== 'http:' ||
|
|
10
|
+
url.hostname !== '127.0.0.1' ||
|
|
11
|
+
!url.port ||
|
|
12
|
+
url.href !== address ||
|
|
13
|
+
url.username ||
|
|
14
|
+
url.password ||
|
|
15
|
+
address.includes('?') ||
|
|
16
|
+
address.includes('#')
|
|
17
|
+
)
|
|
18
|
+
throw Error('Use the exact registered 127.0.0.1 callback URL with a port');
|
|
19
|
+
return url;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function login(
|
|
23
|
+
origin,
|
|
24
|
+
{ clientId, redirectUri, name, file, showURL, fetcher = fetch, timeout = 300000 },
|
|
25
|
+
) {
|
|
26
|
+
const provider = new URL(origin);
|
|
27
|
+
if (provider.protocol !== 'https:' || provider.href !== provider.origin + '/')
|
|
28
|
+
throw Error('Choose a server HTTPS origin');
|
|
29
|
+
if (name !== undefined) {
|
|
30
|
+
validateAgentName(name);
|
|
31
|
+
if (!file || clientId !== undefined || redirectUri !== undefined)
|
|
32
|
+
throw Error('Choose a named agent or a registered client ID and callback.');
|
|
33
|
+
} else if (!clientId || !redirectUri) throw Error('A registered client ID and callback are required.');
|
|
34
|
+
let accept, callback, state, timer;
|
|
35
|
+
const received = new Promise((resolve) => {
|
|
36
|
+
accept = resolve;
|
|
37
|
+
});
|
|
38
|
+
const server = createServer((req, res) => {
|
|
39
|
+
let url;
|
|
40
|
+
try {
|
|
41
|
+
if (callback) url = new URL(req.url, callback.origin);
|
|
42
|
+
} catch {}
|
|
43
|
+
if (
|
|
44
|
+
!state ||
|
|
45
|
+
!url ||
|
|
46
|
+
req.method !== 'GET' ||
|
|
47
|
+
req.headers.host !== callback.host ||
|
|
48
|
+
url.origin !== callback.origin ||
|
|
49
|
+
url.pathname !== callback.pathname ||
|
|
50
|
+
url.searchParams.getAll('state').length !== 1 ||
|
|
51
|
+
url.searchParams.get('state') !== state ||
|
|
52
|
+
(!url.searchParams.get('code') && !url.searchParams.get('error'))
|
|
53
|
+
) {
|
|
54
|
+
res.writeHead(400);
|
|
55
|
+
res.end('Invalid callback');
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
res.writeHead(200, {
|
|
59
|
+
'content-type': 'text/plain',
|
|
60
|
+
'cache-control': 'no-store',
|
|
61
|
+
'referrer-policy': 'no-referrer',
|
|
62
|
+
});
|
|
63
|
+
res.end('You may return to your agent.');
|
|
64
|
+
accept(url.href);
|
|
65
|
+
});
|
|
66
|
+
async function listen(port) {
|
|
67
|
+
server.listen(port, '127.0.0.1');
|
|
68
|
+
try {
|
|
69
|
+
await once(server, 'listening');
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (error.code === 'EADDRINUSE')
|
|
72
|
+
throw Error(
|
|
73
|
+
'The registered local callback is busy. Finish the open connection attempt or close the application using port ' +
|
|
74
|
+
port +
|
|
75
|
+
'.',
|
|
76
|
+
);
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
if (name !== undefined) {
|
|
82
|
+
const registered = await localRegistration(file, provider.origin, name, async () => {
|
|
83
|
+
await listen(0);
|
|
84
|
+
const redirectUri = 'http://127.0.0.1:' + server.address().port + '/callback';
|
|
85
|
+
const clientId = await registerAgentClient(provider.origin, { name, redirectUri, fetcher });
|
|
86
|
+
return { clientId, redirectUri };
|
|
87
|
+
});
|
|
88
|
+
clientId = registered.clientId;
|
|
89
|
+
redirectUri = registered.redirectUri;
|
|
90
|
+
}
|
|
91
|
+
callback = loopbackCallback(redirectUri);
|
|
92
|
+
if (!server.listening) await listen(Number(callback.port));
|
|
93
|
+
const flow = await beginAgentConnection(provider.origin, { clientId, redirectUri, fetcher });
|
|
94
|
+
state = new URL(flow.authorizationURL).searchParams.get('state');
|
|
95
|
+
showURL(flow.authorizationURL);
|
|
96
|
+
const result = await Promise.race([
|
|
97
|
+
received,
|
|
98
|
+
new Promise((_, reject) => {
|
|
99
|
+
timer = setTimeout(() => reject(Error('Pairing expired')), timeout);
|
|
100
|
+
}),
|
|
101
|
+
]);
|
|
102
|
+
return await flow.finish(result);
|
|
103
|
+
} finally {
|
|
104
|
+
clearTimeout(timer);
|
|
105
|
+
if (server.listening) {
|
|
106
|
+
server.closeAllConnections();
|
|
107
|
+
await new Promise((resolve) => server.close(resolve));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { detailTypes } from './wire.js';
|
|
2
|
+
import * as z from 'zod/v4';
|
|
3
|
+
|
|
4
|
+
export function registerServerTools(
|
|
5
|
+
mcp,
|
|
6
|
+
use,
|
|
7
|
+
{
|
|
8
|
+
formLink = () => use((server) => server.websiteFormLink()),
|
|
9
|
+
setupLink = () => use((server) => server.ownerSetupLink()),
|
|
10
|
+
directory,
|
|
11
|
+
orderStatus = true,
|
|
12
|
+
setupInvitation = true,
|
|
13
|
+
} = {},
|
|
14
|
+
) {
|
|
15
|
+
const identifier = z.string().min(1).max(200);
|
|
16
|
+
if (directory)
|
|
17
|
+
mcp.registerTool(
|
|
18
|
+
'public_directory',
|
|
19
|
+
{
|
|
20
|
+
description: 'Look up available actions and publicly listed agents and merchants at the owner’s server. An empty integration list means no names are published. Each use of a private detail needs its own authorization.',
|
|
21
|
+
inputSchema: z.strictObject({}),
|
|
22
|
+
annotations: { readOnlyHint: true },
|
|
23
|
+
},
|
|
24
|
+
directory,
|
|
25
|
+
);
|
|
26
|
+
mcp.registerTool(
|
|
27
|
+
'request_use',
|
|
28
|
+
{
|
|
29
|
+
description:
|
|
30
|
+
'When an order needs a shipping address, request its use here. Show review_url so the owner can choose a saved address or add one privately in aSecret. Resume the order only after check_request returns confirmed.',
|
|
31
|
+
inputSchema: z.strictObject({
|
|
32
|
+
recipient: identifier,
|
|
33
|
+
order_id: identifier,
|
|
34
|
+
idempotency_key: identifier,
|
|
35
|
+
reference: z
|
|
36
|
+
.string()
|
|
37
|
+
.regex(/^ref:\/\/detail\/[0-9a-f]{32}$/)
|
|
38
|
+
.optional(),
|
|
39
|
+
}),
|
|
40
|
+
},
|
|
41
|
+
(args) =>
|
|
42
|
+
use((server) =>
|
|
43
|
+
server.requestAddress({
|
|
44
|
+
recipient: args.recipient,
|
|
45
|
+
orderId: args.order_id,
|
|
46
|
+
idempotencyKey: args.idempotency_key,
|
|
47
|
+
reference: args.reference,
|
|
48
|
+
}),
|
|
49
|
+
),
|
|
50
|
+
);
|
|
51
|
+
if (setupInvitation)
|
|
52
|
+
mcp.registerTool(
|
|
53
|
+
'request_setup',
|
|
54
|
+
{
|
|
55
|
+
description:
|
|
56
|
+
'When the owner wants to set up their server, share the review URL. Each detail is optional. Wait for an explicit ready reply through check_request. It grants no access and reveals nothing about what the owner saved.',
|
|
57
|
+
inputSchema: z.strictObject({ idempotency_key: identifier }),
|
|
58
|
+
},
|
|
59
|
+
(args) => use((server) => server.requestSetup({ idempotencyKey: args.idempotency_key })),
|
|
60
|
+
);
|
|
61
|
+
if (orderStatus)
|
|
62
|
+
mcp.registerTool(
|
|
63
|
+
'request_order_status',
|
|
64
|
+
{
|
|
65
|
+
description:
|
|
66
|
+
'Ask the owner to check an order at their connected merchant. Show the review URL. The owner chooses whether to share the order status. Use check_request for the result.',
|
|
67
|
+
inputSchema: z.strictObject({
|
|
68
|
+
recipient: identifier,
|
|
69
|
+
order_id: z
|
|
70
|
+
.string()
|
|
71
|
+
.max(128)
|
|
72
|
+
.regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),
|
|
73
|
+
idempotency_key: identifier,
|
|
74
|
+
}),
|
|
75
|
+
},
|
|
76
|
+
(args) =>
|
|
77
|
+
use((server) =>
|
|
78
|
+
server.requestOrderStatus({
|
|
79
|
+
recipient: args.recipient,
|
|
80
|
+
orderId: args.order_id,
|
|
81
|
+
idempotencyKey: args.idempotency_key,
|
|
82
|
+
}),
|
|
83
|
+
),
|
|
84
|
+
);
|
|
85
|
+
mcp.registerTool(
|
|
86
|
+
'request_save',
|
|
87
|
+
{
|
|
88
|
+
description:
|
|
89
|
+
'Ask the owner to save one private detail. Show review_url. For payment_method, the owner chooses a merchant and enters the card on hosted checkout. Never ask for a card number or a private merchant link. Confirmation grants no permission to use a detail or make a purchase.',
|
|
90
|
+
inputSchema: z.strictObject({
|
|
91
|
+
detail_type: z.enum([...detailTypes, 'payment_method']),
|
|
92
|
+
idempotency_key: identifier,
|
|
93
|
+
}),
|
|
94
|
+
},
|
|
95
|
+
(args) =>
|
|
96
|
+
use((server) =>
|
|
97
|
+
server.requestSave({ detailType: args.detail_type, idempotencyKey: args.idempotency_key }),
|
|
98
|
+
),
|
|
99
|
+
);
|
|
100
|
+
mcp.registerTool(
|
|
101
|
+
'owner_setup_link',
|
|
102
|
+
{
|
|
103
|
+
description:
|
|
104
|
+
'Offer first-time private setup with the owner’s server. Share the public owner_setup_url unchanged and offer Skip for now. Let the owner choose what to save. Wait for their reply before resuming the task. This link has no callback, receipt or permission to use a detail.',
|
|
105
|
+
inputSchema: z.strictObject({}),
|
|
106
|
+
annotations: { readOnlyHint: true },
|
|
107
|
+
},
|
|
108
|
+
setupLink,
|
|
109
|
+
);
|
|
110
|
+
mcp.registerTool(
|
|
111
|
+
'website_form_link',
|
|
112
|
+
{
|
|
113
|
+
description:
|
|
114
|
+
'Get the owner’s public server link for completing a website form. Share it unchanged and explain the recipient and purpose. If id_number is true, explain why the organization needs the ID and let the owner select and approve it in aSecret. Keep ID numbers out of chat. If membership_number is true, the owner can choose a saved membership on a compatible booking form. Keep the number out of chat. If document_upload is true, owners can send saved files from a compatible owner app. Never request file names, attachments or private values in chat. Wait for the owner to tell you the outcome.',
|
|
115
|
+
inputSchema: z.strictObject({}),
|
|
116
|
+
annotations: { readOnlyHint: true },
|
|
117
|
+
},
|
|
118
|
+
formLink,
|
|
119
|
+
);
|
|
120
|
+
for (const [name, method, description] of [
|
|
121
|
+
['check_request', 'status', 'Read the state and approved receipt for a request.'],
|
|
122
|
+
['cancel_request', 'cancel', 'Cancel a pending request before dispatch.'],
|
|
123
|
+
]) {
|
|
124
|
+
mcp.registerTool(
|
|
125
|
+
name,
|
|
126
|
+
{ description, inputSchema: z.strictObject({ request_id: identifier }) },
|
|
127
|
+
(args) => use((server) => server[method](args.request_id)),
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
}
|