UNPKG

@dynamic-labs/sdk-react-core

Version:

A React SDK for implementing wallet web3 authentication and authorization to your website.

67 lines (62 loc) 3.02 kB
'use client' 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _tslib = require('../../../../../../_virtual/_tslib.cjs'); // Converts an ArrayBuffer to a hex-encoded string const buf2hex = (buffer) => [...new Uint8Array(buffer)] .map((x) => x.toString(16).padStart(2, '0')) .join(''); // Takes a base64url-encoded string (e.g. "nMueRPiAm51YXEjRtka8S_8Ura3HaqbmqDqMJCZmvkM") // and return the corresponding bytes, as an array buffer. const base64urlDecode = (s) => { // Go from base64url encoding to base64 encoding s = (s === null || s === void 0 ? void 0 : s.replace(/-/g, '+').replace(/_/g, '/')) || ''; // use `atob` to decode base64 return Uint8Array.from(atob(s), (c) => c.charCodeAt(0)); }; // Accepts a public key array buffer, and returns a buffer with the compressed version of the public key const compressRawPublicKey = (rawPublicKey) => { const rawPublicKeyBytes = new Uint8Array(rawPublicKey); const len = rawPublicKeyBytes.byteLength; // Drop the y coordinate const compressedBytes = rawPublicKeyBytes.slice(0, (1 + len) >>> 1); // Encode the parity of `y` in first bit compressedBytes[0] = 0x2 | (rawPublicKeyBytes[len - 1] & 0x01); return compressedBytes.buffer; }; const p256Keygen = () => _tslib.__awaiter(void 0, void 0, void 0, function* () { // Create a new P-256 keypair const p256Keypair = yield crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256', }, true, ['sign', 'verify']); // Export the raw public key. By default this will export in uncompressed format const rawPublicKey = yield crypto.subtle.exportKey('raw', p256Keypair.publicKey); // We need to export with JWK format because exporting EC private keys with "raw" isn't supported const privateKeyJwk = yield crypto.subtle.exportKey('jwk', p256Keypair.privateKey); // Optional: compress the public key! But you don't have to const compressedPublicKeyBuffer = compressRawPublicKey(rawPublicKey); const privateKeyBuffer = base64urlDecode(privateKeyJwk.d); return { private: buf2hex(privateKeyBuffer), // format for Turnkey API key stamper privateJwk: privateKeyJwk, // format required for use in signing redcoast signatures public: buf2hex(compressedPublicKeyBuffer), publicUncompressed: buf2hex(rawPublicKey), }; }); const p256Sign = (privateKeyJwk, message) => _tslib.__awaiter(void 0, void 0, void 0, function* () { const privateKey = yield crypto.subtle.importKey('jwk', privateKeyJwk, { name: 'ECDSA', namedCurve: 'P-256', }, false, ['sign']); const signature = yield crypto.subtle.sign({ hash: 'SHA-256', name: 'ECDSA', }, privateKey, new TextEncoder().encode(message)); return buf2hex(signature); }); exports.base64urlDecode = base64urlDecode; exports.buf2hex = buf2hex; exports.compressRawPublicKey = compressRawPublicKey; exports.p256Keygen = p256Keygen; exports.p256Sign = p256Sign;