Elffuss BraidHub

kikocis/continue public

main · 4.8 KiBRawPermalink
1import {
2 AuthenticatedConfig,
3 login as doLogin,
4 logout as doLogout,
5 ensureOrganization,
6 isAuthenticated,
7 listUserOrganizations,
8 loadAuthConfig,
9 saveAuthConfig,
10} from "../auth/workos.js";
11import { logger } from "../util/logger.js";
12
13import { BaseService } from "./BaseService.js";
14import { AuthServiceState } from "./types.js";
15
16/**
17 * Service for managing authentication state and operations
18 * Encapsulates all auth logic and provides reactive updates
19 */
20export class AuthService extends BaseService<AuthServiceState> {
21 constructor() {
22 super("AuthService", {
23 authConfig: null,
24 isAuthenticated: false,
25 });
26 }
27
28 /**
29 * Initialize the auth service by loading current config
30 */
31 async doInitialize(): Promise<AuthServiceState> {
32 const authConfig = loadAuthConfig();
33 const authenticated = isAuthenticated();
34
35 const state: AuthServiceState = {
36 authConfig,
37 isAuthenticated: authenticated,
38 organizationId: authConfig?.organizationId || undefined,
39 };
40
41 logger.debug("AuthService initialized", {
42 authenticated,
43 hasConfig: !!authConfig,
44 orgId: state.organizationId,
45 });
46
47 return state;
48 }
49
50 /**
51 * Perform login flow
52 */
53 async login(): Promise<AuthServiceState> {
54 logger.debug("Starting login flow");
55
56 try {
57 const newAuthConfig = await doLogin();
58
59 this.setState({
60 authConfig: newAuthConfig,
61 isAuthenticated: true,
62 organizationId: newAuthConfig?.organizationId || undefined,
63 });
64
65 logger.debug("Login successful", {
66 orgId: this.currentState.organizationId,
67 });
68
69 return this.getState();
70 } catch (error: any) {
71 logger.error("Login failed:", error);
72 this.emit("error", error);
73 throw error;
74 }
75 }
76
77 /**
78 * Perform logout
79 */
80 async logout(): Promise<AuthServiceState> {
81 logger.debug("Logging out");
82
83 doLogout();
84
85 this.setState({
86 authConfig: null,
87 isAuthenticated: false,
88 organizationId: undefined,
89 });
90
91 logger.debug("Logout complete");
92 return this.getState();
93 }
94
95 /**
96 * Ensure organization is selected, prompting if necessary
97 */
98 async ensureOrganization(
99 isHeadless: boolean = false,
100 cliOrganizationSlug?: string,
101 ): Promise<AuthServiceState> {
102 if (!this.currentState.authConfig) {
103 throw new Error("Not authenticated - cannot ensure organization");
104 }
105
106 logger.debug("Ensuring organization is selected", {
107 currentOrgId: this.currentState.organizationId,
108 isHeadless,
109 cliOrganizationSlug,
110 });
111
112 const updatedConfig = await ensureOrganization(
113 this.currentState.authConfig,
114 isHeadless,
115 cliOrganizationSlug,
116 );
117
118 this.setState({
119 authConfig: updatedConfig,
120 isAuthenticated: true,
121 organizationId: updatedConfig?.organizationId || undefined,
122 });
123
124 logger.debug("Organization ensured", {
125 orgId: this.currentState.organizationId,
126 });
127
128 return this.getState();
129 }
130
131 /**
132 * Switch to a different organization
133 */
134 async switchOrganization(
135 organizationId: string | null,
136 ): Promise<AuthServiceState> {
137 if (
138 !this.currentState.authConfig ||
139 !("userId" in this.currentState.authConfig)
140 ) {
141 throw new Error(
142 "Not authenticated with file-based auth - cannot switch organizations",
143 );
144 }
145
146 logger.debug("Switching organization", {
147 from: this.currentState.organizationId,
148 to: organizationId,
149 });
150
151 const authenticatedConfig = this.currentState
152 .authConfig as AuthenticatedConfig;
153
154 const updatedConfig: AuthenticatedConfig = {
155 ...authenticatedConfig,
156 organizationId,
157 };
158
159 saveAuthConfig(updatedConfig);
160
161 this.setState({
162 authConfig: updatedConfig,
163 isAuthenticated: true,
164 organizationId: organizationId || undefined,
165 });
166
167 logger.debug("Organization switched", {
168 newOrgId: this.currentState.organizationId,
169 });
170
171 return this.getState();
172 }
173
174 /**
175 * Get available organizations for the current user
176 */
177 async getAvailableOrganizations(): Promise<
178 { id: string; name: string }[] | null
179 > {
180 if (!this.currentState.isAuthenticated) {
181 return null;
182 }
183
184 try {
185 return await listUserOrganizations();
186 } catch (error: any) {
187 logger.error("Failed to list organizations:", error);
188 this.emit("error", error);
189 return null;
190 }
191 }
192
193 /**
194 * Check if the current user has multiple organizations available
195 */
196 async hasMultipleOrganizations(): Promise<boolean> {
197 const orgs = await this.getAvailableOrganizations();
198 return orgs !== null && orgs.length > 0;
199 }
200
201 /**
202 * Refresh auth state from disk (useful after external changes)
203 */
204 async refresh(): Promise<AuthServiceState> {
205 logger.debug("Refreshing auth state from disk");
206 return this.reload();
207 }
208}