@sixb/server 0.1.21 → 0.1.23

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 (165) hide show
  1. package/dist/artifacts/frame.d.ts +5 -0
  2. package/dist/artifacts/frame.d.ts.map +1 -1
  3. package/dist/auth/browser-origin.d.ts +5 -1
  4. package/dist/auth/browser-origin.d.ts.map +1 -1
  5. package/dist/auth/experience.d.ts +1 -0
  6. package/dist/auth/experience.d.ts.map +1 -1
  7. package/dist/auth/public-routes.d.ts.map +1 -1
  8. package/dist/auth/responses.d.ts +1 -1
  9. package/dist/auth/responses.d.ts.map +1 -1
  10. package/dist/auth/scope.d.ts +19 -3
  11. package/dist/auth/scope.d.ts.map +1 -1
  12. package/dist/index.js +10093 -7553
  13. package/dist/index.js.map +51 -39
  14. package/dist/models/display.d.ts +27 -0
  15. package/dist/models/display.d.ts.map +1 -1
  16. package/dist/openapi/components.d.ts +14 -0
  17. package/dist/openapi/components.d.ts.map +1 -0
  18. package/dist/openapi/tags.d.ts +14 -2
  19. package/dist/openapi/tags.d.ts.map +1 -1
  20. package/dist/registerRoutes.d.ts.map +1 -1
  21. package/dist/routes/actions.d.ts +5 -5
  22. package/dist/routes/agent-api-gateway.d.ts.map +1 -1
  23. package/dist/routes/agent-approval-gate.d.ts +27 -0
  24. package/dist/routes/agent-approval-gate.d.ts.map +1 -0
  25. package/dist/routes/agent-approvals.d.ts +599 -0
  26. package/dist/routes/agent-approvals.d.ts.map +1 -0
  27. package/dist/routes/agent-children.d.ts +318 -0
  28. package/dist/routes/agent-children.d.ts.map +1 -0
  29. package/dist/routes/agent-memory.d.ts +267 -0
  30. package/dist/routes/agent-memory.d.ts.map +1 -0
  31. package/dist/routes/agents.d.ts +999 -80
  32. package/dist/routes/agents.d.ts.map +1 -1
  33. package/dist/routes/ai-accounting.d.ts.map +1 -1
  34. package/dist/routes/artifact-frames.d.ts +3 -3
  35. package/dist/routes/artifact-frames.d.ts.map +1 -1
  36. package/dist/routes/artifacts.d.ts +790 -134
  37. package/dist/routes/artifacts.d.ts.map +1 -1
  38. package/dist/routes/auth.d.ts +116 -10
  39. package/dist/routes/auth.d.ts.map +1 -1
  40. package/dist/routes/connector-connection-runs.d.ts +50 -50
  41. package/dist/routes/connectors.d.ts +2 -2
  42. package/dist/routes/datasets.d.ts +20 -20
  43. package/dist/routes/events.d.ts +4 -4
  44. package/dist/routes/files.d.ts +14 -14
  45. package/dist/routes/files.d.ts.map +1 -1
  46. package/dist/routes/links.d.ts +2 -2
  47. package/dist/routes/logs.d.ts +5 -5
  48. package/dist/routes/model-calls.d.ts +155 -0
  49. package/dist/routes/model-calls.d.ts.map +1 -0
  50. package/dist/routes/model-generations.d.ts +400 -0
  51. package/dist/routes/model-generations.d.ts.map +1 -0
  52. package/dist/routes/models.d.ts +434 -1
  53. package/dist/routes/models.d.ts.map +1 -1
  54. package/dist/routes/objects.d.ts +71 -40
  55. package/dist/routes/objects.d.ts.map +1 -1
  56. package/dist/routes/observed-agent-threads.d.ts +682 -0
  57. package/dist/routes/observed-agent-threads.d.ts.map +1 -0
  58. package/dist/routes/ontology.d.ts +66 -62
  59. package/dist/routes/ontology.d.ts.map +1 -1
  60. package/dist/routes/pipelines.d.ts +24 -24
  61. package/dist/routes/projections.d.ts +55 -55
  62. package/dist/routes/rules.d.ts +2 -2
  63. package/dist/routes/share-grants.d.ts +9 -9
  64. package/dist/routes/syncs.d.ts +46 -46
  65. package/dist/routes/users.d.ts +117 -0
  66. package/dist/routes/users.d.ts.map +1 -0
  67. package/dist/routes/webhook-runs.d.ts +1 -1
  68. package/dist/routes/workflows.d.ts +118 -52
  69. package/dist/routes/workflows.d.ts.map +1 -1
  70. package/dist/routes/ws/agents.d.ts +7 -2
  71. package/dist/routes/ws/agents.d.ts.map +1 -1
  72. package/dist/routes/ws/events.d.ts +6 -6
  73. package/dist/routes/ws/logs.d.ts +14 -14
  74. package/dist/schemas/actions.d.ts +15 -15
  75. package/dist/schemas/activity.d.ts +48 -28
  76. package/dist/schemas/activity.d.ts.map +1 -1
  77. package/dist/schemas/agent-approvals.d.ts +1091 -0
  78. package/dist/schemas/agent-approvals.d.ts.map +1 -0
  79. package/dist/schemas/agent-memory.d.ts +250 -0
  80. package/dist/schemas/agent-memory.d.ts.map +1 -0
  81. package/dist/schemas/agents.d.ts +5442 -369
  82. package/dist/schemas/agents.d.ts.map +1 -1
  83. package/dist/schemas/ai-accounting.d.ts +1290 -411
  84. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  85. package/dist/schemas/ai-limits.d.ts +10 -10
  86. package/dist/schemas/ai-usage.d.ts +12 -0
  87. package/dist/schemas/ai-usage.d.ts.map +1 -1
  88. package/dist/schemas/artifacts.d.ts +650 -98
  89. package/dist/schemas/artifacts.d.ts.map +1 -1
  90. package/dist/schemas/auth.d.ts +119 -46
  91. package/dist/schemas/auth.d.ts.map +1 -1
  92. package/dist/schemas/connectors.d.ts +22 -22
  93. package/dist/schemas/datasets.d.ts +98 -98
  94. package/dist/schemas/event-payloads.d.ts +6 -6
  95. package/dist/schemas/events.d.ts +26 -26
  96. package/dist/schemas/events.d.ts.map +1 -1
  97. package/dist/schemas/files.d.ts +24 -24
  98. package/dist/schemas/links.d.ts +2 -2
  99. package/dist/schemas/logs.d.ts +32 -32
  100. package/dist/schemas/models.d.ts +8889 -10
  101. package/dist/schemas/models.d.ts.map +1 -1
  102. package/dist/schemas/objects.d.ts +48 -12
  103. package/dist/schemas/objects.d.ts.map +1 -1
  104. package/dist/schemas/ontology.d.ts +127 -104
  105. package/dist/schemas/ontology.d.ts.map +1 -1
  106. package/dist/schemas/pipelines.d.ts +132 -132
  107. package/dist/schemas/projections.d.ts +314 -314
  108. package/dist/schemas/rules.d.ts +4 -4
  109. package/dist/schemas/share-grants.d.ts +30 -30
  110. package/dist/schemas/syncs.d.ts +49 -49
  111. package/dist/schemas/users.d.ts +72 -0
  112. package/dist/schemas/users.d.ts.map +1 -0
  113. package/dist/schemas/webhook-runs.d.ts +6 -6
  114. package/dist/schemas/workflows.d.ts +701 -186
  115. package/dist/schemas/workflows.d.ts.map +1 -1
  116. package/dist/server.d.ts +1 -0
  117. package/dist/server.d.ts.map +1 -1
  118. package/dist/utils/http.d.ts.map +1 -1
  119. package/package.json +7 -7
  120. package/src/artifacts/frame.ts +6 -1
  121. package/src/auth/browser-origin.ts +8 -3
  122. package/src/auth/experience.ts +1 -1
  123. package/src/auth/guard.ts +2 -2
  124. package/src/auth/public-routes.ts +6 -0
  125. package/src/auth/responses.ts +7 -6
  126. package/src/auth/scope.ts +32 -3
  127. package/src/models/display.ts +61 -16
  128. package/src/openapi/components.ts +54 -0
  129. package/src/openapi/tags.ts +12 -0
  130. package/src/registerRoutes.ts +14 -0
  131. package/src/routes/agent-api-gateway.ts +115 -91
  132. package/src/routes/agent-approval-gate.ts +213 -0
  133. package/src/routes/agent-approvals.ts +299 -0
  134. package/src/routes/agent-children.ts +209 -0
  135. package/src/routes/agent-memory.ts +210 -0
  136. package/src/routes/agents.ts +363 -142
  137. package/src/routes/ai-accounting.ts +4 -0
  138. package/src/routes/artifact-frames.ts +14 -8
  139. package/src/routes/artifacts.ts +297 -22
  140. package/src/routes/auth.ts +306 -13
  141. package/src/routes/files.ts +6 -7
  142. package/src/routes/model-calls.ts +120 -0
  143. package/src/routes/model-generations.ts +245 -0
  144. package/src/routes/models.ts +116 -9
  145. package/src/routes/objects.ts +55 -61
  146. package/src/routes/observed-agent-threads.ts +253 -0
  147. package/src/routes/ontology.ts +1 -0
  148. package/src/routes/users.ts +73 -0
  149. package/src/routes/workflows.ts +6 -9
  150. package/src/routes/ws/agents.ts +10 -5
  151. package/src/schemas/activity.ts +2 -0
  152. package/src/schemas/agent-approvals.ts +129 -0
  153. package/src/schemas/agent-memory.ts +96 -0
  154. package/src/schemas/agents.ts +239 -0
  155. package/src/schemas/ai-accounting.ts +40 -4
  156. package/src/schemas/ai-usage.ts +10 -0
  157. package/src/schemas/artifacts.ts +91 -3
  158. package/src/schemas/auth.ts +25 -0
  159. package/src/schemas/models.ts +197 -1
  160. package/src/schemas/objects.ts +181 -0
  161. package/src/schemas/ontology.ts +1 -0
  162. package/src/schemas/users.ts +24 -0
  163. package/src/schemas/workflows.ts +2 -0
  164. package/src/server.ts +9 -10
  165. package/src/utils/http.ts +2 -0
@@ -18,6 +18,7 @@ import {
18
18
  type MagicLinkAuthStrategy,
19
19
  type MemberSummary,
20
20
  type OidcStartSignInResult,
21
+ type OwnProfile,
21
22
  SignInRefusedError,
22
23
  shouldUseSecureCookies,
23
24
  verifyCsrfToken,
@@ -58,6 +59,7 @@ import {
58
59
  import { OPENAPI_TAGS } from "../openapi/tags"
59
60
  import {
60
61
  AuthMemberParamsSchema,
62
+ AuthProfileResponseSchema,
61
63
  AuthServiceAccountParamsSchema,
62
64
  AuthSessionResponseSchema,
63
65
  AuthSignOutResponseSchema,
@@ -101,6 +103,7 @@ import {
101
103
  SuspendAuthMemberResponseSchema,
102
104
  UpdateAuthMemberGroupsBodySchema,
103
105
  UpdateAuthMemberGroupsResponseSchema,
106
+ UpdateAuthProfileBodySchema,
104
107
  } from "../schemas/auth"
105
108
  import { ErrorResponseSchema } from "../schemas/common"
106
109
  import { parseDate, parseOptionalInt, toIsoString } from "../utils/http"
@@ -343,6 +346,8 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
343
346
  "<h1>Authorize this device?</h1>",
344
347
  `<p><strong>${escapeHtml(authorization.clientName)}</strong> is requesting to sign in as you.</p>`,
345
348
  `<p>Code: <strong>${escapeHtml(authorization.userCode)}</strong></p>`,
349
+ // Whoever starts a request names it, so the code is what ties it to the user's device.
350
+ "<p>Authorize it only if you started this sign-in, and the device asking shows this same code.</p>",
346
351
  "<p>It stays signed in until you sign it out or it goes unused for a while.</p>",
347
352
  groups,
348
353
  '<form method="post" action="/auth/device">',
@@ -415,6 +420,138 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
415
420
  detail: { hide: true },
416
421
  }
417
422
  )
423
+ .get(
424
+ "/auth/sign-in/device",
425
+ async ({ request }) => {
426
+ const url = new URL(request.url)
427
+ const authRedirect = resolveAuthRedirectContext(options, request, {
428
+ returnTo: url.searchParams.get("returnTo"),
429
+ })
430
+ if (authRedirect instanceof Response) return authRedirect
431
+
432
+ const current = await host.auth.getSession(request)
433
+ if (current.authenticated) return redirectResponse(authRedirect.returnTo)
434
+
435
+ const storage = requireAuthStorage(host)
436
+ const now = new Date()
437
+ const deviceCode = getCookie(request, DEVICE_SIGN_IN_COOKIE_NAME)?.trim()
438
+ const id = deviceCode ? parseDeviceAuthorizationId(deviceCode) : null
439
+ const held = id
440
+ ? await storage.deviceAuthorizations.getById({ projectId: host.id, id })
441
+ : null
442
+ const authorization =
443
+ held && deviceCode && held.deviceCodeHash === hashDeviceCode(deviceCode) ? held : null
444
+ const clearCookie = deviceSignInCookieHeader({ request, host, value: "", maxAgeSeconds: 0 })
445
+
446
+ if (authorization?.status === "approved" && authorization.approvedUserId && deviceCode) {
447
+ const sessionCredential = createSessionCredential()
448
+ try {
449
+ const completed = await storage.completeDeviceAuthorization({
450
+ projectId: host.id,
451
+ id: authorization.id,
452
+ deviceCodeHash: hashDeviceCode(deviceCode),
453
+ completedAt: now,
454
+ session: {
455
+ id: sessionCredential.sessionId,
456
+ projectId: host.id,
457
+ userId: authorization.approvedUserId,
458
+ strategyId: "device",
459
+ tokenHash: sessionCredential.tokenHash,
460
+ createdAt: now,
461
+ ...host.auth.createSessionDeadlines(now),
462
+ ...resolveSessionDevice(request),
463
+ },
464
+ })
465
+ const response = sessionCallbackCompletionResponse({
466
+ host,
467
+ request,
468
+ apiOrigin: options.resolveAuthRequestOrigin(request),
469
+ sessionCredential,
470
+ expiresAt: completed.session.expiresAt,
471
+ returnTo: authRedirect.returnTo,
472
+ })
473
+ response.headers.append("set-cookie", clearCookie)
474
+ return response
475
+ } catch (error) {
476
+ if (
477
+ !(
478
+ error instanceof AuthStorageError &&
479
+ (error.code === "invalid_device_authorization" ||
480
+ error.code === "missing_device_authorization")
481
+ )
482
+ ) {
483
+ throw error
484
+ }
485
+ // Expired or removed since the approval; answer with the expired page below.
486
+ }
487
+ }
488
+
489
+ if (authorization?.status === "pending" && authorization.expiresAt > now) {
490
+ // The code in the URL is how an embedding shell learns which approval page to open. It
491
+ // is not a credential: the cookie is what ties this browser to the authorization.
492
+ if (url.searchParams.get("user_code") !== authorization.userCode) {
493
+ return redirectResponse(deviceSignInPath(url, authorization.userCode))
494
+ }
495
+ return deviceSignInPendingResponse(
496
+ authorization.userCode,
497
+ deviceVerificationUrl(options, request, authorization.userCode)
498
+ )
499
+ }
500
+
501
+ // A URL that still names a code belongs to an authorization this browser no longer holds.
502
+ // Stop here rather than start another: a page left open must not keep minting requests.
503
+ if (authorization || url.searchParams.has("user_code")) {
504
+ const response = authPageResponse(
505
+ [
506
+ authorization?.status === "denied"
507
+ ? "<h1>Sign-in was denied</h1>"
508
+ : "<h1>This sign-in request has expired</h1>",
509
+ `<p><a href="${escapeHtml(deviceSignInPath(url, null))}">Try again</a></p>`,
510
+ ].join(""),
511
+ 400
512
+ )
513
+ response.headers.append("set-cookie", clearCookie)
514
+ return response
515
+ }
516
+
517
+ if (
518
+ !deviceAuthorizationLimiter.tryConsume(getRequestClientAddress(request), now.getTime())
519
+ ) {
520
+ return authPageResponse("<h1>Too many sign-in requests</h1><p>Try again later.</p>", 429)
521
+ }
522
+ const client = CreateDeviceAuthorizationBodySchema.safeParse({
523
+ clientName: url.searchParams.get("client") ?? "",
524
+ })
525
+ const newId = `dva_${randomUUID()}`
526
+ const newDeviceCode = `${newId}.${randomBytes(32).toString("base64url")}`
527
+ const userCode = createDeviceUserCode()
528
+ try {
529
+ await storage.deviceAuthorizations.create({
530
+ id: newId,
531
+ projectId: host.id,
532
+ deviceCodeHash: hashDeviceCode(newDeviceCode),
533
+ userCode,
534
+ clientName: client.success ? client.data.clientName : "A web browser",
535
+ createdAt: now,
536
+ expiresAt: new Date(now.getTime() + DEVICE_AUTHORIZATION_TTL_MS),
537
+ })
538
+ } catch (error) {
539
+ return authRouteErrorResponse(error)
540
+ }
541
+ const response = redirectResponse(deviceSignInPath(url, userCode))
542
+ response.headers.append(
543
+ "set-cookie",
544
+ deviceSignInCookieHeader({
545
+ request,
546
+ host,
547
+ value: newDeviceCode,
548
+ maxAgeSeconds: DEVICE_AUTHORIZATION_TTL_MS / 1000,
549
+ })
550
+ )
551
+ return response
552
+ },
553
+ { detail: { hide: true } }
554
+ )
418
555
  .get(
419
556
  "/api/auth/session",
420
557
  async ({ request }) => {
@@ -601,6 +738,70 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
601
738
  },
602
739
  }
603
740
  )
741
+ .get(
742
+ "/api/auth/profile",
743
+ async (context) => {
744
+ const session = requireSessionCaller(context)
745
+ if (session instanceof Response) {
746
+ return session
747
+ }
748
+
749
+ try {
750
+ return jsonResponse(serializeOwnProfile(await host.auth.getProfile(session)), 200)
751
+ } catch (error) {
752
+ return authRouteErrorResponse(error)
753
+ }
754
+ },
755
+ {
756
+ response: {
757
+ 200: AuthProfileResponseSchema,
758
+ 401: ErrorResponseSchema,
759
+ 404: ErrorResponseSchema,
760
+ },
761
+ detail: {
762
+ summary: "Get the current user's profile",
763
+ tags: [OPENAPI_TAGS.authProfile.name],
764
+ operationId: "getAuthProfile",
765
+ },
766
+ }
767
+ )
768
+ .patch(
769
+ "/api/auth/profile",
770
+ async ({ body, ...context }) => {
771
+ const session = requireSessionCaller(context)
772
+ if (session instanceof Response) {
773
+ return session
774
+ }
775
+
776
+ try {
777
+ const changes = UpdateAuthProfileBodySchema.parse(body)
778
+ return jsonResponse(
779
+ serializeOwnProfile(await host.auth.updateProfile(session, changes)),
780
+ 200
781
+ )
782
+ } catch (error) {
783
+ return authRouteErrorResponse(error)
784
+ }
785
+ },
786
+ {
787
+ body: UpdateAuthProfileBodySchema,
788
+ response: {
789
+ 200: AuthProfileResponseSchema,
790
+ 400: ErrorResponseSchema,
791
+ 401: ErrorResponseSchema,
792
+ 403: ErrorResponseSchema,
793
+ 404: ErrorResponseSchema,
794
+ },
795
+ detail: {
796
+ summary: "Update the current user's name or picture",
797
+ description:
798
+ "Fields the identity provider manages, listed in `managedFields`, are refused with 403.",
799
+ tags: [OPENAPI_TAGS.authProfile.name],
800
+ operationId: "updateAuthProfile",
801
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
802
+ },
803
+ }
804
+ )
604
805
  .get(
605
806
  "/api/auth/access-management-options",
606
807
  async (context) => {
@@ -1432,6 +1633,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1432
1633
  // owns the validity rules (including token verification, so a bare
1433
1634
  // magicLinkId cannot disclose the account email).
1434
1635
  let email: string | undefined
1636
+ let firstSignIn = false
1435
1637
  if (strategy.peekMagicLink) {
1436
1638
  try {
1437
1639
  const peeked = await strategy.peekMagicLink({
@@ -1444,6 +1646,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1444
1646
  return await invalidMagicLinkResponse(options, authRedirectHint)
1445
1647
  }
1446
1648
  email = peeked.email
1649
+ firstSignIn = peeked.firstSignIn === true
1447
1650
  } catch (error) {
1448
1651
  logAuthCallbackError("Magic-link", error)
1449
1652
  return await authExperienceErrorResponse(options, authRedirectHint)
@@ -1454,16 +1657,17 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1454
1657
  // holds the preimage of the URL's `requester` hash, so it may sign in
1455
1658
  // straight from the navigation. Scanners and other browsers get the
1456
1659
  // confirmation page; POST /auth/callback completes the sign-in there.
1660
+ // A link that creates the account always shows it, to ask for a name.
1457
1661
  const requesterHash = url.searchParams.get("requester")?.trim()
1458
1662
  const pendingSecret = getCookie(request, MAGIC_LINK_PENDING_COOKIE_NAME)?.trim()
1459
1663
  if (
1664
+ !firstSignIn &&
1460
1665
  requesterHash &&
1461
1666
  pendingSecret &&
1462
1667
  matchesMagicLinkRequester(pendingSecret, requesterHash)
1463
1668
  ) {
1464
1669
  return completeMagicLinkCallback({
1465
1670
  host,
1466
- strategy,
1467
1671
  options,
1468
1672
  request,
1469
1673
  magicLinkId,
@@ -1477,6 +1681,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1477
1681
  magicLinkId,
1478
1682
  token,
1479
1683
  email,
1684
+ firstSignIn,
1480
1685
  authRedirect: authRedirectHint,
1481
1686
  })
1482
1687
  }
@@ -1494,9 +1699,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1494
1699
  "[SixbServer] OIDC callback reached a browser that did not start this sign-in."
1495
1700
  )
1496
1701
  }
1497
- const result = await strategy.completeOidcSignIn({
1498
- projectId: host.id,
1499
- authStorage: requireAuthStorage(host),
1702
+ const result = await host.auth.completeOidcSignIn({
1500
1703
  requestUrl: request.url,
1501
1704
  requestOrigin: options.resolveAuthRequestOrigin(request),
1502
1705
  session: {
@@ -1561,11 +1764,13 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1561
1764
 
1562
1765
  return completeMagicLinkCallback({
1563
1766
  host,
1564
- strategy,
1565
1767
  options,
1566
1768
  request,
1567
1769
  magicLinkId,
1568
1770
  token,
1771
+ displayName: body.displayName,
1772
+ // A link that creates the account is confirmed here even in the browser that asked for it.
1773
+ clearPendingCookie: getCookie(request, MAGIC_LINK_PENDING_COOKIE_NAME) !== undefined,
1569
1774
  authRedirectHint,
1570
1775
  })
1571
1776
  },
@@ -1573,6 +1778,8 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1573
1778
  body: t.Object({
1574
1779
  magicLinkId: t.Optional(t.String()),
1575
1780
  token: t.Optional(t.String()),
1781
+ // Asked on the confirmation page when the link creates an account.
1782
+ displayName: t.Optional(t.String()),
1576
1783
  }),
1577
1784
  parse: "urlencoded",
1578
1785
  detail: { hide: true },
@@ -1610,6 +1817,75 @@ function normalizeDeviceUserCode(value: string): string | null {
1610
1817
  return `${compact.slice(0, 4)}-${compact.slice(4)}`
1611
1818
  }
1612
1819
 
1820
+ // A browser that cannot finish a sign-in itself, such as one embedded in another program, waits on
1821
+ // GET /auth/sign-in/device while a browser the user is signed in to approves it at /auth/device.
1822
+ // This cookie holds its device code, so only the browser that started the request can collect the
1823
+ // session: a link to someone else's pending page arrives without it, and one's own approved code
1824
+ // cannot be planted in another browser.
1825
+ const DEVICE_SIGN_IN_COOKIE_NAME = "sixb_device"
1826
+
1827
+ // SameSite=Lax, not Strict: an embedding shell may send the browser here from the app's origin.
1828
+ function deviceSignInCookieHeader(params: {
1829
+ readonly request: Request
1830
+ readonly host: SixbHostView
1831
+ readonly value: string
1832
+ readonly maxAgeSeconds: number
1833
+ }): string {
1834
+ const parts = [
1835
+ `${DEVICE_SIGN_IN_COOKIE_NAME}=${params.value}`,
1836
+ "Path=/auth/sign-in/device",
1837
+ "SameSite=Lax",
1838
+ "HttpOnly",
1839
+ `Max-Age=${params.maxAgeSeconds}`,
1840
+ ]
1841
+ if (shouldUseSecureCookies(params.request, params.host.auth.getCookieOptions())) {
1842
+ parts.push("Secure")
1843
+ }
1844
+ return parts.join("; ")
1845
+ }
1846
+
1847
+ /** This page's own address, naming `userCode` or, with `null`, starting a new request. */
1848
+ function deviceSignInPath(url: URL, userCode: string | null): string {
1849
+ const next = new URL(url)
1850
+ if (userCode) next.searchParams.set("user_code", userCode)
1851
+ else next.searchParams.delete("user_code")
1852
+ return `${next.pathname}${next.search}`
1853
+ }
1854
+
1855
+ function deviceVerificationUrl(
1856
+ options: AuthRoutesOptions,
1857
+ request: Request,
1858
+ userCode: string
1859
+ ): string {
1860
+ const url = new URL("/auth/device", options.resolveAuthRequestOrigin(request))
1861
+ url.searchParams.set("user_code", userCode)
1862
+ return url.toString()
1863
+ }
1864
+
1865
+ // Reloads itself instead of polling from a script, so the page stays script-free like the other
1866
+ // auth pages; the reload that follows the approval is the request that signs the browser in.
1867
+ function deviceSignInPendingResponse(userCode: string, verificationUrl: string): Response {
1868
+ return new Response(
1869
+ authPageDocument(
1870
+ [
1871
+ "<h1>Continue in your browser</h1>",
1872
+ "<p>Approve this sign-in from a browser where you are signed in. This page continues on its own.</p>",
1873
+ `<p>Code: <strong>${escapeHtml(userCode)}</strong></p>`,
1874
+ `<p><a href="${escapeHtml(verificationUrl)}" target="_blank" rel="noopener">Open the approval page</a></p>`,
1875
+ ].join(""),
1876
+ "Sign in",
1877
+ `<meta http-equiv="refresh" content="${DEVICE_AUTHORIZATION_POLL_INTERVAL_SECONDS}">`
1878
+ ),
1879
+ {
1880
+ status: 200,
1881
+ headers: {
1882
+ "content-type": "text/html; charset=utf-8",
1883
+ "cache-control": "no-store",
1884
+ },
1885
+ }
1886
+ )
1887
+ }
1888
+
1613
1889
  // The pending cookie carries the preimage of the `requester` hash embedded in
1614
1890
  // the emailed callback URL. Only the browser that requested the link holds it,
1615
1891
  // so GET /auth/callback can distinguish that browser (sign in immediately) from
@@ -1670,11 +1946,11 @@ function callbackCookieHeader(params: {
1670
1946
  // path on GET. Consumes the single-use token and mints the session cookies.
1671
1947
  async function completeMagicLinkCallback(input: {
1672
1948
  readonly host: SixbHostView
1673
- readonly strategy: MagicLinkAuthStrategy
1674
1949
  readonly options: AuthRoutesOptions
1675
1950
  readonly request: Request
1676
1951
  readonly magicLinkId: string
1677
1952
  readonly token: string
1953
+ readonly displayName?: string
1678
1954
  readonly clearPendingCookie?: boolean
1679
1955
  readonly authRedirectHint?: AuthRedirectContext
1680
1956
  }): Promise<Response> {
@@ -1683,11 +1959,10 @@ async function completeMagicLinkCallback(input: {
1683
1959
  const device = resolveSessionDevice(input.request)
1684
1960
 
1685
1961
  try {
1686
- const result = await input.strategy.completeMagicLinkSignIn({
1687
- projectId: input.host.id,
1688
- authStorage: requireAuthStorage(input.host),
1962
+ const result = await input.host.auth.completeMagicLinkSignIn({
1689
1963
  magicLinkId: input.magicLinkId,
1690
1964
  token: input.token,
1965
+ displayName: input.displayName,
1691
1966
  session: {
1692
1967
  id: sessionCredential.sessionId,
1693
1968
  tokenHash: sessionCredential.tokenHash,
@@ -2054,7 +2329,8 @@ a {
2054
2329
  text-underline-offset: 0.2em;
2055
2330
  }
2056
2331
  form { margin: 1.75rem 0 0; }
2057
- input[type="email"] {
2332
+ input[type="email"],
2333
+ input[type="text"] {
2058
2334
  width: 100%;
2059
2335
  height: 2.5rem;
2060
2336
  padding: 0 0.875rem;
@@ -2065,8 +2341,10 @@ input[type="email"] {
2065
2341
  border: 1px solid var(--border);
2066
2342
  border-radius: calc(var(--radius) - 2px);
2067
2343
  }
2068
- input[type="email"]::placeholder { color: var(--muted-foreground); }
2069
- input[type="email"]:focus {
2344
+ input[type="email"]::placeholder,
2345
+ input[type="text"]::placeholder { color: var(--muted-foreground); }
2346
+ input[type="email"]:focus,
2347
+ input[type="text"]:focus {
2070
2348
  outline: none;
2071
2349
  border-color: var(--ring);
2072
2350
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--ring) 18%, transparent);
@@ -2245,12 +2523,18 @@ async function magicLinkConfirmResponse(
2245
2523
  readonly token: string
2246
2524
  // Absent when the strategy doesn't support the read-only peek.
2247
2525
  readonly email?: string
2526
+ // The link creates an account, so the page asks for the person's name.
2527
+ readonly firstSignIn: boolean
2248
2528
  readonly authRedirect?: AuthRedirectContext
2249
2529
  }
2250
2530
  ): Promise<Response> {
2251
2531
  if (input.authRedirect) {
2252
2532
  const custom = await customAuthExperienceResponse(options.authExperience, {
2253
- state: { kind: "confirm", ...(input.email ? { email: input.email } : {}) },
2533
+ state: {
2534
+ kind: "confirm",
2535
+ ...(input.email ? { email: input.email } : {}),
2536
+ ...(input.firstSignIn ? { firstSignIn: true } : {}),
2537
+ },
2254
2538
  signInUrl: authExperienceSignInUrl(input.authRedirect),
2255
2539
  submission: {
2256
2540
  kind: "confirmSignIn",
@@ -2278,6 +2562,11 @@ async function magicLinkConfirmResponse(
2278
2562
  '<form method="post" action="/auth/callback" id="confirm">',
2279
2563
  `<input type="hidden" name="magicLinkId" value="${escapeHtml(input.magicLinkId)}">`,
2280
2564
  `<input type="hidden" name="token" value="${escapeHtml(input.token)}">`,
2565
+ // The server drops a name it refuses here without a word, so the field stops at the limit.
2566
+ // Settings › Personal shows the server's error instead, so its field has no cap.
2567
+ input.firstSignIn
2568
+ ? '<input name="displayName" type="text" autocomplete="name" maxlength="100" placeholder="Your name (optional)" aria-label="Your name (optional)" autofocus>'
2569
+ : "",
2281
2570
  '<button type="submit" id="confirm-button">Continue</button>',
2282
2571
  "</form>",
2283
2572
  "<script>",
@@ -2473,6 +2762,10 @@ function serializeManagedMember(member: Omit<MemberSummary, "capabilities">) {
2473
2762
  }
2474
2763
  }
2475
2764
 
2765
+ function serializeOwnProfile(own: OwnProfile) {
2766
+ return { profile: own.profile, managedFields: [...own.managedFields] }
2767
+ }
2768
+
2476
2769
  function serializeMemberUser(user: UserRecord) {
2477
2770
  return {
2478
2771
  id: user.id,
@@ -3,7 +3,6 @@ import {
3
3
  DEFAULT_SIMPLE_FILE_UPLOAD_BYTES,
4
4
  type FileRef,
5
5
  type SixbHostView,
6
- SYSTEM_PRINCIPAL,
7
6
  } from "@sixb/core"
8
7
  import { computeBlobDigest, supportsDirectUpload } from "@sixb/core/blob-storage/server"
9
8
  import { canonicalMediaType } from "@sixb/core/internal/blob-storage"
@@ -11,7 +10,7 @@ import { createFileUploadId, createUploadExpiresAt } from "@sixb/core/internal/s
11
10
  import { type FileUploadSession, FileUploadSessionError } from "@sixb/core/storage"
12
11
  import type { Elysia } from "elysia"
13
12
  import { accessTokenSecurityRequirement } from "../auth/access-token-boundary"
14
- import { requireRequestSixb } from "../auth/scope"
13
+ import { requestActor, requireRequestSixb } from "../auth/scope"
15
14
  import { SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT } from "../openapi/security"
16
15
  import { OPENAPI_TAGS } from "../openapi/tags"
17
16
  import { ErrorResponseSchema, SuccessResponseSchema } from "../schemas/common"
@@ -124,7 +123,7 @@ export function registerFileRoutes(app: Elysia, host: SixbHostView) {
124
123
  return unconfiguredStorageResponse(set, "File upload session storage")
125
124
  }
126
125
  const parsed = CreateFileUploadBodySchema.parse(body)
127
- const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL
126
+ const principal = requestActor(requireRequestSixb(context))
128
127
  const uploadId = createFileUploadId()
129
128
  const expiresAt = createUploadExpiresAt()
130
129
  const expectedDigest = parsed.digest as BlobDigest | undefined
@@ -186,7 +185,7 @@ export function registerFileRoutes(app: Elysia, host: SixbHostView) {
186
185
  if (!uploadSessions) {
187
186
  return unconfiguredStorageResponse(set, "File upload session storage")
188
187
  }
189
- const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL
188
+ const principal = requestActor(requireRequestSixb(context))
190
189
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal)
191
190
  if (session.status !== "pending") {
192
191
  throw terminalSessionError(session.status)
@@ -279,7 +278,7 @@ export function registerFileRoutes(app: Elysia, host: SixbHostView) {
279
278
  if (!uploadSessions) {
280
279
  return unconfiguredStorageResponse(set, "File upload session storage")
281
280
  }
282
- const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL
281
+ const principal = requestActor(requireRequestSixb(context))
283
282
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal)
284
283
  if (session.status !== "pending") {
285
284
  throw terminalSessionError(session.status)
@@ -341,7 +340,7 @@ export function registerFileRoutes(app: Elysia, host: SixbHostView) {
341
340
  if (!uploadSessions) {
342
341
  return unconfiguredStorageResponse(set, "File upload session storage")
343
342
  }
344
- const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL
343
+ const principal = requestActor(requireRequestSixb(context))
345
344
  const parsed = CompleteFileUploadBodySchema.parse(body ?? {})
346
345
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal)
347
346
 
@@ -414,7 +413,7 @@ export function registerFileRoutes(app: Elysia, host: SixbHostView) {
414
413
  if (!uploadSessions) {
415
414
  return unconfiguredStorageResponse(set, "File upload session storage")
416
415
  }
417
- const principal = requireRequestSixb(context).execution.requestedBy ?? SYSTEM_PRINCIPAL
416
+ const principal = requestActor(requireRequestSixb(context))
418
417
  const session = await uploadSessions.getForPrincipal(params.uploadId, principal)
419
418
 
420
419
  if (session.status === "completed") {
@@ -0,0 +1,120 @@
1
+ import type { SixbHostView } from "@sixb/core"
2
+ import type { ModelCallFiles } from "@sixb/core/models"
3
+ import type { Elysia } from "elysia"
4
+ import { z } from "zod"
5
+ import { accessTokenSecurityRequirement } from "../auth/access-token-boundary"
6
+ import { requireRequestSixb } from "../auth/scope"
7
+ import {
8
+ createContextualFileContentResponse,
9
+ fileContentGetResponses,
10
+ fileContentHeadResponses,
11
+ handleFileContentQueryValidationError,
12
+ } from "../files/content"
13
+ import { OPENAPI_TAGS } from "../openapi/tags"
14
+ import { ErrorResponseSchema } from "../schemas/common"
15
+ import { FileContentQuerySchema } from "../schemas/files"
16
+ import { ModelCallFilesSchema, ModelCallParamsSchema } from "../schemas/models"
17
+ import { handleRouteError } from "../utils/http"
18
+
19
+ const ModelCallFileContentQuerySchema = FileContentQuerySchema.extend({
20
+ path: z
21
+ .string()
22
+ .min(1)
23
+ .regex(/^\/files(?:\/|$)/, "Model call file content paths must start with /files/"),
24
+ })
25
+
26
+ function serializeModelCallFiles(call: ModelCallFiles) {
27
+ return ModelCallFilesSchema.parse({
28
+ callId: call.callId,
29
+ files: call.files,
30
+ recordedAt: call.recordedAt.toISOString(),
31
+ })
32
+ }
33
+
34
+ async function modelCallFileContentResponse(
35
+ host: SixbHostView,
36
+ context: {
37
+ readonly params: { readonly callId: string }
38
+ readonly query: unknown
39
+ readonly request: Request
40
+ readonly set: { status?: number | string }
41
+ },
42
+ options: { readonly head?: boolean } = {}
43
+ ) {
44
+ const sixb = requireRequestSixb(context)
45
+ return createContextualFileContentResponse({
46
+ blobStorage: host.blobStorage,
47
+ query: context.query,
48
+ querySchema: ModelCallFileContentQuerySchema,
49
+ request: context.request,
50
+ set: context.set,
51
+ head: options.head,
52
+ resolveRoot: async () => {
53
+ const call = await sixb.models.calls.files(context.params.callId)
54
+ return call ? serializeModelCallFiles(call) : null
55
+ },
56
+ })
57
+ }
58
+
59
+ /** What a model call produced, as visible as the run that made it. */
60
+ export function registerModelCallRoutes(app: Elysia, host: SixbHostView) {
61
+ return app
62
+ .get(
63
+ "/api/ai/model-calls/:callId/files",
64
+ async (context) => {
65
+ const { params, set } = context
66
+ try {
67
+ const call = await requireRequestSixb(context).models.calls.files(params.callId)
68
+ if (!call) {
69
+ set.status = 404
70
+ return { error: "Model call not found" }
71
+ }
72
+ return serializeModelCallFiles(call)
73
+ } catch (error) {
74
+ return handleRouteError(error, set)
75
+ }
76
+ },
77
+ {
78
+ params: ModelCallParamsSchema,
79
+ response: { 200: ModelCallFilesSchema, 404: ErrorResponseSchema },
80
+ detail: {
81
+ summary: "Get the files a model call produced",
82
+ tags: [OPENAPI_TAGS.models.name],
83
+ operationId: "getAiModelCallFiles",
84
+ security: accessTokenSecurityRequirement("getAiModelCallFiles"),
85
+ },
86
+ }
87
+ )
88
+ .get(
89
+ "/api/ai/model-calls/:callId/files/content",
90
+ (context) => modelCallFileContentResponse(host, context),
91
+ {
92
+ params: ModelCallParamsSchema,
93
+ query: ModelCallFileContentQuerySchema,
94
+ error: handleFileContentQueryValidationError,
95
+ detail: {
96
+ summary: "Get model call file content",
97
+ tags: [OPENAPI_TAGS.models.name],
98
+ operationId: "getAiModelCallFileContent",
99
+ security: accessTokenSecurityRequirement("getAiModelCallFileContent"),
100
+ responses: fileContentGetResponses(),
101
+ },
102
+ }
103
+ )
104
+ .head(
105
+ "/api/ai/model-calls/:callId/files/content",
106
+ (context) => modelCallFileContentResponse(host, context, { head: true }),
107
+ {
108
+ params: ModelCallParamsSchema,
109
+ query: ModelCallFileContentQuerySchema,
110
+ error: handleFileContentQueryValidationError,
111
+ detail: {
112
+ summary: "Head model call file content",
113
+ tags: [OPENAPI_TAGS.models.name],
114
+ operationId: "headAiModelCallFileContent",
115
+ security: accessTokenSecurityRequirement("headAiModelCallFileContent"),
116
+ responses: fileContentHeadResponses(),
117
+ },
118
+ }
119
+ )
120
+ }