-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathauth.ts
More file actions
1161 lines (1060 loc) · 33.6 KB
/
Copy pathauth.ts
File metadata and controls
1161 lines (1060 loc) · 33.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";
import {
type IPowerManager,
POWER_MANAGER_SERVICE,
} from "@posthog/platform/power-manager";
import {
type BackoffOptions,
type CloudRegion,
getCloudUrlFromRegion,
NotAuthenticatedError,
OAUTH_SCOPE_VERSION,
sleepWithBackoff,
TypedEventEmitter,
withTimeout,
} from "@posthog/shared";
import { inject, injectable, postConstruct, preDestroy } from "inversify";
import {
AUTH_CONNECTIVITY,
AUTH_OAUTH_FLOW_SERVICE,
AUTH_PREFERENCE_STORE,
AUTH_SESSION_STORE,
AUTH_TOKEN_CIPHER,
AUTH_TOKEN_OVERRIDE,
type IAuthConnectivity,
type IAuthOAuthFlowService,
type IAuthPreferenceStore,
type IAuthSessionStore,
type IAuthTokenCipher,
} from "./identifiers";
import {
AuthServiceEvent,
type AuthServiceEvents,
type AuthState,
type AuthTokenResponse,
findOrgForProject,
flattenProjectIds,
type OrgProjects,
type OrgProjectsMap,
pickInitialProjectId,
type ValidAccessTokenOutput,
} from "./schemas";
const TOKEN_EXPIRY_SKEW_MS = 60_000;
const AUTH_FETCH_TIMEOUT_MS = 30_000;
const AUTH_BOOTSTRAP_DEADLINE_MS = 20_000;
type FetchLike = (
input: string | Request,
init?: RequestInit,
) => Promise<Response>;
interface InMemorySession {
accountKey: string | null;
accessToken: string;
accessTokenExpiresAt: number;
refreshToken: string;
cloudRegion: CloudRegion;
orgProjectsMap: OrgProjectsMap;
currentOrgId: string | null;
currentProjectId: number | null;
orgProjectsIncomplete: boolean;
}
interface StoredSessionInput {
refreshToken: string;
cloudRegion: CloudRegion;
selectedProjectId: number | null;
}
interface TokenResponseOptions {
cloudRegion: CloudRegion;
selectedProjectId: number | null;
}
@injectable()
export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
private state: AuthState = {
status: "anonymous",
bootstrapComplete: false,
accountKey: null,
cloudRegion: null,
orgProjectsMap: {},
currentOrgId: null,
currentProjectId: null,
hasCodeAccess: null,
needsScopeReauth: false,
};
private session: InMemorySession | null = null;
private initializePromise: Promise<void> | null = null;
private refreshPromise: Promise<InMemorySession> | null = null;
constructor(
@inject(AUTH_PREFERENCE_STORE)
private readonly authPreference: IAuthPreferenceStore,
@inject(AUTH_SESSION_STORE)
private readonly authSession: IAuthSessionStore,
@inject(AUTH_OAUTH_FLOW_SERVICE)
private readonly oauthFlow: IAuthOAuthFlowService,
@inject(AUTH_CONNECTIVITY)
private readonly connectivity: IAuthConnectivity,
@inject(AUTH_TOKEN_CIPHER)
private readonly cipher: IAuthTokenCipher,
@inject(POWER_MANAGER_SERVICE)
private readonly powerManager: IPowerManager,
@inject(ROOT_LOGGER)
private readonly logger: RootLogger,
@inject(AUTH_TOKEN_OVERRIDE)
private readonly tokenOverride: string | null,
) {
super();
}
async initialize(): Promise<void> {
if (this.initializePromise) {
return this.initializePromise;
}
this.initializePromise = this.doInitialize();
return this.initializePromise;
}
getState(): AuthState {
return { ...this.state };
}
async login(region: CloudRegion): Promise<AuthState> {
await this.authenticateWithFlow(
() => this.oauthFlow.startFlow(region),
region,
"OAuth flow failed",
);
return this.getState();
}
async signup(region: CloudRegion): Promise<AuthState> {
await this.authenticateWithFlow(
() => this.oauthFlow.startSignupFlow(region),
region,
"Signup failed",
);
return this.getState();
}
async getValidAccessToken(): Promise<ValidAccessTokenOutput> {
const override = this.tokenOverride;
if (override) {
await this.initialize();
const region = this.session?.cloudRegion ?? "us";
return {
accessToken: override,
apiHost: getCloudUrlFromRegion(region),
};
}
await this.initialize();
const session = await this.ensureValidSession();
return {
accessToken: session.accessToken,
apiHost: getCloudUrlFromRegion(session.cloudRegion),
};
}
async refreshAccessToken(): Promise<ValidAccessTokenOutput> {
const override = this.tokenOverride;
if (override) {
await this.initialize();
const region = this.session?.cloudRegion ?? "us";
return {
accessToken: override,
apiHost: getCloudUrlFromRegion(region),
};
}
await this.initialize();
const session = await this.ensureValidSession(true);
return {
accessToken: session.accessToken,
apiHost: getCloudUrlFromRegion(session.cloudRegion),
};
}
async invalidateAccessTokenForTest(): Promise<void> {
await this.initialize();
if (!this.session) {
return;
}
this.session = {
...this.session,
accessToken: `${this.session.accessToken}_invalid`,
accessTokenExpiresAt: Date.now() + 5 * 60 * 1000,
};
}
async authenticatedFetch(
fetchImpl: FetchLike,
input: string | Request,
init: RequestInit = {},
): Promise<Response> {
const initialAuth = await this.getValidAccessToken();
let response = await this.executeAuthenticatedFetch(
fetchImpl,
input,
init,
initialAuth.accessToken,
);
if (response.status === 401 || response.status === 403) {
const refreshedAuth = await this.refreshAccessToken();
response = await this.executeAuthenticatedFetch(
fetchImpl,
input,
init,
refreshedAuth.accessToken,
);
}
return response;
}
async redeemInviteCode(code: string): Promise<AuthState> {
const { apiHost } = await this.getValidAccessToken();
const response = await this.authenticatedFetch(
fetch,
`${apiHost}/api/code/invites/redeem/`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ code }),
},
);
const data = (await response.json().catch(() => ({}))) as {
success?: boolean;
error?: string;
};
if (!response.ok || !data.success) {
throw new Error(data.error || "Failed to redeem invite code");
}
this.updateState({ hasCodeAccess: true });
return this.getState();
}
async selectProject(projectId: number): Promise<AuthState> {
await this.initialize();
const session = this.requireSession();
if (!flattenProjectIds(session.orgProjectsMap).includes(projectId)) {
throw new Error("Invalid project selection");
}
const newOrgId =
findOrgForProject(
session.orgProjectsMap,
projectId,
session.currentOrgId,
) ?? session.currentOrgId;
const orgProjectsMap =
newOrgId && newOrgId !== session.currentOrgId
? await this.applyOrgChange(session, newOrgId)
: session.orgProjectsMap;
this.commitSessionState(session, {
orgProjectsMap,
currentOrgId: newOrgId,
currentProjectId: projectId,
});
return this.getState();
}
async switchOrg(orgId: string): Promise<AuthState> {
await this.initialize();
const session = this.requireSession();
if (!session.orgProjectsMap[orgId]) {
throw new Error("Invalid organization");
}
const orgProjectsMap = await this.applyOrgChange(session, orgId);
const currentProjectId = this.pickProjectForOrg(
session,
orgProjectsMap,
orgId,
);
this.commitSessionState(session, {
orgProjectsMap,
currentOrgId: orgId,
currentProjectId,
});
return this.getState();
}
private async applyOrgChange(
session: InMemorySession,
orgId: string,
): Promise<OrgProjectsMap> {
await this.patchCurrentOrganization(orgId);
const refreshedProjects = await this.fetchOrgProjects(
session.accessToken,
session.cloudRegion,
orgId,
);
if (!refreshedProjects) {
return session.orgProjectsMap;
}
return {
...session.orgProjectsMap,
[orgId]: {
orgName: session.orgProjectsMap[orgId]?.orgName ?? "(unknown)",
projects: refreshedProjects,
},
};
}
private pickProjectForOrg(
session: InMemorySession,
orgProjectsMap: OrgProjectsMap,
orgId: string,
): number | null {
const orgProjects = orgProjectsMap[orgId]?.projects ?? [];
const preferredProjectId = session.accountKey
? (this.authPreference.getOrgProject(
session.accountKey,
session.cloudRegion,
orgId,
)?.lastSelectedProjectId ?? null)
: null;
if (
preferredProjectId &&
orgProjects.some((p) => p.id === preferredProjectId)
) {
return preferredProjectId;
}
return orgProjects[0]?.id ?? null;
}
private commitSessionState(
prevSession: InMemorySession,
next: {
orgProjectsMap: OrgProjectsMap;
currentOrgId: string | null;
currentProjectId: number | null;
},
): void {
this.session = {
...prevSession,
orgProjectsMap: next.orgProjectsMap,
currentOrgId: next.currentOrgId,
currentProjectId: next.currentProjectId,
orgProjectsIncomplete: false,
};
this.persistProjectPreference(this.session);
this.persistSession({
refreshToken: this.session.refreshToken,
cloudRegion: this.session.cloudRegion,
selectedProjectId: next.currentProjectId,
});
this.updateState({
orgProjectsMap: next.orgProjectsMap,
currentOrgId: next.currentOrgId,
currentProjectId: next.currentProjectId,
});
}
private async patchCurrentOrganization(orgId: string): Promise<void> {
const { apiHost } = await this.getValidAccessToken();
const response = await this.authenticatedFetch(
fetch,
`${apiHost}/api/users/@me/`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ set_current_organization: orgId }),
},
);
if (!response.ok) {
throw new Error(`Failed to switch organization: ${response.statusText}`);
}
}
async logout(): Promise<AuthState> {
const { cloudRegion, currentProjectId } = this.state;
this.authSession.clearCurrent();
this.session = null;
this.setAnonymousState({ cloudRegion, currentProjectId });
return this.getState();
}
private executeAuthenticatedFetch(
fetchImpl: FetchLike,
input: string | Request,
init: RequestInit,
accessToken: string,
): Promise<Response> {
const headers = new Headers(init.headers);
headers.set("authorization", `Bearer ${accessToken}`);
return fetchImpl(input, {
...init,
headers,
signal: init.signal ?? AbortSignal.timeout(AUTH_FETCH_TIMEOUT_MS),
});
}
private async doInitialize(): Promise<void> {
const stored = this.authSession.getCurrent();
if (!stored) {
this.setAnonymousState({ bootstrapComplete: true });
return;
}
if (stored.scopeVersion < OAUTH_SCOPE_VERSION) {
this.session = null;
this.setAnonymousState({
bootstrapComplete: true,
cloudRegion: stored.cloudRegion,
currentProjectId: stored.selectedProjectId,
needsScopeReauth: true,
});
return;
}
const storedSession = this.resolveStoredSession();
if (!storedSession) {
this.logger.warn("Stored auth session could not be decrypted");
this.authSession.clearCurrent();
this.setAnonymousState({ bootstrapComplete: true });
return;
}
this.setRestoringState(storedSession, false);
try {
const restore = this.ensureValidSession().then(() => undefined);
const outcome = await withTimeout(restore, AUTH_BOOTSTRAP_DEADLINE_MS);
if (outcome.result === "timeout") {
this.logger.warn(
"Auth bootstrap exceeded deadline; completing bootstrap while the restore continues in the background",
);
// A stored session that is merely slow to refresh must not strand the
// renderer on the boot screen. Complete bootstrap but stay "restoring"
// so a late success still upgrades and consumers don't treat the delay
// as a logout.
this.completeBootstrapWhileRestoring(storedSession);
restore.catch((error) => {
this.logger.warn("Background auth restore failed after deadline", {
error,
});
this.handleStoredSessionRestoreFailure(storedSession);
});
}
} catch (error) {
this.logger.warn("Failed to restore stored auth session", { error });
this.handleStoredSessionRestoreFailure(storedSession);
}
}
private setRestoringState(
storedSession: StoredSessionInput,
bootstrapComplete: boolean,
): void {
this.session = null;
this.updateState({
status: "restoring",
bootstrapComplete,
accountKey: null,
cloudRegion: storedSession.cloudRegion,
orgProjectsMap: {},
currentOrgId: null,
currentProjectId: storedSession.selectedProjectId,
hasCodeAccess: null,
needsScopeReauth: false,
});
}
private completeBootstrapWhileRestoring(
storedSession: StoredSessionInput,
): void {
// Only meaningful while the stored session is still on disk: a rejected
// refresh token clears it and publishes a real anonymous state instead.
// Transient/offline failures keep the session, so stay "restoring" (no
// logout side effects) but flip bootstrapComplete so the renderer leaves
// the boot gate rather than stranding on the loading screen.
if (this.authSession.getCurrent()) {
this.setRestoringState(storedSession, true);
}
}
private handleStoredSessionRestoreFailure(
storedSession: StoredSessionInput,
): void {
this.completeBootstrapWhileRestoring(storedSession);
}
private async ensureValidSession(
forceRefresh = false,
): Promise<InMemorySession> {
if (
this.session &&
!forceRefresh &&
!this.isSessionExpiring(this.session)
) {
return this.session;
}
if (this.refreshPromise) {
return this.refreshPromise;
}
const sessionInput = this.getSessionInputForRefresh();
const refreshAndSync = async (): Promise<InMemorySession> => {
const session = await this.refreshSession(sessionInput);
await this.syncAuthenticatedSession(session);
return session;
};
this.refreshPromise = refreshAndSync().finally(() => {
this.refreshPromise = null;
});
return this.refreshPromise;
}
private getSessionInputForRefresh(): StoredSessionInput {
if (this.session) {
return {
refreshToken: this.session.refreshToken,
cloudRegion: this.session.cloudRegion,
selectedProjectId: this.session.currentProjectId,
};
}
const storedSession = this.resolveStoredSession();
if (!storedSession) {
throw new NotAuthenticatedError();
}
return storedSession;
}
private async refreshSession(
input: StoredSessionInput,
): Promise<InMemorySession> {
if (!this.connectivity.getStatus().isOnline) {
throw new Error("Offline");
}
let lastError = "Token refresh failed";
for (
let attempt = 0;
attempt < AuthService.REFRESH_MAX_ATTEMPTS;
attempt++
) {
const result = await this.oauthFlow.refreshToken(
input.refreshToken,
input.cloudRegion,
);
if (result.success && result.data) {
return await this.createSessionFromTokenResponse(result.data, input);
}
lastError = result.error || "Token refresh failed";
if (result.errorCode === "auth_error") {
this.logger.warn("Refresh token rejected by server, forcing logout");
this.authSession.clearCurrent();
this.session = null;
this.setAnonymousState({
cloudRegion: input.cloudRegion,
currentProjectId: input.selectedProjectId,
});
throw new Error(lastError);
}
const isRetryable =
result.errorCode === "network_error" ||
result.errorCode === "server_error";
if (!isRetryable) {
throw new Error(lastError);
}
const isLastAttempt = attempt === AuthService.REFRESH_MAX_ATTEMPTS - 1;
if (isLastAttempt) break;
this.logger.warn("Transient refresh failure, retrying", {
attempt,
errorCode: result.errorCode,
});
await sleepWithBackoff(attempt, AuthService.REFRESH_BACKOFF);
}
throw new Error(lastError);
}
private async createSessionFromTokenResponse(
tokenResponse: AuthTokenResponse,
options: TokenResponseOptions,
): Promise<InMemorySession> {
const scopedOrgIds = tokenResponse.scoped_organizations ?? [];
const { accountKey, currentOrgId } = await this.fetchUserContext(
tokenResponse.access_token,
options.cloudRegion,
);
const { map: orgProjectsMap, incomplete: orgProjectsIncomplete } =
await this.buildOrgProjectsMap(
tokenResponse.access_token,
options.cloudRegion,
scopedOrgIds,
this.session?.orgProjectsMap ?? {},
);
const lastPrefs = accountKey
? this.authPreference.get(accountKey, options.cloudRegion)
: null;
const currentProjectId = pickInitialProjectId({
orgProjectsMap,
currentOrgId,
preferredProjectId:
options.selectedProjectId ?? lastPrefs?.lastSelectedProjectId ?? null,
lastSelectedOrgId: lastPrefs?.lastSelectedOrgId ?? null,
});
const session: InMemorySession = {
accountKey,
accessToken: tokenResponse.access_token,
accessTokenExpiresAt: Date.now() + tokenResponse.expires_in * 1000,
refreshToken: tokenResponse.refresh_token,
cloudRegion: options.cloudRegion,
orgProjectsMap,
currentOrgId,
currentProjectId,
orgProjectsIncomplete,
};
return session;
}
private async buildOrgProjectsMap(
accessToken: string,
cloudRegion: CloudRegion,
orgIds: string[],
previousMap: OrgProjectsMap,
): Promise<{ map: OrgProjectsMap; incomplete: boolean }> {
let incomplete = false;
const entries = await Promise.all(
orgIds.map(async (orgId): Promise<[string, OrgProjects]> => {
const { org, transient } = await this.fetchOrgWithProjects(
accessToken,
cloudRegion,
orgId,
);
if (org) {
return [orgId, org];
}
const fallback = previousMap[orgId] ?? {
orgName: "(unknown)",
projects: [],
};
if (transient && fallback.projects.length === 0) {
incomplete = true;
}
return [orgId, fallback];
}),
);
return { map: Object.fromEntries(entries), incomplete };
}
private async fetchOrgProjects(
accessToken: string,
cloudRegion: CloudRegion,
orgId: string,
): Promise<{ id: number; name: string }[] | null> {
const { org } = await this.fetchOrgWithProjects(
accessToken,
cloudRegion,
orgId,
);
return org?.projects ?? null;
}
private async fetchOrgWithProjects(
accessToken: string,
cloudRegion: CloudRegion,
orgId: string,
): Promise<{ org: OrgProjects | null; transient: boolean }> {
for (
let attempt = 0;
attempt < AuthService.ORG_FETCH_MAX_ATTEMPTS;
attempt++
) {
const result = await this.fetchOrgWithProjectsOnce(
accessToken,
cloudRegion,
orgId,
);
if (result.ok) {
return { org: result.data, transient: false };
}
if (!result.retryable) {
return { org: null, transient: false };
}
const isLastAttempt = attempt === AuthService.ORG_FETCH_MAX_ATTEMPTS - 1;
if (isLastAttempt) {
break;
}
this.logger.warn("Transient org fetch failure, retrying", {
orgId,
attempt,
});
await sleepWithBackoff(attempt, AuthService.REFRESH_BACKOFF);
}
return { org: null, transient: true };
}
private async fetchOrgWithProjectsOnce(
accessToken: string,
cloudRegion: CloudRegion,
orgId: string,
): Promise<
{ ok: true; data: OrgProjects } | { ok: false; retryable: boolean }
> {
const apiHost = getCloudUrlFromRegion(cloudRegion);
try {
const res = await this.executeAuthenticatedFetch(
fetch,
`${apiHost}/api/organizations/${orgId}/`,
{},
accessToken,
);
if (!res.ok) {
return { ok: false, retryable: res.status >= 500 };
}
const raw = (await res.json().catch(() => null)) as {
name?: unknown;
teams?: unknown;
} | null;
const orgName =
typeof raw?.name === "string" && raw.name.length > 0
? raw.name
: "(unknown)";
const teams = Array.isArray(raw?.teams) ? raw.teams : [];
const projects = teams
.map((t) => t as { id?: unknown; name?: unknown })
.filter((t) => typeof t.id === "number" && typeof t.name === "string")
.map((t) => ({ id: t.id as number, name: t.name as string }));
return { ok: true, data: { orgName, projects } };
} catch (error) {
this.logger.warn("Failed to fetch org with projects", { orgId, error });
return { ok: false, retryable: true };
}
}
private async authenticateWithFlow(
runFlow: () => Promise<{
success: boolean;
data?: AuthTokenResponse;
error?: string;
}>,
region: CloudRegion,
fallbackError: string,
): Promise<void> {
const result = await runFlow();
if (!result.success || !result.data) {
throw new Error(result.error || fallbackError);
}
const session = await this.createSessionFromTokenResponse(result.data, {
cloudRegion: region,
selectedProjectId: this.state.currentProjectId,
});
await this.syncAuthenticatedSession(session);
}
private async syncAuthenticatedSession(
session: InMemorySession,
): Promise<void> {
this.persistProjectPreference(session);
this.persistSession({
refreshToken: session.refreshToken,
cloudRegion: session.cloudRegion,
selectedProjectId: session.currentProjectId,
});
this.session = session;
this.updateState({
status: "authenticated",
bootstrapComplete: true,
accountKey: session.accountKey,
cloudRegion: session.cloudRegion,
orgProjectsMap: session.orgProjectsMap,
currentOrgId: session.currentOrgId,
currentProjectId: session.currentProjectId,
needsScopeReauth: false,
});
await this.updateCodeAccessFromSession();
if (session.orgProjectsIncomplete) {
void this.refreshOrgProjects();
}
}
private persistSession(input: {
refreshToken: string;
cloudRegion: CloudRegion;
selectedProjectId: number | null;
}): void {
const priorSelected =
this.authSession.getCurrent()?.selectedProjectId ?? null;
this.authSession.saveCurrent({
refreshTokenEncrypted: this.cipher.encrypt(input.refreshToken),
cloudRegion: input.cloudRegion,
selectedProjectId: input.selectedProjectId ?? priorSelected,
scopeVersion: OAUTH_SCOPE_VERSION,
});
}
private persistProjectPreference(session: InMemorySession): void {
if (!session.accountKey || session.currentProjectId === null) {
return;
}
this.authPreference.save({
accountKey: session.accountKey,
cloudRegion: session.cloudRegion,
lastSelectedProjectId: session.currentProjectId,
lastSelectedOrgId: session.currentOrgId,
});
const orgIdForProject = session.currentProjectId
? findOrgForProject(
session.orgProjectsMap,
session.currentProjectId,
session.currentOrgId,
)
: null;
if (orgIdForProject && session.currentProjectId) {
this.authPreference.saveOrgProject({
accountKey: session.accountKey,
cloudRegion: session.cloudRegion,
orgId: orgIdForProject,
lastSelectedProjectId: session.currentProjectId,
});
}
}
private isSessionExpiring(session: InMemorySession): boolean {
return session.accessTokenExpiresAt - Date.now() <= TOKEN_EXPIRY_SKEW_MS;
}
private async fetchUserContext(
accessToken: string,
cloudRegion: CloudRegion,
): Promise<{ accountKey: string | null; currentOrgId: string | null }> {
try {
const response = await this.executeAuthenticatedFetch(
fetch,
`${getCloudUrlFromRegion(cloudRegion)}/api/users/@me/`,
{},
accessToken,
);
if (!response.ok) {
return { accountKey: null, currentOrgId: null };
}
const data = (await response.json().catch(() => ({}))) as {
uuid?: unknown;
distinct_id?: unknown;
email?: unknown;
organization?: { id?: unknown } | null;
};
let accountKey: string | null = null;
if (typeof data.uuid === "string" && data.uuid.length > 0) {
accountKey = data.uuid;
} else if (
typeof data.distinct_id === "string" &&
data.distinct_id.length > 0
) {
accountKey = data.distinct_id;
} else if (typeof data.email === "string" && data.email.length > 0) {
accountKey = data.email;
}
const orgId = data.organization?.id;
const currentOrgId =
typeof orgId === "string" && orgId.length > 0 ? orgId : null;
return { accountKey, currentOrgId };
} catch (error) {
this.logger.warn("Failed to resolve user context", { error });
return { accountKey: null, currentOrgId: null };
}
}
private requireSession(): InMemorySession {
if (!this.session) {
throw new NotAuthenticatedError();
}
return this.session;
}
private setAnonymousState(
partial: Pick<
Partial<AuthState>,
| "bootstrapComplete"
| "cloudRegion"
| "currentProjectId"
| "needsScopeReauth"
> = {},
): void {
this.updateState({
status: "anonymous",
bootstrapComplete: partial.bootstrapComplete ?? true,
accountKey: null,
cloudRegion: partial.cloudRegion ?? null,
orgProjectsMap: {},
currentOrgId: null,
currentProjectId: partial.currentProjectId ?? null,
hasCodeAccess: null,
needsScopeReauth: partial.needsScopeReauth ?? false,
});
}
private async updateCodeAccessFromSession(): Promise<void> {
if (!this.session) {
this.updateState({ hasCodeAccess: null });
return;
}
const hasAccess = await this.checkCodeAccess(this.session);
if (hasAccess !== null) {
this.updateState({ hasCodeAccess: hasAccess });
return;
}
// Indeterminate: a transient/unauthorized failure isn't proof the invite
// was revoked, so keep the prior value and let the next sync re-check.
this.logger.warn(
"Code access check was inconclusive; keeping previous value",
{ hasCodeAccess: this.state.hasCodeAccess },
);
}
/**
* Resolves Code invite access. Only a 2xx response with an explicit boolean
* `has_access` is authoritative; everything else (offline, network error,
* non-2xx, malformed body) is indeterminate, retried with backoff, then
* returned as `null` so the caller keeps the prior value. Uses the synced
* token directly rather than `authenticatedFetch`, which would re-enter the
* refresh flow this runs inside and deadlock.
*/
private async checkCodeAccess(
session: InMemorySession,
): Promise<boolean | null> {
const url = `${getCloudUrlFromRegion(session.cloudRegion)}/api/code/invites/check-access/`;
for (
let attempt = 0;
attempt < AuthService.CODE_ACCESS_MAX_ATTEMPTS;
attempt++
) {
if (!this.connectivity.getStatus().isOnline) {
return null;
}
try {
const response = await this.executeAuthenticatedFetch(
fetch,
url,
{},
session.accessToken,
);
if (response.ok) {
const data = (await response.json().catch(() => null)) as {
has_access?: unknown;
} | null;
if (data && typeof data.has_access === "boolean") {
return data.has_access;
}
this.logger.warn("Code access response missing has_access flag", {
status: response.status,
});
} else {
this.logger.warn("Code access check returned non-OK status", {
status: response.status,
});
}
} catch (error) {
this.logger.warn("Code access check request failed", {
error,
attempt,
});
}
const isLastAttempt =
attempt === AuthService.CODE_ACCESS_MAX_ATTEMPTS - 1;
if (isLastAttempt) break;
await sleepWithBackoff(attempt, AuthService.REFRESH_BACKOFF);
}
return null;
}
private static readonly REFRESH_MAX_ATTEMPTS = 3;
private static readonly ORG_FETCH_MAX_ATTEMPTS = 3;
private static readonly CODE_ACCESS_MAX_ATTEMPTS = 3;
private static readonly ORG_RECOVERY_MAX_ATTEMPTS = 5;
private static readonly REFRESH_BACKOFF: BackoffOptions = {
initialDelayMs: 1_000,
maxDelayMs: 5_000,
multiplier: 2,
};