@arcblock/did 1.30.26 → 1.31.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/esm/did-domain-resolver.d.mts +450 -0
- package/esm/did-domain-resolver.mjs +1163 -0
- package/esm/index.d.mts +7 -5
- package/esm/index.mjs +7 -1
- package/esm/subaccount.d.mts +38 -0
- package/esm/subaccount.mjs +95 -0
- package/lib/did-domain-resolver.cjs +1190 -0
- package/lib/did-domain-resolver.d.cts +450 -0
- package/lib/index.cjs +41 -1
- package/lib/index.d.cts +8 -6
- package/lib/subaccount.cjs +98 -0
- package/lib/subaccount.d.cts +38 -0
- package/package.json +3 -3
|
@@ -0,0 +1,1163 @@
|
|
|
1
|
+
import { normalizeName } from "./name.mjs";
|
|
2
|
+
import { extractIdentifier, extractMethod, formatDid } from "./parse.mjs";
|
|
3
|
+
import { isSameEntity } from "./entity.mjs";
|
|
4
|
+
import { toBytes } from "./util.mjs";
|
|
5
|
+
import { isEthereumDid, toChecksumAddress, toTypeInfo, toTypeInfoStr } from "./type.mjs";
|
|
6
|
+
import { encodeLengthPrefixedTuple } from "./subaccount.mjs";
|
|
7
|
+
import { fromPublicKey, isValid } from "./index.mjs";
|
|
8
|
+
import { Hasher, getSigner, types } from "@ocap/mcrypto";
|
|
9
|
+
import { fromBase58, stripHexPrefix, toAddress, toBase58, toHex } from "@ocap/util";
|
|
10
|
+
|
|
11
|
+
//#region src/did-domain-resolver.ts
|
|
12
|
+
/**
|
|
13
|
+
* DID Domain Gateway (`did.abtnet.io`), DNS-NFT Ownership Binding,
|
|
14
|
+
* Cloudflare Worker 3-Tier Edge Router (`Custom Domain -> CNAME DID Domain -> Endpoint`),
|
|
15
|
+
* W3C DID v1.1 Document Synthesizer, and KERI-style Key Pre-Rotation Log.
|
|
16
|
+
*
|
|
17
|
+
* Issue #1291: Modernize `@arcblock/did` for deep `ARC` & `ArcSpace` integration
|
|
18
|
+
* while maintaining 100% backward compatibility with the 2018-2019 26-byte binary DID layout.
|
|
19
|
+
*/
|
|
20
|
+
const DEFAULT_DID_DOMAIN_GATEWAY = "did.abtnet.io";
|
|
21
|
+
const DNS_NFT_BINDING_DOMAIN_TAG = "arcblock:dns-nft-binding:v1";
|
|
22
|
+
const DID_ENDPOINT_DOMAIN_TAG = "arcblock:did-endpoint:v1";
|
|
23
|
+
const KEY_ROTATION_DOMAIN_TAG = "arcblock:did-key-rotation:v1";
|
|
24
|
+
const PRE_ROTATION_DOMAIN_TAG = "arcblock:did-pre-rotation:v1";
|
|
25
|
+
const MAX_ROTATION_CHAIN_LENGTH = 64;
|
|
26
|
+
const MAX_CUSTOM_DOMAINS_PER_DID = 32;
|
|
27
|
+
const SYNCHRONOUS_KEY_TYPES = new Set([
|
|
28
|
+
types.KeyType.ED25519,
|
|
29
|
+
types.KeyType.SECP256K1,
|
|
30
|
+
types.KeyType.ETHEREUM
|
|
31
|
+
]);
|
|
32
|
+
/**
|
|
33
|
+
* Verify whether `publicKeyHex` derives the unrotated genesis `did` (supporting both 26-byte ArcBlock DIDs
|
|
34
|
+
* and 20-byte case-insensitive Ethereum DIDs).
|
|
35
|
+
*/
|
|
36
|
+
function doesPublicKeyMatchGenesisDid(did, publicKeyHex) {
|
|
37
|
+
try {
|
|
38
|
+
if (!isValid(did)) return false;
|
|
39
|
+
const pkNormalized = `0x${stripHexPrefix(publicKeyHex).toLowerCase()}`;
|
|
40
|
+
const typeInfo = toTypeInfo(did);
|
|
41
|
+
if (typeInfo.pk === void 0) return false;
|
|
42
|
+
return isSameEntity(fromPublicKey(pkNormalized, typeInfo), toAddress(did));
|
|
43
|
+
} catch {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Strictly synchronous cryptographic signature verification that rejects async signers (`PASSKEY`)
|
|
49
|
+
* so a `Promise` return value can never be evaluated as truthy `true` or trigger an unhandled rejection.
|
|
50
|
+
*/
|
|
51
|
+
function verifySyncKeySignature(keyType, digestHex, signatureHex, publicKeyHex) {
|
|
52
|
+
if (!SYNCHRONOUS_KEY_TYPES.has(keyType)) return false;
|
|
53
|
+
try {
|
|
54
|
+
const result = getSigner(keyType).verify(digestHex, `0x${stripHexPrefix(signatureHex)}`, `0x${stripHexPrefix(publicKeyHex).toLowerCase()}`);
|
|
55
|
+
return typeof result === "boolean" && result === true;
|
|
56
|
+
} catch {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const BASE36_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
61
|
+
const DID_BYTES_LENGTH = 26;
|
|
62
|
+
const ETH_BYTES_LENGTH = 20;
|
|
63
|
+
const BASE36_DID_WIDTH = 41;
|
|
64
|
+
const BASE36_ETH_WIDTH = 31;
|
|
65
|
+
function bytesToBigInt(bytes) {
|
|
66
|
+
let result = 0n;
|
|
67
|
+
for (const b of bytes) result = result << 8n | BigInt(b);
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
function bigIntToFixedBytes(value, byteLength) {
|
|
71
|
+
if (value < 0n) throw new Error("Cannot encode negative bigint to bytes");
|
|
72
|
+
const out = new Uint8Array(byteLength);
|
|
73
|
+
let rem = value;
|
|
74
|
+
for (let i = byteLength - 1; i >= 0; i--) {
|
|
75
|
+
out[i] = Number(rem & 255n);
|
|
76
|
+
rem >>= 8n;
|
|
77
|
+
}
|
|
78
|
+
if (rem > 0n) throw new Error(`BigInt overflows target byte length (${byteLength})`);
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
function parseBase36ToBigInt(str) {
|
|
82
|
+
let result = 0n;
|
|
83
|
+
for (let i = 0; i < str.length; i++) {
|
|
84
|
+
const ch = str[i];
|
|
85
|
+
const idx = BASE36_ALPHABET.indexOf(ch);
|
|
86
|
+
if (idx === -1) throw new Error(`Invalid base36 character "${ch}"`);
|
|
87
|
+
result = result * 36n + BigInt(idx);
|
|
88
|
+
}
|
|
89
|
+
return result;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Convert a DID (e.g. `did:abt:z1...` or `z1...` or `0x...`) into a DNS-case-safe
|
|
93
|
+
* lowercase subdomain label suitable for `<label>.did.abtnet.io`.
|
|
94
|
+
*
|
|
95
|
+
* Why this is needed:
|
|
96
|
+
* - Standard Base58btc DIDs (`z1nYowHg...`) are case-sensitive.
|
|
97
|
+
* - DNS hostnames (RFC 4343 / browsers) fold all labels to lowercase.
|
|
98
|
+
* - `toDnsDidLabel` encodes the 26-byte binary DID into either:
|
|
99
|
+
* - `'base36'` (default): `k` + 41 lowercase base36 chars (42 chars total, <= 63 DNS limit)
|
|
100
|
+
* - `'hex'`: `f` + 52 lowercase hex chars (53 chars total, <= 63 DNS limit)
|
|
101
|
+
* - For 20-byte Ethereum DIDs (`0x...`): `e` + 31 base36 chars (or `0x` + 40 hex chars).
|
|
102
|
+
*/
|
|
103
|
+
function toDnsDidLabel(did, encoding = "base36") {
|
|
104
|
+
if (!did || typeof did !== "string") throw new Error("DID must be a non-empty string");
|
|
105
|
+
const address = toAddress(did.trim());
|
|
106
|
+
if (!isValid(address)) throw new Error(`Cannot encode invalid DID to DNS label: ${did}`);
|
|
107
|
+
if (isEthereumDid(address)) {
|
|
108
|
+
const cleanHex = stripHexPrefix(address).toLowerCase();
|
|
109
|
+
if (encoding === "hex") return `0x${cleanHex}`;
|
|
110
|
+
return `e${bytesToBigInt(Uint8Array.from(Buffer.from(cleanHex, "hex"))).toString(36).padStart(BASE36_ETH_WIDTH, "0")}`;
|
|
111
|
+
}
|
|
112
|
+
const rawBytes = Uint8Array.from(toBytes(address));
|
|
113
|
+
if (rawBytes.length !== DID_BYTES_LENGTH) throw new Error(`Unexpected DID byte length: ${rawBytes.length}`);
|
|
114
|
+
if (encoding === "hex") return `f${Buffer.from(rawBytes).toString("hex").toLowerCase()}`;
|
|
115
|
+
return `k${bytesToBigInt(rawBytes).toString(36).padStart(BASE36_DID_WIDTH, "0")}`;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Decode a DNS subdomain label (or raw DID string) back into a canonical,
|
|
119
|
+
* checksum-verified DID (`did:abt:z...` or `did:abt:0x...`).
|
|
120
|
+
*
|
|
121
|
+
* Supports:
|
|
122
|
+
* - `k<41-char-base36>` (26-byte ArcBlock binary DID)
|
|
123
|
+
* - `f<52-char-hex>` (26-byte ArcBlock binary DID in hex)
|
|
124
|
+
* - `e<31-char-base36>` or `0x<40-char-hex>` (20-byte Ethereum DID)
|
|
125
|
+
* - Case-preserved raw Base58btc DID (`z...`) when routed via Cloudflare Worker paths/headers
|
|
126
|
+
*/
|
|
127
|
+
function fromDnsDidLabel(label, method = "abt") {
|
|
128
|
+
if (!label || typeof label !== "string") throw new Error("DNS DID label must be a non-empty string");
|
|
129
|
+
const trimmed = label.trim();
|
|
130
|
+
if (!trimmed) throw new Error("DNS DID label cannot be empty");
|
|
131
|
+
if (isValid(trimmed)) {
|
|
132
|
+
const addr = toAddress(trimmed);
|
|
133
|
+
return formatDid(isEthereumDid(addr) ? toChecksumAddress(addr) : addr, method);
|
|
134
|
+
}
|
|
135
|
+
const lower = trimmed.toLowerCase();
|
|
136
|
+
if (lower.startsWith("k") && lower.length === BASE36_DID_WIDTH + 1) {
|
|
137
|
+
const bytes = bigIntToFixedBytes(parseBase36ToBigInt(lower.slice(1)), DID_BYTES_LENGTH);
|
|
138
|
+
const candidate = toBase58(`0x${Buffer.from(bytes).toString("hex")}`);
|
|
139
|
+
if (!isValid(candidate)) throw new Error(`Decoded base36 DNS label failed DID checksum validation: ${label}`);
|
|
140
|
+
return formatDid(candidate, method);
|
|
141
|
+
}
|
|
142
|
+
if (lower.startsWith("f") && lower.length === DID_BYTES_LENGTH * 2 + 1 && /^f[0-9a-f]{52}$/.test(lower)) {
|
|
143
|
+
const candidate = toBase58(`0x${lower.slice(1)}`);
|
|
144
|
+
if (!isValid(candidate)) throw new Error(`Decoded hex DNS label failed DID checksum validation: ${label}`);
|
|
145
|
+
return formatDid(candidate, method);
|
|
146
|
+
}
|
|
147
|
+
if (lower.startsWith("e") && lower.length === BASE36_ETH_WIDTH + 1) {
|
|
148
|
+
const bytes = bigIntToFixedBytes(parseBase36ToBigInt(lower.slice(1)), ETH_BYTES_LENGTH);
|
|
149
|
+
return formatDid(toChecksumAddress(`0x${Buffer.from(bytes).toString("hex")}`), method);
|
|
150
|
+
}
|
|
151
|
+
throw new Error(`Invalid or unrecognized DNS DID label: ${label}`);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Format the canonical DID Domain hostname (`<label>.did.abtnet.io`).
|
|
155
|
+
*/
|
|
156
|
+
function toDidDomainHost(did, gatewayDomain = DEFAULT_DID_DOMAIN_GATEWAY, encoding = "base36") {
|
|
157
|
+
const cleanGateway = normalizeName(gatewayDomain);
|
|
158
|
+
return `${toDnsDidLabel(did, encoding)}.${cleanGateway}`;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Extract and verify the canonical DID from a `<label>.did.abtnet.io` hostname.
|
|
162
|
+
*/
|
|
163
|
+
function extractDidFromDomainHost(hostname, gatewayDomain = DEFAULT_DID_DOMAIN_GATEWAY, method = "abt") {
|
|
164
|
+
if (!hostname || typeof hostname !== "string") return null;
|
|
165
|
+
try {
|
|
166
|
+
const cleanGateway = normalizeName(gatewayDomain);
|
|
167
|
+
const trimmedHost = hostname.trim().replace(/\.$/, "");
|
|
168
|
+
const lowerHost = trimmedHost.toLowerCase();
|
|
169
|
+
const suffix = `.${cleanGateway}`;
|
|
170
|
+
if (!lowerHost.endsWith(suffix)) return null;
|
|
171
|
+
const rawLabel = trimmedHost.slice(0, trimmedHost.length - suffix.length);
|
|
172
|
+
if (!rawLabel || rawLabel.includes(".")) return null;
|
|
173
|
+
return fromDnsDidLabel(rawLabel, method);
|
|
174
|
+
} catch {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Construct the canonical `.well-known` resolution URL for a DID via the DID Domain Gateway.
|
|
180
|
+
*/
|
|
181
|
+
function toDidWellKnownUrl(did, options = {}) {
|
|
182
|
+
const host = toDidDomainHost(did, options.gatewayDomain ?? DEFAULT_DID_DOMAIN_GATEWAY, options.encoding ?? "base36");
|
|
183
|
+
const doc = options.document ?? "did.json";
|
|
184
|
+
return `${options.protocol ?? "https"}://${host}/.well-known/${doc}`;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Normalize a public key (`0x` hex, raw hex, `z` Base58btc / Base58 string, or `Uint8Array`)
|
|
188
|
+
* into a canonical lowercase hex string (without `0x` prefix).
|
|
189
|
+
*/
|
|
190
|
+
function normalizePublicKeyHex(pk) {
|
|
191
|
+
try {
|
|
192
|
+
if (typeof pk !== "string") {
|
|
193
|
+
if (!pk || pk.length === 0) return "";
|
|
194
|
+
return stripHexPrefix(toHex(pk)).toLowerCase();
|
|
195
|
+
}
|
|
196
|
+
const trimmed = pk.trim();
|
|
197
|
+
if (!trimmed) return "";
|
|
198
|
+
if (trimmed.startsWith("z")) return stripHexPrefix(toHex(fromBase58(trimmed))).toLowerCase();
|
|
199
|
+
if (/^0x[0-9a-fA-F]+$/.test(trimmed) && trimmed.length % 2 === 0) return trimmed.slice(2).toLowerCase();
|
|
200
|
+
if (/^[0-9a-fA-F]+$/.test(trimmed) && trimmed.length % 2 === 0) return trimmed.toLowerCase();
|
|
201
|
+
return stripHexPrefix(toHex(fromBase58(trimmed))).toLowerCase();
|
|
202
|
+
} catch {
|
|
203
|
+
return "";
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Validate whether an input is a canonical 32-byte (64-hex-char) SHA3-256 pre-rotation commitment.
|
|
208
|
+
*/
|
|
209
|
+
function isValidPreRotationCommitment(commitment) {
|
|
210
|
+
if (typeof commitment !== "string") return false;
|
|
211
|
+
return /^(0x)?[0-9a-fA-F]{64}$/.test(commitment.trim());
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Normalize a pre-rotation commitment into canonical lowercase `0x<64-hex>`.
|
|
215
|
+
*/
|
|
216
|
+
function normalizePreRotationCommitment(commitment) {
|
|
217
|
+
if (!isValidPreRotationCommitment(commitment)) throw new Error("Invalid pre-rotation commitment: expected 32-byte (64-char) hex SHA3-256 digest");
|
|
218
|
+
return `0x${stripHexPrefix(commitment.trim()).toLowerCase()}`;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Compute a KERI-style pre-rotation commitment (`sha3-256` over domain tag + keyType + normalized publicKey).
|
|
222
|
+
* Even if the current hot key is compromised, an attacker cannot rotate the DID without the pre-committed key.
|
|
223
|
+
*/
|
|
224
|
+
function createPreRotationCommitment(nextPublicKey, nextKeyType = types.KeyType.ED25519) {
|
|
225
|
+
const pkHex = normalizePublicKeyHex(nextPublicKey);
|
|
226
|
+
if (!pkHex) throw new Error("nextPublicKey cannot be empty");
|
|
227
|
+
const tuple = encodeLengthPrefixedTuple([
|
|
228
|
+
PRE_ROTATION_DOMAIN_TAG,
|
|
229
|
+
String(nextKeyType),
|
|
230
|
+
pkHex
|
|
231
|
+
], 0);
|
|
232
|
+
return Hasher.SHA3.hash256(tuple, 1, "hex");
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Verify whether `publicKey` (and `keyType` or target `address` DID type) satisfies an active `commitment`.
|
|
236
|
+
*/
|
|
237
|
+
function verifyPreRotationCommitment(params) {
|
|
238
|
+
try {
|
|
239
|
+
if (!isValidPreRotationCommitment(params.commitment)) return false;
|
|
240
|
+
let keyType = params.keyType;
|
|
241
|
+
if (keyType === void 0 && params.address) {
|
|
242
|
+
if (!isValid(params.address)) return false;
|
|
243
|
+
keyType = toTypeInfo(params.address).pk;
|
|
244
|
+
}
|
|
245
|
+
const resolvedKeyType = keyType ?? types.KeyType.ED25519;
|
|
246
|
+
return stripHexPrefix(createPreRotationCommitment(params.publicKey, resolvedKeyType)).toLowerCase() === stripHexPrefix(params.commitment.trim()).toLowerCase();
|
|
247
|
+
} catch {
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
function encodeKeyRotationPayload(params) {
|
|
252
|
+
const tuple = encodeLengthPrefixedTuple([
|
|
253
|
+
KEY_ROTATION_DOMAIN_TAG,
|
|
254
|
+
toAddress(params.did),
|
|
255
|
+
stripHexPrefix(params.previousPublicKey).toLowerCase(),
|
|
256
|
+
stripHexPrefix(params.newPublicKey).toLowerCase(),
|
|
257
|
+
String(params.newKeyType),
|
|
258
|
+
params.nextKeyCommitment || "",
|
|
259
|
+
String(params.rotatedAt)
|
|
260
|
+
], params.seq);
|
|
261
|
+
return Hasher.SHA3.hash256(tuple, 1, "hex");
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Create a dual-signed Key Rotation Event (`previousKey` + `newKey`) for a DID.
|
|
265
|
+
*/
|
|
266
|
+
function createKeyRotationEvent(params) {
|
|
267
|
+
if (!isValid(params.did)) throw new Error(`Invalid DID for key rotation: ${params.did}`);
|
|
268
|
+
if (!Number.isSafeInteger(params.seq) || params.seq < 1 || params.seq > MAX_ROTATION_CHAIN_LENGTH) throw new Error(`Invalid rotation sequence number: ${params.seq}`);
|
|
269
|
+
const didType = toTypeInfo(params.did);
|
|
270
|
+
const prevKeyType = params.previousKeyType ?? didType.pk ?? types.KeyType.ED25519;
|
|
271
|
+
const nextKeyType = params.newKeyType ?? prevKeyType;
|
|
272
|
+
if (!SYNCHRONOUS_KEY_TYPES.has(prevKeyType) || !SYNCHRONOUS_KEY_TYPES.has(nextKeyType)) throw new Error("Key rotation events require synchronous cryptographic key types (ED25519, SECP256K1, ETHEREUM)");
|
|
273
|
+
const rotatedAt = params.rotatedAt ?? Math.floor(Date.now() / 1e3);
|
|
274
|
+
const prevPkClean = stripHexPrefix(params.previousPublicKey).toLowerCase();
|
|
275
|
+
const newPkClean = stripHexPrefix(params.newPublicKey).toLowerCase();
|
|
276
|
+
if (!prevPkClean || !newPkClean || prevPkClean === newPkClean) throw new Error("previousPublicKey and newPublicKey must be non-empty and distinct");
|
|
277
|
+
const digestHex = encodeKeyRotationPayload({
|
|
278
|
+
did: params.did,
|
|
279
|
+
seq: params.seq,
|
|
280
|
+
previousPublicKey: prevPkClean,
|
|
281
|
+
newPublicKey: newPkClean,
|
|
282
|
+
newKeyType: nextKeyType,
|
|
283
|
+
nextKeyCommitment: params.nextKeyCommitment,
|
|
284
|
+
rotatedAt
|
|
285
|
+
});
|
|
286
|
+
const prevSig = getSigner(prevKeyType).sign(digestHex, params.previousSecretKey, "hex");
|
|
287
|
+
const newSig = getSigner(nextKeyType).sign(digestHex, params.newSecretKey, "hex");
|
|
288
|
+
return {
|
|
289
|
+
domain: KEY_ROTATION_DOMAIN_TAG,
|
|
290
|
+
did: formatDid(toAddress(params.did), extractMethod(params.did) || "abt"),
|
|
291
|
+
seq: params.seq,
|
|
292
|
+
previousPublicKey: `0x${prevPkClean}`,
|
|
293
|
+
newPublicKey: `0x${newPkClean}`,
|
|
294
|
+
newKeyType: nextKeyType,
|
|
295
|
+
...params.nextKeyCommitment ? { nextKeyCommitment: params.nextKeyCommitment } : {},
|
|
296
|
+
rotatedAt,
|
|
297
|
+
previousKeySignature: `0x${stripHexPrefix(prevSig)}`,
|
|
298
|
+
newKeySignature: `0x${stripHexPrefix(newSig)}`
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Verify an offline Key Rotation Event Log (`KeyRotationEvent[]`) for a `did`.
|
|
303
|
+
*
|
|
304
|
+
* Enforces:
|
|
305
|
+
* 1. Genesis anchor: Event #1's `previousPublicKey` MUST derive `did` (`fromPublicKey` match),
|
|
306
|
+
* and if `genesisPreRotationCommitment` is provided, Event #1's `newPublicKey` must match it.
|
|
307
|
+
* 2. Hash/key continuity: Each subsequent event `seq = i` must have `previousPublicKey === event[i-1].newPublicKey`.
|
|
308
|
+
* 3. Pre-rotation commitment continuity: If `event[i-1].nextKeyCommitment` is present,
|
|
309
|
+
* `createPreRotationCommitment(event[i].newPublicKey, event[i].newKeyType)` MUST match it!
|
|
310
|
+
* 4. Dual signatures (`previousKeySignature` and `newKeySignature`) must be cryptographically valid.
|
|
311
|
+
*/
|
|
312
|
+
function verifyKeyRotationChain(params) {
|
|
313
|
+
try {
|
|
314
|
+
if (!isValid(params.did)) return {
|
|
315
|
+
valid: false,
|
|
316
|
+
activePublicKey: null,
|
|
317
|
+
activeKeyType: null,
|
|
318
|
+
reason: "INVALID_DID"
|
|
319
|
+
};
|
|
320
|
+
if (!Array.isArray(params.events) || params.events.length === 0) return {
|
|
321
|
+
valid: false,
|
|
322
|
+
activePublicKey: null,
|
|
323
|
+
activeKeyType: null,
|
|
324
|
+
reason: "EMPTY_ROTATION_CHAIN"
|
|
325
|
+
};
|
|
326
|
+
if (params.events.length > MAX_ROTATION_CHAIN_LENGTH) return {
|
|
327
|
+
valid: false,
|
|
328
|
+
activePublicKey: null,
|
|
329
|
+
activeKeyType: null,
|
|
330
|
+
reason: "ROTATION_CHAIN_TOO_LONG"
|
|
331
|
+
};
|
|
332
|
+
const targetAddr = toAddress(params.did);
|
|
333
|
+
let currentKeyType = toTypeInfo(targetAddr).pk ?? types.KeyType.ED25519;
|
|
334
|
+
let currentPkClean = "";
|
|
335
|
+
let pendingCommitment = params.genesisPreRotationCommitment;
|
|
336
|
+
let prevRotatedAt = 0;
|
|
337
|
+
for (let i = 0; i < params.events.length; i++) {
|
|
338
|
+
const ev = params.events[i];
|
|
339
|
+
if (!ev || ev.domain !== KEY_ROTATION_DOMAIN_TAG) return {
|
|
340
|
+
valid: false,
|
|
341
|
+
activePublicKey: null,
|
|
342
|
+
activeKeyType: null,
|
|
343
|
+
reason: "INVALID_EVENT_DOMAIN"
|
|
344
|
+
};
|
|
345
|
+
if (ev.seq !== i + 1) return {
|
|
346
|
+
valid: false,
|
|
347
|
+
activePublicKey: null,
|
|
348
|
+
activeKeyType: null,
|
|
349
|
+
reason: "NON_SEQUENTIAL_ROTATION_SEQ"
|
|
350
|
+
};
|
|
351
|
+
if (toAddress(ev.did) !== targetAddr) return {
|
|
352
|
+
valid: false,
|
|
353
|
+
activePublicKey: null,
|
|
354
|
+
activeKeyType: null,
|
|
355
|
+
reason: "DID_MISMATCH_IN_EVENT"
|
|
356
|
+
};
|
|
357
|
+
if (!Number.isSafeInteger(ev.rotatedAt) || ev.rotatedAt < prevRotatedAt) return {
|
|
358
|
+
valid: false,
|
|
359
|
+
activePublicKey: null,
|
|
360
|
+
activeKeyType: null,
|
|
361
|
+
reason: "ROTATION_TIMESTAMP_REGRESSION"
|
|
362
|
+
};
|
|
363
|
+
const evPrevPk = stripHexPrefix(ev.previousPublicKey).toLowerCase();
|
|
364
|
+
const evNewPk = stripHexPrefix(ev.newPublicKey).toLowerCase();
|
|
365
|
+
if (!evPrevPk || !evNewPk || evPrevPk === evNewPk) return {
|
|
366
|
+
valid: false,
|
|
367
|
+
activePublicKey: null,
|
|
368
|
+
activeKeyType: null,
|
|
369
|
+
reason: "INVALID_ROTATION_KEYS"
|
|
370
|
+
};
|
|
371
|
+
if (i === 0) {
|
|
372
|
+
if (!doesPublicKeyMatchGenesisDid(targetAddr, evPrevPk)) return {
|
|
373
|
+
valid: false,
|
|
374
|
+
activePublicKey: null,
|
|
375
|
+
activeKeyType: null,
|
|
376
|
+
reason: "GENESIS_PUBLIC_KEY_MISMATCH"
|
|
377
|
+
};
|
|
378
|
+
} else if (evPrevPk !== currentPkClean) return {
|
|
379
|
+
valid: false,
|
|
380
|
+
activePublicKey: null,
|
|
381
|
+
activeKeyType: null,
|
|
382
|
+
reason: "BROKEN_KEY_CONTINUITY"
|
|
383
|
+
};
|
|
384
|
+
if (pendingCommitment) {
|
|
385
|
+
if (!verifyPreRotationCommitment({
|
|
386
|
+
commitment: pendingCommitment,
|
|
387
|
+
publicKey: `0x${evNewPk}`,
|
|
388
|
+
keyType: ev.newKeyType
|
|
389
|
+
})) return {
|
|
390
|
+
valid: false,
|
|
391
|
+
activePublicKey: null,
|
|
392
|
+
activeKeyType: null,
|
|
393
|
+
reason: "PRE_ROTATION_COMMITMENT_MISMATCH"
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
if (ev.nextKeyCommitment !== void 0 && !isValidPreRotationCommitment(ev.nextKeyCommitment)) return {
|
|
397
|
+
valid: false,
|
|
398
|
+
activePublicKey: null,
|
|
399
|
+
activeKeyType: null,
|
|
400
|
+
reason: "INVALID_NEXT_KEY_COMMITMENT"
|
|
401
|
+
};
|
|
402
|
+
const digestHex = encodeKeyRotationPayload({
|
|
403
|
+
did: targetAddr,
|
|
404
|
+
seq: ev.seq,
|
|
405
|
+
previousPublicKey: evPrevPk,
|
|
406
|
+
newPublicKey: evNewPk,
|
|
407
|
+
newKeyType: ev.newKeyType,
|
|
408
|
+
nextKeyCommitment: ev.nextKeyCommitment,
|
|
409
|
+
rotatedAt: ev.rotatedAt
|
|
410
|
+
});
|
|
411
|
+
if (!verifySyncKeySignature(currentKeyType, digestHex, ev.previousKeySignature, evPrevPk)) return {
|
|
412
|
+
valid: false,
|
|
413
|
+
activePublicKey: null,
|
|
414
|
+
activeKeyType: null,
|
|
415
|
+
reason: "INVALID_PREVIOUS_KEY_SIGNATURE"
|
|
416
|
+
};
|
|
417
|
+
if (!verifySyncKeySignature(ev.newKeyType, digestHex, ev.newKeySignature, evNewPk)) return {
|
|
418
|
+
valid: false,
|
|
419
|
+
activePublicKey: null,
|
|
420
|
+
activeKeyType: null,
|
|
421
|
+
reason: "INVALID_NEW_KEY_SIGNATURE"
|
|
422
|
+
};
|
|
423
|
+
currentPkClean = evNewPk;
|
|
424
|
+
currentKeyType = ev.newKeyType;
|
|
425
|
+
pendingCommitment = ev.nextKeyCommitment;
|
|
426
|
+
prevRotatedAt = ev.rotatedAt;
|
|
427
|
+
}
|
|
428
|
+
if (params.expectedCurrentPublicKey) {
|
|
429
|
+
if (normalizePublicKeyHex(params.expectedCurrentPublicKey) !== currentPkClean) return {
|
|
430
|
+
valid: false,
|
|
431
|
+
activePublicKey: `0x${currentPkClean}`,
|
|
432
|
+
activeKeyType: currentKeyType,
|
|
433
|
+
reason: "EXPECTED_CURRENT_KEY_MISMATCH"
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
return {
|
|
437
|
+
valid: true,
|
|
438
|
+
activePublicKey: `0x${currentPkClean}`,
|
|
439
|
+
activeKeyType: currentKeyType,
|
|
440
|
+
...pendingCommitment ? { nextKeyCommitment: pendingCommitment } : {}
|
|
441
|
+
};
|
|
442
|
+
} catch (err) {
|
|
443
|
+
return {
|
|
444
|
+
valid: false,
|
|
445
|
+
activePublicKey: null,
|
|
446
|
+
activeKeyType: null,
|
|
447
|
+
reason: err?.message || "ROTATION_VERIFY_ERROR"
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Extract the plain `AccountPreRotationStateData` object from `IAccountState.data` or `itx.data`,
|
|
453
|
+
* supporting `{ typeUrl: 'json', value: { ... } }`, `{ type: 'json', value: { ... } }`, or a plain object.
|
|
454
|
+
*/
|
|
455
|
+
function extractAccountPreRotationData(rawData) {
|
|
456
|
+
if (!rawData || typeof rawData !== "object" || Array.isArray(rawData) || rawData instanceof Uint8Array) return null;
|
|
457
|
+
const obj = rawData;
|
|
458
|
+
if (obj.typeUrl === "json" || obj.type === "json" || typeof obj.typeUrl === "string") {
|
|
459
|
+
if (obj.value && typeof obj.value === "object" && !Array.isArray(obj.value) && !(obj.value instanceof Uint8Array)) return obj.value;
|
|
460
|
+
if (obj.value instanceof Uint8Array || typeof obj.value === "string" || Buffer.isBuffer(obj.value)) try {
|
|
461
|
+
const text = typeof obj.value === "string" ? obj.value : Buffer.from(obj.value).toString("utf8");
|
|
462
|
+
const parsed = JSON.parse(text);
|
|
463
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
|
|
464
|
+
} catch {
|
|
465
|
+
return null;
|
|
466
|
+
}
|
|
467
|
+
return null;
|
|
468
|
+
}
|
|
469
|
+
return obj;
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Construct a canonical `itx.data` payload (`{ type: 'json', value: ... }`) for `AccountMigrateTx`
|
|
473
|
+
* carrying a KERI `nextKeyCommitment` (for the next hop) and/or an inline `KeyRotationEvent`.
|
|
474
|
+
*/
|
|
475
|
+
function createAccountMigratePreRotationData(params) {
|
|
476
|
+
const value = { ...params.extra || {} };
|
|
477
|
+
if (params.purpose !== void 0) value.purpose = params.purpose;
|
|
478
|
+
if (params.nextKeyCommitment === null || params.nextKeyCommitment === "") value.nextKeyCommitment = null;
|
|
479
|
+
else if (params.nextKeyCommitment !== void 0) value.nextKeyCommitment = normalizePreRotationCommitment(params.nextKeyCommitment);
|
|
480
|
+
if (params.keyRotationEvent !== void 0) value.keyRotationEvent = params.keyRotationEvent;
|
|
481
|
+
return {
|
|
482
|
+
type: "json",
|
|
483
|
+
value
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Verify a single KERI `KeyRotationEvent` against an on-chain `account_migrate` transition
|
|
488
|
+
* (`senderAddress -> receiverAddress` with `receiverPublicKey` and optional `activePreRotationCommitment`).
|
|
489
|
+
*/
|
|
490
|
+
function verifySingleKeyRotationEvent(params) {
|
|
491
|
+
try {
|
|
492
|
+
const ev = params.event;
|
|
493
|
+
if (!ev || typeof ev !== "object" || ev.domain !== KEY_ROTATION_DOMAIN_TAG) return {
|
|
494
|
+
valid: false,
|
|
495
|
+
reason: "INVALID_EVENT_DOMAIN"
|
|
496
|
+
};
|
|
497
|
+
if (!Number.isSafeInteger(ev.seq) || ev.seq < 1 || ev.seq > MAX_ROTATION_CHAIN_LENGTH) return {
|
|
498
|
+
valid: false,
|
|
499
|
+
reason: "INVALID_ROTATION_SEQ"
|
|
500
|
+
};
|
|
501
|
+
if (params.expectedSeq !== void 0 && ev.seq !== params.expectedSeq) return {
|
|
502
|
+
valid: false,
|
|
503
|
+
reason: "NON_SEQUENTIAL_ROTATION_SEQ"
|
|
504
|
+
};
|
|
505
|
+
if (!Number.isSafeInteger(ev.rotatedAt) || ev.rotatedAt < 0) return {
|
|
506
|
+
valid: false,
|
|
507
|
+
reason: "INVALID_ROTATED_AT"
|
|
508
|
+
};
|
|
509
|
+
if (params.minRotatedAt !== void 0 && ev.rotatedAt < params.minRotatedAt) return {
|
|
510
|
+
valid: false,
|
|
511
|
+
reason: "ROTATION_TIMESTAMP_REGRESSION"
|
|
512
|
+
};
|
|
513
|
+
if (!isValid(ev.did) || !isValid(params.senderAddress) || !isValid(params.receiverAddress)) return {
|
|
514
|
+
valid: false,
|
|
515
|
+
reason: "INVALID_DID"
|
|
516
|
+
};
|
|
517
|
+
const expectedDid = params.expectedGenesisDid || (ev.seq === 1 ? params.senderAddress : void 0);
|
|
518
|
+
if (expectedDid) {
|
|
519
|
+
if (!isValid(expectedDid) || !isSameEntity(toAddress(ev.did), toAddress(expectedDid))) return {
|
|
520
|
+
valid: false,
|
|
521
|
+
reason: "DID_MISMATCH_IN_EVENT"
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
const senderType = toTypeInfo(params.senderAddress);
|
|
525
|
+
const receiverType = toTypeInfo(params.receiverAddress);
|
|
526
|
+
const prevKeyType = senderType.pk ?? types.KeyType.ED25519;
|
|
527
|
+
const expectedNewKeyType = receiverType.pk ?? types.KeyType.ED25519;
|
|
528
|
+
if (!SYNCHRONOUS_KEY_TYPES.has(prevKeyType) || !SYNCHRONOUS_KEY_TYPES.has(ev.newKeyType)) return {
|
|
529
|
+
valid: false,
|
|
530
|
+
reason: "UNSUPPORTED_ASYNC_KEY_TYPE"
|
|
531
|
+
};
|
|
532
|
+
if (ev.newKeyType !== expectedNewKeyType) return {
|
|
533
|
+
valid: false,
|
|
534
|
+
reason: "NEW_KEY_TYPE_MISMATCH"
|
|
535
|
+
};
|
|
536
|
+
const evPrevPk = normalizePublicKeyHex(ev.previousPublicKey);
|
|
537
|
+
const evNewPk = normalizePublicKeyHex(ev.newPublicKey);
|
|
538
|
+
const expectedNewPk = normalizePublicKeyHex(params.receiverPublicKey);
|
|
539
|
+
if (!evPrevPk || !evNewPk || evPrevPk === evNewPk || evNewPk !== expectedNewPk) return {
|
|
540
|
+
valid: false,
|
|
541
|
+
reason: "NEW_PUBLIC_KEY_MISMATCH"
|
|
542
|
+
};
|
|
543
|
+
if (!doesPublicKeyMatchGenesisDid(params.senderAddress, evPrevPk)) return {
|
|
544
|
+
valid: false,
|
|
545
|
+
reason: "SENDER_PUBLIC_KEY_MISMATCH"
|
|
546
|
+
};
|
|
547
|
+
if (!doesPublicKeyMatchGenesisDid(params.receiverAddress, evNewPk)) return {
|
|
548
|
+
valid: false,
|
|
549
|
+
reason: "RECEIVER_PUBLIC_KEY_MISMATCH"
|
|
550
|
+
};
|
|
551
|
+
if (params.activePreRotationCommitment) {
|
|
552
|
+
if (!verifyPreRotationCommitment({
|
|
553
|
+
commitment: params.activePreRotationCommitment,
|
|
554
|
+
publicKey: `0x${evNewPk}`,
|
|
555
|
+
keyType: ev.newKeyType
|
|
556
|
+
})) return {
|
|
557
|
+
valid: false,
|
|
558
|
+
reason: "PRE_ROTATION_COMMITMENT_MISMATCH"
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
if (ev.nextKeyCommitment !== void 0 && !isValidPreRotationCommitment(ev.nextKeyCommitment)) return {
|
|
562
|
+
valid: false,
|
|
563
|
+
reason: "INVALID_NEXT_KEY_COMMITMENT"
|
|
564
|
+
};
|
|
565
|
+
const digestHex = encodeKeyRotationPayload({
|
|
566
|
+
did: toAddress(ev.did),
|
|
567
|
+
seq: ev.seq,
|
|
568
|
+
previousPublicKey: evPrevPk,
|
|
569
|
+
newPublicKey: evNewPk,
|
|
570
|
+
newKeyType: ev.newKeyType,
|
|
571
|
+
nextKeyCommitment: ev.nextKeyCommitment,
|
|
572
|
+
rotatedAt: ev.rotatedAt
|
|
573
|
+
});
|
|
574
|
+
if (!verifySyncKeySignature(prevKeyType, digestHex, ev.previousKeySignature, evPrevPk)) return {
|
|
575
|
+
valid: false,
|
|
576
|
+
reason: "INVALID_PREVIOUS_KEY_SIGNATURE"
|
|
577
|
+
};
|
|
578
|
+
if (!verifySyncKeySignature(ev.newKeyType, digestHex, ev.newKeySignature, evNewPk)) return {
|
|
579
|
+
valid: false,
|
|
580
|
+
reason: "INVALID_NEW_KEY_SIGNATURE"
|
|
581
|
+
};
|
|
582
|
+
return {
|
|
583
|
+
valid: true,
|
|
584
|
+
...ev.nextKeyCommitment ? { nextKeyCommitment: normalizePreRotationCommitment(ev.nextKeyCommitment) } : {}
|
|
585
|
+
};
|
|
586
|
+
} catch (err) {
|
|
587
|
+
return {
|
|
588
|
+
valid: false,
|
|
589
|
+
reason: err?.message || "SINGLE_ROTATION_VERIFY_ERROR"
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* Verify that an on-chain OCAP `account_migrate` state chain (`migratedFrom` + `currentAddress` + `currentPublicKey`)
|
|
595
|
+
* is 100% cryptographically consistent with an off-chain KERI `KeyRotationEvent[]` log (`KEL`).
|
|
596
|
+
*
|
|
597
|
+
* In OCAP `account_migrate`, `migratedFrom` on the current terminal account is ordered newest-to-oldest:
|
|
598
|
+
* `[A_{n-1}, ..., A_1, A_0]`, where `A_0` is the genesis DID and `currentAddress` is `A_n`.
|
|
599
|
+
*/
|
|
600
|
+
function verifyAccountMigrationChainWithKel(params) {
|
|
601
|
+
if (!Array.isArray(params.migratedFrom) || !Array.isArray(params.events)) return {
|
|
602
|
+
valid: false,
|
|
603
|
+
activePublicKey: null,
|
|
604
|
+
activeKeyType: null,
|
|
605
|
+
reason: "INVALID_MIGRATION_INPUT"
|
|
606
|
+
};
|
|
607
|
+
if (params.migratedFrom.length !== params.events.length || params.events.length === 0) return {
|
|
608
|
+
valid: false,
|
|
609
|
+
activePublicKey: null,
|
|
610
|
+
activeKeyType: null,
|
|
611
|
+
reason: "MIGRATION_HOP_COUNT_MISMATCH"
|
|
612
|
+
};
|
|
613
|
+
if (!isValid(params.genesisDid) || !isValid(params.currentAddress)) return {
|
|
614
|
+
valid: false,
|
|
615
|
+
activePublicKey: null,
|
|
616
|
+
activeKeyType: null,
|
|
617
|
+
reason: "INVALID_DID"
|
|
618
|
+
};
|
|
619
|
+
for (const addr of params.migratedFrom) if (!isValid(addr)) return {
|
|
620
|
+
valid: false,
|
|
621
|
+
activePublicKey: null,
|
|
622
|
+
activeKeyType: null,
|
|
623
|
+
reason: "INVALID_DID"
|
|
624
|
+
};
|
|
625
|
+
const chronologicalAddresses = [...params.migratedFrom].reverse().map((a) => toAddress(a));
|
|
626
|
+
const currentAddrClean = toAddress(params.currentAddress);
|
|
627
|
+
const allLineageLower = [...chronologicalAddresses, currentAddrClean].map((a) => a.toLowerCase());
|
|
628
|
+
if (new Set(allLineageLower).size !== allLineageLower.length) return {
|
|
629
|
+
valid: false,
|
|
630
|
+
activePublicKey: null,
|
|
631
|
+
activeKeyType: null,
|
|
632
|
+
reason: "DUPLICATE_MIGRATION_ADDRESS"
|
|
633
|
+
};
|
|
634
|
+
if (!isSameEntity(chronologicalAddresses[0], toAddress(params.genesisDid))) return {
|
|
635
|
+
valid: false,
|
|
636
|
+
activePublicKey: null,
|
|
637
|
+
activeKeyType: null,
|
|
638
|
+
reason: "GENESIS_MIGRATED_FROM_MISMATCH"
|
|
639
|
+
};
|
|
640
|
+
const kelCheck = verifyKeyRotationChain({
|
|
641
|
+
did: params.genesisDid,
|
|
642
|
+
events: params.events,
|
|
643
|
+
expectedCurrentPublicKey: normalizePublicKeyHex(params.currentPublicKey),
|
|
644
|
+
genesisPreRotationCommitment: params.genesisPreRotationCommitment
|
|
645
|
+
});
|
|
646
|
+
if (!kelCheck.valid) return kelCheck;
|
|
647
|
+
for (let i = 0; i < params.events.length; i++) {
|
|
648
|
+
const ev = params.events[i];
|
|
649
|
+
const expectedFromAddr = chronologicalAddresses[i];
|
|
650
|
+
const expectedToAddr = i === params.events.length - 1 ? currentAddrClean : chronologicalAddresses[i + 1];
|
|
651
|
+
const expectedToKeyType = toTypeInfo(expectedToAddr).pk ?? types.KeyType.ED25519;
|
|
652
|
+
if (ev.newKeyType !== expectedToKeyType) return {
|
|
653
|
+
valid: false,
|
|
654
|
+
activePublicKey: null,
|
|
655
|
+
activeKeyType: null,
|
|
656
|
+
reason: "NEW_KEY_TYPE_MISMATCH"
|
|
657
|
+
};
|
|
658
|
+
if (!doesPublicKeyMatchGenesisDid(expectedFromAddr, ev.previousPublicKey)) return {
|
|
659
|
+
valid: false,
|
|
660
|
+
activePublicKey: null,
|
|
661
|
+
activeKeyType: null,
|
|
662
|
+
reason: "MIGRATION_HOP_FROM_ADDRESS_MISMATCH"
|
|
663
|
+
};
|
|
664
|
+
if (!doesPublicKeyMatchGenesisDid(expectedToAddr, ev.newPublicKey)) return {
|
|
665
|
+
valid: false,
|
|
666
|
+
activePublicKey: null,
|
|
667
|
+
activeKeyType: null,
|
|
668
|
+
reason: "MIGRATION_HOP_TO_ADDRESS_MISMATCH"
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
return kelCheck;
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* Synthesize a deterministic W3C DID v1.1 Document for any `did:abt:`, `did:spaces:`, `did:afs:`, or `did:aos:`.
|
|
675
|
+
*/
|
|
676
|
+
function synthesizeDidDocument(options) {
|
|
677
|
+
if (!options?.did || !isValid(options.did)) throw new Error(`Cannot synthesize DID Document for invalid DID: ${options?.did}`);
|
|
678
|
+
const method = extractMethod(options.did) || "abt";
|
|
679
|
+
const canonicalDid = formatDid(toAddress(options.did), method);
|
|
680
|
+
const typeStr = toTypeInfoStr(canonicalDid);
|
|
681
|
+
const didDomainHost = toDidDomainHost(canonicalDid, options.gatewayDomain ?? DEFAULT_DID_DOMAIN_GATEWAY);
|
|
682
|
+
let activePk = options.publicKey ? `0x${stripHexPrefix(options.publicKey).toLowerCase()}` : void 0;
|
|
683
|
+
let activeKeyTypeStr = typeStr.pk || "ED25519";
|
|
684
|
+
let activeCommitment = options.nextKeyCommitment;
|
|
685
|
+
if (options.keyRotationEvents && options.keyRotationEvents.length > 0) {
|
|
686
|
+
const rot = verifyKeyRotationChain({
|
|
687
|
+
did: canonicalDid,
|
|
688
|
+
events: options.keyRotationEvents,
|
|
689
|
+
expectedCurrentPublicKey: activePk
|
|
690
|
+
});
|
|
691
|
+
if (!rot.valid || !rot.activePublicKey) throw new Error(`Invalid keyRotationEvents for ${canonicalDid}: ${rot.reason}`);
|
|
692
|
+
activePk = rot.activePublicKey;
|
|
693
|
+
activeCommitment = rot.nextKeyCommitment ?? activeCommitment;
|
|
694
|
+
const keyNames = Object.keys(types.KeyType);
|
|
695
|
+
const idx = Object.values(types.KeyType).indexOf(rot.activeKeyType);
|
|
696
|
+
if (idx !== -1) activeKeyTypeStr = keyNames[idx];
|
|
697
|
+
} else if (activePk) {
|
|
698
|
+
if (!doesPublicKeyMatchGenesisDid(canonicalDid, activePk)) throw new Error(`Public key ${activePk} does not match unrotated DID ${canonicalDid}`);
|
|
699
|
+
}
|
|
700
|
+
const keyMethodId = `${canonicalDid}#key-1`;
|
|
701
|
+
const verificationMethods = [{
|
|
702
|
+
id: keyMethodId,
|
|
703
|
+
type: activeKeyTypeStr === "ED25519" ? "Ed25519VerificationKey2020" : activeKeyTypeStr === "PASSKEY" ? "JsonWebKey2020" : "EcdsaSecp256k1VerificationKey2019",
|
|
704
|
+
controller: canonicalDid,
|
|
705
|
+
...activePk ? { publicKeyHex: stripHexPrefix(activePk) } : {},
|
|
706
|
+
arcblockMeta: {
|
|
707
|
+
role: typeStr.role,
|
|
708
|
+
keyType: activeKeyTypeStr,
|
|
709
|
+
hashType: typeStr.hash
|
|
710
|
+
}
|
|
711
|
+
}];
|
|
712
|
+
const keyAgreementIds = [];
|
|
713
|
+
if (options.x25519PublicKey) {
|
|
714
|
+
const kaId = `${canonicalDid}#key-agreement-1`;
|
|
715
|
+
verificationMethods.push({
|
|
716
|
+
id: kaId,
|
|
717
|
+
type: "X25519KeyAgreementKey2020",
|
|
718
|
+
controller: canonicalDid,
|
|
719
|
+
publicKeyHex: stripHexPrefix(options.x25519PublicKey).toLowerCase()
|
|
720
|
+
});
|
|
721
|
+
keyAgreementIds.push(kaId);
|
|
722
|
+
}
|
|
723
|
+
const alsoKnownAs = [`https://${didDomainHost}`];
|
|
724
|
+
for (const dom of options.customDomains ?? []) if (dom.startsWith("did:name:")) alsoKnownAs.push(`did:name:${normalizeName(extractIdentifier(dom))}`);
|
|
725
|
+
else {
|
|
726
|
+
const cleanDom = normalizeName(dom);
|
|
727
|
+
alsoKnownAs.push(`did:name:${cleanDom}`);
|
|
728
|
+
alsoKnownAs.push(`https://${cleanDom}`);
|
|
729
|
+
}
|
|
730
|
+
const services = [{
|
|
731
|
+
id: `${canonicalDid}#did-resolver`,
|
|
732
|
+
type: "DIDResolverService",
|
|
733
|
+
serviceEndpoint: `https://${didDomainHost}/.well-known/did.json`,
|
|
734
|
+
description: "Canonical ArcBlock DID Domain Gateway resolver endpoint"
|
|
735
|
+
}];
|
|
736
|
+
if (options.arcSpaceEndpoint) services.push({
|
|
737
|
+
id: `${canonicalDid}#arc-space`,
|
|
738
|
+
type: "ArcSpacePDS",
|
|
739
|
+
serviceEndpoint: options.arcSpaceEndpoint,
|
|
740
|
+
description: "Holder-sovereign ArcSpace Personal Data Server"
|
|
741
|
+
});
|
|
742
|
+
if (options.afsEndpoint) services.push({
|
|
743
|
+
id: `${canonicalDid}#afs-agent`,
|
|
744
|
+
type: "AfsAgentEndpoint",
|
|
745
|
+
serviceEndpoint: options.afsEndpoint,
|
|
746
|
+
description: "ARC Agentic File System (AFS) action endpoint"
|
|
747
|
+
});
|
|
748
|
+
if (options.noiseMeshEndpoint) services.push({
|
|
749
|
+
id: `${canonicalDid}#noise-mesh`,
|
|
750
|
+
type: "NoiseMeshEndpoint",
|
|
751
|
+
serviceEndpoint: options.noiseMeshEndpoint,
|
|
752
|
+
description: "DID-Noise encrypted WireGuard-style mesh endpoint"
|
|
753
|
+
});
|
|
754
|
+
return {
|
|
755
|
+
"@context": ["https://www.w3.org/ns/did/v1", "https://w3id.org/security/multikey/v1"],
|
|
756
|
+
id: canonicalDid,
|
|
757
|
+
alsoKnownAs: [...new Set(alsoKnownAs)],
|
|
758
|
+
verificationMethod: verificationMethods,
|
|
759
|
+
authentication: [keyMethodId],
|
|
760
|
+
assertionMethod: [keyMethodId],
|
|
761
|
+
capabilityInvocation: [keyMethodId],
|
|
762
|
+
capabilityDelegation: [keyMethodId],
|
|
763
|
+
...keyAgreementIds.length > 0 ? { keyAgreement: keyAgreementIds } : {},
|
|
764
|
+
service: services,
|
|
765
|
+
...activeCommitment ? { nextKeyCommitment: activeCommitment } : {},
|
|
766
|
+
...options.keyRotationEvents?.length ? { keyRotationHistory: options.keyRotationEvents } : {}
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
const IPV4_OR_IPV6_REGEX = /^(?:\d{1,3}\.){3}\d{1,3}$|^\[?[0-9a-fA-F:]+\]?$/;
|
|
770
|
+
function encodeDidEndpointDigest(params) {
|
|
771
|
+
const tuple = encodeLengthPrefixedTuple([
|
|
772
|
+
DID_ENDPOINT_DOMAIN_TAG,
|
|
773
|
+
toAddress(params.did),
|
|
774
|
+
params.endpointUrl.trim()
|
|
775
|
+
], params.updatedAt);
|
|
776
|
+
return Hasher.SHA3.hash256(tuple, 1, "hex");
|
|
777
|
+
}
|
|
778
|
+
function encodeDomainNftBindingDigest(params) {
|
|
779
|
+
const tuple = encodeLengthPrefixedTuple([
|
|
780
|
+
DNS_NFT_BINDING_DOMAIN_TAG,
|
|
781
|
+
normalizeName(params.customDomain),
|
|
782
|
+
toAddress(params.domainNftAssetDid),
|
|
783
|
+
toAddress(params.ownerDid),
|
|
784
|
+
normalizeName(params.cnameTargetDidDomain),
|
|
785
|
+
String(params.issuedAt)
|
|
786
|
+
], params.expiresAt);
|
|
787
|
+
return Hasher.SHA3.hash256(tuple, 1, "hex");
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* Create a signed Domain-NFT Binding Proof authorizing the DID Name Server / Cloudflare Worker
|
|
791
|
+
* to bind `customDomain -> CNAME <label>.did.abtnet.io`.
|
|
792
|
+
*/
|
|
793
|
+
function createDomainNftBindingProof(params) {
|
|
794
|
+
const cleanDomain = normalizeName(params.customDomain.replace(/^did:name:/i, ""));
|
|
795
|
+
if (IPV4_OR_IPV6_REGEX.test(cleanDomain)) throw new Error("customDomain cannot be a raw IP address");
|
|
796
|
+
if (!isValid(params.domainNftAssetDid)) throw new Error(`Invalid domainNftAssetDid: ${params.domainNftAssetDid}`);
|
|
797
|
+
if (toTypeInfo(params.domainNftAssetDid).role !== types.RoleType.ROLE_ASSET) throw new Error("domainNftAssetDid must have ROLE_ASSET");
|
|
798
|
+
if (!isValid(params.ownerDid)) throw new Error(`Invalid ownerDid: ${params.ownerDid}`);
|
|
799
|
+
const gateway = params.gatewayDomain ?? DEFAULT_DID_DOMAIN_GATEWAY;
|
|
800
|
+
const cnameTargetDidDomain = toDidDomainHost(params.ownerDid, gateway);
|
|
801
|
+
const issuedAt = params.issuedAt ?? Math.floor(Date.now() / 1e3);
|
|
802
|
+
const expiresAt = params.expiresAt ?? 0;
|
|
803
|
+
if (!Number.isSafeInteger(issuedAt) || issuedAt < 0 || !Number.isSafeInteger(expiresAt) || expiresAt < 0) throw new Error("issuedAt and expiresAt must be non-negative safe integers");
|
|
804
|
+
const ownerType = toTypeInfo(params.ownerDid);
|
|
805
|
+
const digestHex = encodeDomainNftBindingDigest({
|
|
806
|
+
customDomain: cleanDomain,
|
|
807
|
+
domainNftAssetDid: params.domainNftAssetDid,
|
|
808
|
+
ownerDid: params.ownerDid,
|
|
809
|
+
cnameTargetDidDomain,
|
|
810
|
+
issuedAt,
|
|
811
|
+
expiresAt
|
|
812
|
+
});
|
|
813
|
+
const sigHex = getSigner(ownerType.pk).sign(digestHex, params.ownerSecretKey, "hex");
|
|
814
|
+
return {
|
|
815
|
+
domain: DNS_NFT_BINDING_DOMAIN_TAG,
|
|
816
|
+
customDomain: cleanDomain,
|
|
817
|
+
domainNftAssetDid: formatDid(toAddress(params.domainNftAssetDid), "abt"),
|
|
818
|
+
ownerDid: formatDid(toAddress(params.ownerDid), "abt"),
|
|
819
|
+
ownerPublicKey: `0x${stripHexPrefix(params.ownerPublicKey).toLowerCase()}`,
|
|
820
|
+
cnameTargetDidDomain,
|
|
821
|
+
issuedAt,
|
|
822
|
+
expiresAt,
|
|
823
|
+
ownerSignature: `0x${stripHexPrefix(sigHex)}`
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Verify a Domain-NFT Binding Proof against:
|
|
828
|
+
* 1. Canonical 3-Tier CNAME rule (`cnameTargetDidDomain` MUST decode to `ownerDid` under `gatewayDomain`, never a raw IP);
|
|
829
|
+
* 2. `domainNftAssetDid` role (`ROLE_ASSET`) and optional live `nftAssetState` ownership/domain match;
|
|
830
|
+
* 3. Cryptographic signature by `ownerDid` (`ownerPublicKey` or rotated key via `keyRotationEvents`).
|
|
831
|
+
*/
|
|
832
|
+
function verifyDomainNftBindingProof(proof, options = {}) {
|
|
833
|
+
try {
|
|
834
|
+
if (!proof || proof.domain !== DNS_NFT_BINDING_DOMAIN_TAG) return {
|
|
835
|
+
valid: false,
|
|
836
|
+
reason: "INVALID_BINDING_DOMAIN_TAG"
|
|
837
|
+
};
|
|
838
|
+
const cleanCustomDomain = normalizeName(proof.customDomain);
|
|
839
|
+
if (IPV4_OR_IPV6_REGEX.test(cleanCustomDomain)) return {
|
|
840
|
+
valid: false,
|
|
841
|
+
reason: "CUSTOM_DOMAIN_CANNOT_BE_RAW_IP"
|
|
842
|
+
};
|
|
843
|
+
if (!isValid(proof.domainNftAssetDid) || toTypeInfo(proof.domainNftAssetDid).role !== types.RoleType.ROLE_ASSET) return {
|
|
844
|
+
valid: false,
|
|
845
|
+
reason: "INVALID_DOMAIN_NFT_ASSET_DID"
|
|
846
|
+
};
|
|
847
|
+
if (!isValid(proof.ownerDid)) return {
|
|
848
|
+
valid: false,
|
|
849
|
+
reason: "INVALID_OWNER_DID"
|
|
850
|
+
};
|
|
851
|
+
const gateway = options.gatewayDomain ?? DEFAULT_DID_DOMAIN_GATEWAY;
|
|
852
|
+
if (IPV4_OR_IPV6_REGEX.test(proof.cnameTargetDidDomain)) return {
|
|
853
|
+
valid: false,
|
|
854
|
+
reason: "DIRECT_IP_BYPASS_FORBIDDEN"
|
|
855
|
+
};
|
|
856
|
+
const extractedDid = extractDidFromDomainHost(proof.cnameTargetDidDomain, gateway, "abt");
|
|
857
|
+
if (!extractedDid || toAddress(extractedDid) !== toAddress(proof.ownerDid)) return {
|
|
858
|
+
valid: false,
|
|
859
|
+
reason: "CNAME_TARGET_MUST_MATCH_OWNER_DID_DOMAIN"
|
|
860
|
+
};
|
|
861
|
+
if (proof.expiresAt > 0) {
|
|
862
|
+
if ((options.now ?? Math.floor(Date.now() / 1e3)) > proof.expiresAt) return {
|
|
863
|
+
valid: false,
|
|
864
|
+
reason: "BINDING_PROOF_EXPIRED"
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
if (options.nftAssetState) {
|
|
868
|
+
const st = options.nftAssetState;
|
|
869
|
+
if (toAddress(st.address) !== toAddress(proof.domainNftAssetDid)) return {
|
|
870
|
+
valid: false,
|
|
871
|
+
reason: "NFT_ASSET_ADDRESS_MISMATCH"
|
|
872
|
+
};
|
|
873
|
+
if (st.consumed) return {
|
|
874
|
+
valid: false,
|
|
875
|
+
reason: "DOMAIN_NFT_CONSUMED"
|
|
876
|
+
};
|
|
877
|
+
if (toAddress(st.owner) !== toAddress(proof.ownerDid)) return {
|
|
878
|
+
valid: false,
|
|
879
|
+
reason: "DOMAIN_NFT_OWNER_CHANGED"
|
|
880
|
+
};
|
|
881
|
+
const nftDomainRaw = st.data?.domain ?? st.moniker;
|
|
882
|
+
if (!nftDomainRaw || typeof nftDomainRaw !== "string" || !nftDomainRaw.trim()) return {
|
|
883
|
+
valid: false,
|
|
884
|
+
reason: "DOMAIN_NFT_MISSING_DOMAIN_METADATA"
|
|
885
|
+
};
|
|
886
|
+
if (normalizeName(String(nftDomainRaw)) !== cleanCustomDomain) return {
|
|
887
|
+
valid: false,
|
|
888
|
+
reason: "DOMAIN_NFT_NAME_MISMATCH"
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
let signerKeyType = toTypeInfo(proof.ownerDid).pk ?? types.KeyType.ED25519;
|
|
892
|
+
const pkClean = stripHexPrefix(proof.ownerPublicKey).toLowerCase();
|
|
893
|
+
if (options.keyRotationEvents && options.keyRotationEvents.length > 0) {
|
|
894
|
+
const rot = verifyKeyRotationChain({
|
|
895
|
+
did: proof.ownerDid,
|
|
896
|
+
events: options.keyRotationEvents,
|
|
897
|
+
expectedCurrentPublicKey: pkClean
|
|
898
|
+
});
|
|
899
|
+
if (!rot.valid || rot.activeKeyType === null) return {
|
|
900
|
+
valid: false,
|
|
901
|
+
reason: `KEY_ROTATION_INVALID:${rot.reason}`
|
|
902
|
+
};
|
|
903
|
+
signerKeyType = rot.activeKeyType;
|
|
904
|
+
} else if (!doesPublicKeyMatchGenesisDid(proof.ownerDid, pkClean)) return {
|
|
905
|
+
valid: false,
|
|
906
|
+
reason: "OWNER_PUBLIC_KEY_MISMATCH"
|
|
907
|
+
};
|
|
908
|
+
const digestHex = encodeDomainNftBindingDigest({
|
|
909
|
+
customDomain: cleanCustomDomain,
|
|
910
|
+
domainNftAssetDid: proof.domainNftAssetDid,
|
|
911
|
+
ownerDid: proof.ownerDid,
|
|
912
|
+
cnameTargetDidDomain: proof.cnameTargetDidDomain,
|
|
913
|
+
issuedAt: proof.issuedAt,
|
|
914
|
+
expiresAt: proof.expiresAt
|
|
915
|
+
});
|
|
916
|
+
if (!verifySyncKeySignature(signerKeyType, digestHex, proof.ownerSignature, pkClean)) return {
|
|
917
|
+
valid: false,
|
|
918
|
+
reason: "INVALID_OWNER_SIGNATURE"
|
|
919
|
+
};
|
|
920
|
+
return { valid: true };
|
|
921
|
+
} catch (err) {
|
|
922
|
+
return {
|
|
923
|
+
valid: false,
|
|
924
|
+
reason: err?.message || "BINDING_VERIFY_ERROR"
|
|
925
|
+
};
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Cloudflare Worker & `ARC` Edge DID Domain Router (`Custom Domain -> CNAME DID Domain -> Endpoint`).
|
|
930
|
+
*
|
|
931
|
+
* Implements `NameRegistry` so it can also act as the backing store for `DIDNameResolver`.
|
|
932
|
+
* Supports wildcard `<label>.did.abtnet.io` resolution with zero pre-registration needed
|
|
933
|
+
* for the DID identity layer, plus NFT-verified custom domain bindings.
|
|
934
|
+
*/
|
|
935
|
+
var DIDDomainEdgeRouter = class {
|
|
936
|
+
constructor(options = {}) {
|
|
937
|
+
this.bindingsByDomain = /* @__PURE__ */ new Map();
|
|
938
|
+
this.nftStateByDomain = /* @__PURE__ */ new Map();
|
|
939
|
+
this.endpointsByDidAddr = /* @__PURE__ */ new Map();
|
|
940
|
+
this.simpleNameMap = /* @__PURE__ */ new Map();
|
|
941
|
+
this.gatewayDomain = normalizeName(options.gatewayDomain ?? DEFAULT_DID_DOMAIN_GATEWAY);
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Register or update a Tier-3 physical/tunnel endpoint for a DID (`<label>.did.abtnet.io -> endpoint`).
|
|
945
|
+
* Updating Tier 3 never requires changing Tier 1 (`Custom Domain -> CNAME DID Domain`).
|
|
946
|
+
*
|
|
947
|
+
* Security invariants:
|
|
948
|
+
* - If `keyRotationEvents` or `publicKey` is supplied, it is cryptographically validated against `did` immediately.
|
|
949
|
+
* - Supports cryptographic authentication via `secretKey` or `publicKey + endpointSignature`.
|
|
950
|
+
* - Once an endpoint for a DID is cryptographically authenticated (`authenticated: true`), any subsequent
|
|
951
|
+
* update MUST also be cryptographically authenticated with `updatedAt >= existing.updatedAt`.
|
|
952
|
+
*/
|
|
953
|
+
registerDidEndpoint(input) {
|
|
954
|
+
if (!isValid(input.did)) throw new Error(`Invalid DID for endpoint registration: ${input.did}`);
|
|
955
|
+
if (!input.endpointUrl || typeof input.endpointUrl !== "string" || !input.endpointUrl.trim()) throw new Error("endpointUrl must be a non-empty string");
|
|
956
|
+
const addr = toAddress(input.did);
|
|
957
|
+
const canonicalDid = formatDid(addr, extractMethod(input.did) || "abt");
|
|
958
|
+
const cleanEndpointUrl = input.endpointUrl.trim();
|
|
959
|
+
const updatedAt = input.updatedAt ?? Math.floor(Date.now() / 1e3);
|
|
960
|
+
if (!Number.isSafeInteger(updatedAt) || updatedAt < 0) throw new Error("updatedAt must be a non-negative safe integer");
|
|
961
|
+
const existing = this.endpointsByDidAddr.get(addr);
|
|
962
|
+
if (existing && updatedAt < existing.updatedAt) throw new Error("STALE_ENDPOINT_UPDATE: updatedAt cannot regress below existing record");
|
|
963
|
+
const effectiveRotationEvents = input.keyRotationEvents ?? existing?.keyRotationEvents;
|
|
964
|
+
let activeKeyType = toTypeInfo(canonicalDid).pk ?? types.KeyType.ED25519;
|
|
965
|
+
let verifiedPkHex = input.publicKey ? `0x${stripHexPrefix(input.publicKey).toLowerCase()}` : void 0;
|
|
966
|
+
if (effectiveRotationEvents && effectiveRotationEvents.length > 0) {
|
|
967
|
+
const rot = verifyKeyRotationChain({
|
|
968
|
+
did: canonicalDid,
|
|
969
|
+
events: effectiveRotationEvents,
|
|
970
|
+
expectedCurrentPublicKey: verifiedPkHex
|
|
971
|
+
});
|
|
972
|
+
if (!rot.valid || !rot.activePublicKey || rot.activeKeyType === null) throw new Error(`Invalid keyRotationEvents for endpoint registration: ${rot.reason}`);
|
|
973
|
+
verifiedPkHex = rot.activePublicKey;
|
|
974
|
+
activeKeyType = rot.activeKeyType;
|
|
975
|
+
} else if (verifiedPkHex) {
|
|
976
|
+
if (!doesPublicKeyMatchGenesisDid(canonicalDid, verifiedPkHex)) throw new Error(`Public key ${verifiedPkHex} does not match unrotated DID ${canonicalDid}`);
|
|
977
|
+
}
|
|
978
|
+
let endpointSignature;
|
|
979
|
+
let authenticated = false;
|
|
980
|
+
if (input.secretKey !== void 0 || input.endpointSignature !== void 0) {
|
|
981
|
+
if (!SYNCHRONOUS_KEY_TYPES.has(activeKeyType)) throw new Error("Authenticated endpoint registration requires a synchronous key type");
|
|
982
|
+
const digestHex = encodeDidEndpointDigest({
|
|
983
|
+
did: canonicalDid,
|
|
984
|
+
endpointUrl: cleanEndpointUrl,
|
|
985
|
+
updatedAt
|
|
986
|
+
});
|
|
987
|
+
if (input.secretKey !== void 0) {
|
|
988
|
+
const derivedPk = `0x${stripHexPrefix(String(getSigner(activeKeyType).getPublicKey(input.secretKey, "hex"))).toLowerCase()}`;
|
|
989
|
+
if (verifiedPkHex && derivedPk !== verifiedPkHex) throw new Error("secretKey does not match provided or active publicKey");
|
|
990
|
+
if (!effectiveRotationEvents?.length && !doesPublicKeyMatchGenesisDid(canonicalDid, derivedPk)) throw new Error(`secretKey does not match unrotated DID ${canonicalDid}`);
|
|
991
|
+
verifiedPkHex = derivedPk;
|
|
992
|
+
endpointSignature = `0x${stripHexPrefix(getSigner(activeKeyType).sign(digestHex, input.secretKey, "hex"))}`;
|
|
993
|
+
authenticated = true;
|
|
994
|
+
} else if (input.endpointSignature !== void 0) {
|
|
995
|
+
if (!verifiedPkHex) throw new Error("publicKey (or keyRotationEvents) is required when verifying endpointSignature");
|
|
996
|
+
if (!verifySyncKeySignature(activeKeyType, digestHex, input.endpointSignature, verifiedPkHex)) throw new Error("INVALID_ENDPOINT_SIGNATURE: endpointSignature verification failed");
|
|
997
|
+
endpointSignature = `0x${stripHexPrefix(input.endpointSignature)}`;
|
|
998
|
+
authenticated = true;
|
|
999
|
+
}
|
|
1000
|
+
} else if (existing?.authenticated) throw new Error("UNAUTHORIZED_ENDPOINT_OVERWRITE: existing endpoint is cryptographically authenticated");
|
|
1001
|
+
const record = {
|
|
1002
|
+
did: canonicalDid,
|
|
1003
|
+
didDomainHost: toDidDomainHost(canonicalDid, this.gatewayDomain),
|
|
1004
|
+
endpointUrl: cleanEndpointUrl,
|
|
1005
|
+
...input.ipOrMeshAddress ? { ipOrMeshAddress: input.ipOrMeshAddress.trim() } : {},
|
|
1006
|
+
...verifiedPkHex ? { publicKey: verifiedPkHex } : {},
|
|
1007
|
+
...input.x25519PublicKey ? { x25519PublicKey: input.x25519PublicKey } : {},
|
|
1008
|
+
...input.afsEndpoint ? { afsEndpoint: input.afsEndpoint } : {},
|
|
1009
|
+
...input.nextKeyCommitment ? { nextKeyCommitment: input.nextKeyCommitment } : {},
|
|
1010
|
+
...effectiveRotationEvents ? { keyRotationEvents: effectiveRotationEvents } : {},
|
|
1011
|
+
...authenticated ? {
|
|
1012
|
+
authenticated: true,
|
|
1013
|
+
endpointSignature
|
|
1014
|
+
} : {},
|
|
1015
|
+
updatedAt
|
|
1016
|
+
};
|
|
1017
|
+
this.endpointsByDidAddr.set(addr, record);
|
|
1018
|
+
return record;
|
|
1019
|
+
}
|
|
1020
|
+
/**
|
|
1021
|
+
* Register a Tier-1 -> Tier-2 custom domain binding verified by an on-chain DNS Domain NFT proof.
|
|
1022
|
+
*/
|
|
1023
|
+
registerDomainNftBinding(proof, options = {}) {
|
|
1024
|
+
const check = verifyDomainNftBindingProof(proof, {
|
|
1025
|
+
gatewayDomain: this.gatewayDomain,
|
|
1026
|
+
nftAssetState: options.nftAssetState,
|
|
1027
|
+
keyRotationEvents: options.keyRotationEvents,
|
|
1028
|
+
now: options.now
|
|
1029
|
+
});
|
|
1030
|
+
if (!check.valid) throw new Error(`Domain NFT binding verification failed: ${check.reason}`);
|
|
1031
|
+
const cleanDomain = normalizeName(proof.customDomain);
|
|
1032
|
+
this.bindingsByDomain.set(cleanDomain, proof);
|
|
1033
|
+
if (options.nftAssetState) this.nftStateByDomain.set(cleanDomain, options.nftAssetState);
|
|
1034
|
+
this.simpleNameMap.set(cleanDomain, proof.ownerDid);
|
|
1035
|
+
return proof;
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* Update the cached on-chain DNS Domain NFT state snapshot for a custom domain
|
|
1039
|
+
* (e.g., when an indexer or chain listener observes an NFT transfer or consumption).
|
|
1040
|
+
*/
|
|
1041
|
+
updateDomainNftState(customDomain, nftAssetState) {
|
|
1042
|
+
const cleanDomain = normalizeName(customDomain.replace(/^did:name:/i, ""));
|
|
1043
|
+
this.nftStateByDomain.set(cleanDomain, nftAssetState);
|
|
1044
|
+
}
|
|
1045
|
+
/**
|
|
1046
|
+
* Resolve any hostname, `did:name:`, `<label>.did.abtnet.io`, or `did:abt:` across all 3 tiers:
|
|
1047
|
+
* `Custom Domain (Tier 1) -> CNAME <label>.did.abtnet.io (Tier 2) -> Endpoint & DID Document (Tier 3)`.
|
|
1048
|
+
*/
|
|
1049
|
+
resolveThreeTier(queryInput, options = {}) {
|
|
1050
|
+
if (!queryInput || typeof queryInput !== "string") return null;
|
|
1051
|
+
const trimmed = queryInput.trim();
|
|
1052
|
+
const trace = [];
|
|
1053
|
+
if (trimmed.startsWith("did:") && !trimmed.startsWith("did:name:")) {
|
|
1054
|
+
if (!isValid(trimmed)) return null;
|
|
1055
|
+
const canonicalDid = formatDid(toAddress(trimmed), extractMethod(trimmed) || "abt");
|
|
1056
|
+
const cnameTarget = toDidDomainHost(canonicalDid, this.gatewayDomain);
|
|
1057
|
+
trace.push(`did:${canonicalDid}`, `cname:${cnameTarget}`);
|
|
1058
|
+
return this._buildResult(trimmed, void 0, void 0, cnameTarget, canonicalDid, trace);
|
|
1059
|
+
}
|
|
1060
|
+
const wildcardDid = extractDidFromDomainHost(trimmed, this.gatewayDomain, "abt");
|
|
1061
|
+
if (wildcardDid) {
|
|
1062
|
+
const cnameTarget = toDidDomainHost(wildcardDid, this.gatewayDomain);
|
|
1063
|
+
trace.push(`wildcard_did_domain:${cnameTarget}`, `did:${wildcardDid}`);
|
|
1064
|
+
return this._buildResult(trimmed, void 0, void 0, cnameTarget, wildcardDid, trace);
|
|
1065
|
+
}
|
|
1066
|
+
try {
|
|
1067
|
+
const cleanName = normalizeName(trimmed.replace(/^did:name:/i, ""));
|
|
1068
|
+
const binding = this.bindingsByDomain.get(cleanName);
|
|
1069
|
+
if (binding) {
|
|
1070
|
+
const effectiveNftState = options.nftAssetState ?? this.nftStateByDomain.get(cleanName);
|
|
1071
|
+
const recheck = verifyDomainNftBindingProof(binding, {
|
|
1072
|
+
gatewayDomain: this.gatewayDomain,
|
|
1073
|
+
nftAssetState: effectiveNftState,
|
|
1074
|
+
keyRotationEvents: this.endpointsByDidAddr.get(toAddress(binding.ownerDid))?.keyRotationEvents,
|
|
1075
|
+
now: options.now
|
|
1076
|
+
});
|
|
1077
|
+
if (!recheck.valid) {
|
|
1078
|
+
trace.push(`invalidated_nft_binding:${cleanName}:${recheck.reason}`);
|
|
1079
|
+
return null;
|
|
1080
|
+
}
|
|
1081
|
+
trace.push(`custom_domain:${cleanName}`, `nft_verified:${binding.domainNftAssetDid}`, `cname:${binding.cnameTargetDidDomain}`, `did:${binding.ownerDid}`);
|
|
1082
|
+
return this._buildResult(trimmed, cleanName, binding.domainNftAssetDid, binding.cnameTargetDidDomain, binding.ownerDid, trace);
|
|
1083
|
+
}
|
|
1084
|
+
const fallbackDid = this.simpleNameMap.get(cleanName);
|
|
1085
|
+
if (fallbackDid && isValid(fallbackDid)) {
|
|
1086
|
+
const cnameTarget = toDidDomainHost(fallbackDid, this.gatewayDomain);
|
|
1087
|
+
trace.push(`name:${cleanName}`, `cname:${cnameTarget}`, `did:${fallbackDid}`);
|
|
1088
|
+
return this._buildResult(trimmed, cleanName, void 0, cnameTarget, fallbackDid, trace);
|
|
1089
|
+
}
|
|
1090
|
+
} catch {
|
|
1091
|
+
return null;
|
|
1092
|
+
}
|
|
1093
|
+
return null;
|
|
1094
|
+
}
|
|
1095
|
+
_buildResult(query, customDomain, domainNftAssetDid, cnameTargetDidDomain, did, trace) {
|
|
1096
|
+
const addr = toAddress(did);
|
|
1097
|
+
const endpoint = this.endpointsByDidAddr.get(addr);
|
|
1098
|
+
if (endpoint) trace.push(`endpoint:${endpoint.endpointUrl}`);
|
|
1099
|
+
const customDomainsForDid = [];
|
|
1100
|
+
for (const [dom, b] of this.bindingsByDomain.entries()) if (toAddress(b.ownerDid) === addr && customDomainsForDid.length < MAX_CUSTOM_DOMAINS_PER_DID) customDomainsForDid.push(dom);
|
|
1101
|
+
if (customDomain && !customDomainsForDid.includes(customDomain)) customDomainsForDid.push(customDomain);
|
|
1102
|
+
const didDocument = synthesizeDidDocument({
|
|
1103
|
+
did,
|
|
1104
|
+
publicKey: endpoint?.publicKey,
|
|
1105
|
+
x25519PublicKey: endpoint?.x25519PublicKey,
|
|
1106
|
+
customDomains: customDomainsForDid,
|
|
1107
|
+
gatewayDomain: this.gatewayDomain,
|
|
1108
|
+
arcSpaceEndpoint: endpoint?.endpointUrl,
|
|
1109
|
+
afsEndpoint: endpoint?.afsEndpoint,
|
|
1110
|
+
noiseMeshEndpoint: endpoint?.ipOrMeshAddress,
|
|
1111
|
+
nextKeyCommitment: endpoint?.nextKeyCommitment,
|
|
1112
|
+
keyRotationEvents: endpoint?.keyRotationEvents
|
|
1113
|
+
});
|
|
1114
|
+
return {
|
|
1115
|
+
found: true,
|
|
1116
|
+
query,
|
|
1117
|
+
...customDomain ? { customDomain } : {},
|
|
1118
|
+
...domainNftAssetDid ? { domainNftAssetDid } : {},
|
|
1119
|
+
cnameTargetDidDomain,
|
|
1120
|
+
did: formatDid(addr, extractMethod(did) || "abt"),
|
|
1121
|
+
...endpoint ? { endpoint } : {},
|
|
1122
|
+
didDocument,
|
|
1123
|
+
trace
|
|
1124
|
+
};
|
|
1125
|
+
}
|
|
1126
|
+
resolve(name) {
|
|
1127
|
+
const res = this.resolveThreeTier(name);
|
|
1128
|
+
return res ? res.did : null;
|
|
1129
|
+
}
|
|
1130
|
+
register(name, did) {
|
|
1131
|
+
const clean = normalizeName(name);
|
|
1132
|
+
if (!did || !did.startsWith("did:")) throw new Error("DID must start with did:");
|
|
1133
|
+
this.simpleNameMap.set(clean, did);
|
|
1134
|
+
}
|
|
1135
|
+
unregister(name) {
|
|
1136
|
+
try {
|
|
1137
|
+
const clean = normalizeName(name);
|
|
1138
|
+
this.simpleNameMap.delete(clean);
|
|
1139
|
+
this.bindingsByDomain.delete(clean);
|
|
1140
|
+
this.nftStateByDomain.delete(clean);
|
|
1141
|
+
} catch {}
|
|
1142
|
+
}
|
|
1143
|
+
has(name) {
|
|
1144
|
+
try {
|
|
1145
|
+
const clean = normalizeName(name);
|
|
1146
|
+
return this.bindingsByDomain.has(clean) || this.simpleNameMap.has(clean);
|
|
1147
|
+
} catch {
|
|
1148
|
+
return false;
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
list() {
|
|
1152
|
+
return [...new Set([...this.simpleNameMap.keys(), ...this.bindingsByDomain.keys()])];
|
|
1153
|
+
}
|
|
1154
|
+
clear() {
|
|
1155
|
+
this.simpleNameMap.clear();
|
|
1156
|
+
this.bindingsByDomain.clear();
|
|
1157
|
+
this.nftStateByDomain.clear();
|
|
1158
|
+
this.endpointsByDidAddr.clear();
|
|
1159
|
+
}
|
|
1160
|
+
};
|
|
1161
|
+
|
|
1162
|
+
//#endregion
|
|
1163
|
+
export { DEFAULT_DID_DOMAIN_GATEWAY, DIDDomainEdgeRouter, DID_ENDPOINT_DOMAIN_TAG, DNS_NFT_BINDING_DOMAIN_TAG, KEY_ROTATION_DOMAIN_TAG, MAX_CUSTOM_DOMAINS_PER_DID, MAX_ROTATION_CHAIN_LENGTH, PRE_ROTATION_DOMAIN_TAG, createAccountMigratePreRotationData, createDomainNftBindingProof, createKeyRotationEvent, createPreRotationCommitment, encodeDidEndpointDigest, extractAccountPreRotationData, extractDidFromDomainHost, fromDnsDidLabel, isValidPreRotationCommitment, normalizePreRotationCommitment, normalizePublicKeyHex, synthesizeDidDocument, toDidDomainHost, toDidWellKnownUrl, toDnsDidLabel, verifyAccountMigrationChainWithKel, verifyDomainNftBindingProof, verifyKeyRotationChain, verifyPreRotationCommitment, verifySingleKeyRotationEvent };
|