@sixb/server 0.1.12 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/access-token-boundary.d.ts +13 -9
  3. package/dist/auth/access-token-boundary.d.ts.map +1 -1
  4. package/dist/auth/client-address.d.ts +12 -0
  5. package/dist/auth/client-address.d.ts.map +1 -0
  6. package/dist/auth/guard.d.ts.map +1 -1
  7. package/dist/auth/public-routes.d.ts +5 -0
  8. package/dist/auth/public-routes.d.ts.map +1 -1
  9. package/dist/auth/rate-limit.d.ts +15 -0
  10. package/dist/auth/rate-limit.d.ts.map +1 -0
  11. package/dist/auth/scope.d.ts +8 -3
  12. package/dist/auth/scope.d.ts.map +1 -1
  13. package/dist/auth/shared-access.d.ts.map +1 -1
  14. package/dist/index.js +578 -455
  15. package/dist/index.js.map +40 -38
  16. package/dist/openapi/security.d.ts +34 -10
  17. package/dist/openapi/security.d.ts.map +1 -1
  18. package/dist/routes/auth.d.ts +64 -17
  19. package/dist/routes/auth.d.ts.map +1 -1
  20. package/dist/routes/connectors.d.ts.map +1 -1
  21. package/dist/routes/events.d.ts +0 -4
  22. package/dist/routes/events.d.ts.map +1 -1
  23. package/dist/routes/files.d.ts +15 -2
  24. package/dist/routes/files.d.ts.map +1 -1
  25. package/dist/routes/models.d.ts +7 -7
  26. package/dist/routes/ontology.d.ts +13 -1
  27. package/dist/routes/ontology.d.ts.map +1 -1
  28. package/dist/routes/shared-access.d.ts.map +1 -1
  29. package/dist/routes/workflows.d.ts +30 -30
  30. package/dist/routes/workflows.d.ts.map +1 -1
  31. package/dist/routes/ws/agents.d.ts +2 -3
  32. package/dist/routes/ws/agents.d.ts.map +1 -1
  33. package/dist/schemas/auth.d.ts +241 -85
  34. package/dist/schemas/auth.d.ts.map +1 -1
  35. package/dist/schemas/common.d.ts +11 -0
  36. package/dist/schemas/common.d.ts.map +1 -1
  37. package/dist/schemas/events.d.ts +74 -44
  38. package/dist/schemas/events.d.ts.map +1 -1
  39. package/dist/schemas/models.d.ts +38 -38
  40. package/dist/schemas/ontology.d.ts +160 -0
  41. package/dist/schemas/ontology.d.ts.map +1 -1
  42. package/dist/schemas/workflows.d.ts +180 -190
  43. package/dist/schemas/workflows.d.ts.map +1 -1
  44. package/dist/server.d.ts +6 -0
  45. package/dist/server.d.ts.map +1 -1
  46. package/dist/utils/ws.d.ts +1 -2
  47. package/dist/utils/ws.d.ts.map +1 -1
  48. package/package.json +4 -4
  49. package/src/auth/access-token-boundary.ts +31 -30
  50. package/src/auth/client-address.ts +67 -0
  51. package/src/auth/guard.ts +13 -4
  52. package/src/auth/public-routes.ts +9 -2
  53. package/src/auth/rate-limit.ts +43 -0
  54. package/src/auth/scope.ts +13 -3
  55. package/src/auth/shared-access.ts +0 -3
  56. package/src/openapi/security.ts +37 -17
  57. package/src/routes/action-runs.ts +5 -5
  58. package/src/routes/actions.ts +4 -4
  59. package/src/routes/agents.ts +9 -9
  60. package/src/routes/ai-accounting.ts +10 -10
  61. package/src/routes/auth.ts +331 -432
  62. package/src/routes/connector-connection-runs.ts +5 -5
  63. package/src/routes/connector-connections.ts +3 -3
  64. package/src/routes/connectors.ts +2 -2
  65. package/src/routes/events.ts +2 -2
  66. package/src/routes/files.ts +30 -15
  67. package/src/routes/links.ts +3 -3
  68. package/src/routes/logs.ts +2 -2
  69. package/src/routes/objects.ts +12 -12
  70. package/src/routes/ontology.ts +27 -9
  71. package/src/routes/pipelines.ts +2 -2
  72. package/src/routes/project.ts +2 -2
  73. package/src/routes/share-grants.ts +4 -4
  74. package/src/routes/shared-access.ts +3 -2
  75. package/src/routes/syncs.ts +2 -2
  76. package/src/routes/telemetry.ts +5 -5
  77. package/src/routes/workflows.ts +18 -19
  78. package/src/routes/ws/agents.ts +4 -5
  79. package/src/schemas/auth.ts +27 -8
  80. package/src/schemas/common.ts +6 -0
  81. package/src/schemas/events.ts +35 -7
  82. package/src/schemas/ontology.ts +16 -1
  83. package/src/schemas/workflows.ts +4 -9
  84. package/src/server.ts +35 -5
  85. package/src/utils/ws.ts +2 -3
@@ -1,23 +1,29 @@
1
1
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"
2
- import type { AuthSessionAudience, GroupDefinition, SixbHostView } from "@sixb/core"
3
2
  import {
3
+ type AuthSessionAudience,
4
+ DEFAULT_AUTH_SESSION_AUDIENCE,
5
+ type GroupDefinition,
6
+ type SixbHostView,
7
+ } from "@sixb/core"
8
+ import {
9
+ type AuthenticatedAuthSession,
4
10
  type AuthenticatedUserRequestSession,
5
- type AuthRequestResult,
6
11
  AuthRuntimeError,
7
12
  clearCsrfCookieHeader,
8
13
  clearSessionCookieHeader,
9
- createAccessTokenCredential,
10
14
  createCsrfCookieHeader,
11
15
  createSessionCookieHeader,
12
16
  createSessionCredential,
13
17
  generateCsrfToken,
14
18
  getCookie,
19
+ getRequestClientAddress,
15
20
  type InviteDeliveryResult,
16
21
  isMagicLinkAuthStrategy,
17
22
  isOidcAuthStrategy,
18
23
  type MagicLinkAuthStrategy,
19
24
  type MemberSummary,
20
25
  shouldUseSecureCookies,
26
+ verifyCsrfToken,
21
27
  verifyDoubleSubmitCsrf,
22
28
  } from "@sixb/core/internal/auth"
23
29
  import {
@@ -29,7 +35,7 @@ import {
29
35
  type UserRecord,
30
36
  } from "@sixb/core/storage"
31
37
  import { type Elysia, t } from "elysia"
32
- import { bearerSecurityRequirement } from "../auth/access-token-boundary"
38
+ import { accessTokenSecurityRequirement } from "../auth/access-token-boundary"
33
39
  import { sessionCanAccessApplication } from "../auth/application-access"
34
40
  import {
35
41
  type AuthInvitationDestinationOptions,
@@ -46,15 +52,22 @@ import {
46
52
  customAuthExperienceResponse,
47
53
  type SixbAuthExperienceOptions,
48
54
  } from "../auth/experience"
55
+ import { ClientAddressRateLimiter } from "../auth/rate-limit"
56
+ import { requestCaller } from "../auth/scope"
49
57
  import { hasForegroundSessionActivity } from "../auth/session-activity"
50
58
  import { createSessionRenewalCookieHeaders } from "../auth/session-cookies"
51
- import { SIXB_CSRF_SECURITY_REQUIREMENT } from "../openapi/security"
59
+ import {
60
+ SIXB_OPTIONAL_SESSION_MUTATION_SECURITY_REQUIREMENT,
61
+ SIXB_OPTIONAL_SESSION_SECURITY_REQUIREMENT,
62
+ SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
63
+ } from "../openapi/security"
52
64
  import { OPENAPI_TAGS } from "../openapi/tags"
53
65
  import {
54
66
  AuthMemberParamsSchema,
55
67
  AuthServiceAccountParamsSchema,
56
68
  AuthSessionResponseSchema,
57
69
  AuthSignOutResponseSchema,
70
+ BearerSessionTokensSchema,
58
71
  CreateAuthInvitationBodySchema,
59
72
  CreateAuthInvitationResponseSchema,
60
73
  CreateAuthPersonalAccessTokenBodySchema,
@@ -81,6 +94,7 @@ import {
81
94
  ListAuthServiceAccountsResponseSchema,
82
95
  ListAuthSessionsResponseSchema,
83
96
  ReactivateAuthMemberResponseSchema,
97
+ RefreshAuthSessionBodySchema,
84
98
  RevokeAuthAccessTokenParamsSchema,
85
99
  RevokeAuthAccessTokenResponseSchema,
86
100
  RevokeAuthInvitationParamsSchema,
@@ -131,6 +145,10 @@ export interface AuthRoutesOptions {
131
145
  }
132
146
 
133
147
  export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: AuthRoutesOptions) {
148
+ const deviceAuthorizationLimiter = new ClientAddressRateLimiter(
149
+ DEVICE_AUTHORIZATIONS_PER_ADDRESS,
150
+ DEVICE_AUTHORIZATION_TTL_MS
151
+ )
134
152
  return app
135
153
  .get(
136
154
  "/auth/assets/*",
@@ -147,6 +165,19 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
147
165
  async ({ body, request }) => {
148
166
  const parsed = CreateDeviceAuthorizationBodySchema.parse(body)
149
167
  const now = new Date()
168
+ // Creation is unauthenticated and the project-wide pending cap is shared, so one address
169
+ // must not be able to fill it.
170
+ if (
171
+ !deviceAuthorizationLimiter.tryConsume(getRequestClientAddress(request), now.getTime())
172
+ ) {
173
+ return jsonResponse(
174
+ {
175
+ error:
176
+ "[SixbServer] Too many device authorizations from this address. Try again later.",
177
+ },
178
+ 429
179
+ )
180
+ }
150
181
  const id = `dva_${randomUUID()}`
151
182
  const deviceCode = `${id}.${randomBytes(32).toString("base64url")}`
152
183
  const userCode = createDeviceUserCode()
@@ -158,8 +189,6 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
158
189
  deviceCodeHash: hashDeviceCode(deviceCode),
159
190
  userCode,
160
191
  clientName: parsed.clientName,
161
- tokenName: parsed.tokenName,
162
- tokenExpiresAt: new Date(now.getTime() + DEVICE_ACCESS_TOKEN_TTL_MS),
163
192
  createdAt: now,
164
193
  expiresAt,
165
194
  })
@@ -191,12 +220,13 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
191
220
  summary: "Start device authorization",
192
221
  tags: [OPENAPI_TAGS.authSessions.name],
193
222
  operationId: "createDeviceAuthorization",
223
+ security: [],
194
224
  },
195
225
  }
196
226
  )
197
227
  .post(
198
228
  "/api/auth/device-authorizations/token",
199
- async ({ body }) => {
229
+ async ({ body, request }) => {
200
230
  const { deviceCode } = ExchangeDeviceAuthorizationBodySchema.parse(body)
201
231
  const id = parseDeviceAuthorizationId(deviceCode)
202
232
  if (!id) return jsonResponse({ status: "expired" as const }, 200)
@@ -223,26 +253,18 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
223
253
  if (!authorization.approvedUserId || !authorization.approvedSessionId) {
224
254
  return jsonResponse({ status: "expired" as const }, 200)
225
255
  }
226
- const credential = createAccessTokenCredential("personal")
256
+ const { session, tokens } = host.auth.prepareBearerSession({
257
+ userId: authorization.approvedUserId,
258
+ clientName: authorization.clientName,
259
+ now,
260
+ })
227
261
  try {
228
262
  await storage.completeDeviceAuthorization({
229
263
  projectId: host.id,
230
264
  id,
231
265
  deviceCodeHash: hashDeviceCode(deviceCode),
232
266
  completedAt: now,
233
- accessToken: {
234
- id: credential.tokenId,
235
- projectId: host.id,
236
- name: authorization.tokenName,
237
- kind: "personal",
238
- subjectType: "user",
239
- subjectId: authorization.approvedUserId,
240
- tokenHash: credential.tokenHash,
241
- createdByPrincipal: { type: "user", id: authorization.approvedUserId },
242
- createdBySessionId: authorization.approvedSessionId,
243
- createdAt: now,
244
- expiresAt: authorization.tokenExpiresAt,
245
- },
267
+ session: { ...session, ...resolveSessionDevice(request) },
246
268
  })
247
269
  } catch (error) {
248
270
  if (error instanceof AuthStorageError && error.code === "invalid_device_authorization") {
@@ -251,7 +273,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
251
273
  throw error
252
274
  }
253
275
  return jsonResponse(
254
- { status: "approved" as const, accessToken: credential.tokenValue },
276
+ { status: "approved" as const, ...bearerTokensBody(tokens, session.bearer, now) },
255
277
  200
256
278
  )
257
279
  },
@@ -262,6 +284,29 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
262
284
  summary: "Exchange an approved device authorization",
263
285
  tags: [OPENAPI_TAGS.authSessions.name],
264
286
  operationId: "exchangeDeviceAuthorization",
287
+ security: [],
288
+ },
289
+ }
290
+ )
291
+ .post(
292
+ "/api/auth/refresh",
293
+ async ({ body }) => {
294
+ const { refreshToken } = RefreshAuthSessionBodySchema.parse(body)
295
+ const refreshed = await host.auth.refreshSession(refreshToken)
296
+ const bearer = refreshed?.session.bearer
297
+ if (!refreshed || !bearer?.refreshedAt) {
298
+ return jsonResponse({ error: "Invalid refresh token" }, 401)
299
+ }
300
+ return jsonResponse(bearerTokensBody(refreshed.tokens, bearer, bearer.refreshedAt), 200)
301
+ },
302
+ {
303
+ body: RefreshAuthSessionBodySchema,
304
+ response: { 200: BearerSessionTokensSchema, 401: ErrorResponseSchema },
305
+ detail: {
306
+ summary: "Refresh a native client's session tokens",
307
+ tags: [OPENAPI_TAGS.authSessions.name],
308
+ operationId: "refreshAuthSession",
309
+ security: [],
265
310
  },
266
311
  }
267
312
  )
@@ -309,10 +354,9 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
309
354
  const response = authPageResponse(
310
355
  [
311
356
  "<h1>Authorize this device?</h1>",
312
- `<p><strong>${escapeHtml(authorization.clientName)}</strong> is requesting access.</p>`,
357
+ `<p><strong>${escapeHtml(authorization.clientName)}</strong> is requesting to sign in as you.</p>`,
313
358
  `<p>Code: <strong>${escapeHtml(authorization.userCode)}</strong></p>`,
314
- `<p>Token: ${escapeHtml(authorization.tokenName)}</p>`,
315
- `<p>Expires: ${escapeHtml(authorization.tokenExpiresAt.toLocaleDateString("en-US"))}</p>`,
359
+ "<p>It stays signed in until you sign it out or it goes unused for a while.</p>",
316
360
  groups,
317
361
  '<form method="post" action="/auth/device">',
318
362
  `<input type="hidden" name="userCode" value="${escapeHtml(userCode)}">`,
@@ -333,20 +377,10 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
333
377
  const parsed = DeviceAuthorizationDecisionBodySchema.parse(body)
334
378
  const authOptions = resolveAuthOptions(options, request)
335
379
  const session = await host.auth.getSession(request, authOptions)
380
+ // Every signed-in user may approve their own CLI login, whichever web app they may open.
336
381
  if (!session.authenticated) return authPageResponse("<h1>Authentication required</h1>", 401)
337
- if (!sessionCanAccessApplication(host, session, authOptions.audience)) {
338
- return authPageResponse("<h1>Access denied</h1>", 403)
339
- }
340
- const csrfHeaders = new Headers(request.headers)
341
- csrfHeaders.set("x-sixb-csrf", parsed.csrfToken)
342
- if (
343
- !verifyDoubleSubmitCsrf(
344
- new Request(request.url, { method: "POST", headers: csrfHeaders }),
345
- {
346
- cookieName: host.auth.getCookieOptions(authOptions).csrfCookieName,
347
- }
348
- )
349
- ) {
382
+ const csrfCookieName = host.auth.getCookieOptions(authOptions).csrfCookieName
383
+ if (!verifyCsrfToken(request, { cookieName: csrfCookieName, token: parsed.csrfToken })) {
350
384
  return authPageResponse("<h1>Invalid authorization request</h1>", 403)
351
385
  }
352
386
  const storage = requireAuthStorage(host)
@@ -355,22 +389,35 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
355
389
  userCode: parsed.userCode,
356
390
  })
357
391
  if (!authorization) return authPageResponse("<h1>Invalid authorization</h1>", 400)
358
- if (parsed.decision === "approve") {
359
- await storage.deviceAuthorizations.approve({
360
- projectId: host.id,
361
- id: authorization.id,
362
- userId: session.user.id,
363
- sessionId: session.session.id,
364
- approvedAt: new Date(),
365
- })
366
- return authPageResponse("<h1>Device authorized</h1><p>You can close this window.</p>")
392
+ const decidedAt = new Date()
393
+ try {
394
+ if (parsed.decision === "approve") {
395
+ await storage.deviceAuthorizations.approve({
396
+ projectId: host.id,
397
+ id: authorization.id,
398
+ userId: session.user.id,
399
+ sessionId: session.session.id,
400
+ approvedAt: decidedAt,
401
+ })
402
+ } else {
403
+ await storage.deviceAuthorizations.deny({
404
+ projectId: host.id,
405
+ id: authorization.id,
406
+ deniedAt: decidedAt,
407
+ })
408
+ }
409
+ } catch (error) {
410
+ // The authorization expired or was decided after this page rendered.
411
+ if (error instanceof AuthStorageError && error.code === "invalid_device_authorization") {
412
+ return authPageResponse("<h1>This authorization has expired</h1>", 400)
413
+ }
414
+ throw error
367
415
  }
368
- await storage.deviceAuthorizations.deny({
369
- projectId: host.id,
370
- id: authorization.id,
371
- deniedAt: new Date(),
372
- })
373
- return authPageResponse("<h1>Authorization denied</h1><p>You can close this window.</p>")
416
+ return authPageResponse(
417
+ parsed.decision === "approve"
418
+ ? "<h1>Device authorized</h1><p>You can close this window.</p>"
419
+ : "<h1>Authorization denied</h1><p>You can close this window.</p>"
420
+ )
374
421
  },
375
422
  {
376
423
  body: t.Object({
@@ -386,29 +433,26 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
386
433
  "/api/auth/session",
387
434
  async ({ request }) => {
388
435
  const authOptions = resolveAuthOptions(options, request)
389
- let session = await host.auth.getSession(request, authOptions)
390
- if (!session.authenticated) {
436
+ const caller = await host.auth.getSession(request, {
437
+ ...authOptions,
438
+ credentialSource: "any",
439
+ })
440
+ // Access tokens are not sessions; a native client's session has no cookies to renew.
441
+ if (!caller.authenticated || caller.credentialSource !== "session") {
391
442
  return jsonResponse({ authenticated: false as const }, 200)
392
443
  }
444
+ // A native client belongs to no web app; tell it whether its user may open Atlas.
445
+ if (caller.session.bearer) {
446
+ return jsonResponse(authSessionBody(host, caller, DEFAULT_AUTH_SESSION_AUDIENCE), 200)
447
+ }
393
448
 
394
- let applicationAccessAllowed = sessionCanAccessApplication(
395
- host,
396
- session,
397
- authOptions.audience
398
- )
399
- if (applicationAccessAllowed && hasForegroundSessionActivity(request)) {
400
- session = await host.auth.getSession(request, {
401
- ...authOptions,
402
- sessionActivity: "foreground",
403
- })
404
- if (!session.authenticated) {
405
- return jsonResponse({ authenticated: false as const }, 200)
406
- }
407
- applicationAccessAllowed = sessionCanAccessApplication(
408
- host,
409
- session,
410
- authOptions.audience
411
- )
449
+ const session =
450
+ hasForegroundSessionActivity(request) &&
451
+ sessionCanAccessApplication(host, caller, authOptions.audience)
452
+ ? await host.auth.getSession(request, { ...authOptions, sessionActivity: "foreground" })
453
+ : caller
454
+ if (!session.authenticated) {
455
+ return jsonResponse({ authenticated: false as const }, 200)
412
456
  }
413
457
 
414
458
  const cookieOptions = host.auth.getCookieOptions(authOptions)
@@ -427,25 +471,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
427
471
  })
428
472
  : null
429
473
  return authSessionJsonResponse(
430
- {
431
- authenticated: true as const,
432
- csrfToken: csrf.token,
433
- applicationAccess: {
434
- allowed: applicationAccessAllowed,
435
- audience: authOptions.audience,
436
- },
437
- user: {
438
- id: session.user.id,
439
- email: session.user.email,
440
- displayName: session.user.displayName,
441
- avatarUrl: session.user.avatarUrl,
442
- groupIds: [...session.groupIds],
443
- },
444
- session: {
445
- id: session.session.id,
446
- expiresAt: toIsoString(session.session.expiresAt),
447
- },
448
- },
474
+ { ...authSessionBody(host, session, authOptions.audience), csrfToken: csrf.token },
449
475
  renewal?.headers ?? (csrf.setCookie ? [csrf.setCookie] : [])
450
476
  )
451
477
  },
@@ -455,6 +481,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
455
481
  summary: "Get current auth session",
456
482
  tags: [OPENAPI_TAGS.authSessions.name],
457
483
  operationId: "getAuthSession",
484
+ security: SIXB_OPTIONAL_SESSION_SECURITY_REQUIREMENT,
458
485
  },
459
486
  }
460
487
  )
@@ -462,10 +489,17 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
462
489
  "/api/auth/sign-out",
463
490
  async ({ request }) => {
464
491
  const authOptions = resolveAuthOptions(options, request)
465
- const session = await host.auth.getSession(request, authOptions)
492
+ const result = await host.auth.getSession(request, {
493
+ ...authOptions,
494
+ credentialSource: "any",
495
+ })
496
+ // Access tokens are not sessions; revoke those through their own route.
497
+ const session =
498
+ result.authenticated && result.credentialSource === "session" ? result : null
466
499
  const cookieOptions = host.auth.getCookieOptions(authOptions)
467
500
  if (
468
- session.authenticated &&
501
+ session &&
502
+ !session.session.bearer &&
469
503
  !verifyDoubleSubmitCsrf(request, {
470
504
  cookieName: cookieOptions.csrfCookieName,
471
505
  })
@@ -473,24 +507,11 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
473
507
  return jsonResponse({ error: "CSRF verification failed" }, 403)
474
508
  }
475
509
 
476
- if (session.authenticated) {
477
- await host.storage.auth?.sessions.revoke({
478
- projectId: host.id,
479
- id: session.session.id,
480
- revokedAt: new Date(),
481
- })
482
- // Drop the cached session immediately so it isn't honored for the cache TTL.
483
- host.auth.invalidateSession(session.session.id)
510
+ if (session) {
511
+ await host.auth.revokeSession(session, session.session.id)
484
512
  }
485
513
 
486
- const headers = new Headers({ "content-type": "application/json; charset=utf-8" })
487
- headers.append("set-cookie", clearSessionCookieHeader({ request, options: cookieOptions }))
488
- headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }))
489
-
490
- return new Response(JSON.stringify({ success: true }), {
491
- status: 200,
492
- headers,
493
- })
514
+ return signedOutResponse(request, cookieOptions, { success: true })
494
515
  },
495
516
  {
496
517
  response: {
@@ -501,36 +522,31 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
501
522
  summary: "Sign out current auth session",
502
523
  tags: [OPENAPI_TAGS.authSessions.name],
503
524
  operationId: "signOut",
504
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
525
+ security: SIXB_OPTIONAL_SESSION_MUTATION_SECURITY_REQUIREMENT,
505
526
  },
506
527
  }
507
528
  )
508
529
  .get(
509
530
  "/api/auth/sessions",
510
- async ({ request }) => {
511
- const authOptions = resolveAuthOptions(options, request)
512
- const session = await host.auth.getSession(request, authOptions)
513
- if (!session.authenticated) {
514
- return jsonResponse({ error: "Authentication required" }, 401)
531
+ async (context) => {
532
+ const session = requireSessionCaller(context)
533
+ if (session instanceof Response) {
534
+ return session
515
535
  }
516
536
 
517
- const sessions = await requireAuthStorage(host).sessions.listActiveByUserId({
518
- projectId: host.id,
519
- userId: session.user.id,
520
- now: new Date(),
521
- })
522
-
537
+ const sessions = await host.auth.listSessions(session)
523
538
  return jsonResponse(
524
539
  {
525
540
  sessions: sessions.map((entry) => ({
526
541
  id: entry.id,
527
- audience: entry.audience,
542
+ audience: entry.bearer ? undefined : entry.audience,
528
543
  current: entry.id === session.session.id,
529
544
  createdAt: toIsoString(entry.createdAt),
530
545
  expiresAt: toIsoString(entry.expiresAt),
531
546
  lastSeenAt: entry.lastSeenAt ? toIsoString(entry.lastSeenAt) : undefined,
532
547
  userAgent: entry.userAgent,
533
548
  ipAddress: entry.ipAddress,
549
+ clientName: entry.bearer?.clientName,
534
550
  })),
535
551
  },
536
552
  200
@@ -550,40 +566,22 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
550
566
  )
551
567
  .post(
552
568
  "/api/auth/sessions/:sessionId/revoke",
553
- async ({ request, params }) => {
554
- const authOptions = resolveAuthOptions(options, request)
555
- const session = await host.auth.getSession(request, authOptions)
556
- const cookieOptions = host.auth.getCookieOptions(authOptions)
557
- if (!session.authenticated) {
558
- return jsonResponse({ error: "Authentication required" }, 401)
559
- }
560
- if (!verifyDoubleSubmitCsrf(request, { cookieName: cookieOptions.csrfCookieName })) {
561
- return jsonResponse({ error: "CSRF verification failed" }, 403)
569
+ async ({ request, params, ...context }) => {
570
+ const session = requireSessionCaller(context)
571
+ if (session instanceof Response) {
572
+ return session
562
573
  }
563
574
 
564
575
  const { sessionId } = RevokeAuthSessionParamsSchema.parse(params)
565
- const storage = requireAuthStorage(host)
566
- const target = await storage.sessions.getById({ projectId: host.id, id: sessionId })
567
- // Only the caller's own sessions are revocable. A missing or foreign
568
- // session id returns the same 404 so it cannot probe other accounts.
569
- if (!target || target.userId !== session.user.id) {
576
+ if (!(await host.auth.revokeSession(session, sessionId))) {
570
577
  return jsonResponse({ error: "Session not found" }, 404)
571
578
  }
572
579
 
573
- await storage.sessions.revoke({ projectId: host.id, id: sessionId, revokedAt: new Date() })
574
- host.auth.invalidateSession(sessionId)
575
-
576
- const headers = new Headers({ "content-type": "application/json; charset=utf-8" })
577
- // Revoking the session backing this request also clears its cookies.
578
- if (sessionId === session.session.id) {
579
- headers.append(
580
- "set-cookie",
581
- clearSessionCookieHeader({ request, options: cookieOptions })
582
- )
583
- headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }))
580
+ if (sessionId !== session.session.id) {
581
+ return jsonResponse({ success: true }, 200)
584
582
  }
585
-
586
- return new Response(JSON.stringify({ success: true }), { status: 200, headers })
583
+ const cookieOptions = host.auth.getCookieOptions(resolveAuthOptions(options, request))
584
+ return signedOutResponse(request, cookieOptions, { success: true })
587
585
  },
588
586
  {
589
587
  params: RevokeAuthSessionParamsSchema,
@@ -597,43 +595,23 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
597
595
  summary: "Revoke one of the current user's sessions",
598
596
  tags: [OPENAPI_TAGS.authSessions.name],
599
597
  operationId: "revokeAuthSession",
600
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
598
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
601
599
  },
602
600
  }
603
601
  )
604
602
  .post(
605
603
  "/api/auth/sign-out-all",
606
- async ({ request }) => {
607
- const authOptions = resolveAuthOptions(options, request)
608
- const session = await host.auth.getSession(request, authOptions)
609
- const cookieOptions = host.auth.getCookieOptions(authOptions)
610
- if (!session.authenticated) {
611
- return jsonResponse({ error: "Authentication required" }, 401)
612
- }
613
- if (!verifyDoubleSubmitCsrf(request, { cookieName: cookieOptions.csrfCookieName })) {
614
- return jsonResponse({ error: "CSRF verification failed" }, 403)
615
- }
616
-
617
- // Global sign-out: revoke every active session for the user across all
618
- // audiences. Other audiences' cookies remain client-side but their
619
- // sessions are revoked, so the next request re-authenticates.
620
- const revoked = await requireAuthStorage(host).sessions.revokeActiveForUser({
621
- projectId: host.id,
622
- userId: session.user.id,
623
- revokedAt: new Date(),
624
- })
625
- for (const revokedSession of revoked) {
626
- host.auth.invalidateSession(revokedSession.id)
604
+ async ({ request, ...context }) => {
605
+ const session = requireSessionCaller(context)
606
+ if (session instanceof Response) {
607
+ return session
627
608
  }
628
609
 
629
- const headers = new Headers({ "content-type": "application/json; charset=utf-8" })
630
- headers.append("set-cookie", clearSessionCookieHeader({ request, options: cookieOptions }))
631
- headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }))
632
-
633
- return new Response(JSON.stringify({ success: true, revokedCount: revoked.length }), {
634
- status: 200,
635
- headers,
636
- })
610
+ // Other audiences' cookies stay in their browsers, but their sessions are revoked, so the
611
+ // next request there re-authenticates.
612
+ const revokedCount = await host.auth.revokeAllSessions(session)
613
+ const cookieOptions = host.auth.getCookieOptions(resolveAuthOptions(options, request))
614
+ return signedOutResponse(request, cookieOptions, { success: true, revokedCount })
637
615
  },
638
616
  {
639
617
  response: {
@@ -645,26 +623,17 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
645
623
  summary: "Sign out the current user everywhere (all devices and apps)",
646
624
  tags: [OPENAPI_TAGS.authSessions.name],
647
625
  operationId: "signOutAll",
648
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
626
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
649
627
  },
650
628
  }
651
629
  )
652
630
  .get(
653
631
  "/api/auth/access-management-options",
654
- async ({ request }) => {
632
+ async (context) => {
655
633
  try {
656
- const authOptions = resolveAuthOptions(options, request)
657
- const session = requireAuthenticatedUserSession(
658
- await host.auth.getSession(request, {
659
- ...authOptions,
660
- credentialSource: "any",
661
- })
662
- )
663
- if (session instanceof Response) {
664
- return session
665
- }
634
+ const caller = requireUserCaller(context)
666
635
 
667
- const assignableGroupIds = new Set(session.groupIds)
636
+ const assignableGroupIds = new Set(caller.groupIds)
668
637
 
669
638
  return jsonResponse(
670
639
  {
@@ -692,31 +661,22 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
692
661
  summary: "Get auth access-token management options",
693
662
  tags: [OPENAPI_TAGS.authAccessTokens.name],
694
663
  operationId: "getAuthAccessManagementOptions",
695
- security: bearerSecurityRequirement("getAuthAccessManagementOptions"),
664
+ security: accessTokenSecurityRequirement("getAuthAccessManagementOptions"),
696
665
  },
697
666
  }
698
667
  )
699
668
  .get(
700
669
  "/api/auth/access-tokens",
701
- async ({ request }) => {
670
+ async ({ ...context }) => {
702
671
  try {
703
- const authOptions = resolveAuthOptions(options, request)
704
- const session = requireAuthenticatedUserSession(
705
- await host.auth.getSession(request, {
706
- ...authOptions,
707
- credentialSource: "any",
708
- })
709
- )
710
- if (session instanceof Response) {
711
- return session
712
- }
672
+ const caller = requireUserCaller(context)
713
673
 
714
- const { accessTokens } = await host.auth.listPersonalAccessTokens(request, authOptions)
674
+ const { accessTokens } = await host.auth.listPersonalAccessTokens(caller)
715
675
 
716
676
  return jsonResponse(
717
677
  {
718
678
  accessTokens: accessTokens.map((accessToken) =>
719
- serializeAccessToken(accessToken, { subjectLabel: session.user.email })
679
+ serializeAccessToken(accessToken, { subjectLabel: caller.user.email })
720
680
  ),
721
681
  },
722
682
  200
@@ -735,39 +695,30 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
735
695
  summary: "List personal access tokens for the current user",
736
696
  tags: [OPENAPI_TAGS.authAccessTokens.name],
737
697
  operationId: "listAuthAccessTokens",
738
- security: bearerSecurityRequirement("listAuthAccessTokens"),
698
+ security: accessTokenSecurityRequirement("listAuthAccessTokens"),
739
699
  },
740
700
  }
741
701
  )
742
702
  .post(
743
703
  "/api/auth/access-tokens",
744
- async ({ request, body }) => {
704
+ async ({ body, ...context }) => {
745
705
  try {
746
- const authOptions = resolveAuthOptions(options, request)
747
706
  const parsed = CreateAuthPersonalAccessTokenBodySchema.parse(body)
748
- const session = requireAuthenticatedUserSession(
749
- await host.auth.getSession(request, {
750
- ...authOptions,
751
- credentialSource: "any",
752
- })
753
- )
754
- if (session instanceof Response) {
755
- return session
756
- }
707
+ const caller = requireUserCaller(context)
757
708
 
758
709
  const expiresAt = parseRequiredFutureDate(parsed.expiresAt)
759
- const result = await host.auth.createPersonalAccessToken(
760
- request,
761
- { name: parsed.name, expiresAt, groupIds: parsed.groupIds },
762
- authOptions
763
- )
710
+ const result = await host.auth.createPersonalAccessToken(caller, {
711
+ name: parsed.name,
712
+ expiresAt,
713
+ groupIds: parsed.groupIds,
714
+ })
764
715
 
765
716
  // The raw token is only returned on creation. Storage keeps a hash, so
766
717
  // Atlas can never reveal it again after this response leaves the page.
767
718
  return jsonResponse(
768
719
  {
769
720
  accessToken: serializeAccessToken(result.accessToken, {
770
- subjectLabel: session.user.email,
721
+ subjectLabel: caller.user.email,
771
722
  }),
772
723
  tokenValue: result.tokenValue,
773
724
  },
@@ -790,35 +741,22 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
790
741
  summary: "Create a personal access token",
791
742
  tags: [OPENAPI_TAGS.authAccessTokens.name],
792
743
  operationId: "createAuthPersonalAccessToken",
793
- security: bearerSecurityRequirement("createAuthPersonalAccessToken"),
744
+ security: accessTokenSecurityRequirement("createAuthPersonalAccessToken"),
794
745
  },
795
746
  }
796
747
  )
797
748
  .post(
798
749
  "/api/auth/access-tokens/:tokenId/revoke",
799
- async ({ request, params }) => {
750
+ async ({ params, ...context }) => {
800
751
  try {
801
- const authOptions = resolveAuthOptions(options, request)
802
- const session = requireAuthenticatedUserSession(
803
- await host.auth.getSession(request, {
804
- ...authOptions,
805
- credentialSource: "any",
806
- })
807
- )
808
- if (session instanceof Response) {
809
- return session
810
- }
752
+ const caller = requireUserCaller(context)
811
753
 
812
754
  const { tokenId } = RevokeAuthAccessTokenParamsSchema.parse(params)
813
- const result = await host.auth.revokePersonalAccessToken(
814
- request,
815
- { tokenId },
816
- authOptions
817
- )
755
+ const result = await host.auth.revokePersonalAccessToken(caller, { tokenId })
818
756
  return jsonResponse(
819
757
  {
820
758
  accessToken: serializeAccessToken(result.accessToken, {
821
- subjectLabel: session.user.email,
759
+ subjectLabel: caller.user.email,
822
760
  }),
823
761
  },
824
762
  200
@@ -840,21 +778,16 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
840
778
  summary: "Revoke one of the current user's personal access tokens",
841
779
  tags: [OPENAPI_TAGS.authAccessTokens.name],
842
780
  operationId: "revokeAuthAccessToken",
843
- security: bearerSecurityRequirement("revokeAuthAccessToken"),
781
+ security: accessTokenSecurityRequirement("revokeAuthAccessToken"),
844
782
  },
845
783
  }
846
784
  )
847
785
  .get(
848
786
  "/api/auth/service-accounts",
849
- async ({ request }) => {
787
+ async ({ ...context }) => {
850
788
  try {
851
- const authOptions = resolveAuthOptions(options, request)
852
- const session = requireAuthenticatedUserSession(
853
- await host.auth.getSession(request, { ...authOptions, credentialSource: "any" })
854
- )
855
- if (session instanceof Response) return session
856
-
857
- const { serviceAccounts } = await host.auth.listServiceAccounts(request, authOptions)
789
+ const caller = requireUserCaller(context)
790
+ const { serviceAccounts } = await host.auth.listServiceAccounts(caller)
858
791
 
859
792
  return jsonResponse(
860
793
  {
@@ -879,31 +812,22 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
879
812
  summary: "List auth service accounts",
880
813
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
881
814
  operationId: "listAuthServiceAccounts",
882
- security: bearerSecurityRequirement("listAuthServiceAccounts"),
815
+ security: accessTokenSecurityRequirement("listAuthServiceAccounts"),
883
816
  },
884
817
  }
885
818
  )
886
819
  .post(
887
820
  "/api/auth/service-accounts",
888
- async ({ request, body }) => {
821
+ async ({ body, ...context }) => {
889
822
  try {
890
- const authOptions = resolveAuthOptions(options, request)
823
+ const caller = requireUserCaller(context)
891
824
  const parsed = CreateAuthServiceAccountBodySchema.parse(body)
892
- const session = requireAuthenticatedUserSession(
893
- await host.auth.getSession(request, { ...authOptions, credentialSource: "any" })
894
- )
895
- if (session instanceof Response) return session
896
-
897
- const result = await host.auth.createServiceAccount(
898
- request,
899
- {
900
- id: parsed.id,
901
- name: parsed.name,
902
- description: optionalTrimmed(parsed.description),
903
- groupIds: parsed.groupIds,
904
- },
905
- { ...authOptions, credentialSource: "any" }
906
- )
825
+ const result = await host.auth.createServiceAccount(caller, {
826
+ id: parsed.id,
827
+ name: parsed.name,
828
+ description: optionalTrimmed(parsed.description),
829
+ groupIds: parsed.groupIds,
830
+ })
907
831
 
908
832
  return jsonResponse(
909
833
  {
@@ -931,26 +855,17 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
931
855
  summary: "Create an auth service account",
932
856
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
933
857
  operationId: "createAuthServiceAccount",
934
- security: bearerSecurityRequirement("createAuthServiceAccount"),
858
+ security: accessTokenSecurityRequirement("createAuthServiceAccount"),
935
859
  },
936
860
  }
937
861
  )
938
862
  .post(
939
863
  "/api/auth/service-accounts/:serviceAccountId/disable",
940
- async ({ request, params }) => {
864
+ async ({ params, ...context }) => {
941
865
  try {
942
- const authOptions = resolveAuthOptions(options, request)
943
- const session = requireAuthenticatedUserSession(
944
- await host.auth.getSession(request, { ...authOptions, credentialSource: "any" })
945
- )
946
- if (session instanceof Response) return session
947
-
866
+ const caller = requireUserCaller(context)
948
867
  const { serviceAccountId } = AuthServiceAccountParamsSchema.parse(params)
949
- const result = await host.auth.disableServiceAccount(
950
- request,
951
- { serviceAccountId },
952
- authOptions
953
- )
868
+ const result = await host.auth.disableServiceAccount(caller, { serviceAccountId })
954
869
 
955
870
  return jsonResponse(
956
871
  {
@@ -975,25 +890,19 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
975
890
  summary: "Disable an auth service account",
976
891
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
977
892
  operationId: "disableAuthServiceAccount",
978
- security: bearerSecurityRequirement("disableAuthServiceAccount"),
893
+ security: accessTokenSecurityRequirement("disableAuthServiceAccount"),
979
894
  },
980
895
  }
981
896
  )
982
897
  .get(
983
898
  "/api/auth/service-accounts/:serviceAccountId/access-tokens",
984
- async ({ request, params }) => {
899
+ async ({ params, ...context }) => {
985
900
  try {
986
- const authOptions = resolveAuthOptions(options, request)
987
- const session = requireAuthenticatedUserSession(
988
- await host.auth.getSession(request, { ...authOptions, credentialSource: "any" })
989
- )
990
- if (session instanceof Response) return session
991
-
901
+ const caller = requireUserCaller(context)
992
902
  const { serviceAccountId } = AuthServiceAccountParamsSchema.parse(params)
993
903
  const { serviceAccount, accessTokens } = await host.auth.listServiceAccountAccessTokens(
994
- request,
995
- { serviceAccountId },
996
- authOptions
904
+ caller,
905
+ { serviceAccountId }
997
906
  )
998
907
 
999
908
  return jsonResponse(
@@ -1021,33 +930,24 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1021
930
  summary: "List access tokens for an auth service account",
1022
931
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
1023
932
  operationId: "listAuthServiceAccountAccessTokens",
1024
- security: bearerSecurityRequirement("listAuthServiceAccountAccessTokens"),
933
+ security: accessTokenSecurityRequirement("listAuthServiceAccountAccessTokens"),
1025
934
  },
1026
935
  }
1027
936
  )
1028
937
  .post(
1029
938
  "/api/auth/service-accounts/:serviceAccountId/access-tokens",
1030
- async ({ request, params, body }) => {
939
+ async ({ params, body, ...context }) => {
1031
940
  try {
1032
- const authOptions = resolveAuthOptions(options, request)
941
+ const caller = requireUserCaller(context)
1033
942
  const parsedParams = AuthServiceAccountParamsSchema.parse(params)
1034
943
  const parsed = CreateAuthServiceAccountAccessTokenBodySchema.parse(body)
1035
- const session = requireAuthenticatedUserSession(
1036
- await host.auth.getSession(request, { ...authOptions, credentialSource: "any" })
1037
- )
1038
- if (session instanceof Response) return session
1039
-
1040
944
  const expiresAt = parseRequiredFutureDate(parsed.expiresAt)
1041
- const result = await host.auth.createServiceAccountAccessToken(
1042
- request,
1043
- {
1044
- serviceAccountId: parsedParams.serviceAccountId,
1045
- name: parsed.name,
1046
- expiresAt,
1047
- groupIds: parsed.groupIds,
1048
- },
1049
- { ...authOptions, credentialSource: "any" }
1050
- )
945
+ const result = await host.auth.createServiceAccountAccessToken(caller, {
946
+ serviceAccountId: parsedParams.serviceAccountId,
947
+ name: parsed.name,
948
+ expiresAt,
949
+ groupIds: parsed.groupIds,
950
+ })
1051
951
 
1052
952
  return jsonResponse(
1053
953
  {
@@ -1077,26 +977,20 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1077
977
  summary: "Create an access token for an auth service account",
1078
978
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
1079
979
  operationId: "createAuthServiceAccountAccessToken",
1080
- security: bearerSecurityRequirement("createAuthServiceAccountAccessToken"),
980
+ security: accessTokenSecurityRequirement("createAuthServiceAccountAccessToken"),
1081
981
  },
1082
982
  }
1083
983
  )
1084
984
  .post(
1085
985
  "/api/auth/service-accounts/:serviceAccountId/access-tokens/:tokenId/revoke",
1086
- async ({ request, params }) => {
986
+ async ({ params, ...context }) => {
1087
987
  try {
1088
- const authOptions = resolveAuthOptions(options, request)
988
+ const caller = requireUserCaller(context)
1089
989
  const parsed = RevokeAuthServiceAccountAccessTokenParamsSchema.parse(params)
1090
- const session = requireAuthenticatedUserSession(
1091
- await host.auth.getSession(request, { ...authOptions, credentialSource: "any" })
1092
- )
1093
- if (session instanceof Response) return session
1094
-
1095
- const result = await host.auth.revokeServiceAccountAccessToken(
1096
- request,
1097
- { serviceAccountId: parsed.serviceAccountId, tokenId: parsed.tokenId },
1098
- authOptions
1099
- )
990
+ const result = await host.auth.revokeServiceAccountAccessToken(caller, {
991
+ serviceAccountId: parsed.serviceAccountId,
992
+ tokenId: parsed.tokenId,
993
+ })
1100
994
 
1101
995
  return jsonResponse(
1102
996
  {
@@ -1123,15 +1017,15 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1123
1017
  summary: "Revoke an access token for an auth service account",
1124
1018
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
1125
1019
  operationId: "revokeAuthServiceAccountAccessToken",
1126
- security: bearerSecurityRequirement("revokeAuthServiceAccountAccessToken"),
1020
+ security: accessTokenSecurityRequirement("revokeAuthServiceAccountAccessToken"),
1127
1021
  },
1128
1022
  }
1129
1023
  )
1130
1024
  .post(
1131
1025
  "/api/auth/invitations",
1132
- async ({ request, body }) => {
1026
+ async ({ request, body, ...context }) => {
1133
1027
  try {
1134
- const authOptions = resolveAuthOptions(options, request)
1028
+ const caller = requireUserCaller(context)
1135
1029
  const parsed = CreateAuthInvitationBodySchema.parse(body)
1136
1030
  const deliveryContext = resolveInvitationDeliveryContext(options, request, {
1137
1031
  destinationId: parsed.destinationId,
@@ -1142,22 +1036,14 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1142
1036
  }
1143
1037
 
1144
1038
  const result = await host.auth.invite(
1145
- request,
1039
+ caller,
1146
1040
  {
1147
1041
  email: parsed.email,
1148
1042
  groupIds: parsed.groupIds,
1149
1043
  expiresAt: parseDate(parsed.expiresAt),
1150
- returnTo: deliveryContext.returnTo,
1151
1044
  revealLink: parsed.revealLink,
1152
1045
  },
1153
- {
1154
- ...authOptions,
1155
- delivery: {
1156
- audience: deliveryContext.audience,
1157
- returnTo: deliveryContext.returnTo,
1158
- requestOrigin: deliveryContext.requestOrigin,
1159
- },
1160
- }
1046
+ deliveryContext
1161
1047
  )
1162
1048
 
1163
1049
  return jsonResponse(
@@ -1186,18 +1072,18 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1186
1072
  summary: "Create an auth invitation",
1187
1073
  tags: [OPENAPI_TAGS.authInvitations.name],
1188
1074
  operationId: "createAuthInvitation",
1189
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
1075
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
1190
1076
  },
1191
1077
  }
1192
1078
  )
1193
1079
  .get(
1194
1080
  "/api/auth/invitation-options",
1195
- async ({ request }) => {
1081
+ async ({ request, ...context }) => {
1196
1082
  try {
1197
- const authOptions = resolveAuthOptions(options, request)
1083
+ const caller = requireUserCaller(context)
1198
1084
  return jsonResponse(
1199
1085
  {
1200
- ...(await host.auth.getInvitationOptions(request, authOptions)),
1086
+ ...(await host.auth.getInvitationOptions(caller)),
1201
1087
  ...options.getInvitationDestinationOptions(request),
1202
1088
  },
1203
1089
  200
@@ -1221,21 +1107,17 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1221
1107
  )
1222
1108
  .get(
1223
1109
  "/api/auth/invitations",
1224
- async ({ request, query }) => {
1110
+ async ({ query, ...context }) => {
1225
1111
  try {
1226
- const authOptions = resolveAuthOptions(options, request)
1112
+ const caller = requireUserCaller(context)
1227
1113
  const parsed = ListAuthInvitationsQuerySchema.parse(query)
1228
- const result = await host.auth.listInvitations(
1229
- request,
1230
- {
1231
- email: parsed.email,
1232
- statuses: parsed.status ? [parsed.status] : undefined,
1233
- limit: parseOptionalInt(parsed.limit),
1234
- offset: parseOptionalInt(parsed.offset),
1235
- order: parsed.order,
1236
- },
1237
- authOptions
1238
- )
1114
+ const result = await host.auth.listInvitations(caller, {
1115
+ email: parsed.email,
1116
+ statuses: parsed.status ? [parsed.status] : undefined,
1117
+ limit: parseOptionalInt(parsed.limit),
1118
+ offset: parseOptionalInt(parsed.offset),
1119
+ order: parsed.order,
1120
+ })
1239
1121
 
1240
1122
  return jsonResponse(
1241
1123
  {
@@ -1268,17 +1150,13 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1268
1150
  )
1269
1151
  .post(
1270
1152
  "/api/auth/invitations/:invitationId/revoke",
1271
- async ({ request, params }) => {
1153
+ async ({ params, ...context }) => {
1272
1154
  try {
1273
- const authOptions = resolveAuthOptions(options, request)
1155
+ const caller = requireUserCaller(context)
1274
1156
  const parsed = RevokeAuthInvitationParamsSchema.parse(params)
1275
- const result = await host.auth.revokeInvitation(
1276
- request,
1277
- {
1278
- invitationId: parsed.invitationId,
1279
- },
1280
- authOptions
1281
- )
1157
+ const result = await host.auth.revokeInvitation(caller, {
1158
+ invitationId: parsed.invitationId,
1159
+ })
1282
1160
 
1283
1161
  return jsonResponse(
1284
1162
  {
@@ -1304,16 +1182,16 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1304
1182
  summary: "Revoke an auth invitation",
1305
1183
  tags: [OPENAPI_TAGS.authInvitations.name],
1306
1184
  operationId: "revokeAuthInvitation",
1307
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
1185
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
1308
1186
  },
1309
1187
  }
1310
1188
  )
1311
1189
  .get(
1312
1190
  "/api/auth/membership-options",
1313
- async ({ request }) => {
1191
+ async ({ ...context }) => {
1314
1192
  try {
1315
- const authOptions = resolveAuthOptions(options, request)
1316
- return jsonResponse(await host.auth.getMembershipOptions(request, authOptions), 200)
1193
+ const caller = requireUserCaller(context)
1194
+ return jsonResponse(await host.auth.getMembershipOptions(caller), 200)
1317
1195
  } catch (error) {
1318
1196
  return authRouteErrorResponse(error)
1319
1197
  }
@@ -1333,19 +1211,15 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1333
1211
  )
1334
1212
  .get(
1335
1213
  "/api/auth/members",
1336
- async ({ request, query }) => {
1214
+ async ({ query, ...context }) => {
1337
1215
  try {
1338
- const authOptions = resolveAuthOptions(options, request)
1216
+ const caller = requireUserCaller(context)
1339
1217
  const parsed = ListAuthMembersQuerySchema.parse(query)
1340
- const result = await host.auth.listMembers(
1341
- request,
1342
- {
1343
- limit: parseOptionalInt(parsed.limit),
1344
- offset: parseOptionalInt(parsed.offset),
1345
- order: parsed.order,
1346
- },
1347
- authOptions
1348
- )
1218
+ const result = await host.auth.listMembers(caller, {
1219
+ limit: parseOptionalInt(parsed.limit),
1220
+ offset: parseOptionalInt(parsed.offset),
1221
+ order: parsed.order,
1222
+ })
1349
1223
 
1350
1224
  return jsonResponse(
1351
1225
  {
@@ -1376,16 +1250,15 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1376
1250
  )
1377
1251
  .patch(
1378
1252
  "/api/auth/members/:userId/groups",
1379
- async ({ request, params, body }) => {
1253
+ async ({ params, body, ...context }) => {
1380
1254
  try {
1381
- const authOptions = resolveAuthOptions(options, request)
1255
+ const caller = requireUserCaller(context)
1382
1256
  const parsedParams = AuthMemberParamsSchema.parse(params)
1383
1257
  const parsed = UpdateAuthMemberGroupsBodySchema.parse(body)
1384
- const result = await host.auth.updateMemberGroups(
1385
- request,
1386
- { userId: parsedParams.userId, groupIds: parsed.groupIds },
1387
- authOptions
1388
- )
1258
+ const result = await host.auth.updateMemberGroups(caller, {
1259
+ userId: parsedParams.userId,
1260
+ groupIds: parsed.groupIds,
1261
+ })
1389
1262
 
1390
1263
  return jsonResponse({ member: serializeManagedMember(result.user, result.groupIds) }, 200)
1391
1264
  } catch (error) {
@@ -1407,21 +1280,17 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1407
1280
  summary: "Update an auth member's groups",
1408
1281
  tags: [OPENAPI_TAGS.authMembers.name],
1409
1282
  operationId: "updateAuthMemberGroups",
1410
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
1283
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
1411
1284
  },
1412
1285
  }
1413
1286
  )
1414
1287
  .post(
1415
1288
  "/api/auth/members/:userId/suspend",
1416
- async ({ request, params }) => {
1289
+ async ({ params, ...context }) => {
1417
1290
  try {
1418
- const authOptions = resolveAuthOptions(options, request)
1291
+ const caller = requireUserCaller(context)
1419
1292
  const parsed = AuthMemberParamsSchema.parse(params)
1420
- const result = await host.auth.suspendMember(
1421
- request,
1422
- { userId: parsed.userId },
1423
- authOptions
1424
- )
1293
+ const result = await host.auth.suspendMember(caller, { userId: parsed.userId })
1425
1294
 
1426
1295
  return jsonResponse({ member: serializeManagedMember(result.user, result.groupIds) }, 200)
1427
1296
  } catch (error) {
@@ -1441,21 +1310,17 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1441
1310
  summary: "Suspend an auth member",
1442
1311
  tags: [OPENAPI_TAGS.authMembers.name],
1443
1312
  operationId: "suspendAuthMember",
1444
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
1313
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
1445
1314
  },
1446
1315
  }
1447
1316
  )
1448
1317
  .post(
1449
1318
  "/api/auth/members/:userId/reactivate",
1450
- async ({ request, params }) => {
1319
+ async ({ params, ...context }) => {
1451
1320
  try {
1452
- const authOptions = resolveAuthOptions(options, request)
1321
+ const caller = requireUserCaller(context)
1453
1322
  const parsed = AuthMemberParamsSchema.parse(params)
1454
- const result = await host.auth.reactivateMember(
1455
- request,
1456
- { userId: parsed.userId },
1457
- authOptions
1458
- )
1323
+ const result = await host.auth.reactivateMember(caller, { userId: parsed.userId })
1459
1324
 
1460
1325
  return jsonResponse({ member: serializeManagedMember(result.user, result.groupIds) }, 200)
1461
1326
  } catch (error) {
@@ -1475,7 +1340,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1475
1340
  summary: "Reactivate an auth member",
1476
1341
  tags: [OPENAPI_TAGS.authMembers.name],
1477
1342
  operationId: "reactivateAuthMember",
1478
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
1343
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
1479
1344
  },
1480
1345
  }
1481
1346
  )
@@ -1738,7 +1603,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1738
1603
  }
1739
1604
 
1740
1605
  const DEVICE_AUTHORIZATION_TTL_MS = 10 * 60 * 1000
1741
- const DEVICE_ACCESS_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000
1606
+ const DEVICE_AUTHORIZATIONS_PER_ADDRESS = 10
1742
1607
  const DEVICE_AUTHORIZATION_POLL_INTERVAL_SECONDS = 2
1743
1608
  const DEVICE_USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXYZ23456789"
1744
1609
 
@@ -1881,19 +1746,26 @@ async function completeMagicLinkCallback(input: {
1881
1746
  }
1882
1747
  }
1883
1748
 
1884
- // Best-effort client metadata for the active-sessions view. `x-forwarded-for`
1885
- // only reflects the real client behind a trusted proxy; both values are display
1886
- // only and never used for authorization.
1749
+ function bearerTokensBody(
1750
+ tokens: { readonly accessToken: string; readonly refreshToken: string },
1751
+ bearer: { readonly accessExpiresAt: Date },
1752
+ issuedAt: Date
1753
+ ) {
1754
+ return {
1755
+ accessToken: tokens.accessToken,
1756
+ refreshToken: tokens.refreshToken,
1757
+ expiresIn: Math.round((bearer.accessExpiresAt.getTime() - issuedAt.getTime()) / 1000),
1758
+ }
1759
+ }
1760
+
1761
+ // Client metadata for the active-sessions view. Display only; never used for authorization.
1887
1762
  function resolveSessionDevice(request: Request): {
1888
1763
  readonly userAgent?: string
1889
1764
  readonly ipAddress?: string
1890
1765
  } {
1891
1766
  return {
1892
1767
  userAgent: request.headers.get("user-agent")?.trim() || undefined,
1893
- ipAddress:
1894
- request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
1895
- request.headers.get("x-real-ip")?.trim() ||
1896
- undefined,
1768
+ ipAddress: getRequestClientAddress(request),
1897
1769
  }
1898
1770
  }
1899
1771
 
@@ -2053,6 +1925,25 @@ function resolveSessionCsrfToken(input: {
2053
1925
  }
2054
1926
  }
2055
1927
 
1928
+ function authSessionBody(
1929
+ host: SixbHostView,
1930
+ session: AuthenticatedAuthSession,
1931
+ audience: AuthSessionAudience
1932
+ ): Omit<AuthenticatedAuthSessionResponse, "csrfToken"> {
1933
+ return {
1934
+ authenticated: true,
1935
+ applicationAccess: { allowed: sessionCanAccessApplication(host, session, audience), audience },
1936
+ user: {
1937
+ id: session.user.id,
1938
+ email: session.user.email,
1939
+ displayName: session.user.displayName,
1940
+ avatarUrl: session.user.avatarUrl,
1941
+ groupIds: [...session.groupIds],
1942
+ },
1943
+ session: { id: session.session.id, expiresAt: toIsoString(session.session.expiresAt) },
1944
+ }
1945
+ }
1946
+
2056
1947
  function authSessionJsonResponse(
2057
1948
  body: AuthenticatedAuthSessionResponse,
2058
1949
  setCookies: readonly string[]
@@ -2470,8 +2361,7 @@ function serializeAccessToken(
2470
2361
  name: accessToken.name,
2471
2362
  kind: accessToken.kind,
2472
2363
  status,
2473
- subjectType: accessToken.subjectType,
2474
- subjectId: accessToken.subjectId,
2364
+ subject: { type: accessToken.subject.type, id: accessToken.subject.id },
2475
2365
  subjectLabel: options.subjectLabel,
2476
2366
  groupIds: accessToken.groupIds ? [...accessToken.groupIds] : undefined,
2477
2367
  createdAt: toIsoString(accessToken.createdAt),
@@ -2516,29 +2406,38 @@ function optionalTrimmed(value: string | undefined): string | undefined {
2516
2406
  return trimmed ? trimmed : undefined
2517
2407
  }
2518
2408
 
2519
- // Token and service-account management can be driven by a personal access
2520
- // token (for CLI credential rotation) as well as a browser session, so reject
2521
- // unauthenticated requests with 401 and non-user principals (service-account
2522
- // tokens) with 403. Service-account tokens are runtime credentials and must not
2523
- // mint or manage further credentials.
2524
- function requireAuthenticatedUserSession(
2525
- session: AuthRequestResult
2526
- ): AuthenticatedUserRequestSession | Response {
2527
- if (!session.authenticated) {
2528
- return jsonResponse({ error: "Authentication required" }, 401)
2409
+ // Management routes act for the caller the guard resolved: a browser session, or a personal access
2410
+ // token on bearer routes. Service-account tokens are runtime credentials and must not mint or
2411
+ // manage further credentials. The route's catch maps these errors to 401 and 403.
2412
+ function requireUserCaller(context: unknown): AuthenticatedUserRequestSession {
2413
+ const caller = requestCaller(context)
2414
+ if (!caller) {
2415
+ throw new AuthRuntimeError("authentication_required", "Authentication required")
2529
2416
  }
2530
-
2531
- if (!isAuthenticatedUserSession(session)) {
2532
- return jsonResponse({ error: "User authentication is required" }, 403)
2417
+ if (!("user" in caller)) {
2418
+ throw new AuthRuntimeError("authorization_denied", "User authentication is required")
2533
2419
  }
2420
+ return caller
2421
+ }
2534
2422
 
2535
- return session
2423
+ // Session management routes are cookie-only; the guard rejects tokens before they get here.
2424
+ function requireSessionCaller(context: unknown): AuthenticatedAuthSession | Response {
2425
+ const caller = requestCaller(context)
2426
+ return caller?.credentialSource === "session"
2427
+ ? caller
2428
+ : jsonResponse({ error: "Authentication required" }, 401)
2536
2429
  }
2537
2430
 
2538
- function isAuthenticatedUserSession(
2539
- session: AuthRequestResult & { readonly authenticated: true }
2540
- ): session is AuthenticatedUserRequestSession {
2541
- return session.principal.type === "user"
2431
+ // Ending the session behind this request also clears its cookies.
2432
+ function signedOutResponse(
2433
+ request: Request,
2434
+ cookieOptions: ResolvedCookieOptions,
2435
+ body: Record<string, unknown>
2436
+ ): Response {
2437
+ const headers = new Headers({ "content-type": "application/json; charset=utf-8" })
2438
+ headers.append("set-cookie", clearSessionCookieHeader({ request, options: cookieOptions }))
2439
+ headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }))
2440
+ return new Response(JSON.stringify(body), { status: 200, headers })
2542
2441
  }
2543
2442
 
2544
2443
  function serializeInvitation(invitation: InvitationRecord) {