-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathapiBuilder.server.ts
More file actions
1520 lines (1395 loc) · 51.3 KB
/
Copy pathapiBuilder.server.ts
File metadata and controls
1520 lines (1395 loc) · 51.3 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 { z } from "zod";
import { ApiAuthenticationResultSuccess } from "../apiAuth.server";
import { ActionFunctionArgs, json, LoaderFunctionArgs } from "@remix-run/server-runtime";
import { fromZodError } from "zod-validation-error";
import { apiCors } from "~/utils/apiCors";
import { logger } from "../logger.server";
import { sanitizeAuthFailure } from "./publicAuthError";
import { rbac } from "../rbac.server";
import type { RbacAbility, RbacResource } from "@trigger.dev/rbac";
import {
PersonalAccessTokenAuthenticationResult,
updateLastAccessedAtIfStale,
} from "../personalAccessToken.server";
import { safeJsonParse } from "~/utils/json";
import {
AuthenticatedWorkerInstance,
WorkerGroupTokenService,
} from "~/v3/services/worker/workerGroupTokenService.server";
import { API_VERSIONS, getApiVersion } from "~/api/versions";
import { WORKER_HEADERS } from "@trigger.dev/core/v3/runEngineWorker";
import { ServiceValidationError } from "~/v3/services/common.server";
import { EngineServiceValidationError } from "@internal/run-engine";
import {
tenantContext,
tenantContextFromAuthEnvironment,
} from "~/services/tenantContext.server";
// Client aborts and service-level validation errors aren't bugs — they're
// expected at API boundaries. Log them at `warn` so they stay in stdout
// without flowing to Sentry via Logger.onError.
function logBoundaryError(
message: "Error in loader" | "Error in action",
error: unknown,
url: string
) {
const formatted =
error instanceof Error
? { name: error.name, message: error.message, stack: error.stack }
: String(error);
const isExpected =
error instanceof Error &&
(error.name === "AbortError" ||
error instanceof ServiceValidationError ||
error instanceof EngineServiceValidationError);
if (isExpected) {
logger.warn(message, { error: formatted, url });
} else {
logger.error(message, { error: formatted, url });
}
}
// Bridges the RBAC plugin (source of truth for auth + abilities) to the legacy
// ApiAuthenticationResultSuccess shape route handlers still expect. All three
// apiBuilder call sites funnel through this helper — no handler-level changes
// needed.
async function authenticateRequestForApiBuilder(
request: Request,
{ allowJWT }: { allowJWT: boolean }
): Promise<
| { ok: false; status: 401 | 403; error: string }
| { ok: true; authentication: ApiAuthenticationResultSuccess; ability: RbacAbility }
> {
const result = await rbac.authenticateBearer(request, { allowJWT });
if (!result.ok) {
// Plugin auth distinguishes 401 (who are you?) from 403 (you're not
// allowed) — e.g. a suspended account or IP block returns 403.
// Forwarding the status preserves that semantic for client retry logic.
//
// Never forward the controller's `error` string: a controller can
// conflate an infra failure with an auth rejection (e.g. an
// unreachable DB throws a Prisma error carrying the prod RDS hostname,
// which the plugin returns as the auth error). Log it server-side and
// return a fixed status-derived message instead. See sanitizeAuthFailure.
logger.warn("API bearer auth failed", { status: result.status, error: result.error });
return { ok: false, ...sanitizeAuthFailure(result) };
}
// Plugins return the full AuthenticatedEnvironment shape directly — no
// follow-up DB lookup. The fallback fetches via Prisma, the cloud plugin
// via Drizzle; both produce the same slim contract type.
const authentication: ApiAuthenticationResultSuccess = {
ok: true,
apiKey: result.environment.apiKey,
type: result.subject.type === "publicJWT" ? "PUBLIC_JWT" : "PRIVATE",
environment: result.environment,
realtime: result.jwt?.realtime,
oneTimeUse: result.jwt?.oneTimeUse,
};
return { ok: true, authentication, ability: result.ability };
}
type AnyZodSchema = z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>;
// A multi-resource auth check has two possible directions, and route authors
// have to pick one explicitly:
//
// - `anyResource(...)` — succeed if *any* element passes. Used when a single
// record carries multiple identifiers (a run is addressable by friendlyId /
// batch / tags / task) so a JWT scoped to *any* of them grants access.
//
// - `everyResource(...)` — succeed only if *every* element passes. Used for
// batch operations where each element is a *distinct* resource and a JWT
// scoped to one element must not authorize the others.
//
// Bare `RbacResource[]` is intentionally *not* part of `AuthResource` — the
// type system forces every multi-resource site to disambiguate. The original
// pre-RBAC apiBuilder had a separate `superScopes: [...]` whitelist for
// "broader-than-this-resource" access; post-RBAC that's expressed via the JWT
// ability's wildcard branches (`*:all` and `admin*` — see
// `internal-packages/rbac/src/ability.ts`) plus a collection-level shape
// `{ type: "<subject>" }` (no id) in the `anyResource` array so a
// `<action>:<subject>` JWT matches it. No code knob needed.
//
// Markers are Symbols so they can't collide with arbitrary RbacResource fields.
const ANY_RESOURCE_MARKER = Symbol.for("@trigger.dev/rbac.anyResource");
const EVERY_RESOURCE_MARKER = Symbol.for("@trigger.dev/rbac.everyResource");
type AnyResourceAuth = {
readonly [ANY_RESOURCE_MARKER]: true;
readonly resources: readonly RbacResource[];
};
type EveryResourceAuth = {
readonly [EVERY_RESOURCE_MARKER]: true;
readonly resources: readonly RbacResource[];
};
export function anyResource(resources: RbacResource[]): AnyResourceAuth {
return { [ANY_RESOURCE_MARKER]: true, resources };
}
export function everyResource(resources: RbacResource[]): EveryResourceAuth {
return { [EVERY_RESOURCE_MARKER]: true, resources };
}
function isAnyResource(value: unknown): value is AnyResourceAuth {
return (
typeof value === "object" &&
value !== null &&
(value as Record<symbol, unknown>)[ANY_RESOURCE_MARKER] === true
);
}
function isEveryResource(value: unknown): value is EveryResourceAuth {
return (
typeof value === "object" &&
value !== null &&
(value as Record<symbol, unknown>)[EVERY_RESOURCE_MARKER] === true
);
}
type AuthResource = RbacResource | AnyResourceAuth | EveryResourceAuth;
function checkAuth(
ability: RbacAbility,
action: string,
resource: AuthResource
): boolean {
if (isEveryResource(resource)) {
// Empty array via [].every() is vacuously true — would let any token
// pass auth. Routes building everyResource() from request bodies
// (e.g. batch trigger items) should never produce zero elements
// because body validation rejects empty arrays first, but defending
// here anyway since the auth layer should never grant on no input.
if (resource.resources.length === 0) return false;
return resource.resources.every((r) => ability.can(action, r));
}
if (isAnyResource(resource)) {
// Symmetric guard: anyResource([]) is benign for most abilities
// (.some() is false on empty), but the permissive ability would
// still grant. Treat empty as "no resource declared" → deny.
if (resource.resources.length === 0) return false;
return ability.can(action, [...resource.resources]);
}
return ability.can(action, resource);
}
type ApiKeyRouteBuilderOptions<
TParamsSchema extends AnyZodSchema | undefined = undefined,
TSearchParamsSchema extends AnyZodSchema | undefined = undefined,
THeadersSchema extends AnyZodSchema | undefined = undefined,
TResource = never
> = {
params?: TParamsSchema;
searchParams?: TSearchParamsSchema;
headers?: THeadersSchema;
allowJWT?: boolean;
corsStrategy?: "all" | "none";
findResource: (
params: TParamsSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<TParamsSchema>
: undefined,
authentication: ApiAuthenticationResultSuccess,
searchParams: TSearchParamsSchema extends
| z.ZodFirstPartySchemaTypes
| z.ZodDiscriminatedUnion<any, any>
? z.infer<TSearchParamsSchema>
: undefined
) => Promise<TResource | undefined>;
shouldRetryNotFound?: boolean;
authorization?: {
action: string;
resource: (
resource: NonNullable<TResource>,
params: TParamsSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<TParamsSchema>
: undefined,
searchParams: TSearchParamsSchema extends
| z.ZodFirstPartySchemaTypes
| z.ZodDiscriminatedUnion<any, any>
? z.infer<TSearchParamsSchema>
: undefined,
headers: THeadersSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<THeadersSchema>
: undefined
) => AuthResource;
};
};
type ApiKeyHandlerFunction<
TParamsSchema extends AnyZodSchema | undefined,
TSearchParamsSchema extends AnyZodSchema | undefined,
THeadersSchema extends AnyZodSchema | undefined = undefined,
TResource = never
> = (args: {
params: TParamsSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<TParamsSchema>
: undefined;
searchParams: TSearchParamsSchema extends
| z.ZodFirstPartySchemaTypes
| z.ZodDiscriminatedUnion<any, any>
? z.infer<TSearchParamsSchema>
: undefined;
headers: THeadersSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<THeadersSchema>
: undefined;
authentication: ApiAuthenticationResultSuccess;
request: Request;
resource: NonNullable<TResource>;
apiVersion: API_VERSIONS;
}) => Promise<Response>;
export function createLoaderApiRoute<
TParamsSchema extends AnyZodSchema | undefined = undefined,
TSearchParamsSchema extends AnyZodSchema | undefined = undefined,
THeadersSchema extends AnyZodSchema | undefined = undefined,
TResource = never
>(
options: ApiKeyRouteBuilderOptions<TParamsSchema, TSearchParamsSchema, THeadersSchema, TResource>,
handler: ApiKeyHandlerFunction<TParamsSchema, TSearchParamsSchema, THeadersSchema, TResource>
) {
return async function loader({ request, params }: LoaderFunctionArgs) {
const {
params: paramsSchema,
searchParams: searchParamsSchema,
headers: headersSchema,
allowJWT = false,
corsStrategy = "none",
authorization,
findResource,
shouldRetryNotFound,
} = options;
if (corsStrategy !== "none" && request.method.toUpperCase() === "OPTIONS") {
return apiCors(request, json({}));
}
try {
const authResult = await authenticateRequestForApiBuilder(request, { allowJWT });
if (!authResult.ok) {
return await wrapResponse(
request,
json({ error: authResult.error }, { status: authResult.status }),
corsStrategy !== "none"
);
}
const { authentication: authenticationResult, ability } = authResult;
let parsedParams: any = undefined;
if (paramsSchema) {
const parsed = paramsSchema.safeParse(params);
if (!parsed.success) {
return await wrapResponse(
request,
json(
{ error: "Params Error", details: fromZodError(parsed.error).details },
{ status: 400 }
),
corsStrategy !== "none"
);
}
parsedParams = parsed.data;
}
let parsedSearchParams: any = undefined;
if (searchParamsSchema) {
const searchParams = Object.fromEntries(new URL(request.url).searchParams);
const parsed = searchParamsSchema.safeParse(searchParams);
if (!parsed.success) {
return await wrapResponse(
request,
json(
{ error: "Query Error", details: fromZodError(parsed.error).details },
{ status: 400 }
),
corsStrategy !== "none"
);
}
parsedSearchParams = parsed.data;
}
let parsedHeaders: any = undefined;
if (headersSchema) {
const rawHeaders = Object.fromEntries(request.headers);
const headers = headersSchema.safeParse(rawHeaders);
if (!headers.success) {
return await wrapResponse(
request,
json(
{ error: "Headers Error", details: fromZodError(headers.error).details },
{ status: 400 }
),
corsStrategy !== "none"
);
}
parsedHeaders = headers.data;
}
// Find the resource
const resource = await findResource(parsedParams, authenticationResult, parsedSearchParams);
if (!resource) {
return await wrapResponse(
request,
json(
{ error: "Not found" },
{ status: 404, headers: { "x-should-retry": shouldRetryNotFound ? "true" : "false" } }
),
corsStrategy !== "none"
);
}
if (authorization) {
const { action, resource: authResource } = authorization;
const $authResource = authResource(
resource,
parsedParams,
parsedSearchParams,
parsedHeaders
);
if (!checkAuth(ability, action, $authResource)) {
return await wrapResponse(
request,
json(
{
error: "Unauthorized",
code: "unauthorized",
param: "access_token",
type: "authorization",
},
{ status: 403 }
),
corsStrategy !== "none"
);
}
}
const apiVersion = getApiVersion(request);
const result = await tenantContext.run(
tenantContextFromAuthEnvironment(authenticationResult.environment),
() =>
handler({
params: parsedParams,
searchParams: parsedSearchParams,
headers: parsedHeaders,
authentication: authenticationResult,
request,
resource,
apiVersion,
})
);
return await wrapResponse(request, result, corsStrategy !== "none");
} catch (error) {
try {
if (error instanceof Response) {
return await wrapResponse(request, error, corsStrategy !== "none");
}
logBoundaryError("Error in loader", error, request.url);
return await wrapResponse(
request,
json({ error: "Internal Server Error" }, { status: 500 }),
corsStrategy !== "none"
);
} catch (innerError) {
logger.error("[apiBuilder] Failed to handle error", { error, innerError });
return json({ error: "Internal Server Error" }, { status: 500 });
}
}
};
}
type PATRouteBuilderOptions<
TParamsSchema extends AnyZodSchema | undefined = undefined,
TSearchParamsSchema extends AnyZodSchema | undefined = undefined,
THeadersSchema extends AnyZodSchema | undefined = undefined
> = {
params?: TParamsSchema;
searchParams?: TSearchParamsSchema;
headers?: THeadersSchema;
corsStrategy?: "all" | "none";
// Resolves the target org/project for the request. Fed to
// `rbac.authenticatePat` so the plugin can compute the user's role
// floor (their authority in that org) for the cap intersection.
// When omitted, the PAT runs in identity-only mode — no role floor,
// no per-route ability gating beyond what authorization (if any)
// declares against a permissive baseline. Routes added before TRI-9087
// run in this mode by default.
context?: (
params: TParamsSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<TParamsSchema>
: undefined,
request: Request
) =>
| { organizationId?: string; projectId?: string }
| Promise<{ organizationId?: string; projectId?: string }>;
authorization?: {
action: string;
resource: (
params: TParamsSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<TParamsSchema>
: undefined,
searchParams: TSearchParamsSchema extends
| z.ZodFirstPartySchemaTypes
| z.ZodDiscriminatedUnion<any, any>
? z.infer<TSearchParamsSchema>
: undefined,
headers: THeadersSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<THeadersSchema>
: undefined
) => AuthResource;
};
};
type PATHandlerFunction<
TParamsSchema extends AnyZodSchema | undefined,
TSearchParamsSchema extends AnyZodSchema | undefined,
THeadersSchema extends AnyZodSchema | undefined = undefined
> = (args: {
params: TParamsSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<TParamsSchema>
: undefined;
searchParams: TSearchParamsSchema extends
| z.ZodFirstPartySchemaTypes
| z.ZodDiscriminatedUnion<any, any>
? z.infer<TSearchParamsSchema>
: undefined;
headers: THeadersSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<THeadersSchema>
: undefined;
authentication: PersonalAccessTokenAuthenticationResult;
ability: RbacAbility;
request: Request;
apiVersion: API_VERSIONS;
}) => Promise<Response>;
export function createLoaderPATApiRoute<
TParamsSchema extends AnyZodSchema | undefined = undefined,
TSearchParamsSchema extends AnyZodSchema | undefined = undefined,
THeadersSchema extends AnyZodSchema | undefined = undefined
>(
options: PATRouteBuilderOptions<TParamsSchema, TSearchParamsSchema, THeadersSchema>,
handler: PATHandlerFunction<TParamsSchema, TSearchParamsSchema, THeadersSchema>
) {
return async function loader({ request, params }: LoaderFunctionArgs) {
const {
params: paramsSchema,
searchParams: searchParamsSchema,
headers: headersSchema,
corsStrategy = "none",
context: contextFn,
authorization,
} = options;
if (corsStrategy !== "none" && request.method.toUpperCase() === "OPTIONS") {
return apiCors(request, json({}));
}
try {
let parsedParams: any = undefined;
if (paramsSchema) {
const parsed = paramsSchema.safeParse(params);
if (!parsed.success) {
return await wrapResponse(
request,
json(
{ error: "Params Error", details: fromZodError(parsed.error).details },
{ status: 400 }
),
corsStrategy !== "none"
);
}
parsedParams = parsed.data;
}
let parsedSearchParams: any = undefined;
if (searchParamsSchema) {
const searchParams = Object.fromEntries(new URL(request.url).searchParams);
const parsed = searchParamsSchema.safeParse(searchParams);
if (!parsed.success) {
return await wrapResponse(
request,
json(
{ error: "Query Error", details: fromZodError(parsed.error).details },
{ status: 400 }
),
corsStrategy !== "none"
);
}
parsedSearchParams = parsed.data;
}
let parsedHeaders: any = undefined;
if (headersSchema) {
const rawHeaders = Object.fromEntries(request.headers);
const headers = headersSchema.safeParse(rawHeaders);
if (!headers.success) {
return await wrapResponse(
request,
json(
{ error: "Headers Error", details: fromZodError(headers.error).details },
{ status: 400 }
),
corsStrategy !== "none"
);
}
parsedHeaders = headers.data;
}
const apiVersion = getApiVersion(request);
// Single PAT auth roundtrip. `rbac.authenticatePat` validates the
// token AND computes the cap-and-floor ability in one DB query
// (the OSS fallback does the validation only and returns a
// permissive ability; the cloud plugin returns the joined
// cap/floor result). We previously called
// `authenticateApiRequestWithPersonalAccessToken` here first as
// belt-and-braces, but that meant two PAT lookups per request
// for routes with `context`/`authorization` declared. Routes
// without those still get a working `authentication` object —
// we pass an empty ctx and the fallback validates fine.
//
// `lastAccessedAt` is plumbed through the plugin result so the
// host can decide whether to fire the update (smart-skip in
// `updateLastAccessedAtIfStale` — no DB roundtrip when the
// cached timestamp is fresher than the throttle window).
const ctx = contextFn ? await contextFn(parsedParams, request) : {};
const patAuth = await rbac.authenticatePat(request, ctx);
if (!patAuth.ok) {
// Same provenance rule as bearer auth: never forward the
// controller's raw `error` string to the client. Log it
// server-side, return a fixed status-derived message.
logger.warn("API PAT auth failed", { status: patAuth.status, error: patAuth.error });
const safe = sanitizeAuthFailure(patAuth);
return await wrapResponse(
request,
json({ error: safe.error }, { status: safe.status }),
corsStrategy !== "none"
);
}
const authenticationResult: PersonalAccessTokenAuthenticationResult = {
userId: patAuth.userId,
};
const ability: RbacAbility = patAuth.ability;
// Fire the `lastAccessedAt` write conditionally. Two-layer throttle:
// JS skips the SQL when the value is fresh (most requests); the
// SQL `WHERE` clause inside the helper is race-safe for concurrent
// auths that both decide to fire. Don't `await` it from the
// critical path? — it's a one-row update on a small hot table and
// we want to surface failures, so it's awaited (same shape as the
// legacy `authenticatePersonalAccessToken`).
await updateLastAccessedAtIfStale(patAuth.tokenId, patAuth.lastAccessedAt);
if (authorization) {
const $resource = authorization.resource(parsedParams, parsedSearchParams, parsedHeaders);
if (!checkAuth(ability, authorization.action, $resource)) {
return await wrapResponse(
request,
json(
{
error: "Unauthorized",
code: "unauthorized",
param: "access_token",
type: "authorization",
},
{ status: 403 }
),
corsStrategy !== "none"
);
}
}
// PAT auth carries `userId` but no environment — enrich the scope
// the Express middleware established with the authenticated user so
// Sentry events from this handler get user-level attribution.
tenantContext.enrich({ userId: authenticationResult.userId });
const result = await handler({
params: parsedParams,
searchParams: parsedSearchParams,
headers: parsedHeaders,
authentication: authenticationResult,
ability,
request,
apiVersion,
});
return await wrapResponse(request, result, corsStrategy !== "none");
} catch (error) {
try {
if (error instanceof Response) {
return await wrapResponse(request, error, corsStrategy !== "none");
}
return await wrapResponse(
request,
json({ error: "Internal Server Error" }, { status: 500 }),
corsStrategy !== "none"
);
} catch (innerError) {
logger.error("[apiBuilder] Failed to handle error", { error, innerError });
return json({ error: "Internal Server Error" }, { status: 500 });
}
}
};
}
type ApiKeyActionRouteBuilderOptions<
TParamsSchema extends AnyZodSchema | undefined = undefined,
TSearchParamsSchema extends AnyZodSchema | undefined = undefined,
THeadersSchema extends AnyZodSchema | undefined = undefined,
TBodySchema extends AnyZodSchema | undefined = undefined,
TResource = never
> = {
params?: TParamsSchema;
searchParams?: TSearchParamsSchema;
headers?: THeadersSchema;
allowJWT?: boolean;
corsStrategy?: "all" | "none";
method?: "POST" | "PUT" | "DELETE" | "PATCH";
findResource?: (
params: TParamsSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<TParamsSchema>
: undefined,
authentication: ApiAuthenticationResultSuccess,
searchParams: TSearchParamsSchema extends
| z.ZodFirstPartySchemaTypes
| z.ZodDiscriminatedUnion<any, any>
? z.infer<TSearchParamsSchema>
: undefined
) => Promise<TResource | undefined>;
authorization?: {
action: string;
resource: (
params: TParamsSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<TParamsSchema>
: undefined,
searchParams: TSearchParamsSchema extends
| z.ZodFirstPartySchemaTypes
| z.ZodDiscriminatedUnion<any, any>
? z.infer<TSearchParamsSchema>
: undefined,
headers: THeadersSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<THeadersSchema>
: undefined,
body: TBodySchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<TBodySchema>
: undefined,
// The resolved resource from `findResource`. `undefined` when the route
// doesn't declare `findResource`. Routes that need to expand the auth
// scope to alternate identifiers of the same row (e.g. friendlyId +
// externalId for sessions) read it here so a JWT minted for either form
// authorizes both URL forms.
resource: TResource | undefined
) => AuthResource;
};
maxContentLength?: number;
body?: TBodySchema;
};
type ApiKeyActionHandlerFunction<
TParamsSchema extends AnyZodSchema | undefined,
TSearchParamsSchema extends AnyZodSchema | undefined,
THeadersSchema extends AnyZodSchema | undefined = undefined,
TBodySchema extends AnyZodSchema | undefined = undefined,
TResource = never
> = (args: {
params: TParamsSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<TParamsSchema>
: undefined;
searchParams: TSearchParamsSchema extends
| z.ZodFirstPartySchemaTypes
| z.ZodDiscriminatedUnion<any, any>
? z.infer<TSearchParamsSchema>
: undefined;
headers: THeadersSchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<THeadersSchema>
: undefined;
body: TBodySchema extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<TBodySchema>
: undefined;
authentication: ApiAuthenticationResultSuccess;
request: Request;
resource?: TResource;
}) => Promise<Response>;
export function createActionApiRoute<
TParamsSchema extends AnyZodSchema | undefined = undefined,
TSearchParamsSchema extends AnyZodSchema | undefined = undefined,
THeadersSchema extends AnyZodSchema | undefined = undefined,
TBodySchema extends AnyZodSchema | undefined = undefined,
TResource = never
>(
options: ApiKeyActionRouteBuilderOptions<
TParamsSchema,
TSearchParamsSchema,
THeadersSchema,
TBodySchema,
TResource
>,
handler: ApiKeyActionHandlerFunction<
TParamsSchema,
TSearchParamsSchema,
THeadersSchema,
TBodySchema,
TResource
>
) {
const {
params: paramsSchema,
searchParams: searchParamsSchema,
headers: headersSchema,
body: bodySchema,
allowJWT = false,
corsStrategy = "none",
authorization,
maxContentLength,
} = options;
async function loader({ request, params }: LoaderFunctionArgs) {
if (corsStrategy !== "none" && request.method.toUpperCase() === "OPTIONS") {
return apiCors(request, json({}));
}
return new Response(null, { status: 405 });
}
async function action({ request, params }: ActionFunctionArgs) {
if (options.method) {
if (request.method.toUpperCase() !== options.method) {
return await wrapResponse(
request,
json(
{ error: "Method not allowed" },
{ status: 405, headers: { Allow: options.method } }
),
corsStrategy !== "none"
);
}
}
try {
const authResult = await authenticateRequestForApiBuilder(request, { allowJWT });
if (!authResult.ok) {
return await wrapResponse(
request,
json({ error: authResult.error }, { status: authResult.status }),
corsStrategy !== "none"
);
}
const { authentication: authenticationResult, ability } = authResult;
if (maxContentLength) {
const contentLength = request.headers.get("content-length");
if (!contentLength || parseInt(contentLength) > maxContentLength) {
return await wrapResponse(
request,
json({ error: "Request body too large" }, { status: 413 }),
corsStrategy !== "none"
);
}
}
let parsedParams: any = undefined;
if (paramsSchema) {
const parsed = paramsSchema.safeParse(params);
if (!parsed.success) {
return await wrapResponse(
request,
json(
{ error: "Params Error", details: fromZodError(parsed.error).details },
{ status: 400 }
),
corsStrategy !== "none"
);
}
parsedParams = parsed.data;
}
let parsedSearchParams: any = undefined;
if (searchParamsSchema) {
const searchParams = Object.fromEntries(new URL(request.url).searchParams);
const parsed = searchParamsSchema.safeParse(searchParams);
if (!parsed.success) {
return await wrapResponse(
request,
json(
{ error: "Query Error", details: fromZodError(parsed.error).details },
{ status: 400 }
),
corsStrategy !== "none"
);
}
parsedSearchParams = parsed.data;
}
let parsedHeaders: any = undefined;
if (headersSchema) {
const rawHeaders = Object.fromEntries(request.headers);
const headers = headersSchema.safeParse(rawHeaders);
if (!headers.success) {
return await wrapResponse(
request,
json(
{ error: "Headers Error", details: fromZodError(headers.error).details },
{ status: 400 }
),
corsStrategy !== "none"
);
}
parsedHeaders = headers.data;
}
let parsedBody: any = undefined;
if (bodySchema) {
const rawBody = await request.text();
if (rawBody.length === 0) {
return await wrapResponse(
request,
json({ error: "Request body is empty" }, { status: 400 }),
corsStrategy !== "none"
);
}
const rawParsedJson = safeJsonParse(rawBody);
if (!rawParsedJson) {
return await wrapResponse(
request,
json({ error: "Invalid JSON" }, { status: 400 }),
corsStrategy !== "none"
);
}
const body = bodySchema.safeParse(rawParsedJson);
if (!body.success) {
return await wrapResponse(
request,
json({ error: fromZodError(body.error).toString() }, { status: 400 }),
corsStrategy !== "none"
);
}
parsedBody = body.data;
}
// Resolve the resource before authorization so the auth scope check
// can expand to alternate identifiers of the same row (e.g. a Session
// is addressable by both `friendlyId` and `externalId` and a JWT minted
// for either form should authorize both URL forms). Mirrors the
// ordering in `createLoaderApiRoute`.
const resource = options.findResource
? await options.findResource(parsedParams, authenticationResult, parsedSearchParams)
: undefined;
// Run authorization first — but with the resolved resource available
// as the 5th arg so the auth scope check can expand to alternate
// identifiers of the same row (e.g. a Session is addressable by both
// `friendlyId` and `externalId`). Resource-null is checked AFTER auth
// so:
// - underscoped JWT + missing resource → 403 (no info leak)
// - underscoped JWT + existing resource → 403 (existing behavior)
// - PRIVATE key + missing resource → auth passes → 404 (correct)
// - PRIVATE key + existing resource → auth passes → handler runs
if (authorization) {
const { action, resource: authResource } = authorization;
const $resource = authResource(
parsedParams,
parsedSearchParams,
parsedHeaders,
parsedBody,
resource
);
if (!checkAuth(ability, action, $resource)) {
return await wrapResponse(
request,
json(
{
error: "Unauthorized",
code: "unauthorized",
param: "access_token",
type: "authorization",
},
{ status: 403 }
),
corsStrategy !== "none"
);
}
}
if (options.findResource && !resource) {
return await wrapResponse(
request,
json({ error: "Resource not found" }, { status: 404 }),
corsStrategy !== "none"
);
}
const result = await tenantContext.run(
tenantContextFromAuthEnvironment(authenticationResult.environment),
() =>
handler({
params: parsedParams,
searchParams: parsedSearchParams,
headers: parsedHeaders,
body: parsedBody,
authentication: authenticationResult,
request,
resource,
})
);
return await wrapResponse(request, result, corsStrategy !== "none");
} catch (error) {
try {
if (error instanceof Response) {
return await wrapResponse(request, error, corsStrategy !== "none");
}
logBoundaryError("Error in action", error, request.url);
return await wrapResponse(
request,
json({ error: "Internal Server Error" }, { status: 500 }),
corsStrategy !== "none"
);
} catch (innerError) {
logger.error("[apiBuilder] Failed to handle error", { error, innerError });
return json({ error: "Internal Server Error" }, { status: 500 });
}
}
}
return { loader, action };
}
// ---------------------------------------------------------------------------
// Multi-method action route builder
// ---------------------------------------------------------------------------
type HttpMethod = "POST" | "PUT" | "PATCH" | "DELETE";
type InferZod<T> = T extends z.ZodFirstPartySchemaTypes | z.ZodDiscriminatedUnion<any, any>
? z.infer<T>
: undefined;
type MethodHandlerArgs<TParamsSchema, TSearchParamsSchema, THeadersSchema, TBodySchema> = {
params: InferZod<TParamsSchema>;
searchParams: InferZod<TSearchParamsSchema>;
headers: InferZod<THeadersSchema>;
body: InferZod<TBodySchema>;
authentication: ApiAuthenticationResultSuccess;
request: Request;
};
type MethodConfig<TParamsSchema, TSearchParamsSchema, THeadersSchema> = {
body?: AnyZodSchema;
handler: (
args: MethodHandlerArgs<TParamsSchema, TSearchParamsSchema, THeadersSchema, any>
) => Promise<Response>;
};
type MultiMethodApiRouteOptions<