@ocap/mcrypto 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/envelope.d.mts +76 -0
- package/esm/envelope.mjs +306 -0
- package/esm/hasher/sha2.d.mts +8 -2
- package/esm/hasher/sha2.mjs +24 -2
- package/esm/index.d.mts +3 -2
- package/esm/index.mjs +3 -2
- package/esm/signer/ed25519.d.mts +1 -1
- package/esm/signer/ed25519.mjs +14 -6
- package/esm/signer/ethereum.mjs +1 -1
- package/esm/signer/secp256k1.d.mts +1 -1
- package/esm/signer/secp256k1.mjs +9 -3
- package/esm/webauthn.mjs +1 -1
- package/lib/_vendor/@noble/hashes/sha2.cjs +1 -1
- package/lib/_vendor/@noble/hashes/sha3.cjs +1 -1
- package/lib/envelope.cjs +322 -0
- package/lib/envelope.d.cts +76 -0
- package/lib/hasher/sha2.cjs +25 -2
- package/lib/hasher/sha2.d.cts +8 -2
- package/lib/index.cjs +19 -0
- package/lib/index.d.cts +3 -2
- package/lib/signer/ed25519.cjs +13 -5
- package/lib/signer/ed25519.d.cts +1 -1
- package/lib/signer/ethereum.cjs +1 -1
- package/lib/signer/secp256k1.cjs +8 -2
- package/lib/signer/secp256k1.d.cts +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { BytesType } from "@ocap/util";
|
|
2
|
+
|
|
3
|
+
//#region src/envelope.d.ts
|
|
4
|
+
declare namespace envelope_d_exports {
|
|
5
|
+
export { ExpectedEnvelopeTxContext, WalletEnvelopeExtra, WalletEnvelopeType, assertEnvelopeMatchesTxContext, buildEd25519EnvelopePayload, buildSolanaOffchainEnvelopeBytes, computeEip191EnvelopeDigest, computeEip712EnvelopeDigest, formatWalletEnvelopeText, isCanonicalWalletEnvelopeExtra, normalizeChallengeHex, parseWalletEnvelopeExtra, signEthereumEnvelope, verifyEthereumEnvelope };
|
|
6
|
+
}
|
|
7
|
+
type WalletEnvelopeType = 'eip191' | 'eip712' | 'solana-message' | 'solana-offchain';
|
|
8
|
+
interface WalletEnvelopeExtra {
|
|
9
|
+
envelope: WalletEnvelopeType;
|
|
10
|
+
statement?: string;
|
|
11
|
+
chainId?: string;
|
|
12
|
+
action?: string;
|
|
13
|
+
from?: string;
|
|
14
|
+
nonce?: string;
|
|
15
|
+
domainName?: string;
|
|
16
|
+
domainVersion?: string;
|
|
17
|
+
applicationDomain?: string;
|
|
18
|
+
messageFormat?: number;
|
|
19
|
+
challenge?: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Normalize a challenge input (hex string or bytes) into a canonical lowercase `0x`-prefixed hex string.
|
|
23
|
+
*/
|
|
24
|
+
declare function normalizeChallengeHex(challenge: BytesType): string;
|
|
25
|
+
/**
|
|
26
|
+
* Validate whether an `extra` JSON string is a canonical cross-ecosystem wallet signature envelope.
|
|
27
|
+
* When `keyType` is provided (0 = ED25519, 1 = SECP256K1, 2 = ETHEREUM), also enforces curve compatibility.
|
|
28
|
+
*/
|
|
29
|
+
declare function isCanonicalWalletEnvelopeExtra(extra: unknown, keyType?: number): boolean;
|
|
30
|
+
declare function parseWalletEnvelopeExtra(extra: string, expectedKeyType?: number): WalletEnvelopeExtra;
|
|
31
|
+
interface ExpectedEnvelopeTxContext {
|
|
32
|
+
chainId?: string;
|
|
33
|
+
signer?: string;
|
|
34
|
+
from?: string;
|
|
35
|
+
nonce?: string | number | bigint;
|
|
36
|
+
action?: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Verifies that any human-readable metadata field present in a signed wallet envelope
|
|
40
|
+
* (`chainId`, `from`, `nonce`, `action`) matches the authoritative transaction context,
|
|
41
|
+
* preventing "What You See Is Not What You Sign" (WYSIWYS) blind-phishing spoofing.
|
|
42
|
+
*/
|
|
43
|
+
declare function assertEnvelopeMatchesTxContext(extra: string | WalletEnvelopeExtra, expected: ExpectedEnvelopeTxContext): void;
|
|
44
|
+
/**
|
|
45
|
+
* Deterministically reconstruct the human-readable envelope text from the authoritative transaction challenge
|
|
46
|
+
* and validated single-line metadata fields.
|
|
47
|
+
*/
|
|
48
|
+
declare function formatWalletEnvelopeText(challenge: BytesType, meta?: Partial<WalletEnvelopeExtra>): string;
|
|
49
|
+
/**
|
|
50
|
+
* Compute the EIP-191 (`personal_sign`) 32-byte keccak256 digest over the canonical envelope text.
|
|
51
|
+
*/
|
|
52
|
+
declare function computeEip191EnvelopeDigest(challenge: BytesType, meta?: Partial<WalletEnvelopeExtra>): Uint8Array;
|
|
53
|
+
/**
|
|
54
|
+
* Compute the EIP-712 (`eth_signTypedData_v4`) 32-byte digest for an ArcBlockTransaction envelope.
|
|
55
|
+
*/
|
|
56
|
+
declare function computeEip712EnvelopeDigest(challenge: BytesType, meta?: Partial<WalletEnvelopeExtra>): Uint8Array;
|
|
57
|
+
/**
|
|
58
|
+
* Build the canonical Solana Off-Chain Message v0 binary payload (`\xffsolana offchain` header + UTF-8 body).
|
|
59
|
+
* Compatible with Phantom, Solflare, and Ledger Solana off-chain message signing.
|
|
60
|
+
*/
|
|
61
|
+
declare function buildSolanaOffchainEnvelopeBytes(challenge: BytesType, pk: BytesType, meta?: Partial<WalletEnvelopeExtra>): Uint8Array;
|
|
62
|
+
/**
|
|
63
|
+
* Sign an Ethereum/Secp256k1 wallet envelope (`eip191` or `eip712`) and return a 65-byte recoverable `0x{r}{s}{v}` hex signature.
|
|
64
|
+
*/
|
|
65
|
+
declare function signEthereumEnvelope(challenge: BytesType, sk: BytesType, extra: string | WalletEnvelopeExtra): string;
|
|
66
|
+
/**
|
|
67
|
+
* Verify an Ethereum/Secp256k1 wallet envelope (`eip191` or `eip712`) against `pk`.
|
|
68
|
+
* Requires a canonical 65-byte Ethereum recoverable signature (`r[32] || s[32] || v[1]`) with `v` in `{27, 28}` and low-S.
|
|
69
|
+
*/
|
|
70
|
+
declare function verifyEthereumEnvelope(challenge: BytesType, signature: BytesType, pk: BytesType, extra: string): boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Construct the exact byte payload to be signed/verified for a Solana Ed25519 wallet envelope (`solana-message` or `solana-offchain`).
|
|
73
|
+
*/
|
|
74
|
+
declare function buildEd25519EnvelopePayload(challenge: BytesType, pk: BytesType, extra: string): Uint8Array;
|
|
75
|
+
//#endregion
|
|
76
|
+
export { ExpectedEnvelopeTxContext, WalletEnvelopeExtra, WalletEnvelopeType, assertEnvelopeMatchesTxContext, buildEd25519EnvelopePayload, buildSolanaOffchainEnvelopeBytes, computeEip191EnvelopeDigest, computeEip712EnvelopeDigest, envelope_d_exports, formatWalletEnvelopeText, isCanonicalWalletEnvelopeExtra, normalizeChallengeHex, parseWalletEnvelopeExtra, signEthereumEnvelope, verifyEthereumEnvelope };
|
package/esm/envelope.mjs
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import { __exportAll } from "./_virtual/rolldown_runtime.mjs";
|
|
2
|
+
import { toHex, toUint8Array } from "@ocap/util";
|
|
3
|
+
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
4
|
+
import { keccak_256 } from "@noble/hashes/sha3.js";
|
|
5
|
+
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
6
|
+
|
|
7
|
+
//#region src/envelope.ts
|
|
8
|
+
var envelope_exports = /* @__PURE__ */ __exportAll({
|
|
9
|
+
assertEnvelopeMatchesTxContext: () => assertEnvelopeMatchesTxContext,
|
|
10
|
+
buildEd25519EnvelopePayload: () => buildEd25519EnvelopePayload,
|
|
11
|
+
buildSolanaOffchainEnvelopeBytes: () => buildSolanaOffchainEnvelopeBytes,
|
|
12
|
+
computeEip191EnvelopeDigest: () => computeEip191EnvelopeDigest,
|
|
13
|
+
computeEip712EnvelopeDigest: () => computeEip712EnvelopeDigest,
|
|
14
|
+
formatWalletEnvelopeText: () => formatWalletEnvelopeText,
|
|
15
|
+
isCanonicalWalletEnvelopeExtra: () => isCanonicalWalletEnvelopeExtra,
|
|
16
|
+
normalizeChallengeHex: () => normalizeChallengeHex,
|
|
17
|
+
parseWalletEnvelopeExtra: () => parseWalletEnvelopeExtra,
|
|
18
|
+
signEthereumEnvelope: () => signEthereumEnvelope,
|
|
19
|
+
verifyEthereumEnvelope: () => verifyEthereumEnvelope
|
|
20
|
+
});
|
|
21
|
+
const ETHEREUM_ENVELOPES = new Set(["eip191", "eip712"]);
|
|
22
|
+
const ED25519_ENVELOPES = new Set(["solana-message", "solana-offchain"]);
|
|
23
|
+
const ALL_ENVELOPES = new Set([
|
|
24
|
+
"eip191",
|
|
25
|
+
"eip712",
|
|
26
|
+
"solana-message",
|
|
27
|
+
"solana-offchain"
|
|
28
|
+
]);
|
|
29
|
+
const MAX_FIELD_LENGTH = 256;
|
|
30
|
+
const MAX_ENVELOPE_EXTRA_LENGTH = 2048;
|
|
31
|
+
const ALLOWED_ENVELOPE_KEYS = new Set([
|
|
32
|
+
"envelope",
|
|
33
|
+
"statement",
|
|
34
|
+
"chainId",
|
|
35
|
+
"action",
|
|
36
|
+
"from",
|
|
37
|
+
"nonce",
|
|
38
|
+
"domainName",
|
|
39
|
+
"domainVersion",
|
|
40
|
+
"applicationDomain",
|
|
41
|
+
"messageFormat",
|
|
42
|
+
"challenge"
|
|
43
|
+
]);
|
|
44
|
+
const SOLANA_OFFCHAIN_SIGNING_DOMAIN = new Uint8Array([
|
|
45
|
+
255,
|
|
46
|
+
115,
|
|
47
|
+
111,
|
|
48
|
+
108,
|
|
49
|
+
97,
|
|
50
|
+
110,
|
|
51
|
+
97,
|
|
52
|
+
32,
|
|
53
|
+
111,
|
|
54
|
+
102,
|
|
55
|
+
102,
|
|
56
|
+
99,
|
|
57
|
+
104,
|
|
58
|
+
97,
|
|
59
|
+
105,
|
|
60
|
+
110
|
|
61
|
+
]);
|
|
62
|
+
const DEFAULT_SOLANA_APP_DOMAIN = "ArcBlock Transaction Envelope v1";
|
|
63
|
+
function isSafeSingleLine(value, maxLen = MAX_FIELD_LENGTH) {
|
|
64
|
+
if (typeof value !== "string") return false;
|
|
65
|
+
if (value.length > maxLen) return false;
|
|
66
|
+
return !/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/.test(value);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Normalize a challenge input (hex string or bytes) into a canonical lowercase `0x`-prefixed hex string.
|
|
70
|
+
*/
|
|
71
|
+
function normalizeChallengeHex(challenge) {
|
|
72
|
+
if (typeof challenge === "string") {
|
|
73
|
+
const trimmed = challenge.trim();
|
|
74
|
+
if (/^(0x)?[0-9a-fA-F]+$/.test(trimmed) && trimmed.replace(/^0x/i, "").length % 2 === 0) return `0x${trimmed.replace(/^0x/i, "").toLowerCase()}`;
|
|
75
|
+
}
|
|
76
|
+
return `0x${bytesToHex(toUint8Array(challenge)).toLowerCase()}`;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Validate whether an `extra` JSON string is a canonical cross-ecosystem wallet signature envelope.
|
|
80
|
+
* When `keyType` is provided (0 = ED25519, 1 = SECP256K1, 2 = ETHEREUM), also enforces curve compatibility.
|
|
81
|
+
*/
|
|
82
|
+
function isCanonicalWalletEnvelopeExtra(extra, keyType) {
|
|
83
|
+
if (typeof extra !== "string" || !extra || extra.length > MAX_ENVELOPE_EXTRA_LENGTH) return false;
|
|
84
|
+
try {
|
|
85
|
+
const parsed = JSON.parse(extra);
|
|
86
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
|
|
87
|
+
for (const key of Object.keys(parsed)) if (!ALLOWED_ENVELOPE_KEYS.has(key)) return false;
|
|
88
|
+
const envelope = parsed.envelope;
|
|
89
|
+
if (!ALL_ENVELOPES.has(envelope)) return false;
|
|
90
|
+
if (keyType !== void 0) {
|
|
91
|
+
if (keyType === 0 && !ED25519_ENVELOPES.has(envelope)) return false;
|
|
92
|
+
if ((keyType === 1 || keyType === 2) && !ETHEREUM_ENVELOPES.has(envelope)) return false;
|
|
93
|
+
if (keyType !== 0 && keyType !== 1 && keyType !== 2) return false;
|
|
94
|
+
}
|
|
95
|
+
for (const field of [
|
|
96
|
+
"statement",
|
|
97
|
+
"chainId",
|
|
98
|
+
"action",
|
|
99
|
+
"from",
|
|
100
|
+
"nonce",
|
|
101
|
+
"domainName",
|
|
102
|
+
"domainVersion",
|
|
103
|
+
"applicationDomain",
|
|
104
|
+
"challenge"
|
|
105
|
+
]) if (parsed[field] !== void 0 && !isSafeSingleLine(parsed[field])) return false;
|
|
106
|
+
if (parsed.messageFormat !== void 0 && parsed.messageFormat !== 0 && parsed.messageFormat !== 1 && parsed.messageFormat !== 2) return false;
|
|
107
|
+
return true;
|
|
108
|
+
} catch {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function parseWalletEnvelopeExtra(extra, expectedKeyType) {
|
|
113
|
+
if (!isCanonicalWalletEnvelopeExtra(extra, expectedKeyType)) throw new Error("Invalid or non-canonical wallet signature envelope extra");
|
|
114
|
+
return JSON.parse(extra);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Verifies that any human-readable metadata field present in a signed wallet envelope
|
|
118
|
+
* (`chainId`, `from`, `nonce`, `action`) matches the authoritative transaction context,
|
|
119
|
+
* preventing "What You See Is Not What You Sign" (WYSIWYS) blind-phishing spoofing.
|
|
120
|
+
*/
|
|
121
|
+
function assertEnvelopeMatchesTxContext(extra, expected) {
|
|
122
|
+
const parsed = typeof extra === "string" ? parseWalletEnvelopeExtra(extra) : extra;
|
|
123
|
+
if (parsed.chainId !== void 0 && expected.chainId !== void 0 && expected.chainId !== "") {
|
|
124
|
+
if (parsed.chainId !== expected.chainId) throw new Error(`Envelope chainId "${parsed.chainId}" does not match transaction chainId "${expected.chainId}"`);
|
|
125
|
+
}
|
|
126
|
+
if (parsed.from !== void 0) {
|
|
127
|
+
const allowedSigners = [expected.signer, expected.from].filter((v) => typeof v === "string" && v.length > 0);
|
|
128
|
+
if (allowedSigners.length > 0 && !allowedSigners.includes(parsed.from)) throw new Error(`Envelope signer "${parsed.from}" does not match transaction signer "${allowedSigners[0]}"`);
|
|
129
|
+
}
|
|
130
|
+
if (parsed.nonce !== void 0 && expected.nonce !== void 0 && String(expected.nonce) !== "") {
|
|
131
|
+
if (parsed.nonce !== String(expected.nonce)) throw new Error(`Envelope nonce "${parsed.nonce}" does not match transaction nonce "${String(expected.nonce)}"`);
|
|
132
|
+
}
|
|
133
|
+
if (parsed.action !== void 0 && expected.action !== void 0 && expected.action !== "") {
|
|
134
|
+
const shortAction = expected.action.replace(/^fg:t:/, "");
|
|
135
|
+
if (parsed.action !== expected.action && parsed.action !== shortAction) throw new Error(`Envelope action "${parsed.action}" does not match transaction action "${expected.action}"`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Deterministically reconstruct the human-readable envelope text from the authoritative transaction challenge
|
|
140
|
+
* and validated single-line metadata fields.
|
|
141
|
+
*/
|
|
142
|
+
function formatWalletEnvelopeText(challenge, meta = {}) {
|
|
143
|
+
const challengeHex = normalizeChallengeHex(challenge);
|
|
144
|
+
if (meta.challenge !== void 0 && normalizeChallengeHex(meta.challenge) !== challengeHex) throw new Error("challenge mismatch in wallet signature envelope");
|
|
145
|
+
for (const field of [
|
|
146
|
+
"statement",
|
|
147
|
+
"chainId",
|
|
148
|
+
"action",
|
|
149
|
+
"from",
|
|
150
|
+
"nonce"
|
|
151
|
+
]) if (meta[field] !== void 0 && !isSafeSingleLine(meta[field])) throw new Error(`Invalid character in wallet envelope field "${field}"`);
|
|
152
|
+
const lines = ["ArcBlock Transaction v1"];
|
|
153
|
+
if (meta.statement) lines.push(`Statement: ${meta.statement}`);
|
|
154
|
+
if (meta.chainId) lines.push(`Chain: ${meta.chainId}`);
|
|
155
|
+
if (meta.action) lines.push(`Action: ${meta.action}`);
|
|
156
|
+
if (meta.from) lines.push(`Signer: ${meta.from}`);
|
|
157
|
+
if (meta.nonce) lines.push(`Nonce: ${meta.nonce}`);
|
|
158
|
+
lines.push(`Challenge: ${challengeHex}`);
|
|
159
|
+
return lines.join("\n");
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Compute the EIP-191 (`personal_sign`) 32-byte keccak256 digest over the canonical envelope text.
|
|
163
|
+
*/
|
|
164
|
+
function computeEip191EnvelopeDigest(challenge, meta = {}) {
|
|
165
|
+
const text = formatWalletEnvelopeText(challenge, meta);
|
|
166
|
+
const messageBytes = Buffer.from(text, "utf8");
|
|
167
|
+
const preamble = Buffer.from(`\x19Ethereum Signed Message:\n${messageBytes.byteLength}`, "utf8");
|
|
168
|
+
return keccak_256(new Uint8Array(Buffer.concat([preamble, messageBytes])));
|
|
169
|
+
}
|
|
170
|
+
const EIP712_DOMAIN_TYPEHASH = keccak_256(new Uint8Array(Buffer.from("EIP712Domain(string name,string version)", "utf8")));
|
|
171
|
+
const EIP712_TX_TYPEHASH = keccak_256(new Uint8Array(Buffer.from("ArcBlockTransaction(string chainId,string action,string from,string nonce,string challenge)", "utf8")));
|
|
172
|
+
function keccakUtf8(value) {
|
|
173
|
+
return keccak_256(new Uint8Array(Buffer.from(value, "utf8")));
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Compute the EIP-712 (`eth_signTypedData_v4`) 32-byte digest for an ArcBlockTransaction envelope.
|
|
177
|
+
*/
|
|
178
|
+
function computeEip712EnvelopeDigest(challenge, meta = {}) {
|
|
179
|
+
const challengeHex = normalizeChallengeHex(challenge);
|
|
180
|
+
if (meta.challenge !== void 0 && normalizeChallengeHex(meta.challenge) !== challengeHex) throw new Error("challenge mismatch in wallet signature envelope");
|
|
181
|
+
for (const field of [
|
|
182
|
+
"chainId",
|
|
183
|
+
"action",
|
|
184
|
+
"from",
|
|
185
|
+
"nonce",
|
|
186
|
+
"domainName",
|
|
187
|
+
"domainVersion"
|
|
188
|
+
]) if (meta[field] !== void 0 && !isSafeSingleLine(meta[field])) throw new Error(`Invalid character in wallet envelope field "${field}"`);
|
|
189
|
+
const domainName = meta.domainName || "ArcBlock";
|
|
190
|
+
const domainVersion = meta.domainVersion || "1";
|
|
191
|
+
const chainId = meta.chainId || "arcblock";
|
|
192
|
+
const action = meta.action || "transaction";
|
|
193
|
+
const from = meta.from || "";
|
|
194
|
+
const nonce = meta.nonce || "";
|
|
195
|
+
const domainSeparator = keccak_256(new Uint8Array(Buffer.concat([
|
|
196
|
+
EIP712_DOMAIN_TYPEHASH,
|
|
197
|
+
keccakUtf8(domainName),
|
|
198
|
+
keccakUtf8(domainVersion)
|
|
199
|
+
])));
|
|
200
|
+
const structHash = keccak_256(new Uint8Array(Buffer.concat([
|
|
201
|
+
EIP712_TX_TYPEHASH,
|
|
202
|
+
keccakUtf8(chainId),
|
|
203
|
+
keccakUtf8(action),
|
|
204
|
+
keccakUtf8(from),
|
|
205
|
+
keccakUtf8(nonce),
|
|
206
|
+
keccakUtf8(challengeHex)
|
|
207
|
+
])));
|
|
208
|
+
return keccak_256(new Uint8Array(Buffer.concat([
|
|
209
|
+
Buffer.from([25, 1]),
|
|
210
|
+
domainSeparator,
|
|
211
|
+
structHash
|
|
212
|
+
])));
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Build the canonical Solana Off-Chain Message v0 binary payload (`\xffsolana offchain` header + UTF-8 body).
|
|
216
|
+
* Compatible with Phantom, Solflare, and Ledger Solana off-chain message signing.
|
|
217
|
+
*/
|
|
218
|
+
function buildSolanaOffchainEnvelopeBytes(challenge, pk, meta = {}) {
|
|
219
|
+
const pkBytes = toUint8Array(pk);
|
|
220
|
+
if (pkBytes.byteLength !== 32) throw new Error("Solana offchain envelope requires a 32-byte Ed25519 public key");
|
|
221
|
+
const text = formatWalletEnvelopeText(challenge, meta);
|
|
222
|
+
const messageBytes = Buffer.from(text, "utf8");
|
|
223
|
+
if (messageBytes.byteLength > 65535) throw new Error("Solana offchain message exceeds maximum uint16 length");
|
|
224
|
+
const appDomainStr = meta.applicationDomain || DEFAULT_SOLANA_APP_DOMAIN;
|
|
225
|
+
if (!isSafeSingleLine(appDomainStr, 32)) throw new Error("Solana offchain applicationDomain must be a single-line string of at most 32 bytes");
|
|
226
|
+
const appDomainBytes = Buffer.alloc(32, 0);
|
|
227
|
+
const encodedDomain = Buffer.from(appDomainStr, "utf8");
|
|
228
|
+
if (encodedDomain.byteLength > 32) throw new Error("Solana offchain applicationDomain exceeds 32 UTF-8 bytes");
|
|
229
|
+
encodedDomain.copy(appDomainBytes);
|
|
230
|
+
const messageFormat = meta.messageFormat ?? 1;
|
|
231
|
+
const header = Buffer.alloc(85);
|
|
232
|
+
let offset = 0;
|
|
233
|
+
Buffer.from(SOLANA_OFFCHAIN_SIGNING_DOMAIN).copy(header, offset);
|
|
234
|
+
offset += 16;
|
|
235
|
+
header.writeUInt8(0, offset);
|
|
236
|
+
offset += 1;
|
|
237
|
+
appDomainBytes.copy(header, offset);
|
|
238
|
+
offset += 32;
|
|
239
|
+
header.writeUInt8(messageFormat, offset);
|
|
240
|
+
offset += 1;
|
|
241
|
+
header.writeUInt8(1, offset);
|
|
242
|
+
offset += 1;
|
|
243
|
+
Buffer.from(pkBytes).copy(header, offset);
|
|
244
|
+
offset += 32;
|
|
245
|
+
header.writeUInt16LE(messageBytes.byteLength, offset);
|
|
246
|
+
return new Uint8Array(Buffer.concat([header, messageBytes]));
|
|
247
|
+
}
|
|
248
|
+
function normalizeSecp256k1PublicKey(pk) {
|
|
249
|
+
const pkBytes = toUint8Array(pk);
|
|
250
|
+
if (pkBytes.byteLength === 64) {
|
|
251
|
+
const prefixed = new Uint8Array(65);
|
|
252
|
+
prefixed[0] = 4;
|
|
253
|
+
prefixed.set(pkBytes, 1);
|
|
254
|
+
return prefixed;
|
|
255
|
+
}
|
|
256
|
+
return pkBytes;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Sign an Ethereum/Secp256k1 wallet envelope (`eip191` or `eip712`) and return a 65-byte recoverable `0x{r}{s}{v}` hex signature.
|
|
260
|
+
*/
|
|
261
|
+
function signEthereumEnvelope(challenge, sk, extra) {
|
|
262
|
+
const parsed = typeof extra === "string" ? parseWalletEnvelopeExtra(extra, 2) : extra;
|
|
263
|
+
const digest = parsed.envelope === "eip712" ? computeEip712EnvelopeDigest(challenge, parsed) : computeEip191EnvelopeDigest(challenge, parsed);
|
|
264
|
+
const skBytes = toUint8Array(sk);
|
|
265
|
+
const recoveredBytes = secp256k1.sign(digest, skBytes, {
|
|
266
|
+
prehash: false,
|
|
267
|
+
format: "recovered"
|
|
268
|
+
});
|
|
269
|
+
const sig = secp256k1.Signature.fromBytes(recoveredBytes, "recovered");
|
|
270
|
+
const v = (27 + sig.recovery).toString(16).padStart(2, "0");
|
|
271
|
+
return `0x${sig.toHex("compact")}${v}`;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Verify an Ethereum/Secp256k1 wallet envelope (`eip191` or `eip712`) against `pk`.
|
|
275
|
+
* Requires a canonical 65-byte Ethereum recoverable signature (`r[32] || s[32] || v[1]`) with `v` in `{27, 28}` and low-S.
|
|
276
|
+
*/
|
|
277
|
+
function verifyEthereumEnvelope(challenge, signature, pk, extra) {
|
|
278
|
+
const parsed = parseWalletEnvelopeExtra(extra, 2);
|
|
279
|
+
const digest = parsed.envelope === "eip712" ? computeEip712EnvelopeDigest(challenge, parsed) : computeEip191EnvelopeDigest(challenge, parsed);
|
|
280
|
+
const expectedPk = normalizeSecp256k1PublicKey(pk);
|
|
281
|
+
const sigHex = toHex(toUint8Array(signature)).replace(/^0x/i, "");
|
|
282
|
+
if (sigHex.length !== 130) return false;
|
|
283
|
+
const v = Number.parseInt(sigHex.slice(128, 130), 16);
|
|
284
|
+
if (v !== 27 && v !== 28) return false;
|
|
285
|
+
const recovery = v - 27;
|
|
286
|
+
try {
|
|
287
|
+
const sig = secp256k1.Signature.fromHex(sigHex.slice(0, 128), "compact").addRecoveryBit(recovery);
|
|
288
|
+
if (sig.hasHighS()) return false;
|
|
289
|
+
const recoveredPk = sig.recoverPublicKey(digest).toBytes(expectedPk.byteLength === 33);
|
|
290
|
+
return recoveredPk.byteLength === expectedPk.byteLength && recoveredPk.every((b, idx) => b === expectedPk[idx]);
|
|
291
|
+
} catch {
|
|
292
|
+
return false;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Construct the exact byte payload to be signed/verified for a Solana Ed25519 wallet envelope (`solana-message` or `solana-offchain`).
|
|
297
|
+
*/
|
|
298
|
+
function buildEd25519EnvelopePayload(challenge, pk, extra) {
|
|
299
|
+
const parsed = parseWalletEnvelopeExtra(extra, 0);
|
|
300
|
+
if (parsed.envelope === "solana-offchain") return buildSolanaOffchainEnvelopeBytes(challenge, pk, parsed);
|
|
301
|
+
const text = formatWalletEnvelopeText(challenge, parsed);
|
|
302
|
+
return new Uint8Array(Buffer.from(text, "utf8"));
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
//#endregion
|
|
306
|
+
export { assertEnvelopeMatchesTxContext, buildEd25519EnvelopePayload, buildSolanaOffchainEnvelopeBytes, computeEip191EnvelopeDigest, computeEip712EnvelopeDigest, envelope_exports, formatWalletEnvelopeText, isCanonicalWalletEnvelopeExtra, normalizeChallengeHex, parseWalletEnvelopeExtra, signEthereumEnvelope, verifyEthereumEnvelope };
|
package/esm/hasher/sha2.d.mts
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import { BytesType, EncodingType } from "@ocap/util";
|
|
2
2
|
|
|
3
3
|
//#region src/hasher/sha2.d.ts
|
|
4
|
-
|
|
4
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: 'hex'): string;
|
|
5
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: 'base16'): string;
|
|
6
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: 'base58'): string;
|
|
7
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: 'base64'): string;
|
|
8
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: 'buffer'): Buffer;
|
|
9
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: 'Uint8Array'): Uint8Array;
|
|
10
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: EncodingType): BytesType;
|
|
5
11
|
/**
|
|
6
12
|
* Sha2 support with different hash length
|
|
7
13
|
* Uses native node:crypto when available with @noble/hashes fallback
|
|
@@ -14,4 +20,4 @@ declare class Sha2Hasher {
|
|
|
14
20
|
}
|
|
15
21
|
declare const _default: Sha2Hasher;
|
|
16
22
|
//#endregion
|
|
17
|
-
export { Sha2Hasher, _default as default };
|
|
23
|
+
export { Sha2Hasher, _default as default, hmacSha256 };
|
package/esm/hasher/sha2.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { encode } from "../encode.mjs";
|
|
2
2
|
import { toUint8Array } from "@ocap/util";
|
|
3
3
|
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
4
|
+
import { hmac } from "@noble/hashes/hmac.js";
|
|
4
5
|
import { sha224, sha256, sha384, sha512 } from "@noble/hashes/sha2.js";
|
|
5
6
|
|
|
6
7
|
//#region src/hasher/sha2.ts
|
|
@@ -10,7 +11,28 @@ const hashFns = {
|
|
|
10
11
|
sha384,
|
|
11
12
|
sha512
|
|
12
13
|
};
|
|
13
|
-
const
|
|
14
|
+
const nodeCrypto = typeof process !== "undefined" ? process.getBuiltinModule?.("node:crypto") : void 0;
|
|
15
|
+
const createHash = nodeCrypto?.createHash;
|
|
16
|
+
const createHmac = nodeCrypto?.createHmac;
|
|
17
|
+
const toBytes = (data) => {
|
|
18
|
+
if (data instanceof Uint8Array) return data;
|
|
19
|
+
if (typeof data === "string") try {
|
|
20
|
+
return toUint8Array(data);
|
|
21
|
+
} catch (_err) {
|
|
22
|
+
return new TextEncoder().encode(data);
|
|
23
|
+
}
|
|
24
|
+
return toUint8Array(data);
|
|
25
|
+
};
|
|
26
|
+
function hmacSha256(key, data, encoding = "hex") {
|
|
27
|
+
const keyBytes = toBytes(key);
|
|
28
|
+
const dataBytes = toBytes(data);
|
|
29
|
+
const res = createHmac ? createHmac("sha256", keyBytes).update(dataBytes).digest() : hmac(sha256, keyBytes, dataBytes);
|
|
30
|
+
const isBuf = typeof Buffer !== "undefined" && Buffer.isBuffer(res);
|
|
31
|
+
if (encoding === "hex" || encoding === "base16") return isBuf ? `0x${res.toString("hex")}` : `0x${bytesToHex(res)}`;
|
|
32
|
+
if (encoding === "buffer" && typeof Buffer !== "undefined") return isBuf ? res : Buffer.from(res.buffer, res.byteOffset, res.byteLength);
|
|
33
|
+
if (encoding === "Uint8Array") return isBuf ? new Uint8Array(res) : res;
|
|
34
|
+
return encode(res, encoding);
|
|
35
|
+
}
|
|
14
36
|
/**
|
|
15
37
|
* Sha2 support with different hash length
|
|
16
38
|
* Uses native node:crypto when available with @noble/hashes fallback
|
|
@@ -60,4 +82,4 @@ var Sha2Hasher = class {
|
|
|
60
82
|
var sha2_default = new Sha2Hasher();
|
|
61
83
|
|
|
62
84
|
//#endregion
|
|
63
|
-
export { Sha2Hasher, sha2_default as default };
|
|
85
|
+
export { Sha2Hasher, sha2_default as default, hmacSha256 };
|
package/esm/index.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { ExpectedEnvelopeTxContext, WalletEnvelopeExtra, WalletEnvelopeType, assertEnvelopeMatchesTxContext, buildEd25519EnvelopePayload, buildSolanaOffchainEnvelopeBytes, computeEip191EnvelopeDigest, computeEip712EnvelopeDigest, envelope_d_exports, formatWalletEnvelopeText, isCanonicalWalletEnvelopeExtra, normalizeChallengeHex, parseWalletEnvelopeExtra, signEthereumEnvelope, verifyEthereumEnvelope } from "./envelope.mjs";
|
|
1
2
|
import { KeccakHasher } from "./hasher/keccak.mjs";
|
|
2
|
-
import { Sha2Hasher } from "./hasher/sha2.mjs";
|
|
3
|
+
import { Sha2Hasher, hmacSha256 } from "./hasher/sha2.mjs";
|
|
3
4
|
import { Sha3Hasher } from "./hasher/sha3.mjs";
|
|
4
5
|
import { Ed25519Signer } from "./signer/ed25519.mjs";
|
|
5
6
|
import { Secp256k1Signer } from "./signer/secp256k1.mjs";
|
|
@@ -239,4 +240,4 @@ declare function getRandomBytes(length: number, encoding?: 'Uint8Array'): Uint8A
|
|
|
239
240
|
declare function getRandomBytes(length: number, encoding?: EncodingType): BytesType;
|
|
240
241
|
declare const toTxHash: (buf: Buffer | Uint8Array) => string;
|
|
241
242
|
//#endregion
|
|
242
|
-
export { AddressType, HashFnType, HashType, Hasher, KeyType, RoleType, Signer, SignerType, getHasher, getRandomBytes, getSigner, toTxHash, types, webauthn_d_exports as webauthn };
|
|
243
|
+
export { AddressType, ExpectedEnvelopeTxContext, HashFnType, HashType, Hasher, KeyType, RoleType, Signer, SignerType, WalletEnvelopeExtra, WalletEnvelopeType, assertEnvelopeMatchesTxContext, buildEd25519EnvelopePayload, buildSolanaOffchainEnvelopeBytes, computeEip191EnvelopeDigest, computeEip712EnvelopeDigest, envelope_d_exports as envelope, formatWalletEnvelopeText, getHasher, getRandomBytes, getSigner, hmacSha256, isCanonicalWalletEnvelopeExtra, normalizeChallengeHex, parseWalletEnvelopeExtra, signEthereumEnvelope, toTxHash, types, verifyEthereumEnvelope, webauthn_d_exports as webauthn };
|
package/esm/index.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { encode } from "./encode.mjs";
|
|
2
|
+
import { assertEnvelopeMatchesTxContext, buildEd25519EnvelopePayload, buildSolanaOffchainEnvelopeBytes, computeEip191EnvelopeDigest, computeEip712EnvelopeDigest, envelope_exports, formatWalletEnvelopeText, isCanonicalWalletEnvelopeExtra, normalizeChallengeHex, parseWalletEnvelopeExtra, signEthereumEnvelope, verifyEthereumEnvelope } from "./envelope.mjs";
|
|
2
3
|
import keccak_default from "./hasher/keccak.mjs";
|
|
3
|
-
import sha2_default from "./hasher/sha2.mjs";
|
|
4
|
+
import sha2_default, { hmacSha256 } from "./hasher/sha2.mjs";
|
|
4
5
|
import sha3_default from "./hasher/sha3.mjs";
|
|
5
6
|
import ed25519_default from "./signer/ed25519.mjs";
|
|
6
7
|
import secp256k1_default from "./signer/secp256k1.mjs";
|
|
@@ -182,4 +183,4 @@ function getRandomBytes(length = 32, encoding = "hex") {
|
|
|
182
183
|
const toTxHash = (buf) => Hasher.SHA2.hash256(buf, 1, "hex").replace(/^0x/, "").toUpperCase();
|
|
183
184
|
|
|
184
185
|
//#endregion
|
|
185
|
-
export { Hasher, Signer, getHasher, getRandomBytes, getSigner, toTxHash, types, webauthn_exports as webauthn };
|
|
186
|
+
export { Hasher, Signer, assertEnvelopeMatchesTxContext, buildEd25519EnvelopePayload, buildSolanaOffchainEnvelopeBytes, computeEip191EnvelopeDigest, computeEip712EnvelopeDigest, envelope_exports as envelope, formatWalletEnvelopeText, getHasher, getRandomBytes, getSigner, hmacSha256, isCanonicalWalletEnvelopeExtra, normalizeChallengeHex, parseWalletEnvelopeExtra, signEthereumEnvelope, toTxHash, types, verifyEthereumEnvelope, webauthn_exports as webauthn };
|
package/esm/signer/ed25519.d.mts
CHANGED
|
@@ -58,7 +58,7 @@ declare class Ed25519Signer extends _default$1 {
|
|
|
58
58
|
* @param {string|buffer} pk
|
|
59
59
|
* @returns {bool}
|
|
60
60
|
*/
|
|
61
|
-
verify(message: BytesType, signature: BytesType, pk: BytesType): boolean;
|
|
61
|
+
verify(message: BytesType, signature: BytesType, pk: BytesType, extra?: string): boolean;
|
|
62
62
|
}
|
|
63
63
|
declare const _default: Ed25519Signer;
|
|
64
64
|
//#endregion
|
package/esm/signer/ed25519.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { encode } from "../encode.mjs";
|
|
2
|
+
import { buildEd25519EnvelopePayload } from "../envelope.mjs";
|
|
2
3
|
import signer_default from "../protocols/signer.mjs";
|
|
3
4
|
import { toUint8Array } from "@ocap/util";
|
|
4
|
-
import randomBytes from "randombytes";
|
|
5
5
|
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
6
|
+
import randomBytes from "randombytes";
|
|
6
7
|
import { sha512 } from "@noble/hashes/sha2.js";
|
|
7
8
|
import * as ed from "@noble/ed25519";
|
|
8
9
|
|
|
@@ -204,15 +205,22 @@ var Ed25519Signer = class extends signer_default {
|
|
|
204
205
|
* @param {string|buffer} pk
|
|
205
206
|
* @returns {bool}
|
|
206
207
|
*/
|
|
207
|
-
verify(message, signature, pk) {
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
208
|
+
verify(message, signature, pk, extra) {
|
|
209
|
+
let pkBytes;
|
|
210
|
+
let messageBytes;
|
|
211
|
+
let signatureBytes;
|
|
212
|
+
try {
|
|
213
|
+
pkBytes = toBytes(pk);
|
|
214
|
+
messageBytes = extra ? buildEd25519EnvelopePayload(message, pkBytes, extra) : toBytes(message);
|
|
215
|
+
signatureBytes = toBytes(signature);
|
|
216
|
+
} catch {
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
211
219
|
if (pkBytes.byteLength !== 32 || signatureBytes.byteLength !== 64) return false;
|
|
212
220
|
if (nodeCrypto?.verify) {
|
|
213
221
|
const pubKeyObject = getNativePublicKeyObject(pkBytes);
|
|
214
222
|
if (pubKeyObject) try {
|
|
215
|
-
|
|
223
|
+
return nodeCrypto.verify(null, messageBytes, pubKeyObject, signatureBytes);
|
|
216
224
|
} catch {}
|
|
217
225
|
}
|
|
218
226
|
try {
|
package/esm/signer/ethereum.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Secp256k1Signer } from "./secp256k1.mjs";
|
|
2
2
|
import { hexToBytes, isHexStrict, utf8ToHex } from "@ocap/util";
|
|
3
|
+
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
3
4
|
import { keccak_256 } from "@noble/hashes/sha3.js";
|
|
4
5
|
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
5
|
-
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
6
6
|
|
|
7
7
|
//#region src/signer/ethereum.ts
|
|
8
8
|
function toChecksumAddress(address) {
|
|
@@ -35,7 +35,7 @@ declare class Secp256k1Signer extends _default$1 {
|
|
|
35
35
|
/**
|
|
36
36
|
* Verify if a signature is valid
|
|
37
37
|
*/
|
|
38
|
-
verify(message: BytesType, signature: BytesType, pk: BytesType): boolean;
|
|
38
|
+
verify(message: BytesType, signature: BytesType, pk: BytesType, extra?: string): boolean;
|
|
39
39
|
}
|
|
40
40
|
declare const _default: Secp256k1Signer;
|
|
41
41
|
//#endregion
|
package/esm/signer/secp256k1.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { encode } from "../encode.mjs";
|
|
2
|
+
import { verifyEthereumEnvelope } from "../envelope.mjs";
|
|
2
3
|
import signer_default from "../protocols/signer.mjs";
|
|
3
4
|
import { toHex, toUint8Array } from "@ocap/util";
|
|
4
|
-
import randomBytes from "randombytes";
|
|
5
|
-
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
6
5
|
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
6
|
+
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
7
|
+
import randomBytes from "randombytes";
|
|
7
8
|
|
|
8
9
|
//#region src/signer/secp256k1.ts
|
|
9
10
|
/**
|
|
@@ -65,7 +66,12 @@ var Secp256k1Signer = class extends signer_default {
|
|
|
65
66
|
/**
|
|
66
67
|
* Verify if a signature is valid
|
|
67
68
|
*/
|
|
68
|
-
verify(message, signature, pk) {
|
|
69
|
+
verify(message, signature, pk, extra) {
|
|
70
|
+
if (extra) try {
|
|
71
|
+
return verifyEthereumEnvelope(message, signature, pk, extra);
|
|
72
|
+
} catch {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
69
75
|
const msg = toUint8Array(message);
|
|
70
76
|
const sigHex = toHex(toUint8Array(signature)).replace(/^0x/i, "");
|
|
71
77
|
let pkBytes = toUint8Array(pk);
|
package/esm/webauthn.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { __exportAll } from "./_virtual/rolldown_runtime.mjs";
|
|
2
|
-
import { sha256, sha384, sha512 } from "@noble/hashes/sha2.js";
|
|
3
2
|
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
3
|
+
import { sha256, sha384, sha512 } from "@noble/hashes/sha2.js";
|
|
4
4
|
import { p256, p384, p521 } from "@noble/curves/nist.js";
|
|
5
5
|
|
|
6
6
|
//#region src/webauthn.ts
|
package/lib/envelope.cjs
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_utils = require('./_vendor/@noble/hashes/utils.cjs');
|
|
3
|
+
const require_secp256k1 = require('./_vendor/@noble/curves/secp256k1.cjs');
|
|
4
|
+
const require_sha3 = require('./_vendor/@noble/hashes/sha3.cjs');
|
|
5
|
+
let _ocap_util = require("@ocap/util");
|
|
6
|
+
|
|
7
|
+
//#region src/envelope.ts
|
|
8
|
+
var envelope_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
|
|
9
|
+
assertEnvelopeMatchesTxContext: () => assertEnvelopeMatchesTxContext,
|
|
10
|
+
buildEd25519EnvelopePayload: () => buildEd25519EnvelopePayload,
|
|
11
|
+
buildSolanaOffchainEnvelopeBytes: () => buildSolanaOffchainEnvelopeBytes,
|
|
12
|
+
computeEip191EnvelopeDigest: () => computeEip191EnvelopeDigest,
|
|
13
|
+
computeEip712EnvelopeDigest: () => computeEip712EnvelopeDigest,
|
|
14
|
+
formatWalletEnvelopeText: () => formatWalletEnvelopeText,
|
|
15
|
+
isCanonicalWalletEnvelopeExtra: () => isCanonicalWalletEnvelopeExtra,
|
|
16
|
+
normalizeChallengeHex: () => normalizeChallengeHex,
|
|
17
|
+
parseWalletEnvelopeExtra: () => parseWalletEnvelopeExtra,
|
|
18
|
+
signEthereumEnvelope: () => signEthereumEnvelope,
|
|
19
|
+
verifyEthereumEnvelope: () => verifyEthereumEnvelope
|
|
20
|
+
});
|
|
21
|
+
const ETHEREUM_ENVELOPES = new Set(["eip191", "eip712"]);
|
|
22
|
+
const ED25519_ENVELOPES = new Set(["solana-message", "solana-offchain"]);
|
|
23
|
+
const ALL_ENVELOPES = new Set([
|
|
24
|
+
"eip191",
|
|
25
|
+
"eip712",
|
|
26
|
+
"solana-message",
|
|
27
|
+
"solana-offchain"
|
|
28
|
+
]);
|
|
29
|
+
const MAX_FIELD_LENGTH = 256;
|
|
30
|
+
const MAX_ENVELOPE_EXTRA_LENGTH = 2048;
|
|
31
|
+
const ALLOWED_ENVELOPE_KEYS = new Set([
|
|
32
|
+
"envelope",
|
|
33
|
+
"statement",
|
|
34
|
+
"chainId",
|
|
35
|
+
"action",
|
|
36
|
+
"from",
|
|
37
|
+
"nonce",
|
|
38
|
+
"domainName",
|
|
39
|
+
"domainVersion",
|
|
40
|
+
"applicationDomain",
|
|
41
|
+
"messageFormat",
|
|
42
|
+
"challenge"
|
|
43
|
+
]);
|
|
44
|
+
const SOLANA_OFFCHAIN_SIGNING_DOMAIN = new Uint8Array([
|
|
45
|
+
255,
|
|
46
|
+
115,
|
|
47
|
+
111,
|
|
48
|
+
108,
|
|
49
|
+
97,
|
|
50
|
+
110,
|
|
51
|
+
97,
|
|
52
|
+
32,
|
|
53
|
+
111,
|
|
54
|
+
102,
|
|
55
|
+
102,
|
|
56
|
+
99,
|
|
57
|
+
104,
|
|
58
|
+
97,
|
|
59
|
+
105,
|
|
60
|
+
110
|
|
61
|
+
]);
|
|
62
|
+
const DEFAULT_SOLANA_APP_DOMAIN = "ArcBlock Transaction Envelope v1";
|
|
63
|
+
function isSafeSingleLine(value, maxLen = MAX_FIELD_LENGTH) {
|
|
64
|
+
if (typeof value !== "string") return false;
|
|
65
|
+
if (value.length > maxLen) return false;
|
|
66
|
+
return !/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/.test(value);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Normalize a challenge input (hex string or bytes) into a canonical lowercase `0x`-prefixed hex string.
|
|
70
|
+
*/
|
|
71
|
+
function normalizeChallengeHex(challenge) {
|
|
72
|
+
if (typeof challenge === "string") {
|
|
73
|
+
const trimmed = challenge.trim();
|
|
74
|
+
if (/^(0x)?[0-9a-fA-F]+$/.test(trimmed) && trimmed.replace(/^0x/i, "").length % 2 === 0) return `0x${trimmed.replace(/^0x/i, "").toLowerCase()}`;
|
|
75
|
+
}
|
|
76
|
+
return `0x${require_utils.bytesToHex((0, _ocap_util.toUint8Array)(challenge)).toLowerCase()}`;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Validate whether an `extra` JSON string is a canonical cross-ecosystem wallet signature envelope.
|
|
80
|
+
* When `keyType` is provided (0 = ED25519, 1 = SECP256K1, 2 = ETHEREUM), also enforces curve compatibility.
|
|
81
|
+
*/
|
|
82
|
+
function isCanonicalWalletEnvelopeExtra(extra, keyType) {
|
|
83
|
+
if (typeof extra !== "string" || !extra || extra.length > MAX_ENVELOPE_EXTRA_LENGTH) return false;
|
|
84
|
+
try {
|
|
85
|
+
const parsed = JSON.parse(extra);
|
|
86
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
|
|
87
|
+
for (const key of Object.keys(parsed)) if (!ALLOWED_ENVELOPE_KEYS.has(key)) return false;
|
|
88
|
+
const envelope = parsed.envelope;
|
|
89
|
+
if (!ALL_ENVELOPES.has(envelope)) return false;
|
|
90
|
+
if (keyType !== void 0) {
|
|
91
|
+
if (keyType === 0 && !ED25519_ENVELOPES.has(envelope)) return false;
|
|
92
|
+
if ((keyType === 1 || keyType === 2) && !ETHEREUM_ENVELOPES.has(envelope)) return false;
|
|
93
|
+
if (keyType !== 0 && keyType !== 1 && keyType !== 2) return false;
|
|
94
|
+
}
|
|
95
|
+
for (const field of [
|
|
96
|
+
"statement",
|
|
97
|
+
"chainId",
|
|
98
|
+
"action",
|
|
99
|
+
"from",
|
|
100
|
+
"nonce",
|
|
101
|
+
"domainName",
|
|
102
|
+
"domainVersion",
|
|
103
|
+
"applicationDomain",
|
|
104
|
+
"challenge"
|
|
105
|
+
]) if (parsed[field] !== void 0 && !isSafeSingleLine(parsed[field])) return false;
|
|
106
|
+
if (parsed.messageFormat !== void 0 && parsed.messageFormat !== 0 && parsed.messageFormat !== 1 && parsed.messageFormat !== 2) return false;
|
|
107
|
+
return true;
|
|
108
|
+
} catch {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function parseWalletEnvelopeExtra(extra, expectedKeyType) {
|
|
113
|
+
if (!isCanonicalWalletEnvelopeExtra(extra, expectedKeyType)) throw new Error("Invalid or non-canonical wallet signature envelope extra");
|
|
114
|
+
return JSON.parse(extra);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Verifies that any human-readable metadata field present in a signed wallet envelope
|
|
118
|
+
* (`chainId`, `from`, `nonce`, `action`) matches the authoritative transaction context,
|
|
119
|
+
* preventing "What You See Is Not What You Sign" (WYSIWYS) blind-phishing spoofing.
|
|
120
|
+
*/
|
|
121
|
+
function assertEnvelopeMatchesTxContext(extra, expected) {
|
|
122
|
+
const parsed = typeof extra === "string" ? parseWalletEnvelopeExtra(extra) : extra;
|
|
123
|
+
if (parsed.chainId !== void 0 && expected.chainId !== void 0 && expected.chainId !== "") {
|
|
124
|
+
if (parsed.chainId !== expected.chainId) throw new Error(`Envelope chainId "${parsed.chainId}" does not match transaction chainId "${expected.chainId}"`);
|
|
125
|
+
}
|
|
126
|
+
if (parsed.from !== void 0) {
|
|
127
|
+
const allowedSigners = [expected.signer, expected.from].filter((v) => typeof v === "string" && v.length > 0);
|
|
128
|
+
if (allowedSigners.length > 0 && !allowedSigners.includes(parsed.from)) throw new Error(`Envelope signer "${parsed.from}" does not match transaction signer "${allowedSigners[0]}"`);
|
|
129
|
+
}
|
|
130
|
+
if (parsed.nonce !== void 0 && expected.nonce !== void 0 && String(expected.nonce) !== "") {
|
|
131
|
+
if (parsed.nonce !== String(expected.nonce)) throw new Error(`Envelope nonce "${parsed.nonce}" does not match transaction nonce "${String(expected.nonce)}"`);
|
|
132
|
+
}
|
|
133
|
+
if (parsed.action !== void 0 && expected.action !== void 0 && expected.action !== "") {
|
|
134
|
+
const shortAction = expected.action.replace(/^fg:t:/, "");
|
|
135
|
+
if (parsed.action !== expected.action && parsed.action !== shortAction) throw new Error(`Envelope action "${parsed.action}" does not match transaction action "${expected.action}"`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Deterministically reconstruct the human-readable envelope text from the authoritative transaction challenge
|
|
140
|
+
* and validated single-line metadata fields.
|
|
141
|
+
*/
|
|
142
|
+
function formatWalletEnvelopeText(challenge, meta = {}) {
|
|
143
|
+
const challengeHex = normalizeChallengeHex(challenge);
|
|
144
|
+
if (meta.challenge !== void 0 && normalizeChallengeHex(meta.challenge) !== challengeHex) throw new Error("challenge mismatch in wallet signature envelope");
|
|
145
|
+
for (const field of [
|
|
146
|
+
"statement",
|
|
147
|
+
"chainId",
|
|
148
|
+
"action",
|
|
149
|
+
"from",
|
|
150
|
+
"nonce"
|
|
151
|
+
]) if (meta[field] !== void 0 && !isSafeSingleLine(meta[field])) throw new Error(`Invalid character in wallet envelope field "${field}"`);
|
|
152
|
+
const lines = ["ArcBlock Transaction v1"];
|
|
153
|
+
if (meta.statement) lines.push(`Statement: ${meta.statement}`);
|
|
154
|
+
if (meta.chainId) lines.push(`Chain: ${meta.chainId}`);
|
|
155
|
+
if (meta.action) lines.push(`Action: ${meta.action}`);
|
|
156
|
+
if (meta.from) lines.push(`Signer: ${meta.from}`);
|
|
157
|
+
if (meta.nonce) lines.push(`Nonce: ${meta.nonce}`);
|
|
158
|
+
lines.push(`Challenge: ${challengeHex}`);
|
|
159
|
+
return lines.join("\n");
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Compute the EIP-191 (`personal_sign`) 32-byte keccak256 digest over the canonical envelope text.
|
|
163
|
+
*/
|
|
164
|
+
function computeEip191EnvelopeDigest(challenge, meta = {}) {
|
|
165
|
+
const text = formatWalletEnvelopeText(challenge, meta);
|
|
166
|
+
const messageBytes = Buffer.from(text, "utf8");
|
|
167
|
+
const preamble = Buffer.from(`\x19Ethereum Signed Message:\n${messageBytes.byteLength}`, "utf8");
|
|
168
|
+
return require_sha3.keccak_256(new Uint8Array(Buffer.concat([preamble, messageBytes])));
|
|
169
|
+
}
|
|
170
|
+
const EIP712_DOMAIN_TYPEHASH = require_sha3.keccak_256(new Uint8Array(Buffer.from("EIP712Domain(string name,string version)", "utf8")));
|
|
171
|
+
const EIP712_TX_TYPEHASH = require_sha3.keccak_256(new Uint8Array(Buffer.from("ArcBlockTransaction(string chainId,string action,string from,string nonce,string challenge)", "utf8")));
|
|
172
|
+
function keccakUtf8(value) {
|
|
173
|
+
return require_sha3.keccak_256(new Uint8Array(Buffer.from(value, "utf8")));
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Compute the EIP-712 (`eth_signTypedData_v4`) 32-byte digest for an ArcBlockTransaction envelope.
|
|
177
|
+
*/
|
|
178
|
+
function computeEip712EnvelopeDigest(challenge, meta = {}) {
|
|
179
|
+
const challengeHex = normalizeChallengeHex(challenge);
|
|
180
|
+
if (meta.challenge !== void 0 && normalizeChallengeHex(meta.challenge) !== challengeHex) throw new Error("challenge mismatch in wallet signature envelope");
|
|
181
|
+
for (const field of [
|
|
182
|
+
"chainId",
|
|
183
|
+
"action",
|
|
184
|
+
"from",
|
|
185
|
+
"nonce",
|
|
186
|
+
"domainName",
|
|
187
|
+
"domainVersion"
|
|
188
|
+
]) if (meta[field] !== void 0 && !isSafeSingleLine(meta[field])) throw new Error(`Invalid character in wallet envelope field "${field}"`);
|
|
189
|
+
const domainName = meta.domainName || "ArcBlock";
|
|
190
|
+
const domainVersion = meta.domainVersion || "1";
|
|
191
|
+
const chainId = meta.chainId || "arcblock";
|
|
192
|
+
const action = meta.action || "transaction";
|
|
193
|
+
const from = meta.from || "";
|
|
194
|
+
const nonce = meta.nonce || "";
|
|
195
|
+
const domainSeparator = require_sha3.keccak_256(new Uint8Array(Buffer.concat([
|
|
196
|
+
EIP712_DOMAIN_TYPEHASH,
|
|
197
|
+
keccakUtf8(domainName),
|
|
198
|
+
keccakUtf8(domainVersion)
|
|
199
|
+
])));
|
|
200
|
+
const structHash = require_sha3.keccak_256(new Uint8Array(Buffer.concat([
|
|
201
|
+
EIP712_TX_TYPEHASH,
|
|
202
|
+
keccakUtf8(chainId),
|
|
203
|
+
keccakUtf8(action),
|
|
204
|
+
keccakUtf8(from),
|
|
205
|
+
keccakUtf8(nonce),
|
|
206
|
+
keccakUtf8(challengeHex)
|
|
207
|
+
])));
|
|
208
|
+
return require_sha3.keccak_256(new Uint8Array(Buffer.concat([
|
|
209
|
+
Buffer.from([25, 1]),
|
|
210
|
+
domainSeparator,
|
|
211
|
+
structHash
|
|
212
|
+
])));
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Build the canonical Solana Off-Chain Message v0 binary payload (`\xffsolana offchain` header + UTF-8 body).
|
|
216
|
+
* Compatible with Phantom, Solflare, and Ledger Solana off-chain message signing.
|
|
217
|
+
*/
|
|
218
|
+
function buildSolanaOffchainEnvelopeBytes(challenge, pk, meta = {}) {
|
|
219
|
+
const pkBytes = (0, _ocap_util.toUint8Array)(pk);
|
|
220
|
+
if (pkBytes.byteLength !== 32) throw new Error("Solana offchain envelope requires a 32-byte Ed25519 public key");
|
|
221
|
+
const text = formatWalletEnvelopeText(challenge, meta);
|
|
222
|
+
const messageBytes = Buffer.from(text, "utf8");
|
|
223
|
+
if (messageBytes.byteLength > 65535) throw new Error("Solana offchain message exceeds maximum uint16 length");
|
|
224
|
+
const appDomainStr = meta.applicationDomain || DEFAULT_SOLANA_APP_DOMAIN;
|
|
225
|
+
if (!isSafeSingleLine(appDomainStr, 32)) throw new Error("Solana offchain applicationDomain must be a single-line string of at most 32 bytes");
|
|
226
|
+
const appDomainBytes = Buffer.alloc(32, 0);
|
|
227
|
+
const encodedDomain = Buffer.from(appDomainStr, "utf8");
|
|
228
|
+
if (encodedDomain.byteLength > 32) throw new Error("Solana offchain applicationDomain exceeds 32 UTF-8 bytes");
|
|
229
|
+
encodedDomain.copy(appDomainBytes);
|
|
230
|
+
const messageFormat = meta.messageFormat ?? 1;
|
|
231
|
+
const header = Buffer.alloc(85);
|
|
232
|
+
let offset = 0;
|
|
233
|
+
Buffer.from(SOLANA_OFFCHAIN_SIGNING_DOMAIN).copy(header, offset);
|
|
234
|
+
offset += 16;
|
|
235
|
+
header.writeUInt8(0, offset);
|
|
236
|
+
offset += 1;
|
|
237
|
+
appDomainBytes.copy(header, offset);
|
|
238
|
+
offset += 32;
|
|
239
|
+
header.writeUInt8(messageFormat, offset);
|
|
240
|
+
offset += 1;
|
|
241
|
+
header.writeUInt8(1, offset);
|
|
242
|
+
offset += 1;
|
|
243
|
+
Buffer.from(pkBytes).copy(header, offset);
|
|
244
|
+
offset += 32;
|
|
245
|
+
header.writeUInt16LE(messageBytes.byteLength, offset);
|
|
246
|
+
return new Uint8Array(Buffer.concat([header, messageBytes]));
|
|
247
|
+
}
|
|
248
|
+
function normalizeSecp256k1PublicKey(pk) {
|
|
249
|
+
const pkBytes = (0, _ocap_util.toUint8Array)(pk);
|
|
250
|
+
if (pkBytes.byteLength === 64) {
|
|
251
|
+
const prefixed = new Uint8Array(65);
|
|
252
|
+
prefixed[0] = 4;
|
|
253
|
+
prefixed.set(pkBytes, 1);
|
|
254
|
+
return prefixed;
|
|
255
|
+
}
|
|
256
|
+
return pkBytes;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Sign an Ethereum/Secp256k1 wallet envelope (`eip191` or `eip712`) and return a 65-byte recoverable `0x{r}{s}{v}` hex signature.
|
|
260
|
+
*/
|
|
261
|
+
function signEthereumEnvelope(challenge, sk, extra) {
|
|
262
|
+
const parsed = typeof extra === "string" ? parseWalletEnvelopeExtra(extra, 2) : extra;
|
|
263
|
+
const digest = parsed.envelope === "eip712" ? computeEip712EnvelopeDigest(challenge, parsed) : computeEip191EnvelopeDigest(challenge, parsed);
|
|
264
|
+
const skBytes = (0, _ocap_util.toUint8Array)(sk);
|
|
265
|
+
const recoveredBytes = require_secp256k1.secp256k1.sign(digest, skBytes, {
|
|
266
|
+
prehash: false,
|
|
267
|
+
format: "recovered"
|
|
268
|
+
});
|
|
269
|
+
const sig = require_secp256k1.secp256k1.Signature.fromBytes(recoveredBytes, "recovered");
|
|
270
|
+
const v = (27 + sig.recovery).toString(16).padStart(2, "0");
|
|
271
|
+
return `0x${sig.toHex("compact")}${v}`;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Verify an Ethereum/Secp256k1 wallet envelope (`eip191` or `eip712`) against `pk`.
|
|
275
|
+
* Requires a canonical 65-byte Ethereum recoverable signature (`r[32] || s[32] || v[1]`) with `v` in `{27, 28}` and low-S.
|
|
276
|
+
*/
|
|
277
|
+
function verifyEthereumEnvelope(challenge, signature, pk, extra) {
|
|
278
|
+
const parsed = parseWalletEnvelopeExtra(extra, 2);
|
|
279
|
+
const digest = parsed.envelope === "eip712" ? computeEip712EnvelopeDigest(challenge, parsed) : computeEip191EnvelopeDigest(challenge, parsed);
|
|
280
|
+
const expectedPk = normalizeSecp256k1PublicKey(pk);
|
|
281
|
+
const sigHex = (0, _ocap_util.toHex)((0, _ocap_util.toUint8Array)(signature)).replace(/^0x/i, "");
|
|
282
|
+
if (sigHex.length !== 130) return false;
|
|
283
|
+
const v = Number.parseInt(sigHex.slice(128, 130), 16);
|
|
284
|
+
if (v !== 27 && v !== 28) return false;
|
|
285
|
+
const recovery = v - 27;
|
|
286
|
+
try {
|
|
287
|
+
const sig = require_secp256k1.secp256k1.Signature.fromHex(sigHex.slice(0, 128), "compact").addRecoveryBit(recovery);
|
|
288
|
+
if (sig.hasHighS()) return false;
|
|
289
|
+
const recoveredPk = sig.recoverPublicKey(digest).toBytes(expectedPk.byteLength === 33);
|
|
290
|
+
return recoveredPk.byteLength === expectedPk.byteLength && recoveredPk.every((b, idx) => b === expectedPk[idx]);
|
|
291
|
+
} catch {
|
|
292
|
+
return false;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Construct the exact byte payload to be signed/verified for a Solana Ed25519 wallet envelope (`solana-message` or `solana-offchain`).
|
|
297
|
+
*/
|
|
298
|
+
function buildEd25519EnvelopePayload(challenge, pk, extra) {
|
|
299
|
+
const parsed = parseWalletEnvelopeExtra(extra, 0);
|
|
300
|
+
if (parsed.envelope === "solana-offchain") return buildSolanaOffchainEnvelopeBytes(challenge, pk, parsed);
|
|
301
|
+
const text = formatWalletEnvelopeText(challenge, parsed);
|
|
302
|
+
return new Uint8Array(Buffer.from(text, "utf8"));
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
//#endregion
|
|
306
|
+
exports.assertEnvelopeMatchesTxContext = assertEnvelopeMatchesTxContext;
|
|
307
|
+
exports.buildEd25519EnvelopePayload = buildEd25519EnvelopePayload;
|
|
308
|
+
exports.buildSolanaOffchainEnvelopeBytes = buildSolanaOffchainEnvelopeBytes;
|
|
309
|
+
exports.computeEip191EnvelopeDigest = computeEip191EnvelopeDigest;
|
|
310
|
+
exports.computeEip712EnvelopeDigest = computeEip712EnvelopeDigest;
|
|
311
|
+
Object.defineProperty(exports, 'envelope_exports', {
|
|
312
|
+
enumerable: true,
|
|
313
|
+
get: function () {
|
|
314
|
+
return envelope_exports;
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
exports.formatWalletEnvelopeText = formatWalletEnvelopeText;
|
|
318
|
+
exports.isCanonicalWalletEnvelopeExtra = isCanonicalWalletEnvelopeExtra;
|
|
319
|
+
exports.normalizeChallengeHex = normalizeChallengeHex;
|
|
320
|
+
exports.parseWalletEnvelopeExtra = parseWalletEnvelopeExtra;
|
|
321
|
+
exports.signEthereumEnvelope = signEthereumEnvelope;
|
|
322
|
+
exports.verifyEthereumEnvelope = verifyEthereumEnvelope;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { BytesType } from "@ocap/util";
|
|
2
|
+
|
|
3
|
+
//#region src/envelope.d.ts
|
|
4
|
+
declare namespace envelope_d_exports {
|
|
5
|
+
export { ExpectedEnvelopeTxContext, WalletEnvelopeExtra, WalletEnvelopeType, assertEnvelopeMatchesTxContext, buildEd25519EnvelopePayload, buildSolanaOffchainEnvelopeBytes, computeEip191EnvelopeDigest, computeEip712EnvelopeDigest, formatWalletEnvelopeText, isCanonicalWalletEnvelopeExtra, normalizeChallengeHex, parseWalletEnvelopeExtra, signEthereumEnvelope, verifyEthereumEnvelope };
|
|
6
|
+
}
|
|
7
|
+
type WalletEnvelopeType = 'eip191' | 'eip712' | 'solana-message' | 'solana-offchain';
|
|
8
|
+
interface WalletEnvelopeExtra {
|
|
9
|
+
envelope: WalletEnvelopeType;
|
|
10
|
+
statement?: string;
|
|
11
|
+
chainId?: string;
|
|
12
|
+
action?: string;
|
|
13
|
+
from?: string;
|
|
14
|
+
nonce?: string;
|
|
15
|
+
domainName?: string;
|
|
16
|
+
domainVersion?: string;
|
|
17
|
+
applicationDomain?: string;
|
|
18
|
+
messageFormat?: number;
|
|
19
|
+
challenge?: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Normalize a challenge input (hex string or bytes) into a canonical lowercase `0x`-prefixed hex string.
|
|
23
|
+
*/
|
|
24
|
+
declare function normalizeChallengeHex(challenge: BytesType): string;
|
|
25
|
+
/**
|
|
26
|
+
* Validate whether an `extra` JSON string is a canonical cross-ecosystem wallet signature envelope.
|
|
27
|
+
* When `keyType` is provided (0 = ED25519, 1 = SECP256K1, 2 = ETHEREUM), also enforces curve compatibility.
|
|
28
|
+
*/
|
|
29
|
+
declare function isCanonicalWalletEnvelopeExtra(extra: unknown, keyType?: number): boolean;
|
|
30
|
+
declare function parseWalletEnvelopeExtra(extra: string, expectedKeyType?: number): WalletEnvelopeExtra;
|
|
31
|
+
interface ExpectedEnvelopeTxContext {
|
|
32
|
+
chainId?: string;
|
|
33
|
+
signer?: string;
|
|
34
|
+
from?: string;
|
|
35
|
+
nonce?: string | number | bigint;
|
|
36
|
+
action?: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Verifies that any human-readable metadata field present in a signed wallet envelope
|
|
40
|
+
* (`chainId`, `from`, `nonce`, `action`) matches the authoritative transaction context,
|
|
41
|
+
* preventing "What You See Is Not What You Sign" (WYSIWYS) blind-phishing spoofing.
|
|
42
|
+
*/
|
|
43
|
+
declare function assertEnvelopeMatchesTxContext(extra: string | WalletEnvelopeExtra, expected: ExpectedEnvelopeTxContext): void;
|
|
44
|
+
/**
|
|
45
|
+
* Deterministically reconstruct the human-readable envelope text from the authoritative transaction challenge
|
|
46
|
+
* and validated single-line metadata fields.
|
|
47
|
+
*/
|
|
48
|
+
declare function formatWalletEnvelopeText(challenge: BytesType, meta?: Partial<WalletEnvelopeExtra>): string;
|
|
49
|
+
/**
|
|
50
|
+
* Compute the EIP-191 (`personal_sign`) 32-byte keccak256 digest over the canonical envelope text.
|
|
51
|
+
*/
|
|
52
|
+
declare function computeEip191EnvelopeDigest(challenge: BytesType, meta?: Partial<WalletEnvelopeExtra>): Uint8Array;
|
|
53
|
+
/**
|
|
54
|
+
* Compute the EIP-712 (`eth_signTypedData_v4`) 32-byte digest for an ArcBlockTransaction envelope.
|
|
55
|
+
*/
|
|
56
|
+
declare function computeEip712EnvelopeDigest(challenge: BytesType, meta?: Partial<WalletEnvelopeExtra>): Uint8Array;
|
|
57
|
+
/**
|
|
58
|
+
* Build the canonical Solana Off-Chain Message v0 binary payload (`\xffsolana offchain` header + UTF-8 body).
|
|
59
|
+
* Compatible with Phantom, Solflare, and Ledger Solana off-chain message signing.
|
|
60
|
+
*/
|
|
61
|
+
declare function buildSolanaOffchainEnvelopeBytes(challenge: BytesType, pk: BytesType, meta?: Partial<WalletEnvelopeExtra>): Uint8Array;
|
|
62
|
+
/**
|
|
63
|
+
* Sign an Ethereum/Secp256k1 wallet envelope (`eip191` or `eip712`) and return a 65-byte recoverable `0x{r}{s}{v}` hex signature.
|
|
64
|
+
*/
|
|
65
|
+
declare function signEthereumEnvelope(challenge: BytesType, sk: BytesType, extra: string | WalletEnvelopeExtra): string;
|
|
66
|
+
/**
|
|
67
|
+
* Verify an Ethereum/Secp256k1 wallet envelope (`eip191` or `eip712`) against `pk`.
|
|
68
|
+
* Requires a canonical 65-byte Ethereum recoverable signature (`r[32] || s[32] || v[1]`) with `v` in `{27, 28}` and low-S.
|
|
69
|
+
*/
|
|
70
|
+
declare function verifyEthereumEnvelope(challenge: BytesType, signature: BytesType, pk: BytesType, extra: string): boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Construct the exact byte payload to be signed/verified for a Solana Ed25519 wallet envelope (`solana-message` or `solana-offchain`).
|
|
73
|
+
*/
|
|
74
|
+
declare function buildEd25519EnvelopePayload(challenge: BytesType, pk: BytesType, extra: string): Uint8Array;
|
|
75
|
+
//#endregion
|
|
76
|
+
export { ExpectedEnvelopeTxContext, WalletEnvelopeExtra, WalletEnvelopeType, assertEnvelopeMatchesTxContext, buildEd25519EnvelopePayload, buildSolanaOffchainEnvelopeBytes, computeEip191EnvelopeDigest, computeEip712EnvelopeDigest, envelope_d_exports, formatWalletEnvelopeText, isCanonicalWalletEnvelopeExtra, normalizeChallengeHex, parseWalletEnvelopeExtra, signEthereumEnvelope, verifyEthereumEnvelope };
|
package/lib/hasher/sha2.cjs
CHANGED
|
@@ -3,6 +3,7 @@ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
|
3
3
|
const require_encode = require('../encode.cjs');
|
|
4
4
|
const require_utils = require('../_vendor/@noble/hashes/utils.cjs');
|
|
5
5
|
const require_sha2 = require('../_vendor/@noble/hashes/sha2.cjs');
|
|
6
|
+
const require_hmac = require('../_vendor/@noble/hashes/hmac.cjs');
|
|
6
7
|
let _ocap_util = require("@ocap/util");
|
|
7
8
|
|
|
8
9
|
//#region src/hasher/sha2.ts
|
|
@@ -12,7 +13,28 @@ const hashFns = {
|
|
|
12
13
|
sha384: require_sha2.sha384,
|
|
13
14
|
sha512: require_sha2.sha512
|
|
14
15
|
};
|
|
15
|
-
const
|
|
16
|
+
const nodeCrypto = typeof process !== "undefined" ? process.getBuiltinModule?.("node:crypto") : void 0;
|
|
17
|
+
const createHash = nodeCrypto?.createHash;
|
|
18
|
+
const createHmac = nodeCrypto?.createHmac;
|
|
19
|
+
const toBytes = (data) => {
|
|
20
|
+
if (data instanceof Uint8Array) return data;
|
|
21
|
+
if (typeof data === "string") try {
|
|
22
|
+
return (0, _ocap_util.toUint8Array)(data);
|
|
23
|
+
} catch (_err) {
|
|
24
|
+
return new TextEncoder().encode(data);
|
|
25
|
+
}
|
|
26
|
+
return (0, _ocap_util.toUint8Array)(data);
|
|
27
|
+
};
|
|
28
|
+
function hmacSha256(key, data, encoding = "hex") {
|
|
29
|
+
const keyBytes = toBytes(key);
|
|
30
|
+
const dataBytes = toBytes(data);
|
|
31
|
+
const res = createHmac ? createHmac("sha256", keyBytes).update(dataBytes).digest() : require_hmac.hmac(require_sha2.sha256, keyBytes, dataBytes);
|
|
32
|
+
const isBuf = typeof Buffer !== "undefined" && Buffer.isBuffer(res);
|
|
33
|
+
if (encoding === "hex" || encoding === "base16") return isBuf ? `0x${res.toString("hex")}` : `0x${require_utils.bytesToHex(res)}`;
|
|
34
|
+
if (encoding === "buffer" && typeof Buffer !== "undefined") return isBuf ? res : Buffer.from(res.buffer, res.byteOffset, res.byteLength);
|
|
35
|
+
if (encoding === "Uint8Array") return isBuf ? new Uint8Array(res) : res;
|
|
36
|
+
return require_encode.encode(res, encoding);
|
|
37
|
+
}
|
|
16
38
|
/**
|
|
17
39
|
* Sha2 support with different hash length
|
|
18
40
|
* Uses native node:crypto when available with @noble/hashes fallback
|
|
@@ -63,4 +85,5 @@ var sha2_default = new Sha2Hasher();
|
|
|
63
85
|
|
|
64
86
|
//#endregion
|
|
65
87
|
exports.Sha2Hasher = Sha2Hasher;
|
|
66
|
-
exports.default = sha2_default;
|
|
88
|
+
exports.default = sha2_default;
|
|
89
|
+
exports.hmacSha256 = hmacSha256;
|
package/lib/hasher/sha2.d.cts
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import { BytesType, EncodingType } from "@ocap/util";
|
|
2
2
|
|
|
3
3
|
//#region src/hasher/sha2.d.ts
|
|
4
|
-
|
|
4
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: 'hex'): string;
|
|
5
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: 'base16'): string;
|
|
6
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: 'base58'): string;
|
|
7
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: 'base64'): string;
|
|
8
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: 'buffer'): Buffer;
|
|
9
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: 'Uint8Array'): Uint8Array;
|
|
10
|
+
declare function hmacSha256(key: BytesType, data: BytesType, encoding?: EncodingType): BytesType;
|
|
5
11
|
/**
|
|
6
12
|
* Sha2 support with different hash length
|
|
7
13
|
* Uses native node:crypto when available with @noble/hashes fallback
|
|
@@ -14,4 +20,4 @@ declare class Sha2Hasher {
|
|
|
14
20
|
}
|
|
15
21
|
declare const _default: Sha2Hasher;
|
|
16
22
|
//#endregion
|
|
17
|
-
export { Sha2Hasher, _default as default };
|
|
23
|
+
export { Sha2Hasher, _default as default, hmacSha256 };
|
package/lib/index.cjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_encode = require('./encode.cjs');
|
|
3
|
+
const require_envelope = require('./envelope.cjs');
|
|
3
4
|
const require_hasher_keccak = require('./hasher/keccak.cjs');
|
|
4
5
|
const require_hasher_sha2 = require('./hasher/sha2.cjs');
|
|
5
6
|
const require_hasher_sha3 = require('./hasher/sha3.cjs');
|
|
@@ -186,11 +187,29 @@ const toTxHash = (buf) => Hasher.SHA2.hash256(buf, 1, "hex").replace(/^0x/, "").
|
|
|
186
187
|
//#endregion
|
|
187
188
|
exports.Hasher = Hasher;
|
|
188
189
|
exports.Signer = Signer;
|
|
190
|
+
exports.assertEnvelopeMatchesTxContext = require_envelope.assertEnvelopeMatchesTxContext;
|
|
191
|
+
exports.buildEd25519EnvelopePayload = require_envelope.buildEd25519EnvelopePayload;
|
|
192
|
+
exports.buildSolanaOffchainEnvelopeBytes = require_envelope.buildSolanaOffchainEnvelopeBytes;
|
|
193
|
+
exports.computeEip191EnvelopeDigest = require_envelope.computeEip191EnvelopeDigest;
|
|
194
|
+
exports.computeEip712EnvelopeDigest = require_envelope.computeEip712EnvelopeDigest;
|
|
195
|
+
Object.defineProperty(exports, 'envelope', {
|
|
196
|
+
enumerable: true,
|
|
197
|
+
get: function () {
|
|
198
|
+
return require_envelope.envelope_exports;
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
exports.formatWalletEnvelopeText = require_envelope.formatWalletEnvelopeText;
|
|
189
202
|
exports.getHasher = getHasher;
|
|
190
203
|
exports.getRandomBytes = getRandomBytes;
|
|
191
204
|
exports.getSigner = getSigner;
|
|
205
|
+
exports.hmacSha256 = require_hasher_sha2.hmacSha256;
|
|
206
|
+
exports.isCanonicalWalletEnvelopeExtra = require_envelope.isCanonicalWalletEnvelopeExtra;
|
|
207
|
+
exports.normalizeChallengeHex = require_envelope.normalizeChallengeHex;
|
|
208
|
+
exports.parseWalletEnvelopeExtra = require_envelope.parseWalletEnvelopeExtra;
|
|
209
|
+
exports.signEthereumEnvelope = require_envelope.signEthereumEnvelope;
|
|
192
210
|
exports.toTxHash = toTxHash;
|
|
193
211
|
exports.types = types;
|
|
212
|
+
exports.verifyEthereumEnvelope = require_envelope.verifyEthereumEnvelope;
|
|
194
213
|
Object.defineProperty(exports, 'webauthn', {
|
|
195
214
|
enumerable: true,
|
|
196
215
|
get: function () {
|
package/lib/index.d.cts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { ExpectedEnvelopeTxContext, WalletEnvelopeExtra, WalletEnvelopeType, assertEnvelopeMatchesTxContext, buildEd25519EnvelopePayload, buildSolanaOffchainEnvelopeBytes, computeEip191EnvelopeDigest, computeEip712EnvelopeDigest, envelope_d_exports, formatWalletEnvelopeText, isCanonicalWalletEnvelopeExtra, normalizeChallengeHex, parseWalletEnvelopeExtra, signEthereumEnvelope, verifyEthereumEnvelope } from "./envelope.cjs";
|
|
1
2
|
import { KeccakHasher } from "./hasher/keccak.cjs";
|
|
2
|
-
import { Sha2Hasher } from "./hasher/sha2.cjs";
|
|
3
|
+
import { Sha2Hasher, hmacSha256 } from "./hasher/sha2.cjs";
|
|
3
4
|
import { Sha3Hasher } from "./hasher/sha3.cjs";
|
|
4
5
|
import { Ed25519Signer } from "./signer/ed25519.cjs";
|
|
5
6
|
import { Secp256k1Signer } from "./signer/secp256k1.cjs";
|
|
@@ -239,4 +240,4 @@ declare function getRandomBytes(length: number, encoding?: 'Uint8Array'): Uint8A
|
|
|
239
240
|
declare function getRandomBytes(length: number, encoding?: EncodingType): BytesType;
|
|
240
241
|
declare const toTxHash: (buf: Buffer | Uint8Array) => string;
|
|
241
242
|
//#endregion
|
|
242
|
-
export { AddressType, HashFnType, HashType, Hasher, KeyType, RoleType, Signer, SignerType, getHasher, getRandomBytes, getSigner, toTxHash, types, webauthn_d_exports as webauthn };
|
|
243
|
+
export { AddressType, ExpectedEnvelopeTxContext, HashFnType, HashType, Hasher, KeyType, RoleType, Signer, SignerType, WalletEnvelopeExtra, WalletEnvelopeType, assertEnvelopeMatchesTxContext, buildEd25519EnvelopePayload, buildSolanaOffchainEnvelopeBytes, computeEip191EnvelopeDigest, computeEip712EnvelopeDigest, envelope_d_exports as envelope, formatWalletEnvelopeText, getHasher, getRandomBytes, getSigner, hmacSha256, isCanonicalWalletEnvelopeExtra, normalizeChallengeHex, parseWalletEnvelopeExtra, signEthereumEnvelope, toTxHash, types, verifyEthereumEnvelope, webauthn_d_exports as webauthn };
|
package/lib/signer/ed25519.cjs
CHANGED
|
@@ -3,6 +3,7 @@ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
|
3
3
|
const require_encode = require('../encode.cjs');
|
|
4
4
|
const require_utils = require('../_vendor/@noble/hashes/utils.cjs');
|
|
5
5
|
const require_sha2 = require('../_vendor/@noble/hashes/sha2.cjs');
|
|
6
|
+
const require_envelope = require('../envelope.cjs');
|
|
6
7
|
const require_index = require('../_vendor/@noble/ed25519/index.cjs');
|
|
7
8
|
const require_protocols_signer = require('../protocols/signer.cjs');
|
|
8
9
|
let _ocap_util = require("@ocap/util");
|
|
@@ -207,15 +208,22 @@ var Ed25519Signer = class extends require_protocols_signer.default {
|
|
|
207
208
|
* @param {string|buffer} pk
|
|
208
209
|
* @returns {bool}
|
|
209
210
|
*/
|
|
210
|
-
verify(message, signature, pk) {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
211
|
+
verify(message, signature, pk, extra) {
|
|
212
|
+
let pkBytes;
|
|
213
|
+
let messageBytes;
|
|
214
|
+
let signatureBytes;
|
|
215
|
+
try {
|
|
216
|
+
pkBytes = toBytes(pk);
|
|
217
|
+
messageBytes = extra ? require_envelope.buildEd25519EnvelopePayload(message, pkBytes, extra) : toBytes(message);
|
|
218
|
+
signatureBytes = toBytes(signature);
|
|
219
|
+
} catch {
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
214
222
|
if (pkBytes.byteLength !== 32 || signatureBytes.byteLength !== 64) return false;
|
|
215
223
|
if (nodeCrypto?.verify) {
|
|
216
224
|
const pubKeyObject = getNativePublicKeyObject(pkBytes);
|
|
217
225
|
if (pubKeyObject) try {
|
|
218
|
-
|
|
226
|
+
return nodeCrypto.verify(null, messageBytes, pubKeyObject, signatureBytes);
|
|
219
227
|
} catch {}
|
|
220
228
|
}
|
|
221
229
|
try {
|
package/lib/signer/ed25519.d.cts
CHANGED
|
@@ -58,7 +58,7 @@ declare class Ed25519Signer extends _default$1 {
|
|
|
58
58
|
* @param {string|buffer} pk
|
|
59
59
|
* @returns {bool}
|
|
60
60
|
*/
|
|
61
|
-
verify(message: BytesType, signature: BytesType, pk: BytesType): boolean;
|
|
61
|
+
verify(message: BytesType, signature: BytesType, pk: BytesType, extra?: string): boolean;
|
|
62
62
|
}
|
|
63
63
|
declare const _default: Ed25519Signer;
|
|
64
64
|
//#endregion
|
package/lib/signer/ethereum.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
2
2
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
3
3
|
const require_utils = require('../_vendor/@noble/hashes/utils.cjs');
|
|
4
|
-
const require_sha3 = require('../_vendor/@noble/hashes/sha3.cjs');
|
|
5
4
|
const require_secp256k1 = require('../_vendor/@noble/curves/secp256k1.cjs');
|
|
5
|
+
const require_sha3 = require('../_vendor/@noble/hashes/sha3.cjs');
|
|
6
6
|
const require_signer_secp256k1 = require('./secp256k1.cjs');
|
|
7
7
|
let _ocap_util = require("@ocap/util");
|
|
8
8
|
|
package/lib/signer/secp256k1.cjs
CHANGED
|
@@ -2,8 +2,9 @@ Object.defineProperty(exports, '__esModule', { value: true });
|
|
|
2
2
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
3
3
|
const require_encode = require('../encode.cjs');
|
|
4
4
|
const require_utils = require('../_vendor/@noble/hashes/utils.cjs');
|
|
5
|
-
const require_protocols_signer = require('../protocols/signer.cjs');
|
|
6
5
|
const require_secp256k1 = require('../_vendor/@noble/curves/secp256k1.cjs');
|
|
6
|
+
const require_envelope = require('../envelope.cjs');
|
|
7
|
+
const require_protocols_signer = require('../protocols/signer.cjs');
|
|
7
8
|
let _ocap_util = require("@ocap/util");
|
|
8
9
|
let randombytes = require("randombytes");
|
|
9
10
|
randombytes = require_rolldown_runtime.__toESM(randombytes);
|
|
@@ -68,7 +69,12 @@ var Secp256k1Signer = class extends require_protocols_signer.default {
|
|
|
68
69
|
/**
|
|
69
70
|
* Verify if a signature is valid
|
|
70
71
|
*/
|
|
71
|
-
verify(message, signature, pk) {
|
|
72
|
+
verify(message, signature, pk, extra) {
|
|
73
|
+
if (extra) try {
|
|
74
|
+
return require_envelope.verifyEthereumEnvelope(message, signature, pk, extra);
|
|
75
|
+
} catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
72
78
|
const msg = (0, _ocap_util.toUint8Array)(message);
|
|
73
79
|
const sigHex = (0, _ocap_util.toHex)((0, _ocap_util.toUint8Array)(signature)).replace(/^0x/i, "");
|
|
74
80
|
let pkBytes = (0, _ocap_util.toUint8Array)(pk);
|
|
@@ -35,7 +35,7 @@ declare class Secp256k1Signer extends _default$1 {
|
|
|
35
35
|
/**
|
|
36
36
|
* Verify if a signature is valid
|
|
37
37
|
*/
|
|
38
|
-
verify(message: BytesType, signature: BytesType, pk: BytesType): boolean;
|
|
38
|
+
verify(message: BytesType, signature: BytesType, pk: BytesType, extra?: string): boolean;
|
|
39
39
|
}
|
|
40
40
|
declare const _default: Secp256k1Signer;
|
|
41
41
|
//#endregion
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ocap/mcrypto",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.31.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Crypto lib that provides signer,crypter,hasher interface",
|
|
6
6
|
"keywords": [
|
|
@@ -75,7 +75,7 @@
|
|
|
75
75
|
"@noble/curves": "2.2.0",
|
|
76
76
|
"@noble/ed25519": "3.0.1",
|
|
77
77
|
"@noble/hashes": "2.2.0",
|
|
78
|
-
"@ocap/util": "1.
|
|
78
|
+
"@ocap/util": "1.31.1",
|
|
79
79
|
"interface": "^1.2.1",
|
|
80
80
|
"randombytes": "^2.1.0"
|
|
81
81
|
},
|