@asecret/sdk 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 +21 -0
- package/README.md +28 -2
- package/package.json +22 -4
- package/spec/0.2/messages.schema.json +751 -0
- package/src/agent-crypto.d.ts +31 -0
- package/src/agent-crypto.js +191 -0
- package/src/agent.d.ts +124 -0
- package/src/agent.js +237 -0
- package/src/assistant-instructions.js +64 -0
- package/src/authorization.d.ts +33 -0
- package/src/authorization.js +266 -0
- package/src/wire.js +76 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Types for agent-crypto.js, which the SDK exports as @asecret/sdk/crypto.
|
|
2
|
+
|
|
3
|
+
export function toBase64url(bytes: Uint8Array): string;
|
|
4
|
+
export function fromBase64url(text: string): Uint8Array;
|
|
5
|
+
/** A new random 32-byte key, base64url. */
|
|
6
|
+
export function newKey(): string;
|
|
7
|
+
export function sha256Hex(bytes: Uint8Array): Promise<string>;
|
|
8
|
+
/** A new X25519 key pair, base64url (raw public key, PKCS #8 private key). A person's recovery key is one. */
|
|
9
|
+
export function newReceiveKeys(): Promise<{ public: string; private: string }>;
|
|
10
|
+
/** Seal bytes so only the holder of the private key can open them: how an agent escrows its keys. */
|
|
11
|
+
export function sealToReceiveKey(publicKey: string, bytes: Uint8Array): Promise<string>;
|
|
12
|
+
export function wrapItemKey(agentKey: string, itemKey: Uint8Array): Promise<string>;
|
|
13
|
+
/** The raw key of a stored item, unwrapped with the agent key, or an escrow opened with an X25519 key, as `item.wrap` says. */
|
|
14
|
+
export function itemKeyOf(
|
|
15
|
+
item: { wrap: string; wrapped_key: string },
|
|
16
|
+
keys: { agentKey?: string; receivePrivate?: string; receivePublic?: string },
|
|
17
|
+
): Promise<Uint8Array>;
|
|
18
|
+
export function sealMeta(itemKey: Uint8Array, meta: unknown): Promise<string>;
|
|
19
|
+
export function openMeta(itemKey: Uint8Array, sealedMeta: string): Promise<any>;
|
|
20
|
+
export function sealContent(itemKey: Uint8Array, bytes: Uint8Array): Promise<Uint8Array>;
|
|
21
|
+
export function openContent(itemKey: Uint8Array, sealedBytes: Uint8Array): Promise<Uint8Array>;
|
|
22
|
+
/** A new secret: its own key, wrapped with the agent key, with sealed metadata and value. */
|
|
23
|
+
export function sealItem(
|
|
24
|
+
agentKey: string,
|
|
25
|
+
meta: unknown,
|
|
26
|
+
bytes: Uint8Array,
|
|
27
|
+
): Promise<{ itemKey: Uint8Array; wrap: 'agent'; wrapped_key: string; meta: string; content: Uint8Array }>;
|
|
28
|
+
/** The media type of a framed item upload: application/asecret-item. */
|
|
29
|
+
export const ITEM_TYPE: string;
|
|
30
|
+
export function frameItem(fields: Record<string, unknown>, content: Uint8Array): Uint8Array;
|
|
31
|
+
export function unframeItem(bytes: Uint8Array): { fields: any; content: Uint8Array };
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// Encryption for an agent's secrets. The same file runs in Node and in a browser: it uses only
|
|
2
|
+
// WebCrypto and never touches the network. Every secret gets its own AES-256-GCM key, which the
|
|
3
|
+
// agent key wraps. The X25519 half (a "receive key" pair) seals bytes so only the holder of a
|
|
4
|
+
// private key can open them: an agent's keys, sealed to its person's recovery key (the escrow).
|
|
5
|
+
|
|
6
|
+
const subtle = globalThis.crypto.subtle;
|
|
7
|
+
const encoder = new TextEncoder();
|
|
8
|
+
const decoder = new TextDecoder();
|
|
9
|
+
|
|
10
|
+
const KEY = 'asecret-item-key/1';
|
|
11
|
+
const META = 'asecret-item-meta/1';
|
|
12
|
+
const CONTENT = 'asecret-item-content/1';
|
|
13
|
+
const RECEIVE = 'asecret-receive/1';
|
|
14
|
+
|
|
15
|
+
export function toBase64url(bytes) {
|
|
16
|
+
let binary = '';
|
|
17
|
+
for (let i = 0; i < bytes.length; i += 0x8000)
|
|
18
|
+
binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
|
|
19
|
+
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function fromBase64url(text) {
|
|
23
|
+
if (typeof text !== 'string' || !/^[A-Za-z0-9_-]*$/.test(text)) throw new Error('Damaged encrypted data');
|
|
24
|
+
const binary = atob(text.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - (text.length % 4)) % 4));
|
|
25
|
+
const bytes = new Uint8Array(binary.length);
|
|
26
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
27
|
+
return bytes;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function concat(...parts) {
|
|
31
|
+
const out = new Uint8Array(parts.reduce((n, part) => n + part.length, 0));
|
|
32
|
+
let offset = 0;
|
|
33
|
+
for (const part of parts) {
|
|
34
|
+
out.set(part, offset);
|
|
35
|
+
offset += part.length;
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function randomBytes(length) {
|
|
41
|
+
return globalThis.crypto.getRandomValues(new Uint8Array(length));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A new 256-bit key, as base64url. */
|
|
45
|
+
export function newKey() {
|
|
46
|
+
return toBase64url(randomBytes(32));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function seal(rawKey, bytes, label) {
|
|
50
|
+
const iv = randomBytes(12);
|
|
51
|
+
const key = await subtle.importKey('raw', rawKey, 'AES-GCM', false, ['encrypt']);
|
|
52
|
+
const sealed = new Uint8Array(
|
|
53
|
+
await subtle.encrypt({ name: 'AES-GCM', iv, additionalData: encoder.encode(label) }, key, bytes),
|
|
54
|
+
);
|
|
55
|
+
return concat(iv, sealed);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function open(rawKey, sealed, label) {
|
|
59
|
+
if (!(sealed instanceof Uint8Array) || sealed.length < 28) throw new Error('Damaged encrypted data');
|
|
60
|
+
const key = await subtle.importKey('raw', rawKey, 'AES-GCM', false, ['decrypt']);
|
|
61
|
+
try {
|
|
62
|
+
return new Uint8Array(
|
|
63
|
+
await subtle.decrypt(
|
|
64
|
+
{ name: 'AES-GCM', iv: sealed.subarray(0, 12), additionalData: encoder.encode(label) },
|
|
65
|
+
key,
|
|
66
|
+
sealed.subarray(12),
|
|
67
|
+
),
|
|
68
|
+
);
|
|
69
|
+
} catch {
|
|
70
|
+
throw new Error('This data does not decrypt with this key');
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function sha256Hex(bytes) {
|
|
75
|
+
const hash = new Uint8Array(await subtle.digest('SHA-256', bytes));
|
|
76
|
+
return Array.from(hash, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** An X25519 key pair: the public key is shared, the private key stays here. A person's recovery key is one. */
|
|
80
|
+
export async function newReceiveKeys() {
|
|
81
|
+
const pair = await subtle.generateKey({ name: 'X25519' }, true, ['deriveBits']);
|
|
82
|
+
return {
|
|
83
|
+
public: toBase64url(new Uint8Array(await subtle.exportKey('raw', pair.publicKey))),
|
|
84
|
+
private: toBase64url(new Uint8Array(await subtle.exportKey('pkcs8', pair.privateKey))),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function agreedKey(privateKey, peerRaw, ephemeralRaw, recipientRaw) {
|
|
89
|
+
const peer = await subtle.importKey('raw', peerRaw, { name: 'X25519' }, false, []);
|
|
90
|
+
const bits = await subtle.deriveBits({ name: 'X25519', public: peer }, privateKey, 256);
|
|
91
|
+
const material = await subtle.importKey('raw', bits, 'HKDF', false, ['deriveBits']);
|
|
92
|
+
return new Uint8Array(
|
|
93
|
+
await subtle.deriveBits(
|
|
94
|
+
{ name: 'HKDF', hash: 'SHA-256', salt: concat(ephemeralRaw, recipientRaw), info: encoder.encode(RECEIVE) },
|
|
95
|
+
material,
|
|
96
|
+
256,
|
|
97
|
+
),
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Seal bytes (an item key, or an agent's keys for escrow) so only the holder of the private key can open them. */
|
|
102
|
+
export async function sealToReceiveKey(publicKey, itemKey) {
|
|
103
|
+
const recipient = fromBase64url(publicKey);
|
|
104
|
+
if (recipient.length !== 32) throw new Error('Damaged receive key');
|
|
105
|
+
const ephemeral = await subtle.generateKey({ name: 'X25519' }, true, ['deriveBits']);
|
|
106
|
+
const ephemeralRaw = new Uint8Array(await subtle.exportKey('raw', ephemeral.publicKey));
|
|
107
|
+
const key = await agreedKey(ephemeral.privateKey, recipient, ephemeralRaw, recipient);
|
|
108
|
+
return toBase64url(concat(ephemeralRaw, await seal(key, itemKey, RECEIVE)));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function openFromReceiveKey(envelope, keys) {
|
|
112
|
+
if (!keys.receivePrivate || !keys.receivePublic) throw new Error('This agent has no receive key');
|
|
113
|
+
if (envelope.length < 32 + 28) throw new Error('Damaged encrypted data');
|
|
114
|
+
const ephemeralRaw = envelope.subarray(0, 32);
|
|
115
|
+
const privateKey = await subtle.importKey(
|
|
116
|
+
'pkcs8',
|
|
117
|
+
fromBase64url(keys.receivePrivate),
|
|
118
|
+
{ name: 'X25519' },
|
|
119
|
+
false,
|
|
120
|
+
['deriveBits'],
|
|
121
|
+
);
|
|
122
|
+
const key = await agreedKey(privateKey, ephemeralRaw, ephemeralRaw, fromBase64url(keys.receivePublic));
|
|
123
|
+
return open(key, envelope.subarray(32), RECEIVE);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export async function wrapItemKey(agentKey, itemKey) {
|
|
127
|
+
return toBase64url(await seal(fromBase64url(agentKey), itemKey, KEY));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The raw key of a stored item. `item.wrap` says how it was wrapped: "agent" with the agent key,
|
|
132
|
+
* "receive" to an X25519 key (how an escrow opens). `keys` holds `agentKey`, or `receivePrivate`
|
|
133
|
+
* and `receivePublic`.
|
|
134
|
+
*/
|
|
135
|
+
export async function itemKeyOf(item, keys) {
|
|
136
|
+
const wrapped = fromBase64url(item.wrapped_key);
|
|
137
|
+
if (item.wrap === 'receive') return openFromReceiveKey(wrapped, keys);
|
|
138
|
+
if (item.wrap !== 'agent') throw new Error('Unknown key wrapping');
|
|
139
|
+
return open(fromBase64url(keys.agentKey), wrapped, KEY);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function sealMeta(itemKey, meta) {
|
|
143
|
+
return toBase64url(await seal(itemKey, encoder.encode(JSON.stringify(meta)), META));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function openMeta(itemKey, sealedMeta) {
|
|
147
|
+
return JSON.parse(decoder.decode(await open(itemKey, fromBase64url(sealedMeta), META)));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export async function sealContent(itemKey, bytes) {
|
|
151
|
+
return seal(itemKey, bytes, CONTENT);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export async function openContent(itemKey, sealedBytes) {
|
|
155
|
+
return open(itemKey, sealedBytes, CONTENT);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** A new secret: its own key, wrapped with the agent key, with sealed metadata and value. */
|
|
159
|
+
export async function sealItem(agentKey, meta, bytes) {
|
|
160
|
+
const itemKey = randomBytes(32);
|
|
161
|
+
return {
|
|
162
|
+
itemKey,
|
|
163
|
+
wrap: 'agent',
|
|
164
|
+
wrapped_key: await wrapItemKey(agentKey, itemKey),
|
|
165
|
+
meta: await sealMeta(itemKey, meta),
|
|
166
|
+
content: await sealContent(itemKey, bytes),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* An upload as raw bytes: a 4-byte big-endian length, that many bytes of JSON fields, then the
|
|
172
|
+
* sealed contents. Servers stream the contents without decoding them, which keeps uploads cheap.
|
|
173
|
+
*/
|
|
174
|
+
export const ITEM_TYPE = 'application/asecret-item';
|
|
175
|
+
|
|
176
|
+
export function frameItem(fields, content) {
|
|
177
|
+
const head = encoder.encode(JSON.stringify(fields));
|
|
178
|
+
const out = new Uint8Array(4 + head.length + content.length);
|
|
179
|
+
new DataView(out.buffer).setUint32(0, head.length);
|
|
180
|
+
out.set(head, 4);
|
|
181
|
+
out.set(content, 4 + head.length);
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The fields and contents of a framed upload. */
|
|
186
|
+
export function unframeItem(bytes) {
|
|
187
|
+
if (bytes.length < 4) throw new Error('The upload is too short.');
|
|
188
|
+
const length = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0);
|
|
189
|
+
if (length > 65536 || bytes.length < 4 + length) throw new Error('The upload header is damaged.');
|
|
190
|
+
return { fields: JSON.parse(decoder.decode(bytes.subarray(4, 4 + length))), content: bytes.subarray(4 + length) };
|
|
191
|
+
}
|
package/src/agent.d.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
export type DetailType =
|
|
2
|
+
| 'postal_address' | 'email' | 'phone' | 'membership' | 'secure_note'
|
|
3
|
+
| 'api_key' | 'password' | 'id_number' | 'document';
|
|
4
|
+
|
|
5
|
+
export type SaveType = DetailType | 'payment_method';
|
|
6
|
+
export type OrderStatus = 'pending' | 'processing' | 'shipped' | 'delivered' | 'canceled' | 'unknown';
|
|
7
|
+
|
|
8
|
+
export interface Discovery {
|
|
9
|
+
versions: string[];
|
|
10
|
+
profiles: string[];
|
|
11
|
+
operations: string[];
|
|
12
|
+
api_base: string;
|
|
13
|
+
save_detail_types?: DetailType[];
|
|
14
|
+
owner_setup_url?: string;
|
|
15
|
+
private_form_url?: string;
|
|
16
|
+
server_info_url?: string;
|
|
17
|
+
directory_url?: string;
|
|
18
|
+
mcp_endpoint?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface PublicIntegration {
|
|
22
|
+
kind: 'assistant' | 'merchant';
|
|
23
|
+
id: string;
|
|
24
|
+
name: string;
|
|
25
|
+
operations: string[];
|
|
26
|
+
regions?: string[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface PublicDirectory {
|
|
30
|
+
version: '0.2';
|
|
31
|
+
operations: string[];
|
|
32
|
+
integrations: PublicIntegration[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface WebsiteFormLink {
|
|
36
|
+
private_form_url: string;
|
|
37
|
+
document_upload: boolean;
|
|
38
|
+
membership_number?: true;
|
|
39
|
+
id_number?: true;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface Invitation {
|
|
43
|
+
request_id: string;
|
|
44
|
+
state: 'awaiting_owner';
|
|
45
|
+
review_url: string;
|
|
46
|
+
expires_at: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface RequestState {
|
|
50
|
+
request_id: string;
|
|
51
|
+
state: 'awaiting_owner' | 'authorized' | 'dispatch_committed' | 'outcome_unknown'
|
|
52
|
+
| 'declined' | 'canceled' | 'expired' | 'failed';
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface OperationResults {
|
|
56
|
+
'details.request_setup': { owner_status: 'ready' };
|
|
57
|
+
'details.save': { detail_status: 'saved' };
|
|
58
|
+
'payments.save_method': { detail_status: 'saved' };
|
|
59
|
+
'orders.set_delivery_address': { order_id: string; delivery_address_status: 'accepted' };
|
|
60
|
+
'orders.get_status': { order_id: string; order_status: OrderStatus };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export type Operation = keyof OperationResults;
|
|
64
|
+
type OrderOperation = 'orders.set_delivery_address' | 'orders.get_status';
|
|
65
|
+
|
|
66
|
+
export type ReceiptExpectation =
|
|
67
|
+
| { operation: OrderOperation; orderId: string }
|
|
68
|
+
| { operation: Exclude<Operation, OrderOperation>; orderId?: never };
|
|
69
|
+
|
|
70
|
+
export interface Receipt<O extends Operation = Operation> {
|
|
71
|
+
request_id: string;
|
|
72
|
+
state: 'confirmed';
|
|
73
|
+
receipt_id: string;
|
|
74
|
+
result: OperationResults[O];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export type RequestResponse<O extends Operation = Operation> = Invitation | RequestState | Receipt<O>;
|
|
78
|
+
|
|
79
|
+
interface RequestOptions {
|
|
80
|
+
/** Reuse this key when retrying the same task. */
|
|
81
|
+
idempotencyKey?: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
interface OrderOptions extends RequestOptions {
|
|
85
|
+
recipient: string;
|
|
86
|
+
orderId: string;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
interface ReadRequest {
|
|
90
|
+
<E extends ReceiptExpectation>(id: string, expected: E): Promise<RequestResponse<E['operation']>>;
|
|
91
|
+
(id: string, expected?: ReceiptExpectation): Promise<RequestResponse>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface Agent {
|
|
95
|
+
websiteFormLink(): WebsiteFormLink;
|
|
96
|
+
ownerSetupLink(): { owner_setup_url: string };
|
|
97
|
+
requestSetup(options?: RequestOptions): Promise<RequestResponse<'details.request_setup'>>;
|
|
98
|
+
requestSave(options: RequestOptions & { detailType: SaveType }): Promise<RequestResponse<'details.save'>>;
|
|
99
|
+
requestAddress(options: OrderOptions & { reference?: string }): Promise<RequestResponse<'orders.set_delivery_address'>>;
|
|
100
|
+
requestOrderStatus(options: OrderOptions): Promise<RequestResponse<'orders.get_status'>>;
|
|
101
|
+
/** Supply the original task to validate its confirmed receipt after a restart. */
|
|
102
|
+
status: ReadRequest;
|
|
103
|
+
/** A request already completed when cancellation arrives can return a receipt. */
|
|
104
|
+
cancel: ReadRequest;
|
|
105
|
+
disconnect(id: string): Promise<{ state: 'disconnected' }>;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface FetchOptions {
|
|
109
|
+
fetcher?: typeof fetch;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export class ServerError extends Error {
|
|
113
|
+
constructor(status: number, code: string);
|
|
114
|
+
status: number;
|
|
115
|
+
code: string;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function discover(origin: string, options?: FetchOptions): Promise<Discovery>;
|
|
119
|
+
export function getPublicDirectory(origin: string, options?: FetchOptions): Promise<PublicDirectory>;
|
|
120
|
+
export function privateWebsiteFormLink(origin: string, options?: FetchOptions): Promise<WebsiteFormLink>;
|
|
121
|
+
export function privateOwnerSetupLink(origin: string, options?: FetchOptions): Promise<{ owner_setup_url: string }>;
|
|
122
|
+
export function privateSaveLink(origin: string, detailType: SaveType, options?: FetchOptions): Promise<string>;
|
|
123
|
+
export function assistantInstructions(origin?: string, options?: FetchOptions): Promise<string>;
|
|
124
|
+
export function connectServer(origin: string, options: FetchOptions & { accessToken: string }): Promise<Agent>;
|
package/src/agent.js
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import {
|
|
2
|
+
instructionsForProvider,
|
|
3
|
+
ownerSetupLink,
|
|
4
|
+
saveLinkTypes,
|
|
5
|
+
websiteFormLink,
|
|
6
|
+
} from './assistant-instructions.js';
|
|
7
|
+
import { randomUUID } from 'node:crypto';
|
|
8
|
+
import { check, conforms, httpsURL, readJSON, saveIntent, requestShape } from './wire.js';
|
|
9
|
+
|
|
10
|
+
const operation = 'orders.set_delivery_address';
|
|
11
|
+
const knownErrors = new Set([
|
|
12
|
+
'invalid_request',
|
|
13
|
+
'unsupported_operation',
|
|
14
|
+
'unsupported_version',
|
|
15
|
+
'access_paused',
|
|
16
|
+
'invalid_token',
|
|
17
|
+
'insufficient_scope',
|
|
18
|
+
'not_found',
|
|
19
|
+
'idempotency_conflict',
|
|
20
|
+
'rate_limited',
|
|
21
|
+
'unsupported_recipient',
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
export class ServerError extends Error {
|
|
25
|
+
constructor(status, code) {
|
|
26
|
+
super('Server request failed (' + status + ', ' + code + ')');
|
|
27
|
+
this.status = status;
|
|
28
|
+
this.code = code;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function call(fetcher, url, options = {}) {
|
|
33
|
+
const response = await fetcher(url, {
|
|
34
|
+
...options,
|
|
35
|
+
redirect: 'error',
|
|
36
|
+
credentials: 'omit',
|
|
37
|
+
signal: options.signal ?? AbortSignal.timeout(15000),
|
|
38
|
+
});
|
|
39
|
+
const message = await readJSON(response);
|
|
40
|
+
if (!response.ok) {
|
|
41
|
+
const code =
|
|
42
|
+
conforms('error', message) && knownErrors.has(message.error) ? message.error : 'provider_error';
|
|
43
|
+
throw new ServerError(response.status, code);
|
|
44
|
+
}
|
|
45
|
+
return message;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function discover(origin, { fetcher = fetch } = {}) {
|
|
49
|
+
const url = httpsURL(origin);
|
|
50
|
+
if (url.pathname !== '/' || url.search) throw new Error('Choose a server origin without a path or query');
|
|
51
|
+
const data = check('discovery', await call(fetcher, new URL('/.well-known/asecret', url)));
|
|
52
|
+
const base = httpsURL(data.api_base, url.origin);
|
|
53
|
+
if (base.search) throw new Error('Invalid API base');
|
|
54
|
+
if (!data.versions.includes('0.2') || !data.profiles.includes('agent-http')) {
|
|
55
|
+
throw new Error('Server does not support aSecret 0.2 agent-http');
|
|
56
|
+
}
|
|
57
|
+
const ownerLinks = {};
|
|
58
|
+
for (const field of ['owner_setup_url', 'private_form_url', 'server_info_url', 'directory_url']) {
|
|
59
|
+
if (data[field] === undefined) continue;
|
|
60
|
+
const link = httpsURL(data[field], url.origin);
|
|
61
|
+
if (link.href !== link.origin + link.pathname) throw Error('Invalid owner URL');
|
|
62
|
+
ownerLinks[field] = link.href;
|
|
63
|
+
}
|
|
64
|
+
// Discovery permits extensions. Only expose defined fields to callers.
|
|
65
|
+
return {
|
|
66
|
+
versions: data.versions,
|
|
67
|
+
profiles: data.profiles,
|
|
68
|
+
operations: data.operations,
|
|
69
|
+
api_base: base.href,
|
|
70
|
+
...ownerLinks,
|
|
71
|
+
...(data.save_detail_types ? { save_detail_types: data.save_detail_types } : {}),
|
|
72
|
+
...(data.profiles.includes('mcp-http') && typeof data.mcp_endpoint === 'string'
|
|
73
|
+
? { mcp_endpoint: httpsURL(data.mcp_endpoint, url.origin).href }
|
|
74
|
+
: {}),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function getPublicDirectory(origin, options = {}) {
|
|
79
|
+
const info = await discover(origin, options);
|
|
80
|
+
if (!info.directory_url) throw Error('This server does not publish a directory');
|
|
81
|
+
const directory = check('publicDirectory', await call(options.fetcher ?? fetch, info.directory_url));
|
|
82
|
+
if (directory.operations.some((op) => !info.operations.includes(op)))
|
|
83
|
+
throw Error('The directory includes an operation missing from discovery');
|
|
84
|
+
const seen = new Set();
|
|
85
|
+
for (const entry of directory.integrations) {
|
|
86
|
+
const key = JSON.stringify([entry.kind, entry.id]);
|
|
87
|
+
if (seen.has(key) || entry.operations.some((op) => !directory.operations.includes(op)))
|
|
88
|
+
throw Error('Invalid public integration listing');
|
|
89
|
+
seen.add(key);
|
|
90
|
+
}
|
|
91
|
+
return directory;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function resourceId(id) {
|
|
95
|
+
if (typeof id !== 'string' || !id || id === '.' || id === '..') throw new Error('Invalid resource ID');
|
|
96
|
+
return encodeURIComponent(id);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const receiptShapes = new Map([
|
|
100
|
+
['orders.set_delivery_address', 'addressConfirmed'],
|
|
101
|
+
['orders.get_status', 'orderStatusConfirmed'],
|
|
102
|
+
['details.save', 'saveConfirmed'],
|
|
103
|
+
['payments.save_method', 'saveConfirmed'],
|
|
104
|
+
['details.request_setup', 'setupConfirmed'],
|
|
105
|
+
]);
|
|
106
|
+
const confirmedShapes = [...new Set(receiptShapes.values())];
|
|
107
|
+
|
|
108
|
+
function expectedReceipt(expected) {
|
|
109
|
+
if (expected === undefined) return;
|
|
110
|
+
const shape = receiptShapes.get(expected?.operation);
|
|
111
|
+
if (!shape) throw Error('Unknown receipt operation');
|
|
112
|
+
const orderId = expected.orderId;
|
|
113
|
+
if (shape === 'addressConfirmed' || shape === 'orderStatusConfirmed') {
|
|
114
|
+
if (typeof orderId !== 'string' || !orderId.length) throw Error('Expected the original order identifier');
|
|
115
|
+
} else if (orderId !== undefined) {
|
|
116
|
+
throw Error('This operation has no order identifier');
|
|
117
|
+
}
|
|
118
|
+
return { shape, orderId };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export async function privateWebsiteFormLink(origin, options) {
|
|
122
|
+
return websiteFormLink(await discover(origin, options));
|
|
123
|
+
}
|
|
124
|
+
export async function privateOwnerSetupLink(origin, options) {
|
|
125
|
+
return ownerSetupLink(await discover(origin, options));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export async function privateSaveLink(origin, detailType, options) {
|
|
129
|
+
if (!saveLinkTypes(await discover(origin, options)).includes(detailType))
|
|
130
|
+
throw new Error('This server does not offer a private save link for that type');
|
|
131
|
+
return new URL('/save/' + detailType, origin).href;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export async function assistantInstructions(origin, options) {
|
|
135
|
+
return instructionsForProvider(
|
|
136
|
+
origin,
|
|
137
|
+
origin === undefined ? undefined : await discover(origin, options),
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export async function connectServer(origin, { accessToken, fetcher = fetch } = {}) {
|
|
142
|
+
const info = await discover(origin, { fetcher });
|
|
143
|
+
if (typeof accessToken !== 'string' || !accessToken.trim())
|
|
144
|
+
throw new Error('Connection access token required');
|
|
145
|
+
const base = info.api_base.replace(/\/$/, '');
|
|
146
|
+
async function send(path, method, { body, idempotencyKey } = {}) {
|
|
147
|
+
const headers = { authorization: 'Bearer ' + accessToken, 'asecret-version': '0.2' };
|
|
148
|
+
if (body) headers['content-type'] = 'application/json';
|
|
149
|
+
if (idempotencyKey) headers['idempotency-key'] = idempotencyKey;
|
|
150
|
+
return call(fetcher, base + path, { method, headers, body: body ? JSON.stringify(body) : undefined });
|
|
151
|
+
}
|
|
152
|
+
function resource(value, expectedId, receipt) {
|
|
153
|
+
if (Object.hasOwn(value ?? {}, 'review_url')) {
|
|
154
|
+
check('created', value);
|
|
155
|
+
httpsURL(value.review_url, new URL(origin).origin);
|
|
156
|
+
} else if (value?.state === 'confirmed') {
|
|
157
|
+
if (receipt) {
|
|
158
|
+
check(receipt.shape, value);
|
|
159
|
+
if (receipt.orderId !== undefined && value.result.order_id !== receipt.orderId)
|
|
160
|
+
throw Error('Unexpected order identifier');
|
|
161
|
+
} else if (!confirmedShapes.some((shape) => conforms(shape, value))) {
|
|
162
|
+
throw Error('Invalid aSecret message: confirmed receipt');
|
|
163
|
+
}
|
|
164
|
+
} else {
|
|
165
|
+
check('stateOnly', value);
|
|
166
|
+
}
|
|
167
|
+
if (expectedId && value.request_id !== expectedId) throw new Error('Unexpected request identifier');
|
|
168
|
+
return value;
|
|
169
|
+
}
|
|
170
|
+
async function create(body, idempotencyKey) {
|
|
171
|
+
if (typeof idempotencyKey !== 'string' || !idempotencyKey.trim())
|
|
172
|
+
throw Error('Expected an idempotency key');
|
|
173
|
+
const receipt = expectedReceipt({ operation: body.operation, orderId: body.order_id });
|
|
174
|
+
return resource(await send('/requests', 'POST', { body, idempotencyKey }), undefined, receipt);
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
websiteFormLink: () => websiteFormLink(info),
|
|
178
|
+
ownerSetupLink: () => ownerSetupLink(info),
|
|
179
|
+
async requestSetup({ idempotencyKey = randomUUID() } = {}) {
|
|
180
|
+
if (!info.profiles.includes('setup-invitation') || !info.operations.includes('details.request_setup'))
|
|
181
|
+
throw Error('This server does not support paired setup invitations');
|
|
182
|
+
return create({ operation: 'details.request_setup' }, idempotencyKey);
|
|
183
|
+
},
|
|
184
|
+
async requestSave({ detailType, idempotencyKey = randomUUID() }) {
|
|
185
|
+
const intent = saveIntent(detailType),
|
|
186
|
+
payment = detailType === 'payment_method';
|
|
187
|
+
if (
|
|
188
|
+
!info.profiles.includes(payment ? 'payment-method-setup' : 'save-detail') ||
|
|
189
|
+
!info.operations.includes(intent.operation)
|
|
190
|
+
)
|
|
191
|
+
throw new Error('Server does not support this private save invitation');
|
|
192
|
+
if (!payment && !info.save_detail_types?.includes(detailType))
|
|
193
|
+
throw new Error('This server does not support saving the requested detail type');
|
|
194
|
+
const body = check(requestShape(intent.operation), intent);
|
|
195
|
+
return create(body, idempotencyKey);
|
|
196
|
+
},
|
|
197
|
+
async requestOrderStatus({ recipient, orderId, idempotencyKey = randomUUID() }) {
|
|
198
|
+
if (!info.profiles.includes('order-status') || !info.operations.includes('orders.get_status'))
|
|
199
|
+
throw new Error('Server does not support order status requests');
|
|
200
|
+
const body = check('orderStatusRequest', {
|
|
201
|
+
operation: 'orders.get_status',
|
|
202
|
+
recipient,
|
|
203
|
+
order_id: orderId,
|
|
204
|
+
});
|
|
205
|
+
return create(body, idempotencyKey);
|
|
206
|
+
},
|
|
207
|
+
async requestAddress({ recipient, orderId, reference, idempotencyKey = randomUUID() }) {
|
|
208
|
+
if (!info.profiles.includes('delivery-address') || !info.operations.includes(operation)) {
|
|
209
|
+
throw new Error('Server does not support delivery addresses');
|
|
210
|
+
}
|
|
211
|
+
if (reference !== undefined && !info.profiles.includes('detail-reference'))
|
|
212
|
+
throw new Error('Server does not support detail references');
|
|
213
|
+
const body = check('addressRequest', {
|
|
214
|
+
...(reference === undefined ? {} : { reference }),
|
|
215
|
+
operation,
|
|
216
|
+
recipient,
|
|
217
|
+
order_id: orderId,
|
|
218
|
+
requested_fields: ['postal_address'],
|
|
219
|
+
});
|
|
220
|
+
return create(body, idempotencyKey);
|
|
221
|
+
},
|
|
222
|
+
async status(id, expected) {
|
|
223
|
+
const receipt = expectedReceipt(expected);
|
|
224
|
+
return resource(await send('/requests/' + resourceId(id), 'GET'), id, receipt);
|
|
225
|
+
},
|
|
226
|
+
async cancel(id, expected) {
|
|
227
|
+
const receipt = expectedReceipt(expected);
|
|
228
|
+
return resource(await send('/requests/' + resourceId(id) + '/cancel', 'POST'), id, receipt);
|
|
229
|
+
},
|
|
230
|
+
async disconnect(id) {
|
|
231
|
+
const result = await send('/connections/' + resourceId(id) + '/disconnect', 'POST');
|
|
232
|
+
if (result?.state !== 'disconnected' || Object.keys(result).length !== 1)
|
|
233
|
+
throw new Error('Invalid disconnect response');
|
|
234
|
+
return { state: 'disconnected' };
|
|
235
|
+
},
|
|
236
|
+
};
|
|
237
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export function ownerSetupLink(discovery) {
|
|
2
|
+
if (!discovery.owner_setup_url) throw Error('This server has no public setup link.');
|
|
3
|
+
return { owner_setup_url: discovery.owner_setup_url };
|
|
4
|
+
}
|
|
5
|
+
export function websiteFormLink(discovery) {
|
|
6
|
+
if (!discovery.private_form_url) throw Error('This server has no private website form link.');
|
|
7
|
+
return {
|
|
8
|
+
private_form_url: discovery.private_form_url,
|
|
9
|
+
document_upload: discovery.profiles.includes('document-upload-form'),
|
|
10
|
+
...(discovery.profiles.includes('id-number-form') ? { id_number: true } : {}),
|
|
11
|
+
...(discovery.profiles.includes('membership-form') ? { membership_number: true } : {}),
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export function saveLinkTypes(info) {
|
|
15
|
+
if (!info.profiles.includes('private-save-link')) return [];
|
|
16
|
+
const types = [...(info.save_detail_types ?? [])];
|
|
17
|
+
if (info.profiles.includes('payment-method-setup') && info.operations.includes('payments.save_method'))
|
|
18
|
+
types.push('payment_method');
|
|
19
|
+
return types;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function instructionsForProvider(origin, discovery) {
|
|
23
|
+
if (origin === undefined)
|
|
24
|
+
return [
|
|
25
|
+
'If I want to set up several details, invite me to open My details and choose Set up private details. Let me skip and continue our conversation.',
|
|
26
|
+
'When a task needs a private detail, ask whether I want to save it in aSecret. Tell me which detail the task needs and why. I can open aSecret on my phone or computer, choose My details and add the detail.',
|
|
27
|
+
'Keep private values, documents, recovery keys and merchant setup links out of our chat. Wait for me to tell you when I am done. Saving a detail gives no permission to send it, log into an account or make a purchase.',
|
|
28
|
+
'If you need to use a detail, ask me to complete the step privately or show me a separate approval from a server tool I have connected. If I decline, stop that step.',
|
|
29
|
+
].join('\n\n');
|
|
30
|
+
const types = saveLinkTypes(discovery);
|
|
31
|
+
if (!types.length && !discovery.private_form_url && !discovery.owner_setup_url)
|
|
32
|
+
throw Error('This server does not offer private chat links. Check its agent connection options.');
|
|
33
|
+
const base = new URL(origin).origin;
|
|
34
|
+
const links = types.map((type) => new URL('/save/' + type, base).href);
|
|
35
|
+
return [
|
|
36
|
+
'Use ' +
|
|
37
|
+
base +
|
|
38
|
+
' as my aSecret server. When a task needs a private detail, ask whether I want to save it there. Keep private values, documents, recovery keys and merchant setup links out of our chat.',
|
|
39
|
+
'If you have a paired aSecret tool for the task, show me its review link and wait for its result. Ask only for details needed for this task.',
|
|
40
|
+
discovery.profiles.includes('setup-invitation') &&
|
|
41
|
+
discovery.operations.includes('details.request_setup') &&
|
|
42
|
+
'If we are paired and I choose general setup, use request_setup when available. I can send a ready reply even if I save nothing. Wait for that reply or for me to continue in chat.',
|
|
43
|
+
discovery.owner_setup_url &&
|
|
44
|
+
'For first-time setup, offer this link unchanged and give me the option to skip. I choose what to save and tell you when I’m ready.\n' +
|
|
45
|
+
discovery.owner_setup_url,
|
|
46
|
+
links.length > 0 &&
|
|
47
|
+
'To save a detail privately, send its matching link in this chat and tell me why the task needs it. I can add or edit the detail in my browser and return here with a ready reply. Wait for my reply before continuing.',
|
|
48
|
+
links.join('\n'),
|
|
49
|
+
discovery.private_form_url && discovery.profiles.includes('id-number-form') &&
|
|
50
|
+
'If a website needs an ID number, tell me which organization needs it and why. Let me choose my ID and review the full number and destination in aSecret. Keep the number out of chat.',
|
|
51
|
+
discovery.private_form_url &&
|
|
52
|
+
discovery.profiles.includes('membership-form') &&
|
|
53
|
+
'If a booking needs a membership number, ask me to choose the membership in aSecret and review the booking website. Keep the number out of chat.',
|
|
54
|
+
discovery.private_form_url &&
|
|
55
|
+
discovery.profiles.includes('document-upload-form') &&
|
|
56
|
+
'If a website needs a document, ask me to choose and send it from aSecret. Keep file names and attachments out of this chat.',
|
|
57
|
+
discovery.private_form_url &&
|
|
58
|
+
'For a website form, tell me the website and why it needs the fields. I choose the form in aSecret and decide whether to send it. Wait for me to tell you the outcome. Offer this link unchanged.\n' +
|
|
59
|
+
discovery.private_form_url,
|
|
60
|
+
'Saving a detail gives no permission to send it, log into an account or make a purchase. If I decline or the server cannot do the next step, leave that step pending.',
|
|
61
|
+
]
|
|
62
|
+
.filter(Boolean)
|
|
63
|
+
.join('\n\n');
|
|
64
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { FetchOptions } from './agent.js';
|
|
2
|
+
|
|
3
|
+
export interface AgentGrant {
|
|
4
|
+
origin: string;
|
|
5
|
+
clientId: string;
|
|
6
|
+
connectionId: string;
|
|
7
|
+
accessToken: string;
|
|
8
|
+
expiresAt: number;
|
|
9
|
+
refreshToken?: string;
|
|
10
|
+
resource?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface Pairing {
|
|
14
|
+
authorizationURL: string;
|
|
15
|
+
/** Finish once, in the host session where the owner started this flow. */
|
|
16
|
+
finish(callbackAddress: string): Promise<AgentGrant>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface PairingOptions extends FetchOptions {
|
|
20
|
+
redirectUri: string;
|
|
21
|
+
persistent?: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function validateAgentName(name: string): string;
|
|
25
|
+
export function registerAgentClient(origin: string, options: PairingOptions & { name: string }): Promise<string>;
|
|
26
|
+
export function beginAgentConnection(
|
|
27
|
+
origin: string,
|
|
28
|
+
options: PairingOptions & { clientId: string; resource?: string },
|
|
29
|
+
): Promise<Pairing>;
|
|
30
|
+
export function renewAgentConnection(
|
|
31
|
+
grant: AgentGrant,
|
|
32
|
+
options?: FetchOptions & { beforeExchange?: () => void | Promise<void> },
|
|
33
|
+
): Promise<AgentGrant & { refreshToken: string }>;
|