-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathworkos.ts
More file actions
332 lines (285 loc) · 9.07 KB
/
workos.ts
File metadata and controls
332 lines (285 loc) · 9.07 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
import {
GenericServerException,
NoApiKeyProvidedException,
NotFoundException,
UnauthorizedException,
UnprocessableEntityException,
OauthException,
RateLimitExceededException,
} from './common/exceptions';
import {
GetOptions,
PostOptions,
PutOptions,
WorkOSOptions,
WorkOSResponseError,
} from './common/interfaces';
import { DirectorySync } from './directory-sync/directory-sync';
import { Events } from './events/events';
import { Organizations } from './organizations/organizations';
import { OrganizationDomains } from './organization-domains/organization-domains';
import { Passwordless } from './passwordless/passwordless';
import { Portal } from './portal/portal';
import { SSO } from './sso/sso';
import { Webhooks } from './webhooks/webhooks';
import { Mfa } from './mfa/mfa';
import { AuditLogs } from './audit-logs/audit-logs';
import { UserManagement } from './user-management/user-management';
import { FGA } from './fga/fga';
import { BadRequestException } from './common/exceptions/bad-request.exception';
import { HttpClient, HttpClientError } from './common/net/http-client';
import { SubtleCryptoProvider } from './common/crypto/subtle-crypto-provider';
import { FetchHttpClient } from './common/net/fetch-client';
import { IronSessionProvider } from './common/iron-session/iron-session-provider';
import { Widgets } from './widgets/widgets';
import { Actions } from './actions/actions';
import { Vault } from './vault/vault';
import { ConflictException } from './common/exceptions/conflict.exception';
import { CryptoProvider } from './common/crypto/crypto-provider';
const VERSION = '7.60.0';
const DEFAULT_HOSTNAME = 'api.workos.com';
const HEADER_AUTHORIZATION = 'Authorization';
const HEADER_IDEMPOTENCY_KEY = 'Idempotency-Key';
const HEADER_WARRANT_TOKEN = 'Warrant-Token';
export class WorkOS {
readonly baseURL: string;
readonly client: HttpClient;
readonly clientId?: string;
readonly actions: Actions;
readonly auditLogs = new AuditLogs(this);
readonly directorySync = new DirectorySync(this);
readonly organizations = new Organizations(this);
readonly organizationDomains = new OrganizationDomains(this);
readonly passwordless = new Passwordless(this);
readonly portal = new Portal(this);
readonly sso = new SSO(this);
readonly webhooks: Webhooks;
readonly mfa = new Mfa(this);
readonly events = new Events(this);
readonly userManagement: UserManagement;
readonly fga = new FGA(this);
readonly widgets = new Widgets(this);
readonly vault = new Vault(this);
constructor(readonly key?: string, readonly options: WorkOSOptions = {}) {
if (!key) {
// process might be undefined in some environments
this.key =
typeof process !== 'undefined'
? process?.env.WORKOS_API_KEY
: undefined;
if (!this.key) {
throw new NoApiKeyProvidedException();
}
}
if (this.options.https === undefined) {
this.options.https = true;
}
this.clientId = this.options.clientId;
if (!this.clientId && typeof process !== 'undefined') {
this.clientId = process?.env.WORKOS_CLIENT_ID;
}
const protocol: string = this.options.https ? 'https' : 'http';
const apiHostname: string = this.options.apiHostname || DEFAULT_HOSTNAME;
const port: number | undefined = this.options.port;
this.baseURL = `${protocol}://${apiHostname}`;
if (port) {
this.baseURL = this.baseURL + `:${port}`;
}
let userAgent: string = `workos-node/${VERSION}`;
if (options.appInfo) {
const { name, version }: { name: string; version: string } =
options.appInfo;
userAgent += ` ${name}: ${version}`;
}
this.webhooks = this.createWebhookClient();
this.actions = this.createActionsClient();
// Must initialize UserManagement after baseURL is configured
this.userManagement = new UserManagement(
this,
this.createIronSessionProvider(),
);
this.client = this.createHttpClient(options, userAgent);
}
createWebhookClient() {
return new Webhooks(this.getCryptoProvider());
}
createActionsClient() {
return new Actions(this.getCryptoProvider());
}
getCryptoProvider(): CryptoProvider {
return new SubtleCryptoProvider();
}
createHttpClient(options: WorkOSOptions, userAgent: string) {
return new FetchHttpClient(this.baseURL, {
...options.config,
headers: {
...options.config?.headers,
Authorization: `Bearer ${this.key}`,
'User-Agent': userAgent,
},
}) as HttpClient;
}
createIronSessionProvider(): IronSessionProvider {
throw new Error(
'IronSessionProvider not implemented. Use WorkOSNode or WorkOSWorker instead.',
);
}
get version() {
return VERSION;
}
async post<Result = any, Entity = any>(
path: string,
entity: Entity,
options: PostOptions = {},
): Promise<{ data: Result }> {
const requestHeaders: Record<string, string> = {};
if (options.idempotencyKey) {
requestHeaders[HEADER_IDEMPOTENCY_KEY] = options.idempotencyKey;
}
if (options.warrantToken) {
requestHeaders[HEADER_WARRANT_TOKEN] = options.warrantToken;
}
try {
const res = await this.client.post<Entity>(path, entity, {
params: options.query,
headers: requestHeaders,
});
return { data: await res.toJSON() };
} catch (error) {
this.handleHttpError({ path, error });
throw error;
}
}
async get<Result = any>(
path: string,
options: GetOptions = {},
): Promise<{ data: Result }> {
const requestHeaders: Record<string, string> = {};
if (options.accessToken) {
requestHeaders[HEADER_AUTHORIZATION] = `Bearer ${options.accessToken}`;
}
if (options.warrantToken) {
requestHeaders[HEADER_WARRANT_TOKEN] = options.warrantToken;
}
try {
const res = await this.client.get(path, {
params: options.query,
headers: requestHeaders,
});
return { data: await res.toJSON() };
} catch (error) {
this.handleHttpError({ path, error });
throw error;
}
}
async put<Result = any, Entity = any>(
path: string,
entity: Entity,
options: PutOptions = {},
): Promise<{ data: Result }> {
const requestHeaders: Record<string, string> = {};
if (options.idempotencyKey) {
requestHeaders[HEADER_IDEMPOTENCY_KEY] = options.idempotencyKey;
}
try {
const res = await this.client.put<Entity>(path, entity, {
params: options.query,
headers: requestHeaders,
});
return { data: await res.toJSON() };
} catch (error) {
this.handleHttpError({ path, error });
throw error;
}
}
async delete(path: string, query?: any): Promise<void> {
try {
await this.client.delete(path, {
params: query,
});
} catch (error) {
this.handleHttpError({ path, error });
throw error;
}
}
emitWarning(warning: string) {
// tslint:disable-next-line:no-console
console.warn(`WorkOS: ${warning}`);
}
private handleHttpError({ path, error }: { path: string; error: unknown }) {
if (!(error instanceof HttpClientError)) {
throw new Error(`Unexpected error: ${error}`, { cause: error });
}
const { response } = error as HttpClientError<WorkOSResponseError>;
if (response) {
const { status, data, headers } = response;
const requestID = headers['X-Request-ID'] ?? '';
const {
code,
error_description: errorDescription,
error,
errors,
message,
} = data;
switch (status) {
case 401: {
throw new UnauthorizedException(requestID);
}
case 409: {
throw new ConflictException({ requestID, message, error });
}
case 422: {
throw new UnprocessableEntityException({
code,
errors,
message,
requestID,
});
}
case 404: {
throw new NotFoundException({
code,
message,
path,
requestID,
});
}
case 429: {
const retryAfter = headers.get('Retry-After');
throw new RateLimitExceededException(
data.message,
requestID,
retryAfter ? Number(retryAfter) : null,
);
}
default: {
if (error || errorDescription) {
throw new OauthException(
status,
requestID,
error,
errorDescription,
data,
);
} else if (code && errors) {
// Note: ideally this should be mapped directly with a `400` status code.
// However, this would break existing logic for the `OauthException` exception.
throw new BadRequestException({
code,
errors,
message,
requestID,
});
} else {
throw new GenericServerException(
status,
data.message,
data,
requestID,
);
}
}
}
}
}
}