-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathauth.ts
More file actions
405 lines (369 loc) · 11.1 KB
/
auth.ts
File metadata and controls
405 lines (369 loc) · 11.1 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
import {
type ApiClientConfiguration,
apiClientManager,
RealtimeRunSkipColumns,
} from "@trigger.dev/core/v3";
import { generateJWT as internal_generateJWT } from "@trigger.dev/core/v3";
/**
* Register the global API client configuration. Alternatively, you can set the `TRIGGER_SECRET_KEY` and `TRIGGER_API_URL` environment variables.
* @param options The API client configuration.
* @param options.baseURL The base URL of the Trigger API. (default: `https://api.trigger.dev`)
* @param options.accessToken The accessToken to authenticate with the Trigger API. (default: `process.env.TRIGGER_SECRET_KEY`) This can be found in your Trigger.dev project "API Keys" settings.
*
* @example
*
* ```typescript
* import { configure } from "@trigger.dev/sdk/v3";
*
* configure({
* baseURL: "https://api.trigger.dev",
* accessToken: "tr_dev_1234567890"
* });
* ```
*/
export function configure(options: ApiClientConfiguration) {
apiClientManager.setGlobalAPIClientConfiguration(options);
}
export const auth = {
configure,
createPublicToken,
createTriggerPublicToken,
createBatchTriggerPublicToken,
withAuth,
withPublicToken,
withTriggerPublicToken,
withBatchTriggerPublicToken,
};
type PublicTokenPermissionProperties = {
/**
* Grant access to specific tasks
*/
tasks?: string | string[];
/**
* Grant access to specific run tags
*/
tags?: string | string[];
/**
* Grant access to specific runs
*/
runs?: string | string[] | true;
/**
* Grant access to specific batch runs
*/
batch?: string | string[];
/**
* Grant access to specific waitpoints
*/
waitpoints?: string | string[];
};
export type PublicTokenPermissions = {
read?: PublicTokenPermissionProperties;
write?: PublicTokenPermissionProperties;
/**
* Use auth.createTriggerPublicToken
*/
trigger?: {
tasks: string | string[];
};
/**
* Use auth.createBatchTriggerPublicToken
*/
batchTrigger?: {
tasks: string | string[];
};
};
export type CreatePublicTokenOptions = {
/**
* A collection of permission scopes to be granted to the token.
*
* @example
*
* ```typescript
* scopes: {
* read: {
* tags: ["file:1234"]
* }
* }
* ```
*/
scopes?: PublicTokenPermissions;
/**
* The expiration time for the token. This can be a number representing the time in milliseconds, a `Date` object, or a string.
*
* @example
*
* ```typescript
* expirationTime: "1h"
* ```
*/
expirationTime?: number | Date | string;
realtime?: {
/**
* Skip columns from the subscription.
*
* @default []
*
* @example
* ```ts
* auth.createPublicToken({
* realtime: {
* skipColumns: ["payload", "output"]
* }
* });
* ```
*/
skipColumns?: RealtimeRunSkipColumns;
};
};
/**
* Creates a public token using the provided options.
*
* @param options - Optional parameters for creating the public token.
* @param options.scopes - An array of permission scopes to be included in the token.
* @param options.expirationTime - The expiration time for the token.
* @param options.realtime - Options for realtime subscriptions.
* @param options.realtime.skipColumns - Skip columns from the subscription.
* @returns A promise that resolves to a string representing the generated public token.
*
* @example
*
* ```typescript
* import { auth } from "@trigger.dev/sdk/v3";
*
* const publicToken = await auth.createPublicToken({
* scopes: {
* read: {
* tags: ["file:1234"]
* }
* });
* ```
*/
async function createPublicToken(options?: CreatePublicTokenOptions): Promise<string> {
const apiClient = apiClientManager.clientOrThrow();
const claims = await apiClient.generateJWTClaims();
return await internal_generateJWT({
secretKey: apiClient.accessToken,
payload: {
...claims,
scopes: options?.scopes ? flattenScopes(options.scopes) : undefined,
realtime: options?.realtime,
},
expirationTime: options?.expirationTime,
});
}
/**
* Executes a function with a public token, providing temporary access permissions.
*
* @param options - Options for creating the public token.
* @param fn - The asynchronous function to be executed with the public token.
*/
async function withPublicToken(options: CreatePublicTokenOptions, fn: () => Promise<void>) {
const token = await createPublicToken(options);
await withAuth({ accessToken: token }, fn);
}
export type CreateTriggerTokenOptions = {
/**
* The expiration time for the token. This can be a number representing the time in milliseconds, a `Date` object, or a string.
*
* @example
*
* ```typescript
* expirationTime: "1h"
* ```
*/
expirationTime?: number | Date | string;
/**
* Whether the token can be used multiple times. By default trigger tokens are one-time use.
* @default false
*/
multipleUse?: boolean;
realtime?: {
/**
* Skip columns from the subscription.
*
* @default []
*
* @example
* ```ts
* auth.createTriggerPublicToken("my-task", {
* realtime: {
* skipColumns: ["payload", "output"]
* }
* });
* ```
*/
skipColumns?: RealtimeRunSkipColumns;
};
};
/**
* Creates a one-time use token to trigger a specific task.
*
* @param task - The task ID or an array of task IDs that the token should allow triggering.
* @param options - Options for creating the one-time use token.
* @returns A promise that resolves to a string representing the generated one-time use token.
*
* @example
* Create a one-time use public token that allows triggering a specific task:
*
* ```ts
* import { auth } from "@trigger.dev/sdk/v3";
*
* const token = await auth.createTriggerPublicToken("my-task");
* ```
*
* @example You can also create a one-time use token that allows triggering multiple tasks:
*
* ```ts
* import { auth } from "@trigger.dev/sdk/v3";
*
* const token = await auth.createTriggerPublicToken(["task1", "task2"]);
* ```
*
* @example You can also create a one-time use token that allows triggering a task with a specific expiration time:
*
* ```ts
* import { auth } from "@trigger.dev/sdk/v3";
*
* const token = await auth.createTriggerPublicToken("my-task", { expirationTime: "1h" });
* ```
*/
async function createTriggerPublicToken(
task: string | string[],
options?: CreateTriggerTokenOptions
): Promise<string> {
const apiClient = apiClientManager.clientOrThrow();
const claims = await apiClient.generateJWTClaims();
return await internal_generateJWT({
secretKey: apiClient.accessToken,
payload: {
...claims,
otu: typeof options?.multipleUse === "boolean" ? !options.multipleUse : true,
realtime: options?.realtime,
scopes: flattenScopes({
trigger: {
tasks: task,
},
}),
},
expirationTime: options?.expirationTime,
});
}
/**
* Executes a function with a one-time use token that allows triggering a specific task.
*
* @param task - The task ID or an array of task IDs that the token should allow triggering.
* @param options - Options for creating the one-time use token.
* @param fn - The asynchronous function to be executed with the one-time use token.
*/
async function withTriggerPublicToken(
task: string | string[],
options: CreateTriggerTokenOptions = {},
fn: () => Promise<void>
) {
const token = await createTriggerPublicToken(task, options);
await withAuth({ accessToken: token }, fn);
}
/**
* Creates a one-time use token to batch trigger a specific task or tasks.
*
* @param task - The task ID or an array of task IDs that the token should allow triggering.
* @param options - Options for creating the one-time use token.
* @returns A promise that resolves to a string representing the generated one-time use token.
*
* @example
*
* ```ts
* import { auth } from "@trigger.dev/sdk/v3";
*
* const token = await auth.createBatchTriggerPublicToken("my-task");
* ```
*
* @example You can also create a one-time use token that allows batch triggering multiple tasks:
*
* ```ts
* import { auth } from "@trigger.dev/sdk/v3";
*
* const token = await auth.createBatchTriggerPublicToken(["task1", "task2"]);
* ```
*
* @example You can also create a one-time use token that allows batch triggering a task with a specific expiration time:
*
* ```ts
* import { auth } from "@trigger.dev/sdk/v3";
*
* const token = await auth.createBatchTriggerPublicToken("my-task", { expirationTime: "1h" });
* ```
*/
async function createBatchTriggerPublicToken(
task: string | string[],
options?: CreateTriggerTokenOptions
): Promise<string> {
const apiClient = apiClientManager.clientOrThrow();
const claims = await apiClient.generateJWTClaims();
return await internal_generateJWT({
secretKey: apiClient.accessToken,
payload: {
...claims,
otu: typeof options?.multipleUse === "boolean" ? !options.multipleUse : true,
realtime: options?.realtime,
scopes: flattenScopes({
batchTrigger: {
tasks: task,
},
}),
},
expirationTime: options?.expirationTime,
});
}
/**
* Executes a function with a one-time use token that allows triggering a specific task.
*
* @param task - The task ID or an array of task IDs that the token should allow triggering.
* @param options - Options for creating the one-time use token.
* @param fn - The asynchronous function to be executed with the one-time use token.
*/
async function withBatchTriggerPublicToken(
task: string | string[],
options: CreateTriggerTokenOptions = {},
fn: () => Promise<void>
) {
const token = await createBatchTriggerPublicToken(task, options);
await withAuth({ accessToken: token }, fn);
}
/**
* Executes a provided asynchronous function with a specified API client configuration.
*
* @template R - The type of the asynchronous function to be executed.
* @param {ApiClientConfiguration} config - The configuration for the API client.
* @param {R} fn - The asynchronous function to be executed.
* @returns {Promise<ReturnType<R>>} A promise that resolves to the return type of the provided function.
*/
async function withAuth<R extends (...args: any[]) => Promise<any>>(
config: ApiClientConfiguration,
fn: R
): Promise<ReturnType<R>> {
return apiClientManager.runWithConfig(config, fn);
}
function flattenScopes(permissions: PublicTokenPermissions): string[] {
const flattenedPermissions: string[] = [];
for (const [action, properties] of Object.entries(permissions)) {
if (properties) {
if (typeof properties === "boolean" && properties) {
flattenedPermissions.push(action);
} else if (typeof properties === "object") {
for (const [property, value] of Object.entries(properties)) {
if (Array.isArray(value)) {
for (const item of value) {
flattenedPermissions.push(`${action}:${property}:${item}`);
}
} else if (typeof value === "string") {
flattenedPermissions.push(`${action}:${property}:${value}`);
} else if (typeof value === "boolean" && value) {
flattenedPermissions.push(`${action}:${property}`);
}
}
}
}
}
return flattenedPermissions;
}