Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
20 changes: 20 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"@tkey/core": "^15.1.0",
"@tkey/share-serialization": "^15.1.0",
"@tkey/storage-layer-torus": "^15.1.0",
"@tkey/share-transfer": "^15.1.0",
"@tkey/tss": "^15.1.0",
"@toruslabs/constants": "^14.0.0",
"@toruslabs/customauth": "^20.3.0",
Expand Down
7 changes: 7 additions & 0 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { KeyType, Point as TkeyPoint, ShareDescriptionMap } from "@tkey/common-types";
import { ShareTransferStore } from "@tkey/share-transfer";
import { TKeyTSS } from "@tkey/tss";
import type {
AGGREGATE_VERIFIER_TYPE,
Expand Down Expand Up @@ -262,6 +263,12 @@ export interface ICoreKit {
*/
createFactor(createFactorParams: CreateFactorParams): Promise<string>;

requestShare(userAgent?: string): Promise<string>;
waitForRequestShareResponse(currentEncPubKeyX: string): Promise<void>;
getShareTransferStore(): Promise<ShareTransferStore>;
approveShareRequest(pubKey: string): Promise<void>;
createDeviceFactor(metadata: Record<string, string>): Promise<BN>;

/**
* Deletes the factor identified by the given public key, including all
* associated metadata.
Expand Down
52 changes: 52 additions & 0 deletions src/mpcCoreKit.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BNString, KeyType, ONE_KEY_DELETE_NONCE, Point, secp256k1, SHARE_DELETED, ShareStore, StringifiedType } from "@tkey/common-types";
import { CoreError } from "@tkey/core";
import { ShareSerializationModule } from "@tkey/share-serialization";
import { ShareTransferModule, ShareTransferStore } from "@tkey/share-transfer";
import { TorusStorageLayer } from "@tkey/storage-layer-torus";
import { factorKeyCurve, getPubKeyPoint, lagrangeInterpolation, TKeyTSS, TSSTorusServiceProvider } from "@tkey/tss";
import { KEY_TYPE, SIGNER_MAP } from "@toruslabs/constants";
Expand Down Expand Up @@ -260,6 +261,7 @@ export class Web3AuthMPCCoreKit implements ICoreKit {
});

const shareSerializationModule = new ShareSerializationModule();
const shareTransferModule = new ShareTransferModule();

this.tkey = new TKeyTSS({
enableLogging: this.enableLogging,
Expand All @@ -268,6 +270,7 @@ export class Web3AuthMPCCoreKit implements ICoreKit {
manualSync: this.options.manualSync,
modules: {
shareSerialization: shareSerializationModule,
shareTransfer: shareTransferModule,
},
tssKeyType: this.keyType,
});
Expand Down Expand Up @@ -670,6 +673,55 @@ export class Web3AuthMPCCoreKit implements ICoreKit {
});
}

public async requestShare(userAgent?: string): Promise<string> {
return (this.tKey.modules.shareTransfer as ShareTransferModule).requestNewShare(
userAgent ?? navigator.userAgent,
this.tKey.getCurrentShareIndexes()
);
}

public async waitForRequestShareResponse(currentEncPubKeyX: string): Promise<void> {
const shareStore = await (this.tkey!.modules.shareTransfer as ShareTransferModule).startRequestStatusCheck(currentEncPubKeyX, true);
await this.tKey.reconstructKey();
this.tKey.inputShareStore(shareStore);
}

public async getShareTransferStore(): Promise<ShareTransferStore> {
return (this.tKey.modules.shareTransfer as ShareTransferModule).getShareTransferStore();
}

public async approveShareRequest(currentEncPubKeyY: string): Promise<void> {
try {
const newShare = await this.tKey.generateNewShare();
const shareToShare = newShare.newShareStores[newShare.newShareIndex.toString("hex")];
await (this.tKey.modules.shareTransfer as ShareTransferModule).approveRequest(currentEncPubKeyY, shareToShare);
await this.tKey.syncLocalMetadataTransitions();
} catch (err) {
log.error("Failed to process share transfer store:", err);
}
}

public async createDeviceFactor(metadata: Record<string, string>): Promise<BN> {
this.tKey.initialize();

const deviceFactorKey = new BN(
await this.createFactor({
shareType: TssShareType.DEVICE,
additionalMetadata: metadata,
}),
"hex"
);

await this.atomicSync(async () => {
await this.setDeviceFactor(deviceFactorKey);
await this.inputFactorKey(new BN(deviceFactorKey, "hex"));

await this.commitChanges();
});

return deviceFactorKey;
}

/**
* Get public key point in SEC1 format.
*/
Expand Down
165 changes: 165 additions & 0 deletions tests/shareCreateDelete.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import { factorKeyCurve, getPubKeyPoint } from "@tkey/tss";
import { tssLib as tssLibDKLS } from "@toruslabs/tss-dkls-lib";
import BN from "bn.js";
import assert from "node:assert";
import test from "node:test";

import {
COREKIT_STATUS,
FactorKeyTypeShareDescription,
generateFactorKey,
getHashedPrivateKey,
IAsyncStorage,
IStorage,
MemoryStorage,
TssLibType,
TssShareType,
WEB3AUTH_NETWORK,
Web3AuthMPCCoreKit,
} from "../src";
import { criticalResetAccount, mockLogin } from "./setup";
import { Point, secp256k1 } from "@tkey/common-types";

type FactorTestVariable = {
manualSync?: boolean;
storage?: IAsyncStorage | IStorage;
email: string;
tssLib?: TssLibType;
userAgent?: string;
};

export const FactorManipulationTest = async (testVariable: FactorTestVariable) => {
const { email, tssLib } = testVariable;
const newInstance = async () => {
const instance = new Web3AuthMPCCoreKit({
web3AuthClientId: "torus-key-test",
web3AuthNetwork: WEB3AUTH_NETWORK.DEVNET,
baseUrl: "http://localhost:3000",
uxMode: "nodejs",
tssLib: tssLib || tssLibDKLS,
storage: testVariable.storage,
manualSync: testVariable.manualSync,
});

const { idToken, parsedToken } = await mockLogin(email);
await instance.init({ handleRedirectResult: false, rehydrate: false });
await instance.loginWithJWT({
verifier: "torus-test-health",
verifierId: parsedToken.email,
idToken,
});
return instance;
};

async function beforeTest() {
const resetInstance = await newInstance();
await criticalResetAccount(resetInstance);
await resetInstance.logout();
}

await test(`#Factor manipulation - manualSync ${testVariable.manualSync} `, async function (t) {
await beforeTest();

await t.test("should be able to create factor", async function () {
const coreKitInstance = await newInstance();
assert.equal(coreKitInstance.status, COREKIT_STATUS.LOGGED_IN, "Instance should be logged in after initialization");

await coreKitInstance.commitChanges();

const socialFactorKey = new BN(coreKitInstance.state.postBoxKey, "hex");
await coreKitInstance.enableMFA({
factorKey: socialFactorKey,
shareDescription: FactorKeyTypeShareDescription.SocialShare,
});

// Sync if manualSync is enabled
if (testVariable.manualSync) {
await coreKitInstance.commitChanges();
}

// Create a new instance to simulate another device
const instance2 = await newInstance();
assert.equal(instance2.status, COREKIT_STATUS.REQUIRED_SHARE, "Second instance should require a share");

const pubKeyX = await instance2.requestShare(testVariable.userAgent);
const transferStore = await coreKitInstance.getShareTransferStore();
assert(Object.keys(transferStore).length > 0, "Share transfer store should have pending requests");

await coreKitInstance.approveShareRequest(Object.keys(transferStore)[0]);
assert.equal(instance2.status, COREKIT_STATUS.REQUIRED_SHARE, "Second instance should still require a share until input");

await instance2.waitForRequestShareResponse(pubKeyX);
await instance2.inputFactorKey(socialFactorKey);
assert.equal(instance2.status, COREKIT_STATUS.LOGGED_IN, "Second instance should be logged in after inputting factor key");

// Create a new factor (recovery factor)
const otherFactorKey = generateFactorKey().private;
await instance2.createFactor({
factorKey: otherFactorKey,
shareType: TssShareType.RECOVERY,
shareDescription: FactorKeyTypeShareDescription.Other,
});

await instance2.inputFactorKey(otherFactorKey);
await instance2.logout();

// Create a third instance to verify recovery
const instance3 = await newInstance();
await instance3.inputFactorKey(new BN(await instance3.getDeviceFactor(), "hex"));
await instance3.inputFactorKey(socialFactorKey);
assert.equal(instance3.status, COREKIT_STATUS.LOGGED_IN, "Third instance should be logged in after inputting factor keys");

// Verify the recovery factor exists
let factorPub: string | undefined;
for (const [key, value] of Object.entries(instance3.getKeyDetails().shareDescriptions)) {
if (value.length > 0) {
const parsedData = JSON.parse(value[0]);
if (parsedData.module === FactorKeyTypeShareDescription.Other) {
factorPub = key;
}
}
}
assert(factorPub, "Recovery factor should exist in key details");

// Delete the recovery factor
const pub = Point.fromSEC1(secp256k1, factorPub);
await instance3.deleteFactor(pub);
await instance3.commitChanges();

factorPub = undefined;

for (const [key, value] of Object.entries(instance3.getKeyDetails().shareDescriptions)) {
if (value.length > 0) {
const parsedData = JSON.parse(value[0]);
if (parsedData.module === FactorKeyTypeShareDescription.Other) {
factorPub = key;
}
}
}

assert(!factorPub, "Recovery factor should be deleted");

await coreKitInstance.logout();
await instance3.logout();
});
});
};

const variable: FactorTestVariable[] = [
{
manualSync: true,
storage: new MemoryStorage(),
email: "testmail1012",
userAgent: "Mozilla/5.0 (Linux; Android 12; Pixel 6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36",
},
// { manualSync: false, storage: new MemoryStorage(), email: "testmail1013" },

// { manualSync: true, storage: new AsyncMemoryStorage(), email: "testmail1014" },
// { manualSync: false, storage: new AsyncMemoryStorage(), email: "testmail1015" },

// { manualSync: true, storage: new MemoryStorage(), email: "testmail1012ed25519", tssLib: tssLibFROST },
];

variable.forEach(async (testVariable) => {
await FactorManipulationTest(testVariable);
});