Skip to content

Commit d82f4c1

Browse files
Merge pull request #188 from Web3Auth/feat/disableSessionManager
Feat/disable session manager
2 parents 946c061 + 04a5f01 commit d82f4c1

File tree

3 files changed

+106
-47
lines changed

3 files changed

+106
-47
lines changed

src/interfaces.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,13 @@ export interface Web3AuthOptions {
336336
*/
337337
storage: IAsyncStorage | IStorage;
338338

339+
/**
340+
* @defaultValue false
341+
* disable session manager creation
342+
* signatures from web3auth newtorks will still expired after sessionTime if session manager is disabled
343+
*/
344+
disableSessionManager?: boolean;
345+
339346
/**
340347
* @defaultValue 86400
341348
*/

src/mpcCoreKit.ts

Lines changed: 38 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ export class Web3AuthMPCCoreKit implements ICoreKit {
8080

8181
private tkey: TKeyTSS | null = null;
8282

83-
private sessionManager!: SessionManager<SessionData>;
83+
private sessionManager?: SessionManager<SessionData>;
8484

8585
private currentStorage: AsyncStorage;
8686

@@ -108,27 +108,33 @@ export class Web3AuthMPCCoreKit implements ICoreKit {
108108

109109
const isNodejsOrRN = this.isNodejsOrRN(options.uxMode);
110110

111-
// if (await storageAvailable(options.storage)) {
112-
// throw CoreKitError.storageTypeUnsupported(`Unsupported storage type ${options.storageKey} for ${options.uxMode} mode.`);
113-
// }
114-
115111
if (options.enableLogging) {
116112
log.enableAll();
117113
this.enableLogging = true;
118114
} else log.setLevel("error");
119115
if (typeof options.manualSync !== "boolean") options.manualSync = false;
120116
if (!options.web3AuthNetwork) options.web3AuthNetwork = WEB3AUTH_NETWORK.MAINNET;
117+
// if sessionTime is not provided, it is defaulted to 86400
121118
if (!options.sessionTime) options.sessionTime = 86400;
122119
if (!options.serverTimeOffset) options.serverTimeOffset = 0;
123120
if (!options.uxMode) options.uxMode = UX_MODE.REDIRECT;
124121
if (!options.redirectPathName) options.redirectPathName = "redirect";
125122
if (!options.baseUrl) options.baseUrl = isNodejsOrRN ? "https://localhost" : `${window?.location.origin}/serviceworker`;
126123
if (!options.disableHashedFactorKey) options.disableHashedFactorKey = false;
127124
if (!options.hashedFactorNonce) options.hashedFactorNonce = options.web3AuthClientId;
125+
if (options.disableSessionManager === undefined) options.disableSessionManager = false;
128126

129127
this.options = options as Web3AuthOptionsWithDefaults;
130128

131129
this.currentStorage = new AsyncStorage(this._storageBaseKey, options.storage);
130+
131+
if (!options.disableSessionManager) {
132+
this.sessionManager = new SessionManager<SessionData>({
133+
sessionTime: options.sessionTime,
134+
});
135+
}
136+
137+
TorusUtils.setSessionTime(this.options.sessionTime);
132138
}
133139

134140
get tKey(): TKeyTSS {
@@ -270,13 +276,6 @@ export class Web3AuthMPCCoreKit implements ICoreKit {
270276

271277
this.ready = true;
272278

273-
// setup session Manager during init instead of async constructor
274-
const sessionId = await this.currentStorage.get<string>("sessionId");
275-
this.sessionManager = new SessionManager({
276-
sessionTime: this.options.sessionTime,
277-
sessionId,
278-
});
279-
280279
// try handle redirect flow if enabled and return(redirect) from oauth login
281280
if (
282281
params.handleRedirectResult &&
@@ -286,26 +285,31 @@ export class Web3AuthMPCCoreKit implements ICoreKit {
286285
// on failed redirect, instance is reseted.
287286
// skip check feature gating on redirection as it was check before login
288287
await this.handleRedirectResult();
288+
289+
// return early on successful redirect, the rest of the code will not be executed
290+
return;
291+
} else if (params.rehydrate && this.sessionManager) {
289292
// if not redirect flow try to rehydrate session if available
290-
} else if (params.rehydrate && this.sessionManager.sessionId) {
291-
// swallowed, should not throw on rehydrate timed out session
292-
const sessionResult = await this.sessionManager.authorizeSession().catch(async (err) => {
293-
log.error("rehydrate session error", err);
294-
});
293+
const sessionId = await this.currentStorage.get<string>("sessionId");
294+
if (sessionId) {
295+
this.sessionManager.sessionId = sessionId;
295296

296-
// try rehydrate session
297-
if (sessionResult) {
298-
await this.rehydrateSession(sessionResult);
299-
} else {
300-
// feature gating on no session rehydration
301-
await this.featureRequest();
302-
TorusUtils.setSessionTime(this.options.sessionTime);
297+
// swallowed, should not throw on rehydrate timed out session
298+
const sessionResult = await this.sessionManager.authorizeSession().catch(async (err) => {
299+
log.error("rehydrate session error", err);
300+
});
301+
302+
// try rehydrate session
303+
if (sessionResult) {
304+
await this.rehydrateSession(sessionResult);
305+
306+
// return early on success rehydration
307+
return;
308+
}
303309
}
304-
} else {
305-
// feature gating if not redirect flow or session rehydration
306-
await this.featureRequest();
307-
TorusUtils.setSessionTime(this.options.sessionTime);
308310
}
311+
// feature gating if not redirect flow or session rehydration
312+
await this.featureRequest();
309313
}
310314

311315
public async loginWithOAuth(params: OAuthLoginParams): Promise<void> {
@@ -697,7 +701,7 @@ export class Web3AuthMPCCoreKit implements ICoreKit {
697701
}
698702

699703
public async logout(): Promise<void> {
700-
if (this.sessionManager.sessionId) {
704+
if (this.sessionManager?.sessionId) {
701705
await this.sessionManager.invalidateSession();
702706
}
703707
// to accommodate async storage
@@ -1034,11 +1038,15 @@ export class Web3AuthMPCCoreKit implements ICoreKit {
10341038
userInfo: result.userInfo,
10351039
});
10361040
} catch (err) {
1037-
log.error("error trying to authorize session", err);
1041+
log.warn("failed to authorize session", err);
10381042
}
10391043
}
10401044

10411045
private async createSession() {
1046+
if (!this.sessionManager) {
1047+
throw new Error("sessionManager is not available");
1048+
}
1049+
10421050
try {
10431051
const sessionId = SessionManager.generateRandomSessionKey();
10441052
this.sessionManager.sessionId = sessionId;

tests/sessionTime.spec.ts

Lines changed: 61 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,13 @@ type TestVariable = {
1515
email: string;
1616
gated?: boolean;
1717
sessionTime?: number;
18+
disableSessionManager?: boolean;
1819
};
1920

2021
const defaultTestEmail = "testEmail1";
22+
23+
const isBasePlan = (id: string) => id === "BCriFlI9ihm81N-bc7x6N-xbqwBLuxfRDMmSH87spKH27QTNOPj1W9s2K3-mp9NzXuaRiqxvAGHyuGlXG5wLD1g";
24+
// BasePlan up to 1 day only
2125
const variable: TestVariable[] = [
2226
{ web3AuthNetwork: WEB3AUTH_NETWORK.DEVNET, uxMode: "nodejs", email: defaultTestEmail, web3ClientID: "torus-key-test", sessionTime: 3600 },
2327
{
@@ -34,46 +38,78 @@ const variable: TestVariable[] = [
3438
web3ClientID: "BCriFlI9ihm81N-bc7x6N-xbqwBLuxfRDMmSH87spKH27QTNOPj1W9s2K3-mp9NzXuaRiqxvAGHyuGlXG5wLD1g",
3539
sessionTime: 172800,
3640
},
41+
{
42+
web3AuthNetwork: WEB3AUTH_NETWORK.MAINNET,
43+
uxMode: "nodejs",
44+
email: defaultTestEmail,
45+
web3ClientID: "BJ57yveG_XBLqZUpjtJCnJMrord0AaXpd_9OSy4HzkxpnpPn6Co73h-vR6GEI1VogtW4yMHq13GNPKmVpliFXY0",
46+
sessionTime: 7200,
47+
disableSessionManager : false
48+
},
49+
50+
{
51+
web3AuthNetwork: WEB3AUTH_NETWORK.MAINNET,
52+
uxMode: "nodejs",
53+
email: defaultTestEmail,
54+
web3ClientID: "BJ57yveG_XBLqZUpjtJCnJMrord0AaXpd_9OSy4HzkxpnpPn6Co73h-vR6GEI1VogtW4yMHq13GNPKmVpliFXY0",
55+
sessionTime: 7200,
56+
disableSessionManager : true
57+
},
3758
];
3859

3960
const storageInstance = new MemoryStorage();
40-
variable.forEach((testVariable) => {
41-
const { web3AuthNetwork, uxMode, manualSync, email, web3ClientID: web3AuthClientId, sessionTime } = variable[0];
42-
const coreKitInstance = new Web3AuthMPCCoreKit({
43-
web3AuthClientId,
44-
web3AuthNetwork,
45-
baseUrl: "http://localhost:3000",
46-
uxMode,
47-
tssLib,
48-
storage: storageInstance,
49-
manualSync,
50-
sessionTime,
51-
});
61+
variable.forEach(async (testVariable) => {
62+
const { web3AuthNetwork, uxMode, manualSync, email, web3ClientID: web3AuthClientId, sessionTime, disableSessionManager } = testVariable;
63+
64+
65+
await test(`#Variable SessionTime test : ${JSON.stringify({ sessionTime: testVariable.sessionTime })} - disableSessionManager: ${disableSessionManager} client_id: ${web3AuthClientId}`, async (t) => {
66+
const coreKitInstance = new Web3AuthMPCCoreKit({
67+
web3AuthClientId,
68+
web3AuthNetwork,
69+
baseUrl: "http://localhost:3000",
70+
uxMode,
71+
tssLib,
72+
storage: storageInstance,
73+
manualSync,
74+
sessionTime,
75+
disableSessionManager,
76+
});
5277

53-
test(`#Variable SessionTime test : ${JSON.stringify({ sessionTime: testVariable.sessionTime })}`, async (t) => {
5478
async function beforeTest() {
5579
if (coreKitInstance.status === COREKIT_STATUS.INITIALIZED) await criticalResetAccount(coreKitInstance);
5680
}
5781

5882
t.after(async function () {
5983
// after all test tear down
60-
await coreKitInstance.logout();
84+
if (!isBasePlan(web3AuthClientId)) await coreKitInstance.logout();
6185
});
6286

6387
await beforeTest();
6488

65-
await t.test("`sessionTime` should be equal to `sessionTokenDuration` from #Login", async function () {
89+
await t.test("`sessionTime` should be equal to `sessionTokenDuration` from #Login", async function (t) {
6690
// mocklogin
6791
const { idToken, parsedToken } = await mockLogin(email);
6892

69-
await coreKitInstance.init({ handleRedirectResult: false });
93+
await coreKitInstance.init({ handleRedirectResult: false }).catch((err) => {
94+
if ( !isBasePlan(testVariable.web3ClientID) ) {
95+
throw err;
96+
}
97+
});
7098

7199
await coreKitInstance.loginWithJWT({
72100
verifier: "torus-test-health",
73101
verifierId: parsedToken.email,
74102
idToken,
103+
}).catch((err) => {
104+
if ( !isBasePlan(testVariable.web3ClientID) ) {
105+
throw err;
106+
}
75107
});
76-
108+
if ( !isBasePlan(testVariable.web3ClientID) ) {
109+
// skip remaining test if is BasePlan
110+
return;
111+
}
112+
77113
coreKitInstance.signatures.forEach((sig) => {
78114
const parsedSig = JSON.parse(sig);
79115
const parsedSigData = JSON.parse(atob(parsedSig.data));
@@ -84,6 +120,14 @@ variable.forEach((testVariable) => {
84120
const sessionTimeDiff = Math.abs(sessionTokenDuration - sessionTime);
85121
assert.strictEqual(sessionTimeDiff <= 3, true);
86122
});
123+
124+
if (disableSessionManager) {
125+
assert.equal(coreKitInstance.sessionId , undefined);
126+
} else {
127+
assert.notEqual(coreKitInstance.sessionId , undefined);
128+
}
87129
});
130+
131+
88132
});
89133
});

0 commit comments

Comments
 (0)