@arcblock/did-ext 1.30.26 → 1.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.d.mts CHANGED
@@ -1,13 +1,171 @@
1
- import { WalletObject } from "@ocap/wallet";
2
1
  import { DIDTypeArg } from "@arcblock/did";
2
+ import { WalletObject } from "@ocap/wallet";
3
3
 
4
4
  //#region src/index.d.ts
5
-
5
+ declare const STEALTH_DOMAIN_TAG = "arcblock:stealth:v1";
6
+ declare const LINK_PROOF_DOMAIN_TAG = "arcblock:link-proof:v1";
7
+ interface ChainAccountLinkProof {
8
+ domain: typeof LINK_PROOF_DOMAIN_TAG;
9
+ rootDid: string;
10
+ rootPk: string;
11
+ chainDid: string;
12
+ chainAccountDid: string;
13
+ chainAccountPk: string;
14
+ index: number;
15
+ challenge: string;
16
+ expiresAt: number;
17
+ rootSignature: string;
18
+ chainAccountSignature: string;
19
+ }
6
20
  /**
7
21
  * Gen user DID from app did and rootSk
8
22
  *
9
23
  * Spec: https://github.com/ArcBlock/ABT-DID-Protocol#request-did-authentication
10
24
  */
11
25
  declare const fromAppDid: (appDid: string, rootSk: string, type?: DIDTypeArg, index?: number) => WalletObject;
26
+ /**
27
+ * Layer 2 Cross-Chain Unlinkable Key Derivation (#1167):
28
+ * Derives an independent, cryptographically unlinkable per-chain `WalletObject`
29
+ * from a software wallet `rootSk`, `chainDid`, and `index` using length-prefixed
30
+ * HMAC-SHA256 over the master secret key.
31
+ *
32
+ * Unlike Layer 1 (`deriveSubAccountAddress`), each derived chain account has a
33
+ * completely independent on-chain `publicKey` and `address`, preventing block
34
+ * explorer `GROUP BY pk` correlation across chains.
35
+ */
36
+ declare const fromChainDid: (chainDid: string, rootSk: string, type?: DIDTypeArg, index?: number) => WalletObject;
37
+ /**
38
+ * Create a selective cross-chain ownership proof (#1167) binding a `rootWallet`
39
+ * and a derived `chainWallet` for a specific `chainDid` and `challenge` without
40
+ * revealing `rootSk` or any other chain's derived accounts.
41
+ */
42
+ declare function createChainAccountLinkProof(params: {
43
+ rootWallet: WalletObject;
44
+ chainWallet: WalletObject;
45
+ chainDid: string;
46
+ index?: number;
47
+ challenge?: string;
48
+ expiresAt?: number;
49
+ }): Promise<ChainAccountLinkProof>;
50
+ /**
51
+ * Verify a selective cross-chain ownership proof (#1167).
52
+ */
53
+ declare function verifyChainAccountLinkProof(proof: ChainAccountLinkProof, options?: {
54
+ expectedChallenge?: string;
55
+ now?: number;
56
+ }): Promise<boolean>;
57
+ declare const BITSTRING_STATUS_LIST_DOMAIN_TAG = "arcblock:bitstring-status-list:v1";
58
+ declare const DEFAULT_STATUS_LIST_ENTRIES = 131072;
59
+ declare const MIN_STATUS_LIST_ENTRIES = 1024;
60
+ declare const MAX_STATUS_LIST_ENTRIES = 8388608;
61
+ declare const MAX_COMPRESSED_STATUS_LIST_CHARS = 524288;
62
+ declare const MAX_RAW_BITSTRING_BYTES = 2097152;
63
+ type StatusListBitSize = 1 | 2;
64
+ type StatusListPurpose = 'revocation' | 'suspension' | 'multi';
65
+ declare const CredentialBitStatus: Readonly<{
66
+ readonly ACTIVE: 0;
67
+ readonly REVOKED: 1;
68
+ readonly SUSPENDED: 2;
69
+ readonly RESERVED: 3;
70
+ }>;
71
+ interface SignedStatusListCredential {
72
+ '@context': string[];
73
+ id: string;
74
+ type: ['VerifiableCredential', 'BitstringStatusListCredential'];
75
+ issuer: string;
76
+ issuerPublicKey: string;
77
+ validFrom: string;
78
+ issuedAt: number;
79
+ expiresAt: number;
80
+ credentialSubject: {
81
+ id: string;
82
+ type: 'BitstringStatusList';
83
+ statusPurpose: StatusListPurpose;
84
+ bitSize: StatusListBitSize;
85
+ length: number;
86
+ encodedList: string;
87
+ stateRootHash: string;
88
+ };
89
+ proof: {
90
+ type: 'ArcBlockStatusListSignature2026';
91
+ domain: typeof BITSTRING_STATUS_LIST_DOMAIN_TAG;
92
+ signature: string;
93
+ };
94
+ }
95
+ /**
96
+ * W3C Bitstring Status List v1.0 implementation for zero-phone-home, O(1) credential
97
+ * and AI agent session key revocation/suspension.
98
+ *
99
+ * Bit numbering follows W3C Bitstring Status List specification (MSB-first within each byte):
100
+ * - For `bitSize = 1`: `byteIndex = index >> 3`, `bitOffset = 7 - (index & 7)`.
101
+ * - For `bitSize = 2`: `byteIndex = index >> 2`, `bitOffset = 6 - ((index & 3) * 2)`.
102
+ */
103
+ declare class BitstringStatusList {
104
+ readonly length: number;
105
+ readonly bitSize: StatusListBitSize;
106
+ readonly statusPurpose: StatusListPurpose;
107
+ private readonly bytes;
108
+ constructor(options?: {
109
+ length?: number;
110
+ bitSize?: StatusListBitSize;
111
+ statusPurpose?: StatusListPurpose;
112
+ rawBytes?: Uint8Array;
113
+ });
114
+ private _assertValidIndex;
115
+ /**
116
+ * Set the status value at `index` (`0..1` for `bitSize=1`, `0..3` for `bitSize=2`).
117
+ */
118
+ setStatus(index: number, status: number): void;
119
+ /**
120
+ * Get the numeric status at `index`.
121
+ */
122
+ getStatus(index: number): number;
123
+ revoke(index: number): void;
124
+ suspend(index: number): void;
125
+ reinstate(index: number): void;
126
+ isRevoked(index: number): boolean;
127
+ isSuspended(index: number): boolean;
128
+ isActive(index: number): boolean;
129
+ getRawBytes(): Uint8Array;
130
+ /**
131
+ * Compress the raw bitstring with Gzip and encode as multibase base64url (`u...`) per W3C Bitstring Status List v1.0.
132
+ */
133
+ encode(): string;
134
+ /**
135
+ * Decode a multibase base64url (`u...`) Gzip-compressed status list with anti-zip-bomb protection.
136
+ */
137
+ static decode(encodedList: string, options?: {
138
+ length?: number;
139
+ bitSize?: StatusListBitSize;
140
+ statusPurpose?: StatusListPurpose;
141
+ }): BitstringStatusList;
142
+ /**
143
+ * Compute a deterministic `SHA3-256` state root commitment suitable for anchoring
144
+ * in on-chain `IAssetState.data` or `ArcSpace` checkpoints.
145
+ */
146
+ computeStateRootHash(listId: string): string;
147
+ }
148
+ /**
149
+ * Issue and sign a W3C `BitstringStatusListCredential` using a `@ocap/wallet` `WalletObject`.
150
+ */
151
+ declare function createSignedStatusListCredential(params: {
152
+ id: string;
153
+ issuerWallet: WalletObject;
154
+ statusList: BitstringStatusList;
155
+ issuedAt?: number;
156
+ expiresAt?: number;
157
+ }): Promise<SignedStatusListCredential>;
158
+ /**
159
+ * Verify a `SignedStatusListCredential` and decode its `BitstringStatusList`.
160
+ */
161
+ declare function verifySignedStatusListCredential(credential: SignedStatusListCredential, options?: {
162
+ expectedIssuerDid?: string;
163
+ expectedStateRootHash?: string;
164
+ now?: number;
165
+ }): Promise<{
166
+ valid: boolean;
167
+ statusList?: BitstringStatusList;
168
+ reason?: string;
169
+ }>;
12
170
  //#endregion
13
- export { fromAppDid };
171
+ export { BITSTRING_STATUS_LIST_DOMAIN_TAG, BitstringStatusList, ChainAccountLinkProof, CredentialBitStatus, DEFAULT_STATUS_LIST_ENTRIES, LINK_PROOF_DOMAIN_TAG, MAX_COMPRESSED_STATUS_LIST_CHARS, MAX_RAW_BITSTRING_BYTES, MAX_STATUS_LIST_ENTRIES, MIN_STATUS_LIST_ENTRIES, STEALTH_DOMAIN_TAG, SignedStatusListCredential, StatusListBitSize, StatusListPurpose, createChainAccountLinkProof, createSignedStatusListCredential, fromAppDid, fromChainDid, verifyChainAccountLinkProof, verifySignedStatusListCredential };
package/esm/index.mjs CHANGED
@@ -1,9 +1,13 @@
1
- import { Hasher, Signer, types } from "@ocap/mcrypto";
1
+ import { gunzipSync, gzipSync } from "node:zlib";
2
+ import { encodeLengthPrefixedTuple, formatDid, fromTypeInfo, isEthereumDid, isFromPublicKey, isSameEntity, toAddress, toChecksumAddress, toTypeInfo } from "@arcblock/did";
3
+ import { Hasher, Signer, hmacSha256, types } from "@ocap/mcrypto";
2
4
  import { isHexStrict, stripHexPrefix, toBuffer, toHex, toUint8Array } from "@ocap/util";
3
- import { WalletType, fromSecretKey } from "@ocap/wallet";
5
+ import { WalletType, fromPublicKey, fromSecretKey } from "@ocap/wallet";
4
6
  import { HDKey } from "@scure/bip32";
5
7
 
6
8
  //#region src/index.ts
9
+ const STEALTH_DOMAIN_TAG = "arcblock:stealth:v1";
10
+ const LINK_PROOF_DOMAIN_TAG = "arcblock:link-proof:v1";
7
11
  /**
8
12
  * Gen user DID from app did and rootSk
9
13
  *
@@ -30,6 +34,398 @@ const fromAppDid = (appDid, rootSk, type = { role: types.RoleType.ROLE_ACCOUNT }
30
34
  if (pk === types.KeyType.ETHEREUM) sk = sk.slice(0, 66);
31
35
  return fromSecretKey(sk, typeObj);
32
36
  };
37
+ /**
38
+ * Layer 2 Cross-Chain Unlinkable Key Derivation (#1167):
39
+ * Derives an independent, cryptographically unlinkable per-chain `WalletObject`
40
+ * from a software wallet `rootSk`, `chainDid`, and `index` using length-prefixed
41
+ * HMAC-SHA256 over the master secret key.
42
+ *
43
+ * Unlike Layer 1 (`deriveSubAccountAddress`), each derived chain account has a
44
+ * completely independent on-chain `publicKey` and `address`, preventing block
45
+ * explorer `GROUP BY pk` correlation across chains.
46
+ */
47
+ const fromChainDid = (chainDid, rootSk, type = { role: types.RoleType.ROLE_ACCOUNT }, index = 0) => {
48
+ if (!rootSk) throw new Error("Cannot derive chain wallet with empty root sk");
49
+ if (typeof chainDid !== "string" || chainDid.trim().length === 0) throw new Error("Invalid chainDid: must be a non-empty string");
50
+ if (!Number.isInteger(index) || index < 0 || index >= 2147483648) throw new Error("Invalid index: must be a non-negative 31-bit integer");
51
+ const normalizedChainScope = toAddress(chainDid.trim());
52
+ const typeObj = WalletType(type);
53
+ const { pk = types.KeyType.ED25519 } = typeObj;
54
+ const typeHex = fromTypeInfo(typeObj);
55
+ const rootSkBytes = isHexStrict(rootSk) ? toUint8Array(rootSk) : /^[0-9a-fA-F]+$/.test(rootSk) && rootSk.length % 2 === 0 ? toUint8Array(`0x${rootSk}`) : toUint8Array(rootSk);
56
+ if (rootSkBytes.byteLength === 0) throw new Error("Cannot derive chain wallet with empty root sk");
57
+ const prk = hmacSha256(new TextEncoder().encode(STEALTH_DOMAIN_TAG), rootSkBytes, "Uint8Array");
58
+ const baseTuple = encodeLengthPrefixedTuple([normalizedChainScope, typeHex], index);
59
+ let childSeed = null;
60
+ for (let counter = 0; counter < 256; counter++) {
61
+ const msg = new Uint8Array(baseTuple.byteLength + 1);
62
+ msg.set(baseTuple, 0);
63
+ msg[baseTuple.byteLength] = counter;
64
+ const candidate = hmacSha256(prk, msg, "Uint8Array");
65
+ if (pk === types.KeyType.ED25519 || Signer.Secp256k1.isValidSK(candidate)) {
66
+ childSeed = candidate;
67
+ break;
68
+ }
69
+ }
70
+ if (!childSeed) throw new Error("Failed to derive valid child secret key");
71
+ let sk;
72
+ if (pk === types.KeyType.ED25519) sk = Signer.Ed25519.genKeyPair("hex", childSeed).secretKey;
73
+ else sk = toHex(childSeed);
74
+ if (pk === types.KeyType.ETHEREUM) sk = sk.slice(0, 66);
75
+ return fromSecretKey(sk, typeObj);
76
+ };
77
+ function encodeLinkProofStatement(params) {
78
+ return encodeLengthPrefixedTuple([
79
+ LINK_PROOF_DOMAIN_TAG,
80
+ toAddress(params.rootDid),
81
+ toAddress(params.chainDid),
82
+ toAddress(params.chainAccountDid),
83
+ params.challenge,
84
+ String(params.expiresAt)
85
+ ], params.index);
86
+ }
87
+ /**
88
+ * Create a selective cross-chain ownership proof (#1167) binding a `rootWallet`
89
+ * and a derived `chainWallet` for a specific `chainDid` and `challenge` without
90
+ * revealing `rootSk` or any other chain's derived accounts.
91
+ */
92
+ async function createChainAccountLinkProof(params) {
93
+ const { rootWallet, chainWallet, chainDid, index = 0, challenge = "", expiresAt = 0 } = params;
94
+ if (!rootWallet?.address || !rootWallet?.publicKey) throw new Error("Invalid rootWallet");
95
+ if (!chainWallet?.address || !chainWallet?.publicKey) throw new Error("Invalid chainWallet");
96
+ if (typeof chainDid !== "string" || chainDid.trim().length === 0) throw new Error("Invalid chainDid: must be a non-empty string");
97
+ if (!Number.isInteger(expiresAt) || expiresAt < 0) throw new Error("Invalid expiresAt: must be a non-negative integer");
98
+ const rootDid = toAddress(rootWallet.address);
99
+ const normalizedChainDid = toAddress(chainDid.trim());
100
+ const chainAccountDid = toAddress(chainWallet.address);
101
+ const statement = encodeLinkProofStatement({
102
+ rootDid,
103
+ chainDid: normalizedChainDid,
104
+ chainAccountDid,
105
+ index,
106
+ challenge,
107
+ expiresAt
108
+ });
109
+ const [rootSignature, chainAccountSignature] = await Promise.all([rootWallet.sign(statement, true, "hex"), chainWallet.sign(statement, true, "hex")]);
110
+ return {
111
+ domain: LINK_PROOF_DOMAIN_TAG,
112
+ rootDid,
113
+ rootPk: String(rootWallet.publicKey),
114
+ chainDid: normalizedChainDid,
115
+ chainAccountDid,
116
+ chainAccountPk: String(chainWallet.publicKey),
117
+ index,
118
+ challenge,
119
+ expiresAt,
120
+ rootSignature,
121
+ chainAccountSignature
122
+ };
123
+ }
124
+ /**
125
+ * Verify a selective cross-chain ownership proof (#1167).
126
+ */
127
+ async function verifyChainAccountLinkProof(proof, options = {}) {
128
+ try {
129
+ if (!proof || proof.domain !== LINK_PROOF_DOMAIN_TAG) return false;
130
+ if (!proof.rootDid || !proof.rootPk || !proof.chainDid || !proof.chainAccountDid || !proof.chainAccountPk) return false;
131
+ if (!Number.isInteger(proof.index) || proof.index < 0 || proof.index > 4294967295) return false;
132
+ if (!Number.isInteger(proof.expiresAt) || proof.expiresAt < 0) return false;
133
+ if (options.expectedChallenge !== void 0 && proof.challenge !== options.expectedChallenge) return false;
134
+ if (proof.expiresAt > 0) {
135
+ if ((options.now ?? Date.now()) > proof.expiresAt) return false;
136
+ }
137
+ if (!isFromPublicKey(proof.rootDid, proof.rootPk)) return false;
138
+ if (!isFromPublicKey(proof.chainAccountDid, proof.chainAccountPk)) return false;
139
+ const statement = encodeLinkProofStatement({
140
+ rootDid: proof.rootDid,
141
+ chainDid: proof.chainDid,
142
+ chainAccountDid: proof.chainAccountDid,
143
+ index: proof.index,
144
+ challenge: proof.challenge,
145
+ expiresAt: proof.expiresAt
146
+ });
147
+ const rootVerifier = fromPublicKey(proof.rootPk, toTypeInfo(proof.rootDid));
148
+ const chainVerifier = fromPublicKey(proof.chainAccountPk, toTypeInfo(proof.chainAccountDid));
149
+ const [rootOk, chainOk] = await Promise.all([rootVerifier.verify(statement, proof.rootSignature, true), chainVerifier.verify(statement, proof.chainAccountSignature, true)]);
150
+ return Boolean(rootOk && chainOk);
151
+ } catch {
152
+ return false;
153
+ }
154
+ }
155
+ const BITSTRING_STATUS_LIST_DOMAIN_TAG = "arcblock:bitstring-status-list:v1";
156
+ const DEFAULT_STATUS_LIST_ENTRIES = 131072;
157
+ const MIN_STATUS_LIST_ENTRIES = 1024;
158
+ const MAX_STATUS_LIST_ENTRIES = 8388608;
159
+ const MAX_COMPRESSED_STATUS_LIST_CHARS = 524288;
160
+ const MAX_RAW_BITSTRING_BYTES = 2097152;
161
+ const CredentialBitStatus = Object.freeze({
162
+ ACTIVE: 0,
163
+ REVOKED: 1,
164
+ SUSPENDED: 2,
165
+ RESERVED: 3
166
+ });
167
+ /**
168
+ * W3C Bitstring Status List v1.0 implementation for zero-phone-home, O(1) credential
169
+ * and AI agent session key revocation/suspension.
170
+ *
171
+ * Bit numbering follows W3C Bitstring Status List specification (MSB-first within each byte):
172
+ * - For `bitSize = 1`: `byteIndex = index >> 3`, `bitOffset = 7 - (index & 7)`.
173
+ * - For `bitSize = 2`: `byteIndex = index >> 2`, `bitOffset = 6 - ((index & 3) * 2)`.
174
+ */
175
+ var BitstringStatusList = class BitstringStatusList {
176
+ constructor(options = {}) {
177
+ const bitSize = options.bitSize ?? 1;
178
+ if (bitSize !== 1 && bitSize !== 2) throw new Error(`Invalid bitSize ${bitSize}: must be 1 or 2`);
179
+ const length = options.length ?? DEFAULT_STATUS_LIST_ENTRIES;
180
+ if (!Number.isSafeInteger(length) || length < MIN_STATUS_LIST_ENTRIES || length > MAX_STATUS_LIST_ENTRIES) throw new Error(`Invalid BitstringStatusList length ${length}: must be in [${MIN_STATUS_LIST_ENTRIES}, ${MAX_STATUS_LIST_ENTRIES}]`);
181
+ const entriesPerByte = 8 / bitSize;
182
+ const expectedByteLen = Math.ceil(length / entriesPerByte);
183
+ if (expectedByteLen > MAX_RAW_BITSTRING_BYTES) throw new Error(`Bitstring byte length (${expectedByteLen}) exceeds MAX_RAW_BITSTRING_BYTES`);
184
+ this.length = length;
185
+ this.bitSize = bitSize;
186
+ this.statusPurpose = options.statusPurpose ?? (bitSize === 2 ? "multi" : "revocation");
187
+ if (options.rawBytes) {
188
+ if (options.rawBytes.byteLength !== expectedByteLen) throw new Error(`rawBytes length mismatch: expected ${expectedByteLen} bytes for length=${length}, bitSize=${bitSize}, got ${options.rawBytes.byteLength}`);
189
+ this.bytes = new Uint8Array(options.rawBytes);
190
+ } else this.bytes = new Uint8Array(expectedByteLen);
191
+ }
192
+ _assertValidIndex(index) {
193
+ if (!Number.isSafeInteger(index) || index < 0 || index >= this.length) throw new Error(`Status index ${index} out of bounds [0, ${this.length - 1}]`);
194
+ }
195
+ /**
196
+ * Set the status value at `index` (`0..1` for `bitSize=1`, `0..3` for `bitSize=2`).
197
+ */
198
+ setStatus(index, status) {
199
+ this._assertValidIndex(index);
200
+ const maxVal = (1 << this.bitSize) - 1;
201
+ if (!Number.isSafeInteger(status) || status < 0 || status > maxVal) throw new Error(`Status value ${status} out of range [0, ${maxVal}] for bitSize=${this.bitSize}`);
202
+ if (this.bitSize === 1) {
203
+ const byteIdx = index >> 3;
204
+ const shift = 7 - (index & 7);
205
+ if (status === 1) this.bytes[byteIdx] |= 1 << shift;
206
+ else this.bytes[byteIdx] &= ~(1 << shift);
207
+ } else {
208
+ const byteIdx = index >> 2;
209
+ const shift = 6 - (index & 3) * 2;
210
+ this.bytes[byteIdx] = this.bytes[byteIdx] & ~(3 << shift) | (status & 3) << shift;
211
+ }
212
+ }
213
+ /**
214
+ * Get the numeric status at `index`.
215
+ */
216
+ getStatus(index) {
217
+ this._assertValidIndex(index);
218
+ if (this.bitSize === 1) {
219
+ const byteIdx$1 = index >> 3;
220
+ const shift$1 = 7 - (index & 7);
221
+ return this.bytes[byteIdx$1] >> shift$1 & 1;
222
+ }
223
+ const byteIdx = index >> 2;
224
+ const shift = 6 - (index & 3) * 2;
225
+ return this.bytes[byteIdx] >> shift & 3;
226
+ }
227
+ revoke(index) {
228
+ this.setStatus(index, CredentialBitStatus.REVOKED);
229
+ }
230
+ suspend(index) {
231
+ if (this.bitSize < 2) throw new Error("Cannot suspend credential on a 1-bit status list (requires bitSize = 2)");
232
+ this.setStatus(index, CredentialBitStatus.SUSPENDED);
233
+ }
234
+ reinstate(index) {
235
+ this.setStatus(index, CredentialBitStatus.ACTIVE);
236
+ }
237
+ isRevoked(index) {
238
+ return this.getStatus(index) === CredentialBitStatus.REVOKED;
239
+ }
240
+ isSuspended(index) {
241
+ return this.bitSize === 2 && this.getStatus(index) === CredentialBitStatus.SUSPENDED;
242
+ }
243
+ isActive(index) {
244
+ return this.getStatus(index) === CredentialBitStatus.ACTIVE;
245
+ }
246
+ getRawBytes() {
247
+ return new Uint8Array(this.bytes);
248
+ }
249
+ /**
250
+ * Compress the raw bitstring with Gzip and encode as multibase base64url (`u...`) per W3C Bitstring Status List v1.0.
251
+ */
252
+ encode() {
253
+ return `u${gzipSync(Buffer.from(this.bytes), { level: 9 }).toString("base64url")}`;
254
+ }
255
+ /**
256
+ * Decode a multibase base64url (`u...`) Gzip-compressed status list with anti-zip-bomb protection.
257
+ */
258
+ static decode(encodedList, options = {}) {
259
+ if (!encodedList || typeof encodedList !== "string") throw new Error("encodedList must be a non-empty string");
260
+ if (encodedList.length > MAX_COMPRESSED_STATUS_LIST_CHARS) throw new Error("encodedList exceeds maximum allowed compressed size");
261
+ if (!encodedList.startsWith("u")) throw new Error("encodedList must use multibase base64url prefix (\"u\")");
262
+ const b64u = encodedList.slice(1);
263
+ if (!b64u || !/^[A-Za-z0-9_-]+$/.test(b64u)) throw new Error("encodedList contains invalid base64url characters");
264
+ const decompressed = gunzipSync(Buffer.from(b64u, "base64url"), { maxOutputLength: MAX_RAW_BITSTRING_BYTES });
265
+ const rawBytes = new Uint8Array(decompressed);
266
+ const bitSize = options.bitSize ?? 1;
267
+ const entriesPerByte = 8 / bitSize;
268
+ return new BitstringStatusList({
269
+ length: options.length ?? rawBytes.byteLength * entriesPerByte,
270
+ bitSize,
271
+ statusPurpose: options.statusPurpose,
272
+ rawBytes
273
+ });
274
+ }
275
+ /**
276
+ * Compute a deterministic `SHA3-256` state root commitment suitable for anchoring
277
+ * in on-chain `IAssetState.data` or `ArcSpace` checkpoints.
278
+ */
279
+ computeStateRootHash(listId) {
280
+ if (!listId || typeof listId !== "string") throw new Error("listId must be a non-empty string");
281
+ const rawDigest = Hasher.SHA3.hash256(this.bytes, 1, "hex");
282
+ const tuple = encodeLengthPrefixedTuple([
283
+ BITSTRING_STATUS_LIST_DOMAIN_TAG,
284
+ listId.trim(),
285
+ this.statusPurpose,
286
+ String(this.bitSize),
287
+ String(this.length),
288
+ rawDigest
289
+ ], 0);
290
+ return Hasher.SHA3.hash256(tuple, 1, "hex");
291
+ }
292
+ };
293
+ function encodeStatusListSigningStatement(params) {
294
+ return encodeLengthPrefixedTuple([
295
+ BITSTRING_STATUS_LIST_DOMAIN_TAG,
296
+ params.id,
297
+ toAddress(params.issuerDid),
298
+ params.statusPurpose,
299
+ String(params.bitSize),
300
+ String(params.length),
301
+ params.encodedList,
302
+ params.stateRootHash,
303
+ String(params.issuedAt)
304
+ ], params.expiresAt);
305
+ }
306
+ /**
307
+ * Issue and sign a W3C `BitstringStatusListCredential` using a `@ocap/wallet` `WalletObject`.
308
+ */
309
+ async function createSignedStatusListCredential(params) {
310
+ if (!params.id || typeof params.id !== "string") throw new Error("Status list credential id is required");
311
+ if (!params.issuerWallet?.address || !params.issuerWallet?.publicKey) throw new Error("Valid issuerWallet is required");
312
+ const issuedAt = params.issuedAt ?? Math.floor(Date.now() / 1e3);
313
+ const expiresAt = params.expiresAt ?? 0;
314
+ if (!Number.isSafeInteger(issuedAt) || issuedAt < 0 || !Number.isSafeInteger(expiresAt) || expiresAt < 0) throw new Error("issuedAt and expiresAt must be non-negative safe integers");
315
+ const rawIssuerAddr = toAddress(params.issuerWallet.address);
316
+ const issuerDid = formatDid(isEthereumDid(rawIssuerAddr) ? toChecksumAddress(rawIssuerAddr) : rawIssuerAddr, "abt");
317
+ const encodedList = params.statusList.encode();
318
+ const stateRootHash = params.statusList.computeStateRootHash(params.id);
319
+ const statement = encodeStatusListSigningStatement({
320
+ id: params.id,
321
+ issuerDid,
322
+ statusPurpose: params.statusList.statusPurpose,
323
+ bitSize: params.statusList.bitSize,
324
+ length: params.statusList.length,
325
+ encodedList,
326
+ stateRootHash,
327
+ issuedAt,
328
+ expiresAt
329
+ });
330
+ const signature = await params.issuerWallet.sign(statement, true, "hex");
331
+ return {
332
+ "@context": ["https://www.w3.org/ns/credentials/v2"],
333
+ id: params.id,
334
+ type: ["VerifiableCredential", "BitstringStatusListCredential"],
335
+ issuer: issuerDid,
336
+ issuerPublicKey: String(params.issuerWallet.publicKey),
337
+ validFrom: (/* @__PURE__ */ new Date(issuedAt * 1e3)).toISOString(),
338
+ issuedAt,
339
+ expiresAt,
340
+ credentialSubject: {
341
+ id: `${params.id}#list`,
342
+ type: "BitstringStatusList",
343
+ statusPurpose: params.statusList.statusPurpose,
344
+ bitSize: params.statusList.bitSize,
345
+ length: params.statusList.length,
346
+ encodedList,
347
+ stateRootHash
348
+ },
349
+ proof: {
350
+ type: "ArcBlockStatusListSignature2026",
351
+ domain: BITSTRING_STATUS_LIST_DOMAIN_TAG,
352
+ signature: String(signature)
353
+ }
354
+ };
355
+ }
356
+ /**
357
+ * Verify a `SignedStatusListCredential` and decode its `BitstringStatusList`.
358
+ */
359
+ async function verifySignedStatusListCredential(credential, options = {}) {
360
+ try {
361
+ if (!credential || credential.proof?.domain !== BITSTRING_STATUS_LIST_DOMAIN_TAG) return {
362
+ valid: false,
363
+ reason: "INVALID_CREDENTIAL_DOMAIN"
364
+ };
365
+ if (!credential.issuer || !credential.issuerPublicKey) return {
366
+ valid: false,
367
+ reason: "MISSING_ISSUER_OR_PUBLIC_KEY"
368
+ };
369
+ if (options.expectedIssuerDid && !isSameEntity(toAddress(credential.issuer), toAddress(options.expectedIssuerDid))) return {
370
+ valid: false,
371
+ reason: "ISSUER_DID_MISMATCH"
372
+ };
373
+ const rawIssuerAddr = toAddress(credential.issuer);
374
+ if (!isFromPublicKey(isEthereumDid(rawIssuerAddr) ? toChecksumAddress(rawIssuerAddr) : credential.issuer, credential.issuerPublicKey)) return {
375
+ valid: false,
376
+ reason: "ISSUER_PUBLIC_KEY_MISMATCH"
377
+ };
378
+ if (credential.expiresAt > 0) {
379
+ if ((options.now ?? Math.floor(Date.now() / 1e3)) > credential.expiresAt) return {
380
+ valid: false,
381
+ reason: "STATUS_LIST_CREDENTIAL_EXPIRED"
382
+ };
383
+ }
384
+ const subj = credential.credentialSubject;
385
+ if (!subj || !subj.encodedList) return {
386
+ valid: false,
387
+ reason: "MISSING_CREDENTIAL_SUBJECT"
388
+ };
389
+ const statusList = BitstringStatusList.decode(subj.encodedList, {
390
+ length: subj.length,
391
+ bitSize: subj.bitSize,
392
+ statusPurpose: subj.statusPurpose
393
+ });
394
+ const computedRoot = statusList.computeStateRootHash(credential.id);
395
+ if (computedRoot !== subj.stateRootHash) return {
396
+ valid: false,
397
+ reason: "STATE_ROOT_HASH_TAMPERED"
398
+ };
399
+ if (options.expectedStateRootHash && computedRoot !== options.expectedStateRootHash) return {
400
+ valid: false,
401
+ reason: "EXPECTED_STATE_ROOT_MISMATCH"
402
+ };
403
+ const statement = encodeStatusListSigningStatement({
404
+ id: credential.id,
405
+ issuerDid: credential.issuer,
406
+ statusPurpose: subj.statusPurpose,
407
+ bitSize: subj.bitSize,
408
+ length: subj.length,
409
+ encodedList: subj.encodedList,
410
+ stateRootHash: subj.stateRootHash,
411
+ issuedAt: credential.issuedAt,
412
+ expiresAt: credential.expiresAt
413
+ });
414
+ if (!await fromPublicKey(credential.issuerPublicKey, toTypeInfo(credential.issuer)).verify(statement, credential.proof.signature, true)) return {
415
+ valid: false,
416
+ reason: "INVALID_ISSUER_SIGNATURE"
417
+ };
418
+ return {
419
+ valid: true,
420
+ statusList
421
+ };
422
+ } catch (err) {
423
+ return {
424
+ valid: false,
425
+ reason: err?.message || "VERIFY_STATUS_LIST_ERROR"
426
+ };
427
+ }
428
+ }
33
429
 
34
430
  //#endregion
35
- export { fromAppDid };
431
+ export { BITSTRING_STATUS_LIST_DOMAIN_TAG, BitstringStatusList, CredentialBitStatus, DEFAULT_STATUS_LIST_ENTRIES, LINK_PROOF_DOMAIN_TAG, MAX_COMPRESSED_STATUS_LIST_CHARS, MAX_RAW_BITSTRING_BYTES, MAX_STATUS_LIST_ENTRIES, MIN_STATUS_LIST_ENTRIES, STEALTH_DOMAIN_TAG, createChainAccountLinkProof, createSignedStatusListCredential, fromAppDid, fromChainDid, verifyChainAccountLinkProof, verifySignedStatusListCredential };
package/lib/index.cjs CHANGED
@@ -1,9 +1,13 @@
1
+ let node_zlib = require("node:zlib");
2
+ let _arcblock_did = require("@arcblock/did");
1
3
  let _ocap_mcrypto = require("@ocap/mcrypto");
2
4
  let _ocap_util = require("@ocap/util");
3
5
  let _ocap_wallet = require("@ocap/wallet");
4
6
  let _scure_bip32 = require("@scure/bip32");
5
7
 
6
8
  //#region src/index.ts
9
+ const STEALTH_DOMAIN_TAG = "arcblock:stealth:v1";
10
+ const LINK_PROOF_DOMAIN_TAG = "arcblock:link-proof:v1";
7
11
  /**
8
12
  * Gen user DID from app did and rootSk
9
13
  *
@@ -30,6 +34,413 @@ const fromAppDid = (appDid, rootSk, type = { role: _ocap_mcrypto.types.RoleType.
30
34
  if (pk === _ocap_mcrypto.types.KeyType.ETHEREUM) sk = sk.slice(0, 66);
31
35
  return (0, _ocap_wallet.fromSecretKey)(sk, typeObj);
32
36
  };
37
+ /**
38
+ * Layer 2 Cross-Chain Unlinkable Key Derivation (#1167):
39
+ * Derives an independent, cryptographically unlinkable per-chain `WalletObject`
40
+ * from a software wallet `rootSk`, `chainDid`, and `index` using length-prefixed
41
+ * HMAC-SHA256 over the master secret key.
42
+ *
43
+ * Unlike Layer 1 (`deriveSubAccountAddress`), each derived chain account has a
44
+ * completely independent on-chain `publicKey` and `address`, preventing block
45
+ * explorer `GROUP BY pk` correlation across chains.
46
+ */
47
+ const fromChainDid = (chainDid, rootSk, type = { role: _ocap_mcrypto.types.RoleType.ROLE_ACCOUNT }, index = 0) => {
48
+ if (!rootSk) throw new Error("Cannot derive chain wallet with empty root sk");
49
+ if (typeof chainDid !== "string" || chainDid.trim().length === 0) throw new Error("Invalid chainDid: must be a non-empty string");
50
+ if (!Number.isInteger(index) || index < 0 || index >= 2147483648) throw new Error("Invalid index: must be a non-negative 31-bit integer");
51
+ const normalizedChainScope = (0, _arcblock_did.toAddress)(chainDid.trim());
52
+ const typeObj = (0, _ocap_wallet.WalletType)(type);
53
+ const { pk = _ocap_mcrypto.types.KeyType.ED25519 } = typeObj;
54
+ const typeHex = (0, _arcblock_did.fromTypeInfo)(typeObj);
55
+ const rootSkBytes = (0, _ocap_util.isHexStrict)(rootSk) ? (0, _ocap_util.toUint8Array)(rootSk) : /^[0-9a-fA-F]+$/.test(rootSk) && rootSk.length % 2 === 0 ? (0, _ocap_util.toUint8Array)(`0x${rootSk}`) : (0, _ocap_util.toUint8Array)(rootSk);
56
+ if (rootSkBytes.byteLength === 0) throw new Error("Cannot derive chain wallet with empty root sk");
57
+ const prk = (0, _ocap_mcrypto.hmacSha256)(new TextEncoder().encode(STEALTH_DOMAIN_TAG), rootSkBytes, "Uint8Array");
58
+ const baseTuple = (0, _arcblock_did.encodeLengthPrefixedTuple)([normalizedChainScope, typeHex], index);
59
+ let childSeed = null;
60
+ for (let counter = 0; counter < 256; counter++) {
61
+ const msg = new Uint8Array(baseTuple.byteLength + 1);
62
+ msg.set(baseTuple, 0);
63
+ msg[baseTuple.byteLength] = counter;
64
+ const candidate = (0, _ocap_mcrypto.hmacSha256)(prk, msg, "Uint8Array");
65
+ if (pk === _ocap_mcrypto.types.KeyType.ED25519 || _ocap_mcrypto.Signer.Secp256k1.isValidSK(candidate)) {
66
+ childSeed = candidate;
67
+ break;
68
+ }
69
+ }
70
+ if (!childSeed) throw new Error("Failed to derive valid child secret key");
71
+ let sk;
72
+ if (pk === _ocap_mcrypto.types.KeyType.ED25519) sk = _ocap_mcrypto.Signer.Ed25519.genKeyPair("hex", childSeed).secretKey;
73
+ else sk = (0, _ocap_util.toHex)(childSeed);
74
+ if (pk === _ocap_mcrypto.types.KeyType.ETHEREUM) sk = sk.slice(0, 66);
75
+ return (0, _ocap_wallet.fromSecretKey)(sk, typeObj);
76
+ };
77
+ function encodeLinkProofStatement(params) {
78
+ return (0, _arcblock_did.encodeLengthPrefixedTuple)([
79
+ LINK_PROOF_DOMAIN_TAG,
80
+ (0, _arcblock_did.toAddress)(params.rootDid),
81
+ (0, _arcblock_did.toAddress)(params.chainDid),
82
+ (0, _arcblock_did.toAddress)(params.chainAccountDid),
83
+ params.challenge,
84
+ String(params.expiresAt)
85
+ ], params.index);
86
+ }
87
+ /**
88
+ * Create a selective cross-chain ownership proof (#1167) binding a `rootWallet`
89
+ * and a derived `chainWallet` for a specific `chainDid` and `challenge` without
90
+ * revealing `rootSk` or any other chain's derived accounts.
91
+ */
92
+ async function createChainAccountLinkProof(params) {
93
+ const { rootWallet, chainWallet, chainDid, index = 0, challenge = "", expiresAt = 0 } = params;
94
+ if (!rootWallet?.address || !rootWallet?.publicKey) throw new Error("Invalid rootWallet");
95
+ if (!chainWallet?.address || !chainWallet?.publicKey) throw new Error("Invalid chainWallet");
96
+ if (typeof chainDid !== "string" || chainDid.trim().length === 0) throw new Error("Invalid chainDid: must be a non-empty string");
97
+ if (!Number.isInteger(expiresAt) || expiresAt < 0) throw new Error("Invalid expiresAt: must be a non-negative integer");
98
+ const rootDid = (0, _arcblock_did.toAddress)(rootWallet.address);
99
+ const normalizedChainDid = (0, _arcblock_did.toAddress)(chainDid.trim());
100
+ const chainAccountDid = (0, _arcblock_did.toAddress)(chainWallet.address);
101
+ const statement = encodeLinkProofStatement({
102
+ rootDid,
103
+ chainDid: normalizedChainDid,
104
+ chainAccountDid,
105
+ index,
106
+ challenge,
107
+ expiresAt
108
+ });
109
+ const [rootSignature, chainAccountSignature] = await Promise.all([rootWallet.sign(statement, true, "hex"), chainWallet.sign(statement, true, "hex")]);
110
+ return {
111
+ domain: LINK_PROOF_DOMAIN_TAG,
112
+ rootDid,
113
+ rootPk: String(rootWallet.publicKey),
114
+ chainDid: normalizedChainDid,
115
+ chainAccountDid,
116
+ chainAccountPk: String(chainWallet.publicKey),
117
+ index,
118
+ challenge,
119
+ expiresAt,
120
+ rootSignature,
121
+ chainAccountSignature
122
+ };
123
+ }
124
+ /**
125
+ * Verify a selective cross-chain ownership proof (#1167).
126
+ */
127
+ async function verifyChainAccountLinkProof(proof, options = {}) {
128
+ try {
129
+ if (!proof || proof.domain !== LINK_PROOF_DOMAIN_TAG) return false;
130
+ if (!proof.rootDid || !proof.rootPk || !proof.chainDid || !proof.chainAccountDid || !proof.chainAccountPk) return false;
131
+ if (!Number.isInteger(proof.index) || proof.index < 0 || proof.index > 4294967295) return false;
132
+ if (!Number.isInteger(proof.expiresAt) || proof.expiresAt < 0) return false;
133
+ if (options.expectedChallenge !== void 0 && proof.challenge !== options.expectedChallenge) return false;
134
+ if (proof.expiresAt > 0) {
135
+ if ((options.now ?? Date.now()) > proof.expiresAt) return false;
136
+ }
137
+ if (!(0, _arcblock_did.isFromPublicKey)(proof.rootDid, proof.rootPk)) return false;
138
+ if (!(0, _arcblock_did.isFromPublicKey)(proof.chainAccountDid, proof.chainAccountPk)) return false;
139
+ const statement = encodeLinkProofStatement({
140
+ rootDid: proof.rootDid,
141
+ chainDid: proof.chainDid,
142
+ chainAccountDid: proof.chainAccountDid,
143
+ index: proof.index,
144
+ challenge: proof.challenge,
145
+ expiresAt: proof.expiresAt
146
+ });
147
+ const rootVerifier = (0, _ocap_wallet.fromPublicKey)(proof.rootPk, (0, _arcblock_did.toTypeInfo)(proof.rootDid));
148
+ const chainVerifier = (0, _ocap_wallet.fromPublicKey)(proof.chainAccountPk, (0, _arcblock_did.toTypeInfo)(proof.chainAccountDid));
149
+ const [rootOk, chainOk] = await Promise.all([rootVerifier.verify(statement, proof.rootSignature, true), chainVerifier.verify(statement, proof.chainAccountSignature, true)]);
150
+ return Boolean(rootOk && chainOk);
151
+ } catch {
152
+ return false;
153
+ }
154
+ }
155
+ const BITSTRING_STATUS_LIST_DOMAIN_TAG = "arcblock:bitstring-status-list:v1";
156
+ const DEFAULT_STATUS_LIST_ENTRIES = 131072;
157
+ const MIN_STATUS_LIST_ENTRIES = 1024;
158
+ const MAX_STATUS_LIST_ENTRIES = 8388608;
159
+ const MAX_COMPRESSED_STATUS_LIST_CHARS = 524288;
160
+ const MAX_RAW_BITSTRING_BYTES = 2097152;
161
+ const CredentialBitStatus = Object.freeze({
162
+ ACTIVE: 0,
163
+ REVOKED: 1,
164
+ SUSPENDED: 2,
165
+ RESERVED: 3
166
+ });
167
+ /**
168
+ * W3C Bitstring Status List v1.0 implementation for zero-phone-home, O(1) credential
169
+ * and AI agent session key revocation/suspension.
170
+ *
171
+ * Bit numbering follows W3C Bitstring Status List specification (MSB-first within each byte):
172
+ * - For `bitSize = 1`: `byteIndex = index >> 3`, `bitOffset = 7 - (index & 7)`.
173
+ * - For `bitSize = 2`: `byteIndex = index >> 2`, `bitOffset = 6 - ((index & 3) * 2)`.
174
+ */
175
+ var BitstringStatusList = class BitstringStatusList {
176
+ constructor(options = {}) {
177
+ const bitSize = options.bitSize ?? 1;
178
+ if (bitSize !== 1 && bitSize !== 2) throw new Error(`Invalid bitSize ${bitSize}: must be 1 or 2`);
179
+ const length = options.length ?? DEFAULT_STATUS_LIST_ENTRIES;
180
+ if (!Number.isSafeInteger(length) || length < MIN_STATUS_LIST_ENTRIES || length > MAX_STATUS_LIST_ENTRIES) throw new Error(`Invalid BitstringStatusList length ${length}: must be in [${MIN_STATUS_LIST_ENTRIES}, ${MAX_STATUS_LIST_ENTRIES}]`);
181
+ const entriesPerByte = 8 / bitSize;
182
+ const expectedByteLen = Math.ceil(length / entriesPerByte);
183
+ if (expectedByteLen > MAX_RAW_BITSTRING_BYTES) throw new Error(`Bitstring byte length (${expectedByteLen}) exceeds MAX_RAW_BITSTRING_BYTES`);
184
+ this.length = length;
185
+ this.bitSize = bitSize;
186
+ this.statusPurpose = options.statusPurpose ?? (bitSize === 2 ? "multi" : "revocation");
187
+ if (options.rawBytes) {
188
+ if (options.rawBytes.byteLength !== expectedByteLen) throw new Error(`rawBytes length mismatch: expected ${expectedByteLen} bytes for length=${length}, bitSize=${bitSize}, got ${options.rawBytes.byteLength}`);
189
+ this.bytes = new Uint8Array(options.rawBytes);
190
+ } else this.bytes = new Uint8Array(expectedByteLen);
191
+ }
192
+ _assertValidIndex(index) {
193
+ if (!Number.isSafeInteger(index) || index < 0 || index >= this.length) throw new Error(`Status index ${index} out of bounds [0, ${this.length - 1}]`);
194
+ }
195
+ /**
196
+ * Set the status value at `index` (`0..1` for `bitSize=1`, `0..3` for `bitSize=2`).
197
+ */
198
+ setStatus(index, status) {
199
+ this._assertValidIndex(index);
200
+ const maxVal = (1 << this.bitSize) - 1;
201
+ if (!Number.isSafeInteger(status) || status < 0 || status > maxVal) throw new Error(`Status value ${status} out of range [0, ${maxVal}] for bitSize=${this.bitSize}`);
202
+ if (this.bitSize === 1) {
203
+ const byteIdx = index >> 3;
204
+ const shift = 7 - (index & 7);
205
+ if (status === 1) this.bytes[byteIdx] |= 1 << shift;
206
+ else this.bytes[byteIdx] &= ~(1 << shift);
207
+ } else {
208
+ const byteIdx = index >> 2;
209
+ const shift = 6 - (index & 3) * 2;
210
+ this.bytes[byteIdx] = this.bytes[byteIdx] & ~(3 << shift) | (status & 3) << shift;
211
+ }
212
+ }
213
+ /**
214
+ * Get the numeric status at `index`.
215
+ */
216
+ getStatus(index) {
217
+ this._assertValidIndex(index);
218
+ if (this.bitSize === 1) {
219
+ const byteIdx$1 = index >> 3;
220
+ const shift$1 = 7 - (index & 7);
221
+ return this.bytes[byteIdx$1] >> shift$1 & 1;
222
+ }
223
+ const byteIdx = index >> 2;
224
+ const shift = 6 - (index & 3) * 2;
225
+ return this.bytes[byteIdx] >> shift & 3;
226
+ }
227
+ revoke(index) {
228
+ this.setStatus(index, CredentialBitStatus.REVOKED);
229
+ }
230
+ suspend(index) {
231
+ if (this.bitSize < 2) throw new Error("Cannot suspend credential on a 1-bit status list (requires bitSize = 2)");
232
+ this.setStatus(index, CredentialBitStatus.SUSPENDED);
233
+ }
234
+ reinstate(index) {
235
+ this.setStatus(index, CredentialBitStatus.ACTIVE);
236
+ }
237
+ isRevoked(index) {
238
+ return this.getStatus(index) === CredentialBitStatus.REVOKED;
239
+ }
240
+ isSuspended(index) {
241
+ return this.bitSize === 2 && this.getStatus(index) === CredentialBitStatus.SUSPENDED;
242
+ }
243
+ isActive(index) {
244
+ return this.getStatus(index) === CredentialBitStatus.ACTIVE;
245
+ }
246
+ getRawBytes() {
247
+ return new Uint8Array(this.bytes);
248
+ }
249
+ /**
250
+ * Compress the raw bitstring with Gzip and encode as multibase base64url (`u...`) per W3C Bitstring Status List v1.0.
251
+ */
252
+ encode() {
253
+ return `u${(0, node_zlib.gzipSync)(Buffer.from(this.bytes), { level: 9 }).toString("base64url")}`;
254
+ }
255
+ /**
256
+ * Decode a multibase base64url (`u...`) Gzip-compressed status list with anti-zip-bomb protection.
257
+ */
258
+ static decode(encodedList, options = {}) {
259
+ if (!encodedList || typeof encodedList !== "string") throw new Error("encodedList must be a non-empty string");
260
+ if (encodedList.length > MAX_COMPRESSED_STATUS_LIST_CHARS) throw new Error("encodedList exceeds maximum allowed compressed size");
261
+ if (!encodedList.startsWith("u")) throw new Error("encodedList must use multibase base64url prefix (\"u\")");
262
+ const b64u = encodedList.slice(1);
263
+ if (!b64u || !/^[A-Za-z0-9_-]+$/.test(b64u)) throw new Error("encodedList contains invalid base64url characters");
264
+ const decompressed = (0, node_zlib.gunzipSync)(Buffer.from(b64u, "base64url"), { maxOutputLength: MAX_RAW_BITSTRING_BYTES });
265
+ const rawBytes = new Uint8Array(decompressed);
266
+ const bitSize = options.bitSize ?? 1;
267
+ const entriesPerByte = 8 / bitSize;
268
+ return new BitstringStatusList({
269
+ length: options.length ?? rawBytes.byteLength * entriesPerByte,
270
+ bitSize,
271
+ statusPurpose: options.statusPurpose,
272
+ rawBytes
273
+ });
274
+ }
275
+ /**
276
+ * Compute a deterministic `SHA3-256` state root commitment suitable for anchoring
277
+ * in on-chain `IAssetState.data` or `ArcSpace` checkpoints.
278
+ */
279
+ computeStateRootHash(listId) {
280
+ if (!listId || typeof listId !== "string") throw new Error("listId must be a non-empty string");
281
+ const rawDigest = _ocap_mcrypto.Hasher.SHA3.hash256(this.bytes, 1, "hex");
282
+ const tuple = (0, _arcblock_did.encodeLengthPrefixedTuple)([
283
+ BITSTRING_STATUS_LIST_DOMAIN_TAG,
284
+ listId.trim(),
285
+ this.statusPurpose,
286
+ String(this.bitSize),
287
+ String(this.length),
288
+ rawDigest
289
+ ], 0);
290
+ return _ocap_mcrypto.Hasher.SHA3.hash256(tuple, 1, "hex");
291
+ }
292
+ };
293
+ function encodeStatusListSigningStatement(params) {
294
+ return (0, _arcblock_did.encodeLengthPrefixedTuple)([
295
+ BITSTRING_STATUS_LIST_DOMAIN_TAG,
296
+ params.id,
297
+ (0, _arcblock_did.toAddress)(params.issuerDid),
298
+ params.statusPurpose,
299
+ String(params.bitSize),
300
+ String(params.length),
301
+ params.encodedList,
302
+ params.stateRootHash,
303
+ String(params.issuedAt)
304
+ ], params.expiresAt);
305
+ }
306
+ /**
307
+ * Issue and sign a W3C `BitstringStatusListCredential` using a `@ocap/wallet` `WalletObject`.
308
+ */
309
+ async function createSignedStatusListCredential(params) {
310
+ if (!params.id || typeof params.id !== "string") throw new Error("Status list credential id is required");
311
+ if (!params.issuerWallet?.address || !params.issuerWallet?.publicKey) throw new Error("Valid issuerWallet is required");
312
+ const issuedAt = params.issuedAt ?? Math.floor(Date.now() / 1e3);
313
+ const expiresAt = params.expiresAt ?? 0;
314
+ if (!Number.isSafeInteger(issuedAt) || issuedAt < 0 || !Number.isSafeInteger(expiresAt) || expiresAt < 0) throw new Error("issuedAt and expiresAt must be non-negative safe integers");
315
+ const rawIssuerAddr = (0, _arcblock_did.toAddress)(params.issuerWallet.address);
316
+ const issuerDid = (0, _arcblock_did.formatDid)((0, _arcblock_did.isEthereumDid)(rawIssuerAddr) ? (0, _arcblock_did.toChecksumAddress)(rawIssuerAddr) : rawIssuerAddr, "abt");
317
+ const encodedList = params.statusList.encode();
318
+ const stateRootHash = params.statusList.computeStateRootHash(params.id);
319
+ const statement = encodeStatusListSigningStatement({
320
+ id: params.id,
321
+ issuerDid,
322
+ statusPurpose: params.statusList.statusPurpose,
323
+ bitSize: params.statusList.bitSize,
324
+ length: params.statusList.length,
325
+ encodedList,
326
+ stateRootHash,
327
+ issuedAt,
328
+ expiresAt
329
+ });
330
+ const signature = await params.issuerWallet.sign(statement, true, "hex");
331
+ return {
332
+ "@context": ["https://www.w3.org/ns/credentials/v2"],
333
+ id: params.id,
334
+ type: ["VerifiableCredential", "BitstringStatusListCredential"],
335
+ issuer: issuerDid,
336
+ issuerPublicKey: String(params.issuerWallet.publicKey),
337
+ validFrom: (/* @__PURE__ */ new Date(issuedAt * 1e3)).toISOString(),
338
+ issuedAt,
339
+ expiresAt,
340
+ credentialSubject: {
341
+ id: `${params.id}#list`,
342
+ type: "BitstringStatusList",
343
+ statusPurpose: params.statusList.statusPurpose,
344
+ bitSize: params.statusList.bitSize,
345
+ length: params.statusList.length,
346
+ encodedList,
347
+ stateRootHash
348
+ },
349
+ proof: {
350
+ type: "ArcBlockStatusListSignature2026",
351
+ domain: BITSTRING_STATUS_LIST_DOMAIN_TAG,
352
+ signature: String(signature)
353
+ }
354
+ };
355
+ }
356
+ /**
357
+ * Verify a `SignedStatusListCredential` and decode its `BitstringStatusList`.
358
+ */
359
+ async function verifySignedStatusListCredential(credential, options = {}) {
360
+ try {
361
+ if (!credential || credential.proof?.domain !== BITSTRING_STATUS_LIST_DOMAIN_TAG) return {
362
+ valid: false,
363
+ reason: "INVALID_CREDENTIAL_DOMAIN"
364
+ };
365
+ if (!credential.issuer || !credential.issuerPublicKey) return {
366
+ valid: false,
367
+ reason: "MISSING_ISSUER_OR_PUBLIC_KEY"
368
+ };
369
+ if (options.expectedIssuerDid && !(0, _arcblock_did.isSameEntity)((0, _arcblock_did.toAddress)(credential.issuer), (0, _arcblock_did.toAddress)(options.expectedIssuerDid))) return {
370
+ valid: false,
371
+ reason: "ISSUER_DID_MISMATCH"
372
+ };
373
+ const rawIssuerAddr = (0, _arcblock_did.toAddress)(credential.issuer);
374
+ if (!(0, _arcblock_did.isFromPublicKey)((0, _arcblock_did.isEthereumDid)(rawIssuerAddr) ? (0, _arcblock_did.toChecksumAddress)(rawIssuerAddr) : credential.issuer, credential.issuerPublicKey)) return {
375
+ valid: false,
376
+ reason: "ISSUER_PUBLIC_KEY_MISMATCH"
377
+ };
378
+ if (credential.expiresAt > 0) {
379
+ if ((options.now ?? Math.floor(Date.now() / 1e3)) > credential.expiresAt) return {
380
+ valid: false,
381
+ reason: "STATUS_LIST_CREDENTIAL_EXPIRED"
382
+ };
383
+ }
384
+ const subj = credential.credentialSubject;
385
+ if (!subj || !subj.encodedList) return {
386
+ valid: false,
387
+ reason: "MISSING_CREDENTIAL_SUBJECT"
388
+ };
389
+ const statusList = BitstringStatusList.decode(subj.encodedList, {
390
+ length: subj.length,
391
+ bitSize: subj.bitSize,
392
+ statusPurpose: subj.statusPurpose
393
+ });
394
+ const computedRoot = statusList.computeStateRootHash(credential.id);
395
+ if (computedRoot !== subj.stateRootHash) return {
396
+ valid: false,
397
+ reason: "STATE_ROOT_HASH_TAMPERED"
398
+ };
399
+ if (options.expectedStateRootHash && computedRoot !== options.expectedStateRootHash) return {
400
+ valid: false,
401
+ reason: "EXPECTED_STATE_ROOT_MISMATCH"
402
+ };
403
+ const statement = encodeStatusListSigningStatement({
404
+ id: credential.id,
405
+ issuerDid: credential.issuer,
406
+ statusPurpose: subj.statusPurpose,
407
+ bitSize: subj.bitSize,
408
+ length: subj.length,
409
+ encodedList: subj.encodedList,
410
+ stateRootHash: subj.stateRootHash,
411
+ issuedAt: credential.issuedAt,
412
+ expiresAt: credential.expiresAt
413
+ });
414
+ if (!await (0, _ocap_wallet.fromPublicKey)(credential.issuerPublicKey, (0, _arcblock_did.toTypeInfo)(credential.issuer)).verify(statement, credential.proof.signature, true)) return {
415
+ valid: false,
416
+ reason: "INVALID_ISSUER_SIGNATURE"
417
+ };
418
+ return {
419
+ valid: true,
420
+ statusList
421
+ };
422
+ } catch (err) {
423
+ return {
424
+ valid: false,
425
+ reason: err?.message || "VERIFY_STATUS_LIST_ERROR"
426
+ };
427
+ }
428
+ }
33
429
 
34
430
  //#endregion
35
- exports.fromAppDid = fromAppDid;
431
+ exports.BITSTRING_STATUS_LIST_DOMAIN_TAG = BITSTRING_STATUS_LIST_DOMAIN_TAG;
432
+ exports.BitstringStatusList = BitstringStatusList;
433
+ exports.CredentialBitStatus = CredentialBitStatus;
434
+ exports.DEFAULT_STATUS_LIST_ENTRIES = DEFAULT_STATUS_LIST_ENTRIES;
435
+ exports.LINK_PROOF_DOMAIN_TAG = LINK_PROOF_DOMAIN_TAG;
436
+ exports.MAX_COMPRESSED_STATUS_LIST_CHARS = MAX_COMPRESSED_STATUS_LIST_CHARS;
437
+ exports.MAX_RAW_BITSTRING_BYTES = MAX_RAW_BITSTRING_BYTES;
438
+ exports.MAX_STATUS_LIST_ENTRIES = MAX_STATUS_LIST_ENTRIES;
439
+ exports.MIN_STATUS_LIST_ENTRIES = MIN_STATUS_LIST_ENTRIES;
440
+ exports.STEALTH_DOMAIN_TAG = STEALTH_DOMAIN_TAG;
441
+ exports.createChainAccountLinkProof = createChainAccountLinkProof;
442
+ exports.createSignedStatusListCredential = createSignedStatusListCredential;
443
+ exports.fromAppDid = fromAppDid;
444
+ exports.fromChainDid = fromChainDid;
445
+ exports.verifyChainAccountLinkProof = verifyChainAccountLinkProof;
446
+ exports.verifySignedStatusListCredential = verifySignedStatusListCredential;
package/lib/index.d.cts CHANGED
@@ -2,12 +2,170 @@ import { DIDTypeArg } from "@arcblock/did";
2
2
  import { WalletObject } from "@ocap/wallet";
3
3
 
4
4
  //#region src/index.d.ts
5
-
5
+ declare const STEALTH_DOMAIN_TAG = "arcblock:stealth:v1";
6
+ declare const LINK_PROOF_DOMAIN_TAG = "arcblock:link-proof:v1";
7
+ interface ChainAccountLinkProof {
8
+ domain: typeof LINK_PROOF_DOMAIN_TAG;
9
+ rootDid: string;
10
+ rootPk: string;
11
+ chainDid: string;
12
+ chainAccountDid: string;
13
+ chainAccountPk: string;
14
+ index: number;
15
+ challenge: string;
16
+ expiresAt: number;
17
+ rootSignature: string;
18
+ chainAccountSignature: string;
19
+ }
6
20
  /**
7
21
  * Gen user DID from app did and rootSk
8
22
  *
9
23
  * Spec: https://github.com/ArcBlock/ABT-DID-Protocol#request-did-authentication
10
24
  */
11
25
  declare const fromAppDid: (appDid: string, rootSk: string, type?: DIDTypeArg, index?: number) => WalletObject;
26
+ /**
27
+ * Layer 2 Cross-Chain Unlinkable Key Derivation (#1167):
28
+ * Derives an independent, cryptographically unlinkable per-chain `WalletObject`
29
+ * from a software wallet `rootSk`, `chainDid`, and `index` using length-prefixed
30
+ * HMAC-SHA256 over the master secret key.
31
+ *
32
+ * Unlike Layer 1 (`deriveSubAccountAddress`), each derived chain account has a
33
+ * completely independent on-chain `publicKey` and `address`, preventing block
34
+ * explorer `GROUP BY pk` correlation across chains.
35
+ */
36
+ declare const fromChainDid: (chainDid: string, rootSk: string, type?: DIDTypeArg, index?: number) => WalletObject;
37
+ /**
38
+ * Create a selective cross-chain ownership proof (#1167) binding a `rootWallet`
39
+ * and a derived `chainWallet` for a specific `chainDid` and `challenge` without
40
+ * revealing `rootSk` or any other chain's derived accounts.
41
+ */
42
+ declare function createChainAccountLinkProof(params: {
43
+ rootWallet: WalletObject;
44
+ chainWallet: WalletObject;
45
+ chainDid: string;
46
+ index?: number;
47
+ challenge?: string;
48
+ expiresAt?: number;
49
+ }): Promise<ChainAccountLinkProof>;
50
+ /**
51
+ * Verify a selective cross-chain ownership proof (#1167).
52
+ */
53
+ declare function verifyChainAccountLinkProof(proof: ChainAccountLinkProof, options?: {
54
+ expectedChallenge?: string;
55
+ now?: number;
56
+ }): Promise<boolean>;
57
+ declare const BITSTRING_STATUS_LIST_DOMAIN_TAG = "arcblock:bitstring-status-list:v1";
58
+ declare const DEFAULT_STATUS_LIST_ENTRIES = 131072;
59
+ declare const MIN_STATUS_LIST_ENTRIES = 1024;
60
+ declare const MAX_STATUS_LIST_ENTRIES = 8388608;
61
+ declare const MAX_COMPRESSED_STATUS_LIST_CHARS = 524288;
62
+ declare const MAX_RAW_BITSTRING_BYTES = 2097152;
63
+ type StatusListBitSize = 1 | 2;
64
+ type StatusListPurpose = 'revocation' | 'suspension' | 'multi';
65
+ declare const CredentialBitStatus: Readonly<{
66
+ readonly ACTIVE: 0;
67
+ readonly REVOKED: 1;
68
+ readonly SUSPENDED: 2;
69
+ readonly RESERVED: 3;
70
+ }>;
71
+ interface SignedStatusListCredential {
72
+ '@context': string[];
73
+ id: string;
74
+ type: ['VerifiableCredential', 'BitstringStatusListCredential'];
75
+ issuer: string;
76
+ issuerPublicKey: string;
77
+ validFrom: string;
78
+ issuedAt: number;
79
+ expiresAt: number;
80
+ credentialSubject: {
81
+ id: string;
82
+ type: 'BitstringStatusList';
83
+ statusPurpose: StatusListPurpose;
84
+ bitSize: StatusListBitSize;
85
+ length: number;
86
+ encodedList: string;
87
+ stateRootHash: string;
88
+ };
89
+ proof: {
90
+ type: 'ArcBlockStatusListSignature2026';
91
+ domain: typeof BITSTRING_STATUS_LIST_DOMAIN_TAG;
92
+ signature: string;
93
+ };
94
+ }
95
+ /**
96
+ * W3C Bitstring Status List v1.0 implementation for zero-phone-home, O(1) credential
97
+ * and AI agent session key revocation/suspension.
98
+ *
99
+ * Bit numbering follows W3C Bitstring Status List specification (MSB-first within each byte):
100
+ * - For `bitSize = 1`: `byteIndex = index >> 3`, `bitOffset = 7 - (index & 7)`.
101
+ * - For `bitSize = 2`: `byteIndex = index >> 2`, `bitOffset = 6 - ((index & 3) * 2)`.
102
+ */
103
+ declare class BitstringStatusList {
104
+ readonly length: number;
105
+ readonly bitSize: StatusListBitSize;
106
+ readonly statusPurpose: StatusListPurpose;
107
+ private readonly bytes;
108
+ constructor(options?: {
109
+ length?: number;
110
+ bitSize?: StatusListBitSize;
111
+ statusPurpose?: StatusListPurpose;
112
+ rawBytes?: Uint8Array;
113
+ });
114
+ private _assertValidIndex;
115
+ /**
116
+ * Set the status value at `index` (`0..1` for `bitSize=1`, `0..3` for `bitSize=2`).
117
+ */
118
+ setStatus(index: number, status: number): void;
119
+ /**
120
+ * Get the numeric status at `index`.
121
+ */
122
+ getStatus(index: number): number;
123
+ revoke(index: number): void;
124
+ suspend(index: number): void;
125
+ reinstate(index: number): void;
126
+ isRevoked(index: number): boolean;
127
+ isSuspended(index: number): boolean;
128
+ isActive(index: number): boolean;
129
+ getRawBytes(): Uint8Array;
130
+ /**
131
+ * Compress the raw bitstring with Gzip and encode as multibase base64url (`u...`) per W3C Bitstring Status List v1.0.
132
+ */
133
+ encode(): string;
134
+ /**
135
+ * Decode a multibase base64url (`u...`) Gzip-compressed status list with anti-zip-bomb protection.
136
+ */
137
+ static decode(encodedList: string, options?: {
138
+ length?: number;
139
+ bitSize?: StatusListBitSize;
140
+ statusPurpose?: StatusListPurpose;
141
+ }): BitstringStatusList;
142
+ /**
143
+ * Compute a deterministic `SHA3-256` state root commitment suitable for anchoring
144
+ * in on-chain `IAssetState.data` or `ArcSpace` checkpoints.
145
+ */
146
+ computeStateRootHash(listId: string): string;
147
+ }
148
+ /**
149
+ * Issue and sign a W3C `BitstringStatusListCredential` using a `@ocap/wallet` `WalletObject`.
150
+ */
151
+ declare function createSignedStatusListCredential(params: {
152
+ id: string;
153
+ issuerWallet: WalletObject;
154
+ statusList: BitstringStatusList;
155
+ issuedAt?: number;
156
+ expiresAt?: number;
157
+ }): Promise<SignedStatusListCredential>;
158
+ /**
159
+ * Verify a `SignedStatusListCredential` and decode its `BitstringStatusList`.
160
+ */
161
+ declare function verifySignedStatusListCredential(credential: SignedStatusListCredential, options?: {
162
+ expectedIssuerDid?: string;
163
+ expectedStateRootHash?: string;
164
+ now?: number;
165
+ }): Promise<{
166
+ valid: boolean;
167
+ statusList?: BitstringStatusList;
168
+ reason?: string;
169
+ }>;
12
170
  //#endregion
13
- export { fromAppDid };
171
+ export { BITSTRING_STATUS_LIST_DOMAIN_TAG, BitstringStatusList, ChainAccountLinkProof, CredentialBitStatus, DEFAULT_STATUS_LIST_ENTRIES, LINK_PROOF_DOMAIN_TAG, MAX_COMPRESSED_STATUS_LIST_CHARS, MAX_RAW_BITSTRING_BYTES, MAX_STATUS_LIST_ENTRIES, MIN_STATUS_LIST_ENTRIES, STEALTH_DOMAIN_TAG, SignedStatusListCredential, StatusListBitSize, StatusListPurpose, createChainAccountLinkProof, createSignedStatusListCredential, fromAppDid, fromChainDid, verifyChainAccountLinkProof, verifySignedStatusListCredential };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcblock/did-ext",
3
- "version": "1.30.26",
3
+ "version": "1.31.1",
4
4
  "description": "Extension to work with ArcBlock DID",
5
5
  "keywords": [
6
6
  "arcblock",
@@ -57,10 +57,10 @@
57
57
  "url": "https://github.com/ArcBlock/blockchain/issues"
58
58
  },
59
59
  "dependencies": {
60
- "@arcblock/did": "1.30.26",
61
- "@ocap/mcrypto": "1.30.26",
62
- "@ocap/util": "1.30.26",
63
- "@ocap/wallet": "1.30.26",
60
+ "@arcblock/did": "1.31.1",
61
+ "@ocap/mcrypto": "1.31.1",
62
+ "@ocap/util": "1.31.1",
63
+ "@ocap/wallet": "1.31.1",
64
64
  "@scure/bip32": "^2.0.1"
65
65
  }
66
66
  }