@plitzi/sdk-server 0.39.0 → 0.39.2

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 (666) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +364 -61
  3. package/dist/adapters/authAdapters.d.ts +2 -1
  4. package/dist/adapters/cloudAdapters.d.ts +2 -1
  5. package/dist/adapters/jsonAdapters.d.ts +2 -1
  6. package/dist/adapters/space/index.d.ts +3 -3
  7. package/dist/adapters/space/resolvers.d.ts +41 -4
  8. package/dist/adapters/space/types.d.ts +11 -1
  9. package/dist/auth.d.ts +9 -29
  10. package/dist/auth.js +2323 -22
  11. package/dist/bundle.d.ts +6 -0
  12. package/dist/bundle.js +171 -0
  13. package/dist/cache.d.ts +7 -0
  14. package/dist/cache.js +1 -0
  15. package/dist/chunks/buildBody-W9D8ySNY.js +1450 -0
  16. package/dist/chunks/core-TlrWmT4B.js +2118 -0
  17. package/dist/chunks/createServer-Bd_b7T3k.js +2956 -0
  18. package/dist/chunks/platform-DhdFYWm5.js +38 -0
  19. package/dist/{core/auth/routes.js → chunks/renewal-D98v6-Jd.js} +23 -4
  20. package/dist/chunks/template-M3IEZ6os.js +42 -0
  21. package/dist/{core/auth/throttle.js → chunks/throttle-BH7JLIOF.js} +4 -5
  22. package/dist/chunks/token-B2uY9JzU.js +824 -0
  23. package/dist/chunks/views/inline/keepTaps.js +1 -0
  24. package/dist/chunks/views/inline/motionSeen.js +2 -0
  25. package/dist/{modules/ssr → chunks}/views/template.ejs +62 -100
  26. package/dist/core/auth/api/admin.d.ts +2 -3
  27. package/dist/core/auth/api/context.d.ts +24 -29
  28. package/dist/core/auth/api/factors.d.ts +1 -2
  29. package/dist/core/auth/api/index.d.ts +30 -30
  30. package/dist/core/auth/api/profile.d.ts +1 -1
  31. package/dist/core/auth/api/session.d.ts +1 -2
  32. package/dist/core/auth/api/types.d.ts +2 -280
  33. package/dist/core/auth/api/values.d.ts +2 -3
  34. package/dist/core/auth/createAuth.d.ts +67 -76
  35. package/dist/core/auth/oauth/index.d.ts +1 -1
  36. package/dist/core/auth/oauth/providers/oidc.d.ts +0 -6
  37. package/dist/core/auth/renewal.d.ts +1 -3
  38. package/dist/core/auth/routes.d.ts +1 -5
  39. package/dist/core/auth/throttle.d.ts +2 -2
  40. package/dist/core/createServer.d.ts +14 -5
  41. package/dist/core/handlers/authMiddleware.d.ts +1 -2
  42. package/dist/core/handlers/authRouteHandlers.d.ts +1 -2
  43. package/dist/core/handlers/csrfMiddleware.d.ts +1 -2
  44. package/dist/core/handlers/oauthRouteHandlers.d.ts +1 -1
  45. package/dist/core/handlers/socialRouteHandlers.d.ts +2 -3
  46. package/dist/core/handlers/types.d.ts +1 -3
  47. package/dist/core/http/pageContext.d.ts +25 -0
  48. package/dist/core/http/stages/authApi.d.ts +1 -1
  49. package/dist/core/http/stages/authRoutes.d.ts +4 -10
  50. package/dist/core/http/stages/cspReport.d.ts +6 -0
  51. package/dist/core/http/stages/defaultFavicon.d.ts +3 -0
  52. package/dist/core/http/stages/exchangeRoute.d.ts +3 -2
  53. package/dist/core/http/stages/fontAssets.d.ts +3 -2
  54. package/dist/core/http/stages/googleFonts.d.ts +7 -0
  55. package/dist/core/http/stages/images.d.ts +4 -3
  56. package/dist/core/http/stages/livePages.d.ts +3 -2
  57. package/dist/core/http/stages/oauth.d.ts +2 -2
  58. package/dist/core/http/stages/pluginAssets.d.ts +2 -1
  59. package/dist/core/http/stages/{static.d.ts → sdkAssets.d.ts} +1 -4
  60. package/dist/core/http/stages/sessionRenewal.d.ts +4 -3
  61. package/dist/core/http/stages/signInRoute.d.ts +3 -2
  62. package/dist/core/oauth/authorize.d.ts +1 -1
  63. package/dist/core/oauth/challenge.d.ts +1 -1
  64. package/dist/core/oauth/consentPage.d.ts +1 -1
  65. package/dist/core/oauth/issueContext.d.ts +1 -1
  66. package/dist/core/oauth/metadata.d.ts +1 -5
  67. package/dist/core/oauth/records.d.ts +1 -1
  68. package/dist/core/oauth/register.d.ts +1 -1
  69. package/dist/core/oauth/respond.d.ts +1 -1
  70. package/dist/core/oauth/token.d.ts +1 -1
  71. package/dist/core/platform.d.ts +13 -0
  72. package/dist/core/sdkAssets.d.ts +11 -1
  73. package/dist/core/server/pageServer.d.ts +4 -3
  74. package/dist/core/server/{fleet/relay.d.ts → relay.d.ts} +1 -2
  75. package/dist/core/server/reportCacheSharing.d.ts +11 -0
  76. package/dist/core/services/registry.d.ts +4 -2
  77. package/dist/core/services/resolve.d.ts +1 -9
  78. package/dist/core/services/robotsTxt.d.ts +2 -1
  79. package/dist/core/services/rsc.d.ts +2 -1
  80. package/dist/core/services/servedSpace.d.ts +1 -1
  81. package/dist/core/services/sitemapXml.d.ts +2 -1
  82. package/dist/core/services/spaceDocument.d.ts +2 -1
  83. package/dist/core/services/ssr.d.ts +2 -1
  84. package/dist/core/services/styleSheet.d.ts +3 -0
  85. package/dist/env.js +1 -2
  86. package/dist/handlers.d.ts +1 -1
  87. package/dist/handlers.js +517 -5
  88. package/dist/helpers/buildServerInfo.d.ts +3 -1
  89. package/dist/helpers/cache/cacheManager.d.ts +1 -1
  90. package/dist/helpers/cache/defaults.d.ts +22 -1
  91. package/dist/helpers/cache/index.d.ts +11 -4
  92. package/dist/helpers/cache/keys.d.ts +27 -4
  93. package/dist/helpers/cache/limits.d.ts +16 -0
  94. package/dist/helpers/cache/pages.d.ts +20 -0
  95. package/dist/helpers/cache/queryParams.d.ts +11 -0
  96. package/dist/helpers/cache/serverCaches.d.ts +24 -11
  97. package/dist/helpers/cache/sharedCache.d.ts +29 -0
  98. package/dist/helpers/hydrationPayload.d.ts +35 -8
  99. package/dist/helpers/metrics.d.ts +5 -1
  100. package/dist/helpers/paintedCookie.d.ts +13 -0
  101. package/dist/helpers/visitorScheme.d.ts +10 -0
  102. package/dist/hosts/authoringHost/index.d.ts +1 -1
  103. package/dist/hosts/project/agentRuns.d.ts +1 -1
  104. package/dist/hosts/project/bundle.d.ts +22 -0
  105. package/dist/hosts/project/laterAsks.d.ts +1 -1
  106. package/dist/hosts/project/plugins.d.ts +3 -2
  107. package/dist/hosts/project/serveProject.d.ts +17 -7
  108. package/dist/hosts/project/spaceFailure.d.ts +1 -1
  109. package/dist/index.d.ts +9 -18
  110. package/dist/index.js +168 -24
  111. package/dist/modules/fonts/googleFonts.d.ts +27 -0
  112. package/dist/modules/images/imageProxy.d.ts +1 -1
  113. package/dist/modules/rsc/connectorRscData.d.ts +10 -12
  114. package/dist/modules/rsc/externalQueryReader.d.ts +28 -5
  115. package/dist/modules/rsc/handler.d.ts +3 -1
  116. package/dist/modules/rsc/matchRscPage.d.ts +0 -8
  117. package/dist/modules/rsc/publicFileResolver.d.ts +1 -1
  118. package/dist/modules/rsc/resolveRscData.d.ts +3 -31
  119. package/dist/modules/ssr/Component.d.ts +6 -3
  120. package/dist/modules/ssr/applySSRResult.d.ts +2 -6
  121. package/dist/modules/ssr/buildBody.d.ts +7 -2
  122. package/dist/modules/ssr/defaultFavicon.d.ts +10 -0
  123. package/dist/modules/ssr/earlyHints.d.ts +18 -0
  124. package/dist/modules/ssr/handler.d.ts +4 -2
  125. package/dist/modules/ssr/loadPluginComponents.d.ts +2 -1
  126. package/dist/modules/ssr/meterPage.d.ts +4 -0
  127. package/dist/modules/ssr/pageCache.d.ts +47 -0
  128. package/dist/modules/ssr/prepareRender.d.ts +11 -3
  129. package/dist/modules/ssr/preview.d.ts +5 -3
  130. package/dist/modules/ssr/redisPageStore.d.ts +29 -0
  131. package/dist/modules/ssr/registerExternalPlugins.d.ts +1 -1
  132. package/dist/modules/ssr/renderTurns.d.ts +34 -0
  133. package/dist/modules/ssr/reportMissingPlugins.d.ts +0 -7
  134. package/dist/modules/ssr/scriptPolicy.d.ts +39 -0
  135. package/dist/modules/ssr/spaceDocument.d.ts +25 -2
  136. package/dist/modules/ssr/streamBody.d.ts +9 -3
  137. package/dist/modules/ssr/styleSheet.d.ts +15 -0
  138. package/dist/modules/ssr/template.d.ts +8 -1
  139. package/dist/oauth.js +139 -9
  140. package/dist/platform.d.ts +6 -0
  141. package/dist/platform.js +1 -0
  142. package/dist/project.js +939 -1
  143. package/dist/spaces.d.ts +7 -0
  144. package/dist/spaces.js +1 -0
  145. package/dist/ssr.d.ts +1 -2
  146. package/dist/ssr.js +1 -4
  147. package/dist/types/config.d.ts +252 -0
  148. package/dist/types/index.d.ts +2 -0
  149. package/dist/types/server.d.ts +111 -0
  150. package/package.json +41 -83
  151. package/skills/plitzi-authoring/recipes/server-data.ts +4 -0
  152. package/skills/plitzi-authoring/reference/accessibility.md +9 -2
  153. package/skills/plitzi-authoring/reference/auth.md +6 -1
  154. package/skills/plitzi-authoring/reference/authoring-errors.md +7 -4
  155. package/skills/plitzi-authoring/reference/flows.md +9 -9
  156. package/skills/plitzi-authoring/reference/kept-state.md +12 -0
  157. package/skills/plitzi-authoring/reference/lists.md +7 -1
  158. package/skills/plitzi-authoring/reference/plugins.md +5 -2
  159. package/skills/plitzi-authoring/reference/testing.md +3 -3
  160. package/dist/actions.d.ts +0 -87
  161. package/dist/actions.js +0 -23
  162. package/dist/adapters/authAdapters.js +0 -12
  163. package/dist/adapters/cloudAdapters.js +0 -364
  164. package/dist/adapters/jsonAdapters.js +0 -88
  165. package/dist/adapters/space/index.js +0 -122
  166. package/dist/adapters/space/resolvers.js +0 -79
  167. package/dist/adapters/space/types.js +0 -41
  168. package/dist/core/auth/api/accounts.js +0 -175
  169. package/dist/core/auth/api/admin.js +0 -146
  170. package/dist/core/auth/api/context.js +0 -262
  171. package/dist/core/auth/api/factors.js +0 -209
  172. package/dist/core/auth/api/index.js +0 -43
  173. package/dist/core/auth/api/profile.js +0 -243
  174. package/dist/core/auth/api/session.js +0 -312
  175. package/dist/core/auth/api/values.js +0 -90
  176. package/dist/core/auth/authorize.d.ts +0 -96
  177. package/dist/core/auth/authorize.js +0 -92
  178. package/dist/core/auth/createAuth.js +0 -216
  179. package/dist/core/auth/credentials.d.ts +0 -40
  180. package/dist/core/auth/credentials.js +0 -56
  181. package/dist/core/auth/csrf.d.ts +0 -143
  182. package/dist/core/auth/csrf.js +0 -295
  183. package/dist/core/auth/domains.d.ts +0 -41
  184. package/dist/core/auth/domains.js +0 -78
  185. package/dist/core/auth/identity.d.ts +0 -118
  186. package/dist/core/auth/identity.js +0 -194
  187. package/dist/core/auth/oauth/client.js +0 -52
  188. package/dist/core/auth/oauth/index.js +0 -130
  189. package/dist/core/auth/oauth/providers/github.js +0 -48
  190. package/dist/core/auth/oauth/providers/google.js +0 -30
  191. package/dist/core/auth/oauth/providers/oidc.js +0 -197
  192. package/dist/core/auth/oauth/state.js +0 -57
  193. package/dist/core/auth/oauth/types.js +0 -16
  194. package/dist/core/auth/passwords.d.ts +0 -15
  195. package/dist/core/auth/passwords.js +0 -32
  196. package/dist/core/auth/redirects.js +0 -31
  197. package/dist/core/auth/renewal.js +0 -24
  198. package/dist/core/auth/session.d.ts +0 -194
  199. package/dist/core/auth/session.js +0 -237
  200. package/dist/core/auth/sessionActivity.d.ts +0 -11
  201. package/dist/core/auth/sessionActivity.js +0 -14
  202. package/dist/core/auth/spaceTokens.d.ts +0 -173
  203. package/dist/core/auth/spaceTokens.js +0 -264
  204. package/dist/core/auth/tokens.d.ts +0 -224
  205. package/dist/core/auth/tokens.js +0 -264
  206. package/dist/core/auth/totp.js +0 -123
  207. package/dist/core/configSeam.d.ts +0 -10
  208. package/dist/core/configSeam.js +0 -151
  209. package/dist/core/createServer.js +0 -119
  210. package/dist/core/fontStore.js +0 -53
  211. package/dist/core/freePort.d.ts +0 -24
  212. package/dist/core/freePort.js +0 -74
  213. package/dist/core/handlers/authMiddleware.js +0 -38
  214. package/dist/core/handlers/authRouteHandlers.js +0 -112
  215. package/dist/core/handlers/csrfMiddleware.js +0 -56
  216. package/dist/core/handlers/oauthRouteHandlers.js +0 -161
  217. package/dist/core/handlers/socialRouteHandlers.js +0 -169
  218. package/dist/core/health.d.ts +0 -21
  219. package/dist/core/health.js +0 -40
  220. package/dist/core/http/dispatcher.d.ts +0 -15
  221. package/dist/core/http/dispatcher.js +0 -115
  222. package/dist/core/http/navigation.d.ts +0 -14
  223. package/dist/core/http/navigation.js +0 -19
  224. package/dist/core/http/securityHeaders.d.ts +0 -2
  225. package/dist/core/http/securityHeaders.js +0 -17
  226. package/dist/core/http/socketResponse.d.ts +0 -18
  227. package/dist/core/http/socketResponse.js +0 -59
  228. package/dist/core/http/sse.d.ts +0 -26
  229. package/dist/core/http/sse.js +0 -78
  230. package/dist/core/http/stages/authApi.js +0 -66
  231. package/dist/core/http/stages/authRoutes.js +0 -116
  232. package/dist/core/http/stages/crossSiteWrites.d.ts +0 -24
  233. package/dist/core/http/stages/crossSiteWrites.js +0 -45
  234. package/dist/core/http/stages/exchangeRoute.js +0 -69
  235. package/dist/core/http/stages/fontAssets.js +0 -27
  236. package/dist/core/http/stages/health.d.ts +0 -11
  237. package/dist/core/http/stages/health.js +0 -34
  238. package/dist/core/http/stages/images.js +0 -49
  239. package/dist/core/http/stages/livePages.js +0 -80
  240. package/dist/core/http/stages/middlewares.d.ts +0 -2
  241. package/dist/core/http/stages/middlewares.js +0 -23
  242. package/dist/core/http/stages/oauth.js +0 -118
  243. package/dist/core/http/stages/pluginAssets.js +0 -21
  244. package/dist/core/http/stages/sessionRenewal.js +0 -82
  245. package/dist/core/http/stages/signInRoute.js +0 -139
  246. package/dist/core/http/stages/static.js +0 -48
  247. package/dist/core/http/types.d.ts +0 -56
  248. package/dist/core/http/webExchange.d.ts +0 -18
  249. package/dist/core/http/webExchange.js +0 -53
  250. package/dist/core/mimeTypes.d.ts +0 -13
  251. package/dist/core/mimeTypes.js +0 -42
  252. package/dist/core/oauth/authorize.js +0 -279
  253. package/dist/core/oauth/challenge.js +0 -33
  254. package/dist/core/oauth/consentPage.js +0 -134
  255. package/dist/core/oauth/issueContext.js +0 -32
  256. package/dist/core/oauth/metadata.js +0 -71
  257. package/dist/core/oauth/params.js +0 -5
  258. package/dist/core/oauth/pkce.js +0 -15
  259. package/dist/core/oauth/records.js +0 -49
  260. package/dist/core/oauth/register.js +0 -76
  261. package/dist/core/oauth/respond.js +0 -59
  262. package/dist/core/oauth/token.js +0 -145
  263. package/dist/core/previewToken.d.ts +0 -21
  264. package/dist/core/previewToken.js +0 -32
  265. package/dist/core/requestParser.d.ts +0 -22
  266. package/dist/core/requestParser.js +0 -79
  267. package/dist/core/sdkAssets.js +0 -46
  268. package/dist/core/server/baseServer.d.ts +0 -30
  269. package/dist/core/server/baseServer.js +0 -106
  270. package/dist/core/server/closeOnSignals.d.ts +0 -28
  271. package/dist/core/server/closeOnSignals.js +0 -47
  272. package/dist/core/server/drain.d.ts +0 -18
  273. package/dist/core/server/drain.js +0 -82
  274. package/dist/core/server/fleet/channel.d.ts +0 -103
  275. package/dist/core/server/fleet/channel.js +0 -191
  276. package/dist/core/server/fleet/link.d.ts +0 -23
  277. package/dist/core/server/fleet/link.js +0 -70
  278. package/dist/core/server/fleet/relay.js +0 -112
  279. package/dist/core/server/fleet/role.d.ts +0 -46
  280. package/dist/core/server/fleet/role.js +0 -59
  281. package/dist/core/server/fleet/stores.d.ts +0 -21
  282. package/dist/core/server/fleet/stores.js +0 -46
  283. package/dist/core/server/fleet/supervisor.d.ts +0 -28
  284. package/dist/core/server/fleet/supervisor.js +0 -120
  285. package/dist/core/server/pageServer.js +0 -124
  286. package/dist/core/services/action.d.ts +0 -11
  287. package/dist/core/services/action.js +0 -123
  288. package/dist/core/services/functionRoutes.d.ts +0 -9
  289. package/dist/core/services/functionRoutes.js +0 -53
  290. package/dist/core/services/realtime.d.ts +0 -8
  291. package/dist/core/services/realtime.js +0 -62
  292. package/dist/core/services/registry.js +0 -47
  293. package/dist/core/services/resolve.js +0 -25
  294. package/dist/core/services/robotsTxt.js +0 -50
  295. package/dist/core/services/rsc.js +0 -13
  296. package/dist/core/services/servedSpace.js +0 -16
  297. package/dist/core/services/sitemapXml.js +0 -37
  298. package/dist/core/services/spaceDocument.js +0 -11
  299. package/dist/core/services/ssr.js +0 -13
  300. package/dist/core/staticFiles.d.ts +0 -3
  301. package/dist/core/staticFiles.js +0 -49
  302. package/dist/core/transports.d.ts +0 -31
  303. package/dist/core/transports.js +0 -61
  304. package/dist/core/unusedPort.d.ts +0 -10
  305. package/dist/core/unusedPort.js +0 -38
  306. package/dist/functions-api.d.ts +0 -679
  307. package/dist/functions.d.ts +0 -21
  308. package/dist/functions.js +0 -6
  309. package/dist/functionsRunner.d.ts +0 -20
  310. package/dist/functionsRunner.js +0 -7
  311. package/dist/helpers/atomicFile.d.ts +0 -10
  312. package/dist/helpers/atomicFile.js +0 -33
  313. package/dist/helpers/buildResponseHelpers.d.ts +0 -21
  314. package/dist/helpers/buildResponseHelpers.js +0 -84
  315. package/dist/helpers/buildServerInfo.js +0 -86
  316. package/dist/helpers/cache/CompressedFileCache.d.ts +0 -18
  317. package/dist/helpers/cache/CompressedFileCache.js +0 -44
  318. package/dist/helpers/cache/TtlCache.d.ts +0 -15
  319. package/dist/helpers/cache/TtlCache.js +0 -57
  320. package/dist/helpers/cache/cacheManager.js +0 -50
  321. package/dist/helpers/cache/defaults.js +0 -9
  322. package/dist/helpers/cache/keys.js +0 -130
  323. package/dist/helpers/cache/serverCaches.js +0 -15
  324. package/dist/helpers/compress.d.ts +0 -20
  325. package/dist/helpers/compress.js +0 -61
  326. package/dist/helpers/debugAuthorization.d.ts +0 -24
  327. package/dist/helpers/debugAuthorization.js +0 -27
  328. package/dist/helpers/escapeHtml.js +0 -13
  329. package/dist/helpers/escapeJson.js +0 -4
  330. package/dist/helpers/fileStore.d.ts +0 -60
  331. package/dist/helpers/fileStore.js +0 -127
  332. package/dist/helpers/flagOverrides.d.ts +0 -30
  333. package/dist/helpers/flagOverrides.js +0 -26
  334. package/dist/helpers/hydrationPayload.js +0 -57
  335. package/dist/helpers/metrics.js +0 -37
  336. package/dist/helpers/normalizePlugins.js +0 -16
  337. package/dist/helpers/offlineDataLoader.js +0 -15
  338. package/dist/helpers/onAbort.d.ts +0 -12
  339. package/dist/helpers/onAbort.js +0 -22
  340. package/dist/helpers/outboundGuard.d.ts +0 -64
  341. package/dist/helpers/outboundGuard.js +0 -218
  342. package/dist/helpers/paintedCookie.js +0 -13
  343. package/dist/helpers/readCookie.js +0 -11
  344. package/dist/helpers/reportReactBuild.js +0 -18
  345. package/dist/helpers/resolveDebugMode.js +0 -13
  346. package/dist/helpers/runMiddlewares.d.ts +0 -2
  347. package/dist/helpers/runMiddlewares.js +0 -21
  348. package/dist/helpers/serverLog.d.ts +0 -37
  349. package/dist/helpers/serverLog.js +0 -116
  350. package/dist/helpers/wsFrame.d.ts +0 -3
  351. package/dist/helpers/wsFrame.js +0 -5
  352. package/dist/hosts/authoringHost/index.js +0 -118
  353. package/dist/hosts/project/agentRuns.js +0 -107
  354. package/dist/hosts/project/laterAsks.js +0 -117
  355. package/dist/hosts/project/plugins.js +0 -185
  356. package/dist/hosts/project/serveProject.js +0 -396
  357. package/dist/hosts/project/spaceFailure.js +0 -86
  358. package/dist/hosts/project/watchSpace.js +0 -86
  359. package/dist/kernel.d.ts +0 -25
  360. package/dist/kernel.js +0 -10
  361. package/dist/middlewares/auth.d.ts +0 -2
  362. package/dist/middlewares/auth.js +0 -10
  363. package/dist/middlewares/basicAuth.d.ts +0 -6
  364. package/dist/middlewares/basicAuth.js +0 -67
  365. package/dist/middlewares/spaceDeployment.d.ts +0 -2
  366. package/dist/middlewares/spaceDeployment.js +0 -17
  367. package/dist/modules/actions/connectorWrite.d.ts +0 -11
  368. package/dist/modules/actions/connectorWrite.js +0 -83
  369. package/dist/modules/actions/index.d.ts +0 -78
  370. package/dist/modules/actions/index.js +0 -129
  371. package/dist/modules/actions/jobs/failureStreak.d.ts +0 -17
  372. package/dist/modules/actions/jobs/failureStreak.js +0 -47
  373. package/dist/modules/actions/jobs/fileQueue.d.ts +0 -34
  374. package/dist/modules/actions/jobs/fileQueue.js +0 -72
  375. package/dist/modules/actions/jobs/index.d.ts +0 -34
  376. package/dist/modules/actions/jobs/index.js +0 -60
  377. package/dist/modules/actions/jobs/later.d.ts +0 -43
  378. package/dist/modules/actions/jobs/later.js +0 -69
  379. package/dist/modules/actions/jobs/memoryQueue.d.ts +0 -33
  380. package/dist/modules/actions/jobs/memoryQueue.js +0 -42
  381. package/dist/modules/actions/jobs/queueDocument.d.ts +0 -14
  382. package/dist/modules/actions/jobs/queueDocument.js +0 -22
  383. package/dist/modules/actions/jobs/queueRules.d.ts +0 -39
  384. package/dist/modules/actions/jobs/queueRules.js +0 -270
  385. package/dist/modules/actions/jobs/scheduler.d.ts +0 -64
  386. package/dist/modules/actions/jobs/scheduler.js +0 -133
  387. package/dist/modules/actions/jobs/schedules.d.ts +0 -23
  388. package/dist/modules/actions/jobs/schedules.js +0 -47
  389. package/dist/modules/actions/jobs/storeClock.d.ts +0 -16
  390. package/dist/modules/actions/jobs/storeClock.js +0 -32
  391. package/dist/modules/actions/jobs/worker.d.ts +0 -67
  392. package/dist/modules/actions/jobs/worker.js +0 -361
  393. package/dist/modules/actions/moduleFor.d.ts +0 -3
  394. package/dist/modules/actions/moduleFor.js +0 -44
  395. package/dist/modules/actions/runtime/check.d.ts +0 -24
  396. package/dist/modules/actions/runtime/check.js +0 -122
  397. package/dist/modules/actions/runtime/credentials.d.ts +0 -10
  398. package/dist/modules/actions/runtime/credentials.js +0 -28
  399. package/dist/modules/actions/runtime/email.d.ts +0 -39
  400. package/dist/modules/actions/runtime/email.js +0 -91
  401. package/dist/modules/actions/runtime/errors.d.ts +0 -42
  402. package/dist/modules/actions/runtime/errors.js +0 -53
  403. package/dist/modules/actions/runtime/fileKv.d.ts +0 -35
  404. package/dist/modules/actions/runtime/fileKv.js +0 -81
  405. package/dist/modules/actions/runtime/flags.d.ts +0 -16
  406. package/dist/modules/actions/runtime/flags.js +0 -49
  407. package/dist/modules/actions/runtime/guards.d.ts +0 -144
  408. package/dist/modules/actions/runtime/guards.js +0 -255
  409. package/dist/modules/actions/runtime/kvChange.d.ts +0 -67
  410. package/dist/modules/actions/runtime/kvChange.js +0 -45
  411. package/dist/modules/actions/runtime/kvList.d.ts +0 -55
  412. package/dist/modules/actions/runtime/kvList.js +0 -56
  413. package/dist/modules/actions/runtime/kvStore.d.ts +0 -35
  414. package/dist/modules/actions/runtime/kvStore.js +0 -81
  415. package/dist/modules/actions/runtime/limits.d.ts +0 -11
  416. package/dist/modules/actions/runtime/limits.js +0 -35
  417. package/dist/modules/actions/runtime/memoryKv.d.ts +0 -28
  418. package/dist/modules/actions/runtime/memoryKv.js +0 -110
  419. package/dist/modules/actions/runtime/namespaceKv.d.ts +0 -9
  420. package/dist/modules/actions/runtime/namespaceKv.js +0 -35
  421. package/dist/modules/actions/runtime/precheck.d.ts +0 -27
  422. package/dist/modules/actions/runtime/precheck.js +0 -41
  423. package/dist/modules/actions/runtime/projectData.d.ts +0 -18
  424. package/dist/modules/actions/runtime/projectData.js +0 -69
  425. package/dist/modules/actions/runtime/rateLimit.d.ts +0 -26
  426. package/dist/modules/actions/runtime/rateLimit.js +0 -25
  427. package/dist/modules/actions/runtime/redisKv.d.ts +0 -27
  428. package/dist/modules/actions/runtime/redisKv.js +0 -46
  429. package/dist/modules/actions/runtime/renderResolver.d.ts +0 -16
  430. package/dist/modules/actions/runtime/renderResolver.js +0 -240
  431. package/dist/modules/actions/runtime/renderShare.d.ts +0 -12
  432. package/dist/modules/actions/runtime/renderShare.js +0 -70
  433. package/dist/modules/actions/runtime/report.d.ts +0 -14
  434. package/dist/modules/actions/runtime/report.js +0 -23
  435. package/dist/modules/actions/runtime/runAction.d.ts +0 -26
  436. package/dist/modules/actions/runtime/runAction.js +0 -606
  437. package/dist/modules/actions/runtime/runLogger.d.ts +0 -36
  438. package/dist/modules/actions/runtime/runLogger.js +0 -72
  439. package/dist/modules/actions/runtime/scope.d.ts +0 -40
  440. package/dist/modules/actions/runtime/scope.js +0 -129
  441. package/dist/modules/actions/runtime/signing.d.ts +0 -27
  442. package/dist/modules/actions/runtime/signing.js +0 -50
  443. package/dist/modules/actions/runtime/taskContext.d.ts +0 -51
  444. package/dist/modules/actions/runtime/taskContext.js +0 -125
  445. package/dist/modules/actions/runtime/triggers.d.ts +0 -12
  446. package/dist/modules/actions/runtime/triggers.js +0 -14
  447. package/dist/modules/actions/taskCatalog.d.ts +0 -28
  448. package/dist/modules/actions/taskCatalog.js +0 -25
  449. package/dist/modules/actions/tasks/auth.d.ts +0 -2
  450. package/dist/modules/actions/tasks/auth.js +0 -42
  451. package/dist/modules/actions/tasks/builtins.d.ts +0 -10
  452. package/dist/modules/actions/tasks/builtins.js +0 -32
  453. package/dist/modules/actions/tasks/connector.d.ts +0 -2
  454. package/dist/modules/actions/tasks/connector.js +0 -145
  455. package/dist/modules/actions/tasks/db.d.ts +0 -2
  456. package/dist/modules/actions/tasks/db.js +0 -59
  457. package/dist/modules/actions/tasks/email.d.ts +0 -2
  458. package/dist/modules/actions/tasks/email.js +0 -72
  459. package/dist/modules/actions/tasks/flow.d.ts +0 -3
  460. package/dist/modules/actions/tasks/flow.js +0 -282
  461. package/dist/modules/actions/tasks/helpers.d.ts +0 -16
  462. package/dist/modules/actions/tasks/helpers.js +0 -30
  463. package/dist/modules/actions/tasks/http.d.ts +0 -2
  464. package/dist/modules/actions/tasks/http.js +0 -111
  465. package/dist/modules/actions/tasks/kv.d.ts +0 -2
  466. package/dist/modules/actions/tasks/kv.js +0 -146
  467. package/dist/modules/actions/tasks/list.d.ts +0 -2
  468. package/dist/modules/actions/tasks/list.js +0 -154
  469. package/dist/modules/actions/tasks/realtime.d.ts +0 -2
  470. package/dist/modules/actions/tasks/realtime.js +0 -104
  471. package/dist/modules/actions/tasks/registry.d.ts +0 -26
  472. package/dist/modules/actions/tasks/registry.js +0 -63
  473. package/dist/modules/actions/tasks/transform.d.ts +0 -2
  474. package/dist/modules/actions/tasks/transform.js +0 -36
  475. package/dist/modules/actions/transport/callHandler.d.ts +0 -24
  476. package/dist/modules/actions/transport/callHandler.js +0 -296
  477. package/dist/modules/actions/transport/cancelHandler.d.ts +0 -23
  478. package/dist/modules/actions/transport/cancelHandler.js +0 -23
  479. package/dist/modules/actions/transport/catalogHandler.d.ts +0 -21
  480. package/dist/modules/actions/transport/catalogHandler.js +0 -22
  481. package/dist/modules/actions/transport/stream.d.ts +0 -22
  482. package/dist/modules/actions/transport/stream.js +0 -36
  483. package/dist/modules/actions/transport/verifySignature.d.ts +0 -16
  484. package/dist/modules/actions/transport/verifySignature.js +0 -72
  485. package/dist/modules/actions/transport/webhookHandler.d.ts +0 -25
  486. package/dist/modules/actions/transport/webhookHandler.js +0 -207
  487. package/dist/modules/actions/types.d.ts +0 -520
  488. package/dist/modules/connectors/engine.d.ts +0 -47
  489. package/dist/modules/connectors/engine.js +0 -222
  490. package/dist/modules/connectors/getByPath.d.ts +0 -8
  491. package/dist/modules/connectors/getByPath.js +0 -21
  492. package/dist/modules/connectors/index.d.ts +0 -7
  493. package/dist/modules/connectors/projection.d.ts +0 -18
  494. package/dist/modules/connectors/projection.js +0 -108
  495. package/dist/modules/connectors/resolver.d.ts +0 -27
  496. package/dist/modules/connectors/resolver.js +0 -74
  497. package/dist/modules/connectors/types.d.ts +0 -19
  498. package/dist/modules/functions/build.d.ts +0 -27
  499. package/dist/modules/functions/build.js +0 -216
  500. package/dist/modules/functions/capabilities.d.ts +0 -22
  501. package/dist/modules/functions/capabilities.js +0 -435
  502. package/dist/modules/functions/config.d.ts +0 -76
  503. package/dist/modules/functions/config.js +0 -40
  504. package/dist/modules/functions/context.d.ts +0 -20
  505. package/dist/modules/functions/context.js +0 -146
  506. package/dist/modules/functions/contract.d.ts +0 -329
  507. package/dist/modules/functions/contract.js +0 -9
  508. package/dist/modules/functions/driver.d.ts +0 -37
  509. package/dist/modules/functions/driver.js +0 -368
  510. package/dist/modules/functions/jobControl.d.ts +0 -21
  511. package/dist/modules/functions/jobControl.js +0 -43
  512. package/dist/modules/functions/jobs.d.ts +0 -98
  513. package/dist/modules/functions/jobs.js +0 -438
  514. package/dist/modules/functions/load.d.ts +0 -22
  515. package/dist/modules/functions/load.js +0 -49
  516. package/dist/modules/functions/local.d.ts +0 -31
  517. package/dist/modules/functions/local.js +0 -64
  518. package/dist/modules/functions/manifest.d.ts +0 -31
  519. package/dist/modules/functions/manifest.js +0 -337
  520. package/dist/modules/functions/native.d.ts +0 -9
  521. package/dist/modules/functions/native.js +0 -22
  522. package/dist/modules/functions/oauth.d.ts +0 -33
  523. package/dist/modules/functions/oauth.js +0 -360
  524. package/dist/modules/functions/protocol.d.ts +0 -344
  525. package/dist/modules/functions/protocol.js +0 -32
  526. package/dist/modules/functions/routes.d.ts +0 -51
  527. package/dist/modules/functions/routes.js +0 -242
  528. package/dist/modules/functions/runner/messages.d.ts +0 -4
  529. package/dist/modules/functions/runner/messages.js +0 -229
  530. package/dist/modules/functions/runner/remote.d.ts +0 -19
  531. package/dist/modules/functions/runner/remote.js +0 -168
  532. package/dist/modules/functions/runner/service.d.ts +0 -32
  533. package/dist/modules/functions/runner/service.js +0 -255
  534. package/dist/modules/functions/sandbox/guest/bytes.d.ts +0 -27
  535. package/dist/modules/functions/sandbox/guest/bytes.js +0 -108
  536. package/dist/modules/functions/sandbox/guest/crypto.d.ts +0 -47
  537. package/dist/modules/functions/sandbox/guest/crypto.js +0 -144
  538. package/dist/modules/functions/sandbox/guest/events.d.ts +0 -152
  539. package/dist/modules/functions/sandbox/guest/events.js +0 -143
  540. package/dist/modules/functions/sandbox/guest/fetch.d.ts +0 -305
  541. package/dist/modules/functions/sandbox/guest/fetch.js +0 -237
  542. package/dist/modules/functions/sandbox/guest/index.d.ts +0 -28
  543. package/dist/modules/functions/sandbox/guest/index.js +0 -130
  544. package/dist/modules/functions/sandbox/guest/types.d.ts +0 -38
  545. package/dist/modules/functions/sandbox/isolate.d.ts +0 -37
  546. package/dist/modules/functions/sandbox/isolate.js +0 -360
  547. package/dist/modules/functions/sandbox/prelude.d.ts +0 -2
  548. package/dist/modules/functions/sandbox/prelude.js +0 -49
  549. package/dist/modules/functions/scope.d.ts +0 -30
  550. package/dist/modules/functions/scope.js +0 -28
  551. package/dist/modules/functions/space.d.ts +0 -47
  552. package/dist/modules/functions/space.js +0 -185
  553. package/dist/modules/functions/tryEntry.d.ts +0 -9
  554. package/dist/modules/functions/tryEntry.js +0 -49
  555. package/dist/modules/images/allowlist.js +0 -18
  556. package/dist/modules/images/imageProxy.js +0 -291
  557. package/dist/modules/images/transform.js +0 -28
  558. package/dist/modules/mongo/index.d.ts +0 -4
  559. package/dist/modules/mongo/jobQueue.d.ts +0 -38
  560. package/dist/modules/mongo/jobQueue.js +0 -453
  561. package/dist/modules/mongo/kv.d.ts +0 -15
  562. package/dist/modules/mongo/kv.js +0 -129
  563. package/dist/modules/mysql/accounts.d.ts +0 -5
  564. package/dist/modules/mysql/accounts.js +0 -378
  565. package/dist/modules/mysql/admin.d.ts +0 -58
  566. package/dist/modules/mysql/admin.js +0 -133
  567. package/dist/modules/mysql/config.d.ts +0 -82
  568. package/dist/modules/mysql/config.js +0 -30
  569. package/dist/modules/mysql/identities.d.ts +0 -35
  570. package/dist/modules/mysql/identities.js +0 -43
  571. package/dist/modules/mysql/index.d.ts +0 -68
  572. package/dist/modules/mysql/index.js +0 -62
  573. package/dist/modules/mysql/jobs/index.d.ts +0 -5
  574. package/dist/modules/mysql/jobs/jobQueue.d.ts +0 -40
  575. package/dist/modules/mysql/jobs/jobQueue.js +0 -458
  576. package/dist/modules/mysql/jobs/kv.d.ts +0 -18
  577. package/dist/modules/mysql/jobs/kv.js +0 -108
  578. package/dist/modules/mysql/jobs/schema.d.ts +0 -28
  579. package/dist/modules/mysql/jobs/schema.js +0 -109
  580. package/dist/modules/mysql/pool.d.ts +0 -3
  581. package/dist/modules/mysql/pool.js +0 -88
  582. package/dist/modules/mysql/query.d.ts +0 -12
  583. package/dist/modules/mysql/query.js +0 -21
  584. package/dist/modules/mysql/schema.d.ts +0 -43
  585. package/dist/modules/mysql/schema.js +0 -390
  586. package/dist/modules/mysql/sessions.d.ts +0 -23
  587. package/dist/modules/mysql/sessions.js +0 -52
  588. package/dist/modules/mysql/spaceTokens.d.ts +0 -11
  589. package/dist/modules/mysql/spaceTokens.js +0 -59
  590. package/dist/modules/realtime/declarations.d.ts +0 -11
  591. package/dist/modules/realtime/declarations.js +0 -26
  592. package/dist/modules/realtime/failure.d.ts +0 -6
  593. package/dist/modules/realtime/failure.js +0 -11
  594. package/dist/modules/realtime/grants.d.ts +0 -23
  595. package/dist/modules/realtime/grants.js +0 -61
  596. package/dist/modules/realtime/handlers.d.ts +0 -85
  597. package/dist/modules/realtime/handlers.js +0 -266
  598. package/dist/modules/realtime/hub.d.ts +0 -71
  599. package/dist/modules/realtime/hub.js +0 -184
  600. package/dist/modules/realtime/index.d.ts +0 -75
  601. package/dist/modules/realtime/index.js +0 -89
  602. package/dist/modules/realtime/jobs.d.ts +0 -20
  603. package/dist/modules/realtime/jobs.js +0 -41
  604. package/dist/modules/realtime/memoryPubSub.d.ts +0 -10
  605. package/dist/modules/realtime/memoryPubSub.js +0 -43
  606. package/dist/modules/realtime/message.d.ts +0 -3
  607. package/dist/modules/realtime/message.js +0 -5
  608. package/dist/modules/realtime/presence.d.ts +0 -33
  609. package/dist/modules/realtime/presence.js +0 -56
  610. package/dist/modules/realtime/redisPubSub.d.ts +0 -24
  611. package/dist/modules/realtime/redisPubSub.js +0 -36
  612. package/dist/modules/realtime/retained.d.ts +0 -25
  613. package/dist/modules/realtime/retained.js +0 -47
  614. package/dist/modules/realtime/socket.d.ts +0 -30
  615. package/dist/modules/realtime/socket.js +0 -123
  616. package/dist/modules/rsc/connectorRscData.js +0 -79
  617. package/dist/modules/rsc/externalQueryReader.js +0 -43
  618. package/dist/modules/rsc/handler.js +0 -176
  619. package/dist/modules/rsc/matchRscPage.js +0 -26
  620. package/dist/modules/rsc/publicFileResolver.js +0 -73
  621. package/dist/modules/rsc/resolveRscData.js +0 -146
  622. package/dist/modules/runtime/bundle.d.ts +0 -29
  623. package/dist/modules/runtime/bundle.js +0 -117
  624. package/dist/modules/runtime/contract.d.ts +0 -37
  625. package/dist/modules/runtime/contract.js +0 -21
  626. package/dist/modules/runtime/host.d.ts +0 -38
  627. package/dist/modules/runtime/host.js +0 -68
  628. package/dist/modules/runtime/inside.d.ts +0 -36
  629. package/dist/modules/runtime/inside.js +0 -95
  630. package/dist/modules/runtime/runner.d.ts +0 -12
  631. package/dist/modules/runtime/runner.js +0 -48
  632. package/dist/modules/runtime/stages.d.ts +0 -53
  633. package/dist/modules/runtime/stages.js +0 -117
  634. package/dist/modules/sqlite/jobQueue.d.ts +0 -35
  635. package/dist/modules/sqlite/jobQueue.js +0 -56
  636. package/dist/modules/sqlite/kv.d.ts +0 -34
  637. package/dist/modules/sqlite/kv.js +0 -91
  638. package/dist/modules/sqlite/open.d.ts +0 -3
  639. package/dist/modules/sqlite/open.js +0 -13
  640. package/dist/modules/ssr/Component.js +0 -37
  641. package/dist/modules/ssr/applySSRResult.js +0 -54
  642. package/dist/modules/ssr/buildBody.js +0 -35
  643. package/dist/modules/ssr/handler.js +0 -103
  644. package/dist/modules/ssr/loadPluginComponents.js +0 -81
  645. package/dist/modules/ssr/prepareRender.js +0 -332
  646. package/dist/modules/ssr/preview.js +0 -70
  647. package/dist/modules/ssr/registerExternalPlugins.js +0 -111
  648. package/dist/modules/ssr/reportMissingPlugins.js +0 -24
  649. package/dist/modules/ssr/resolvePageSeo.js +0 -41
  650. package/dist/modules/ssr/spaceDocument.js +0 -85
  651. package/dist/modules/ssr/streamBody.js +0 -69
  652. package/dist/modules/ssr/template.js +0 -10
  653. package/dist/mongo.d.ts +0 -25
  654. package/dist/mongo.js +0 -3
  655. package/dist/mysql.d.ts +0 -37
  656. package/dist/mysql.js +0 -7
  657. package/dist/plugins/compile.js +0 -53
  658. package/dist/plugins/copy.js +0 -28
  659. package/dist/plugins/detect.js +0 -9
  660. package/dist/plugins/manager.js +0 -508
  661. package/dist/plugins/validate.js +0 -23
  662. package/dist/plugins/watch.js +0 -79
  663. package/dist/runtime.d.ts +0 -16
  664. package/dist/runtime.js +0 -7
  665. package/dist/sqlite.d.ts +0 -24
  666. package/dist/sqlite.js +0 -3
package/dist/auth.js CHANGED
@@ -1,22 +1,2323 @@
1
- import { createMemoryRateLimit } from "./core/auth/throttle.js";
2
- import { createCarriers, presentedOrigin } from "./core/auth/credentials.js";
3
- import { appendCookies, clearFlowCookie, clearSessionCookies, createSessionCookies, isLocalHost, parseSessionHint, readFlowCookie, readRefreshToken, readSessionHint, readSessionToken, sessionCookieParams, sessionHintValue, sessionReturnTarget, writeFlowCookie, writeSessionCookies } from "./core/auth/session.js";
4
- import { createCsrf, csrfFailureMessage } from "./core/auth/csrf.js";
5
- import { applySessionOutcome, authPolicyRules, authRoutes } from "./core/auth/routes.js";
6
- import { isDocumentNavigation, renewForNavigation } from "./core/auth/renewal.js";
7
- import { ANY_DOMAIN, corsOrigins, domainAllowed, frameAncestors, hostnameOf, normalizeDomain } from "./core/auth/domains.js";
8
- import { checkPermission, checkSpaceAccess, createAuthorizer, requirementFor } from "./core/auth/authorize.js";
9
- import { generateToken, hashPassword, verifyPassword } from "./core/auth/passwords.js";
10
- import { generateRecoveryCodes, generateTotpSecret, normalizeRecoveryCode, randomCode, totpCode, totpStep, totpUri, verifyTotp } from "./core/auth/totp.js";
11
- import { SCOPES, authFailureMessage, createTokens, userIdOf } from "./core/auth/tokens.js";
12
- import { createAuthApi } from "./core/auth/api/index.js";
13
- import { createIdentity } from "./core/auth/identity.js";
14
- import { createAuth } from "./core/auth/createAuth.js";
15
- import { SESSION_ACTIVITY_RESOLUTION_SECONDS, activityDue } from "./core/auth/sessionActivity.js";
16
- import { OAuthFailure } from "./core/auth/oauth/types.js";
17
- import { requestProfileJson } from "./core/auth/oauth/client.js";
18
- import { createRedirectPolicy } from "./core/auth/redirects.js";
19
- import { createOidcProvider, discoverOidc } from "./core/auth/oauth/providers/oidc.js";
20
- import { BUILT_IN_PROVIDERS, createSocialAuth } from "./core/auth/oauth/index.js";
21
- import { createSpaceTokenApi } from "./core/auth/spaceTokens.js";
22
- export { ANY_DOMAIN, BUILT_IN_PROVIDERS, OAuthFailure, SCOPES, SESSION_ACTIVITY_RESOLUTION_SECONDS, activityDue, appendCookies, applySessionOutcome, authFailureMessage, authPolicyRules, authRoutes, checkPermission, checkSpaceAccess, clearFlowCookie, clearSessionCookies, corsOrigins, createAuth, createAuthApi, createAuthorizer, createCarriers, createCsrf, createIdentity, createMemoryRateLimit, createOidcProvider, createRedirectPolicy, createSessionCookies, createSocialAuth, createSpaceTokenApi, createTokens, csrfFailureMessage, discoverOidc, domainAllowed, frameAncestors, generateRecoveryCodes, generateToken, generateTotpSecret, hashPassword, hostnameOf, isDocumentNavigation, isLocalHost, normalizeDomain, normalizeRecoveryCode, parseSessionHint, presentedOrigin, randomCode, readFlowCookie, readRefreshToken, readSessionHint, readSessionToken, renewForNavigation, requestProfileJson, requirementFor, sessionCookieParams, sessionHintValue, sessionReturnTarget, totpCode, totpStep, totpUri, userIdOf, verifyPassword, verifyTotp, writeFlowCookie, writeSessionCookies };
1
+ import { n as createMemoryRateLimit, r as fleetRateLimit } from "./chunks/throttle-BH7JLIOF.js";
2
+ import { a as authRoutes, i as authPolicyRules, n as renewForNavigation, r as applySessionOutcome, t as isDocumentNavigation } from "./chunks/renewal-D98v6-Jd.js";
3
+ import { forwardedIp } from "@plitzi/sdk-kernel/http";
4
+ import { serverLog } from "@plitzi/sdk-kernel/log";
5
+ import { authFailureMessage, checkPermission, createAuthorizer, createCarriers, createCsrf, createIdentity, createSessionCookies, generateToken, hashPassword, presentedOrigin, sessionCookieParams, verifyPassword } from "@plitzi/sdk-kernel/identity";
6
+ import { createHash, createHmac, createPublicKey, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
7
+ import { createTokens, userIdOf } from "@plitzi/sdk-kernel/tokens";
8
+ import jwt from "jsonwebtoken";
9
+ // src/core/auth/api/values.ts
10
+ var clientOf = (carrier) => {
11
+ if (!carrier) return;
12
+ const userAgent = carrier.headers["user-agent"];
13
+ const ip = carrier.ip || forwardedIp(carrier.headers);
14
+ const client = {
15
+ ...typeof userAgent === "string" && userAgent ? { userAgent } : {},
16
+ ...ip ? { ip } : {},
17
+ ...carrier.hostname ? { host: carrier.hostname.toLowerCase() } : {}
18
+ };
19
+ return client.userAgent || client.ip || client.host ? client : void 0;
20
+ };
21
+ /**
22
+ * The account store, as auth needs to see it. Every method is optional except the three the session cycle cannot do
23
+ * without, and **what is absent decides what this server offers**: a deployment with no `createAccount` has no
24
+ * signup, and its route answers 404 rather than failing at runtime. That rule is what lets one server serve a
25
+ * deployment with its own user table and one that signs everybody in through an external provider.
26
+ */
27
+ var refuse = (status, error, reason) => ({
28
+ ok: false,
29
+ status,
30
+ body: reason ? {
31
+ error,
32
+ reason
33
+ } : { error }
34
+ });
35
+ var NOT_OFFERED = refuse(404, "Not found");
36
+ /**
37
+ * A field from a request body, as a string. Numbers count: JSON carries an all-digits password as a number, and a
38
+ * client that sends one has supplied a password — refusing it as "credentials are required" is a lie about what
39
+ * arrived. Objects and arrays do not, since `[object Object]` is not a value anybody sent.
40
+ */
41
+ var asText = (value) => {
42
+ if (typeof value === "string") return value;
43
+ return typeof value === "number" && Number.isFinite(value) ? String(value) : "";
44
+ };
45
+ var asString = (value) => asText(value).trim();
46
+ /**
47
+ * The destination a caller named, for a mail to carry — or nothing at all.
48
+ *
49
+ * Carried, not judged: the kernel has no redirect policy, and the link it ends up in is composed by the deployment,
50
+ * which vets it there (`createRedirectPolicy`). Absent rather than empty when there is none, so a mail template never
51
+ * has to know that `''` means "nowhere".
52
+ */
53
+ var destinationOf = (value) => {
54
+ const redirect = asString(value);
55
+ return redirect ? { redirect } : {};
56
+ };
57
+ var now = () => Math.floor(Date.now() / 1e3);
58
+ var HOUR = 3600;
59
+ /**
60
+ * How long the things this server mails or hands out stay good for. Constants rather than configuration: each is a
61
+ * security answer with one sensible value, and an option here is a question every deployment has to work out an
62
+ * answer to before it can start.
63
+ */
64
+ var LIFETIME = {
65
+ /** A code from an email. Long enough to go and find it, short enough that a stolen one is worthless. */
66
+ signInCode: 600,
67
+ /** A reset link IS a password, and it sits in an inbox, a mail archive, a forwarded ticket. */
68
+ resetLink: HOUR,
69
+ /** Confirming an address is not a credential in the same way, and people read their mail tomorrow. */
70
+ confirmLink: 24 * HOUR,
71
+ /** A borrowed session — see `admin.impersonate`. Short, and it cannot renew. */
72
+ impersonation: 900
73
+ };
74
+ var STATUSES = [
75
+ "active",
76
+ "inactive",
77
+ "blocked"
78
+ ];
79
+ /**
80
+ * Why an account may not hold a session, when it may not.
81
+ *
82
+ * `active` answers whether it may sign in at all; `verified` answers whether its owner can do anything about that.
83
+ * A deployment where confirming an address is what makes an account active — Plitzi is one — refuses both through
84
+ * the same flag, so a screen told only `inactive` has to tell somebody whose address has simply never answered that
85
+ * their password was wrong. It was, in fact, right.
86
+ */
87
+ var deniedReason = (account) => account && !account.verified ? "unverified" : "inactive";
88
+ /** An account as it may be shown. Never the password hash, and never the credentials — not even to an admin. */
89
+ var profileOf = (account) => ({
90
+ id: account.id,
91
+ username: account.username,
92
+ email: account.email,
93
+ active: account.active,
94
+ verified: account.verified
95
+ });
96
+ // src/core/auth/api/accounts.ts
97
+ /** An account made and recovered: signing up, verifying the address, forgetting and resetting the password. */
98
+ var accountsFlows = ({ adapters, hashPassword, generateToken, verifyOnSignup, terms, record, mintLink, linkExpired, deliver, throttled, rejectPassword, capabilities }) => ({
99
+ signup: async (fields) => {
100
+ if (!capabilities.signup) return NOT_OFFERED;
101
+ const username = asString(fields.username);
102
+ const email = asString(fields.email);
103
+ const password = asText(fields.password);
104
+ if (!username || !email || !password) return refuse(400, "A username, an email and a password are required");
105
+ if (terms && fields.acceptedTerms !== true && fields.acceptedTerms !== "true") return {
106
+ ok: false,
107
+ status: 400,
108
+ body: {
109
+ error: "Accept the terms of service to create an account",
110
+ field: "acceptedTerms"
111
+ }
112
+ };
113
+ const weak = await rejectPassword(password, {
114
+ username,
115
+ email
116
+ });
117
+ if (weak) return weak;
118
+ const limited = await throttled({
119
+ action: "signup",
120
+ key: email
121
+ });
122
+ if (limited) return limited;
123
+ const takenBy = async () => {
124
+ const taken = await adapters.findByUsername?.(username) ? "username" : await adapters.findByEmail?.(email) ? "email" : void 0;
125
+ return taken ? {
126
+ ok: false,
127
+ status: 400,
128
+ body: {
129
+ error: taken === "username" ? "That username is already taken" : "An account with that email already exists",
130
+ field: taken
131
+ }
132
+ } : void 0;
133
+ };
134
+ const takenBefore = await takenBy();
135
+ if (takenBefore) return takenBefore;
136
+ if (!adapters.createAccount) return NOT_OFFERED;
137
+ const createAccount = adapters.createAccount;
138
+ /**
139
+ * Taken in the meantime, by a sign-up with the same name or address that got there first: what the store refused
140
+ * is said as the check above says it. Two at once (a double submit, two tabs) answered one of them a 500.
141
+ */
142
+ const account = await createAccount({
143
+ username,
144
+ email,
145
+ passwordHash: await hashPassword(password),
146
+ ...terms ? { termsAccepted: {
147
+ version: terms.version,
148
+ at: /* @__PURE__ */ new Date()
149
+ } } : {}
150
+ }).catch(async (error) => {
151
+ const takenSince = await takenBy();
152
+ if (takenSince) return takenSince;
153
+ throw error;
154
+ });
155
+ if ("ok" in account) return account;
156
+ if (!verifyOnSignup && capabilities.emailVerification && adapters.setValidationToken) {
157
+ const validationToken = mintLink(generateToken(), LIFETIME.confirmLink);
158
+ await adapters.setValidationToken(account.id, validationToken);
159
+ await deliver({
160
+ to: email,
161
+ template: "validation",
162
+ data: {
163
+ username,
164
+ validationToken,
165
+ ...destinationOf(fields.redirect)
166
+ }
167
+ });
168
+ }
169
+ record({
170
+ type: "signup",
171
+ userId: account.id
172
+ });
173
+ return {
174
+ ok: true,
175
+ status: 201,
176
+ body: {
177
+ message: "User created successfully",
178
+ userId: account.id
179
+ }
180
+ };
181
+ },
182
+ /** Answers the same either way: whether an address has an account here is not something a stranger may probe. */
183
+ forgotPassword: async (email) => {
184
+ if (!capabilities.passwordReset) return NOT_OFFERED;
185
+ const limited = await throttled({
186
+ action: "forgotPassword",
187
+ key: asString(email)
188
+ });
189
+ if (limited) return limited;
190
+ const account = await adapters.findByEmail?.(asString(email));
191
+ if (account) {
192
+ const resetToken = mintLink(generateToken(), LIFETIME.resetLink);
193
+ await adapters.setResetToken?.(account.id, resetToken);
194
+ await deliver({
195
+ to: account.email,
196
+ template: "password-reset",
197
+ data: {
198
+ username: account.username,
199
+ resetToken
200
+ }
201
+ });
202
+ }
203
+ return {
204
+ ok: true,
205
+ body: { message: "Password reset email sent" }
206
+ };
207
+ },
208
+ resetPassword: async (token, password) => {
209
+ if (!capabilities.passwordReset) return NOT_OFFERED;
210
+ if (!token || !password) return refuse(400, "A token and a password are required");
211
+ const limited = await throttled({
212
+ action: "resetPassword",
213
+ key: token
214
+ });
215
+ if (limited) return limited;
216
+ const account = linkExpired(token) ? void 0 : await adapters.findByResetToken?.(token);
217
+ if (!account) return refuse(400, "Invalid or expired token");
218
+ const weak = await rejectPassword(password, {
219
+ username: account.username,
220
+ email: account.email
221
+ });
222
+ if (weak) return weak;
223
+ await adapters.setPassword?.(account.id, await hashPassword(password));
224
+ await adapters.setResetToken?.(account.id, "");
225
+ await adapters.clearSession({ userId: account.id });
226
+ record({
227
+ type: "password.reset",
228
+ userId: account.id
229
+ });
230
+ return {
231
+ ok: true,
232
+ body: { message: "Password reset successfully" },
233
+ endSession: true
234
+ };
235
+ },
236
+ validateAccount: async (token) => {
237
+ if (!capabilities.emailVerification) return NOT_OFFERED;
238
+ const account = linkExpired(token) ? void 0 : await adapters.findByValidationToken?.(token);
239
+ if (!account) return refuse(400, "Invalid or expired token");
240
+ await adapters.setVerified?.(account.id, true);
241
+ return {
242
+ ok: true,
243
+ body: { message: "Account validated successfully" }
244
+ };
245
+ },
246
+ resendVerification: async (email, redirect) => {
247
+ if (!capabilities.emailVerification) return NOT_OFFERED;
248
+ const account = await adapters.findByEmail?.(asString(email));
249
+ if (account && !account.verified) {
250
+ const validationToken = mintLink(generateToken(), LIFETIME.confirmLink);
251
+ await adapters.setValidationToken?.(account.id, validationToken);
252
+ await deliver({
253
+ to: account.email,
254
+ template: "validation",
255
+ data: {
256
+ username: account.username,
257
+ validationToken,
258
+ ...destinationOf(redirect)
259
+ }
260
+ });
261
+ }
262
+ return {
263
+ ok: true,
264
+ body: { message: "Verification email resent" }
265
+ };
266
+ }
267
+ });
268
+ // src/core/auth/api/admin.ts
269
+ /** What an admin does to other accounts. */
270
+ var adminFlows = ({ adapters, impersonationPermission, record, capabilities, requireAdmin, issue, grantBody }) => ({ admin: {
271
+ list: async (actor, query) => {
272
+ const denial = requireAdmin(actor);
273
+ if (denial) return denial;
274
+ if (!adapters.listAccounts) return NOT_OFFERED;
275
+ const { accounts, total } = await adapters.listAccounts(query);
276
+ return {
277
+ ok: true,
278
+ body: {
279
+ accounts: accounts.map(profileOf),
280
+ total
281
+ }
282
+ };
283
+ },
284
+ get: async (actor, userId) => {
285
+ const denial = requireAdmin(actor);
286
+ if (denial) return denial;
287
+ const account = await adapters.findById?.(userId);
288
+ if (!account) return refuse(404, "No such account");
289
+ return {
290
+ ok: true,
291
+ body: {
292
+ account: profileOf(account),
293
+ access: await adapters.loadAccess(userId)
294
+ }
295
+ };
296
+ },
297
+ /**
298
+ * Suspend, block or restore an account — and **end its sessions when it stops being active**.
299
+ *
300
+ * That second half is the whole point. A ban that leaves the credential working is not a ban, it is a note
301
+ * in a database; the person stays signed in until their token happens to lapse.
302
+ */
303
+ setStatus: async (actor, userId, status) => {
304
+ const denial = requireAdmin(actor, userId);
305
+ if (denial) return denial;
306
+ if (!adapters.setStatus) return NOT_OFFERED;
307
+ if (!STATUSES.includes(status)) return refuse(400, `Status must be one of ${STATUSES.join(", ")}`);
308
+ if (!await adapters.findById?.(userId)) return refuse(404, "No such account");
309
+ await adapters.setStatus(userId, status);
310
+ if (status !== "active") await adapters.clearSession({ userId });
311
+ record({
312
+ type: "admin.status-changed",
313
+ userId,
314
+ actorId: actor?.id,
315
+ detail: { status }
316
+ });
317
+ return {
318
+ ok: true,
319
+ body: {
320
+ success: true,
321
+ status
322
+ }
323
+ };
324
+ },
325
+ setRoles: async (actor, userId, roles) => {
326
+ const denial = requireAdmin(actor);
327
+ if (denial) return denial;
328
+ if (!adapters.setRoles) return NOT_OFFERED;
329
+ if (!Array.isArray(roles) || roles.some((role) => typeof role !== "string")) return refuse(400, "Roles must be a list of names");
330
+ const names = roles;
331
+ if (!await adapters.findById?.(userId)) return refuse(404, "No such account");
332
+ await adapters.setRoles(userId, names);
333
+ record({
334
+ type: "admin.roles-changed",
335
+ userId,
336
+ actorId: actor?.id,
337
+ detail: { roles: names }
338
+ });
339
+ return {
340
+ ok: true,
341
+ body: {
342
+ success: true,
343
+ roles: names
344
+ }
345
+ };
346
+ },
347
+ remove: async (actor, userId) => {
348
+ const denial = requireAdmin(actor, userId);
349
+ if (denial) return denial;
350
+ if (!adapters.deleteAccount) return NOT_OFFERED;
351
+ if (!await adapters.findById?.(userId)) return refuse(404, "No such account");
352
+ await adapters.deleteAccount(userId);
353
+ record({
354
+ type: "admin.account-deleted",
355
+ userId,
356
+ actorId: actor?.id
357
+ });
358
+ return {
359
+ ok: true,
360
+ body: { success: true }
361
+ };
362
+ },
363
+ /**
364
+ * A session AS somebody else, for support that has to see what they see.
365
+ *
366
+ * Three properties make it something a deployment can live with, and all three are deliberate:
367
+ *
368
+ * - **It says so.** The credential carries `act` (RFC 8693), so every request made with it can be told from
369
+ * one the account holder made — `Actor.impersonatedBy` is that claim, read back. A borrowed session that
370
+ * is indistinguishable from a real one turns an audit log into fiction.
371
+ * - **It is short and cannot renew.** Fifteen minutes by default and no refresh token, so it expires rather
372
+ * than becoming a permanent second key to somebody's account.
373
+ * - **It is off unless asked for**, behind its own permission — see `impersonationPermission`.
374
+ *
375
+ * The session is answered in the BODY and no cookie is written. Swapping the administrator's own session
376
+ * cookie for this one would sign them out of the account they administer from, and getting back would mean
377
+ * signing in again; whoever asked decides where to put a credential they were handed.
378
+ *
379
+ * One caveat a deployment has to know: a store that keeps a single session per account — no `session` table —
380
+ * will overwrite the subject's own session with this one, signing them out. Anything with per-session rows,
381
+ * which is what `createMysqlStore` builds, does not.
382
+ */
383
+ impersonate: async (actor, userId, carrier) => {
384
+ if (!capabilities.impersonation || !impersonationPermission || !adapters.findById) return NOT_OFFERED;
385
+ const check = checkPermission(actor, impersonationPermission);
386
+ if (!check.ok) return refuse(check.status, check.error, check.status === 401 ? "missing" : void 0);
387
+ if (!actor || userId === actor.id) return refuse(400, "You are already signed in as yourself");
388
+ const account = await adapters.findById(userId);
389
+ if (!account) return refuse(404, "No such account");
390
+ if (!account.active) return refuse(403, "That account is not active");
391
+ const session = await issue(userId, { client: clientOf(carrier) }, {
392
+ actingAs: actor.id,
393
+ ttlSeconds: LIFETIME.impersonation,
394
+ renewable: false
395
+ });
396
+ record({
397
+ type: "admin.impersonated",
398
+ userId,
399
+ actorId: actor.id
400
+ });
401
+ return {
402
+ ok: true,
403
+ body: {
404
+ ...await grantBody(account, session),
405
+ impersonatedBy: actor.id
406
+ }
407
+ };
408
+ }
409
+ } });
410
+ // src/core/auth/totp.ts
411
+ /**
412
+ * Time-based one-time passwords, RFC 6238, on the standard library.
413
+ *
414
+ * Six digits over HMAC-SHA1 in thirty-second steps, because that is what every authenticator app assumes and the
415
+ * point of this is that Google Authenticator, 1Password and Aegis all work without being told anything. The RFC
416
+ * allows SHA-256 and other digit counts; almost nothing in the wild reads them off the enrolment URI.
417
+ */
418
+ var DIGITS = 6;
419
+ var STEP_SECONDS = 30;
420
+ /** RFC 4648 base32, which is the alphabet authenticator apps expect a secret in. No padding: apps dislike it. */
421
+ var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
422
+ var base32Encode = (bytes) => {
423
+ let bits = 0;
424
+ let value = 0;
425
+ let output = "";
426
+ for (const byte of bytes) {
427
+ value = value << 8 | byte;
428
+ bits += 8;
429
+ while (bits >= 5) {
430
+ output += ALPHABET[value >>> bits - 5 & 31];
431
+ bits -= 5;
432
+ }
433
+ }
434
+ if (bits > 0) output += ALPHABET[value << 5 - bits & 31];
435
+ return output;
436
+ };
437
+ var base32Decode = (secret) => {
438
+ const clean = secret.toUpperCase().replace(/[^A-Z2-7]/g, "");
439
+ const bytes = [];
440
+ let bits = 0;
441
+ let value = 0;
442
+ for (const character of clean) {
443
+ value = value << 5 | ALPHABET.indexOf(character);
444
+ bits += 5;
445
+ if (bits >= 8) {
446
+ bytes.push(value >>> bits - 8 & 255);
447
+ bits -= 8;
448
+ }
449
+ }
450
+ return Buffer.from(bytes);
451
+ };
452
+ /** A 20-byte secret, which is what RFC 4226 recommends for HMAC-SHA1 and what apps are sized for. */
453
+ var generateTotpSecret = () => base32Encode(randomBytes(20));
454
+ var codeAt = (secret, counter) => {
455
+ const buffer = Buffer.alloc(8);
456
+ buffer.writeUInt32BE(Math.floor(counter / 2 ** 32), 0);
457
+ buffer.writeUInt32BE(counter >>> 0, 4);
458
+ const digest = createHmac("sha1", base32Decode(secret)).update(buffer).digest();
459
+ const offset = digest[digest.length - 1] & 15;
460
+ const binary = (digest[offset] & 127) << 24 | (digest[offset + 1] & 255) << 16 | (digest[offset + 2] & 255) << 8 | digest[offset + 3] & 255;
461
+ return String(binary % 10 ** DIGITS).padStart(DIGITS, "0");
462
+ };
463
+ /** The code an app would be showing right now. Exported so a test does not have to reimplement the algorithm. */
464
+ var totpCode = (secret, at = Date.now()) => codeAt(secret, Math.floor(at / 1e3 / STEP_SECONDS));
465
+ /**
466
+ * Which time step this code belongs to, or `undefined` when it belongs to none near now.
467
+ *
468
+ * `window` steps either side are accepted, one by default — thirty seconds of tolerance for a clock that drifts
469
+ * and for a person who starts typing at second twenty-nine. Wider is friendlier and weaker; this is the usual
470
+ * trade and the same one Google Authenticator's own guidance makes.
471
+ *
472
+ * The step is the answer, not a yes: a code stays valid for its whole window, so a verifier that remembers nothing
473
+ * accepts the same code twice. RFC 6238 §5.2 forbids that — see `MfaRecord.lastUsedStep`.
474
+ *
475
+ * Compared in constant time: a comparison that returns on the first differing digit leaks how much of a guess was
476
+ * right, which turns a million-guess space into ten guesses per position.
477
+ */
478
+ var totpStep = (secret, code, options = {}) => {
479
+ const { window = 1, at = Date.now() } = options;
480
+ const candidate = code.trim();
481
+ if (!/^\d{6}$/.test(candidate)) return;
482
+ const counter = Math.floor(at / 1e3 / STEP_SECONDS);
483
+ const supplied = Buffer.from(candidate);
484
+ let matched;
485
+ for (let drift = -window; drift <= window; drift++) {
486
+ const expected = Buffer.from(codeAt(secret, counter + drift));
487
+ if (timingSafeEqual(expected, supplied)) matched = counter + drift;
488
+ }
489
+ return matched;
490
+ };
491
+ /** Is this the code? `totpStep`, for a caller that does not need to know which step it was. */
492
+ var verifyTotp = (secret, code, options = {}) => totpStep(secret, code, options) !== void 0;
493
+ /**
494
+ * The URI an authenticator app scans. `issuer` appears twice by convention — in the label and as a parameter —
495
+ * because different apps read different ones, and an entry that says only an email address is unidentifiable in a
496
+ * list of thirty.
497
+ */
498
+ var totpUri = ({ secret, account, issuer }) => {
499
+ return `otpauth://totp/${encodeURIComponent(`${issuer}:${account}`)}?${new URLSearchParams({
500
+ secret,
501
+ issuer,
502
+ algorithm: "SHA1",
503
+ digits: String(DIGITS),
504
+ period: "30"
505
+ }).toString()}`;
506
+ };
507
+ /**
508
+ * An unbiased random string over an alphabet.
509
+ *
510
+ * `randomInt` rejection-samples, which is the whole point: the obvious `byte % alphabet.length` over-represents the
511
+ * first `256 % length` characters, and a token that gates an account has to draw every character with equal
512
+ * probability. Hand-rolling that correctly is a known trap, so it is written once here.
513
+ *
514
+ * Default alphabet is Crockford-ish base32 — no `0`/`O`/`1`/`I`, so a code read aloud or off paper survives.
515
+ */
516
+ var randomCode = (length, alphabet = ALPHABET) => Array.from({ length }, () => alphabet[randomInt(alphabet.length)]).join("");
517
+ /**
518
+ * Recovery codes, for the phone that went in a river.
519
+ *
520
+ * Ten of them, each 40 bits of entropy in a shape somebody can read off paper. Generated once and shown once: they
521
+ * are stored hashed, so a deployment that loses them cannot print them again, which is the property that makes
522
+ * them worth having.
523
+ */
524
+ var generateRecoveryCodes = (count = 10) => Array.from({ length: count }, () => {
525
+ const digits = randomCode(10);
526
+ return `${digits.slice(0, 5)}-${digits.slice(5)}`;
527
+ });
528
+ /** Normalised before hashing so that case and the hyphen a person types or omits do not decide whether it works. */
529
+ var normalizeRecoveryCode = (code) => code.trim().toUpperCase().replace(/[^A-Z0-9]/g, "");
530
+ // src/core/auth/api/context.ts
531
+ /** What every flow of the auth API shares: the adapters and the settings, read once, and the steps they take alike. */
532
+ var createAuthContext = ({ tokens, identity, adapters, config = {} }) => {
533
+ const { verifyPassword: verifyPassword$1 = verifyPassword, hashPassword: hashPassword$1 = hashPassword, generateToken: generateToken$1 = generateToken, verifyOnSignup = false, terms, adminPermission = "userManage", impersonationPermission, password: policy = {}, rateLimit = fleetRateLimit() ?? createMemoryRateLimit(), onMailError, onEvent, mfaIssuer, csrf } = config;
534
+ /** Never awaited, never able to throw: a logging outage must not become an authentication outage. */
535
+ const record = (event) => {
536
+ if (!onEvent) return;
537
+ try {
538
+ onEvent({
539
+ ...event,
540
+ at: Math.floor(Date.now() / 1e3)
541
+ });
542
+ } catch (error) {
543
+ serverLog.error("auth", "security event handler threw", error);
544
+ }
545
+ };
546
+ /**
547
+ * A single-use link token that stops working.
548
+ *
549
+ * The deadline is carried **inside the token**, after a `~`, and that is what makes this cost nothing: no column,
550
+ * no adapter argument, and nothing a deployment with its own store has to remember to enforce — which is the
551
+ * failure mode of putting the check in the adapters, where forgetting it is silent and looks like everything
552
+ * working. It is not a secret and does not need to be: the token is compared against the stored copy, so editing
553
+ * the deadline just produces a string that matches no row.
554
+ *
555
+ * A token issued before this existed has no `~`, reads as no deadline, and keeps working — the links already in
556
+ * people's inboxes when a deployment upgrades.
557
+ */
558
+ const mintLink = (random, lifetime) => `${random}~${now() + lifetime}`;
559
+ const linkExpired = (token) => {
560
+ const deadline = Number(token.slice(token.lastIndexOf("~") + 1));
561
+ return Number.isFinite(deadline) && token.includes("~") && deadline < now();
562
+ };
563
+ /** Recovery codes are high-entropy, so a fast digest is right — scrypt ten times per sign-in would not be. */
564
+ const digestRecoveryCode = (code) => createHash("sha256").update(normalizeRecoveryCode(code)).digest("hex");
565
+ /**
566
+ * Sends, and never fails the flow if it cannot.
567
+ *
568
+ * Every one of these goes out AFTER something has already been committed — an account created, an address
569
+ * changed, a reset token stored. Letting the mail provider decide whether that request succeeded turns an
570
+ * outage at Brevo into a 500 on a change that did happen, which is the worst of both: the caller is told it
571
+ * failed and retries against the new state. Reported instead, and the person can ask for another.
572
+ */
573
+ const deliver = async (message) => {
574
+ try {
575
+ await adapters.sendMail?.(message);
576
+ } catch (error) {
577
+ (onMailError ?? ((cause) => serverLog.error("auth", "could not send mail", cause)))(error, {
578
+ to: message.to,
579
+ template: message.template
580
+ });
581
+ }
582
+ };
583
+ /**
584
+ * Checked before the password is, so a throttled attempt costs no hash — which is the difference between a rate
585
+ * limit and a slightly slower way to be brute-forced.
586
+ */
587
+ /** Whatever was counted against this key is forgiven: the attempt it was guarding against succeeded. */
588
+ const throttleSucceeded = (attempt) => {
589
+ Promise.resolve(rateLimit({
590
+ ...attempt,
591
+ succeeded: true
592
+ })).catch(() => void 0);
593
+ };
594
+ const throttled = async (attempt) => {
595
+ const verdict = await rateLimit(attempt);
596
+ if (typeof verdict === "boolean" ? verdict : verdict.allowed) return;
597
+ const retryAfter = typeof verdict === "boolean" ? void 0 : verdict.retryAfter;
598
+ return {
599
+ ok: false,
600
+ status: 429,
601
+ body: {
602
+ error: "Too many attempts",
603
+ ...retryAfter !== void 0 ? { retryAfter } : {}
604
+ }
605
+ };
606
+ };
607
+ /** The one place a new password is judged, so signing up, resetting and changing cannot disagree about it. */
608
+ const rejectPassword = async (value, context = {}) => {
609
+ const minLength = policy.minLength ?? 8;
610
+ if (value.length < minLength) return refuse(400, `The password must be at least ${minLength} characters`);
611
+ const reason = await policy.validate?.(value, context);
612
+ return reason ? refuse(400, reason) : void 0;
613
+ };
614
+ /**
615
+ * What this deployment offers, decided by what it supplied and nothing else.
616
+ *
617
+ * There used to be a parallel set of `features` switches. They were redundant in every case — each flow reads
618
+ * adapters that no other flow reads, so leaving one out is already how you decline it — and two ways of saying
619
+ * the same thing invite the state where they disagree: an adapter wired up, the flag forgotten, and an endpoint
620
+ * that answers 404 for no reason anyone can see. Declining a flow is now one act: do not implement it.
621
+ */
622
+ const capabilities = {
623
+ passwordLogin: !!adapters.findByUsername,
624
+ refresh: !!adapters.findByRefreshToken,
625
+ signup: !!adapters.createAccount,
626
+ passwordReset: !!adapters.findByEmail && !!adapters.setResetToken,
627
+ emailVerification: !!adapters.findByValidationToken && !!adapters.setVerified,
628
+ exchange: !!adapters.exchangeCredential,
629
+ mfa: !!adapters.loadMfa && !!adapters.saveMfa,
630
+ passwordless: !!adapters.saveOtp && !!adapters.findOtp && !!adapters.findByEmail && !!adapters.sendMail,
631
+ profile: !!adapters.updateAccount,
632
+ passwordChange: !!adapters.findById && !!adapters.setPassword,
633
+ accountDeletion: !!adapters.deleteAccount,
634
+ sessionList: !!adapters.listSessions,
635
+ administration: !!adapters.listAccounts && !!adapters.findById,
636
+ /** Changing an address by confirming it, rather than on the spot. Needs somewhere to park it and a way to write. */
637
+ emailChange: !!adapters.setPendingEmail && !!adapters.findByPendingEmail && !!adapters.clearPendingEmail && !!adapters.updateAccount && !!adapters.sendMail,
638
+ /** Off unless the deployment named the capability it takes — see `impersonationPermission`. */
639
+ impersonation: !!impersonationPermission && !!adapters.findById
640
+ };
641
+ /**
642
+ * An administrator acting on somebody else.
643
+ *
644
+ * `subject` refuses the case where that somebody is themselves. Banning or deleting your own account through the
645
+ * admin surface is how a deployment loses its last administrator, and it is never what was meant: closing your
646
+ * own account is the self-service flow, which asks for a password precisely because it is irreversible.
647
+ */
648
+ const requireAdmin = (actor, subject) => {
649
+ const check = checkPermission(actor, adminPermission);
650
+ if (!check.ok) return refuse(check.status, check.error, check.status === 401 ? "missing" : void 0);
651
+ if (subject !== void 0 && subject === actor?.id) return refuse(400, "Use the self-service route to act on your own account");
652
+ };
653
+ /**
654
+ * A session for this account. `options` is only for the one that is not an ordinary sign-in: a borrowed session
655
+ * carries who borrowed it and cannot renew itself, so it dies at its deadline instead of quietly living for a
656
+ * month behind a refresh token.
657
+ */
658
+ const issue = async (userId, context, options = {}) => {
659
+ const { actingAs, ttlSeconds, renewable = true } = options;
660
+ const now = Math.floor(Date.now() / 1e3);
661
+ const session = {
662
+ token: tokens.generateUserToken(userId, {
663
+ actingAs,
664
+ ttlSeconds
665
+ }),
666
+ expiresAt: now + (ttlSeconds ?? tokens.lifetimes.access),
667
+ ...renewable ? {
668
+ refreshToken: tokens.generateRefreshToken(userId),
669
+ refreshExpiresAt: now + tokens.lifetimes.refresh
670
+ } : {}
671
+ };
672
+ await adapters.saveSession(userId, session, context);
673
+ return session;
674
+ };
675
+ /**
676
+ * The body a grant answers with. `details` is the same object the session endpoint returns, deliberately: it makes
677
+ * a grant an identity, so a client that has just signed in or renewed knows who it is without a second request.
678
+ */
679
+ const grantBody = async (account, session, loaded) => {
680
+ const access = loaded ?? await adapters.loadAccess(account.id);
681
+ const now = Math.floor(Date.now() / 1e3);
682
+ return {
683
+ success: true,
684
+ details: {
685
+ id: account.id,
686
+ username: account.username,
687
+ email: account.email,
688
+ verified: account.verified,
689
+ roles: access.roles,
690
+ permissions: access.permissions
691
+ },
692
+ access_token: session.token,
693
+ expire_in: Math.max(0, session.expiresAt - now),
694
+ expire_at: session.expiresAt,
695
+ refresh_token: session.refreshToken,
696
+ refresh_expire_in: Math.max(0, (session.refreshExpiresAt ?? 0) - now),
697
+ refresh_expire_at: session.refreshExpiresAt
698
+ };
699
+ };
700
+ /**
701
+ * Turning a credential from an external identity provider into a session here, answered in accounts.
702
+ *
703
+ * `offered` separates "this deployment does not do exchanges" from "that credential was refused" — a 404 and a
704
+ * 401 respectively, and a caller that cannot tell them apart reports a misconfiguration as a bad password.
705
+ */
706
+ const exchangeAccount = async (provider, token, carrier) => {
707
+ if (!capabilities.exchange) return {
708
+ ok: false,
709
+ offered: false,
710
+ status: 404,
711
+ error: "Not found"
712
+ };
713
+ if (!provider || !token) return {
714
+ ok: false,
715
+ offered: true,
716
+ status: 400,
717
+ error: "A provider and a token are required"
718
+ };
719
+ if (await throttled({
720
+ action: "exchange",
721
+ key: provider,
722
+ carrier
723
+ })) return {
724
+ ok: false,
725
+ offered: true,
726
+ status: 429,
727
+ error: "Too many attempts"
728
+ };
729
+ const result = await adapters.exchangeCredential?.(provider, token, carrier);
730
+ if (!result) return {
731
+ ok: false,
732
+ offered: true,
733
+ status: 401,
734
+ error: "Token Invalid",
735
+ reason: "revoked"
736
+ };
737
+ if ("error" in result) return {
738
+ ok: false,
739
+ offered: true,
740
+ status: result.status ?? 400,
741
+ error: result.error,
742
+ reason: "revoked"
743
+ };
744
+ return {
745
+ ok: true,
746
+ account: result,
747
+ access: await adapters.loadAccess(result.id),
748
+ session: await issue(result.id, { client: clientOf(carrier) })
749
+ };
750
+ };
751
+ return {
752
+ tokens,
753
+ identity,
754
+ adapters,
755
+ verifyPassword: verifyPassword$1,
756
+ hashPassword: hashPassword$1,
757
+ generateToken: generateToken$1,
758
+ verifyOnSignup,
759
+ terms,
760
+ adminPermission,
761
+ impersonationPermission,
762
+ policy,
763
+ rateLimit,
764
+ onMailError,
765
+ onEvent,
766
+ mfaIssuer,
767
+ csrf,
768
+ record,
769
+ mintLink,
770
+ linkExpired,
771
+ digestRecoveryCode,
772
+ deliver,
773
+ throttleSucceeded,
774
+ throttled,
775
+ rejectPassword,
776
+ capabilities,
777
+ requireAdmin,
778
+ issue,
779
+ grantBody,
780
+ exchangeAccount
781
+ };
782
+ };
783
+ // src/core/auth/api/factors.ts
784
+ /** The ways in besides a password: a code or a link by email (`passwordless`), and the second factor (`mfa`). */
785
+ var factorsFlows = ({ tokens, adapters, verifyPassword, mfaIssuer, record, digestRecoveryCode, deliver, throttleSucceeded, throttled, capabilities, issue, grantBody }) => ({
786
+ /**
787
+ * Signing in with a code sent to an email address, and no password at all.
788
+ *
789
+ * Two decisions worth stating. **The request answers the same whether the address exists or not** — anything
790
+ * else turns this endpoint into a way to ask which addresses have accounts. And **it never creates an
791
+ * account**: a sign-in flow that silently registers whoever asks is a different feature, and one a deployment
792
+ * should choose deliberately rather than inherit.
793
+ */
794
+ passwordless: {
795
+ request: async (email, carrier) => {
796
+ if (!capabilities.passwordless) return NOT_OFFERED;
797
+ const address = asString(email).toLowerCase();
798
+ if (!address) return refuse(400, "An email is required");
799
+ const limited = await throttled({
800
+ action: "passwordless",
801
+ key: address,
802
+ carrier
803
+ });
804
+ if (limited) return limited;
805
+ const account = await adapters.findByEmail?.(address);
806
+ if (account?.active) {
807
+ /**
808
+ * Six characters somebody reads out of an email and types, not a link token — `generateToken` mints 128
809
+ * random bits, which is right for something clicked and hostile for something retyped. Two different jobs
810
+ * that were sharing one function, and the deployment that fixed the code for typing quietly weakened
811
+ * every reset link it mailed.
812
+ */
813
+ const code = randomCode(6);
814
+ await adapters.saveOtp?.({
815
+ purpose: "signin",
816
+ identifier: address,
817
+ codeHash: digestRecoveryCode(code),
818
+ expiresAt: now() + LIFETIME.signInCode,
819
+ userId: account.id
820
+ });
821
+ await deliver({
822
+ to: account.email,
823
+ template: "signin-code",
824
+ data: {
825
+ username: account.username,
826
+ code
827
+ }
828
+ });
829
+ }
830
+ return {
831
+ ok: true,
832
+ body: { message: "If that address has an account, a sign-in link is on its way" }
833
+ };
834
+ },
835
+ complete: async (email, code, carrier) => {
836
+ if (!capabilities.passwordless) return NOT_OFFERED;
837
+ const address = asString(email).toLowerCase();
838
+ if (!address || !code) return refuse(400, "An email and a code are required");
839
+ const limited = await throttled({
840
+ action: "passwordless",
841
+ key: address,
842
+ carrier
843
+ });
844
+ if (limited) return limited;
845
+ const stored = await adapters.findOtp?.("signin", address);
846
+ if (!stored || stored.expiresAt < now() || stored.codeHash !== digestRecoveryCode(code)) {
847
+ record({
848
+ type: "login.failed",
849
+ carrier,
850
+ detail: {
851
+ method: "passwordless",
852
+ email: address
853
+ }
854
+ });
855
+ return refuse(401, "Invalid or expired code");
856
+ }
857
+ await adapters.consumeOtp?.(stored.id);
858
+ const account = stored.userId === void 0 ? void 0 : await adapters.findById?.(stored.userId);
859
+ if (!account?.active) {
860
+ const reason = deniedReason(account);
861
+ return refuse(401, authFailureMessage[reason], reason);
862
+ }
863
+ if ((capabilities.mfa ? await adapters.loadMfa?.(account.id) : void 0)?.confirmedAt) {
864
+ record({
865
+ type: "login.mfa-required",
866
+ userId: account.id,
867
+ carrier
868
+ });
869
+ return {
870
+ ok: true,
871
+ body: {
872
+ success: false,
873
+ mfaRequired: true,
874
+ mfaToken: tokens.generateMfaChallenge(account.id)
875
+ }
876
+ };
877
+ }
878
+ const session = await issue(account.id, { client: clientOf(carrier) });
879
+ throttleSucceeded({
880
+ action: "passwordless",
881
+ key: address,
882
+ carrier
883
+ });
884
+ record({
885
+ type: "login",
886
+ userId: account.id,
887
+ carrier,
888
+ detail: { method: "passwordless" }
889
+ });
890
+ return {
891
+ ok: true,
892
+ body: await grantBody(account, session),
893
+ session
894
+ };
895
+ }
896
+ },
897
+ /**
898
+ * Everything about this account's second factor. `begin` hands back a secret and the URI an app scans; nothing
899
+ * is in force until `confirm` proves a code from it.
900
+ */
901
+ mfa: {
902
+ status: async (actor) => {
903
+ if (!capabilities.mfa) return NOT_OFFERED;
904
+ if (!actor) return refuse(401, "Not authenticated", "missing");
905
+ const mfa = await adapters.loadMfa?.(actor.id);
906
+ return {
907
+ ok: true,
908
+ body: {
909
+ enabled: Boolean(mfa?.confirmedAt),
910
+ pending: Boolean(mfa && !mfa.confirmedAt),
911
+ recoveryCodesRemaining: mfa?.recoveryCodes?.length ?? 0
912
+ }
913
+ };
914
+ },
915
+ begin: async (actor) => {
916
+ if (!capabilities.mfa) return NOT_OFFERED;
917
+ if (!actor) return refuse(401, "Not authenticated", "missing");
918
+ if ((await adapters.loadMfa?.(actor.id))?.confirmedAt) return refuse(409, "A second factor is already set up. Remove it before enrolling another.");
919
+ const secret = generateTotpSecret();
920
+ await adapters.saveMfa?.(actor.id, { secret });
921
+ return {
922
+ ok: true,
923
+ body: {
924
+ secret,
925
+ uri: totpUri({
926
+ secret,
927
+ account: actor.email || actor.username,
928
+ issuer: mfaIssuer ?? tokens.issuer
929
+ })
930
+ }
931
+ };
932
+ },
933
+ /** Proves the app was actually set up, and only then does the factor start being required. */
934
+ confirm: async (actor, code) => {
935
+ if (!capabilities.mfa) return NOT_OFFERED;
936
+ if (!actor) return refuse(401, "Not authenticated", "missing");
937
+ const mfa = await adapters.loadMfa?.(actor.id);
938
+ if (!mfa) return refuse(400, "Start the enrolment first");
939
+ if (mfa.confirmedAt) return refuse(409, "A second factor is already set up");
940
+ const step = totpStep(mfa.secret, code);
941
+ if (step === void 0) {
942
+ record({
943
+ type: "mfa.failed",
944
+ userId: actor.id
945
+ });
946
+ return refuse(401, "Invalid code");
947
+ }
948
+ const plain = generateRecoveryCodes();
949
+ await adapters.saveMfa?.(actor.id, {
950
+ ...mfa,
951
+ confirmedAt: Math.floor(Date.now() / 1e3),
952
+ recoveryCodes: plain.map(digestRecoveryCode),
953
+ lastUsedStep: step
954
+ });
955
+ record({
956
+ type: "mfa.enabled",
957
+ userId: actor.id
958
+ });
959
+ return {
960
+ ok: true,
961
+ body: {
962
+ success: true,
963
+ recoveryCodes: plain
964
+ }
965
+ };
966
+ },
967
+ /** Removing a factor is a security downgrade, so it asks for the password the way deleting an account does. */
968
+ disable: async (actor, password) => {
969
+ if (!capabilities.mfa || !adapters.deleteMfa) return NOT_OFFERED;
970
+ if (!actor) return refuse(401, "Not authenticated", "missing");
971
+ const account = await adapters.findById?.(actor.id);
972
+ if (account?.passwordHash) {
973
+ if (!password || !await verifyPassword(password, account.passwordHash)) return refuse(401, "Invalid credentials");
974
+ }
975
+ await adapters.deleteMfa(actor.id);
976
+ record({
977
+ type: "mfa.disabled",
978
+ userId: actor.id
979
+ });
980
+ return {
981
+ ok: true,
982
+ body: { success: true }
983
+ };
984
+ }
985
+ }
986
+ });
987
+ // src/core/auth/api/profile.ts
988
+ /** What a signed-in person does to their own account: the profile, the address, the password, the sessions. */
989
+ var profileFlows = ({ adapters, verifyPassword, hashPassword, generateToken, record, mintLink, linkExpired, deliver, throttleSucceeded, throttled, rejectPassword, capabilities }) => ({
990
+ /**
991
+ * Change what an account says about itself.
992
+ *
993
+ * Both fields are sign-in identifiers, so both are checked for collision first — a store that only has a unique
994
+ * index reports the clash as a driver error five hundred lines away.
995
+ */
996
+ updateProfile: async (actor, fields) => {
997
+ if (!capabilities.profile || !adapters.updateAccount) return NOT_OFFERED;
998
+ if (!actor) return refuse(401, "Not authenticated", "missing");
999
+ const username = asString(fields.username);
1000
+ const email = asString(fields.email);
1001
+ if (!username && !email) return refuse(400, "Nothing to change");
1002
+ if (username && username !== actor.username) {
1003
+ const taken = await adapters.findByUsername?.(username);
1004
+ if (taken && taken.id !== actor.id) return refuse(409, "That username is taken");
1005
+ }
1006
+ if (email && email !== actor.email) {
1007
+ const taken = await adapters.findByEmail?.(email);
1008
+ if (taken && taken.id !== actor.id) return refuse(409, "That email is taken");
1009
+ }
1010
+ const changingEmail = Boolean(email) && email !== actor.email;
1011
+ /**
1012
+ * A new address is PARKED, not applied: the account keeps the one it has until the new one answers a
1013
+ * confirmation. That is what makes a typo survivable — `n@exmaple.com` costs a resend, not the account.
1014
+ *
1015
+ * The alternative, applying it and taking `verified` away, was tried and reverted: `verified` in this server
1016
+ * gates ACCESS (`createAuthorizer` refuses to present an unverified account as an actor at all), so it locked
1017
+ * people out of the account they were sitting in. And the attack it guarded against needs a live session,
1018
+ * from which the same person could simply change the password.
1019
+ *
1020
+ * A deployment that supplies nowhere to park it changes the address on the spot, as it always did.
1021
+ */
1022
+ const parking = changingEmail && capabilities.emailChange;
1023
+ const account = await adapters.updateAccount(actor.id, {
1024
+ ...username ? { username } : {},
1025
+ ...email && !parking ? { email } : {}
1026
+ });
1027
+ if (parking && adapters.setPendingEmail) {
1028
+ const confirmationToken = mintLink(generateToken(), LIFETIME.confirmLink);
1029
+ await adapters.setPendingEmail(actor.id, email, confirmationToken);
1030
+ await deliver({
1031
+ to: email,
1032
+ template: "email-change",
1033
+ data: {
1034
+ username: account.username,
1035
+ email,
1036
+ confirmationToken
1037
+ }
1038
+ });
1039
+ return {
1040
+ ok: true,
1041
+ body: {
1042
+ success: true,
1043
+ details: profileOf(account),
1044
+ pendingEmail: email,
1045
+ message: "A confirmation was sent to the new address. It takes effect once confirmed."
1046
+ }
1047
+ };
1048
+ }
1049
+ if (changingEmail && capabilities.emailVerification && adapters.setValidationToken) {
1050
+ const validationToken = mintLink(generateToken(), LIFETIME.confirmLink);
1051
+ await adapters.setValidationToken(actor.id, validationToken);
1052
+ await deliver({
1053
+ to: account.email,
1054
+ template: "validation",
1055
+ data: {
1056
+ username: account.username,
1057
+ validationToken
1058
+ }
1059
+ });
1060
+ return {
1061
+ ok: true,
1062
+ body: {
1063
+ success: true,
1064
+ details: profileOf(account),
1065
+ message: "A confirmation was sent to the new address"
1066
+ }
1067
+ };
1068
+ }
1069
+ return {
1070
+ ok: true,
1071
+ body: {
1072
+ success: true,
1073
+ details: profileOf(account)
1074
+ }
1075
+ };
1076
+ },
1077
+ /**
1078
+ * Takes the parked address, having proved somebody reads it.
1079
+ *
1080
+ * Public, and it has to be: the link is opened from a mail client, in whatever browser that happens to be, with
1081
+ * no session. The token is the whole credential — which is why it is single-use and why confirming also marks
1082
+ * the account verified: an address that answered a link is an address that was proven.
1083
+ */
1084
+ confirmEmailChange: async (token) => {
1085
+ if (!capabilities.emailChange || !adapters.findByPendingEmail || !adapters.clearPendingEmail) return NOT_OFFERED;
1086
+ const confirmation = asString(token);
1087
+ const pending = linkExpired(confirmation) ? void 0 : await adapters.findByPendingEmail(confirmation);
1088
+ if (!pending) return refuse(400, "Invalid or expired token");
1089
+ const taken = await adapters.findByEmail?.(pending.email);
1090
+ if (taken && taken.id !== pending.account.id) {
1091
+ await adapters.clearPendingEmail(pending.account.id);
1092
+ return refuse(409, "That email is taken");
1093
+ }
1094
+ const account = await adapters.updateAccount?.(pending.account.id, { email: pending.email });
1095
+ await adapters.clearPendingEmail(pending.account.id);
1096
+ if (adapters.setVerified) await adapters.setVerified(pending.account.id, true);
1097
+ record({
1098
+ type: "email.changed",
1099
+ userId: pending.account.id,
1100
+ detail: { email: pending.email }
1101
+ });
1102
+ const confirmed = {
1103
+ ...account ?? pending.account,
1104
+ email: pending.email
1105
+ };
1106
+ return {
1107
+ ok: true,
1108
+ body: {
1109
+ success: true,
1110
+ details: profileOf(adapters.setVerified ? {
1111
+ ...confirmed,
1112
+ verified: true
1113
+ } : confirmed)
1114
+ }
1115
+ };
1116
+ },
1117
+ /**
1118
+ * Change a password, having proved you know the current one.
1119
+ *
1120
+ * Then **every other session ends**. Changing a password is what somebody does when they think a credential
1121
+ * escaped, and one that leaves the other sessions signed in has not done the thing they asked for. The session
1122
+ * making the change survives, or the act of securing the account would sign them out of it.
1123
+ */
1124
+ changePassword: async (actor, currentPassword, newPassword) => {
1125
+ if (!capabilities.passwordChange || !adapters.findById) return NOT_OFFERED;
1126
+ if (!actor) return refuse(401, "Not authenticated", "missing");
1127
+ if (!currentPassword || !newPassword) return refuse(400, "The current and the new password are required");
1128
+ const weak = await rejectPassword(newPassword, {
1129
+ username: actor.username,
1130
+ email: actor.email
1131
+ });
1132
+ if (weak) return weak;
1133
+ const limited = await throttled({
1134
+ action: "changePassword",
1135
+ key: String(actor.id)
1136
+ });
1137
+ if (limited) return limited;
1138
+ const account = await adapters.findById(actor.id);
1139
+ if (!account?.passwordHash || !await verifyPassword(currentPassword, account.passwordHash)) return refuse(401, "Invalid credentials");
1140
+ await adapters.setPassword?.(actor.id, await hashPassword(newPassword));
1141
+ await adapters.revokeOtherSessions?.(actor.id, actor.token);
1142
+ throttleSucceeded({
1143
+ action: "changePassword",
1144
+ key: String(actor.id)
1145
+ });
1146
+ record({
1147
+ type: "password.changed",
1148
+ userId: actor.id
1149
+ });
1150
+ return {
1151
+ ok: true,
1152
+ body: {
1153
+ success: true,
1154
+ message: "Password changed. Other sessions were signed out."
1155
+ }
1156
+ };
1157
+ },
1158
+ /**
1159
+ * Close the account.
1160
+ *
1161
+ * Confirmed with the password when there is one — this is irreversible, and a borrowed session should not be
1162
+ * able to do it. An account with no password (one that signs in through a provider) cannot be asked, so the
1163
+ * session alone has to be enough.
1164
+ */
1165
+ deleteSelf: async (actor, password) => {
1166
+ if (!capabilities.accountDeletion || !adapters.deleteAccount) return NOT_OFFERED;
1167
+ if (!actor) return refuse(401, "Not authenticated", "missing");
1168
+ const account = await adapters.findById?.(actor.id);
1169
+ if (account?.passwordHash) {
1170
+ if (!password || !await verifyPassword(password, account.passwordHash)) return refuse(401, "Invalid credentials");
1171
+ }
1172
+ const blockers = await adapters.deletionBlockers?.(actor.id) ?? [];
1173
+ if (blockers.length > 0) return {
1174
+ ok: false,
1175
+ status: 409,
1176
+ body: {
1177
+ error: "This account still owns things that would be lost with it",
1178
+ blockers
1179
+ }
1180
+ };
1181
+ await adapters.deleteAccount(actor.id);
1182
+ record({
1183
+ type: "account.deleted",
1184
+ userId: actor.id
1185
+ });
1186
+ return {
1187
+ ok: true,
1188
+ body: {
1189
+ success: true,
1190
+ message: "Account deleted"
1191
+ },
1192
+ endSession: true
1193
+ };
1194
+ },
1195
+ /** The devices this account is signed in on, with the one asking marked. */
1196
+ listSessions: async (actor) => {
1197
+ if (!capabilities.sessionList || !adapters.listSessions) return NOT_OFFERED;
1198
+ if (!actor) return refuse(401, "Not authenticated", "missing");
1199
+ return {
1200
+ ok: true,
1201
+ body: { sessions: await adapters.listSessions(actor.id, actor.token) }
1202
+ };
1203
+ },
1204
+ /** End one of them. Scoped to the caller's own account, or a session id would be an IDOR. */
1205
+ revokeSession: async (actor, sessionId) => {
1206
+ if (!adapters.revokeSession) return NOT_OFFERED;
1207
+ if (!actor) return refuse(401, "Not authenticated", "missing");
1208
+ if (!Number.isInteger(sessionId)) return refuse(400, "A session id is required");
1209
+ return await adapters.revokeSession(actor.id, sessionId) ? {
1210
+ ok: true,
1211
+ body: { success: true }
1212
+ } : refuse(404, "No such session");
1213
+ },
1214
+ /** "Sign out everywhere else" — the thing to do from a device you still hold after losing one you do not. */
1215
+ revokeOtherSessions: async (actor) => {
1216
+ if (!adapters.revokeOtherSessions) return NOT_OFFERED;
1217
+ if (!actor) return refuse(401, "Not authenticated", "missing");
1218
+ return {
1219
+ ok: true,
1220
+ body: {
1221
+ success: true,
1222
+ revoked: await adapters.revokeOtherSessions(actor.id, actor.token)
1223
+ }
1224
+ };
1225
+ }
1226
+ });
1227
+ // src/core/auth/api/session.ts
1228
+ /** Signing in and out: the session, a password or a provider's token, the second factor, refreshing and revoking. */
1229
+ var sessionFlows = ({ tokens, adapters, verifyPassword, csrf, record, digestRecoveryCode, throttleSucceeded, throttled, capabilities, issue, grantBody, exchangeAccount }) => ({
1230
+ capabilities,
1231
+ /** What a client reads to know which of the flows below actually exist here. */
1232
+ describe: () => ({
1233
+ ok: true,
1234
+ body: { features: capabilities }
1235
+ }),
1236
+ /**
1237
+ * Who the caller is, and until when. Reaching a resolved actor at all is the answer to "is the session alive" —
1238
+ * the guard refuses with a `reason` when it could not, so a client learns whether to renew or to drop to
1239
+ * signed-out from the refusal itself. It costs no query: the actor was resolved before routing.
1240
+ */
1241
+ session: (actor) => {
1242
+ if (!actor) return refuse(401, "Not authenticated", "missing");
1243
+ const now = Math.floor(Date.now() / 1e3);
1244
+ return {
1245
+ ok: true,
1246
+ body: {
1247
+ success: true,
1248
+ details: {
1249
+ id: actor.id,
1250
+ username: actor.username,
1251
+ email: actor.email,
1252
+ verified: actor.verified,
1253
+ roles: actor.roles,
1254
+ permissions: actor.permissions,
1255
+ ...actor.impersonatedBy === void 0 ? {} : { impersonatedBy: actor.impersonatedBy }
1256
+ },
1257
+ access_token: actor.token,
1258
+ expire_in: Math.max(0, actor.expiresAt - now),
1259
+ expire_at: actor.expiresAt
1260
+ }
1261
+ };
1262
+ },
1263
+ login: async (credentials, carrier) => {
1264
+ if (!capabilities.passwordLogin) return NOT_OFFERED;
1265
+ const username = asString(credentials.username);
1266
+ const password = asText(credentials.password);
1267
+ if (!username || !password) return refuse(400, "A username and a password are required");
1268
+ const limited = await throttled({
1269
+ action: "login",
1270
+ key: username,
1271
+ carrier
1272
+ });
1273
+ if (limited) return limited;
1274
+ /**
1275
+ * The username, or the email — in that order.
1276
+ *
1277
+ * Every sign-in screen worth using offers both, because the one thing a person reliably remembers about an
1278
+ * account is the address it was created with. Username first so an account whose name happens to be somebody
1279
+ * else's address cannot shadow the owner of that address; the email lookup only runs when the first misses,
1280
+ * so this costs a second query on a failed sign-in and nothing on a successful one.
1281
+ *
1282
+ * `findByEmail` is optional like everything else here: a deployment that supplies no email store keeps exactly
1283
+ * the behaviour it had.
1284
+ */
1285
+ const account = await adapters.findByUsername?.(username) ?? (username.includes("@") ? await adapters.findByEmail?.(username) : void 0);
1286
+ if (!account) return refuse(401, "Invalid credentials");
1287
+ if (!account.passwordHash || !await verifyPassword(password, account.passwordHash)) {
1288
+ record({
1289
+ type: "login.failed",
1290
+ userId: account.id,
1291
+ carrier,
1292
+ detail: { username }
1293
+ });
1294
+ return refuse(401, "Invalid credentials");
1295
+ }
1296
+ /**
1297
+ * Whether this account may hold a session — asked AFTER the password, and that order is the point.
1298
+ *
1299
+ * Anything said about an account before its password is checked is said to anybody who types an address. The
1300
+ * other way round, "that address has not been confirmed" once cost nothing to establish: two attempts with a
1301
+ * made-up password told a stranger which of a list of addresses have accounts here and which do not. It is
1302
+ * only a refusal somebody has earned the right to understand once they have proved the account is theirs.
1303
+ */
1304
+ if (!account.active) {
1305
+ const reason = deniedReason(account);
1306
+ return refuse(401, authFailureMessage[reason], reason);
1307
+ }
1308
+ const ssoOnly = await adapters.passwordSignInRefused?.(account);
1309
+ if (ssoOnly) {
1310
+ throttleSucceeded({
1311
+ action: "login",
1312
+ key: username,
1313
+ carrier
1314
+ });
1315
+ record({
1316
+ type: "login.failed",
1317
+ userId: account.id,
1318
+ carrier,
1319
+ detail: {
1320
+ username,
1321
+ reason: "sso-required"
1322
+ }
1323
+ });
1324
+ return refuse(401, ssoOnly, "sso-required");
1325
+ }
1326
+ if ((capabilities.mfa ? await adapters.loadMfa?.(account.id) : void 0)?.confirmedAt) {
1327
+ throttleSucceeded({
1328
+ action: "login",
1329
+ key: username,
1330
+ carrier
1331
+ });
1332
+ record({
1333
+ type: "login.mfa-required",
1334
+ userId: account.id,
1335
+ carrier
1336
+ });
1337
+ return {
1338
+ ok: true,
1339
+ body: {
1340
+ success: false,
1341
+ mfaRequired: true,
1342
+ mfaToken: tokens.generateMfaChallenge(account.id)
1343
+ }
1344
+ };
1345
+ }
1346
+ const session = await issue(account.id, { client: clientOf(carrier) });
1347
+ throttleSucceeded({
1348
+ action: "login",
1349
+ key: username,
1350
+ carrier
1351
+ });
1352
+ record({
1353
+ type: "login",
1354
+ userId: account.id,
1355
+ carrier
1356
+ });
1357
+ return {
1358
+ ok: true,
1359
+ body: await grantBody(account, session),
1360
+ session
1361
+ };
1362
+ },
1363
+ /**
1364
+ * The second half of a sign-in that owed a factor.
1365
+ *
1366
+ * Takes a TOTP code or a recovery code. A recovery code is SPENT — removed from the stored list — because one
1367
+ * that survives being used is a password with extra steps.
1368
+ */
1369
+ completeMfa: async (mfaToken, code, carrier) => {
1370
+ if (!capabilities.mfa) return NOT_OFFERED;
1371
+ const verified = tokens.verifyMfaChallenge(mfaToken);
1372
+ if (!verified.ok) return refuse(401, authFailureMessage[verified.reason], verified.reason);
1373
+ const userId = Number(verified.payload.sub);
1374
+ const limited = await throttled({
1375
+ action: "mfa",
1376
+ key: String(userId),
1377
+ carrier
1378
+ });
1379
+ if (limited) return limited;
1380
+ const account = await adapters.findById?.(userId);
1381
+ const mfa = await adapters.loadMfa?.(userId);
1382
+ if (!account || !mfa?.confirmedAt) return refuse(401, "Invalid credentials");
1383
+ if (!account.active) {
1384
+ const reason = deniedReason(account);
1385
+ return refuse(401, authFailureMessage[reason], reason);
1386
+ }
1387
+ const stored = mfa.recoveryCodes ?? [];
1388
+ const supplied = digestRecoveryCode(code);
1389
+ const usedRecovery = stored.includes(supplied);
1390
+ const step = usedRecovery ? void 0 : totpStep(mfa.secret, code);
1391
+ const replayed = step !== void 0 && mfa.lastUsedStep !== void 0 && step <= mfa.lastUsedStep;
1392
+ if (!usedRecovery && (step === void 0 || replayed)) {
1393
+ record({
1394
+ type: "mfa.failed",
1395
+ userId,
1396
+ carrier,
1397
+ ...replayed ? { detail: { replayed: true } } : {}
1398
+ });
1399
+ return refuse(401, "Invalid code");
1400
+ }
1401
+ await adapters.saveMfa?.(userId, usedRecovery ? {
1402
+ ...mfa,
1403
+ recoveryCodes: stored.filter((entry) => entry !== supplied)
1404
+ } : {
1405
+ ...mfa,
1406
+ lastUsedStep: step
1407
+ });
1408
+ const session = await issue(userId, { client: clientOf(carrier) });
1409
+ throttleSucceeded({
1410
+ action: "mfa",
1411
+ key: String(userId),
1412
+ carrier
1413
+ });
1414
+ record({
1415
+ type: "login",
1416
+ userId,
1417
+ carrier,
1418
+ detail: { recoveryCode: usedRecovery }
1419
+ });
1420
+ return {
1421
+ ok: true,
1422
+ body: {
1423
+ ...await grantBody(account, session),
1424
+ ...usedRecovery ? { recoveryCodeUsed: true } : {}
1425
+ },
1426
+ session
1427
+ };
1428
+ },
1429
+ refresh: async (refreshToken, carrier) => {
1430
+ if (!capabilities.refresh) return NOT_OFFERED;
1431
+ if (!refreshToken) return refuse(400, "Refresh token is required");
1432
+ /**
1433
+ * Every refusal below ends the session in this browser, because each of them means the credential it just
1434
+ * presented can never work again: not one this deployment signed, no such row, past its deadline, or an
1435
+ * account that may not hold one. What is being cleared is not authority — the row is already gone — it is the
1436
+ * browser's reason to keep asking.
1437
+ *
1438
+ * The token carries its own deadline, so the store is asked only whether it still holds the row — the switch
1439
+ * that revokes it. A `refreshExpiresAt` it reports overrides that deadline, and a store that keeps none needs
1440
+ * to report nothing.
1441
+ */
1442
+ const lapsed = {
1443
+ ...refuse(401, "Invalid or expired refresh token", "expired"),
1444
+ endSession: true
1445
+ };
1446
+ const verified = tokens.verifyRefreshToken(refreshToken);
1447
+ if (!verified.ok) return lapsed;
1448
+ const account = await adapters.findByRefreshToken?.(refreshToken);
1449
+ const deadline = account?.refreshExpiresAt ?? verified.payload.exp;
1450
+ if (!account || account.id !== userIdOf(verified.payload) || deadline === void 0 || deadline < now()) return lapsed;
1451
+ if (!account.active) {
1452
+ const reason = deniedReason(account);
1453
+ return {
1454
+ ...refuse(401, authFailureMessage[reason], reason),
1455
+ endSession: true
1456
+ };
1457
+ }
1458
+ const cap = tokens.lifetimes.session;
1459
+ if (cap > 0 && account.sessionStartedAt !== void 0 && account.sessionStartedAt + cap < now()) {
1460
+ await adapters.clearSession({ refreshToken });
1461
+ return {
1462
+ ...refuse(401, "This session has reached its maximum lifetime", "expired"),
1463
+ endSession: true
1464
+ };
1465
+ }
1466
+ const session = await issue(account.id, {
1467
+ replaces: { refreshToken },
1468
+ client: clientOf(carrier)
1469
+ });
1470
+ return {
1471
+ ok: true,
1472
+ body: await grantBody(account, session),
1473
+ session
1474
+ };
1475
+ },
1476
+ /** Reachable with an expired access token on purpose, or a live refresh token could never be revoked. */
1477
+ logout: async (credentials) => {
1478
+ if (credentials.accessToken || credentials.refreshToken) await adapters.clearSession(credentials);
1479
+ return {
1480
+ ok: true,
1481
+ body: { message: "Logged out successfully" },
1482
+ endSession: true
1483
+ };
1484
+ },
1485
+ /**
1486
+ * Ends this account's session everywhere, for the case where one leaked. Unlike logout it is authenticated and
1487
+ * works by account id, so it can be used from a device that still has a good session while the stolen copy is
1488
+ * somewhere else entirely.
1489
+ */
1490
+ /**
1491
+ * Signing out everywhere: every session of the account (`scope` `all`, or none said) — or, `site`, those signed in on
1492
+ * `host`, the one asking: a space's visitor ending theirs there and nowhere else.
1493
+ */
1494
+ revokeSessions: async (userId, scope, host) => {
1495
+ if (!userId) return refuse(401, "Not authenticated", "missing");
1496
+ if (scope !== void 0 && scope !== "" && scope !== "site" && scope !== "all") return refuse(400, "A scope is \"site\" — this site's sessions — or \"all\", every one of the account");
1497
+ await adapters.clearSession(scope === "site" ? {
1498
+ userId,
1499
+ host: host.toLowerCase()
1500
+ } : { userId });
1501
+ return {
1502
+ ok: true,
1503
+ body: { message: "All sessions revoked" },
1504
+ endSession: true
1505
+ };
1506
+ },
1507
+ exchange: async (provider, token, carrier) => {
1508
+ const result = await exchangeAccount(provider, token, carrier);
1509
+ if (!result.ok) return result.offered ? refuse(result.status, result.error, result.reason) : NOT_OFFERED;
1510
+ const { account, access, session } = result;
1511
+ return {
1512
+ ok: true,
1513
+ body: await grantBody(account, session, access),
1514
+ session
1515
+ };
1516
+ },
1517
+ /**
1518
+ * A CSRF token for whoever is asking, bound to their session when they have one. Answered as a body AND as the
1519
+ * cookie the binding writes, so a page can take whichever it finds easier to read.
1520
+ */
1521
+ issueCsrf: (sessionToken) => {
1522
+ if (!csrf) return NOT_OFFERED;
1523
+ const token = csrf.issue(sessionToken);
1524
+ return {
1525
+ ok: true,
1526
+ body: {
1527
+ token,
1528
+ headerName: csrf.headerName
1529
+ },
1530
+ csrf: token
1531
+ };
1532
+ }
1533
+ });
1534
+ // src/core/auth/api/index.ts
1535
+ /**
1536
+ * The HTTP surface of authentication, as functions rather than routes.
1537
+ *
1538
+ * Nothing here knows about Express, or about this server's own pipeline: a handler is given what the request
1539
+ * carried and answers what should be sent, including whether the session cookies should be written or cleared. The
1540
+ * binding does the rest, which is what lets the same login live behind an API endpoint and behind a rendered page's
1541
+ * form without either owning it.
1542
+ */
1543
+ var createAuthApi = ({ tokens, identity, adapters, config = {} }) => {
1544
+ const ctx = createAuthContext({
1545
+ tokens,
1546
+ identity,
1547
+ adapters,
1548
+ config
1549
+ });
1550
+ return {
1551
+ ...sessionFlows(ctx),
1552
+ ...factorsFlows(ctx),
1553
+ ...accountsFlows(ctx),
1554
+ ...profileFlows(ctx),
1555
+ ...adminFlows(ctx),
1556
+ /**
1557
+ * The same exchange, answering in accounts rather than in HTTP.
1558
+ *
1559
+ * A page server needs who came back and the session they got; the flow above needs a body and a status. They
1560
+ * are the same act, and the translation between them has one correct answer — so it is made once, here, rather
1561
+ * than by every deployment that wires an external identity provider into a rendered page.
1562
+ */
1563
+ exchangeAccount: ctx.exchangeAccount,
1564
+ /** Exposed so a deployment can mint a session outside the flows above — a rendered page's login form. */
1565
+ issueSession: ctx.issue,
1566
+ resolveActor: identity.resolveActor
1567
+ };
1568
+ };
1569
+ // src/core/auth/createAuth.ts
1570
+ /**
1571
+ * The refusals of a session credential that no renewal brings back: the store has no such session, the account may not
1572
+ * sign in, the token was never one this deployment would accept. `expired` is not one — the refresh may still renew it.
1573
+ */
1574
+ var SESSION_OVER = /* @__PURE__ */ new Set([
1575
+ "revoked",
1576
+ "outdated",
1577
+ "inactive",
1578
+ "malformed",
1579
+ "issuer-not-allowed"
1580
+ ]);
1581
+ /**
1582
+ * The whole auth cycle, wired.
1583
+ *
1584
+ * ```ts
1585
+ * const auth = createAuth({
1586
+ * tokens: { keys, issuer: 'https://acme.test', audience: ['https://api.acme.test'] },
1587
+ * secret,
1588
+ * cookie: { name: 'acme_session' },
1589
+ * adapters: myStore
1590
+ * });
1591
+ *
1592
+ * // guard every request
1593
+ * const result = await auth.authorize(req, req.url);
1594
+ * // serve the flows
1595
+ * for (const { method, path, handler } of auth.routes) { … }
1596
+ * ```
1597
+ */
1598
+ var createAuth = (config) => {
1599
+ if (config.secret.length < 32) throw new Error(`createAuth's \`secret\` is ${String(config.secret.length)} characters; it signs the CSRF token, so it takes at least 32 — \`openssl rand -base64 48\` makes one`);
1600
+ const tokens = createTokens(config.tokens);
1601
+ const cookieName = (hostname) => sessionCookieParams({ hostname }, config.cookie).name;
1602
+ const cookies = createSessionCookies(config.cookie);
1603
+ const identity = createIdentity({
1604
+ tokens,
1605
+ carriers: createCarriers(cookieName),
1606
+ presentedOrigin,
1607
+ adapters: config.adapters,
1608
+ config: config.identity
1609
+ });
1610
+ /**
1611
+ * The hosts this deployment already declared are the ones its own pages are served from, which is exactly the
1612
+ * question the sign-in check asks. Taken from there rather than asked for again: two lists that have to agree
1613
+ * are two lists that will not.
1614
+ */
1615
+ const csrf = config.csrf === false ? void 0 : createCsrf({
1616
+ secret: config.secret,
1617
+ cookie: config.cookie,
1618
+ allowedOrigins: config.identity?.platformOrigins
1619
+ });
1620
+ const api = createAuthApi({
1621
+ tokens,
1622
+ identity,
1623
+ adapters: config.adapters,
1624
+ config: {
1625
+ ...config.api,
1626
+ ...csrf ? { csrf } : {}
1627
+ }
1628
+ });
1629
+ const basePath = config.basePath ?? "/auth";
1630
+ const pageAuth = {
1631
+ userProvider: "basic",
1632
+ loginUrl: `${basePath}/login`,
1633
+ userUrl: `${basePath}/session`,
1634
+ logoutUrl: `${basePath}/logout`,
1635
+ revokeUrl: `${basePath}/sessions/revoke`,
1636
+ ...api.capabilities.refresh ? { refreshUrl: `${basePath}/refresh` } : {},
1637
+ ...api.capabilities.mfa ? { mfaUrl: `${basePath}/mfa/complete` } : {}
1638
+ };
1639
+ const policy = {
1640
+ rules: [...config.rules ?? [], ...authPolicyRules(basePath)],
1641
+ fallback: config.fallback ?? "actor"
1642
+ };
1643
+ /**
1644
+ * Identity as a page server sees it, kept apart from the sign-in flows so a deployment can take one without the
1645
+ * other — see the `ssrIdentityAdapters` note below.
1646
+ *
1647
+ * `exchangeCredential` is omitted entirely when no exchange adapter was supplied. A key that is present but inert
1648
+ * would make the page server advertise `sessionExchangeUrl` for a flow that answers 404 — and a browser-side
1649
+ * identity provider handing its credential to an endpoint that is not there fails as a hydration mismatch, which
1650
+ * is nowhere near where the mistake was made.
1651
+ */
1652
+ const ssrIdentityAdapters = {
1653
+ getUser: async (req, res) => {
1654
+ const resolved = await identity.resolveActor(req);
1655
+ if (!resolved.ok) {
1656
+ const fromCookie = !req.headers.authorization?.startsWith("Bearer ") && !!cookies.resolveSessionToken(req);
1657
+ if (res && fromCookie && SESSION_OVER.has(resolved.reason)) cookies.clear(req, res);
1658
+ return;
1659
+ }
1660
+ const { id, username, email, verified, permissions, roles, token, expiresAt } = resolved.actor;
1661
+ return {
1662
+ id,
1663
+ username,
1664
+ email,
1665
+ verified,
1666
+ permissions,
1667
+ roles,
1668
+ token,
1669
+ expiresAt
1670
+ };
1671
+ },
1672
+ ...api.capabilities.exchange ? { exchangeCredential: async (provider, token, req) => {
1673
+ const result = await api.exchangeAccount(provider, token, req);
1674
+ if (!result.ok) return {
1675
+ ok: false,
1676
+ error: result.error,
1677
+ status: result.status,
1678
+ reason: result.reason
1679
+ };
1680
+ const { account, access, session } = result;
1681
+ return {
1682
+ ok: true,
1683
+ session,
1684
+ user: {
1685
+ token: session.token,
1686
+ expiresAt: session.expiresAt,
1687
+ id: account.id,
1688
+ username: account.username,
1689
+ email: account.email,
1690
+ verified: account.verified,
1691
+ roles: access.roles,
1692
+ permissions: access.permissions
1693
+ }
1694
+ };
1695
+ } } : {}
1696
+ };
1697
+ return {
1698
+ tokens,
1699
+ identity,
1700
+ api,
1701
+ cookies,
1702
+ policy,
1703
+ /** Where these flows were mounted, so whatever serves them reads it here rather than defaulting to `/auth`
1704
+ * on its own — a host that guessed would serve the routes somewhere the policy above does not guard. */
1705
+ basePath,
1706
+ /**
1707
+ * What a page server tells the pages it renders about these flows (`server.auth`), so a space signs in here with
1708
+ * nothing to declare: the HTTP+JSON shape the SDK's `basic` provider speaks, at this `basePath`, with renewal and
1709
+ * the second factor only where this deployment offers them.
1710
+ */
1711
+ pageAuth,
1712
+ /** The naming this was built with, so a page server takes it from here instead of being told a second time. */
1713
+ cookieConfig: config.cookie,
1714
+ /**
1715
+ * The sites this deployment's own pages are served from (`identity.platformOrigins`): a page server counts their
1716
+ * writes as its own (`crossSiteWrites`), as the sign-in check here does.
1717
+ */
1718
+ platformOrigins: config.identity?.platformOrigins ?? [],
1719
+ /**
1720
+ * Cross-site request forgery: issuing tokens, writing the readable cookie, and the check. `undefined` when the
1721
+ * deployment turned it off. The `/auth` routes below already enforce it.
1722
+ */
1723
+ csrf,
1724
+ /** The `/auth` flows as descriptors, ready for whatever serves HTTP here. */
1725
+ routes: authRoutes({
1726
+ api,
1727
+ cookies,
1728
+ csrf
1729
+ }),
1730
+ /** May this request proceed, and as whom. */
1731
+ authorize: createAuthorizer(identity, policy),
1732
+ /**
1733
+ * Does what a flow's answer says about the cookies — the session, and the CSRF token that has to be re-issued
1734
+ * alongside it. Bound to this deployment's `csrf`, so a caller cannot forget to pass it.
1735
+ */
1736
+ applySession: (req, res, outcome) => applySessionOutcome(req, res, outcome, cookies, csrf),
1737
+ /** Both halves of a space permission: a global capability, and membership of that space. */
1738
+ can: identity.can,
1739
+ /**
1740
+ * One account's public face — its id and username, nothing else: by username or id, an active account only. What a
1741
+ * self-hosted space's functions read of another person (`ctx.visitors.get`): every account of its own is its
1742
+ * visitor. The platform says its own (`lookups.getVisitor`): only the people of the space being asked.
1743
+ */
1744
+ publicAccount: async (who) => {
1745
+ const { findById, findByUsername } = config.adapters;
1746
+ const account = typeof who === "number" ? await findById?.(who) : await findByUsername?.(who);
1747
+ return account?.active ? {
1748
+ id: account.id,
1749
+ username: account.username
1750
+ } : void 0;
1751
+ },
1752
+ /**
1753
+ * WHO a page request carries, and nothing about signing anyone in or out.
1754
+ *
1755
+ * This is the set a deployment wants when its renderer and its sign-in live in different processes — a page
1756
+ * server that must know who is looking at it, while the `/auth` flows are served by an API tier next to it.
1757
+ * That shape had no name, so a deployment expressed it by reaching into `ssrAdapters` and lifting two keys out
1758
+ * by hand: correct until a third identity adapter appears, which it then silently does not get. A worker takes the
1759
+ * same object (`createWorker({ identity })`, `RequestIdentity`), so the two answer who a request is alike.
1760
+ *
1761
+ * `exchangeCredential` belongs here rather than with the flows: turning a credential a browser already holds
1762
+ * into a session is a question about identity, and it is the one the page server itself answers.
1763
+ */
1764
+ ssrIdentityAdapters,
1765
+ /**
1766
+ * Every adapter a page server asks for, already answered. Spread these into `createServer`'s `adapters`
1767
+ * and a rendered page knows who is looking at it, `POST /auth/login` signs them in, `POST /auth/logout` signs
1768
+ * them out, and the cookies are written and cleared by the same code that reads them back. A renderer that
1769
+ * serves no login of its own wants {@link ssrIdentityAdapters} instead.
1770
+ *
1771
+ * They exist because the page server speaks in sessions and users while the flows above answer in outcomes,
1772
+ * and translating between the two is a step with exactly one right answer — which makes it the server's, not
1773
+ * something for every deployment to rediscover.
1774
+ */
1775
+ ssrAdapters: {
1776
+ authenticate: async (credentials) => {
1777
+ const outcome = await api.login(credentials);
1778
+ return outcome.ok ? outcome.session : void 0;
1779
+ },
1780
+ endSession: async (req) => {
1781
+ await api.logout({ accessToken: cookies.resolveSessionToken(req) });
1782
+ },
1783
+ endSessions: async (req, scope) => {
1784
+ const resolved = await identity.resolveActor(req);
1785
+ if (!resolved.ok) return false;
1786
+ await api.revokeSessions(resolved.actor.id, scope, req.hostname);
1787
+ return true;
1788
+ },
1789
+ ...ssrIdentityAdapters
1790
+ }
1791
+ };
1792
+ };
1793
+ // src/core/auth/oauth/types.ts
1794
+ /** Carried all the way to the browser as `?error=<reason>` on the redirect target, so a front-end can tell "you
1795
+ * cancelled" from "that account is disabled" without parsing prose. */
1796
+ var OAuthFailure = class extends Error {
1797
+ reason;
1798
+ /** A short code of the deployment's, carried as `&detail=<code>` beside the reason, for a screen to say more by. */
1799
+ detail;
1800
+ constructor(reason, message, detail) {
1801
+ super(message);
1802
+ this.name = "OAuthFailure";
1803
+ this.reason = reason;
1804
+ if (detail !== void 0) this.detail = detail;
1805
+ }
1806
+ };
1807
+ // src/core/auth/oauth/client.ts
1808
+ function buildAuthorizationUrl(provider, state, challenge) {
1809
+ const params = new URLSearchParams({
1810
+ client_id: provider.config.clientId,
1811
+ redirect_uri: provider.config.redirectUri,
1812
+ response_type: "code",
1813
+ scope: provider.scope,
1814
+ state: state.nonce,
1815
+ ...provider.authorizationParams
1816
+ });
1817
+ if (provider.usePkce && challenge) {
1818
+ params.set("code_challenge", challenge);
1819
+ params.set("code_challenge_method", "S256");
1820
+ }
1821
+ if (provider.sendsNonce) params.set("nonce", state.idNonce);
1822
+ return `${provider.authorizationUrl}?${params.toString()}`;
1823
+ }
1824
+ async function exchangeCodeForToken(provider, code, state) {
1825
+ const body = new URLSearchParams({
1826
+ code,
1827
+ client_id: provider.config.clientId,
1828
+ client_secret: provider.config.clientSecret,
1829
+ redirect_uri: provider.config.redirectUri,
1830
+ grant_type: "authorization_code"
1831
+ });
1832
+ if (provider.usePkce) body.set("code_verifier", state.verifier);
1833
+ const response = await fetch(provider.tokenUrl, {
1834
+ method: "POST",
1835
+ headers: {
1836
+ "Content-Type": "application/x-www-form-urlencoded",
1837
+ Accept: "application/json",
1838
+ ...provider.tokenHeaders
1839
+ },
1840
+ body
1841
+ });
1842
+ if (!response.ok) throw new OAuthFailure("exchange_failed", `${provider.id} rejected the authorization code (${response.status})`);
1843
+ const payload = await response.json();
1844
+ if (!payload.access_token) throw new OAuthFailure("exchange_failed", `${provider.id} returned no access token (${payload.error ?? "unknown"})`);
1845
+ return {
1846
+ accessToken: payload.access_token,
1847
+ ...payload.id_token ? { idToken: payload.id_token } : {},
1848
+ nonce: state.idNonce
1849
+ };
1850
+ }
1851
+ async function requestProfileJson(url, headers) {
1852
+ const response = await fetch(url, { headers });
1853
+ if (!response.ok) throw new OAuthFailure("profile_failed", `Failed to read the profile from ${url} (${response.status})`);
1854
+ return await response.json();
1855
+ }
1856
+ // src/core/auth/oauth/providers/github.ts
1857
+ var USER_URL = "https://api.github.com/user";
1858
+ var EMAILS_URL = "https://api.github.com/user/emails";
1859
+ var apiHeaders = (accessToken) => ({
1860
+ Authorization: `Bearer ${accessToken}`,
1861
+ Accept: "application/vnd.github+json",
1862
+ "X-GitHub-Api-Version": "2022-11-28",
1863
+ "User-Agent": "plitzi-sdk-server"
1864
+ });
1865
+ var createGitHubProvider = (config) => ({
1866
+ id: "github",
1867
+ label: "GitHub",
1868
+ config,
1869
+ authorizationUrl: "https://github.com/login/oauth/authorize",
1870
+ tokenUrl: "https://github.com/login/oauth/access_token",
1871
+ scope: "read:user user:email",
1872
+ usePkce: false,
1873
+ async verifyAudience(accessToken) {
1874
+ const credentials = Buffer.from(`${config.clientId}:${config.clientSecret}`).toString("base64");
1875
+ return (await fetch(`https://api.github.com/applications/${config.clientId}/token`, {
1876
+ method: "POST",
1877
+ headers: {
1878
+ Authorization: `Basic ${credentials}`,
1879
+ Accept: "application/vnd.github+json",
1880
+ "X-GitHub-Api-Version": "2022-11-28",
1881
+ "User-Agent": "plitzi-sdk-server",
1882
+ "Content-Type": "application/json"
1883
+ },
1884
+ body: JSON.stringify({ access_token: accessToken })
1885
+ })).ok;
1886
+ },
1887
+ async fetchProfile({ accessToken }) {
1888
+ const headers = apiHeaders(accessToken);
1889
+ const user = await requestProfileJson(USER_URL, headers);
1890
+ const emails = await requestProfileJson(EMAILS_URL, headers);
1891
+ const verified = emails.find((entry) => entry.primary && entry.verified) ?? emails.find((entry) => entry.verified);
1892
+ const address = verified ?? emails.find((entry) => entry.primary) ?? emails.at(0);
1893
+ return {
1894
+ id: String(user.id),
1895
+ email: address?.email ?? user.email ?? "",
1896
+ emailVerified: verified !== void 0,
1897
+ username: user.name ?? user.login
1898
+ };
1899
+ }
1900
+ });
1901
+ // src/core/auth/oauth/providers/google.ts
1902
+ var USERINFO_URL = "https://openidconnect.googleapis.com/v1/userinfo";
1903
+ var TOKENINFO_URL = "https://oauth2.googleapis.com/tokeninfo";
1904
+ var createGoogleProvider = (config) => ({
1905
+ id: "google",
1906
+ label: "Google",
1907
+ config,
1908
+ authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth",
1909
+ tokenUrl: "https://oauth2.googleapis.com/token",
1910
+ scope: "openid email profile",
1911
+ usePkce: true,
1912
+ authorizationParams: { prompt: "select_account" },
1913
+ async verifyAudience(accessToken) {
1914
+ const response = await fetch(`${TOKENINFO_URL}?access_token=${encodeURIComponent(accessToken)}`);
1915
+ if (!response.ok) return false;
1916
+ return (await response.json()).aud === config.clientId;
1917
+ },
1918
+ async fetchProfile({ accessToken }) {
1919
+ const profile = await requestProfileJson(USERINFO_URL, { Authorization: `Bearer ${accessToken}` });
1920
+ return {
1921
+ id: profile.sub,
1922
+ email: profile.email ?? "",
1923
+ emailVerified: profile.email_verified === true,
1924
+ username: profile.name ?? ""
1925
+ };
1926
+ }
1927
+ });
1928
+ // src/core/auth/oauth/state.ts
1929
+ var base64Url = (value) => value.toString("base64url");
1930
+ var createCodeVerifier = () => base64Url(randomBytes(32));
1931
+ var codeChallenge = (verifier) => base64Url(createHash("sha256").update(verifier).digest());
1932
+ var equals = (a, b) => {
1933
+ const left = Buffer.from(a);
1934
+ const right = Buffer.from(b);
1935
+ return left.length === right.length && timingSafeEqual(left, right);
1936
+ };
1937
+ /**
1938
+ * Starts a flow. The whole state is signed into a value the browser holds, and the provider only ever sees the
1939
+ * nonce: that is what binds the callback to the browser that began it, and it keeps the PKCE verifier out of every
1940
+ * URL the authorization code travels through.
1941
+ *
1942
+ * The value is returned rather than written — whoever calls this owns the cookie.
1943
+ */
1944
+ var startFlow = (provider, redirect, secret, ttlSeconds) => {
1945
+ const state = {
1946
+ provider,
1947
+ nonce: base64Url(randomBytes(16)),
1948
+ idNonce: base64Url(randomBytes(16)),
1949
+ verifier: createCodeVerifier(),
1950
+ redirect
1951
+ };
1952
+ return {
1953
+ state,
1954
+ cookie: jwt.sign(state, secret, {
1955
+ algorithm: "HS256",
1956
+ expiresIn: ttlSeconds
1957
+ })
1958
+ };
1959
+ };
1960
+ /**
1961
+ * Reads back the flow started above. Null unless the value is intact, unexpired, for this same provider, and its
1962
+ * nonce matches the one the provider echoed back — the four things that together make a callback trustworthy.
1963
+ */
1964
+ var consumeFlow = (cookie, provider, nonce, secret) => {
1965
+ if (!cookie || typeof nonce !== "string" || nonce === "") return null;
1966
+ let claims;
1967
+ try {
1968
+ claims = jwt.verify(cookie, secret, { algorithms: ["HS256"] });
1969
+ } catch {
1970
+ return null;
1971
+ }
1972
+ if (claims.provider !== provider || !equals(claims.nonce, nonce)) return null;
1973
+ return {
1974
+ provider: claims.provider,
1975
+ nonce: claims.nonce,
1976
+ idNonce: claims.idNonce,
1977
+ verifier: claims.verifier,
1978
+ redirect: claims.redirect
1979
+ };
1980
+ };
1981
+ // src/core/auth/redirects.ts
1982
+ var originOf = (value) => {
1983
+ try {
1984
+ return new URL(value).origin;
1985
+ } catch {
1986
+ return null;
1987
+ }
1988
+ };
1989
+ /**
1990
+ * Vet a caller-supplied landing page against a deployment's policy: the target itself when it is ours, the default when
1991
+ * it is not.
1992
+ *
1993
+ * Every flow that takes a `?redirect=` somebody else wrote and later navigates to it — social sign-in, the shared
1994
+ * sign-in screen's way out, a confirmation mail that has to bring somebody back — asks THIS, built once from the same
1995
+ * configuration. Two implementations of "is this target ours" is how one of them ends up accepting `//evil.com`.
1996
+ *
1997
+ * A relative path stays on the host that navigates to it and is allowed; a protocol-relative (`//evil.com`) or
1998
+ * backslash (`/\evil.com`) one reads as a path and navigates off-site, and is not.
1999
+ */
2000
+ var createRedirectPolicy = (config) => {
2001
+ const fallback = config.defaultRedirect;
2002
+ const allowed = [fallback, ...config.allowedRedirects ?? []].map(originOf).filter((value) => value !== null);
2003
+ return (target) => {
2004
+ if (typeof target !== "string" || target === "") return fallback;
2005
+ if (target.startsWith("/") && !target.startsWith("//") && !target.startsWith("/\\")) return target;
2006
+ const origin = originOf(target);
2007
+ return origin && allowed.includes(origin) ? target : fallback;
2008
+ };
2009
+ };
2010
+ // src/core/auth/oauth/providers/oidc.ts
2011
+ /** How long a discovery document and a key set are trusted before they are read again. */
2012
+ var CACHE_MS = 36e5;
2013
+ /** The least time between two reads of a key set forced by a key it did not have: a stranger's token cannot flood it. */
2014
+ var KEY_REFRESH_MS = 6e4;
2015
+ var FETCH_TIMEOUT_MS = 1e4;
2016
+ /** Asymmetric signatures only: an HMAC would be keyed by the client secret, and `none` by nothing. */
2017
+ var SIGNING_ALGORITHMS = [
2018
+ "RS256",
2019
+ "RS384",
2020
+ "RS512",
2021
+ "PS256",
2022
+ "PS384",
2023
+ "PS512",
2024
+ "ES256",
2025
+ "ES384",
2026
+ "ES512"
2027
+ ];
2028
+ var isSigningAlgorithm = (value) => typeof value === "string" && SIGNING_ALGORITHMS.includes(value);
2029
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2030
+ /**
2031
+ * An endpoint an issuer may name: HTTPS, or plain HTTP on this machine's loopback — a development identity provider,
2032
+ * never one across a network, where the code and the tokens would travel readable.
2033
+ */
2034
+ var isSafeEndpoint = (value) => {
2035
+ if (typeof value !== "string") return false;
2036
+ try {
2037
+ const url = new URL(value);
2038
+ return url.protocol === "https:" || url.protocol === "http:" && [
2039
+ "localhost",
2040
+ "127.0.0.1",
2041
+ "[::1]"
2042
+ ].includes(url.hostname);
2043
+ } catch {
2044
+ return false;
2045
+ }
2046
+ };
2047
+ var fetchJson = async (url, what) => {
2048
+ let response;
2049
+ try {
2050
+ response = await fetch(url, {
2051
+ headers: { Accept: "application/json" },
2052
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
2053
+ });
2054
+ } catch (error) {
2055
+ throw new Error(`Could not reach ${what} at ${url}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
2056
+ }
2057
+ if (!response.ok) throw new Error(`${what} at ${url} answered ${String(response.status)}`);
2058
+ try {
2059
+ return await response.json();
2060
+ } catch {
2061
+ throw new Error(`${what} at ${url} is not JSON`);
2062
+ }
2063
+ };
2064
+ var discoveries = /* @__PURE__ */ new Map();
2065
+ /**
2066
+ * Reads an issuer's discovery document, and checks it is the issuer's: its `issuer` is the one asked for, exactly
2067
+ * (OpenID Connect Discovery §4.3 — a document that names another issuer is somebody else's), and every endpoint it
2068
+ * names is one a sign-in may use. Kept an hour. Throws, saying what is wrong, for whoever set the issuer to read.
2069
+ */
2070
+ var discoverOidc = async (issuer) => {
2071
+ const cached = discoveries.get(issuer);
2072
+ if (cached && Date.now() - cached.at < CACHE_MS) return cached.discovery;
2073
+ if (!isSafeEndpoint(issuer)) throw new Error(`The issuer must be an https:// address (${issuer})`);
2074
+ const url = `${issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`;
2075
+ const document = await fetchJson(url, "The discovery document");
2076
+ if (!isRecord(document)) throw new Error(`The discovery document at ${url} is not an object`);
2077
+ if (document.issuer !== issuer) throw new Error(`The discovery document at ${url} is for "${String(document.issuer)}", not "${issuer}": use the issuer it names`);
2078
+ const missing = [
2079
+ "authorization_endpoint",
2080
+ "token_endpoint",
2081
+ "jwks_uri"
2082
+ ].filter((key) => !isSafeEndpoint(document[key]));
2083
+ if (missing.length > 0) throw new Error(`The discovery document at ${url} has no https:// ${missing.join(", ")}`);
2084
+ const discovery = {
2085
+ issuer,
2086
+ authorizationEndpoint: String(document.authorization_endpoint),
2087
+ tokenEndpoint: String(document.token_endpoint),
2088
+ jwksUri: String(document.jwks_uri)
2089
+ };
2090
+ discoveries.set(issuer, {
2091
+ at: Date.now(),
2092
+ discovery
2093
+ });
2094
+ return discovery;
2095
+ };
2096
+ var keySets = /* @__PURE__ */ new Map();
2097
+ /** The public parts of a published key that a signature is checked with, read field by field from what was fetched. */
2098
+ var publicKeyOf = (key) => {
2099
+ const jwk = {};
2100
+ for (const field of [
2101
+ "kty",
2102
+ "crv",
2103
+ "n",
2104
+ "e",
2105
+ "x",
2106
+ "y",
2107
+ "alg"
2108
+ ]) {
2109
+ const value = key[field];
2110
+ if (typeof value === "string") jwk[field] = value;
2111
+ }
2112
+ return jwk;
2113
+ };
2114
+ var readKeys = async (jwksUri) => {
2115
+ const document = await fetchJson(jwksUri, "The key set");
2116
+ const keys = /* @__PURE__ */ new Map();
2117
+ const listed = isRecord(document) && Array.isArray(document.keys) ? document.keys : [];
2118
+ for (const key of listed) if (isRecord(key) && typeof key.kid === "string" && key.use !== "enc") keys.set(key.kid, publicKeyOf(key));
2119
+ keySets.set(jwksUri, {
2120
+ at: Date.now(),
2121
+ keys
2122
+ });
2123
+ return keys;
2124
+ };
2125
+ /** The issuer's key named `kid`: from the kept set, or the set read again when it is old or lacks it (a rotation). */
2126
+ var signingKey = async (jwksUri, kid) => {
2127
+ const kept = keySets.get(jwksUri);
2128
+ let key = kept && Date.now() - kept.at < CACHE_MS ? kept.keys.get(kid) : void 0;
2129
+ if (!key && (!kept || Date.now() - kept.at >= KEY_REFRESH_MS)) key = (await readKeys(jwksUri)).get(kid);
2130
+ if (!key) throw new OAuthFailure("profile_failed", `The ID token is signed with a key the issuer does not publish (${kid})`);
2131
+ return createPublicKey({
2132
+ key,
2133
+ format: "jwk"
2134
+ });
2135
+ };
2136
+ var claimString = (claims, name) => {
2137
+ const value = claims[name];
2138
+ return typeof value === "string" ? value : "";
2139
+ };
2140
+ /**
2141
+ * Who an ID token says signed in, once it is proved to be this sign-in's: signed by the issuer's published key with an
2142
+ * asymmetric algorithm, from this issuer, for this client — and, when it names several audiences, authorized for this
2143
+ * one (`azp`) — unexpired, and carrying this flow's nonce, so a token from another sign-in cannot be replayed into it.
2144
+ */
2145
+ var verifyIdToken = async (idToken, discovery, clientId, nonce) => {
2146
+ const decoded = jwt.decode(idToken, { complete: true });
2147
+ if (!decoded || typeof decoded.header.kid !== "string" || !isSigningAlgorithm(decoded.header.alg)) throw new OAuthFailure("profile_failed", "The ID token is not signed with a published asymmetric key");
2148
+ const key = await signingKey(discovery.jwksUri, decoded.header.kid);
2149
+ let claims;
2150
+ try {
2151
+ claims = jwt.verify(idToken, key, {
2152
+ algorithms: [decoded.header.alg],
2153
+ issuer: discovery.issuer,
2154
+ audience: clientId,
2155
+ clockTolerance: 60
2156
+ });
2157
+ } catch (error) {
2158
+ throw new OAuthFailure("profile_failed", `The ID token did not verify: ${error instanceof Error ? error.message : String(error)}`);
2159
+ }
2160
+ if (!isRecord(claims)) throw new OAuthFailure("profile_failed", "The ID token carries no claims");
2161
+ if (Array.isArray(claims.aud) && claims.aud.length > 1 && claims.azp !== clientId) throw new OAuthFailure("profile_failed", "The ID token was issued for several clients and authorized for another");
2162
+ if (claims.nonce !== nonce) throw new OAuthFailure("profile_failed", "The ID token is not this sign-in’s (its nonce differs)");
2163
+ return claims;
2164
+ };
2165
+ /**
2166
+ * A provider for any OpenID Connect issuer — a company's own identity provider (Okta, Microsoft Entra ID, Google
2167
+ * Workspace, Keycloak…) — from its issuer, its client and its secret. The authorization-code grant with PKCE, as every
2168
+ * provider here; what makes it OpenID Connect is the profile: read from the ID token the token endpoint returns,
2169
+ * verified against the issuer's published keys, never from an endpoint the access token would reach.
2170
+ *
2171
+ * `email_verified` is reported as the issuer states it — many corporate issuers omit it for addresses they own. What a
2172
+ * deployment trusts an issuer to vouch for is the deployment's to decide in `linkAccount`.
2173
+ */
2174
+ var createOidcProvider = async (options) => {
2175
+ const discovery = await discoverOidc(options.issuer);
2176
+ return {
2177
+ id: options.id,
2178
+ label: options.label,
2179
+ config: {
2180
+ clientId: options.clientId,
2181
+ clientSecret: options.clientSecret,
2182
+ redirectUri: options.redirectUri
2183
+ },
2184
+ authorizationUrl: discovery.authorizationEndpoint,
2185
+ tokenUrl: discovery.tokenEndpoint,
2186
+ scope: "openid email profile",
2187
+ usePkce: true,
2188
+ sendsNonce: true,
2189
+ async fetchProfile({ idToken, nonce }) {
2190
+ if (!idToken) throw new OAuthFailure("profile_failed", `${options.label} returned no ID token: is it an OpenID Connect issuer?`);
2191
+ const claims = await verifyIdToken(idToken, discovery, options.clientId, nonce);
2192
+ const verified = claims.email_verified;
2193
+ return {
2194
+ id: claimString(claims, "sub"),
2195
+ email: claimString(claims, "email").toLowerCase(),
2196
+ emailVerified: verified === true || verified === "true",
2197
+ username: claimString(claims, "name") || claimString(claims, "preferred_username")
2198
+ };
2199
+ }
2200
+ };
2201
+ };
2202
+ // src/core/auth/oauth/index.ts
2203
+ /** The adapters shipped with the server. A deployment adds its credentials and gets the provider; nothing else. */
2204
+ var BUILT_IN_PROVIDERS = {
2205
+ google: createGoogleProvider,
2206
+ github: createGitHubProvider
2207
+ };
2208
+ /**
2209
+ * Social sign-in, as two functions and a list.
2210
+ *
2211
+ * The authorization-code grant is the same everywhere and none of it is anyone's product: the CSRF nonce, PKCE, the
2212
+ * vetted redirect, the token exchange, reading the profile. What differs per deployment is which providers it has
2213
+ * credentials for and what it does with the person who comes back — so those are the adapters, and everything else
2214
+ * is here, once.
2215
+ *
2216
+ * Neither function touches a response: `start` hands back where to send the browser and the state to store, and
2217
+ * `complete` hands back where to send it next and who came back. The binding mints the session and writes cookies.
2218
+ */
2219
+ var createSocialAuth = ({ config, adapters, providers: configured, customProviders = {} }) => {
2220
+ const stateTtl = config.stateTtl ?? 600;
2221
+ const registry = /* @__PURE__ */ new Map();
2222
+ for (const [id, credentials] of Object.entries(configured)) {
2223
+ const factory = customProviders[id] ?? BUILT_IN_PROVIDERS[id];
2224
+ if (!factory || !credentials?.clientId || !credentials.clientSecret) continue;
2225
+ registry.set(id, factory({
2226
+ clientId: credentials.clientId,
2227
+ clientSecret: credentials.clientSecret,
2228
+ redirectUri: credentials.redirectUri || `${config.callbackBaseUrl ?? ""}/auth/${id}/callback`
2229
+ }));
2230
+ }
2231
+ const sanitizeRedirect = createRedirectPolicy({
2232
+ defaultRedirect: config.defaultRedirect,
2233
+ allowedRedirects: config.allowedRedirects
2234
+ });
2235
+ const withError = (target, reason, detail) => `${target}${target.includes("?") ? "&" : "?"}error=${encodeURIComponent(reason)}${detail ? `&detail=${encodeURIComponent(detail)}` : ""}`;
2236
+ const loginBase = config.loginBaseUrl ?? config.callbackBaseUrl ?? "";
2237
+ const listed = (provider) => ({
2238
+ id: provider.id,
2239
+ label: provider.label,
2240
+ url: `${loginBase}/auth/${provider.id}/login`
2241
+ });
2242
+ /** A configured provider, or one the deployment resolves at run time; never a run-time one under a configured id. */
2243
+ const lookup = async (id) => registry.get(id) ?? await adapters.resolveProvider?.(id, `${config.callbackBaseUrl ?? ""}/auth/${id}/callback`);
2244
+ return {
2245
+ /**
2246
+ * Vet a caller-supplied landing page against this deployment's policy, for the flows that are not this one.
2247
+ *
2248
+ * Exposed because social sign-in is no longer the only thing that takes a `?redirect=` and then navigates to
2249
+ * it: the shared sign-in screen does too, and the check has to be the SAME check. Two implementations of "is
2250
+ * this target ours" is how one of them ends up accepting `//evil.com`.
2251
+ */
2252
+ sanitizeRedirect,
2253
+ /** Registered providers, so a front-end renders exactly the buttons that will work. */
2254
+ list: () => [...registry.values()].map(listed),
2255
+ /** A configured provider. Run-time ones are not here: they sign in through the flow, never a token handed over. */
2256
+ get: (id) => registry.get(id),
2257
+ /**
2258
+ * The single sign-on that signs in `email`, if its domain has one — or why there is none. Asked by a sign-in
2259
+ * screen before it sends anybody anywhere, so an address with no sign-on of its own hears so instead of a 404.
2260
+ */
2261
+ sso: async (email) => {
2262
+ const address = email.trim().toLowerCase();
2263
+ if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(address)) return { error: "An email address is required" };
2264
+ const id = await adapters.providerForEmail?.(address);
2265
+ const provider = id ? await lookup(id) : void 0;
2266
+ return provider ? { provider: listed(provider) } : { error: `${address.split("@")[1] ?? address} has no single sign-on here: sign in another way` };
2267
+ },
2268
+ start: async (providerId, redirect) => {
2269
+ const provider = await lookup(providerId);
2270
+ if (!provider) return;
2271
+ const { state, cookie } = startFlow(provider.id, sanitizeRedirect(redirect), config.secret, stateTtl);
2272
+ return {
2273
+ redirectTo: buildAuthorizationUrl(provider, state, codeChallenge(state.verifier)),
2274
+ stateCookie: cookie,
2275
+ ttl: stateTtl
2276
+ };
2277
+ },
2278
+ complete: async (providerId, params) => {
2279
+ const provider = await lookup(providerId);
2280
+ if (!provider) return {
2281
+ ok: false,
2282
+ error: "Unknown provider",
2283
+ reason: "invalid_state"
2284
+ };
2285
+ const flow = consumeFlow(params.stateCookie, provider.id, params.state, config.secret);
2286
+ if (!flow) return {
2287
+ ok: false,
2288
+ error: "Invalid or expired authorization state",
2289
+ reason: "invalid_state"
2290
+ };
2291
+ if (params.error || !params.code) {
2292
+ const reason = params.error ? "access_denied" : "invalid_state";
2293
+ return {
2294
+ ok: false,
2295
+ redirectTo: withError(flow.redirect, reason),
2296
+ error: params.error ?? "",
2297
+ reason
2298
+ };
2299
+ }
2300
+ try {
2301
+ const tokens = await exchangeCodeForToken(provider, params.code, flow);
2302
+ const profile = await provider.fetchProfile(tokens);
2303
+ const account = await adapters.linkAccount(provider.id, profile);
2304
+ return {
2305
+ ok: true,
2306
+ redirectTo: flow.redirect,
2307
+ account
2308
+ };
2309
+ } catch (error) {
2310
+ const reason = error instanceof OAuthFailure ? error.reason : "server_error";
2311
+ const detail = error instanceof OAuthFailure ? error.detail : void 0;
2312
+ return {
2313
+ ok: false,
2314
+ redirectTo: withError(flow.redirect, reason, detail),
2315
+ error: error instanceof Error ? error.message : "server_error",
2316
+ reason,
2317
+ ...detail === void 0 ? {} : { detail }
2318
+ };
2319
+ }
2320
+ }
2321
+ };
2322
+ };
2323
+ export { BUILT_IN_PROVIDERS, OAuthFailure, applySessionOutcome, authPolicyRules, authRoutes, createAuth, createAuthApi, createMemoryRateLimit, createOidcProvider, createRedirectPolicy, createSocialAuth, discoverOidc, generateRecoveryCodes, generateTotpSecret, isDocumentNavigation, normalizeRecoveryCode, randomCode, renewForNavigation, requestProfileJson, totpCode, totpStep, totpUri, verifyTotp };