-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathembedded-wallet-sign.js
More file actions
executable file
·188 lines (175 loc) · 7.15 KB
/
Copy pathembedded-wallet-sign.js
File metadata and controls
executable file
·188 lines (175 loc) · 7.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env node
/**
* Embedded-wallet signing helpers for the Grid offramp flow.
*
* Four primitives that aren't expressible in plain curl. Everything else
* (create customer, on-ramp quote, register OTP, offramp quote, execute)
* is a regular HTTP call — see scripts/README.md for the full walkthrough.
*
* Subcommands:
*
* gen-keypair [--compressed]
* Generate an ephemeral P-256 keypair. Prints JSON with `pubHex` and
* `privHex`. `pubHex` is uncompressed (`04...`) by default, or
* compressed (`02...`/`03...`) with `--compressed`.
*
* Use `--compressed` for:
* - EMAIL_OTP. The enclave rejects an uncompressed key inside the OTP
* bundle, and verify returns `400 INVALID_INPUT`.
* - The OAuth/PASSKEY client-held-key flow, where you pass `pubHex` as
* `clientPublicKey`.
* In both, the private key becomes the session signing key directly.
*
* The uncompressed default is only for the legacy PASSKEY/OAUTH flow,
* where you decrypt the session key with `decrypt-bundle`.
*
* encrypt-otp <otpEncryptionTargetBundle> <pubHex> <otpCode>
* HPKE-encrypt `{otp_code, public_key}` under the target bundle
* returned by `POST /auth/credentials/{id}/challenge`. Prints the
* `encryptedOtpBundle` JSON to pass on
* `POST /auth/credentials/{id}/verify`.
*
* decrypt-bundle <bundle> <privHex>
* HPKE-open the `encryptedSessionSigningKey` returned by the legacy
* (uncompressed-key) PASSKEY/OAUTH `POST /auth/credentials/{id}/verify`
* flow. Not needed for EMAIL_OTP or the compressed-key client-held
* flow — in both, the generated private key IS the session signing
* key. Prints the session API private key as hex.
*
* stamp <sessionPrivHex> <payload>
* Build a Grid wallet signature over a `payloadToSign`. Prints the value
* to drop into the `Grid-Wallet-Signature` header on
* `POST /quotes/{id}/execute` or EMAIL_OTP verify signed retry.
*
* For long arguments, pass `-` to read from stdin:
*
* cat bundle.txt | embedded-wallet-sign decrypt-bundle - $PRIV_HEX
*/
"use strict";
const { generateKeyPairSync, createPublicKey } = require("node:crypto");
const { decryptCredentialBundle, hpkeEncrypt, formatHpkeBuf } = require("@turnkey/crypto");
const { ApiKeyStamper } = require("@turnkey/api-key-stamper");
function readArg(value) {
if (value !== "-") return value;
return require("node:fs").readFileSync(0, "utf8").trim();
}
function jwkB64ToHex(b64url) {
return Buffer.from(b64url, "base64url").toString("hex");
}
function genKeypair({ compressed = false } = {}) {
const { publicKey, privateKey } = generateKeyPairSync("ec", {
namedCurve: "prime256v1",
});
const privJwk = privateKey.export({ format: "jwk" });
const privHex = jwkB64ToHex(privJwk.d);
if (compressed) {
// Compressed SEC1 (02/03 prefix) selects the client-held-key flow on
// the OAuth/PASSKEY challenge and verify endpoints.
return { pubHex: privHexToCompressedPubHex(privHex), privHex };
}
const pubJwk = publicKey.export({ format: "jwk" });
// Uncompressed SEC1: 0x04 || X || Y
const pubHex =
"04" + jwkB64ToHex(pubJwk.x) + jwkB64ToHex(pubJwk.y);
return { pubHex, privHex };
}
function hexToBytes(hex) {
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return bytes;
}
function encryptOtp(otpEncryptionTargetBundle, pubHex, otpCode) {
// Extract targetPublic from the signed bundle
const { data } = JSON.parse(otpEncryptionTargetBundle);
const dataJson = Buffer.from(data, "hex").toString("utf8");
const { targetPublic } = JSON.parse(dataJson);
// HPKE-encrypt {otp_code, public_key} to the target
const plainText = JSON.stringify({ otp_code: otpCode, public_key: pubHex });
const plainTextBuf = Buffer.from(plainText, "utf8");
const targetKeyBuf = hexToBytes(targetPublic);
const encryptedBuf = hpkeEncrypt({ plainTextBuf, targetKeyBuf });
return formatHpkeBuf(encryptedBuf);
}
function privHexToCompressedPubHex(privHex) {
// Build a JWK from the private key, then re-derive the public point in
// compressed SEC1 form (the format the Grid wallet signature expects).
const dB64 = Buffer.from(privHex, "hex").toString("base64url");
// We need x/y to construct a JWK key object, but we only have d.
// Use noble curves from the signing helper dependency.
const { p256 } = require("@noble/curves/p256");
const compressed = p256.getPublicKey(privHex, true); // Uint8Array
return Buffer.from(compressed).toString("hex");
}
async function main() {
const [, , cmd, ...rest] = process.argv;
switch (cmd) {
case "gen-keypair": {
const compressed = rest.includes("--compressed");
const out = genKeypair({ compressed });
process.stdout.write(JSON.stringify(out, null, 2) + "\n");
return;
}
case "encrypt-otp": {
const [targetArg, pubArg, otpArg] = rest;
if (!targetArg || !pubArg || !otpArg) usage(1);
const targetBundle = readArg(targetArg);
const pubHex = readArg(pubArg);
const otpCode = readArg(otpArg);
const encBundle = encryptOtp(targetBundle, pubHex, otpCode);
process.stdout.write(JSON.stringify(encBundle) + "\n");
return;
}
case "decrypt-bundle": {
const [bundleArg, privArg] = rest;
if (!bundleArg || !privArg) usage(1);
const bundle = readArg(bundleArg);
const privHex = readArg(privArg);
const sessionPrivHex = await decryptCredentialBundle(bundle, privHex);
process.stdout.write(sessionPrivHex + "\n");
return;
}
case "stamp": {
const [sessArg, payloadArg] = rest;
if (!sessArg || !payloadArg) usage(1);
const sessionPrivHex = readArg(sessArg);
const payload = readArg(payloadArg);
const sessionPubHex = privHexToCompressedPubHex(sessionPrivHex);
const stamper = new ApiKeyStamper({
apiPublicKey: sessionPubHex,
apiPrivateKey: sessionPrivHex,
});
const { stampHeaderValue } = await stamper.stamp(payload);
process.stdout.write(stampHeaderValue + "\n");
return;
}
case "--help":
case "-h":
case undefined:
usage(0);
return;
default:
console.error(`Unknown command: ${cmd}`);
usage(1);
}
}
function usage(code) {
const msg = [
"embedded-wallet-sign — signing helpers for the Grid offramp flow",
"",
"Subcommands:",
" gen-keypair [--compressed] Generate ephemeral P-256 keypair; --compressed for EMAIL_OTP and the OAuth/PASSKEY client-held flow",
" encrypt-otp <targetBundle> <pubHex> <otpCode> HPKE-encrypt OTP for EMAIL_OTP verify",
" decrypt-bundle <bundle> <privHex> HPKE-open the session signing key (legacy PASSKEY/OAUTH flow)",
" stamp <sessionPrivHex> <payload> Build a Grid-Wallet-Signature stamp",
"",
"Use - in place of any argument to read it from stdin.",
].join("\n");
(code === 0 ? process.stdout : process.stderr).write(msg + "\n");
process.exit(code);
}
main().catch((err) => {
console.error(err.stack || String(err));
process.exit(1);
});