Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add session signature with SubtleCrypto #654

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/webapp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"async-sema": "^3.1.1",
"cids": "^1.1.6",
"dayjs": "^1.10.4",
"elliptic": "^6.5.4",
"eosjs": "^21.0.3",
"graphiql": "^1.4.2",
"graphql": "^15.5.1",
Expand Down Expand Up @@ -51,6 +52,7 @@
"zod": "^3.0.0-beta.1"
},
"devDependencies": {
"@types/elliptic": "^6.4.14",
"@types/node": "~14.0.23",
"@types/nprogress": "^0.2.0",
"@types/react": "~17.0.0",
Expand Down
190 changes: 182 additions & 8 deletions packages/webapp/src/_app/eos/sessions.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
import dayjs from "dayjs";
import { generateKeyPair, sha256 } from "eosjs/dist/eosjs-key-conversions";
import { KeyType } from "eosjs/dist/eosjs-numeric";
import { generateKeyPair } from "eosjs/dist/eosjs-key-conversions";
import {
Key,
KeyType,
publicKeyToString,
signatureToString,
} from "eosjs/dist/eosjs-numeric";
import { PrivateKey } from "eosjs/dist/eosjs-jssig";
import { Signature } from "eosjs/dist/Signature";
import { hexToUint8Array, SerialBuffer } from "eosjs/dist/eosjs-serialize";
import { get as idbGet, set as idbSet } from "idb-keyval";
import { SessionSignRequest } from "@edenos/common";
import { ec as elliptic } from "elliptic";

import { edenContractAccount, box } from "config";
import { eosDefaultApi, eosJsonRpc } from "_app";

const EC = new elliptic("p256") as any;

const DEFAULT_EXPIRATION_SECONDS = 30 * 24 * 60 * 60; // 30 days
const DEFAULT_SESSION_DESCRIPTION = "eden login";

Expand All @@ -17,6 +26,7 @@ interface SessionKeyData {
privateKey: string;
expiration: Date;
lastSequence: number;
subtleKey?: CryptoKeyPair;
}

class SessionKeysStorage {
Expand Down Expand Up @@ -55,11 +65,21 @@ export const generateSessionKey = async (
secureEnv: true,
});

const subtleKey = await crypto.subtle.generateKey(
{
name: "ECDSA",
namedCurve: "P-256",
},
false, // not extractable
["sign", "verify"]
);

const expiration = dayjs().add(expirationSeconds, "seconds").toDate();

return {
publicKey: publicKey.toString(),
privateKey: privateKey.toString(),
subtleKey,
lastSequence: 0,
expiration,
};
Expand All @@ -70,7 +90,15 @@ export const newSessionTransaction = async (
sessionKeyData: SessionKeyData,
description = DEFAULT_SESSION_DESCRIPTION
) => {
const key = sessionKeyData.publicKey;
let key = sessionKeyData.publicKey;

if (sessionKeyData.subtleKey?.publicKey) {
const subtlePubKey = sessionKeyData.subtleKey.publicKey;
const eosKey = await subtleToEosPublicKey(subtlePubKey);
console.info("subtle eos pubkey >>>", eosKey);
key = publicKeyToString(eosKey);
}

const expiration =
sessionKeyData.expiration.toISOString().slice(0, -4) + "000";

Expand Down Expand Up @@ -129,14 +157,14 @@ export const signSessionTransaction = async (
const sequence = sessionKey.lastSequence + 1;
const verbs = convertActionsToVerbs(actions);

const signatureAuthSha = await makeSignatureAuthSha(
const signatureAuthData = await makeSignatureAuthSha(
edenContractAccount,
authorizerAccount,
sequence,
verbs
);

const signature = await signSha(sessionKey, signatureAuthSha);
const signature = await signData(sessionKey, signatureAuthData);

const data: SessionSignRequest = {
signature: signature.toString(),
Expand Down Expand Up @@ -164,7 +192,8 @@ const makeSignatureAuthSha = async (
sequence,
verbs
);
return sha256(Buffer.from(signatureAuthBytes));
return signatureAuthBytes;
// return sha256(Buffer.from(signatureAuthBytes));
};

const convertActionsToVerbs = (actions: any[]) =>
Expand Down Expand Up @@ -194,7 +223,152 @@ const serializeSignatureAuth = async (
return buffer.asUint8Array();
};

const signSha = (sessionKey: SessionKeyData, sha: number[]) => {
const signData = async (
sessionKey: SessionKeyData,
data: Uint8Array
): Promise<string> => {
const privateKey = PrivateKey.fromString(sessionKey.privateKey);
return privateKey.sign(sha, false);
const signature = privateKey.sign(data, true);
console.info("eos signature >>>", signature, signature.toString());

if (sessionKey.subtleKey?.privateKey) {
console.info("i will sign with subtle >>>", sessionKey.subtleKey);

const privateKey = sessionKey.subtleKey.privateKey;
const signature = await crypto.subtle.sign(
{ name: "ECDSA", hash: "SHA-256" },
privateKey,
data
);
const signatureBytes = new Uint8Array(signature);

const eosPubKey = await subtleToEosPublicKey(
sessionKey.subtleKey.publicKey!
);

// const pubKey = EC.keyFromPublic(
// eosPubKey.data.subarray(0, 33)
// ).getPublic();
// const hash = new Uint8Array(
// await crypto.subtle.digest("SHA-256", data)
// );

// const ecSignature = {
// r: signatureBytes.slice(0, 32),
// s: signatureBytes.slice(32, 64),
// };
// console.info(ecSignature, eosPubKey, pubKey, hash, signatureBytes);
// const recid = EC.getKeyRecoveryParam(hash, ecSignature, pubKey);
// const recidByte = 27 + 4 + recid; <<<--- still presenting failures
sparkplug0025 marked this conversation as resolved.
Show resolved Hide resolved

let recId = 31;

const sigDataWithRecovery = {
type: KeyType.r1,
data: new Uint8Array([recId].concat(Array.from(signatureBytes))),
};
console.info(
"signature from subtle",
recId,
signatureBytes,
signature,
sigDataWithRecovery,
signatureToString(sigDataWithRecovery)
);

const sessionPubKeyString = publicKeyToString(eosPubKey);
let x = signatureToString(sigDataWithRecovery);
let y = Signature.fromString(x);
let recoveredKey = y.recover(data, true).toString();

console.info(
"recoveredKey >>>",
recoveredKey.toString(),
sessionPubKeyString
);

if (recoveredKey.toString() === sessionPubKeyString) {
return x;
}

recId += 1;
sigDataWithRecovery.data[0] = recId;
x = signatureToString(sigDataWithRecovery);
y = Signature.fromString(x);
recoveredKey = y.recover(data, true).toString();

console.info(
"recoveredKey 2 >>>",
recoveredKey.toString(),
sessionPubKeyString
);

return x;
}
return signature.toString();
};

const subtleToEosPublicKey = async (
subtlePublicKey: CryptoKey
): Promise<Key> => {
const rawKey = await crypto.subtle.exportKey("raw", subtlePublicKey);
const x = new Uint8Array(rawKey.slice(1, 33));
const y = new Uint8Array(rawKey.slice(33, 65));
console.info("raw data pubkey >>>", rawKey, x, y);
const data = new Uint8Array([y[31] & 1 ? 3 : 2].concat(Array.from(x)));
const key = { type: KeyType.r1, data };
console.info("subtle to eoskey >>>", key);
return key;
};

function toDER(pr: number[], ps: number[]) {
let r = [...pr];
let s = [...ps];

// Pad values
if (r[0] & 0x80) r = [0].concat(r);
// Pad values
if (s[0] & 0x80) s = [0].concat(s);

r = rmPadding(r);
s = rmPadding(s);

while (!s[0] && !(s[1] & 0x80)) {
s = s.slice(1);
}
var arr = [0x02];
constructLength(arr, r.length);
arr = arr.concat(r);
arr.push(0x02);
constructLength(arr, s.length);
var backHalf = arr.concat(s);
var res = [0x30];
constructLength(res, backHalf.length);
res = res.concat(backHalf);
return res;
}

function rmPadding(buf: number[]) {
var i = 0;
var len = buf.length - 1;
while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
i++;
}
if (i === 0) {
return buf;
}
return buf.slice(i);
}

function constructLength(arr: number[], len: number) {
if (len < 0x80) {
arr.push(len);
return;
}
var octets = 1 + ((Math.log(len) / Math.LN2) >>> 3);
arr.push(octets | 0x80);
while (--octets) {
arr.push((len >>> (octets << 3)) & 0xff);
}
arr.push(len);
}
7 changes: 7 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2101,6 +2101,13 @@
dependencies:
"@types/bn.js" "*"

"@types/elliptic@^6.4.14":
version "6.4.14"
resolved "https://registry.yarnpkg.com/@types/elliptic/-/elliptic-6.4.14.tgz#7bbaad60567a588c1f08b10893453e6b9b4de48e"
integrity sha512-z4OBcDAU0GVwDTuwJzQCiL6188QvZMkvoERgcVjq0/mPM8jCfdwZ3x5zQEVoL9WCAru3aG5wl3Z5Ww5wBWn7ZQ==
dependencies:
"@types/bn.js" "*"

"@types/express-serve-static-core@^4.17.18":
version "4.17.21"
resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.17.21.tgz#a427278e106bca77b83ad85221eae709a3414d42"
Expand Down