@workos/authkit-session 0.0.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,403 @@
1
+ import { WorkOSOptions } from '@workos-inc/node';
2
+ import { JWTPayload } from 'jose';
3
+
4
+ interface UserManagementInterface {
5
+ getAuthorizationUrl: (options: AuthorizationURLOptions) => string;
6
+ authenticateWithCode: (options: AuthenticateWithCodeOptions) => Promise<AuthenticationResponse>;
7
+ authenticateWithRefreshToken: (options: AuthenticateWithRefreshTokenOptions) => Promise<AuthenticationResponse>;
8
+ getLogoutUrl: (optoions: {
9
+ sessionId: string;
10
+ returnTo?: string;
11
+ }) => string;
12
+ }
13
+ interface WorkOSClient {
14
+ userManagement: UserManagementInterface;
15
+ getJwksUrl: (clientId: string) => string;
16
+ }
17
+ interface User {
18
+ object: string;
19
+ id: string;
20
+ email: string;
21
+ emailVerified: boolean;
22
+ profilePictureUrl: string | null;
23
+ firstName: string | null;
24
+ lastName: string | null;
25
+ lastSignInAt: string | null;
26
+ createdAt: string;
27
+ updatedAt: string;
28
+ externalId: string | null;
29
+ metadata: Record<string, string>;
30
+ }
31
+ interface Impersonator {
32
+ email: string;
33
+ reason: string | null;
34
+ }
35
+ interface AuthenticationResponse {
36
+ user: User;
37
+ organizationId?: string;
38
+ accessToken: string;
39
+ refreshToken: string;
40
+ impersonator?: Impersonator;
41
+ authenticationMethod?: string;
42
+ sealedSession?: string;
43
+ }
44
+ interface AuthenticateWithOptionsBase {
45
+ clientId: string;
46
+ ipAddress?: string;
47
+ userAgent?: string;
48
+ session?: {
49
+ cookiePassword?: string;
50
+ sealSession: boolean;
51
+ };
52
+ }
53
+ interface AuthenticateWithRefreshTokenOptions extends AuthenticateWithOptionsBase {
54
+ refreshToken: string;
55
+ organizationId?: string;
56
+ }
57
+ interface AuthenticateWithCodeOptions extends AuthenticateWithOptionsBase {
58
+ codeVerifier?: string;
59
+ code: string;
60
+ invitationToken?: string;
61
+ }
62
+ interface AuthorizationURLOptions {
63
+ clientId: string;
64
+ codeChallenge?: string;
65
+ codeChallengeMethod?: 'S256';
66
+ connectionId?: string;
67
+ context?: string;
68
+ organizationId?: string;
69
+ domainHint?: string;
70
+ loginHint?: string;
71
+ provider?: string;
72
+ redirectUri: string;
73
+ state?: string;
74
+ screenHint?: 'sign-up' | 'sign-in';
75
+ }
76
+
77
+ declare class WorkOSLite implements WorkOSClient {
78
+ protected apiKey: string;
79
+ protected baseURL: string;
80
+ userManagement: UserManagementInterface;
81
+ constructor(apiKey: string, options: WorkOSOptions);
82
+ getJwksUrl(clientId: string): string;
83
+ }
84
+ /**
85
+ * Create a WorkOS instance with the provided API key and optional settings.
86
+ * This function is lazy loaded to avoid loading the WorkOS SDK when it's not needed.
87
+ */
88
+ declare const getWorkOS: () => WorkOSLite;
89
+
90
+ /**
91
+ * AuthKit Configuration Options
92
+ */
93
+ interface AuthKitConfig {
94
+ /**
95
+ * The WorkOS Client ID
96
+ * Equivalent to the WORKOS_CLIENT_ID environment variable
97
+ */
98
+ clientId: string;
99
+ /**
100
+ * The WorkOS API Key
101
+ * Equivalent to the WORKOS_API_KEY environment variable
102
+ */
103
+ apiKey: string;
104
+ /**
105
+ * The redirect URI for the authentication callback
106
+ * Equivalent to the WORKOS_REDIRECT_URI environment variable
107
+ */
108
+ redirectUri: string;
109
+ /**
110
+ * The password used to encrypt the session cookie
111
+ * Equivalent to the WORKOS_COOKIE_PASSWORD environment variable
112
+ * Must be at least 32 characters long
113
+ */
114
+ cookiePassword: string;
115
+ /**
116
+ * The hostname of the API to use
117
+ * Equivalent to the WORKOS_API_HOSTNAME environment variable
118
+ */
119
+ apiHostname?: string;
120
+ /**
121
+ * Whether to use HTTPS for API requests
122
+ * Equivalent to the WORKOS_API_HTTPS environment variable
123
+ */
124
+ apiHttps: boolean;
125
+ /**
126
+ * The port to use for the API
127
+ * Equivalent to the WORKOS_API_PORT environment variable
128
+ */
129
+ apiPort?: number;
130
+ /**
131
+ * The maximum age of the session cookie in seconds
132
+ * Equivalent to the WORKOS_COOKIE_MAX_AGE environment variable
133
+ */
134
+ cookieMaxAge: number;
135
+ /**
136
+ * The sameSite attribute for the session cookie
137
+ */
138
+ cookieSameSite?: 'strict' | 'lax' | 'none';
139
+ /**
140
+ * The name of the session cookie
141
+ * Equivalent to the WORKOS_COOKIE_NAME environment variable
142
+ * Defaults to "wos-session"
143
+ */
144
+ cookieName: string;
145
+ /**
146
+ * The domain for the session cookie
147
+ */
148
+ cookieDomain?: string;
149
+ }
150
+ type ValueSource = Record<string, any> | ((key: string) => any);
151
+
152
+ /**
153
+ * Configuration class for AuthKit.
154
+ * This class is used to manage configuration values and provide defaults.
155
+ * It also provides a way to get configuration values from environment variables.
156
+ * @internal
157
+ */
158
+ declare class ConfigurationProvider {
159
+ private config;
160
+ private valueSource;
161
+ private readonly requiredKeys;
162
+ /**
163
+ * Convert a camelCase string to an uppercase, underscore-separated environment variable name.
164
+ * @param str The string to convert
165
+ * @returns The environment variable name
166
+ */
167
+ protected getEnvironmentVariableName(str: string): string;
168
+ private updateConfig;
169
+ setValueSource(source: ValueSource): void;
170
+ configure(configOrSource: Partial<AuthKitConfig> | ValueSource, source?: ValueSource): void;
171
+ getValue<K extends keyof AuthKitConfig>(key: K): AuthKitConfig[K];
172
+ getConfig(): AuthKitConfig;
173
+ }
174
+
175
+ /**
176
+ * Configure AuthKit with a custom value source.
177
+ * @param source The source of configuration values
178
+ *
179
+ * @example
180
+ * configure(key => Deno.env.get(key));
181
+ */
182
+ declare function configure(source: ValueSource): void;
183
+ /**
184
+ * Configure AuthKit with custom values.
185
+ * @param config The configuration values
186
+ *
187
+ * @example
188
+ * configure({
189
+ * clientId: 'your-client-id',
190
+ * redirectUri: 'https://your-app.com/auth/callback',
191
+ * apiKey: 'your-api-key',
192
+ * cookiePassword: 'your-cookie-password',
193
+ * });
194
+ */
195
+ declare function configure(config: Partial<AuthKitConfig>): void;
196
+ /**
197
+ * Configure AuthKit with custom values and a custom value source.
198
+ * @param config The configuration values
199
+ * @param source The source of configuration values
200
+ *
201
+ * @example
202
+ * configure({
203
+ * clientId: 'your-client-id',
204
+ * }, env);
205
+ */
206
+ declare function configure(config: Partial<AuthKitConfig>, source: ValueSource): void;
207
+ /**
208
+ * Get a configuration value by key.
209
+ * This function will first check environment variables, then programmatically provided config,
210
+ * and finally fall back to defaults for optional settings.
211
+ * If a required setting is missing, an error will be thrown.
212
+ * @param key The configuration key
213
+ * @returns The configuration value
214
+ */
215
+ declare function getConfig<K extends keyof AuthKitConfig>(key: K): AuthKitConfig[K];
216
+
217
+ interface BaseTokenClaims extends JWTPayload {
218
+ sid: string;
219
+ org_id?: string;
220
+ role?: string;
221
+ permissions?: string[];
222
+ entitlements?: string[];
223
+ feature_flags?: string[];
224
+ }
225
+ type CustomClaims = Record<string, unknown>;
226
+ interface AuthResult<TCustomClaims = Record<string, unknown>> {
227
+ refreshToken?: string;
228
+ user?: User | null;
229
+ claims?: BaseTokenClaims & TCustomClaims;
230
+ impersonator?: Impersonator;
231
+ accessToken?: string;
232
+ sessionId?: string;
233
+ }
234
+ /**
235
+ * AuthKit Session
236
+ */
237
+ interface Session {
238
+ /**
239
+ * The session access token
240
+ */
241
+ accessToken: string;
242
+ /**
243
+ * The session refresh token - used to refresh the access token
244
+ */
245
+ refreshToken: string;
246
+ /**
247
+ * The logged-in user
248
+ */
249
+ user: User;
250
+ /**
251
+ * The impersonator user, if any
252
+ */
253
+ impersonator?: Impersonator;
254
+ }
255
+ interface SessionStorage<TRequest, TResponse, TOptions = unknown> {
256
+ getSession(request: TRequest): Promise<string | null>;
257
+ /**
258
+ * Save session data to a response object.
259
+ * @param response The framework-specific response object.
260
+ * @param sessionData The encrypted session string.
261
+ * @param options Optional cookie options.
262
+ * @returns The framework-specific response object with the session cookie set.
263
+ */
264
+ saveSession(response: TResponse, sessionData: string, options?: TOptions): Promise<TResponse>;
265
+ /**
266
+ * @param response The frmework-specific response object.
267
+ * @returns The framework-specific response object with the session cookie removed.
268
+ */
269
+ clearSession(response: TResponse, options?: TOptions): Promise<TResponse>;
270
+ }
271
+ interface SessionEncryption {
272
+ sealData: (data: unknown, options: {
273
+ password: string;
274
+ ttl?: number | undefined;
275
+ }) => Promise<string>;
276
+ unsealData: <T>(encryptedData: string, options: {
277
+ password: string;
278
+ }) => Promise<T>;
279
+ }
280
+
281
+ declare class TokenManager {
282
+ private clientId;
283
+ private client;
284
+ constructor(clientId: string, client: WorkOSClient);
285
+ private readonly getPublicKey;
286
+ verifyToken(token: string): Promise<boolean>;
287
+ parseTokenClaims<TCustomClaims = CustomClaims>(token: string): BaseTokenClaims & TCustomClaims;
288
+ isTokenExpiring(token: string, bufferSeconds?: number): boolean;
289
+ getTokenExpiryTime(token: string): number | null;
290
+ }
291
+
292
+ declare class SessionManager<TRequest, TResponse> {
293
+ private readonly config;
294
+ private readonly storage;
295
+ private readonly tokenManager;
296
+ private readonly client;
297
+ private readonly encryption;
298
+ constructor(config: ConfigurationProvider, storage: SessionStorage<TRequest, TResponse>, tokenManager: TokenManager, client: WorkOSClient, encryption: SessionEncryption);
299
+ private encryptSession;
300
+ private decryptSession;
301
+ private getSession;
302
+ private validateSession;
303
+ withAuth<TCustomClaims = CustomClaims>(request: TRequest): Promise<AuthResult<TCustomClaims>>;
304
+ refreshSession<TCustomClaims = CustomClaims>(session: Session, organizationId?: string): Promise<{
305
+ user: User;
306
+ sessionId: string;
307
+ organizationId: string | undefined;
308
+ role: string | undefined;
309
+ permissions: string[] | undefined;
310
+ entitlements: string[] | undefined;
311
+ impersonator: Impersonator | undefined;
312
+ accessToken: string;
313
+ claims: BaseTokenClaims & TCustomClaims;
314
+ sessionData: string;
315
+ session: Session;
316
+ }>;
317
+ getAuthorizationUrl({ returnPathname, redirectUri, screenHint, }: {
318
+ returnPathname?: string;
319
+ redirectUri?: string;
320
+ screenHint?: 'sign-up' | 'sign-in';
321
+ }): Promise<string>;
322
+ createSession(authResponse: AuthenticationResponse, response: TResponse): Promise<TResponse>;
323
+ switchToOrganization<TCustomClaims = CustomClaims>(request: TRequest, response: TResponse, organizationId: string): Promise<{
324
+ response: TResponse;
325
+ authResult: AuthResult<TCustomClaims>;
326
+ }>;
327
+ terminateSession(session: Session, response: TResponse, options?: {
328
+ returnTo?: string;
329
+ }): Promise<{
330
+ response: TResponse;
331
+ logoutUrl: string;
332
+ }>;
333
+ }
334
+
335
+ interface CookieOptions {
336
+ path?: string;
337
+ domain?: string;
338
+ maxAge?: number;
339
+ expires?: Date;
340
+ httpOnly?: boolean;
341
+ secure?: boolean;
342
+ sameSite?: 'lax' | 'strict' | 'none';
343
+ priority?: 'low' | 'medium' | 'high';
344
+ partitioned?: boolean;
345
+ }
346
+ declare abstract class CookieSessionStorage<TRequest, TResponse> implements SessionStorage<TRequest, TResponse> {
347
+ protected cookieName: string;
348
+ protected readonly cookieOptions: CookieOptions;
349
+ constructor(config: ConfigurationProvider);
350
+ abstract getSession(request: TRequest): Promise<string | null>;
351
+ abstract saveSession(response: TResponse, sessionData: string): Promise<TResponse>;
352
+ abstract clearSession(response: TResponse): Promise<TResponse>;
353
+ }
354
+
355
+ declare const createAuthKitFactory: <TRequest, TResponse>(options: {
356
+ sessionStorageFactory: (config: AuthKitConfig) => SessionStorage<TRequest, TResponse>;
357
+ sessionEncryptionFactory?: (confg: AuthKitConfig) => SessionEncryption;
358
+ clientFactory?: (config: AuthKitConfig) => WorkOSClient;
359
+ }) => {
360
+ withAuth: (request: any) => Promise<AuthResult<CustomClaims>>;
361
+ getAuthorizationUrl: (args_0: {
362
+ returnPathname?: string;
363
+ redirectUri?: string;
364
+ screenHint?: "sign-up" | "sign-in";
365
+ }) => Promise<string>;
366
+ refreshSession: (session: Session, organizationId?: string | undefined) => Promise<{
367
+ user: User;
368
+ sessionId: string;
369
+ organizationId: string | undefined;
370
+ role: string | undefined;
371
+ permissions: string[] | undefined;
372
+ entitlements: string[] | undefined;
373
+ impersonator: Impersonator | undefined;
374
+ accessToken: string;
375
+ claims: BaseTokenClaims & CustomClaims;
376
+ sessionData: string;
377
+ session: Session;
378
+ }>;
379
+ saveSession: (response: TResponse, sessionData: string, options?: unknown) => Promise<TResponse>;
380
+ getSignInUrl: (options: {
381
+ organizationId?: string;
382
+ loginHint?: string;
383
+ redirectUri?: string;
384
+ }) => Promise<string>;
385
+ getSignUpUrl: (options: {
386
+ organizationId?: string;
387
+ loginHint?: string;
388
+ redirectUri?: string;
389
+ }) => Promise<string>;
390
+ getLogoutUrl: (session: Session, response: any, options?: {
391
+ returnTo?: string;
392
+ } | undefined) => Promise<{
393
+ response: TResponse;
394
+ logoutUrl: string;
395
+ }>;
396
+ switchToOrganization: (request: any, response: any, organizationId: string) => Promise<{
397
+ response: TResponse;
398
+ authResult: AuthResult<CustomClaims>;
399
+ }>;
400
+ getTokenClaims: <TCustomClaims = CustomClaims>(request: TRequest, accessToken?: string) => Promise<Partial<BaseTokenClaims & TCustomClaims>>;
401
+ };
402
+
403
+ export { type AuthKitConfig, type AuthResult, type BaseTokenClaims, CookieSessionStorage, type CustomClaims, type Session, type SessionEncryption, SessionManager, type SessionStorage, type ValueSource, configure, createAuthKitFactory, getConfig, getWorkOS };