@sixb/server 0.1.1 → 0.1.3

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 (178) hide show
  1. package/README.md +3 -3
  2. package/dist/auth/application-access.d.ts +2 -2
  3. package/dist/auth/application-access.d.ts.map +1 -1
  4. package/dist/auth/connector-callback-cookie.d.ts +12 -0
  5. package/dist/auth/connector-callback-cookie.d.ts.map +1 -0
  6. package/dist/auth/experience.d.ts +33 -0
  7. package/dist/auth/experience.d.ts.map +1 -0
  8. package/dist/auth/guard.d.ts +3 -3
  9. package/dist/auth/guard.d.ts.map +1 -1
  10. package/dist/auth/public-routes.d.ts.map +1 -1
  11. package/dist/auth/scope.d.ts +13 -27
  12. package/dist/auth/scope.d.ts.map +1 -1
  13. package/dist/auth/session-cookies.d.ts +2 -2
  14. package/dist/auth/session-cookies.d.ts.map +1 -1
  15. package/dist/connectors/http.d.ts +16 -0
  16. package/dist/connectors/http.d.ts.map +1 -0
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +3903 -2760
  20. package/dist/index.js.map +58 -50
  21. package/dist/openapi/tags.d.ts +15 -3
  22. package/dist/openapi/tags.d.ts.map +1 -1
  23. package/dist/registerRoutes.d.ts +6 -2
  24. package/dist/registerRoutes.d.ts.map +1 -1
  25. package/dist/routes/action-runs.d.ts +21 -31
  26. package/dist/routes/action-runs.d.ts.map +1 -1
  27. package/dist/routes/actions.d.ts +12 -11
  28. package/dist/routes/actions.d.ts.map +1 -1
  29. package/dist/routes/agent-api-gateway.d.ts +2 -2
  30. package/dist/routes/agent-api-gateway.d.ts.map +1 -1
  31. package/dist/routes/agents.d.ts +230 -159
  32. package/dist/routes/agents.d.ts.map +1 -1
  33. package/dist/routes/ai-accounting.d.ts +31 -0
  34. package/dist/routes/ai-accounting.d.ts.map +1 -0
  35. package/dist/routes/auth.d.ts +149 -92
  36. package/dist/routes/auth.d.ts.map +1 -1
  37. package/dist/routes/connector-connection-runs.d.ts +794 -0
  38. package/dist/routes/connector-connection-runs.d.ts.map +1 -0
  39. package/dist/routes/connector-connections.d.ts +219 -0
  40. package/dist/routes/connector-connections.d.ts.map +1 -0
  41. package/dist/routes/connectors.d.ts +10 -4
  42. package/dist/routes/connectors.d.ts.map +1 -1
  43. package/dist/routes/datasets.d.ts +16 -12
  44. package/dist/routes/datasets.d.ts.map +1 -1
  45. package/dist/routes/events.d.ts +9 -9
  46. package/dist/routes/events.d.ts.map +1 -1
  47. package/dist/routes/files.d.ts +19 -18
  48. package/dist/routes/files.d.ts.map +1 -1
  49. package/dist/routes/links.d.ts +11 -11
  50. package/dist/routes/links.d.ts.map +1 -1
  51. package/dist/routes/logs.d.ts +5 -5
  52. package/dist/routes/logs.d.ts.map +1 -1
  53. package/dist/routes/objects.d.ts +37 -37
  54. package/dist/routes/objects.d.ts.map +1 -1
  55. package/dist/routes/ontology.d.ts +50 -50
  56. package/dist/routes/ontology.d.ts.map +1 -1
  57. package/dist/routes/pipelines.d.ts +28 -38
  58. package/dist/routes/pipelines.d.ts.map +1 -1
  59. package/dist/routes/project.d.ts +2 -2
  60. package/dist/routes/project.d.ts.map +1 -1
  61. package/dist/routes/projections.d.ts +145 -85
  62. package/dist/routes/projections.d.ts.map +1 -1
  63. package/dist/routes/rules.d.ts +6 -6
  64. package/dist/routes/rules.d.ts.map +1 -1
  65. package/dist/routes/status.d.ts +2 -2
  66. package/dist/routes/status.d.ts.map +1 -1
  67. package/dist/routes/syncs.d.ts +23 -28
  68. package/dist/routes/syncs.d.ts.map +1 -1
  69. package/dist/routes/telemetry.d.ts +9 -9
  70. package/dist/routes/telemetry.d.ts.map +1 -1
  71. package/dist/routes/webhook-runs.d.ts +9 -9
  72. package/dist/routes/webhook-runs.d.ts.map +1 -1
  73. package/dist/routes/webhooks.d.ts +2 -2
  74. package/dist/routes/webhooks.d.ts.map +1 -1
  75. package/dist/routes/workflows.d.ts +177 -66
  76. package/dist/routes/workflows.d.ts.map +1 -1
  77. package/dist/routes/ws/agents.d.ts +11 -5
  78. package/dist/routes/ws/agents.d.ts.map +1 -1
  79. package/dist/routes/ws/events.d.ts +8 -8
  80. package/dist/routes/ws/events.d.ts.map +1 -1
  81. package/dist/routes/ws/log-subscription-hub.d.ts +6 -3
  82. package/dist/routes/ws/log-subscription-hub.d.ts.map +1 -1
  83. package/dist/routes/ws/logs.d.ts +10 -10
  84. package/dist/routes/ws/logs.d.ts.map +1 -1
  85. package/dist/schemas/actions.d.ts +89 -194
  86. package/dist/schemas/actions.d.ts.map +1 -1
  87. package/dist/schemas/agents.d.ts +791 -471
  88. package/dist/schemas/agents.d.ts.map +1 -1
  89. package/dist/schemas/ai-accounting.d.ts +2393 -0
  90. package/dist/schemas/ai-accounting.d.ts.map +1 -0
  91. package/dist/schemas/ai-usage.d.ts +34 -0
  92. package/dist/schemas/ai-usage.d.ts.map +1 -0
  93. package/dist/schemas/auth.d.ts +102 -102
  94. package/dist/schemas/common.d.ts +37 -0
  95. package/dist/schemas/common.d.ts.map +1 -1
  96. package/dist/schemas/connectors.d.ts +713 -2
  97. package/dist/schemas/connectors.d.ts.map +1 -1
  98. package/dist/schemas/datasets.d.ts +2 -2
  99. package/dist/schemas/event-payloads.d.ts +12 -12
  100. package/dist/schemas/events.d.ts +40 -40
  101. package/dist/schemas/links.d.ts +2 -2
  102. package/dist/schemas/logs.d.ts +22 -22
  103. package/dist/schemas/objects.d.ts +10 -10
  104. package/dist/schemas/ontology.d.ts +118 -118
  105. package/dist/schemas/pipelines.d.ts +89 -184
  106. package/dist/schemas/pipelines.d.ts.map +1 -1
  107. package/dist/schemas/projections.d.ts +1030 -563
  108. package/dist/schemas/projections.d.ts.map +1 -1
  109. package/dist/schemas/rules.d.ts +6 -6
  110. package/dist/schemas/syncs.d.ts +65 -108
  111. package/dist/schemas/syncs.d.ts.map +1 -1
  112. package/dist/schemas/webhook-runs.d.ts +41 -41
  113. package/dist/schemas/webhook-runs.d.ts.map +1 -1
  114. package/dist/schemas/workflows.d.ts +1189 -185
  115. package/dist/schemas/workflows.d.ts.map +1 -1
  116. package/dist/server.d.ts +11 -6
  117. package/dist/server.d.ts.map +1 -1
  118. package/dist/utils/http.d.ts +2 -0
  119. package/dist/utils/http.d.ts.map +1 -1
  120. package/dist/utils/ws.d.ts +4 -3
  121. package/dist/utils/ws.d.ts.map +1 -1
  122. package/package.json +5 -5
  123. package/src/auth/access-token-boundary.ts +4 -4
  124. package/src/auth/application-access.ts +8 -9
  125. package/src/auth/connector-callback-cookie.ts +95 -0
  126. package/src/auth/experience.ts +190 -0
  127. package/src/auth/guard.ts +11 -11
  128. package/src/auth/public-routes.ts +20 -0
  129. package/src/auth/scope.ts +26 -36
  130. package/src/auth/session-cookies.ts +3 -3
  131. package/src/connectors/http.ts +110 -0
  132. package/src/index.ts +1 -0
  133. package/src/openapi/tags.ts +13 -1
  134. package/src/registerRoutes.ts +36 -23
  135. package/src/routes/action-runs.ts +39 -39
  136. package/src/routes/actions.ts +7 -13
  137. package/src/routes/agent-api-gateway.ts +41 -38
  138. package/src/routes/agents.ts +90 -200
  139. package/src/routes/ai-accounting.ts +166 -0
  140. package/src/routes/auth.ts +274 -122
  141. package/src/routes/connector-connection-runs.ts +346 -0
  142. package/src/routes/connector-connections.ts +135 -0
  143. package/src/routes/connectors.ts +24 -12
  144. package/src/routes/datasets.ts +55 -54
  145. package/src/routes/events.ts +5 -5
  146. package/src/routes/files.ts +22 -30
  147. package/src/routes/links.ts +31 -35
  148. package/src/routes/logs.ts +6 -11
  149. package/src/routes/objects.ts +51 -114
  150. package/src/routes/ontology.ts +27 -38
  151. package/src/routes/pipelines.ts +28 -62
  152. package/src/routes/project.ts +3 -3
  153. package/src/routes/projections.ts +44 -42
  154. package/src/routes/rules.ts +11 -25
  155. package/src/routes/status.ts +5 -5
  156. package/src/routes/syncs.ts +19 -45
  157. package/src/routes/telemetry.ts +18 -29
  158. package/src/routes/webhook-runs.ts +5 -5
  159. package/src/routes/webhooks.ts +259 -341
  160. package/src/routes/workflows.ts +242 -248
  161. package/src/routes/ws/agents.ts +196 -66
  162. package/src/routes/ws/events.ts +11 -10
  163. package/src/routes/ws/log-subscription-hub.ts +6 -12
  164. package/src/routes/ws/logs.ts +13 -5
  165. package/src/schemas/actions.ts +58 -25
  166. package/src/schemas/agents.ts +23 -23
  167. package/src/schemas/ai-accounting.ts +182 -0
  168. package/src/schemas/ai-usage.ts +16 -0
  169. package/src/schemas/common.ts +24 -0
  170. package/src/schemas/connectors.ts +164 -0
  171. package/src/schemas/pipelines.ts +23 -15
  172. package/src/schemas/projections.ts +23 -3
  173. package/src/schemas/syncs.ts +13 -8
  174. package/src/schemas/webhook-runs.ts +10 -5
  175. package/src/schemas/workflows.ts +23 -8
  176. package/src/server.ts +75 -26
  177. package/src/utils/http.ts +34 -6
  178. package/src/utils/ws.ts +10 -5
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto"
2
- import type { AuthSessionAudience, GroupDefinition, OntologySource, Sixb } from "@sixb/core"
2
+ import type { AuthSessionAudience, GroupDefinition, SixbHostView } from "@sixb/core"
3
3
  import {
4
4
  type AuthenticatedUserRequestSession,
5
5
  type AuthRequestResult,
@@ -39,6 +39,11 @@ import {
39
39
  type ResolveRequestAuthContext,
40
40
  } from "../auth/browser-origin"
41
41
  import { CSRF_TOKEN_RESPONSE_HEADER_NAME } from "../auth/csrf"
42
+ import {
43
+ customAuthExperienceAssetResponse,
44
+ customAuthExperienceResponse,
45
+ type SixbAuthExperienceOptions,
46
+ } from "../auth/experience"
42
47
  import { hasForegroundSessionActivity } from "../auth/session-activity"
43
48
  import { createSessionRenewalCookieHeaders } from "../auth/session-cookies"
44
49
  import { SIXB_CSRF_SECURITY_REQUIREMENT } from "../openapi/security"
@@ -115,30 +120,37 @@ export interface AuthRoutesOptions {
115
120
  request: Request,
116
121
  input: AuthInvitationRedirectInput
117
122
  ) => AuthInvitationRedirectContext
123
+ readonly authExperience?: SixbAuthExperienceOptions
118
124
  }
119
125
 
120
- export function registerAuthRoutes(
121
- app: Elysia,
122
- sixb: Sixb<readonly OntologySource[]>,
123
- options: AuthRoutesOptions
124
- ) {
126
+ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: AuthRoutesOptions) {
125
127
  return app
128
+ .get(
129
+ "/auth/assets/*",
130
+ async ({ request }) => customAuthExperienceAssetResponse(options.authExperience, request),
131
+ { detail: { hide: true } }
132
+ )
133
+ .head(
134
+ "/auth/assets/*",
135
+ async ({ request }) => customAuthExperienceAssetResponse(options.authExperience, request),
136
+ { detail: { hide: true } }
137
+ )
126
138
  .get(
127
139
  "/api/auth/session",
128
140
  async ({ request }) => {
129
141
  const authOptions = resolveAuthOptions(options, request)
130
- let session = await sixb.auth.getSession(request, authOptions)
142
+ let session = await host.auth.getSession(request, authOptions)
131
143
  if (!session.authenticated) {
132
144
  return jsonResponse({ authenticated: false as const }, 200)
133
145
  }
134
146
 
135
147
  let applicationAccessAllowed = sessionCanAccessApplication(
136
- sixb,
148
+ host,
137
149
  session,
138
150
  authOptions.audience
139
151
  )
140
152
  if (applicationAccessAllowed && hasForegroundSessionActivity(request)) {
141
- session = await sixb.auth.getSession(request, {
153
+ session = await host.auth.getSession(request, {
142
154
  ...authOptions,
143
155
  sessionActivity: "foreground",
144
156
  })
@@ -146,13 +158,13 @@ export function registerAuthRoutes(
146
158
  return jsonResponse({ authenticated: false as const }, 200)
147
159
  }
148
160
  applicationAccessAllowed = sessionCanAccessApplication(
149
- sixb,
161
+ host,
150
162
  session,
151
163
  authOptions.audience
152
164
  )
153
165
  }
154
166
 
155
- const cookieOptions = sixb.auth.getCookieOptions(authOptions)
167
+ const cookieOptions = host.auth.getCookieOptions(authOptions)
156
168
  const csrf = resolveSessionCsrfToken({
157
169
  request,
158
170
  cookieOptions,
@@ -161,7 +173,7 @@ export function registerAuthRoutes(
161
173
  const renewal =
162
174
  session.sessionRenewed === true
163
175
  ? createSessionRenewalCookieHeaders({
164
- sixb,
176
+ host,
165
177
  request,
166
178
  session,
167
179
  csrfToken: csrf.token,
@@ -203,8 +215,8 @@ export function registerAuthRoutes(
203
215
  "/api/auth/sign-out",
204
216
  async ({ request }) => {
205
217
  const authOptions = resolveAuthOptions(options, request)
206
- const session = await sixb.auth.getSession(request, authOptions)
207
- const cookieOptions = sixb.auth.getCookieOptions(authOptions)
218
+ const session = await host.auth.getSession(request, authOptions)
219
+ const cookieOptions = host.auth.getCookieOptions(authOptions)
208
220
  if (
209
221
  session.authenticated &&
210
222
  !verifyDoubleSubmitCsrf(request, {
@@ -215,13 +227,13 @@ export function registerAuthRoutes(
215
227
  }
216
228
 
217
229
  if (session.authenticated) {
218
- await sixb.storage.auth?.sessions.revoke({
219
- projectId: sixb.id,
230
+ await host.storage.auth?.sessions.revoke({
231
+ projectId: host.id,
220
232
  id: session.session.id,
221
233
  revokedAt: new Date(),
222
234
  })
223
235
  // Drop the cached session immediately so it isn't honored for the cache TTL.
224
- sixb.auth.invalidateSession(session.session.id)
236
+ host.auth.invalidateSession(session.session.id)
225
237
  }
226
238
 
227
239
  const headers = new Headers({ "content-type": "application/json; charset=utf-8" })
@@ -250,13 +262,13 @@ export function registerAuthRoutes(
250
262
  "/api/auth/sessions",
251
263
  async ({ request }) => {
252
264
  const authOptions = resolveAuthOptions(options, request)
253
- const session = await sixb.auth.getSession(request, authOptions)
265
+ const session = await host.auth.getSession(request, authOptions)
254
266
  if (!session.authenticated) {
255
267
  return jsonResponse({ error: "Authentication required" }, 401)
256
268
  }
257
269
 
258
- const sessions = await requireAuthStorage(sixb).sessions.listActiveByUserId({
259
- projectId: sixb.id,
270
+ const sessions = await requireAuthStorage(host).sessions.listActiveByUserId({
271
+ projectId: host.id,
260
272
  userId: session.user.id,
261
273
  now: new Date(),
262
274
  })
@@ -293,8 +305,8 @@ export function registerAuthRoutes(
293
305
  "/api/auth/sessions/:sessionId/revoke",
294
306
  async ({ request, params }) => {
295
307
  const authOptions = resolveAuthOptions(options, request)
296
- const session = await sixb.auth.getSession(request, authOptions)
297
- const cookieOptions = sixb.auth.getCookieOptions(authOptions)
308
+ const session = await host.auth.getSession(request, authOptions)
309
+ const cookieOptions = host.auth.getCookieOptions(authOptions)
298
310
  if (!session.authenticated) {
299
311
  return jsonResponse({ error: "Authentication required" }, 401)
300
312
  }
@@ -303,16 +315,16 @@ export function registerAuthRoutes(
303
315
  }
304
316
 
305
317
  const { sessionId } = RevokeAuthSessionParamsSchema.parse(params)
306
- const storage = requireAuthStorage(sixb)
307
- const target = await storage.sessions.getById({ projectId: sixb.id, id: sessionId })
318
+ const storage = requireAuthStorage(host)
319
+ const target = await storage.sessions.getById({ projectId: host.id, id: sessionId })
308
320
  // Only the caller's own sessions are revocable. A missing or foreign
309
321
  // session id returns the same 404 so it cannot probe other accounts.
310
322
  if (!target || target.userId !== session.user.id) {
311
323
  return jsonResponse({ error: "Session not found" }, 404)
312
324
  }
313
325
 
314
- await storage.sessions.revoke({ projectId: sixb.id, id: sessionId, revokedAt: new Date() })
315
- sixb.auth.invalidateSession(sessionId)
326
+ await storage.sessions.revoke({ projectId: host.id, id: sessionId, revokedAt: new Date() })
327
+ host.auth.invalidateSession(sessionId)
316
328
 
317
329
  const headers = new Headers({ "content-type": "application/json; charset=utf-8" })
318
330
  // Revoking the session backing this request also clears its cookies.
@@ -346,8 +358,8 @@ export function registerAuthRoutes(
346
358
  "/api/auth/sign-out-all",
347
359
  async ({ request }) => {
348
360
  const authOptions = resolveAuthOptions(options, request)
349
- const session = await sixb.auth.getSession(request, authOptions)
350
- const cookieOptions = sixb.auth.getCookieOptions(authOptions)
361
+ const session = await host.auth.getSession(request, authOptions)
362
+ const cookieOptions = host.auth.getCookieOptions(authOptions)
351
363
  if (!session.authenticated) {
352
364
  return jsonResponse({ error: "Authentication required" }, 401)
353
365
  }
@@ -358,13 +370,13 @@ export function registerAuthRoutes(
358
370
  // Global sign-out: revoke every active session for the user across all
359
371
  // audiences. Other audiences' cookies remain client-side but their
360
372
  // sessions are revoked, so the next request re-authenticates.
361
- const revoked = await requireAuthStorage(sixb).sessions.revokeActiveForUser({
362
- projectId: sixb.id,
373
+ const revoked = await requireAuthStorage(host).sessions.revokeActiveForUser({
374
+ projectId: host.id,
363
375
  userId: session.user.id,
364
376
  revokedAt: new Date(),
365
377
  })
366
378
  for (const revokedSession of revoked) {
367
- sixb.auth.invalidateSession(revokedSession.id)
379
+ host.auth.invalidateSession(revokedSession.id)
368
380
  }
369
381
 
370
382
  const headers = new Headers({ "content-type": "application/json; charset=utf-8" })
@@ -396,7 +408,7 @@ export function registerAuthRoutes(
396
408
  try {
397
409
  const authOptions = resolveAuthOptions(options, request)
398
410
  const session = requireAuthenticatedUserSession(
399
- await sixb.auth.getSession(request, {
411
+ await host.auth.getSession(request, {
400
412
  ...authOptions,
401
413
  credentialSource: "any",
402
414
  })
@@ -409,7 +421,7 @@ export function registerAuthRoutes(
409
421
 
410
422
  return jsonResponse(
411
423
  {
412
- groups: sixb.security
424
+ groups: host.definitions.security
413
425
  .listGroups()
414
426
  // V1 avoids privilege escalation by only offering groups the
415
427
  // current session already has. Runtime token auth still
@@ -443,7 +455,7 @@ export function registerAuthRoutes(
443
455
  try {
444
456
  const authOptions = resolveAuthOptions(options, request)
445
457
  const session = requireAuthenticatedUserSession(
446
- await sixb.auth.getSession(request, {
458
+ await host.auth.getSession(request, {
447
459
  ...authOptions,
448
460
  credentialSource: "any",
449
461
  })
@@ -452,7 +464,7 @@ export function registerAuthRoutes(
452
464
  return session
453
465
  }
454
466
 
455
- const { accessTokens } = await sixb.auth.listPersonalAccessTokens(request, authOptions)
467
+ const { accessTokens } = await host.auth.listPersonalAccessTokens(request, authOptions)
456
468
 
457
469
  return jsonResponse(
458
470
  {
@@ -487,7 +499,7 @@ export function registerAuthRoutes(
487
499
  const authOptions = resolveAuthOptions(options, request)
488
500
  const parsed = CreateAuthPersonalAccessTokenBodySchema.parse(body)
489
501
  const session = requireAuthenticatedUserSession(
490
- await sixb.auth.getSession(request, {
502
+ await host.auth.getSession(request, {
491
503
  ...authOptions,
492
504
  credentialSource: "any",
493
505
  })
@@ -497,7 +509,7 @@ export function registerAuthRoutes(
497
509
  }
498
510
 
499
511
  const expiresAt = parseRequiredFutureDate(parsed.expiresAt)
500
- const result = await sixb.auth.createPersonalAccessToken(
512
+ const result = await host.auth.createPersonalAccessToken(
501
513
  request,
502
514
  { name: parsed.name, expiresAt, groupIds: parsed.groupIds },
503
515
  authOptions
@@ -541,7 +553,7 @@ export function registerAuthRoutes(
541
553
  try {
542
554
  const authOptions = resolveAuthOptions(options, request)
543
555
  const session = requireAuthenticatedUserSession(
544
- await sixb.auth.getSession(request, {
556
+ await host.auth.getSession(request, {
545
557
  ...authOptions,
546
558
  credentialSource: "any",
547
559
  })
@@ -551,7 +563,7 @@ export function registerAuthRoutes(
551
563
  }
552
564
 
553
565
  const { tokenId } = RevokeAuthAccessTokenParamsSchema.parse(params)
554
- const result = await sixb.auth.revokePersonalAccessToken(
566
+ const result = await host.auth.revokePersonalAccessToken(
555
567
  request,
556
568
  { tokenId },
557
569
  authOptions
@@ -591,11 +603,11 @@ export function registerAuthRoutes(
591
603
  try {
592
604
  const authOptions = resolveAuthOptions(options, request)
593
605
  const session = requireAuthenticatedUserSession(
594
- await sixb.auth.getSession(request, { ...authOptions, credentialSource: "any" })
606
+ await host.auth.getSession(request, { ...authOptions, credentialSource: "any" })
595
607
  )
596
608
  if (session instanceof Response) return session
597
609
 
598
- const { serviceAccounts } = await sixb.auth.listServiceAccounts(request, authOptions)
610
+ const { serviceAccounts } = await host.auth.listServiceAccounts(request, authOptions)
599
611
 
600
612
  return jsonResponse(
601
613
  {
@@ -631,11 +643,11 @@ export function registerAuthRoutes(
631
643
  const authOptions = resolveAuthOptions(options, request)
632
644
  const parsed = CreateAuthServiceAccountBodySchema.parse(body)
633
645
  const session = requireAuthenticatedUserSession(
634
- await sixb.auth.getSession(request, { ...authOptions, credentialSource: "any" })
646
+ await host.auth.getSession(request, { ...authOptions, credentialSource: "any" })
635
647
  )
636
648
  if (session instanceof Response) return session
637
649
 
638
- const result = await sixb.auth.createServiceAccount(
650
+ const result = await host.auth.createServiceAccount(
639
651
  request,
640
652
  {
641
653
  id: parsed.id,
@@ -682,12 +694,12 @@ export function registerAuthRoutes(
682
694
  try {
683
695
  const authOptions = resolveAuthOptions(options, request)
684
696
  const session = requireAuthenticatedUserSession(
685
- await sixb.auth.getSession(request, { ...authOptions, credentialSource: "any" })
697
+ await host.auth.getSession(request, { ...authOptions, credentialSource: "any" })
686
698
  )
687
699
  if (session instanceof Response) return session
688
700
 
689
701
  const { serviceAccountId } = AuthServiceAccountParamsSchema.parse(params)
690
- const result = await sixb.auth.disableServiceAccount(
702
+ const result = await host.auth.disableServiceAccount(
691
703
  request,
692
704
  { serviceAccountId },
693
705
  authOptions
@@ -726,12 +738,12 @@ export function registerAuthRoutes(
726
738
  try {
727
739
  const authOptions = resolveAuthOptions(options, request)
728
740
  const session = requireAuthenticatedUserSession(
729
- await sixb.auth.getSession(request, { ...authOptions, credentialSource: "any" })
741
+ await host.auth.getSession(request, { ...authOptions, credentialSource: "any" })
730
742
  )
731
743
  if (session instanceof Response) return session
732
744
 
733
745
  const { serviceAccountId } = AuthServiceAccountParamsSchema.parse(params)
734
- const { serviceAccount, accessTokens } = await sixb.auth.listServiceAccountAccessTokens(
746
+ const { serviceAccount, accessTokens } = await host.auth.listServiceAccountAccessTokens(
735
747
  request,
736
748
  { serviceAccountId },
737
749
  authOptions
@@ -774,12 +786,12 @@ export function registerAuthRoutes(
774
786
  const parsedParams = AuthServiceAccountParamsSchema.parse(params)
775
787
  const parsed = CreateAuthServiceAccountAccessTokenBodySchema.parse(body)
776
788
  const session = requireAuthenticatedUserSession(
777
- await sixb.auth.getSession(request, { ...authOptions, credentialSource: "any" })
789
+ await host.auth.getSession(request, { ...authOptions, credentialSource: "any" })
778
790
  )
779
791
  if (session instanceof Response) return session
780
792
 
781
793
  const expiresAt = parseRequiredFutureDate(parsed.expiresAt)
782
- const result = await sixb.auth.createServiceAccountAccessToken(
794
+ const result = await host.auth.createServiceAccountAccessToken(
783
795
  request,
784
796
  {
785
797
  serviceAccountId: parsedParams.serviceAccountId,
@@ -829,11 +841,11 @@ export function registerAuthRoutes(
829
841
  const authOptions = resolveAuthOptions(options, request)
830
842
  const parsed = RevokeAuthServiceAccountAccessTokenParamsSchema.parse(params)
831
843
  const session = requireAuthenticatedUserSession(
832
- await sixb.auth.getSession(request, { ...authOptions, credentialSource: "any" })
844
+ await host.auth.getSession(request, { ...authOptions, credentialSource: "any" })
833
845
  )
834
846
  if (session instanceof Response) return session
835
847
 
836
- const result = await sixb.auth.revokeServiceAccountAccessToken(
848
+ const result = await host.auth.revokeServiceAccountAccessToken(
837
849
  request,
838
850
  { serviceAccountId: parsed.serviceAccountId, tokenId: parsed.tokenId },
839
851
  authOptions
@@ -882,7 +894,7 @@ export function registerAuthRoutes(
882
894
  return deliveryContext
883
895
  }
884
896
 
885
- const result = await sixb.auth.invite(
897
+ const result = await host.auth.invite(
886
898
  request,
887
899
  {
888
900
  email: parsed.email,
@@ -937,7 +949,7 @@ export function registerAuthRoutes(
937
949
  const authOptions = resolveAuthOptions(options, request)
938
950
  return jsonResponse(
939
951
  {
940
- ...(await sixb.auth.getInvitationOptions(request, authOptions)),
952
+ ...(await host.auth.getInvitationOptions(request, authOptions)),
941
953
  ...options.getInvitationDestinationOptions(request),
942
954
  },
943
955
  200
@@ -965,7 +977,7 @@ export function registerAuthRoutes(
965
977
  try {
966
978
  const authOptions = resolveAuthOptions(options, request)
967
979
  const parsed = ListAuthInvitationsQuerySchema.parse(query)
968
- const result = await sixb.auth.listInvitations(
980
+ const result = await host.auth.listInvitations(
969
981
  request,
970
982
  {
971
983
  email: parsed.email,
@@ -1012,7 +1024,7 @@ export function registerAuthRoutes(
1012
1024
  try {
1013
1025
  const authOptions = resolveAuthOptions(options, request)
1014
1026
  const parsed = RevokeAuthInvitationParamsSchema.parse(params)
1015
- const result = await sixb.auth.revokeInvitation(
1027
+ const result = await host.auth.revokeInvitation(
1016
1028
  request,
1017
1029
  {
1018
1030
  invitationId: parsed.invitationId,
@@ -1053,7 +1065,7 @@ export function registerAuthRoutes(
1053
1065
  async ({ request }) => {
1054
1066
  try {
1055
1067
  const authOptions = resolveAuthOptions(options, request)
1056
- return jsonResponse(await sixb.auth.getMembershipOptions(request, authOptions), 200)
1068
+ return jsonResponse(await host.auth.getMembershipOptions(request, authOptions), 200)
1057
1069
  } catch (error) {
1058
1070
  return authRouteErrorResponse(error)
1059
1071
  }
@@ -1077,7 +1089,7 @@ export function registerAuthRoutes(
1077
1089
  try {
1078
1090
  const authOptions = resolveAuthOptions(options, request)
1079
1091
  const parsed = ListAuthMembersQuerySchema.parse(query)
1080
- const result = await sixb.auth.listMembers(
1092
+ const result = await host.auth.listMembers(
1081
1093
  request,
1082
1094
  {
1083
1095
  limit: parseOptionalInt(parsed.limit),
@@ -1121,7 +1133,7 @@ export function registerAuthRoutes(
1121
1133
  const authOptions = resolveAuthOptions(options, request)
1122
1134
  const parsedParams = AuthMemberParamsSchema.parse(params)
1123
1135
  const parsed = UpdateAuthMemberGroupsBodySchema.parse(body)
1124
- const result = await sixb.auth.updateMemberGroups(
1136
+ const result = await host.auth.updateMemberGroups(
1125
1137
  request,
1126
1138
  { userId: parsedParams.userId, groupIds: parsed.groupIds },
1127
1139
  authOptions
@@ -1157,7 +1169,7 @@ export function registerAuthRoutes(
1157
1169
  try {
1158
1170
  const authOptions = resolveAuthOptions(options, request)
1159
1171
  const parsed = AuthMemberParamsSchema.parse(params)
1160
- const result = await sixb.auth.suspendMember(
1172
+ const result = await host.auth.suspendMember(
1161
1173
  request,
1162
1174
  { userId: parsed.userId },
1163
1175
  authOptions
@@ -1191,7 +1203,7 @@ export function registerAuthRoutes(
1191
1203
  try {
1192
1204
  const authOptions = resolveAuthOptions(options, request)
1193
1205
  const parsed = AuthMemberParamsSchema.parse(params)
1194
- const result = await sixb.auth.reactivateMember(
1206
+ const result = await host.auth.reactivateMember(
1195
1207
  request,
1196
1208
  { userId: parsed.userId },
1197
1209
  authOptions
@@ -1222,7 +1234,7 @@ export function registerAuthRoutes(
1222
1234
  .post(
1223
1235
  "/auth/sign-in",
1224
1236
  async ({ body, request }) => {
1225
- const strategy = sixb.auth.getStrategy()
1237
+ const strategy = host.auth.getStrategy()
1226
1238
  const authRedirect = resolveAuthRedirectContext(options, request, {
1227
1239
  audience: body.audience,
1228
1240
  returnTo: body.returnTo,
@@ -1231,12 +1243,12 @@ export function registerAuthRoutes(
1231
1243
  return authRedirect
1232
1244
  }
1233
1245
 
1234
- const authStorage = requireAuthStorage(sixb)
1246
+ const authStorage = requireAuthStorage(host)
1235
1247
 
1236
1248
  if (isMagicLinkAuthStrategy(strategy)) {
1237
1249
  const pending = createMagicLinkPendingCredential()
1238
1250
  const result = await strategy.requestMagicLink({
1239
- projectId: sixb.id,
1251
+ projectId: host.id,
1240
1252
  authStorage,
1241
1253
  email: body.email ?? "",
1242
1254
  audience: authRedirect.audience,
@@ -1245,11 +1257,7 @@ export function registerAuthRoutes(
1245
1257
  requesterHash: pending.hash,
1246
1258
  })
1247
1259
 
1248
- const response = htmlMessageResponse(
1249
- "If this email can sign in, we sent a link. Check your inbox to continue.",
1250
- 200,
1251
- "Check your email"
1252
- )
1260
+ const response = await magicLinkRequestedResponse(options, authRedirect)
1253
1261
  // Same-device fast path: this browser keeps the preimage of the
1254
1262
  // `requester` hash embedded in the emailed callback URL, so opening
1255
1263
  // the link here signs in without the confirmation click. Always
@@ -1263,7 +1271,7 @@ export function registerAuthRoutes(
1263
1271
  "set-cookie",
1264
1272
  magicLinkPendingCookieHeader({
1265
1273
  request,
1266
- sixb,
1274
+ host,
1267
1275
  value: result.status === "sent" ? pending.secret : existingPending || pending.secret,
1268
1276
  maxAgeSeconds: magicLinkPendingCookieMaxAgeSeconds(strategy),
1269
1277
  })
@@ -1273,7 +1281,7 @@ export function registerAuthRoutes(
1273
1281
 
1274
1282
  if (isOidcAuthStrategy(strategy)) {
1275
1283
  const result = await strategy.startOidcSignIn({
1276
- projectId: sixb.id,
1284
+ projectId: host.id,
1277
1285
  authStorage,
1278
1286
  audience: authRedirect.audience,
1279
1287
  returnTo: authRedirect.returnTo,
@@ -1297,7 +1305,7 @@ export function registerAuthRoutes(
1297
1305
  .get(
1298
1306
  "/auth/sign-in",
1299
1307
  async ({ request }) => {
1300
- const strategy = sixb.auth.getStrategy()
1308
+ const strategy = host.auth.getStrategy()
1301
1309
  const url = new URL(request.url)
1302
1310
  const authRedirect = resolveAuthRedirectContext(options, request, {
1303
1311
  audience: url.searchParams.get("audience"),
@@ -1308,13 +1316,13 @@ export function registerAuthRoutes(
1308
1316
  }
1309
1317
 
1310
1318
  if (isMagicLinkAuthStrategy(strategy)) {
1311
- return signInFormResponse(authRedirect)
1319
+ return await signInFormResponse(options, authRedirect)
1312
1320
  }
1313
1321
 
1314
1322
  if (isOidcAuthStrategy(strategy)) {
1315
1323
  const result = await strategy.startOidcSignIn({
1316
- projectId: sixb.id,
1317
- authStorage: requireAuthStorage(sixb),
1324
+ projectId: host.id,
1325
+ authStorage: requireAuthStorage(host),
1318
1326
  audience: authRedirect.audience,
1319
1327
  returnTo: authRedirect.returnTo,
1320
1328
  requestOrigin: authRedirect.requestOrigin,
@@ -1329,15 +1337,20 @@ export function registerAuthRoutes(
1329
1337
  .get(
1330
1338
  "/auth/callback",
1331
1339
  async ({ request }) => {
1332
- const strategy = sixb.auth.getStrategy()
1340
+ const strategy = host.auth.getStrategy()
1333
1341
 
1334
1342
  if (isMagicLinkAuthStrategy(strategy)) {
1335
1343
  const url = new URL(request.url)
1336
1344
  const magicLinkId = url.searchParams.get("magicLinkId")?.trim()
1337
1345
  const token = url.searchParams.get("token")?.trim()
1346
+ const authRedirectHint = resolveAuthExperienceRedirectHint(
1347
+ options,
1348
+ request,
1349
+ url.searchParams.get("audience")
1350
+ )
1338
1351
 
1339
1352
  if (!magicLinkId || !token) {
1340
- return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
1353
+ return await invalidMagicLinkResponse(options, authRedirectHint)
1341
1354
  }
1342
1355
 
1343
1356
  // Read-only peek so the page can greet the user by email and dead
@@ -1351,17 +1364,18 @@ export function registerAuthRoutes(
1351
1364
  if (strategy.peekMagicLink) {
1352
1365
  try {
1353
1366
  const peeked = await strategy.peekMagicLink({
1354
- projectId: sixb.id,
1355
- authStorage: requireAuthStorage(sixb),
1367
+ projectId: host.id,
1368
+ authStorage: requireAuthStorage(host),
1356
1369
  magicLinkId,
1357
1370
  token,
1358
1371
  })
1359
1372
  if (!peeked) {
1360
- return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
1373
+ return await invalidMagicLinkResponse(options, authRedirectHint)
1361
1374
  }
1362
1375
  email = peeked.email
1363
- } catch {
1364
- return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
1376
+ } catch (error) {
1377
+ logAuthCallbackError("Magic-link", error)
1378
+ return await authExperienceErrorResponse(options, authRedirectHint)
1365
1379
  }
1366
1380
  }
1367
1381
 
@@ -1377,17 +1391,23 @@ export function registerAuthRoutes(
1377
1391
  matchesMagicLinkRequester(pendingSecret, requesterHash)
1378
1392
  ) {
1379
1393
  return completeMagicLinkCallback({
1380
- sixb,
1394
+ host,
1381
1395
  strategy,
1382
1396
  options,
1383
1397
  request,
1384
1398
  magicLinkId,
1385
1399
  token,
1386
1400
  clearPendingCookie: true,
1401
+ authRedirectHint,
1387
1402
  })
1388
1403
  }
1389
1404
 
1390
- return magicLinkConfirmResponse({ magicLinkId, token, email })
1405
+ return await magicLinkConfirmResponse(options, {
1406
+ magicLinkId,
1407
+ token,
1408
+ email,
1409
+ authRedirect: authRedirectHint,
1410
+ })
1391
1411
  }
1392
1412
 
1393
1413
  if (isOidcAuthStrategy(strategy)) {
@@ -1398,8 +1418,8 @@ export function registerAuthRoutes(
1398
1418
  try {
1399
1419
  const authOptions = resolveAuthOptions(options, request)
1400
1420
  const result = await strategy.completeOidcSignIn({
1401
- projectId: sixb.id,
1402
- authStorage: requireAuthStorage(sixb),
1421
+ projectId: host.id,
1422
+ authStorage: requireAuthStorage(host),
1403
1423
  requestUrl: request.url,
1404
1424
  requestOrigin: options.resolveAuthRequestOrigin(request),
1405
1425
  session: {
@@ -1407,13 +1427,13 @@ export function registerAuthRoutes(
1407
1427
  audience: authOptions.audience,
1408
1428
  tokenHash: sessionCredential.tokenHash,
1409
1429
  createdAt: now,
1410
- ...sixb.auth.createSessionDeadlines(now),
1430
+ ...host.auth.createSessionDeadlines(now),
1411
1431
  ...device,
1412
1432
  },
1413
1433
  })
1414
1434
 
1415
1435
  return sessionCallbackCompletionResponse({
1416
- sixb,
1436
+ host,
1417
1437
  request,
1418
1438
  apiOrigin: options.resolveAuthRequestOrigin(request),
1419
1439
  sessionCredential,
@@ -1434,7 +1454,7 @@ export function registerAuthRoutes(
1434
1454
  .post(
1435
1455
  "/auth/callback",
1436
1456
  async ({ body, request }) => {
1437
- const strategy = sixb.auth.getStrategy()
1457
+ const strategy = host.auth.getStrategy()
1438
1458
 
1439
1459
  if (!isMagicLinkAuthStrategy(strategy)) {
1440
1460
  return strategyNotImplementedResponse("Auth callback is not implemented yet.")
@@ -1442,16 +1462,26 @@ export function registerAuthRoutes(
1442
1462
 
1443
1463
  const magicLinkId = body.magicLinkId?.trim()
1444
1464
  const token = body.token?.trim()
1465
+ const authRedirectHint = resolveAuthExperienceRedirectHint(options, request, body.audience)
1445
1466
  if (!magicLinkId || !token) {
1446
- return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
1467
+ return await invalidMagicLinkResponse(options, authRedirectHint)
1447
1468
  }
1448
1469
 
1449
- return completeMagicLinkCallback({ sixb, strategy, options, request, magicLinkId, token })
1470
+ return completeMagicLinkCallback({
1471
+ host,
1472
+ strategy,
1473
+ options,
1474
+ request,
1475
+ magicLinkId,
1476
+ token,
1477
+ authRedirectHint,
1478
+ })
1450
1479
  },
1451
1480
  {
1452
1481
  body: t.Object({
1453
1482
  magicLinkId: t.Optional(t.String()),
1454
1483
  token: t.Optional(t.String()),
1484
+ audience: t.Optional(t.String()),
1455
1485
  }),
1456
1486
  parse: "urlencoded",
1457
1487
  detail: { hide: true },
@@ -1497,7 +1527,7 @@ function matchesMagicLinkRequester(pendingSecret: string, requesterHash: string)
1497
1527
  // navigation and the cookie must accompany that GET for the fast path to work.
1498
1528
  function magicLinkPendingCookieHeader(params: {
1499
1529
  readonly request: Request
1500
- readonly sixb: Sixb<readonly OntologySource[]>
1530
+ readonly host: SixbHostView
1501
1531
  readonly value: string
1502
1532
  readonly maxAgeSeconds: number
1503
1533
  }): string {
@@ -1508,7 +1538,7 @@ function magicLinkPendingCookieHeader(params: {
1508
1538
  "HttpOnly",
1509
1539
  `Max-Age=${params.maxAgeSeconds}`,
1510
1540
  ]
1511
- if (shouldUseSecureCookies(params.request, params.sixb.auth.getCookieOptions())) {
1541
+ if (shouldUseSecureCookies(params.request, params.host.auth.getCookieOptions())) {
1512
1542
  parts.push("Secure")
1513
1543
  }
1514
1544
  return parts.join("; ")
@@ -1517,13 +1547,14 @@ function magicLinkPendingCookieHeader(params: {
1517
1547
  // Shared by POST /auth/callback (confirmation click) and the same-device fast
1518
1548
  // path on GET. Consumes the single-use token and mints the session cookies.
1519
1549
  async function completeMagicLinkCallback(input: {
1520
- readonly sixb: Sixb<readonly OntologySource[]>
1550
+ readonly host: SixbHostView
1521
1551
  readonly strategy: MagicLinkAuthStrategy
1522
1552
  readonly options: AuthRoutesOptions
1523
1553
  readonly request: Request
1524
1554
  readonly magicLinkId: string
1525
1555
  readonly token: string
1526
1556
  readonly clearPendingCookie?: boolean
1557
+ readonly authRedirectHint?: AuthRedirectContext
1527
1558
  }): Promise<Response> {
1528
1559
  const authOptions = resolveAuthOptions(input.options, input.request)
1529
1560
  const now = new Date()
@@ -1532,8 +1563,8 @@ async function completeMagicLinkCallback(input: {
1532
1563
 
1533
1564
  try {
1534
1565
  const result = await input.strategy.completeMagicLinkSignIn({
1535
- projectId: input.sixb.id,
1536
- authStorage: requireAuthStorage(input.sixb),
1566
+ projectId: input.host.id,
1567
+ authStorage: requireAuthStorage(input.host),
1537
1568
  magicLinkId: input.magicLinkId,
1538
1569
  token: input.token,
1539
1570
  session: {
@@ -1541,13 +1572,13 @@ async function completeMagicLinkCallback(input: {
1541
1572
  audience: authOptions.audience,
1542
1573
  tokenHash: sessionCredential.tokenHash,
1543
1574
  createdAt: now,
1544
- ...input.sixb.auth.createSessionDeadlines(now),
1575
+ ...input.host.auth.createSessionDeadlines(now),
1545
1576
  ...device,
1546
1577
  },
1547
1578
  })
1548
1579
 
1549
1580
  const response = sessionCallbackCompletionResponse({
1550
- sixb: input.sixb,
1581
+ host: input.host,
1551
1582
  request: input.request,
1552
1583
  apiOrigin: input.options.resolveAuthRequestOrigin(input.request),
1553
1584
  sessionCredential,
@@ -1560,7 +1591,7 @@ async function completeMagicLinkCallback(input: {
1560
1591
  "set-cookie",
1561
1592
  magicLinkPendingCookieHeader({
1562
1593
  request: input.request,
1563
- sixb: input.sixb,
1594
+ host: input.host,
1564
1595
  value: "",
1565
1596
  maxAgeSeconds: 0,
1566
1597
  })
@@ -1568,7 +1599,7 @@ async function completeMagicLinkCallback(input: {
1568
1599
  }
1569
1600
  return response
1570
1601
  } catch {
1571
- return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
1602
+ return await invalidMagicLinkResponse(input.options, input.authRedirectHint)
1572
1603
  }
1573
1604
  }
1574
1605
 
@@ -1589,7 +1620,7 @@ function resolveSessionDevice(request: Request): {
1589
1620
  }
1590
1621
 
1591
1622
  function sessionCallbackCompletionResponse(input: {
1592
- readonly sixb: Sixb<readonly OntologySource[]>
1623
+ readonly host: SixbHostView
1593
1624
  readonly request: Request
1594
1625
  readonly apiOrigin: string
1595
1626
  readonly sessionCredential: ReturnType<typeof createSessionCredential>
@@ -1597,7 +1628,7 @@ function sessionCallbackCompletionResponse(input: {
1597
1628
  readonly expiresAt: Date
1598
1629
  readonly returnTo: string
1599
1630
  }): Response {
1600
- const cookieOptions = input.sixb.auth.getCookieOptions({ audience: input.audience })
1631
+ const cookieOptions = input.host.auth.getCookieOptions({ audience: input.audience })
1601
1632
  const headers = new Headers({
1602
1633
  "cache-control": "no-store",
1603
1634
  })
@@ -1929,21 +1960,110 @@ function authPageResponse(body: string, status = 200): Response {
1929
1960
  })
1930
1961
  }
1931
1962
 
1932
- function signInFormResponse(context: AuthRedirectContext): Response {
1933
- return authPageResponse(
1934
- [
1935
- "<h1>Sign in</h1>",
1936
- "<p>We'll email you a sign-in link.</p>",
1937
- '<form method="post" action="/auth/sign-in">',
1938
- `<input type="hidden" name="audience" value="${escapeHtml(context.audience)}">`,
1939
- `<input type="hidden" name="returnTo" value="${escapeHtml(context.returnTo)}">`,
1940
- '<input name="email" type="email" autocomplete="email" placeholder="you@example.com" aria-label="Email address" required autofocus>',
1941
- '<button type="submit">Send sign-in link</button>',
1942
- "</form>",
1943
- ].join("")
1963
+ async function signInFormResponse(
1964
+ options: AuthRoutesOptions,
1965
+ context: AuthRedirectContext
1966
+ ): Promise<Response> {
1967
+ return (
1968
+ (await customAuthExperienceResponse(options.authExperience, {
1969
+ audience: context.audience,
1970
+ state: { kind: "signIn" },
1971
+ signInUrl: authExperienceSignInUrl(context),
1972
+ submission: {
1973
+ kind: "requestMagicLink",
1974
+ action: "/auth/sign-in",
1975
+ fields: { audience: context.audience, returnTo: context.returnTo },
1976
+ },
1977
+ // Native POST forms inherit the document's referrer policy when
1978
+ // constructing their Origin header. `no-referrer` produces
1979
+ // `Origin: null`, which the API origin guard correctly rejects.
1980
+ referrerPolicy: "same-origin",
1981
+ })) ??
1982
+ authPageResponse(
1983
+ [
1984
+ "<h1>Sign in</h1>",
1985
+ "<p>We'll email you a sign-in link.</p>",
1986
+ '<form method="post" action="/auth/sign-in">',
1987
+ `<input type="hidden" name="audience" value="${escapeHtml(context.audience)}">`,
1988
+ `<input type="hidden" name="returnTo" value="${escapeHtml(context.returnTo)}">`,
1989
+ '<input name="email" type="email" autocomplete="email" placeholder="you@example.com" aria-label="Email address" required autofocus>',
1990
+ '<button type="submit">Send sign-in link</button>',
1991
+ "</form>",
1992
+ ].join("")
1993
+ )
1944
1994
  )
1945
1995
  }
1946
1996
 
1997
+ async function magicLinkRequestedResponse(
1998
+ options: AuthRoutesOptions,
1999
+ context: AuthRedirectContext
2000
+ ): Promise<Response> {
2001
+ return (
2002
+ (await customAuthExperienceResponse(options.authExperience, {
2003
+ audience: context.audience,
2004
+ state: { kind: "checkEmail" },
2005
+ signInUrl: authExperienceSignInUrl(context),
2006
+ })) ??
2007
+ htmlMessageResponse(
2008
+ "If this email can sign in, we sent a link. Check your inbox to continue.",
2009
+ 200,
2010
+ "Check your email"
2011
+ )
2012
+ )
2013
+ }
2014
+
2015
+ async function invalidMagicLinkResponse(
2016
+ options: AuthRoutesOptions,
2017
+ context: AuthRedirectContext | undefined
2018
+ ): Promise<Response> {
2019
+ if (context) {
2020
+ const custom = await customAuthExperienceResponse(options.authExperience, {
2021
+ audience: context.audience,
2022
+ state: { kind: "invalidLink" },
2023
+ signInUrl: authExperienceSignInUrl(context),
2024
+ status: 400,
2025
+ })
2026
+ if (custom) return custom
2027
+ }
2028
+
2029
+ return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
2030
+ }
2031
+
2032
+ async function authExperienceErrorResponse(
2033
+ options: AuthRoutesOptions,
2034
+ context: AuthRedirectContext | undefined
2035
+ ): Promise<Response> {
2036
+ if (context) {
2037
+ const custom = await customAuthExperienceResponse(options.authExperience, {
2038
+ audience: context.audience,
2039
+ state: { kind: "error" },
2040
+ signInUrl: authExperienceSignInUrl(context),
2041
+ status: 500,
2042
+ })
2043
+ if (custom) return custom
2044
+ }
2045
+
2046
+ return await invalidMagicLinkResponse(options, undefined)
2047
+ }
2048
+
2049
+ function authExperienceSignInUrl(context: AuthRedirectContext): string {
2050
+ const params = new URLSearchParams({ audience: context.audience, returnTo: context.returnTo })
2051
+ return `/auth/sign-in?${params.toString()}`
2052
+ }
2053
+
2054
+ function resolveAuthExperienceRedirectHint(
2055
+ options: AuthRoutesOptions,
2056
+ request: Request,
2057
+ audience: string | null | undefined
2058
+ ): AuthRedirectContext | undefined {
2059
+ if (audience !== "app" && audience !== "atlas") {
2060
+ return undefined
2061
+ }
2062
+
2063
+ const context = resolveInvitationDeliveryContext(options, request, { destinationId: audience })
2064
+ return context instanceof Response ? undefined : context
2065
+ }
2066
+
1947
2067
  // Deliberately a plain form with no auto-submit: link scanners that execute
1948
2068
  // pages headlessly still won't press the button, so the token survives until a
1949
2069
  // person clicks Continue. The extra click also keeps the link reusable when a
@@ -1952,12 +2072,39 @@ function signInFormResponse(context: AuthRedirectContext): Response {
1952
2072
  // a disabled spinner. The form POST is a normal navigation, so this page stays
1953
2073
  // visible (spinner and all) until the server responds; the pageshow handler
1954
2074
  // resets the button when the page is restored from the back/forward cache.
1955
- function magicLinkConfirmResponse(input: {
1956
- readonly magicLinkId: string
1957
- readonly token: string
1958
- // Absent when the strategy doesn't support the read-only peek.
1959
- readonly email?: string
1960
- }): Response {
2075
+ async function magicLinkConfirmResponse(
2076
+ options: AuthRoutesOptions,
2077
+ input: {
2078
+ readonly magicLinkId: string
2079
+ readonly token: string
2080
+ // Absent when the strategy doesn't support the read-only peek.
2081
+ readonly email?: string
2082
+ readonly authRedirect?: AuthRedirectContext
2083
+ }
2084
+ ): Promise<Response> {
2085
+ if (input.authRedirect) {
2086
+ const custom = await customAuthExperienceResponse(options.authExperience, {
2087
+ audience: input.authRedirect.audience,
2088
+ state: { kind: "confirm", ...(input.email ? { email: input.email } : {}) },
2089
+ signInUrl: authExperienceSignInUrl(input.authRedirect),
2090
+ submission: {
2091
+ kind: "confirmSignIn",
2092
+ action: "/auth/callback",
2093
+ fields: {
2094
+ magicLinkId: input.magicLinkId,
2095
+ token: input.token,
2096
+ audience: input.authRedirect.audience,
2097
+ },
2098
+ },
2099
+ referrerPolicy: "same-origin",
2100
+ // The callback POST is same-origin, but its successful 303 continues to
2101
+ // the validated custom-app origin. CSP applies form-action across that
2102
+ // redirect chain, so permit that exact origin for this state only.
2103
+ formActionOrigins: [new URL(input.authRedirect.returnTo).origin],
2104
+ })
2105
+ if (custom) return custom
2106
+ }
2107
+
1961
2108
  const response = authPageResponse(
1962
2109
  [
1963
2110
  "<h1>Sign in</h1>",
@@ -1967,6 +2114,11 @@ function magicLinkConfirmResponse(input: {
1967
2114
  '<form method="post" action="/auth/callback" id="confirm">',
1968
2115
  `<input type="hidden" name="magicLinkId" value="${escapeHtml(input.magicLinkId)}">`,
1969
2116
  `<input type="hidden" name="token" value="${escapeHtml(input.token)}">`,
2117
+ ...(input.authRedirect
2118
+ ? [
2119
+ `<input type="hidden" name="audience" value="${escapeHtml(input.authRedirect.audience)}">`,
2120
+ ]
2121
+ : []),
1970
2122
  '<button type="submit" id="confirm-button">Continue</button>',
1971
2123
  "</form>",
1972
2124
  "<script>",
@@ -2008,12 +2160,12 @@ function htmlMessageResponse(message: string, status = 200, heading?: string): R
2008
2160
  )
2009
2161
  }
2010
2162
 
2011
- function requireAuthStorage(sixb: Sixb<readonly OntologySource[]>): AuthStorage {
2012
- if (!sixb.storage.auth) {
2163
+ function requireAuthStorage(host: SixbHostView): AuthStorage {
2164
+ if (!host.storage.auth) {
2013
2165
  throw new Error("[SixbServer] Auth storage is required for auth routes.")
2014
2166
  }
2015
2167
 
2016
- return sixb.storage.auth
2168
+ return host.storage.auth
2017
2169
  }
2018
2170
 
2019
2171
  function serializeGroupOption(group: GroupDefinition) {