@softistx/alxia-react-router 0.0.0-stage → 0.83.1

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 (609) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2085 -2
  3. package/dist/api-keys/api-keys.d.ts +93 -0
  4. package/dist/api-keys/api-keys.d.ts.map +1 -0
  5. package/dist/api-keys/index.d.ts +9 -0
  6. package/dist/api-keys/index.d.ts.map +1 -0
  7. package/dist/api-keys/index.js +66 -0
  8. package/dist/api-keys/index.js.map +10 -0
  9. package/dist/assets.d.ts +14 -0
  10. package/dist/assets.d.ts.map +1 -0
  11. package/dist/chunks/index-0786n4qe.js +25 -0
  12. package/dist/chunks/index-0786n4qe.js.map +10 -0
  13. package/dist/chunks/index-1nw5yeek.js +169 -0
  14. package/dist/chunks/index-1nw5yeek.js.map +11 -0
  15. package/dist/chunks/index-59vhfj6n.js +10 -0
  16. package/dist/chunks/index-59vhfj6n.js.map +10 -0
  17. package/dist/chunks/index-5gqcpyyg.js +34 -0
  18. package/dist/chunks/index-5gqcpyyg.js.map +10 -0
  19. package/dist/chunks/index-6jf7zpxz.js +119 -0
  20. package/dist/chunks/index-6jf7zpxz.js.map +11 -0
  21. package/dist/chunks/index-8as4j8m3.js +340 -0
  22. package/dist/chunks/index-8as4j8m3.js.map +16 -0
  23. package/dist/chunks/index-9xv2a8et.js +108 -0
  24. package/dist/chunks/index-9xv2a8et.js.map +11 -0
  25. package/dist/chunks/index-ajtvyq35.js +16 -0
  26. package/dist/chunks/index-ajtvyq35.js.map +10 -0
  27. package/dist/chunks/index-c55hxgr5.js +124 -0
  28. package/dist/chunks/index-c55hxgr5.js.map +14 -0
  29. package/dist/chunks/index-d42p3mdp.js +19 -0
  30. package/dist/chunks/index-d42p3mdp.js.map +10 -0
  31. package/dist/chunks/index-gac44rs5.js +42 -0
  32. package/dist/chunks/index-gac44rs5.js.map +11 -0
  33. package/dist/chunks/index-j4ktpcke.js +62 -0
  34. package/dist/chunks/index-j4ktpcke.js.map +10 -0
  35. package/dist/chunks/index-mscfme4r.js +12 -0
  36. package/dist/chunks/index-mscfme4r.js.map +10 -0
  37. package/dist/chunks/index-pghmb2dm.js +30 -0
  38. package/dist/chunks/index-pghmb2dm.js.map +10 -0
  39. package/dist/chunks/index-rfr02vg4.js +40 -0
  40. package/dist/chunks/index-rfr02vg4.js.map +10 -0
  41. package/dist/chunks/index-sfhshxqz.js +31 -0
  42. package/dist/chunks/index-sfhshxqz.js.map +10 -0
  43. package/dist/chunks/index-skwypsjz.js +357 -0
  44. package/dist/chunks/index-skwypsjz.js.map +12 -0
  45. package/dist/chunks/index-sxh06ged.js +118 -0
  46. package/dist/chunks/index-sxh06ged.js.map +11 -0
  47. package/dist/chunks/index-t2ph23wk.js +96 -0
  48. package/dist/chunks/index-t2ph23wk.js.map +13 -0
  49. package/dist/chunks/index-thyabr5n.js +19 -0
  50. package/dist/chunks/index-thyabr5n.js.map +10 -0
  51. package/dist/chunks/index-tx36swjx.js +134 -0
  52. package/dist/chunks/index-tx36swjx.js.map +11 -0
  53. package/dist/chunks/index-v2z5k640.js +54 -0
  54. package/dist/chunks/index-v2z5k640.js.map +11 -0
  55. package/dist/chunks/index-vr82typq.js +23 -0
  56. package/dist/chunks/index-vr82typq.js.map +11 -0
  57. package/dist/chunks/index-whj6h5eg.js +9 -0
  58. package/dist/chunks/index-whj6h5eg.js.map +10 -0
  59. package/dist/chunks/index-wyypkfdv.js +130 -0
  60. package/dist/chunks/index-wyypkfdv.js.map +13 -0
  61. package/dist/chunks/index-xd5aqy3g.js +90 -0
  62. package/dist/chunks/index-xd5aqy3g.js.map +10 -0
  63. package/dist/chunks/index-zdbqzcjp.js +97 -0
  64. package/dist/chunks/index-zdbqzcjp.js.map +12 -0
  65. package/dist/chunks/index-zyg8amjc.js +23 -0
  66. package/dist/chunks/index-zyg8amjc.js.map +10 -0
  67. package/dist/cli/index.d.ts +3 -0
  68. package/dist/cli/index.d.ts.map +1 -0
  69. package/dist/cli/index.js +215 -0
  70. package/dist/cli/index.js.map +13 -0
  71. package/dist/cli/main.d.ts +13 -0
  72. package/dist/cli/main.d.ts.map +1 -0
  73. package/dist/cli/reveal.d.ts +18 -0
  74. package/dist/cli/reveal.d.ts.map +1 -0
  75. package/dist/cli/template.d.ts +8 -0
  76. package/dist/cli/template.d.ts.map +1 -0
  77. package/dist/context.d.ts +104 -0
  78. package/dist/context.d.ts.map +1 -0
  79. package/dist/document/index.d.ts +11 -0
  80. package/dist/document/index.d.ts.map +1 -0
  81. package/dist/document/index.js +19 -0
  82. package/dist/document/index.js.map +9 -0
  83. package/dist/document/inline-script.d.ts +27 -0
  84. package/dist/document/inline-script.d.ts.map +1 -0
  85. package/dist/document/language-store.d.ts +8 -0
  86. package/dist/document/language-store.d.ts.map +1 -0
  87. package/dist/document/nonce.d.ts +34 -0
  88. package/dist/document/nonce.d.ts.map +1 -0
  89. package/dist/document/page-language.d.ts +39 -0
  90. package/dist/document/page-language.d.ts.map +1 -0
  91. package/dist/document/text-direction.d.ts +10 -0
  92. package/dist/document/text-direction.d.ts.map +1 -0
  93. package/dist/entry/abort.d.ts +21 -0
  94. package/dist/entry/abort.d.ts.map +1 -0
  95. package/dist/entry/create-entry.d.ts +41 -0
  96. package/dist/entry/create-entry.d.ts.map +1 -0
  97. package/dist/entry/index.d.ts +8 -0
  98. package/dist/entry/index.d.ts.map +1 -0
  99. package/dist/entry/index.js +154 -0
  100. package/dist/entry/index.js.map +13 -0
  101. package/dist/entry/root-data.d.ts +27 -0
  102. package/dist/entry/root-data.d.ts.map +1 -0
  103. package/dist/entry/whole-page.d.ts +10 -0
  104. package/dist/entry/whole-page.d.ts.map +1 -0
  105. package/dist/errors/api-error.d.ts +117 -0
  106. package/dist/errors/api-error.d.ts.map +1 -0
  107. package/dist/errors/api-errors.d.ts +122 -0
  108. package/dist/errors/api-errors.d.ts.map +1 -0
  109. package/dist/errors/call-failure.d.ts +45 -0
  110. package/dist/errors/call-failure.d.ts.map +1 -0
  111. package/dist/errors/catalogue-check.d.ts +24 -0
  112. package/dist/errors/catalogue-check.d.ts.map +1 -0
  113. package/dist/errors/catalogue-read.d.ts +33 -0
  114. package/dist/errors/catalogue-read.d.ts.map +1 -0
  115. package/dist/errors/catalogue.d.ts +59 -0
  116. package/dist/errors/catalogue.d.ts.map +1 -0
  117. package/dist/errors/code-resolver.d.ts +44 -0
  118. package/dist/errors/code-resolver.d.ts.map +1 -0
  119. package/dist/errors/cross-site.d.ts +8 -0
  120. package/dist/errors/cross-site.d.ts.map +1 -0
  121. package/dist/errors/describe-refusal.d.ts +6 -0
  122. package/dist/errors/describe-refusal.d.ts.map +1 -0
  123. package/dist/errors/describe.d.ts +3 -0
  124. package/dist/errors/describe.d.ts.map +1 -0
  125. package/dist/errors/fetcher-result.d.ts +33 -0
  126. package/dist/errors/fetcher-result.d.ts.map +1 -0
  127. package/dist/errors/field-placement.d.ts +12 -0
  128. package/dist/errors/field-placement.d.ts.map +1 -0
  129. package/dist/errors/form-errors.d.ts +8 -0
  130. package/dist/errors/form-errors.d.ts.map +1 -0
  131. package/dist/errors/form-refusal.d.ts +25 -0
  132. package/dist/errors/form-refusal.d.ts.map +1 -0
  133. package/dist/errors/index.d.ts +21 -0
  134. package/dist/errors/index.d.ts.map +1 -0
  135. package/dist/errors/index.js +588 -0
  136. package/dist/errors/index.js.map +26 -0
  137. package/dist/errors/json-actions.d.ts +38 -0
  138. package/dist/errors/json-actions.d.ts.map +1 -0
  139. package/dist/errors/log.d.ts +8 -0
  140. package/dist/errors/log.d.ts.map +1 -0
  141. package/dist/errors/message-values.d.ts +11 -0
  142. package/dist/errors/message-values.d.ts.map +1 -0
  143. package/dist/errors/messages.d.ts +63 -0
  144. package/dist/errors/messages.d.ts.map +1 -0
  145. package/dist/errors/page-path.d.ts +9 -0
  146. package/dist/errors/page-path.d.ts.map +1 -0
  147. package/dist/errors/problem-error.d.ts +50 -0
  148. package/dist/errors/problem-error.d.ts.map +1 -0
  149. package/dist/errors/provider.d.ts +20 -0
  150. package/dist/errors/provider.d.ts.map +1 -0
  151. package/dist/errors/request-id.d.ts +5 -0
  152. package/dist/errors/request-id.d.ts.map +1 -0
  153. package/dist/errors/route-error.d.ts +33 -0
  154. package/dist/errors/route-error.d.ts.map +1 -0
  155. package/dist/errors/route-refusal.d.ts +20 -0
  156. package/dist/errors/route-refusal.d.ts.map +1 -0
  157. package/dist/errors/same-site.d.ts +49 -0
  158. package/dist/errors/same-site.d.ts.map +1 -0
  159. package/dist/errors/section-action.d.ts +46 -0
  160. package/dist/errors/section-action.d.ts.map +1 -0
  161. package/dist/errors/standard-schema.d.ts +34 -0
  162. package/dist/errors/standard-schema.d.ts.map +1 -0
  163. package/dist/errors/submit-form.d.ts +16 -0
  164. package/dist/errors/submit-form.d.ts.map +1 -0
  165. package/dist/errors/upstream-headers.d.ts +18 -0
  166. package/dist/errors/upstream-headers.d.ts.map +1 -0
  167. package/dist/errors/use-json-fetcher.d.ts +18 -0
  168. package/dist/errors/use-json-fetcher.d.ts.map +1 -0
  169. package/dist/fetcher/auth-refusal.d.ts +29 -0
  170. package/dist/fetcher/auth-refusal.d.ts.map +1 -0
  171. package/dist/fetcher/index.d.ts +20 -0
  172. package/dist/fetcher/index.d.ts.map +1 -0
  173. package/dist/fetcher/index.js +392 -0
  174. package/dist/fetcher/index.js.map +21 -0
  175. package/dist/fetcher/section-form.d.ts +24 -0
  176. package/dist/fetcher/section-form.d.ts.map +1 -0
  177. package/dist/fetcher/section-reload.d.ts +17 -0
  178. package/dist/fetcher/section-reload.d.ts.map +1 -0
  179. package/dist/fetcher/section-save.d.ts +29 -0
  180. package/dist/fetcher/section-save.d.ts.map +1 -0
  181. package/dist/fetcher/use-debounced-fetcher.d.ts +57 -0
  182. package/dist/fetcher/use-debounced-fetcher.d.ts.map +1 -0
  183. package/dist/fetcher/use-fetcher-answer.d.ts +16 -0
  184. package/dist/fetcher/use-fetcher-answer.d.ts.map +1 -0
  185. package/dist/fetcher/use-fetcher-done.d.ts +15 -0
  186. package/dist/fetcher/use-fetcher-done.d.ts.map +1 -0
  187. package/dist/fetcher/use-fetcher-promise.d.ts +48 -0
  188. package/dist/fetcher/use-fetcher-promise.d.ts.map +1 -0
  189. package/dist/fetcher/use-form-refusal.d.ts +20 -0
  190. package/dist/fetcher/use-form-refusal.d.ts.map +1 -0
  191. package/dist/fetcher/use-revalidate-on-focus.d.ts +20 -0
  192. package/dist/fetcher/use-revalidate-on-focus.d.ts.map +1 -0
  193. package/dist/fetcher/use-row-save.d.ts +32 -0
  194. package/dist/fetcher/use-row-save.d.ts.map +1 -0
  195. package/dist/fetcher/use-section-save.d.ts +46 -0
  196. package/dist/fetcher/use-section-save.d.ts.map +1 -0
  197. package/dist/fetcher/use-visible-interval.d.ts +24 -0
  198. package/dist/fetcher/use-visible-interval.d.ts.map +1 -0
  199. package/dist/fetcher/use-visible-revalidation.d.ts +10 -0
  200. package/dist/fetcher/use-visible-revalidation.d.ts.map +1 -0
  201. package/dist/health.d.ts +21 -0
  202. package/dist/health.d.ts.map +1 -0
  203. package/dist/help/check/check.d.ts +35 -0
  204. package/dist/help/check/check.d.ts.map +1 -0
  205. package/dist/help/check/index.d.ts +8 -0
  206. package/dist/help/check/index.d.ts.map +1 -0
  207. package/dist/help/check/index.js +17 -0
  208. package/dist/help/check/index.js.map +9 -0
  209. package/dist/help/check/routes.d.ts +22 -0
  210. package/dist/help/check/routes.d.ts.map +1 -0
  211. package/dist/help/guide.d.ts +33 -0
  212. package/dist/help/guide.d.ts.map +1 -0
  213. package/dist/help/index.d.ts +16 -0
  214. package/dist/help/index.d.ts.map +1 -0
  215. package/dist/help/index.js +192 -0
  216. package/dist/help/index.js.map +14 -0
  217. package/dist/help/load.d.ts +39 -0
  218. package/dist/help/load.d.ts.map +1 -0
  219. package/dist/help/panel.d.ts +69 -0
  220. package/dist/help/panel.d.ts.map +1 -0
  221. package/dist/help/parse-flow.d.ts +27 -0
  222. package/dist/help/parse-flow.d.ts.map +1 -0
  223. package/dist/help/react.d.ts +12 -0
  224. package/dist/help/react.d.ts.map +1 -0
  225. package/dist/help/resolve.d.ts +24 -0
  226. package/dist/help/resolve.d.ts.map +1 -0
  227. package/dist/help/types.d.ts +50 -0
  228. package/dist/help/types.d.ts.map +1 -0
  229. package/dist/help/yaml.d.ts +18 -0
  230. package/dist/help/yaml.d.ts.map +1 -0
  231. package/dist/index.d.ts +7 -0
  232. package/dist/index.d.ts.map +1 -0
  233. package/dist/index.js +197 -0
  234. package/dist/index.js.map +14 -0
  235. package/dist/link/index.d.ts +7 -0
  236. package/dist/link/index.d.ts.map +1 -0
  237. package/dist/link/index.js +16 -0
  238. package/dist/link/index.js.map +10 -0
  239. package/dist/link/router-link.d.ts +27 -0
  240. package/dist/link/router-link.d.ts.map +1 -0
  241. package/dist/lists/connection-page.d.ts +50 -0
  242. package/dist/lists/connection-page.d.ts.map +1 -0
  243. package/dist/lists/index.d.ts +13 -0
  244. package/dist/lists/index.d.ts.map +1 -0
  245. package/dist/lists/index.js +205 -0
  246. package/dist/lists/index.js.map +15 -0
  247. package/dist/lists/newest-first.d.ts +5 -0
  248. package/dist/lists/newest-first.d.ts.map +1 -0
  249. package/dist/lists/nodes-of.d.ts +21 -0
  250. package/dist/lists/nodes-of.d.ts.map +1 -0
  251. package/dist/lists/or-failed.d.ts +19 -0
  252. package/dist/lists/or-failed.d.ts.map +1 -0
  253. package/dist/lists/use-paged-rows.d.ts +40 -0
  254. package/dist/lists/use-paged-rows.d.ts.map +1 -0
  255. package/dist/lists/use-same-route-loading.d.ts +8 -0
  256. package/dist/lists/use-same-route-loading.d.ts.map +1 -0
  257. package/dist/lists/use-search-change.d.ts +20 -0
  258. package/dist/lists/use-search-change.d.ts.map +1 -0
  259. package/dist/mcp/index.d.ts +8 -0
  260. package/dist/mcp/index.d.ts.map +1 -0
  261. package/dist/mcp/index.js +105 -0
  262. package/dist/mcp/index.js.map +11 -0
  263. package/dist/mcp/mcp-relay.d.ts +58 -0
  264. package/dist/mcp/mcp-relay.d.ts.map +1 -0
  265. package/dist/mcp/relay.d.ts +38 -0
  266. package/dist/mcp/relay.d.ts.map +1 -0
  267. package/dist/media/client/error.d.ts +29 -0
  268. package/dist/media/client/error.d.ts.map +1 -0
  269. package/dist/media/client/index.d.ts +8 -0
  270. package/dist/media/client/index.d.ts.map +1 -0
  271. package/dist/media/client/index.js +133 -0
  272. package/dist/media/client/index.js.map +11 -0
  273. package/dist/media/client/upload.d.ts +32 -0
  274. package/dist/media/client/upload.d.ts.map +1 -0
  275. package/dist/media/forward.d.ts +14 -0
  276. package/dist/media/forward.d.ts.map +1 -0
  277. package/dist/media/headers.d.ts +11 -0
  278. package/dist/media/headers.d.ts.map +1 -0
  279. package/dist/media/index.d.ts +9 -0
  280. package/dist/media/index.d.ts.map +1 -0
  281. package/dist/media/index.js +396 -0
  282. package/dist/media/index.js.map +16 -0
  283. package/dist/media/options.d.ts +114 -0
  284. package/dist/media/options.d.ts.map +1 -0
  285. package/dist/media/path.d.ts +12 -0
  286. package/dist/media/path.d.ts.map +1 -0
  287. package/dist/media/read.d.ts +11 -0
  288. package/dist/media/read.d.ts.map +1 -0
  289. package/dist/media/refusal.d.ts +11 -0
  290. package/dist/media/refusal.d.ts.map +1 -0
  291. package/dist/media/respond.d.ts +8 -0
  292. package/dist/media/respond.d.ts.map +1 -0
  293. package/dist/media/write.d.ts +13 -0
  294. package/dist/media/write.d.ts.map +1 -0
  295. package/dist/navigation/index.d.ts +9 -0
  296. package/dist/navigation/index.d.ts.map +1 -0
  297. package/dist/navigation/index.js +48 -0
  298. package/dist/navigation/index.js.map +11 -0
  299. package/dist/navigation/use-focus-on-navigate.d.ts +16 -0
  300. package/dist/navigation/use-focus-on-navigate.d.ts.map +1 -0
  301. package/dist/navigation/use-route-transition.d.ts +19 -0
  302. package/dist/navigation/use-route-transition.d.ts.map +1 -0
  303. package/dist/nonce.d.ts +16 -0
  304. package/dist/nonce.d.ts.map +1 -0
  305. package/dist/oauth/answer.d.ts +33 -0
  306. package/dist/oauth/answer.d.ts.map +1 -0
  307. package/dist/oauth/binding.d.ts +43 -0
  308. package/dist/oauth/binding.d.ts.map +1 -0
  309. package/dist/oauth/consent.d.ts +134 -0
  310. package/dist/oauth/consent.d.ts.map +1 -0
  311. package/dist/oauth/grants.d.ts +88 -0
  312. package/dist/oauth/grants.d.ts.map +1 -0
  313. package/dist/oauth/index.d.ts +16 -0
  314. package/dist/oauth/index.d.ts.map +1 -0
  315. package/dist/oauth/index.js +207 -0
  316. package/dist/oauth/index.js.map +12 -0
  317. package/dist/oauth/model.d.ts +13 -0
  318. package/dist/oauth/model.d.ts.map +1 -0
  319. package/dist/oauth/react/index.d.ts +7 -0
  320. package/dist/oauth/react/index.d.ts.map +1 -0
  321. package/dist/oauth/react/index.js +99 -0
  322. package/dist/oauth/react/index.js.map +10 -0
  323. package/dist/oauth/react/use-consent.d.ts +52 -0
  324. package/dist/oauth/react/use-consent.d.ts.map +1 -0
  325. package/dist/oidc/dpop.d.ts +80 -0
  326. package/dist/oidc/dpop.d.ts.map +1 -0
  327. package/dist/oidc/errors.d.ts +16 -0
  328. package/dist/oidc/errors.d.ts.map +1 -0
  329. package/dist/oidc/flow.d.ts +59 -0
  330. package/dist/oidc/flow.d.ts.map +1 -0
  331. package/dist/oidc/index.d.ts +11 -0
  332. package/dist/oidc/index.d.ts.map +1 -0
  333. package/dist/oidc/index.js +742 -0
  334. package/dist/oidc/index.js.map +15 -0
  335. package/dist/oidc/oidc.d.ts +132 -0
  336. package/dist/oidc/oidc.d.ts.map +1 -0
  337. package/dist/oidc/revoke.d.ts +28 -0
  338. package/dist/oidc/revoke.d.ts.map +1 -0
  339. package/dist/oidc/seal.d.ts +20 -0
  340. package/dist/oidc/seal.d.ts.map +1 -0
  341. package/dist/pwa/build/build-worker.d.ts +41 -0
  342. package/dist/pwa/build/build-worker.d.ts.map +1 -0
  343. package/dist/pwa/build/index.d.ts +9 -0
  344. package/dist/pwa/build/index.d.ts.map +1 -0
  345. package/dist/pwa/build/index.js +9 -0
  346. package/dist/pwa/build/index.js.map +9 -0
  347. package/dist/pwa/build/precache.d.ts +17 -0
  348. package/dist/pwa/build/precache.d.ts.map +1 -0
  349. package/dist/pwa/index.d.ts +16 -0
  350. package/dist/pwa/index.d.ts.map +1 -0
  351. package/dist/pwa/index.js +110 -0
  352. package/dist/pwa/index.js.map +12 -0
  353. package/dist/pwa/model/caching.d.ts +46 -0
  354. package/dist/pwa/model/caching.d.ts.map +1 -0
  355. package/dist/pwa/model/clear-app-caches.d.ts +9 -0
  356. package/dist/pwa/model/clear-app-caches.d.ts.map +1 -0
  357. package/dist/pwa/model/font-precache.d.ts +15 -0
  358. package/dist/pwa/model/font-precache.d.ts.map +1 -0
  359. package/dist/pwa/model/manifest.d.ts +80 -0
  360. package/dist/pwa/model/manifest.d.ts.map +1 -0
  361. package/dist/pwa/model/precache-list.d.ts +40 -0
  362. package/dist/pwa/model/precache-list.d.ts.map +1 -0
  363. package/dist/pwa/model/registration.d.ts +39 -0
  364. package/dist/pwa/model/registration.d.ts.map +1 -0
  365. package/dist/pwa/model/start-service-worker.d.ts +24 -0
  366. package/dist/pwa/model/start-service-worker.d.ts.map +1 -0
  367. package/dist/pwa/model/storable.d.ts +8 -0
  368. package/dist/pwa/model/storable.d.ts.map +1 -0
  369. package/dist/pwa/model/theme-color.d.ts +20 -0
  370. package/dist/pwa/model/theme-color.d.ts.map +1 -0
  371. package/dist/pwa/model/update-notice.d.ts +38 -0
  372. package/dist/pwa/model/update-notice.d.ts.map +1 -0
  373. package/dist/pwa/model/worker-contract.d.ts +61 -0
  374. package/dist/pwa/model/worker-contract.d.ts.map +1 -0
  375. package/dist/pwa/react/index.d.ts +9 -0
  376. package/dist/pwa/react/index.d.ts.map +1 -0
  377. package/dist/pwa/react/index.js +75 -0
  378. package/dist/pwa/react/index.js.map +13 -0
  379. package/dist/pwa/react/use-online.d.ts +6 -0
  380. package/dist/pwa/react/use-online.d.ts.map +1 -0
  381. package/dist/pwa/react/use-service-worker.d.ts +33 -0
  382. package/dist/pwa/react/use-service-worker.d.ts.map +1 -0
  383. package/dist/pwa/react/use-update-notice.d.ts +14 -0
  384. package/dist/pwa/react/use-update-notice.d.ts.map +1 -0
  385. package/dist/pwa/server/index.d.ts +7 -0
  386. package/dist/pwa/server/index.d.ts.map +1 -0
  387. package/dist/pwa/server/index.js +18 -0
  388. package/dist/pwa/server/index.js.map +10 -0
  389. package/dist/pwa/server/no-cache.d.ts +22 -0
  390. package/dist/pwa/server/no-cache.d.ts.map +1 -0
  391. package/dist/pwa/worker/index.d.ts +9 -0
  392. package/dist/pwa/worker/index.d.ts.map +1 -0
  393. package/dist/pwa/worker/index.js +144 -0
  394. package/dist/pwa/worker/index.js.map +12 -0
  395. package/dist/pwa/worker/injected.d.ts +15 -0
  396. package/dist/pwa/worker/injected.d.ts.map +1 -0
  397. package/dist/pwa/worker/plan.d.ts +65 -0
  398. package/dist/pwa/worker/plan.d.ts.map +1 -0
  399. package/dist/pwa/worker/scope.d.ts +18 -0
  400. package/dist/pwa/worker/scope.d.ts.map +1 -0
  401. package/dist/pwa/worker/start-worker.d.ts +17 -0
  402. package/dist/pwa/worker/start-worker.d.ts.map +1 -0
  403. package/dist/react-router.d.ts +68 -0
  404. package/dist/react-router.d.ts.map +1 -0
  405. package/dist/server.d.ts +127 -0
  406. package/dist/server.d.ts.map +1 -0
  407. package/dist/session/codes.d.ts +9 -0
  408. package/dist/session/codes.d.ts.map +1 -0
  409. package/dist/session/cookies.d.ts +128 -0
  410. package/dist/session/cookies.d.ts.map +1 -0
  411. package/dist/session/flow-types.d.ts +235 -0
  412. package/dist/session/flow-types.d.ts.map +1 -0
  413. package/dist/session/guard.d.ts +10 -0
  414. package/dist/session/guard.d.ts.map +1 -0
  415. package/dist/session/index.d.ts +22 -0
  416. package/dist/session/index.d.ts.map +1 -0
  417. package/dist/session/index.js +1090 -0
  418. package/dist/session/index.js.map +27 -0
  419. package/dist/session/land.d.ts +28 -0
  420. package/dist/session/land.d.ts.map +1 -0
  421. package/dist/session/link-json.d.ts +22 -0
  422. package/dist/session/link-json.d.ts.map +1 -0
  423. package/dist/session/link-land.d.ts +20 -0
  424. package/dist/session/link-land.d.ts.map +1 -0
  425. package/dist/session/link-token.d.ts +24 -0
  426. package/dist/session/link-token.d.ts.map +1 -0
  427. package/dist/session/link-types.d.ts +142 -0
  428. package/dist/session/link-types.d.ts.map +1 -0
  429. package/dist/session/links.d.ts +14 -0
  430. package/dist/session/links.d.ts.map +1 -0
  431. package/dist/session/model/index.d.ts +8 -0
  432. package/dist/session/model/index.d.ts.map +1 -0
  433. package/dist/session/model/index.js +35 -0
  434. package/dist/session/model/index.js.map +9 -0
  435. package/dist/session/model/link-post.d.ts +35 -0
  436. package/dist/session/model/link-post.d.ts.map +1 -0
  437. package/dist/session/model/paths.d.ts +24 -0
  438. package/dist/session/model/paths.d.ts.map +1 -0
  439. package/dist/session/model/safe-next.d.ts +15 -0
  440. package/dist/session/model/safe-next.d.ts.map +1 -0
  441. package/dist/session/model/second-factor.d.ts +16 -0
  442. package/dist/session/model/second-factor.d.ts.map +1 -0
  443. package/dist/session/model/site-path.d.ts +10 -0
  444. package/dist/session/model/site-path.d.ts.map +1 -0
  445. package/dist/session/model/step-up-answers.d.ts +45 -0
  446. package/dist/session/model/step-up-answers.d.ts.map +1 -0
  447. package/dist/session/model/step-up-props.d.ts +22 -0
  448. package/dist/session/model/step-up-props.d.ts.map +1 -0
  449. package/dist/session/model/step-up.d.ts +48 -0
  450. package/dist/session/model/step-up.d.ts.map +1 -0
  451. package/dist/session/react/index.d.ts +13 -0
  452. package/dist/session/react/index.d.ts.map +1 -0
  453. package/dist/session/react/index.js +196 -0
  454. package/dist/session/react/index.js.map +14 -0
  455. package/dist/session/react/step-up/answers.d.ts +9 -0
  456. package/dist/session/react/step-up/answers.d.ts.map +1 -0
  457. package/dist/session/react/step-up/dialog-props.d.ts +27 -0
  458. package/dist/session/react/step-up/dialog-props.d.ts.map +1 -0
  459. package/dist/session/react/step-up/index.d.ts +7 -0
  460. package/dist/session/react/step-up/index.d.ts.map +1 -0
  461. package/dist/session/react/step-up/pending-runs.d.ts +21 -0
  462. package/dist/session/react/step-up/pending-runs.d.ts.map +1 -0
  463. package/dist/session/react/step-up/phase.d.ts +8 -0
  464. package/dist/session/react/step-up/phase.d.ts.map +1 -0
  465. package/dist/session/react/step-up/use-step-up-replay.d.ts +59 -0
  466. package/dist/session/react/step-up/use-step-up-replay.d.ts.map +1 -0
  467. package/dist/session/react/step-up/use-step-up-runner.d.ts +70 -0
  468. package/dist/session/react/step-up/use-step-up-runner.d.ts.map +1 -0
  469. package/dist/session/react/step-up/use-step-up.d.ts +51 -0
  470. package/dist/session/react/step-up/use-step-up.d.ts.map +1 -0
  471. package/dist/session/react/use-code-field.d.ts +37 -0
  472. package/dist/session/react/use-code-field.d.ts.map +1 -0
  473. package/dist/session/react/use-link-fragment.d.ts +22 -0
  474. package/dist/session/react/use-link-fragment.d.ts.map +1 -0
  475. package/dist/session/react/use-link-param.d.ts +26 -0
  476. package/dist/session/react/use-link-param.d.ts.map +1 -0
  477. package/dist/session/react/use-link-post.d.ts +39 -0
  478. package/dist/session/react/use-link-post.d.ts.map +1 -0
  479. package/dist/session/react/use-sign-out.d.ts +46 -0
  480. package/dist/session/react/use-sign-out.d.ts.map +1 -0
  481. package/dist/session/second-factor.d.ts +22 -0
  482. package/dist/session/second-factor.d.ts.map +1 -0
  483. package/dist/session/serialize.d.ts +42 -0
  484. package/dist/session/serialize.d.ts.map +1 -0
  485. package/dist/session/sign-in.d.ts +19 -0
  486. package/dist/session/sign-in.d.ts.map +1 -0
  487. package/dist/session/signed.d.ts +44 -0
  488. package/dist/session/signed.d.ts.map +1 -0
  489. package/dist/session/social-flow.d.ts +22 -0
  490. package/dist/session/social-flow.d.ts.map +1 -0
  491. package/dist/session/social-land.d.ts +31 -0
  492. package/dist/session/social-land.d.ts.map +1 -0
  493. package/dist/session/social-types.d.ts +136 -0
  494. package/dist/session/social-types.d.ts.map +1 -0
  495. package/dist/session/social.d.ts +32 -0
  496. package/dist/session/social.d.ts.map +1 -0
  497. package/dist/session/step-up-codes.d.ts +9 -0
  498. package/dist/session/step-up-codes.d.ts.map +1 -0
  499. package/dist/session/step-up-signed-out.d.ts +21 -0
  500. package/dist/session/step-up-signed-out.d.ts.map +1 -0
  501. package/dist/session/step-up-types.d.ts +127 -0
  502. package/dist/session/step-up-types.d.ts.map +1 -0
  503. package/dist/session/step-up.d.ts +17 -0
  504. package/dist/session/step-up.d.ts.map +1 -0
  505. package/dist/session/step.d.ts +22 -0
  506. package/dist/session/step.d.ts.map +1 -0
  507. package/dist/session/throttle.d.ts +73 -0
  508. package/dist/session/throttle.d.ts.map +1 -0
  509. package/dist/session/timed-wait.d.ts +4 -0
  510. package/dist/session/timed-wait.d.ts.map +1 -0
  511. package/dist/session/viewer.d.ts +34 -0
  512. package/dist/session/viewer.d.ts.map +1 -0
  513. package/dist/subscription/documents.d.ts +3 -0
  514. package/dist/subscription/documents.d.ts.map +1 -0
  515. package/dist/subscription/index.d.ts +7 -0
  516. package/dist/subscription/index.d.ts.map +1 -0
  517. package/dist/subscription/index.js +359 -0
  518. package/dist/subscription/index.js.map +14 -0
  519. package/dist/subscription/proxy.d.ts +54 -0
  520. package/dist/subscription/proxy.d.ts.map +1 -0
  521. package/dist/subscription/react/backoff.d.ts +8 -0
  522. package/dist/subscription/react/backoff.d.ts.map +1 -0
  523. package/dist/subscription/react/classify.d.ts +15 -0
  524. package/dist/subscription/react/classify.d.ts.map +1 -0
  525. package/dist/subscription/react/controller.d.ts +40 -0
  526. package/dist/subscription/react/controller.d.ts.map +1 -0
  527. package/dist/subscription/react/fake-timers.d.ts +8 -0
  528. package/dist/subscription/react/fake-timers.d.ts.map +1 -0
  529. package/dist/subscription/react/index.d.ts +15 -0
  530. package/dist/subscription/react/index.d.ts.map +1 -0
  531. package/dist/subscription/react/index.js +227 -0
  532. package/dist/subscription/react/index.js.map +17 -0
  533. package/dist/subscription/react/reconnect.d.ts +9 -0
  534. package/dist/subscription/react/reconnect.d.ts.map +1 -0
  535. package/dist/subscription/react/scheduler.d.ts +13 -0
  536. package/dist/subscription/react/scheduler.d.ts.map +1 -0
  537. package/dist/subscription/react/timers.d.ts +7 -0
  538. package/dist/subscription/react/timers.d.ts.map +1 -0
  539. package/dist/subscription/react/use-live-subscription.d.ts +36 -0
  540. package/dist/subscription/react/use-live-subscription.d.ts.map +1 -0
  541. package/dist/subscription/react/versions.d.ts +6 -0
  542. package/dist/subscription/react/versions.d.ts.map +1 -0
  543. package/dist/subscription/read.d.ts +17 -0
  544. package/dist/subscription/read.d.ts.map +1 -0
  545. package/dist/subscription/refusal.d.ts +11 -0
  546. package/dist/subscription/refusal.d.ts.map +1 -0
  547. package/dist/subscription/relay.d.ts +16 -0
  548. package/dist/subscription/relay.d.ts.map +1 -0
  549. package/dist/vite/bun.d.ts +21 -0
  550. package/dist/vite/bun.d.ts.map +1 -0
  551. package/dist/vite/bundle.d.ts +33 -0
  552. package/dist/vite/bundle.d.ts.map +1 -0
  553. package/dist/vite/compress.d.ts +18 -0
  554. package/dist/vite/compress.d.ts.map +1 -0
  555. package/dist/vite/config.d.ts +33 -0
  556. package/dist/vite/config.d.ts.map +1 -0
  557. package/dist/vite/dev.d.ts +28 -0
  558. package/dist/vite/dev.d.ts.map +1 -0
  559. package/dist/vite/entry.d.ts +20 -0
  560. package/dist/vite/entry.d.ts.map +1 -0
  561. package/dist/vite/hosts.d.ts +16 -0
  562. package/dist/vite/hosts.d.ts.map +1 -0
  563. package/dist/vite/index.d.ts +68 -0
  564. package/dist/vite/index.d.ts.map +1 -0
  565. package/dist/vite/index.js +635 -0
  566. package/dist/vite/index.js.map +22 -0
  567. package/dist/vite/inline.d.ts +18 -0
  568. package/dist/vite/inline.d.ts.map +1 -0
  569. package/dist/vite/node.d.ts +16 -0
  570. package/dist/vite/node.d.ts.map +1 -0
  571. package/dist/vite/preview.d.ts +8 -0
  572. package/dist/vite/preview.d.ts.map +1 -0
  573. package/dist/vite/runtime.d.ts +8 -0
  574. package/dist/vite/runtime.d.ts.map +1 -0
  575. package/dist/vite/socket.d.ts +75 -0
  576. package/dist/vite/socket.d.ts.map +1 -0
  577. package/dist/vite/worker.d.ts +16 -0
  578. package/dist/vite/worker.d.ts.map +1 -0
  579. package/dist/with-alxia.d.ts +36 -0
  580. package/dist/with-alxia.d.ts.map +1 -0
  581. package/docs/README.md +42 -0
  582. package/docs/guide/api-keys.md +216 -0
  583. package/docs/guide/beside-the-pages.md +201 -0
  584. package/docs/guide/csp-nonce.md +166 -0
  585. package/docs/guide/customising-the-server.md +324 -0
  586. package/docs/guide/deploying.md +102 -0
  587. package/docs/guide/document.md +334 -0
  588. package/docs/guide/errors.md +1147 -0
  589. package/docs/guide/fetcher.md +355 -0
  590. package/docs/guide/getting-started.md +112 -0
  591. package/docs/guide/help.md +325 -0
  592. package/docs/guide/how-it-works.md +274 -0
  593. package/docs/guide/link.md +32 -0
  594. package/docs/guide/lists.md +225 -0
  595. package/docs/guide/mcp.md +173 -0
  596. package/docs/guide/media.md +273 -0
  597. package/docs/guide/navigation.md +52 -0
  598. package/docs/guide/oauth.md +342 -0
  599. package/docs/guide/oidc.md +262 -0
  600. package/docs/guide/openapi.md +51 -0
  601. package/docs/guide/pwa.md +670 -0
  602. package/docs/guide/session.md +2105 -0
  603. package/docs/guide/subscriptions.md +211 -0
  604. package/docs/guide/testing.md +42 -0
  605. package/docs/guide/typing-the-loaders.md +311 -0
  606. package/docs/guide.md +82 -0
  607. package/docs/roadmap.md +474 -0
  608. package/docs/troubleshooting.md +3837 -0
  609. package/package.json +301 -5
@@ -0,0 +1,2105 @@
1
+ # A BFF session
2
+
3
+ This page is for a React Router app that is the backend of its own pages (a
4
+ BFF) in front of a GraphQL API that signs users in with `@softistx/janus`, and
5
+ holds the API's session token in an HttpOnly cookie of its own. The browser
6
+ never sees the token; the app sends it to the API as a bearer, on the user's
7
+ behalf.
8
+
9
+ It covers three subpaths:
10
+
11
+ - `@softistx/alxia-react-router/session`, the server side: the cookies, the sign-in
12
+ flow, the step-up and the pages a mail's link opens. It imports
13
+ `react-router` and `/errors`' files, nothing else, knows no API client and
14
+ adds no peer.
15
+ - `@softistx/alxia-react-router/session/react`, the page's hooks around those flows:
16
+ signing out, a mail link's parameter, a one-code field and the step-up
17
+ with the replay of the refused action. They import
18
+ `react` and `react-router`, both already peers.
19
+ - `@softistx/alxia-react-router/session/model`, the part that imports nothing and is
20
+ safe in a component as well as in a loader: redirects that stay on the
21
+ site, the sign-in pages' paths, and the step-up's state.
22
+
23
+ The flow speaks `@softistx/janus`'s words (`signedIn`, `secondFactor`,
24
+ `CODE_INVALID`, `via: 'email' | 'secondFactor'`) without importing it; the app
25
+ maps its API's enums once. An app that runs `@softistx/janus` itself, with its own
26
+ database, wants [`@softistx/alxia-janus`](https://www.npmjs.com/package/@softistx/alxia-janus)
27
+ instead.
28
+
29
+ - [A complete sign-in](#a-complete-sign-in)
30
+ - [Redirects that stay on the site](#redirects-that-stay-on-the-site)
31
+ - [The sign-in pages' paths](#the-sign-in-pages-paths)
32
+ - [Cookies](#cookies)
33
+ - [Signing in](#signing-in)
34
+ - [The second factor](#the-second-factor)
35
+ - [Signing out](#signing-out)
36
+ - [Step-up](#step-up)
37
+ - [Pages a mail's link opens](#pages-a-mails-link-opens)
38
+ - [The page's hooks](#the-pages-hooks)
39
+ - [The types and the rest of `/session/model`](#the-types-and-the-rest-of-sessionmodel)
40
+
41
+ ## A complete sign-in
42
+
43
+ The app's side is three server files and four routes. `execute`, `t`,
44
+ `toAnswer`, `readViewer`, `apiMessages` and the GraphQL documents
45
+ (`SignInMutation`, `ConfirmMutation`, `RecoverMutation`, `SignOutMutation`,
46
+ `ViewerQuery`) are the app's own: the package knows no API client and no
47
+ wording. `toAnswer` maps the API's result to a `SignInAnswer` (see
48
+ [Signing in](#signing-in)).
49
+
50
+ ```ts
51
+ // app/cookies.server.ts
52
+ import { sessionCookies } from '@softistx/alxia-react-router/session';
53
+
54
+ export const cookies = sessionCookies({
55
+ session: 'my-app_session',
56
+ challenge: 'my-app_challenge',
57
+ secure: !import.meta.env.DEV,
58
+ });
59
+ ```
60
+
61
+ ```ts
62
+ // app/errors.server.ts
63
+ import { createApiErrors, jsonActions } from '@softistx/alxia-react-router/errors';
64
+
65
+ export const errors = createApiErrors<'en' | 'fr'>({
66
+ messages: apiMessages,
67
+ unavailable: (language) => t('app.error.unavailable', {}, language),
68
+ });
69
+ export const json = jsonActions({ origin: () => process.env.APP_ORIGIN });
70
+ ```
71
+
72
+ ```ts
73
+ // app/session.server.ts
74
+ import { signInFlow } from '@softistx/alxia-react-router/session';
75
+ import { SignOutMutation, execute } from './api.server';
76
+ import { cookies } from './cookies.server';
77
+ import { errors, json } from './errors.server';
78
+
79
+ export const signIn = signInFlow({
80
+ cookies,
81
+ errors,
82
+ json,
83
+ revoke: (token, request) =>
84
+ execute(SignOutMutation, {}, { token, signal: request.signal }),
85
+ attemptsLeft: (count, language) => t('auth.attempts-left', { count }, language),
86
+ });
87
+ ```
88
+
89
+ The password page. Its loader sends a live session home and clears what a
90
+ signed-out visit should not keep; its action runs the API's mutation inside
91
+ `signInStep`, which redirects where the answer leads or stays on the form with
92
+ a message:
93
+
94
+ ```tsx
95
+ // app/routes/sign-in.tsx
96
+ import { data, redirect } from 'react-router';
97
+ import { useJsonFetcher } from '@softistx/alxia-react-router/errors';
98
+ import { cookies } from '~/cookies.server';
99
+ import { json } from '~/errors.server';
100
+ import { signIn } from '~/session.server';
101
+
102
+ export async function loader({ request }: Route.LoaderArgs) {
103
+ const viewer = await signIn.viewer(request, readViewer);
104
+ // A live session goes home; a challenge left by a half-done sign-in goes too.
105
+ if (viewer) {
106
+ throw redirect(signIn.nextParam(request), {
107
+ headers: { 'Set-Cookie': cookies.destroyChallenge() },
108
+ });
109
+ }
110
+ return data({}, { headers: cookies.signInPageHeaders(viewer === null) });
111
+ }
112
+
113
+ export async function action({ context, request }: Route.ActionArgs) {
114
+ const { language } = alxiaOf(context);
115
+ // First, for a form posted before hydration: it goes back to its page.
116
+ json.requireJsonPost(request);
117
+ const input = await json.readInput(request, SignInInput);
118
+ return signIn.signInStep(
119
+ async () => toAnswer((await execute(SignInMutation, input)).signIn),
120
+ { request, language, next: signIn.nextParam(request), extra: {} },
121
+ );
122
+ }
123
+
124
+ export default function SignIn() {
125
+ const { fetcher, post, busy } = useJsonFetcher<typeof action>();
126
+ return (
127
+ <form onSubmit={(event) => { event.preventDefault(); post(formValues(event)); }}>
128
+ {/* the fields */}
129
+ {fetcher.data && 'formError' in fetcher.data ? <p>{fetcher.data.formError}</p> : null}
130
+ <button disabled={busy}>Sign in</button>
131
+ </form>
132
+ );
133
+ }
134
+ ```
135
+
136
+ The code page, reached when the answer is `secondFactor`. Its loader needs
137
+ the challenge cookie; its action posts the code against it, a recovery code
138
+ included:
139
+
140
+ ```ts
141
+ // app/routes/sign-in.second-factor.tsx
142
+ import { redirect } from 'react-router';
143
+ import { signInPath } from '@softistx/alxia-react-router/session/model';
144
+ import { cookies } from '~/cookies.server';
145
+ import { signIn } from '~/session.server';
146
+
147
+ export function loader({ request }: Route.LoaderArgs) {
148
+ if (!cookies.challengeOf(request)) {
149
+ throw redirect(signInPath(signIn.nextParam(request)));
150
+ }
151
+ return null;
152
+ }
153
+
154
+ export async function action({ context, request }: Route.ActionArgs) {
155
+ const { language } = alxiaOf(context);
156
+ const input = await signIn.readCodeInput(request);
157
+ const challenge = cookies.challengeOf(request);
158
+ if (!challenge) throw redirect(signInPath(signIn.nextParam(request)));
159
+ return signIn.signInStep(
160
+ () =>
161
+ signIn.codeStep(input, challenge, {
162
+ confirm: async (challenge, code) =>
163
+ toAnswer((await execute(ConfirmMutation, { challenge, code })).confirm),
164
+ recover: async (challenge, recoveryCode) =>
165
+ toAnswer((await execute(RecoverMutation, { challenge, recoveryCode })).recover),
166
+ }),
167
+ {
168
+ request,
169
+ language,
170
+ next: signIn.nextParam(request),
171
+ extra: { kind: input.kind },
172
+ // A refused code stays on the form with the tries left; a challenge
173
+ // that is over goes back to the password page.
174
+ refused: (error) =>
175
+ signIn.codeRefusal(error, language) ??
176
+ redirect(signInPath(signIn.nextParam(request), { query: { expired: '1' } }), {
177
+ headers: { 'Set-Cookie': cookies.destroyChallenge() },
178
+ }),
179
+ },
180
+ );
181
+ }
182
+ ```
183
+
184
+ Sign-out, and a page that needs a user:
185
+
186
+ ```ts
187
+ // app/routes/sign-out.tsx
188
+ import { redirect } from 'react-router';
189
+ import { signIn } from '~/session.server';
190
+
191
+ export const loader = () => redirect('/');
192
+
193
+ export function action({ request }: Route.ActionArgs) {
194
+ return signIn.signOut(request);
195
+ }
196
+ ```
197
+
198
+ ```ts
199
+ // app/routes/orders.tsx
200
+ import { data } from 'react-router';
201
+ import { signIn } from '~/session.server';
202
+
203
+ export async function loader({ request }: Route.LoaderArgs) {
204
+ const { viewer, headers } = await signIn.requireViewer(
205
+ request,
206
+ (token) => execute(ViewerQuery, {}, { token }).then((r) => r.viewer),
207
+ (viewer) => viewer.sessionExpiresAt,
208
+ );
209
+ return data({ viewer }, { headers });
210
+ }
211
+ ```
212
+
213
+ A request with no session, or one the API refuses, is redirected to
214
+ `/sign-in?next=%2Forders`, and the user comes back to `/orders` once signed in.
215
+ The sections below say what each call does and what it refuses.
216
+
217
+ ## Redirects that stay on the site
218
+
219
+ After a sign-in the user goes back to the page they came from, carried in
220
+ `next`. A `next` is whatever the request says, so it is checked before any
221
+ redirect: `safeNext` answers a path of this site (with its search and hash),
222
+ and `/` for anything else.
223
+
224
+ ```ts
225
+ import { safeNext } from '@softistx/alxia-react-router/session/model';
226
+
227
+ safeNext('/orders/42?tab=items'); // '/orders/42?tab=items'
228
+ safeNext('//evil.test'); // '/'
229
+ safeNext('https://evil.test/'); // '/'
230
+ safeNext('/a/..//evil.test'); // '/'
231
+ ```
232
+
233
+ It refuses a value that does not start with `/`, one that starts with `//`,
234
+ one holding a backslash, a space or a control character (a browser drops a
235
+ tab or a newline, or reads `\` as `/`), a value over 2000 characters, and
236
+ one that resolves to another site once its dot segments are applied. A
237
+ percent-encoded `//` stays a path of this site; it is not decoded.
238
+
239
+ `nextOf(request.url)` from [`@softistx/alxia-react-router/errors`](errors.md) is the
240
+ page a request is for, and `safeNext` is applied on the way back.
241
+
242
+ ## The sign-in pages' paths
243
+
244
+ `signInPath(next)` is the sign-in page's URL, coming back to `next`, and
245
+ `secondFactorPath(next)` the second-factor page's. Both go through
246
+ `safeNext`, and add no `next` for the home page.
247
+
248
+ ```ts
249
+ import {
250
+ SIGN_IN_PATHS,
251
+ secondFactorPath,
252
+ signInPath,
253
+ } from '@softistx/alxia-react-router/session/model';
254
+
255
+ signInPath('/orders'); // '/sign-in?next=%2Forders'
256
+ signInPath('/', { query: { expired: '1' } }); // '/sign-in?expired=1'
257
+ signInPath('/orders', { path: '/login' }); // '/login?next=%2Forders'
258
+ secondFactorPath('/orders'); // '/sign-in/second-factor?next=%2Forders'
259
+ ```
260
+
261
+ `SIGN_IN_PATHS` holds the defaults, `/sign-in` and `/sign-in/second-factor`.
262
+ If every `next` comes out as `/`, see
263
+ [`next` is always `/`](../troubleshooting.md#next-is-always-).
264
+
265
+ ## Cookies
266
+
267
+ `sessionCookies` names, writes, reads and removes the two cookies a sign-in
268
+ needs: the session, which holds the API's token, and the challenge, which
269
+ carries a second factor's challenge from the password page to the code page.
270
+ Both are `HttpOnly`, so a script never reads them.
271
+
272
+ ```ts
273
+ // app/cookies.server.ts
274
+ import { sessionCookies } from '@softistx/alxia-react-router/session';
275
+
276
+ export const cookies = sessionCookies({
277
+ session: 'my-app_session',
278
+ challenge: 'my-app_challenge',
279
+ secure: !import.meta.env.DEV,
280
+ });
281
+ ```
282
+
283
+ `secure` is required and is never read from the environment: pass `true`
284
+ when the app is served over HTTPS, and `false` for plain HTTP in development.
285
+ A wrong value in production would send the token over HTTP, so the package
286
+ leaves that choice to you in plain sight.
287
+
288
+ `sameSite` (`'lax'` by default, `'strict'` or `'none'`) sets the `SameSite`
289
+ attribute of every cookie written, `destroy` and the challenge included. Use
290
+ `'strict'` for an app that nobody reaches from a link on another site while
291
+ signed in; `'none'` needs `secure: true` and throws a `TypeError` without it.
292
+
293
+ | `secure` | session cookie | challenge cookie |
294
+ | --- | --- | --- |
295
+ | `true` | `__Host-my-app_session`, `Secure` | `__Secure-my-app_challenge`, `Secure` |
296
+ | `false` | `my-app_session` | `my-app_challenge` |
297
+
298
+ Pass the base names. The package adds the prefix itself and refuses a name
299
+ that already has one.
300
+
301
+ An app served on per-tenant subdomains passes `challengeHostPrefix: true` with
302
+ `challengePath: '/'`: the challenge is then named `__Host-my-app_challenge`
303
+ (`Secure`, `Path=/`, no `Domain`), which a sibling subdomain cannot shadow.
304
+ Without `challengePath: '/'` it throws a `TypeError`; with `secure: false`
305
+ there is no prefix.
306
+
307
+ ```ts
308
+ sessionCookies({
309
+ session: 'my-app_session',
310
+ challenge: 'my-app_challenge',
311
+ challengePath: '/',
312
+ challengeHostPrefix: true,
313
+ secure: !import.meta.env.DEV,
314
+ });
315
+ ```
316
+
317
+ ### What is written
318
+
319
+ The bytes are, in this order:
320
+
321
+ ```
322
+ Name=value; Max-Age=n; Path=/; HttpOnly[; Secure]; SameSite=Lax
323
+ ```
324
+
325
+ (`SameSite=Strict` or `None` with the `sameSite` option.)
326
+
327
+ The session cookie's value is `<expiry in ms>.<token>`, percent-encoded. A
328
+ session set by an app that wrote its own cookies in this format is read as it
329
+ is, so adopting the package does not sign anyone out.
330
+
331
+ - **`__Host-`** holds only with `Secure`, `Path=/` and no `Domain`. The session
332
+ cookie sets exactly that, so a sibling subdomain cannot plant one that
333
+ shadows it.
334
+ - **The challenge** is sent to `/sign-in` only (`challengePath`) and lives at
335
+ most five minutes (`challengeSeconds`), or less when the API's challenge
336
+ ends sooner. A sibling subdomain can plant a `__Secure-` cookie (it has no
337
+ `Path` lock), which makes a code fail; it never yields a session.
338
+ `challengeHostPrefix: true` (with `challengePath: '/'`) names it `__Host-`
339
+ and closes that.
340
+ - **The expiry in the value** only decides when the cookie is set again: the
341
+ API alone decides whether a session is valid. A forged expiry gains nothing.
342
+
343
+ ### Using them
344
+
345
+ ```ts
346
+ import { data } from 'react-router';
347
+ import { cookies } from './cookies.server';
348
+
349
+ // After a sign-in: the API's token and the session's end.
350
+ const headers = new Headers();
351
+ headers.append('Set-Cookie', cookies.commit(token, expiresAt));
352
+
353
+ // A request's token, to send to the API as a bearer.
354
+ const session = cookies.read(request); // { token, expiresAt } or null
355
+ const token = cookies.token(request);
356
+
357
+ // Sign-out.
358
+ headers.append('Set-Cookie', cookies.destroy());
359
+
360
+ // A guest page: a session cookie that is there but unreadable is cleared.
361
+ // `present` is true for any value, where `token` is null for a malformed one.
362
+ if (!cookies.token(request))
363
+ return data(guest, cookies.present(request) ? { headers: { 'Set-Cookie': cookies.destroy() } } : undefined);
364
+
365
+ // A session the API renewed: the cookie is set again only when the expiry moved.
366
+ // An expiry that is absent or not a date changes nothing: the cookie is kept.
367
+ const renewed = cookies.refreshed(session, viewer.sessionExpiresAt); // {} or a Set-Cookie
368
+ ```
369
+
370
+ `refreshed` never ends a session because the API sent an expiry it cannot
371
+ read: it returns `{}` for a missing or unparseable one, and the API alone
372
+ decides when a session is over.
373
+
374
+ `commit` takes the expiry as an ISO string or a `Date`, and sets `Max-Age`
375
+ to the seconds left: floored, and 0 for a past or unreadable date.
376
+
377
+ With no `challenge` option the cookies have no challenge helpers, and `names`
378
+ holds the session alone (`SessionCookies<false>`). The challenge has its own three: `commitChallenge(challenge, expiresAt?)`,
379
+ `challengeOf(request)`, `destroyChallenge()`.
380
+
381
+ `cookies.names` holds the names as sent, prefixes included
382
+ (`{ session: '__Host-my-app_session', challenge: '__Secure-my-app_challenge' }`
383
+ when `secure`), for a log line, a test or a header that must name the cookie.
384
+
385
+ `signInPageHeaders(deadSession)` is what a signed-out visit of the sign-in page
386
+ sets. It clears the challenge blind: a client navigation fetches
387
+ `/sign-in.data`, which the cookie's path `/sign-in` does not match, so the
388
+ request never shows the challenge, yet a `Set-Cookie` with that path removes
389
+ it. With `deadSession`, it also removes a session cookie the API refused.
390
+
391
+ `serializeCookie(name, value, { maxAge, path?, secure, sameSite? })`,
392
+ `readCookie(request, name)` and `secondsUntil(expiresAt, now?)` are exported
393
+ for the cookies of your own (a language, a preference) that must be written in
394
+ the same bytes. A name that is not an RFC 6265 token, or a path with a `;` or a
395
+ control character, throws a `TypeError`; a `maxAge` that is not finite is 0.
396
+ `readCookie` returns the first non-empty cookie of that name, and `null` when
397
+ its value is not valid percent-encoding.
398
+
399
+ ### A signed session without Janus
400
+
401
+ An app with one local operator, whose password the server checks itself, has
402
+ no API token to keep. `signedSession` writes a stateless cookie instead: the
403
+ value is `<expiresAt ms>.<nonce>.<mac>`, the MAC an HMAC-SHA256 of
404
+ `<expiresAt>.<nonce>`, so the expiry cannot be moved without the secret.
405
+
406
+ ```ts
407
+ // app/operator.server.ts
408
+ import { signedSession } from '@softistx/alxia-react-router/session';
409
+
410
+ export const operator = signedSession({
411
+ secret: process.env.SESSION_SECRET ?? '',
412
+ name: 'my-app_operator',
413
+ maxAge: 8 * 60 * 60,
414
+ secure: !import.meta.env.DEV,
415
+ sameSite: 'strict',
416
+ });
417
+ ```
418
+
419
+ ```ts
420
+ // in the sign-in action, once the password was checked
421
+ const headers = new Headers();
422
+ headers.append('Set-Cookie', await operator.commit());
423
+
424
+ // in a loader
425
+ if (!(await operator.valid(request))) throw redirect('/sign-in');
426
+
427
+ // sign-out
428
+ headers.append('Set-Cookie', operator.destroy());
429
+ ```
430
+
431
+ The cookie is `HttpOnly`, `Path=/`, has no `Domain`, is named `__Host-…` when
432
+ `secure`, and its `Max-Age` is `maxAge`. `commit` and `valid` are async (Web Crypto, so the subpath keeps
433
+ importing `react-router` alone). `valid` resolves to `false`, and never
434
+ throws, for a missing cookie, a malformed value, an expiry that is not digits,
435
+ a MAC of the wrong length or that does not match (compared in constant time)
436
+ and an expiry in the past. `secret` is at least 32 characters, from the
437
+ environment; changing it signs everyone out. The session is not revocable
438
+ before its expiry: keep `maxAge` short, and check the password again for
439
+ anything sensitive.
440
+
441
+ ### A sign-in throttle
442
+
443
+ A password sign-in needs a failed-attempt throttle and a cap on concurrent
444
+ password hashes (argon2 at 64 MiB each is a memory spike when a hundred
445
+ requests arrive together). `createSignInThrottle` is both, next to
446
+ `signedSession`, and works with any sign-in, not only a signed session.
447
+
448
+ ```ts
449
+ // app/throttle.server.ts
450
+ import { createSignInThrottle } from '@softistx/alxia-react-router/session';
451
+
452
+ export const throttle = createSignInThrottle({
453
+ max: 5, // failures per key...
454
+ windowMs: 15 * 60_000, // ...within this window
455
+ });
456
+ ```
457
+
458
+ ```ts
459
+ // in the sign-in action
460
+ const email = String(form.get('email')).trim().toLowerCase();
461
+
462
+ const seconds = throttle.wait(email);
463
+ if (seconds > 0) return tooMany(seconds); // e.g. a 429 with Retry-After: seconds
464
+
465
+ const checked = await throttle.verify(() => Bun.password.verify(password, hash));
466
+ if (checked.busy) return tryLater(); // e.g. a 503 with Retry-After: 2
467
+ if (!checked.value) {
468
+ throttle.fail(email);
469
+ return refused();
470
+ }
471
+
472
+ throttle.clear(email);
473
+ headers.append('Set-Cookie', await operator.commit());
474
+ ```
475
+
476
+ - `wait(key)` returns the seconds to wait, `0` when the key may try. It
477
+ records nothing, so call it before every attempt, also for an address that
478
+ does not exist: answer the same for a known and an unknown one.
479
+ - `fail(key)` records a failure; `clear(key)` forgets the key after a success.
480
+ A key is blocked at `max` failures within `windowMs`, until the oldest
481
+ leaves the window.
482
+ - `maxKeys` (10 000 by default) bounds the memory an attacker can make you
483
+ hold: past it the oldest key is dropped.
484
+ - The global bucket counts every failure, all keys together. Past `globalMax`
485
+ failures within `globalWindowMs` (100 and one minute by default), `wait`
486
+ answers the seconds until the oldest of them leaves that window, for every
487
+ key. It delays everyone briefly and lifts itself; it never locks an
488
+ account, so one attacker spraying addresses cannot lock the real owner out
489
+ for the per-key window. `clear` leaves it alone. For a softer policy, see
490
+ [the delay-only global bucket](#a-delay-only-global-bucket).
491
+ - `verify(task)` runs `task` (the password check) with at most
492
+ `maxConcurrentVerifies` (2) at once, and up to `maxQueuedVerifies` (4) more
493
+ waiting for a slot. Past that it answers `{ busy: true }` without running
494
+ the task. Otherwise `{ busy: false, value }`; a rejection of `task` passes
495
+ through and frees its slot.
496
+ - `now` replaces the clock (`() => number` in milliseconds), for a test.
497
+
498
+ #### A delay-only global bucket
499
+
500
+ By default a full global bucket makes `wait` answer a wait for every key, so
501
+ a flood from many addresses also turns the real user away for up to
502
+ `globalWindowMs`. With `globalMode: 'delay'` the bucket never refuses: `wait`
503
+ answers per key only, and `globalDelay()` gives the milliseconds to slow the
504
+ attempt down by.
505
+
506
+ ```ts
507
+ export const throttle = createSignInThrottle({
508
+ max: 5,
509
+ windowMs: 15 * 60_000,
510
+ globalMax: 20, // failures, all keys together...
511
+ globalWindowMs: 15 * 60_000, // ...within this window
512
+ globalMode: 'delay', // 'refuse' by default
513
+ maxDelayMs: 3_000, // the longest delay, 3 000 by default
514
+ });
515
+ ```
516
+
517
+ ```ts
518
+ // in the sign-in action, before the verification
519
+ const seconds = throttle.wait(email); // per key only in this mode
520
+ if (seconds > 0) return tooMany(seconds);
521
+
522
+ const delay = throttle.globalDelay();
523
+ if (delay > 0) await Bun.sleep(delay);
524
+ ```
525
+
526
+ - `globalDelay()` is `0` below `globalMax` failures in the window. From the
527
+ `globalMax`th it is `maxDelayMs / globalMax` for the first, and grows by
528
+ that much with each failure after, until it reaches `maxDelayMs` just
529
+ before twice `globalMax` failures (for `globalMax: 20` and `maxDelayMs: 3000`: 150 ms, 300 ms,
530
+ and so on up to 3 000 ms). It falls back as failures leave the window.
531
+ It records nothing, and `clear` leaves it alone.
532
+ - It is always `0` in the default `'refuse'` mode.
533
+ - Sleeping holds the request open, so keep `maxDelayMs` to a few seconds,
534
+ and let `verify`'s queue bound how many requests wait at once.
535
+
536
+ It is per process, in memory: a restart forgets every failure, and behind
537
+ several instances (or workers) each counts alone, so the effective limits are
538
+ multiplied by the instance count. For a limit shared between instances, count
539
+ in a store they share (for example `@softistx/redis`' rate limits).
540
+
541
+ ### Safari and `http://localhost`
542
+
543
+ Safari (WebKit) drops a `Secure` cookie set over `http://localhost`, where
544
+ Chromium and Firefox keep it. With `secure: true` in development, sign-in
545
+ succeeds and the next request carries no session, so the app loops back to the
546
+ sign-in page. Pass `secure: !import.meta.env.DEV`: development then sets no
547
+ `Secure` and no prefix, since the prefixes require `Secure`. See
548
+ [the troubleshooting entry](../troubleshooting.md#sign-in-loops-on-httplocalhost-in-safari).
549
+
550
+ ## Signing in
551
+
552
+ `signInFlow` is the server side of the sign-in pages: where an answer leads,
553
+ the form's refusals, the second factor, the viewer and sign-out. Build it once
554
+ ([the example](#a-complete-sign-in) does, in `app/session.server.ts`), over the
555
+ app's `createApiErrors` and `jsonActions` (the same instances its other
556
+ actions use, so every body is read with the same same-origin check).
557
+ `revoke(token, request, context)` ends a session at the API and receives the
558
+ request, for its abort signal, and [the caller's context](#the-callers-context),
559
+ for the visitor's address and language.
560
+
561
+ `toAnswer` maps the API's words to `@softistx/janus`'s: a
562
+ `SignInAnswer` is `{ status: 'signedIn', token, expiresAt }`,
563
+ `{ status: 'secondFactor', challenge, expiresAt? }` or `{ status: 'other' }`
564
+ (an API's `LINKED`, say, which opens no session). The default codes are
565
+ janus's, `CODE_INVALID` for a wrong code and `TOKEN_UNKNOWN`, `TOKEN_SPENT`
566
+ and `TOKEN_EXPIRED` for a challenge that is gone; an API with its own pass
567
+ `codes: { invalidCode, challengeOver }`. `paths` replaces the pages' paths
568
+ (`SIGN_IN_PATHS`), `clear` lists the `Set-Cookie` values a new session and a
569
+ sign-out also remove (a per-account preference), `unavailable` words an API
570
+ that cannot be reached (`errors.unavailableMessage` by default), and
571
+ `endedParam` is a query key, such as `'expired'`, that `signInRedirect` adds
572
+ when the request carried a session cookie, to say the session ended.
573
+
574
+ A sign-in page's action runs the API's mutation inside `signInStep`, as the
575
+ example does. The order matters, because `readInput` reads the body:
576
+ `json.requireJsonPost(request)` first (a form posted before hydration goes
577
+ back to its page), then `json.readInput` (it checks the origin and the content
578
+ type, and refuses another site with a 403), then `signInStep`, which runs the
579
+ same two checks again on the headers before it signs anyone in or revokes a
580
+ session: a native post goes back to its page, and a JSON post from another
581
+ site is a 403, even for an action that read its input some other way. It reads
582
+ headers only, never the body. Its outcomes:
583
+
584
+ - A **signed-in** answer lands only when it has a token and an `expiresAt`
585
+ that is a date still in the future; otherwise it opens no session (see
586
+ *other* below). A session set with a dead end would be gone at once.
587
+ - A **signed-in** answer redirects to `next` (through `safeNext`) with the
588
+ session cookie set and the challenge and the app's `clear()` cookies removed.
589
+ The session the browser held is revoked first (`landReplacing`): one browser
590
+ holds one session. A revoke that fails is ignored, and the old session lives
591
+ until it expires.
592
+ - A **second factor** answer redirects to the second-factor page with the
593
+ challenge in its own cookie. It is a secret: never in a URL, a log or the
594
+ loader's data.
595
+ - An **API refusal** stays on the page: `{ ...extra, formError }`, worded by
596
+ `errors`, with the API's status. An API that cannot be reached says
597
+ `unavailable`, with 503. Anything else is thrown. `refused(error)` runs
598
+ first: it returns a `Response` (a redirect), a string (a richer message) or
599
+ `undefined`.
600
+ - An **other** answer opens no session, so the step says `unavailable`. Check
601
+ an answer such as `LINKED` yourself, with `landing(answer, next)`, which is
602
+ `null` for it.
603
+
604
+ The flow also exposes what it was built with, for the steps built on it:
605
+ `signIn.cookies`, `signIn.errors` and `signIn.json`, `signIn.attemptsLeft`,
606
+ `signIn.unavailable(language)` (the `unavailable` option, else
607
+ `errors.unavailableMessage`) and `signIn.clear()` (the `clear` option's
608
+ cookies, none by default). `stepUpSteps` and `authLinks` take the flow and read
609
+ these, so the app wires `errors`, `json` and the wording once.
610
+
611
+ `signIn.nextParam(request)` is the `next` the sign-in page was opened with,
612
+ through `safeNext`. `signIn.signInRedirect(request)` is the redirect
613
+ `requireViewer` throws: to the sign-in page, back to this request's page,
614
+ with the session cookie cleared. `signIn.revokeSession(request)` ends the
615
+ request's session at the API (through `revoke`; a failure is ignored) and
616
+ answers `true` when the request carried one.
617
+
618
+ `signIn.landing(answer, next)` and `signIn.landReplacing(answer, next,
619
+ { request, revokeOn? })` are the same redirects for a step that does not go
620
+ through `signInStep` (a link a mail carries). `revokeOn` lists the statuses
621
+ that end the browser's session; `['signedIn']` by default.
622
+
623
+ ### The caller's context
624
+
625
+ A bare `Request` carries no socket, so `revoke` cannot resolve the visitor's
626
+ address from it, and reading `X-Forwarded-For` would trust a header the browser
627
+ can forge. The address and the language come from alxia's trusted proxy
628
+ resolution, which your loader or action reads from its `context`, and which
629
+ every other call to the API already carries. Hand that to the flow: every step
630
+ that can revoke takes an optional `context`, and passes it to `revoke` as its
631
+ third argument.
632
+
633
+ Name its type with the `revoke` parameter's annotation, and `signInFlow` infers
634
+ it (`C`) for every step. Without a context, `revoke` receives `undefined`.
635
+
636
+ ```ts
637
+ // app/session.server.ts
638
+ import type { AlxiaContextOf } from '@softistx/alxia-react-router';
639
+
640
+ // The app's registered context: `ip` is the address alxia resolved
641
+ // (through its `proxy` option), and `language` is there when the app
642
+ // registers `@softistx/alxia-language`.
643
+ type Caller = AlxiaContextOf;
644
+
645
+ export const signIn = signInFlow({
646
+ cookies,
647
+ errors,
648
+ json,
649
+ revoke: (token, request, caller?: Caller) =>
650
+ execute(SignOutMutation, {}, { token, signal: request.signal, caller }),
651
+ attemptsLeft: (count, language) => t('auth.attempts-left', { count }, language),
652
+ });
653
+
654
+ // app/routes/sign-out.ts
655
+ export async function action({ context, request }: Route.ActionArgs) {
656
+ return signIn.signOut(request, { context: alxiaOf(context) });
657
+ }
658
+ ```
659
+
660
+ `stepUpSteps` and `authLinks` take such a flow as it is, with no cast. The
661
+ step-up never calls `revoke`, so it needs no `context` of its own: its
662
+ `request` and `confirm` take none.
663
+
664
+ ```ts
665
+ export const stepUp = stepUpSteps({
666
+ signIn, // the flow above, typed with `Caller`
667
+ spent: (language) => t('step-up.spent', {}, language),
668
+ });
669
+ ```
670
+
671
+ The same `context` is taken by `revokeSession(request, { context })`,
672
+ `landReplacing(answer, next, { request, context })`,
673
+ `signInStep(run, { ..., context })`, and, on `authLinks`, by
674
+ `landByLink(answer, { ..., context })` and `afterReset(request, { context })`.
675
+ A callback written with two parameters keeps working. With an explicit
676
+ `signInFlow<Lang>`, `C` stays `undefined` and a `context` is a type error:
677
+ write both type arguments (`signInFlow<Lang, Caller>`) or none (see
678
+ [the troubleshooting entry](../troubleshooting.md#type--is-not-assignable-to-type-undefined-passing-a-context-to-a-step)).
679
+
680
+ ### Which steps guard themselves
681
+
682
+ Every step that signs in, out, spends or mails runs the same guard before it
683
+ reads anything: a native form post is redirected back to its page, and a JSON
684
+ post from another site is a 403. These guard themselves: `signInStep`,
685
+ `readCodeInput`, `landReplacing`, `revokeSession`, `signOut` (through
686
+ `readJson`), the step-up's `request` and `confirm`, and `linkArgs`,
687
+ `spendToken`, `landByLink`, `afterReset` and `requestLink`. `landing`,
688
+ `codeStep`, `codeRefusal`, `viewer` and `requireViewer` take no post and do not.
689
+
690
+ An app's own step (a passkey's registration, say) calls `signIn.guard(request)`
691
+ first, in a POST action, before it reads the body or calls the API. It throws
692
+ the same redirect or 403. Do not call it in a GET callback (an OAuth return, a
693
+ magic link's landing): a GET carries no JSON content type, so the guard would
694
+ redirect it to itself.
695
+
696
+ ### The viewer
697
+
698
+ ```ts
699
+ // a page that needs a user (as in the example)
700
+ const { viewer, headers } = await signIn.requireViewer(
701
+ request,
702
+ (token) => execute(ViewerQuery, {}, { token }).then((r) => r.viewer),
703
+ (viewer) => viewer.sessionExpiresAt,
704
+ );
705
+ return data({ viewer }, { headers });
706
+
707
+ // the sign-in page itself: a live session goes home
708
+ const viewer = await signIn.viewer(request, read); // the viewer, null, or undefined
709
+ ```
710
+
711
+ `requireViewer` throws `signInRedirect(request)` without a cookie, on a 401
712
+ and when `read` finds no viewer; any other failure is thrown through
713
+ `routeError`. The redirect comes back to the page and clears the cookie, and
714
+ adds `?<endedParam>=1` when the request carried one. `headers` set the cookie
715
+ again when the API moved the session's end. `viewer` answers `null` for a
716
+ 401 (a dead session: send `cookies.signInPageHeaders(true)`), and `undefined`
717
+ without a cookie or when the API cannot tell.
718
+
719
+ ## The second factor
720
+
721
+ A second factor is optional. An API with none builds the cookies without
722
+ `challenge` and the flow without `attemptsLeft`. Neither carries a
723
+ second-factor member on its type, a `secondFactor` answer lands nowhere
724
+ (`landing` returns `null`), and no challenge cookie is set or cleared:
725
+
726
+ ```ts
727
+ export const cookies = sessionCookies({ session: 'my-app_session', secure: true });
728
+ export const signIn = signInFlow({ cookies, errors, json, revoke });
729
+ // signIn.codeStep, signIn.readCodeInput and cookies.challengeOf do not exist.
730
+ ```
731
+
732
+ Give both or neither: `signInFlow` refuses cookies with a challenge and no
733
+ `attemptsLeft` at compile time, and throws a TypeError at runtime when only
734
+ one is given ([troubleshooting](../troubleshooting.md)). To type a helper
735
+ that takes the flow or the cookies, use `SignInFlow<L, C, false>` and
736
+ `SessionCookies<false>` (no second factor), `SignInFlow<L, C>` and
737
+ `SessionCookies` (one), or `SignInFlow<L, C, boolean>` and
738
+ `SessionCookies<boolean>` for either. `signInFlow` itself takes
739
+ `SessionCookies<true>` or `SessionCookies<false>`, not the union: when
740
+ `challenge` may be `undefined`, `sessionCookies` returns
741
+ `SessionCookies<boolean>`, so branch on `challenge` and call `sessionCookies`
742
+ in each branch. `stepUpSteps` takes a flow with a second factor; `authLinks`
743
+ takes either. The rest of this section is for an app that has one.
744
+
745
+ The sign-in page's answer `secondFactor` leads to the second-factor page,
746
+ whose loader needs the challenge cookie (`cookies.challengeOf(request)`; back
747
+ to the sign-in page without one) and whose action posts the code.
748
+
749
+ [The example](#a-complete-sign-in) shows both: `codeStep` runs `confirm` for an
750
+ issued code and `recover` for a recovery code, and `refused` words a refusal
751
+ with the tries left or, when the challenge is over, sends the user back to the
752
+ password page.
753
+
754
+ `readCodeInput` takes the page's JSON post, `{ kind, code }`: `kind` is
755
+ `'code'` for an issued code (an authenticator app's, or the one mailed) and
756
+ `'recovery'` for a recovery code (`SecondFactorKind`); `code` is at most 40
757
+ characters. A native form post (before hydration) goes back to its page, a
758
+ cross-site post is a 403 even when it is JSON, and a body of another shape is a
759
+ 400.
760
+
761
+ `codeRefusal(error, language, whenNone?)` words a refused code:
762
+
763
+ | the API says | the form shows |
764
+ | --- | --- |
765
+ | `CODE_INVALID` with `attemptsLeft: 3` | the message and `attemptsLeft(3, language)` |
766
+ | `CODE_INVALID` with `attemptsLeft: 0` | `undefined`: the challenge is over, sign in again (with `whenNone`, the message and `whenNone` instead) |
767
+ | `CODE_INVALID` with no count | the message alone |
768
+ | any code with `reason: 'throttled'` (the account's code tries are limited) and `retryAfter: 840` | `throttled(14, language)`: "Too many tries, wait 14 min." (`retryAfter` rounded up to minutes, at least 1) |
769
+ | `reason: 'throttled'` with no `retryAfter` | `throttled(undefined, language)`: "Try again later." |
770
+ | `TOKEN_UNKNOWN`, `TOKEN_SPENT`, `TOKEN_EXPIRED` | `undefined` |
771
+ | anything else | the message `errors` words |
772
+
773
+ The default wording is « Trop d'essais, réessayez dans N min. » and
774
+ « Réessayez plus tard. » in French (a `language` of `fr`, `fr-CA`, `fr_CH`),
775
+ and "Too many tries, wait N min." and "Try again later." otherwise.
776
+
777
+ `throttled` is an optional option of `signInFlow` beside `attemptsLeft`
778
+ (`throttled(minutes: number | undefined, language)`). Without it the flow
779
+ words the wait in English, or in French when `language` starts with `fr`. A
780
+ throttled refusal wins over the tries left, `whenNone` and the challenge
781
+ codes: the user is told to wait, not that the code is wrong.
782
+
783
+ ```ts
784
+ signInFlow({
785
+ cookies,
786
+ errors,
787
+ json,
788
+ revoke,
789
+ attemptsLeft: (count, language) => t(language, 'tries-left', { count }),
790
+ throttled: (minutes, language) =>
791
+ minutes === undefined
792
+ ? t(language, 'try-later')
793
+ : t(language, 'too-many-tries', { minutes }),
794
+ });
795
+ ```
796
+
797
+ The count is `attemptsLeftOf(error)` of
798
+ [`@softistx/alxia-react-router/errors`](errors.md#the-tries-a-code-leaves), which
799
+ reads janus's `extensions.attemptsLeft`.
800
+
801
+ #### The wait, for a code field that locks itself
802
+
803
+ `codeRefusal` still returns a string. `signInStep` tells a throttled refusal
804
+ (`reason: 'throttled'`) by itself and adds the wait to its stayed answer,
805
+ beside `formError`: `throttled: true` and, when the API gives the seconds,
806
+ `retryAfter` (`retryAfterOf`, a whole number from 0). Both are optional and
807
+ absent from any other refusal, as in the magic-link flow's answers.
808
+
809
+ ```ts
810
+ const stayed = await signIn.signInStep(step, {
811
+ request, language, next, extra,
812
+ refused: (error) => signIn.codeRefusal(error, language),
813
+ });
814
+ // a throttled code: { ...extra, formError: 'Too many tries, wait 10 min.',
815
+ // throttled: true, retryAfter: 600 }
816
+ ```
817
+
818
+ On the page, hand them to the verification-code field, which locks Confirm
819
+ and counts down:
820
+
821
+ ```tsx
822
+ <VerificationCode
823
+ error={actionData?.throttled ? 'throttled' : actionData?.formError}
824
+ retryAfter={actionData?.retryAfter}
825
+ />
826
+ ```
827
+
828
+ ## Signing out
829
+
830
+ `signIn.signOut(request)` is the whole action of the example's sign-out route.
831
+
832
+ `signOut` reads the body as JSON first (same-origin only, a 403 or 415
833
+ otherwise), so another site cannot sign anyone out, and a GET signs nobody
834
+ out. It then ends the session at the API (a failure is ignored: the cookie
835
+ goes anyway), removes the session cookie, the challenge cookie and the app's
836
+ `clear()` cookies and
837
+ redirects to `${paths.signIn}?signed-out=1` (`/sign-in?signed-out=1` by
838
+ default). When the JSON body carries a `next` (`{ "next": "/orders" }`, what
839
+ `useSignOut({ next })` posts), the redirect carries it as `?next=`
840
+ (`/sign-in?signed-out=1&next=%2Forders`), so the user lands there after signing
841
+ in again. `next` goes through `safeNext`: a value that leaves the site, or is not
842
+ a string, is dropped and the redirect is the default one.
843
+ `signOut(request, { to })` redirects to `to` instead (and wins over `next`),
844
+ after `safeNext`: a value that leaves the site goes to `/`.
845
+
846
+ ## Step-up
847
+
848
+ A step-up is a code asked for before a sensitive action: the API refuses the
849
+ mutation with `STEP_UP_REQUIRED`, the page asks for a challenge
850
+ (`requestStepUp`), the user reads the code (in the mail, or in their
851
+ authenticator app) and the page confirms it (`confirmStepUp`). `stepUpSteps`
852
+ is the server half: two steps for the route's action, whose answers
853
+ [`stepUpReducer`](#the-state-on-the-page) takes as they are.
854
+
855
+ ```ts
856
+ // app/step-up.server.ts
857
+ import { stepUpSteps } from '@softistx/alxia-react-router/session';
858
+ import { signIn } from './session.server';
859
+
860
+ export const stepUp = stepUpSteps({
861
+ // The app's signInFlow: the step-up reads its errors, its json (a step runs
862
+ // for a same-site JSON post only) and its attemptsLeft.
863
+ signIn,
864
+ spent: (language) => t('step-up.spent', {}, language), // "Ask for a new code."
865
+ });
866
+ ```
867
+
868
+ The `locked` option is `@deprecated` and ignored (a refusal is never a timed lockout, see "Changed in 0.51" below). `spent` is the text for a challenge that ended because the tries ran out. A
869
+ challenge that is gone (unknown, expired, stale: `codes.challengeOver`) is
870
+ worded by `wording(error, language)` when you pass it and it returns a string
871
+ (the API's own words, say); when it returns `undefined`, or is not given, that
872
+ challenge is worded with `spent` too.
873
+
874
+ ```ts
875
+ stepUpSteps({
876
+ signIn,
877
+ spent: (language) => t('step-up.spent', {}, language),
878
+ wording: (error, language) =>
879
+ error.code === 'TOKEN_EXPIRED' ? t('step-up.expired', {}, language) : undefined,
880
+ });
881
+ ```
882
+
883
+ `signIn` need not be a `signInFlow(...)`. An app with a hand-written sign-in
884
+ passes an object with the members the step-up reads, typed `StepUpSignIn`, with
885
+ no cast:
886
+
887
+ ```ts
888
+ import { type StepUpSignIn, stepUpSteps } from '@softistx/alxia-react-router/session';
889
+
890
+ const signIn: StepUpSignIn<'en' | 'fr'> = {
891
+ errors, // createApiErrors(...)
892
+ json, // jsonActions(...)
893
+ attemptsLeft: (count, language) => t('step-up.tries', { count }, language),
894
+ // signInRedirect: (request) => redirect('/sign-in'), // needed with onSignedOut: 'sign-in'
895
+ };
896
+ export const stepUp = stepUpSteps({ signIn, spent: (language) => t('step-up.spent', {}, language) });
897
+ ```
898
+
899
+ `onSignedOut: 'sign-in'` also needs `signInRedirect`; without it `stepUpSteps`
900
+ throws a `TypeError` when it is called.
901
+
902
+ `json.readJson`, `toVia`, `execute` and `sessionCaller` below are the app's
903
+ own helpers (its `jsonActions`, its mapping of the API's method to `via`, its
904
+ GraphQL call and its session caller), not this package's.
905
+
906
+ ```ts
907
+ // app/routes/account.step-up.tsx
908
+ import { stepUp } from '~/step-up.server';
909
+
910
+ export async function action({ context, request }: Route.ActionArgs) {
911
+ const { language } = alxiaOf(context);
912
+ json.requireJsonPost(request); // a native post goes back to its page
913
+ const caller = await sessionCaller(request);
914
+ const input = await json.readJson(request); // same-origin JSON only
915
+ if (input.intent === 'request-step-up') {
916
+ return stepUp.request(
917
+ async () => {
918
+ const { requestStepUp } = await execute(RequestStepUpMutation, {}, caller);
919
+ return { challenge: requestStepUp.challenge, via: toVia(requestStepUp.method) };
920
+ },
921
+ { request, language },
922
+ );
923
+ }
924
+ return stepUp.confirm(
925
+ () =>
926
+ execute(ConfirmStepUpMutation, { challenge: input.challenge, code: input.code }, caller),
927
+ { request, language },
928
+ );
929
+ }
930
+ ```
931
+
932
+ To serve the step-up to every page from one resource route, `route(run, {
933
+ request, language })` is that whole action: it reads the same-site JSON body
934
+ and runs `run.request()` for `{ intent: 'request-step-up' }` or
935
+ `run.confirm({ challenge, code })` for `{ intent: 'confirm-step-up',
936
+ challenge, code }` (a `via` in the body is ignored). Any other intent is a 400.
937
+
938
+ ```ts
939
+ // app/routes/step-up.tsx: any page posts the step-up intents here
940
+ export async function action({ context, request }: Route.ActionArgs) {
941
+ const { language } = alxiaOf(context);
942
+ const caller = await sessionCaller(request);
943
+ return stepUp.route(
944
+ {
945
+ request: async () => {
946
+ const { requestStepUp } = await execute(RequestStepUpMutation, {}, caller);
947
+ return { challenge: requestStepUp.challenge, via: toVia(requestStepUp.method) };
948
+ },
949
+ confirm: (input) => execute(ConfirmStepUpMutation, input, caller),
950
+ },
951
+ { request, language },
952
+ );
953
+ }
954
+ ```
955
+
956
+ A signed-out user has no page to come back to on that route. Set
957
+ `onSignedOut: 'sign-in'` on `stepUpSteps` and `route` throws the flow's
958
+ sign-in redirect (clearing the session cookie) when `run` fails with an
959
+ `ApiError` whose code is `UNAUTHENTICATED` (`codes.unauthenticated` renames
960
+ it). From `run.request` a bare 401 `Response` counts too; from `run.confirm`
961
+ it does not, since a wrong code is a 401 as well: `run.confirm` must throw an
962
+ `ApiError` for the API's code refusals. `next` is the page of a same-site
963
+ `Referer`; a `Referer` of another origin (port and protocol count) or one
964
+ that is not a URL is ignored and `next` is the route's own path. Behind a
965
+ TLS-terminating proxy an `http` `request.url` never matches an `https`
966
+ `Referer`, so `next` falls back to the route's own path there. A wrong or
967
+ expired code stays a refusal for the dialog, and a second-factor-required
968
+ answer is a refusal, never a redirect of the fetcher. Your caller must
969
+ therefore not redirect on 401 or second-factor-required itself.
970
+
971
+ This replaces the `stepUpSteps({ signIn, spent })` definition above
972
+ and applies to the `stepUp.route(...)` call of the resource route:
973
+
974
+ ```ts
975
+ export const stepUp = stepUpSteps({ signIn, spent, onSignedOut: 'sign-in' });
976
+
977
+ // app/routes/step-up.tsx: a signed-out user is redirected, never answered
978
+ export const action = ({ request }: Route.ActionArgs) =>
979
+ stepUp.route({ request: runRequest, confirm: runConfirm }, { request, language: 'en' });
980
+ ```
981
+
982
+ `request(run, { request, language })` answers `{ ok: true,
983
+ intent: 'request-step-up', challenge, via }`. `confirm(run, { request,
984
+ language })` answers `{ ok: true, intent: 'confirm-step-up' }`. Both
985
+ first run the same guard as `signInStep`: a form posted before hydration goes
986
+ back to its page, and a JSON post from another site is a 403, before `run`
987
+ is called. A refusal stays on the page, with the
988
+ API's status, as `data(...)`:
989
+
990
+ ```ts no-check
991
+ type StepUpError = 'invalid' | 'expired' | 'failed' | 'throttled';
992
+
993
+ // request, refused
994
+ { ok: false, intent: 'request-step-up', error: StepUpError, message, retryAfter? }
995
+ // confirm, refused
996
+ { ok: false, intent: 'confirm-step-up', error: StepUpError, attemptsLeft?, locked, message, retryAfter? }
997
+ ```
998
+
999
+ The answer must not be cached: `Cache-Control: private, no-store`, which
1000
+ `@softistx/alxia-secure-headers`' `pageHeaders` sets.
1001
+
1002
+ A refused request reaches the UI as `error` (`'failed'`, or `'throttled'` for a
1003
+ mail held back) with `message`, the refusal worded for the page. The reducer
1004
+ keeps both: `state.message` until the next step, and `state.retryAfter` for a
1005
+ throttle whose seconds the API gave.
1006
+
1007
+ The `via` option of `confirm` is `@deprecated` and ignored: the answer no
1008
+ longer depends on the factor. The `run` function of `confirm` takes nothing:
1009
+ bind the challenge and the code in it, as above, and keep the step's `intent`
1010
+ out of the API's variables.
1011
+
1012
+ **The challenge stays in the fetcher's answer.** It is a secret: never put it
1013
+ in a URL, in a cookie, in the loader's data or in a log. The page keeps it in
1014
+ the reducer's state and posts it back with the code. A page that carries it in
1015
+ the loader would keep it in the browser's history and the caches.
1016
+
1017
+ ### What each answer leads to
1018
+
1019
+ This is the table of `@softistx/janus-graphql`'s `confirmStepUp`, with what
1020
+ `confirm` answers:
1021
+
1022
+ | the API says | status | `confirm` answers |
1023
+ | --- | --- | --- |
1024
+ | accepted | 200 | `{ ok: true }`: send the refused mutation again |
1025
+ | `CODE_INVALID`, `attemptsLeft: 3` | 401 | `error: 'invalid'`, `attemptsLeft: 3`, `locked: false`: ask for the code again |
1026
+ | `CODE_INVALID`, `attemptsLeft: 0`, no `reason`, any `via` | 401 | `error: 'expired'`, `attemptsLeft: 0`, `locked: false`: the challenge is spent, ask for a new code |
1027
+ | `CODE_INVALID`, `reason: 'throttled'` (`attemptsLeft` is 0 or not), `retryAfter` | 400 or 401 | `error: 'throttled'`, `locked: false`, `retryAfter` in seconds: the shared window is spent, wait before sending a code again |
1028
+ | `TOKEN_SPENT`, `TOKEN_EXPIRED`, `TOKEN_UNKNOWN`, `TOKEN_STALE` | 400 | `error: 'expired'`: ask for a new code |
1029
+ | `SECOND_FACTOR_ACTIVE`, `SECOND_FACTOR_NOT_ENROLLED` | 409 | `error: 'expired'`: start over, the way to confirm changed |
1030
+ | `USER_INACTIVE`, anything else | 403 or other | `error: 'failed'`, in `wording`'s words or `errors`' |
1031
+ | an API it cannot reach | 503 | `error: 'failed'` |
1032
+ | `request` refused with `MAIL_THROTTLED`, or any 429 (a rate limit) | 429 | `error: 'throttled'`, `retryAfter` in seconds when the API sent them, `message` in `wording`'s words or `errors`' |
1033
+ | `confirm` refused with a 429 (a rate limit), whatever the code | 429 | `error: 'throttled'`, `locked: false`, `retryAfter` when sent: the challenge and its tries stay, wait and send the code again |
1034
+
1035
+ A request that the API refuses is `error: 'failed'`. A mail throttled
1036
+ (`MAIL_THROTTLED`) or any refusal with the status 429 (a rate limit, under
1037
+ whatever code, on `request` or on `confirm`) is `error: 'throttled'` instead, with `retryAfter`, the
1038
+ whole seconds to wait, read from `extensions.params.retryAfter` or
1039
+ `extensions.retryAfter` (a number or a numeric string, rounded up; with none
1040
+ usable the answer is still `throttled`, without `retryAfter`). Its `message`
1041
+ is worded by the `wording` option, which sees the error before `errors` does,
1042
+ so it can say the wait:
1043
+
1044
+ ```ts
1045
+ import { waitMinutes } from '@softistx/alxia-react-router/errors';
1046
+
1047
+ stepUpSteps({
1048
+ // …
1049
+ wording: (error, language) =>
1050
+ error.code === 'MAIL_THROTTLED'
1051
+ ? t('mail.wait', { minutes: waitMinutes(error.errors[0]?.extensions) }, language)
1052
+ : undefined,
1053
+ });
1054
+ ```
1055
+
1056
+ `confirm` reads two signals apart. A refusal with `extensions.reason ===
1057
+ 'throttled'` (also read in `params`) or a 429 is `error: 'throttled'`: the
1058
+ auth server's per-user window for authenticator codes is spent (it is shared by
1059
+ the step-up and the recovery-code regeneration), `retryAfter` says how many
1060
+ seconds to wait, and `attemptsLeft` is left out. `attemptsLeft: 0` with no
1061
+ `reason` is a challenge that used up its own tries, whatever the factor:
1062
+ `error: 'expired'`, ask for a new one. `attemptsLeft === 0` on its own is
1063
+ never a timed lockout, so `locked` is always `false`.
1064
+
1065
+ ```ts
1066
+ const answer = await stepUp.confirm(run, { request, language });
1067
+ // { ok: false, error: 'throttled', retryAfter: 540, locked: false, message }
1068
+ // -> "Try again in 9 minutes"; the challenge and its tries stay.
1069
+ // { ok: false, error: 'expired', attemptsLeft: 0, locked: false, message }
1070
+ // -> offer a new code.
1071
+ ```
1072
+
1073
+ **Changed in 0.51:** an app or recovery code with `attemptsLeft: 0` used to
1074
+ answer `invalid` with `locked: true`; it now answers `expired` with
1075
+ `locked: false`. `locked` stays in the types, always `false`, and the `locked`
1076
+ wording and the `via` option of `confirm` are no longer read.
1077
+
1078
+ `stepUp.isStepUpRequired(error)` is true for the API's `STEP_UP_REQUIRED`
1079
+ refusal of a sensitive mutation, so an action can answer the page with the
1080
+ request for a challenge instead of the error page.
1081
+
1082
+ ### The codes it tells apart
1083
+
1084
+ `codes` takes `invalidCode` (`'CODE_INVALID'`), `challengeOver` (the table's
1085
+ codes that end a challenge; passing a list replaces it), `stepUpRequired`
1086
+ (`'STEP_UP_REQUIRED'`) and `mailThrottled` (`'MAIL_THROTTLED'`).
1087
+ `STEP_UP_OVER` is `[...CHALLENGE_OVER, …]`, so a list that adds a code of its
1088
+ own can spread either. `invalidCode` in `challengeOver` is a
1089
+ [`TypeError`](../troubleshooting.md#typeerror-stepupsteps-the-code--is-both-the-wrong-code-code-codesinvalidcode-and-in-codeschallengeover-a-wrong-code-that-leaves-tries-cannot-end-the-challenge).
1090
+
1091
+ ### Call the step-up with a caller that does not sign out on a 401
1092
+
1093
+ `@softistx/janus-graphql` answers a wrong code (`CODE_INVALID`) with HTTP 401. A
1094
+ caller that treats every 401 as "the session is dead" and redirects to the
1095
+ sign-in page would sign the user out on the first typo. Make the caller of the
1096
+ step-up's two operations leave a 401 alone, or have it redirect only when the
1097
+ error's code is `UNAUTHENTICATED`. This applies when `onSignedOut` is unset;
1098
+ with `onSignedOut: 'sign-in'`, `route()` does it
1099
+ ([a signed-out user](#step-up)).
1100
+
1101
+ ### The state on the page
1102
+
1103
+ A step-up asks for a code before a sensitive action. `stepUpReducer` holds
1104
+ its state on the page, with no React: `phase` (`idle`, `requesting`, `code`,
1105
+ `confirming`, `done`), the `via` that confirms it (`email` or
1106
+ `secondFactor`), the `challenge` held, `attemptsLeft`, `locked`, `error`
1107
+ (`invalid`, `expired`, `failed` or `throttled`), `message` (the last refusal
1108
+ worded for the page), `retryAfter` (a throttle's seconds, from a request or a code), `pending` and
1109
+ `resent`. `start`, `submit`, an accepted answer and `release` clear `message`
1110
+ and `retryAfter`.
1111
+
1112
+ `stepUpProps(state)` gives the part a code form shows (not the challenge, a
1113
+ secret that stays out of the markup, and not `message`: the dialog words its
1114
+ own texts from `error`, `attemptsLeft`, `locked` and `retryAfter`):
1115
+
1116
+ ```ts
1117
+ import {
1118
+ INITIAL_STEP_UP,
1119
+ stepUpProps,
1120
+ stepUpReducer,
1121
+ } from '@softistx/alxia-react-router/session/model';
1122
+
1123
+ let state = stepUpReducer(INITIAL_STEP_UP, { type: 'start' });
1124
+ state = stepUpReducer(state, {
1125
+ type: 'requested',
1126
+ answer: {
1127
+ ok: true,
1128
+ intent: 'request-step-up',
1129
+ challenge: 'c1',
1130
+ via: 'secondFactor',
1131
+ },
1132
+ });
1133
+ state = stepUpReducer(state, {
1134
+ type: 'confirmed',
1135
+ answer: {
1136
+ ok: false,
1137
+ intent: 'confirm-step-up',
1138
+ error: 'expired',
1139
+ attemptsLeft: 0,
1140
+ locked: false,
1141
+ },
1142
+ });
1143
+
1144
+ stepUpProps(state);
1145
+ // { via: 'secondFactor', attemptsLeft: 0, locked: false, error: 'expired', pending: false, resent: false }
1146
+ // A throttled request or code (a 429) adds `error: 'throttled'` and `retryAfter` (seconds) when the API said how long:
1147
+ // the challenge and its tries stay, and `VerificationCode` makes Resend wait without locking.
1148
+ ```
1149
+
1150
+ With no try left the challenge is over (`error: 'expired'`: ask for a new
1151
+ one), for a mailed, an app or a recovery code. A code refused with
1152
+ `reason: 'throttled'` is `error: 'throttled'` with `retryAfter`: the
1153
+ challenge stays, the form says to wait.
1154
+
1155
+ ## Social sign-in
1156
+
1157
+ A BFF that offers "Sign in with Google" needs two routes: one that sends the
1158
+ browser to the provider, and one the provider calls back. `socialRoutes` writes
1159
+ both. The GraphQL calls (`socialSignInStart`, `socialSignInComplete`) stay the
1160
+ app's, since the app owns its API client and the session cookie it keeps the
1161
+ API's token in (a janus `Set-Cookie` cannot be relayed to the browser).
1162
+
1163
+ ```ts
1164
+ // app/social.server.ts
1165
+ import { socialRoutes } from '@softistx/alxia-react-router/session';
1166
+ import { cookies } from './session.server';
1167
+
1168
+ // The app's own: its caller context and its GraphQL client.
1169
+ declare const apiOf: (context: AppContext | undefined) => {
1170
+ socialSignInStart(input: {
1171
+ provider: string;
1172
+ returnTo: string;
1173
+ }): Promise<{ url: string; flow: string }>;
1174
+ socialSignInComplete(input: {
1175
+ provider: string;
1176
+ callbackUrl: string;
1177
+ flow: string;
1178
+ }): Promise<
1179
+ | { kind: 'session'; token: string; expiresAt: string }
1180
+ | { kind: 'secondFactor'; challenge: string }
1181
+ | { kind: 'error'; code: string }
1182
+ >;
1183
+ };
1184
+ interface AppContext {
1185
+ readonly user?: string;
1186
+ }
1187
+
1188
+ export const social = socialRoutes<AppContext, 'google' | 'github'>({
1189
+ providers: ['google', 'github'],
1190
+ flowCookie: { secure: !import.meta.env.DEV },
1191
+ start: (provider, { returnTo, context }) =>
1192
+ apiOf(context).socialSignInStart({ provider, returnTo }),
1193
+ complete: ({ provider, callbackUrl, flow }, { context }) =>
1194
+ apiOf(context).socialSignInComplete({ provider, callbackUrl, flow }),
1195
+ cookies,
1196
+ });
1197
+ ```
1198
+
1199
+ `complete` needs no code to keep the visitor's `?next`: the path `start` kept
1200
+ is the default landing of a `session` or `secondFactor` outcome that sets no
1201
+ `returnTo` of its own. To read it anyway, it is in the second argument:
1202
+
1203
+ ```ts no-check
1204
+ complete: ({ provider, callbackUrl, flow }, { context, returnTo }) => /* … */,
1205
+ ```
1206
+
1207
+ ```ts
1208
+ // app/routes/auth.$provider.tsx
1209
+ export const loader = social.start;
1210
+ // app/routes/auth.$provider.callback.tsx
1211
+ export const loader = social.callback;
1212
+ ```
1213
+
1214
+ - `start` answers a 404 for a provider that is not in `providers`. It passes
1215
+ the request's `?next` (checked with `safeNext`, `/` otherwise) as
1216
+ `returnTo`, keeps the `flow` token in an `HttpOnly; SameSite=Lax` cookie
1217
+ (`social_flow`, `__Secure-` when `secure`, `Path=/auth`, 600 s) and redirects
1218
+ to `url`. When that `returnTo` is not `/`, it is kept with the token in the
1219
+ same flow cookie (no second cookie), so the callback can use it.
1220
+ - `callback` reads that cookie (none: the sign-in page with
1221
+ `?error=flow_missing`, and the API is not called), gives `complete` the full
1222
+ callback URL and the kept `returnTo` (`complete(input, { request, context,
1223
+ returnTo })`; `/` when there was none or the cookie was written by an older
1224
+ version), and clears the cookie on every outcome it lands. `complete`
1225
+ answers one of: `{ kind: 'session', token, expiresAt, returnTo? }` (the
1226
+ session cookie is written and any challenge cookie cleared, then a redirect
1227
+ to `returnTo`, checked; with none of its own, the kept `returnTo`),
1228
+ `{ kind: 'secondFactor', challenge, expiresAt?, returnTo? }` (the challenge
1229
+ cookie is written, then a redirect to `/sign-in/second-factor?next=…`, with
1230
+ the kept `returnTo` when the outcome has none; `?next` is left out when
1231
+ `returnTo` is `/`)
1232
+ or `{ kind: 'error', code, params? }` (a redirect to `/sign-in?error=<code>`;
1233
+ `params`, such as the wait of a throttled callback, are added as query
1234
+ parameters: `params: { minutes: 5, retryAfter: 300 }` lands on
1235
+ `/sign-in?error=<code>&minutes=5&retryAfter=300`, so the page can word the
1236
+ wait; `undefined` values and a key equal to `errorParam` or `socialParam` are left out).
1237
+ A session with no token or an end that is missing, unreadable or past, a
1238
+ second factor with an empty challenge, and a second factor when `cookies`
1239
+ has no challenge helpers, are each an error outcome with the code
1240
+ `invalid_session` (`invalidSessionCode` changes it).
1241
+
1242
+ ```ts
1243
+ // complete: the API answered 429 with a wait of 5 minutes
1244
+ return { kind: 'error', code: 'auth.errors.too-many-attempts', params: { minutes: 5, retryAfter: 300 } };
1245
+ // landing: /sign-in?error=auth.errors.too-many-attempts&minutes=5&retryAfter=300
1246
+ const minutes = Number(new URL(request.url).searchParams.get('minutes'));
1247
+ ```
1248
+ - The state check is the API's: a flow token that does not match the callback's
1249
+ `state` comes back as an error outcome. A `complete` that throws (the API is
1250
+ unreachable) is not caught: the route's error boundary answers, and the flow
1251
+ cookie is left to expire after its 600 s.
1252
+ - `paths: { base, signIn, secondFactor, linked }`, `errorParam`, `socialParam`, `missingFlowCode` and `crossSiteCode` (`'social_cross_site'` by default)
1253
+ change the defaults (`signIn` is `/sign-in` and `secondFactor` is
1254
+ `/sign-in/second-factor`); each path must be a path of this site (a
1255
+ `TypeError` otherwise). `flowCookie.name` must be an RFC 6265 token with no
1256
+ `__Secure-` or `__Host-` prefix and `flowCookie.seconds` a finite number
1257
+ above 0, or `socialRoutes()` throws a `TypeError`.
1258
+ - **Both routes must live under `paths.base`** (`/auth` by default): the flow
1259
+ cookie's `Path` is that prefix, so a route elsewhere never receives it and
1260
+ the callback answers `flow_missing`.
1261
+ - **GET callbacks only.** A provider that answers with a cross-site `POST`
1262
+ (`response_mode=form_post`, as Apple does) is not supported: a `Lax` cookie is
1263
+ not sent on a cross-site POST, so the flow cookie would be missing.
1264
+ - A `sameSite: 'strict'` session cookie is not sent on the request that follows
1265
+ the provider's redirect chain, so the page the callback lands on can look
1266
+ signed out until the next navigation. Keep `lax` for a social sign-in.
1267
+ - A social sign-in over a browser that already holds a session writes the new
1268
+ cookie but does not revoke the old API session: it ends when it expires.
1269
+ Revoke it in `complete` (the request's cookie is on `request`) if that matters.
1270
+
1271
+ ### Linking a provider
1272
+
1273
+ A signed-in user can attach another provider to the account. Give
1274
+ `socialRoutes()` a `linkStart`, the link twin of `start`, and mount its `link`
1275
+ loader under the same `paths.base` (the flow cookie's `Path`):
1276
+
1277
+ ```ts
1278
+ // app/social.server.ts, added to the socialRoutes({ … }) options
1279
+ linkStart: async (provider, { request, context, returnTo }) => {
1280
+ const viewer = await viewerOf(request, context);
1281
+ // The app refuses a caller with no session: throw a redirect (or a Response).
1282
+ if (!viewer) throw redirect(`/sign-in?next=${encodeURIComponent(returnTo)}`);
1283
+ return apiOf(context).socialLinkStart({ provider, returnTo });
1284
+ },
1285
+ complete: async ({ provider, callbackUrl, flow }, { context, kind }) => {
1286
+ const api = apiOf(context);
1287
+ if (kind === 'link') {
1288
+ const r = await api.socialLinkComplete({ provider, callbackUrl, flow });
1289
+ return r.ok ? { kind: 'linked' } : { kind: 'error', code: r.code };
1290
+ }
1291
+ return api.socialSignInComplete({ provider, callbackUrl, flow });
1292
+ },
1293
+ paths: { linked: '/account' },
1294
+ ```
1295
+
1296
+ ```ts no-check
1297
+ // app/routes/auth.$provider.link.tsx
1298
+ export const loader = social.link;
1299
+ ```
1300
+
1301
+ - `link` is served like `start` (`/auth/:provider/link?next=/account`): same
1302
+ 404 for an unknown provider, same checked `?next`, same flow cookie
1303
+ attributes. It is a 404 when `linkStart` is not given. The cookie records the
1304
+ kind as `r2.l.<base64url path>.<flow>`; a cookie from `start` (`r1.…` or the
1305
+ bare token) stays a sign-in, and a malformed `r2` value is read as a sign-in
1306
+ whose flow token is the value whole.
1307
+ - The same `callback` serves both flows; `complete` is told the `kind`
1308
+ (`'signIn'` or `'link'`) beside `returnTo`.
1309
+ - `{ kind: 'linked', returnTo? }` opens no session and clears the flow cookie.
1310
+ It lands on the outcome's `returnTo`, else the kept one when it is not `/`,
1311
+ else `paths.linked` (`/` by default), checked by `safeNext`, with
1312
+ `?social=linked` added (`socialParam` renames the parameter; an existing
1313
+ query and fragment are kept).
1314
+ - An `error` outcome of a link flow follows the same rule (the kept
1315
+ `returnTo` when not `/`, else `paths.linked`) with `?error=<code>`
1316
+ (`errorParam`), not the sign-in page, and carries the outcome's `params` the
1317
+ same way (`?error=<code>&minutes=5`). A `session` or `secondFactor` outcome in
1318
+ a link flow, and a `linked` outcome in a sign-in flow, are errors with the
1319
+ `invalid_session` code (`invalidSessionCode`); no cookie is written for them.
1320
+ - An expired or missing flow cookie during a link has no kind to read: it
1321
+ lands on `/sign-in?error=flow_missing`, as for a sign-in.
1322
+ - **`link` refuses a request from another site.** The session cookie is
1323
+ `SameSite=Lax`, so a cross-site top-level navigation to the link URL would
1324
+ carry it. `link` reads `Sec-Fetch-Site` first (after the provider check, before
1325
+ `linkStart`): `same-origin` and `none` (a typed URL or a bookmark) go on, and
1326
+ any other value (`cross-site`, `same-site`…; a sibling subdomain is another
1327
+ origin) is refused. The refusal calls nothing, writes no cookie and lands
1328
+ where a link error lands (the kept `?next`, else `paths.linked`, `/` by
1329
+ default) with `?error=social_cross_site` (`crossSiteCode` renames it). With
1330
+ no header (Safari before 16.4, old browsers) the guard cannot tell, so the
1331
+ link goes on and only the `SameSite=Lax` cookie protects it. `start` is not
1332
+ guarded: it signs nobody in without the provider's own consent and changes
1333
+ nothing for an existing account. The landing page maps the code to a message
1334
+ like any other `?error=` code (`errorParam`):
1335
+
1336
+ ```ts
1337
+ const MESSAGES: Record<string, string> = {
1338
+ social_cross_site: 'Start linking from your account page.',
1339
+ ALREADY_LINKED: 'This provider is already linked.',
1340
+ };
1341
+ export function loader({ request }: Route.LoaderArgs) {
1342
+ const code = new URL(request.url).searchParams.get('error');
1343
+ return { error: code ? (MESSAGES[code] ?? 'Linking failed.') : null };
1344
+ }
1345
+ ```
1346
+ - **The session check is the app's.** `linkStart` runs for anyone who opens the
1347
+ URL. The API's link start refuses a guest or a stale proof (a fresh proof is
1348
+ required to link), so catch that in `linkStart` and throw the sign-in or
1349
+ step-up redirect.
1350
+ - **`kind` comes from a cookie the visitor can edit.** It only picks the
1351
+ landing; the API must bind the flow to its kind and its user, as the flow
1352
+ token of a janus `social.link` does.
1353
+ - Start a link from a confirming button (a form `POST` to a route that
1354
+ redirects to `link`) rather than a bare link, so a page cannot start it for a
1355
+ visitor by an image or a redirect.
1356
+
1357
+ ## Pages a mail's link opens
1358
+
1359
+ A magic link, a password reset or an invitation opens a page whose URL
1360
+ carries a token. `authLinks` is the server side of those pages, built once
1361
+ beside the app's `signInFlow`:
1362
+
1363
+ ```ts
1364
+ // app/links.server.ts
1365
+ import { authLinks } from '@softistx/alxia-react-router/session';
1366
+ import { signIn } from './session.server';
1367
+
1368
+ export const links = authLinks({
1369
+ // The app's signInFlow: the links use its cookies, its errors and its json
1370
+ // (every body is read with the same CSRF check).
1371
+ signIn,
1372
+ start: async (token) => (await homeOf(token)) ?? '/', // optional
1373
+ });
1374
+ ```
1375
+
1376
+ `homeOf`, `viewerOf`, `confirmMagicLink` and `toAnswer` below are the app's
1377
+ own: its GraphQL calls and its mapping of the API's enums to a `SignInAnswer`.
1378
+ `ConfirmArgs` is any Standard Schema; a Zod 4 stub:
1379
+
1380
+ ```ts
1381
+ import { z } from 'zod';
1382
+
1383
+ const ConfirmArgs = z.object({ token: z.string().max(200) });
1384
+ ```
1385
+
1386
+ ```tsx
1387
+ // app/routes/auth/magic-link.tsx
1388
+ import { data } from 'react-router';
1389
+ import { TOKEN_PAGE_HEADERS } from '@softistx/alxia-react-router/session';
1390
+
1391
+ const PATH = '/auth/magic-link';
1392
+
1393
+ export const headers = () => TOKEN_PAGE_HEADERS;
1394
+
1395
+ export async function loader({ request }: Route.LoaderArgs) {
1396
+ // Spends nothing: a mail scanner opens links first.
1397
+ return data({ signedInAs: (await viewerOf(request))?.name ?? null }, { headers: TOKEN_PAGE_HEADERS });
1398
+ }
1399
+
1400
+ export async function action({ request }: Route.ActionArgs) {
1401
+ const { token } = await links.linkArgs(ConfirmArgs, request, PATH);
1402
+ const spent = await links.spendToken(() => confirmMagicLink(token), {
1403
+ request,
1404
+ language: 'en',
1405
+ path: PATH,
1406
+ states: { 'auth.errors.invalid-token': 'invalid' },
1407
+ });
1408
+ if (!spent.ok) return links.answerOf(spent);
1409
+ return links.landByLink(toAnswer(spent.value), {
1410
+ request,
1411
+ language: 'en',
1412
+ // The API's LINKED opens no session: end on the page's `linked` state.
1413
+ other: { path: PATH, state: 'linked' },
1414
+ });
1415
+ }
1416
+ ```
1417
+
1418
+ Asking for the mail, and the reset's last step:
1419
+
1420
+ ```ts
1421
+ // app/routes/auth/sign-in-link.tsx
1422
+ export async function action({ request }: Route.ActionArgs) {
1423
+ json.requireJsonPost(request); // a native post goes back to its page
1424
+ const { email } = await json.readInput(request, EmailArgs);
1425
+ return links.requestLink(() => requestMagicLink(email), {
1426
+ request,
1427
+ language: 'en',
1428
+ });
1429
+ }
1430
+
1431
+ // app/routes/auth/reset-password.tsx, once the new password is set
1432
+ export async function action({ request }: Route.ActionArgs) {
1433
+ // ... linkArgs, spendToken ...
1434
+ return links.afterReset(request); // to /sign-in?password-reset=1
1435
+ }
1436
+ ```
1437
+
1438
+ - `TOKEN_PAGE_HEADERS` is `Referrer-Policy: no-referrer` and
1439
+ `X-Robots-Tag: noindex, nofollow`: no `Referer` carries the token to another
1440
+ site (a font, an image), and no search engine keeps the page. Set them on
1441
+ the page's document and its `.data` responses. The redirects of `ended`,
1442
+ `landByLink` and `afterReset` carry them already.
1443
+ - `linkArgs(schema, request, path)` first refuses a post that is not a
1444
+ same-site JSON one (a form posted before hydration goes back to its page, a
1445
+ cross-site post is a 403), reads the request as JSON with `json.readJson`
1446
+ and checks it against any Standard Schema
1447
+ (Zod 4, Valibot, ArkType; async is fine). An issue on `token` (missing, or
1448
+ over the API's limit: a link cut or padded on its way) throws the redirect
1449
+ to the `invalid` end state, as an unknown token does; any other issue throws
1450
+ a 400. `invalidState` names another state.
1451
+ - `spendToken(run, { request, language, path, states, fields })` runs the API
1452
+ call that spends the token, after the same guard on `request`. It returns `{ ok: true, value }`, or what the page answers:
1453
+ an API code in `states` ends the page on that state (the redirect replaces
1454
+ the token's history entry); refused `fields` stay under the form fields the
1455
+ page shows; a wait (`codes.mailThrottled`, one code or a list, as for
1456
+ `requestLink`) stays on the page as a 429 whose refusal carries
1457
+ `throttled: true` and `retryAfter` (the seconds, when the API gives them), so
1458
+ `useLinkPost()` can count it down; any other refusal or an unreachable API is
1459
+ the form's message with the API's status. `answerOf(spent)` turns the
1460
+ refusal into the action's answer, `retryAfter` included. Anything that is not an API refusal is rethrown.
1461
+ - `statePath(path, state)` is `path?state=…`: the token page in an end state,
1462
+ with no token. `ended(path, state, headers?)` is the redirect to it, replacing
1463
+ the token's history entry (React Router's `replace`), so Back never opens
1464
+ the token's URL again.
1465
+ - `landByLink(answer, { request, language, other? })` signs the link in. The
1466
+ session the browser held, whoever's, is revoked first (one browser holds one
1467
+ session), on a `secondFactor` answer as well as a `signedIn` one. A signed-in
1468
+ answer whose session is still live goes to `start(token, request)`'s path
1469
+ (`/` when `start` is missing, throws, or answers a path off the site), so the
1470
+ redirect lands at once instead of pushing a history entry after `/`'s own
1471
+ redirect. An answer that leads nowhere (a session already ended included)
1472
+ is the form's `unavailable` with a 503. An `other` answer is one too, unless
1473
+ `other: { path, state }` is given: an app whose API can answer "linked" (no
1474
+ session opened) passes the page and its state, and the answer ends there,
1475
+ keeping the browser's session.
1476
+ - `afterReset(request)` follows a password reset, which signs the account out
1477
+ everywhere: the browser's session is revoked and its session cookie, its
1478
+ challenge cookie and the flow's `clear()` cookies are cleared, then
1479
+ the page replaces the token's entry with `resetDone` (`/sign-in?password-reset=1`
1480
+ by default).
1481
+ - `requestLink(run, { request, language })` requests the mail. It answers
1482
+ `{ sent: true }` whoever the address is, so the page does not tell which
1483
+ addresses hold an account (`RequestLinkAnswer` is its shape). A wait is a
1484
+ 429 with the `formError`, `throttled: true` and, when the API gave the
1485
+ seconds, a typed `retryAfter` beside it; a malformed address is the `email` field's refusal.
1486
+
1487
+ `linkArgs`, `spendToken`, `landByLink`, `afterReset` and `requestLink` first
1488
+ refuse a post that is not a same-site JSON one: the redirect a native form
1489
+ post gets goes back to its page, which then posts JSON, and a JSON post from
1490
+ another site is a 403, before anything is read, spent, revoked or landed.
1491
+
1492
+ The wait is recognised by the app's own throttle code, so pass it, as the
1493
+ step-up's `codes` and `wording` do (`AuthLinksCodes` is the type of `codes`).
1494
+ `wording` words every refusal of `requestLink` that is not a field's, the
1495
+ wait included; returning `undefined` keeps `errors`' words:
1496
+
1497
+ ```ts
1498
+ authLinks({
1499
+ signIn,
1500
+ codes: { mailThrottled: 'auth.errors.too-many-attempts' }, // 'MAIL_THROTTLED' by default
1501
+ wording: (error, language) => waitMessage(error, language), // else the catalogue's
1502
+ });
1503
+ ```
1504
+
1505
+ An API that refuses with several 429 codes (per address, per e-mail) gets a
1506
+ countdown on each: `mailThrottled` takes a list, and every listed code
1507
+ exposes its `retryAfter` to the page. The single string keeps working:
1508
+
1509
+ ```ts
1510
+ authLinks({
1511
+ signIn,
1512
+ codes: { mailThrottled: ['auth.errors.address-throttled', 'auth.errors.mail-throttled'] },
1513
+ });
1514
+ ```
1515
+
1516
+ A token is never logged, worded in an error or put in a redirect built by the
1517
+ helpers: the end states and the sign-in's redirects carry a state or a path
1518
+ alone, and a `TypeError` about a path prints it only up to its `?` or `#`.
1519
+ `statePath`, `ended`, `linkArgs` and `spendToken` throw that `TypeError` for a
1520
+ page `path` with a query, a fragment or a host (naming the call), and
1521
+ `authLinks` throws one for a `resetDone` that leaves the site.
1522
+
1523
+ One redirect does carry the page's URL as it was: the native post (a form
1524
+ submitted before hydration) that `linkArgs`, `landByLink`, `afterReset`,
1525
+ `requestLink` and `spendToken` send back to the token page itself. It is
1526
+ harmless because it goes only to the URL the browser already holds, on this
1527
+ site, as a GET that spends nothing; the token is no further from the user than
1528
+ it was in the address bar, and the page's `TOKEN_PAGE_HEADERS` still keep it
1529
+ out of any `Referer`.
1530
+
1531
+ ### A page that posts with `fetch`
1532
+
1533
+ A link route's redirects (an end state, a refused token) are 302s: `fetch`
1534
+ follows them and reads the next page, so a promise-based form (material's
1535
+ `EmailRequestForm`, `NewPasswordForm`) would show a success. Wrap the action
1536
+ in `handingOver`: for a request that carries the `X-Alxia-Link: json` header
1537
+ (`postLinkArgs` sends it), every redirect, returned or thrown (`linkArgs`
1538
+ throws a 302 for a code the schema refuses), becomes a 200
1539
+ `{ redirect: location }` with its other headers (the cookies) kept, and
1540
+ `replace: true` when the redirect replaces the history entry (the token's).
1541
+ A native form post or a `<Form>` has no header, so it keeps its redirect.
1542
+ `handOver(response)` does the swap for one response, whatever the request.
1543
+ Other answers pass through.
1544
+
1545
+ The route must be a resource route (a module with an `action` and no default
1546
+ export), at a path of its own: `/forgot/submit` beside the `/forgot` page,
1547
+ `/reset/submit` beside `/reset`. On a route that has a component, React
1548
+ Router answers a `fetch` POST with the page's HTML and the action's data
1549
+ inside it, which the page cannot read as JSON; the form would show its
1550
+ "unreachable" message. Keep the page's own path (`/reset`) as the `path` of
1551
+ `linkArgs` and `spendToken`, so the end states and the sign-in still land on
1552
+ the page. The `reset` loader forwards the query because a post made before
1553
+ hydration is sent back with its `?token=...`. To keep a flat-route file
1554
+ name from nesting under `forgot.tsx` / `reset.tsx`, name the files
1555
+ `forgot_.submit.ts` / `reset_.submit.ts`.
1556
+
1557
+ A post that is not JSON (a form submitted before the page hydrated) is
1558
+ redirected by the helpers to the URL it was posted to, which is now the
1559
+ resource route. Give the route a `loader` that sends that GET back to the
1560
+ page, or let the form post only after hydration.
1561
+
1562
+ ```ts
1563
+ import { handingOver } from '@softistx/alxia-react-router/session';
1564
+ import { redirect } from 'react-router';
1565
+ import { z } from 'zod';
1566
+
1567
+ // app/routes/forgot_.submit.ts: the request for the mail
1568
+ export const loader = () => redirect('/forgot');
1569
+ export const action = handingOver(async ({ request }: { request: Request }) =>
1570
+ links.requestLink(() => sendResetMail(request), { request, language: 'en' }),
1571
+ );
1572
+
1573
+ // app/routes/reset_.submit.ts: the new password, a token spent
1574
+ const schema = z.object({
1575
+ token: z.string().min(1).max(200),
1576
+ password: z.string().min(8),
1577
+ });
1578
+ export const loader = ({ request }: { request: Request }) =>
1579
+ redirect('/reset' + new URL(request.url).search);
1580
+ export const action = handingOver(async ({ request }: { request: Request }) => {
1581
+ const { token, password } = await links.linkArgs(schema, request, '/reset');
1582
+ const spent = await links.spendToken(() => resetPassword(token, password), {
1583
+ request,
1584
+ language: 'en',
1585
+ path: '/reset',
1586
+ fields: ['password'],
1587
+ states: { 'auth.errors.invalid-token': 'invalid' },
1588
+ });
1589
+ return spent.ok ? links.afterReset(request) : links.answerOf(spent);
1590
+ });
1591
+ ```
1592
+
1593
+ On the page, `postLinkRequest(path, email, options?)` and
1594
+ `postLinkArgs(path, body, fields, options?)`, from
1595
+ `@softistx/alxia-react-router/session/model` (a module that pulls in no other module
1596
+ and is safe in a component), post the JSON and return what the form's
1597
+ `onSubmit` takes: `undefined` when the answer is accepted (`sent`) or a
1598
+ `{ redirect }` is followed, else `{ form, retryAfter, ...fields }`, `fields`
1599
+ naming the `fieldErrors` to carry over. A refused answer (status 400 and up)
1600
+ is never followed. `postLinkRequest` posts `{ input: { email } }` and carries
1601
+ `email`. The options:
1602
+
1603
+ - `fetch`: the `fetch` to use, the global one by default.
1604
+ - `navigate(location, { replace })`: where a `{ redirect }` leads;
1605
+ `location.assign`, or `location.replace` when the answer says `replace`.
1606
+ - `unreachable`: the form's message for a failed call or an answer with no
1607
+ shape, in the app's language (English by default); it is never a success.
1608
+
1609
+ ```ts
1610
+ import { postLinkArgs, postLinkRequest } from '@softistx/alxia-react-router/session/model';
1611
+
1612
+ export const onRequest = (email: string) =>
1613
+ postLinkRequest('/forgot/submit', email, { unreachable: 'Une erreur est survenue.' });
1614
+ export const onReset = (token: string, password: string) =>
1615
+ postLinkArgs('/reset/submit', { token, password }, ['password']);
1616
+ ```
1617
+
1618
+ ## The page's hooks
1619
+
1620
+ `@softistx/alxia-react-router/session/react` holds the client pieces every app
1621
+ writes around the flows above. It imports `react` and `react-router` (peers
1622
+ the package already has) and nothing else; every hook renders on the server.
1623
+
1624
+ ### `useSignOut`
1625
+
1626
+ Posts `{}` (or `{ next }`, below) as JSON to the sign-out route (the one `signIn.signOut` serves; JSON
1627
+ and same-origin only), wherever the control is. `busy` is true from the call
1628
+ until the navigation it starts has ended, so the button can show it.
1629
+
1630
+ ```tsx
1631
+ import { useSignOut } from '@softistx/alxia-react-router/session/react';
1632
+
1633
+ export function SignOutButton() {
1634
+ const { signOut, busy } = useSignOut();
1635
+ return (
1636
+ <button type="button" onClick={signOut} disabled={busy}>
1637
+ {busy ? 'Signing out…' : 'Sign out'}
1638
+ </button>
1639
+ );
1640
+ }
1641
+ ```
1642
+
1643
+ Options: `action` (the route, default `/sign-out`), `before`, run before the
1644
+ post, for what must be gone from a shared device first, and `next`. A `before`
1645
+ that throws or rejects never keeps the user signed in: the sign-out goes on.
1646
+
1647
+ `next` is the path to come back to: a page that asks the user to sign in again
1648
+ ends the session with `useSignOut({ next })`, or `signOut({ next })` per call
1649
+ (the call's wins), and after signing in the user lands on that path. It is
1650
+ posted as `{ next }` (a path that leaves the site is not posted, the body stays
1651
+ `{}`), and the sign-out action carries it to the sign-in page as `?next=`,
1652
+ through `safeNext` again. Without it nothing changes.
1653
+
1654
+ ```tsx
1655
+ const { signOut } = useSignOut();
1656
+ // …
1657
+ signOut({ next: location.pathname + location.search });
1658
+ ```
1659
+
1660
+ ```tsx
1661
+ const { signOut } = useSignOut({
1662
+ action: '/account/sign-out',
1663
+ before: () => caches.keys().then((keys) => Promise.all(keys.map((k) => caches.delete(k)))),
1664
+ });
1665
+ ```
1666
+
1667
+ ### `useLinkParam`
1668
+
1669
+ Reads the query parameter a mail's link carries, once: the first render's value
1670
+ is kept for the page's life (unless `live: true`, below). With `drop: true` the parameter is then removed
1671
+ from the address bar (`history.replaceState`, keeping the history state and the
1672
+ hash), so a token is not left in the history, a bookmark or a screenshot. It is
1673
+ `null` when the parameter is absent or empty.
1674
+
1675
+ ```tsx
1676
+ import { useLinkParam } from '@softistx/alxia-react-router/session/react';
1677
+
1678
+ export default function ResetPassword() {
1679
+ const token = useLinkParam('token', { drop: true });
1680
+ if (!token) return <p>This link is not valid. Ask for a new one.</p>;
1681
+ return (
1682
+ <form method="post">
1683
+ <input type="hidden" name="token" value={token} />
1684
+ <input type="password" name="password" autoComplete="new-password" />
1685
+ <button type="submit">Choose a new password</button>
1686
+ </form>
1687
+ );
1688
+ }
1689
+ ```
1690
+
1691
+ The router's own location is not updated by `replaceState`: a loader or
1692
+ `useSearchParams` elsewhere still sees the token until the next navigation.
1693
+ Read it with the hook once, and pass it down.
1694
+
1695
+ #### `live: true`: a parameter set after the page mounted
1696
+
1697
+ By default the value is read once. A route that stays mounted while an action
1698
+ redirects back to it with a new parameter (`/settings` to
1699
+ `/settings?state=linked`) never sees it. `live: true` follows the URL: the
1700
+ value is the parameter of the current location, and each new location is read
1701
+ again.
1702
+
1703
+ ```tsx
1704
+ const state = useLinkParam('state', { live: true }); // 'linked' | 'invalid' | null
1705
+ ```
1706
+
1707
+ With `drop: true` too, the value is kept after the address bar loses the
1708
+ parameter, until a location carries a new one: a navigation that has no such
1709
+ parameter does not clear it, since the drop removed it. Without `drop` the
1710
+ value is exactly the current location's parameter, `null` when it is gone.
1711
+
1712
+ ### `useLinkFragment`
1713
+
1714
+ The fragment twin of `useLinkParam`, for a mail link whose secret travels after
1715
+ the `#` (`/invitations/accept#<code>`): a fragment never reaches a server, a
1716
+ log or a `Referer`. It returns the decoded fragment, read once.
1717
+
1718
+ - `undefined` until the page has hydrated and read it (the server render and
1719
+ the first client render agree, so there is no mismatch), then the code, or
1720
+ `null` when the fragment is absent or empty. Render a neutral state while it
1721
+ is `undefined`, not "invalid link".
1722
+ - `drop: true` removes the fragment from the address bar
1723
+ (`history.replaceState`, keeping the history state, the path and the query),
1724
+ so the code stays out of the history, a copied address and a screenshot.
1725
+ - The value is kept across React Strict Mode's second effect run, which would
1726
+ find the fragment already gone.
1727
+
1728
+ ```tsx
1729
+ import { useLinkFragment } from '@softistx/alxia-react-router/session/react';
1730
+
1731
+ export default function AcceptInvitation() {
1732
+ const code = useLinkFragment({ drop: true });
1733
+ if (code === undefined) return <p>Loading...</p>;
1734
+ if (code === null) return <p>This link is not valid. Ask for a new one.</p>;
1735
+ return (
1736
+ <form method="post">
1737
+ <input type="hidden" name="code" value={code} />
1738
+ <button type="submit">Join</button>
1739
+ </form>
1740
+ );
1741
+ }
1742
+ ```
1743
+
1744
+ As with `useLinkParam`, the router's own location is not updated by
1745
+ `replaceState`. A fragment is only readable in the browser: a loader cannot
1746
+ see it.
1747
+
1748
+ ### `useLinkPost`
1749
+
1750
+ Posts JSON to the page's own action and resolves the refusal a sign-in or
1751
+ link form takes, so a page does not repeat the `useJsonFetcher` +
1752
+ `useFetcherPromise` glue. `send(body)` resolves `{ form?, retryAfter?, email? }`
1753
+ built from the answer's `formError`, `retryAfter` and `fieldErrors.email`, or
1754
+ `undefined` when nothing was refused or a navigation aborted the post (a
1755
+ `FetcherPromiseAborted`); any other failure rejects. `busy` is true while the
1756
+ post is in flight. `refusalOf(answer)` is the pure mapping, for an answer you
1757
+ already hold.
1758
+
1759
+ The post goes to the page's own action unless you name another route's:
1760
+ `useLinkPost({ action: '/auth/resend' })` fixes the target for the hook (a
1761
+ banner rendered on every page, posting to one resource route), and
1762
+ `send(body, { action })` overrides it for one call, as `useJsonFetcher`'s
1763
+ `post(body, to)` does. The resource route answers `formError`, `retryAfter` or
1764
+ `fieldErrors.email` like any link action.
1765
+
1766
+ ```tsx
1767
+ import { useLinkPost } from '@softistx/alxia-react-router/session/react';
1768
+
1769
+ export default function Confirm() {
1770
+ const { send, busy } = useLinkPost();
1771
+ const confirm = async (link: string) => {
1772
+ const refusal = await send({ link });
1773
+ if (refusal) setRefusal(refusal); // { form: 'Link expired', retryAfter: 30 }
1774
+ };
1775
+ // <ConfirmLink busy={busy} onConfirm={() => confirm(link)} />
1776
+ }
1777
+ ```
1778
+
1779
+ ### `useCodeField` and `useOnRefusal`
1780
+
1781
+ A form that asks for one code (an authenticator app's, a recovery code) and
1782
+ whose action answers a refusal object when the code is wrong: on each new
1783
+ refusal the refused code goes and the field takes focus, for the next try. A
1784
+ refusal already there when the component mounted is the page's own and is
1785
+ ignored.
1786
+
1787
+ `useCodeField(schema, refusal)` needs no form library. `schema` is any
1788
+ [Standard Schema](https://standardschema.dev) (Zod, Valibot, ArkType; a
1789
+ synchronous one). It returns `code`, `setCode`, `ref` (put it on the input),
1790
+ `error` (the first message of the last `check()`, cleared by typing) and
1791
+ `check()` (the parsed value, or `undefined` with `error` set).
1792
+
1793
+ ```tsx
1794
+ import { useCodeField } from '@softistx/alxia-react-router/session/react';
1795
+ import { TOTP_CODE } from '@softistx/alxia-react-router/session/model';
1796
+ import { Form, useActionData } from 'react-router';
1797
+ import { z } from 'zod';
1798
+
1799
+ const schema = z.string().regex(TOTP_CODE, 'Six digits');
1800
+
1801
+ export function CodeForm() {
1802
+ const refusal = useActionData<object>(); // a new object on each refusal
1803
+ const field = useCodeField(schema, refusal);
1804
+ return (
1805
+ <Form method="post" onSubmit={(event) => { if (field.check() === undefined) event.preventDefault(); }}>
1806
+ <input
1807
+ ref={field.ref}
1808
+ name="code"
1809
+ inputMode="numeric"
1810
+ autoComplete="one-time-code"
1811
+ value={field.code}
1812
+ onChange={(event) => field.setCode(event.target.value)}
1813
+ />
1814
+ {field.error ? <p role="alert">{field.error}</p> : null}
1815
+ <button type="submit">Confirm</button>
1816
+ </Form>
1817
+ );
1818
+ }
1819
+ ```
1820
+
1821
+ An app on react-hook-form keeps its form and its resolver and uses the part
1822
+ underneath, `useOnRefusal(refusal, handler)`, which calls `handler` once per
1823
+ new refusal:
1824
+
1825
+ ```tsx
1826
+ import { useOnRefusal } from '@softistx/alxia-react-router/session/react';
1827
+ import { useForm } from 'react-hook-form';
1828
+
1829
+ const form = useForm({ defaultValues: { code: '' } /* , resolver */ });
1830
+ useOnRefusal(refusal, () => {
1831
+ form.setValue('code', '');
1832
+ form.setFocus('code');
1833
+ });
1834
+ ```
1835
+
1836
+ The package takes no form library as a peer: react-hook-form would also need
1837
+ its resolver for the schema, and a library-agnostic core serves every form
1838
+ library at the price of three lines.
1839
+
1840
+ ### `useStepUpReplay`
1841
+
1842
+ A sensitive action the API refuses with `step-up-required` answers with
1843
+ `stepUp` set. `useStepUpReplay` opens the step-up on that answer, posts the
1844
+ `request-step-up` and `confirm-step-up` intents, and sends the refused action
1845
+ again once the session is confirmed. The dialog stays, saying so, until the
1846
+ replayed action is answered; an answer that asks for a step-up again reopens
1847
+ it. Cancelling forgets the step-up: a code accepted or a challenge granted
1848
+ after `cancel()` is ignored and replays nothing. `dismissNotice()` clears
1849
+ `confirmedNotice` without sending or cancelling anything. It is generic over your own
1850
+ `post`s, so each intent keeps the fields your action types.
1851
+
1852
+ An action that carries a one-time code (`spendsCode`) is not replayed after a
1853
+ step-up by the second factor: that code was just spent, so the dialog closes
1854
+ and `confirmedNotice` is true ("confirmed, type a new code"). The notice
1855
+ clears as soon as `action` becomes another value, that is when the user posts
1856
+ a new action, not when its answer arrives; pass a new object for each post
1857
+ (`last.current = action`), since an identical reference is not a new action.
1858
+ `cancel()` clears it too.
1859
+
1860
+ If `replay()` posts nothing, no answer ever ends the confirming phase
1861
+ (`dialogProps.confirming` stays true): have `replay` post, or call `cancel()`.
1862
+
1863
+ `route()` answers both intents from one action, so a fetcher on it has their
1864
+ union as data. `requestAnswerOf(data)` and `confirmAnswerOf(data)` narrow it on
1865
+ `intent` (and give `undefined` for any other answer), so each channel is typed
1866
+ from the one action.
1867
+
1868
+ ```tsx
1869
+ import { useRef } from 'react';
1870
+ import { useFetcher } from 'react-router';
1871
+ import {
1872
+ confirmAnswerOf,
1873
+ requestAnswerOf,
1874
+ useStepUpReplay,
1875
+ } from '@softistx/alxia-react-router/session/react';
1876
+ import type { action as stepUpAction } from './step-up'; // the route with `stepUp.route`
1877
+
1878
+ type DeleteItem = { intent: 'delete-item'; id: string };
1879
+
1880
+ export function useDeleteItem() {
1881
+ const fetcher = useFetcher<{ ok: boolean; stepUp?: boolean }>();
1882
+ const request = useFetcher<typeof stepUpAction>({ key: 'step-up-request' });
1883
+ const confirm = useFetcher<typeof stepUpAction>({ key: 'step-up-confirm' });
1884
+ const last = useRef<DeleteItem | null>(null);
1885
+
1886
+ const post = (action: DeleteItem) => {
1887
+ last.current = action;
1888
+ void fetcher.submit(action, { method: 'post', encType: 'application/json' });
1889
+ };
1890
+ const toStepUp = (body: Record<string, unknown>) =>
1891
+ void request.submit(body, {
1892
+ method: 'post',
1893
+ action: '/step-up',
1894
+ encType: 'application/json',
1895
+ });
1896
+
1897
+ const stepUp = useStepUpReplay({
1898
+ answer: fetcher.state === 'idle' ? fetcher.data : undefined,
1899
+ action: last.current ?? undefined,
1900
+ replay: () => {
1901
+ if (last.current) post(last.current);
1902
+ },
1903
+ request: {
1904
+ post: () => toStepUp({ intent: 'request-step-up' }),
1905
+ answer: requestAnswerOf(request.data),
1906
+ busy: request.state !== 'idle',
1907
+ reset: () => request.reset(),
1908
+ },
1909
+ confirm: {
1910
+ post: (fields) =>
1911
+ void confirm.submit(
1912
+ { intent: 'confirm-step-up', ...fields },
1913
+ { method: 'post', action: '/step-up', encType: 'application/json' },
1914
+ ),
1915
+ answer: confirmAnswerOf(confirm.data),
1916
+ busy: confirm.state !== 'idle',
1917
+ reset: () => confirm.reset(),
1918
+ },
1919
+ });
1920
+ return { post, ...stepUp };
1921
+ }
1922
+ // Pass `dialogProps` to your step-up dialog: phase, via, props, message,
1923
+ // busy, confirming, onCancel, onRetry, onSubmit, onResend.
1924
+ ```
1925
+
1926
+ `dialogProps` is `dialogPropsOf(stepUp, open, cancel)`, which is plain and
1927
+ exported, for a host that builds them itself.
1928
+
1929
+ `via` is kept in every phase once a challenge was granted (`code`, `expired`,
1930
+ `failed`, `confirmed`) and is `undefined` before, so a dialog can tell a mailed
1931
+ code from an authenticator-app code.
1932
+
1933
+ ### `useStepUpRunner`
1934
+
1935
+ `useStepUpReplay` leaves the bookkeeping to the page: the refused action, the
1936
+ fetcher's answer, the cancel. `useStepUpRunner` does it once, so a feature
1937
+ only declares its request type and its post. `run(request)` posts the request
1938
+ and returns a promise of its outcome, or of `'cancelled'`:
1939
+
1940
+ - the answer that is not a step-up request settles the run, an error answer
1941
+ included (it is the outcome, not a rejection);
1942
+ - a refusal carrying `stepUp` (`asksStepUp`) opens the dialog and keeps the run pending;
1943
+ once the session is confirmed the same request is posted again and its
1944
+ answer settles the run;
1945
+ - cancelling the dialog (`dialogProps.onCancel` or `cancel()`) resolves the
1946
+ run as `'cancelled'`;
1947
+ - a second `run` replaces the pending one: it settles with its own action's
1948
+ outcome when its `post` returned a promise (see below), else `'cancelled'`.
1949
+
1950
+ It is UI-library-agnostic: `dialogProps` are the plain
1951
+ `StepUpDialogProps`. Features of one page share one runner, so one dialog and
1952
+ one pair of step-up channels serve them all (put the runner in a context
1953
+ provider and hand `run` to the features).
1954
+
1955
+ ```tsx
1956
+ import { useFetcher } from 'react-router';
1957
+ import {
1958
+ type StepUpChannel,
1959
+ useStepUpRunner,
1960
+ } from '@softistx/alxia-react-router/session/react';
1961
+
1962
+ type ItemRequest = { intent: 'remove' | 'rename'; id: string; name?: string };
1963
+ type ItemOutcome = { ok: boolean; error?: string };
1964
+
1965
+ export function useItemActions(request: StepUpChannel, confirm: StepUpChannel) {
1966
+ const fetcher = useFetcher<ItemOutcome>({ key: 'item-actions' });
1967
+ return useStepUpRunner<ItemRequest, ItemOutcome>({
1968
+ answer: fetcher.state === 'idle' ? fetcher.data : undefined,
1969
+ post: (r) =>
1970
+ void fetcher.submit(r, { method: 'post', encType: 'application/json' }),
1971
+ request, // the step-up channels, as for useStepUpReplay
1972
+ confirm,
1973
+ });
1974
+ }
1975
+
1976
+ // const { run, busy, dialogProps } = useItemActions(request, confirm);
1977
+ // const outcome = await run({ intent: 'remove', id });
1978
+ // if (outcome === 'cancelled' || !outcome.ok) return;
1979
+ // return <YourStepUpDialog {...dialogProps} />;
1980
+ ```
1981
+
1982
+ `answer` is the settled answer: pass `undefined` while the fetcher works, so
1983
+ the answer of the previous request is not read again. `busy` is true while a
1984
+ run is pending, behind the step-up included.
1985
+
1986
+ - **One runner, one fetcher key.** A new submit on a fetcher supersedes the one
1987
+ in flight, so the answer of a replaced run never settles the run that
1988
+ replaced it.
1989
+ - **Unmount.** A run pending at unmount resolves as `'cancelled'`.
1990
+ - **`post` returns the outcome.** `post` may return a promise: when it
1991
+ resolves with a value, the run settles with it, so no fetcher is needed
1992
+ (`post: (r) => save(r)`, then `const outcome = await run(input)`). A
1993
+ refusal asking for a step-up opens the dialog as an answer would, and the
1994
+ replay's value settles the run. A promise resolving with `undefined` (a
1995
+ fetcher's `submit`) leaves the settling to `answer`.
1996
+ - **A failing `post`.** A `post` that throws or returns a rejected promise
1997
+ (the replay included) rejects the run with that error and clears `busy`,
1998
+ so `try { await run(x) } catch { ... }` sees it. It no longer resolves
1999
+ `'cancelled'`.
2000
+ - **A replaced run.** When its `post` returned a promise (a fetcher's
2001
+ `submit` included, which then resolves `'cancelled'` once it settles), the replaced run
2002
+ settles with that promise's own outcome (or rejects with its error) once it
2003
+ arrives, and never takes the next run's answer. Without a promise it
2004
+ resolves `'cancelled'`.
2005
+ - **A stale answer.** An answer that arrives after `cancel()`, or one already
2006
+ held when the next run starts, never opens the dialog nor settles that run.
2007
+ - **`spendsCode`** works as in `useStepUpReplay`: when a second-factor step-up
2008
+ spent the request's code, the run resolves as `'cancelled'` and
2009
+ `confirmedNotice` is true, so the page shows "confirmed, type a new code".
2010
+ `dismissNotice()` clears it without starting a run.
2011
+
2012
+ ### `useStepUp`, `asksStepUp` and `stepUpDialogPhase`
2013
+
2014
+ `useStepUp({ request, confirm, onConfirmed })` is the part under it, for a host
2015
+ that decides itself what to do once the code is accepted. `start()` asks for a
2016
+ challenge, `submit(code)` posts it, `release()` forgets everything.
2017
+
2018
+ ```tsx
2019
+ import { useStepUp } from '@softistx/alxia-react-router/session/react';
2020
+
2021
+ const stepUp = useStepUp({ request, confirm, onConfirmed: () => revalidate() });
2022
+ // stepUp.phase: 'asking' | 'failed' | 'code' | 'expired' | 'confirmed'
2023
+ ```
2024
+
2025
+ `asksStepUp(answer)` is true for a refusal carrying `stepUp` (what opens the
2026
+ dialog), and `stepUpDialogPhase(state)` is what the dialog shows for a
2027
+ `stepUpReducer` state:
2028
+
2029
+ ```ts
2030
+ import { asksStepUp, stepUpDialogPhase } from '@softistx/alxia-react-router/session/react';
2031
+ import { INITIAL_STEP_UP } from '@softistx/alxia-react-router/session/model';
2032
+
2033
+ asksStepUp({ ok: false, stepUp: true }); // true
2034
+ stepUpDialogPhase(INITIAL_STEP_UP); // 'asking'
2035
+ ```
2036
+
2037
+ ## The types and the rest of `/session/model`
2038
+
2039
+ The rest of `@softistx/alxia-react-router/session/model`, beside `safeNext`,
2040
+ `signInPath` and the step-up's reducer above:
2041
+
2042
+ ```ts
2043
+ import {
2044
+ HOME,
2045
+ INITIAL_STEP_UP,
2046
+ TOTP_CODE,
2047
+ type SecondFactorKind,
2048
+ type SignInStatus,
2049
+ type SignInPaths,
2050
+ SIGN_IN_PATHS,
2051
+ type StepUpConfirmAnswer,
2052
+ type StepUpProps,
2053
+ type StepUpRequestAnswer,
2054
+ type StepUpVia,
2055
+ } from '@softistx/alxia-react-router/session/model';
2056
+
2057
+ TOTP_CODE.test('123456'); // true: six digits, nothing else
2058
+ HOME; // '/', where `safeNext` falls back to
2059
+ INITIAL_STEP_UP.phase; // 'idle'
2060
+ SIGN_IN_PATHS.signIn; // '/sign-in'
2061
+
2062
+ const paths: SignInPaths = { ...SIGN_IN_PATHS, signIn: '/login' };
2063
+ const kind: SecondFactorKind = 'recovery';
2064
+ const status: SignInStatus = 'secondFactor';
2065
+ const via: StepUpVia = 'email';
2066
+ ```
2067
+
2068
+ - `TOTP_CODE` is the regular expression of an authenticator app's code: six digits.
2069
+ - `HOME` is the path `safeNext` returns when a `next` value is unsafe or missing.
2070
+ - `SIGN_IN_PATHS` and `SignInPaths` are the sign-in pages' paths and their
2071
+ type: `{ signIn, secondFactor }`.
2072
+ - `SecondFactorKind` is what a second-factor form sends: `'code' | 'recovery'`.
2073
+ - `SignInStatus` is how a sign-in ended: `'signedIn' | 'secondFactor'`.
2074
+ - `StepUpVia` is how a step-up is confirmed, `'email' | 'secondFactor'`, matching janus's vocabulary.
2075
+ - `StepUpRequestAnswer` is what the server answers to a request for a challenge, with the `message` of a refusal and a throttle's `retryAfter`.
2076
+ - `StepUpConfirmAnswer` is what the server answers to a code, with the `message` `stepUpSteps` words.
2077
+ - `StepUpError` is `'invalid' | 'expired' | 'failed' | 'throttled'`.
2078
+ - `StepUpProps` is the shape `stepUpProps` returns (`via`, `attemptsLeft`, `locked`, `error`, `retryAfter`, `pending`, `resent`); it spreads onto a step-up dialog's props.
2079
+
2080
+ The types of `/session`:
2081
+
2082
+ - `SignInAnswer` is what a step answers: `signedIn`, `secondFactor` or `other`.
2083
+ - `SignInFlowOptions` is what `signInFlow` takes, `SignInFlow` what it returns.
2084
+ - `SignInCodes` is its `codes` option: `invalidCode` and `challengeOver`.
2085
+ - `SignInFormError<T>` is `T & { formError: string; throttled?: true;
2086
+ retryAfter?: number }`, a form step's answer when it stays on the page
2087
+ (a throttled refusal adds `throttled` and `retryAfter`), and
2088
+ `SignInStayed<T>` is `signInStep`'s `data(...)` return for it, with the
2089
+ status.
2090
+ - `SessionCookies`, `SessionCookiesOptions` and `CookieSession` are the cookies,
2091
+ their options and a session read from a request (`{ token, expiresAt }`).
2092
+ - `StepUpStepsOptions` is what `stepUpSteps` takes, `StepUpSteps` what it returns.
2093
+ - `StepUpCodes` is the `codes` option.
2094
+ - `StepUpStayed<T>` is a step's `data(...)` return for an answer that stays on the page.
2095
+ - `StepUpCall<L>` is the `{ request, language }` each step-up step takes.
2096
+ - `INVALID_CODE`, `CHALLENGE_OVER`, `STEP_UP_OVER`, `STEP_UP_REQUIRED` and
2097
+ `MAIL_THROTTLED` are the default codes, so an app can extend a list
2098
+ (`challengeOver: [...CHALLENGE_OVER, 'auth.errors.gone']`).
2099
+ - `AuthLinksOptions` is what `authLinks` takes: `signIn`, and the optional
2100
+ `codes` (`AuthLinksCodes`: `mailThrottled`), `wording`, `start`, `resetDone`
2101
+ and `invalidState`. `AuthLinks` is what it returns.
2102
+ - `Spent<T>` is what `spendToken` returns, `LinkStayed` is the `data(...)` a
2103
+ refusal answers with, `SpentRefusal` is a refusal that stays on the page
2104
+ (`FormErrors` plus `throttled?` and `retryAfter?`), and `SpendOptions` is
2105
+ its second argument.