@useopentab/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/LICENSE +202 -0
- package/README.md +147 -2
- package/dist/bin.js +361 -0
- package/dist/chunks/chunk-4R3NAR3C.js +28 -0
- package/dist/chunks/chunk-D3C7KAMJ.js +2221 -0
- package/dist/chunks/chunk-EKJH2AJS.js +371 -0
- package/dist/chunks/chunk-GOEFQ62Z.js +53 -0
- package/dist/chunks/chunk-HTU7QRDF.js +223 -0
- package/dist/chunks/chunk-HZHOKJIM.js +360 -0
- package/dist/chunks/chunk-IRXOU25X.js +1856 -0
- package/dist/chunks/chunk-MOZ4BFSB.js +13 -0
- package/dist/chunks/chunk-Q776JIO3.js +1821 -0
- package/dist/chunks/chunk-QTI2WM44.js +68 -0
- package/dist/chunks/chunk-S5IAH7CT.js +84 -0
- package/dist/chunks/config-OPZLVTYX.js +73 -0
- package/dist/chunks/gate-53O3YCXE.js +74 -0
- package/dist/chunks/indexer-OLIWEEFT.js +491 -0
- package/dist/chunks/init-JSZX6AF5.js +176 -0
- package/dist/chunks/line-2QBTLAUN.js +95 -0
- package/dist/chunks/liveNode-SLQN4XRB.js +299 -0
- package/dist/chunks/liveOnboard-Z4GRTSHR.js +400 -0
- package/dist/chunks/liveSettle-V5W7D2U5.js +1398 -0
- package/dist/chunks/notary-PQDSEOVV.js +122 -0
- package/dist/chunks/onboardError-RLJPEEFU.js +10 -0
- package/dist/chunks/src-RIOYQO2J.js +556 -0
- package/dist/chunks/tab-QPO2545T.js +59 -0
- package/dist/chunks/verify-Z7BGKZOB.js +719 -0
- package/package.json +66 -3
|
@@ -0,0 +1,1856 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ByteReader,
|
|
3
|
+
ByteWriter,
|
|
4
|
+
accountCaip10,
|
|
5
|
+
accountFromBase58,
|
|
6
|
+
accountToBase58,
|
|
7
|
+
agentBadge,
|
|
8
|
+
bytesEqual as bytesEqual2,
|
|
9
|
+
concatBytes,
|
|
10
|
+
contractCaip,
|
|
11
|
+
fromHex as fromHex2,
|
|
12
|
+
isAccountAddress,
|
|
13
|
+
toHex as toHex2,
|
|
14
|
+
toU64
|
|
15
|
+
} from "./chunk-HZHOKJIM.js";
|
|
16
|
+
import {
|
|
17
|
+
BADGE_EXTENSION_URI,
|
|
18
|
+
CIS8,
|
|
19
|
+
CIS8004,
|
|
20
|
+
HOSTED_REST_BASE,
|
|
21
|
+
TESTNET_CAIP2
|
|
22
|
+
} from "./chunk-S5IAH7CT.js";
|
|
23
|
+
import {
|
|
24
|
+
ATTESTOR_KEY_NAMESPACE,
|
|
25
|
+
CloseAckV1Codec,
|
|
26
|
+
CloseVoucherV1Codec,
|
|
27
|
+
CodecError,
|
|
28
|
+
ConsentAttestationV1Codec,
|
|
29
|
+
ED25519_SEED_LENGTH,
|
|
30
|
+
MAX_LANES,
|
|
31
|
+
ReceiptV1Codec,
|
|
32
|
+
ReportV1Codec,
|
|
33
|
+
SESSION_KEY_NAMESPACE,
|
|
34
|
+
SET_AGENT_WALLET_MESSAGE_LENGTH,
|
|
35
|
+
TabAgreementV1Codec,
|
|
36
|
+
U64_MAX,
|
|
37
|
+
VoucherV1Codec,
|
|
38
|
+
Writer,
|
|
39
|
+
acceptSigningBytes,
|
|
40
|
+
accountAddressFromBase58,
|
|
41
|
+
ascii,
|
|
42
|
+
bytesEqual,
|
|
43
|
+
contractAddress,
|
|
44
|
+
ed25519KeyId,
|
|
45
|
+
ed25519PublicKey,
|
|
46
|
+
ed25519Sign,
|
|
47
|
+
ed25519Verify,
|
|
48
|
+
encodeSetAgentWalletParams,
|
|
49
|
+
fromHex,
|
|
50
|
+
fromUtf8,
|
|
51
|
+
helloSigningBytes,
|
|
52
|
+
sessionKeyHash,
|
|
53
|
+
setAgentWalletMessage,
|
|
54
|
+
singleKeyAccountSignatures,
|
|
55
|
+
toHex,
|
|
56
|
+
utf8,
|
|
57
|
+
zeroHash
|
|
58
|
+
} from "./chunk-D3C7KAMJ.js";
|
|
59
|
+
|
|
60
|
+
// packages/keyd/src/rpc/client.ts
|
|
61
|
+
import net from "node:net";
|
|
62
|
+
|
|
63
|
+
// packages/keyd/src/errors.ts
|
|
64
|
+
var KEYD_ERROR_CODES = [
|
|
65
|
+
// request shape
|
|
66
|
+
"invalid_params",
|
|
67
|
+
"invalid_message",
|
|
68
|
+
"unknown_key",
|
|
69
|
+
"role_forbidden",
|
|
70
|
+
"ci_key_misuse",
|
|
71
|
+
// message context
|
|
72
|
+
"wrong_network",
|
|
73
|
+
"wrong_bureau",
|
|
74
|
+
"clock_skew",
|
|
75
|
+
"expired",
|
|
76
|
+
// voucher and close policy
|
|
77
|
+
"tab_unknown",
|
|
78
|
+
"lane_out_of_range",
|
|
79
|
+
"lane_unsynced",
|
|
80
|
+
"seq_not_next",
|
|
81
|
+
"acked_mismatch",
|
|
82
|
+
"prev_receipt_mismatch",
|
|
83
|
+
"over_tab_limit",
|
|
84
|
+
"over_cycle_budget",
|
|
85
|
+
"over_price_cap",
|
|
86
|
+
"over_limit_cap",
|
|
87
|
+
"cycle_closed",
|
|
88
|
+
"cycle_out_of_range",
|
|
89
|
+
"close_mismatch",
|
|
90
|
+
"close_incomplete",
|
|
91
|
+
"close_total_mismatch",
|
|
92
|
+
// resync
|
|
93
|
+
"receipt_bad_signature",
|
|
94
|
+
"receipt_mismatch",
|
|
95
|
+
"stale_receipt",
|
|
96
|
+
// durability and files
|
|
97
|
+
"persist_failed",
|
|
98
|
+
"audit_failed",
|
|
99
|
+
"state_corrupt",
|
|
100
|
+
"audit_corrupt",
|
|
101
|
+
"key_file_invalid",
|
|
102
|
+
"insecure_permissions",
|
|
103
|
+
// transport
|
|
104
|
+
"message_too_large",
|
|
105
|
+
"too_many_requests",
|
|
106
|
+
"unavailable",
|
|
107
|
+
"internal"
|
|
108
|
+
];
|
|
109
|
+
var CODES = new Set(KEYD_ERROR_CODES);
|
|
110
|
+
function isKeydErrorCode(code) {
|
|
111
|
+
return typeof code === "string" && CODES.has(code);
|
|
112
|
+
}
|
|
113
|
+
var KeydError = class extends Error {
|
|
114
|
+
code;
|
|
115
|
+
constructor(code, message) {
|
|
116
|
+
super(message);
|
|
117
|
+
this.name = "KeydError";
|
|
118
|
+
this.code = code;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
// packages/keyd/src/drpRequest.ts
|
|
123
|
+
var DRP_REQUEST_TAG = "CCD-TAB/v1/drp";
|
|
124
|
+
var TAG = ascii(DRP_REQUEST_TAG);
|
|
125
|
+
var DRP_NONCE_LENGTH = 16;
|
|
126
|
+
var DRP_REQUEST_SIZE = TAG.length + 32 + 16 + 8 + 32 + DRP_NONCE_LENGTH + 8;
|
|
127
|
+
function encodeDrpRequestV1(r) {
|
|
128
|
+
return new Writer().raw(TAG).fixed(r.genesis, 32, "genesis").u64(r.bureau.index, "bureau index").u64(r.bureau.subindex, "bureau subindex").u64(r.sellerToken, "seller_token").fixed(r.bodyHash, 32, "body_hash").fixed(r.nonce, DRP_NONCE_LENGTH, "nonce").u64(r.issuedAt, "issued_at").toBytes();
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// packages/keyd/src/signers.ts
|
|
132
|
+
function keyIdFromInfo(info) {
|
|
133
|
+
return { namespace: info.keyId.namespace, keyType: info.keyId.keyType, publicKey: fromHex(info.keyId.publicKey, 32) };
|
|
134
|
+
}
|
|
135
|
+
function identityOf(backend, name) {
|
|
136
|
+
let cached;
|
|
137
|
+
const info = () => {
|
|
138
|
+
cached ??= backend.identity(name).catch((err) => {
|
|
139
|
+
cached = void 0;
|
|
140
|
+
throw err;
|
|
141
|
+
});
|
|
142
|
+
return cached;
|
|
143
|
+
};
|
|
144
|
+
return {
|
|
145
|
+
keyId: async () => keyIdFromInfo(await info()),
|
|
146
|
+
publicKey: async () => fromHex((await info()).publicKey, 32)
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
function bindBuyer(backend, name) {
|
|
150
|
+
return {
|
|
151
|
+
...identityOf(backend, name),
|
|
152
|
+
signHello: (hello) => backend.signHello(name, hello),
|
|
153
|
+
signAgreement: (agreement) => backend.signAgreement(name, agreement),
|
|
154
|
+
signVoucher: (voucher, policy) => backend.signVoucher(name, voucher, policy),
|
|
155
|
+
signClose: (close) => backend.signClose(name, close),
|
|
156
|
+
signStatusRequest: (request2) => backend.signStatusRequest(name, request2),
|
|
157
|
+
resyncLane: (receipt, signature) => backend.resyncLane(name, receipt, signature)
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
function bindSeller(backend, name) {
|
|
161
|
+
return {
|
|
162
|
+
...identityOf(backend, name),
|
|
163
|
+
signAccept: (accept) => backend.signAccept(name, accept),
|
|
164
|
+
signAgreement: (agreement) => backend.signAgreement(name, agreement),
|
|
165
|
+
signReceipt: (receipt) => backend.signReceipt(name, receipt),
|
|
166
|
+
signCloseAck: (ack) => backend.signCloseAck(name, ack),
|
|
167
|
+
signReport: (report) => backend.signReport(name, report),
|
|
168
|
+
signDrpRequest: (request2) => backend.signDrpRequest(name, request2)
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function bindAttestor(backend, name) {
|
|
172
|
+
return {
|
|
173
|
+
...identityOf(backend, name),
|
|
174
|
+
signAttestation: (attestation) => backend.signAttestation(name, attestation)
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// packages/keyd/src/statusRequest.ts
|
|
179
|
+
var TAB_STATUS_REQUEST_TAG = "CCD-TAB/v1/status";
|
|
180
|
+
var TAG2 = utf8(TAB_STATUS_REQUEST_TAG);
|
|
181
|
+
var TAB_STATUS_REQUEST_SIZE = TAG2.length + 32 + 16 + 8 + 8;
|
|
182
|
+
var TAB_AUTH_HEADER = "CCD-TAB-AUTH";
|
|
183
|
+
var U64_MAX2 = (1n << 64n) - 1n;
|
|
184
|
+
function u64(value, what) {
|
|
185
|
+
if (typeof value !== "bigint" || value < 0n || value > U64_MAX2) throw new CodecError(`${what} is not a u64`);
|
|
186
|
+
return value;
|
|
187
|
+
}
|
|
188
|
+
function encodeTabStatusRequestV1(r) {
|
|
189
|
+
if (!(r.genesis instanceof Uint8Array) || r.genesis.length !== 32) throw new CodecError("genesis must be 32 bytes");
|
|
190
|
+
const out = new Uint8Array(TAB_STATUS_REQUEST_SIZE);
|
|
191
|
+
const view = new DataView(out.buffer);
|
|
192
|
+
out.set(TAG2, 0);
|
|
193
|
+
out.set(r.genesis, TAG2.length);
|
|
194
|
+
let at = TAG2.length + 32;
|
|
195
|
+
for (const [value, what] of [
|
|
196
|
+
[r.bureau.index, "bureau index"],
|
|
197
|
+
[r.bureau.subindex, "bureau subindex"],
|
|
198
|
+
[r.tabId, "tab_id"],
|
|
199
|
+
[r.issuedAt, "issued_at"]
|
|
200
|
+
]) {
|
|
201
|
+
view.setBigUint64(at, u64(value, what), true);
|
|
202
|
+
at += 8;
|
|
203
|
+
}
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
function encodeTabAuthHeader(request2, signature) {
|
|
207
|
+
return `${toHex(request2)}.${toHex(signature)}`;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// packages/keyd/src/rpc/protocol.ts
|
|
211
|
+
import { z as z3 } from "zod";
|
|
212
|
+
|
|
213
|
+
// packages/keyd/src/roles.ts
|
|
214
|
+
var KEY_ROLES = ["buyer", "seller", "attestor", "ci-attestor"];
|
|
215
|
+
function namespaceForRole(role) {
|
|
216
|
+
return role === "buyer" || role === "seller" ? SESSION_KEY_NAMESPACE : ATTESTOR_KEY_NAMESPACE;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// packages/keyd/src/keys/secret.ts
|
|
220
|
+
import { inspect } from "node:util";
|
|
221
|
+
var Ed25519Secret = class {
|
|
222
|
+
#seed;
|
|
223
|
+
/** 32-byte public key. */
|
|
224
|
+
publicKey;
|
|
225
|
+
/** Copies `seed` (32 bytes); the caller may wipe its own copy afterwards. */
|
|
226
|
+
constructor(seed) {
|
|
227
|
+
if (!(seed instanceof Uint8Array) || seed.length !== ED25519_SEED_LENGTH) {
|
|
228
|
+
throw new KeydError("key_file_invalid", `an ed25519 seed must be ${ED25519_SEED_LENGTH} bytes`);
|
|
229
|
+
}
|
|
230
|
+
this.#seed = Uint8Array.from(seed);
|
|
231
|
+
this.publicKey = ed25519PublicKey(this.#seed);
|
|
232
|
+
}
|
|
233
|
+
/** Raw ed25519 over `message`. Only keyd's typed signing paths call this. */
|
|
234
|
+
sign(message) {
|
|
235
|
+
return ed25519Sign(message, this.#seed);
|
|
236
|
+
}
|
|
237
|
+
/** A copy of the seed, for writing a key file. Never log or transmit it. */
|
|
238
|
+
exportSeed() {
|
|
239
|
+
return Uint8Array.from(this.#seed);
|
|
240
|
+
}
|
|
241
|
+
/** Overwrites the seed in memory (best effort; JS cannot guarantee no other copies exist). */
|
|
242
|
+
destroy() {
|
|
243
|
+
this.#seed.fill(0);
|
|
244
|
+
}
|
|
245
|
+
toJSON() {
|
|
246
|
+
return { publicKey: toHex(this.publicKey) };
|
|
247
|
+
}
|
|
248
|
+
[inspect.custom]() {
|
|
249
|
+
return `Ed25519Secret(${toHex(this.publicKey)})`;
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
// packages/keyd/src/keys/key.ts
|
|
254
|
+
var KEY_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
255
|
+
function assertKeyName(name) {
|
|
256
|
+
if (!KEY_NAME_RE.test(name)) {
|
|
257
|
+
throw new KeydError("invalid_params", `key name ${JSON.stringify(name)} must match ${KEY_NAME_RE.source}`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
function keyFromSeed(name, role, seed) {
|
|
261
|
+
assertKeyName(name);
|
|
262
|
+
const secret = new Ed25519Secret(seed);
|
|
263
|
+
const keyId = ed25519KeyId(secret.publicKey, namespaceForRole(role));
|
|
264
|
+
return { name, role, secret, keyId, keyIdHash: sessionKeyHash(keyId) };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// packages/keyd/src/validate.ts
|
|
268
|
+
import { z } from "zod";
|
|
269
|
+
var u64Decimal = z.string().regex(/^(0|[1-9][0-9]{0,19})$/).refine((s) => BigInt(s) < 1n << 64n, "out of u64 range");
|
|
270
|
+
var hexOf = (bytes) => z.string().regex(new RegExp(`^[0-9a-f]{${bytes * 2}}$`));
|
|
271
|
+
var unixSeconds = z.number().int().min(0).max(2 ** 40);
|
|
272
|
+
var helloSchema = z.strictObject({
|
|
273
|
+
iss: z.strictObject({ badge: z.string().min(1).max(256), lineId: u64Decimal, sessionKey: hexOf(32) }),
|
|
274
|
+
aud: z.strictObject({ badge: z.string().min(1).max(256), url: z.string().min(1).max(2048) }),
|
|
275
|
+
terms: z.strictObject({
|
|
276
|
+
limit: u64Decimal,
|
|
277
|
+
cycleMs: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
|
|
278
|
+
maxLanes: z.number().int().min(1).max(MAX_LANES)
|
|
279
|
+
}),
|
|
280
|
+
nonce: z.string().min(8).max(128),
|
|
281
|
+
iat: unixSeconds,
|
|
282
|
+
exp: unixSeconds
|
|
283
|
+
});
|
|
284
|
+
var acceptSchema = z.strictObject({
|
|
285
|
+
helloHash: hexOf(32),
|
|
286
|
+
agreement: z.string().regex(/^(?:[0-9a-f]{2}){1,1024}$/),
|
|
287
|
+
sellerSig: hexOf(64),
|
|
288
|
+
iat: unixSeconds
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
// packages/keyd/src/rpc/wire.ts
|
|
292
|
+
import { z as z2 } from "zod";
|
|
293
|
+
var u64Wire = z2.string().regex(/^(0|[1-9][0-9]{0,19})$/, "expected a u64 decimal string").transform((s) => BigInt(s)).refine((v) => v <= U64_MAX, "out of u64 range");
|
|
294
|
+
var bytesWire = (length) => z2.string().regex(new RegExp(`^[0-9a-f]{${length * 2}}$`), `expected ${length} bytes of lowercase hex`).transform((s) => fromHex(s, length));
|
|
295
|
+
var uint = (max) => z2.number().int().min(0).max(max);
|
|
296
|
+
var contractWire = z2.strictObject({ index: u64Wire, subindex: u64Wire }).transform((c) => contractAddress(c.index, c.subindex));
|
|
297
|
+
var laneStateWire = z2.strictObject({
|
|
298
|
+
lane: uint(65535),
|
|
299
|
+
seq: u64Wire,
|
|
300
|
+
chargedCumulative: u64Wire,
|
|
301
|
+
lastReceiptHash: bytesWire(32)
|
|
302
|
+
});
|
|
303
|
+
var FIELD_SCHEMAS = {
|
|
304
|
+
bytes16: bytesWire(16),
|
|
305
|
+
bytes32: bytesWire(32),
|
|
306
|
+
u64: u64Wire,
|
|
307
|
+
u8: uint(255),
|
|
308
|
+
u16: uint(65535),
|
|
309
|
+
u32: uint(4294967295),
|
|
310
|
+
contract: contractWire,
|
|
311
|
+
lanes: z2.array(laneStateWire).max(MAX_LANES)
|
|
312
|
+
};
|
|
313
|
+
function fieldToWire(kind, value) {
|
|
314
|
+
switch (kind) {
|
|
315
|
+
case "bytes16":
|
|
316
|
+
case "bytes32":
|
|
317
|
+
return toHex(value);
|
|
318
|
+
case "u64":
|
|
319
|
+
return value.toString();
|
|
320
|
+
case "u8":
|
|
321
|
+
case "u16":
|
|
322
|
+
case "u32":
|
|
323
|
+
return value;
|
|
324
|
+
case "contract": {
|
|
325
|
+
const c = value;
|
|
326
|
+
return { index: c.index.toString(), subindex: c.subindex.toString() };
|
|
327
|
+
}
|
|
328
|
+
case "lanes":
|
|
329
|
+
return value.map((l) => ({
|
|
330
|
+
lane: l.lane,
|
|
331
|
+
seq: l.seq.toString(),
|
|
332
|
+
chargedCumulative: l.chargedCumulative.toString(),
|
|
333
|
+
lastReceiptHash: toHex(l.lastReceiptHash)
|
|
334
|
+
}));
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
function wireCodec(fields) {
|
|
338
|
+
const entries = Object.entries(fields);
|
|
339
|
+
const shape = {};
|
|
340
|
+
for (const [name, kind] of entries) shape[name] = FIELD_SCHEMAS[kind];
|
|
341
|
+
return {
|
|
342
|
+
schema: z2.strictObject(shape),
|
|
343
|
+
toWire(value) {
|
|
344
|
+
const rec = value;
|
|
345
|
+
const out = {};
|
|
346
|
+
for (const [name, kind] of entries) out[name] = fieldToWire(kind, rec[name]);
|
|
347
|
+
return out;
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
var voucherWire = wireCodec({
|
|
352
|
+
genesis: "bytes32",
|
|
353
|
+
bureau: "contract",
|
|
354
|
+
tabId: "u64",
|
|
355
|
+
lane: "u16",
|
|
356
|
+
seq: "u64",
|
|
357
|
+
ackedCumulative: "u64",
|
|
358
|
+
maxPrice: "u64",
|
|
359
|
+
requestHash: "bytes32",
|
|
360
|
+
prevReceiptHash: "bytes32",
|
|
361
|
+
issuedAt: "u64"
|
|
362
|
+
});
|
|
363
|
+
var receiptWire = wireCodec({
|
|
364
|
+
genesis: "bytes32",
|
|
365
|
+
bureau: "contract",
|
|
366
|
+
tabId: "u64",
|
|
367
|
+
lane: "u16",
|
|
368
|
+
seq: "u64",
|
|
369
|
+
voucherHash: "bytes32",
|
|
370
|
+
responseHash: "bytes32",
|
|
371
|
+
charged: "u64",
|
|
372
|
+
chargedCumulative: "u64",
|
|
373
|
+
issuedAt: "u64"
|
|
374
|
+
});
|
|
375
|
+
var agreementWire = wireCodec({
|
|
376
|
+
genesis: "bytes32",
|
|
377
|
+
bureau: "contract",
|
|
378
|
+
lineId: "u64",
|
|
379
|
+
sellerToken: "u64",
|
|
380
|
+
sellerWallet: "bytes32",
|
|
381
|
+
limit: "u64",
|
|
382
|
+
cycleMs: "u64",
|
|
383
|
+
graceMs: "u64",
|
|
384
|
+
maxLanes: "u16",
|
|
385
|
+
priceScheduleHash: "bytes32",
|
|
386
|
+
termsHash: "bytes32",
|
|
387
|
+
handshakeHash: "bytes32",
|
|
388
|
+
nonce: "u64",
|
|
389
|
+
expiry: "u64"
|
|
390
|
+
});
|
|
391
|
+
var closeWire = wireCodec({
|
|
392
|
+
genesis: "bytes32",
|
|
393
|
+
bureau: "contract",
|
|
394
|
+
tabId: "u64",
|
|
395
|
+
cycle: "u32",
|
|
396
|
+
lanes: "lanes",
|
|
397
|
+
total: "u64",
|
|
398
|
+
issuedAt: "u64"
|
|
399
|
+
});
|
|
400
|
+
var closeAckWire = wireCodec({
|
|
401
|
+
genesis: "bytes32",
|
|
402
|
+
bureau: "contract",
|
|
403
|
+
tabId: "u64",
|
|
404
|
+
cycle: "u32",
|
|
405
|
+
closeHash: "bytes32",
|
|
406
|
+
issuedAt: "u64"
|
|
407
|
+
});
|
|
408
|
+
var reportWire = wireCodec({
|
|
409
|
+
genesis: "bytes32",
|
|
410
|
+
bureau: "contract",
|
|
411
|
+
tabId: "u64",
|
|
412
|
+
cycle: "u32",
|
|
413
|
+
vouchersHash: "bytes32",
|
|
414
|
+
issuedAt: "u64"
|
|
415
|
+
});
|
|
416
|
+
var attestationWire = wireCodec({
|
|
417
|
+
genesis: "bytes32",
|
|
418
|
+
bureau: "contract",
|
|
419
|
+
owner: "bytes32",
|
|
420
|
+
termsHash: "bytes32",
|
|
421
|
+
vraTx: "bytes32",
|
|
422
|
+
vaaTx: "bytes32",
|
|
423
|
+
statementsHash: "bytes32",
|
|
424
|
+
tier: "u8",
|
|
425
|
+
subjectKey: "bytes32",
|
|
426
|
+
validUntil: "u64"
|
|
427
|
+
});
|
|
428
|
+
var policyWire = {
|
|
429
|
+
schema: z2.strictObject({ tabLimit: u64Wire, cycleBudget: u64Wire.optional() }).transform((p) => p.cycleBudget === void 0 ? { tabLimit: p.tabLimit } : { tabLimit: p.tabLimit, cycleBudget: p.cycleBudget }),
|
|
430
|
+
toWire: (p) => p.cycleBudget === void 0 ? { tabLimit: p.tabLimit.toString() } : { tabLimit: p.tabLimit.toString(), cycleBudget: p.cycleBudget.toString() }
|
|
431
|
+
};
|
|
432
|
+
var statusRequestWire = wireCodec({
|
|
433
|
+
genesis: "bytes32",
|
|
434
|
+
bureau: "contract",
|
|
435
|
+
tabId: "u64",
|
|
436
|
+
issuedAt: "u64"
|
|
437
|
+
});
|
|
438
|
+
var drpRequestWire = wireCodec({
|
|
439
|
+
genesis: "bytes32",
|
|
440
|
+
bureau: "contract",
|
|
441
|
+
sellerToken: "u64",
|
|
442
|
+
bodyHash: "bytes32",
|
|
443
|
+
nonce: "bytes16",
|
|
444
|
+
issuedAt: "u64"
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
// packages/keyd/src/rpc/protocol.ts
|
|
448
|
+
var MAX_MESSAGE_BYTES = 64 * 1024;
|
|
449
|
+
var JSONRPC_ERROR = Object.freeze({
|
|
450
|
+
parseError: -32700,
|
|
451
|
+
invalidRequest: -32600,
|
|
452
|
+
methodNotFound: -32601,
|
|
453
|
+
invalidParams: -32602,
|
|
454
|
+
internal: -32603,
|
|
455
|
+
/** The request was well formed but keyd's policy or checks refused it. */
|
|
456
|
+
refused: -32001,
|
|
457
|
+
unknownKey: -32002,
|
|
458
|
+
forbidden: -32003,
|
|
459
|
+
unavailable: -32004,
|
|
460
|
+
tooLarge: -32005,
|
|
461
|
+
busy: -32006
|
|
462
|
+
});
|
|
463
|
+
var keyName = z3.string().regex(KEY_NAME_RE);
|
|
464
|
+
var signed = (shape) => z3.strictObject({ key: keyName, ...shape });
|
|
465
|
+
var METHOD_PARAMS = {
|
|
466
|
+
identity: signed({}),
|
|
467
|
+
status: z3.strictObject({}),
|
|
468
|
+
signHello: signed({ hello: helloSchema }),
|
|
469
|
+
signAccept: signed({ accept: acceptSchema }),
|
|
470
|
+
signAgreement: signed({ agreement: agreementWire.schema }),
|
|
471
|
+
signVoucher: signed({ voucher: voucherWire.schema, policy: policyWire.schema }),
|
|
472
|
+
signClose: signed({ close: closeWire.schema }),
|
|
473
|
+
signReceipt: signed({ receipt: receiptWire.schema }),
|
|
474
|
+
signCloseAck: signed({ ack: closeAckWire.schema }),
|
|
475
|
+
signReport: signed({ report: reportWire.schema }),
|
|
476
|
+
signAttestation: signed({ attestation: attestationWire.schema }),
|
|
477
|
+
signStatusRequest: signed({ request: statusRequestWire.schema }),
|
|
478
|
+
signDrpRequest: signed({ request: drpRequestWire.schema }),
|
|
479
|
+
resyncLane: signed({ receipt: receiptWire.schema, signature: bytesWire(64) })
|
|
480
|
+
};
|
|
481
|
+
var RPC_METHODS = Object.keys(METHOD_PARAMS);
|
|
482
|
+
var requestSchema = z3.strictObject({
|
|
483
|
+
jsonrpc: z3.literal("2.0"),
|
|
484
|
+
id: z3.union([z3.number().int().min(0).max(Number.MAX_SAFE_INTEGER), z3.string().min(1).max(64)]),
|
|
485
|
+
method: z3.string().min(1).max(64),
|
|
486
|
+
params: z3.unknown().optional()
|
|
487
|
+
});
|
|
488
|
+
var hex = (bytes) => z3.string().regex(new RegExp(`^[0-9a-f]{${bytes * 2}}$`));
|
|
489
|
+
var signatureResultSchema = z3.strictObject({ signature: bytesWire(64) });
|
|
490
|
+
var keyInfoSchema = z3.strictObject({
|
|
491
|
+
name: keyName,
|
|
492
|
+
role: z3.enum(KEY_ROLES),
|
|
493
|
+
publicKey: hex(32),
|
|
494
|
+
keyId: z3.strictObject({ namespace: z3.string().max(128), keyType: z3.string().max(32), publicKey: hex(32) }),
|
|
495
|
+
keyIdHash: hex(32)
|
|
496
|
+
});
|
|
497
|
+
var statusSchema = z3.strictObject({
|
|
498
|
+
version: z3.string().max(64),
|
|
499
|
+
keys: z3.array(keyInfoSchema).max(1024),
|
|
500
|
+
restored: z3.boolean(),
|
|
501
|
+
restoredAt: z3.number().int().nullable(),
|
|
502
|
+
restoreReason: z3.string().max(512).nullable(),
|
|
503
|
+
unsyncedLanes: z3.number().int().min(0),
|
|
504
|
+
audit: z3.strictObject({ seq: z3.number().int().min(0), hash: hex(32) }),
|
|
505
|
+
failure: z3.string().max(1024).nullable()
|
|
506
|
+
});
|
|
507
|
+
var resyncResultSchema = z3.strictObject({
|
|
508
|
+
tabId: u64Wire,
|
|
509
|
+
lane: z3.number().int().min(0).max(65535),
|
|
510
|
+
seq: u64Wire,
|
|
511
|
+
chargedCumulative: u64Wire
|
|
512
|
+
});
|
|
513
|
+
var responseSchema = z3.union([
|
|
514
|
+
z3.strictObject({ jsonrpc: z3.literal("2.0"), id: requestSchema.shape.id.nullable(), result: z3.unknown() }),
|
|
515
|
+
z3.strictObject({
|
|
516
|
+
jsonrpc: z3.literal("2.0"),
|
|
517
|
+
id: requestSchema.shape.id.nullable(),
|
|
518
|
+
error: z3.strictObject({
|
|
519
|
+
code: z3.number().int(),
|
|
520
|
+
message: z3.string().max(4096),
|
|
521
|
+
data: z3.strictObject({ error: z3.enum(KEYD_ERROR_CODES) }).optional()
|
|
522
|
+
})
|
|
523
|
+
})
|
|
524
|
+
]);
|
|
525
|
+
|
|
526
|
+
// packages/keyd/src/rpc/client.ts
|
|
527
|
+
var KeydClient = class {
|
|
528
|
+
#opts;
|
|
529
|
+
#socket;
|
|
530
|
+
#connecting;
|
|
531
|
+
#pending = /* @__PURE__ */ new Map();
|
|
532
|
+
#identities = /* @__PURE__ */ new Map();
|
|
533
|
+
#nextId = 1;
|
|
534
|
+
#closed = false;
|
|
535
|
+
#active = 0;
|
|
536
|
+
/** Timed-out requests still holding a slot on the current connection. */
|
|
537
|
+
#orphans = 0;
|
|
538
|
+
#recycle;
|
|
539
|
+
#waiting = [];
|
|
540
|
+
constructor(opts) {
|
|
541
|
+
const timeoutMs = opts.timeoutMs ?? 1e4;
|
|
542
|
+
this.#opts = { maxMessageBytes: MAX_MESSAGE_BYTES, maxInflight: 8, ...opts, timeoutMs, recycleAfterMs: opts.recycleAfterMs ?? 4 * timeoutMs };
|
|
543
|
+
if (!Number.isInteger(this.#opts.maxInflight) || this.#opts.maxInflight < 1) throw new RangeError("maxInflight must be a positive integer");
|
|
544
|
+
}
|
|
545
|
+
buyer(name) {
|
|
546
|
+
return bindBuyer(this, name);
|
|
547
|
+
}
|
|
548
|
+
seller(name) {
|
|
549
|
+
return bindSeller(this, name);
|
|
550
|
+
}
|
|
551
|
+
attestor(name) {
|
|
552
|
+
return bindAttestor(this, name);
|
|
553
|
+
}
|
|
554
|
+
async identity(name) {
|
|
555
|
+
let info = this.#identities.get(name);
|
|
556
|
+
if (info === void 0) {
|
|
557
|
+
info = this.#call("identity", { key: name }).then((r) => parse(keyInfoSchema, r, "identity"));
|
|
558
|
+
info.catch(() => this.#identities.delete(name));
|
|
559
|
+
this.#identities.set(name, info);
|
|
560
|
+
}
|
|
561
|
+
return info;
|
|
562
|
+
}
|
|
563
|
+
async status() {
|
|
564
|
+
return parse(statusSchema, await this.#call("status", {}), "status");
|
|
565
|
+
}
|
|
566
|
+
signHello(name, hello) {
|
|
567
|
+
return this.#signed("signHello", name, { hello }, helloSigningBytes(hello));
|
|
568
|
+
}
|
|
569
|
+
signAccept(name, accept) {
|
|
570
|
+
return this.#signed("signAccept", name, { accept }, acceptSigningBytes(accept));
|
|
571
|
+
}
|
|
572
|
+
signAgreement(name, agreement) {
|
|
573
|
+
return this.#signed("signAgreement", name, { agreement: agreementWire.toWire(agreement) }, TabAgreementV1Codec.encode(agreement));
|
|
574
|
+
}
|
|
575
|
+
signVoucher(name, voucher, policy) {
|
|
576
|
+
return this.#signed(
|
|
577
|
+
"signVoucher",
|
|
578
|
+
name,
|
|
579
|
+
{ voucher: voucherWire.toWire(voucher), policy: policyWire.toWire(policy) },
|
|
580
|
+
VoucherV1Codec.encode(voucher)
|
|
581
|
+
);
|
|
582
|
+
}
|
|
583
|
+
signClose(name, close) {
|
|
584
|
+
return this.#signed("signClose", name, { close: closeWire.toWire(close) }, CloseVoucherV1Codec.encode(close));
|
|
585
|
+
}
|
|
586
|
+
signReceipt(name, receipt) {
|
|
587
|
+
return this.#signed("signReceipt", name, { receipt: receiptWire.toWire(receipt) }, ReceiptV1Codec.encode(receipt));
|
|
588
|
+
}
|
|
589
|
+
signCloseAck(name, ack) {
|
|
590
|
+
return this.#signed("signCloseAck", name, { ack: closeAckWire.toWire(ack) }, CloseAckV1Codec.encode(ack));
|
|
591
|
+
}
|
|
592
|
+
signReport(name, report) {
|
|
593
|
+
return this.#signed("signReport", name, { report: reportWire.toWire(report) }, ReportV1Codec.encode(report));
|
|
594
|
+
}
|
|
595
|
+
signAttestation(name, attestation) {
|
|
596
|
+
return this.#signed(
|
|
597
|
+
"signAttestation",
|
|
598
|
+
name,
|
|
599
|
+
{ attestation: attestationWire.toWire(attestation) },
|
|
600
|
+
ConsentAttestationV1Codec.encode(attestation)
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
signStatusRequest(name, request2) {
|
|
604
|
+
return this.#signed("signStatusRequest", name, { request: statusRequestWire.toWire(request2) }, encodeTabStatusRequestV1(request2));
|
|
605
|
+
}
|
|
606
|
+
signDrpRequest(name, request2) {
|
|
607
|
+
return this.#signed("signDrpRequest", name, { request: drpRequestWire.toWire(request2) }, encodeDrpRequestV1(request2));
|
|
608
|
+
}
|
|
609
|
+
async resyncLane(name, receipt, signature) {
|
|
610
|
+
const result = await this.#call("resyncLane", { key: name, receipt: receiptWire.toWire(receipt), signature: toHex(signature) });
|
|
611
|
+
return parse(resyncResultSchema, result, "resyncLane");
|
|
612
|
+
}
|
|
613
|
+
/** Closes the connection; pending and queued requests fail with `unavailable`. */
|
|
614
|
+
close() {
|
|
615
|
+
this.#closed = true;
|
|
616
|
+
clearTimeout(this.#recycle);
|
|
617
|
+
this.#socket?.destroy();
|
|
618
|
+
this.#failAll(new KeydError("unavailable", "the keyd client was closed"), null);
|
|
619
|
+
for (const wake of this.#waiting.splice(0)) wake();
|
|
620
|
+
}
|
|
621
|
+
// -------------------------------------------------------------------------
|
|
622
|
+
async #signed(method, name, params, preimage) {
|
|
623
|
+
const [result, info] = await Promise.all([this.#call(method, { key: name, ...params }), this.identity(name)]);
|
|
624
|
+
const { signature } = parse(signatureResultSchema, result, method);
|
|
625
|
+
if (!ed25519Verify(signature, preimage, fromHex(info.publicKey, 32))) {
|
|
626
|
+
throw new KeydError("internal", `keyd returned a ${method} signature that does not verify against key "${name}"`);
|
|
627
|
+
}
|
|
628
|
+
return signature;
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* Runs one request in a connection slot. The slot is held until the daemon answers (or the
|
|
632
|
+
* connection closes), not just until the caller gives up, because the daemon counts the request
|
|
633
|
+
* against its per-connection limit until then. A released slot passes straight to the next waiter.
|
|
634
|
+
*/
|
|
635
|
+
async #call(method, params) {
|
|
636
|
+
if (this.#active < this.#opts.maxInflight) this.#active++;
|
|
637
|
+
else await new Promise((wake) => this.#waiting.push(wake));
|
|
638
|
+
let released = false;
|
|
639
|
+
const release = () => {
|
|
640
|
+
if (released) return;
|
|
641
|
+
released = true;
|
|
642
|
+
const next = this.#waiting.shift();
|
|
643
|
+
if (next === void 0) this.#active--;
|
|
644
|
+
else next();
|
|
645
|
+
};
|
|
646
|
+
return this.#send(method, params, release);
|
|
647
|
+
}
|
|
648
|
+
async #send(method, params, release) {
|
|
649
|
+
let socket;
|
|
650
|
+
try {
|
|
651
|
+
if (this.#closed) throw new KeydError("unavailable", "the keyd client was closed");
|
|
652
|
+
socket = await this.#connect();
|
|
653
|
+
} catch (err) {
|
|
654
|
+
release();
|
|
655
|
+
throw err;
|
|
656
|
+
}
|
|
657
|
+
const id = this.#nextId++;
|
|
658
|
+
const line = `${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
|
|
659
|
+
`;
|
|
660
|
+
if (Buffer.byteLength(line) > this.#opts.maxMessageBytes) {
|
|
661
|
+
release();
|
|
662
|
+
throw new KeydError("message_too_large", `${method} request exceeds ${this.#opts.maxMessageBytes} bytes`);
|
|
663
|
+
}
|
|
664
|
+
return new Promise((resolve, reject) => {
|
|
665
|
+
const entry = {
|
|
666
|
+
resolve,
|
|
667
|
+
reject,
|
|
668
|
+
socket,
|
|
669
|
+
release,
|
|
670
|
+
timedOut: false,
|
|
671
|
+
timer: setTimeout(() => {
|
|
672
|
+
entry.timedOut = true;
|
|
673
|
+
this.#orphans++;
|
|
674
|
+
reject(new KeydError("unavailable", `keyd did not answer ${method} within ${this.#opts.timeoutMs} ms`));
|
|
675
|
+
this.#watchOrphans(socket);
|
|
676
|
+
}, this.#opts.timeoutMs)
|
|
677
|
+
};
|
|
678
|
+
this.#pending.set(id, entry);
|
|
679
|
+
socket.write(line);
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* When every slot is held by a timed-out request, waits `recycleAfterMs` for the daemon to answer
|
|
684
|
+
* one; if none is answered by then, the connection is given up (its slots are freed, and the
|
|
685
|
+
* daemon's limit applies to the new connection afresh).
|
|
686
|
+
*/
|
|
687
|
+
#watchOrphans(socket) {
|
|
688
|
+
if (this.#orphans < this.#opts.maxInflight || this.#recycle !== void 0) return;
|
|
689
|
+
this.#recycle = setTimeout(() => {
|
|
690
|
+
this.#recycle = void 0;
|
|
691
|
+
if (this.#orphans >= this.#opts.maxInflight && !socket.destroyed) socket.destroy();
|
|
692
|
+
}, this.#opts.recycleAfterMs);
|
|
693
|
+
this.#recycle.unref();
|
|
694
|
+
}
|
|
695
|
+
/** Removes a request and frees its slot. */
|
|
696
|
+
#finish(id, entry) {
|
|
697
|
+
this.#pending.delete(id);
|
|
698
|
+
clearTimeout(entry.timer);
|
|
699
|
+
if (entry.timedOut) this.#orphans--;
|
|
700
|
+
entry.release();
|
|
701
|
+
}
|
|
702
|
+
#connect() {
|
|
703
|
+
if (this.#socket !== void 0 && !this.#socket.destroyed) return Promise.resolve(this.#socket);
|
|
704
|
+
this.#connecting ??= new Promise((resolve, reject) => {
|
|
705
|
+
const socket = net.createConnection(this.#opts.socketPath);
|
|
706
|
+
let buffered = Buffer.alloc(0);
|
|
707
|
+
socket.once("connect", () => {
|
|
708
|
+
this.#socket = socket;
|
|
709
|
+
this.#connecting = void 0;
|
|
710
|
+
resolve(socket);
|
|
711
|
+
});
|
|
712
|
+
socket.on("data", (chunk) => {
|
|
713
|
+
buffered = buffered.length === 0 ? chunk : Buffer.concat([buffered, chunk]);
|
|
714
|
+
for (; ; ) {
|
|
715
|
+
const nl = buffered.indexOf(10);
|
|
716
|
+
if (nl < 0 ? buffered.length > this.#opts.maxMessageBytes : nl > this.#opts.maxMessageBytes) {
|
|
717
|
+
socket.destroy(new KeydError("message_too_large", "keyd sent an oversized response"));
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
if (nl < 0) return;
|
|
721
|
+
const line = buffered.subarray(0, nl).toString("utf8");
|
|
722
|
+
buffered = buffered.subarray(nl + 1);
|
|
723
|
+
this.#onLine(line);
|
|
724
|
+
}
|
|
725
|
+
});
|
|
726
|
+
socket.on("error", (err) => {
|
|
727
|
+
if (this.#connecting !== void 0) {
|
|
728
|
+
this.#connecting = void 0;
|
|
729
|
+
reject(new KeydError("unavailable", `cannot reach keyd at ${this.#opts.socketPath}: ${err.message}`));
|
|
730
|
+
}
|
|
731
|
+
});
|
|
732
|
+
socket.on("close", () => {
|
|
733
|
+
if (this.#socket === socket) this.#socket = void 0;
|
|
734
|
+
this.#failAll(new KeydError("unavailable", "the keyd connection closed"), socket);
|
|
735
|
+
});
|
|
736
|
+
});
|
|
737
|
+
return this.#connecting;
|
|
738
|
+
}
|
|
739
|
+
#onLine(line) {
|
|
740
|
+
let json;
|
|
741
|
+
try {
|
|
742
|
+
json = JSON.parse(line);
|
|
743
|
+
} catch {
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
const res = responseSchema.safeParse(json);
|
|
747
|
+
if (!res.success) return;
|
|
748
|
+
const msg = res.data;
|
|
749
|
+
if (typeof msg.id !== "number") {
|
|
750
|
+
if ("error" in msg) this.#failAll(toKeydError(msg.error), null);
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
const pending = this.#pending.get(msg.id);
|
|
754
|
+
if (pending === void 0) return;
|
|
755
|
+
this.#finish(msg.id, pending);
|
|
756
|
+
if (pending.timedOut) return;
|
|
757
|
+
if ("error" in msg) pending.reject(toKeydError(msg.error));
|
|
758
|
+
else pending.resolve(msg.result);
|
|
759
|
+
}
|
|
760
|
+
/** Fails the requests written to `socket` (every request when null) and frees their slots. */
|
|
761
|
+
#failAll(err, socket) {
|
|
762
|
+
for (const [id, p] of [...this.#pending]) {
|
|
763
|
+
if (socket !== null && p.socket !== socket) continue;
|
|
764
|
+
this.#finish(id, p);
|
|
765
|
+
if (!p.timedOut) p.reject(err);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
};
|
|
769
|
+
function toKeydError(error) {
|
|
770
|
+
const code = error.data?.error;
|
|
771
|
+
if (isKeydErrorCode(code)) return new KeydError(code, error.message);
|
|
772
|
+
return new KeydError(error.code === JSONRPC_ERROR.invalidParams ? "invalid_params" : "internal", error.message);
|
|
773
|
+
}
|
|
774
|
+
function parse(schema, value, what) {
|
|
775
|
+
const r = schema.safeParse(value);
|
|
776
|
+
if (!r.success) throw new KeydError("internal", `keyd sent a malformed ${what} result`);
|
|
777
|
+
return r.data;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// packages/keyd/src/account/transaction.ts
|
|
781
|
+
import {
|
|
782
|
+
AccountAddress,
|
|
783
|
+
AccountTransactionV0,
|
|
784
|
+
AccountTransactionV1,
|
|
785
|
+
BlockItemKind,
|
|
786
|
+
Payload,
|
|
787
|
+
Transaction
|
|
788
|
+
} from "@concordium/web-sdk";
|
|
789
|
+
function transactionDigest(tx) {
|
|
790
|
+
return tx.version === 1 ? AccountTransactionV1.signDigest(Transaction.preFinalized(tx)) : AccountTransactionV0.signDigest(Transaction.preFinalized(tx));
|
|
791
|
+
}
|
|
792
|
+
function roleAccount(tx, role) {
|
|
793
|
+
if (role === "sender") {
|
|
794
|
+
return { address: AccountAddress.toBase58(tx.header.sender), numSignatures: tx.header.numSignatures };
|
|
795
|
+
}
|
|
796
|
+
if (tx.version !== 1 || tx.header.sponsor === void 0) {
|
|
797
|
+
throw new KeydError("invalid_message", "sponsor signing needs a sponsored AccountTransactionV1");
|
|
798
|
+
}
|
|
799
|
+
return { address: AccountAddress.toBase58(tx.header.sponsor.account), numSignatures: tx.header.sponsor.numSignatures };
|
|
800
|
+
}
|
|
801
|
+
function assertRole(tx, role, address) {
|
|
802
|
+
const want = roleAccount(tx, role);
|
|
803
|
+
if (want.address !== address) {
|
|
804
|
+
throw new KeydError("role_forbidden", `the transaction's ${role} is ${want.address}, not ${address}`);
|
|
805
|
+
}
|
|
806
|
+
return want.numSignatures;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
// packages/keyd/src/account/walletExport.ts
|
|
810
|
+
import { z as z4 } from "zod";
|
|
811
|
+
|
|
812
|
+
// packages/keyd/src/fsutil.ts
|
|
813
|
+
import { constants, promises as fsp } from "node:fs";
|
|
814
|
+
import path from "node:path";
|
|
815
|
+
var GROUP_WORLD_BITS = 63;
|
|
816
|
+
function currentUid() {
|
|
817
|
+
return typeof process.getuid === "function" ? process.getuid() : void 0;
|
|
818
|
+
}
|
|
819
|
+
function checkOwnerAndMode(what, uid, mode) {
|
|
820
|
+
const me = currentUid();
|
|
821
|
+
if (me !== void 0 && uid !== me) {
|
|
822
|
+
throw new KeydError("insecure_permissions", `${what} is owned by uid ${uid}, not by this user (${me})`);
|
|
823
|
+
}
|
|
824
|
+
if ((mode & GROUP_WORLD_BITS) !== 0) {
|
|
825
|
+
throw new KeydError(
|
|
826
|
+
"insecure_permissions",
|
|
827
|
+
`${what} has mode ${(mode & 511).toString(8)}; group and world must have no access (chmod go-rwx)`
|
|
828
|
+
);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
async function assertPrivateDir(dir) {
|
|
832
|
+
const st = await fsp.lstat(dir);
|
|
833
|
+
if (!st.isDirectory()) throw new KeydError("insecure_permissions", `${dir} is not a directory`);
|
|
834
|
+
checkOwnerAndMode(dir, st.uid, st.mode);
|
|
835
|
+
}
|
|
836
|
+
async function ensurePrivateDir(dir) {
|
|
837
|
+
await fsp.mkdir(dir, { recursive: true, mode: 448 });
|
|
838
|
+
await assertPrivateDir(dir);
|
|
839
|
+
}
|
|
840
|
+
async function readPrivateFile(file, maxBytes, tooLarge = "key_file_invalid") {
|
|
841
|
+
let handle;
|
|
842
|
+
try {
|
|
843
|
+
handle = await fsp.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
844
|
+
} catch (err) {
|
|
845
|
+
if (err.code === "ELOOP") {
|
|
846
|
+
throw new KeydError("insecure_permissions", `${file} is a symlink`);
|
|
847
|
+
}
|
|
848
|
+
throw err;
|
|
849
|
+
}
|
|
850
|
+
try {
|
|
851
|
+
const st = await handle.stat();
|
|
852
|
+
if (!st.isFile()) throw new KeydError("insecure_permissions", `${file} is not a regular file`);
|
|
853
|
+
checkOwnerAndMode(file, st.uid, st.mode);
|
|
854
|
+
if (st.size > maxBytes) throw new KeydError(tooLarge, `${file} is larger than ${maxBytes} bytes`);
|
|
855
|
+
const buf = await handle.readFile();
|
|
856
|
+
if (buf.length > maxBytes) throw new KeydError(tooLarge, `${file} is larger than ${maxBytes} bytes`);
|
|
857
|
+
return new Uint8Array(buf.buffer, buf.byteOffset, buf.length);
|
|
858
|
+
} finally {
|
|
859
|
+
await handle.close();
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
async function fsyncDir(dir) {
|
|
863
|
+
const handle = await fsp.open(dir, constants.O_RDONLY);
|
|
864
|
+
try {
|
|
865
|
+
await handle.sync();
|
|
866
|
+
} finally {
|
|
867
|
+
await handle.close();
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
async function writeFileExclusive(file, data, mode = 384) {
|
|
871
|
+
const handle = await fsp.open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, mode);
|
|
872
|
+
try {
|
|
873
|
+
await handle.writeFile(data);
|
|
874
|
+
await handle.sync();
|
|
875
|
+
} finally {
|
|
876
|
+
await handle.close();
|
|
877
|
+
}
|
|
878
|
+
await fsyncDir(path.dirname(file));
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
// packages/keyd/src/account/walletExport.ts
|
|
882
|
+
var MAX_EXPORT_BYTES = 64 * 1024;
|
|
883
|
+
var hex32 = z4.string().regex(/^[0-9a-fA-F]{64}$/);
|
|
884
|
+
var index = z4.string().regex(/^(0|[1-9][0-9]{0,2})$/).transform(Number).refine((n) => n <= 255);
|
|
885
|
+
var exportSchema = z4.object({
|
|
886
|
+
type: z4.string().max(128),
|
|
887
|
+
v: z4.number().int(),
|
|
888
|
+
environment: z4.string().max(32),
|
|
889
|
+
value: z4.object({
|
|
890
|
+
address: z4.string().max(64),
|
|
891
|
+
accountKeys: z4.object({
|
|
892
|
+
keys: z4.record(z4.string(), z4.object({ keys: z4.record(z4.string(), z4.object({ signKey: hex32, verifyKey: hex32 })), threshold: z4.number().int() })),
|
|
893
|
+
threshold: z4.number().int()
|
|
894
|
+
}),
|
|
895
|
+
credentials: z4.record(z4.string(), z4.string())
|
|
896
|
+
})
|
|
897
|
+
});
|
|
898
|
+
function parseWalletExport(json, opts = {}) {
|
|
899
|
+
const parsed = exportSchema.safeParse(json);
|
|
900
|
+
if (!parsed.success) throw new KeydError("key_file_invalid", "not a Concordium wallet key export");
|
|
901
|
+
const { environment, value } = parsed.data;
|
|
902
|
+
const want = opts.environment ?? "testnet";
|
|
903
|
+
if (environment !== want) throw new KeydError("wrong_network", `the wallet export is for ${environment}, not ${want}`);
|
|
904
|
+
let addressBytes;
|
|
905
|
+
try {
|
|
906
|
+
addressBytes = accountAddressFromBase58(value.address);
|
|
907
|
+
} catch {
|
|
908
|
+
throw new KeydError("key_file_invalid", "the wallet export has an invalid account address");
|
|
909
|
+
}
|
|
910
|
+
const keys = [];
|
|
911
|
+
for (const [cred, credKeys] of Object.entries(value.accountKeys.keys)) {
|
|
912
|
+
for (const [key, pair] of Object.entries(credKeys.keys)) {
|
|
913
|
+
const credential = index.safeParse(cred);
|
|
914
|
+
const keyIndex = index.safeParse(key);
|
|
915
|
+
if (!credential.success || !keyIndex.success) throw new KeydError("key_file_invalid", "invalid credential or key index");
|
|
916
|
+
const seed = fromHex(pair.signKey.toLowerCase(), 32);
|
|
917
|
+
const secret = new Ed25519Secret(seed);
|
|
918
|
+
seed.fill(0);
|
|
919
|
+
if (!bytesEqual(secret.publicKey, fromHex(pair.verifyKey.toLowerCase(), 32))) {
|
|
920
|
+
secret.destroy();
|
|
921
|
+
throw new KeydError("key_file_invalid", `key ${cred}:${key}: verifyKey does not match signKey`);
|
|
922
|
+
}
|
|
923
|
+
keys.push({ credential: credential.data, key: keyIndex.data, secret });
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
if (keys.length === 0) throw new KeydError("key_file_invalid", "the wallet export holds no keys");
|
|
927
|
+
keys.sort((a, b) => a.credential - b.credential || a.key - b.key);
|
|
928
|
+
return { address: value.address, addressBytes, environment, keys };
|
|
929
|
+
}
|
|
930
|
+
async function loadWalletExport(file, opts = {}) {
|
|
931
|
+
const bytes = await readPrivateFile(file, MAX_EXPORT_BYTES);
|
|
932
|
+
let json;
|
|
933
|
+
try {
|
|
934
|
+
json = JSON.parse(fromUtf8(bytes));
|
|
935
|
+
} catch {
|
|
936
|
+
throw new KeydError("key_file_invalid", `${file} is not valid JSON`);
|
|
937
|
+
} finally {
|
|
938
|
+
bytes.fill(0);
|
|
939
|
+
}
|
|
940
|
+
return parseWalletExport(json, opts);
|
|
941
|
+
}
|
|
942
|
+
function destroyWallet(wallet) {
|
|
943
|
+
for (const k of wallet.keys) k.secret.destroy();
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
// packages/keyd/src/account/keyFileSigner.ts
|
|
947
|
+
var KeyFileAccountSigner = class _KeyFileAccountSigner {
|
|
948
|
+
address;
|
|
949
|
+
#wallet;
|
|
950
|
+
constructor(wallet) {
|
|
951
|
+
this.#wallet = wallet;
|
|
952
|
+
this.address = wallet.address;
|
|
953
|
+
}
|
|
954
|
+
/** Loads the export at `file` (owner-only, outside the repo; the path is supplied at runtime). */
|
|
955
|
+
static async fromFile(file, opts = {}) {
|
|
956
|
+
return new _KeyFileAccountSigner(await loadWalletExport(file, opts));
|
|
957
|
+
}
|
|
958
|
+
signAsSender(tx) {
|
|
959
|
+
return this.#sign(tx, "sender");
|
|
960
|
+
}
|
|
961
|
+
signAsSponsor(tx) {
|
|
962
|
+
return this.#sign(tx, "sponsor");
|
|
963
|
+
}
|
|
964
|
+
/** Wipes the keys from memory; the signer is unusable afterwards. */
|
|
965
|
+
destroy() {
|
|
966
|
+
destroyWallet(this.#wallet);
|
|
967
|
+
}
|
|
968
|
+
async #sign(tx, role) {
|
|
969
|
+
const budget = assertRole(tx, role, this.address);
|
|
970
|
+
if (BigInt(this.#wallet.keys.length) > budget) {
|
|
971
|
+
throw new KeydError(
|
|
972
|
+
"invalid_message",
|
|
973
|
+
`the transaction allows ${budget} ${role} signature(s) but the export holds ${this.#wallet.keys.length} keys`
|
|
974
|
+
);
|
|
975
|
+
}
|
|
976
|
+
const digest = transactionDigest(tx);
|
|
977
|
+
const out = {};
|
|
978
|
+
for (const k of this.#wallet.keys) {
|
|
979
|
+
const cred = out[k.credential] ??= {};
|
|
980
|
+
cred[k.key] = toHex(k.secret.sign(digest));
|
|
981
|
+
}
|
|
982
|
+
return out;
|
|
983
|
+
}
|
|
984
|
+
};
|
|
985
|
+
|
|
986
|
+
// packages/keyd/src/keys/keyfile.ts
|
|
987
|
+
import { randomBytes } from "node:crypto";
|
|
988
|
+
import os from "node:os";
|
|
989
|
+
import path2 from "node:path";
|
|
990
|
+
import { z as z5 } from "zod";
|
|
991
|
+
var KEY_FILE_FORMAT = "opentab-keyd-key/v1";
|
|
992
|
+
var KEY_FILE_SUFFIX = ".key.json";
|
|
993
|
+
var MAX_KEY_FILE_BYTES = 4096;
|
|
994
|
+
var hex322 = z5.string().regex(/^[0-9a-f]{64}$/, "expected 32 bytes of lowercase hex");
|
|
995
|
+
var keyFileSchema = z5.strictObject({
|
|
996
|
+
format: z5.literal(KEY_FILE_FORMAT),
|
|
997
|
+
name: z5.string().regex(KEY_NAME_RE),
|
|
998
|
+
role: z5.enum(KEY_ROLES),
|
|
999
|
+
seed: hex322,
|
|
1000
|
+
publicKey: hex322,
|
|
1001
|
+
createdAt: z5.string().max(64)
|
|
1002
|
+
});
|
|
1003
|
+
function defaultKeyDir(env = process.env) {
|
|
1004
|
+
return env.KEYD_KEY_DIR ?? path2.join(os.homedir(), ".opentab", "keyd");
|
|
1005
|
+
}
|
|
1006
|
+
function keyFilePath(dir, name) {
|
|
1007
|
+
assertKeyName(name);
|
|
1008
|
+
return path2.join(dir, `${name}${KEY_FILE_SUFFIX}`);
|
|
1009
|
+
}
|
|
1010
|
+
async function readKeyFile(file) {
|
|
1011
|
+
const bytes = await readPrivateFile(file, MAX_KEY_FILE_BYTES);
|
|
1012
|
+
let json;
|
|
1013
|
+
try {
|
|
1014
|
+
json = JSON.parse(fromUtf8(bytes));
|
|
1015
|
+
} catch {
|
|
1016
|
+
throw new KeydError("key_file_invalid", `${file} is not valid JSON`);
|
|
1017
|
+
}
|
|
1018
|
+
const parsed = keyFileSchema.safeParse(json);
|
|
1019
|
+
if (!parsed.success) throw new KeydError("key_file_invalid", `${file} is not an ${KEY_FILE_FORMAT} key file`);
|
|
1020
|
+
const { name, role, seed, publicKey } = parsed.data;
|
|
1021
|
+
if (path2.basename(file) !== `${name}${KEY_FILE_SUFFIX}`) {
|
|
1022
|
+
throw new KeydError("key_file_invalid", `${file} holds key "${name}" but is not named ${name}${KEY_FILE_SUFFIX}`);
|
|
1023
|
+
}
|
|
1024
|
+
const seedBytes = fromHex(seed, 32);
|
|
1025
|
+
try {
|
|
1026
|
+
const key = keyFromSeed(name, role, seedBytes);
|
|
1027
|
+
if (!bytesEqual(key.secret.publicKey, fromHex(publicKey, 32))) {
|
|
1028
|
+
key.secret.destroy();
|
|
1029
|
+
throw new KeydError("key_file_invalid", `${file}: publicKey does not match the seed`);
|
|
1030
|
+
}
|
|
1031
|
+
return key;
|
|
1032
|
+
} finally {
|
|
1033
|
+
seedBytes.fill(0);
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
async function generateKeyFile(dir, name, role, now = /* @__PURE__ */ new Date()) {
|
|
1037
|
+
const file = keyFilePath(dir, name);
|
|
1038
|
+
await ensurePrivateDir(dir);
|
|
1039
|
+
const seed = new Uint8Array(randomBytes(32));
|
|
1040
|
+
try {
|
|
1041
|
+
const key = keyFromSeed(name, role, seed);
|
|
1042
|
+
const body = {
|
|
1043
|
+
format: KEY_FILE_FORMAT,
|
|
1044
|
+
name,
|
|
1045
|
+
role,
|
|
1046
|
+
seed: toHex(seed),
|
|
1047
|
+
publicKey: toHex(key.secret.publicKey),
|
|
1048
|
+
createdAt: now.toISOString()
|
|
1049
|
+
};
|
|
1050
|
+
try {
|
|
1051
|
+
await writeFileExclusive(file, `${JSON.stringify(body, null, 2)}
|
|
1052
|
+
`, 384);
|
|
1053
|
+
} catch (err) {
|
|
1054
|
+
key.secret.destroy();
|
|
1055
|
+
if (err.code === "EEXIST") {
|
|
1056
|
+
throw new KeydError("key_file_invalid", `${file} already exists; keyd never overwrites a key`);
|
|
1057
|
+
}
|
|
1058
|
+
throw err;
|
|
1059
|
+
}
|
|
1060
|
+
return key;
|
|
1061
|
+
} finally {
|
|
1062
|
+
seed.fill(0);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
// packages/keyd/src/policy/state.ts
|
|
1067
|
+
import { z as z6 } from "zod";
|
|
1068
|
+
var MAX_SUPERSEDED = 16;
|
|
1069
|
+
var FRESH_HEAD = Object.freeze({
|
|
1070
|
+
kind: "receipted",
|
|
1071
|
+
seq: 0n,
|
|
1072
|
+
cumulative: 0n,
|
|
1073
|
+
receiptHash: zeroHash()
|
|
1074
|
+
});
|
|
1075
|
+
var STATE_FORMAT = "opentab-keyd-state/v1";
|
|
1076
|
+
var dec = z6.string().regex(/^(0|[1-9][0-9]{0,19})$/).transform((s) => BigInt(s));
|
|
1077
|
+
var hex323 = z6.string().regex(/^[0-9a-f]{64}$/).transform((s) => fromHex(s, 32));
|
|
1078
|
+
var cycle = z6.number().int().min(0).max(4294967295);
|
|
1079
|
+
var headSchema = z6.discriminatedUnion("kind", [
|
|
1080
|
+
z6.strictObject({
|
|
1081
|
+
kind: z6.literal("pending"),
|
|
1082
|
+
seq: dec,
|
|
1083
|
+
acked: dec,
|
|
1084
|
+
maxPrice: dec,
|
|
1085
|
+
prevReceiptHash: hex323,
|
|
1086
|
+
commitment: hex323
|
|
1087
|
+
}),
|
|
1088
|
+
z6.strictObject({ kind: z6.literal("receipted"), seq: dec, cumulative: dec, receiptHash: hex323 })
|
|
1089
|
+
]);
|
|
1090
|
+
var tailSchema = z6.strictObject({
|
|
1091
|
+
cycle: cycle.nullable(),
|
|
1092
|
+
before: cycle,
|
|
1093
|
+
seq: dec,
|
|
1094
|
+
cumulative: dec,
|
|
1095
|
+
receiptHash: hex323
|
|
1096
|
+
});
|
|
1097
|
+
var supersededSchema = z6.strictObject({
|
|
1098
|
+
seq: dec,
|
|
1099
|
+
acked: dec,
|
|
1100
|
+
maxPrice: dec,
|
|
1101
|
+
commitment: hex323,
|
|
1102
|
+
cycle: cycle.nullable()
|
|
1103
|
+
});
|
|
1104
|
+
var laneSchema = z6.strictObject({
|
|
1105
|
+
head: headSchema,
|
|
1106
|
+
synced: z6.boolean(),
|
|
1107
|
+
closed: z6.strictObject({ seq: dec, cumulative: dec }).nullable(),
|
|
1108
|
+
cycle: cycle.nullable().optional(),
|
|
1109
|
+
boundary: tailSchema.nullable().optional(),
|
|
1110
|
+
superseded: z6.array(supersededSchema).max(MAX_SUPERSEDED).optional()
|
|
1111
|
+
});
|
|
1112
|
+
var tabSchema = z6.strictObject({
|
|
1113
|
+
closedCycle: cycle.nullable(),
|
|
1114
|
+
spend: z6.strictObject({ cycle, amount: dec }).nullable(),
|
|
1115
|
+
lanes: z6.record(z6.string().regex(/^(0|[1-9][0-9]?)$/), laneSchema)
|
|
1116
|
+
});
|
|
1117
|
+
var stateSchema = z6.strictObject({
|
|
1118
|
+
format: z6.literal(STATE_FORMAT),
|
|
1119
|
+
generation: z6.string().regex(/^[0-9a-f-]{8,64}$/),
|
|
1120
|
+
counter: z6.number().int().min(0),
|
|
1121
|
+
restoredAt: z6.number().int().min(0).nullable(),
|
|
1122
|
+
tabs: z6.record(z6.string().max(200), tabSchema)
|
|
1123
|
+
});
|
|
1124
|
+
|
|
1125
|
+
// packages/keyd/src/policy/rules.ts
|
|
1126
|
+
var ZERO_HASH = zeroHash();
|
|
1127
|
+
|
|
1128
|
+
// packages/keyd/src/policy/store.ts
|
|
1129
|
+
import { z as z7 } from "zod";
|
|
1130
|
+
var MARKER_FORMAT = "opentab-keyd-marker/v1";
|
|
1131
|
+
var MAX_STATE_BYTES = 16 * 1024 * 1024;
|
|
1132
|
+
var markerSchema = z7.strictObject({
|
|
1133
|
+
format: z7.literal(MARKER_FORMAT),
|
|
1134
|
+
generation: z7.string().regex(/^[0-9a-f-]{8,64}$/),
|
|
1135
|
+
counter: z7.number().int().min(0)
|
|
1136
|
+
});
|
|
1137
|
+
|
|
1138
|
+
// packages/keyd/src/audit/log.ts
|
|
1139
|
+
import { z as z8 } from "zod";
|
|
1140
|
+
var AUDIT_OUTCOMES = ["signed", "refused", "resynced", "started", "recovered"];
|
|
1141
|
+
var AUDIT_GENESIS_HASH = "0".repeat(64);
|
|
1142
|
+
var MAX_AUDIT_BYTES = 512 * 1024 * 1024;
|
|
1143
|
+
var hex64 = z8.string().regex(/^[0-9a-f]{64}$/);
|
|
1144
|
+
var entrySchema = z8.strictObject({
|
|
1145
|
+
v: z8.literal(1),
|
|
1146
|
+
seq: z8.number().int().min(1),
|
|
1147
|
+
time: z8.string().max(40),
|
|
1148
|
+
method: z8.string().max(64),
|
|
1149
|
+
keyName: z8.string().max(64).nullable(),
|
|
1150
|
+
keyId: hex64.nullable(),
|
|
1151
|
+
messageHash: hex64.nullable(),
|
|
1152
|
+
outcome: z8.enum(AUDIT_OUTCOMES),
|
|
1153
|
+
error: z8.string().max(200).optional(),
|
|
1154
|
+
prev: hex64,
|
|
1155
|
+
hash: hex64
|
|
1156
|
+
});
|
|
1157
|
+
|
|
1158
|
+
// packages/keyd/src/chain/bureauTabDirectory.ts
|
|
1159
|
+
import {
|
|
1160
|
+
BlockHash,
|
|
1161
|
+
ContractAddress as SdkContractAddress,
|
|
1162
|
+
Energy,
|
|
1163
|
+
isKnown,
|
|
1164
|
+
Parameter,
|
|
1165
|
+
ReceiveName,
|
|
1166
|
+
ReturnValue
|
|
1167
|
+
} from "@concordium/web-sdk";
|
|
1168
|
+
|
|
1169
|
+
// packages/keyd/src/daemon.ts
|
|
1170
|
+
import { ConcordiumGRPCNodeClient, credentials } from "@concordium/web-sdk/nodejs";
|
|
1171
|
+
|
|
1172
|
+
// packages/keyd/src/account/ccdSigner.ts
|
|
1173
|
+
import { AccountAddress as AccountAddress2 } from "@concordium/web-sdk";
|
|
1174
|
+
import { z as z10 } from "zod";
|
|
1175
|
+
|
|
1176
|
+
// packages/keyd/src/account/mcpStdio.ts
|
|
1177
|
+
import { z as z9 } from "zod";
|
|
1178
|
+
var messageSchema = z9.object({
|
|
1179
|
+
jsonrpc: z9.literal("2.0"),
|
|
1180
|
+
id: z9.union([z9.number(), z9.string()]).nullable().optional(),
|
|
1181
|
+
method: z9.string().optional(),
|
|
1182
|
+
result: z9.unknown().optional(),
|
|
1183
|
+
error: z9.object({ code: z9.number(), message: z9.string() }).optional()
|
|
1184
|
+
});
|
|
1185
|
+
var toolResultSchema = z9.object({
|
|
1186
|
+
content: z9.array(z9.unknown()).optional(),
|
|
1187
|
+
structuredContent: z9.unknown().optional(),
|
|
1188
|
+
isError: z9.boolean().optional()
|
|
1189
|
+
});
|
|
1190
|
+
|
|
1191
|
+
// packages/keyd/src/account/ccdSigner.ts
|
|
1192
|
+
var index2 = z10.string().regex(/^(0|[1-9][0-9]{0,2})$/);
|
|
1193
|
+
var signatureMap = z10.record(index2, z10.record(index2, z10.string().regex(/^[0-9a-f]{128}$/)));
|
|
1194
|
+
var signOutputSchema = z10.object({
|
|
1195
|
+
address: z10.string(),
|
|
1196
|
+
roleSigned: z10.enum(["sender", "sponsor"]),
|
|
1197
|
+
newSignature: signatureMap
|
|
1198
|
+
});
|
|
1199
|
+
|
|
1200
|
+
// packages/keyd/src/account/agentWalletProof.ts
|
|
1201
|
+
function agentWalletProof(wallet, input) {
|
|
1202
|
+
const key = wallet.keys.find((k) => k.credential === 0 && k.key === 0);
|
|
1203
|
+
if (key === void 0) throw new KeydError("key_file_invalid", "the wallet export has no credential 0 key 0");
|
|
1204
|
+
const message = setAgentWalletMessage({
|
|
1205
|
+
tokenId: input.tokenId,
|
|
1206
|
+
owner: input.owner,
|
|
1207
|
+
newWallet: wallet.addressBytes,
|
|
1208
|
+
walletSetNonce: input.walletSetNonce,
|
|
1209
|
+
deadline: input.deadline,
|
|
1210
|
+
...input.contract === void 0 ? {} : { contract: input.contract },
|
|
1211
|
+
...input.genesis === void 0 ? {} : { genesis: input.genesis }
|
|
1212
|
+
});
|
|
1213
|
+
if (message.length !== SET_AGENT_WALLET_MESSAGE_LENGTH) {
|
|
1214
|
+
throw new KeydError("internal", `setAgentWallet message is ${message.length} bytes, expected ${SET_AGENT_WALLET_MESSAGE_LENGTH}`);
|
|
1215
|
+
}
|
|
1216
|
+
const signature = key.secret.sign(message);
|
|
1217
|
+
const accountSignatures = singleKeyAccountSignatures(signature);
|
|
1218
|
+
const parameter = encodeSetAgentWalletParams({
|
|
1219
|
+
tokenId: input.tokenId,
|
|
1220
|
+
newWallet: wallet.addressBytes,
|
|
1221
|
+
deadline: input.deadline,
|
|
1222
|
+
signature: accountSignatures
|
|
1223
|
+
});
|
|
1224
|
+
return { newWallet: wallet.address, message, signature, accountSignatures, parameter };
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
// packages/registry/src/cis8.ts
|
|
1228
|
+
function writeExternalKeyId(w, key) {
|
|
1229
|
+
return w.string(key.namespace).string(key.keyType).bytestring(fromHex2(key.publicKey, "public key"));
|
|
1230
|
+
}
|
|
1231
|
+
function serializeExternalKeyId(key) {
|
|
1232
|
+
return writeExternalKeyId(new ByteWriter(), key).finish();
|
|
1233
|
+
}
|
|
1234
|
+
function readExternalKeyId(r, field) {
|
|
1235
|
+
const namespace = r.string(`${field}.namespace`);
|
|
1236
|
+
const keyType = r.string(`${field}.key_type`);
|
|
1237
|
+
const publicKey = toHex2(r.bytestring(`${field}.public_key`));
|
|
1238
|
+
return { namespace, keyType, publicKey };
|
|
1239
|
+
}
|
|
1240
|
+
function externalKeyIdEquals(a, b) {
|
|
1241
|
+
return bytesEqual2(serializeExternalKeyId(a), serializeExternalKeyId(b));
|
|
1242
|
+
}
|
|
1243
|
+
function readStatus(r, field) {
|
|
1244
|
+
const at = r.offset;
|
|
1245
|
+
const tag = r.u8(field);
|
|
1246
|
+
if (tag === 0) return "Active";
|
|
1247
|
+
if (tag === 1) return "Revoked";
|
|
1248
|
+
return r.fail(`${field}: unknown status tag ${tag}`, at);
|
|
1249
|
+
}
|
|
1250
|
+
function readRegistration(r) {
|
|
1251
|
+
const owner = accountToBase58(r.bytes(32, "owner"));
|
|
1252
|
+
const externalKey = readExternalKeyId(r, "external_key");
|
|
1253
|
+
const proofScheme = r.string("proof_scheme");
|
|
1254
|
+
const count = r.u32("metadata count");
|
|
1255
|
+
const metadata = [];
|
|
1256
|
+
for (let i = 0; i < count; i++) {
|
|
1257
|
+
if (r.remaining < 8) r.fail(`metadata[${i}]: truncated`);
|
|
1258
|
+
metadata.push({ key: r.string(`metadata[${i}].key`), value: r.string(`metadata[${i}].value`) });
|
|
1259
|
+
}
|
|
1260
|
+
const status = readStatus(r, "status");
|
|
1261
|
+
const lastUpdated = r.u64("last_updated");
|
|
1262
|
+
return { owner, externalKey, proofScheme, metadata, status, lastUpdated };
|
|
1263
|
+
}
|
|
1264
|
+
function parseOwnerOfKeyResponse(bytes) {
|
|
1265
|
+
const r = new ByteReader(bytes, "CIS-8.ownerOfKey");
|
|
1266
|
+
const reg = r.option("registration", () => readRegistration(r));
|
|
1267
|
+
r.end();
|
|
1268
|
+
return reg;
|
|
1269
|
+
}
|
|
1270
|
+
function isKeyBoundTo(reg, owner, pinned) {
|
|
1271
|
+
if (!reg || reg.status !== "Active") return false;
|
|
1272
|
+
if (!bytesEqual2(accountFromBase58(reg.owner), accountFromBase58(owner))) return false;
|
|
1273
|
+
return externalKeyIdEquals(reg.externalKey, pinned);
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
// packages/registry/src/badge.ts
|
|
1277
|
+
import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
|
|
1278
|
+
|
|
1279
|
+
// packages/registry/src/safeFetch.ts
|
|
1280
|
+
import { lookup as dnsLookup } from "node:dns/promises";
|
|
1281
|
+
import { Agent, buildConnector, request } from "undici";
|
|
1282
|
+
|
|
1283
|
+
// packages/registry/src/ip.ts
|
|
1284
|
+
function parseIPv4(s) {
|
|
1285
|
+
const parts = s.split(".");
|
|
1286
|
+
if (parts.length !== 4) return null;
|
|
1287
|
+
const out = new Uint8Array(4);
|
|
1288
|
+
for (let i = 0; i < 4; i++) {
|
|
1289
|
+
const p = parts[i];
|
|
1290
|
+
if (!/^(?:0|[1-9][0-9]{0,2})$/.test(p)) return null;
|
|
1291
|
+
const v = Number(p);
|
|
1292
|
+
if (v > 255) return null;
|
|
1293
|
+
out[i] = v;
|
|
1294
|
+
}
|
|
1295
|
+
return out;
|
|
1296
|
+
}
|
|
1297
|
+
function parseIPv6(input) {
|
|
1298
|
+
let s = input;
|
|
1299
|
+
if (s.startsWith("[") && s.endsWith("]")) s = s.slice(1, -1);
|
|
1300
|
+
if (s.length === 0 || s.length > 45 || s.includes("%")) return null;
|
|
1301
|
+
const words2 = [];
|
|
1302
|
+
let tail = [];
|
|
1303
|
+
let compressed = false;
|
|
1304
|
+
const dbl = s.indexOf("::");
|
|
1305
|
+
if (dbl !== -1) {
|
|
1306
|
+
if (s.indexOf("::", dbl + 1) !== -1) return null;
|
|
1307
|
+
compressed = true;
|
|
1308
|
+
}
|
|
1309
|
+
const parseGroups = (part, allowV4Tail) => {
|
|
1310
|
+
if (part === "") return [];
|
|
1311
|
+
const groups = part.split(":");
|
|
1312
|
+
const out2 = [];
|
|
1313
|
+
for (let i = 0; i < groups.length; i++) {
|
|
1314
|
+
const g = groups[i];
|
|
1315
|
+
if (allowV4Tail && i === groups.length - 1 && g.includes(".")) {
|
|
1316
|
+
const v4 = parseIPv4(g);
|
|
1317
|
+
if (!v4) return null;
|
|
1318
|
+
out2.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
|
|
1319
|
+
continue;
|
|
1320
|
+
}
|
|
1321
|
+
if (!/^[0-9a-fA-F]{1,4}$/.test(g)) return null;
|
|
1322
|
+
out2.push(Number.parseInt(g, 16));
|
|
1323
|
+
}
|
|
1324
|
+
return out2;
|
|
1325
|
+
};
|
|
1326
|
+
if (compressed) {
|
|
1327
|
+
const head = parseGroups(s.slice(0, dbl), false);
|
|
1328
|
+
const rest = parseGroups(s.slice(dbl + 2), true);
|
|
1329
|
+
if (!head || !rest) return null;
|
|
1330
|
+
if (head.length + rest.length > 7) return null;
|
|
1331
|
+
words2.push(...head);
|
|
1332
|
+
tail = rest;
|
|
1333
|
+
while (words2.length + tail.length < 8) words2.push(0);
|
|
1334
|
+
words2.push(...tail);
|
|
1335
|
+
} else {
|
|
1336
|
+
const all = parseGroups(s, true);
|
|
1337
|
+
if (!all || all.length !== 8) return null;
|
|
1338
|
+
words2.push(...all);
|
|
1339
|
+
}
|
|
1340
|
+
const out = new Uint8Array(16);
|
|
1341
|
+
for (let i = 0; i < 8; i++) {
|
|
1342
|
+
out[2 * i] = words2[i] >> 8;
|
|
1343
|
+
out[2 * i + 1] = words2[i] & 255;
|
|
1344
|
+
}
|
|
1345
|
+
return out;
|
|
1346
|
+
}
|
|
1347
|
+
function inPrefix(addr, prefix, bits) {
|
|
1348
|
+
for (let i = 0; i < bits; i++) {
|
|
1349
|
+
const byte = i >> 3;
|
|
1350
|
+
const mask = 128 >> (i & 7);
|
|
1351
|
+
if ((addr[byte] & mask) !== ((prefix[byte] ?? 0) & mask)) return false;
|
|
1352
|
+
}
|
|
1353
|
+
return true;
|
|
1354
|
+
}
|
|
1355
|
+
var V4_BLOCKS = [
|
|
1356
|
+
[[0, 0, 0, 0], 8, "unspecified"],
|
|
1357
|
+
// "this network"
|
|
1358
|
+
[[10, 0, 0, 0], 8, "private"],
|
|
1359
|
+
[[100, 64, 0, 0], 10, "cgnat"],
|
|
1360
|
+
[[127, 0, 0, 0], 8, "loopback"],
|
|
1361
|
+
[[169, 254, 0, 0], 16, "link-local"],
|
|
1362
|
+
[[172, 16, 0, 0], 12, "private"],
|
|
1363
|
+
[[192, 0, 0, 0], 24, "reserved"],
|
|
1364
|
+
// IETF protocol assignments
|
|
1365
|
+
[[192, 0, 2, 0], 24, "documentation"],
|
|
1366
|
+
[[192, 88, 99, 0], 24, "reserved"],
|
|
1367
|
+
// deprecated 6to4 relay anycast
|
|
1368
|
+
[[192, 168, 0, 0], 16, "private"],
|
|
1369
|
+
[[198, 18, 0, 0], 15, "benchmarking"],
|
|
1370
|
+
[[198, 51, 100, 0], 24, "documentation"],
|
|
1371
|
+
[[203, 0, 113, 0], 24, "documentation"],
|
|
1372
|
+
[[224, 0, 0, 0], 4, "multicast"],
|
|
1373
|
+
[[255, 255, 255, 255], 32, "broadcast"],
|
|
1374
|
+
[[240, 0, 0, 0], 4, "reserved"]
|
|
1375
|
+
];
|
|
1376
|
+
function classifyIPv4Bytes(a) {
|
|
1377
|
+
for (const [prefix, bits, reason] of V4_BLOCKS) {
|
|
1378
|
+
if (inPrefix(a, prefix, bits)) return { version: 4, allowed: false, reason };
|
|
1379
|
+
}
|
|
1380
|
+
return { version: 4, allowed: true, reason: void 0 };
|
|
1381
|
+
}
|
|
1382
|
+
function words(a) {
|
|
1383
|
+
const w = [];
|
|
1384
|
+
for (let i = 0; i < 8; i++) w.push(a[2 * i] << 8 | a[2 * i + 1]);
|
|
1385
|
+
return w;
|
|
1386
|
+
}
|
|
1387
|
+
function embedded(a) {
|
|
1388
|
+
const v4 = a.slice(12, 16);
|
|
1389
|
+
const inner = classifyIPv4Bytes(v4);
|
|
1390
|
+
const embeddedIPv4 = `${v4[0]}.${v4[1]}.${v4[2]}.${v4[3]}`;
|
|
1391
|
+
return { version: 6, allowed: inner.allowed, reason: inner.reason, embeddedIPv4 };
|
|
1392
|
+
}
|
|
1393
|
+
function classifyIPv6Bytes(a) {
|
|
1394
|
+
const w = words(a);
|
|
1395
|
+
const block = (reason) => ({ version: 6, allowed: false, reason });
|
|
1396
|
+
const zeroUpTo = (n) => w.slice(0, n).every((x) => x === 0);
|
|
1397
|
+
if (zeroUpTo(8)) return block("unspecified");
|
|
1398
|
+
if (zeroUpTo(7) && w[7] === 1) return block("loopback");
|
|
1399
|
+
if (zeroUpTo(5) && w[5] === 65535) return embedded(a);
|
|
1400
|
+
if (w[0] === 100 && w[1] === 65435 && w.slice(2, 6).every((x) => x === 0)) return embedded(a);
|
|
1401
|
+
const first = w[0];
|
|
1402
|
+
if ((first & 65280) === 65280) return block("multicast");
|
|
1403
|
+
if ((first & 65472) === 65152) return block("link-local");
|
|
1404
|
+
if ((first & 65472) === 65216) return block("private");
|
|
1405
|
+
if ((first & 65024) === 64512) return block("private");
|
|
1406
|
+
if ((first & 57344) !== 8192) return block("reserved");
|
|
1407
|
+
if (first === 8193 && w[1] === 3512) return block("documentation");
|
|
1408
|
+
if (first === 8193 && (w[1] & 65024) === 0) return block("reserved");
|
|
1409
|
+
if (first === 8194) return block("reserved");
|
|
1410
|
+
if ((first & 65520) === 16368) return block("documentation");
|
|
1411
|
+
return { version: 6, allowed: true, reason: void 0 };
|
|
1412
|
+
}
|
|
1413
|
+
function classifyIp(address) {
|
|
1414
|
+
const v4 = parseIPv4(address);
|
|
1415
|
+
if (v4) return classifyIPv4Bytes(v4);
|
|
1416
|
+
const v6 = parseIPv6(address);
|
|
1417
|
+
if (v6) return classifyIPv6Bytes(v6);
|
|
1418
|
+
return { version: null, allowed: false, reason: "invalid" };
|
|
1419
|
+
}
|
|
1420
|
+
function ipKey(address) {
|
|
1421
|
+
const v4 = parseIPv4(address);
|
|
1422
|
+
if (v4) return v4.join(".");
|
|
1423
|
+
const v6 = parseIPv6(address);
|
|
1424
|
+
if (!v6) return null;
|
|
1425
|
+
const w = words(v6);
|
|
1426
|
+
if (w.slice(0, 5).every((x) => x === 0) && w[5] === 65535) return Array.from(v6.slice(12)).join(".");
|
|
1427
|
+
return Array.from(v6, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
// packages/registry/src/safeFetch.ts
|
|
1431
|
+
var SafeFetchError = class extends Error {
|
|
1432
|
+
name = "SafeFetchError";
|
|
1433
|
+
code;
|
|
1434
|
+
/** The URL being fetched when the error happened (userinfo never included). */
|
|
1435
|
+
url;
|
|
1436
|
+
constructor(code, message, url, cause) {
|
|
1437
|
+
super(`${code}: ${message}`, cause === void 0 ? void 0 : { cause });
|
|
1438
|
+
this.code = code;
|
|
1439
|
+
this.url = url;
|
|
1440
|
+
}
|
|
1441
|
+
};
|
|
1442
|
+
var SAFE_FETCH_DEFAULTS = Object.freeze({ maxBytes: 65536, timeoutMs: 5e3, maxRedirects: 3 });
|
|
1443
|
+
var REDIRECTS = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
1444
|
+
var FORBIDDEN_HEADERS = /* @__PURE__ */ new Set(["host", "cookie", "authorization", "proxy-authorization", "connection", "transfer-encoding"]);
|
|
1445
|
+
var systemResolver = async (hostname) => {
|
|
1446
|
+
const rows = await dnsLookup(hostname, { all: true, verbatim: true });
|
|
1447
|
+
return rows.map((r) => ({ address: r.address, family: r.family === 6 ? 6 : 4 }));
|
|
1448
|
+
};
|
|
1449
|
+
function display(url) {
|
|
1450
|
+
return `${url.protocol}//${url.host}${url.pathname}${url.search}`;
|
|
1451
|
+
}
|
|
1452
|
+
function normalizeOrigin(o) {
|
|
1453
|
+
try {
|
|
1454
|
+
return new URL(o).origin;
|
|
1455
|
+
} catch {
|
|
1456
|
+
throw new SafeFetchError("BAD_OPTION", `bad allow-list origin ${o}`);
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
function raceAbort(p, signal) {
|
|
1460
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
1461
|
+
return new Promise((resolve, reject) => {
|
|
1462
|
+
const onAbort = () => reject(signal.reason);
|
|
1463
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1464
|
+
p.then(
|
|
1465
|
+
(v) => {
|
|
1466
|
+
signal.removeEventListener("abort", onAbort);
|
|
1467
|
+
resolve(v);
|
|
1468
|
+
},
|
|
1469
|
+
(e) => {
|
|
1470
|
+
signal.removeEventListener("abort", onAbort);
|
|
1471
|
+
reject(e);
|
|
1472
|
+
}
|
|
1473
|
+
);
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
async function vet(url, allowed, resolve, signal) {
|
|
1477
|
+
const testOrigin = allowed.has(url.origin);
|
|
1478
|
+
if (url.protocol !== "https:" && !(testOrigin && url.protocol === "http:")) {
|
|
1479
|
+
throw new SafeFetchError("SCHEME_NOT_ALLOWED", `scheme ${url.protocol} is not allowed`, display(url));
|
|
1480
|
+
}
|
|
1481
|
+
if (url.username !== "" || url.password !== "") {
|
|
1482
|
+
throw new SafeFetchError("CREDENTIALS_IN_URL", "URLs with credentials are not fetched", display(url));
|
|
1483
|
+
}
|
|
1484
|
+
const host = url.hostname;
|
|
1485
|
+
if (host === "") throw new SafeFetchError("BAD_URL", "empty host", display(url));
|
|
1486
|
+
let candidates;
|
|
1487
|
+
const literal4 = parseIPv4(host);
|
|
1488
|
+
const literal6 = literal4 ? null : host.startsWith("[") ? parseIPv6(host) : null;
|
|
1489
|
+
if (literal4) candidates = [{ address: host, family: 4 }];
|
|
1490
|
+
else if (literal6) candidates = [{ address: host.slice(1, -1), family: 6 }];
|
|
1491
|
+
else {
|
|
1492
|
+
let answers;
|
|
1493
|
+
try {
|
|
1494
|
+
answers = await raceAbort(resolve(host), signal);
|
|
1495
|
+
} catch (e) {
|
|
1496
|
+
if (signal.aborted) throw e;
|
|
1497
|
+
throw new SafeFetchError("DNS_FAILED", `cannot resolve ${host}`, display(url), e);
|
|
1498
|
+
}
|
|
1499
|
+
if (answers.length === 0) throw new SafeFetchError("DNS_FAILED", `no addresses for ${host}`, display(url));
|
|
1500
|
+
candidates = answers.map((a) => ({ address: a.address, family: parseIPv4(a.address) ? 4 : 6 }));
|
|
1501
|
+
}
|
|
1502
|
+
if (!testOrigin) {
|
|
1503
|
+
for (const c of candidates) {
|
|
1504
|
+
const cls = classifyIp(c.address);
|
|
1505
|
+
if (!cls.allowed) {
|
|
1506
|
+
throw new SafeFetchError("BLOCKED_ADDRESS", `${host} resolves to ${c.address} (${cls.reason})`, display(url));
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
const pinned = candidates.find((c) => c.family === 4) ?? candidates[0];
|
|
1511
|
+
if (!pinned || ipKey(pinned.address) === null) {
|
|
1512
|
+
throw new SafeFetchError("DNS_FAILED", `unusable address for ${host}`, display(url));
|
|
1513
|
+
}
|
|
1514
|
+
return pinned;
|
|
1515
|
+
}
|
|
1516
|
+
function pinnedConnector(target, timeoutMs) {
|
|
1517
|
+
const lookup = (_hostname, options, callback) => {
|
|
1518
|
+
if (options.all) callback(null, [{ address: target.address, family: target.family }]);
|
|
1519
|
+
else callback(null, target.address, target.family);
|
|
1520
|
+
};
|
|
1521
|
+
const base = buildConnector({ lookup, timeout: timeoutMs });
|
|
1522
|
+
const want = ipKey(target.address);
|
|
1523
|
+
return (opts, callback) => {
|
|
1524
|
+
base(opts, (err, socket) => {
|
|
1525
|
+
if (err !== null) {
|
|
1526
|
+
callback(err, null);
|
|
1527
|
+
return;
|
|
1528
|
+
}
|
|
1529
|
+
const remote = socket.remoteAddress;
|
|
1530
|
+
if (remote === void 0 || ipKey(remote) !== want) {
|
|
1531
|
+
socket.destroy();
|
|
1532
|
+
callback(new SafeFetchError("BLOCKED_ADDRESS", `connected to ${remote ?? "unknown"}, pinned ${target.address}`), null);
|
|
1533
|
+
return;
|
|
1534
|
+
}
|
|
1535
|
+
callback(null, socket);
|
|
1536
|
+
});
|
|
1537
|
+
};
|
|
1538
|
+
}
|
|
1539
|
+
function discard(body) {
|
|
1540
|
+
body.on("error", () => void 0);
|
|
1541
|
+
body.destroy();
|
|
1542
|
+
}
|
|
1543
|
+
function flattenHeaders(h) {
|
|
1544
|
+
const out = {};
|
|
1545
|
+
for (const [k, v] of Object.entries(h)) {
|
|
1546
|
+
if (v === void 0) continue;
|
|
1547
|
+
out[k.toLowerCase()] = Array.isArray(v) ? v.join(", ") : v;
|
|
1548
|
+
}
|
|
1549
|
+
return out;
|
|
1550
|
+
}
|
|
1551
|
+
async function safeFetch(input, opts = {}) {
|
|
1552
|
+
const maxBytes = opts.maxBytes ?? SAFE_FETCH_DEFAULTS.maxBytes;
|
|
1553
|
+
const timeoutMs = opts.timeoutMs ?? SAFE_FETCH_DEFAULTS.timeoutMs;
|
|
1554
|
+
const maxRedirects = opts.maxRedirects ?? SAFE_FETCH_DEFAULTS.maxRedirects;
|
|
1555
|
+
const resolve = opts.resolve ?? systemResolver;
|
|
1556
|
+
const allowed = new Set((opts.testOnlyAllowOrigins ?? []).map(normalizeOrigin));
|
|
1557
|
+
const headers = {
|
|
1558
|
+
accept: "application/json, */*;q=0.5",
|
|
1559
|
+
"accept-encoding": "identity",
|
|
1560
|
+
"user-agent": "opentab-registry/0.0"
|
|
1561
|
+
};
|
|
1562
|
+
for (const [k, v] of Object.entries(opts.headers ?? {})) {
|
|
1563
|
+
if (FORBIDDEN_HEADERS.has(k.toLowerCase())) throw new SafeFetchError("BAD_OPTION", `header ${k} may not be set`);
|
|
1564
|
+
headers[k.toLowerCase()] = v;
|
|
1565
|
+
}
|
|
1566
|
+
let url;
|
|
1567
|
+
try {
|
|
1568
|
+
url = typeof input === "string" ? new URL(input) : new URL(input.href);
|
|
1569
|
+
} catch (e) {
|
|
1570
|
+
throw new SafeFetchError("BAD_URL", "not an absolute URL", void 0, e);
|
|
1571
|
+
}
|
|
1572
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
1573
|
+
const signal = opts.signal ? AbortSignal.any([opts.signal, timeout]) : timeout;
|
|
1574
|
+
const deadline = Date.now() + timeoutMs;
|
|
1575
|
+
const redirects = [];
|
|
1576
|
+
try {
|
|
1577
|
+
for (let hop = 0; ; hop++) {
|
|
1578
|
+
const target = await vet(url, allowed, resolve, signal);
|
|
1579
|
+
const remaining = Math.max(1, deadline - Date.now());
|
|
1580
|
+
const agent = new Agent({ connect: pinnedConnector(target, remaining), connections: 1, pipelining: 1, allowH2: false });
|
|
1581
|
+
try {
|
|
1582
|
+
const res = await request(url, {
|
|
1583
|
+
dispatcher: agent,
|
|
1584
|
+
method: "GET",
|
|
1585
|
+
headers,
|
|
1586
|
+
signal,
|
|
1587
|
+
headersTimeout: remaining,
|
|
1588
|
+
bodyTimeout: remaining
|
|
1589
|
+
});
|
|
1590
|
+
const resHeaders = flattenHeaders(res.headers);
|
|
1591
|
+
const location = resHeaders.location;
|
|
1592
|
+
if (REDIRECTS.has(res.statusCode) && location !== void 0) {
|
|
1593
|
+
discard(res.body);
|
|
1594
|
+
if (hop >= maxRedirects) {
|
|
1595
|
+
throw new SafeFetchError("TOO_MANY_REDIRECTS", `more than ${maxRedirects} redirects`, display(url));
|
|
1596
|
+
}
|
|
1597
|
+
let next;
|
|
1598
|
+
try {
|
|
1599
|
+
next = new URL(location, url);
|
|
1600
|
+
} catch (e) {
|
|
1601
|
+
throw new SafeFetchError("BAD_REDIRECT", "unparseable Location header", display(url), e);
|
|
1602
|
+
}
|
|
1603
|
+
url = next;
|
|
1604
|
+
redirects.push(display(url));
|
|
1605
|
+
continue;
|
|
1606
|
+
}
|
|
1607
|
+
const declared = resHeaders["content-length"];
|
|
1608
|
+
if (declared !== void 0 && /^[0-9]+$/.test(declared) && Number(declared) > maxBytes) {
|
|
1609
|
+
discard(res.body);
|
|
1610
|
+
throw new SafeFetchError("TOO_LARGE", `declared ${declared} bytes, cap is ${maxBytes}`, display(url));
|
|
1611
|
+
}
|
|
1612
|
+
const chunks = [];
|
|
1613
|
+
let total = 0;
|
|
1614
|
+
for await (const chunk of res.body) {
|
|
1615
|
+
const c = chunk;
|
|
1616
|
+
total += c.length;
|
|
1617
|
+
if (total > maxBytes) {
|
|
1618
|
+
discard(res.body);
|
|
1619
|
+
throw new SafeFetchError("TOO_LARGE", `body exceeds ${maxBytes} bytes`, display(url));
|
|
1620
|
+
}
|
|
1621
|
+
chunks.push(c);
|
|
1622
|
+
}
|
|
1623
|
+
return {
|
|
1624
|
+
url: display(url),
|
|
1625
|
+
status: res.statusCode,
|
|
1626
|
+
headers: resHeaders,
|
|
1627
|
+
body: concatBytes(...chunks),
|
|
1628
|
+
redirects,
|
|
1629
|
+
address: target.address
|
|
1630
|
+
};
|
|
1631
|
+
} finally {
|
|
1632
|
+
await agent.destroy().catch(() => void 0);
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
} catch (e) {
|
|
1636
|
+
if (timeout.aborted) {
|
|
1637
|
+
throw new SafeFetchError("TIMEOUT", `no complete response within ${timeoutMs} ms`, display(url), e);
|
|
1638
|
+
}
|
|
1639
|
+
if (e instanceof SafeFetchError) throw e;
|
|
1640
|
+
if (opts.signal?.aborted) throw new SafeFetchError("ABORTED", "aborted by caller", display(url), e);
|
|
1641
|
+
const cause = e?.cause;
|
|
1642
|
+
if (cause instanceof SafeFetchError) throw cause;
|
|
1643
|
+
const undiciCode = e?.code;
|
|
1644
|
+
if (undiciCode === "UND_ERR_CONNECT_TIMEOUT" || undiciCode === "UND_ERR_HEADERS_TIMEOUT" || undiciCode === "UND_ERR_BODY_TIMEOUT") {
|
|
1645
|
+
throw new SafeFetchError("TIMEOUT", `no complete response within ${timeoutMs} ms`, display(url), e);
|
|
1646
|
+
}
|
|
1647
|
+
throw new SafeFetchError("NETWORK", e?.message ?? String(e), display(url), e);
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
// packages/registry/src/badge.ts
|
|
1652
|
+
var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
1653
|
+
function isObject(v) {
|
|
1654
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1655
|
+
}
|
|
1656
|
+
function percentDecodeToBytes(s) {
|
|
1657
|
+
const out = [];
|
|
1658
|
+
const enc = new TextEncoder();
|
|
1659
|
+
let i = 0;
|
|
1660
|
+
while (i < s.length) {
|
|
1661
|
+
if (s[i] === "%" && /^[0-9a-fA-F]{2}$/.test(s.slice(i + 1, i + 3))) {
|
|
1662
|
+
out.push(Number.parseInt(s.slice(i + 1, i + 3), 16));
|
|
1663
|
+
i += 3;
|
|
1664
|
+
continue;
|
|
1665
|
+
}
|
|
1666
|
+
const ch = String.fromCodePoint(s.codePointAt(i));
|
|
1667
|
+
out.push(...enc.encode(ch));
|
|
1668
|
+
i += ch.length;
|
|
1669
|
+
}
|
|
1670
|
+
return Uint8Array.from(out);
|
|
1671
|
+
}
|
|
1672
|
+
function decodeDataUri(uri) {
|
|
1673
|
+
const m = /^data:([^,]*),(.*)$/s.exec(uri);
|
|
1674
|
+
if (!m) return null;
|
|
1675
|
+
const meta = m[1];
|
|
1676
|
+
const data = m[2];
|
|
1677
|
+
if (/;base64$/i.test(meta)) {
|
|
1678
|
+
let clean;
|
|
1679
|
+
try {
|
|
1680
|
+
clean = decodeURIComponent(data).replace(/\s+/g, "");
|
|
1681
|
+
} catch {
|
|
1682
|
+
return null;
|
|
1683
|
+
}
|
|
1684
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean) || clean.length % 4 === 1) return null;
|
|
1685
|
+
return Uint8Array.from(Buffer.from(clean, "base64"));
|
|
1686
|
+
}
|
|
1687
|
+
return percentDecodeToBytes(data);
|
|
1688
|
+
}
|
|
1689
|
+
async function fetchAgentCard(uri, opts = {}) {
|
|
1690
|
+
const maxBytes = opts.maxBytes ?? SAFE_FETCH_DEFAULTS.maxBytes;
|
|
1691
|
+
if (uri.startsWith("data:")) {
|
|
1692
|
+
const body = decodeDataUri(uri);
|
|
1693
|
+
if (body === null) return { ok: false, uri, error: "malformed data: URI" };
|
|
1694
|
+
if (body.length > maxBytes) return { ok: false, uri, error: `data: URI exceeds ${maxBytes} bytes` };
|
|
1695
|
+
return { ok: true, uri, body };
|
|
1696
|
+
}
|
|
1697
|
+
try {
|
|
1698
|
+
const res = await safeFetch(uri, opts);
|
|
1699
|
+
if (res.status !== 200) return { ok: false, uri, finalUrl: res.url, status: res.status, body: res.body, error: `HTTP ${res.status}` };
|
|
1700
|
+
return { ok: true, uri, finalUrl: res.url, status: res.status, body: res.body };
|
|
1701
|
+
} catch (e) {
|
|
1702
|
+
const msg = e instanceof SafeFetchError ? e.message : `fetch failed: ${e?.message ?? String(e)}`;
|
|
1703
|
+
return { ok: false, uri, error: msg };
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
function parseCaip10Account(v, chain = TESTNET_CAIP2) {
|
|
1707
|
+
if (typeof v !== "string" || !v.startsWith(`${chain}:`)) return null;
|
|
1708
|
+
const addr = v.slice(chain.length + 1);
|
|
1709
|
+
return isAccountAddress(addr) ? addr : null;
|
|
1710
|
+
}
|
|
1711
|
+
function acceptedVerifyUrls(badge) {
|
|
1712
|
+
const urls = /* @__PURE__ */ new Set();
|
|
1713
|
+
for (const path3 of ["check-badge", "badge-check"]) {
|
|
1714
|
+
urls.add(`${HOSTED_REST_BASE}/v1/${path3}/${badge}`);
|
|
1715
|
+
urls.add(`${HOSTED_REST_BASE}/v1/${path3}/${badge}?network=testnet`);
|
|
1716
|
+
}
|
|
1717
|
+
return urls;
|
|
1718
|
+
}
|
|
1719
|
+
function evaluateBadge(tokenIdInput, agent, card, chain = TESTNET_CAIP2) {
|
|
1720
|
+
const tokenId = toU64(tokenIdInput, "token id");
|
|
1721
|
+
const badge = agentBadge(tokenId);
|
|
1722
|
+
const issues = [];
|
|
1723
|
+
const checks = {
|
|
1724
|
+
on_chain_agent_found: agent !== null,
|
|
1725
|
+
status_active: agent?.status === "Active",
|
|
1726
|
+
has_agent_uri: typeof agent?.agentUri === "string" && agent.agentUri.length > 0,
|
|
1727
|
+
card_fetched: false,
|
|
1728
|
+
hash_matches_on_chain: false,
|
|
1729
|
+
badge_present: false,
|
|
1730
|
+
badge_embedding: "none",
|
|
1731
|
+
badge_well_formed: false,
|
|
1732
|
+
token_address_matches: false,
|
|
1733
|
+
owner_matches: false,
|
|
1734
|
+
contracts_match: false,
|
|
1735
|
+
verify_present: false,
|
|
1736
|
+
extension_conformant: false,
|
|
1737
|
+
verification_present: false,
|
|
1738
|
+
verify_url_matches: false,
|
|
1739
|
+
wallet_matches: false
|
|
1740
|
+
};
|
|
1741
|
+
if (!agent) issues.push("agent not found on chain");
|
|
1742
|
+
else if (agent.status !== "Active") issues.push("agent is revoked");
|
|
1743
|
+
if (agent && !checks.has_agent_uri) issues.push("agent has no agent_uri");
|
|
1744
|
+
let cardHash;
|
|
1745
|
+
let cardWallet = null;
|
|
1746
|
+
if (card) {
|
|
1747
|
+
checks.card_fetched = card.ok && card.body !== void 0;
|
|
1748
|
+
if (!checks.card_fetched) issues.push(`card not fetched: ${card.error ?? "unknown error"}`);
|
|
1749
|
+
}
|
|
1750
|
+
if (card?.ok && card.body) {
|
|
1751
|
+
cardHash = toHex2(sha2562(card.body));
|
|
1752
|
+
if (agent?.metadataHash) {
|
|
1753
|
+
checks.hash_matches_on_chain = cardHash === agent.metadataHash.toLowerCase();
|
|
1754
|
+
if (!checks.hash_matches_on_chain) issues.push("card SHA-256 differs from on-chain metadata_hash");
|
|
1755
|
+
} else issues.push("agent has no metadata_hash");
|
|
1756
|
+
let json;
|
|
1757
|
+
try {
|
|
1758
|
+
json = JSON.parse(UTF8.decode(card.body));
|
|
1759
|
+
} catch {
|
|
1760
|
+
issues.push("card is not valid UTF-8 JSON");
|
|
1761
|
+
}
|
|
1762
|
+
let params;
|
|
1763
|
+
if (isObject(json)) {
|
|
1764
|
+
const caps = json.capabilities;
|
|
1765
|
+
const exts = isObject(caps) && Array.isArray(caps.extensions) ? caps.extensions : [];
|
|
1766
|
+
const ext = exts.find((e) => isObject(e) && e.uri === BADGE_EXTENSION_URI);
|
|
1767
|
+
if (ext) {
|
|
1768
|
+
checks.badge_present = true;
|
|
1769
|
+
checks.badge_embedding = "extension";
|
|
1770
|
+
if (isObject(ext.params)) params = ext.params;
|
|
1771
|
+
checks.extension_conformant = isObject(ext.params) && (ext.required === void 0 || typeof ext.required === "boolean");
|
|
1772
|
+
if (!checks.extension_conformant) issues.push("badge extension is not conformant");
|
|
1773
|
+
} else if (isObject(json.concordium)) {
|
|
1774
|
+
checks.badge_present = true;
|
|
1775
|
+
checks.badge_embedding = "legacy";
|
|
1776
|
+
params = json.concordium;
|
|
1777
|
+
issues.push("badge uses the legacy top-level embedding");
|
|
1778
|
+
} else issues.push("card has no Concordium badge");
|
|
1779
|
+
}
|
|
1780
|
+
if (params) {
|
|
1781
|
+
const owner = params.owner;
|
|
1782
|
+
const contracts = params.contracts;
|
|
1783
|
+
checks.badge_well_formed = typeof params.tokenAddress === "string" && isObject(owner) && typeof owner.account === "string" && isObject(contracts) && typeof contracts.cis8004 === "string" && typeof contracts.cis8 === "string";
|
|
1784
|
+
if (!checks.badge_well_formed) issues.push("badge block is malformed");
|
|
1785
|
+
checks.token_address_matches = params.tokenAddress === `${chain}/cis-2:${badge}`;
|
|
1786
|
+
if (!checks.token_address_matches) issues.push("badge tokenAddress does not match");
|
|
1787
|
+
checks.owner_matches = agent !== null && isObject(owner) && owner.account === accountCaip10(agent.ownerAccount, chain);
|
|
1788
|
+
if (!checks.owner_matches) issues.push("badge owner does not match the on-chain owner");
|
|
1789
|
+
checks.contracts_match = isObject(contracts) && contracts.cis8004 === contractCaip(CIS8004.address, chain) && contracts.cis8 === contractCaip(CIS8.address, chain);
|
|
1790
|
+
if (!checks.contracts_match) issues.push("badge contracts do not match");
|
|
1791
|
+
checks.verify_present = typeof params.verify === "string" && params.verify.length > 0;
|
|
1792
|
+
if (!checks.verify_present) issues.push("badge has no verify text");
|
|
1793
|
+
const verification = params.verification;
|
|
1794
|
+
checks.verification_present = isObject(verification);
|
|
1795
|
+
if (!checks.verification_present) issues.push("badge has no verification block");
|
|
1796
|
+
checks.verify_url_matches = isObject(verification) && typeof verification.verifyUrl === "string" && acceptedVerifyUrls(badge).has(verification.verifyUrl);
|
|
1797
|
+
if (checks.verification_present && !checks.verify_url_matches) issues.push("badge verifyUrl does not match");
|
|
1798
|
+
cardWallet = parseCaip10Account(params.agentWallet, chain);
|
|
1799
|
+
if (params.agentWallet === void 0) issues.push("badge has no agentWallet");
|
|
1800
|
+
else if (cardWallet === null) issues.push("badge agentWallet is not a testnet account");
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
checks.wallet_matches = agent !== null && agent.agentWallet !== null && cardWallet !== null && cardWallet === agent.agentWallet;
|
|
1804
|
+
if (agent && agent.agentWallet === null) issues.push("registry has no agent_wallet");
|
|
1805
|
+
else if (cardWallet !== null && agent && !checks.wallet_matches) issues.push("card agentWallet differs from the registry wallet");
|
|
1806
|
+
const { wallet_matches: _w, badge_embedding: embedding, ...hostedEquivalent } = checks;
|
|
1807
|
+
const badgeValid = embedding === "extension" && Object.values(hostedEquivalent).every((v) => v === true);
|
|
1808
|
+
return {
|
|
1809
|
+
tokenId,
|
|
1810
|
+
badge,
|
|
1811
|
+
badgeValid,
|
|
1812
|
+
walletMatches: checks.wallet_matches,
|
|
1813
|
+
checks,
|
|
1814
|
+
issues,
|
|
1815
|
+
onChain: agent ? {
|
|
1816
|
+
ownerAccount: agent.ownerAccount,
|
|
1817
|
+
agentWallet: agent.agentWallet,
|
|
1818
|
+
status: agent.status,
|
|
1819
|
+
agentUri: agent.agentUri,
|
|
1820
|
+
metadataHash: agent.metadataHash
|
|
1821
|
+
} : null,
|
|
1822
|
+
card: card ? {
|
|
1823
|
+
uri: card.uri,
|
|
1824
|
+
finalUrl: card.finalUrl,
|
|
1825
|
+
status: card.status,
|
|
1826
|
+
sha256: cardHash,
|
|
1827
|
+
size: card.body?.length,
|
|
1828
|
+
wallet: cardWallet
|
|
1829
|
+
} : null
|
|
1830
|
+
};
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
export {
|
|
1834
|
+
writeExternalKeyId,
|
|
1835
|
+
serializeExternalKeyId,
|
|
1836
|
+
readExternalKeyId,
|
|
1837
|
+
externalKeyIdEquals,
|
|
1838
|
+
parseOwnerOfKeyResponse,
|
|
1839
|
+
isKeyBoundTo,
|
|
1840
|
+
fetchAgentCard,
|
|
1841
|
+
parseCaip10Account,
|
|
1842
|
+
acceptedVerifyUrls,
|
|
1843
|
+
evaluateBadge,
|
|
1844
|
+
TAB_AUTH_HEADER,
|
|
1845
|
+
encodeTabStatusRequestV1,
|
|
1846
|
+
encodeTabAuthHeader,
|
|
1847
|
+
defaultKeyDir,
|
|
1848
|
+
keyFilePath,
|
|
1849
|
+
readKeyFile,
|
|
1850
|
+
generateKeyFile,
|
|
1851
|
+
KeydClient,
|
|
1852
|
+
loadWalletExport,
|
|
1853
|
+
destroyWallet,
|
|
1854
|
+
KeyFileAccountSigner,
|
|
1855
|
+
agentWalletProof
|
|
1856
|
+
};
|