@sixb/server 0.1.12 → 0.1.13

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.
Files changed (85) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/access-token-boundary.d.ts +13 -9
  3. package/dist/auth/access-token-boundary.d.ts.map +1 -1
  4. package/dist/auth/client-address.d.ts +12 -0
  5. package/dist/auth/client-address.d.ts.map +1 -0
  6. package/dist/auth/guard.d.ts.map +1 -1
  7. package/dist/auth/public-routes.d.ts +5 -0
  8. package/dist/auth/public-routes.d.ts.map +1 -1
  9. package/dist/auth/rate-limit.d.ts +15 -0
  10. package/dist/auth/rate-limit.d.ts.map +1 -0
  11. package/dist/auth/scope.d.ts +8 -3
  12. package/dist/auth/scope.d.ts.map +1 -1
  13. package/dist/auth/shared-access.d.ts.map +1 -1
  14. package/dist/index.js +578 -455
  15. package/dist/index.js.map +40 -38
  16. package/dist/openapi/security.d.ts +34 -10
  17. package/dist/openapi/security.d.ts.map +1 -1
  18. package/dist/routes/auth.d.ts +64 -17
  19. package/dist/routes/auth.d.ts.map +1 -1
  20. package/dist/routes/connectors.d.ts.map +1 -1
  21. package/dist/routes/events.d.ts +0 -4
  22. package/dist/routes/events.d.ts.map +1 -1
  23. package/dist/routes/files.d.ts +15 -2
  24. package/dist/routes/files.d.ts.map +1 -1
  25. package/dist/routes/models.d.ts +7 -7
  26. package/dist/routes/ontology.d.ts +13 -1
  27. package/dist/routes/ontology.d.ts.map +1 -1
  28. package/dist/routes/shared-access.d.ts.map +1 -1
  29. package/dist/routes/workflows.d.ts +30 -30
  30. package/dist/routes/workflows.d.ts.map +1 -1
  31. package/dist/routes/ws/agents.d.ts +2 -3
  32. package/dist/routes/ws/agents.d.ts.map +1 -1
  33. package/dist/schemas/auth.d.ts +241 -85
  34. package/dist/schemas/auth.d.ts.map +1 -1
  35. package/dist/schemas/common.d.ts +11 -0
  36. package/dist/schemas/common.d.ts.map +1 -1
  37. package/dist/schemas/events.d.ts +74 -44
  38. package/dist/schemas/events.d.ts.map +1 -1
  39. package/dist/schemas/models.d.ts +38 -38
  40. package/dist/schemas/ontology.d.ts +160 -0
  41. package/dist/schemas/ontology.d.ts.map +1 -1
  42. package/dist/schemas/workflows.d.ts +180 -190
  43. package/dist/schemas/workflows.d.ts.map +1 -1
  44. package/dist/server.d.ts +6 -0
  45. package/dist/server.d.ts.map +1 -1
  46. package/dist/utils/ws.d.ts +1 -2
  47. package/dist/utils/ws.d.ts.map +1 -1
  48. package/package.json +4 -4
  49. package/src/auth/access-token-boundary.ts +31 -30
  50. package/src/auth/client-address.ts +67 -0
  51. package/src/auth/guard.ts +13 -4
  52. package/src/auth/public-routes.ts +9 -2
  53. package/src/auth/rate-limit.ts +43 -0
  54. package/src/auth/scope.ts +13 -3
  55. package/src/auth/shared-access.ts +0 -3
  56. package/src/openapi/security.ts +37 -17
  57. package/src/routes/action-runs.ts +5 -5
  58. package/src/routes/actions.ts +4 -4
  59. package/src/routes/agents.ts +9 -9
  60. package/src/routes/ai-accounting.ts +10 -10
  61. package/src/routes/auth.ts +331 -432
  62. package/src/routes/connector-connection-runs.ts +5 -5
  63. package/src/routes/connector-connections.ts +3 -3
  64. package/src/routes/connectors.ts +2 -2
  65. package/src/routes/events.ts +2 -2
  66. package/src/routes/files.ts +30 -15
  67. package/src/routes/links.ts +3 -3
  68. package/src/routes/logs.ts +2 -2
  69. package/src/routes/objects.ts +12 -12
  70. package/src/routes/ontology.ts +27 -9
  71. package/src/routes/pipelines.ts +2 -2
  72. package/src/routes/project.ts +2 -2
  73. package/src/routes/share-grants.ts +4 -4
  74. package/src/routes/shared-access.ts +3 -2
  75. package/src/routes/syncs.ts +2 -2
  76. package/src/routes/telemetry.ts +5 -5
  77. package/src/routes/workflows.ts +18 -19
  78. package/src/routes/ws/agents.ts +4 -5
  79. package/src/schemas/auth.ts +27 -8
  80. package/src/schemas/common.ts +6 -0
  81. package/src/schemas/events.ts +35 -7
  82. package/src/schemas/ontology.ts +16 -1
  83. package/src/schemas/workflows.ts +4 -9
  84. package/src/server.ts +35 -5
  85. package/src/utils/ws.ts +2 -3
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // src/server.ts
3
3
  import { cors } from "@elysiajs/cors";
4
4
  import { openapi } from "@elysiajs/openapi";
5
- import { CSRF_HEADER_NAME as CSRF_HEADER_NAME3 } from "@sixb/core/internal/auth";
5
+ import { CSRF_HEADER_NAME as CSRF_HEADER_NAME2, setRequestClientAddress } from "@sixb/core/internal/auth";
6
6
  import { bindRequestExecution } from "@sixb/core/internal/request-execution";
7
7
  import { Elysia } from "elysia";
8
8
  import { websocket as elysiaWebSocket } from "elysia/ws";
@@ -228,6 +228,53 @@ function normalizeHttpOrigin(value, label) {
228
228
  return url.origin;
229
229
  }
230
230
 
231
+ // src/auth/client-address.ts
232
+ import { BlockList, isIP, isIPv4 } from "net";
233
+ var PRIVATE_NETWORKS = "private";
234
+ var PRIVATE_NETWORK_RANGES = [
235
+ "127.0.0.0/8",
236
+ "10.0.0.0/8",
237
+ "172.16.0.0/12",
238
+ "192.168.0.0/16",
239
+ "169.254.0.0/16",
240
+ "::1/128",
241
+ "fc00::/7",
242
+ "fe80::/10"
243
+ ];
244
+ function createClientAddressResolver(trustedProxies) {
245
+ const trusted = new BlockList;
246
+ for (const entry of trustedProxies.flatMap((value) => value === PRIVATE_NETWORKS ? PRIVATE_NETWORK_RANGES : [value])) {
247
+ addTrustedRange(trusted, entry);
248
+ }
249
+ const isTrusted = (address) => trusted.check(address, isIPv4(address) ? "ipv4" : "ipv6");
250
+ return (socketAddress, forwardedFor) => {
251
+ let address = normalizeAddress(socketAddress);
252
+ const hops = forwardedFor?.split(",") ?? [];
253
+ for (let index = hops.length - 1;index >= 0 && isTrusted(address); index -= 1) {
254
+ const hop = normalizeAddress(hops[index]?.trim() ?? "");
255
+ if (!isIP(hop))
256
+ break;
257
+ address = hop;
258
+ }
259
+ return address;
260
+ };
261
+ }
262
+ function addTrustedRange(list, entry) {
263
+ const [address = "", prefix, ...rest] = entry.split("/");
264
+ const family = isIP(address);
265
+ const maxBits = family === 4 ? 32 : 128;
266
+ const bits = prefix === undefined ? maxBits : Number(prefix);
267
+ const validPrefix = prefix === undefined || /^\d{1,3}$/.test(prefix);
268
+ if (!family || !validPrefix || rest.length > 0 || bits > maxBits) {
269
+ throw new Error(`[SixbServer] Trusted proxy '${entry}' is not an IP address, CIDR range, or '${PRIVATE_NETWORKS}'.`);
270
+ }
271
+ list.addSubnet(address, bits, family === 4 ? "ipv4" : "ipv6");
272
+ }
273
+ function normalizeAddress(address) {
274
+ const lower = address.toLowerCase();
275
+ return lower.startsWith("::ffff:") && isIPv4(lower.slice(7)) ? lower.slice(7) : lower;
276
+ }
277
+
231
278
  // src/auth/csrf.ts
232
279
  var CSRF_TOKEN_RESPONSE_HEADER_NAME = "x-sixb-csrf-token";
233
280
 
@@ -241,12 +288,11 @@ import { isCsrfExemptMethod as isCsrfExemptMethod2 } from "@sixb/core/internal/a
241
288
  import { matchesPathPattern as matchesPathPattern3, normalizeRoutePath as normalizeRoutePath3, SIXB_API_ROUTES as SIXB_API_ROUTES3 } from "@sixb/core/internal/http";
242
289
 
243
290
  // src/openapi/security.ts
244
- import { CSRF_HEADER_NAME as CSRF_HEADER_NAME2 } from "@sixb/core/internal/auth";
291
+ import { CSRF_HEADER_NAME } from "@sixb/core/internal/auth";
245
292
 
246
293
  // src/auth/shared-access.ts
247
294
  import { createHash } from "crypto";
248
295
  import {
249
- CSRF_HEADER_NAME,
250
296
  generateCsrfToken,
251
297
  getCookie,
252
298
  isCsrfExemptMethod,
@@ -316,8 +362,7 @@ class SharedAccessBoundary {
316
362
  return { kind: "deny", response: sharedAccessUnauthenticatedResponse() };
317
363
  }
318
364
  if (!isCsrfExemptMethod(request.method) && !verifyDoubleSubmitCsrf(request, {
319
- cookieName: sharedCookieNames(selectedGrantId).csrf,
320
- headerName: CSRF_HEADER_NAME
365
+ cookieName: sharedCookieNames(selectedGrantId).csrf
321
366
  })) {
322
367
  return { kind: "deny", response: sharedAccessForbiddenResponse() };
323
368
  }
@@ -387,8 +432,7 @@ class SharedAccessBoundary {
387
432
  if (!resolved)
388
433
  return { kind: "invalid", setCookies: clearCookies };
389
434
  if (!verifyDoubleSubmitCsrf(request, {
390
- cookieName: sharedCookieNames(grantId).csrf,
391
- headerName: CSRF_HEADER_NAME
435
+ cookieName: sharedCookieNames(grantId).csrf
392
436
  })) {
393
437
  return { kind: "csrf" };
394
438
  }
@@ -533,22 +577,18 @@ function isStoredIdentifier(value) {
533
577
 
534
578
  // src/openapi/security.ts
535
579
  var SIXB_CSRF_SECURITY_SCHEME_ID = "sixbCsrf";
536
- var SIXB_BEARER_SECURITY_SCHEME_ID = "sixbBearer";
580
+ var SIXB_SESSION_SECURITY_SCHEME_ID = "sixbSession";
581
+ var SIXB_ACCESS_TOKEN_SECURITY_SCHEME_ID = "sixbAccessToken";
537
582
  var SIXB_SHARED_GRANT_SECURITY_SCHEME_ID = "sixbSharedGrant";
538
- var SIXB_CSRF_SECURITY_REQUIREMENT = [
539
- {
540
- [SIXB_CSRF_SECURITY_SCHEME_ID]: []
541
- }
542
- ];
543
- var SIXB_BEARER_SECURITY_REQUIREMENT = [
544
- {
545
- [SIXB_BEARER_SECURITY_SCHEME_ID]: []
546
- }
547
- ];
548
- var SIXB_CSRF_OR_BEARER_SECURITY_REQUIREMENT = [
549
- ...SIXB_CSRF_SECURITY_REQUIREMENT,
550
- ...SIXB_BEARER_SECURITY_REQUIREMENT
551
- ];
583
+ var csrf = { [SIXB_CSRF_SECURITY_SCHEME_ID]: [] };
584
+ var session = { [SIXB_SESSION_SECURITY_SCHEME_ID]: [] };
585
+ var accessToken = { [SIXB_ACCESS_TOKEN_SECURITY_SCHEME_ID]: [] };
586
+ var SIXB_SESSION_SECURITY_REQUIREMENT = [session];
587
+ var SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT = [csrf, session];
588
+ var SIXB_OPTIONAL_SESSION_SECURITY_REQUIREMENT = [session, {}];
589
+ var SIXB_OPTIONAL_SESSION_MUTATION_SECURITY_REQUIREMENT = [csrf, session, {}];
590
+ var SIXB_ACCESS_TOKEN_READ_SECURITY_REQUIREMENT = [accessToken, session];
591
+ var SIXB_ACCESS_TOKEN_MUTATION_SECURITY_REQUIREMENT = [csrf, accessToken, session];
552
592
  var SIXB_SHARED_READ_SECURITY_REQUIREMENT = {
553
593
  [SIXB_SHARED_GRANT_SECURITY_SCHEME_ID]: []
554
594
  };
@@ -559,14 +599,20 @@ var SIXB_SHARED_MUTATION_SECURITY_REQUIREMENT = {
559
599
  var SIXB_CSRF_SECURITY_SCHEME = {
560
600
  type: "apiKey",
561
601
  in: "header",
562
- name: CSRF_HEADER_NAME2,
602
+ name: CSRF_HEADER_NAME,
563
603
  description: "Required for cookie-authenticated mutating requests. Use the csrfToken returned by the corresponding session endpoint."
564
604
  };
565
- var SIXB_BEARER_SECURITY_SCHEME = {
605
+ var SIXB_SESSION_SECURITY_SCHEME = {
606
+ type: "http",
607
+ scheme: "bearer",
608
+ bearerFormat: "Sixb session access token",
609
+ description: "A signed-in native client's session access token, from device login and renewed through /api/auth/refresh. Accepted wherever a browser session is; browsers authenticate with the session cookie instead."
610
+ };
611
+ var SIXB_ACCESS_TOKEN_SECURITY_SCHEME = {
566
612
  type: "http",
567
613
  scheme: "bearer",
568
614
  bearerFormat: "Sixb access token",
569
- description: "Use a Sixb personal access token or service-account token. Bearer tokens are accepted only on routes that explicitly document this scheme."
615
+ description: "A personal access token or service-account token, for scripts and services. Accepted only on routes that document this scheme. A native client's session token uses sixbSession instead."
570
616
  };
571
617
  var SIXB_SHARED_GRANT_SECURITY_SCHEME = {
572
618
  type: "apiKey",
@@ -582,12 +628,12 @@ var ACCESS_TOKEN_ROUTES = SIXB_API_ROUTES3.filter((route) => route.accessToken).
582
628
  path: route.path,
583
629
  sharedSession: route.sharedSession ?? false
584
630
  }));
585
- function bearerSecurityRequirement(operationId) {
631
+ function accessTokenSecurityRequirement(operationId) {
586
632
  const route = ACCESS_TOKEN_ROUTES.find((candidate) => candidate.operationId === operationId);
587
633
  if (!route) {
588
- throw new Error(`[SixbServer] '${operationId}' is not a registered bearer route. Add it to ACCESS_TOKEN_ROUTES.`);
634
+ throw new Error(`[SixbServer] '${operationId}' is not a registered access-token route. Add it to ACCESS_TOKEN_ROUTES.`);
589
635
  }
590
- const standard = isCsrfExemptMethod2(route.method) ? SIXB_BEARER_SECURITY_REQUIREMENT : SIXB_CSRF_OR_BEARER_SECURITY_REQUIREMENT;
636
+ const standard = isCsrfExemptMethod2(route.method) ? SIXB_ACCESS_TOKEN_READ_SECURITY_REQUIREMENT : SIXB_ACCESS_TOKEN_MUTATION_SECURITY_REQUIREMENT;
591
637
  if (!route.sharedSession)
592
638
  return standard;
593
639
  return [
@@ -601,8 +647,11 @@ function isAccessTokenRoute(request) {
601
647
  const pathname = normalizeRoutePath3(url.pathname);
602
648
  return ACCESS_TOKEN_ROUTES.some((route) => route.method === method && matchesPathPattern3(pathname, route.path));
603
649
  }
604
- function shouldVerifyCsrfForAuthSource(route, source) {
605
- return route.csrfProtected && source === "session";
650
+ function credentialTransport(caller) {
651
+ return caller.credentialSource === "session" && !caller.session.bearer ? "cookie" : "bearer";
652
+ }
653
+ function shouldVerifyCsrf(route, transport) {
654
+ return route.csrfProtected && transport === "cookie";
606
655
  }
607
656
 
608
657
  // src/auth/application-access.ts
@@ -629,7 +678,7 @@ function classifyRoute(request) {
629
678
  return { kind: "api", csrfProtected: !isCsrfExemptMethod3(request.method) };
630
679
  }
631
680
  if (pathname === "/auth/device") {
632
- return { kind: "html", csrfProtected: !isCsrfExemptMethod3(request.method) };
681
+ return { kind: "html", csrfProtected: !isCsrfExemptMethod3(request.method), account: true };
633
682
  }
634
683
  if (pathname === "/docs" || pathname.startsWith("/docs/")) {
635
684
  return { kind: "html", csrfProtected: !isCsrfExemptMethod3(request.method) };
@@ -662,7 +711,7 @@ function isPublicRoute(pathname, method) {
662
711
  if (pathname === "/api/auth/sign-out" && normalizedMethod === "POST") {
663
712
  return true;
664
713
  }
665
- if ((pathname === "/api/auth/device-authorizations" || pathname === "/api/auth/device-authorizations/token") && normalizedMethod === "POST") {
714
+ if ((pathname === "/api/auth/device-authorizations" || pathname === "/api/auth/device-authorizations/token" || pathname === "/api/auth/refresh") && normalizedMethod === "POST") {
666
715
  return true;
667
716
  }
668
717
  if (pathname === "/auth/device" && normalizedMethod === "POST") {
@@ -787,7 +836,8 @@ class ServerAuthGuard {
787
836
  }
788
837
  return { kind: "deny", response: jsonAuthRequiredResponse() };
789
838
  }
790
- if (!sessionCanAccessApplication(this.host, session, authContext.audience)) {
839
+ const deniedApplication = (caller) => !route.account && credentialTransport(caller) === "cookie" && !sessionCanAccessApplication(this.host, caller, authContext.audience);
840
+ if (deniedApplication(session)) {
791
841
  return {
792
842
  kind: "deny",
793
843
  response: jsonForbiddenResponse("Application access is not allowed")
@@ -799,10 +849,10 @@ class ServerAuthGuard {
799
849
  response: jsonForbiddenResponse("Access tokens cannot authenticate this route")
800
850
  };
801
851
  }
802
- if (shouldVerifyCsrfForAuthSource(route, session.credentialSource) && !this.verifyCsrf(request, session)) {
852
+ if (shouldVerifyCsrf(route, credentialTransport(session)) && !this.verifyCsrf(request, session)) {
803
853
  return { kind: "deny", response: jsonCsrfFailedResponse() };
804
854
  }
805
- if (session.credentialSource === "session" && route.kind !== "websocket" && !isSessionTerminationRequest(request) && hasForegroundSessionActivity(request)) {
855
+ if (session.credentialSource === "session" && credentialTransport(session) === "cookie" && route.kind !== "websocket" && !isSessionTerminationRequest(request) && hasForegroundSessionActivity(request)) {
806
856
  const activeSession = await this.host.auth.getSession(request, {
807
857
  audience: authContext.audience,
808
858
  credentialSource: "session",
@@ -820,7 +870,7 @@ class ServerAuthGuard {
820
870
  }
821
871
  return { kind: "deny", response: jsonAuthRequiredResponse() };
822
872
  }
823
- if (!sessionCanAccessApplication(this.host, activeSession, authContext.audience)) {
873
+ if (deniedApplication(activeSession)) {
824
874
  return {
825
875
  kind: "deny",
826
876
  response: jsonForbiddenResponse("Application access is not allowed")
@@ -878,6 +928,10 @@ function requireRequestSixb(context) {
878
928
  }
879
929
  return sixb;
880
930
  }
931
+ function requestCaller(context) {
932
+ const auth = context.auth;
933
+ return auth?.kind === "allow" ? auth.session : null;
934
+ }
881
935
 
882
936
  // src/auth/session-cookies.ts
883
937
  import {
@@ -1425,6 +1479,10 @@ function codedErrorResponseSchema(codes) {
1425
1479
  });
1426
1480
  }
1427
1481
  var SuccessResponseSchema = z.object({ success: z.boolean() });
1482
+ var PrincipalSchema = z.object({
1483
+ type: z.enum(["user", "serviceAccount", "system"]),
1484
+ id: z.string().min(1)
1485
+ });
1428
1486
  var JsonValueSchema = z.lazy(() => z.union([
1429
1487
  z.string(),
1430
1488
  z.number().finite(),
@@ -1496,6 +1554,15 @@ var PropertyDefinitionSchema = z2.object({
1496
1554
  weight: z2.number().optional()
1497
1555
  }).optional()
1498
1556
  });
1557
+ var PropertyQueryCapabilitiesSchema = z2.object({
1558
+ operators: z2.array(z2.enum(["eq", "neq", "lt", "lte", "gt", "gte", "in", "exists", "contains"])),
1559
+ sortable: z2.boolean(),
1560
+ facet: z2.boolean(),
1561
+ text: z2.boolean()
1562
+ }).describe("What object queries accept for this property, resolved from its schema and query metadata.");
1563
+ var ObjectPropertyDefinitionSchema = PropertyDefinitionSchema.extend({
1564
+ capabilities: PropertyQueryCapabilitiesSchema
1565
+ });
1499
1566
  var LinkDefinitionSchema = z2.object({
1500
1567
  id: z2.string(),
1501
1568
  name: z2.string(),
@@ -1525,7 +1592,7 @@ var ObjectTypeSchema = z2.object({
1525
1592
  description: z2.string().optional(),
1526
1593
  extends: z2.string().optional(),
1527
1594
  implements: z2.array(z2.string()).optional(),
1528
- properties: z2.array(PropertyDefinitionSchema),
1595
+ properties: z2.array(ObjectPropertyDefinitionSchema),
1529
1596
  search: z2.object({
1530
1597
  title: z2.string().optional(),
1531
1598
  defaultText: z2.array(z2.string()).optional(),
@@ -2014,7 +2081,7 @@ function registerActionRunRoutes(app, host) {
2014
2081
  summary: "List action run history",
2015
2082
  tags: [OPENAPI_TAGS.actionRuns.name],
2016
2083
  operationId: "listActionRuns",
2017
- security: bearerSecurityRequirement("listActionRuns")
2084
+ security: accessTokenSecurityRequirement("listActionRuns")
2018
2085
  }
2019
2086
  }).get("/api/action-runs/:runId", async (context) => {
2020
2087
  const { params, set } = context;
@@ -2045,7 +2112,7 @@ function registerActionRunRoutes(app, host) {
2045
2112
  summary: "Get action run detail",
2046
2113
  tags: [OPENAPI_TAGS.actionRuns.name],
2047
2114
  operationId: "getActionRun",
2048
- security: bearerSecurityRequirement("getActionRun")
2115
+ security: accessTokenSecurityRequirement("getActionRun")
2049
2116
  }
2050
2117
  }).get("/api/action-runs/:runId/files/content", (context) => actionRunFileContentResponse(host, context), {
2051
2118
  params: ActionRunIdParamsSchema,
@@ -2055,7 +2122,7 @@ function registerActionRunRoutes(app, host) {
2055
2122
  summary: "Get action run file content",
2056
2123
  tags: ["Actions"],
2057
2124
  operationId: "getActionRunFileContent",
2058
- security: bearerSecurityRequirement("getActionRunFileContent"),
2125
+ security: accessTokenSecurityRequirement("getActionRunFileContent"),
2059
2126
  responses: fileContentGetResponses({ optionalStorage: true })
2060
2127
  }
2061
2128
  }).head("/api/action-runs/:runId/files/content", (context) => actionRunFileContentResponse(host, context, { head: true }), {
@@ -2066,7 +2133,7 @@ function registerActionRunRoutes(app, host) {
2066
2133
  summary: "Head action run file content",
2067
2134
  tags: ["Actions"],
2068
2135
  operationId: "headActionRunFileContent",
2069
- security: bearerSecurityRequirement("headActionRunFileContent"),
2136
+ security: accessTokenSecurityRequirement("headActionRunFileContent"),
2070
2137
  responses: fileContentHeadResponses({ optionalStorage: true })
2071
2138
  }
2072
2139
  });
@@ -2111,7 +2178,7 @@ function registerActionRoutes(app, host) {
2111
2178
  summary: "List registered actions",
2112
2179
  tags: [OPENAPI_TAGS.actions.name],
2113
2180
  operationId: "listActions",
2114
- security: bearerSecurityRequirement("listActions")
2181
+ security: accessTokenSecurityRequirement("listActions")
2115
2182
  }
2116
2183
  }).get("/api/actions/:actionId", async (context) => {
2117
2184
  const { params, set } = context;
@@ -2128,7 +2195,7 @@ function registerActionRoutes(app, host) {
2128
2195
  summary: "Get action metadata",
2129
2196
  tags: [OPENAPI_TAGS.actions.name],
2130
2197
  operationId: "getAction",
2131
- security: bearerSecurityRequirement("getAction")
2198
+ security: accessTokenSecurityRequirement("getAction")
2132
2199
  }
2133
2200
  }).post("/api/actions/:actionId", async (context) => {
2134
2201
  const { params, body, set } = context;
@@ -2160,7 +2227,7 @@ function registerActionRoutes(app, host) {
2160
2227
  summary: "Request an action",
2161
2228
  tags: [OPENAPI_TAGS.actions.name],
2162
2229
  operationId: "requestAction",
2163
- security: bearerSecurityRequirement("requestAction")
2230
+ security: accessTokenSecurityRequirement("requestAction")
2164
2231
  }
2165
2232
  });
2166
2233
  }
@@ -2180,7 +2247,6 @@ import { normalizeRoutePath as normalizeRoutePath4, pathSegmentsFor } from "@six
2180
2247
  // src/routes/files.ts
2181
2248
  import {
2182
2249
  DEFAULT_SIMPLE_FILE_UPLOAD_BYTES,
2183
- InMemoryFileUploadSessions,
2184
2250
  SYSTEM_PRINCIPAL
2185
2251
  } from "@sixb/core";
2186
2252
  import { computeBlobDigest, supportsDirectUpload } from "@sixb/core/blob-storage/server";
@@ -2188,7 +2254,7 @@ import { createFileUploadId, createUploadExpiresAt } from "@sixb/core/internal/s
2188
2254
  import { FileUploadSessionError as FileUploadSessionError2 } from "@sixb/core/storage";
2189
2255
  var DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES = DEFAULT_SIMPLE_FILE_UPLOAD_BYTES + 1024 * 1024;
2190
2256
  function registerFileRoutes(app, host) {
2191
- const uploadSessions = host.storage.fileUploadSessions ?? new InMemoryFileUploadSessions;
2257
+ const uploadSessions = host.storage.fileUploadSessions;
2192
2258
  return app.post("/api/files", async ({ request, set }) => {
2193
2259
  try {
2194
2260
  const requestSizeError = requestSizeLimitError(request, DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES);
@@ -2233,7 +2299,7 @@ function registerFileRoutes(app, host) {
2233
2299
  summary: "Upload a file",
2234
2300
  tags: [OPENAPI_TAGS.files.name],
2235
2301
  operationId: "uploadFileRaw",
2236
- security: bearerSecurityRequirement("uploadFileRaw"),
2302
+ security: accessTokenSecurityRequirement("uploadFileRaw"),
2237
2303
  requestBody: {
2238
2304
  required: true,
2239
2305
  content: {
@@ -2258,6 +2324,9 @@ function registerFileRoutes(app, host) {
2258
2324
  }).post("/api/files/uploads", async (context) => {
2259
2325
  const { body, set } = context;
2260
2326
  try {
2327
+ if (!uploadSessions) {
2328
+ return unconfiguredStorageResponse2(set, "File upload session storage");
2329
+ }
2261
2330
  const parsed = CreateFileUploadBodySchema.parse(body);
2262
2331
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2263
2332
  const uploadId = createFileUploadId();
@@ -2294,17 +2363,21 @@ function registerFileRoutes(app, host) {
2294
2363
  body: CreateFileUploadBodySchema,
2295
2364
  response: {
2296
2365
  201: CreateFileUploadResponseSchema,
2297
- 400: ErrorResponseSchema
2366
+ 400: ErrorResponseSchema,
2367
+ 501: ErrorResponseSchema
2298
2368
  },
2299
2369
  detail: {
2300
2370
  summary: "Create a staged file upload",
2301
2371
  tags: [OPENAPI_TAGS.files.name],
2302
2372
  operationId: "createFileUpload",
2303
- security: SIXB_CSRF_SECURITY_REQUIREMENT
2373
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
2304
2374
  }
2305
2375
  }).put("/api/files/uploads/:uploadId/content", async (context) => {
2306
2376
  const { params, request, set } = context;
2307
2377
  try {
2378
+ if (!uploadSessions) {
2379
+ return unconfiguredStorageResponse2(set, "File upload session storage");
2380
+ }
2308
2381
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2309
2382
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
2310
2383
  if (session.status !== "pending") {
@@ -2355,13 +2428,14 @@ function registerFileRoutes(app, host) {
2355
2428
  400: ErrorResponseSchema,
2356
2429
  404: ErrorResponseSchema,
2357
2430
  409: ErrorResponseSchema,
2358
- 410: ErrorResponseSchema
2431
+ 410: ErrorResponseSchema,
2432
+ 501: ErrorResponseSchema
2359
2433
  },
2360
2434
  detail: {
2361
2435
  summary: "Upload staged file content through Sixb",
2362
2436
  tags: [OPENAPI_TAGS.files.name],
2363
2437
  operationId: "uploadFileContent",
2364
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
2438
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
2365
2439
  requestBody: {
2366
2440
  required: true,
2367
2441
  content: {
@@ -2377,6 +2451,9 @@ function registerFileRoutes(app, host) {
2377
2451
  }).post("/api/files/uploads/:uploadId/parts/:partNumber", async (context) => {
2378
2452
  const { params, set } = context;
2379
2453
  try {
2454
+ if (!uploadSessions) {
2455
+ return unconfiguredStorageResponse2(set, "File upload session storage");
2456
+ }
2380
2457
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2381
2458
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
2382
2459
  if (session.status !== "pending") {
@@ -2412,17 +2489,21 @@ function registerFileRoutes(app, host) {
2412
2489
  400: ErrorResponseSchema,
2413
2490
  404: ErrorResponseSchema,
2414
2491
  409: ErrorResponseSchema,
2415
- 410: ErrorResponseSchema
2492
+ 410: ErrorResponseSchema,
2493
+ 501: ErrorResponseSchema
2416
2494
  },
2417
2495
  detail: {
2418
2496
  summary: "Sign a staged multipart upload part",
2419
2497
  tags: [OPENAPI_TAGS.files.name],
2420
2498
  operationId: "signFileUploadPart",
2421
- security: SIXB_CSRF_SECURITY_REQUIREMENT
2499
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
2422
2500
  }
2423
2501
  }).post("/api/files/uploads/:uploadId/complete", async (context) => {
2424
2502
  const { body, params, set } = context;
2425
2503
  try {
2504
+ if (!uploadSessions) {
2505
+ return unconfiguredStorageResponse2(set, "File upload session storage");
2506
+ }
2426
2507
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2427
2508
  const parsed = CompleteFileUploadBodySchema.parse(body ?? {});
2428
2509
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
@@ -2464,17 +2545,21 @@ function registerFileRoutes(app, host) {
2464
2545
  400: ErrorResponseSchema,
2465
2546
  404: ErrorResponseSchema,
2466
2547
  409: ErrorResponseSchema,
2467
- 410: ErrorResponseSchema
2548
+ 410: ErrorResponseSchema,
2549
+ 501: ErrorResponseSchema
2468
2550
  },
2469
2551
  detail: {
2470
2552
  summary: "Complete a staged file upload",
2471
2553
  tags: [OPENAPI_TAGS.files.name],
2472
2554
  operationId: "completeFileUpload",
2473
- security: SIXB_CSRF_SECURITY_REQUIREMENT
2555
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
2474
2556
  }
2475
2557
  }).post("/api/files/uploads/:uploadId/abort", async (context) => {
2476
2558
  const { params, set } = context;
2477
2559
  try {
2560
+ if (!uploadSessions) {
2561
+ return unconfiguredStorageResponse2(set, "File upload session storage");
2562
+ }
2478
2563
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2479
2564
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
2480
2565
  if (session.status === "completed") {
@@ -2505,13 +2590,14 @@ function registerFileRoutes(app, host) {
2505
2590
  400: ErrorResponseSchema,
2506
2591
  404: ErrorResponseSchema,
2507
2592
  409: ErrorResponseSchema,
2508
- 410: ErrorResponseSchema
2593
+ 410: ErrorResponseSchema,
2594
+ 501: ErrorResponseSchema
2509
2595
  },
2510
2596
  detail: {
2511
2597
  summary: "Abort a staged file upload",
2512
2598
  tags: [OPENAPI_TAGS.files.name],
2513
2599
  operationId: "abortFileUpload",
2514
- security: SIXB_CSRF_SECURITY_REQUIREMENT
2600
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
2515
2601
  }
2516
2602
  });
2517
2603
  }
@@ -3721,7 +3807,7 @@ function registerAgentRoutes(app, host) {
3721
3807
  summary: "Create an agent thread",
3722
3808
  tags: [OPENAPI_TAGS.agentThreads.name],
3723
3809
  operationId: "createAgentThread",
3724
- security: SIXB_CSRF_SECURITY_REQUIREMENT
3810
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
3725
3811
  }
3726
3812
  }).get("/api/agent-threads/:threadId", async (context) => {
3727
3813
  const { params, set } = context;
@@ -3778,7 +3864,7 @@ function registerAgentRoutes(app, host) {
3778
3864
  summary: "Explicitly recreate an unavailable or uncertain workspace without deleting its previous state",
3779
3865
  operationId: "recreateAgentThreadSandbox",
3780
3866
  tags: [OPENAPI_TAGS.agentThreads.name],
3781
- security: SIXB_CSRF_SECURITY_REQUIREMENT
3867
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
3782
3868
  }
3783
3869
  }).get("/api/agent-threads/:threadId/messages", async (context) => {
3784
3870
  const { params, query, set } = context;
@@ -3840,7 +3926,7 @@ function registerAgentRoutes(app, host) {
3840
3926
  summary: "Get agent message file content",
3841
3927
  tags: ["Agents"],
3842
3928
  operationId: "getAgentMessageFileContent",
3843
- security: bearerSecurityRequirement("getAgentMessageFileContent"),
3929
+ security: accessTokenSecurityRequirement("getAgentMessageFileContent"),
3844
3930
  responses: fileContentGetResponses({ optionalStorage: true })
3845
3931
  }
3846
3932
  }).head("/api/agent-threads/:threadId/messages/:messageId/files/content", async (context) => agentMessageFileContentResponse(host, context, { head: true }), {
@@ -3850,7 +3936,7 @@ function registerAgentRoutes(app, host) {
3850
3936
  summary: "Head agent message file content",
3851
3937
  tags: ["Agents"],
3852
3938
  operationId: "headAgentMessageFileContent",
3853
- security: bearerSecurityRequirement("headAgentMessageFileContent"),
3939
+ security: accessTokenSecurityRequirement("headAgentMessageFileContent"),
3854
3940
  responses: fileContentHeadResponses({ optionalStorage: true })
3855
3941
  }
3856
3942
  }).post("/api/agent-threads/:threadId/messages", async (context) => {
@@ -3900,7 +3986,7 @@ function registerAgentRoutes(app, host) {
3900
3986
  summary: "Post an agent thread message",
3901
3987
  tags: [OPENAPI_TAGS.agentThreads.name],
3902
3988
  operationId: "postAgentThreadMessage",
3903
- security: SIXB_CSRF_SECURITY_REQUIREMENT
3989
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
3904
3990
  }
3905
3991
  }).post("/api/agent-threads/:threadId/cancel", async (context) => {
3906
3992
  const { params, body, set } = context;
@@ -3981,7 +4067,7 @@ function registerAgentRoutes(app, host) {
3981
4067
  summary: "Cancel an agent thread's active run",
3982
4068
  tags: [OPENAPI_TAGS.agentRuns.name],
3983
4069
  operationId: "cancelAgentRun",
3984
- security: SIXB_CSRF_SECURITY_REQUIREMENT
4070
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
3985
4071
  }
3986
4072
  }).post("/api/agent-threads/:threadId/runs/:runId/retry", async (context) => {
3987
4073
  const { params, set } = context;
@@ -4027,7 +4113,7 @@ function registerAgentRoutes(app, host) {
4027
4113
  summary: "Retry a failed agent run",
4028
4114
  tags: [OPENAPI_TAGS.agentRuns.name],
4029
4115
  operationId: "retryAgentRun",
4030
- security: SIXB_CSRF_SECURITY_REQUIREMENT
4116
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
4031
4117
  }
4032
4118
  }).get("/api/agent-threads/:threadId/runs", async (context) => {
4033
4119
  const { params, query, set } = context;
@@ -4366,7 +4452,7 @@ function registerAiAccountingRoutes(app, host) {
4366
4452
  summary: "Get project AI usage and cost analytics",
4367
4453
  tags: [OPENAPI_TAGS.aiAccounting.name],
4368
4454
  operationId: "getAiAccountingOverview",
4369
- security: bearerSecurityRequirement("getAiAccountingOverview")
4455
+ security: accessTokenSecurityRequirement("getAiAccountingOverview")
4370
4456
  }
4371
4457
  });
4372
4458
  app.get("/api/ai/model-calls", async (context) => {
@@ -4409,7 +4495,7 @@ function registerAiAccountingRoutes(app, host) {
4409
4495
  summary: "List project AI model-call accounting records",
4410
4496
  tags: [OPENAPI_TAGS.aiAccounting.name],
4411
4497
  operationId: "listAiModelCalls",
4412
- security: bearerSecurityRequirement("listAiModelCalls")
4498
+ security: accessTokenSecurityRequirement("listAiModelCalls")
4413
4499
  }
4414
4500
  });
4415
4501
  app.get("/api/ai/limits", async (context) => {
@@ -4442,7 +4528,7 @@ function registerAiAccountingRoutes(app, host) {
4442
4528
  summary: "List project AI usage-limit policies",
4443
4529
  tags: [OPENAPI_TAGS.aiAccounting.name],
4444
4530
  operationId: "listAiLimitPolicies",
4445
- security: bearerSecurityRequirement("listAiLimitPolicies")
4531
+ security: accessTokenSecurityRequirement("listAiLimitPolicies")
4446
4532
  }
4447
4533
  });
4448
4534
  app.get("/api/ai/limits/status", async (context) => {
@@ -4476,7 +4562,7 @@ function registerAiAccountingRoutes(app, host) {
4476
4562
  summary: "Get current project AI usage-limit status",
4477
4563
  tags: [OPENAPI_TAGS.aiAccounting.name],
4478
4564
  operationId: "getAiLimitStatus",
4479
- security: bearerSecurityRequirement("getAiLimitStatus")
4565
+ security: accessTokenSecurityRequirement("getAiLimitStatus")
4480
4566
  }
4481
4567
  });
4482
4568
  app.get("/api/ai/limits/subjects", async (context) => {
@@ -4498,7 +4584,7 @@ function registerAiAccountingRoutes(app, host) {
4498
4584
  description: "Lists registered groups and auth principals available for AI usage-limit policies.",
4499
4585
  tags: [OPENAPI_TAGS.aiAccounting.name],
4500
4586
  operationId: "getAiLimitSubjectOptions",
4501
- security: bearerSecurityRequirement("getAiLimitSubjectOptions")
4587
+ security: accessTokenSecurityRequirement("getAiLimitSubjectOptions")
4502
4588
  }
4503
4589
  });
4504
4590
  app.post("/api/ai/limits", async (context) => {
@@ -4527,7 +4613,7 @@ function registerAiAccountingRoutes(app, host) {
4527
4613
  summary: "Create an AI usage-limit policy",
4528
4614
  tags: [OPENAPI_TAGS.aiAccounting.name],
4529
4615
  operationId: "createAiLimitPolicy",
4530
- security: bearerSecurityRequirement("createAiLimitPolicy")
4616
+ security: accessTokenSecurityRequirement("createAiLimitPolicy")
4531
4617
  }
4532
4618
  });
4533
4619
  app.put("/api/ai/limits/:limitId", async (context) => {
@@ -4558,7 +4644,7 @@ function registerAiAccountingRoutes(app, host) {
4558
4644
  summary: "Update an AI usage-limit policy",
4559
4645
  tags: [OPENAPI_TAGS.aiAccounting.name],
4560
4646
  operationId: "updateAiLimitPolicy",
4561
- security: bearerSecurityRequirement("updateAiLimitPolicy")
4647
+ security: accessTokenSecurityRequirement("updateAiLimitPolicy")
4562
4648
  }
4563
4649
  });
4564
4650
  app.delete("/api/ai/limits/:limitId", async (context) => {
@@ -4591,7 +4677,7 @@ function registerAiAccountingRoutes(app, host) {
4591
4677
  summary: "Delete an AI usage-limit policy",
4592
4678
  tags: [OPENAPI_TAGS.aiAccounting.name],
4593
4679
  operationId: "deleteAiLimitPolicy",
4594
- security: bearerSecurityRequirement("deleteAiLimitPolicy")
4680
+ security: accessTokenSecurityRequirement("deleteAiLimitPolicy")
4595
4681
  }
4596
4682
  });
4597
4683
  app.get("/api/ai/model-call-groups", async (context) => {
@@ -4630,7 +4716,7 @@ function registerAiAccountingRoutes(app, host) {
4630
4716
  summary: "List AI model calls grouped by initiating execution",
4631
4717
  tags: [OPENAPI_TAGS.aiAccounting.name],
4632
4718
  operationId: "listAiModelCallGroups",
4633
- security: bearerSecurityRequirement("listAiModelCallGroups")
4719
+ security: accessTokenSecurityRequirement("listAiModelCallGroups")
4634
4720
  }
4635
4721
  });
4636
4722
  return app;
@@ -5010,7 +5096,7 @@ function registerConnectorConnectionRunRoutes(app, host, options) {
5010
5096
  summary: "Start a connector connection run",
5011
5097
  tags: [OPENAPI_TAGS.connectorConnectionRuns.name],
5012
5098
  operationId: "startConnectorConnectionRun",
5013
- security: SIXB_CSRF_SECURITY_REQUIREMENT
5099
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5014
5100
  }
5015
5101
  }).get("/api/connectors/:connectorId/connection-runs/:runId", async (context) => {
5016
5102
  const { params, set } = context;
@@ -5069,7 +5155,7 @@ function registerConnectorConnectionRunRoutes(app, host, options) {
5069
5155
  summary: "Add a connector connection from an existing authorization",
5070
5156
  tags: [OPENAPI_TAGS.connectorConnectionRuns.name],
5071
5157
  operationId: "addConnectorConnection",
5072
- security: SIXB_CSRF_SECURITY_REQUIREMENT
5158
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5073
5159
  }
5074
5160
  }).post("/api/connectors/:connectorId/connection-runs/:runId/selection", async (context) => {
5075
5161
  const { params, body, set } = context;
@@ -5100,7 +5186,7 @@ function registerConnectorConnectionRunRoutes(app, host, options) {
5100
5186
  summary: "Select a connector account",
5101
5187
  tags: [OPENAPI_TAGS.connectorConnectionRuns.name],
5102
5188
  operationId: "selectConnectorConnectionRunAccount",
5103
- security: SIXB_CSRF_SECURITY_REQUIREMENT
5189
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5104
5190
  }
5105
5191
  }).post("/api/connectors/:connectorId/connections/:connectionId/reauthorize", async (context) => {
5106
5192
  const { params, body, request, set } = context;
@@ -5143,7 +5229,7 @@ function registerConnectorConnectionRunRoutes(app, host, options) {
5143
5229
  summary: "Reauthorize a connector connection",
5144
5230
  tags: [OPENAPI_TAGS.connectorConnectionRuns.name],
5145
5231
  operationId: "reauthorizeConnectorConnection",
5146
- security: SIXB_CSRF_SECURITY_REQUIREMENT
5232
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5147
5233
  }
5148
5234
  }).get("/auth/connectors/callback", async ({ request, set, server }) => {
5149
5235
  server?.timeout(request, 0);
@@ -5248,7 +5334,7 @@ function registerConnectorConnectionRoutes(app, host) {
5248
5334
  summary: "Disconnect a connector account",
5249
5335
  tags: [OPENAPI_TAGS.connectorConnections.name],
5250
5336
  operationId: "disconnectConnectorConnection",
5251
- security: SIXB_CSRF_SECURITY_REQUIREMENT
5337
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5252
5338
  }
5253
5339
  }).post("/api/connectors/:connectorId/connections/:connectionId/revoke", async (context) => {
5254
5340
  const { params, set } = context;
@@ -5277,7 +5363,7 @@ function registerConnectorConnectionRoutes(app, host) {
5277
5363
  summary: "Revoke a connector authorization",
5278
5364
  tags: [OPENAPI_TAGS.connectorConnections.name],
5279
5365
  operationId: "revokeConnectorConnection",
5280
- security: SIXB_CSRF_SECURITY_REQUIREMENT
5366
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5281
5367
  }
5282
5368
  });
5283
5369
  }
@@ -5831,12 +5917,34 @@ var StoredEventBaseSchema = z15.object({
5831
5917
  schemaVersion: z15.literal(1),
5832
5918
  projectId: z15.string(),
5833
5919
  occurredAt: z15.string(),
5834
- actor: z15.object({
5835
- type: z15.enum(["user", "serviceAccount", "system"]),
5836
- id: z15.string()
5837
- }).optional(),
5838
5920
  partitionKey: z15.string()
5839
5921
  });
5922
+ var TRUSTED_PRIMITIVE_KINDS = [
5923
+ "action",
5924
+ "pipeline",
5925
+ "projection",
5926
+ "rule",
5927
+ "sync",
5928
+ "webhook",
5929
+ "workflow"
5930
+ ];
5931
+ var EventExecutorSchema = z15.discriminatedUnion("type", [
5932
+ z15.object({ type: z15.literal("request"), requestId: z15.string() }),
5933
+ z15.object({
5934
+ type: z15.literal("primitive"),
5935
+ kind: z15.enum(TRUSTED_PRIMITIVE_KINDS),
5936
+ id: z15.string(),
5937
+ runId: z15.string()
5938
+ }),
5939
+ z15.object({ type: z15.literal("agent"), runId: z15.string() }),
5940
+ z15.object({
5941
+ type: z15.literal("kernel"),
5942
+ operation: z15.discriminatedUnion("type", [
5943
+ z15.object({ type: z15.literal("ontology.recover"), recoveryId: z15.string() }),
5944
+ z15.object({ type: z15.literal("ontology.indexVectors"), indexingId: z15.string() })
5945
+ ])
5946
+ })
5947
+ ]);
5840
5948
  var StoredAuthorableEventBaseSchema = StoredEventBaseSchema.extend({
5841
5949
  correlationId: z15.string().optional(),
5842
5950
  causationId: z15.string().optional(),
@@ -5846,6 +5954,8 @@ var StoredAuthorableEventBaseSchema = StoredEventBaseSchema.extend({
5846
5954
  });
5847
5955
  var StoredOntologyEventBaseSchema = StoredEventBaseSchema.extend({
5848
5956
  origin: EventOriginSchema,
5957
+ requestedBy: z15.object({ type: z15.enum(["user", "serviceAccount"]), id: z15.string() }).optional().describe("Principal on whose behalf the write ran; absent for automatic or anonymous work."),
5958
+ executor: EventExecutorSchema,
5849
5959
  commitId: z15.string(),
5850
5960
  commitOrdinal: z15.number().int().nonnegative()
5851
5961
  });
@@ -5905,7 +6015,7 @@ function registerEventRoutes(app, _host) {
5905
6015
  summary: "Read domain events",
5906
6016
  tags: [OPENAPI_TAGS.events.name],
5907
6017
  operationId: "listEvents",
5908
- security: bearerSecurityRequirement("listEvents")
6018
+ security: accessTokenSecurityRequirement("listEvents")
5909
6019
  }
5910
6020
  });
5911
6021
  }
@@ -5957,7 +6067,7 @@ function registerLinkRoutes(app, _host) {
5957
6067
  summary: "Create or update object link",
5958
6068
  tags: [OPENAPI_TAGS.links.name],
5959
6069
  operationId: "upsertObjectLink",
5960
- security: bearerSecurityRequirement("upsertObjectLink")
6070
+ security: accessTokenSecurityRequirement("upsertObjectLink")
5961
6071
  }
5962
6072
  }).delete("/api/objects/:objectTypeId/:objectId/links/:linkId", async (context) => {
5963
6073
  const { params, query, set } = context;
@@ -5984,7 +6094,7 @@ function registerLinkRoutes(app, _host) {
5984
6094
  summary: "Remove object link",
5985
6095
  tags: [OPENAPI_TAGS.links.name],
5986
6096
  operationId: "removeObjectLink",
5987
- security: bearerSecurityRequirement("removeObjectLink")
6097
+ security: accessTokenSecurityRequirement("removeObjectLink")
5988
6098
  }
5989
6099
  });
5990
6100
  }
@@ -6097,7 +6207,7 @@ function registerLogRoutes(app, _host) {
6097
6207
  summary: "Read run logs",
6098
6208
  tags: [OPENAPI_TAGS.logs.name],
6099
6209
  operationId: "listLogs",
6100
- security: bearerSecurityRequirement("listLogs")
6210
+ security: accessTokenSecurityRequirement("listLogs")
6101
6211
  }
6102
6212
  });
6103
6213
  }
@@ -7161,7 +7271,7 @@ function registerObjectRoutes(app, host) {
7161
7271
  summary: "Search objects",
7162
7272
  tags: [OPENAPI_TAGS.objects.name],
7163
7273
  operationId: "searchObjects",
7164
- security: bearerSecurityRequirement("searchObjects")
7274
+ security: accessTokenSecurityRequirement("searchObjects")
7165
7275
  }
7166
7276
  }).get("/api/objects", async (context) => {
7167
7277
  const { query, set } = context;
@@ -7211,7 +7321,7 @@ function registerObjectRoutes(app, host) {
7211
7321
  summary: "List objects",
7212
7322
  tags: [OPENAPI_TAGS.objects.name],
7213
7323
  operationId: "listObjects",
7214
- security: bearerSecurityRequirement("listObjects")
7324
+ security: accessTokenSecurityRequirement("listObjects")
7215
7325
  }
7216
7326
  }).post("/api/objects/query", async (context) => {
7217
7327
  const { body, set } = context;
@@ -7237,7 +7347,7 @@ function registerObjectRoutes(app, host) {
7237
7347
  summary: "Query objects",
7238
7348
  tags: [OPENAPI_TAGS.objects.name],
7239
7349
  operationId: "queryObjects",
7240
- security: bearerSecurityRequirement("queryObjects"),
7350
+ security: accessTokenSecurityRequirement("queryObjects"),
7241
7351
  requestBody: {
7242
7352
  required: true,
7243
7353
  content: {
@@ -7314,7 +7424,7 @@ function registerObjectRoutes(app, host) {
7314
7424
  summary: "Query object links",
7315
7425
  tags: [OPENAPI_TAGS.links.name],
7316
7426
  operationId: "queryObjectLinks",
7317
- security: bearerSecurityRequirement("queryObjectLinks"),
7427
+ security: accessTokenSecurityRequirement("queryObjectLinks"),
7318
7428
  requestBody: {
7319
7429
  required: true,
7320
7430
  content: {
@@ -7375,7 +7485,7 @@ function registerObjectRoutes(app, host) {
7375
7485
  summary: "Count objects",
7376
7486
  tags: [OPENAPI_TAGS.objects.name],
7377
7487
  operationId: "countObjects",
7378
- security: bearerSecurityRequirement("countObjects"),
7488
+ security: accessTokenSecurityRequirement("countObjects"),
7379
7489
  requestBody: {
7380
7490
  required: true,
7381
7491
  content: {
@@ -7450,7 +7560,7 @@ function registerObjectRoutes(app, host) {
7450
7560
  summary: "Check object existence",
7451
7561
  tags: [OPENAPI_TAGS.objects.name],
7452
7562
  operationId: "existsObjects",
7453
- security: bearerSecurityRequirement("existsObjects"),
7563
+ security: accessTokenSecurityRequirement("existsObjects"),
7454
7564
  requestBody: {
7455
7565
  required: true,
7456
7566
  content: {
@@ -7528,7 +7638,7 @@ function registerObjectRoutes(app, host) {
7528
7638
  summary: "Facet objects",
7529
7639
  tags: [OPENAPI_TAGS.objects.name],
7530
7640
  operationId: "facetObjects",
7531
- security: bearerSecurityRequirement("facetObjects"),
7641
+ security: accessTokenSecurityRequirement("facetObjects"),
7532
7642
  requestBody: {
7533
7643
  required: true,
7534
7644
  content: {
@@ -7579,7 +7689,7 @@ function registerObjectRoutes(app, host) {
7579
7689
  summary: "Get object file content",
7580
7690
  tags: [OPENAPI_TAGS.objectFiles.name],
7581
7691
  operationId: "getObjectFileContent",
7582
- security: bearerSecurityRequirement("getObjectFileContent"),
7692
+ security: accessTokenSecurityRequirement("getObjectFileContent"),
7583
7693
  responses: fileContentGetResponses()
7584
7694
  }
7585
7695
  }).head("/api/objects/:objectTypeId/:objectId/files/content", (context) => objectFileContentResponse(host, context, { head: true }), {
@@ -7589,7 +7699,7 @@ function registerObjectRoutes(app, host) {
7589
7699
  summary: "Head object file content",
7590
7700
  tags: [OPENAPI_TAGS.objectFiles.name],
7591
7701
  operationId: "headObjectFileContent",
7592
- security: bearerSecurityRequirement("headObjectFileContent"),
7702
+ security: accessTokenSecurityRequirement("headObjectFileContent"),
7593
7703
  responses: fileContentHeadResponses()
7594
7704
  }
7595
7705
  }).get("/api/objects/:objectTypeId/:objectId", async (context) => {
@@ -7616,7 +7726,7 @@ function registerObjectRoutes(app, host) {
7616
7726
  summary: "Get object by id",
7617
7727
  tags: [OPENAPI_TAGS.objects.name],
7618
7728
  operationId: "getObject",
7619
- security: bearerSecurityRequirement("getObject")
7729
+ security: accessTokenSecurityRequirement("getObject")
7620
7730
  }
7621
7731
  }).put("/api/objects/:objectTypeId/:objectId", async (context) => {
7622
7732
  const { params, body, set } = context;
@@ -7643,12 +7753,13 @@ function registerObjectRoutes(app, host) {
7643
7753
  summary: "Create or update object",
7644
7754
  tags: [OPENAPI_TAGS.objects.name],
7645
7755
  operationId: "upsertObject",
7646
- security: bearerSecurityRequirement("upsertObject")
7756
+ security: accessTokenSecurityRequirement("upsertObject")
7647
7757
  }
7648
7758
  });
7649
7759
  }
7650
7760
 
7651
7761
  // src/routes/ontology.ts
7762
+ import { resolvePropertyQueryCapabilities } from "@sixb/core/internal/ontology";
7652
7763
  function serializeProperty(property) {
7653
7764
  return {
7654
7765
  id: property.id,
@@ -7663,6 +7774,13 @@ function serializeProperty(property) {
7663
7774
  query: property.query ? { ...property.query } : undefined
7664
7775
  };
7665
7776
  }
7777
+ function serializeObjectProperty(property, valueTypesById) {
7778
+ const capabilities = resolvePropertyQueryCapabilities(property, valueTypesById);
7779
+ return {
7780
+ ...serializeProperty(property),
7781
+ capabilities: { ...capabilities, operators: [...capabilities.operators] }
7782
+ };
7783
+ }
7666
7784
  function serializeSearch(search) {
7667
7785
  if (!search)
7668
7786
  return;
@@ -7684,14 +7802,14 @@ function serializeSearch(search) {
7684
7802
  ])) : undefined
7685
7803
  };
7686
7804
  }
7687
- function serializeObjectType(execution, objectType) {
7805
+ function serializeObjectType(execution, valueTypesById, objectType) {
7688
7806
  return {
7689
7807
  id: objectType.id,
7690
7808
  name: objectType.name,
7691
7809
  description: objectType.description,
7692
7810
  extends: objectType.extends,
7693
7811
  implements: objectType.implements ? [...objectType.implements] : undefined,
7694
- properties: objectType.properties.map(serializeProperty),
7812
+ properties: objectType.properties.map((property) => serializeObjectProperty(property, valueTypesById)),
7695
7813
  search: serializeSearch(objectType.search),
7696
7814
  links: objectType.links.map((link) => ({
7697
7815
  id: link.id,
@@ -7717,17 +7835,18 @@ function serializeObjectType(execution, objectType) {
7717
7835
  }))
7718
7836
  };
7719
7837
  }
7720
- function registerOntologyRoutes(app, _host) {
7838
+ function registerOntologyRoutes(app, host) {
7721
7839
  return app.get("/api/object-types", async (context) => {
7722
7840
  const sixb = requireRequestSixb(context);
7723
- return sixb.objects.listTypes().map((objectType) => serializeObjectType(sixb, objectType));
7841
+ const valueTypesById = host.definitions.ontology.getValueTypesById();
7842
+ return sixb.objects.listTypes().map((objectType) => serializeObjectType(sixb, valueTypesById, objectType));
7724
7843
  }, {
7725
7844
  response: { 200: ObjectTypeSchema.array() },
7726
7845
  detail: {
7727
7846
  summary: "List registered object types",
7728
7847
  tags: [OPENAPI_TAGS.ontology.name],
7729
7848
  operationId: "listObjectTypes",
7730
- security: bearerSecurityRequirement("listObjectTypes")
7849
+ security: accessTokenSecurityRequirement("listObjectTypes")
7731
7850
  }
7732
7851
  }).get("/api/object-types/:objectTypeId", async (context) => {
7733
7852
  const { params, set } = context;
@@ -7737,7 +7856,7 @@ function registerOntologyRoutes(app, _host) {
7737
7856
  set.status = 404;
7738
7857
  return { error: "Object type not found" };
7739
7858
  }
7740
- return serializeObjectType(sixb, objectType);
7859
+ return serializeObjectType(sixb, host.definitions.ontology.getValueTypesById(), objectType);
7741
7860
  }, {
7742
7861
  params: ObjectTypeParamsSchema,
7743
7862
  response: { 200: ObjectTypeSchema, 404: ErrorResponseSchema },
@@ -7745,7 +7864,7 @@ function registerOntologyRoutes(app, _host) {
7745
7864
  summary: "Get object type definition",
7746
7865
  tags: [OPENAPI_TAGS.ontology.name],
7747
7866
  operationId: "getObjectType",
7748
- security: bearerSecurityRequirement("getObjectType")
7867
+ security: accessTokenSecurityRequirement("getObjectType")
7749
7868
  }
7750
7869
  });
7751
7870
  }
@@ -8074,7 +8193,7 @@ function registerPipelineRoutes(app, host) {
8074
8193
  summary: "Request a pipeline run",
8075
8194
  tags: [OPENAPI_TAGS.pipelineRuns.name],
8076
8195
  operationId: "requestPipelineRun",
8077
- security: SIXB_CSRF_SECURITY_REQUIREMENT
8196
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
8078
8197
  }
8079
8198
  });
8080
8199
  }
@@ -8093,7 +8212,7 @@ function registerProjectRoutes(app, host) {
8093
8212
  summary: "Get current project metadata",
8094
8213
  tags: [OPENAPI_TAGS.project.name],
8095
8214
  operationId: "getProjectInfo",
8096
- security: bearerSecurityRequirement("getProjectInfo")
8215
+ security: accessTokenSecurityRequirement("getProjectInfo")
8097
8216
  }
8098
8217
  });
8099
8218
  }
@@ -8612,7 +8731,7 @@ var AuthorizablePrincipalSchema = z24.object({
8612
8731
  type: z24.enum(["user", "serviceAccount"]),
8613
8732
  id: StoredIdentifierSchema
8614
8733
  });
8615
- var PrincipalSchema = z24.object({
8734
+ var PrincipalSchema2 = z24.object({
8616
8735
  type: z24.enum(["user", "serviceAccount", "system"]),
8617
8736
  id: StoredIdentifierSchema
8618
8737
  });
@@ -8625,7 +8744,7 @@ var SharedAccessGrantSchema = z24.object({
8625
8744
  createdAt: Rfc3339DateSchema2,
8626
8745
  expiresAt: Rfc3339DateSchema2,
8627
8746
  revokedAt: Rfc3339DateSchema2.optional(),
8628
- revokedBy: PrincipalSchema.optional()
8747
+ revokedBy: PrincipalSchema2.optional()
8629
8748
  });
8630
8749
  var IssueSharedAccessGrantBodySchema = z24.object({
8631
8750
  definitionId: StoredIdentifierSchema,
@@ -8701,7 +8820,7 @@ function registerShareGrantRoutes(app, _host) {
8701
8820
  summary: "Issue a shared-access grant",
8702
8821
  tags: [OPENAPI_TAGS.sharedAccess.name],
8703
8822
  operationId: "issueSharedAccessGrant",
8704
- security: bearerSecurityRequirement("issueSharedAccessGrant")
8823
+ security: accessTokenSecurityRequirement("issueSharedAccessGrant")
8705
8824
  }
8706
8825
  }).get("/api/share-grants", async (context) => {
8707
8826
  const { query, set } = context;
@@ -8739,7 +8858,7 @@ function registerShareGrantRoutes(app, _host) {
8739
8858
  summary: "List shared-access grants",
8740
8859
  tags: [OPENAPI_TAGS.sharedAccess.name],
8741
8860
  operationId: "listSharedAccessGrants",
8742
- security: bearerSecurityRequirement("listSharedAccessGrants")
8861
+ security: accessTokenSecurityRequirement("listSharedAccessGrants")
8743
8862
  }
8744
8863
  }).delete("/api/share-grants/:grantId", async (context) => {
8745
8864
  const { params, set } = context;
@@ -8772,7 +8891,7 @@ function registerShareGrantRoutes(app, _host) {
8772
8891
  summary: "Revoke a shared-access grant",
8773
8892
  tags: [OPENAPI_TAGS.sharedAccess.name],
8774
8893
  operationId: "revokeSharedAccessGrant",
8775
- security: bearerSecurityRequirement("revokeSharedAccessGrant")
8894
+ security: accessTokenSecurityRequirement("revokeSharedAccessGrant")
8776
8895
  }
8777
8896
  });
8778
8897
  }
@@ -8953,7 +9072,7 @@ function registerSharedAccessRoutes(app, boundary) {
8953
9072
  summary: "Sign out a shared-access session",
8954
9073
  tags: [OPENAPI_TAGS.sharedAccess.name],
8955
9074
  operationId: "signOutSharedAccess",
8956
- security: SIXB_CSRF_SECURITY_REQUIREMENT
9075
+ security: [{ [SIXB_CSRF_SECURITY_SCHEME_ID]: [] }, {}]
8957
9076
  }
8958
9077
  });
8959
9078
  }
@@ -9289,7 +9408,7 @@ function registerSyncRoutes(app, host) {
9289
9408
  summary: "Request a sync run",
9290
9409
  tags: [OPENAPI_TAGS.syncRuns.name],
9291
9410
  operationId: "requestSyncRun",
9292
- security: SIXB_CSRF_SECURITY_REQUIREMENT
9411
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
9293
9412
  }
9294
9413
  });
9295
9414
  }
@@ -9386,7 +9505,7 @@ function registerTelemetryRoutes(app, _host) {
9386
9505
  summary: "Append telemetry point",
9387
9506
  tags: [OPENAPI_TAGS.telemetry.name],
9388
9507
  operationId: "appendTelemetry",
9389
- security: bearerSecurityRequirement("appendTelemetry")
9508
+ security: accessTokenSecurityRequirement("appendTelemetry")
9390
9509
  }
9391
9510
  }).post("/api/telemetry/history", async (context) => {
9392
9511
  const { body, set } = context;
@@ -9421,7 +9540,7 @@ function registerTelemetryRoutes(app, _host) {
9421
9540
  summary: "Get bulk telemetry history",
9422
9541
  tags: [OPENAPI_TAGS.telemetry.name],
9423
9542
  operationId: "getBulkTelemetryHistory",
9424
- security: bearerSecurityRequirement("getBulkTelemetryHistory")
9543
+ security: accessTokenSecurityRequirement("getBulkTelemetryHistory")
9425
9544
  }
9426
9545
  }).get("/api/objects/:objectTypeId/:objectId/telemetry/:propertyId/history", async (context) => {
9427
9546
  const { params, query, set } = context;
@@ -9457,7 +9576,7 @@ function registerTelemetryRoutes(app, _host) {
9457
9576
  summary: "Get telemetry history",
9458
9577
  tags: [OPENAPI_TAGS.telemetry.name],
9459
9578
  operationId: "getTelemetryHistory",
9460
- security: bearerSecurityRequirement("getTelemetryHistory")
9579
+ security: accessTokenSecurityRequirement("getTelemetryHistory")
9461
9580
  }
9462
9581
  }).get("/api/objects/:objectTypeId/:objectId/telemetry/:propertyId/latest", async (context) => {
9463
9582
  const { params, set } = context;
@@ -9491,7 +9610,7 @@ function registerTelemetryRoutes(app, _host) {
9491
9610
  summary: "Get latest telemetry point",
9492
9611
  tags: [OPENAPI_TAGS.telemetry.name],
9493
9612
  operationId: "getLatestTelemetry",
9494
- security: bearerSecurityRequirement("getLatestTelemetry")
9613
+ security: accessTokenSecurityRequirement("getLatestTelemetry")
9495
9614
  }
9496
9615
  });
9497
9616
  }
@@ -9664,10 +9783,6 @@ var WorkflowInterventionsQuerySchema = z30.object({
9664
9783
  var RequestWorkflowRunBodySchema = z30.object({
9665
9784
  input: WorkflowIOSnapshotSchema.optional()
9666
9785
  }).default({});
9667
- var WorkflowInterventionActorSchema = z30.object({
9668
- principalType: z30.enum(["user", "serviceAccount", "system"]),
9669
- principalId: z30.string().min(1)
9670
- });
9671
9786
  var CancelWorkflowRunBodySchema = z30.object({}).default({});
9672
9787
  var SubmitWorkflowInterventionBodySchema = z30.object({
9673
9788
  response: WorkflowIOSnapshotSchema
@@ -9717,7 +9832,7 @@ var WorkflowRunSummarySchema = z30.object({
9717
9832
  startedAt: z30.string(),
9718
9833
  finishedAt: z30.string().optional(),
9719
9834
  error: WorkflowRunFailureSchema.optional(),
9720
- requestedBy: WorkflowInterventionActorSchema
9835
+ requestedBy: PrincipalSchema
9721
9836
  });
9722
9837
  var WorkflowRunDetailSchema = WorkflowRunSummarySchema.extend({
9723
9838
  input: WorkflowIOSnapshotSchema,
@@ -9776,10 +9891,10 @@ var WorkflowInterventionSchema = z30.object({
9776
9891
  requestedAt: z30.string(),
9777
9892
  expiresAt: z30.string().optional(),
9778
9893
  submittedAt: z30.string().optional(),
9779
- submittedBy: WorkflowInterventionActorSchema.optional(),
9894
+ submittedBy: PrincipalSchema.optional(),
9780
9895
  response: WorkflowIOSnapshotSchema.optional(),
9781
9896
  cancelledAt: z30.string().optional(),
9782
- cancelledBy: WorkflowInterventionActorSchema.optional(),
9897
+ cancelledBy: PrincipalSchema.optional(),
9783
9898
  expiredAt: z30.string().optional()
9784
9899
  });
9785
9900
  var WorkflowSchema = z30.object({
@@ -9868,7 +9983,7 @@ function serializeWorkflowNodeRun(node) {
9868
9983
  };
9869
9984
  }
9870
9985
  function serializePrincipal(principal) {
9871
- return { principalType: principal.type, principalId: principal.id };
9986
+ return { type: principal.type, id: principal.id };
9872
9987
  }
9873
9988
  function serializeWorkflowAgentExecutionSummary(execution) {
9874
9989
  return {
@@ -10197,7 +10312,7 @@ function registerWorkflowRoutes(app, host) {
10197
10312
  summary: "List registered workflows",
10198
10313
  tags: [OPENAPI_TAGS.workflows.name],
10199
10314
  operationId: "listWorkflows",
10200
- security: bearerSecurityRequirement("listWorkflows")
10315
+ security: accessTokenSecurityRequirement("listWorkflows")
10201
10316
  }
10202
10317
  }).get("/api/workflows/:workflowId", async (context) => {
10203
10318
  const { params, set } = context;
@@ -10215,7 +10330,7 @@ function registerWorkflowRoutes(app, host) {
10215
10330
  summary: "Get workflow metadata",
10216
10331
  tags: [OPENAPI_TAGS.workflows.name],
10217
10332
  operationId: "getWorkflow",
10218
- security: bearerSecurityRequirement("getWorkflow")
10333
+ security: accessTokenSecurityRequirement("getWorkflow")
10219
10334
  }
10220
10335
  }).get("/api/workflow-interventions", async (context) => {
10221
10336
  const { query, set } = context;
@@ -10359,7 +10474,7 @@ function registerWorkflowRoutes(app, host) {
10359
10474
  summary: "Submit a workflow intervention response",
10360
10475
  tags: [OPENAPI_TAGS.workflowInterventions.name],
10361
10476
  operationId: "submitWorkflowIntervention",
10362
- security: SIXB_CSRF_SECURITY_REQUIREMENT
10477
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
10363
10478
  }
10364
10479
  }).post("/api/workflow-interventions/:interventionId/cancel", async (context) => {
10365
10480
  const { params, body, set } = context;
@@ -10472,7 +10587,7 @@ function registerWorkflowRoutes(app, host) {
10472
10587
  summary: "Cancel a workflow intervention",
10473
10588
  tags: [OPENAPI_TAGS.workflowInterventions.name],
10474
10589
  operationId: "cancelWorkflowIntervention",
10475
- security: SIXB_CSRF_SECURITY_REQUIREMENT
10590
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
10476
10591
  }
10477
10592
  }).get("/api/workflow-runs", async (context) => {
10478
10593
  const { query, set } = context;
@@ -10513,7 +10628,7 @@ function registerWorkflowRoutes(app, host) {
10513
10628
  summary: "List workflow run history",
10514
10629
  tags: [OPENAPI_TAGS.workflowRuns.name],
10515
10630
  operationId: "listWorkflowRuns",
10516
- security: bearerSecurityRequirement("listWorkflowRuns")
10631
+ security: accessTokenSecurityRequirement("listWorkflowRuns")
10517
10632
  }
10518
10633
  }).get("/api/workflow-runs/:runId", async (context) => {
10519
10634
  const { params, set } = context;
@@ -10556,7 +10671,7 @@ function registerWorkflowRoutes(app, host) {
10556
10671
  summary: "Get workflow run detail",
10557
10672
  tags: [OPENAPI_TAGS.workflowRuns.name],
10558
10673
  operationId: "getWorkflowRun",
10559
- security: bearerSecurityRequirement("getWorkflowRun")
10674
+ security: accessTokenSecurityRequirement("getWorkflowRun")
10560
10675
  }
10561
10676
  }).get("/api/workflow-runs/:runId/nodes/:nodeKey/agent-execution", async (context) => {
10562
10677
  const { params, set } = context;
@@ -10598,7 +10713,7 @@ function registerWorkflowRoutes(app, host) {
10598
10713
  summary: "Get workflow agent node execution detail",
10599
10714
  tags: [OPENAPI_TAGS.workflowRuns.name],
10600
10715
  operationId: "getWorkflowAgentNodeExecution",
10601
- security: bearerSecurityRequirement("getWorkflowAgentNodeExecution")
10716
+ security: accessTokenSecurityRequirement("getWorkflowAgentNodeExecution")
10602
10717
  }
10603
10718
  }).post("/api/workflow-runs/:runId/cancel", async (context) => {
10604
10719
  const { params, body, set } = context;
@@ -10757,7 +10872,7 @@ function registerWorkflowRoutes(app, host) {
10757
10872
  summary: "Cancel a workflow run",
10758
10873
  tags: [OPENAPI_TAGS.workflowRuns.name],
10759
10874
  operationId: "cancelWorkflowRun",
10760
- security: bearerSecurityRequirement("cancelWorkflowRun")
10875
+ security: accessTokenSecurityRequirement("cancelWorkflowRun")
10761
10876
  }
10762
10877
  }).get("/api/workflow-runs/:runId/files/content", (context) => workflowRunFileContentResponse(host, context), {
10763
10878
  params: WorkflowRunParamsSchema,
@@ -10767,7 +10882,7 @@ function registerWorkflowRoutes(app, host) {
10767
10882
  summary: "Get workflow run file content",
10768
10883
  tags: ["Workflows"],
10769
10884
  operationId: "getWorkflowRunFileContent",
10770
- security: bearerSecurityRequirement("getWorkflowRunFileContent"),
10885
+ security: accessTokenSecurityRequirement("getWorkflowRunFileContent"),
10771
10886
  responses: fileContentGetResponses({ optionalStorage: true })
10772
10887
  }
10773
10888
  }).head("/api/workflow-runs/:runId/files/content", (context) => workflowRunFileContentResponse(host, context, { head: true }), {
@@ -10778,7 +10893,7 @@ function registerWorkflowRoutes(app, host) {
10778
10893
  summary: "Head workflow run file content",
10779
10894
  tags: ["Workflows"],
10780
10895
  operationId: "headWorkflowRunFileContent",
10781
- security: bearerSecurityRequirement("headWorkflowRunFileContent"),
10896
+ security: accessTokenSecurityRequirement("headWorkflowRunFileContent"),
10782
10897
  responses: fileContentHeadResponses({ optionalStorage: true })
10783
10898
  }
10784
10899
  }).get("/api/workflow-runs/:runId/nodes/:nodeKey/files/content", (context) => workflowNodeFileContentResponse(host, context), {
@@ -10789,7 +10904,7 @@ function registerWorkflowRoutes(app, host) {
10789
10904
  summary: "Get workflow node run file content",
10790
10905
  tags: ["Workflows"],
10791
10906
  operationId: "getWorkflowNodeRunFileContent",
10792
- security: bearerSecurityRequirement("getWorkflowNodeRunFileContent"),
10907
+ security: accessTokenSecurityRequirement("getWorkflowNodeRunFileContent"),
10793
10908
  responses: fileContentGetResponses({ optionalStorage: true })
10794
10909
  }
10795
10910
  }).head("/api/workflow-runs/:runId/nodes/:nodeKey/files/content", (context) => workflowNodeFileContentResponse(host, context, { head: true }), {
@@ -10800,7 +10915,7 @@ function registerWorkflowRoutes(app, host) {
10800
10915
  summary: "Head workflow node run file content",
10801
10916
  tags: ["Workflows"],
10802
10917
  operationId: "headWorkflowNodeRunFileContent",
10803
- security: bearerSecurityRequirement("headWorkflowNodeRunFileContent"),
10918
+ security: accessTokenSecurityRequirement("headWorkflowNodeRunFileContent"),
10804
10919
  responses: fileContentHeadResponses({ optionalStorage: true })
10805
10920
  }
10806
10921
  }).post("/api/workflows/:workflowId/runs", async (context) => {
@@ -10841,7 +10956,7 @@ function registerWorkflowRoutes(app, host) {
10841
10956
  summary: "Request a workflow run",
10842
10957
  tags: [OPENAPI_TAGS.workflowRuns.name],
10843
10958
  operationId: "requestWorkflowRun",
10844
- security: bearerSecurityRequirement("requestWorkflowRun")
10959
+ security: accessTokenSecurityRequirement("requestWorkflowRun")
10845
10960
  }
10846
10961
  });
10847
10962
  }
@@ -10880,19 +10995,23 @@ function registerHttpRoutes(app, host, options) {
10880
10995
 
10881
10996
  // src/routes/auth.ts
10882
10997
  import { createHash as createHash3, randomBytes, randomUUID, timingSafeEqual } from "crypto";
10998
+ import {
10999
+ DEFAULT_AUTH_SESSION_AUDIENCE as DEFAULT_AUTH_SESSION_AUDIENCE2
11000
+ } from "@sixb/core";
10883
11001
  import {
10884
11002
  AuthRuntimeError,
10885
11003
  clearCsrfCookieHeader,
10886
11004
  clearSessionCookieHeader,
10887
- createAccessTokenCredential,
10888
11005
  createCsrfCookieHeader as createCsrfCookieHeader2,
10889
11006
  createSessionCookieHeader as createSessionCookieHeader2,
10890
11007
  createSessionCredential,
10891
11008
  generateCsrfToken as generateCsrfToken3,
10892
11009
  getCookie as getCookie4,
11010
+ getRequestClientAddress,
10893
11011
  isMagicLinkAuthStrategy,
10894
11012
  isOidcAuthStrategy,
10895
11013
  shouldUseSecureCookies,
11014
+ verifyCsrfToken,
10896
11015
  verifyDoubleSubmitCsrf as verifyDoubleSubmitCsrf3
10897
11016
  } from "@sixb/core/internal/auth";
10898
11017
  import {
@@ -11030,6 +11149,45 @@ function notFoundResponse() {
11030
11149
  });
11031
11150
  }
11032
11151
 
11152
+ // src/auth/rate-limit.ts
11153
+ import { isIPv4 as isIPv42 } from "net";
11154
+
11155
+ class ClientAddressRateLimiter {
11156
+ limit;
11157
+ windowMs;
11158
+ windows = new Map;
11159
+ constructor(limit, windowMs) {
11160
+ this.limit = limit;
11161
+ this.windowMs = windowMs;
11162
+ }
11163
+ tryConsume(address, nowMs = Date.now()) {
11164
+ for (const [key, window] of this.windows) {
11165
+ if (window.resetAt > nowMs)
11166
+ break;
11167
+ this.windows.delete(key);
11168
+ }
11169
+ const key = rateLimitKey(address);
11170
+ const window = this.windows.get(key);
11171
+ if (!window) {
11172
+ this.windows.set(key, { count: 1, resetAt: nowMs + this.windowMs });
11173
+ return true;
11174
+ }
11175
+ if (window.count >= this.limit)
11176
+ return false;
11177
+ window.count += 1;
11178
+ return true;
11179
+ }
11180
+ }
11181
+ function rateLimitKey(address) {
11182
+ if (!address || isIPv42(address))
11183
+ return address ?? "";
11184
+ const [head = "", tail = ""] = address.split("::");
11185
+ const left = head ? head.split(":") : [];
11186
+ const right = tail ? tail.split(":") : [];
11187
+ const zeros = Array(Math.max(0, 8 - left.length - right.length)).fill("0");
11188
+ return `${[...left, ...zeros, ...right].slice(0, 4).join(":")}::/64`;
11189
+ }
11190
+
11033
11191
  // src/schemas/auth.ts
11034
11192
  import { z as z32 } from "zod";
11035
11193
  var AuthInvitationStatusSchema = z32.enum(["pending", "accepted", "revoked"]);
@@ -11058,17 +11216,19 @@ var AuthInvitationDeliverySchema = z32.object({
11058
11216
  });
11059
11217
  var AuthInvitationGroupOptionSchema = AuthGroupOptionSchema;
11060
11218
  var AuthAccessTokenKindSchema = z32.enum(["personal", "serviceAccount"]);
11061
- var AuthAccessTokenSubjectTypeSchema = z32.enum(["user", "serviceAccount"]);
11062
11219
  var AuthAccessTokenStatusSchema = z32.enum(["active", "expired", "revoked"]);
11063
11220
  var AuthServiceAccountStatusSchema = z32.enum(["active", "suspended"]);
11064
11221
  var AuthUserStatusSchema = z32.enum(["active", "suspended"]);
11222
+ var AuthAccessTokenSubjectSchema = z32.object({
11223
+ type: z32.enum(["user", "serviceAccount"]),
11224
+ id: z32.string()
11225
+ });
11065
11226
  var AuthAccessTokenSchema = z32.object({
11066
11227
  id: z32.string(),
11067
11228
  name: z32.string(),
11068
11229
  kind: AuthAccessTokenKindSchema,
11069
11230
  status: AuthAccessTokenStatusSchema,
11070
- subjectType: AuthAccessTokenSubjectTypeSchema,
11071
- subjectId: z32.string(),
11231
+ subject: AuthAccessTokenSubjectSchema,
11072
11232
  subjectLabel: z32.string().optional(),
11073
11233
  groupIds: z32.array(z32.string()).optional(),
11074
11234
  createdAt: z32.string(),
@@ -11256,7 +11416,7 @@ var AuthSessionResponseSchema = z32.union([
11256
11416
  }),
11257
11417
  z32.object({
11258
11418
  authenticated: z32.literal(true),
11259
- csrfToken: z32.string(),
11419
+ csrfToken: z32.string().optional(),
11260
11420
  applicationAccess: z32.object({
11261
11421
  allowed: z32.boolean(),
11262
11422
  audience: z32.enum(["atlas", "app"])
@@ -11278,9 +11438,15 @@ var AuthSignOutResponseSchema = z32.object({
11278
11438
  success: z32.boolean()
11279
11439
  });
11280
11440
  var CreateDeviceAuthorizationBodySchema = z32.object({
11281
- clientName: z32.string().trim().min(1).max(100),
11282
- tokenName: z32.string().trim().min(1).max(100),
11283
- expiresIn: z32.literal("90d").optional()
11441
+ clientName: z32.string().trim().min(1).max(100)
11442
+ });
11443
+ var BearerSessionTokensSchema = z32.object({
11444
+ accessToken: z32.string(),
11445
+ refreshToken: z32.string(),
11446
+ expiresIn: z32.number()
11447
+ });
11448
+ var RefreshAuthSessionBodySchema = z32.object({
11449
+ refreshToken: z32.string().min(1)
11284
11450
  });
11285
11451
  var CreateDeviceAuthorizationResponseSchema = z32.object({
11286
11452
  deviceCode: z32.string(),
@@ -11297,7 +11463,7 @@ var ExchangeDeviceAuthorizationResponseSchema = z32.union([
11297
11463
  z32.object({ status: z32.literal("pending") }),
11298
11464
  z32.object({ status: z32.literal("denied") }),
11299
11465
  z32.object({ status: z32.literal("expired") }),
11300
- z32.object({ status: z32.literal("approved"), accessToken: z32.string() })
11466
+ BearerSessionTokensSchema.extend({ status: z32.literal("approved") })
11301
11467
  ]);
11302
11468
  var DeviceAuthorizationDecisionBodySchema = z32.object({
11303
11469
  userCode: z32.string().trim().min(1),
@@ -11306,13 +11472,14 @@ var DeviceAuthorizationDecisionBodySchema = z32.object({
11306
11472
  });
11307
11473
  var AuthSessionSummarySchema = z32.object({
11308
11474
  id: z32.string(),
11309
- audience: z32.enum(["atlas", "app"]),
11475
+ audience: z32.enum(["atlas", "app"]).optional(),
11310
11476
  current: z32.boolean(),
11311
11477
  createdAt: z32.string(),
11312
11478
  expiresAt: z32.string(),
11313
11479
  lastSeenAt: z32.string().optional(),
11314
11480
  userAgent: z32.string().optional(),
11315
- ipAddress: z32.string().optional()
11481
+ ipAddress: z32.string().optional(),
11482
+ clientName: z32.string().optional()
11316
11483
  });
11317
11484
  var ListAuthSessionsResponseSchema = z32.object({
11318
11485
  sessions: z32.array(AuthSessionSummarySchema)
@@ -11330,9 +11497,15 @@ var SignOutAllResponseSchema = z32.object({
11330
11497
 
11331
11498
  // src/routes/auth.ts
11332
11499
  function registerAuthRoutes(app, host, options) {
11500
+ const deviceAuthorizationLimiter = new ClientAddressRateLimiter(DEVICE_AUTHORIZATIONS_PER_ADDRESS, DEVICE_AUTHORIZATION_TTL_MS);
11333
11501
  return app.get("/auth/assets/*", async ({ request }) => customAuthExperienceAssetResponse(options.authExperience, request), { detail: { hide: true } }).head("/auth/assets/*", async ({ request }) => customAuthExperienceAssetResponse(options.authExperience, request), { detail: { hide: true } }).post("/api/auth/device-authorizations", async ({ body, request }) => {
11334
11502
  const parsed = CreateDeviceAuthorizationBodySchema.parse(body);
11335
11503
  const now = new Date;
11504
+ if (!deviceAuthorizationLimiter.tryConsume(getRequestClientAddress(request), now.getTime())) {
11505
+ return jsonResponse2({
11506
+ error: "[SixbServer] Too many device authorizations from this address. Try again later."
11507
+ }, 429);
11508
+ }
11336
11509
  const id = `dva_${randomUUID()}`;
11337
11510
  const deviceCode = `${id}.${randomBytes(32).toString("base64url")}`;
11338
11511
  const userCode = createDeviceUserCode();
@@ -11344,8 +11517,6 @@ function registerAuthRoutes(app, host, options) {
11344
11517
  deviceCodeHash: hashDeviceCode(deviceCode),
11345
11518
  userCode,
11346
11519
  clientName: parsed.clientName,
11347
- tokenName: parsed.tokenName,
11348
- tokenExpiresAt: new Date(now.getTime() + DEVICE_ACCESS_TOKEN_TTL_MS),
11349
11520
  createdAt: now,
11350
11521
  expiresAt
11351
11522
  });
@@ -11369,9 +11540,10 @@ function registerAuthRoutes(app, host, options) {
11369
11540
  detail: {
11370
11541
  summary: "Start device authorization",
11371
11542
  tags: [OPENAPI_TAGS.authSessions.name],
11372
- operationId: "createDeviceAuthorization"
11543
+ operationId: "createDeviceAuthorization",
11544
+ security: []
11373
11545
  }
11374
- }).post("/api/auth/device-authorizations/token", async ({ body }) => {
11546
+ }).post("/api/auth/device-authorizations/token", async ({ body, request }) => {
11375
11547
  const { deviceCode } = ExchangeDeviceAuthorizationBodySchema.parse(body);
11376
11548
  const id = parseDeviceAuthorizationId(deviceCode);
11377
11549
  if (!id)
@@ -11394,26 +11566,18 @@ function registerAuthRoutes(app, host, options) {
11394
11566
  if (!authorization.approvedUserId || !authorization.approvedSessionId) {
11395
11567
  return jsonResponse2({ status: "expired" }, 200);
11396
11568
  }
11397
- const credential = createAccessTokenCredential("personal");
11569
+ const { session, tokens } = host.auth.prepareBearerSession({
11570
+ userId: authorization.approvedUserId,
11571
+ clientName: authorization.clientName,
11572
+ now
11573
+ });
11398
11574
  try {
11399
11575
  await storage.completeDeviceAuthorization({
11400
11576
  projectId: host.id,
11401
11577
  id,
11402
11578
  deviceCodeHash: hashDeviceCode(deviceCode),
11403
11579
  completedAt: now,
11404
- accessToken: {
11405
- id: credential.tokenId,
11406
- projectId: host.id,
11407
- name: authorization.tokenName,
11408
- kind: "personal",
11409
- subjectType: "user",
11410
- subjectId: authorization.approvedUserId,
11411
- tokenHash: credential.tokenHash,
11412
- createdByPrincipal: { type: "user", id: authorization.approvedUserId },
11413
- createdBySessionId: authorization.approvedSessionId,
11414
- createdAt: now,
11415
- expiresAt: authorization.tokenExpiresAt
11416
- }
11580
+ session: { ...session, ...resolveSessionDevice(request) }
11417
11581
  });
11418
11582
  } catch (error) {
11419
11583
  if (error instanceof AuthStorageError && error.code === "invalid_device_authorization") {
@@ -11421,14 +11585,32 @@ function registerAuthRoutes(app, host, options) {
11421
11585
  }
11422
11586
  throw error;
11423
11587
  }
11424
- return jsonResponse2({ status: "approved", accessToken: credential.tokenValue }, 200);
11588
+ return jsonResponse2({ status: "approved", ...bearerTokensBody(tokens, session.bearer, now) }, 200);
11425
11589
  }, {
11426
11590
  body: ExchangeDeviceAuthorizationBodySchema,
11427
11591
  response: { 200: ExchangeDeviceAuthorizationResponseSchema },
11428
11592
  detail: {
11429
11593
  summary: "Exchange an approved device authorization",
11430
11594
  tags: [OPENAPI_TAGS.authSessions.name],
11431
- operationId: "exchangeDeviceAuthorization"
11595
+ operationId: "exchangeDeviceAuthorization",
11596
+ security: []
11597
+ }
11598
+ }).post("/api/auth/refresh", async ({ body }) => {
11599
+ const { refreshToken } = RefreshAuthSessionBodySchema.parse(body);
11600
+ const refreshed = await host.auth.refreshSession(refreshToken);
11601
+ const bearer = refreshed?.session.bearer;
11602
+ if (!refreshed || !bearer?.refreshedAt) {
11603
+ return jsonResponse2({ error: "Invalid refresh token" }, 401);
11604
+ }
11605
+ return jsonResponse2(bearerTokensBody(refreshed.tokens, bearer, bearer.refreshedAt), 200);
11606
+ }, {
11607
+ body: RefreshAuthSessionBodySchema,
11608
+ response: { 200: BearerSessionTokensSchema, 401: ErrorResponseSchema },
11609
+ detail: {
11610
+ summary: "Refresh a native client's session tokens",
11611
+ tags: [OPENAPI_TAGS.authSessions.name],
11612
+ operationId: "refreshAuthSession",
11613
+ security: []
11432
11614
  }
11433
11615
  }).get("/auth/device", async ({ request }) => {
11434
11616
  const rawUserCode = new URL(request.url).searchParams.get("user_code");
@@ -11465,10 +11647,9 @@ function registerAuthRoutes(app, host, options) {
11465
11647
  const groups = session.groupIds.length ? `<p>Groups: ${escapeHtml(session.groupIds.join(", "))}</p>` : "<p>Groups: none</p>";
11466
11648
  const response = authPageResponse([
11467
11649
  "<h1>Authorize this device?</h1>",
11468
- `<p><strong>${escapeHtml(authorization.clientName)}</strong> is requesting access.</p>`,
11650
+ `<p><strong>${escapeHtml(authorization.clientName)}</strong> is requesting to sign in as you.</p>`,
11469
11651
  `<p>Code: <strong>${escapeHtml(authorization.userCode)}</strong></p>`,
11470
- `<p>Token: ${escapeHtml(authorization.tokenName)}</p>`,
11471
- `<p>Expires: ${escapeHtml(authorization.tokenExpiresAt.toLocaleDateString("en-US"))}</p>`,
11652
+ "<p>It stays signed in until you sign it out or it goes unused for a while.</p>",
11472
11653
  groups,
11473
11654
  '<form method="post" action="/auth/device">',
11474
11655
  `<input type="hidden" name="userCode" value="${escapeHtml(userCode)}">`,
@@ -11486,14 +11667,8 @@ function registerAuthRoutes(app, host, options) {
11486
11667
  const session = await host.auth.getSession(request, authOptions);
11487
11668
  if (!session.authenticated)
11488
11669
  return authPageResponse("<h1>Authentication required</h1>", 401);
11489
- if (!sessionCanAccessApplication(host, session, authOptions.audience)) {
11490
- return authPageResponse("<h1>Access denied</h1>", 403);
11491
- }
11492
- const csrfHeaders = new Headers(request.headers);
11493
- csrfHeaders.set("x-sixb-csrf", parsed.csrfToken);
11494
- if (!verifyDoubleSubmitCsrf3(new Request(request.url, { method: "POST", headers: csrfHeaders }), {
11495
- cookieName: host.auth.getCookieOptions(authOptions).csrfCookieName
11496
- })) {
11670
+ const csrfCookieName = host.auth.getCookieOptions(authOptions).csrfCookieName;
11671
+ if (!verifyCsrfToken(request, { cookieName: csrfCookieName, token: parsed.csrfToken })) {
11497
11672
  return authPageResponse("<h1>Invalid authorization request</h1>", 403);
11498
11673
  }
11499
11674
  const storage = requireAuthStorage(host);
@@ -11503,22 +11678,30 @@ function registerAuthRoutes(app, host, options) {
11503
11678
  });
11504
11679
  if (!authorization)
11505
11680
  return authPageResponse("<h1>Invalid authorization</h1>", 400);
11506
- if (parsed.decision === "approve") {
11507
- await storage.deviceAuthorizations.approve({
11508
- projectId: host.id,
11509
- id: authorization.id,
11510
- userId: session.user.id,
11511
- sessionId: session.session.id,
11512
- approvedAt: new Date
11513
- });
11514
- return authPageResponse("<h1>Device authorized</h1><p>You can close this window.</p>");
11681
+ const decidedAt = new Date;
11682
+ try {
11683
+ if (parsed.decision === "approve") {
11684
+ await storage.deviceAuthorizations.approve({
11685
+ projectId: host.id,
11686
+ id: authorization.id,
11687
+ userId: session.user.id,
11688
+ sessionId: session.session.id,
11689
+ approvedAt: decidedAt
11690
+ });
11691
+ } else {
11692
+ await storage.deviceAuthorizations.deny({
11693
+ projectId: host.id,
11694
+ id: authorization.id,
11695
+ deniedAt: decidedAt
11696
+ });
11697
+ }
11698
+ } catch (error) {
11699
+ if (error instanceof AuthStorageError && error.code === "invalid_device_authorization") {
11700
+ return authPageResponse("<h1>This authorization has expired</h1>", 400);
11701
+ }
11702
+ throw error;
11515
11703
  }
11516
- await storage.deviceAuthorizations.deny({
11517
- projectId: host.id,
11518
- id: authorization.id,
11519
- deniedAt: new Date
11520
- });
11521
- return authPageResponse("<h1>Authorization denied</h1><p>You can close this window.</p>");
11704
+ return authPageResponse(parsed.decision === "approve" ? "<h1>Device authorized</h1><p>You can close this window.</p>" : "<h1>Authorization denied</h1><p>You can close this window.</p>");
11522
11705
  }, {
11523
11706
  body: t.Object({
11524
11707
  userCode: t.String(),
@@ -11529,20 +11712,19 @@ function registerAuthRoutes(app, host, options) {
11529
11712
  detail: { hide: true }
11530
11713
  }).get("/api/auth/session", async ({ request }) => {
11531
11714
  const authOptions = resolveAuthOptions(options, request);
11532
- let session = await host.auth.getSession(request, authOptions);
11533
- if (!session.authenticated) {
11715
+ const caller = await host.auth.getSession(request, {
11716
+ ...authOptions,
11717
+ credentialSource: "any"
11718
+ });
11719
+ if (!caller.authenticated || caller.credentialSource !== "session") {
11534
11720
  return jsonResponse2({ authenticated: false }, 200);
11535
11721
  }
11536
- let applicationAccessAllowed = sessionCanAccessApplication(host, session, authOptions.audience);
11537
- if (applicationAccessAllowed && hasForegroundSessionActivity(request)) {
11538
- session = await host.auth.getSession(request, {
11539
- ...authOptions,
11540
- sessionActivity: "foreground"
11541
- });
11542
- if (!session.authenticated) {
11543
- return jsonResponse2({ authenticated: false }, 200);
11544
- }
11545
- applicationAccessAllowed = sessionCanAccessApplication(host, session, authOptions.audience);
11722
+ if (caller.session.bearer) {
11723
+ return jsonResponse2(authSessionBody(host, caller, DEFAULT_AUTH_SESSION_AUDIENCE2), 200);
11724
+ }
11725
+ const session = hasForegroundSessionActivity(request) && sessionCanAccessApplication(host, caller, authOptions.audience) ? await host.auth.getSession(request, { ...authOptions, sessionActivity: "foreground" }) : caller;
11726
+ if (!session.authenticated) {
11727
+ return jsonResponse2({ authenticated: false }, 200);
11546
11728
  }
11547
11729
  const cookieOptions = host.auth.getCookieOptions(authOptions);
11548
11730
  const csrf = resolveSessionCsrfToken({
@@ -11556,56 +11738,32 @@ function registerAuthRoutes(app, host, options) {
11556
11738
  session,
11557
11739
  csrfToken: csrf.token
11558
11740
  }) : null;
11559
- return authSessionJsonResponse({
11560
- authenticated: true,
11561
- csrfToken: csrf.token,
11562
- applicationAccess: {
11563
- allowed: applicationAccessAllowed,
11564
- audience: authOptions.audience
11565
- },
11566
- user: {
11567
- id: session.user.id,
11568
- email: session.user.email,
11569
- displayName: session.user.displayName,
11570
- avatarUrl: session.user.avatarUrl,
11571
- groupIds: [...session.groupIds]
11572
- },
11573
- session: {
11574
- id: session.session.id,
11575
- expiresAt: toIsoString(session.session.expiresAt)
11576
- }
11577
- }, renewal?.headers ?? (csrf.setCookie ? [csrf.setCookie] : []));
11741
+ return authSessionJsonResponse({ ...authSessionBody(host, session, authOptions.audience), csrfToken: csrf.token }, renewal?.headers ?? (csrf.setCookie ? [csrf.setCookie] : []));
11578
11742
  }, {
11579
11743
  response: { 200: AuthSessionResponseSchema },
11580
11744
  detail: {
11581
11745
  summary: "Get current auth session",
11582
11746
  tags: [OPENAPI_TAGS.authSessions.name],
11583
- operationId: "getAuthSession"
11747
+ operationId: "getAuthSession",
11748
+ security: SIXB_OPTIONAL_SESSION_SECURITY_REQUIREMENT
11584
11749
  }
11585
11750
  }).post("/api/auth/sign-out", async ({ request }) => {
11586
11751
  const authOptions = resolveAuthOptions(options, request);
11587
- const session = await host.auth.getSession(request, authOptions);
11752
+ const result = await host.auth.getSession(request, {
11753
+ ...authOptions,
11754
+ credentialSource: "any"
11755
+ });
11756
+ const session = result.authenticated && result.credentialSource === "session" ? result : null;
11588
11757
  const cookieOptions = host.auth.getCookieOptions(authOptions);
11589
- if (session.authenticated && !verifyDoubleSubmitCsrf3(request, {
11758
+ if (session && !session.session.bearer && !verifyDoubleSubmitCsrf3(request, {
11590
11759
  cookieName: cookieOptions.csrfCookieName
11591
11760
  })) {
11592
11761
  return jsonResponse2({ error: "CSRF verification failed" }, 403);
11593
11762
  }
11594
- if (session.authenticated) {
11595
- await host.storage.auth?.sessions.revoke({
11596
- projectId: host.id,
11597
- id: session.session.id,
11598
- revokedAt: new Date
11599
- });
11600
- host.auth.invalidateSession(session.session.id);
11601
- }
11602
- const headers = new Headers({ "content-type": "application/json; charset=utf-8" });
11603
- headers.append("set-cookie", clearSessionCookieHeader({ request, options: cookieOptions }));
11604
- headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }));
11605
- return new Response(JSON.stringify({ success: true }), {
11606
- status: 200,
11607
- headers
11608
- });
11763
+ if (session) {
11764
+ await host.auth.revokeSession(session, session.session.id);
11765
+ }
11766
+ return signedOutResponse(request, cookieOptions, { success: true });
11609
11767
  }, {
11610
11768
  response: {
11611
11769
  200: AuthSignOutResponseSchema,
@@ -11615,29 +11773,25 @@ function registerAuthRoutes(app, host, options) {
11615
11773
  summary: "Sign out current auth session",
11616
11774
  tags: [OPENAPI_TAGS.authSessions.name],
11617
11775
  operationId: "signOut",
11618
- security: SIXB_CSRF_SECURITY_REQUIREMENT
11776
+ security: SIXB_OPTIONAL_SESSION_MUTATION_SECURITY_REQUIREMENT
11619
11777
  }
11620
- }).get("/api/auth/sessions", async ({ request }) => {
11621
- const authOptions = resolveAuthOptions(options, request);
11622
- const session = await host.auth.getSession(request, authOptions);
11623
- if (!session.authenticated) {
11624
- return jsonResponse2({ error: "Authentication required" }, 401);
11778
+ }).get("/api/auth/sessions", async (context) => {
11779
+ const session = requireSessionCaller(context);
11780
+ if (session instanceof Response) {
11781
+ return session;
11625
11782
  }
11626
- const sessions = await requireAuthStorage(host).sessions.listActiveByUserId({
11627
- projectId: host.id,
11628
- userId: session.user.id,
11629
- now: new Date
11630
- });
11783
+ const sessions = await host.auth.listSessions(session);
11631
11784
  return jsonResponse2({
11632
11785
  sessions: sessions.map((entry) => ({
11633
11786
  id: entry.id,
11634
- audience: entry.audience,
11787
+ audience: entry.bearer ? undefined : entry.audience,
11635
11788
  current: entry.id === session.session.id,
11636
11789
  createdAt: toIsoString(entry.createdAt),
11637
11790
  expiresAt: toIsoString(entry.expiresAt),
11638
11791
  lastSeenAt: entry.lastSeenAt ? toIsoString(entry.lastSeenAt) : undefined,
11639
11792
  userAgent: entry.userAgent,
11640
- ipAddress: entry.ipAddress
11793
+ ipAddress: entry.ipAddress,
11794
+ clientName: entry.bearer?.clientName
11641
11795
  }))
11642
11796
  }, 200);
11643
11797
  }, {
@@ -11650,30 +11804,20 @@ function registerAuthRoutes(app, host, options) {
11650
11804
  tags: [OPENAPI_TAGS.authSessions.name],
11651
11805
  operationId: "listAuthSessions"
11652
11806
  }
11653
- }).post("/api/auth/sessions/:sessionId/revoke", async ({ request, params }) => {
11654
- const authOptions = resolveAuthOptions(options, request);
11655
- const session = await host.auth.getSession(request, authOptions);
11656
- const cookieOptions = host.auth.getCookieOptions(authOptions);
11657
- if (!session.authenticated) {
11658
- return jsonResponse2({ error: "Authentication required" }, 401);
11659
- }
11660
- if (!verifyDoubleSubmitCsrf3(request, { cookieName: cookieOptions.csrfCookieName })) {
11661
- return jsonResponse2({ error: "CSRF verification failed" }, 403);
11807
+ }).post("/api/auth/sessions/:sessionId/revoke", async ({ request, params, ...context }) => {
11808
+ const session = requireSessionCaller(context);
11809
+ if (session instanceof Response) {
11810
+ return session;
11662
11811
  }
11663
11812
  const { sessionId } = RevokeAuthSessionParamsSchema.parse(params);
11664
- const storage = requireAuthStorage(host);
11665
- const target = await storage.sessions.getById({ projectId: host.id, id: sessionId });
11666
- if (!target || target.userId !== session.user.id) {
11813
+ if (!await host.auth.revokeSession(session, sessionId)) {
11667
11814
  return jsonResponse2({ error: "Session not found" }, 404);
11668
11815
  }
11669
- await storage.sessions.revoke({ projectId: host.id, id: sessionId, revokedAt: new Date });
11670
- host.auth.invalidateSession(sessionId);
11671
- const headers = new Headers({ "content-type": "application/json; charset=utf-8" });
11672
- if (sessionId === session.session.id) {
11673
- headers.append("set-cookie", clearSessionCookieHeader({ request, options: cookieOptions }));
11674
- headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }));
11816
+ if (sessionId !== session.session.id) {
11817
+ return jsonResponse2({ success: true }, 200);
11675
11818
  }
11676
- return new Response(JSON.stringify({ success: true }), { status: 200, headers });
11819
+ const cookieOptions = host.auth.getCookieOptions(resolveAuthOptions(options, request));
11820
+ return signedOutResponse(request, cookieOptions, { success: true });
11677
11821
  }, {
11678
11822
  params: RevokeAuthSessionParamsSchema,
11679
11823
  response: {
@@ -11686,33 +11830,16 @@ function registerAuthRoutes(app, host, options) {
11686
11830
  summary: "Revoke one of the current user's sessions",
11687
11831
  tags: [OPENAPI_TAGS.authSessions.name],
11688
11832
  operationId: "revokeAuthSession",
11689
- security: SIXB_CSRF_SECURITY_REQUIREMENT
11833
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
11690
11834
  }
11691
- }).post("/api/auth/sign-out-all", async ({ request }) => {
11692
- const authOptions = resolveAuthOptions(options, request);
11693
- const session = await host.auth.getSession(request, authOptions);
11694
- const cookieOptions = host.auth.getCookieOptions(authOptions);
11695
- if (!session.authenticated) {
11696
- return jsonResponse2({ error: "Authentication required" }, 401);
11835
+ }).post("/api/auth/sign-out-all", async ({ request, ...context }) => {
11836
+ const session = requireSessionCaller(context);
11837
+ if (session instanceof Response) {
11838
+ return session;
11697
11839
  }
11698
- if (!verifyDoubleSubmitCsrf3(request, { cookieName: cookieOptions.csrfCookieName })) {
11699
- return jsonResponse2({ error: "CSRF verification failed" }, 403);
11700
- }
11701
- const revoked = await requireAuthStorage(host).sessions.revokeActiveForUser({
11702
- projectId: host.id,
11703
- userId: session.user.id,
11704
- revokedAt: new Date
11705
- });
11706
- for (const revokedSession of revoked) {
11707
- host.auth.invalidateSession(revokedSession.id);
11708
- }
11709
- const headers = new Headers({ "content-type": "application/json; charset=utf-8" });
11710
- headers.append("set-cookie", clearSessionCookieHeader({ request, options: cookieOptions }));
11711
- headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }));
11712
- return new Response(JSON.stringify({ success: true, revokedCount: revoked.length }), {
11713
- status: 200,
11714
- headers
11715
- });
11840
+ const revokedCount = await host.auth.revokeAllSessions(session);
11841
+ const cookieOptions = host.auth.getCookieOptions(resolveAuthOptions(options, request));
11842
+ return signedOutResponse(request, cookieOptions, { success: true, revokedCount });
11716
11843
  }, {
11717
11844
  response: {
11718
11845
  200: SignOutAllResponseSchema,
@@ -11723,19 +11850,12 @@ function registerAuthRoutes(app, host, options) {
11723
11850
  summary: "Sign out the current user everywhere (all devices and apps)",
11724
11851
  tags: [OPENAPI_TAGS.authSessions.name],
11725
11852
  operationId: "signOutAll",
11726
- security: SIXB_CSRF_SECURITY_REQUIREMENT
11853
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
11727
11854
  }
11728
- }).get("/api/auth/access-management-options", async ({ request }) => {
11855
+ }).get("/api/auth/access-management-options", async (context) => {
11729
11856
  try {
11730
- const authOptions = resolveAuthOptions(options, request);
11731
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, {
11732
- ...authOptions,
11733
- credentialSource: "any"
11734
- }));
11735
- if (session instanceof Response) {
11736
- return session;
11737
- }
11738
- const assignableGroupIds = new Set(session.groupIds);
11857
+ const caller = requireUserCaller(context);
11858
+ const assignableGroupIds = new Set(caller.groupIds);
11739
11859
  return jsonResponse2({
11740
11860
  groups: host.definitions.security.listGroups().filter((group) => assignableGroupIds.has(group.id)).map(serializeGroupOption)
11741
11861
  }, 200);
@@ -11752,21 +11872,14 @@ function registerAuthRoutes(app, host, options) {
11752
11872
  summary: "Get auth access-token management options",
11753
11873
  tags: [OPENAPI_TAGS.authAccessTokens.name],
11754
11874
  operationId: "getAuthAccessManagementOptions",
11755
- security: bearerSecurityRequirement("getAuthAccessManagementOptions")
11875
+ security: accessTokenSecurityRequirement("getAuthAccessManagementOptions")
11756
11876
  }
11757
- }).get("/api/auth/access-tokens", async ({ request }) => {
11877
+ }).get("/api/auth/access-tokens", async ({ ...context }) => {
11758
11878
  try {
11759
- const authOptions = resolveAuthOptions(options, request);
11760
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, {
11761
- ...authOptions,
11762
- credentialSource: "any"
11763
- }));
11764
- if (session instanceof Response) {
11765
- return session;
11766
- }
11767
- const { accessTokens } = await host.auth.listPersonalAccessTokens(request, authOptions);
11879
+ const caller = requireUserCaller(context);
11880
+ const { accessTokens } = await host.auth.listPersonalAccessTokens(caller);
11768
11881
  return jsonResponse2({
11769
- accessTokens: accessTokens.map((accessToken) => serializeAccessToken(accessToken, { subjectLabel: session.user.email }))
11882
+ accessTokens: accessTokens.map((accessToken) => serializeAccessToken(accessToken, { subjectLabel: caller.user.email }))
11770
11883
  }, 200);
11771
11884
  } catch (error) {
11772
11885
  return authRouteErrorResponse(error);
@@ -11781,24 +11894,21 @@ function registerAuthRoutes(app, host, options) {
11781
11894
  summary: "List personal access tokens for the current user",
11782
11895
  tags: [OPENAPI_TAGS.authAccessTokens.name],
11783
11896
  operationId: "listAuthAccessTokens",
11784
- security: bearerSecurityRequirement("listAuthAccessTokens")
11897
+ security: accessTokenSecurityRequirement("listAuthAccessTokens")
11785
11898
  }
11786
- }).post("/api/auth/access-tokens", async ({ request, body }) => {
11899
+ }).post("/api/auth/access-tokens", async ({ body, ...context }) => {
11787
11900
  try {
11788
- const authOptions = resolveAuthOptions(options, request);
11789
11901
  const parsed = CreateAuthPersonalAccessTokenBodySchema.parse(body);
11790
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, {
11791
- ...authOptions,
11792
- credentialSource: "any"
11793
- }));
11794
- if (session instanceof Response) {
11795
- return session;
11796
- }
11902
+ const caller = requireUserCaller(context);
11797
11903
  const expiresAt = parseRequiredFutureDate(parsed.expiresAt);
11798
- const result = await host.auth.createPersonalAccessToken(request, { name: parsed.name, expiresAt, groupIds: parsed.groupIds }, authOptions);
11904
+ const result = await host.auth.createPersonalAccessToken(caller, {
11905
+ name: parsed.name,
11906
+ expiresAt,
11907
+ groupIds: parsed.groupIds
11908
+ });
11799
11909
  return jsonResponse2({
11800
11910
  accessToken: serializeAccessToken(result.accessToken, {
11801
- subjectLabel: session.user.email
11911
+ subjectLabel: caller.user.email
11802
11912
  }),
11803
11913
  tokenValue: result.tokenValue
11804
11914
  }, 201);
@@ -11818,23 +11928,16 @@ function registerAuthRoutes(app, host, options) {
11818
11928
  summary: "Create a personal access token",
11819
11929
  tags: [OPENAPI_TAGS.authAccessTokens.name],
11820
11930
  operationId: "createAuthPersonalAccessToken",
11821
- security: bearerSecurityRequirement("createAuthPersonalAccessToken")
11931
+ security: accessTokenSecurityRequirement("createAuthPersonalAccessToken")
11822
11932
  }
11823
- }).post("/api/auth/access-tokens/:tokenId/revoke", async ({ request, params }) => {
11933
+ }).post("/api/auth/access-tokens/:tokenId/revoke", async ({ params, ...context }) => {
11824
11934
  try {
11825
- const authOptions = resolveAuthOptions(options, request);
11826
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, {
11827
- ...authOptions,
11828
- credentialSource: "any"
11829
- }));
11830
- if (session instanceof Response) {
11831
- return session;
11832
- }
11935
+ const caller = requireUserCaller(context);
11833
11936
  const { tokenId } = RevokeAuthAccessTokenParamsSchema.parse(params);
11834
- const result = await host.auth.revokePersonalAccessToken(request, { tokenId }, authOptions);
11937
+ const result = await host.auth.revokePersonalAccessToken(caller, { tokenId });
11835
11938
  return jsonResponse2({
11836
11939
  accessToken: serializeAccessToken(result.accessToken, {
11837
- subjectLabel: session.user.email
11940
+ subjectLabel: caller.user.email
11838
11941
  })
11839
11942
  }, 200);
11840
11943
  } catch (error) {
@@ -11853,15 +11956,12 @@ function registerAuthRoutes(app, host, options) {
11853
11956
  summary: "Revoke one of the current user's personal access tokens",
11854
11957
  tags: [OPENAPI_TAGS.authAccessTokens.name],
11855
11958
  operationId: "revokeAuthAccessToken",
11856
- security: bearerSecurityRequirement("revokeAuthAccessToken")
11959
+ security: accessTokenSecurityRequirement("revokeAuthAccessToken")
11857
11960
  }
11858
- }).get("/api/auth/service-accounts", async ({ request }) => {
11961
+ }).get("/api/auth/service-accounts", async ({ ...context }) => {
11859
11962
  try {
11860
- const authOptions = resolveAuthOptions(options, request);
11861
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, { ...authOptions, credentialSource: "any" }));
11862
- if (session instanceof Response)
11863
- return session;
11864
- const { serviceAccounts } = await host.auth.listServiceAccounts(request, authOptions);
11963
+ const caller = requireUserCaller(context);
11964
+ const { serviceAccounts } = await host.auth.listServiceAccounts(caller);
11865
11965
  return jsonResponse2({
11866
11966
  serviceAccounts: serviceAccounts.map(({ serviceAccount, groupIds }) => serializeServiceAccount(serviceAccount, groupIds))
11867
11967
  }, 200);
@@ -11879,21 +11979,18 @@ function registerAuthRoutes(app, host, options) {
11879
11979
  summary: "List auth service accounts",
11880
11980
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
11881
11981
  operationId: "listAuthServiceAccounts",
11882
- security: bearerSecurityRequirement("listAuthServiceAccounts")
11982
+ security: accessTokenSecurityRequirement("listAuthServiceAccounts")
11883
11983
  }
11884
- }).post("/api/auth/service-accounts", async ({ request, body }) => {
11984
+ }).post("/api/auth/service-accounts", async ({ body, ...context }) => {
11885
11985
  try {
11886
- const authOptions = resolveAuthOptions(options, request);
11986
+ const caller = requireUserCaller(context);
11887
11987
  const parsed = CreateAuthServiceAccountBodySchema.parse(body);
11888
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, { ...authOptions, credentialSource: "any" }));
11889
- if (session instanceof Response)
11890
- return session;
11891
- const result = await host.auth.createServiceAccount(request, {
11988
+ const result = await host.auth.createServiceAccount(caller, {
11892
11989
  id: parsed.id,
11893
11990
  name: parsed.name,
11894
11991
  description: optionalTrimmed(parsed.description),
11895
11992
  groupIds: parsed.groupIds
11896
- }, { ...authOptions, credentialSource: "any" });
11993
+ });
11897
11994
  return jsonResponse2({
11898
11995
  serviceAccount: serializeServiceAccount(result.serviceAccount, result.groupMemberships.map((membership) => membership.groupId))
11899
11996
  }, 201);
@@ -11913,16 +12010,13 @@ function registerAuthRoutes(app, host, options) {
11913
12010
  summary: "Create an auth service account",
11914
12011
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
11915
12012
  operationId: "createAuthServiceAccount",
11916
- security: bearerSecurityRequirement("createAuthServiceAccount")
12013
+ security: accessTokenSecurityRequirement("createAuthServiceAccount")
11917
12014
  }
11918
- }).post("/api/auth/service-accounts/:serviceAccountId/disable", async ({ request, params }) => {
12015
+ }).post("/api/auth/service-accounts/:serviceAccountId/disable", async ({ params, ...context }) => {
11919
12016
  try {
11920
- const authOptions = resolveAuthOptions(options, request);
11921
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, { ...authOptions, credentialSource: "any" }));
11922
- if (session instanceof Response)
11923
- return session;
12017
+ const caller = requireUserCaller(context);
11924
12018
  const { serviceAccountId } = AuthServiceAccountParamsSchema.parse(params);
11925
- const result = await host.auth.disableServiceAccount(request, { serviceAccountId }, authOptions);
12019
+ const result = await host.auth.disableServiceAccount(caller, { serviceAccountId });
11926
12020
  return jsonResponse2({
11927
12021
  serviceAccount: serializeServiceAccount(result.serviceAccount, result.groupIds)
11928
12022
  }, 200);
@@ -11942,16 +12036,13 @@ function registerAuthRoutes(app, host, options) {
11942
12036
  summary: "Disable an auth service account",
11943
12037
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
11944
12038
  operationId: "disableAuthServiceAccount",
11945
- security: bearerSecurityRequirement("disableAuthServiceAccount")
12039
+ security: accessTokenSecurityRequirement("disableAuthServiceAccount")
11946
12040
  }
11947
- }).get("/api/auth/service-accounts/:serviceAccountId/access-tokens", async ({ request, params }) => {
12041
+ }).get("/api/auth/service-accounts/:serviceAccountId/access-tokens", async ({ params, ...context }) => {
11948
12042
  try {
11949
- const authOptions = resolveAuthOptions(options, request);
11950
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, { ...authOptions, credentialSource: "any" }));
11951
- if (session instanceof Response)
11952
- return session;
12043
+ const caller = requireUserCaller(context);
11953
12044
  const { serviceAccountId } = AuthServiceAccountParamsSchema.parse(params);
11954
- const { serviceAccount, accessTokens } = await host.auth.listServiceAccountAccessTokens(request, { serviceAccountId }, authOptions);
12045
+ const { serviceAccount, accessTokens } = await host.auth.listServiceAccountAccessTokens(caller, { serviceAccountId });
11955
12046
  return jsonResponse2({
11956
12047
  accessTokens: accessTokens.map((accessToken) => serializeAccessToken(accessToken, { subjectLabel: serviceAccount.name }))
11957
12048
  }, 200);
@@ -11971,23 +12062,20 @@ function registerAuthRoutes(app, host, options) {
11971
12062
  summary: "List access tokens for an auth service account",
11972
12063
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
11973
12064
  operationId: "listAuthServiceAccountAccessTokens",
11974
- security: bearerSecurityRequirement("listAuthServiceAccountAccessTokens")
12065
+ security: accessTokenSecurityRequirement("listAuthServiceAccountAccessTokens")
11975
12066
  }
11976
- }).post("/api/auth/service-accounts/:serviceAccountId/access-tokens", async ({ request, params, body }) => {
12067
+ }).post("/api/auth/service-accounts/:serviceAccountId/access-tokens", async ({ params, body, ...context }) => {
11977
12068
  try {
11978
- const authOptions = resolveAuthOptions(options, request);
12069
+ const caller = requireUserCaller(context);
11979
12070
  const parsedParams = AuthServiceAccountParamsSchema.parse(params);
11980
12071
  const parsed = CreateAuthServiceAccountAccessTokenBodySchema.parse(body);
11981
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, { ...authOptions, credentialSource: "any" }));
11982
- if (session instanceof Response)
11983
- return session;
11984
12072
  const expiresAt = parseRequiredFutureDate(parsed.expiresAt);
11985
- const result = await host.auth.createServiceAccountAccessToken(request, {
12073
+ const result = await host.auth.createServiceAccountAccessToken(caller, {
11986
12074
  serviceAccountId: parsedParams.serviceAccountId,
11987
12075
  name: parsed.name,
11988
12076
  expiresAt,
11989
12077
  groupIds: parsed.groupIds
11990
- }, { ...authOptions, credentialSource: "any" });
12078
+ });
11991
12079
  return jsonResponse2({
11992
12080
  accessToken: serializeAccessToken(result.accessToken, {
11993
12081
  subjectLabel: result.serviceAccount.name
@@ -12012,16 +12100,16 @@ function registerAuthRoutes(app, host, options) {
12012
12100
  summary: "Create an access token for an auth service account",
12013
12101
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
12014
12102
  operationId: "createAuthServiceAccountAccessToken",
12015
- security: bearerSecurityRequirement("createAuthServiceAccountAccessToken")
12103
+ security: accessTokenSecurityRequirement("createAuthServiceAccountAccessToken")
12016
12104
  }
12017
- }).post("/api/auth/service-accounts/:serviceAccountId/access-tokens/:tokenId/revoke", async ({ request, params }) => {
12105
+ }).post("/api/auth/service-accounts/:serviceAccountId/access-tokens/:tokenId/revoke", async ({ params, ...context }) => {
12018
12106
  try {
12019
- const authOptions = resolveAuthOptions(options, request);
12107
+ const caller = requireUserCaller(context);
12020
12108
  const parsed = RevokeAuthServiceAccountAccessTokenParamsSchema.parse(params);
12021
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, { ...authOptions, credentialSource: "any" }));
12022
- if (session instanceof Response)
12023
- return session;
12024
- const result = await host.auth.revokeServiceAccountAccessToken(request, { serviceAccountId: parsed.serviceAccountId, tokenId: parsed.tokenId }, authOptions);
12109
+ const result = await host.auth.revokeServiceAccountAccessToken(caller, {
12110
+ serviceAccountId: parsed.serviceAccountId,
12111
+ tokenId: parsed.tokenId
12112
+ });
12025
12113
  return jsonResponse2({
12026
12114
  accessToken: serializeAccessToken(result.accessToken, {
12027
12115
  subjectLabel: result.serviceAccount.name
@@ -12043,11 +12131,11 @@ function registerAuthRoutes(app, host, options) {
12043
12131
  summary: "Revoke an access token for an auth service account",
12044
12132
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
12045
12133
  operationId: "revokeAuthServiceAccountAccessToken",
12046
- security: bearerSecurityRequirement("revokeAuthServiceAccountAccessToken")
12134
+ security: accessTokenSecurityRequirement("revokeAuthServiceAccountAccessToken")
12047
12135
  }
12048
- }).post("/api/auth/invitations", async ({ request, body }) => {
12136
+ }).post("/api/auth/invitations", async ({ request, body, ...context }) => {
12049
12137
  try {
12050
- const authOptions = resolveAuthOptions(options, request);
12138
+ const caller = requireUserCaller(context);
12051
12139
  const parsed = CreateAuthInvitationBodySchema.parse(body);
12052
12140
  const deliveryContext = resolveInvitationDeliveryContext(options, request, {
12053
12141
  destinationId: parsed.destinationId,
@@ -12056,20 +12144,12 @@ function registerAuthRoutes(app, host, options) {
12056
12144
  if (deliveryContext instanceof Response) {
12057
12145
  return deliveryContext;
12058
12146
  }
12059
- const result = await host.auth.invite(request, {
12147
+ const result = await host.auth.invite(caller, {
12060
12148
  email: parsed.email,
12061
12149
  groupIds: parsed.groupIds,
12062
12150
  expiresAt: parseDate(parsed.expiresAt),
12063
- returnTo: deliveryContext.returnTo,
12064
12151
  revealLink: parsed.revealLink
12065
- }, {
12066
- ...authOptions,
12067
- delivery: {
12068
- audience: deliveryContext.audience,
12069
- returnTo: deliveryContext.returnTo,
12070
- requestOrigin: deliveryContext.requestOrigin
12071
- }
12072
- });
12152
+ }, deliveryContext);
12073
12153
  return jsonResponse2({
12074
12154
  invitation: serializeInvitation(result.invitation),
12075
12155
  delivery: serializeInvitationDelivery(result.delivery)
@@ -12092,13 +12172,13 @@ function registerAuthRoutes(app, host, options) {
12092
12172
  summary: "Create an auth invitation",
12093
12173
  tags: [OPENAPI_TAGS.authInvitations.name],
12094
12174
  operationId: "createAuthInvitation",
12095
- security: SIXB_CSRF_SECURITY_REQUIREMENT
12175
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
12096
12176
  }
12097
- }).get("/api/auth/invitation-options", async ({ request }) => {
12177
+ }).get("/api/auth/invitation-options", async ({ request, ...context }) => {
12098
12178
  try {
12099
- const authOptions = resolveAuthOptions(options, request);
12179
+ const caller = requireUserCaller(context);
12100
12180
  return jsonResponse2({
12101
- ...await host.auth.getInvitationOptions(request, authOptions),
12181
+ ...await host.auth.getInvitationOptions(caller),
12102
12182
  ...options.getInvitationDestinationOptions(request)
12103
12183
  }, 200);
12104
12184
  } catch (error) {
@@ -12115,17 +12195,17 @@ function registerAuthRoutes(app, host, options) {
12115
12195
  tags: [OPENAPI_TAGS.authInvitations.name],
12116
12196
  operationId: "getAuthInvitationOptions"
12117
12197
  }
12118
- }).get("/api/auth/invitations", async ({ request, query }) => {
12198
+ }).get("/api/auth/invitations", async ({ query, ...context }) => {
12119
12199
  try {
12120
- const authOptions = resolveAuthOptions(options, request);
12200
+ const caller = requireUserCaller(context);
12121
12201
  const parsed = ListAuthInvitationsQuerySchema.parse(query);
12122
- const result = await host.auth.listInvitations(request, {
12202
+ const result = await host.auth.listInvitations(caller, {
12123
12203
  email: parsed.email,
12124
12204
  statuses: parsed.status ? [parsed.status] : undefined,
12125
12205
  limit: parseOptionalInt(parsed.limit),
12126
12206
  offset: parseOptionalInt(parsed.offset),
12127
12207
  order: parsed.order
12128
- }, authOptions);
12208
+ });
12129
12209
  return jsonResponse2({
12130
12210
  invitations: result.invitations.map(serializeInvitation),
12131
12211
  hasMore: result.hasMore,
@@ -12149,13 +12229,13 @@ function registerAuthRoutes(app, host, options) {
12149
12229
  tags: [OPENAPI_TAGS.authInvitations.name],
12150
12230
  operationId: "listAuthInvitations"
12151
12231
  }
12152
- }).post("/api/auth/invitations/:invitationId/revoke", async ({ request, params }) => {
12232
+ }).post("/api/auth/invitations/:invitationId/revoke", async ({ params, ...context }) => {
12153
12233
  try {
12154
- const authOptions = resolveAuthOptions(options, request);
12234
+ const caller = requireUserCaller(context);
12155
12235
  const parsed = RevokeAuthInvitationParamsSchema.parse(params);
12156
- const result = await host.auth.revokeInvitation(request, {
12236
+ const result = await host.auth.revokeInvitation(caller, {
12157
12237
  invitationId: parsed.invitationId
12158
- }, authOptions);
12238
+ });
12159
12239
  return jsonResponse2({
12160
12240
  invitation: serializeInvitation(result.invitation)
12161
12241
  }, 200);
@@ -12176,12 +12256,12 @@ function registerAuthRoutes(app, host, options) {
12176
12256
  summary: "Revoke an auth invitation",
12177
12257
  tags: [OPENAPI_TAGS.authInvitations.name],
12178
12258
  operationId: "revokeAuthInvitation",
12179
- security: SIXB_CSRF_SECURITY_REQUIREMENT
12259
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
12180
12260
  }
12181
- }).get("/api/auth/membership-options", async ({ request }) => {
12261
+ }).get("/api/auth/membership-options", async ({ ...context }) => {
12182
12262
  try {
12183
- const authOptions = resolveAuthOptions(options, request);
12184
- return jsonResponse2(await host.auth.getMembershipOptions(request, authOptions), 200);
12263
+ const caller = requireUserCaller(context);
12264
+ return jsonResponse2(await host.auth.getMembershipOptions(caller), 200);
12185
12265
  } catch (error) {
12186
12266
  return authRouteErrorResponse(error);
12187
12267
  }
@@ -12196,15 +12276,15 @@ function registerAuthRoutes(app, host, options) {
12196
12276
  tags: [OPENAPI_TAGS.authMembers.name],
12197
12277
  operationId: "getAuthMembershipOptions"
12198
12278
  }
12199
- }).get("/api/auth/members", async ({ request, query }) => {
12279
+ }).get("/api/auth/members", async ({ query, ...context }) => {
12200
12280
  try {
12201
- const authOptions = resolveAuthOptions(options, request);
12281
+ const caller = requireUserCaller(context);
12202
12282
  const parsed = ListAuthMembersQuerySchema.parse(query);
12203
- const result = await host.auth.listMembers(request, {
12283
+ const result = await host.auth.listMembers(caller, {
12204
12284
  limit: parseOptionalInt(parsed.limit),
12205
12285
  offset: parseOptionalInt(parsed.offset),
12206
12286
  order: parsed.order
12207
- }, authOptions);
12287
+ });
12208
12288
  return jsonResponse2({
12209
12289
  members: result.members.map(serializeMemberSummary),
12210
12290
  hasMore: result.hasMore,
@@ -12226,12 +12306,15 @@ function registerAuthRoutes(app, host, options) {
12226
12306
  tags: [OPENAPI_TAGS.authMembers.name],
12227
12307
  operationId: "listAuthMembers"
12228
12308
  }
12229
- }).patch("/api/auth/members/:userId/groups", async ({ request, params, body }) => {
12309
+ }).patch("/api/auth/members/:userId/groups", async ({ params, body, ...context }) => {
12230
12310
  try {
12231
- const authOptions = resolveAuthOptions(options, request);
12311
+ const caller = requireUserCaller(context);
12232
12312
  const parsedParams = AuthMemberParamsSchema.parse(params);
12233
12313
  const parsed = UpdateAuthMemberGroupsBodySchema.parse(body);
12234
- const result = await host.auth.updateMemberGroups(request, { userId: parsedParams.userId, groupIds: parsed.groupIds }, authOptions);
12314
+ const result = await host.auth.updateMemberGroups(caller, {
12315
+ userId: parsedParams.userId,
12316
+ groupIds: parsed.groupIds
12317
+ });
12235
12318
  return jsonResponse2({ member: serializeManagedMember(result.user, result.groupIds) }, 200);
12236
12319
  } catch (error) {
12237
12320
  return authRouteErrorResponse(error);
@@ -12251,13 +12334,13 @@ function registerAuthRoutes(app, host, options) {
12251
12334
  summary: "Update an auth member's groups",
12252
12335
  tags: [OPENAPI_TAGS.authMembers.name],
12253
12336
  operationId: "updateAuthMemberGroups",
12254
- security: SIXB_CSRF_SECURITY_REQUIREMENT
12337
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
12255
12338
  }
12256
- }).post("/api/auth/members/:userId/suspend", async ({ request, params }) => {
12339
+ }).post("/api/auth/members/:userId/suspend", async ({ params, ...context }) => {
12257
12340
  try {
12258
- const authOptions = resolveAuthOptions(options, request);
12341
+ const caller = requireUserCaller(context);
12259
12342
  const parsed = AuthMemberParamsSchema.parse(params);
12260
- const result = await host.auth.suspendMember(request, { userId: parsed.userId }, authOptions);
12343
+ const result = await host.auth.suspendMember(caller, { userId: parsed.userId });
12261
12344
  return jsonResponse2({ member: serializeManagedMember(result.user, result.groupIds) }, 200);
12262
12345
  } catch (error) {
12263
12346
  return authRouteErrorResponse(error);
@@ -12275,13 +12358,13 @@ function registerAuthRoutes(app, host, options) {
12275
12358
  summary: "Suspend an auth member",
12276
12359
  tags: [OPENAPI_TAGS.authMembers.name],
12277
12360
  operationId: "suspendAuthMember",
12278
- security: SIXB_CSRF_SECURITY_REQUIREMENT
12361
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
12279
12362
  }
12280
- }).post("/api/auth/members/:userId/reactivate", async ({ request, params }) => {
12363
+ }).post("/api/auth/members/:userId/reactivate", async ({ params, ...context }) => {
12281
12364
  try {
12282
- const authOptions = resolveAuthOptions(options, request);
12365
+ const caller = requireUserCaller(context);
12283
12366
  const parsed = AuthMemberParamsSchema.parse(params);
12284
- const result = await host.auth.reactivateMember(request, { userId: parsed.userId }, authOptions);
12367
+ const result = await host.auth.reactivateMember(caller, { userId: parsed.userId });
12285
12368
  return jsonResponse2({ member: serializeManagedMember(result.user, result.groupIds) }, 200);
12286
12369
  } catch (error) {
12287
12370
  return authRouteErrorResponse(error);
@@ -12299,7 +12382,7 @@ function registerAuthRoutes(app, host, options) {
12299
12382
  summary: "Reactivate an auth member",
12300
12383
  tags: [OPENAPI_TAGS.authMembers.name],
12301
12384
  operationId: "reactivateAuthMember",
12302
- security: SIXB_CSRF_SECURITY_REQUIREMENT
12385
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
12303
12386
  }
12304
12387
  }).post("/auth/sign-in", async ({ body, request }) => {
12305
12388
  const strategy = host.auth.getStrategy();
@@ -12490,7 +12573,7 @@ function registerAuthRoutes(app, host, options) {
12490
12573
  });
12491
12574
  }
12492
12575
  var DEVICE_AUTHORIZATION_TTL_MS = 10 * 60 * 1000;
12493
- var DEVICE_ACCESS_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000;
12576
+ var DEVICE_AUTHORIZATIONS_PER_ADDRESS = 10;
12494
12577
  var DEVICE_AUTHORIZATION_POLL_INTERVAL_SECONDS = 2;
12495
12578
  var DEVICE_USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXYZ23456789";
12496
12579
  function hashDeviceCode(deviceCode) {
@@ -12586,10 +12669,17 @@ async function completeMagicLinkCallback(input) {
12586
12669
  return await invalidMagicLinkResponse(input.options, input.authRedirectHint);
12587
12670
  }
12588
12671
  }
12672
+ function bearerTokensBody(tokens, bearer, issuedAt) {
12673
+ return {
12674
+ accessToken: tokens.accessToken,
12675
+ refreshToken: tokens.refreshToken,
12676
+ expiresIn: Math.round((bearer.accessExpiresAt.getTime() - issuedAt.getTime()) / 1000)
12677
+ };
12678
+ }
12589
12679
  function resolveSessionDevice(request) {
12590
12680
  return {
12591
12681
  userAgent: request.headers.get("user-agent")?.trim() || undefined,
12592
- ipAddress: request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || request.headers.get("x-real-ip")?.trim() || undefined
12682
+ ipAddress: getRequestClientAddress(request)
12593
12683
  };
12594
12684
  }
12595
12685
  function sessionCallbackCompletionResponse(input) {
@@ -12680,6 +12770,20 @@ function resolveSessionCsrfToken(input) {
12680
12770
  })
12681
12771
  };
12682
12772
  }
12773
+ function authSessionBody(host, session, audience) {
12774
+ return {
12775
+ authenticated: true,
12776
+ applicationAccess: { allowed: sessionCanAccessApplication(host, session, audience), audience },
12777
+ user: {
12778
+ id: session.user.id,
12779
+ email: session.user.email,
12780
+ displayName: session.user.displayName,
12781
+ avatarUrl: session.user.avatarUrl,
12782
+ groupIds: [...session.groupIds]
12783
+ },
12784
+ session: { id: session.session.id, expiresAt: toIsoString(session.session.expiresAt) }
12785
+ };
12786
+ }
12683
12787
  function authSessionJsonResponse(body, setCookies) {
12684
12788
  const headers = new Headers({
12685
12789
  "content-type": "application/json; charset=utf-8",
@@ -13001,8 +13105,7 @@ function serializeAccessToken(accessToken, options = {}) {
13001
13105
  name: accessToken.name,
13002
13106
  kind: accessToken.kind,
13003
13107
  status,
13004
- subjectType: accessToken.subjectType,
13005
- subjectId: accessToken.subjectId,
13108
+ subject: { type: accessToken.subject.type, id: accessToken.subject.id },
13006
13109
  subjectLabel: options.subjectLabel,
13007
13110
  groupIds: accessToken.groupIds ? [...accessToken.groupIds] : undefined,
13008
13111
  createdAt: toIsoString(accessToken.createdAt),
@@ -13038,17 +13141,25 @@ function optionalTrimmed(value) {
13038
13141
  const trimmed = value?.trim();
13039
13142
  return trimmed ? trimmed : undefined;
13040
13143
  }
13041
- function requireAuthenticatedUserSession(session) {
13042
- if (!session.authenticated) {
13043
- return jsonResponse2({ error: "Authentication required" }, 401);
13144
+ function requireUserCaller(context) {
13145
+ const caller = requestCaller(context);
13146
+ if (!caller) {
13147
+ throw new AuthRuntimeError("authentication_required", "Authentication required");
13044
13148
  }
13045
- if (!isAuthenticatedUserSession(session)) {
13046
- return jsonResponse2({ error: "User authentication is required" }, 403);
13149
+ if (!("user" in caller)) {
13150
+ throw new AuthRuntimeError("authorization_denied", "User authentication is required");
13047
13151
  }
13048
- return session;
13152
+ return caller;
13153
+ }
13154
+ function requireSessionCaller(context) {
13155
+ const caller = requestCaller(context);
13156
+ return caller?.credentialSource === "session" ? caller : jsonResponse2({ error: "Authentication required" }, 401);
13049
13157
  }
13050
- function isAuthenticatedUserSession(session) {
13051
- return session.principal.type === "user";
13158
+ function signedOutResponse(request, cookieOptions, body) {
13159
+ const headers = new Headers({ "content-type": "application/json; charset=utf-8" });
13160
+ headers.append("set-cookie", clearSessionCookieHeader({ request, options: cookieOptions }));
13161
+ headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }));
13162
+ return new Response(JSON.stringify(body), { status: 200, headers });
13052
13163
  }
13053
13164
  function serializeInvitation(invitation) {
13054
13165
  return {
@@ -14457,6 +14568,7 @@ class SixbServer {
14457
14568
  authRedirectContextResolver;
14458
14569
  authExperience;
14459
14570
  sharedAccessOptions;
14571
+ resolveClientAddress;
14460
14572
  app = null;
14461
14573
  bunServer = null;
14462
14574
  maintenance = null;
@@ -14470,6 +14582,7 @@ class SixbServer {
14470
14582
  this.authRedirectContextResolver = createApiBrowserAuthRedirectContextResolver(this.apiBrowserPolicy);
14471
14583
  this.authExperience = options.authExperience;
14472
14584
  this.sharedAccessOptions = options.sharedAccess ?? {};
14585
+ this.resolveClientAddress = createClientAddressResolver(options.trustedProxies ?? [PRIVATE_NETWORKS]);
14473
14586
  }
14474
14587
  getHost() {
14475
14588
  return this.hostRuntime;
@@ -14511,7 +14624,8 @@ class SixbServer {
14511
14624
  this.app = createSixbApi(this);
14512
14625
  this.bunServer = startApiServer(this.app, {
14513
14626
  host: this.hostname,
14514
- port: this.port
14627
+ port: this.port,
14628
+ resolveClientAddress: this.resolveClientAddress
14515
14629
  });
14516
14630
  } catch (error) {
14517
14631
  this.app = null;
@@ -14565,7 +14679,7 @@ function createSixbApi(server) {
14565
14679
  allowedHeaders: [
14566
14680
  "authorization",
14567
14681
  "content-type",
14568
- CSRF_HEADER_NAME3,
14682
+ CSRF_HEADER_NAME2,
14569
14683
  SESSION_ACTIVITY_HEADER_NAME,
14570
14684
  SHARED_ACCESS_GRANT_HEADER_NAME
14571
14685
  ],
@@ -14687,11 +14801,13 @@ function createSixbApi(server) {
14687
14801
  components: {
14688
14802
  securitySchemes: {
14689
14803
  [SIXB_CSRF_SECURITY_SCHEME_ID]: SIXB_CSRF_SECURITY_SCHEME,
14690
- [SIXB_BEARER_SECURITY_SCHEME_ID]: SIXB_BEARER_SECURITY_SCHEME,
14804
+ [SIXB_SESSION_SECURITY_SCHEME_ID]: SIXB_SESSION_SECURITY_SCHEME,
14805
+ [SIXB_ACCESS_TOKEN_SECURITY_SCHEME_ID]: SIXB_ACCESS_TOKEN_SECURITY_SCHEME,
14691
14806
  [SIXB_SHARED_GRANT_SECURITY_SCHEME_ID]: SIXB_SHARED_GRANT_SECURITY_SCHEME
14692
14807
  },
14693
14808
  schemas: ObjectQueryOpenApiSchemas
14694
14809
  },
14810
+ security: SIXB_SESSION_SECURITY_REQUIREMENT,
14695
14811
  tags: OPENAPI_TAG_METADATA
14696
14812
  },
14697
14813
  swagger: {
@@ -14782,7 +14898,14 @@ function startApiServer(app, options) {
14782
14898
  const bunServer = Bun.serve({
14783
14899
  port: options.port,
14784
14900
  hostname: options.host,
14785
- fetch: (request) => app.fetch(request),
14901
+ fetch: (request, server) => {
14902
+ const socketAddress = server.requestIP(request)?.address;
14903
+ if (socketAddress) {
14904
+ const forwardedFor = request.headers.get("x-forwarded-for");
14905
+ setRequestClientAddress(request, options.resolveClientAddress(socketAddress, forwardedFor));
14906
+ }
14907
+ return app.fetch(request);
14908
+ },
14786
14909
  websocket: getElysiaWsHandler(app)
14787
14910
  });
14788
14911
  attachBunServer(app, bunServer);
@@ -14803,4 +14926,4 @@ export {
14803
14926
  createSixbServer
14804
14927
  };
14805
14928
 
14806
- //# debugId=F9832BC92C38240664756E2164756E21
14929
+ //# debugId=FAAE157E14B4AD2064756E2164756E21