@sixb/server 0.1.12 → 0.1.14

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 +608 -465
  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 +68 -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 +273 -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 +6 -6
  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 +370 -443
  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 +29 -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,30 @@
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,
25
+ SignInRefusedError,
20
26
  shouldUseSecureCookies,
27
+ verifyCsrfToken,
21
28
  verifyDoubleSubmitCsrf,
22
29
  } from "@sixb/core/internal/auth"
23
30
  import {
@@ -29,7 +36,7 @@ import {
29
36
  type UserRecord,
30
37
  } from "@sixb/core/storage"
31
38
  import { type Elysia, t } from "elysia"
32
- import { bearerSecurityRequirement } from "../auth/access-token-boundary"
39
+ import { accessTokenSecurityRequirement } from "../auth/access-token-boundary"
33
40
  import { sessionCanAccessApplication } from "../auth/application-access"
34
41
  import {
35
42
  type AuthInvitationDestinationOptions,
@@ -46,15 +53,22 @@ import {
46
53
  customAuthExperienceResponse,
47
54
  type SixbAuthExperienceOptions,
48
55
  } from "../auth/experience"
56
+ import { ClientAddressRateLimiter } from "../auth/rate-limit"
57
+ import { requestCaller } from "../auth/scope"
49
58
  import { hasForegroundSessionActivity } from "../auth/session-activity"
50
59
  import { createSessionRenewalCookieHeaders } from "../auth/session-cookies"
51
- import { SIXB_CSRF_SECURITY_REQUIREMENT } from "../openapi/security"
60
+ import {
61
+ SIXB_OPTIONAL_SESSION_MUTATION_SECURITY_REQUIREMENT,
62
+ SIXB_OPTIONAL_SESSION_SECURITY_REQUIREMENT,
63
+ SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
64
+ } from "../openapi/security"
52
65
  import { OPENAPI_TAGS } from "../openapi/tags"
53
66
  import {
54
67
  AuthMemberParamsSchema,
55
68
  AuthServiceAccountParamsSchema,
56
69
  AuthSessionResponseSchema,
57
70
  AuthSignOutResponseSchema,
71
+ BearerSessionTokensSchema,
58
72
  CreateAuthInvitationBodySchema,
59
73
  CreateAuthInvitationResponseSchema,
60
74
  CreateAuthPersonalAccessTokenBodySchema,
@@ -81,6 +95,7 @@ import {
81
95
  ListAuthServiceAccountsResponseSchema,
82
96
  ListAuthSessionsResponseSchema,
83
97
  ReactivateAuthMemberResponseSchema,
98
+ RefreshAuthSessionBodySchema,
84
99
  RevokeAuthAccessTokenParamsSchema,
85
100
  RevokeAuthAccessTokenResponseSchema,
86
101
  RevokeAuthInvitationParamsSchema,
@@ -131,6 +146,10 @@ export interface AuthRoutesOptions {
131
146
  }
132
147
 
133
148
  export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: AuthRoutesOptions) {
149
+ const deviceAuthorizationLimiter = new ClientAddressRateLimiter(
150
+ DEVICE_AUTHORIZATIONS_PER_ADDRESS,
151
+ DEVICE_AUTHORIZATION_TTL_MS
152
+ )
134
153
  return app
135
154
  .get(
136
155
  "/auth/assets/*",
@@ -147,6 +166,19 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
147
166
  async ({ body, request }) => {
148
167
  const parsed = CreateDeviceAuthorizationBodySchema.parse(body)
149
168
  const now = new Date()
169
+ // Creation is unauthenticated and the project-wide pending cap is shared, so one address
170
+ // must not be able to fill it.
171
+ if (
172
+ !deviceAuthorizationLimiter.tryConsume(getRequestClientAddress(request), now.getTime())
173
+ ) {
174
+ return jsonResponse(
175
+ {
176
+ error:
177
+ "[SixbServer] Too many device authorizations from this address. Try again later.",
178
+ },
179
+ 429
180
+ )
181
+ }
150
182
  const id = `dva_${randomUUID()}`
151
183
  const deviceCode = `${id}.${randomBytes(32).toString("base64url")}`
152
184
  const userCode = createDeviceUserCode()
@@ -158,8 +190,6 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
158
190
  deviceCodeHash: hashDeviceCode(deviceCode),
159
191
  userCode,
160
192
  clientName: parsed.clientName,
161
- tokenName: parsed.tokenName,
162
- tokenExpiresAt: new Date(now.getTime() + DEVICE_ACCESS_TOKEN_TTL_MS),
163
193
  createdAt: now,
164
194
  expiresAt,
165
195
  })
@@ -191,12 +221,13 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
191
221
  summary: "Start device authorization",
192
222
  tags: [OPENAPI_TAGS.authSessions.name],
193
223
  operationId: "createDeviceAuthorization",
224
+ security: [],
194
225
  },
195
226
  }
196
227
  )
197
228
  .post(
198
229
  "/api/auth/device-authorizations/token",
199
- async ({ body }) => {
230
+ async ({ body, request }) => {
200
231
  const { deviceCode } = ExchangeDeviceAuthorizationBodySchema.parse(body)
201
232
  const id = parseDeviceAuthorizationId(deviceCode)
202
233
  if (!id) return jsonResponse({ status: "expired" as const }, 200)
@@ -223,26 +254,18 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
223
254
  if (!authorization.approvedUserId || !authorization.approvedSessionId) {
224
255
  return jsonResponse({ status: "expired" as const }, 200)
225
256
  }
226
- const credential = createAccessTokenCredential("personal")
257
+ const { session, tokens } = host.auth.prepareBearerSession({
258
+ userId: authorization.approvedUserId,
259
+ clientName: authorization.clientName,
260
+ now,
261
+ })
227
262
  try {
228
263
  await storage.completeDeviceAuthorization({
229
264
  projectId: host.id,
230
265
  id,
231
266
  deviceCodeHash: hashDeviceCode(deviceCode),
232
267
  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
- },
268
+ session: { ...session, ...resolveSessionDevice(request) },
246
269
  })
247
270
  } catch (error) {
248
271
  if (error instanceof AuthStorageError && error.code === "invalid_device_authorization") {
@@ -251,7 +274,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
251
274
  throw error
252
275
  }
253
276
  return jsonResponse(
254
- { status: "approved" as const, accessToken: credential.tokenValue },
277
+ { status: "approved" as const, ...bearerTokensBody(tokens, session.bearer, now) },
255
278
  200
256
279
  )
257
280
  },
@@ -262,6 +285,29 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
262
285
  summary: "Exchange an approved device authorization",
263
286
  tags: [OPENAPI_TAGS.authSessions.name],
264
287
  operationId: "exchangeDeviceAuthorization",
288
+ security: [],
289
+ },
290
+ }
291
+ )
292
+ .post(
293
+ "/api/auth/refresh",
294
+ async ({ body }) => {
295
+ const { refreshToken } = RefreshAuthSessionBodySchema.parse(body)
296
+ const refreshed = await host.auth.refreshSession(refreshToken)
297
+ const bearer = refreshed?.session.bearer
298
+ if (!refreshed || !bearer?.refreshedAt) {
299
+ return jsonResponse({ error: "Invalid refresh token" }, 401)
300
+ }
301
+ return jsonResponse(bearerTokensBody(refreshed.tokens, bearer, bearer.refreshedAt), 200)
302
+ },
303
+ {
304
+ body: RefreshAuthSessionBodySchema,
305
+ response: { 200: BearerSessionTokensSchema, 401: ErrorResponseSchema },
306
+ detail: {
307
+ summary: "Refresh a native client's session tokens",
308
+ tags: [OPENAPI_TAGS.authSessions.name],
309
+ operationId: "refreshAuthSession",
310
+ security: [],
265
311
  },
266
312
  }
267
313
  )
@@ -309,10 +355,9 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
309
355
  const response = authPageResponse(
310
356
  [
311
357
  "<h1>Authorize this device?</h1>",
312
- `<p><strong>${escapeHtml(authorization.clientName)}</strong> is requesting access.</p>`,
358
+ `<p><strong>${escapeHtml(authorization.clientName)}</strong> is requesting to sign in as you.</p>`,
313
359
  `<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>`,
360
+ "<p>It stays signed in until you sign it out or it goes unused for a while.</p>",
316
361
  groups,
317
362
  '<form method="post" action="/auth/device">',
318
363
  `<input type="hidden" name="userCode" value="${escapeHtml(userCode)}">`,
@@ -333,20 +378,10 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
333
378
  const parsed = DeviceAuthorizationDecisionBodySchema.parse(body)
334
379
  const authOptions = resolveAuthOptions(options, request)
335
380
  const session = await host.auth.getSession(request, authOptions)
381
+ // Every signed-in user may approve their own CLI login, whichever web app they may open.
336
382
  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
- ) {
383
+ const csrfCookieName = host.auth.getCookieOptions(authOptions).csrfCookieName
384
+ if (!verifyCsrfToken(request, { cookieName: csrfCookieName, token: parsed.csrfToken })) {
350
385
  return authPageResponse("<h1>Invalid authorization request</h1>", 403)
351
386
  }
352
387
  const storage = requireAuthStorage(host)
@@ -355,22 +390,35 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
355
390
  userCode: parsed.userCode,
356
391
  })
357
392
  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>")
393
+ const decidedAt = new Date()
394
+ try {
395
+ if (parsed.decision === "approve") {
396
+ await storage.deviceAuthorizations.approve({
397
+ projectId: host.id,
398
+ id: authorization.id,
399
+ userId: session.user.id,
400
+ sessionId: session.session.id,
401
+ approvedAt: decidedAt,
402
+ })
403
+ } else {
404
+ await storage.deviceAuthorizations.deny({
405
+ projectId: host.id,
406
+ id: authorization.id,
407
+ deniedAt: decidedAt,
408
+ })
409
+ }
410
+ } catch (error) {
411
+ // The authorization expired or was decided after this page rendered.
412
+ if (error instanceof AuthStorageError && error.code === "invalid_device_authorization") {
413
+ return authPageResponse("<h1>This authorization has expired</h1>", 400)
414
+ }
415
+ throw error
367
416
  }
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>")
417
+ return authPageResponse(
418
+ parsed.decision === "approve"
419
+ ? "<h1>Device authorized</h1><p>You can close this window.</p>"
420
+ : "<h1>Authorization denied</h1><p>You can close this window.</p>"
421
+ )
374
422
  },
375
423
  {
376
424
  body: t.Object({
@@ -386,29 +434,26 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
386
434
  "/api/auth/session",
387
435
  async ({ request }) => {
388
436
  const authOptions = resolveAuthOptions(options, request)
389
- let session = await host.auth.getSession(request, authOptions)
390
- if (!session.authenticated) {
437
+ const caller = await host.auth.getSession(request, {
438
+ ...authOptions,
439
+ credentialSource: "any",
440
+ })
441
+ // Access tokens are not sessions; a native client's session has no cookies to renew.
442
+ if (!caller.authenticated || caller.credentialSource !== "session") {
391
443
  return jsonResponse({ authenticated: false as const }, 200)
392
444
  }
445
+ // A native client belongs to no web app; tell it whether its user may open Atlas.
446
+ if (caller.session.bearer) {
447
+ return jsonResponse(authSessionBody(host, caller, DEFAULT_AUTH_SESSION_AUDIENCE), 200)
448
+ }
393
449
 
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
- )
450
+ const session =
451
+ hasForegroundSessionActivity(request) &&
452
+ sessionCanAccessApplication(host, caller, authOptions.audience)
453
+ ? await host.auth.getSession(request, { ...authOptions, sessionActivity: "foreground" })
454
+ : caller
455
+ if (!session.authenticated) {
456
+ return jsonResponse({ authenticated: false as const }, 200)
412
457
  }
413
458
 
414
459
  const cookieOptions = host.auth.getCookieOptions(authOptions)
@@ -427,25 +472,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
427
472
  })
428
473
  : null
429
474
  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
- },
475
+ { ...authSessionBody(host, session, authOptions.audience), csrfToken: csrf.token },
449
476
  renewal?.headers ?? (csrf.setCookie ? [csrf.setCookie] : [])
450
477
  )
451
478
  },
@@ -455,6 +482,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
455
482
  summary: "Get current auth session",
456
483
  tags: [OPENAPI_TAGS.authSessions.name],
457
484
  operationId: "getAuthSession",
485
+ security: SIXB_OPTIONAL_SESSION_SECURITY_REQUIREMENT,
458
486
  },
459
487
  }
460
488
  )
@@ -462,10 +490,17 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
462
490
  "/api/auth/sign-out",
463
491
  async ({ request }) => {
464
492
  const authOptions = resolveAuthOptions(options, request)
465
- const session = await host.auth.getSession(request, authOptions)
493
+ const result = await host.auth.getSession(request, {
494
+ ...authOptions,
495
+ credentialSource: "any",
496
+ })
497
+ // Access tokens are not sessions; revoke those through their own route.
498
+ const session =
499
+ result.authenticated && result.credentialSource === "session" ? result : null
466
500
  const cookieOptions = host.auth.getCookieOptions(authOptions)
467
501
  if (
468
- session.authenticated &&
502
+ session &&
503
+ !session.session.bearer &&
469
504
  !verifyDoubleSubmitCsrf(request, {
470
505
  cookieName: cookieOptions.csrfCookieName,
471
506
  })
@@ -473,24 +508,11 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
473
508
  return jsonResponse({ error: "CSRF verification failed" }, 403)
474
509
  }
475
510
 
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)
511
+ if (session) {
512
+ await host.auth.revokeSession(session, session.session.id)
484
513
  }
485
514
 
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
- })
515
+ return signedOutResponse(request, cookieOptions, { success: true })
494
516
  },
495
517
  {
496
518
  response: {
@@ -501,36 +523,31 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
501
523
  summary: "Sign out current auth session",
502
524
  tags: [OPENAPI_TAGS.authSessions.name],
503
525
  operationId: "signOut",
504
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
526
+ security: SIXB_OPTIONAL_SESSION_MUTATION_SECURITY_REQUIREMENT,
505
527
  },
506
528
  }
507
529
  )
508
530
  .get(
509
531
  "/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)
532
+ async (context) => {
533
+ const session = requireSessionCaller(context)
534
+ if (session instanceof Response) {
535
+ return session
515
536
  }
516
537
 
517
- const sessions = await requireAuthStorage(host).sessions.listActiveByUserId({
518
- projectId: host.id,
519
- userId: session.user.id,
520
- now: new Date(),
521
- })
522
-
538
+ const sessions = await host.auth.listSessions(session)
523
539
  return jsonResponse(
524
540
  {
525
541
  sessions: sessions.map((entry) => ({
526
542
  id: entry.id,
527
- audience: entry.audience,
543
+ audience: entry.bearer ? undefined : entry.audience,
528
544
  current: entry.id === session.session.id,
529
545
  createdAt: toIsoString(entry.createdAt),
530
546
  expiresAt: toIsoString(entry.expiresAt),
531
547
  lastSeenAt: entry.lastSeenAt ? toIsoString(entry.lastSeenAt) : undefined,
532
548
  userAgent: entry.userAgent,
533
549
  ipAddress: entry.ipAddress,
550
+ clientName: entry.bearer?.clientName,
534
551
  })),
535
552
  },
536
553
  200
@@ -550,40 +567,22 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
550
567
  )
551
568
  .post(
552
569
  "/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)
570
+ async ({ request, params, ...context }) => {
571
+ const session = requireSessionCaller(context)
572
+ if (session instanceof Response) {
573
+ return session
562
574
  }
563
575
 
564
576
  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) {
577
+ if (!(await host.auth.revokeSession(session, sessionId))) {
570
578
  return jsonResponse({ error: "Session not found" }, 404)
571
579
  }
572
580
 
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 }))
581
+ if (sessionId !== session.session.id) {
582
+ return jsonResponse({ success: true }, 200)
584
583
  }
585
-
586
- return new Response(JSON.stringify({ success: true }), { status: 200, headers })
584
+ const cookieOptions = host.auth.getCookieOptions(resolveAuthOptions(options, request))
585
+ return signedOutResponse(request, cookieOptions, { success: true })
587
586
  },
588
587
  {
589
588
  params: RevokeAuthSessionParamsSchema,
@@ -597,43 +596,23 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
597
596
  summary: "Revoke one of the current user's sessions",
598
597
  tags: [OPENAPI_TAGS.authSessions.name],
599
598
  operationId: "revokeAuthSession",
600
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
599
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
601
600
  },
602
601
  }
603
602
  )
604
603
  .post(
605
604
  "/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)
605
+ async ({ request, ...context }) => {
606
+ const session = requireSessionCaller(context)
607
+ if (session instanceof Response) {
608
+ return session
627
609
  }
628
610
 
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
- })
611
+ // Other audiences' cookies stay in their browsers, but their sessions are revoked, so the
612
+ // next request there re-authenticates.
613
+ const revokedCount = await host.auth.revokeAllSessions(session)
614
+ const cookieOptions = host.auth.getCookieOptions(resolveAuthOptions(options, request))
615
+ return signedOutResponse(request, cookieOptions, { success: true, revokedCount })
637
616
  },
638
617
  {
639
618
  response: {
@@ -645,26 +624,17 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
645
624
  summary: "Sign out the current user everywhere (all devices and apps)",
646
625
  tags: [OPENAPI_TAGS.authSessions.name],
647
626
  operationId: "signOutAll",
648
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
627
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
649
628
  },
650
629
  }
651
630
  )
652
631
  .get(
653
632
  "/api/auth/access-management-options",
654
- async ({ request }) => {
633
+ async (context) => {
655
634
  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
- }
635
+ const caller = requireUserCaller(context)
666
636
 
667
- const assignableGroupIds = new Set(session.groupIds)
637
+ const assignableGroupIds = new Set(caller.groupIds)
668
638
 
669
639
  return jsonResponse(
670
640
  {
@@ -692,31 +662,22 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
692
662
  summary: "Get auth access-token management options",
693
663
  tags: [OPENAPI_TAGS.authAccessTokens.name],
694
664
  operationId: "getAuthAccessManagementOptions",
695
- security: bearerSecurityRequirement("getAuthAccessManagementOptions"),
665
+ security: accessTokenSecurityRequirement("getAuthAccessManagementOptions"),
696
666
  },
697
667
  }
698
668
  )
699
669
  .get(
700
670
  "/api/auth/access-tokens",
701
- async ({ request }) => {
671
+ async ({ ...context }) => {
702
672
  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
- }
673
+ const caller = requireUserCaller(context)
713
674
 
714
- const { accessTokens } = await host.auth.listPersonalAccessTokens(request, authOptions)
675
+ const { accessTokens } = await host.auth.listPersonalAccessTokens(caller)
715
676
 
716
677
  return jsonResponse(
717
678
  {
718
679
  accessTokens: accessTokens.map((accessToken) =>
719
- serializeAccessToken(accessToken, { subjectLabel: session.user.email })
680
+ serializeAccessToken(accessToken, { subjectLabel: caller.user.email })
720
681
  ),
721
682
  },
722
683
  200
@@ -735,39 +696,30 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
735
696
  summary: "List personal access tokens for the current user",
736
697
  tags: [OPENAPI_TAGS.authAccessTokens.name],
737
698
  operationId: "listAuthAccessTokens",
738
- security: bearerSecurityRequirement("listAuthAccessTokens"),
699
+ security: accessTokenSecurityRequirement("listAuthAccessTokens"),
739
700
  },
740
701
  }
741
702
  )
742
703
  .post(
743
704
  "/api/auth/access-tokens",
744
- async ({ request, body }) => {
705
+ async ({ body, ...context }) => {
745
706
  try {
746
- const authOptions = resolveAuthOptions(options, request)
747
707
  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
- }
708
+ const caller = requireUserCaller(context)
757
709
 
758
710
  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
- )
711
+ const result = await host.auth.createPersonalAccessToken(caller, {
712
+ name: parsed.name,
713
+ expiresAt,
714
+ groupIds: parsed.groupIds,
715
+ })
764
716
 
765
717
  // The raw token is only returned on creation. Storage keeps a hash, so
766
718
  // Atlas can never reveal it again after this response leaves the page.
767
719
  return jsonResponse(
768
720
  {
769
721
  accessToken: serializeAccessToken(result.accessToken, {
770
- subjectLabel: session.user.email,
722
+ subjectLabel: caller.user.email,
771
723
  }),
772
724
  tokenValue: result.tokenValue,
773
725
  },
@@ -790,35 +742,22 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
790
742
  summary: "Create a personal access token",
791
743
  tags: [OPENAPI_TAGS.authAccessTokens.name],
792
744
  operationId: "createAuthPersonalAccessToken",
793
- security: bearerSecurityRequirement("createAuthPersonalAccessToken"),
745
+ security: accessTokenSecurityRequirement("createAuthPersonalAccessToken"),
794
746
  },
795
747
  }
796
748
  )
797
749
  .post(
798
750
  "/api/auth/access-tokens/:tokenId/revoke",
799
- async ({ request, params }) => {
751
+ async ({ params, ...context }) => {
800
752
  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
- }
753
+ const caller = requireUserCaller(context)
811
754
 
812
755
  const { tokenId } = RevokeAuthAccessTokenParamsSchema.parse(params)
813
- const result = await host.auth.revokePersonalAccessToken(
814
- request,
815
- { tokenId },
816
- authOptions
817
- )
756
+ const result = await host.auth.revokePersonalAccessToken(caller, { tokenId })
818
757
  return jsonResponse(
819
758
  {
820
759
  accessToken: serializeAccessToken(result.accessToken, {
821
- subjectLabel: session.user.email,
760
+ subjectLabel: caller.user.email,
822
761
  }),
823
762
  },
824
763
  200
@@ -840,21 +779,16 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
840
779
  summary: "Revoke one of the current user's personal access tokens",
841
780
  tags: [OPENAPI_TAGS.authAccessTokens.name],
842
781
  operationId: "revokeAuthAccessToken",
843
- security: bearerSecurityRequirement("revokeAuthAccessToken"),
782
+ security: accessTokenSecurityRequirement("revokeAuthAccessToken"),
844
783
  },
845
784
  }
846
785
  )
847
786
  .get(
848
787
  "/api/auth/service-accounts",
849
- async ({ request }) => {
788
+ async ({ ...context }) => {
850
789
  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)
790
+ const caller = requireUserCaller(context)
791
+ const { serviceAccounts } = await host.auth.listServiceAccounts(caller)
858
792
 
859
793
  return jsonResponse(
860
794
  {
@@ -879,31 +813,22 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
879
813
  summary: "List auth service accounts",
880
814
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
881
815
  operationId: "listAuthServiceAccounts",
882
- security: bearerSecurityRequirement("listAuthServiceAccounts"),
816
+ security: accessTokenSecurityRequirement("listAuthServiceAccounts"),
883
817
  },
884
818
  }
885
819
  )
886
820
  .post(
887
821
  "/api/auth/service-accounts",
888
- async ({ request, body }) => {
822
+ async ({ body, ...context }) => {
889
823
  try {
890
- const authOptions = resolveAuthOptions(options, request)
824
+ const caller = requireUserCaller(context)
891
825
  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
- )
826
+ const result = await host.auth.createServiceAccount(caller, {
827
+ id: parsed.id,
828
+ name: parsed.name,
829
+ description: optionalTrimmed(parsed.description),
830
+ groupIds: parsed.groupIds,
831
+ })
907
832
 
908
833
  return jsonResponse(
909
834
  {
@@ -931,26 +856,17 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
931
856
  summary: "Create an auth service account",
932
857
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
933
858
  operationId: "createAuthServiceAccount",
934
- security: bearerSecurityRequirement("createAuthServiceAccount"),
859
+ security: accessTokenSecurityRequirement("createAuthServiceAccount"),
935
860
  },
936
861
  }
937
862
  )
938
863
  .post(
939
864
  "/api/auth/service-accounts/:serviceAccountId/disable",
940
- async ({ request, params }) => {
865
+ async ({ params, ...context }) => {
941
866
  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
-
867
+ const caller = requireUserCaller(context)
948
868
  const { serviceAccountId } = AuthServiceAccountParamsSchema.parse(params)
949
- const result = await host.auth.disableServiceAccount(
950
- request,
951
- { serviceAccountId },
952
- authOptions
953
- )
869
+ const result = await host.auth.disableServiceAccount(caller, { serviceAccountId })
954
870
 
955
871
  return jsonResponse(
956
872
  {
@@ -975,25 +891,19 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
975
891
  summary: "Disable an auth service account",
976
892
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
977
893
  operationId: "disableAuthServiceAccount",
978
- security: bearerSecurityRequirement("disableAuthServiceAccount"),
894
+ security: accessTokenSecurityRequirement("disableAuthServiceAccount"),
979
895
  },
980
896
  }
981
897
  )
982
898
  .get(
983
899
  "/api/auth/service-accounts/:serviceAccountId/access-tokens",
984
- async ({ request, params }) => {
900
+ async ({ params, ...context }) => {
985
901
  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
-
902
+ const caller = requireUserCaller(context)
992
903
  const { serviceAccountId } = AuthServiceAccountParamsSchema.parse(params)
993
904
  const { serviceAccount, accessTokens } = await host.auth.listServiceAccountAccessTokens(
994
- request,
995
- { serviceAccountId },
996
- authOptions
905
+ caller,
906
+ { serviceAccountId }
997
907
  )
998
908
 
999
909
  return jsonResponse(
@@ -1021,33 +931,24 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1021
931
  summary: "List access tokens for an auth service account",
1022
932
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
1023
933
  operationId: "listAuthServiceAccountAccessTokens",
1024
- security: bearerSecurityRequirement("listAuthServiceAccountAccessTokens"),
934
+ security: accessTokenSecurityRequirement("listAuthServiceAccountAccessTokens"),
1025
935
  },
1026
936
  }
1027
937
  )
1028
938
  .post(
1029
939
  "/api/auth/service-accounts/:serviceAccountId/access-tokens",
1030
- async ({ request, params, body }) => {
940
+ async ({ params, body, ...context }) => {
1031
941
  try {
1032
- const authOptions = resolveAuthOptions(options, request)
942
+ const caller = requireUserCaller(context)
1033
943
  const parsedParams = AuthServiceAccountParamsSchema.parse(params)
1034
944
  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
945
  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
- )
946
+ const result = await host.auth.createServiceAccountAccessToken(caller, {
947
+ serviceAccountId: parsedParams.serviceAccountId,
948
+ name: parsed.name,
949
+ expiresAt,
950
+ groupIds: parsed.groupIds,
951
+ })
1051
952
 
1052
953
  return jsonResponse(
1053
954
  {
@@ -1077,26 +978,20 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1077
978
  summary: "Create an access token for an auth service account",
1078
979
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
1079
980
  operationId: "createAuthServiceAccountAccessToken",
1080
- security: bearerSecurityRequirement("createAuthServiceAccountAccessToken"),
981
+ security: accessTokenSecurityRequirement("createAuthServiceAccountAccessToken"),
1081
982
  },
1082
983
  }
1083
984
  )
1084
985
  .post(
1085
986
  "/api/auth/service-accounts/:serviceAccountId/access-tokens/:tokenId/revoke",
1086
- async ({ request, params }) => {
987
+ async ({ params, ...context }) => {
1087
988
  try {
1088
- const authOptions = resolveAuthOptions(options, request)
989
+ const caller = requireUserCaller(context)
1089
990
  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
- )
991
+ const result = await host.auth.revokeServiceAccountAccessToken(caller, {
992
+ serviceAccountId: parsed.serviceAccountId,
993
+ tokenId: parsed.tokenId,
994
+ })
1100
995
 
1101
996
  return jsonResponse(
1102
997
  {
@@ -1123,15 +1018,15 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1123
1018
  summary: "Revoke an access token for an auth service account",
1124
1019
  tags: [OPENAPI_TAGS.authServiceAccounts.name],
1125
1020
  operationId: "revokeAuthServiceAccountAccessToken",
1126
- security: bearerSecurityRequirement("revokeAuthServiceAccountAccessToken"),
1021
+ security: accessTokenSecurityRequirement("revokeAuthServiceAccountAccessToken"),
1127
1022
  },
1128
1023
  }
1129
1024
  )
1130
1025
  .post(
1131
1026
  "/api/auth/invitations",
1132
- async ({ request, body }) => {
1027
+ async ({ request, body, ...context }) => {
1133
1028
  try {
1134
- const authOptions = resolveAuthOptions(options, request)
1029
+ const caller = requireUserCaller(context)
1135
1030
  const parsed = CreateAuthInvitationBodySchema.parse(body)
1136
1031
  const deliveryContext = resolveInvitationDeliveryContext(options, request, {
1137
1032
  destinationId: parsed.destinationId,
@@ -1142,22 +1037,14 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1142
1037
  }
1143
1038
 
1144
1039
  const result = await host.auth.invite(
1145
- request,
1040
+ caller,
1146
1041
  {
1147
1042
  email: parsed.email,
1148
1043
  groupIds: parsed.groupIds,
1149
1044
  expiresAt: parseDate(parsed.expiresAt),
1150
- returnTo: deliveryContext.returnTo,
1151
1045
  revealLink: parsed.revealLink,
1152
1046
  },
1153
- {
1154
- ...authOptions,
1155
- delivery: {
1156
- audience: deliveryContext.audience,
1157
- returnTo: deliveryContext.returnTo,
1158
- requestOrigin: deliveryContext.requestOrigin,
1159
- },
1160
- }
1047
+ deliveryContext
1161
1048
  )
1162
1049
 
1163
1050
  return jsonResponse(
@@ -1186,18 +1073,18 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1186
1073
  summary: "Create an auth invitation",
1187
1074
  tags: [OPENAPI_TAGS.authInvitations.name],
1188
1075
  operationId: "createAuthInvitation",
1189
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
1076
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
1190
1077
  },
1191
1078
  }
1192
1079
  )
1193
1080
  .get(
1194
1081
  "/api/auth/invitation-options",
1195
- async ({ request }) => {
1082
+ async ({ request, ...context }) => {
1196
1083
  try {
1197
- const authOptions = resolveAuthOptions(options, request)
1084
+ const caller = requireUserCaller(context)
1198
1085
  return jsonResponse(
1199
1086
  {
1200
- ...(await host.auth.getInvitationOptions(request, authOptions)),
1087
+ ...(await host.auth.getInvitationOptions(caller)),
1201
1088
  ...options.getInvitationDestinationOptions(request),
1202
1089
  },
1203
1090
  200
@@ -1221,21 +1108,17 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1221
1108
  )
1222
1109
  .get(
1223
1110
  "/api/auth/invitations",
1224
- async ({ request, query }) => {
1111
+ async ({ query, ...context }) => {
1225
1112
  try {
1226
- const authOptions = resolveAuthOptions(options, request)
1113
+ const caller = requireUserCaller(context)
1227
1114
  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
- )
1115
+ const result = await host.auth.listInvitations(caller, {
1116
+ email: parsed.email,
1117
+ statuses: parsed.status ? [parsed.status] : undefined,
1118
+ limit: parseOptionalInt(parsed.limit),
1119
+ offset: parseOptionalInt(parsed.offset),
1120
+ order: parsed.order,
1121
+ })
1239
1122
 
1240
1123
  return jsonResponse(
1241
1124
  {
@@ -1268,17 +1151,13 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1268
1151
  )
1269
1152
  .post(
1270
1153
  "/api/auth/invitations/:invitationId/revoke",
1271
- async ({ request, params }) => {
1154
+ async ({ params, ...context }) => {
1272
1155
  try {
1273
- const authOptions = resolveAuthOptions(options, request)
1156
+ const caller = requireUserCaller(context)
1274
1157
  const parsed = RevokeAuthInvitationParamsSchema.parse(params)
1275
- const result = await host.auth.revokeInvitation(
1276
- request,
1277
- {
1278
- invitationId: parsed.invitationId,
1279
- },
1280
- authOptions
1281
- )
1158
+ const result = await host.auth.revokeInvitation(caller, {
1159
+ invitationId: parsed.invitationId,
1160
+ })
1282
1161
 
1283
1162
  return jsonResponse(
1284
1163
  {
@@ -1304,16 +1183,16 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1304
1183
  summary: "Revoke an auth invitation",
1305
1184
  tags: [OPENAPI_TAGS.authInvitations.name],
1306
1185
  operationId: "revokeAuthInvitation",
1307
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
1186
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
1308
1187
  },
1309
1188
  }
1310
1189
  )
1311
1190
  .get(
1312
1191
  "/api/auth/membership-options",
1313
- async ({ request }) => {
1192
+ async ({ ...context }) => {
1314
1193
  try {
1315
- const authOptions = resolveAuthOptions(options, request)
1316
- return jsonResponse(await host.auth.getMembershipOptions(request, authOptions), 200)
1194
+ const caller = requireUserCaller(context)
1195
+ return jsonResponse(await host.auth.getMembershipOptions(caller), 200)
1317
1196
  } catch (error) {
1318
1197
  return authRouteErrorResponse(error)
1319
1198
  }
@@ -1333,19 +1212,15 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1333
1212
  )
1334
1213
  .get(
1335
1214
  "/api/auth/members",
1336
- async ({ request, query }) => {
1215
+ async ({ query, ...context }) => {
1337
1216
  try {
1338
- const authOptions = resolveAuthOptions(options, request)
1217
+ const caller = requireUserCaller(context)
1339
1218
  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
- )
1219
+ const result = await host.auth.listMembers(caller, {
1220
+ limit: parseOptionalInt(parsed.limit),
1221
+ offset: parseOptionalInt(parsed.offset),
1222
+ order: parsed.order,
1223
+ })
1349
1224
 
1350
1225
  return jsonResponse(
1351
1226
  {
@@ -1376,18 +1251,17 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1376
1251
  )
1377
1252
  .patch(
1378
1253
  "/api/auth/members/:userId/groups",
1379
- async ({ request, params, body }) => {
1254
+ async ({ params, body, ...context }) => {
1380
1255
  try {
1381
- const authOptions = resolveAuthOptions(options, request)
1256
+ const caller = requireUserCaller(context)
1382
1257
  const parsedParams = AuthMemberParamsSchema.parse(params)
1383
1258
  const parsed = UpdateAuthMemberGroupsBodySchema.parse(body)
1384
- const result = await host.auth.updateMemberGroups(
1385
- request,
1386
- { userId: parsedParams.userId, groupIds: parsed.groupIds },
1387
- authOptions
1388
- )
1259
+ const result = await host.auth.updateMemberGroups(caller, {
1260
+ userId: parsedParams.userId,
1261
+ groupIds: parsed.groupIds,
1262
+ })
1389
1263
 
1390
- return jsonResponse({ member: serializeManagedMember(result.user, result.groupIds) }, 200)
1264
+ return jsonResponse({ member: serializeManagedMember(result) }, 200)
1391
1265
  } catch (error) {
1392
1266
  return authRouteErrorResponse(error)
1393
1267
  }
@@ -1407,23 +1281,19 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1407
1281
  summary: "Update an auth member's groups",
1408
1282
  tags: [OPENAPI_TAGS.authMembers.name],
1409
1283
  operationId: "updateAuthMemberGroups",
1410
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
1284
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
1411
1285
  },
1412
1286
  }
1413
1287
  )
1414
1288
  .post(
1415
1289
  "/api/auth/members/:userId/suspend",
1416
- async ({ request, params }) => {
1290
+ async ({ params, ...context }) => {
1417
1291
  try {
1418
- const authOptions = resolveAuthOptions(options, request)
1292
+ const caller = requireUserCaller(context)
1419
1293
  const parsed = AuthMemberParamsSchema.parse(params)
1420
- const result = await host.auth.suspendMember(
1421
- request,
1422
- { userId: parsed.userId },
1423
- authOptions
1424
- )
1294
+ const result = await host.auth.suspendMember(caller, { userId: parsed.userId })
1425
1295
 
1426
- return jsonResponse({ member: serializeManagedMember(result.user, result.groupIds) }, 200)
1296
+ return jsonResponse({ member: serializeManagedMember(result) }, 200)
1427
1297
  } catch (error) {
1428
1298
  return authRouteErrorResponse(error)
1429
1299
  }
@@ -1441,23 +1311,19 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1441
1311
  summary: "Suspend an auth member",
1442
1312
  tags: [OPENAPI_TAGS.authMembers.name],
1443
1313
  operationId: "suspendAuthMember",
1444
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
1314
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
1445
1315
  },
1446
1316
  }
1447
1317
  )
1448
1318
  .post(
1449
1319
  "/api/auth/members/:userId/reactivate",
1450
- async ({ request, params }) => {
1320
+ async ({ params, ...context }) => {
1451
1321
  try {
1452
- const authOptions = resolveAuthOptions(options, request)
1322
+ const caller = requireUserCaller(context)
1453
1323
  const parsed = AuthMemberParamsSchema.parse(params)
1454
- const result = await host.auth.reactivateMember(
1455
- request,
1456
- { userId: parsed.userId },
1457
- authOptions
1458
- )
1324
+ const result = await host.auth.reactivateMember(caller, { userId: parsed.userId })
1459
1325
 
1460
- return jsonResponse({ member: serializeManagedMember(result.user, result.groupIds) }, 200)
1326
+ return jsonResponse({ member: serializeManagedMember(result) }, 200)
1461
1327
  } catch (error) {
1462
1328
  return authRouteErrorResponse(error)
1463
1329
  }
@@ -1475,7 +1341,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1475
1341
  summary: "Reactivate an auth member",
1476
1342
  tags: [OPENAPI_TAGS.authMembers.name],
1477
1343
  operationId: "reactivateAuthMember",
1478
- security: SIXB_CSRF_SECURITY_REQUIREMENT,
1344
+ security: SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT,
1479
1345
  },
1480
1346
  }
1481
1347
  )
@@ -1691,6 +1557,9 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1691
1557
  })
1692
1558
  } catch (error) {
1693
1559
  logAuthCallbackError("OIDC", error)
1560
+ if (error instanceof SignInRefusedError) {
1561
+ return htmlMessageResponse(signInRefusalMessage(error), 403, "You can't sign in")
1562
+ }
1694
1563
  return htmlMessageResponse("This sign-in attempt could not be completed.", 400)
1695
1564
  }
1696
1565
  }
@@ -1738,7 +1607,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1738
1607
  }
1739
1608
 
1740
1609
  const DEVICE_AUTHORIZATION_TTL_MS = 10 * 60 * 1000
1741
- const DEVICE_ACCESS_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000
1610
+ const DEVICE_AUTHORIZATIONS_PER_ADDRESS = 10
1742
1611
  const DEVICE_AUTHORIZATION_POLL_INTERVAL_SECONDS = 2
1743
1612
  const DEVICE_USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXYZ23456789"
1744
1613
 
@@ -1881,19 +1750,26 @@ async function completeMagicLinkCallback(input: {
1881
1750
  }
1882
1751
  }
1883
1752
 
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.
1753
+ function bearerTokensBody(
1754
+ tokens: { readonly accessToken: string; readonly refreshToken: string },
1755
+ bearer: { readonly accessExpiresAt: Date },
1756
+ issuedAt: Date
1757
+ ) {
1758
+ return {
1759
+ accessToken: tokens.accessToken,
1760
+ refreshToken: tokens.refreshToken,
1761
+ expiresIn: Math.round((bearer.accessExpiresAt.getTime() - issuedAt.getTime()) / 1000),
1762
+ }
1763
+ }
1764
+
1765
+ // Client metadata for the active-sessions view. Display only; never used for authorization.
1887
1766
  function resolveSessionDevice(request: Request): {
1888
1767
  readonly userAgent?: string
1889
1768
  readonly ipAddress?: string
1890
1769
  } {
1891
1770
  return {
1892
1771
  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,
1772
+ ipAddress: getRequestClientAddress(request),
1897
1773
  }
1898
1774
  }
1899
1775
 
@@ -2053,6 +1929,25 @@ function resolveSessionCsrfToken(input: {
2053
1929
  }
2054
1930
  }
2055
1931
 
1932
+ function authSessionBody(
1933
+ host: SixbHostView,
1934
+ session: AuthenticatedAuthSession,
1935
+ audience: AuthSessionAudience
1936
+ ): Omit<AuthenticatedAuthSessionResponse, "csrfToken"> {
1937
+ return {
1938
+ authenticated: true,
1939
+ applicationAccess: { allowed: sessionCanAccessApplication(host, session, audience), audience },
1940
+ user: {
1941
+ id: session.user.id,
1942
+ email: session.user.email,
1943
+ displayName: session.user.displayName,
1944
+ avatarUrl: session.user.avatarUrl,
1945
+ groupIds: [...session.groupIds],
1946
+ },
1947
+ session: { id: session.session.id, expiresAt: toIsoString(session.session.expiresAt) },
1948
+ }
1949
+ }
1950
+
2056
1951
  function authSessionJsonResponse(
2057
1952
  body: AuthenticatedAuthSessionResponse,
2058
1953
  setCookies: readonly string[]
@@ -2470,8 +2365,7 @@ function serializeAccessToken(
2470
2365
  name: accessToken.name,
2471
2366
  kind: accessToken.kind,
2472
2367
  status,
2473
- subjectType: accessToken.subjectType,
2474
- subjectId: accessToken.subjectId,
2368
+ subject: { type: accessToken.subject.type, id: accessToken.subject.id },
2475
2369
  subjectLabel: options.subjectLabel,
2476
2370
  groupIds: accessToken.groupIds ? [...accessToken.groupIds] : undefined,
2477
2371
  createdAt: toIsoString(accessToken.createdAt),
@@ -2516,29 +2410,38 @@ function optionalTrimmed(value: string | undefined): string | undefined {
2516
2410
  return trimmed ? trimmed : undefined
2517
2411
  }
2518
2412
 
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)
2413
+ // Management routes act for the caller the guard resolved: a browser session, or a personal access
2414
+ // token on bearer routes. Service-account tokens are runtime credentials and must not mint or
2415
+ // manage further credentials. The route's catch maps these errors to 401 and 403.
2416
+ function requireUserCaller(context: unknown): AuthenticatedUserRequestSession {
2417
+ const caller = requestCaller(context)
2418
+ if (!caller) {
2419
+ throw new AuthRuntimeError("authentication_required", "Authentication required")
2529
2420
  }
2530
-
2531
- if (!isAuthenticatedUserSession(session)) {
2532
- return jsonResponse({ error: "User authentication is required" }, 403)
2421
+ if (!("user" in caller)) {
2422
+ throw new AuthRuntimeError("authorization_denied", "User authentication is required")
2533
2423
  }
2424
+ return caller
2425
+ }
2534
2426
 
2535
- return session
2427
+ // Session management routes are cookie-only; the guard rejects tokens before they get here.
2428
+ function requireSessionCaller(context: unknown): AuthenticatedAuthSession | Response {
2429
+ const caller = requestCaller(context)
2430
+ return caller?.credentialSource === "session"
2431
+ ? caller
2432
+ : jsonResponse({ error: "Authentication required" }, 401)
2536
2433
  }
2537
2434
 
2538
- function isAuthenticatedUserSession(
2539
- session: AuthRequestResult & { readonly authenticated: true }
2540
- ): session is AuthenticatedUserRequestSession {
2541
- return session.principal.type === "user"
2435
+ // Ending the session behind this request also clears its cookies.
2436
+ function signedOutResponse(
2437
+ request: Request,
2438
+ cookieOptions: ResolvedCookieOptions,
2439
+ body: Record<string, unknown>
2440
+ ): Response {
2441
+ const headers = new Headers({ "content-type": "application/json; charset=utf-8" })
2442
+ headers.append("set-cookie", clearSessionCookieHeader({ request, options: cookieOptions }))
2443
+ headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }))
2444
+ return new Response(JSON.stringify(body), { status: 200, headers })
2542
2445
  }
2543
2446
 
2544
2447
  function serializeInvitation(invitation: InvitationRecord) {
@@ -2571,15 +2474,16 @@ function serializeInvitationDelivery(delivery: InviteDeliveryResult) {
2571
2474
 
2572
2475
  function serializeMemberSummary(member: MemberSummary) {
2573
2476
  return {
2574
- ...serializeManagedMember(member.user, member.groupIds),
2477
+ ...serializeManagedMember(member),
2575
2478
  capabilities: member.capabilities,
2576
2479
  }
2577
2480
  }
2578
2481
 
2579
- function serializeManagedMember(user: UserRecord, groupIds: readonly string[]) {
2482
+ function serializeManagedMember(member: Omit<MemberSummary, "capabilities">) {
2580
2483
  return {
2581
- user: serializeMemberUser(user),
2582
- groupIds: [...groupIds],
2484
+ user: serializeMemberUser(member.user),
2485
+ groupIds: [...member.groupIds],
2486
+ managedGroupIds: [...member.managedGroupIds],
2583
2487
  }
2584
2488
  }
2585
2489
 
@@ -2653,17 +2557,40 @@ function authRouteErrorResponse(error: unknown): Response {
2653
2557
  return jsonResponse({ error: String(error) }, 500)
2654
2558
  }
2655
2559
 
2560
+ function signInRefusalMessage(error: SignInRefusedError): string {
2561
+ const who = error.email ?? "This account"
2562
+ switch (error.reason) {
2563
+ case "not_invited":
2564
+ return `${who} hasn't been invited. Ask an administrator to invite this address.`
2565
+ case "suspended":
2566
+ return `${who} has been suspended. Ask an administrator to reactivate it.`
2567
+ case "domain_not_allowed":
2568
+ return `${who} isn't on a domain that can sign in here.`
2569
+ case "no_trusted_address":
2570
+ return "Your identity provider didn't share an email address this app trusts. Ask an administrator to check the sign-in setup."
2571
+ }
2572
+ }
2573
+
2656
2574
  function logAuthCallbackError(kind: string, error: unknown): void {
2657
- if (process.env.NODE_ENV !== "development" && process.env.SIXB_AUTH_DEBUG !== "1") {
2575
+ // A provider that vouches for no address is a setup mistake nobody signing in can fix, so it is
2576
+ // logged even without SIXB_AUTH_DEBUG.
2577
+ const setupMistake = error instanceof SignInRefusedError && error.reason === "no_trusted_address"
2578
+ if (
2579
+ !setupMistake &&
2580
+ process.env.NODE_ENV !== "development" &&
2581
+ process.env.SIXB_AUTH_DEBUG !== "1"
2582
+ ) {
2658
2583
  return
2659
2584
  }
2660
2585
 
2661
2586
  const detail =
2662
2587
  error instanceof AuthStorageError
2663
2588
  ? `${error.name}(${error.code}): ${error.message}`
2664
- : error instanceof Error
2665
- ? `${error.name}: ${error.message}`
2666
- : String(error)
2589
+ : error instanceof SignInRefusedError
2590
+ ? `${error.name}(${error.reason}): ${error.message}`
2591
+ : error instanceof Error
2592
+ ? `${error.name}: ${error.message}`
2593
+ : String(error)
2667
2594
 
2668
2595
  console.error(`[SixbServer] ${kind} auth callback failed: ${detail}`)
2669
2596
  }