@sixb/server 0.1.11 → 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 (104) 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 +723 -480
  15. package/dist/index.js.map +43 -41
  16. package/dist/openapi/security.d.ts +34 -10
  17. package/dist/openapi/security.d.ts.map +1 -1
  18. package/dist/routes/agents.d.ts +121 -34
  19. package/dist/routes/agents.d.ts.map +1 -1
  20. package/dist/routes/ai-accounting.d.ts.map +1 -1
  21. package/dist/routes/auth.d.ts +64 -17
  22. package/dist/routes/auth.d.ts.map +1 -1
  23. package/dist/routes/connectors.d.ts.map +1 -1
  24. package/dist/routes/datasets.d.ts +8 -8
  25. package/dist/routes/events.d.ts +0 -4
  26. package/dist/routes/events.d.ts.map +1 -1
  27. package/dist/routes/files.d.ts +15 -2
  28. package/dist/routes/files.d.ts.map +1 -1
  29. package/dist/routes/models.d.ts +7 -7
  30. package/dist/routes/objects.d.ts +16 -5
  31. package/dist/routes/objects.d.ts.map +1 -1
  32. package/dist/routes/ontology.d.ts +37 -13
  33. package/dist/routes/ontology.d.ts.map +1 -1
  34. package/dist/routes/shared-access.d.ts.map +1 -1
  35. package/dist/routes/syncs.d.ts +5 -5
  36. package/dist/routes/workflows.d.ts +36 -36
  37. package/dist/routes/workflows.d.ts.map +1 -1
  38. package/dist/routes/ws/agents.d.ts +2 -3
  39. package/dist/routes/ws/agents.d.ts.map +1 -1
  40. package/dist/schemas/agents.d.ts +205 -100
  41. package/dist/schemas/agents.d.ts.map +1 -1
  42. package/dist/schemas/ai-accounting.d.ts +692 -104
  43. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  44. package/dist/schemas/ai-usage.d.ts +2 -2
  45. package/dist/schemas/auth.d.ts +241 -85
  46. package/dist/schemas/auth.d.ts.map +1 -1
  47. package/dist/schemas/common.d.ts +26 -0
  48. package/dist/schemas/common.d.ts.map +1 -1
  49. package/dist/schemas/datasets.d.ts +22 -22
  50. package/dist/schemas/events.d.ts +74 -44
  51. package/dist/schemas/events.d.ts.map +1 -1
  52. package/dist/schemas/models.d.ts +42 -42
  53. package/dist/schemas/objects.d.ts +8 -0
  54. package/dist/schemas/objects.d.ts.map +1 -1
  55. package/dist/schemas/ontology.d.ts +259 -49
  56. package/dist/schemas/ontology.d.ts.map +1 -1
  57. package/dist/schemas/syncs.d.ts +12 -12
  58. package/dist/schemas/workflows.d.ts +230 -240
  59. package/dist/schemas/workflows.d.ts.map +1 -1
  60. package/dist/server.d.ts +6 -0
  61. package/dist/server.d.ts.map +1 -1
  62. package/dist/utils/ws.d.ts +1 -2
  63. package/dist/utils/ws.d.ts.map +1 -1
  64. package/package.json +5 -5
  65. package/src/auth/access-token-boundary.ts +31 -30
  66. package/src/auth/client-address.ts +67 -0
  67. package/src/auth/guard.ts +13 -4
  68. package/src/auth/public-routes.ts +9 -2
  69. package/src/auth/rate-limit.ts +43 -0
  70. package/src/auth/scope.ts +13 -3
  71. package/src/auth/shared-access.ts +0 -3
  72. package/src/openapi/security.ts +37 -17
  73. package/src/routes/action-runs.ts +5 -5
  74. package/src/routes/actions.ts +4 -4
  75. package/src/routes/agents.ts +56 -14
  76. package/src/routes/ai-accounting.ts +11 -10
  77. package/src/routes/auth.ts +331 -432
  78. package/src/routes/connector-connection-runs.ts +5 -5
  79. package/src/routes/connector-connections.ts +3 -3
  80. package/src/routes/connectors.ts +2 -2
  81. package/src/routes/events.ts +2 -2
  82. package/src/routes/files.ts +30 -15
  83. package/src/routes/links.ts +3 -3
  84. package/src/routes/logs.ts +2 -2
  85. package/src/routes/objects.ts +58 -14
  86. package/src/routes/ontology.ts +42 -14
  87. package/src/routes/pipelines.ts +2 -2
  88. package/src/routes/project.ts +2 -2
  89. package/src/routes/share-grants.ts +4 -4
  90. package/src/routes/shared-access.ts +3 -2
  91. package/src/routes/syncs.ts +2 -2
  92. package/src/routes/telemetry.ts +5 -5
  93. package/src/routes/workflows.ts +18 -19
  94. package/src/routes/ws/agents.ts +4 -5
  95. package/src/schemas/agents.ts +9 -0
  96. package/src/schemas/ai-accounting.ts +19 -1
  97. package/src/schemas/auth.ts +27 -8
  98. package/src/schemas/common.ts +11 -0
  99. package/src/schemas/events.ts +35 -7
  100. package/src/schemas/objects.ts +18 -6
  101. package/src/schemas/ontology.ts +31 -7
  102. package/src/schemas/workflows.ts +4 -9
  103. package/src/server.ts +35 -5
  104. package/src/utils/ws.ts +2 -3
package/dist/index.js CHANGED
@@ -2,11 +2,11 @@
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";
9
- import { zodToJsonSchema } from "zod-to-json-schema";
9
+ import { zodToJsonSchema as zodToJsonSchema2 } from "zod-to-json-schema";
10
10
 
11
11
  // src/auth/browser-origin.ts
12
12
  import {
@@ -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(),
@@ -1468,6 +1526,10 @@ var jsonValueOpenApiOverride = (def) => {
1468
1526
  }
1469
1527
  return ignoreOverride;
1470
1528
  };
1529
+ var AiUsageLimitErrorResponseSchema = codedErrorResponseSchema([
1530
+ "ai.usage_limit_exceeded",
1531
+ "ai.usage_limit_unavailable"
1532
+ ]).extend({ details: JsonValueSchema.optional() });
1471
1533
 
1472
1534
  // src/schemas/ontology.ts
1473
1535
  import { z as z2 } from "zod";
@@ -1489,10 +1551,18 @@ var PropertyDefinitionSchema = z2.object({
1489
1551
  text: z2.boolean().optional(),
1490
1552
  exact: z2.boolean().optional(),
1491
1553
  facet: z2.boolean().optional(),
1492
- vector: z2.boolean().optional(),
1493
1554
  weight: z2.number().optional()
1494
1555
  }).optional()
1495
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
+ });
1496
1566
  var LinkDefinitionSchema = z2.object({
1497
1567
  id: z2.string(),
1498
1568
  name: z2.string(),
@@ -1522,15 +1592,20 @@ var ObjectTypeSchema = z2.object({
1522
1592
  description: z2.string().optional(),
1523
1593
  extends: z2.string().optional(),
1524
1594
  implements: z2.array(z2.string()).optional(),
1525
- properties: z2.array(PropertyDefinitionSchema),
1595
+ properties: z2.array(ObjectPropertyDefinitionSchema),
1526
1596
  search: z2.object({
1527
1597
  title: z2.string().optional(),
1528
1598
  defaultText: z2.array(z2.string()).optional(),
1529
1599
  exact: z2.array(z2.string()).optional(),
1530
- vector: z2.object({
1531
- property: z2.string(),
1532
- source: z2.array(z2.string())
1533
- }).optional()
1600
+ vectors: z2.record(z2.string(), z2.object({
1601
+ source: z2.array(z2.string()),
1602
+ model: z2.object({
1603
+ providerId: z2.string(),
1604
+ modelId: z2.string(),
1605
+ dimensions: z2.number().int().positive(),
1606
+ representation: z2.object({ name: z2.string(), version: z2.string().optional() }).optional()
1607
+ })
1608
+ })).optional()
1534
1609
  }).optional(),
1535
1610
  links: z2.array(LinkDefinitionSchema),
1536
1611
  actions: z2.array(ActionSchema)
@@ -2006,7 +2081,7 @@ function registerActionRunRoutes(app, host) {
2006
2081
  summary: "List action run history",
2007
2082
  tags: [OPENAPI_TAGS.actionRuns.name],
2008
2083
  operationId: "listActionRuns",
2009
- security: bearerSecurityRequirement("listActionRuns")
2084
+ security: accessTokenSecurityRequirement("listActionRuns")
2010
2085
  }
2011
2086
  }).get("/api/action-runs/:runId", async (context) => {
2012
2087
  const { params, set } = context;
@@ -2037,7 +2112,7 @@ function registerActionRunRoutes(app, host) {
2037
2112
  summary: "Get action run detail",
2038
2113
  tags: [OPENAPI_TAGS.actionRuns.name],
2039
2114
  operationId: "getActionRun",
2040
- security: bearerSecurityRequirement("getActionRun")
2115
+ security: accessTokenSecurityRequirement("getActionRun")
2041
2116
  }
2042
2117
  }).get("/api/action-runs/:runId/files/content", (context) => actionRunFileContentResponse(host, context), {
2043
2118
  params: ActionRunIdParamsSchema,
@@ -2047,7 +2122,7 @@ function registerActionRunRoutes(app, host) {
2047
2122
  summary: "Get action run file content",
2048
2123
  tags: ["Actions"],
2049
2124
  operationId: "getActionRunFileContent",
2050
- security: bearerSecurityRequirement("getActionRunFileContent"),
2125
+ security: accessTokenSecurityRequirement("getActionRunFileContent"),
2051
2126
  responses: fileContentGetResponses({ optionalStorage: true })
2052
2127
  }
2053
2128
  }).head("/api/action-runs/:runId/files/content", (context) => actionRunFileContentResponse(host, context, { head: true }), {
@@ -2058,7 +2133,7 @@ function registerActionRunRoutes(app, host) {
2058
2133
  summary: "Head action run file content",
2059
2134
  tags: ["Actions"],
2060
2135
  operationId: "headActionRunFileContent",
2061
- security: bearerSecurityRequirement("headActionRunFileContent"),
2136
+ security: accessTokenSecurityRequirement("headActionRunFileContent"),
2062
2137
  responses: fileContentHeadResponses({ optionalStorage: true })
2063
2138
  }
2064
2139
  });
@@ -2103,7 +2178,7 @@ function registerActionRoutes(app, host) {
2103
2178
  summary: "List registered actions",
2104
2179
  tags: [OPENAPI_TAGS.actions.name],
2105
2180
  operationId: "listActions",
2106
- security: bearerSecurityRequirement("listActions")
2181
+ security: accessTokenSecurityRequirement("listActions")
2107
2182
  }
2108
2183
  }).get("/api/actions/:actionId", async (context) => {
2109
2184
  const { params, set } = context;
@@ -2120,7 +2195,7 @@ function registerActionRoutes(app, host) {
2120
2195
  summary: "Get action metadata",
2121
2196
  tags: [OPENAPI_TAGS.actions.name],
2122
2197
  operationId: "getAction",
2123
- security: bearerSecurityRequirement("getAction")
2198
+ security: accessTokenSecurityRequirement("getAction")
2124
2199
  }
2125
2200
  }).post("/api/actions/:actionId", async (context) => {
2126
2201
  const { params, body, set } = context;
@@ -2152,7 +2227,7 @@ function registerActionRoutes(app, host) {
2152
2227
  summary: "Request an action",
2153
2228
  tags: [OPENAPI_TAGS.actions.name],
2154
2229
  operationId: "requestAction",
2155
- security: bearerSecurityRequirement("requestAction")
2230
+ security: accessTokenSecurityRequirement("requestAction")
2156
2231
  }
2157
2232
  });
2158
2233
  }
@@ -2172,7 +2247,6 @@ import { normalizeRoutePath as normalizeRoutePath4, pathSegmentsFor } from "@six
2172
2247
  // src/routes/files.ts
2173
2248
  import {
2174
2249
  DEFAULT_SIMPLE_FILE_UPLOAD_BYTES,
2175
- InMemoryFileUploadSessions,
2176
2250
  SYSTEM_PRINCIPAL
2177
2251
  } from "@sixb/core";
2178
2252
  import { computeBlobDigest, supportsDirectUpload } from "@sixb/core/blob-storage/server";
@@ -2180,7 +2254,7 @@ import { createFileUploadId, createUploadExpiresAt } from "@sixb/core/internal/s
2180
2254
  import { FileUploadSessionError as FileUploadSessionError2 } from "@sixb/core/storage";
2181
2255
  var DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES = DEFAULT_SIMPLE_FILE_UPLOAD_BYTES + 1024 * 1024;
2182
2256
  function registerFileRoutes(app, host) {
2183
- const uploadSessions = host.storage.fileUploadSessions ?? new InMemoryFileUploadSessions;
2257
+ const uploadSessions = host.storage.fileUploadSessions;
2184
2258
  return app.post("/api/files", async ({ request, set }) => {
2185
2259
  try {
2186
2260
  const requestSizeError = requestSizeLimitError(request, DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES);
@@ -2225,7 +2299,7 @@ function registerFileRoutes(app, host) {
2225
2299
  summary: "Upload a file",
2226
2300
  tags: [OPENAPI_TAGS.files.name],
2227
2301
  operationId: "uploadFileRaw",
2228
- security: bearerSecurityRequirement("uploadFileRaw"),
2302
+ security: accessTokenSecurityRequirement("uploadFileRaw"),
2229
2303
  requestBody: {
2230
2304
  required: true,
2231
2305
  content: {
@@ -2250,6 +2324,9 @@ function registerFileRoutes(app, host) {
2250
2324
  }).post("/api/files/uploads", async (context) => {
2251
2325
  const { body, set } = context;
2252
2326
  try {
2327
+ if (!uploadSessions) {
2328
+ return unconfiguredStorageResponse2(set, "File upload session storage");
2329
+ }
2253
2330
  const parsed = CreateFileUploadBodySchema.parse(body);
2254
2331
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2255
2332
  const uploadId = createFileUploadId();
@@ -2286,17 +2363,21 @@ function registerFileRoutes(app, host) {
2286
2363
  body: CreateFileUploadBodySchema,
2287
2364
  response: {
2288
2365
  201: CreateFileUploadResponseSchema,
2289
- 400: ErrorResponseSchema
2366
+ 400: ErrorResponseSchema,
2367
+ 501: ErrorResponseSchema
2290
2368
  },
2291
2369
  detail: {
2292
2370
  summary: "Create a staged file upload",
2293
2371
  tags: [OPENAPI_TAGS.files.name],
2294
2372
  operationId: "createFileUpload",
2295
- security: SIXB_CSRF_SECURITY_REQUIREMENT
2373
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
2296
2374
  }
2297
2375
  }).put("/api/files/uploads/:uploadId/content", async (context) => {
2298
2376
  const { params, request, set } = context;
2299
2377
  try {
2378
+ if (!uploadSessions) {
2379
+ return unconfiguredStorageResponse2(set, "File upload session storage");
2380
+ }
2300
2381
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2301
2382
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
2302
2383
  if (session.status !== "pending") {
@@ -2347,13 +2428,14 @@ function registerFileRoutes(app, host) {
2347
2428
  400: ErrorResponseSchema,
2348
2429
  404: ErrorResponseSchema,
2349
2430
  409: ErrorResponseSchema,
2350
- 410: ErrorResponseSchema
2431
+ 410: ErrorResponseSchema,
2432
+ 501: ErrorResponseSchema
2351
2433
  },
2352
2434
  detail: {
2353
2435
  summary: "Upload staged file content through Sixb",
2354
2436
  tags: [OPENAPI_TAGS.files.name],
2355
2437
  operationId: "uploadFileContent",
2356
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
2438
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
2357
2439
  requestBody: {
2358
2440
  required: true,
2359
2441
  content: {
@@ -2369,6 +2451,9 @@ function registerFileRoutes(app, host) {
2369
2451
  }).post("/api/files/uploads/:uploadId/parts/:partNumber", async (context) => {
2370
2452
  const { params, set } = context;
2371
2453
  try {
2454
+ if (!uploadSessions) {
2455
+ return unconfiguredStorageResponse2(set, "File upload session storage");
2456
+ }
2372
2457
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2373
2458
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
2374
2459
  if (session.status !== "pending") {
@@ -2404,17 +2489,21 @@ function registerFileRoutes(app, host) {
2404
2489
  400: ErrorResponseSchema,
2405
2490
  404: ErrorResponseSchema,
2406
2491
  409: ErrorResponseSchema,
2407
- 410: ErrorResponseSchema
2492
+ 410: ErrorResponseSchema,
2493
+ 501: ErrorResponseSchema
2408
2494
  },
2409
2495
  detail: {
2410
2496
  summary: "Sign a staged multipart upload part",
2411
2497
  tags: [OPENAPI_TAGS.files.name],
2412
2498
  operationId: "signFileUploadPart",
2413
- security: SIXB_CSRF_SECURITY_REQUIREMENT
2499
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
2414
2500
  }
2415
2501
  }).post("/api/files/uploads/:uploadId/complete", async (context) => {
2416
2502
  const { body, params, set } = context;
2417
2503
  try {
2504
+ if (!uploadSessions) {
2505
+ return unconfiguredStorageResponse2(set, "File upload session storage");
2506
+ }
2418
2507
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2419
2508
  const parsed = CompleteFileUploadBodySchema.parse(body ?? {});
2420
2509
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
@@ -2456,17 +2545,21 @@ function registerFileRoutes(app, host) {
2456
2545
  400: ErrorResponseSchema,
2457
2546
  404: ErrorResponseSchema,
2458
2547
  409: ErrorResponseSchema,
2459
- 410: ErrorResponseSchema
2548
+ 410: ErrorResponseSchema,
2549
+ 501: ErrorResponseSchema
2460
2550
  },
2461
2551
  detail: {
2462
2552
  summary: "Complete a staged file upload",
2463
2553
  tags: [OPENAPI_TAGS.files.name],
2464
2554
  operationId: "completeFileUpload",
2465
- security: SIXB_CSRF_SECURITY_REQUIREMENT
2555
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
2466
2556
  }
2467
2557
  }).post("/api/files/uploads/:uploadId/abort", async (context) => {
2468
2558
  const { params, set } = context;
2469
2559
  try {
2560
+ if (!uploadSessions) {
2561
+ return unconfiguredStorageResponse2(set, "File upload session storage");
2562
+ }
2470
2563
  const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL;
2471
2564
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal);
2472
2565
  if (session.status === "completed") {
@@ -2497,13 +2590,14 @@ function registerFileRoutes(app, host) {
2497
2590
  400: ErrorResponseSchema,
2498
2591
  404: ErrorResponseSchema,
2499
2592
  409: ErrorResponseSchema,
2500
- 410: ErrorResponseSchema
2593
+ 410: ErrorResponseSchema,
2594
+ 501: ErrorResponseSchema
2501
2595
  },
2502
2596
  detail: {
2503
2597
  summary: "Abort a staged file upload",
2504
2598
  tags: [OPENAPI_TAGS.files.name],
2505
2599
  operationId: "abortFileUpload",
2506
- security: SIXB_CSRF_SECURITY_REQUIREMENT
2600
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
2507
2601
  }
2508
2602
  });
2509
2603
  }
@@ -3015,7 +3109,19 @@ var AiCostSummarySchema = z8.object({
3015
3109
  });
3016
3110
  var AiAccountingAggregateSchema = z8.object({
3017
3111
  modelCallCount: z8.number().int().nonnegative(),
3018
- usage: AiUsageSummarySchema,
3112
+ usage: AiUsageSummarySchema.describe("Sums of reported meters; unreported meters are absent. totalTokens sums available input and output counts and is a lower bound when coverage is incomplete."),
3113
+ usageCoverage: z8.object({
3114
+ completeCallCount: z8.number().int().nonnegative().describe("Calls reporting both inputTokens and outputTokens."),
3115
+ fieldCallCounts: z8.object({
3116
+ inputTokens: z8.number().int().nonnegative(),
3117
+ outputTokens: z8.number().int().nonnegative(),
3118
+ uncachedInputTokens: z8.number().int().nonnegative(),
3119
+ cacheReadInputTokens: z8.number().int().nonnegative(),
3120
+ cacheWriteInputTokens: z8.number().int().nonnegative(),
3121
+ textOutputTokens: z8.number().int().nonnegative(),
3122
+ reasoningOutputTokens: z8.number().int().nonnegative()
3123
+ })
3124
+ }),
3019
3125
  costs: AiCostSummarySchema
3020
3126
  });
3021
3127
  var AiAccountingOverviewResponseSchema = z8.object({
@@ -3257,13 +3363,20 @@ var AgentThreadListQuerySchema = z9.object({
3257
3363
  }).strict();
3258
3364
  var CreateAgentThreadBodySchema = z9.object({
3259
3365
  title: z9.string().trim().min(1).optional(),
3260
- threadId: z9.string().trim().min(1).optional()
3366
+ threadId: z9.string().trim().min(1).optional(),
3367
+ sandbox: z9.record(z9.string(), JsonValueSchema).optional()
3261
3368
  }).strict();
3262
3369
  var AgentThreadSchema = z9.object({
3370
+ sandboxState: z9.object({
3371
+ name: z9.string(),
3372
+ status: z9.enum(["new", "busy", "ready", "blocked", "unavailable"]),
3373
+ initialized: z9.boolean()
3374
+ }).optional(),
3263
3375
  id: z9.string(),
3264
3376
  projectId: z9.string(),
3265
3377
  ownerPrincipal: AgentPrincipalSchema,
3266
3378
  title: z9.string().optional(),
3379
+ sandboxParams: z9.record(z9.string(), JsonValueSchema).optional(),
3267
3380
  status: AgentThreadStatusSchema,
3268
3381
  activeRunId: z9.string().nullable(),
3269
3382
  lastMessageAt: z9.string().optional(),
@@ -3434,16 +3547,18 @@ var AgentRunListResponseSchema = z9.object({
3434
3547
  var AgentMessageFileContentQuerySchema = FileContentQuerySchema.extend({
3435
3548
  path: z10.string().min(1).regex(/^\/parts(?:\/|$)/, "Agent message file content paths must start with /parts/")
3436
3549
  });
3437
- var AiUsageLimitErrorResponseSchema = codedErrorResponseSchema([
3438
- "ai.usage_limit_exceeded",
3439
- "ai.usage_limit_unavailable"
3440
- ]).extend({ details: JsonValueSchema.optional() });
3441
3550
  function serializeThread(thread) {
3442
3551
  return AgentThreadSchema.parse({
3443
3552
  id: thread.id,
3444
3553
  projectId: thread.projectId,
3445
3554
  ownerPrincipal: thread.ownerPrincipal,
3446
3555
  title: thread.title,
3556
+ sandboxParams: thread.sandboxParams,
3557
+ sandboxState: thread.sandboxState && {
3558
+ name: thread.sandboxState.name,
3559
+ status: thread.sandboxState.status,
3560
+ initialized: thread.sandboxState.initialized
3561
+ },
3447
3562
  status: thread.status,
3448
3563
  activeRunId: thread.activeRunId,
3449
3564
  lastMessageAt: thread.lastMessageAt ? toIsoString(thread.lastMessageAt) : undefined,
@@ -3535,12 +3650,15 @@ function handleAgentRouteError(error, set) {
3535
3650
  break;
3536
3651
  case "active_run_exists":
3537
3652
  case "run_not_retryable":
3653
+ case "sandbox_execution_unavailable":
3538
3654
  set.status = 409;
3539
3655
  break;
3540
3656
  case "authority_not_inheritable":
3541
3657
  set.status = 403;
3542
3658
  break;
3543
3659
  case "storage_unavailable":
3660
+ case "sandbox_not_configured":
3661
+ case "invalid_sandbox_params":
3544
3662
  case "agent_selector_removed":
3545
3663
  case "invalid_context":
3546
3664
  case "invalid_model_selection":
@@ -3668,7 +3786,8 @@ function registerAgentRoutes(app, host) {
3668
3786
  }
3669
3787
  const thread = await sixb.agent.threads.create({
3670
3788
  ...parsed.threadId === undefined ? {} : { id: parsed.threadId },
3671
- ...parsed.title === undefined ? {} : { title: parsed.title }
3789
+ ...parsed.title === undefined ? {} : { title: parsed.title },
3790
+ ...parsed.sandbox === undefined ? {} : { sandbox: parsed.sandbox }
3672
3791
  });
3673
3792
  set.status = 201;
3674
3793
  return CreateAgentThreadResponseSchema.parse({ thread: serializeThread(thread) });
@@ -3688,7 +3807,7 @@ function registerAgentRoutes(app, host) {
3688
3807
  summary: "Create an agent thread",
3689
3808
  tags: [OPENAPI_TAGS.agentThreads.name],
3690
3809
  operationId: "createAgentThread",
3691
- security: SIXB_CSRF_SECURITY_REQUIREMENT
3810
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
3692
3811
  }
3693
3812
  }).get("/api/agent-threads/:threadId", async (context) => {
3694
3813
  const { params, set } = context;
@@ -3720,6 +3839,33 @@ function registerAgentRoutes(app, host) {
3720
3839
  tags: [OPENAPI_TAGS.agentThreads.name],
3721
3840
  operationId: "getAgentThread"
3722
3841
  }
3842
+ }).post("/api/agent-threads/:threadId/sandbox/recreate", async (context) => {
3843
+ try {
3844
+ const sixb = requireRequestSixb(context);
3845
+ const thread = await sixb.agent.threads.recreateSandbox(context.params.threadId, context.body);
3846
+ return serializeThread(thread);
3847
+ } catch (error) {
3848
+ if (error instanceof AgentStorageError && error.code === "invalid_state") {
3849
+ context.set.status = 409;
3850
+ return { error: "Sandbox state changed or a run is active. Reload and try again." };
3851
+ }
3852
+ return handleAgentRouteError(error, context.set);
3853
+ }
3854
+ }, {
3855
+ params: AgentThreadParamsSchema,
3856
+ body: z10.object({ expectedSandboxName: z10.string().min(1) }).strict(),
3857
+ response: {
3858
+ 200: AgentThreadSchema,
3859
+ 400: ErrorResponseSchema,
3860
+ 404: ErrorResponseSchema,
3861
+ 409: ErrorResponseSchema
3862
+ },
3863
+ detail: {
3864
+ summary: "Explicitly recreate an unavailable or uncertain workspace without deleting its previous state",
3865
+ operationId: "recreateAgentThreadSandbox",
3866
+ tags: [OPENAPI_TAGS.agentThreads.name],
3867
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
3868
+ }
3723
3869
  }).get("/api/agent-threads/:threadId/messages", async (context) => {
3724
3870
  const { params, query, set } = context;
3725
3871
  const sixb = requireRequestSixb(context);
@@ -3780,7 +3926,7 @@ function registerAgentRoutes(app, host) {
3780
3926
  summary: "Get agent message file content",
3781
3927
  tags: ["Agents"],
3782
3928
  operationId: "getAgentMessageFileContent",
3783
- security: bearerSecurityRequirement("getAgentMessageFileContent"),
3929
+ security: accessTokenSecurityRequirement("getAgentMessageFileContent"),
3784
3930
  responses: fileContentGetResponses({ optionalStorage: true })
3785
3931
  }
3786
3932
  }).head("/api/agent-threads/:threadId/messages/:messageId/files/content", async (context) => agentMessageFileContentResponse(host, context, { head: true }), {
@@ -3790,7 +3936,7 @@ function registerAgentRoutes(app, host) {
3790
3936
  summary: "Head agent message file content",
3791
3937
  tags: ["Agents"],
3792
3938
  operationId: "headAgentMessageFileContent",
3793
- security: bearerSecurityRequirement("headAgentMessageFileContent"),
3939
+ security: accessTokenSecurityRequirement("headAgentMessageFileContent"),
3794
3940
  responses: fileContentHeadResponses({ optionalStorage: true })
3795
3941
  }
3796
3942
  }).post("/api/agent-threads/:threadId/messages", async (context) => {
@@ -3840,7 +3986,7 @@ function registerAgentRoutes(app, host) {
3840
3986
  summary: "Post an agent thread message",
3841
3987
  tags: [OPENAPI_TAGS.agentThreads.name],
3842
3988
  operationId: "postAgentThreadMessage",
3843
- security: SIXB_CSRF_SECURITY_REQUIREMENT
3989
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
3844
3990
  }
3845
3991
  }).post("/api/agent-threads/:threadId/cancel", async (context) => {
3846
3992
  const { params, body, set } = context;
@@ -3921,7 +4067,7 @@ function registerAgentRoutes(app, host) {
3921
4067
  summary: "Cancel an agent thread's active run",
3922
4068
  tags: [OPENAPI_TAGS.agentRuns.name],
3923
4069
  operationId: "cancelAgentRun",
3924
- security: SIXB_CSRF_SECURITY_REQUIREMENT
4070
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
3925
4071
  }
3926
4072
  }).post("/api/agent-threads/:threadId/runs/:runId/retry", async (context) => {
3927
4073
  const { params, set } = context;
@@ -3967,7 +4113,7 @@ function registerAgentRoutes(app, host) {
3967
4113
  summary: "Retry a failed agent run",
3968
4114
  tags: [OPENAPI_TAGS.agentRuns.name],
3969
4115
  operationId: "retryAgentRun",
3970
- security: SIXB_CSRF_SECURITY_REQUIREMENT
4116
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
3971
4117
  }
3972
4118
  }).get("/api/agent-threads/:threadId/runs", async (context) => {
3973
4119
  const { params, query, set } = context;
@@ -4145,6 +4291,7 @@ function serializeAggregate(aggregate) {
4145
4291
  return {
4146
4292
  modelCallCount: aggregate.modelCallCount,
4147
4293
  usage: aggregate.usage,
4294
+ usageCoverage: aggregate.usageCoverage,
4148
4295
  costs: aggregate.costs
4149
4296
  };
4150
4297
  }
@@ -4305,7 +4452,7 @@ function registerAiAccountingRoutes(app, host) {
4305
4452
  summary: "Get project AI usage and cost analytics",
4306
4453
  tags: [OPENAPI_TAGS.aiAccounting.name],
4307
4454
  operationId: "getAiAccountingOverview",
4308
- security: bearerSecurityRequirement("getAiAccountingOverview")
4455
+ security: accessTokenSecurityRequirement("getAiAccountingOverview")
4309
4456
  }
4310
4457
  });
4311
4458
  app.get("/api/ai/model-calls", async (context) => {
@@ -4348,7 +4495,7 @@ function registerAiAccountingRoutes(app, host) {
4348
4495
  summary: "List project AI model-call accounting records",
4349
4496
  tags: [OPENAPI_TAGS.aiAccounting.name],
4350
4497
  operationId: "listAiModelCalls",
4351
- security: bearerSecurityRequirement("listAiModelCalls")
4498
+ security: accessTokenSecurityRequirement("listAiModelCalls")
4352
4499
  }
4353
4500
  });
4354
4501
  app.get("/api/ai/limits", async (context) => {
@@ -4381,7 +4528,7 @@ function registerAiAccountingRoutes(app, host) {
4381
4528
  summary: "List project AI usage-limit policies",
4382
4529
  tags: [OPENAPI_TAGS.aiAccounting.name],
4383
4530
  operationId: "listAiLimitPolicies",
4384
- security: bearerSecurityRequirement("listAiLimitPolicies")
4531
+ security: accessTokenSecurityRequirement("listAiLimitPolicies")
4385
4532
  }
4386
4533
  });
4387
4534
  app.get("/api/ai/limits/status", async (context) => {
@@ -4415,7 +4562,7 @@ function registerAiAccountingRoutes(app, host) {
4415
4562
  summary: "Get current project AI usage-limit status",
4416
4563
  tags: [OPENAPI_TAGS.aiAccounting.name],
4417
4564
  operationId: "getAiLimitStatus",
4418
- security: bearerSecurityRequirement("getAiLimitStatus")
4565
+ security: accessTokenSecurityRequirement("getAiLimitStatus")
4419
4566
  }
4420
4567
  });
4421
4568
  app.get("/api/ai/limits/subjects", async (context) => {
@@ -4437,7 +4584,7 @@ function registerAiAccountingRoutes(app, host) {
4437
4584
  description: "Lists registered groups and auth principals available for AI usage-limit policies.",
4438
4585
  tags: [OPENAPI_TAGS.aiAccounting.name],
4439
4586
  operationId: "getAiLimitSubjectOptions",
4440
- security: bearerSecurityRequirement("getAiLimitSubjectOptions")
4587
+ security: accessTokenSecurityRequirement("getAiLimitSubjectOptions")
4441
4588
  }
4442
4589
  });
4443
4590
  app.post("/api/ai/limits", async (context) => {
@@ -4466,7 +4613,7 @@ function registerAiAccountingRoutes(app, host) {
4466
4613
  summary: "Create an AI usage-limit policy",
4467
4614
  tags: [OPENAPI_TAGS.aiAccounting.name],
4468
4615
  operationId: "createAiLimitPolicy",
4469
- security: bearerSecurityRequirement("createAiLimitPolicy")
4616
+ security: accessTokenSecurityRequirement("createAiLimitPolicy")
4470
4617
  }
4471
4618
  });
4472
4619
  app.put("/api/ai/limits/:limitId", async (context) => {
@@ -4497,7 +4644,7 @@ function registerAiAccountingRoutes(app, host) {
4497
4644
  summary: "Update an AI usage-limit policy",
4498
4645
  tags: [OPENAPI_TAGS.aiAccounting.name],
4499
4646
  operationId: "updateAiLimitPolicy",
4500
- security: bearerSecurityRequirement("updateAiLimitPolicy")
4647
+ security: accessTokenSecurityRequirement("updateAiLimitPolicy")
4501
4648
  }
4502
4649
  });
4503
4650
  app.delete("/api/ai/limits/:limitId", async (context) => {
@@ -4530,7 +4677,7 @@ function registerAiAccountingRoutes(app, host) {
4530
4677
  summary: "Delete an AI usage-limit policy",
4531
4678
  tags: [OPENAPI_TAGS.aiAccounting.name],
4532
4679
  operationId: "deleteAiLimitPolicy",
4533
- security: bearerSecurityRequirement("deleteAiLimitPolicy")
4680
+ security: accessTokenSecurityRequirement("deleteAiLimitPolicy")
4534
4681
  }
4535
4682
  });
4536
4683
  app.get("/api/ai/model-call-groups", async (context) => {
@@ -4569,7 +4716,7 @@ function registerAiAccountingRoutes(app, host) {
4569
4716
  summary: "List AI model calls grouped by initiating execution",
4570
4717
  tags: [OPENAPI_TAGS.aiAccounting.name],
4571
4718
  operationId: "listAiModelCallGroups",
4572
- security: bearerSecurityRequirement("listAiModelCallGroups")
4719
+ security: accessTokenSecurityRequirement("listAiModelCallGroups")
4573
4720
  }
4574
4721
  });
4575
4722
  return app;
@@ -4949,7 +5096,7 @@ function registerConnectorConnectionRunRoutes(app, host, options) {
4949
5096
  summary: "Start a connector connection run",
4950
5097
  tags: [OPENAPI_TAGS.connectorConnectionRuns.name],
4951
5098
  operationId: "startConnectorConnectionRun",
4952
- security: SIXB_CSRF_SECURITY_REQUIREMENT
5099
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
4953
5100
  }
4954
5101
  }).get("/api/connectors/:connectorId/connection-runs/:runId", async (context) => {
4955
5102
  const { params, set } = context;
@@ -5008,7 +5155,7 @@ function registerConnectorConnectionRunRoutes(app, host, options) {
5008
5155
  summary: "Add a connector connection from an existing authorization",
5009
5156
  tags: [OPENAPI_TAGS.connectorConnectionRuns.name],
5010
5157
  operationId: "addConnectorConnection",
5011
- security: SIXB_CSRF_SECURITY_REQUIREMENT
5158
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5012
5159
  }
5013
5160
  }).post("/api/connectors/:connectorId/connection-runs/:runId/selection", async (context) => {
5014
5161
  const { params, body, set } = context;
@@ -5039,7 +5186,7 @@ function registerConnectorConnectionRunRoutes(app, host, options) {
5039
5186
  summary: "Select a connector account",
5040
5187
  tags: [OPENAPI_TAGS.connectorConnectionRuns.name],
5041
5188
  operationId: "selectConnectorConnectionRunAccount",
5042
- security: SIXB_CSRF_SECURITY_REQUIREMENT
5189
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5043
5190
  }
5044
5191
  }).post("/api/connectors/:connectorId/connections/:connectionId/reauthorize", async (context) => {
5045
5192
  const { params, body, request, set } = context;
@@ -5082,7 +5229,7 @@ function registerConnectorConnectionRunRoutes(app, host, options) {
5082
5229
  summary: "Reauthorize a connector connection",
5083
5230
  tags: [OPENAPI_TAGS.connectorConnectionRuns.name],
5084
5231
  operationId: "reauthorizeConnectorConnection",
5085
- security: SIXB_CSRF_SECURITY_REQUIREMENT
5232
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5086
5233
  }
5087
5234
  }).get("/auth/connectors/callback", async ({ request, set, server }) => {
5088
5235
  server?.timeout(request, 0);
@@ -5187,7 +5334,7 @@ function registerConnectorConnectionRoutes(app, host) {
5187
5334
  summary: "Disconnect a connector account",
5188
5335
  tags: [OPENAPI_TAGS.connectorConnections.name],
5189
5336
  operationId: "disconnectConnectorConnection",
5190
- security: SIXB_CSRF_SECURITY_REQUIREMENT
5337
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5191
5338
  }
5192
5339
  }).post("/api/connectors/:connectorId/connections/:connectionId/revoke", async (context) => {
5193
5340
  const { params, set } = context;
@@ -5216,7 +5363,7 @@ function registerConnectorConnectionRoutes(app, host) {
5216
5363
  summary: "Revoke a connector authorization",
5217
5364
  tags: [OPENAPI_TAGS.connectorConnections.name],
5218
5365
  operationId: "revokeConnectorConnection",
5219
- security: SIXB_CSRF_SECURITY_REQUIREMENT
5366
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
5220
5367
  }
5221
5368
  });
5222
5369
  }
@@ -5770,12 +5917,34 @@ var StoredEventBaseSchema = z15.object({
5770
5917
  schemaVersion: z15.literal(1),
5771
5918
  projectId: z15.string(),
5772
5919
  occurredAt: z15.string(),
5773
- actor: z15.object({
5774
- type: z15.enum(["user", "serviceAccount", "system"]),
5775
- id: z15.string()
5776
- }).optional(),
5777
5920
  partitionKey: z15.string()
5778
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
+ ]);
5779
5948
  var StoredAuthorableEventBaseSchema = StoredEventBaseSchema.extend({
5780
5949
  correlationId: z15.string().optional(),
5781
5950
  causationId: z15.string().optional(),
@@ -5785,6 +5954,8 @@ var StoredAuthorableEventBaseSchema = StoredEventBaseSchema.extend({
5785
5954
  });
5786
5955
  var StoredOntologyEventBaseSchema = StoredEventBaseSchema.extend({
5787
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,
5788
5959
  commitId: z15.string(),
5789
5960
  commitOrdinal: z15.number().int().nonnegative()
5790
5961
  });
@@ -5844,7 +6015,7 @@ function registerEventRoutes(app, _host) {
5844
6015
  summary: "Read domain events",
5845
6016
  tags: [OPENAPI_TAGS.events.name],
5846
6017
  operationId: "listEvents",
5847
- security: bearerSecurityRequirement("listEvents")
6018
+ security: accessTokenSecurityRequirement("listEvents")
5848
6019
  }
5849
6020
  });
5850
6021
  }
@@ -5896,7 +6067,7 @@ function registerLinkRoutes(app, _host) {
5896
6067
  summary: "Create or update object link",
5897
6068
  tags: [OPENAPI_TAGS.links.name],
5898
6069
  operationId: "upsertObjectLink",
5899
- security: bearerSecurityRequirement("upsertObjectLink")
6070
+ security: accessTokenSecurityRequirement("upsertObjectLink")
5900
6071
  }
5901
6072
  }).delete("/api/objects/:objectTypeId/:objectId/links/:linkId", async (context) => {
5902
6073
  const { params, query, set } = context;
@@ -5923,7 +6094,7 @@ function registerLinkRoutes(app, _host) {
5923
6094
  summary: "Remove object link",
5924
6095
  tags: [OPENAPI_TAGS.links.name],
5925
6096
  operationId: "removeObjectLink",
5926
- security: bearerSecurityRequirement("removeObjectLink")
6097
+ security: accessTokenSecurityRequirement("removeObjectLink")
5927
6098
  }
5928
6099
  });
5929
6100
  }
@@ -6036,7 +6207,7 @@ function registerLogRoutes(app, _host) {
6036
6207
  summary: "Read run logs",
6037
6208
  tags: [OPENAPI_TAGS.logs.name],
6038
6209
  operationId: "listLogs",
6039
- security: bearerSecurityRequirement("listLogs")
6210
+ security: accessTokenSecurityRequirement("listLogs")
6040
6211
  }
6041
6212
  });
6042
6213
  }
@@ -6159,6 +6330,7 @@ import { ZodError as ZodError3, z as z19 } from "zod";
6159
6330
 
6160
6331
  // src/schemas/objects.ts
6161
6332
  import { z as z18 } from "zod";
6333
+ import { zodToJsonSchema } from "zod-to-json-schema";
6162
6334
  var ObjectParamsSchema = z18.object({
6163
6335
  objectTypeId: z18.string().min(1),
6164
6336
  objectId: z18.string().min(1)
@@ -6309,8 +6481,8 @@ var ObjectQuerySchema = z18.lazy(() => z18.discriminatedUnion("kind", [
6309
6481
  z18.object({
6310
6482
  kind: z18.literal("vector"),
6311
6483
  input: ObjectQuerySchema,
6312
- vector: z18.array(z18.number().finite()),
6313
- propertyId: z18.string().min(1),
6484
+ vector: z18.string().min(1).max(8000),
6485
+ profile: z18.string().min(1),
6314
6486
  k: z18.number().int().positive()
6315
6487
  }).strict(),
6316
6488
  z18.object({
@@ -6379,6 +6551,7 @@ var ObjectQueryLinksRequestSchema = z18.object({
6379
6551
  pageToken: z18.string().min(1).optional()
6380
6552
  }).strict();
6381
6553
  var TwinObjectSchema = z18.object({
6554
+ score: z18.number().finite().optional(),
6382
6555
  primaryId: z18.string(),
6383
6556
  objectTypeId: z18.string(),
6384
6557
  properties: z18.record(z18.unknown()),
@@ -6414,6 +6587,7 @@ var ObjectQueryOpenApiSchemas = {
6414
6587
  required: ["primaryId", "objectTypeId", "properties", "createdAt", "updatedAt"],
6415
6588
  additionalProperties: false,
6416
6589
  properties: {
6590
+ score: { type: "number" },
6417
6591
  primaryId: { type: "string" },
6418
6592
  objectTypeId: { type: "string" },
6419
6593
  properties: { type: "object", additionalProperties: true },
@@ -6570,6 +6744,11 @@ var ObjectQueryOpenApiSchemas = {
6570
6744
  nextPageToken: { type: "string" }
6571
6745
  }
6572
6746
  },
6747
+ AiUsageLimitErrorResponse: zodToJsonSchema(AiUsageLimitErrorResponseSchema, {
6748
+ target: "openApi3",
6749
+ $refStrategy: "none",
6750
+ override: jsonValueOpenApiOverride
6751
+ }),
6573
6752
  ObjectQueryErrorResponse: {
6574
6753
  type: "object",
6575
6754
  required: ["error"],
@@ -6708,13 +6887,13 @@ var ObjectQueryOpenApiSchemas = {
6708
6887
  },
6709
6888
  {
6710
6889
  type: "object",
6711
- required: ["kind", "input", "vector", "propertyId", "k"],
6890
+ required: ["kind", "input", "vector", "profile", "k"],
6712
6891
  additionalProperties: false,
6713
6892
  properties: {
6714
6893
  kind: { type: "string", enum: ["vector"] },
6715
6894
  input: objectQueryRef,
6716
- vector: { type: "array", items: { type: "number" } },
6717
- propertyId: { type: "string", minLength: 1 },
6895
+ vector: { type: "string", minLength: 1, maxLength: 8000 },
6896
+ profile: { type: "string", minLength: 1 },
6718
6897
  k: { type: "integer", minimum: 1 }
6719
6898
  }
6720
6899
  },
@@ -6902,6 +7081,7 @@ var ObjectFileContentQuerySchema = FileContentQuerySchema.extend({
6902
7081
  });
6903
7082
  function serializeObject(row) {
6904
7083
  return {
7084
+ ...row.score === undefined ? {} : { score: row.score },
6905
7085
  primaryId: row.primaryId,
6906
7086
  objectTypeId: row.objectTypeId,
6907
7087
  properties: row.properties,
@@ -6992,8 +7172,7 @@ function handleObjectQueryError(error, set) {
6992
7172
  ]
6993
7173
  };
6994
7174
  }
6995
- set.status = 500;
6996
- return { error: error instanceof Error ? error.message : String(error) };
7175
+ return handleRouteError(error, set);
6997
7176
  }
6998
7177
  function formatZodIssuePath(path) {
6999
7178
  if (path.length === 0)
@@ -7092,7 +7271,7 @@ function registerObjectRoutes(app, host) {
7092
7271
  summary: "Search objects",
7093
7272
  tags: [OPENAPI_TAGS.objects.name],
7094
7273
  operationId: "searchObjects",
7095
- security: bearerSecurityRequirement("searchObjects")
7274
+ security: accessTokenSecurityRequirement("searchObjects")
7096
7275
  }
7097
7276
  }).get("/api/objects", async (context) => {
7098
7277
  const { query, set } = context;
@@ -7142,7 +7321,7 @@ function registerObjectRoutes(app, host) {
7142
7321
  summary: "List objects",
7143
7322
  tags: [OPENAPI_TAGS.objects.name],
7144
7323
  operationId: "listObjects",
7145
- security: bearerSecurityRequirement("listObjects")
7324
+ security: accessTokenSecurityRequirement("listObjects")
7146
7325
  }
7147
7326
  }).post("/api/objects/query", async (context) => {
7148
7327
  const { body, set } = context;
@@ -7150,7 +7329,8 @@ function registerObjectRoutes(app, host) {
7150
7329
  const parsed = ObjectQueryRequestSchema.parse(body);
7151
7330
  const result = await requireRequestSixb(context).objects.executeQuery({
7152
7331
  query: parsed.query,
7153
- includeTotal: parsed.includeTotal
7332
+ includeTotal: parsed.includeTotal,
7333
+ signal: context.request.signal
7154
7334
  });
7155
7335
  return {
7156
7336
  objects: result.objects.map(serializeExpandedObject),
@@ -7167,7 +7347,7 @@ function registerObjectRoutes(app, host) {
7167
7347
  summary: "Query objects",
7168
7348
  tags: [OPENAPI_TAGS.objects.name],
7169
7349
  operationId: "queryObjects",
7170
- security: bearerSecurityRequirement("queryObjects"),
7350
+ security: accessTokenSecurityRequirement("queryObjects"),
7171
7351
  requestBody: {
7172
7352
  required: true,
7173
7353
  content: {
@@ -7201,6 +7381,20 @@ function registerObjectRoutes(app, host) {
7201
7381
  }
7202
7382
  }
7203
7383
  },
7384
+ 429: {
7385
+ description: "AI usage limit exceeded or unavailable",
7386
+ headers: {
7387
+ "Retry-After": {
7388
+ description: "Seconds until the budget period resets, when known",
7389
+ schema: { type: "integer" }
7390
+ }
7391
+ },
7392
+ content: {
7393
+ "application/json": {
7394
+ schema: { $ref: "#/components/schemas/AiUsageLimitErrorResponse" }
7395
+ }
7396
+ }
7397
+ },
7204
7398
  500: {
7205
7399
  description: "Response for status 500",
7206
7400
  content: {
@@ -7230,7 +7424,7 @@ function registerObjectRoutes(app, host) {
7230
7424
  summary: "Query object links",
7231
7425
  tags: [OPENAPI_TAGS.links.name],
7232
7426
  operationId: "queryObjectLinks",
7233
- security: bearerSecurityRequirement("queryObjectLinks"),
7427
+ security: accessTokenSecurityRequirement("queryObjectLinks"),
7234
7428
  requestBody: {
7235
7429
  required: true,
7236
7430
  content: {
@@ -7291,7 +7485,7 @@ function registerObjectRoutes(app, host) {
7291
7485
  summary: "Count objects",
7292
7486
  tags: [OPENAPI_TAGS.objects.name],
7293
7487
  operationId: "countObjects",
7294
- security: bearerSecurityRequirement("countObjects"),
7488
+ security: accessTokenSecurityRequirement("countObjects"),
7295
7489
  requestBody: {
7296
7490
  required: true,
7297
7491
  content: {
@@ -7325,6 +7519,20 @@ function registerObjectRoutes(app, host) {
7325
7519
  }
7326
7520
  }
7327
7521
  },
7522
+ 429: {
7523
+ description: "AI usage limit exceeded or unavailable",
7524
+ headers: {
7525
+ "Retry-After": {
7526
+ description: "Seconds until the budget period resets, when known",
7527
+ schema: { type: "integer" }
7528
+ }
7529
+ },
7530
+ content: {
7531
+ "application/json": {
7532
+ schema: { $ref: "#/components/schemas/AiUsageLimitErrorResponse" }
7533
+ }
7534
+ }
7535
+ },
7328
7536
  500: {
7329
7537
  description: "Response for status 500",
7330
7538
  content: {
@@ -7352,7 +7560,7 @@ function registerObjectRoutes(app, host) {
7352
7560
  summary: "Check object existence",
7353
7561
  tags: [OPENAPI_TAGS.objects.name],
7354
7562
  operationId: "existsObjects",
7355
- security: bearerSecurityRequirement("existsObjects"),
7563
+ security: accessTokenSecurityRequirement("existsObjects"),
7356
7564
  requestBody: {
7357
7565
  required: true,
7358
7566
  content: {
@@ -7386,6 +7594,20 @@ function registerObjectRoutes(app, host) {
7386
7594
  }
7387
7595
  }
7388
7596
  },
7597
+ 429: {
7598
+ description: "AI usage limit exceeded or unavailable",
7599
+ headers: {
7600
+ "Retry-After": {
7601
+ description: "Seconds until the budget period resets, when known",
7602
+ schema: { type: "integer" }
7603
+ }
7604
+ },
7605
+ content: {
7606
+ "application/json": {
7607
+ schema: { $ref: "#/components/schemas/AiUsageLimitErrorResponse" }
7608
+ }
7609
+ }
7610
+ },
7389
7611
  500: {
7390
7612
  description: "Response for status 500",
7391
7613
  content: {
@@ -7416,7 +7638,7 @@ function registerObjectRoutes(app, host) {
7416
7638
  summary: "Facet objects",
7417
7639
  tags: [OPENAPI_TAGS.objects.name],
7418
7640
  operationId: "facetObjects",
7419
- security: bearerSecurityRequirement("facetObjects"),
7641
+ security: accessTokenSecurityRequirement("facetObjects"),
7420
7642
  requestBody: {
7421
7643
  required: true,
7422
7644
  content: {
@@ -7467,7 +7689,7 @@ function registerObjectRoutes(app, host) {
7467
7689
  summary: "Get object file content",
7468
7690
  tags: [OPENAPI_TAGS.objectFiles.name],
7469
7691
  operationId: "getObjectFileContent",
7470
- security: bearerSecurityRequirement("getObjectFileContent"),
7692
+ security: accessTokenSecurityRequirement("getObjectFileContent"),
7471
7693
  responses: fileContentGetResponses()
7472
7694
  }
7473
7695
  }).head("/api/objects/:objectTypeId/:objectId/files/content", (context) => objectFileContentResponse(host, context, { head: true }), {
@@ -7477,7 +7699,7 @@ function registerObjectRoutes(app, host) {
7477
7699
  summary: "Head object file content",
7478
7700
  tags: [OPENAPI_TAGS.objectFiles.name],
7479
7701
  operationId: "headObjectFileContent",
7480
- security: bearerSecurityRequirement("headObjectFileContent"),
7702
+ security: accessTokenSecurityRequirement("headObjectFileContent"),
7481
7703
  responses: fileContentHeadResponses()
7482
7704
  }
7483
7705
  }).get("/api/objects/:objectTypeId/:objectId", async (context) => {
@@ -7504,7 +7726,7 @@ function registerObjectRoutes(app, host) {
7504
7726
  summary: "Get object by id",
7505
7727
  tags: [OPENAPI_TAGS.objects.name],
7506
7728
  operationId: "getObject",
7507
- security: bearerSecurityRequirement("getObject")
7729
+ security: accessTokenSecurityRequirement("getObject")
7508
7730
  }
7509
7731
  }).put("/api/objects/:objectTypeId/:objectId", async (context) => {
7510
7732
  const { params, body, set } = context;
@@ -7531,12 +7753,13 @@ function registerObjectRoutes(app, host) {
7531
7753
  summary: "Create or update object",
7532
7754
  tags: [OPENAPI_TAGS.objects.name],
7533
7755
  operationId: "upsertObject",
7534
- security: bearerSecurityRequirement("upsertObject")
7756
+ security: accessTokenSecurityRequirement("upsertObject")
7535
7757
  }
7536
7758
  });
7537
7759
  }
7538
7760
 
7539
7761
  // src/routes/ontology.ts
7762
+ import { resolvePropertyQueryCapabilities } from "@sixb/core/internal/ontology";
7540
7763
  function serializeProperty(property) {
7541
7764
  return {
7542
7765
  id: property.id,
@@ -7551,6 +7774,13 @@ function serializeProperty(property) {
7551
7774
  query: property.query ? { ...property.query } : undefined
7552
7775
  };
7553
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
+ }
7554
7784
  function serializeSearch(search) {
7555
7785
  if (!search)
7556
7786
  return;
@@ -7558,20 +7788,28 @@ function serializeSearch(search) {
7558
7788
  title: search.title,
7559
7789
  defaultText: search.defaultText ? [...search.defaultText] : undefined,
7560
7790
  exact: search.exact ? [...search.exact] : undefined,
7561
- vector: search.vector ? {
7562
- property: search.vector.property,
7563
- source: [...search.vector.source]
7564
- } : undefined
7791
+ vectors: search.vectors ? Object.fromEntries(Object.entries(search.vectors).map(([name, profile]) => [
7792
+ name,
7793
+ {
7794
+ source: [...profile.source],
7795
+ model: {
7796
+ providerId: profile.model.providerId,
7797
+ modelId: profile.model.modelId,
7798
+ dimensions: profile.model.definition.dimensions,
7799
+ representation: profile.model.definition.representation
7800
+ }
7801
+ }
7802
+ ])) : undefined
7565
7803
  };
7566
7804
  }
7567
- function serializeObjectType(execution, objectType) {
7805
+ function serializeObjectType(execution, valueTypesById, objectType) {
7568
7806
  return {
7569
7807
  id: objectType.id,
7570
7808
  name: objectType.name,
7571
7809
  description: objectType.description,
7572
7810
  extends: objectType.extends,
7573
7811
  implements: objectType.implements ? [...objectType.implements] : undefined,
7574
- properties: objectType.properties.map(serializeProperty),
7812
+ properties: objectType.properties.map((property) => serializeObjectProperty(property, valueTypesById)),
7575
7813
  search: serializeSearch(objectType.search),
7576
7814
  links: objectType.links.map((link) => ({
7577
7815
  id: link.id,
@@ -7597,17 +7835,18 @@ function serializeObjectType(execution, objectType) {
7597
7835
  }))
7598
7836
  };
7599
7837
  }
7600
- function registerOntologyRoutes(app, _host) {
7838
+ function registerOntologyRoutes(app, host) {
7601
7839
  return app.get("/api/object-types", async (context) => {
7602
7840
  const sixb = requireRequestSixb(context);
7603
- 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));
7604
7843
  }, {
7605
7844
  response: { 200: ObjectTypeSchema.array() },
7606
7845
  detail: {
7607
7846
  summary: "List registered object types",
7608
7847
  tags: [OPENAPI_TAGS.ontology.name],
7609
7848
  operationId: "listObjectTypes",
7610
- security: bearerSecurityRequirement("listObjectTypes")
7849
+ security: accessTokenSecurityRequirement("listObjectTypes")
7611
7850
  }
7612
7851
  }).get("/api/object-types/:objectTypeId", async (context) => {
7613
7852
  const { params, set } = context;
@@ -7617,7 +7856,7 @@ function registerOntologyRoutes(app, _host) {
7617
7856
  set.status = 404;
7618
7857
  return { error: "Object type not found" };
7619
7858
  }
7620
- return serializeObjectType(sixb, objectType);
7859
+ return serializeObjectType(sixb, host.definitions.ontology.getValueTypesById(), objectType);
7621
7860
  }, {
7622
7861
  params: ObjectTypeParamsSchema,
7623
7862
  response: { 200: ObjectTypeSchema, 404: ErrorResponseSchema },
@@ -7625,7 +7864,7 @@ function registerOntologyRoutes(app, _host) {
7625
7864
  summary: "Get object type definition",
7626
7865
  tags: [OPENAPI_TAGS.ontology.name],
7627
7866
  operationId: "getObjectType",
7628
- security: bearerSecurityRequirement("getObjectType")
7867
+ security: accessTokenSecurityRequirement("getObjectType")
7629
7868
  }
7630
7869
  });
7631
7870
  }
@@ -7954,7 +8193,7 @@ function registerPipelineRoutes(app, host) {
7954
8193
  summary: "Request a pipeline run",
7955
8194
  tags: [OPENAPI_TAGS.pipelineRuns.name],
7956
8195
  operationId: "requestPipelineRun",
7957
- security: SIXB_CSRF_SECURITY_REQUIREMENT
8196
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
7958
8197
  }
7959
8198
  });
7960
8199
  }
@@ -7973,7 +8212,7 @@ function registerProjectRoutes(app, host) {
7973
8212
  summary: "Get current project metadata",
7974
8213
  tags: [OPENAPI_TAGS.project.name],
7975
8214
  operationId: "getProjectInfo",
7976
- security: bearerSecurityRequirement("getProjectInfo")
8215
+ security: accessTokenSecurityRequirement("getProjectInfo")
7977
8216
  }
7978
8217
  });
7979
8218
  }
@@ -8492,7 +8731,7 @@ var AuthorizablePrincipalSchema = z24.object({
8492
8731
  type: z24.enum(["user", "serviceAccount"]),
8493
8732
  id: StoredIdentifierSchema
8494
8733
  });
8495
- var PrincipalSchema = z24.object({
8734
+ var PrincipalSchema2 = z24.object({
8496
8735
  type: z24.enum(["user", "serviceAccount", "system"]),
8497
8736
  id: StoredIdentifierSchema
8498
8737
  });
@@ -8505,7 +8744,7 @@ var SharedAccessGrantSchema = z24.object({
8505
8744
  createdAt: Rfc3339DateSchema2,
8506
8745
  expiresAt: Rfc3339DateSchema2,
8507
8746
  revokedAt: Rfc3339DateSchema2.optional(),
8508
- revokedBy: PrincipalSchema.optional()
8747
+ revokedBy: PrincipalSchema2.optional()
8509
8748
  });
8510
8749
  var IssueSharedAccessGrantBodySchema = z24.object({
8511
8750
  definitionId: StoredIdentifierSchema,
@@ -8581,7 +8820,7 @@ function registerShareGrantRoutes(app, _host) {
8581
8820
  summary: "Issue a shared-access grant",
8582
8821
  tags: [OPENAPI_TAGS.sharedAccess.name],
8583
8822
  operationId: "issueSharedAccessGrant",
8584
- security: bearerSecurityRequirement("issueSharedAccessGrant")
8823
+ security: accessTokenSecurityRequirement("issueSharedAccessGrant")
8585
8824
  }
8586
8825
  }).get("/api/share-grants", async (context) => {
8587
8826
  const { query, set } = context;
@@ -8619,7 +8858,7 @@ function registerShareGrantRoutes(app, _host) {
8619
8858
  summary: "List shared-access grants",
8620
8859
  tags: [OPENAPI_TAGS.sharedAccess.name],
8621
8860
  operationId: "listSharedAccessGrants",
8622
- security: bearerSecurityRequirement("listSharedAccessGrants")
8861
+ security: accessTokenSecurityRequirement("listSharedAccessGrants")
8623
8862
  }
8624
8863
  }).delete("/api/share-grants/:grantId", async (context) => {
8625
8864
  const { params, set } = context;
@@ -8652,7 +8891,7 @@ function registerShareGrantRoutes(app, _host) {
8652
8891
  summary: "Revoke a shared-access grant",
8653
8892
  tags: [OPENAPI_TAGS.sharedAccess.name],
8654
8893
  operationId: "revokeSharedAccessGrant",
8655
- security: bearerSecurityRequirement("revokeSharedAccessGrant")
8894
+ security: accessTokenSecurityRequirement("revokeSharedAccessGrant")
8656
8895
  }
8657
8896
  });
8658
8897
  }
@@ -8833,7 +9072,7 @@ function registerSharedAccessRoutes(app, boundary) {
8833
9072
  summary: "Sign out a shared-access session",
8834
9073
  tags: [OPENAPI_TAGS.sharedAccess.name],
8835
9074
  operationId: "signOutSharedAccess",
8836
- security: SIXB_CSRF_SECURITY_REQUIREMENT
9075
+ security: [{ [SIXB_CSRF_SECURITY_SCHEME_ID]: [] }, {}]
8837
9076
  }
8838
9077
  });
8839
9078
  }
@@ -9169,7 +9408,7 @@ function registerSyncRoutes(app, host) {
9169
9408
  summary: "Request a sync run",
9170
9409
  tags: [OPENAPI_TAGS.syncRuns.name],
9171
9410
  operationId: "requestSyncRun",
9172
- security: SIXB_CSRF_SECURITY_REQUIREMENT
9411
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
9173
9412
  }
9174
9413
  });
9175
9414
  }
@@ -9266,7 +9505,7 @@ function registerTelemetryRoutes(app, _host) {
9266
9505
  summary: "Append telemetry point",
9267
9506
  tags: [OPENAPI_TAGS.telemetry.name],
9268
9507
  operationId: "appendTelemetry",
9269
- security: bearerSecurityRequirement("appendTelemetry")
9508
+ security: accessTokenSecurityRequirement("appendTelemetry")
9270
9509
  }
9271
9510
  }).post("/api/telemetry/history", async (context) => {
9272
9511
  const { body, set } = context;
@@ -9301,7 +9540,7 @@ function registerTelemetryRoutes(app, _host) {
9301
9540
  summary: "Get bulk telemetry history",
9302
9541
  tags: [OPENAPI_TAGS.telemetry.name],
9303
9542
  operationId: "getBulkTelemetryHistory",
9304
- security: bearerSecurityRequirement("getBulkTelemetryHistory")
9543
+ security: accessTokenSecurityRequirement("getBulkTelemetryHistory")
9305
9544
  }
9306
9545
  }).get("/api/objects/:objectTypeId/:objectId/telemetry/:propertyId/history", async (context) => {
9307
9546
  const { params, query, set } = context;
@@ -9337,7 +9576,7 @@ function registerTelemetryRoutes(app, _host) {
9337
9576
  summary: "Get telemetry history",
9338
9577
  tags: [OPENAPI_TAGS.telemetry.name],
9339
9578
  operationId: "getTelemetryHistory",
9340
- security: bearerSecurityRequirement("getTelemetryHistory")
9579
+ security: accessTokenSecurityRequirement("getTelemetryHistory")
9341
9580
  }
9342
9581
  }).get("/api/objects/:objectTypeId/:objectId/telemetry/:propertyId/latest", async (context) => {
9343
9582
  const { params, set } = context;
@@ -9371,7 +9610,7 @@ function registerTelemetryRoutes(app, _host) {
9371
9610
  summary: "Get latest telemetry point",
9372
9611
  tags: [OPENAPI_TAGS.telemetry.name],
9373
9612
  operationId: "getLatestTelemetry",
9374
- security: bearerSecurityRequirement("getLatestTelemetry")
9613
+ security: accessTokenSecurityRequirement("getLatestTelemetry")
9375
9614
  }
9376
9615
  });
9377
9616
  }
@@ -9544,10 +9783,6 @@ var WorkflowInterventionsQuerySchema = z30.object({
9544
9783
  var RequestWorkflowRunBodySchema = z30.object({
9545
9784
  input: WorkflowIOSnapshotSchema.optional()
9546
9785
  }).default({});
9547
- var WorkflowInterventionActorSchema = z30.object({
9548
- principalType: z30.enum(["user", "serviceAccount", "system"]),
9549
- principalId: z30.string().min(1)
9550
- });
9551
9786
  var CancelWorkflowRunBodySchema = z30.object({}).default({});
9552
9787
  var SubmitWorkflowInterventionBodySchema = z30.object({
9553
9788
  response: WorkflowIOSnapshotSchema
@@ -9597,7 +9832,7 @@ var WorkflowRunSummarySchema = z30.object({
9597
9832
  startedAt: z30.string(),
9598
9833
  finishedAt: z30.string().optional(),
9599
9834
  error: WorkflowRunFailureSchema.optional(),
9600
- requestedBy: WorkflowInterventionActorSchema
9835
+ requestedBy: PrincipalSchema
9601
9836
  });
9602
9837
  var WorkflowRunDetailSchema = WorkflowRunSummarySchema.extend({
9603
9838
  input: WorkflowIOSnapshotSchema,
@@ -9656,10 +9891,10 @@ var WorkflowInterventionSchema = z30.object({
9656
9891
  requestedAt: z30.string(),
9657
9892
  expiresAt: z30.string().optional(),
9658
9893
  submittedAt: z30.string().optional(),
9659
- submittedBy: WorkflowInterventionActorSchema.optional(),
9894
+ submittedBy: PrincipalSchema.optional(),
9660
9895
  response: WorkflowIOSnapshotSchema.optional(),
9661
9896
  cancelledAt: z30.string().optional(),
9662
- cancelledBy: WorkflowInterventionActorSchema.optional(),
9897
+ cancelledBy: PrincipalSchema.optional(),
9663
9898
  expiredAt: z30.string().optional()
9664
9899
  });
9665
9900
  var WorkflowSchema = z30.object({
@@ -9748,7 +9983,7 @@ function serializeWorkflowNodeRun(node) {
9748
9983
  };
9749
9984
  }
9750
9985
  function serializePrincipal(principal) {
9751
- return { principalType: principal.type, principalId: principal.id };
9986
+ return { type: principal.type, id: principal.id };
9752
9987
  }
9753
9988
  function serializeWorkflowAgentExecutionSummary(execution) {
9754
9989
  return {
@@ -10077,7 +10312,7 @@ function registerWorkflowRoutes(app, host) {
10077
10312
  summary: "List registered workflows",
10078
10313
  tags: [OPENAPI_TAGS.workflows.name],
10079
10314
  operationId: "listWorkflows",
10080
- security: bearerSecurityRequirement("listWorkflows")
10315
+ security: accessTokenSecurityRequirement("listWorkflows")
10081
10316
  }
10082
10317
  }).get("/api/workflows/:workflowId", async (context) => {
10083
10318
  const { params, set } = context;
@@ -10095,7 +10330,7 @@ function registerWorkflowRoutes(app, host) {
10095
10330
  summary: "Get workflow metadata",
10096
10331
  tags: [OPENAPI_TAGS.workflows.name],
10097
10332
  operationId: "getWorkflow",
10098
- security: bearerSecurityRequirement("getWorkflow")
10333
+ security: accessTokenSecurityRequirement("getWorkflow")
10099
10334
  }
10100
10335
  }).get("/api/workflow-interventions", async (context) => {
10101
10336
  const { query, set } = context;
@@ -10239,7 +10474,7 @@ function registerWorkflowRoutes(app, host) {
10239
10474
  summary: "Submit a workflow intervention response",
10240
10475
  tags: [OPENAPI_TAGS.workflowInterventions.name],
10241
10476
  operationId: "submitWorkflowIntervention",
10242
- security: SIXB_CSRF_SECURITY_REQUIREMENT
10477
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
10243
10478
  }
10244
10479
  }).post("/api/workflow-interventions/:interventionId/cancel", async (context) => {
10245
10480
  const { params, body, set } = context;
@@ -10352,7 +10587,7 @@ function registerWorkflowRoutes(app, host) {
10352
10587
  summary: "Cancel a workflow intervention",
10353
10588
  tags: [OPENAPI_TAGS.workflowInterventions.name],
10354
10589
  operationId: "cancelWorkflowIntervention",
10355
- security: SIXB_CSRF_SECURITY_REQUIREMENT
10590
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
10356
10591
  }
10357
10592
  }).get("/api/workflow-runs", async (context) => {
10358
10593
  const { query, set } = context;
@@ -10393,7 +10628,7 @@ function registerWorkflowRoutes(app, host) {
10393
10628
  summary: "List workflow run history",
10394
10629
  tags: [OPENAPI_TAGS.workflowRuns.name],
10395
10630
  operationId: "listWorkflowRuns",
10396
- security: bearerSecurityRequirement("listWorkflowRuns")
10631
+ security: accessTokenSecurityRequirement("listWorkflowRuns")
10397
10632
  }
10398
10633
  }).get("/api/workflow-runs/:runId", async (context) => {
10399
10634
  const { params, set } = context;
@@ -10436,7 +10671,7 @@ function registerWorkflowRoutes(app, host) {
10436
10671
  summary: "Get workflow run detail",
10437
10672
  tags: [OPENAPI_TAGS.workflowRuns.name],
10438
10673
  operationId: "getWorkflowRun",
10439
- security: bearerSecurityRequirement("getWorkflowRun")
10674
+ security: accessTokenSecurityRequirement("getWorkflowRun")
10440
10675
  }
10441
10676
  }).get("/api/workflow-runs/:runId/nodes/:nodeKey/agent-execution", async (context) => {
10442
10677
  const { params, set } = context;
@@ -10478,7 +10713,7 @@ function registerWorkflowRoutes(app, host) {
10478
10713
  summary: "Get workflow agent node execution detail",
10479
10714
  tags: [OPENAPI_TAGS.workflowRuns.name],
10480
10715
  operationId: "getWorkflowAgentNodeExecution",
10481
- security: bearerSecurityRequirement("getWorkflowAgentNodeExecution")
10716
+ security: accessTokenSecurityRequirement("getWorkflowAgentNodeExecution")
10482
10717
  }
10483
10718
  }).post("/api/workflow-runs/:runId/cancel", async (context) => {
10484
10719
  const { params, body, set } = context;
@@ -10637,7 +10872,7 @@ function registerWorkflowRoutes(app, host) {
10637
10872
  summary: "Cancel a workflow run",
10638
10873
  tags: [OPENAPI_TAGS.workflowRuns.name],
10639
10874
  operationId: "cancelWorkflowRun",
10640
- security: bearerSecurityRequirement("cancelWorkflowRun")
10875
+ security: accessTokenSecurityRequirement("cancelWorkflowRun")
10641
10876
  }
10642
10877
  }).get("/api/workflow-runs/:runId/files/content", (context) => workflowRunFileContentResponse(host, context), {
10643
10878
  params: WorkflowRunParamsSchema,
@@ -10647,7 +10882,7 @@ function registerWorkflowRoutes(app, host) {
10647
10882
  summary: "Get workflow run file content",
10648
10883
  tags: ["Workflows"],
10649
10884
  operationId: "getWorkflowRunFileContent",
10650
- security: bearerSecurityRequirement("getWorkflowRunFileContent"),
10885
+ security: accessTokenSecurityRequirement("getWorkflowRunFileContent"),
10651
10886
  responses: fileContentGetResponses({ optionalStorage: true })
10652
10887
  }
10653
10888
  }).head("/api/workflow-runs/:runId/files/content", (context) => workflowRunFileContentResponse(host, context, { head: true }), {
@@ -10658,7 +10893,7 @@ function registerWorkflowRoutes(app, host) {
10658
10893
  summary: "Head workflow run file content",
10659
10894
  tags: ["Workflows"],
10660
10895
  operationId: "headWorkflowRunFileContent",
10661
- security: bearerSecurityRequirement("headWorkflowRunFileContent"),
10896
+ security: accessTokenSecurityRequirement("headWorkflowRunFileContent"),
10662
10897
  responses: fileContentHeadResponses({ optionalStorage: true })
10663
10898
  }
10664
10899
  }).get("/api/workflow-runs/:runId/nodes/:nodeKey/files/content", (context) => workflowNodeFileContentResponse(host, context), {
@@ -10669,7 +10904,7 @@ function registerWorkflowRoutes(app, host) {
10669
10904
  summary: "Get workflow node run file content",
10670
10905
  tags: ["Workflows"],
10671
10906
  operationId: "getWorkflowNodeRunFileContent",
10672
- security: bearerSecurityRequirement("getWorkflowNodeRunFileContent"),
10907
+ security: accessTokenSecurityRequirement("getWorkflowNodeRunFileContent"),
10673
10908
  responses: fileContentGetResponses({ optionalStorage: true })
10674
10909
  }
10675
10910
  }).head("/api/workflow-runs/:runId/nodes/:nodeKey/files/content", (context) => workflowNodeFileContentResponse(host, context, { head: true }), {
@@ -10680,7 +10915,7 @@ function registerWorkflowRoutes(app, host) {
10680
10915
  summary: "Head workflow node run file content",
10681
10916
  tags: ["Workflows"],
10682
10917
  operationId: "headWorkflowNodeRunFileContent",
10683
- security: bearerSecurityRequirement("headWorkflowNodeRunFileContent"),
10918
+ security: accessTokenSecurityRequirement("headWorkflowNodeRunFileContent"),
10684
10919
  responses: fileContentHeadResponses({ optionalStorage: true })
10685
10920
  }
10686
10921
  }).post("/api/workflows/:workflowId/runs", async (context) => {
@@ -10721,7 +10956,7 @@ function registerWorkflowRoutes(app, host) {
10721
10956
  summary: "Request a workflow run",
10722
10957
  tags: [OPENAPI_TAGS.workflowRuns.name],
10723
10958
  operationId: "requestWorkflowRun",
10724
- security: bearerSecurityRequirement("requestWorkflowRun")
10959
+ security: accessTokenSecurityRequirement("requestWorkflowRun")
10725
10960
  }
10726
10961
  });
10727
10962
  }
@@ -10760,19 +10995,23 @@ function registerHttpRoutes(app, host, options) {
10760
10995
 
10761
10996
  // src/routes/auth.ts
10762
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";
10763
11001
  import {
10764
11002
  AuthRuntimeError,
10765
11003
  clearCsrfCookieHeader,
10766
11004
  clearSessionCookieHeader,
10767
- createAccessTokenCredential,
10768
11005
  createCsrfCookieHeader as createCsrfCookieHeader2,
10769
11006
  createSessionCookieHeader as createSessionCookieHeader2,
10770
11007
  createSessionCredential,
10771
11008
  generateCsrfToken as generateCsrfToken3,
10772
11009
  getCookie as getCookie4,
11010
+ getRequestClientAddress,
10773
11011
  isMagicLinkAuthStrategy,
10774
11012
  isOidcAuthStrategy,
10775
11013
  shouldUseSecureCookies,
11014
+ verifyCsrfToken,
10776
11015
  verifyDoubleSubmitCsrf as verifyDoubleSubmitCsrf3
10777
11016
  } from "@sixb/core/internal/auth";
10778
11017
  import {
@@ -10910,6 +11149,45 @@ function notFoundResponse() {
10910
11149
  });
10911
11150
  }
10912
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
+
10913
11191
  // src/schemas/auth.ts
10914
11192
  import { z as z32 } from "zod";
10915
11193
  var AuthInvitationStatusSchema = z32.enum(["pending", "accepted", "revoked"]);
@@ -10938,17 +11216,19 @@ var AuthInvitationDeliverySchema = z32.object({
10938
11216
  });
10939
11217
  var AuthInvitationGroupOptionSchema = AuthGroupOptionSchema;
10940
11218
  var AuthAccessTokenKindSchema = z32.enum(["personal", "serviceAccount"]);
10941
- var AuthAccessTokenSubjectTypeSchema = z32.enum(["user", "serviceAccount"]);
10942
11219
  var AuthAccessTokenStatusSchema = z32.enum(["active", "expired", "revoked"]);
10943
11220
  var AuthServiceAccountStatusSchema = z32.enum(["active", "suspended"]);
10944
11221
  var AuthUserStatusSchema = z32.enum(["active", "suspended"]);
11222
+ var AuthAccessTokenSubjectSchema = z32.object({
11223
+ type: z32.enum(["user", "serviceAccount"]),
11224
+ id: z32.string()
11225
+ });
10945
11226
  var AuthAccessTokenSchema = z32.object({
10946
11227
  id: z32.string(),
10947
11228
  name: z32.string(),
10948
11229
  kind: AuthAccessTokenKindSchema,
10949
11230
  status: AuthAccessTokenStatusSchema,
10950
- subjectType: AuthAccessTokenSubjectTypeSchema,
10951
- subjectId: z32.string(),
11231
+ subject: AuthAccessTokenSubjectSchema,
10952
11232
  subjectLabel: z32.string().optional(),
10953
11233
  groupIds: z32.array(z32.string()).optional(),
10954
11234
  createdAt: z32.string(),
@@ -11136,7 +11416,7 @@ var AuthSessionResponseSchema = z32.union([
11136
11416
  }),
11137
11417
  z32.object({
11138
11418
  authenticated: z32.literal(true),
11139
- csrfToken: z32.string(),
11419
+ csrfToken: z32.string().optional(),
11140
11420
  applicationAccess: z32.object({
11141
11421
  allowed: z32.boolean(),
11142
11422
  audience: z32.enum(["atlas", "app"])
@@ -11158,9 +11438,15 @@ var AuthSignOutResponseSchema = z32.object({
11158
11438
  success: z32.boolean()
11159
11439
  });
11160
11440
  var CreateDeviceAuthorizationBodySchema = z32.object({
11161
- clientName: z32.string().trim().min(1).max(100),
11162
- tokenName: z32.string().trim().min(1).max(100),
11163
- 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)
11164
11450
  });
11165
11451
  var CreateDeviceAuthorizationResponseSchema = z32.object({
11166
11452
  deviceCode: z32.string(),
@@ -11177,7 +11463,7 @@ var ExchangeDeviceAuthorizationResponseSchema = z32.union([
11177
11463
  z32.object({ status: z32.literal("pending") }),
11178
11464
  z32.object({ status: z32.literal("denied") }),
11179
11465
  z32.object({ status: z32.literal("expired") }),
11180
- z32.object({ status: z32.literal("approved"), accessToken: z32.string() })
11466
+ BearerSessionTokensSchema.extend({ status: z32.literal("approved") })
11181
11467
  ]);
11182
11468
  var DeviceAuthorizationDecisionBodySchema = z32.object({
11183
11469
  userCode: z32.string().trim().min(1),
@@ -11186,13 +11472,14 @@ var DeviceAuthorizationDecisionBodySchema = z32.object({
11186
11472
  });
11187
11473
  var AuthSessionSummarySchema = z32.object({
11188
11474
  id: z32.string(),
11189
- audience: z32.enum(["atlas", "app"]),
11475
+ audience: z32.enum(["atlas", "app"]).optional(),
11190
11476
  current: z32.boolean(),
11191
11477
  createdAt: z32.string(),
11192
11478
  expiresAt: z32.string(),
11193
11479
  lastSeenAt: z32.string().optional(),
11194
11480
  userAgent: z32.string().optional(),
11195
- ipAddress: z32.string().optional()
11481
+ ipAddress: z32.string().optional(),
11482
+ clientName: z32.string().optional()
11196
11483
  });
11197
11484
  var ListAuthSessionsResponseSchema = z32.object({
11198
11485
  sessions: z32.array(AuthSessionSummarySchema)
@@ -11210,9 +11497,15 @@ var SignOutAllResponseSchema = z32.object({
11210
11497
 
11211
11498
  // src/routes/auth.ts
11212
11499
  function registerAuthRoutes(app, host, options) {
11500
+ const deviceAuthorizationLimiter = new ClientAddressRateLimiter(DEVICE_AUTHORIZATIONS_PER_ADDRESS, DEVICE_AUTHORIZATION_TTL_MS);
11213
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 }) => {
11214
11502
  const parsed = CreateDeviceAuthorizationBodySchema.parse(body);
11215
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
+ }
11216
11509
  const id = `dva_${randomUUID()}`;
11217
11510
  const deviceCode = `${id}.${randomBytes(32).toString("base64url")}`;
11218
11511
  const userCode = createDeviceUserCode();
@@ -11224,8 +11517,6 @@ function registerAuthRoutes(app, host, options) {
11224
11517
  deviceCodeHash: hashDeviceCode(deviceCode),
11225
11518
  userCode,
11226
11519
  clientName: parsed.clientName,
11227
- tokenName: parsed.tokenName,
11228
- tokenExpiresAt: new Date(now.getTime() + DEVICE_ACCESS_TOKEN_TTL_MS),
11229
11520
  createdAt: now,
11230
11521
  expiresAt
11231
11522
  });
@@ -11249,9 +11540,10 @@ function registerAuthRoutes(app, host, options) {
11249
11540
  detail: {
11250
11541
  summary: "Start device authorization",
11251
11542
  tags: [OPENAPI_TAGS.authSessions.name],
11252
- operationId: "createDeviceAuthorization"
11543
+ operationId: "createDeviceAuthorization",
11544
+ security: []
11253
11545
  }
11254
- }).post("/api/auth/device-authorizations/token", async ({ body }) => {
11546
+ }).post("/api/auth/device-authorizations/token", async ({ body, request }) => {
11255
11547
  const { deviceCode } = ExchangeDeviceAuthorizationBodySchema.parse(body);
11256
11548
  const id = parseDeviceAuthorizationId(deviceCode);
11257
11549
  if (!id)
@@ -11274,26 +11566,18 @@ function registerAuthRoutes(app, host, options) {
11274
11566
  if (!authorization.approvedUserId || !authorization.approvedSessionId) {
11275
11567
  return jsonResponse2({ status: "expired" }, 200);
11276
11568
  }
11277
- const credential = createAccessTokenCredential("personal");
11569
+ const { session, tokens } = host.auth.prepareBearerSession({
11570
+ userId: authorization.approvedUserId,
11571
+ clientName: authorization.clientName,
11572
+ now
11573
+ });
11278
11574
  try {
11279
11575
  await storage.completeDeviceAuthorization({
11280
11576
  projectId: host.id,
11281
11577
  id,
11282
11578
  deviceCodeHash: hashDeviceCode(deviceCode),
11283
11579
  completedAt: now,
11284
- accessToken: {
11285
- id: credential.tokenId,
11286
- projectId: host.id,
11287
- name: authorization.tokenName,
11288
- kind: "personal",
11289
- subjectType: "user",
11290
- subjectId: authorization.approvedUserId,
11291
- tokenHash: credential.tokenHash,
11292
- createdByPrincipal: { type: "user", id: authorization.approvedUserId },
11293
- createdBySessionId: authorization.approvedSessionId,
11294
- createdAt: now,
11295
- expiresAt: authorization.tokenExpiresAt
11296
- }
11580
+ session: { ...session, ...resolveSessionDevice(request) }
11297
11581
  });
11298
11582
  } catch (error) {
11299
11583
  if (error instanceof AuthStorageError && error.code === "invalid_device_authorization") {
@@ -11301,14 +11585,32 @@ function registerAuthRoutes(app, host, options) {
11301
11585
  }
11302
11586
  throw error;
11303
11587
  }
11304
- return jsonResponse2({ status: "approved", accessToken: credential.tokenValue }, 200);
11588
+ return jsonResponse2({ status: "approved", ...bearerTokensBody(tokens, session.bearer, now) }, 200);
11305
11589
  }, {
11306
11590
  body: ExchangeDeviceAuthorizationBodySchema,
11307
11591
  response: { 200: ExchangeDeviceAuthorizationResponseSchema },
11308
11592
  detail: {
11309
11593
  summary: "Exchange an approved device authorization",
11310
11594
  tags: [OPENAPI_TAGS.authSessions.name],
11311
- 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: []
11312
11614
  }
11313
11615
  }).get("/auth/device", async ({ request }) => {
11314
11616
  const rawUserCode = new URL(request.url).searchParams.get("user_code");
@@ -11345,10 +11647,9 @@ function registerAuthRoutes(app, host, options) {
11345
11647
  const groups = session.groupIds.length ? `<p>Groups: ${escapeHtml(session.groupIds.join(", "))}</p>` : "<p>Groups: none</p>";
11346
11648
  const response = authPageResponse([
11347
11649
  "<h1>Authorize this device?</h1>",
11348
- `<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>`,
11349
11651
  `<p>Code: <strong>${escapeHtml(authorization.userCode)}</strong></p>`,
11350
- `<p>Token: ${escapeHtml(authorization.tokenName)}</p>`,
11351
- `<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>",
11352
11653
  groups,
11353
11654
  '<form method="post" action="/auth/device">',
11354
11655
  `<input type="hidden" name="userCode" value="${escapeHtml(userCode)}">`,
@@ -11366,14 +11667,8 @@ function registerAuthRoutes(app, host, options) {
11366
11667
  const session = await host.auth.getSession(request, authOptions);
11367
11668
  if (!session.authenticated)
11368
11669
  return authPageResponse("<h1>Authentication required</h1>", 401);
11369
- if (!sessionCanAccessApplication(host, session, authOptions.audience)) {
11370
- return authPageResponse("<h1>Access denied</h1>", 403);
11371
- }
11372
- const csrfHeaders = new Headers(request.headers);
11373
- csrfHeaders.set("x-sixb-csrf", parsed.csrfToken);
11374
- if (!verifyDoubleSubmitCsrf3(new Request(request.url, { method: "POST", headers: csrfHeaders }), {
11375
- cookieName: host.auth.getCookieOptions(authOptions).csrfCookieName
11376
- })) {
11670
+ const csrfCookieName = host.auth.getCookieOptions(authOptions).csrfCookieName;
11671
+ if (!verifyCsrfToken(request, { cookieName: csrfCookieName, token: parsed.csrfToken })) {
11377
11672
  return authPageResponse("<h1>Invalid authorization request</h1>", 403);
11378
11673
  }
11379
11674
  const storage = requireAuthStorage(host);
@@ -11383,22 +11678,30 @@ function registerAuthRoutes(app, host, options) {
11383
11678
  });
11384
11679
  if (!authorization)
11385
11680
  return authPageResponse("<h1>Invalid authorization</h1>", 400);
11386
- if (parsed.decision === "approve") {
11387
- await storage.deviceAuthorizations.approve({
11388
- projectId: host.id,
11389
- id: authorization.id,
11390
- userId: session.user.id,
11391
- sessionId: session.session.id,
11392
- approvedAt: new Date
11393
- });
11394
- 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;
11395
11703
  }
11396
- await storage.deviceAuthorizations.deny({
11397
- projectId: host.id,
11398
- id: authorization.id,
11399
- deniedAt: new Date
11400
- });
11401
- 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>");
11402
11705
  }, {
11403
11706
  body: t.Object({
11404
11707
  userCode: t.String(),
@@ -11409,20 +11712,19 @@ function registerAuthRoutes(app, host, options) {
11409
11712
  detail: { hide: true }
11410
11713
  }).get("/api/auth/session", async ({ request }) => {
11411
11714
  const authOptions = resolveAuthOptions(options, request);
11412
- let session = await host.auth.getSession(request, authOptions);
11413
- if (!session.authenticated) {
11715
+ const caller = await host.auth.getSession(request, {
11716
+ ...authOptions,
11717
+ credentialSource: "any"
11718
+ });
11719
+ if (!caller.authenticated || caller.credentialSource !== "session") {
11414
11720
  return jsonResponse2({ authenticated: false }, 200);
11415
11721
  }
11416
- let applicationAccessAllowed = sessionCanAccessApplication(host, session, authOptions.audience);
11417
- if (applicationAccessAllowed && hasForegroundSessionActivity(request)) {
11418
- session = await host.auth.getSession(request, {
11419
- ...authOptions,
11420
- sessionActivity: "foreground"
11421
- });
11422
- if (!session.authenticated) {
11423
- return jsonResponse2({ authenticated: false }, 200);
11424
- }
11425
- 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);
11426
11728
  }
11427
11729
  const cookieOptions = host.auth.getCookieOptions(authOptions);
11428
11730
  const csrf = resolveSessionCsrfToken({
@@ -11436,56 +11738,32 @@ function registerAuthRoutes(app, host, options) {
11436
11738
  session,
11437
11739
  csrfToken: csrf.token
11438
11740
  }) : null;
11439
- return authSessionJsonResponse({
11440
- authenticated: true,
11441
- csrfToken: csrf.token,
11442
- applicationAccess: {
11443
- allowed: applicationAccessAllowed,
11444
- audience: authOptions.audience
11445
- },
11446
- user: {
11447
- id: session.user.id,
11448
- email: session.user.email,
11449
- displayName: session.user.displayName,
11450
- avatarUrl: session.user.avatarUrl,
11451
- groupIds: [...session.groupIds]
11452
- },
11453
- session: {
11454
- id: session.session.id,
11455
- expiresAt: toIsoString(session.session.expiresAt)
11456
- }
11457
- }, renewal?.headers ?? (csrf.setCookie ? [csrf.setCookie] : []));
11741
+ return authSessionJsonResponse({ ...authSessionBody(host, session, authOptions.audience), csrfToken: csrf.token }, renewal?.headers ?? (csrf.setCookie ? [csrf.setCookie] : []));
11458
11742
  }, {
11459
11743
  response: { 200: AuthSessionResponseSchema },
11460
11744
  detail: {
11461
11745
  summary: "Get current auth session",
11462
11746
  tags: [OPENAPI_TAGS.authSessions.name],
11463
- operationId: "getAuthSession"
11747
+ operationId: "getAuthSession",
11748
+ security: SIXB_OPTIONAL_SESSION_SECURITY_REQUIREMENT
11464
11749
  }
11465
11750
  }).post("/api/auth/sign-out", async ({ request }) => {
11466
11751
  const authOptions = resolveAuthOptions(options, request);
11467
- 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;
11468
11757
  const cookieOptions = host.auth.getCookieOptions(authOptions);
11469
- if (session.authenticated && !verifyDoubleSubmitCsrf3(request, {
11758
+ if (session && !session.session.bearer && !verifyDoubleSubmitCsrf3(request, {
11470
11759
  cookieName: cookieOptions.csrfCookieName
11471
11760
  })) {
11472
11761
  return jsonResponse2({ error: "CSRF verification failed" }, 403);
11473
11762
  }
11474
- if (session.authenticated) {
11475
- await host.storage.auth?.sessions.revoke({
11476
- projectId: host.id,
11477
- id: session.session.id,
11478
- revokedAt: new Date
11479
- });
11480
- host.auth.invalidateSession(session.session.id);
11481
- }
11482
- const headers = new Headers({ "content-type": "application/json; charset=utf-8" });
11483
- headers.append("set-cookie", clearSessionCookieHeader({ request, options: cookieOptions }));
11484
- headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }));
11485
- return new Response(JSON.stringify({ success: true }), {
11486
- status: 200,
11487
- headers
11488
- });
11763
+ if (session) {
11764
+ await host.auth.revokeSession(session, session.session.id);
11765
+ }
11766
+ return signedOutResponse(request, cookieOptions, { success: true });
11489
11767
  }, {
11490
11768
  response: {
11491
11769
  200: AuthSignOutResponseSchema,
@@ -11495,29 +11773,25 @@ function registerAuthRoutes(app, host, options) {
11495
11773
  summary: "Sign out current auth session",
11496
11774
  tags: [OPENAPI_TAGS.authSessions.name],
11497
11775
  operationId: "signOut",
11498
- security: SIXB_CSRF_SECURITY_REQUIREMENT
11776
+ security: SIXB_OPTIONAL_SESSION_MUTATION_SECURITY_REQUIREMENT
11499
11777
  }
11500
- }).get("/api/auth/sessions", async ({ request }) => {
11501
- const authOptions = resolveAuthOptions(options, request);
11502
- const session = await host.auth.getSession(request, authOptions);
11503
- if (!session.authenticated) {
11504
- 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;
11505
11782
  }
11506
- const sessions = await requireAuthStorage(host).sessions.listActiveByUserId({
11507
- projectId: host.id,
11508
- userId: session.user.id,
11509
- now: new Date
11510
- });
11783
+ const sessions = await host.auth.listSessions(session);
11511
11784
  return jsonResponse2({
11512
11785
  sessions: sessions.map((entry) => ({
11513
11786
  id: entry.id,
11514
- audience: entry.audience,
11787
+ audience: entry.bearer ? undefined : entry.audience,
11515
11788
  current: entry.id === session.session.id,
11516
11789
  createdAt: toIsoString(entry.createdAt),
11517
11790
  expiresAt: toIsoString(entry.expiresAt),
11518
11791
  lastSeenAt: entry.lastSeenAt ? toIsoString(entry.lastSeenAt) : undefined,
11519
11792
  userAgent: entry.userAgent,
11520
- ipAddress: entry.ipAddress
11793
+ ipAddress: entry.ipAddress,
11794
+ clientName: entry.bearer?.clientName
11521
11795
  }))
11522
11796
  }, 200);
11523
11797
  }, {
@@ -11530,30 +11804,20 @@ function registerAuthRoutes(app, host, options) {
11530
11804
  tags: [OPENAPI_TAGS.authSessions.name],
11531
11805
  operationId: "listAuthSessions"
11532
11806
  }
11533
- }).post("/api/auth/sessions/:sessionId/revoke", async ({ request, params }) => {
11534
- const authOptions = resolveAuthOptions(options, request);
11535
- const session = await host.auth.getSession(request, authOptions);
11536
- const cookieOptions = host.auth.getCookieOptions(authOptions);
11537
- if (!session.authenticated) {
11538
- return jsonResponse2({ error: "Authentication required" }, 401);
11539
- }
11540
- if (!verifyDoubleSubmitCsrf3(request, { cookieName: cookieOptions.csrfCookieName })) {
11541
- 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;
11542
11811
  }
11543
11812
  const { sessionId } = RevokeAuthSessionParamsSchema.parse(params);
11544
- const storage = requireAuthStorage(host);
11545
- const target = await storage.sessions.getById({ projectId: host.id, id: sessionId });
11546
- if (!target || target.userId !== session.user.id) {
11813
+ if (!await host.auth.revokeSession(session, sessionId)) {
11547
11814
  return jsonResponse2({ error: "Session not found" }, 404);
11548
11815
  }
11549
- await storage.sessions.revoke({ projectId: host.id, id: sessionId, revokedAt: new Date });
11550
- host.auth.invalidateSession(sessionId);
11551
- const headers = new Headers({ "content-type": "application/json; charset=utf-8" });
11552
- if (sessionId === session.session.id) {
11553
- headers.append("set-cookie", clearSessionCookieHeader({ request, options: cookieOptions }));
11554
- headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }));
11816
+ if (sessionId !== session.session.id) {
11817
+ return jsonResponse2({ success: true }, 200);
11555
11818
  }
11556
- 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 });
11557
11821
  }, {
11558
11822
  params: RevokeAuthSessionParamsSchema,
11559
11823
  response: {
@@ -11566,33 +11830,16 @@ function registerAuthRoutes(app, host, options) {
11566
11830
  summary: "Revoke one of the current user's sessions",
11567
11831
  tags: [OPENAPI_TAGS.authSessions.name],
11568
11832
  operationId: "revokeAuthSession",
11569
- security: SIXB_CSRF_SECURITY_REQUIREMENT
11570
- }
11571
- }).post("/api/auth/sign-out-all", async ({ request }) => {
11572
- const authOptions = resolveAuthOptions(options, request);
11573
- const session = await host.auth.getSession(request, authOptions);
11574
- const cookieOptions = host.auth.getCookieOptions(authOptions);
11575
- if (!session.authenticated) {
11576
- return jsonResponse2({ error: "Authentication required" }, 401);
11833
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
11577
11834
  }
11578
- if (!verifyDoubleSubmitCsrf3(request, { cookieName: cookieOptions.csrfCookieName })) {
11579
- return jsonResponse2({ error: "CSRF verification failed" }, 403);
11835
+ }).post("/api/auth/sign-out-all", async ({ request, ...context }) => {
11836
+ const session = requireSessionCaller(context);
11837
+ if (session instanceof Response) {
11838
+ return session;
11580
11839
  }
11581
- const revoked = await requireAuthStorage(host).sessions.revokeActiveForUser({
11582
- projectId: host.id,
11583
- userId: session.user.id,
11584
- revokedAt: new Date
11585
- });
11586
- for (const revokedSession of revoked) {
11587
- host.auth.invalidateSession(revokedSession.id);
11588
- }
11589
- const headers = new Headers({ "content-type": "application/json; charset=utf-8" });
11590
- headers.append("set-cookie", clearSessionCookieHeader({ request, options: cookieOptions }));
11591
- headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }));
11592
- return new Response(JSON.stringify({ success: true, revokedCount: revoked.length }), {
11593
- status: 200,
11594
- headers
11595
- });
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 });
11596
11843
  }, {
11597
11844
  response: {
11598
11845
  200: SignOutAllResponseSchema,
@@ -11603,19 +11850,12 @@ function registerAuthRoutes(app, host, options) {
11603
11850
  summary: "Sign out the current user everywhere (all devices and apps)",
11604
11851
  tags: [OPENAPI_TAGS.authSessions.name],
11605
11852
  operationId: "signOutAll",
11606
- security: SIXB_CSRF_SECURITY_REQUIREMENT
11853
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
11607
11854
  }
11608
- }).get("/api/auth/access-management-options", async ({ request }) => {
11855
+ }).get("/api/auth/access-management-options", async (context) => {
11609
11856
  try {
11610
- const authOptions = resolveAuthOptions(options, request);
11611
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, {
11612
- ...authOptions,
11613
- credentialSource: "any"
11614
- }));
11615
- if (session instanceof Response) {
11616
- return session;
11617
- }
11618
- const assignableGroupIds = new Set(session.groupIds);
11857
+ const caller = requireUserCaller(context);
11858
+ const assignableGroupIds = new Set(caller.groupIds);
11619
11859
  return jsonResponse2({
11620
11860
  groups: host.definitions.security.listGroups().filter((group) => assignableGroupIds.has(group.id)).map(serializeGroupOption)
11621
11861
  }, 200);
@@ -11632,21 +11872,14 @@ function registerAuthRoutes(app, host, options) {
11632
11872
  summary: "Get auth access-token management options",
11633
11873
  tags: [OPENAPI_TAGS.authAccessTokens.name],
11634
11874
  operationId: "getAuthAccessManagementOptions",
11635
- security: bearerSecurityRequirement("getAuthAccessManagementOptions")
11875
+ security: accessTokenSecurityRequirement("getAuthAccessManagementOptions")
11636
11876
  }
11637
- }).get("/api/auth/access-tokens", async ({ request }) => {
11877
+ }).get("/api/auth/access-tokens", async ({ ...context }) => {
11638
11878
  try {
11639
- const authOptions = resolveAuthOptions(options, request);
11640
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, {
11641
- ...authOptions,
11642
- credentialSource: "any"
11643
- }));
11644
- if (session instanceof Response) {
11645
- return session;
11646
- }
11647
- const { accessTokens } = await host.auth.listPersonalAccessTokens(request, authOptions);
11879
+ const caller = requireUserCaller(context);
11880
+ const { accessTokens } = await host.auth.listPersonalAccessTokens(caller);
11648
11881
  return jsonResponse2({
11649
- accessTokens: accessTokens.map((accessToken) => serializeAccessToken(accessToken, { subjectLabel: session.user.email }))
11882
+ accessTokens: accessTokens.map((accessToken) => serializeAccessToken(accessToken, { subjectLabel: caller.user.email }))
11650
11883
  }, 200);
11651
11884
  } catch (error) {
11652
11885
  return authRouteErrorResponse(error);
@@ -11661,24 +11894,21 @@ function registerAuthRoutes(app, host, options) {
11661
11894
  summary: "List personal access tokens for the current user",
11662
11895
  tags: [OPENAPI_TAGS.authAccessTokens.name],
11663
11896
  operationId: "listAuthAccessTokens",
11664
- security: bearerSecurityRequirement("listAuthAccessTokens")
11897
+ security: accessTokenSecurityRequirement("listAuthAccessTokens")
11665
11898
  }
11666
- }).post("/api/auth/access-tokens", async ({ request, body }) => {
11899
+ }).post("/api/auth/access-tokens", async ({ body, ...context }) => {
11667
11900
  try {
11668
- const authOptions = resolveAuthOptions(options, request);
11669
11901
  const parsed = CreateAuthPersonalAccessTokenBodySchema.parse(body);
11670
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, {
11671
- ...authOptions,
11672
- credentialSource: "any"
11673
- }));
11674
- if (session instanceof Response) {
11675
- return session;
11676
- }
11902
+ const caller = requireUserCaller(context);
11677
11903
  const expiresAt = parseRequiredFutureDate(parsed.expiresAt);
11678
- 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
+ });
11679
11909
  return jsonResponse2({
11680
11910
  accessToken: serializeAccessToken(result.accessToken, {
11681
- subjectLabel: session.user.email
11911
+ subjectLabel: caller.user.email
11682
11912
  }),
11683
11913
  tokenValue: result.tokenValue
11684
11914
  }, 201);
@@ -11698,23 +11928,16 @@ function registerAuthRoutes(app, host, options) {
11698
11928
  summary: "Create a personal access token",
11699
11929
  tags: [OPENAPI_TAGS.authAccessTokens.name],
11700
11930
  operationId: "createAuthPersonalAccessToken",
11701
- security: bearerSecurityRequirement("createAuthPersonalAccessToken")
11931
+ security: accessTokenSecurityRequirement("createAuthPersonalAccessToken")
11702
11932
  }
11703
- }).post("/api/auth/access-tokens/:tokenId/revoke", async ({ request, params }) => {
11933
+ }).post("/api/auth/access-tokens/:tokenId/revoke", async ({ params, ...context }) => {
11704
11934
  try {
11705
- const authOptions = resolveAuthOptions(options, request);
11706
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, {
11707
- ...authOptions,
11708
- credentialSource: "any"
11709
- }));
11710
- if (session instanceof Response) {
11711
- return session;
11712
- }
11935
+ const caller = requireUserCaller(context);
11713
11936
  const { tokenId } = RevokeAuthAccessTokenParamsSchema.parse(params);
11714
- const result = await host.auth.revokePersonalAccessToken(request, { tokenId }, authOptions);
11937
+ const result = await host.auth.revokePersonalAccessToken(caller, { tokenId });
11715
11938
  return jsonResponse2({
11716
11939
  accessToken: serializeAccessToken(result.accessToken, {
11717
- subjectLabel: session.user.email
11940
+ subjectLabel: caller.user.email
11718
11941
  })
11719
11942
  }, 200);
11720
11943
  } catch (error) {
@@ -11733,15 +11956,12 @@ function registerAuthRoutes(app, host, options) {
11733
11956
  summary: "Revoke one of the current user's personal access tokens",
11734
11957
  tags: [OPENAPI_TAGS.authAccessTokens.name],
11735
11958
  operationId: "revokeAuthAccessToken",
11736
- security: bearerSecurityRequirement("revokeAuthAccessToken")
11959
+ security: accessTokenSecurityRequirement("revokeAuthAccessToken")
11737
11960
  }
11738
- }).get("/api/auth/service-accounts", async ({ request }) => {
11961
+ }).get("/api/auth/service-accounts", async ({ ...context }) => {
11739
11962
  try {
11740
- const authOptions = resolveAuthOptions(options, request);
11741
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, { ...authOptions, credentialSource: "any" }));
11742
- if (session instanceof Response)
11743
- return session;
11744
- const { serviceAccounts } = await host.auth.listServiceAccounts(request, authOptions);
11963
+ const caller = requireUserCaller(context);
11964
+ const { serviceAccounts } = await host.auth.listServiceAccounts(caller);
11745
11965
  return jsonResponse2({
11746
11966
  serviceAccounts: serviceAccounts.map(({ serviceAccount, groupIds }) => serializeServiceAccount(serviceAccount, groupIds))
11747
11967
  }, 200);
@@ -11759,21 +11979,18 @@ function registerAuthRoutes(app, host, options) {
11759
11979
  summary: "List auth service accounts",
11760
11980
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
11761
11981
  operationId: "listAuthServiceAccounts",
11762
- security: bearerSecurityRequirement("listAuthServiceAccounts")
11982
+ security: accessTokenSecurityRequirement("listAuthServiceAccounts")
11763
11983
  }
11764
- }).post("/api/auth/service-accounts", async ({ request, body }) => {
11984
+ }).post("/api/auth/service-accounts", async ({ body, ...context }) => {
11765
11985
  try {
11766
- const authOptions = resolveAuthOptions(options, request);
11986
+ const caller = requireUserCaller(context);
11767
11987
  const parsed = CreateAuthServiceAccountBodySchema.parse(body);
11768
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, { ...authOptions, credentialSource: "any" }));
11769
- if (session instanceof Response)
11770
- return session;
11771
- const result = await host.auth.createServiceAccount(request, {
11988
+ const result = await host.auth.createServiceAccount(caller, {
11772
11989
  id: parsed.id,
11773
11990
  name: parsed.name,
11774
11991
  description: optionalTrimmed(parsed.description),
11775
11992
  groupIds: parsed.groupIds
11776
- }, { ...authOptions, credentialSource: "any" });
11993
+ });
11777
11994
  return jsonResponse2({
11778
11995
  serviceAccount: serializeServiceAccount(result.serviceAccount, result.groupMemberships.map((membership) => membership.groupId))
11779
11996
  }, 201);
@@ -11793,16 +12010,13 @@ function registerAuthRoutes(app, host, options) {
11793
12010
  summary: "Create an auth service account",
11794
12011
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
11795
12012
  operationId: "createAuthServiceAccount",
11796
- security: bearerSecurityRequirement("createAuthServiceAccount")
12013
+ security: accessTokenSecurityRequirement("createAuthServiceAccount")
11797
12014
  }
11798
- }).post("/api/auth/service-accounts/:serviceAccountId/disable", async ({ request, params }) => {
12015
+ }).post("/api/auth/service-accounts/:serviceAccountId/disable", async ({ params, ...context }) => {
11799
12016
  try {
11800
- const authOptions = resolveAuthOptions(options, request);
11801
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, { ...authOptions, credentialSource: "any" }));
11802
- if (session instanceof Response)
11803
- return session;
12017
+ const caller = requireUserCaller(context);
11804
12018
  const { serviceAccountId } = AuthServiceAccountParamsSchema.parse(params);
11805
- const result = await host.auth.disableServiceAccount(request, { serviceAccountId }, authOptions);
12019
+ const result = await host.auth.disableServiceAccount(caller, { serviceAccountId });
11806
12020
  return jsonResponse2({
11807
12021
  serviceAccount: serializeServiceAccount(result.serviceAccount, result.groupIds)
11808
12022
  }, 200);
@@ -11822,16 +12036,13 @@ function registerAuthRoutes(app, host, options) {
11822
12036
  summary: "Disable an auth service account",
11823
12037
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
11824
12038
  operationId: "disableAuthServiceAccount",
11825
- security: bearerSecurityRequirement("disableAuthServiceAccount")
12039
+ security: accessTokenSecurityRequirement("disableAuthServiceAccount")
11826
12040
  }
11827
- }).get("/api/auth/service-accounts/:serviceAccountId/access-tokens", async ({ request, params }) => {
12041
+ }).get("/api/auth/service-accounts/:serviceAccountId/access-tokens", async ({ params, ...context }) => {
11828
12042
  try {
11829
- const authOptions = resolveAuthOptions(options, request);
11830
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, { ...authOptions, credentialSource: "any" }));
11831
- if (session instanceof Response)
11832
- return session;
12043
+ const caller = requireUserCaller(context);
11833
12044
  const { serviceAccountId } = AuthServiceAccountParamsSchema.parse(params);
11834
- const { serviceAccount, accessTokens } = await host.auth.listServiceAccountAccessTokens(request, { serviceAccountId }, authOptions);
12045
+ const { serviceAccount, accessTokens } = await host.auth.listServiceAccountAccessTokens(caller, { serviceAccountId });
11835
12046
  return jsonResponse2({
11836
12047
  accessTokens: accessTokens.map((accessToken) => serializeAccessToken(accessToken, { subjectLabel: serviceAccount.name }))
11837
12048
  }, 200);
@@ -11851,23 +12062,20 @@ function registerAuthRoutes(app, host, options) {
11851
12062
  summary: "List access tokens for an auth service account",
11852
12063
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
11853
12064
  operationId: "listAuthServiceAccountAccessTokens",
11854
- security: bearerSecurityRequirement("listAuthServiceAccountAccessTokens")
12065
+ security: accessTokenSecurityRequirement("listAuthServiceAccountAccessTokens")
11855
12066
  }
11856
- }).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 }) => {
11857
12068
  try {
11858
- const authOptions = resolveAuthOptions(options, request);
12069
+ const caller = requireUserCaller(context);
11859
12070
  const parsedParams = AuthServiceAccountParamsSchema.parse(params);
11860
12071
  const parsed = CreateAuthServiceAccountAccessTokenBodySchema.parse(body);
11861
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, { ...authOptions, credentialSource: "any" }));
11862
- if (session instanceof Response)
11863
- return session;
11864
12072
  const expiresAt = parseRequiredFutureDate(parsed.expiresAt);
11865
- const result = await host.auth.createServiceAccountAccessToken(request, {
12073
+ const result = await host.auth.createServiceAccountAccessToken(caller, {
11866
12074
  serviceAccountId: parsedParams.serviceAccountId,
11867
12075
  name: parsed.name,
11868
12076
  expiresAt,
11869
12077
  groupIds: parsed.groupIds
11870
- }, { ...authOptions, credentialSource: "any" });
12078
+ });
11871
12079
  return jsonResponse2({
11872
12080
  accessToken: serializeAccessToken(result.accessToken, {
11873
12081
  subjectLabel: result.serviceAccount.name
@@ -11892,16 +12100,16 @@ function registerAuthRoutes(app, host, options) {
11892
12100
  summary: "Create an access token for an auth service account",
11893
12101
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
11894
12102
  operationId: "createAuthServiceAccountAccessToken",
11895
- security: bearerSecurityRequirement("createAuthServiceAccountAccessToken")
12103
+ security: accessTokenSecurityRequirement("createAuthServiceAccountAccessToken")
11896
12104
  }
11897
- }).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 }) => {
11898
12106
  try {
11899
- const authOptions = resolveAuthOptions(options, request);
12107
+ const caller = requireUserCaller(context);
11900
12108
  const parsed = RevokeAuthServiceAccountAccessTokenParamsSchema.parse(params);
11901
- const session = requireAuthenticatedUserSession(await host.auth.getSession(request, { ...authOptions, credentialSource: "any" }));
11902
- if (session instanceof Response)
11903
- return session;
11904
- 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
+ });
11905
12113
  return jsonResponse2({
11906
12114
  accessToken: serializeAccessToken(result.accessToken, {
11907
12115
  subjectLabel: result.serviceAccount.name
@@ -11923,11 +12131,11 @@ function registerAuthRoutes(app, host, options) {
11923
12131
  summary: "Revoke an access token for an auth service account",
11924
12132
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
11925
12133
  operationId: "revokeAuthServiceAccountAccessToken",
11926
- security: bearerSecurityRequirement("revokeAuthServiceAccountAccessToken")
12134
+ security: accessTokenSecurityRequirement("revokeAuthServiceAccountAccessToken")
11927
12135
  }
11928
- }).post("/api/auth/invitations", async ({ request, body }) => {
12136
+ }).post("/api/auth/invitations", async ({ request, body, ...context }) => {
11929
12137
  try {
11930
- const authOptions = resolveAuthOptions(options, request);
12138
+ const caller = requireUserCaller(context);
11931
12139
  const parsed = CreateAuthInvitationBodySchema.parse(body);
11932
12140
  const deliveryContext = resolveInvitationDeliveryContext(options, request, {
11933
12141
  destinationId: parsed.destinationId,
@@ -11936,20 +12144,12 @@ function registerAuthRoutes(app, host, options) {
11936
12144
  if (deliveryContext instanceof Response) {
11937
12145
  return deliveryContext;
11938
12146
  }
11939
- const result = await host.auth.invite(request, {
12147
+ const result = await host.auth.invite(caller, {
11940
12148
  email: parsed.email,
11941
12149
  groupIds: parsed.groupIds,
11942
12150
  expiresAt: parseDate(parsed.expiresAt),
11943
- returnTo: deliveryContext.returnTo,
11944
12151
  revealLink: parsed.revealLink
11945
- }, {
11946
- ...authOptions,
11947
- delivery: {
11948
- audience: deliveryContext.audience,
11949
- returnTo: deliveryContext.returnTo,
11950
- requestOrigin: deliveryContext.requestOrigin
11951
- }
11952
- });
12152
+ }, deliveryContext);
11953
12153
  return jsonResponse2({
11954
12154
  invitation: serializeInvitation(result.invitation),
11955
12155
  delivery: serializeInvitationDelivery(result.delivery)
@@ -11972,13 +12172,13 @@ function registerAuthRoutes(app, host, options) {
11972
12172
  summary: "Create an auth invitation",
11973
12173
  tags: [OPENAPI_TAGS.authInvitations.name],
11974
12174
  operationId: "createAuthInvitation",
11975
- security: SIXB_CSRF_SECURITY_REQUIREMENT
12175
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
11976
12176
  }
11977
- }).get("/api/auth/invitation-options", async ({ request }) => {
12177
+ }).get("/api/auth/invitation-options", async ({ request, ...context }) => {
11978
12178
  try {
11979
- const authOptions = resolveAuthOptions(options, request);
12179
+ const caller = requireUserCaller(context);
11980
12180
  return jsonResponse2({
11981
- ...await host.auth.getInvitationOptions(request, authOptions),
12181
+ ...await host.auth.getInvitationOptions(caller),
11982
12182
  ...options.getInvitationDestinationOptions(request)
11983
12183
  }, 200);
11984
12184
  } catch (error) {
@@ -11995,17 +12195,17 @@ function registerAuthRoutes(app, host, options) {
11995
12195
  tags: [OPENAPI_TAGS.authInvitations.name],
11996
12196
  operationId: "getAuthInvitationOptions"
11997
12197
  }
11998
- }).get("/api/auth/invitations", async ({ request, query }) => {
12198
+ }).get("/api/auth/invitations", async ({ query, ...context }) => {
11999
12199
  try {
12000
- const authOptions = resolveAuthOptions(options, request);
12200
+ const caller = requireUserCaller(context);
12001
12201
  const parsed = ListAuthInvitationsQuerySchema.parse(query);
12002
- const result = await host.auth.listInvitations(request, {
12202
+ const result = await host.auth.listInvitations(caller, {
12003
12203
  email: parsed.email,
12004
12204
  statuses: parsed.status ? [parsed.status] : undefined,
12005
12205
  limit: parseOptionalInt(parsed.limit),
12006
12206
  offset: parseOptionalInt(parsed.offset),
12007
12207
  order: parsed.order
12008
- }, authOptions);
12208
+ });
12009
12209
  return jsonResponse2({
12010
12210
  invitations: result.invitations.map(serializeInvitation),
12011
12211
  hasMore: result.hasMore,
@@ -12029,13 +12229,13 @@ function registerAuthRoutes(app, host, options) {
12029
12229
  tags: [OPENAPI_TAGS.authInvitations.name],
12030
12230
  operationId: "listAuthInvitations"
12031
12231
  }
12032
- }).post("/api/auth/invitations/:invitationId/revoke", async ({ request, params }) => {
12232
+ }).post("/api/auth/invitations/:invitationId/revoke", async ({ params, ...context }) => {
12033
12233
  try {
12034
- const authOptions = resolveAuthOptions(options, request);
12234
+ const caller = requireUserCaller(context);
12035
12235
  const parsed = RevokeAuthInvitationParamsSchema.parse(params);
12036
- const result = await host.auth.revokeInvitation(request, {
12236
+ const result = await host.auth.revokeInvitation(caller, {
12037
12237
  invitationId: parsed.invitationId
12038
- }, authOptions);
12238
+ });
12039
12239
  return jsonResponse2({
12040
12240
  invitation: serializeInvitation(result.invitation)
12041
12241
  }, 200);
@@ -12056,12 +12256,12 @@ function registerAuthRoutes(app, host, options) {
12056
12256
  summary: "Revoke an auth invitation",
12057
12257
  tags: [OPENAPI_TAGS.authInvitations.name],
12058
12258
  operationId: "revokeAuthInvitation",
12059
- security: SIXB_CSRF_SECURITY_REQUIREMENT
12259
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
12060
12260
  }
12061
- }).get("/api/auth/membership-options", async ({ request }) => {
12261
+ }).get("/api/auth/membership-options", async ({ ...context }) => {
12062
12262
  try {
12063
- const authOptions = resolveAuthOptions(options, request);
12064
- return jsonResponse2(await host.auth.getMembershipOptions(request, authOptions), 200);
12263
+ const caller = requireUserCaller(context);
12264
+ return jsonResponse2(await host.auth.getMembershipOptions(caller), 200);
12065
12265
  } catch (error) {
12066
12266
  return authRouteErrorResponse(error);
12067
12267
  }
@@ -12076,15 +12276,15 @@ function registerAuthRoutes(app, host, options) {
12076
12276
  tags: [OPENAPI_TAGS.authMembers.name],
12077
12277
  operationId: "getAuthMembershipOptions"
12078
12278
  }
12079
- }).get("/api/auth/members", async ({ request, query }) => {
12279
+ }).get("/api/auth/members", async ({ query, ...context }) => {
12080
12280
  try {
12081
- const authOptions = resolveAuthOptions(options, request);
12281
+ const caller = requireUserCaller(context);
12082
12282
  const parsed = ListAuthMembersQuerySchema.parse(query);
12083
- const result = await host.auth.listMembers(request, {
12283
+ const result = await host.auth.listMembers(caller, {
12084
12284
  limit: parseOptionalInt(parsed.limit),
12085
12285
  offset: parseOptionalInt(parsed.offset),
12086
12286
  order: parsed.order
12087
- }, authOptions);
12287
+ });
12088
12288
  return jsonResponse2({
12089
12289
  members: result.members.map(serializeMemberSummary),
12090
12290
  hasMore: result.hasMore,
@@ -12106,12 +12306,15 @@ function registerAuthRoutes(app, host, options) {
12106
12306
  tags: [OPENAPI_TAGS.authMembers.name],
12107
12307
  operationId: "listAuthMembers"
12108
12308
  }
12109
- }).patch("/api/auth/members/:userId/groups", async ({ request, params, body }) => {
12309
+ }).patch("/api/auth/members/:userId/groups", async ({ params, body, ...context }) => {
12110
12310
  try {
12111
- const authOptions = resolveAuthOptions(options, request);
12311
+ const caller = requireUserCaller(context);
12112
12312
  const parsedParams = AuthMemberParamsSchema.parse(params);
12113
12313
  const parsed = UpdateAuthMemberGroupsBodySchema.parse(body);
12114
- 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
+ });
12115
12318
  return jsonResponse2({ member: serializeManagedMember(result.user, result.groupIds) }, 200);
12116
12319
  } catch (error) {
12117
12320
  return authRouteErrorResponse(error);
@@ -12131,13 +12334,13 @@ function registerAuthRoutes(app, host, options) {
12131
12334
  summary: "Update an auth member's groups",
12132
12335
  tags: [OPENAPI_TAGS.authMembers.name],
12133
12336
  operationId: "updateAuthMemberGroups",
12134
- security: SIXB_CSRF_SECURITY_REQUIREMENT
12337
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
12135
12338
  }
12136
- }).post("/api/auth/members/:userId/suspend", async ({ request, params }) => {
12339
+ }).post("/api/auth/members/:userId/suspend", async ({ params, ...context }) => {
12137
12340
  try {
12138
- const authOptions = resolveAuthOptions(options, request);
12341
+ const caller = requireUserCaller(context);
12139
12342
  const parsed = AuthMemberParamsSchema.parse(params);
12140
- const result = await host.auth.suspendMember(request, { userId: parsed.userId }, authOptions);
12343
+ const result = await host.auth.suspendMember(caller, { userId: parsed.userId });
12141
12344
  return jsonResponse2({ member: serializeManagedMember(result.user, result.groupIds) }, 200);
12142
12345
  } catch (error) {
12143
12346
  return authRouteErrorResponse(error);
@@ -12155,13 +12358,13 @@ function registerAuthRoutes(app, host, options) {
12155
12358
  summary: "Suspend an auth member",
12156
12359
  tags: [OPENAPI_TAGS.authMembers.name],
12157
12360
  operationId: "suspendAuthMember",
12158
- security: SIXB_CSRF_SECURITY_REQUIREMENT
12361
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
12159
12362
  }
12160
- }).post("/api/auth/members/:userId/reactivate", async ({ request, params }) => {
12363
+ }).post("/api/auth/members/:userId/reactivate", async ({ params, ...context }) => {
12161
12364
  try {
12162
- const authOptions = resolveAuthOptions(options, request);
12365
+ const caller = requireUserCaller(context);
12163
12366
  const parsed = AuthMemberParamsSchema.parse(params);
12164
- const result = await host.auth.reactivateMember(request, { userId: parsed.userId }, authOptions);
12367
+ const result = await host.auth.reactivateMember(caller, { userId: parsed.userId });
12165
12368
  return jsonResponse2({ member: serializeManagedMember(result.user, result.groupIds) }, 200);
12166
12369
  } catch (error) {
12167
12370
  return authRouteErrorResponse(error);
@@ -12179,7 +12382,7 @@ function registerAuthRoutes(app, host, options) {
12179
12382
  summary: "Reactivate an auth member",
12180
12383
  tags: [OPENAPI_TAGS.authMembers.name],
12181
12384
  operationId: "reactivateAuthMember",
12182
- security: SIXB_CSRF_SECURITY_REQUIREMENT
12385
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT
12183
12386
  }
12184
12387
  }).post("/auth/sign-in", async ({ body, request }) => {
12185
12388
  const strategy = host.auth.getStrategy();
@@ -12370,7 +12573,7 @@ function registerAuthRoutes(app, host, options) {
12370
12573
  });
12371
12574
  }
12372
12575
  var DEVICE_AUTHORIZATION_TTL_MS = 10 * 60 * 1000;
12373
- var DEVICE_ACCESS_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000;
12576
+ var DEVICE_AUTHORIZATIONS_PER_ADDRESS = 10;
12374
12577
  var DEVICE_AUTHORIZATION_POLL_INTERVAL_SECONDS = 2;
12375
12578
  var DEVICE_USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXYZ23456789";
12376
12579
  function hashDeviceCode(deviceCode) {
@@ -12466,10 +12669,17 @@ async function completeMagicLinkCallback(input) {
12466
12669
  return await invalidMagicLinkResponse(input.options, input.authRedirectHint);
12467
12670
  }
12468
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
+ }
12469
12679
  function resolveSessionDevice(request) {
12470
12680
  return {
12471
12681
  userAgent: request.headers.get("user-agent")?.trim() || undefined,
12472
- ipAddress: request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || request.headers.get("x-real-ip")?.trim() || undefined
12682
+ ipAddress: getRequestClientAddress(request)
12473
12683
  };
12474
12684
  }
12475
12685
  function sessionCallbackCompletionResponse(input) {
@@ -12560,6 +12770,20 @@ function resolveSessionCsrfToken(input) {
12560
12770
  })
12561
12771
  };
12562
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
+ }
12563
12787
  function authSessionJsonResponse(body, setCookies) {
12564
12788
  const headers = new Headers({
12565
12789
  "content-type": "application/json; charset=utf-8",
@@ -12881,8 +13105,7 @@ function serializeAccessToken(accessToken, options = {}) {
12881
13105
  name: accessToken.name,
12882
13106
  kind: accessToken.kind,
12883
13107
  status,
12884
- subjectType: accessToken.subjectType,
12885
- subjectId: accessToken.subjectId,
13108
+ subject: { type: accessToken.subject.type, id: accessToken.subject.id },
12886
13109
  subjectLabel: options.subjectLabel,
12887
13110
  groupIds: accessToken.groupIds ? [...accessToken.groupIds] : undefined,
12888
13111
  createdAt: toIsoString(accessToken.createdAt),
@@ -12918,17 +13141,25 @@ function optionalTrimmed(value) {
12918
13141
  const trimmed = value?.trim();
12919
13142
  return trimmed ? trimmed : undefined;
12920
13143
  }
12921
- function requireAuthenticatedUserSession(session) {
12922
- if (!session.authenticated) {
12923
- 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");
12924
13148
  }
12925
- if (!isAuthenticatedUserSession(session)) {
12926
- return jsonResponse2({ error: "User authentication is required" }, 403);
13149
+ if (!("user" in caller)) {
13150
+ throw new AuthRuntimeError("authorization_denied", "User authentication is required");
12927
13151
  }
12928
- return session;
13152
+ return caller;
12929
13153
  }
12930
- function isAuthenticatedUserSession(session) {
12931
- return session.principal.type === "user";
13154
+ function requireSessionCaller(context) {
13155
+ const caller = requestCaller(context);
13156
+ return caller?.credentialSource === "session" ? caller : jsonResponse2({ error: "Authentication required" }, 401);
13157
+ }
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 });
12932
13163
  }
12933
13164
  function serializeInvitation(invitation) {
12934
13165
  return {
@@ -14337,6 +14568,7 @@ class SixbServer {
14337
14568
  authRedirectContextResolver;
14338
14569
  authExperience;
14339
14570
  sharedAccessOptions;
14571
+ resolveClientAddress;
14340
14572
  app = null;
14341
14573
  bunServer = null;
14342
14574
  maintenance = null;
@@ -14350,6 +14582,7 @@ class SixbServer {
14350
14582
  this.authRedirectContextResolver = createApiBrowserAuthRedirectContextResolver(this.apiBrowserPolicy);
14351
14583
  this.authExperience = options.authExperience;
14352
14584
  this.sharedAccessOptions = options.sharedAccess ?? {};
14585
+ this.resolveClientAddress = createClientAddressResolver(options.trustedProxies ?? [PRIVATE_NETWORKS]);
14353
14586
  }
14354
14587
  getHost() {
14355
14588
  return this.hostRuntime;
@@ -14391,7 +14624,8 @@ class SixbServer {
14391
14624
  this.app = createSixbApi(this);
14392
14625
  this.bunServer = startApiServer(this.app, {
14393
14626
  host: this.hostname,
14394
- port: this.port
14627
+ port: this.port,
14628
+ resolveClientAddress: this.resolveClientAddress
14395
14629
  });
14396
14630
  } catch (error) {
14397
14631
  this.app = null;
@@ -14445,7 +14679,7 @@ function createSixbApi(server) {
14445
14679
  allowedHeaders: [
14446
14680
  "authorization",
14447
14681
  "content-type",
14448
- CSRF_HEADER_NAME3,
14682
+ CSRF_HEADER_NAME2,
14449
14683
  SESSION_ACTIVITY_HEADER_NAME,
14450
14684
  SHARED_ACCESS_GRANT_HEADER_NAME
14451
14685
  ],
@@ -14567,18 +14801,20 @@ function createSixbApi(server) {
14567
14801
  components: {
14568
14802
  securitySchemes: {
14569
14803
  [SIXB_CSRF_SECURITY_SCHEME_ID]: SIXB_CSRF_SECURITY_SCHEME,
14570
- [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,
14571
14806
  [SIXB_SHARED_GRANT_SECURITY_SCHEME_ID]: SIXB_SHARED_GRANT_SECURITY_SCHEME
14572
14807
  },
14573
14808
  schemas: ObjectQueryOpenApiSchemas
14574
14809
  },
14810
+ security: SIXB_SESSION_SECURITY_REQUIREMENT,
14575
14811
  tags: OPENAPI_TAG_METADATA
14576
14812
  },
14577
14813
  swagger: {
14578
14814
  withCredentials: true
14579
14815
  },
14580
14816
  mapJsonSchema: {
14581
- zod: (schema) => zodToJsonSchema(schema, {
14817
+ zod: (schema) => zodToJsonSchema2(schema, {
14582
14818
  $refStrategy: "none",
14583
14819
  target: "openApi3",
14584
14820
  override: jsonValueOpenApiOverride
@@ -14662,7 +14898,14 @@ function startApiServer(app, options) {
14662
14898
  const bunServer = Bun.serve({
14663
14899
  port: options.port,
14664
14900
  hostname: options.host,
14665
- 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
+ },
14666
14909
  websocket: getElysiaWsHandler(app)
14667
14910
  });
14668
14911
  attachBunServer(app, bunServer);
@@ -14683,4 +14926,4 @@ export {
14683
14926
  createSixbServer
14684
14927
  };
14685
14928
 
14686
- //# debugId=6D4551964DA2E95864756E2164756E21
14929
+ //# debugId=FAAE157E14B4AD2064756E2164756E21