Skip to content
Merged
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,5 @@ dist

.env.test
**/*.DS_Store

.npmrc
4 changes: 2 additions & 2 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@toruslabs/torus.js",
"version": "17.2.2",
"version": "17.2.3",
"description": "Handle communication with torus nodes",
"main": "dist/lib.cjs/index.js",
"module": "dist/lib.esm/index.js",
Expand Down
84 changes: 73 additions & 11 deletions src/helpers/citadelUtils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
import { BUILD_ENV_TYPE, CITADEL_SERVER_MAP } from "@toruslabs/constants";
import { get } from "@toruslabs/http-helpers";
import { BUILD_ENV_TYPE, CITADEL_SERVER_MAP, TORUS_NETWORK_TYPE } from "@toruslabs/constants";
import { get, put } from "@toruslabs/http-helpers";
Comment thread
arch1995 marked this conversation as resolved.

import { RetrieveSharesParams } from "../interfaces";
import { isNullOrUndefined } from "./common";

export enum CitadelAllowParamsSetOrUnsetFlag {
SET = 1,
UNSET = 0,
}

export interface CitadelAuthFlowAuditParams {
oauthInitiated?: boolean;
oauthVerified?: boolean;
oauthCompleted?: boolean;
oauthVerificationFailed?: boolean;
oauthFailed?: boolean;
}

export interface CitadelAllowParams {
buildEnv: BUILD_ENV_TYPE;
Expand All @@ -9,9 +25,22 @@ export interface CitadelAllowParams {
clientId: string;
recordId: string;
source?: string;
torusLoginInitiated?: boolean;
torusLoginSuccess?: boolean;
torusLoginFailed?: boolean;
// flags for auditing the auth flow
oauthInitiated?: CitadelAllowParamsSetOrUnsetFlag;
oauthVerified?: CitadelAllowParamsSetOrUnsetFlag;
oauthCompleted?: CitadelAllowParamsSetOrUnsetFlag;
oauthVerificationFailed?: CitadelAllowParamsSetOrUnsetFlag;
oauthFailed?: CitadelAllowParamsSetOrUnsetFlag;
}

export interface CitadelAuditParams extends CitadelAuthFlowAuditParams {
recordId: string;
authConnection: string;
authConnectionId: string;
groupedAuthConnectionId: string;
oAuthUserId: string;
web3AuthNetwork: string;
web3AuthClientId: string;
}

export function buildAllowUrl(params: CitadelAllowParams): string {
Expand All @@ -24,22 +53,55 @@ export function buildAllowUrl(params: CitadelAllowParams): string {
if (params.source) {
url.searchParams.set("source", params.source);
}
if (typeof params.torusLoginInitiated !== "undefined") {
url.searchParams.set("toruslogininitiated", params.torusLoginInitiated.toString());
if (!isNullOrUndefined(params.oauthInitiated)) {
url.searchParams.set("oauthInitiated", params.oauthInitiated.toString());
}
if (typeof params.torusLoginSuccess !== "undefined") {
url.searchParams.set("torusloginsuccess", params.torusLoginSuccess.toString());
if (!isNullOrUndefined(params.oauthVerified)) {
url.searchParams.set("oauthVerified", params.oauthVerified.toString());
}
if (typeof params.torusLoginFailed !== "undefined") {
url.searchParams.set("torusloginfailed", params.torusLoginFailed.toString());
if (!isNullOrUndefined(params.oauthCompleted)) {
url.searchParams.set("oauthCompleted", params.oauthCompleted.toString());
}
if (!isNullOrUndefined(params.oauthVerificationFailed)) {
url.searchParams.set("oauthVerificationFailed", params.oauthVerificationFailed.toString());
}
if (!isNullOrUndefined(params.oauthFailed)) {
url.searchParams.set("oauthFailed", params.oauthFailed.toString());
}
return url.toString();
}

export function buildAuditPayload(
network: TORUS_NETWORK_TYPE,
clientId: string,
params: RetrieveSharesParams,
authFlowAuditParams: CitadelAuthFlowAuditParams
): CitadelAuditParams {
if (!params.recordId) {
params.recordId = generateRecordId();
}
Comment thread
lwin-kyaw marked this conversation as resolved.

return {
...authFlowAuditParams,
recordId: params.recordId,
Comment thread
cursor[bot] marked this conversation as resolved.
authConnection: params.authConnection || "",
authConnectionId: params.verifierParams.sub_verifier_ids?.[0] || "",
groupedAuthConnectionId: params.verifier || "",
oAuthUserId: params.verifierParams.verifier_id || "",
web3AuthNetwork: network,
web3AuthClientId: clientId,
};
}

export async function callAllowApi(params: CitadelAllowParams): Promise<void> {
await get<void>(buildAllowUrl(params));
}

export async function callAuditApi(buildEnv: BUILD_ENV_TYPE, params: CitadelAuditParams): Promise<void> {
const url = new URL(`${CITADEL_SERVER_MAP[buildEnv]}/v1/auth/audit`);
await put<void>(url.toString(), params);
}

export function generateRecordId(): string {
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
if (typeof cr?.randomUUID !== "function") throw new Error("crypto.randomUUID must be defined");
Expand Down
4 changes: 4 additions & 0 deletions src/helpers/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,7 @@ export function retryCommitment(executionPromise: () => Promise<JRPCResponse<Com

return retryWithBackoff(0);
}

export function isNullOrUndefined(value: unknown): value is null | undefined {
return value === null || value === undefined;
}
6 changes: 4 additions & 2 deletions src/helpers/nodeUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
import log from "../loglevel";
import { Some } from "../some";
import { TorusUtilsExtraParams } from "../TorusUtilsExtraParams";
import { callAllowApi } from "./citadelUtils";
import { callAllowApi, CitadelAllowParamsSetOrUnsetFlag } from "./citadelUtils";
import {
base64ToBytes,
bigintToHex,
Expand Down Expand Up @@ -390,6 +390,7 @@ export async function retrieveOrImportShare(params: {
source,
recordId,
} = params;
// call feature-gating check before share retrieval
await callAllowApi({
buildEnv,
verifier,
Expand All @@ -398,7 +399,8 @@ export async function retrieveOrImportShare(params: {
clientId,
source,
recordId,
torusLoginInitiated: true,
oauthInitiated: CitadelAllowParamsSetOrUnsetFlag.SET,
oauthCompleted: CitadelAllowParamsSetOrUnsetFlag.SET,
});

// generate temporary private and public key that is used to secure receive shares
Expand Down
17 changes: 17 additions & 0 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ export interface VerifierParams {
[key: string]: unknown;
verifier_id: string;
extended_verifier_id?: string;
sub_verifier_ids?: string[];
}

export type StringifiedType = Record<string, unknown>;
Expand Down Expand Up @@ -283,6 +284,11 @@ export interface ImportKeyParams {
newPrivateKey: string;
extraParams?: TorusUtilsExtraParams;
checkCommitment?: boolean;

/**
* Optional recordId to used for the analytics tracking.
*/
recordId?: string;
}

export interface RetrieveSharesParams {
Expand All @@ -295,4 +301,15 @@ export interface RetrieveSharesParams {
extraParams?: TorusUtilsExtraParams;
useDkg?: boolean;
checkCommitment?: boolean;

/**
* User social login provider name.
* This is used for the analytics tracking.
*/
authConnection?: string;

/**
* Optional recordId to used for the analytics tracking.
*/
recordId?: string;
}
50 changes: 46 additions & 4 deletions src/torus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@ import { setAPIKey, setEmbedHost } from "@toruslabs/http-helpers";
import { config } from "./config";
import {
bigintToHex,
buildAuditPayload,
bytesToHex,
callAllowApi,
callAuditApi,
CitadelAllowParams,
CitadelAllowParamsSetOrUnsetFlag,
CitadelAuthFlowAuditParams,
Curve,
encodeEd25519Point,
generateAddressFromPubKey,
Expand Down Expand Up @@ -150,17 +154,26 @@ class Torus {
extraParams.session_token_exp_second = Torus.sessionTime;
}

const recordId = params.recordId || generateRecordId();

const allowParams = {
buildEnv: this.buildEnv,
verifier,
verifierId: verifierParams.verifier_id,
network: this.network,
clientId: this.clientId,
source: this.source,
recordId: generateRecordId(),
recordId,
};

// for auditing the auth flow
const auditParams: CitadelAuthFlowAuditParams = {
// at this point, user has completed the oauth login
oauthCompleted: true,
};

let result: TorusKey;

try {
result = await retrieveOrImportShare({
recordId: allowParams.recordId,
Expand All @@ -186,11 +199,23 @@ class Torus {
source: this.source,
});
} catch (error) {
this.reportSignerAllow({ ...allowParams, torusLoginFailed: true });
if (params.recordId) {
// report oauth verification failed, we won't await this call as it's only for analytics tracking
auditParams.oauthVerificationFailed = true;
this.reportUserAuthFlowAudit({ ...params, recordId }, auditParams);
} else {
this.reportSignerAllow({ ...allowParams, oauthVerificationFailed: CitadelAllowParamsSetOrUnsetFlag.SET });
}
throw error;
}

this.reportSignerAllow({ ...allowParams, torusLoginSuccess: true });
if (!params.recordId) {
this.reportSignerAllow({ ...allowParams, oauthVerified: CitadelAllowParamsSetOrUnsetFlag.SET });
} else {
// report oauth verified, we won't await this call as it's only for analytics tracking
auditParams.oauthVerified = true;
this.reportUserAuthFlowAudit({ ...params, recordId }, auditParams);
}
return result;
}

Expand All @@ -202,6 +227,21 @@ class Torus {
}
}

/**
* Report user auth flow audit to the citadel server.
* @param recordId - The record id to be used for the analytics tracking.
* @param params - The parameters for the retrieve shares operation.
* @param authStepStatus - The status of the authentication steps.
*/
async reportUserAuthFlowAudit(params: RetrieveSharesParams, authFlowAuditParams: CitadelAuthFlowAuditParams): Promise<void> {
try {
const auditParams = buildAuditPayload(this.network, this.clientId, params, authFlowAuditParams);
await callAuditApi(this.buildEnv, auditParams);
} catch (error) {
log.error("Failed to log user auth flow audit", error);
}
}

async getPublicAddress(
endpoints: string[],
torusNodePubs: INodePub[],
Expand Down Expand Up @@ -262,8 +302,10 @@ class Torus {
}
}

const recordId = params.recordId || generateRecordId();

return retrieveOrImportShare({
recordId: generateRecordId(),
recordId,
legacyMetadataHost: this.legacyMetadataHost,
serverTimeOffset: this.serverTimeOffset,
enableOneKey: this.enableOneKey,
Expand Down
Loading