create-ailk 0.37.1 → 0.39.0

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 (318) hide show
  1. package/README.md +129 -0
  2. package/component-catalog.json +44 -6
  3. package/component-catalog.md +6 -5
  4. package/dist/add-module.js +16 -1
  5. package/dist/add-route.d.ts +2 -2
  6. package/dist/add-route.js +19 -12
  7. package/dist/cli.js +52 -0
  8. package/dist/declined-routes.d.ts +13 -0
  9. package/dist/declined-routes.js +74 -0
  10. package/dist/derive-architecture.d.ts +0 -6
  11. package/dist/derive-architecture.js +12 -16
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.js +3 -0
  14. package/dist/language-import.d.ts +93 -0
  15. package/dist/language-import.js +270 -43
  16. package/dist/lib/import-mdx.js +1 -1
  17. package/dist/lib/scaffold-render-sweep.d.ts +6 -3
  18. package/dist/lib/scaffold-render-sweep.js +8 -4
  19. package/dist/migrate-content.d.ts +6 -2
  20. package/dist/migrate-content.js +62 -5
  21. package/dist/module-architecture.js +139 -103
  22. package/dist/paid-sections.d.ts +13 -0
  23. package/dist/paid-sections.js +35 -5
  24. package/dist/programmatic.js +6 -16
  25. package/dist/remove-module.js +73 -2
  26. package/dist/routes.d.ts +130 -0
  27. package/dist/routes.js +954 -0
  28. package/dist/site-manifest.js +6 -4
  29. package/dist/site-roster.d.ts +11 -2
  30. package/dist/site-roster.js +63 -21
  31. package/dist/spoke-checkout.d.ts +28 -27
  32. package/dist/spoke-checkout.js +71 -102
  33. package/dist/surfaces.d.ts +26 -0
  34. package/dist/surfaces.js +105 -293
  35. package/dist/sync-routes.d.ts +14 -1
  36. package/dist/sync-routes.js +108 -10
  37. package/dist/template-record.js +3 -1
  38. package/dist/topology.d.ts +26 -1
  39. package/dist/topology.js +273 -7
  40. package/dist/update.d.ts +17 -2
  41. package/dist/update.js +480 -77
  42. package/package.json +3 -3
  43. package/templates/README.md +1 -1
  44. package/templates/apps/mcp/CLAUDE.md +5 -3
  45. package/templates/apps/web/CLAUDE.md +87 -23
  46. package/templates/apps/web/__tests__/__mocks__/next-intl-server.ts +5 -1
  47. package/templates/apps/web/__tests__/__mocks__/next-intl.ts +5 -1
  48. package/templates/apps/web/__tests__/auth/seam.test.ts +34 -0
  49. package/templates/apps/web/account.config.tsx +100 -0
  50. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +1 -1
  51. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +2 -2
  52. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +1 -1
  53. package/templates/apps/web/app/[locale]/layout.tsx +46 -29
  54. package/templates/apps/web/app/apple-icon.tsx +72 -0
  55. package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +22 -12
  56. package/templates/apps/web/app/og/__tests__/__snapshots__/card.test.tsx.snap +3 -0
  57. package/templates/apps/web/app/og/__tests__/card.test.tsx +129 -0
  58. package/templates/apps/web/app/og/__tests__/route.test.ts +3 -4
  59. package/templates/apps/web/app/og/route.tsx +155 -72
  60. package/templates/apps/web/app/sitemap.xml/__tests__/site-listing.test.ts +12 -0
  61. package/templates/apps/web/auth.config.tsx +107 -0
  62. package/templates/apps/web/auth.ts +2 -1
  63. package/templates/apps/web/i18n/request.ts +51 -1
  64. package/templates/apps/web/jest.config.cjs +17 -1
  65. package/templates/apps/web/lib/__tests__/auth-phone.test.ts +11 -0
  66. package/templates/apps/web/lib/__tests__/fixtures/site-topology.ts +73 -0
  67. package/templates/apps/web/lib/__tests__/nav-label-keys.test.ts +14 -0
  68. package/templates/apps/web/lib/__tests__/profile-back-link.test.ts +148 -61
  69. package/templates/apps/web/lib/__tests__/served-pages.test.ts +77 -0
  70. package/templates/apps/web/lib/__tests__/server-api.test.ts +37 -5
  71. package/templates/apps/web/lib/__tests__/structured-data.test.tsx +26 -13
  72. package/templates/apps/web/lib/listings.tsx +2 -2
  73. package/templates/apps/web/lib/nav-label-keys.ts +16 -2
  74. package/templates/apps/web/lib/paid-section-contracts.ts +35 -6
  75. package/templates/apps/web/lib/paid-sections.generated.ts +8 -0
  76. package/templates/apps/web/lib/profile-back-link.ts +105 -32
  77. package/templates/apps/web/lib/served-pages.ts +95 -0
  78. package/templates/apps/web/lib/server-api.ts +1 -1
  79. package/templates/apps/web/lib/site-brand.tsx +3 -5
  80. package/templates/apps/web/lib/topology.generated.ts +5 -0
  81. package/templates/apps/web/messages/en.json +8 -836
  82. package/templates/apps/web/middleware.ts +15 -26
  83. package/templates/apps/web/next.config.mjs +35 -0
  84. package/templates/apps/web/package.json +2 -0
  85. package/templates/apps/web/types/messages.d.ts +6 -1
  86. package/templates/customizations.yaml +9 -0
  87. package/templates/package.json +3 -1
  88. package/templates/tools/lint-architecture.ts +164 -11
  89. package/versions.json +49 -47
  90. package/templates/apps/web/app/[locale]/(auth)/__tests__/auth-pages.test.tsx +0 -322
  91. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +0 -554
  92. package/templates/apps/web/app/[locale]/(auth)/consent/__tests__/consent-actions.test.ts +0 -56
  93. package/templates/apps/web/app/[locale]/(auth)/consent/__tests__/page.test.tsx +0 -164
  94. package/templates/apps/web/app/[locale]/(auth)/consent/consent-form.tsx +0 -132
  95. package/templates/apps/web/app/[locale]/(auth)/consent/consent.actions.ts +0 -51
  96. package/templates/apps/web/app/[locale]/(auth)/consent/page.tsx +0 -144
  97. package/templates/apps/web/app/[locale]/(auth)/forgot-password/forgot-password-card.tsx +0 -101
  98. package/templates/apps/web/app/[locale]/(auth)/forgot-password/page.tsx +0 -111
  99. package/templates/apps/web/app/[locale]/(auth)/layout.tsx +0 -81
  100. package/templates/apps/web/app/[locale]/(auth)/legal-footnote.tsx +0 -35
  101. package/templates/apps/web/app/[locale]/(auth)/reset-password/__tests__/return.test.tsx +0 -179
  102. package/templates/apps/web/app/[locale]/(auth)/reset-password/page.tsx +0 -157
  103. package/templates/apps/web/app/[locale]/(auth)/reset-password/reset-password-card.tsx +0 -126
  104. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/next-path.test.ts +0 -54
  105. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +0 -628
  106. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/remembered-method.test.ts +0 -43
  107. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +0 -266
  108. package/templates/apps/web/app/[locale]/(auth)/sign-in/next-path.ts +0 -20
  109. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +0 -234
  110. package/templates/apps/web/app/[locale]/(auth)/sign-in/remembered-method.ts +0 -37
  111. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +0 -323
  112. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +0 -93
  113. package/templates/apps/web/app/[locale]/(auth)/sign-up/__tests__/page.test.tsx +0 -301
  114. package/templates/apps/web/app/[locale]/(auth)/sign-up/__tests__/sign-up-card.test.tsx +0 -309
  115. package/templates/apps/web/app/[locale]/(auth)/sign-up/page.tsx +0 -201
  116. package/templates/apps/web/app/[locale]/(auth)/sign-up/sign-up-card.tsx +0 -366
  117. package/templates/apps/web/app/[locale]/(auth)/use-auth-card-flow.ts +0 -116
  118. package/templates/apps/web/app/[locale]/(auth)/verify-email/__tests__/actions.test.ts +0 -94
  119. package/templates/apps/web/app/[locale]/(auth)/verify-email/actions.ts +0 -77
  120. package/templates/apps/web/app/[locale]/(auth)/verify-email/page.tsx +0 -154
  121. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/account-frame-sign-out.test.tsx +0 -175
  122. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/agreements-prompt.test.tsx +0 -301
  123. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +0 -515
  124. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/general.test.tsx +0 -883
  125. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +0 -758
  126. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/item.test.tsx +0 -264
  127. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +0 -167
  128. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +0 -730
  129. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-menu.test.tsx +0 -355
  130. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-popups.test.tsx +0 -97
  131. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/notifications.test.tsx +0 -375
  132. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/onboarding.test.tsx +0 -323
  133. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +0 -1208
  134. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/popups.test.tsx +0 -418
  135. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/privacy.test.tsx +0 -462
  136. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/rich-translator.ts +0 -63
  137. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/security.test.tsx +0 -406
  138. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/settings.test.tsx +0 -93
  139. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/support.test.tsx +0 -208
  140. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/thread.test.tsx +0 -340
  141. package/templates/apps/web/app/[locale]/(authed)/account/account-data.ts +0 -182
  142. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +0 -353
  143. package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +0 -57
  144. package/templates/apps/web/app/[locale]/(authed)/account/agreements-actions.ts +0 -58
  145. package/templates/apps/web/app/[locale]/(authed)/account/agreements-gate.ts +0 -61
  146. package/templates/apps/web/app/[locale]/(authed)/account/agreements-prompt.tsx +0 -184
  147. package/templates/apps/web/app/[locale]/(authed)/account/appointments/[slug]/page.tsx +0 -161
  148. package/templates/apps/web/app/[locale]/(authed)/account/appointments/__tests__/page.test.tsx +0 -426
  149. package/templates/apps/web/app/[locale]/(authed)/account/appointments/appointments-data.ts +0 -76
  150. package/templates/apps/web/app/[locale]/(authed)/account/appointments/page.tsx +0 -139
  151. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/page.tsx +0 -406
  152. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/pay-form.tsx +0 -65
  153. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/review-form.tsx +0 -172
  154. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/versions/[version]/file/route.ts +0 -190
  155. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/file-route.test.ts +0 -333
  156. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/page.test.tsx +0 -936
  157. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/pay.test.tsx +0 -193
  158. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/review.test.tsx +0 -476
  159. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-actions.ts +0 -184
  160. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-data.ts +0 -197
  161. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/page.tsx +0 -182
  162. package/templates/apps/web/app/[locale]/(authed)/account/billing/__tests__/offerings.test.ts +0 -99
  163. package/templates/apps/web/app/[locale]/(authed)/account/billing/offerings.ts +0 -123
  164. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +0 -424
  165. package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +0 -303
  166. package/templates/apps/web/app/[locale]/(authed)/account/components/request-quote.tsx +0 -274
  167. package/templates/apps/web/app/[locale]/(authed)/account/error-row.tsx +0 -35
  168. package/templates/apps/web/app/[locale]/(authed)/account/for-you-labels.ts +0 -36
  169. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/phone-verification.test.tsx +0 -215
  170. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/seam-imports.test.ts +0 -65
  171. package/templates/apps/web/app/[locale]/(authed)/account/general/account-name.ts +0 -36
  172. package/templates/apps/web/app/[locale]/(authed)/account/general/billing-anchor.tsx +0 -27
  173. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-actions.ts +0 -149
  174. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-details.tsx +0 -42
  175. package/templates/apps/web/app/[locale]/(authed)/account/general/deletion-request.tsx +0 -132
  176. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +0 -218
  177. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-actions.ts +0 -122
  178. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-verification.tsx +0 -215
  179. package/templates/apps/web/app/[locale]/(authed)/account/general/photo-actions.ts +0 -73
  180. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-form.tsx +0 -107
  181. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-source.ts +0 -87
  182. package/templates/apps/web/app/[locale]/(authed)/account/inbox/[kind]/[id]/page.tsx +0 -119
  183. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/__tests__/route.test.ts +0 -215
  184. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/route.ts +0 -80
  185. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/member-thread-composer.tsx +0 -43
  186. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/page.tsx +0 -125
  187. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-data.ts +0 -88
  188. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-write.ts +0 -31
  189. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/invitation-id.test.ts +0 -35
  190. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/page.test.tsx +0 -266
  191. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/actions.ts +0 -116
  192. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/invitation-id.ts +0 -12
  193. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +0 -154
  194. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +0 -152
  195. package/templates/apps/web/app/[locale]/(authed)/account/new-actions.ts +0 -219
  196. package/templates/apps/web/app/[locale]/(authed)/account/new-menu.tsx +0 -365
  197. package/templates/apps/web/app/[locale]/(authed)/account/new-popups.tsx +0 -86
  198. package/templates/apps/web/app/[locale]/(authed)/account/notifications/page.tsx +0 -143
  199. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/actions.ts +0 -120
  200. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/onboarding-form.tsx +0 -322
  201. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/page.tsx +0 -126
  202. package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +0 -306
  203. package/templates/apps/web/app/[locale]/(authed)/account/privacy/__tests__/export-route.test.ts +0 -173
  204. package/templates/apps/web/app/[locale]/(authed)/account/privacy/actions.ts +0 -103
  205. package/templates/apps/web/app/[locale]/(authed)/account/privacy/export/route.ts +0 -102
  206. package/templates/apps/web/app/[locale]/(authed)/account/privacy/page.tsx +0 -240
  207. package/templates/apps/web/app/[locale]/(authed)/account/profile-actions.ts +0 -116
  208. package/templates/apps/web/app/[locale]/(authed)/account/retry-button.tsx +0 -27
  209. package/templates/apps/web/app/[locale]/(authed)/account/security/__tests__/hub-variant.test.tsx +0 -258
  210. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +0 -131
  211. package/templates/apps/web/app/[locale]/(authed)/account/security/security-panel.tsx +0 -130
  212. package/templates/apps/web/app/[locale]/(authed)/account/security/security-source.ts +0 -92
  213. package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +0 -24
  214. package/templates/apps/web/app/[locale]/(authed)/account/settings-frame.tsx +0 -121
  215. package/templates/apps/web/app/[locale]/(authed)/account/sign-in-method.ts +0 -37
  216. package/templates/apps/web/app/[locale]/(authed)/account/support/page.tsx +0 -60
  217. package/templates/apps/web/app/[locale]/(authed)/account/support/support-form.tsx +0 -98
  218. package/templates/apps/web/app/[locale]/(authed)/account/support-actions.ts +0 -100
  219. package/templates/apps/web/app/[locale]/checkout/__tests__/pages.test.tsx +0 -139
  220. package/templates/apps/web/app/[locale]/checkout/__tests__/thank-you-account.test.tsx +0 -146
  221. package/templates/apps/web/app/[locale]/checkout/thank-you/page.tsx +0 -114
  222. package/templates/apps/web/app/[locale]/checkout/unavailable/page.tsx +0 -51
  223. package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +0 -614
  224. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.count.test.tsx +0 -43
  225. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.deliverable.test.tsx +0 -214
  226. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.ending.test.tsx +0 -197
  227. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.invite.test.tsx +0 -286
  228. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.permalink.test.tsx +0 -520
  229. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.test.tsx +0 -376
  230. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.thanks-by-tier.test.tsx +0 -306
  231. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/account-invite.actions.test.ts +0 -69
  232. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/flow.actions.test.ts +0 -398
  233. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/magnet-page.test.tsx +0 -704
  234. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/save.actions.test.ts +0 -173
  235. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/two-route-tool.test.tsx +0 -141
  236. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/verify.test.tsx +0 -249
  237. package/templates/apps/web/app/[locale]/flows/[slug]/account-invite.actions.ts +0 -35
  238. package/templates/apps/web/app/[locale]/flows/[slug]/email-moment.ts +0 -92
  239. package/templates/apps/web/app/[locale]/flows/[slug]/flow.actions.ts +0 -177
  240. package/templates/apps/web/app/[locale]/flows/[slug]/magnet-page.tsx +0 -472
  241. package/templates/apps/web/app/[locale]/flows/[slug]/page.tsx +0 -48
  242. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/LevelChart.tsx +0 -100
  243. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsCard.tsx +0 -99
  244. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +0 -820
  245. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsEmailStep.tsx +0 -203
  246. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.no-commerce.test.tsx +0 -194
  247. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.report.test.tsx +0 -284
  248. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/by-result.test.tsx +0 -302
  249. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/cards.test.tsx +0 -402
  250. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/landing.test.tsx +0 -293
  251. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/page.test.tsx +0 -485
  252. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/score.test.tsx +0 -231
  253. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/checkout-seam.ts +0 -74
  254. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/meeting-seam.ts +0 -36
  255. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/page.tsx +0 -420
  256. package/templates/apps/web/app/[locale]/flows/[slug]/save.actions.ts +0 -85
  257. package/templates/apps/web/app/[locale]/flows/[slug]/served-flow.ts +0 -91
  258. package/templates/apps/web/app/[locale]/flows/[slug]/start/page.tsx +0 -32
  259. package/templates/apps/web/app/[locale]/flows/[slug]/verify/page.tsx +0 -153
  260. package/templates/apps/web/app/[locale]/flows/[slug]/verify.actions.ts +0 -151
  261. package/templates/apps/web/app/[locale]/meet/confirmed/BookingHandOff.tsx +0 -128
  262. package/templates/apps/web/app/[locale]/meet/confirmed/__tests__/BookingHandOff.test.tsx +0 -126
  263. package/templates/apps/web/app/[locale]/purchase/__tests__/cancel.test.tsx +0 -162
  264. package/templates/apps/web/app/[locale]/purchase/__tests__/module-scope.test.ts +0 -68
  265. package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +0 -411
  266. package/templates/apps/web/app/[locale]/purchase/cancel/page.tsx +0 -115
  267. package/templates/apps/web/app/[locale]/purchase/success/page.tsx +0 -348
  268. package/templates/apps/web/app/api/auth/[...all]/route.ts +0 -16
  269. package/templates/apps/web/app/api/auth/hub/__tests__/continuation.test.ts +0 -143
  270. package/templates/apps/web/app/api/auth/hub/__tests__/entry-routes.test.ts +0 -749
  271. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +0 -964
  272. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +0 -390
  273. package/templates/apps/web/app/api/auth/hub/continuation.ts +0 -127
  274. package/templates/apps/web/app/api/auth/hub/continue/[ref]/__tests__/route.test.ts +0 -188
  275. package/templates/apps/web/app/api/auth/hub/continue/[ref]/route.ts +0 -53
  276. package/templates/apps/web/app/api/auth/hub/email/route.ts +0 -111
  277. package/templates/apps/web/app/api/auth/hub/entry-shared.ts +0 -163
  278. package/templates/apps/web/app/api/auth/hub/password/__tests__/return.test.ts +0 -86
  279. package/templates/apps/web/app/api/auth/hub/password/__tests__/route.test.ts +0 -368
  280. package/templates/apps/web/app/api/auth/hub/password/return.ts +0 -86
  281. package/templates/apps/web/app/api/auth/hub/password/route.ts +0 -171
  282. package/templates/apps/web/app/api/auth/hub/purchase/route.ts +0 -230
  283. package/templates/apps/web/app/api/auth/hub/purchase-link/route.ts +0 -174
  284. package/templates/apps/web/app/api/auth/hub/sign-up/route.ts +0 -60
  285. package/templates/apps/web/app/api/auth/hub/sign-up-evidence.ts +0 -97
  286. package/templates/apps/web/app/api/auth/mcp/__tests__/continuation.test.ts +0 -92
  287. package/templates/apps/web/app/api/auth/mcp/continuation.ts +0 -89
  288. package/templates/apps/web/app/api/auth/mcp/continue/[ref]/__tests__/route.test.ts +0 -59
  289. package/templates/apps/web/app/api/auth/mcp/continue/[ref]/route.ts +0 -41
  290. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +0 -1166
  291. package/templates/apps/web/app/api/hub-session/callback/route.ts +0 -134
  292. package/templates/apps/web/app/api/hub-session/email/route.ts +0 -125
  293. package/templates/apps/web/app/api/hub-session/one-tap/nonce/route.ts +0 -49
  294. package/templates/apps/web/app/api/hub-session/one-tap/route.ts +0 -106
  295. package/templates/apps/web/app/api/hub-session/open/route.ts +0 -111
  296. package/templates/apps/web/app/api/hub-session/password/return/route.ts +0 -69
  297. package/templates/apps/web/app/api/hub-session/password/route.ts +0 -106
  298. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +0 -91
  299. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +0 -54
  300. package/templates/apps/web/components/sign-out-trigger.tsx +0 -62
  301. package/templates/apps/web/lib/__tests__/account-config.test.ts +0 -704
  302. package/templates/apps/web/lib/__tests__/auth-routes.test.ts +0 -140
  303. package/templates/apps/web/lib/account-config.ts +0 -678
  304. package/templates/apps/web/lib/auth-routes.ts +0 -125
  305. package/templates/apps/web/lib/checkout-config.ts +0 -16
  306. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +0 -433
  307. package/templates/apps/web/lib/hub-session/__tests__/spoke-sign-in.test.tsx +0 -332
  308. package/templates/apps/web/lib/hub-session/config.ts +0 -110
  309. package/templates/apps/web/lib/hub-session/entry.ts +0 -238
  310. package/templates/apps/web/lib/hub-session/index.ts +0 -21
  311. package/templates/apps/web/lib/hub-session/one-tap.tsx +0 -148
  312. package/templates/apps/web/lib/hub-session/reseal.ts +0 -90
  313. package/templates/apps/web/lib/hub-session/seal.ts +0 -86
  314. package/templates/apps/web/lib/hub-session/session.ts +0 -298
  315. package/templates/apps/web/lib/hub-session/spoke-sign-in.tsx +0 -277
  316. package/templates/apps/web/lib/next-path.ts +0 -35
  317. package/templates/apps/web/src/lib/__tests__/commerce-sections.test.ts +0 -57
  318. package/templates/apps/web/src/lib/commerce-sections.ts +0 -55
@@ -1,1166 +0,0 @@
1
- /**
2
- * @jest-environment node
3
- */
4
-
5
- /**
6
- * The spoke's three hub-session routes (#7894 D2, D7; spec
7
- * docs/specs/7894-the-hub-signs-in-its-spec.md AC-3, AC-5).
8
- *
9
- * The api-client's `hubSignIn` (the hub API) is the one external boundary
10
- * mocked; the seal, the cookies and the routes' decisions are real. Covers:
11
- * the authorize redirect (PKCE S256, a state, the configured redirect URI —
12
- * never one built from `Host`), the callback's state check and its exchange,
13
- * a callback that BURNS a code it cannot complete (AC-5), and a sign-out that
14
- * refuses a cross-site request and revokes nothing (AC-5). Each route is a 404
15
- * unless the web seam's `SIGN_IN_PROVIDER` is `"hub"` (AC-9).
16
- *
17
- * #8757 D9 (AC-6): a valid single `?email=` on the sign-in route becomes the
18
- * authorize URL's `login_hint`; the sealed flow cookie never carries it.
19
- *
20
- * #9912 D2 (AC-1): exactly one `?prompt=create` rides to the hub as
21
- * `prompt=create`, so the hub sends a visitor with no session to /sign-up;
22
- * any other value adds nothing, and the flow cookie's keys are unchanged.
23
- *
24
- * #11096 (spec docs/specs/11096-the-spoke-hosts-the-sign-spec.md): the
25
- * spoke-hosted entry — the email form's POST (AC-1, AC-2, AC-6), Google's
26
- * `provider` hint (AC-3), the purchase link's "Open my account" (AC-4) and
27
- * One Tap's nonce and credential exchange (AC-5, AC-6). The hub web is
28
- * reached with `fetch` (mocked); the hub API through the api-client.
29
- *
30
- * #11162 (AC-2): the Security tab's password link — a same-origin JSON POST
31
- * for the sealed session's person, asked of the hub web as the spoke's
32
- * client; no address and no password ever crosses this route.
33
- */
34
-
35
- import { createHash } from "node:crypto";
36
-
37
- const mockExchange = jest.fn();
38
- const mockRevoke = jest.fn();
39
- const mockGoogle = jest.fn();
40
- const mockMe = jest.fn();
41
- jest.mock("@working-theory/api-client", () => ({
42
- __esModule: true,
43
- hubSignIn: {
44
- exchange: (...args: unknown[]) => mockExchange(...args),
45
- revoke: (...args: unknown[]) => mockRevoke(...args),
46
- google: (...args: unknown[]) => mockGoogle(...args),
47
- me: (...args: unknown[]) => mockMe(...args),
48
- },
49
- }));
50
-
51
- // #11096 — the bot check's external boundary is Vercel BotID: it runs only
52
- // with `VERCEL=1`, so a case that wants a verdict sets that and answers here.
53
- const mockCheckBotId = jest.fn();
54
- jest.mock("botid/server", () => ({
55
- __esModule: true,
56
- checkBotId: (...args: unknown[]) => mockCheckBotId(...args),
57
- }));
58
-
59
- const mockProvider: { value: "site" | "hub" | "none" } = { value: "hub" };
60
- // eslint-disable-next-line no-restricted-syntax -- #507: the sign-in provider is a generated constant (#7894 D8), not a runtime input; the seam IS the boundary between a hub and a hub-mode spoke build, and no env or HTTP surface selects it.
61
- jest.mock("../../../../lib/topology.generated", () => ({
62
- __esModule: true,
63
- get SIGN_IN_PROVIDER() {
64
- return mockProvider.value;
65
- },
66
- }));
67
-
68
- import { seal, unseal } from "../../../../lib/hub-session/seal";
69
- import { GET as callback } from "../callback/route";
70
- import { POST as email } from "../email/route";
71
- import { POST as oneTapNonce } from "../one-tap/nonce/route";
72
- import { POST as oneTap } from "../one-tap/route";
73
- import { POST as open } from "../open/route";
74
- import { GET as passwordReturn } from "../password/return/route";
75
- import { POST as password } from "../password/route";
76
- import { GET as signIn } from "../sign-in/route";
77
- import { POST as signOut } from "../sign-out/route";
78
-
79
- const ENV = process.env;
80
- const SITE = "http://127.0.0.1:3100";
81
- const HUB = "http://127.0.0.1:4100";
82
- const SESSION_SECRET = "s".repeat(43);
83
- const CLIENT = { clientId: "spoke_0001", clientSecret: `ailk_hcs_${"c".repeat(43)}` };
84
- const CREDENTIAL = `ailk_hst_${"t".repeat(43)}`;
85
- const CODE = "k".repeat(43);
86
- const USER = {
87
- id: "user_1",
88
- name: "Ada Lovelace",
89
- email: "ada@example.com",
90
- emailVerified: true,
91
- createdAt: "2026-09-01T00:00:00.000Z",
92
- };
93
-
94
- function configure(overrides: Record<string, string | undefined> = {}): void {
95
- process.env = {
96
- ...ENV,
97
- AILK_HUB_SIGN_IN_URL: HUB,
98
- AILK_HUB_CLIENT_ID: CLIENT.clientId,
99
- AILK_HUB_CLIENT_SECRET: CLIENT.clientSecret,
100
- AILK_HUB_SESSION_SECRET: SESSION_SECRET,
101
- NEXT_PUBLIC_BASE_URL: SITE,
102
- };
103
- for (const [key, value] of Object.entries(overrides)) {
104
- if (value === undefined) delete process.env[key];
105
- else process.env[key] = value;
106
- }
107
- }
108
-
109
- /** Each `Set-Cookie` the response carries. */
110
- function setCookies(res: Response): string[] {
111
- return res.headers.getSetCookie();
112
- }
113
-
114
- /** `name=value` of the cookie `name` in `res`'s `Set-Cookie` headers. */
115
- function cookieValue(res: Response, name: string): string | undefined {
116
- const line = setCookies(res).find((c) => c.startsWith(`${name}=`));
117
- return line?.slice(name.length + 1).split(";")[0];
118
- }
119
-
120
- /** Start a sign-in and return the flow cookie and the authorize URL. */
121
- function start(next = "/account"): { flow: string; authorize: URL; res: Response } {
122
- const res = signIn(
123
- new Request(`${SITE}/api/hub-session/sign-in?next=${encodeURIComponent(next)}`, {
124
- // A Host unlike the site's: the redirect URI must not follow it.
125
- headers: { host: "attacker.example.com" },
126
- }),
127
- );
128
- const flow = cookieValue(res, "ailk-hub-flow");
129
- if (flow === undefined) throw new Error("no flow cookie");
130
- return { flow, authorize: new URL(res.headers.get("location") ?? ""), res };
131
- }
132
-
133
- function callbackRequest(query: string, cookie?: string): Request {
134
- return new Request(`${SITE}/api/hub-session/callback?${query}`, {
135
- headers: cookie === undefined ? {} : { cookie },
136
- });
137
- }
138
-
139
- const mockFetch = jest.fn();
140
- const realFetch = global.fetch;
141
-
142
- beforeEach(() => {
143
- configure();
144
- mockProvider.value = "hub";
145
- mockExchange.mockReset();
146
- mockGoogle.mockReset();
147
- mockMe.mockReset();
148
- mockCheckBotId.mockReset().mockResolvedValue({ isBot: false });
149
- mockFetch.mockReset();
150
- // eslint-disable-next-line no-restricted-syntax -- a jest.fn stands in for the global fetch, the hub web's HTTP boundary; its call signature is not fetch's own.
151
- global.fetch = mockFetch as unknown as typeof fetch;
152
- mockRevoke.mockReset().mockResolvedValue({ ok: true, body: { revoked: true } });
153
- jest.spyOn(console, "warn").mockImplementation(() => undefined);
154
- jest.spyOn(console, "error").mockImplementation(() => undefined);
155
- });
156
-
157
- afterEach(() => {
158
- jest.restoreAllMocks();
159
- global.fetch = realFetch;
160
- });
161
-
162
- afterAll(() => {
163
- process.env = ENV;
164
- });
165
-
166
- describe("GET /api/hub-session/sign-in", () => {
167
- it("303s to the hub's authorize step with PKCE S256, a state and the configured callback, and sets the flow cookie", () => {
168
- const { authorize, res } = start();
169
- expect(res.status).toBe(303);
170
- expect(`${authorize.origin}${authorize.pathname}`).toBe(`${HUB}/api/auth/hub/authorize`);
171
- const q = authorize.searchParams;
172
- expect(q.get("response_type")).toBe("code");
173
- expect(q.get("client_id")).toBe(CLIENT.clientId);
174
- expect(q.get("redirect_uri")).toBe(`${SITE}/api/hub-session/callback`);
175
- expect(q.get("code_challenge")).toMatch(/^[A-Za-z0-9_-]{43}$/);
176
- expect(q.get("code_challenge_method")).toBe("S256");
177
- expect(q.get("state")).toMatch(/^[A-Za-z0-9_-]{43}$/);
178
- const flow = setCookies(res).find((c) => c.startsWith("ailk-hub-flow="));
179
- expect(flow).toMatch(/; HttpOnly/);
180
- expect(flow).toMatch(/; SameSite=Lax/);
181
- expect(flow).toMatch(/; Max-Age=600/);
182
- expect(flow).not.toMatch(/Secure/);
183
- });
184
-
185
- it("names the __Host- cookie, Secure, on an https site", () => {
186
- configure({ NEXT_PUBLIC_BASE_URL: "https://spoke.example.com" });
187
- const res = signIn(new Request("https://spoke.example.com/api/hub-session/sign-in"));
188
- const flow = setCookies(res).find((c) => c.startsWith("__Host-ailk-hub-flow="));
189
- expect(flow).toMatch(/; Secure$/);
190
- expect(new URL(res.headers.get("location") ?? "").searchParams.get("redirect_uri")).toBe(
191
- "https://spoke.example.com/api/hub-session/callback",
192
- );
193
- });
194
-
195
- // #11095 D4: /account now redirects here, so landing there would loop.
196
- it("with no configuration 303s to the site's home and sets no cookie", () => {
197
- configure({ AILK_HUB_CLIENT_SECRET: undefined });
198
- const res = signIn(new Request(`${SITE}/api/hub-session/sign-in?next=/account`));
199
- expect(res.status).toBe(303);
200
- expect(res.headers.get("location")).toBe("/");
201
- expect(setCookies(res)).toEqual([]);
202
- });
203
-
204
- it.each(["site", "none"] as const)("is 404 when the provider is %s", (provider) => {
205
- mockProvider.value = provider;
206
- expect(signIn(new Request(`${SITE}/api/hub-session/sign-in`)).status).toBe(404);
207
- });
208
- });
209
-
210
- describe("GET /api/hub-session/sign-in — the hinted email (#8757 D9)", () => {
211
- function startWith(query: string): { authorize: URL; payload: Record<string, unknown> } {
212
- const res = signIn(new Request(`${SITE}/api/hub-session/sign-in?${query}`));
213
- expect(res.status).toBe(303);
214
- const flow = cookieValue(res, "ailk-hub-flow");
215
- if (flow === undefined) throw new Error("no flow cookie");
216
- const payload = unseal(flow, SESSION_SECRET, "flow", "ailk-hub-flow");
217
- if (payload === null || typeof payload !== "object") throw new Error("flow did not open");
218
- return {
219
- authorize: new URL(res.headers.get("location") ?? ""),
220
- payload: payload as Record<string, unknown>,
221
- };
222
- }
223
-
224
- it("?next=/account&email=a%40b.example → the authorize URL carries login_hint; the flow cookie does not", () => {
225
- const { authorize, payload } = startWith("next=/account&email=a%40b.example");
226
- expect(authorize.searchParams.get("login_hint")).toBe("a@b.example");
227
- expect(authorize.search).toContain("login_hint=a%40b.example");
228
- // The six keys are untouched beside it.
229
- expect(authorize.searchParams.get("code_challenge_method")).toBe("S256");
230
- expect(authorize.searchParams.getAll("login_hint")).toHaveLength(1);
231
- expect(payload.next).toBe("/account");
232
- expect(payload).not.toHaveProperty("email");
233
- expect(payload).not.toHaveProperty("login_hint");
234
- expect(JSON.stringify(payload)).not.toContain("a@b.example");
235
- });
236
-
237
- it.each([
238
- ["an invalid value", "next=/account&email=bad"],
239
- ["a repeated value", "next=/account&email=a%40b.example&email=c%40d.example"],
240
- ["a value carrying a separator", "next=/account&email=a%40b.example%26x%3D1"],
241
- ["no value", "next=/account"],
242
- ])("%s → no login_hint", (_label, query) => {
243
- const { authorize, payload } = startWith(query);
244
- expect(authorize.searchParams.has("login_hint")).toBe(false);
245
- expect(payload).not.toHaveProperty("email");
246
- expect(payload).not.toHaveProperty("login_hint");
247
- });
248
- });
249
-
250
- describe("GET /api/hub-session/sign-in — the sign-up hint (#9912 D2)", () => {
251
- function startWith(query: string): { authorize: URL; payload: Record<string, unknown> } {
252
- const res = signIn(new Request(`${SITE}/api/hub-session/sign-in?${query}`));
253
- expect(res.status).toBe(303);
254
- const flow = cookieValue(res, "ailk-hub-flow");
255
- if (flow === undefined) throw new Error("no flow cookie");
256
- const payload = unseal(flow, SESSION_SECRET, "flow", "ailk-hub-flow");
257
- if (payload === null || typeof payload !== "object") throw new Error("flow did not open");
258
- return {
259
- authorize: new URL(res.headers.get("location") ?? ""),
260
- payload: payload as Record<string, unknown>,
261
- };
262
- }
263
-
264
- it("?next=/account&prompt=create → the authorize URL carries prompt=create; the flow cookie keeps exactly its five keys", () => {
265
- const { authorize, payload } = startWith("next=/account&prompt=create");
266
- expect(authorize.pathname).toBe("/api/auth/hub/authorize");
267
- expect(authorize.searchParams.getAll("prompt")).toEqual(["create"]);
268
- // The six keys are untouched beside it.
269
- expect(authorize.searchParams.get("response_type")).toBe("code");
270
- expect(authorize.searchParams.get("code_challenge_method")).toBe("S256");
271
- expect(Object.keys(payload).sort()).toEqual(
272
- ["expiresAt", "next", "state", "v", "verifier"],
273
- );
274
- expect(payload.next).toBe("/account");
275
- expect(JSON.stringify(payload)).not.toContain("create");
276
- });
277
-
278
- it("forwards the hint beside a valid login_hint", () => {
279
- const { authorize } = startWith("next=/account&prompt=create&email=a%40b.example");
280
- expect(authorize.searchParams.get("prompt")).toBe("create");
281
- expect(authorize.searchParams.get("login_hint")).toBe("a@b.example");
282
- });
283
-
284
- it.each([
285
- ["another OIDC value", "next=/account&prompt=login"],
286
- ["an empty value", "next=/account&prompt="],
287
- ["a repeated value", "next=/account&prompt=create&prompt=create"],
288
- ["a cased value", "next=/account&prompt=Create"],
289
- ["no value", "next=/account"],
290
- ])("%s → no prompt", (_label, query) => {
291
- const { authorize, payload } = startWith(query);
292
- expect(authorize.searchParams.has("prompt")).toBe(false);
293
- expect(payload).not.toHaveProperty("prompt");
294
- });
295
- });
296
-
297
- describe("GET /api/hub-session/callback", () => {
298
- function exchangeOk(): void {
299
- mockExchange.mockResolvedValue({
300
- ok: true,
301
- body: { accessToken: CREDENTIAL, tokenType: "Bearer", expiresIn: 86400, user: USER },
302
- });
303
- }
304
-
305
- it("exchanges the code with the verifier whose S256 is the challenge, seals the session and lands on next", async () => {
306
- exchangeOk();
307
- const { flow, authorize } = start("/fr/account/inbox");
308
- const state = authorize.searchParams.get("state") ?? "";
309
- const res = await callback(
310
- callbackRequest(`code=${CODE}&state=${state}`, `ailk-hub-flow=${flow}`),
311
- );
312
-
313
- expect(res.status).toBe(303);
314
- expect(res.headers.get("location")).toBe("/fr/account/inbox");
315
- expect(mockExchange).toHaveBeenCalledTimes(1);
316
- const [auth, body] = mockExchange.mock.calls[0] as [
317
- typeof CLIENT,
318
- { code: string; redirectUri: string; codeVerifier: string },
319
- ];
320
- expect(auth).toEqual(CLIENT);
321
- expect(body.code).toBe(CODE);
322
- expect(body.redirectUri).toBe(`${SITE}/api/hub-session/callback`);
323
- expect(createHash("sha256").update(body.codeVerifier).digest("base64url")).toBe(
324
- authorize.searchParams.get("code_challenge"),
325
- );
326
- const session = setCookies(res).find((c) => c.startsWith("ailk-hub-session="));
327
- expect(session).toMatch(/; HttpOnly/);
328
- expect(session).toMatch(/; Max-Age=86400/);
329
- // The flow cookie is cleared, and the credential never appears in clear.
330
- expect(setCookies(res).find((c) => c.startsWith("ailk-hub-flow="))).toMatch(/Max-Age=0/);
331
- expect(setCookies(res).join("\n")).not.toContain(CREDENTIAL);
332
- expect(mockRevoke).not.toHaveBeenCalled();
333
- });
334
-
335
- it("lands on the flow cookie's next, never a next in the callback's query", async () => {
336
- exchangeOk();
337
- const { flow, authorize } = start("/account");
338
- const state = authorize.searchParams.get("state") ?? "";
339
- const res = await callback(
340
- callbackRequest(`code=${CODE}&state=${state}&next=%2F%2Fevil.example.com`, `ailk-hub-flow=${flow}`),
341
- );
342
- expect(res.headers.get("location")).toBe("/account");
343
- });
344
-
345
- it("AC-5: without its flow cookie, burns the code at the hub and exchanges nothing", async () => {
346
- const res = await callback(callbackRequest(`code=${CODE}&state=${"s".repeat(43)}`));
347
- expect(res.status).toBe(303);
348
- expect(res.headers.get("location")).toBe("/");
349
- expect(mockExchange).not.toHaveBeenCalled();
350
- expect(mockRevoke).toHaveBeenCalledTimes(1);
351
- expect(mockRevoke).toHaveBeenCalledWith(CLIENT, { code: CODE });
352
- expect(setCookies(res).some((c) => c.startsWith("ailk-hub-session="))).toBe(false);
353
- });
354
-
355
- it("burns the code on a state mismatch, a hub error, an expired flow and a failed exchange", async () => {
356
- const { flow, authorize } = start();
357
- const state = authorize.searchParams.get("state") ?? "";
358
- const cookie = `ailk-hub-flow=${flow}`;
359
-
360
- // #11095 D4: every refusal lands on the site's home, never /account.
361
- const mismatch = await callback(callbackRequest(`code=${CODE}&state=${"x".repeat(43)}`, cookie));
362
- expect(mismatch.status).toBe(303);
363
- expect(mismatch.headers.get("location")).toBe("/");
364
- const hubError = await callback(
365
- callbackRequest(`code=${CODE}&state=${state}&error=access_denied`, cookie),
366
- );
367
- expect(hubError.status).toBe(303);
368
- expect(hubError.headers.get("location")).toBe("/");
369
- const expired = seal(
370
- { v: 1, state, verifier: "v".repeat(43), next: "/account", expiresAt: Date.now() - 1 },
371
- SESSION_SECRET,
372
- "flow",
373
- "ailk-hub-flow",
374
- );
375
- await callback(callbackRequest(`code=${CODE}&state=${state}`, `ailk-hub-flow=${expired}`));
376
- expect(mockExchange).not.toHaveBeenCalled();
377
-
378
- mockExchange.mockResolvedValue({ ok: false, status: 400, body: { error: "invalid_grant" } });
379
- const failed = await callback(callbackRequest(`code=${CODE}&state=${state}`, cookie));
380
- expect(failed.headers.get("location")).toBe("/");
381
- expect(mockRevoke).toHaveBeenCalledTimes(4);
382
- for (const call of mockRevoke.mock.calls) expect(call).toEqual([CLIENT, { code: CODE }]);
383
- });
384
-
385
- it.each([[0], [86_401], [Number.NaN], [undefined]])(
386
- "refuses a token answer whose expiresIn is %s, setting no session",
387
- async (expiresIn) => {
388
- mockExchange.mockResolvedValue({
389
- ok: true,
390
- body: { accessToken: CREDENTIAL, tokenType: "Bearer", expiresIn, user: USER },
391
- });
392
- const { flow, authorize } = start();
393
- const state = authorize.searchParams.get("state") ?? "";
394
- const res = await callback(callbackRequest(`code=${CODE}&state=${state}`, `ailk-hub-flow=${flow}`));
395
- expect(res.headers.get("location")).toBe("/");
396
- expect(setCookies(res).some((c) => c.startsWith("ailk-hub-session="))).toBe(false);
397
- },
398
- );
399
-
400
- it("never logs the query string, the code or the state", async () => {
401
- const warn = jest.spyOn(console, "warn");
402
- await callback(callbackRequest(`code=${CODE}&state=${"s".repeat(43)}`));
403
- const logged = warn.mock.calls.flat().join(" ");
404
- expect(logged).toContain("reason=no_flow");
405
- expect(logged).not.toContain(CODE);
406
- expect(logged).not.toContain("s".repeat(43));
407
- });
408
-
409
- it("with no configuration 303s to the site's home (#11095 D4)", async () => {
410
- configure({ AILK_HUB_CLIENT_SECRET: undefined });
411
- const res = await callback(callbackRequest(`code=${CODE}&state=x`));
412
- expect(res.status).toBe(303);
413
- expect(res.headers.get("location")).toBe("/");
414
- expect(mockExchange).not.toHaveBeenCalled();
415
- });
416
-
417
- it("does not try to burn a malformed code", async () => {
418
- await callback(callbackRequest("code=not-a-code&state=x"));
419
- expect(mockRevoke).not.toHaveBeenCalled();
420
- });
421
-
422
- it("is 404 unless the provider is hub", async () => {
423
- mockProvider.value = "none";
424
- const res = await callback(callbackRequest(`code=${CODE}&state=x`));
425
- expect(res.status).toBe(404);
426
- expect(mockRevoke).not.toHaveBeenCalled();
427
- });
428
- });
429
-
430
- describe("POST /api/hub-session/sign-out", () => {
431
- function sessionCookie(): string {
432
- const sealed = seal(
433
- { v: 1, accessToken: CREDENTIAL, expiresAt: Date.now() + 60_000, user: USER },
434
- SESSION_SECRET,
435
- "session",
436
- "ailk-hub-session",
437
- );
438
- return `ailk-hub-session=${sealed}`;
439
- }
440
-
441
- function post(headers: Record<string, string>): Promise<Response> {
442
- return signOut(
443
- new Request(`${SITE}/api/hub-session/sign-out`, {
444
- method: "POST",
445
- headers: { cookie: sessionCookie(), ...headers },
446
- }),
447
- );
448
- }
449
-
450
- it("same-origin: revokes the credential at the hub, clears the cookie and answers 204", async () => {
451
- const res = await post({ "sec-fetch-site": "same-origin", origin: SITE });
452
- expect(res.status).toBe(204);
453
- expect(mockRevoke).toHaveBeenCalledTimes(1);
454
- expect(mockRevoke).toHaveBeenCalledWith(CLIENT, { accessToken: CREDENTIAL });
455
- expect(setCookies(res)).toEqual([
456
- "ailk-hub-session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0",
457
- ]);
458
- });
459
-
460
- it("AC-5: refuses Sec-Fetch-Site cross-site with 403, revoking nothing", async () => {
461
- const res = await post({ "sec-fetch-site": "cross-site" });
462
- expect(res.status).toBe(403);
463
- expect(mockRevoke).not.toHaveBeenCalled();
464
- expect(setCookies(res)).toEqual([]);
465
- });
466
-
467
- it("AC-5: refuses a foreign Origin with 403, revoking nothing", async () => {
468
- const res = await post({ origin: "https://evil.example.com" });
469
- expect(res.status).toBe(403);
470
- expect(mockRevoke).not.toHaveBeenCalled();
471
- });
472
-
473
- it("refuses a request carrying neither header", async () => {
474
- expect((await post({})).status).toBe(403);
475
- expect(mockRevoke).not.toHaveBeenCalled();
476
- });
477
-
478
- it("still signs out when the hub cannot be reached", async () => {
479
- mockRevoke.mockRejectedValue(new Error("network"));
480
- const res = await post({ "sec-fetch-site": "same-origin" });
481
- expect(res.status).toBe(204);
482
- expect(setCookies(res)[0]).toMatch(/Max-Age=0/);
483
- });
484
-
485
- it("is 404 unless the provider is hub", async () => {
486
- mockProvider.value = "site";
487
- expect((await post({ "sec-fetch-site": "same-origin" })).status).toBe(404);
488
- });
489
- });
490
-
491
- // ── #11096 — the spoke-hosted entry ─────────────────────────────────────────
492
-
493
- const SPOKE_KEY = "ailk_spk_test_key";
494
- const CLAIM = "C".repeat(120);
495
-
496
- /** A hub web answer for the mocked `fetch`. */
497
- function hubAnswer(status: number, body: unknown): Response {
498
- return new Response(JSON.stringify(body), {
499
- status,
500
- headers: { "content-type": "application/json" },
501
- });
502
- }
503
-
504
- /** A same-origin form POST to one of the spoke's routes. */
505
- function formPost(
506
- path: string,
507
- fields: Array<[string, string]>,
508
- headers: Record<string, string> = { "sec-fetch-site": "same-origin", origin: SITE },
509
- ): Request {
510
- const body = new URLSearchParams(fields);
511
- return new Request(`${SITE}${path}`, {
512
- method: "POST",
513
- headers: { "content-type": "application/x-www-form-urlencoded", ...headers },
514
- body: body.toString(),
515
- });
516
- }
517
-
518
- /** The one hub web call the mocked `fetch` received. */
519
- function hubCall(): { url: string; headers: Headers; body: Record<string, unknown> } {
520
- expect(mockFetch).toHaveBeenCalledTimes(1);
521
- const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit];
522
- return {
523
- url,
524
- headers: new Headers(init.headers),
525
- body: JSON.parse(String(init.body)) as Record<string, unknown>,
526
- };
527
- }
528
-
529
- /** The flow a 303's flow cookie seals. */
530
- function flowOf(res: Response): Record<string, unknown> {
531
- const flow = cookieValue(res, "ailk-hub-flow");
532
- if (flow === undefined) throw new Error("no flow cookie");
533
- const payload = unseal(flow, SESSION_SECRET, "flow", "ailk-hub-flow");
534
- if (payload === null || typeof payload !== "object") throw new Error("flow did not open");
535
- return payload as Record<string, unknown>;
536
- }
537
-
538
- describe("POST /api/hub-session/email (#11096 D2)", () => {
539
- beforeEach(() => {
540
- process.env.AILK_SPOKE_KEY = SPOKE_KEY;
541
- });
542
-
543
- it("AC-1: a known email → the hub web's email route with the client's two headers; 303 /account?sent=1 with the flow cookie", async () => {
544
- mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
545
- const res = await email(
546
- formPost("/api/hub-session/email", [
547
- ["email", "ada@example.com"],
548
- ["next", "/account"],
549
- ]),
550
- );
551
-
552
- expect(res.status).toBe(303);
553
- expect(res.headers.get("location")).toBe("/account?sent=1");
554
- expect(res.headers.get("cache-control")).toBe("no-store");
555
- expect(res.headers.get("referrer-policy")).toBe("no-referrer");
556
- expect(setCookies(res)).toHaveLength(1);
557
- const flow = flowOf(res);
558
- expect(flow.next).toBe("/account");
559
-
560
- const call = hubCall();
561
- expect(call.url).toBe(`${HUB}/api/auth/hub/email`);
562
- expect(call.headers.get("authorization")).toBe(
563
- `Basic ${Buffer.from(`${CLIENT.clientId}:${CLIENT.clientSecret}`).toString("base64")}`,
564
- );
565
- expect(call.headers.get("x-ailk-spoke-key")).toBe(SPOKE_KEY);
566
- expect(call.body).toEqual({
567
- client_id: CLIENT.clientId,
568
- redirect_uri: `${SITE}/api/hub-session/callback`,
569
- state: flow.state,
570
- code_challenge: createHash("sha256").update(String(flow.verifier)).digest("base64url"),
571
- code_challenge_method: "S256",
572
- email: "ada@example.com",
573
- locale: "en",
574
- });
575
- expect(call.body).not.toHaveProperty("agreements");
576
- });
577
-
578
- it("AC-2: ticked agreements ride to the hub web as their ids", async () => {
579
- mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
580
- const res = await email(
581
- formPost("/api/hub-session/email", [
582
- ["email", "new@example.com"],
583
- ["agreements", "account_terms"],
584
- ]),
585
- );
586
- expect(res.headers.get("location")).toBe("/account?sent=1");
587
- expect(hubCall().body.agreements).toEqual(["account_terms"]);
588
- });
589
-
590
- it("AC-2: the hub's agreements_required → 303 /account?error=agreements with no flow cookie", async () => {
591
- mockFetch.mockResolvedValue(hubAnswer(400, { error: "agreements_required" }));
592
- const res = await email(
593
- formPost("/api/hub-session/email", [
594
- ["email", "new@example.com"],
595
- ["agreements", "account_terms"],
596
- ]),
597
- );
598
- expect(res.status).toBe(303);
599
- expect(res.headers.get("location")).toBe("/account?error=agreements");
600
- expect(setCookies(res)).toEqual([]);
601
- });
602
-
603
- it.each([
604
- ["sign_up_closed", () => mockFetch.mockResolvedValue(hubAnswer(400, { error: "sign_up_closed" }))],
605
- ["a 401", () => mockFetch.mockResolvedValue(hubAnswer(401, { error: "invalid_client" }))],
606
- ["a 429", () => mockFetch.mockResolvedValue(hubAnswer(429, { error: "rate_limited" }))],
607
- ["a throw", () => mockFetch.mockRejectedValue(new Error("network"))],
608
- ])("%s → 303 /account?error=unavailable with no flow cookie", async (_label, arrange) => {
609
- arrange();
610
- const res = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]]));
611
- expect(res.headers.get("location")).toBe("/account?error=unavailable");
612
- expect(setCookies(res)).toEqual([]);
613
- });
614
-
615
- it("returns to the locale's own account page", async () => {
616
- configure({ NEXT_PUBLIC_ENABLED_LOCALES: "en,fr" });
617
- process.env.AILK_SPOKE_KEY = SPOKE_KEY;
618
- mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
619
- const res = await email(
620
- formPost("/api/hub-session/email", [
621
- ["email", "ada@example.com"],
622
- ["next", "/fr/account/inbox"],
623
- ]),
624
- );
625
- expect(res.headers.get("location")).toBe("/fr/account?sent=1");
626
- expect(hubCall().body.locale).toBe("fr");
627
- expect(flowOf(res).next).toBe("/fr/account/inbox");
628
- });
629
-
630
- it.each([
631
- ["a password field (AC-6)", [["email", "ada@example.com"], ["password", "hunter22"]]],
632
- ["a repeated email", [["email", "ada@example.com"], ["email", "eve@example.com"]]],
633
- ["no email", [["next", "/account"]]],
634
- ["a malformed email", [["email", "not-an-email"]]],
635
- ["an unknown agreement shape", [["email", "ada@example.com"], ["agreements", "Not An Id"]]],
636
- ] as Array<[string, Array<[string, string]>]>)("%s → 400, no hub call", async (_label, fields) => {
637
- const res = await email(formPost("/api/hub-session/email", fields));
638
- expect(res.status).toBe(400);
639
- expect(mockFetch).not.toHaveBeenCalled();
640
- expect(setCookies(res)).toEqual([]);
641
- });
642
-
643
- it.each([
644
- ["cross-site", { "sec-fetch-site": "cross-site", origin: SITE }],
645
- ["a foreign Origin", { "sec-fetch-site": "same-origin", origin: "https://evil.example.com" }],
646
- ["neither header", {}],
647
- ] as Array<[string, Record<string, string>]>)("refuses %s with 403, calling nothing", async (_label, headers) => {
648
- const res = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]], headers));
649
- expect(res.status).toBe(403);
650
- expect(mockFetch).not.toHaveBeenCalled();
651
- });
652
-
653
- it("a visitor over the limit gets /account?error=unavailable and no hub call", async () => {
654
- mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
655
- configure({ VERCEL: "1", AILK_BOT_CHECK: "off" });
656
- const visitor = { "sec-fetch-site": "same-origin", origin: SITE, "x-vercel-forwarded-for": "203.0.113.77" };
657
- for (let i = 0; i < 10; i++) {
658
- await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]], visitor));
659
- }
660
- mockFetch.mockClear();
661
- const limited = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]], visitor));
662
- expect(limited.headers.get("location")).toBe("/account?error=unavailable");
663
- expect(mockFetch).not.toHaveBeenCalled();
664
- });
665
-
666
- it("a bot gets /account?error=unavailable and no hub call", async () => {
667
- configure({ VERCEL: "1" });
668
- mockCheckBotId.mockResolvedValue({ isBot: true, classificationReason: "test" });
669
- const res = await email(
670
- formPost("/api/hub-session/email", [["email", "ada@example.com"]], {
671
- "sec-fetch-site": "same-origin",
672
- origin: SITE,
673
- "x-vercel-forwarded-for": "203.0.113.78",
674
- }),
675
- );
676
- expect(res.headers.get("location")).toBe("/account?error=unavailable");
677
- expect(mockFetch).not.toHaveBeenCalled();
678
- });
679
-
680
- it("with no configuration 303s to /account?error=unavailable", async () => {
681
- configure({ AILK_HUB_CLIENT_SECRET: undefined });
682
- const res = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]]));
683
- expect(res.status).toBe(303);
684
- expect(res.headers.get("location")).toBe("/account?error=unavailable");
685
- expect(mockFetch).not.toHaveBeenCalled();
686
- });
687
-
688
- it("is 404 unless the provider is hub", async () => {
689
- mockProvider.value = "site";
690
- const res = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]]));
691
- expect(res.status).toBe(404);
692
- });
693
-
694
- it("never logs the email", async () => {
695
- const warn = jest.spyOn(console, "warn");
696
- const error = jest.spyOn(console, "error");
697
- mockFetch.mockRejectedValue(new Error("network"));
698
- await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]]));
699
- const logged = [...warn.mock.calls, ...error.mock.calls].flat().join(" ");
700
- expect(logged).not.toContain("ada@example.com");
701
- });
702
- });
703
-
704
- describe("GET /api/hub-session/sign-in — Google's provider hint (#11096 D4, AC-3)", () => {
705
- function startWith(query: string): { authorize: URL; payload: Record<string, unknown> } {
706
- const res = signIn(new Request(`${SITE}/api/hub-session/sign-in?${query}`));
707
- expect(res.status).toBe(303);
708
- return { authorize: new URL(res.headers.get("location") ?? ""), payload: flowOf(res) };
709
- }
710
-
711
- it("?provider=google → provider_hint=google; the flow cookie keeps exactly its five keys", () => {
712
- const { authorize, payload } = startWith("next=%2Faccount&provider=google");
713
- expect(authorize.searchParams.getAll("provider_hint")).toEqual(["google"]);
714
- expect(authorize.searchParams.get("code_challenge_method")).toBe("S256");
715
- expect(Object.keys(payload).sort()).toEqual(["expiresAt", "next", "state", "v", "verifier"]);
716
- expect(JSON.stringify(payload)).not.toContain("google");
717
- });
718
-
719
- it.each([
720
- ["another provider", "next=/account&provider=github"],
721
- ["an empty value", "next=/account&provider="],
722
- ["a repeated value", "next=/account&provider=google&provider=google"],
723
- ["no value", "next=/account"],
724
- ])("%s → no provider_hint", (_label, query) => {
725
- const { authorize } = startWith(query);
726
- expect(authorize.searchParams.has("provider_hint")).toBe(false);
727
- });
728
- });
729
-
730
- describe("POST /api/hub-session/open — the purchase link's one click (#11096 D9, AC-4)", () => {
731
- beforeEach(() => {
732
- process.env.AILK_SPOKE_KEY = SPOKE_KEY;
733
- });
734
-
735
- const VERIFY = `${HUB}/api/auth/magic-link/verify?token=t&callbackURL=%2Fapi%2Fauth%2Fhub%2Fcontinue%2Fr`;
736
-
737
- it("spends the claim at the hub web and 303s to its verify URL with the flow cookie", async () => {
738
- mockFetch.mockResolvedValue(hubAnswer(200, { verifyUrl: VERIFY }));
739
- const res = await open(formPost("/api/hub-session/open", [["claim", CLAIM]]));
740
- expect(res.status).toBe(303);
741
- expect(res.headers.get("location")).toBe(VERIFY);
742
- expect(res.headers.get("referrer-policy")).toBe("no-referrer");
743
- const flow = flowOf(res);
744
- expect(flow.next).toBe("/account");
745
- const call = hubCall();
746
- expect(call.url).toBe(`${HUB}/api/auth/hub/purchase`);
747
- expect(call.headers.get("authorization")).toMatch(/^Basic /);
748
- expect(call.headers.get("x-ailk-spoke-key")).toBe(SPOKE_KEY);
749
- expect(call.body).toEqual({
750
- claim: CLAIM,
751
- client_id: CLIENT.clientId,
752
- redirect_uri: `${SITE}/api/hub-session/callback`,
753
- state: flow.state,
754
- code_challenge: createHash("sha256").update(String(flow.verifier)).digest("base64url"),
755
- code_challenge_method: "S256",
756
- });
757
- });
758
-
759
- it("409 account_exists → 303 /account?error=exists, no flow cookie", async () => {
760
- mockFetch.mockResolvedValue(hubAnswer(409, { error: "account_exists" }));
761
- const res = await open(formPost("/api/hub-session/open", [["claim", CLAIM]]));
762
- expect(res.headers.get("location")).toBe("/account?error=exists");
763
- expect(setCookies(res)).toEqual([]);
764
- });
765
-
766
- it.each([
767
- ["410 claim_used", () => mockFetch.mockResolvedValue(hubAnswer(410, { error: "claim_used" }))],
768
- ["410 terms_changed", () => mockFetch.mockResolvedValue(hubAnswer(410, { error: "terms_changed" }))],
769
- ["a verify URL off the hub", () => mockFetch.mockResolvedValue(hubAnswer(200, { verifyUrl: "https://evil.example.com/x" }))],
770
- ["a throw", () => mockFetch.mockRejectedValue(new Error("network"))],
771
- ])("%s → 303 /account?error=claim, no flow cookie", async (_label, arrange) => {
772
- arrange();
773
- const res = await open(formPost("/api/hub-session/open", [["claim", CLAIM]]));
774
- expect(res.headers.get("location")).toBe("/account?error=claim");
775
- expect(setCookies(res)).toEqual([]);
776
- });
777
-
778
- it.each([
779
- ["an added field", [["claim", CLAIM], ["email", "ada@example.com"]]],
780
- ["no claim", []],
781
- ["a malformed claim", [["claim", "not a claim!"]]],
782
- ] as Array<[string, Array<[string, string]>]>)("%s → 400, no hub call", async (_label, fields) => {
783
- const res = await open(formPost("/api/hub-session/open", fields));
784
- expect(res.status).toBe(400);
785
- expect(mockFetch).not.toHaveBeenCalled();
786
- });
787
-
788
- it("refuses a cross-site POST with 403", async () => {
789
- const res = await open(
790
- formPost("/api/hub-session/open", [["claim", CLAIM]], { "sec-fetch-site": "cross-site" }),
791
- );
792
- expect(res.status).toBe(403);
793
- expect(mockFetch).not.toHaveBeenCalled();
794
- });
795
- });
796
-
797
- describe("POST /api/hub-session/one-tap and its nonce (#11096 D10, AC-5)", () => {
798
- const ID_TOKEN = "header.payload.signature";
799
- const SAME_ORIGIN = { "sec-fetch-site": "same-origin", origin: SITE };
800
-
801
- function jsonPost(path: string, body: unknown, headers: Record<string, string> = SAME_ORIGIN): Request {
802
- return new Request(`${SITE}${path}`, {
803
- method: "POST",
804
- headers: { "content-type": "application/json", ...headers },
805
- body: JSON.stringify(body),
806
- });
807
- }
808
-
809
- async function mintNonce(): Promise<{ nonce: string; cookie: string }> {
810
- const res = await oneTapNonce(jsonPost("/api/hub-session/one-tap/nonce", {}));
811
- expect(res.status).toBe(200);
812
- const { nonce } = (await res.json()) as { nonce: string };
813
- const value = cookieValue(res, "ailk-hub-one-tap");
814
- if (value === undefined) throw new Error("no nonce cookie");
815
- return { nonce, cookie: `ailk-hub-one-tap=${value}` };
816
- }
817
-
818
- beforeEach(() => {
819
- configure({ AILK_HUB_ONE_TAP: "on" });
820
- });
821
-
822
- it("the nonce route mints 32 random bytes and seals them into a 300 s cookie", async () => {
823
- const res = await oneTapNonce(jsonPost("/api/hub-session/one-tap/nonce", {}));
824
- expect(res.status).toBe(200);
825
- expect(res.headers.get("cache-control")).toBe("no-store");
826
- const { nonce } = (await res.json()) as { nonce: string };
827
- expect(nonce).toMatch(/^[A-Za-z0-9_-]{43}$/);
828
- const line = setCookies(res).find((c) => c.startsWith("ailk-hub-one-tap="));
829
- expect(line).toMatch(/; HttpOnly/);
830
- expect(line).toMatch(/; Max-Age=300/);
831
- expect(line).not.toContain(nonce);
832
- });
833
-
834
- it("AC-5: a valid credential and nonce cookie → 200 { ok: true }, the session cookie, the nonce cleared", async () => {
835
- mockGoogle.mockResolvedValue({
836
- ok: true,
837
- body: { accessToken: CREDENTIAL, tokenType: "Bearer", expiresIn: 86400, user: USER },
838
- });
839
- const { nonce, cookie } = await mintNonce();
840
- const res = await oneTap(
841
- new Request(`${SITE}/api/hub-session/one-tap`, {
842
- method: "POST",
843
- headers: { "content-type": "application/json", cookie, ...SAME_ORIGIN },
844
- body: JSON.stringify({ credential: ID_TOKEN }),
845
- }),
846
- );
847
- expect(res.status).toBe(200);
848
- expect(await res.json()).toEqual({ ok: true });
849
- expect(mockGoogle).toHaveBeenCalledWith(CLIENT, { idToken: ID_TOKEN, nonce, origin: SITE });
850
- const session = setCookies(res).find((c) => c.startsWith("ailk-hub-session="));
851
- expect(session).toMatch(/; Max-Age=86400/);
852
- expect(setCookies(res).find((c) => c.startsWith("ailk-hub-one-tap="))).toMatch(/Max-Age=0/);
853
- expect(setCookies(res).join("\n")).not.toContain(CREDENTIAL);
854
- });
855
-
856
- it("no nonce cookie → 400 and no hub call", async () => {
857
- const res = await oneTap(jsonPost("/api/hub-session/one-tap", { credential: ID_TOKEN }));
858
- expect(res.status).toBe(400);
859
- expect(mockGoogle).not.toHaveBeenCalled();
860
- });
861
-
862
- it.each([
863
- ["a 404 (no Google account row)", { ok: false, status: 404, body: { error: "not_found" } }],
864
- ["a 401", { ok: false, status: 401, body: { error: "invalid_grant" } }],
865
- ])("the hub's %s → 401 { ok: false }, no session, the nonce cleared", async (_label, answer) => {
866
- mockGoogle.mockResolvedValue(answer);
867
- const { cookie } = await mintNonce();
868
- const res = await oneTap(
869
- new Request(`${SITE}/api/hub-session/one-tap`, {
870
- method: "POST",
871
- headers: { "content-type": "application/json", cookie, ...SAME_ORIGIN },
872
- body: JSON.stringify({ credential: ID_TOKEN }),
873
- }),
874
- );
875
- expect(res.status).toBe(401);
876
- expect(await res.json()).toEqual({ ok: false });
877
- expect(setCookies(res).some((c) => c.startsWith("ailk-hub-session="))).toBe(false);
878
- expect(setCookies(res).find((c) => c.startsWith("ailk-hub-one-tap="))).toMatch(/Max-Age=0/);
879
- });
880
-
881
- it("AC-6: a body with a password field → 400, no hub call", async () => {
882
- const { cookie } = await mintNonce();
883
- const res = await oneTap(
884
- new Request(`${SITE}/api/hub-session/one-tap`, {
885
- method: "POST",
886
- headers: { "content-type": "application/json", cookie, ...SAME_ORIGIN },
887
- body: JSON.stringify({ credential: ID_TOKEN, password: "hunter22" }),
888
- }),
889
- );
890
- expect(res.status).toBe(400);
891
- expect(mockGoogle).not.toHaveBeenCalled();
892
- });
893
-
894
- it("refuses a cross-site POST with 403", async () => {
895
- const nonce = await oneTapNonce(
896
- jsonPost("/api/hub-session/one-tap/nonce", {}, { "sec-fetch-site": "cross-site" }),
897
- );
898
- expect(nonce.status).toBe(403);
899
- const res = await oneTap(
900
- jsonPost("/api/hub-session/one-tap", { credential: ID_TOKEN }, { "sec-fetch-site": "cross-site" }),
901
- );
902
- expect(res.status).toBe(403);
903
- });
904
-
905
- it("both routes 404 while AILK_HUB_ONE_TAP is not on", async () => {
906
- configure();
907
- expect((await oneTapNonce(jsonPost("/api/hub-session/one-tap/nonce", {}))).status).toBe(404);
908
- expect(
909
- (await oneTap(jsonPost("/api/hub-session/one-tap", { credential: ID_TOKEN }))).status,
910
- ).toBe(404);
911
- });
912
- });
913
-
914
- describe("POST /api/hub-session/password — the Security tab's password link (#11162 AC-2)", () => {
915
- const SAME_ORIGIN = { "sec-fetch-site": "same-origin", origin: SITE };
916
- const SESSION_COOKIE = "ailk-hub-session";
917
-
918
- function sessionCookie(secret: string = SESSION_SECRET): string {
919
- const sealed = seal(
920
- { v: 1, accessToken: CREDENTIAL, expiresAt: Date.now() + 60_000, user: USER },
921
- secret,
922
- "session",
923
- SESSION_COOKIE,
924
- );
925
- return `${SESSION_COOKIE}=${sealed}`;
926
- }
927
-
928
- function post(
929
- body: unknown,
930
- headers: Record<string, string> = { ...SAME_ORIGIN, cookie: sessionCookie() },
931
- ): Request {
932
- return new Request(`${SITE}/api/hub-session/password`, {
933
- method: "POST",
934
- headers: { "content-type": "application/json", ...headers },
935
- body: typeof body === "string" ? body : JSON.stringify(body),
936
- });
937
- }
938
-
939
- beforeEach(() => {
940
- process.env.AILK_SPOKE_KEY = SPOKE_KEY;
941
- });
942
-
943
- it("asks the hub web as the spoke's client for the sealed session's person, never a body address; 202 { sent: true }", async () => {
944
- mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
945
- const res = await password(post({ locale: "en" }));
946
-
947
- expect(res.status).toBe(202);
948
- expect(await res.json()).toEqual({ sent: true });
949
- expect(res.headers.get("cache-control")).toBe("no-store");
950
- expect(setCookies(res)).toEqual([]);
951
-
952
- const call = hubCall();
953
- expect(call.url).toBe(`${HUB}/api/auth/hub/password`);
954
- expect(call.headers.get("authorization")).toBe(
955
- `Basic ${Buffer.from(`${CLIENT.clientId}:${CLIENT.clientSecret}`).toString("base64")}`,
956
- );
957
- expect(call.headers.get("x-ailk-spoke-key")).toBe(SPOKE_KEY);
958
- expect(call.body).toEqual({
959
- client_id: CLIENT.clientId,
960
- redirect_uri: `${SITE}/api/hub-session/callback`,
961
- access_token: CREDENTIAL,
962
- locale: "en",
963
- return_path: "/account/security",
964
- });
965
- });
966
-
967
- it("returns the person to the locale's own Security tab", async () => {
968
- configure({ NEXT_PUBLIC_ENABLED_LOCALES: "en,fr" });
969
- mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
970
- await password(post({ locale: "fr" }));
971
- expect(hubCall().body).toMatchObject({ locale: "fr", return_path: "/fr/account/security" });
972
- });
973
-
974
- it("a locale this site does not enable reads as the default", async () => {
975
- mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
976
- await password(post({ locale: "de" }));
977
- expect(hubCall().body).toMatchObject({ locale: "en", return_path: "/account/security" });
978
- });
979
-
980
- it.each([
981
- ["a password field (the spoke never accepts one)", { locale: "en", password: "hunter22" }],
982
- ["an email field (the person is the session's)", { locale: "en", email: "eve@example.com" }],
983
- ["no locale", {}],
984
- ["a malformed locale", { locale: "english" }],
985
- ["a body that is not JSON", "locale=en"],
986
- ] as Array<[string, unknown]>)("%s → 400, no hub call", async (_label, body) => {
987
- const res = await password(post(body));
988
- expect(res.status).toBe(400);
989
- expect(await res.json()).toEqual({ error: "invalid_request" });
990
- expect(mockFetch).not.toHaveBeenCalled();
991
- });
992
-
993
- it("without a session cookie → 401, no hub call", async () => {
994
- const res = await password(post({ locale: "en" }, SAME_ORIGIN));
995
- expect(res.status).toBe(401);
996
- expect(await res.json()).toEqual({ error: "no_session" });
997
- expect(mockFetch).not.toHaveBeenCalled();
998
- });
999
-
1000
- it("a session sealed under another key → 401, no hub call", async () => {
1001
- const res = await password(
1002
- post({ locale: "en" }, { ...SAME_ORIGIN, cookie: sessionCookie("x".repeat(43)) }),
1003
- );
1004
- expect(res.status).toBe(401);
1005
- expect(mockFetch).not.toHaveBeenCalled();
1006
- });
1007
-
1008
- it.each([
1009
- ["cross-site", { "sec-fetch-site": "cross-site", origin: SITE }],
1010
- ["a foreign Origin", { "sec-fetch-site": "same-origin", origin: "https://evil.example.com" }],
1011
- ["neither header", {}],
1012
- ] as Array<[string, Record<string, string>]>)("refuses %s with 403, calling nothing", async (_label, headers) => {
1013
- const res = await password(post({ locale: "en" }, { ...headers, cookie: sessionCookie() }));
1014
- expect(res.status).toBe(403);
1015
- expect(mockFetch).not.toHaveBeenCalled();
1016
- });
1017
-
1018
- it("the hub's invalid_grant — a credential it no longer honours — → 401", async () => {
1019
- mockFetch.mockResolvedValue(hubAnswer(400, { error: "invalid_grant" }));
1020
- const res = await password(post({ locale: "en" }));
1021
- expect(res.status).toBe(401);
1022
- expect(await res.json()).toEqual({ error: "invalid_session" });
1023
- });
1024
-
1025
- it.each([
1026
- ["a 401", () => mockFetch.mockResolvedValue(hubAnswer(401, { error: "invalid_client" }))],
1027
- ["a 429", () => mockFetch.mockResolvedValue(hubAnswer(429, { error: "rate_limited" }))],
1028
- ["a 503", () => mockFetch.mockResolvedValue(hubAnswer(503, { error: "temporarily_unavailable" }))],
1029
- ["a throw", () => mockFetch.mockRejectedValue(new Error("network"))],
1030
- ])("%s → 503 temporarily_unavailable", async (_label, arrange) => {
1031
- arrange();
1032
- const res = await password(post({ locale: "en" }));
1033
- expect(res.status).toBe(503);
1034
- expect(await res.json()).toEqual({ error: "temporarily_unavailable" });
1035
- });
1036
-
1037
- it("a visitor over the limit gets 429 and no hub call", async () => {
1038
- configure({ VERCEL: "1", AILK_BOT_CHECK: "off" });
1039
- mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
1040
- const visitor = { ...SAME_ORIGIN, cookie: sessionCookie(), "x-vercel-forwarded-for": "203.0.113.79" };
1041
- for (let i = 0; i < 10; i++) {
1042
- expect((await password(post({ locale: "en" }, visitor))).status).toBe(202);
1043
- }
1044
- mockFetch.mockClear();
1045
- const limited = await password(post({ locale: "en" }, visitor));
1046
- expect(limited.status).toBe(429);
1047
- expect(mockFetch).not.toHaveBeenCalled();
1048
- });
1049
-
1050
- it("a bot gets 503 and no hub call", async () => {
1051
- configure({ VERCEL: "1" });
1052
- mockCheckBotId.mockResolvedValue({ isBot: true, classificationReason: "test" });
1053
- const res = await password(
1054
- post({ locale: "en" }, { ...SAME_ORIGIN, cookie: sessionCookie(), "x-vercel-forwarded-for": "203.0.113.80" }),
1055
- );
1056
- expect(res.status).toBe(503);
1057
- expect(mockFetch).not.toHaveBeenCalled();
1058
- });
1059
-
1060
- it("with no configuration → 503, no hub call", async () => {
1061
- configure({ AILK_HUB_CLIENT_SECRET: undefined });
1062
- const res = await password(post({ locale: "en" }));
1063
- expect(res.status).toBe(503);
1064
- expect(mockFetch).not.toHaveBeenCalled();
1065
- });
1066
-
1067
- it("is 404 unless the provider is hub", async () => {
1068
- mockProvider.value = "site";
1069
- const res = await password(post({ locale: "en" }));
1070
- expect(res.status).toBe(404);
1071
- });
1072
-
1073
- it("never logs the credential or the address", async () => {
1074
- const warn = jest.spyOn(console, "warn");
1075
- const error = jest.spyOn(console, "error");
1076
- mockFetch.mockRejectedValue(new Error("network"));
1077
- await password(post({ locale: "en" }));
1078
- const logged = [...warn.mock.calls, ...error.mock.calls].flat().join(" ");
1079
- expect(logged).not.toContain(CREDENTIAL);
1080
- expect(logged).not.toContain(USER.email);
1081
- });
1082
- });
1083
-
1084
- describe("GET /api/hub-session/password/return — where the hub's set-password page lands the person (#11162 AC-2)", () => {
1085
- const SESSION_COOKIE = "ailk-hub-session";
1086
- const CLEARED = /^ailk-hub-session=; Path=\/; HttpOnly; SameSite=Lax; Max-Age=0$/;
1087
-
1088
- function sessionCookie(): string {
1089
- const sealed = seal(
1090
- { v: 1, accessToken: CREDENTIAL, expiresAt: Date.now() + 60_000, user: USER },
1091
- SESSION_SECRET,
1092
- "session",
1093
- SESSION_COOKIE,
1094
- );
1095
- return `${SESSION_COOKIE}=${sealed}`;
1096
- }
1097
-
1098
- /** `cookie: null` is a request with no session cookie. */
1099
- function get(next: string | null, cookie: string | null = sessionCookie()): Promise<Response> {
1100
- const url = new URL("/api/hub-session/password/return", SITE);
1101
- if (next !== null) url.searchParams.set("next", next);
1102
- return passwordReturn(new Request(url.toString(), { headers: cookie === null ? {} : { cookie } }));
1103
- }
1104
-
1105
- it("a credential the hub no longer honours (the reset revoked it): the session cookie is cleared and the person lands on the tab, whose gate signs them back in", async () => {
1106
- mockMe.mockResolvedValue({ ok: false, status: 401, body: { ok: false } });
1107
- const res = await get("/account/security");
1108
- expect(res.status).toBe(303);
1109
- expect(res.headers.get("location")).toBe("/account/security");
1110
- expect(res.headers.get("cache-control")).toBe("no-store");
1111
- expect(setCookies(res)).toHaveLength(1);
1112
- expect(setCookies(res)[0]).toMatch(CLEARED);
1113
- expect(mockMe).toHaveBeenCalledWith({ headers: { authorization: `Bearer ${CREDENTIAL}` } });
1114
- });
1115
-
1116
- it("a credential the hub still honours keeps its cookie", async () => {
1117
- mockMe.mockResolvedValue({ ok: true, status: 200, body: { user: USER, billingCustomerId: null, hasPassword: true } });
1118
- const res = await get("/fr/account/security");
1119
- expect(res.headers.get("location")).toBe("/fr/account/security");
1120
- expect(setCookies(res)).toEqual([]);
1121
- });
1122
-
1123
- it.each([
1124
- ["cannot be reached", () => mockMe.mockRejectedValue(new Error("network"))],
1125
- ["answers a limit (429)", () => mockMe.mockResolvedValue({ ok: false, status: 429, body: { ok: false } })],
1126
- ["answers an outage (503)", () => mockMe.mockResolvedValue({ ok: false, status: 503, body: { ok: false } })],
1127
- ["refuses the spoke, not the credential (403)", () => mockMe.mockResolvedValue({ ok: false, status: 403, body: { ok: false } })],
1128
- ])("a hub that %s clears nothing — only its 401 does", async (_label, arrange) => {
1129
- arrange();
1130
- const res = await get("/account/security");
1131
- expect(res.headers.get("location")).toBe("/account/security");
1132
- expect(setCookies(res)).toEqual([]);
1133
- });
1134
-
1135
- it("with no session cookie it only lands, asking the hub nothing", async () => {
1136
- const res = await get("/account/security", null);
1137
- expect(res.status).toBe(303);
1138
- expect(res.headers.get("location")).toBe("/account/security");
1139
- expect(setCookies(res)).toEqual([]);
1140
- expect(mockMe).not.toHaveBeenCalled();
1141
- });
1142
-
1143
- it.each([
1144
- ["an absolute URL", "https://evil.example.com/account/security"],
1145
- ["a protocol-relative path", "//evil.example.com/account/security"],
1146
- ["a route-handler path", "/api/hub-session/sign-out"],
1147
- ["no next", null],
1148
- ])("%s as next lands on /account", async (_label, next) => {
1149
- mockMe.mockResolvedValue({ ok: true, status: 200, body: {} });
1150
- const res = await get(next);
1151
- expect(res.headers.get("location")).toBe("/account");
1152
- });
1153
-
1154
- it("with no configuration lands home", async () => {
1155
- configure({ AILK_HUB_CLIENT_SECRET: undefined });
1156
- const res = await get("/account/security");
1157
- expect(res.headers.get("location")).toBe("/");
1158
- expect(mockMe).not.toHaveBeenCalled();
1159
- });
1160
-
1161
- it("is 404 unless the provider is hub", async () => {
1162
- mockProvider.value = "site";
1163
- const res = await get("/account/security");
1164
- expect(res.status).toBe(404);
1165
- });
1166
- });