Skip to content

Commit 37ada3e

Browse files
committed
Changes to state management
1 parent 909de52 commit 37ada3e

File tree

1 file changed

+9
-12
lines changed

1 file changed

+9
-12
lines changed

hono/auth/MsApiClient.ts

+9-12
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,15 @@ type Secrets = {
1010

1111
// Todo: custom errors
1212

13-
// We only want to ensure the request originated from our website,
14-
// hence no identifiable information. An in memory array as your request
15-
// should be done pretty fast + we have a maxStates variable.
16-
const states: string[] = [];
1713

1814
export class MsAuthClient {
1915
msAuthEndpoint: string;
2016
scopeUrls: string[];
17+
statesTail = -1;
18+
// We only want to ensure the request originated from our website,
19+
// hence no identifiable information. An in memory array as your request
20+
// should be done pretty fast + we have a maxStates variable.
21+
states = [] as (string | undefined)[];
2122

2223
public constructor(
2324
private scopes: string[],
@@ -33,12 +34,8 @@ export class MsAuthClient {
3334

3435
public getRedirectUrl(state?: string): string {
3536
const _state = state || crypto.randomUUID();
36-
const noStates = states.push(_state);
37-
// Flush the states for performance
38-
if (noStates > this.maxStates) {
39-
states.length = 1;
40-
states[0] = _state;
41-
}
37+
this.statesTail = (this.statesTail + 1) % this.maxStates;
38+
this.states[this.statesTail] = _state;
4239

4340
const url = buildUrl(this.msAuthEndpoint, {
4441
path: '/authorize',
@@ -57,11 +54,11 @@ export class MsAuthClient {
5754
}
5855

5956
public async verifyAndConsumeCode(code: string, state: string) {
60-
const index = states.indexOf(state);
57+
const index = this.states.indexOf(state);
6158
if (index == -1) {
6259
throw new Error(`Failed to verify code: Mismatched state.`);
6360
}
64-
states.splice(index, 1);
61+
this.states[index] = undefined;
6562

6663
const req = await fetch(`${this.msAuthEndpoint}/token`, {
6764
method: 'POST',

0 commit comments

Comments
 (0)