@robelest/convex-auth 0.0.4-preview.18 → 0.0.4-preview.19

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 (541) hide show
  1. package/README.md +6 -3
  2. package/dist/authorization/index.d.ts +46 -0
  3. package/dist/authorization/index.d.ts.map +1 -1
  4. package/dist/authorization/index.js +46 -0
  5. package/dist/authorization/index.js.map +1 -1
  6. package/dist/bin.cjs +21 -13
  7. package/dist/client/core/types.d.ts +20 -0
  8. package/dist/client/core/types.d.ts.map +1 -0
  9. package/dist/client/index.d.ts +2 -16
  10. package/dist/client/index.d.ts.map +1 -1
  11. package/dist/client/index.js +67 -565
  12. package/dist/client/index.js.map +1 -1
  13. package/dist/component/_generated/api.d.ts +40 -12
  14. package/dist/component/_generated/api.d.ts.map +1 -1
  15. package/dist/component/_generated/api.js.map +1 -1
  16. package/dist/component/_generated/component.d.ts +1306 -1344
  17. package/dist/component/_generated/component.d.ts.map +1 -1
  18. package/dist/component/client/core/types.d.ts +2 -0
  19. package/dist/component/client/index.d.ts +2 -2
  20. package/dist/component/model.d.ts +80 -80
  21. package/dist/component/model.d.ts.map +1 -1
  22. package/dist/component/model.js +5 -1
  23. package/dist/component/model.js.map +1 -1
  24. package/dist/component/providers/credentials.d.ts +3 -2
  25. package/dist/component/providers/credentials.d.ts.map +1 -1
  26. package/dist/component/providers/email.d.ts +30 -0
  27. package/dist/component/providers/email.d.ts.map +1 -1
  28. package/dist/component/providers/phone.d.ts +28 -0
  29. package/dist/component/providers/phone.d.ts.map +1 -1
  30. package/dist/component/public/enterprise/audit.d.ts +73 -0
  31. package/dist/component/public/enterprise/audit.d.ts.map +1 -0
  32. package/dist/component/public/enterprise/audit.js +108 -0
  33. package/dist/component/public/enterprise/audit.js.map +1 -0
  34. package/dist/component/public/enterprise/core.d.ts +176 -0
  35. package/dist/component/public/enterprise/core.d.ts.map +1 -0
  36. package/dist/component/public/enterprise/core.js +292 -0
  37. package/dist/component/public/enterprise/core.js.map +1 -0
  38. package/dist/component/public/enterprise/domains.d.ts +174 -0
  39. package/dist/component/public/enterprise/domains.d.ts.map +1 -0
  40. package/dist/component/public/enterprise/domains.js +271 -0
  41. package/dist/component/public/enterprise/domains.js.map +1 -0
  42. package/dist/component/public/enterprise/scim.d.ts +245 -0
  43. package/dist/component/public/enterprise/scim.d.ts.map +1 -0
  44. package/dist/component/public/enterprise/scim.js +344 -0
  45. package/dist/component/public/enterprise/scim.js.map +1 -0
  46. package/dist/component/public/enterprise/secrets.d.ts +78 -0
  47. package/dist/component/public/enterprise/secrets.d.ts.map +1 -0
  48. package/dist/component/public/enterprise/secrets.js +118 -0
  49. package/dist/component/public/enterprise/secrets.js.map +1 -0
  50. package/dist/component/public/enterprise/webhooks.d.ts +211 -0
  51. package/dist/component/public/enterprise/webhooks.d.ts.map +1 -0
  52. package/dist/component/public/enterprise/webhooks.js +300 -0
  53. package/dist/component/public/enterprise/webhooks.js.map +1 -0
  54. package/dist/component/public/factors/devices.d.ts +157 -0
  55. package/dist/component/public/factors/devices.d.ts.map +1 -0
  56. package/dist/component/public/factors/devices.js +216 -0
  57. package/dist/component/public/factors/devices.js.map +1 -0
  58. package/dist/component/public/factors/passkeys.d.ts +175 -0
  59. package/dist/component/public/factors/passkeys.d.ts.map +1 -0
  60. package/dist/component/public/factors/passkeys.js +238 -0
  61. package/dist/component/public/factors/passkeys.js.map +1 -0
  62. package/dist/component/public/factors/totp.d.ts +189 -0
  63. package/dist/component/public/factors/totp.d.ts.map +1 -0
  64. package/dist/component/public/factors/totp.js +254 -0
  65. package/dist/component/public/factors/totp.js.map +1 -0
  66. package/dist/component/public/groups/core.d.ts +137 -0
  67. package/dist/component/public/groups/core.d.ts.map +1 -0
  68. package/dist/component/public/groups/core.js +321 -0
  69. package/dist/component/public/groups/core.js.map +1 -0
  70. package/dist/component/public/groups/invites.d.ts +217 -0
  71. package/dist/component/public/groups/invites.d.ts.map +1 -0
  72. package/dist/component/public/groups/invites.js +457 -0
  73. package/dist/component/public/groups/invites.js.map +1 -0
  74. package/dist/component/public/groups/members.d.ts +204 -0
  75. package/dist/component/public/groups/members.d.ts.map +1 -0
  76. package/dist/component/public/groups/members.js +355 -0
  77. package/dist/component/public/groups/members.js.map +1 -0
  78. package/dist/component/public/identity/accounts.d.ts +147 -0
  79. package/dist/component/public/identity/accounts.d.ts.map +1 -0
  80. package/dist/component/public/identity/accounts.js +200 -0
  81. package/dist/component/public/identity/accounts.js.map +1 -0
  82. package/dist/component/public/identity/codes.d.ts +104 -0
  83. package/dist/component/public/identity/codes.d.ts.map +1 -0
  84. package/dist/component/public/identity/codes.js +140 -0
  85. package/dist/component/public/identity/codes.js.map +1 -0
  86. package/dist/component/public/identity/sessions.d.ts +128 -0
  87. package/dist/component/public/identity/sessions.d.ts.map +1 -0
  88. package/dist/component/public/identity/sessions.js +192 -0
  89. package/dist/component/public/identity/sessions.js.map +1 -0
  90. package/dist/component/public/identity/tokens.d.ts +169 -0
  91. package/dist/component/public/identity/tokens.d.ts.map +1 -0
  92. package/dist/component/public/identity/tokens.js +227 -0
  93. package/dist/component/public/identity/tokens.js.map +1 -0
  94. package/dist/component/public/identity/users.d.ts +212 -0
  95. package/dist/component/public/identity/users.d.ts.map +1 -0
  96. package/dist/component/public/identity/users.js +311 -0
  97. package/dist/component/public/identity/users.js.map +1 -0
  98. package/dist/component/public/identity/verifiers.d.ts +116 -0
  99. package/dist/component/public/identity/verifiers.d.ts.map +1 -0
  100. package/dist/component/public/identity/verifiers.js +154 -0
  101. package/dist/component/public/identity/verifiers.js.map +1 -0
  102. package/dist/component/public/security/keys.d.ts +209 -0
  103. package/dist/component/public/security/keys.d.ts.map +1 -0
  104. package/dist/component/public/security/keys.js +319 -0
  105. package/dist/component/public/security/keys.js.map +1 -0
  106. package/dist/component/public/security/limits.d.ts +114 -0
  107. package/dist/component/public/security/limits.d.ts.map +1 -0
  108. package/dist/component/public/security/limits.js +169 -0
  109. package/dist/component/public/security/limits.js.map +1 -0
  110. package/dist/component/public.d.ts +22 -7
  111. package/dist/component/public.js +21 -6
  112. package/dist/component/schema.d.ts +288 -288
  113. package/dist/component/server/auth.d.ts +212 -25
  114. package/dist/component/server/auth.d.ts.map +1 -1
  115. package/dist/component/server/auth.js +68 -4
  116. package/dist/component/server/auth.js.map +1 -1
  117. package/dist/component/server/authError.js +34 -0
  118. package/dist/component/server/authError.js.map +1 -0
  119. package/dist/component/server/{providers.js → config.js} +2 -2
  120. package/dist/component/server/config.js.map +1 -0
  121. package/dist/component/server/{domains/core.js → core.js} +107 -88
  122. package/dist/component/server/core.js.map +1 -0
  123. package/dist/component/server/{provider.js → crypto.js} +3 -3
  124. package/dist/component/server/crypto.js.map +1 -0
  125. package/dist/component/server/device.js +1 -1
  126. package/dist/component/server/device.js.map +1 -1
  127. package/dist/component/server/enterprise/config.js +46 -0
  128. package/dist/component/server/enterprise/config.js.map +1 -0
  129. package/dist/component/server/{domains/sso.js → enterprise/domain.js} +6 -5
  130. package/dist/component/server/enterprise/domain.js.map +1 -0
  131. package/dist/component/server/enterprise/http.js +766 -0
  132. package/dist/component/server/enterprise/http.js.map +1 -0
  133. package/dist/component/server/enterprise/oidc.js +248 -0
  134. package/dist/component/server/enterprise/oidc.js.map +1 -0
  135. package/dist/component/server/enterprise/policy.js +85 -0
  136. package/dist/component/server/enterprise/policy.js.map +1 -0
  137. package/dist/component/server/enterprise/saml.js +338 -0
  138. package/dist/component/server/enterprise/saml.js.map +1 -0
  139. package/dist/component/server/enterprise/scim.js +97 -0
  140. package/dist/component/server/enterprise/scim.js.map +1 -0
  141. package/dist/component/server/enterprise/shared.js +51 -0
  142. package/dist/component/server/enterprise/shared.js.map +1 -0
  143. package/dist/component/server/errors.js.map +1 -1
  144. package/dist/component/server/http.js +2 -1
  145. package/dist/component/server/http.js.map +1 -1
  146. package/dist/component/server/identity.js +1 -1
  147. package/dist/component/server/identity.js.map +1 -1
  148. package/dist/component/server/{ratelimit.js → limits.js} +3 -3
  149. package/dist/component/server/limits.js.map +1 -0
  150. package/dist/component/server/mutations/account.js +3 -3
  151. package/dist/component/server/mutations/account.js.map +1 -1
  152. package/dist/component/server/mutations/code.js +2 -2
  153. package/dist/component/server/mutations/code.js.map +1 -1
  154. package/dist/component/server/mutations/invalidate.js +1 -1
  155. package/dist/component/server/mutations/invalidate.js.map +1 -1
  156. package/dist/component/server/mutations/oauth.js +5 -3
  157. package/dist/component/server/mutations/oauth.js.map +1 -1
  158. package/dist/component/server/mutations/refresh.js +1 -1
  159. package/dist/component/server/mutations/refresh.js.map +1 -1
  160. package/dist/component/server/mutations/register.js +3 -3
  161. package/dist/component/server/mutations/register.js.map +1 -1
  162. package/dist/component/server/mutations/retrieve.js +4 -4
  163. package/dist/component/server/mutations/retrieve.js.map +1 -1
  164. package/dist/component/server/mutations/signature.js +2 -2
  165. package/dist/component/server/mutations/signature.js.map +1 -1
  166. package/dist/component/server/mutations/signin.js +1 -1
  167. package/dist/component/server/mutations/signin.js.map +1 -1
  168. package/dist/component/server/mutations/signout.js +1 -1
  169. package/dist/component/server/mutations/signout.js.map +1 -1
  170. package/dist/component/server/mutations/store/refs.js +15 -0
  171. package/dist/component/server/mutations/store/refs.js.map +1 -0
  172. package/dist/component/server/mutations/store.js +80 -10
  173. package/dist/component/server/mutations/store.js.map +1 -1
  174. package/dist/component/server/mutations/verifier.js +1 -1
  175. package/dist/component/server/mutations/verifier.js.map +1 -1
  176. package/dist/component/server/mutations/verify.js +4 -3
  177. package/dist/component/server/mutations/verify.js.map +1 -1
  178. package/dist/component/server/oauth.js +1 -1
  179. package/dist/component/server/oauth.js.map +1 -1
  180. package/dist/component/server/passkey.js +2 -1
  181. package/dist/component/server/passkey.js.map +1 -1
  182. package/dist/component/server/redirects.js +1 -1
  183. package/dist/component/server/redirects.js.map +1 -1
  184. package/dist/component/server/refresh.js +1 -1
  185. package/dist/component/server/refresh.js.map +1 -1
  186. package/dist/component/server/{factory.d.ts → runtime.d.ts} +2 -2
  187. package/dist/component/server/runtime.d.ts.map +1 -0
  188. package/dist/component/server/runtime.js +413 -0
  189. package/dist/component/server/runtime.js.map +1 -0
  190. package/dist/component/server/signin.js +2 -1
  191. package/dist/component/server/signin.js.map +1 -1
  192. package/dist/component/server/totp.js +2 -1
  193. package/dist/component/server/totp.js.map +1 -1
  194. package/dist/component/server/types.d.ts +225 -41
  195. package/dist/component/server/types.d.ts.map +1 -1
  196. package/dist/component/server/types.js.map +1 -1
  197. package/dist/component/server/users.js +1 -1
  198. package/dist/component/server/users.js.map +1 -1
  199. package/dist/component/server/utils.js +1 -1
  200. package/dist/component/server/utils.js.map +1 -1
  201. package/dist/core/types.d.ts +369 -0
  202. package/dist/core/types.d.ts.map +1 -0
  203. package/dist/factors/device.js +105 -0
  204. package/dist/factors/device.js.map +1 -0
  205. package/dist/factors/passkey.js +181 -0
  206. package/dist/factors/passkey.js.map +1 -0
  207. package/dist/factors/totp.js +122 -0
  208. package/dist/factors/totp.js.map +1 -0
  209. package/dist/providers/credentials.d.ts +5 -2
  210. package/dist/providers/credentials.d.ts.map +1 -1
  211. package/dist/providers/credentials.js +2 -0
  212. package/dist/providers/credentials.js.map +1 -1
  213. package/dist/providers/email.d.ts +30 -0
  214. package/dist/providers/email.d.ts.map +1 -1
  215. package/dist/providers/email.js +24 -0
  216. package/dist/providers/email.js.map +1 -1
  217. package/dist/providers/phone.d.ts +28 -0
  218. package/dist/providers/phone.d.ts.map +1 -1
  219. package/dist/providers/phone.js +22 -0
  220. package/dist/providers/phone.js.map +1 -1
  221. package/dist/runtime/browser.js +68 -0
  222. package/dist/runtime/browser.js.map +1 -0
  223. package/dist/runtime/invite.js +51 -0
  224. package/dist/runtime/invite.js.map +1 -0
  225. package/dist/runtime/proxy.js +70 -0
  226. package/dist/runtime/proxy.js.map +1 -0
  227. package/dist/runtime/storage.js +37 -0
  228. package/dist/runtime/storage.js.map +1 -0
  229. package/dist/server/auth.d.ts +218 -28
  230. package/dist/server/auth.d.ts.map +1 -1
  231. package/dist/server/auth.js +68 -4
  232. package/dist/server/auth.js.map +1 -1
  233. package/dist/server/{fx.d.ts → authError.d.ts} +25 -15
  234. package/dist/server/authError.d.ts.map +1 -0
  235. package/dist/server/authError.js +34 -0
  236. package/dist/server/authError.js.map +1 -0
  237. package/dist/server/{providers.js → config.js} +2 -2
  238. package/dist/server/config.js.map +1 -0
  239. package/dist/server/core.d.ts +1436 -0
  240. package/dist/server/core.d.ts.map +1 -0
  241. package/dist/server/{domains/core.js → core.js} +107 -88
  242. package/dist/server/core.js.map +1 -0
  243. package/dist/server/{provider.d.ts → crypto.d.ts} +2 -2
  244. package/dist/server/crypto.d.ts.map +1 -0
  245. package/dist/server/{provider.js → crypto.js} +3 -3
  246. package/dist/{component/server/provider.js.map → server/crypto.js.map} +1 -1
  247. package/dist/server/device.js +1 -1
  248. package/dist/server/device.js.map +1 -1
  249. package/dist/server/enterprise/config.js +46 -0
  250. package/dist/server/enterprise/config.js.map +1 -0
  251. package/dist/server/{domains/sso.d.ts → enterprise/domain.d.ts} +4 -4
  252. package/dist/server/enterprise/domain.d.ts.map +1 -0
  253. package/dist/server/{domains/sso.js → enterprise/domain.js} +6 -5
  254. package/dist/server/enterprise/domain.js.map +1 -0
  255. package/dist/server/enterprise/http.d.ts +26 -0
  256. package/dist/server/enterprise/http.d.ts.map +1 -0
  257. package/dist/server/enterprise/http.js +766 -0
  258. package/dist/server/enterprise/http.js.map +1 -0
  259. package/dist/server/enterprise/oidc.js +248 -0
  260. package/dist/server/enterprise/oidc.js.map +1 -0
  261. package/dist/server/enterprise/policy.js +85 -0
  262. package/dist/server/enterprise/policy.js.map +1 -0
  263. package/dist/server/enterprise/saml.d.ts +1 -0
  264. package/dist/server/enterprise/saml.js +338 -0
  265. package/dist/server/enterprise/saml.js.map +1 -0
  266. package/dist/server/enterprise/scim.d.ts +1 -0
  267. package/dist/server/enterprise/scim.js +97 -0
  268. package/dist/server/enterprise/scim.js.map +1 -0
  269. package/dist/server/enterprise/shared.d.ts +5 -0
  270. package/dist/server/enterprise/shared.d.ts.map +1 -0
  271. package/dist/server/enterprise/shared.js +51 -0
  272. package/dist/server/enterprise/shared.js.map +1 -0
  273. package/dist/server/enterprise/validators.d.ts +1 -0
  274. package/dist/server/{enterpriseValidators.js → enterprise/validators.js} +2 -2
  275. package/dist/server/enterprise/validators.js.map +1 -0
  276. package/dist/server/errors.d.ts +2 -0
  277. package/dist/server/errors.d.ts.map +1 -1
  278. package/dist/server/errors.js +2 -0
  279. package/dist/server/errors.js.map +1 -1
  280. package/dist/server/http.d.ts +2 -2
  281. package/dist/server/http.d.ts.map +1 -1
  282. package/dist/server/http.js +2 -1
  283. package/dist/server/http.js.map +1 -1
  284. package/dist/server/identity.js +1 -1
  285. package/dist/server/identity.js.map +1 -1
  286. package/dist/server/index.d.ts +4 -705
  287. package/dist/server/index.js +4 -1367
  288. package/dist/server/limits.d.ts +1 -0
  289. package/dist/server/{ratelimit.js → limits.js} +3 -3
  290. package/dist/server/limits.js.map +1 -0
  291. package/dist/server/mounts.d.ts +647 -0
  292. package/dist/server/mounts.d.ts.map +1 -0
  293. package/dist/server/mounts.js +643 -0
  294. package/dist/server/mounts.js.map +1 -0
  295. package/dist/server/mutations/account.d.ts +8 -8
  296. package/dist/server/mutations/account.js +3 -3
  297. package/dist/server/mutations/account.js.map +1 -1
  298. package/dist/server/mutations/code.d.ts +13 -13
  299. package/dist/server/mutations/code.js +2 -2
  300. package/dist/server/mutations/code.js.map +1 -1
  301. package/dist/server/mutations/index.d.ts +8 -312
  302. package/dist/server/mutations/index.js +14 -84
  303. package/dist/server/mutations/invalidate.d.ts +5 -5
  304. package/dist/server/mutations/invalidate.d.ts.map +1 -1
  305. package/dist/server/mutations/invalidate.js +1 -1
  306. package/dist/server/mutations/invalidate.js.map +1 -1
  307. package/dist/server/mutations/oauth.d.ts +9 -9
  308. package/dist/server/mutations/oauth.d.ts.map +1 -1
  309. package/dist/server/mutations/oauth.js +5 -3
  310. package/dist/server/mutations/oauth.js.map +1 -1
  311. package/dist/server/mutations/refresh.d.ts +4 -4
  312. package/dist/server/mutations/refresh.js +1 -1
  313. package/dist/server/mutations/refresh.js.map +1 -1
  314. package/dist/server/mutations/register.d.ts +10 -10
  315. package/dist/server/mutations/register.d.ts.map +1 -1
  316. package/dist/server/mutations/register.js +3 -3
  317. package/dist/server/mutations/register.js.map +1 -1
  318. package/dist/server/mutations/retrieve.d.ts +8 -10
  319. package/dist/server/mutations/retrieve.d.ts.map +1 -1
  320. package/dist/server/mutations/retrieve.js +5 -7
  321. package/dist/server/mutations/retrieve.js.map +1 -1
  322. package/dist/server/mutations/signature.d.ts +6 -6
  323. package/dist/server/mutations/signature.d.ts.map +1 -1
  324. package/dist/server/mutations/signature.js +2 -2
  325. package/dist/server/mutations/signature.js.map +1 -1
  326. package/dist/server/mutations/signin.d.ts +1 -1
  327. package/dist/server/mutations/signin.js +1 -1
  328. package/dist/server/mutations/signin.js.map +1 -1
  329. package/dist/server/mutations/signout.d.ts +1 -1
  330. package/dist/server/mutations/signout.js +1 -1
  331. package/dist/server/mutations/signout.js.map +1 -1
  332. package/dist/server/mutations/store/refs.d.ts +12 -0
  333. package/dist/server/mutations/store/refs.d.ts.map +1 -0
  334. package/dist/server/mutations/store/refs.js +15 -0
  335. package/dist/server/mutations/store/refs.js.map +1 -0
  336. package/dist/server/mutations/store.d.ts +303 -9
  337. package/dist/server/mutations/store.d.ts.map +1 -1
  338. package/dist/server/mutations/store.js +80 -10
  339. package/dist/server/mutations/store.js.map +1 -1
  340. package/dist/server/mutations/verifier.d.ts +1 -1
  341. package/dist/server/mutations/verifier.js +1 -1
  342. package/dist/server/mutations/verifier.js.map +1 -1
  343. package/dist/server/mutations/verify.d.ts +8 -8
  344. package/dist/server/mutations/verify.d.ts.map +1 -1
  345. package/dist/server/mutations/verify.js +4 -3
  346. package/dist/server/mutations/verify.js.map +1 -1
  347. package/dist/server/oauth.js +1 -1
  348. package/dist/server/oauth.js.map +1 -1
  349. package/dist/server/passkey.d.ts +2 -2
  350. package/dist/server/passkey.d.ts.map +1 -1
  351. package/dist/server/passkey.js +3 -2
  352. package/dist/server/passkey.js.map +1 -1
  353. package/dist/server/redirects.js +1 -1
  354. package/dist/server/redirects.js.map +1 -1
  355. package/dist/server/refresh.js +1 -1
  356. package/dist/server/refresh.js.map +1 -1
  357. package/dist/server/{factory.d.ts → runtime.d.ts} +16 -16
  358. package/dist/server/runtime.d.ts.map +1 -0
  359. package/dist/server/runtime.js +413 -0
  360. package/dist/server/runtime.js.map +1 -0
  361. package/dist/server/signin.js +3 -2
  362. package/dist/server/signin.js.map +1 -1
  363. package/dist/server/ssr.d.ts +226 -0
  364. package/dist/server/ssr.d.ts.map +1 -0
  365. package/dist/server/ssr.js +786 -0
  366. package/dist/server/ssr.js.map +1 -0
  367. package/dist/server/totp.js +2 -1
  368. package/dist/server/totp.js.map +1 -1
  369. package/dist/server/types.d.ts +242 -42
  370. package/dist/server/types.d.ts.map +1 -1
  371. package/dist/server/types.js +12 -1
  372. package/dist/server/types.js.map +1 -1
  373. package/dist/server/users.js +1 -1
  374. package/dist/server/users.js.map +1 -1
  375. package/dist/server/utils.js +1 -1
  376. package/dist/server/utils.js.map +1 -1
  377. package/package.json +3 -4
  378. package/src/authorization/index.ts +46 -0
  379. package/src/cli/index.ts +38 -20
  380. package/src/client/core/types.ts +437 -0
  381. package/src/client/factors/device.ts +160 -0
  382. package/src/client/factors/passkey.ts +282 -0
  383. package/src/client/factors/totp.ts +150 -0
  384. package/src/client/index.ts +133 -1267
  385. package/src/client/runtime/browser.ts +112 -0
  386. package/src/client/runtime/invite.ts +65 -0
  387. package/src/client/runtime/proxy.ts +111 -0
  388. package/src/client/runtime/storage.ts +79 -0
  389. package/src/component/_generated/api.ts +40 -12
  390. package/src/component/_generated/component.ts +1772 -1798
  391. package/src/component/model.ts +6 -0
  392. package/src/component/public/enterprise/audit.ts +120 -0
  393. package/src/component/public/enterprise/core.ts +354 -0
  394. package/src/component/public/enterprise/domains.ts +323 -0
  395. package/src/component/public/enterprise/scim.ts +396 -0
  396. package/src/component/public/enterprise/secrets.ts +132 -0
  397. package/src/component/public/enterprise/webhooks.ts +306 -0
  398. package/src/component/public/factors/devices.ts +223 -0
  399. package/src/component/public/factors/passkeys.ts +242 -0
  400. package/src/component/public/factors/totp.ts +258 -0
  401. package/src/component/public/groups/core.ts +481 -0
  402. package/src/component/public/groups/invites.ts +602 -0
  403. package/src/component/public/groups/members.ts +409 -0
  404. package/src/component/public/identity/accounts.ts +206 -0
  405. package/src/component/public/identity/codes.ts +148 -0
  406. package/src/component/public/identity/sessions.ts +209 -0
  407. package/src/component/public/identity/tokens.ts +250 -0
  408. package/src/component/public/identity/users.ts +354 -0
  409. package/src/component/public/identity/verifiers.ts +157 -0
  410. package/src/component/public/security/keys.ts +365 -0
  411. package/src/component/public/security/limits.ts +173 -0
  412. package/src/component/public.ts +27 -5
  413. package/src/providers/credentials.ts +4 -5
  414. package/src/providers/email.ts +30 -0
  415. package/src/providers/phone.ts +28 -0
  416. package/src/server/auth.ts +282 -28
  417. package/src/server/authError.ts +44 -0
  418. package/src/server/core.ts +2095 -0
  419. package/src/server/{provider.ts → crypto.ts} +1 -1
  420. package/src/server/device.ts +1 -1
  421. package/src/server/enterprise/config.ts +51 -0
  422. package/src/server/{domains/sso.ts → enterprise/domain.ts} +4 -2
  423. package/src/server/enterprise/http.ts +1324 -0
  424. package/src/server/enterprise/oidc.ts +500 -0
  425. package/src/server/enterprise/policy.ts +128 -0
  426. package/src/server/enterprise/saml.ts +578 -0
  427. package/src/server/enterprise/scim.ts +135 -0
  428. package/src/server/enterprise/shared.ts +134 -0
  429. package/src/server/errors.ts +2 -0
  430. package/src/server/http.ts +3 -1
  431. package/src/server/identity.ts +1 -1
  432. package/src/server/index.ts +32 -2605
  433. package/src/server/{ratelimit.ts → limits.ts} +1 -1
  434. package/src/server/mounts.ts +948 -0
  435. package/src/server/mutations/account.ts +4 -4
  436. package/src/server/mutations/code.ts +3 -3
  437. package/src/server/mutations/index.ts +8 -148
  438. package/src/server/mutations/invalidate.ts +2 -2
  439. package/src/server/mutations/oauth.ts +8 -6
  440. package/src/server/mutations/refresh.ts +3 -3
  441. package/src/server/mutations/register.ts +3 -3
  442. package/src/server/mutations/retrieve.ts +4 -8
  443. package/src/server/mutations/signature.ts +3 -3
  444. package/src/server/mutations/signin.ts +2 -2
  445. package/src/server/mutations/signout.ts +2 -2
  446. package/src/server/mutations/store/refs.ts +10 -0
  447. package/src/server/mutations/store.ts +137 -9
  448. package/src/server/mutations/verifier.ts +2 -2
  449. package/src/server/mutations/verify.ts +5 -5
  450. package/src/server/oauth.ts +1 -1
  451. package/src/server/passkey.ts +3 -4
  452. package/src/server/redirects.ts +1 -1
  453. package/src/server/refresh.ts +1 -1
  454. package/src/server/runtime.ts +880 -0
  455. package/src/server/signin.ts +3 -1
  456. package/src/server/ssr.ts +1764 -0
  457. package/src/server/totp.ts +3 -1
  458. package/src/server/types.ts +254 -43
  459. package/src/server/users.ts +1 -1
  460. package/src/server/utils.ts +1 -1
  461. package/src/test.ts +25 -0
  462. package/dist/component/public/enterprise.d.ts +0 -54
  463. package/dist/component/public/enterprise.d.ts.map +0 -1
  464. package/dist/component/public/enterprise.js +0 -515
  465. package/dist/component/public/enterprise.js.map +0 -1
  466. package/dist/component/public/factors.d.ts +0 -52
  467. package/dist/component/public/factors.d.ts.map +0 -1
  468. package/dist/component/public/factors.js +0 -285
  469. package/dist/component/public/factors.js.map +0 -1
  470. package/dist/component/public/groups.d.ts +0 -124
  471. package/dist/component/public/groups.d.ts.map +0 -1
  472. package/dist/component/public/groups.js +0 -680
  473. package/dist/component/public/groups.js.map +0 -1
  474. package/dist/component/public/identity.d.ts +0 -93
  475. package/dist/component/public/identity.d.ts.map +0 -1
  476. package/dist/component/public/identity.js +0 -426
  477. package/dist/component/public/identity.js.map +0 -1
  478. package/dist/component/public/keys.d.ts +0 -41
  479. package/dist/component/public/keys.d.ts.map +0 -1
  480. package/dist/component/public/keys.js +0 -157
  481. package/dist/component/public/keys.js.map +0 -1
  482. package/dist/component/public/shared.d.ts +0 -26
  483. package/dist/component/public/shared.d.ts.map +0 -1
  484. package/dist/component/public/shared.js +0 -32
  485. package/dist/component/public/shared.js.map +0 -1
  486. package/dist/component/server/domains/core.js.map +0 -1
  487. package/dist/component/server/domains/sso.js.map +0 -1
  488. package/dist/component/server/factory.d.ts.map +0 -1
  489. package/dist/component/server/factory.js +0 -1134
  490. package/dist/component/server/factory.js.map +0 -1
  491. package/dist/component/server/fx.js +0 -66
  492. package/dist/component/server/fx.js.map +0 -1
  493. package/dist/component/server/mutations/index.js +0 -85
  494. package/dist/component/server/mutations/index.js.map +0 -1
  495. package/dist/component/server/providers.js.map +0 -1
  496. package/dist/component/server/ratelimit.js.map +0 -1
  497. package/dist/component/server/sso.js +0 -830
  498. package/dist/component/server/sso.js.map +0 -1
  499. package/dist/server/domains/core.d.ts +0 -449
  500. package/dist/server/domains/core.d.ts.map +0 -1
  501. package/dist/server/domains/core.js.map +0 -1
  502. package/dist/server/domains/sso.d.ts.map +0 -1
  503. package/dist/server/domains/sso.js.map +0 -1
  504. package/dist/server/enterpriseValidators.js.map +0 -1
  505. package/dist/server/factory.d.ts.map +0 -1
  506. package/dist/server/factory.js +0 -1134
  507. package/dist/server/factory.js.map +0 -1
  508. package/dist/server/fx.d.ts.map +0 -1
  509. package/dist/server/fx.js +0 -66
  510. package/dist/server/fx.js.map +0 -1
  511. package/dist/server/index.d.ts.map +0 -1
  512. package/dist/server/index.js.map +0 -1
  513. package/dist/server/mutations/index.d.ts.map +0 -1
  514. package/dist/server/mutations/index.js.map +0 -1
  515. package/dist/server/provider.d.ts.map +0 -1
  516. package/dist/server/provider.js.map +0 -1
  517. package/dist/server/providers.js.map +0 -1
  518. package/dist/server/ratelimit.js.map +0 -1
  519. package/dist/server/sso.js +0 -830
  520. package/dist/server/sso.js.map +0 -1
  521. package/dist/server/version.d.ts +0 -5
  522. package/dist/server/version.d.ts.map +0 -1
  523. package/dist/server/version.js +0 -6
  524. package/dist/server/version.js.map +0 -1
  525. package/src/component/public/enterprise.ts +0 -753
  526. package/src/component/public/factors.ts +0 -333
  527. package/src/component/public/groups.ts +0 -1066
  528. package/src/component/public/identity.ts +0 -569
  529. package/src/component/public/keys.ts +0 -209
  530. package/src/component/public/shared.ts +0 -119
  531. package/src/server/domains/core.ts +0 -1096
  532. package/src/server/factory.ts +0 -2181
  533. package/src/server/fx.ts +0 -152
  534. package/src/server/sso.ts +0 -1516
  535. package/src/server/version.ts +0 -2
  536. /package/dist/server/{enterpriseValidators.d.ts → config.d.ts} +0 -0
  537. /package/dist/server/{providers.d.ts → enterprise/config.d.ts} +0 -0
  538. /package/dist/server/{ratelimit.d.ts → enterprise/oidc.d.ts} +0 -0
  539. /package/dist/server/{sso.d.ts → enterprise/policy.d.ts} +0 -0
  540. /package/src/server/{providers.ts → config.ts} +0 -0
  541. /package/src/server/{enterpriseValidators.ts → enterprise/validators.ts} +0 -0
@@ -1,2605 +1,32 @@
1
- import { ConvexHttpClient } from "convex/browser";
2
- import {
3
- actionGeneric,
4
- makeFunctionReference,
5
- mutationGeneric,
6
- queryGeneric,
7
- } from "convex/server";
8
- import { ConvexError, v } from "convex/values";
9
- import { parse, serialize } from "cookie";
10
- import { jwtDecode } from "jwt-decode";
11
-
12
- import type { AuthApi } from "./auth";
13
- import {
14
- enterpriseConnectionWhereValidator,
15
- enterpriseDomainInputValidator,
16
- enterpriseDomainVerificationInputValidator,
17
- enterprisePolicyPatchValidator,
18
- enterpriseSamlAttributeMappingValidator,
19
- enterpriseSamlSpValidator,
20
- enterpriseStatusValidator,
21
- } from "./enterpriseValidators";
22
- import type {
23
- SignInAction,
24
- SignInActionResult,
25
- SignOutAction,
26
- } from "./factory";
27
- import { Fx } from "./fx";
28
- import type { AuthAuthorizationConfig, AuthRoleId } from "./types";
29
- import { isLocalHost } from "./utils";
30
-
31
- const signInActionRef: SignInAction = makeFunctionReference("auth:signIn");
32
- const signOutActionRef: SignOutAction = makeFunctionReference("auth:signOut");
33
-
34
- export type EnterpriseAdminPermission =
35
- | "sso.connection.create"
36
- | "sso.connection.read"
37
- | "sso.connection.manage"
38
- | "sso.domain.manage"
39
- | "sso.protocol.manage"
40
- | "sso.policy.manage"
41
- | "sso.audit.read"
42
- | "sso.webhook.manage"
43
- | "scim.manage";
44
-
45
- export type EnterpriseAdminAuthorizationInput = {
46
- userId: string;
47
- permission: EnterpriseAdminPermission;
48
- enterpriseId?: string;
49
- groupId?: string;
50
- resolvedGroupId: string | null;
51
- };
52
-
53
- export type EnterpriseAuthorizer = (
54
- ctx: { auth: import("convex/server").Auth },
55
- input: EnterpriseAdminAuthorizationInput,
56
- ) => Promise<void | { ok: false }>;
57
-
58
- type RoleRef<TRoleId extends string> = { id: TRoleId };
59
-
60
- type MountedEnterpriseOptions<TRoleId extends string = string> = {
61
- admin?: {
62
- authorized?: EnterpriseAuthorizer;
63
- roles?: Array<TRoleId | RoleRef<TRoleId>>;
64
- };
65
- };
66
-
67
- export type EnterpriseMountOptions<TRoleId extends string = string> = {
68
- admin: {
69
- authorized: EnterpriseAuthorizer;
70
- roles?: Array<TRoleId | RoleRef<TRoleId>>;
71
- };
72
- };
73
-
74
- type MountedEnterpriseTarget = {
75
- enterpriseId?: string;
76
- groupId?: string;
77
- domain?: string;
78
- };
79
-
80
- function requireSignedInUser(auth: Pick<AuthApi, "user">) {
81
- return async (ctx: {
82
- auth: import("convex/server").Auth;
83
- }): Promise<string | null> => {
84
- return await auth.user.id(ctx as never);
85
- };
86
- }
87
-
88
- function normalizeCreatorRoleIds<TRoleId extends string>(
89
- roles?: Array<TRoleId | RoleRef<TRoleId>>,
90
- ) {
91
- return roles?.map((role) => (typeof role === "string" ? role : role.id));
92
- }
93
-
94
- async function resolveMountedEnterpriseTarget(
95
- auth: Pick<AuthApi, "sso">,
96
- ctx: { auth: import("convex/server").Auth },
97
- target: MountedEnterpriseTarget,
98
- ) {
99
- if (target.groupId !== undefined) {
100
- return {
101
- enterpriseId: target.enterpriseId,
102
- groupId: target.groupId,
103
- resolvedGroupId: target.groupId,
104
- };
105
- }
106
-
107
- if (target.enterpriseId !== undefined) {
108
- const enterprise = await auth.sso.admin.connection.get(
109
- ctx as never,
110
- target.enterpriseId,
111
- );
112
- if (enterprise === null) {
113
- throw new ConvexError({
114
- code: "INVALID_PARAMETERS",
115
- message: "Enterprise not found.",
116
- });
117
- }
118
- return {
119
- enterpriseId: enterprise._id,
120
- groupId: enterprise.groupId,
121
- resolvedGroupId: enterprise.groupId,
122
- };
123
- }
124
-
125
- if (target.domain !== undefined) {
126
- const resolved = await auth.sso.admin.connection.getByDomain(
127
- ctx as never,
128
- target.domain,
129
- );
130
- if (resolved?.enterprise === undefined) {
131
- throw new ConvexError({
132
- code: "INVALID_PARAMETERS",
133
- message: "Enterprise not found.",
134
- });
135
- }
136
- return {
137
- enterpriseId: resolved.enterprise._id,
138
- groupId: resolved.enterprise.groupId,
139
- resolvedGroupId: resolved.enterprise.groupId,
140
- };
141
- }
142
-
143
- return {
144
- enterpriseId: undefined,
145
- groupId: undefined,
146
- resolvedGroupId: null,
147
- };
148
- }
149
-
150
- function createMountedAdminAuthorizer(
151
- auth: Pick<AuthApi, "sso" | "user">,
152
- options?: MountedEnterpriseOptions,
153
- ) {
154
- const requireUserId = requireSignedInUser(auth);
155
-
156
- return async (
157
- ctx: { auth: import("convex/server").Auth },
158
- permission: EnterpriseAdminPermission,
159
- target: MountedEnterpriseTarget = {},
160
- ) => {
161
- const userId = await requireUserId(ctx);
162
- if (userId === null) {
163
- return { ok: false as const, code: "NOT_SIGNED_IN" as const };
164
- }
165
- if (!options?.admin?.authorized) {
166
- return { ok: false as const, code: "FORBIDDEN" as const };
167
- }
168
- const resolved = await resolveMountedEnterpriseTarget(auth, ctx, target);
169
- const authResult = await options.admin.authorized(ctx, {
170
- userId,
171
- permission,
172
- enterpriseId: resolved.enterpriseId,
173
- groupId: resolved.groupId,
174
- resolvedGroupId: resolved.resolvedGroupId,
175
- });
176
- if (authResult && !authResult.ok) {
177
- return { ok: false as const, code: "FORBIDDEN" as const };
178
- }
179
- return { ok: true as const, userId, ...resolved };
180
- };
181
- }
182
-
183
- /**
184
- * Build optional public SSO management actions that apps can mount under
185
- * `convex/auth/sso/**` when they want client-callable enterprise APIs.
186
- *
187
- * `admin` is for tenant-admin control-plane operations and should be mounted
188
- * with an explicit authorization policy. `client` is for end-user sign-in
189
- * helpers and does not require tenant-admin authorization.
190
- */
191
- export function sso<
192
- TAuthorization extends AuthAuthorizationConfig | undefined = undefined,
193
- >(
194
- auth: Pick<AuthApi<TAuthorization>, "group" | "member" | "sso" | "user">,
195
- options?: MountedEnterpriseOptions<AuthRoleId<TAuthorization>>,
196
- ) {
197
- const authorize = createMountedAdminAuthorizer(auth, options);
198
- const adminRoleIds = normalizeCreatorRoleIds(options?.admin?.roles);
199
-
200
- return {
201
- admin: {
202
- connection: {
203
- create: mutationGeneric({
204
- args: {
205
- groupId: v.optional(v.string()),
206
- name: v.optional(v.string()),
207
- slug: v.optional(v.string()),
208
- status: v.optional(enterpriseStatusValidator),
209
- domain: v.optional(v.string()),
210
- },
211
- handler: async (ctx, args) => {
212
- const authResult = await authorize(ctx, "sso.connection.create", {
213
- groupId: args.groupId,
214
- });
215
- if (!authResult.ok)
216
- return { ok: false as const, code: authResult.code };
217
- const { userId } = authResult;
218
- const createsGroup = args.groupId === undefined;
219
- const groupId =
220
- args.groupId ??
221
- (
222
- await auth.group.create(ctx as never, {
223
- name: args.name?.trim() || args.slug?.trim() || "Enterprise",
224
- slug: args.slug,
225
- type: "enterprise",
226
- })
227
- ).groupId;
228
- if (createsGroup) {
229
- await auth.member.create(ctx as never, {
230
- groupId,
231
- userId,
232
- roleIds: adminRoleIds,
233
- });
234
- }
235
- const created = await auth.sso.admin.connection.create(
236
- ctx as never,
237
- {
238
- groupId,
239
- name: args.name,
240
- slug: args.slug,
241
- status: args.status,
242
- },
243
- );
244
- if (args.domain) {
245
- await auth.sso.admin.connection.domain.set(
246
- ctx as never,
247
- created.enterpriseId,
248
- [{ domain: args.domain, isPrimary: true }],
249
- );
250
- }
251
- return {
252
- ...created,
253
- groupId,
254
- createdGroup: createsGroup,
255
- };
256
- },
257
- }),
258
- get: queryGeneric({
259
- args: { enterpriseId: v.string() },
260
- handler: async (ctx, args) => {
261
- const _auth = await authorize(ctx, "sso.connection.read", {
262
- enterpriseId: args.enterpriseId,
263
- });
264
- if (!_auth.ok) return null;
265
- return await auth.sso.admin.connection.get(
266
- ctx as never,
267
- args.enterpriseId,
268
- );
269
- },
270
- }),
271
- getByGroup: queryGeneric({
272
- args: { groupId: v.string() },
273
- handler: async (ctx, args) => {
274
- const _auth = await authorize(ctx, "sso.connection.read", {
275
- groupId: args.groupId,
276
- });
277
- if (!_auth.ok) return null;
278
- return await auth.sso.admin.connection.getByGroup(
279
- ctx as never,
280
- args.groupId,
281
- );
282
- },
283
- }),
284
- getByDomain: queryGeneric({
285
- args: { domain: v.string() },
286
- handler: async (ctx, args) => {
287
- const _auth = await authorize(ctx, "sso.connection.read", {
288
- domain: args.domain,
289
- });
290
- if (!_auth.ok) return null;
291
- return await auth.sso.admin.connection.getByDomain(
292
- ctx as never,
293
- args.domain,
294
- );
295
- },
296
- }),
297
- list: queryGeneric({
298
- args: {
299
- where: v.optional(enterpriseConnectionWhereValidator),
300
- limit: v.optional(v.number()),
301
- cursor: v.optional(v.union(v.string(), v.null())),
302
- orderBy: v.optional(v.string()),
303
- order: v.optional(v.union(v.literal("asc"), v.literal("desc"))),
304
- },
305
- handler: async (ctx, args) => {
306
- const _auth = await authorize(ctx, "sso.connection.read", {
307
- groupId: args.where?.groupId,
308
- });
309
- if (!_auth.ok) return null;
310
- return await auth.sso.admin.connection.list(
311
- ctx as never,
312
- args as never,
313
- );
314
- },
315
- }),
316
- update: mutationGeneric({
317
- args: {
318
- enterpriseId: v.string(),
319
- data: v.object({
320
- name: v.optional(v.string()),
321
- slug: v.optional(v.string()),
322
- status: v.optional(enterpriseStatusValidator),
323
- }),
324
- },
325
- handler: async (ctx, args) => {
326
- const _auth = await authorize(ctx, "sso.connection.manage", {
327
- enterpriseId: args.enterpriseId,
328
- });
329
- if (!_auth.ok) return { ok: false as const, code: _auth.code };
330
- await auth.sso.admin.connection.update(
331
- ctx as never,
332
- args.enterpriseId,
333
- args.data,
334
- );
335
- return { ok: true as const, enterpriseId: args.enterpriseId };
336
- },
337
- }),
338
- delete: mutationGeneric({
339
- args: { enterpriseId: v.string() },
340
- handler: async (ctx, args) => {
341
- const _auth = await authorize(ctx, "sso.connection.manage", {
342
- enterpriseId: args.enterpriseId,
343
- });
344
- if (!_auth.ok) return { ok: false as const, code: _auth.code };
345
- return await auth.sso.admin.connection.delete(
346
- ctx as never,
347
- args.enterpriseId,
348
- );
349
- },
350
- }),
351
- status: queryGeneric({
352
- args: { enterpriseId: v.string() },
353
- handler: async (ctx, args) => {
354
- const _auth = await authorize(ctx, "sso.connection.read", {
355
- enterpriseId: args.enterpriseId,
356
- });
357
- if (!_auth.ok) return null;
358
- return await auth.sso.admin.connection.status(
359
- ctx as never,
360
- args.enterpriseId,
361
- );
362
- },
363
- }),
364
- domain: {
365
- list: queryGeneric({
366
- args: { enterpriseId: v.string() },
367
- handler: async (ctx, args) => {
368
- const _auth = await authorize(ctx, "sso.connection.read", {
369
- enterpriseId: args.enterpriseId,
370
- });
371
- if (!_auth.ok) return null;
372
- return await auth.sso.admin.connection.domain.list(
373
- ctx as never,
374
- args.enterpriseId,
375
- );
376
- },
377
- }),
378
- validate: queryGeneric({
379
- args: { enterpriseId: v.string() },
380
- handler: async (ctx, args) => {
381
- const _auth = await authorize(ctx, "sso.domain.manage", {
382
- enterpriseId: args.enterpriseId,
383
- });
384
- if (!_auth.ok) return null;
385
- return await auth.sso.admin.connection.domain.validate(
386
- ctx as never,
387
- args.enterpriseId,
388
- );
389
- },
390
- }),
391
- set: mutationGeneric({
392
- args: {
393
- enterpriseId: v.string(),
394
- domains: v.array(enterpriseDomainInputValidator),
395
- },
396
- handler: async (ctx, args) => {
397
- const _auth = await authorize(ctx, "sso.domain.manage", {
398
- enterpriseId: args.enterpriseId,
399
- });
400
- if (!_auth.ok) return { ok: false as const, code: _auth.code };
401
- return await auth.sso.admin.connection.domain.set(
402
- ctx as never,
403
- args.enterpriseId,
404
- args.domains,
405
- );
406
- },
407
- }),
408
- verification: {
409
- request: mutationGeneric({
410
- args: enterpriseDomainVerificationInputValidator,
411
- handler: async (ctx, args) => {
412
- const _auth = await authorize(ctx, "sso.domain.manage", {
413
- enterpriseId: args.enterpriseId,
414
- });
415
- if (!_auth.ok) return { ok: false as const, code: _auth.code };
416
- return await auth.sso.admin.connection.domain.verification.request(
417
- ctx as never,
418
- args,
419
- );
420
- },
421
- }),
422
- confirm: actionGeneric({
423
- args: enterpriseDomainVerificationInputValidator,
424
- handler: async (ctx, args) => {
425
- const _auth = await authorize(ctx, "sso.domain.manage", {
426
- enterpriseId: args.enterpriseId,
427
- });
428
- if (!_auth.ok) return { ok: false as const, code: _auth.code };
429
- return await auth.sso.admin.connection.domain.verification.confirm(
430
- ctx as never,
431
- args,
432
- );
433
- },
434
- }),
435
- },
436
- },
437
- },
438
- oidc: {
439
- configure: mutationGeneric({
440
- args: {
441
- enterpriseId: v.string(),
442
- issuer: v.optional(v.string()),
443
- discoveryUrl: v.optional(v.string()),
444
- clientId: v.string(),
445
- clientSecret: v.optional(v.string()),
446
- scopes: v.optional(v.array(v.string())),
447
- authorizationParams: v.optional(v.record(v.string(), v.string())),
448
- clockToleranceSeconds: v.optional(v.number()),
449
- strictIssuer: v.optional(v.boolean()),
450
- extraFields: v.optional(v.record(v.string(), v.string())),
451
- },
452
- handler: async (ctx, args) => {
453
- const _auth = await authorize(ctx, "sso.protocol.manage", {
454
- enterpriseId: args.enterpriseId,
455
- });
456
- if (!_auth.ok) return { ok: false as const, code: _auth.code };
457
- return await auth.sso.admin.oidc.configure(ctx as never, args);
458
- },
459
- }),
460
- get: queryGeneric({
461
- args: { enterpriseId: v.string() },
462
- handler: async (ctx, args) => {
463
- const _auth = await authorize(ctx, "sso.connection.read", {
464
- enterpriseId: args.enterpriseId,
465
- });
466
- if (!_auth.ok) return null;
467
- return await auth.sso.admin.oidc.get(
468
- ctx as never,
469
- args.enterpriseId,
470
- );
471
- },
472
- }),
473
- validate: actionGeneric({
474
- args: { enterpriseId: v.string() },
475
- handler: async (ctx, args) => {
476
- const _auth = await authorize(ctx, "sso.protocol.manage", {
477
- enterpriseId: args.enterpriseId,
478
- });
479
- if (!_auth.ok) return { ok: false as const, code: _auth.code };
480
- return await auth.sso.admin.oidc.validate(
481
- ctx as never,
482
- args.enterpriseId,
483
- );
484
- },
485
- }),
486
- },
487
- saml: {
488
- configure: actionGeneric({
489
- args: {
490
- enterpriseId: v.string(),
491
- metadataXml: v.optional(v.string()),
492
- metadataUrl: v.optional(v.string()),
493
- domains: v.optional(v.array(v.string())),
494
- signAuthnRequests: v.optional(v.boolean()),
495
- attributeMapping: v.optional(
496
- enterpriseSamlAttributeMappingValidator,
497
- ),
498
- sp: v.optional(enterpriseSamlSpValidator),
499
- },
500
- handler: async (ctx, args) => {
501
- const _auth = await authorize(ctx, "sso.protocol.manage", {
502
- enterpriseId: args.enterpriseId,
503
- });
504
- if (!_auth.ok) return { ok: false as const, code: _auth.code };
505
- return await auth.sso.admin.saml.configure(ctx as never, args);
506
- },
507
- }),
508
- validate: queryGeneric({
509
- args: { enterpriseId: v.string() },
510
- handler: async (ctx, args) => {
511
- const _auth = await authorize(ctx, "sso.protocol.manage", {
512
- enterpriseId: args.enterpriseId,
513
- });
514
- if (!_auth.ok) return null;
515
- return await auth.sso.admin.saml.validate(
516
- ctx as never,
517
- args.enterpriseId,
518
- );
519
- },
520
- }),
521
- },
522
- policy: {
523
- get: queryGeneric({
524
- args: { enterpriseId: v.string() },
525
- handler: async (ctx, args) => {
526
- const _auth = await authorize(ctx, "sso.connection.read", {
527
- enterpriseId: args.enterpriseId,
528
- });
529
- if (!_auth.ok) return null;
530
- return await auth.sso.admin.policy.get(
531
- ctx as never,
532
- args.enterpriseId,
533
- );
534
- },
535
- }),
536
- update: mutationGeneric({
537
- args: {
538
- enterpriseId: v.string(),
539
- patch: enterprisePolicyPatchValidator,
540
- },
541
- handler: async (ctx, args) => {
542
- const _auth = await authorize(ctx, "sso.policy.manage", {
543
- enterpriseId: args.enterpriseId,
544
- });
545
- if (!_auth.ok) return { ok: false as const, code: _auth.code };
546
- return await auth.sso.admin.policy.update(
547
- ctx as never,
548
- args.enterpriseId,
549
- args.patch,
550
- );
551
- },
552
- }),
553
- validate: queryGeneric({
554
- args: { enterpriseId: v.string() },
555
- handler: async (ctx, args) => {
556
- const _auth = await authorize(ctx, "sso.policy.manage", {
557
- enterpriseId: args.enterpriseId,
558
- });
559
- if (!_auth.ok) return null;
560
- return await auth.sso.admin.policy.validate(
561
- ctx as never,
562
- args.enterpriseId,
563
- );
564
- },
565
- }),
566
- },
567
- audit: {
568
- list: queryGeneric({
569
- args: {
570
- enterpriseId: v.optional(v.string()),
571
- groupId: v.optional(v.string()),
572
- limit: v.optional(v.number()),
573
- },
574
- handler: async (ctx, args) => {
575
- const _auth = await authorize(ctx, "sso.audit.read", {
576
- enterpriseId: args.enterpriseId,
577
- groupId: args.groupId,
578
- });
579
- if (!_auth.ok) return null;
580
- return await auth.sso.admin.audit.list(ctx as never, args);
581
- },
582
- }),
583
- },
584
- webhook: {
585
- delivery: {
586
- list: queryGeneric({
587
- args: {
588
- enterpriseId: v.string(),
589
- limit: v.optional(v.number()),
590
- },
591
- handler: async (ctx, args) => {
592
- const _auth = await authorize(ctx, "sso.webhook.manage", {
593
- enterpriseId: args.enterpriseId,
594
- });
595
- if (!_auth.ok) return null;
596
- return await (auth.sso.admin.webhook as any).delivery.list(
597
- ctx as never,
598
- args,
599
- );
600
- },
601
- }),
602
- },
603
- endpoint: {
604
- create: mutationGeneric({
605
- args: {
606
- enterpriseId: v.string(),
607
- url: v.string(),
608
- secret: v.string(),
609
- subscriptions: v.array(v.string()),
610
- createdByUserId: v.optional(v.string()),
611
- },
612
- handler: async (ctx, args) => {
613
- const authResult = await authorize(ctx, "sso.webhook.manage", {
614
- enterpriseId: args.enterpriseId,
615
- });
616
- if (!authResult.ok)
617
- return { ok: false as const, code: authResult.code };
618
- const { userId } = authResult;
619
- const result = await auth.sso.admin.webhook.endpoint.create(
620
- ctx as never,
621
- {
622
- ...args,
623
- createdByUserId: args.createdByUserId ?? userId,
624
- },
625
- );
626
- return {
627
- _id: result.endpointId,
628
- enterpriseId: args.enterpriseId,
629
- url: args.url,
630
- subscriptions: args.subscriptions,
631
- createdByUserId: args.createdByUserId ?? userId,
632
- status: "active",
633
- failureCount: 0,
634
- };
635
- },
636
- }),
637
- list: queryGeneric({
638
- args: { enterpriseId: v.string() },
639
- handler: async (ctx, args) => {
640
- const _auth = await authorize(ctx, "sso.webhook.manage", {
641
- enterpriseId: args.enterpriseId,
642
- });
643
- if (!_auth.ok) return null;
644
- const endpoints = await auth.sso.admin.webhook.endpoint.list(
645
- ctx as never,
646
- args.enterpriseId,
647
- );
648
- return endpoints.map((endpoint: Record<string, unknown>) => {
649
- const { secretHash: _secretHash, ...rest } = endpoint;
650
- return rest;
651
- });
652
- },
653
- }),
654
- disable: mutationGeneric({
655
- args: { endpointId: v.string() },
656
- handler: async (ctx, args) => {
657
- const endpoint = await auth.sso.admin.webhook.endpoint.get(
658
- ctx as never,
659
- args.endpointId,
660
- );
661
- if (!endpoint) {
662
- return {
663
- ok: false as const,
664
- code: "INVALID_PARAMETERS" as const,
665
- };
666
- }
667
- const _auth = await authorize(ctx, "sso.webhook.manage", {
668
- enterpriseId: endpoint.enterpriseId,
669
- groupId: endpoint.groupId,
670
- });
671
- if (!_auth.ok) return { ok: false as const, code: _auth.code };
672
- return await auth.sso.admin.webhook.endpoint.disable(
673
- ctx as never,
674
- args.endpointId,
675
- );
676
- },
677
- }),
678
- },
679
- },
680
- },
681
- client: {
682
- signIn: queryGeneric({
683
- args: {
684
- enterpriseId: v.optional(v.string()),
685
- email: v.optional(v.string()),
686
- domain: v.optional(v.string()),
687
- redirectTo: v.optional(v.string()),
688
- },
689
- handler: async (ctx, args) => {
690
- return await auth.sso.client.signIn(ctx as never, args);
691
- },
692
- }),
693
- metadata: queryGeneric({
694
- args: {
695
- enterpriseId: v.string(),
696
- entityId: v.optional(v.string()),
697
- acsUrl: v.optional(v.string()),
698
- sloUrl: v.optional(v.string()),
699
- },
700
- handler: async (ctx, args) => {
701
- return await auth.sso.client.metadata(ctx as never, args);
702
- },
703
- }),
704
- },
705
- };
706
- }
707
-
708
- /**
709
- * Build optional public SCIM management actions that apps can mount under
710
- * `convex/auth/scim/**` when they want client-callable enterprise admin APIs.
711
- */
712
- export function scim<
713
- TAuthorization extends AuthAuthorizationConfig | undefined = undefined,
714
- >(
715
- auth: Pick<AuthApi<TAuthorization>, "scim" | "sso" | "user">,
716
- options?: MountedEnterpriseOptions<AuthRoleId<TAuthorization>>,
717
- ) {
718
- const authorize = createMountedAdminAuthorizer(auth, options);
719
-
720
- return {
721
- admin: {
722
- configure: mutationGeneric({
723
- args: {
724
- enterpriseId: v.string(),
725
- basePath: v.optional(v.string()),
726
- status: v.optional(enterpriseStatusValidator),
727
- },
728
- handler: async (ctx, args) => {
729
- const _auth = await authorize(ctx, "scim.manage", {
730
- enterpriseId: args.enterpriseId,
731
- });
732
- if (!_auth.ok) return { ok: false as const, code: _auth.code };
733
- return await auth.scim.admin.configure(ctx as never, args);
734
- },
735
- }),
736
- get: queryGeneric({
737
- args: { enterpriseId: v.string() },
738
- handler: async (ctx, args) => {
739
- const _auth = await authorize(ctx, "scim.manage", {
740
- enterpriseId: args.enterpriseId,
741
- });
742
- if (!_auth.ok) return null;
743
- return await auth.scim.admin.get(ctx as never, args.enterpriseId);
744
- },
745
- }),
746
- validate: queryGeneric({
747
- args: { enterpriseId: v.string() },
748
- handler: async (ctx, args) => {
749
- const _auth = await authorize(ctx, "scim.manage", {
750
- enterpriseId: args.enterpriseId,
751
- });
752
- if (!_auth.ok) return null;
753
- return await auth.scim.admin.validate(
754
- ctx as never,
755
- args.enterpriseId,
756
- );
757
- },
758
- }),
759
- },
760
- };
761
- }
762
-
763
- /**
764
- * Build a flat mounted enterprise API surface for app-owned Convex exports.
765
- *
766
- * The returned object contains tenant-admin SSO and SCIM control-plane
767
- * functions plus end-user enterprise sign-in helpers. The `authorized`
768
- * callback is required for admin operations.
769
- */
770
- export function enterprise<
771
- TAuthorization extends AuthAuthorizationConfig | undefined = undefined,
772
- >(
773
- auth: Pick<
774
- AuthApi<TAuthorization>,
775
- "group" | "member" | "scim" | "sso" | "user"
776
- >,
777
- options: EnterpriseMountOptions<AuthRoleId<TAuthorization>>,
778
- ) {
779
- const mountedSso = sso(auth, {
780
- admin: options.admin,
781
- });
782
- const mountedScim = scim(auth, {
783
- admin: { authorized: options.admin.authorized },
784
- });
785
-
786
- return {
787
- createConnection: mountedSso.admin.connection.create,
788
- getConnection: mountedSso.admin.connection.get,
789
- getConnectionByGroup: mountedSso.admin.connection.getByGroup,
790
- getConnectionByDomain: mountedSso.admin.connection.getByDomain,
791
- listConnections: mountedSso.admin.connection.list,
792
- updateConnection: mountedSso.admin.connection.update,
793
- deleteConnection: mountedSso.admin.connection.delete,
794
- getConnectionStatus: mountedSso.admin.connection.status,
795
- listDomains: mountedSso.admin.connection.domain.list,
796
- validateDomains: mountedSso.admin.connection.domain.validate,
797
- setDomains: mountedSso.admin.connection.domain.set,
798
- requestDomainVerification:
799
- mountedSso.admin.connection.domain.verification.request,
800
- confirmDomainVerification:
801
- mountedSso.admin.connection.domain.verification.confirm,
802
- configureOidc: mountedSso.admin.oidc.configure,
803
- getOidc: mountedSso.admin.oidc.get,
804
- validateOidc: mountedSso.admin.oidc.validate,
805
- configureSaml: mountedSso.admin.saml.configure,
806
- validateSaml: mountedSso.admin.saml.validate,
807
- getPolicy: mountedSso.admin.policy.get,
808
- updatePolicy: mountedSso.admin.policy.update,
809
- validatePolicy: mountedSso.admin.policy.validate,
810
- listAudit: mountedSso.admin.audit.list,
811
- createWebhookEndpoint: mountedSso.admin.webhook.endpoint.create,
812
- listWebhookEndpoints: mountedSso.admin.webhook.endpoint.list,
813
- listWebhookDeliveries: mountedSso.admin.webhook.delivery.list,
814
- disableWebhookEndpoint: mountedSso.admin.webhook.endpoint.disable,
815
- configureScim: mountedScim.admin.configure,
816
- getScim: mountedScim.admin.get,
817
- validateScim: mountedScim.admin.validate,
818
- signIn: mountedSso.client.signIn,
819
- metadata: mountedSso.client.metadata,
820
- };
821
- }
822
-
823
- /** Cookie lifetime configuration for auth tokens. */
824
- export type AuthCookieConfig = {
825
- /** Maximum age in seconds, or `null` for session cookies. */
826
- maxAge: number | null;
827
- };
828
-
829
- /** Raw cookie values extracted from a request. */
830
- export type AuthCookies = {
831
- /** The JWT access token, or `null` when absent. */
832
- token: string | null;
833
- /** The refresh token, or `null` when absent. */
834
- refreshToken: string | null;
835
- /** The OAuth PKCE verifier, or `null` when absent. */
836
- verifier: string | null;
837
- };
838
-
839
- /** A structured cookie ready to be set via any framework's cookie API. */
840
- export type AuthCookie = {
841
- name: string;
842
- value: string;
843
- options: {
844
- path: string;
845
- httpOnly: boolean;
846
- secure: boolean;
847
- sameSite: "lax" | "strict" | "none";
848
- maxAge?: number;
849
- expires?: Date;
850
- };
851
- };
852
-
853
- /**
854
- * Options for the SSR auth helper returned by {@link server}.
855
- */
856
- export type ServerOptions = {
857
- /** Convex deployment API URL (e.g. `https://your-app.convex.cloud`). */
858
- url: string;
859
- /**
860
- * Accepted JWT issuers for `refresh()` and `verify()`.
861
- *
862
- * By default, this is derived from `url`. If `url` ends with
863
- * `.convex.cloud`, the matching `.convex.site` issuer is also accepted.
864
- */
865
- acceptedIssuers?: string[];
866
- /**
867
- * Path the client POSTs auth actions to. Defaults to `"/api/auth"`.
868
- * Must match the `proxyPath` option on the client.
869
- */
870
- apiRoute?: string;
871
- /** Cookie `maxAge` in seconds, or `null` for session cookies. */
872
- cookieMaxAge?: number | null;
873
- /** Enable verbose debug logging for token refresh and cookie operations. */
874
- verbose?: boolean;
875
- /**
876
- * Optional namespace for auth cookie names.
877
- *
878
- * Use this to isolate auth cookies between multiple local apps on the same host.
879
- * If omitted, a deterministic deployment-scoped namespace is derived from `url`.
880
- */
881
- cookieNamespace?: string;
882
- /**
883
- * Control whether `refresh()` handles OAuth `?code=` query parameters.
884
- *
885
- * - `true` (default): always exchange the code on GET requests with `text/html` accept.
886
- * - `false`: never exchange — useful when only the client handles codes.
887
- * - A function: called with the `Request` for per-request decisions.
888
- */
889
- shouldHandleCode?:
890
- | ((request: Request) => boolean | Promise<boolean>)
891
- | boolean;
892
- };
893
-
894
- export type RefreshResult =
895
- | {
896
- /** Code exchange occurred — return the pre-built redirect `Response`. */
897
- redirect: true;
898
- /** 302 redirect with Set-Cookie headers already serialized. */
899
- response: Response;
900
- }
901
- | {
902
- /** No redirect — apply cookies and read the token. */
903
- redirect: false;
904
- /** Structured cookies to set on the response. */
905
- cookies: AuthCookie[];
906
- /** JWT for SSR hydration, or `null` if not authenticated. */
907
- token: string | null;
908
- };
909
-
910
- const TOKEN_COOKIE_BASE_NAME = "__convexAuthJWT";
911
- const REFRESH_COOKIE_BASE_NAME = "__convexAuthRefreshToken";
912
- const VERIFIER_COOKIE_BASE_NAME = "__convexAuthOAuthVerifier";
913
- const DERIVED_COOKIE_NAMESPACE_FALLBACK = "convexauth";
914
-
915
- /**
916
- * Derive the cookie names used for auth tokens.
917
- *
918
- * On localhost the names are unprefixed; on production hosts they
919
- * use the `__Host-` prefix for tighter security.
920
- *
921
- * @param host - The `Host` header value. Omit to use unprefixed names.
922
- * @param cookieNamespace - Optional namespace suffix for cookie isolation.
923
- * @returns An object with `token`, `refreshToken`, and `verifier` cookie names.
924
- */
925
- export function authCookieNames(
926
- host?: string,
927
- cookieNamespace?: string | null,
928
- ) {
929
- const prefix = isLocalHost(host) ? "" : "__Host-";
930
- const namespace = normalizeCookieNamespace(cookieNamespace);
931
- const suffix = namespace === null ? "" : `_${namespace}`;
932
- return {
933
- token: `${prefix}${TOKEN_COOKIE_BASE_NAME}${suffix}`,
934
- refreshToken: `${prefix}${REFRESH_COOKIE_BASE_NAME}${suffix}`,
935
- verifier: `${prefix}${VERIFIER_COOKIE_BASE_NAME}${suffix}`,
936
- };
937
- }
938
-
939
- /**
940
- * Parse auth cookie values from a raw `Cookie` header string.
941
- *
942
- * @param cookieHeader - The raw `Cookie` header, or `null`/`undefined`.
943
- * @param host - The `Host` header, used to determine cookie name prefixes.
944
- * @param cookieNamespace - Optional namespace suffix for cookie isolation.
945
- * @returns Parsed {@link AuthCookies} with `token`, `refreshToken`, and `verifier`.
946
- */
947
- export function parseAuthCookies(
948
- cookieHeader: string | null | undefined,
949
- host?: string,
950
- cookieNamespace?: string | null,
951
- ): AuthCookies {
952
- const names = authCookieNames(host, cookieNamespace);
953
- const legacyNames = authCookieNames(host);
954
- const parsed = parse(cookieHeader ?? "");
955
- return {
956
- token:
957
- parsed[names.token] ??
958
- (legacyNames.token !== names.token
959
- ? (parsed[legacyNames.token] ?? null)
960
- : null),
961
- refreshToken:
962
- parsed[names.refreshToken] ??
963
- (legacyNames.refreshToken !== names.refreshToken
964
- ? (parsed[legacyNames.refreshToken] ?? null)
965
- : null),
966
- verifier:
967
- parsed[names.verifier] ??
968
- (legacyNames.verifier !== names.verifier
969
- ? (parsed[legacyNames.verifier] ?? null)
970
- : null),
971
- };
972
- }
973
-
974
- /**
975
- * Serialize auth cookies into `Set-Cookie` header strings.
976
- *
977
- * Nulled-out values produce deletion cookies (maxAge 0, expired date).
978
- *
979
- * @param cookies - The auth cookie values to serialize.
980
- * @param host - The `Host` header, used for cookie name prefixes and `Secure` flag.
981
- * @param config - Cookie lifetime config. Defaults to session cookies.
982
- * @param cookieNamespace - Optional namespace suffix for cookie isolation.
983
- * @returns An array of three `Set-Cookie` header strings.
984
- */
985
- export function serializeAuthCookies(
986
- cookies: AuthCookies,
987
- host?: string,
988
- config: AuthCookieConfig = { maxAge: null },
989
- cookieNamespace?: string | null,
990
- ) {
991
- const names = authCookieNames(host, cookieNamespace);
992
- const legacyNames = authCookieNames(host);
993
- const secure = !isLocalHost(host);
994
- const base = {
995
- path: "/",
996
- httpOnly: true,
997
- sameSite: "lax" as const,
998
- secure,
999
- };
1000
- const maxAge = config.maxAge ?? undefined;
1001
- const serialized = [
1002
- serialize(names.token, cookies.token ?? "", {
1003
- ...base,
1004
- maxAge: cookies.token === null ? 0 : maxAge,
1005
- expires: cookies.token === null ? new Date(0) : undefined,
1006
- }),
1007
- serialize(names.refreshToken, cookies.refreshToken ?? "", {
1008
- ...base,
1009
- maxAge: cookies.refreshToken === null ? 0 : maxAge,
1010
- expires: cookies.refreshToken === null ? new Date(0) : undefined,
1011
- }),
1012
- serialize(names.verifier, cookies.verifier ?? "", {
1013
- ...base,
1014
- maxAge: cookies.verifier === null ? 0 : maxAge,
1015
- expires: cookies.verifier === null ? new Date(0) : undefined,
1016
- }),
1017
- ];
1018
- if (legacyNames.token !== names.token) {
1019
- serialized.push(
1020
- serialize(legacyNames.token, "", {
1021
- ...base,
1022
- maxAge: 0,
1023
- expires: new Date(0),
1024
- }),
1025
- serialize(legacyNames.refreshToken, "", {
1026
- ...base,
1027
- maxAge: 0,
1028
- expires: new Date(0),
1029
- }),
1030
- serialize(legacyNames.verifier, "", {
1031
- ...base,
1032
- maxAge: 0,
1033
- expires: new Date(0),
1034
- }),
1035
- );
1036
- }
1037
- return serialized;
1038
- }
1039
-
1040
- /**
1041
- * Build structured cookie objects for any SSR framework.
1042
- *
1043
- * Use with SvelteKit's `event.cookies.set()`, TanStack Start's `setCookie()`,
1044
- * Next.js's `cookies().set()`, or any other framework cookie API.
1045
- */
1046
- export function structuredAuthCookies(
1047
- cookies: AuthCookies,
1048
- host?: string,
1049
- config: AuthCookieConfig = { maxAge: null },
1050
- cookieNamespace?: string | null,
1051
- ): AuthCookie[] {
1052
- const names = authCookieNames(host, cookieNamespace);
1053
- const legacyNames = authCookieNames(host);
1054
- const secure = !isLocalHost(host);
1055
- const base = {
1056
- path: "/" as const,
1057
- httpOnly: true as const,
1058
- secure,
1059
- sameSite: "lax" as const,
1060
- };
1061
- const maxAge = config.maxAge ?? undefined;
1062
- const structured: AuthCookie[] = [
1063
- {
1064
- name: names.token,
1065
- value: cookies.token ?? "",
1066
- options: {
1067
- ...base,
1068
- maxAge: cookies.token === null ? 0 : maxAge,
1069
- expires: cookies.token === null ? new Date(0) : undefined,
1070
- },
1071
- },
1072
- {
1073
- name: names.refreshToken,
1074
- value: cookies.refreshToken ?? "",
1075
- options: {
1076
- ...base,
1077
- maxAge: cookies.refreshToken === null ? 0 : maxAge,
1078
- expires: cookies.refreshToken === null ? new Date(0) : undefined,
1079
- },
1080
- },
1081
- {
1082
- name: names.verifier,
1083
- value: cookies.verifier ?? "",
1084
- options: {
1085
- ...base,
1086
- maxAge: cookies.verifier === null ? 0 : maxAge,
1087
- expires: cookies.verifier === null ? new Date(0) : undefined,
1088
- },
1089
- },
1090
- ];
1091
-
1092
- if (legacyNames.token !== names.token) {
1093
- structured.push(
1094
- {
1095
- name: legacyNames.token,
1096
- value: "",
1097
- options: {
1098
- ...base,
1099
- maxAge: 0,
1100
- expires: new Date(0),
1101
- },
1102
- },
1103
- {
1104
- name: legacyNames.refreshToken,
1105
- value: "",
1106
- options: {
1107
- ...base,
1108
- maxAge: 0,
1109
- expires: new Date(0),
1110
- },
1111
- },
1112
- {
1113
- name: legacyNames.verifier,
1114
- value: "",
1115
- options: {
1116
- ...base,
1117
- maxAge: 0,
1118
- expires: new Date(0),
1119
- },
1120
- },
1121
- );
1122
- }
1123
-
1124
- return structured;
1125
- }
1126
-
1127
- /**
1128
- * Check whether a request pathname matches the auth proxy route.
1129
- *
1130
- * Handles trailing-slash ambiguity: both `/api/auth` and `/api/auth/`
1131
- * match regardless of how `apiRoute` is configured.
1132
- *
1133
- * @param pathname - The request URL pathname.
1134
- * @param apiRoute - The configured proxy route (e.g. `"/api/auth"`).
1135
- * @returns `true` when the pathname matches the proxy route.
1136
- */
1137
- export function shouldProxyAuthAction(pathname: string, apiRoute: string) {
1138
- if (apiRoute.endsWith("/")) {
1139
- return pathname === apiRoute || pathname === apiRoute.slice(0, -1);
1140
- }
1141
- return pathname === apiRoute || pathname === `${apiRoute}/`;
1142
- }
1143
-
1144
- const REQUIRED_TOKEN_LIFETIME_MS = 60_000;
1145
- const MINIMUM_REQUIRED_TOKEN_LIFETIME_MS = 10_000;
1146
-
1147
- type DecodedToken = { exp?: number; iat?: number; iss?: string };
1148
-
1149
- function normalizeCookieNamespace(cookieNamespace?: string | null) {
1150
- if (cookieNamespace === undefined || cookieNamespace === null) {
1151
- return null;
1152
- }
1153
- const normalized = cookieNamespace
1154
- .trim()
1155
- .replace(/[^a-zA-Z0-9]+/g, "_")
1156
- .replace(/^_+|_+$/g, "")
1157
- .toLowerCase();
1158
- return normalized.length > 0 ? normalized : null;
1159
- }
1160
-
1161
- /**
1162
- * Safely check if a string is a valid URL without throwing.
1163
- */
1164
- function canParseUrl(value: string): boolean {
1165
- try {
1166
- new URL(value);
1167
- return true;
1168
- } catch {
1169
- return false;
1170
- }
1171
- }
1172
-
1173
- function serializeAuthCookie(cookie: AuthCookie): string {
1174
- const parts = [
1175
- `${cookie.name}=${cookie.value}`,
1176
- `Path=${cookie.options.path}`,
1177
- ];
1178
- if (cookie.options.httpOnly) parts.push("HttpOnly");
1179
- if (cookie.options.secure) parts.push("Secure");
1180
- if (cookie.options.sameSite)
1181
- parts.push(`SameSite=${cookie.options.sameSite}`);
1182
- if (cookie.options.maxAge !== undefined)
1183
- parts.push(`Max-Age=${cookie.options.maxAge}`);
1184
- if (cookie.options.expires)
1185
- parts.push(`Expires=${cookie.options.expires.toUTCString()}`);
1186
- return parts.join("; ");
1187
- }
1188
-
1189
- function buildRedirectResponse(
1190
- location: string,
1191
- cookies: AuthCookie[],
1192
- ): Response {
1193
- const headers = new Headers({ Location: location });
1194
- for (const cookie of cookies) {
1195
- headers.append("Set-Cookie", serializeAuthCookie(cookie));
1196
- }
1197
- return new Response(null, { status: 302, headers });
1198
- }
1199
-
1200
- function deriveCookieNamespaceFromUrl(url: string) {
1201
- if (!canParseUrl(url)) return DERIVED_COOKIE_NAMESPACE_FALLBACK;
1202
- const parsed = new URL(url);
1203
- const raw = `${parsed.hostname}${parsed.pathname}`;
1204
- return normalizeCookieNamespace(raw) ?? DERIVED_COOKIE_NAMESPACE_FALLBACK;
1205
- }
1206
-
1207
- function normalizeIssuer(value: string) {
1208
- if (!canParseUrl(value)) return value.replace(/\/+$/, "");
1209
- const parsed = new URL(value);
1210
- const pathname =
1211
- parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/+$/, "");
1212
- return `${parsed.protocol}//${parsed.host}${pathname}`;
1213
- }
1214
-
1215
- function convexSiteIssuerFromCloudUrl(value: string) {
1216
- if (!canParseUrl(value)) return null;
1217
- const parsed = new URL(value);
1218
- if (!parsed.hostname.endsWith(".convex.cloud")) {
1219
- return null;
1220
- }
1221
- parsed.hostname =
1222
- parsed.hostname.slice(0, -".convex.cloud".length) + ".convex.site";
1223
- return normalizeIssuer(parsed.toString());
1224
- }
1225
-
1226
- function defaultAcceptedIssuersForUrl(value: string) {
1227
- const issuers = [normalizeIssuer(value)];
1228
- const siteIssuer = convexSiteIssuerFromCloudUrl(value);
1229
- if (siteIssuer !== null) {
1230
- issuers.push(siteIssuer);
1231
- }
1232
- return issuers;
1233
- }
1234
-
1235
- /**
1236
- * Create an SSR auth helper for server-side frameworks.
1237
- *
1238
- * Handles cookie-based token management, OAuth code exchange,
1239
- * and automatic JWT refresh on page loads. Works with any
1240
- * framework that gives you a `Request` object — SvelteKit,
1241
- * TanStack Start, Remix, Next.js, etc.
1242
- *
1243
- * @param options - SSR configuration (Convex API URL, issuer rules, proxy route, cookie lifetime).
1244
- * @returns An object with `token`, `verify`, `proxy`, and `refresh` methods.
1245
- *
1246
- * @example SvelteKit hooks
1247
- * ```ts
1248
- * // src/hooks.server.ts
1249
- * import { server } from '@robelest/convex-auth/server';
1250
- *
1251
- * const auth = server({ url: CONVEX_URL });
1252
- *
1253
- * export const handle = async ({ event, resolve }) => {
1254
- * const { cookies, token } = await auth.refresh(event.request);
1255
- * for (const c of cookies) event.cookies.set(c.name, c.value, c.options);
1256
- * event.locals.token = token;
1257
- * return resolve(event);
1258
- * };
1259
- * ```
1260
- *
1261
- * @example Generic proxy endpoint
1262
- * ```ts
1263
- * if (shouldProxyAuthAction(url.pathname, '/api/auth')) {
1264
- * return auth.proxy(request);
1265
- * }
1266
- * ```
1267
- */
1268
- export function server(options: ServerOptions) {
1269
- const convexUrl = options.url;
1270
- const apiRoute = options.apiRoute ?? "/api/auth";
1271
- const cookieConfig = { maxAge: options.cookieMaxAge ?? null };
1272
- const verbose = options.verbose ?? false;
1273
- const cookieNamespace =
1274
- normalizeCookieNamespace(options.cookieNamespace) ??
1275
- deriveCookieNamespaceFromUrl(convexUrl);
1276
- const acceptedIssuers = new Set(
1277
- (options.acceptedIssuers ?? defaultAcceptedIssuersForUrl(convexUrl))
1278
- .map(normalizeIssuer)
1279
- .filter((issuer) => issuer.length > 0),
1280
- );
1281
-
1282
- return {
1283
- /**
1284
- * Read the JWT from the request cookies without any validation.
1285
- *
1286
- * @param request - The incoming HTTP request.
1287
- * @returns The raw JWT string, or `null` when no token cookie exists.
1288
- */
1289
- token(request: Request): string | null {
1290
- return parseAuthCookies(
1291
- request.headers.get("cookie"),
1292
- request.headers.get("host") ?? new URL(request.url).host,
1293
- cookieNamespace,
1294
- ).token;
1295
- },
1296
-
1297
- /**
1298
- * Check whether the request carries a non-expired JWT.
1299
- *
1300
- * Performs local expiration checking only (no network call).
1301
- * Use for lightweight auth guards in middleware.
1302
- *
1303
- * @param request - The incoming HTTP request.
1304
- * @returns `true` when a valid, non-expired JWT exists in the cookies.
1305
- */
1306
- async verify(request: Request): Promise<boolean> {
1307
- const token = parseAuthCookies(
1308
- request.headers.get("cookie"),
1309
- request.headers.get("host") ?? new URL(request.url).host,
1310
- cookieNamespace,
1311
- ).token;
1312
- if (token === null) {
1313
- return false;
1314
- }
1315
- const decodedToken = await Fx.run(
1316
- Fx.attempt(
1317
- async () => jwtDecode<DecodedToken>(token),
1318
- (decoded) => decoded,
1319
- () => null,
1320
- ),
1321
- );
1322
- if (decodedToken?.exp === undefined || decodedToken.iss === undefined) {
1323
- return false;
1324
- }
1325
- if (!acceptedIssuers.has(normalizeIssuer(decodedToken.iss))) {
1326
- return false;
1327
- }
1328
- return decodedToken.exp * 1000 > Date.now();
1329
- },
1330
-
1331
- /**
1332
- * Handle a proxied `signIn` or `signOut` POST from the client.
1333
- *
1334
- * Validates the route, method, and origin, then forwards the
1335
- * action to Convex and returns a `Response` with updated
1336
- * `Set-Cookie` headers. The client never sees the real
1337
- * refresh token — it stays in httpOnly cookies.
1338
- *
1339
- * @param request - The incoming POST request from the client.
1340
- * @returns A JSON `Response` with auth result and cookie headers.
1341
- */
1342
- async proxy(request: Request): Promise<Response> {
1343
- const requestUrl = new URL(request.url);
1344
- const requestDispatch = !shouldProxyAuthAction(
1345
- requestUrl.pathname,
1346
- apiRoute,
1347
- )
1348
- ? { kind: "invalidRoute" as const }
1349
- : request.method !== "POST"
1350
- ? { kind: "invalidMethod" as const }
1351
- : (() => {
1352
- const originHeader = request.headers.get("origin");
1353
- if (originHeader === null) {
1354
- return false;
1355
- }
1356
- const forwardedProtoHeader =
1357
- request.headers.get("x-forwarded-proto");
1358
- const protocol =
1359
- forwardedProtoHeader !== null
1360
- ? (() => {
1361
- const forwardedProto = forwardedProtoHeader
1362
- .split(",")[0]
1363
- ?.trim();
1364
- if (
1365
- forwardedProto !== undefined &&
1366
- forwardedProto.length > 0
1367
- ) {
1368
- return forwardedProto.endsWith(":")
1369
- ? forwardedProto
1370
- : `${forwardedProto}:`;
1371
- }
1372
- return new URL(request.url).protocol;
1373
- })()
1374
- : new URL(request.url).protocol;
1375
- const requestHost =
1376
- request.headers.get("host") ?? new URL(request.url).host;
1377
- const hostCandidate = `${protocol}//${requestHost}`;
1378
- const host = canParseUrl(hostCandidate)
1379
- ? new URL(hostCandidate).host
1380
- : requestHost;
1381
- if (!canParseUrl(originHeader)) {
1382
- return true;
1383
- }
1384
- const originUrl = new URL(originHeader);
1385
- return (
1386
- originUrl.host !== host || originUrl.protocol !== protocol
1387
- );
1388
- })()
1389
- ? { kind: "invalidOrigin" as const }
1390
- : { kind: "valid" as const };
1391
-
1392
- const validationErrorResponse = await Fx.run(
1393
- Fx.match(requestDispatch, requestDispatch.kind, {
1394
- invalidRoute: () => new Response("Invalid route", { status: 404 }),
1395
- invalidMethod: () => new Response("Invalid method", { status: 405 }),
1396
- invalidOrigin: () => new Response("Invalid origin", { status: 403 }),
1397
- valid: () => null,
1398
- }),
1399
- );
1400
- if (validationErrorResponse !== null) {
1401
- return validationErrorResponse;
1402
- }
1403
-
1404
- const body = await Fx.run(
1405
- Fx.attempt(
1406
- async () => {
1407
- const parsed = await request.json();
1408
- if (typeof parsed !== "object" || parsed === null) {
1409
- return null;
1410
- }
1411
- return parsed as Record<string, unknown>;
1412
- },
1413
- (parsed) => parsed,
1414
- () => null,
1415
- ),
1416
- );
1417
- if (body === null) {
1418
- return new Response("Invalid request body", { status: 400 });
1419
- }
1420
-
1421
- const action = body.action as string;
1422
- const args =
1423
- typeof body.args === "object" && body.args !== null
1424
- ? (body.args as Record<string, any>)
1425
- : {};
1426
-
1427
- const actionDispatch =
1428
- action === "auth:signIn"
1429
- ? { action: "sessionStart" as const }
1430
- : action === "auth:signOut"
1431
- ? { action: "sessionStop" as const }
1432
- : null;
1433
-
1434
- if (actionDispatch === null) {
1435
- return new Response("Invalid action", { status: 400 });
1436
- }
1437
-
1438
- const host = request.headers.get("host") ?? new URL(request.url).host;
1439
- const currentCookies = parseAuthCookies(
1440
- request.headers.get("cookie"),
1441
- host,
1442
- cookieNamespace,
1443
- );
1444
-
1445
- return Fx.run(
1446
- Fx.match(actionDispatch, actionDispatch.action, {
1447
- sessionStart: (_) =>
1448
- Fx.from({
1449
- ok: async () => {
1450
- const refreshDispatch =
1451
- args.refreshToken === undefined
1452
- ? { kind: "passthrough" as const }
1453
- : currentCookies.refreshToken === null
1454
- ? { kind: "refreshRequestedWithoutCookie" as const }
1455
- : {
1456
- kind: "hydrateRefreshFromCookie" as const,
1457
- refreshToken: currentCookies.refreshToken,
1458
- };
1459
-
1460
- const refreshResponse = await Fx.run(
1461
- Fx.match(refreshDispatch, refreshDispatch.kind, {
1462
- passthrough: async () => null,
1463
- hydrateRefreshFromCookie: async ({ refreshToken }) => {
1464
- args.refreshToken = refreshToken;
1465
- return null;
1466
- },
1467
- refreshRequestedWithoutCookie: async () => {
1468
- const currentToken = currentCookies.token;
1469
- const decodedToken =
1470
- currentToken === null
1471
- ? null
1472
- : await Fx.run(
1473
- Fx.attempt(
1474
- async () =>
1475
- jwtDecode<DecodedToken>(currentToken),
1476
- (decoded) => decoded,
1477
- () => null,
1478
- ),
1479
- );
1480
- const tokenDispatch =
1481
- currentToken !== null &&
1482
- decodedToken?.exp !== undefined &&
1483
- decodedToken.iss !== undefined &&
1484
- acceptedIssuers.has(
1485
- normalizeIssuer(decodedToken.iss),
1486
- ) &&
1487
- decodedToken.exp * 1000 > Date.now()
1488
- ? {
1489
- kind: "validToken" as const,
1490
- token: currentToken,
1491
- }
1492
- : { kind: "missingToken" as const };
1493
- return await Fx.run(
1494
- Fx.match(tokenDispatch, tokenDispatch.kind, {
1495
- validToken: ({ token }) =>
1496
- new Response(
1497
- JSON.stringify({
1498
- tokens: {
1499
- token,
1500
- refreshToken: "dummy",
1501
- },
1502
- }),
1503
- {
1504
- status: 200,
1505
- headers: {
1506
- "Content-Type": "application/json",
1507
- },
1508
- },
1509
- ),
1510
- missingToken: () =>
1511
- new Response(JSON.stringify({ tokens: null }), {
1512
- status: 200,
1513
- headers: {
1514
- "Content-Type": "application/json",
1515
- },
1516
- }),
1517
- }),
1518
- );
1519
- },
1520
- }),
1521
- );
1522
- const refreshDecision =
1523
- refreshResponse !== null
1524
- ? {
1525
- kind: "shortCircuit" as const,
1526
- response: refreshResponse,
1527
- }
1528
- : { kind: "continue" as const };
1529
- const maybeShortCircuitResponse = await Fx.run(
1530
- Fx.match(refreshDecision, refreshDecision.kind, {
1531
- shortCircuit: ({ response }) => response,
1532
- continue: () => null,
1533
- }),
1534
- );
1535
- if (maybeShortCircuitResponse !== null) {
1536
- return maybeShortCircuitResponse;
1537
- }
1538
-
1539
- const client = new ConvexHttpClient(convexUrl);
1540
- const authDispatch =
1541
- args.refreshToken === undefined &&
1542
- args.params?.code === undefined &&
1543
- currentCookies.token !== null
1544
- ? {
1545
- kind: "attachAuth" as const,
1546
- token: currentCookies.token,
1547
- }
1548
- : { kind: "skipAuth" as const };
1549
- await Fx.run(
1550
- Fx.match(authDispatch, authDispatch.kind, {
1551
- attachAuth: ({ token }) => {
1552
- client.setAuth(token);
1553
- },
1554
- skipAuth: () => undefined,
1555
- }),
1556
- );
1557
- return Fx.run(
1558
- Fx.from({
1559
- ok: () => client.action(signInActionRef, args),
1560
- err: (error) => error,
1561
- }).pipe(
1562
- Fx.fold({
1563
- ok: (result: SignInActionResult) =>
1564
- Fx.run(
1565
- Fx.match(result, result.kind, {
1566
- redirect: (redirectResult) => {
1567
- const response = new Response(
1568
- JSON.stringify({
1569
- kind: "redirect",
1570
- redirect: redirectResult.redirect,
1571
- verifier: redirectResult.verifier,
1572
- }),
1573
- {
1574
- status: 200,
1575
- headers: {
1576
- "Content-Type": "application/json",
1577
- },
1578
- },
1579
- );
1580
- for (const value of serializeAuthCookies(
1581
- {
1582
- ...currentCookies,
1583
- verifier: redirectResult.verifier,
1584
- },
1585
- host,
1586
- cookieConfig,
1587
- cookieNamespace,
1588
- )) {
1589
- response.headers.append("Set-Cookie", value);
1590
- }
1591
- return Fx.succeed(response);
1592
- },
1593
- signedIn: (signedInResult) => {
1594
- const response = new Response(
1595
- JSON.stringify({
1596
- kind: "signedIn",
1597
- tokens:
1598
- signedInResult.tokens === null
1599
- ? null
1600
- : {
1601
- token: signedInResult.tokens.token,
1602
- refreshToken: "dummy",
1603
- },
1604
- }),
1605
- {
1606
- status: 200,
1607
- headers: {
1608
- "Content-Type": "application/json",
1609
- },
1610
- },
1611
- );
1612
- for (const value of serializeAuthCookies(
1613
- {
1614
- token: signedInResult.tokens?.token ?? null,
1615
- refreshToken:
1616
- signedInResult.tokens?.refreshToken ?? null,
1617
- verifier: null,
1618
- },
1619
- host,
1620
- cookieConfig,
1621
- cookieNamespace,
1622
- )) {
1623
- response.headers.append("Set-Cookie", value);
1624
- }
1625
- return Fx.succeed(response);
1626
- },
1627
- started: (startedResult) =>
1628
- Fx.succeed(
1629
- new Response(JSON.stringify(startedResult), {
1630
- status: 200,
1631
- headers: {
1632
- "Content-Type": "application/json",
1633
- },
1634
- }),
1635
- ),
1636
- passkeyOptions: (passkeyOptionsResult) =>
1637
- Fx.succeed(
1638
- new Response(
1639
- JSON.stringify(passkeyOptionsResult),
1640
- {
1641
- status: 200,
1642
- headers: {
1643
- "Content-Type": "application/json",
1644
- },
1645
- },
1646
- ),
1647
- ),
1648
- totpRequired: (totpRequiredResult) =>
1649
- Fx.succeed(
1650
- new Response(
1651
- JSON.stringify(totpRequiredResult),
1652
- {
1653
- status: 200,
1654
- headers: {
1655
- "Content-Type": "application/json",
1656
- },
1657
- },
1658
- ),
1659
- ),
1660
- totpSetup: (totpSetupResult) =>
1661
- Fx.succeed(
1662
- new Response(JSON.stringify(totpSetupResult), {
1663
- status: 200,
1664
- headers: {
1665
- "Content-Type": "application/json",
1666
- },
1667
- }),
1668
- ),
1669
- deviceCode: (deviceCodeResult) =>
1670
- Fx.succeed(
1671
- new Response(JSON.stringify(deviceCodeResult), {
1672
- status: 200,
1673
- headers: {
1674
- "Content-Type": "application/json",
1675
- },
1676
- }),
1677
- ),
1678
- }),
1679
- ),
1680
- err: (error: unknown) => {
1681
- const errorBody =
1682
- error instanceof ConvexError &&
1683
- typeof error.data === "object" &&
1684
- error.data !== null &&
1685
- "code" in error.data
1686
- ? {
1687
- error:
1688
- (error.data as { message?: string })
1689
- .message ?? String(error),
1690
- authError: error.data,
1691
- }
1692
- : {
1693
- error:
1694
- error instanceof Error
1695
- ? error.message
1696
- : String(error),
1697
- };
1698
- const response = new Response(
1699
- JSON.stringify(errorBody),
1700
- {
1701
- status: 400,
1702
- headers: {
1703
- "Content-Type": "application/json",
1704
- },
1705
- },
1706
- );
1707
- const clearSession =
1708
- args.refreshToken !== undefined &&
1709
- error instanceof ConvexError &&
1710
- typeof error.data === "object" &&
1711
- error.data !== null &&
1712
- (error.data as Record<string, unknown>).code ===
1713
- "INVALID_REFRESH_TOKEN";
1714
- for (const value of serializeAuthCookies(
1715
- {
1716
- token: clearSession ? null : currentCookies.token,
1717
- refreshToken: clearSession
1718
- ? null
1719
- : currentCookies.refreshToken,
1720
- verifier: null,
1721
- },
1722
- host,
1723
- cookieConfig,
1724
- cookieNamespace,
1725
- )) {
1726
- response.headers.append("Set-Cookie", value);
1727
- }
1728
- return response;
1729
- },
1730
- }),
1731
- ),
1732
- );
1733
- },
1734
- err: (e) => e as never,
1735
- }),
1736
- sessionStop: (_) =>
1737
- Fx.from({
1738
- ok: async () => {
1739
- await Fx.run(
1740
- Fx.from({
1741
- ok: () =>
1742
- (() => {
1743
- const client = new ConvexHttpClient(convexUrl);
1744
- if (currentCookies.token !== null) {
1745
- client.setAuth(currentCookies.token);
1746
- }
1747
- return client.action(signOutActionRef);
1748
- })(),
1749
- err: (error) => error,
1750
- }).pipe(
1751
- Fx.recover((error: unknown) => {
1752
- console.error(
1753
- "[convex-auth/server] proxy sign-out failed",
1754
- error,
1755
- );
1756
- const fallbackDispatch =
1757
- currentCookies.refreshToken !== null
1758
- ? {
1759
- kind: "attemptFallback" as const,
1760
- refreshToken: currentCookies.refreshToken,
1761
- }
1762
- : { kind: "skipFallback" as const };
1763
- return Fx.match(fallbackDispatch, fallbackDispatch.kind, {
1764
- attemptFallback: ({ refreshToken }) =>
1765
- Fx.from({
1766
- ok: async () => {
1767
- const refreshClient = new ConvexHttpClient(
1768
- convexUrl,
1769
- );
1770
- const refreshed = (await refreshClient.action(
1771
- signInActionRef,
1772
- {
1773
- refreshToken,
1774
- },
1775
- )) as SignInActionResult;
1776
- const refreshedTokens = await Fx.run(
1777
- Fx.match(refreshed, refreshed.kind, {
1778
- signedIn: (signedInResult) =>
1779
- Fx.succeed(signedInResult.tokens),
1780
- redirect: () =>
1781
- Fx.fatal(
1782
- new Error(
1783
- "Invalid `auth:signIn` result for sign-out fallback refresh",
1784
- ),
1785
- ),
1786
- started: () =>
1787
- Fx.fatal(
1788
- new Error(
1789
- "Invalid `auth:signIn` result for sign-out fallback refresh",
1790
- ),
1791
- ),
1792
- passkeyOptions: () =>
1793
- Fx.fatal(
1794
- new Error(
1795
- "Invalid `auth:signIn` result for sign-out fallback refresh",
1796
- ),
1797
- ),
1798
- totpRequired: () =>
1799
- Fx.fatal(
1800
- new Error(
1801
- "Invalid `auth:signIn` result for sign-out fallback refresh",
1802
- ),
1803
- ),
1804
- totpSetup: () =>
1805
- Fx.fatal(
1806
- new Error(
1807
- "Invalid `auth:signIn` result for sign-out fallback refresh",
1808
- ),
1809
- ),
1810
- deviceCode: () =>
1811
- Fx.fatal(
1812
- new Error(
1813
- "Invalid `auth:signIn` result for sign-out fallback refresh",
1814
- ),
1815
- ),
1816
- }),
1817
- );
1818
- const fallbackSignOutDispatch =
1819
- refreshedTokens !== null
1820
- ? {
1821
- kind: "signOutWithRefreshed" as const,
1822
- token: refreshedTokens.token,
1823
- }
1824
- : { kind: "skipRefreshedSignOut" as const };
1825
- await Fx.match(
1826
- fallbackSignOutDispatch,
1827
- fallbackSignOutDispatch.kind,
1828
- {
1829
- signOutWithRefreshed: async ({ token }) => {
1830
- const client = new ConvexHttpClient(
1831
- convexUrl,
1832
- );
1833
- client.setAuth(token);
1834
- await client.action(signOutActionRef);
1835
- },
1836
- skipRefreshedSignOut: async () => undefined,
1837
- },
1838
- );
1839
- },
1840
- err: (fallbackError) => fallbackError,
1841
- }).pipe(
1842
- Fx.recover((fallbackError: unknown) => {
1843
- console.error(
1844
- "[convex-auth/server] proxy sign-out fallback failed",
1845
- fallbackError,
1846
- );
1847
- return Fx.succeed(undefined);
1848
- }),
1849
- ),
1850
- skipFallback: () => Fx.succeed(undefined),
1851
- });
1852
- }),
1853
- Fx.map(() => undefined),
1854
- ),
1855
- );
1856
- const response = new Response(JSON.stringify(null), {
1857
- status: 200,
1858
- headers: {
1859
- "Content-Type": "application/json",
1860
- },
1861
- });
1862
- for (const value of serializeAuthCookies(
1863
- {
1864
- token: null,
1865
- refreshToken: null,
1866
- verifier: null,
1867
- },
1868
- host,
1869
- cookieConfig,
1870
- cookieNamespace,
1871
- )) {
1872
- response.headers.append("Set-Cookie", value);
1873
- }
1874
- return response;
1875
- },
1876
- err: (e) => e as never,
1877
- }),
1878
- }),
1879
- );
1880
- },
1881
-
1882
- /**
1883
- * Refresh auth tokens on page load.
1884
- *
1885
- * Call this in your server hooks/middleware on every request.
1886
- * It handles three scenarios:
1887
- *
1888
- * 1. **OAuth code exchange** — exchanges a `?code=` query param for tokens and returns a redirect URL.
1889
- * 2. **Token refresh** — refreshes the JWT if it's close to expiry.
1890
- * 3. **No-op** — returns the existing token when no refresh is needed.
1891
- *
1892
- * @param request - The incoming HTTP request.
1893
- * @returns Structured cookies to set on the response, an optional redirect URL, and the current JWT.
1894
- */
1895
- async refresh(request: Request): Promise<RefreshResult> {
1896
- const host = request.headers.get("host") ?? new URL(request.url).host;
1897
- const currentCookies = parseAuthCookies(
1898
- request.headers.get("cookie"),
1899
- host,
1900
- cookieNamespace,
1901
- );
1902
- const currentToken = currentCookies.token;
1903
-
1904
- // CORS request — do not mutate auth cookies from cross-origin requests.
1905
- const originHeader = request.headers.get("origin");
1906
- const forwardedProtoHeader = request.headers.get("x-forwarded-proto");
1907
- const protocol =
1908
- forwardedProtoHeader !== null
1909
- ? (() => {
1910
- const forwardedProto = forwardedProtoHeader.split(",")[0]?.trim();
1911
- if (forwardedProto !== undefined && forwardedProto.length > 0) {
1912
- return forwardedProto.endsWith(":")
1913
- ? forwardedProto
1914
- : `${forwardedProto}:`;
1915
- }
1916
- return new URL(request.url).protocol;
1917
- })()
1918
- : new URL(request.url).protocol;
1919
- const requestHost =
1920
- request.headers.get("host") ?? new URL(request.url).host;
1921
- const hostCandidate = `${protocol}//${requestHost}`;
1922
- const normalizedHost = canParseUrl(hostCandidate)
1923
- ? new URL(hostCandidate).host
1924
- : requestHost;
1925
- const originUrl =
1926
- originHeader !== null && canParseUrl(originHeader)
1927
- ? new URL(originHeader)
1928
- : null;
1929
- const corsRequest =
1930
- originHeader !== null &&
1931
- (originUrl === null ||
1932
- originUrl.host !== normalizedHost ||
1933
- originUrl.protocol !== protocol);
1934
- const corsDispatch = corsRequest
1935
- ? { kind: "crossOrigin" as const }
1936
- : { kind: "sameOrigin" as const };
1937
- const corsRefreshResult = await Fx.run(
1938
- Fx.match(corsDispatch, corsDispatch.kind, {
1939
- crossOrigin: () =>
1940
- ({
1941
- redirect: false,
1942
- cookies: [],
1943
- token: null,
1944
- }) satisfies RefreshResult,
1945
- sameOrigin: () => null,
1946
- }),
1947
- );
1948
- if (corsRefreshResult !== null) {
1949
- return corsRefreshResult;
1950
- }
1951
-
1952
- // OAuth code exchange — exchange code for tokens and redirect.
1953
- const requestUrl = new URL(request.url);
1954
- const code = requestUrl.searchParams.get("code");
1955
- const shouldHandleCode =
1956
- options.shouldHandleCode === undefined
1957
- ? true
1958
- : typeof options.shouldHandleCode === "function"
1959
- ? await options.shouldHandleCode(request)
1960
- : options.shouldHandleCode;
1961
-
1962
- const codeExchangeDispatch =
1963
- code !== null &&
1964
- request.method === "GET" &&
1965
- request.headers.get("accept")?.includes("text/html") &&
1966
- shouldHandleCode
1967
- ? { kind: "exchange" as const, code }
1968
- : { kind: "skip" as const };
1969
- const codeExchangeResult = await Fx.run(
1970
- Fx.match(codeExchangeDispatch, codeExchangeDispatch.kind, {
1971
- exchange: async ({
1972
- code: verificationCode,
1973
- }): Promise<RefreshResult> => {
1974
- const redirectUrl = new URL(requestUrl.toString());
1975
- return Fx.run(
1976
- Fx.from({
1977
- ok: async () => {
1978
- const client = new ConvexHttpClient(convexUrl);
1979
- const result = (await client.action(signInActionRef, {
1980
- params: { code: verificationCode },
1981
- verifier: currentCookies.verifier ?? undefined,
1982
- })) as SignInActionResult;
1983
- const tokens = await Fx.run(
1984
- Fx.match(result, result.kind, {
1985
- signedIn: (signedInResult) =>
1986
- Fx.succeed(signedInResult.tokens),
1987
- redirect: () =>
1988
- Fx.fatal(
1989
- new Error(
1990
- "Invalid `auth:signIn` result for code exchange",
1991
- ),
1992
- ),
1993
- started: () =>
1994
- Fx.fatal(
1995
- new Error(
1996
- "Invalid `auth:signIn` result for code exchange",
1997
- ),
1998
- ),
1999
- passkeyOptions: () =>
2000
- Fx.fatal(
2001
- new Error(
2002
- "Invalid `auth:signIn` result for code exchange",
2003
- ),
2004
- ),
2005
- totpRequired: () =>
2006
- Fx.fatal(
2007
- new Error(
2008
- "Invalid `auth:signIn` result for code exchange",
2009
- ),
2010
- ),
2011
- totpSetup: () =>
2012
- Fx.fatal(
2013
- new Error(
2014
- "Invalid `auth:signIn` result for code exchange",
2015
- ),
2016
- ),
2017
- deviceCode: () =>
2018
- Fx.fatal(
2019
- new Error(
2020
- "Invalid `auth:signIn` result for code exchange",
2021
- ),
2022
- ),
2023
- }),
2024
- );
2025
- return { kind: "signedIn" as const, tokens };
2026
- },
2027
- err: (error) => error,
2028
- }).pipe(
2029
- Fx.fold({
2030
- ok: (result): RefreshResult => {
2031
- redirectUrl.searchParams.delete("code");
2032
- const cookies = structuredAuthCookies(
2033
- {
2034
- token: result.tokens?.token ?? null,
2035
- refreshToken: result.tokens?.refreshToken ?? null,
2036
- verifier: null,
2037
- },
2038
- host,
2039
- cookieConfig,
2040
- cookieNamespace,
2041
- );
2042
- return {
2043
- redirect: true,
2044
- response: buildRedirectResponse(
2045
- redirectUrl.toString(),
2046
- cookies,
2047
- ),
2048
- };
2049
- },
2050
- err: (error: unknown): RefreshResult => {
2051
- console.error(
2052
- "[convex-auth/server] code exchange failed",
2053
- error,
2054
- );
2055
- const errorCode =
2056
- error instanceof ConvexError &&
2057
- typeof error.data === "object" &&
2058
- error.data !== null &&
2059
- typeof (error.data as Record<string, unknown>).code ===
2060
- "string"
2061
- ? ((error.data as Record<string, unknown>)
2062
- .code as string)
2063
- : null;
2064
- const terminalCodeExchangeError =
2065
- errorCode === "OAUTH_INVALID_STATE" ||
2066
- errorCode === "OAUTH_PROVIDER_ERROR" ||
2067
- errorCode === "OAUTH_MISSING_ID_TOKEN" ||
2068
- errorCode === "OAUTH_INVALID_PROFILE" ||
2069
- errorCode === "OAUTH_MISSING_VERIFIER" ||
2070
- errorCode === "INVALID_VERIFIER" ||
2071
- errorCode === "INVALID_VERIFICATION_CODE";
2072
- if (!terminalCodeExchangeError) {
2073
- return {
2074
- redirect: false,
2075
- cookies: [],
2076
- token: currentCookies.token,
2077
- };
2078
- }
2079
- redirectUrl.searchParams.delete("code");
2080
- const cookies = structuredAuthCookies(
2081
- {
2082
- token: currentCookies.token,
2083
- refreshToken: currentCookies.refreshToken,
2084
- verifier: null,
2085
- },
2086
- host,
2087
- cookieConfig,
2088
- cookieNamespace,
2089
- );
2090
- return {
2091
- redirect: true,
2092
- response: buildRedirectResponse(
2093
- redirectUrl.toString(),
2094
- cookies,
2095
- ),
2096
- };
2097
- },
2098
- }),
2099
- ),
2100
- );
2101
- },
2102
- skip: async () => null,
2103
- }),
2104
- );
2105
- const codeExchangeDecision =
2106
- codeExchangeResult !== null
2107
- ? { kind: "done" as const, result: codeExchangeResult }
2108
- : { kind: "continue" as const };
2109
- const maybeCodeExchangeResult = await Fx.run(
2110
- Fx.match(codeExchangeDecision, codeExchangeDecision.kind, {
2111
- done: ({ result }) => result,
2112
- continue: () => null,
2113
- }),
2114
- );
2115
- if (maybeCodeExchangeResult !== null) {
2116
- return maybeCodeExchangeResult;
2117
- }
2118
-
2119
- // Normal page load — refresh tokens if needed.
2120
- const tokens = await Fx.run(
2121
- Fx.gen(function* () {
2122
- const { token, refreshToken } = currentCookies;
2123
-
2124
- const isMalformedRefreshToken =
2125
- refreshToken !== null &&
2126
- (refreshToken.trim().length === 0 || refreshToken === "dummy");
2127
- const malformedRefreshTokenDispatch = isMalformedRefreshToken
2128
- ? { kind: "malformed" as const }
2129
- : { kind: "ok" as const };
2130
- const malformedRefreshTokenResult = yield* Fx.match(
2131
- malformedRefreshTokenDispatch,
2132
- malformedRefreshTokenDispatch.kind,
2133
- {
2134
- malformed: () => {
2135
- if (verbose) {
2136
- console.debug(
2137
- `${new Date().toISOString()} [convex-auth/server] Refresh token cookie malformed, clearing auth cookies`,
2138
- );
2139
- }
2140
- return null;
2141
- },
2142
- ok: () => undefined,
2143
- },
2144
- );
2145
- if (malformedRefreshTokenResult !== undefined) {
2146
- return malformedRefreshTokenResult;
2147
- }
2148
-
2149
- const decodedToken =
2150
- token === null
2151
- ? null
2152
- : yield* Fx.attempt(
2153
- async () => jwtDecode<DecodedToken>(token),
2154
- (decoded) => decoded,
2155
- () => null,
2156
- );
2157
- const issuerDispatch =
2158
- decodedToken?.iss !== undefined &&
2159
- !acceptedIssuers.has(normalizeIssuer(decodedToken.iss))
2160
- ? { kind: "issuerMismatch" as const }
2161
- : { kind: "issuerOk" as const };
2162
- const issuerResult = yield* Fx.match(
2163
- issuerDispatch,
2164
- issuerDispatch.kind,
2165
- {
2166
- issuerMismatch: () => {
2167
- if (verbose) {
2168
- console.debug(
2169
- `${new Date().toISOString()} [convex-auth/server] Access token issuer mismatch, clearing auth cookies`,
2170
- );
2171
- }
2172
- return null;
2173
- },
2174
- issuerOk: () => undefined,
2175
- },
2176
- );
2177
- if (issuerResult !== undefined) {
2178
- return issuerResult;
2179
- }
2180
-
2181
- const tokenState =
2182
- token === null
2183
- ? refreshToken === null
2184
- ? { kind: "none" as const }
2185
- : { kind: "refreshOnly" as const, refreshToken }
2186
- : refreshToken === null
2187
- ? { kind: "accessOnly" as const, token }
2188
- : { kind: "both" as const, token, refreshToken };
2189
-
2190
- return yield* Fx.match(tokenState, tokenState.kind, {
2191
- none: () => {
2192
- if (verbose) {
2193
- console.debug(
2194
- `${new Date().toISOString()} [convex-auth/server] No auth cookies found, skipping refresh`,
2195
- );
2196
- }
2197
- return Fx.succeed(undefined);
2198
- },
2199
- refreshOnly: ({ refreshToken: refreshTokenValue }) => {
2200
- if (verbose) {
2201
- console.debug(
2202
- `${new Date().toISOString()} [convex-auth/server] Access token cookie missing, attempting refresh-token recovery`,
2203
- );
2204
- }
2205
- return Fx.from({
2206
- ok: async () => {
2207
- const client = new ConvexHttpClient(convexUrl);
2208
- const result = (await client.action(signInActionRef, {
2209
- refreshToken: refreshTokenValue,
2210
- })) as SignInActionResult;
2211
- const tokens = await Fx.run(
2212
- Fx.match(result, result.kind, {
2213
- signedIn: (signedInResult) =>
2214
- Fx.succeed(signedInResult.tokens),
2215
- redirect: () =>
2216
- Fx.fatal(
2217
- new Error(
2218
- "Invalid `auth:signIn` result for token refresh",
2219
- ),
2220
- ),
2221
- started: () =>
2222
- Fx.fatal(
2223
- new Error(
2224
- "Invalid `auth:signIn` result for token refresh",
2225
- ),
2226
- ),
2227
- passkeyOptions: () =>
2228
- Fx.fatal(
2229
- new Error(
2230
- "Invalid `auth:signIn` result for token refresh",
2231
- ),
2232
- ),
2233
- totpRequired: () =>
2234
- Fx.fatal(
2235
- new Error(
2236
- "Invalid `auth:signIn` result for token refresh",
2237
- ),
2238
- ),
2239
- totpSetup: () =>
2240
- Fx.fatal(
2241
- new Error(
2242
- "Invalid `auth:signIn` result for token refresh",
2243
- ),
2244
- ),
2245
- deviceCode: () =>
2246
- Fx.fatal(
2247
- new Error(
2248
- "Invalid `auth:signIn` result for token refresh",
2249
- ),
2250
- ),
2251
- }),
2252
- );
2253
- if (verbose) {
2254
- console.debug(
2255
- `${new Date().toISOString()} [convex-auth/server] Refreshed tokens, null=${tokens === null}`,
2256
- );
2257
- }
2258
- return tokens;
2259
- },
2260
- err: (error) => error,
2261
- }).pipe(
2262
- Fx.recover((error: unknown) => {
2263
- console.error(
2264
- "[convex-auth/server] refresh-token exchange failed",
2265
- error,
2266
- );
2267
- const errorCode =
2268
- error instanceof ConvexError &&
2269
- typeof error.data === "object" &&
2270
- error.data !== null &&
2271
- typeof (error.data as Record<string, unknown>).code ===
2272
- "string"
2273
- ? ((error.data as Record<string, unknown>).code as string)
2274
- : null;
2275
- if (errorCode === "INVALID_REFRESH_TOKEN") {
2276
- if (verbose) {
2277
- console.debug(
2278
- `${new Date().toISOString()} [convex-auth/server] Refresh token rejected, clearing auth cookies`,
2279
- );
2280
- }
2281
- return Fx.succeed(
2282
- null as
2283
- | { token: string; refreshToken: string }
2284
- | null
2285
- | undefined,
2286
- );
2287
- }
2288
- if (verbose) {
2289
- console.debug(
2290
- `${new Date().toISOString()} [convex-auth/server] Token refresh failed transiently, keeping current cookies`,
2291
- );
2292
- }
2293
- return Fx.succeed(
2294
- undefined as
2295
- | { token: string; refreshToken: string }
2296
- | null
2297
- | undefined,
2298
- );
2299
- }),
2300
- );
2301
- },
2302
- accessOnly: () => {
2303
- const accessOnlyDispatch =
2304
- decodedToken?.exp !== undefined &&
2305
- decodedToken.iss !== undefined &&
2306
- acceptedIssuers.has(normalizeIssuer(decodedToken.iss)) &&
2307
- decodedToken.exp * 1000 > Date.now()
2308
- ? { kind: "accessValid" as const }
2309
- : { kind: "accessInvalid" as const };
2310
- return Fx.match(accessOnlyDispatch, accessOnlyDispatch.kind, {
2311
- accessValid: () => {
2312
- if (verbose) {
2313
- console.debug(
2314
- `${new Date().toISOString()} [convex-auth/server] Refresh token cookie missing but access token still valid`,
2315
- );
2316
- }
2317
- return Fx.succeed(undefined);
2318
- },
2319
- accessInvalid: () => {
2320
- if (verbose) {
2321
- console.debug(
2322
- `${new Date().toISOString()} [convex-auth/server] Refresh token cookie missing and access token invalid, clearing`,
2323
- );
2324
- }
2325
- return Fx.succeed(null);
2326
- },
2327
- });
2328
- },
2329
- both: ({ refreshToken: refreshTokenValue }) => {
2330
- const bothDecodeDispatch:
2331
- | { kind: "undecodable" }
2332
- | {
2333
- kind: "decoded";
2334
- decodedToken: DecodedToken & {
2335
- exp: number;
2336
- iat: number;
2337
- };
2338
- } =
2339
- decodedToken?.exp === undefined ||
2340
- decodedToken.iat === undefined
2341
- ? { kind: "undecodable" as const }
2342
- : {
2343
- kind: "decoded" as const,
2344
- decodedToken: decodedToken as DecodedToken & {
2345
- exp: number;
2346
- iat: number;
2347
- },
2348
- };
2349
- return Fx.match(bothDecodeDispatch, bothDecodeDispatch.kind, {
2350
- undecodable: () => {
2351
- if (verbose) {
2352
- console.debug(
2353
- `${new Date().toISOString()} [convex-auth/server] Failed to decode access token, attempting refresh-token recovery`,
2354
- );
2355
- }
2356
- return Fx.from({
2357
- ok: async () => {
2358
- const client = new ConvexHttpClient(convexUrl);
2359
- const result = (await client.action(signInActionRef, {
2360
- refreshToken: refreshTokenValue,
2361
- })) as SignInActionResult;
2362
- const tokens = await Fx.run(
2363
- Fx.match(result, result.kind, {
2364
- signedIn: (signedInResult) =>
2365
- Fx.succeed(signedInResult.tokens),
2366
- redirect: () =>
2367
- Fx.fatal(
2368
- new Error(
2369
- "Invalid `auth:signIn` result for token refresh",
2370
- ),
2371
- ),
2372
- started: () =>
2373
- Fx.fatal(
2374
- new Error(
2375
- "Invalid `auth:signIn` result for token refresh",
2376
- ),
2377
- ),
2378
- passkeyOptions: () =>
2379
- Fx.fatal(
2380
- new Error(
2381
- "Invalid `auth:signIn` result for token refresh",
2382
- ),
2383
- ),
2384
- totpRequired: () =>
2385
- Fx.fatal(
2386
- new Error(
2387
- "Invalid `auth:signIn` result for token refresh",
2388
- ),
2389
- ),
2390
- totpSetup: () =>
2391
- Fx.fatal(
2392
- new Error(
2393
- "Invalid `auth:signIn` result for token refresh",
2394
- ),
2395
- ),
2396
- deviceCode: () =>
2397
- Fx.fatal(
2398
- new Error(
2399
- "Invalid `auth:signIn` result for token refresh",
2400
- ),
2401
- ),
2402
- }),
2403
- );
2404
- if (verbose) {
2405
- console.debug(
2406
- `${new Date().toISOString()} [convex-auth/server] Refreshed tokens, null=${tokens === null}`,
2407
- );
2408
- }
2409
- return tokens;
2410
- },
2411
- err: (error) => error,
2412
- }).pipe(
2413
- Fx.recover((error: unknown) => {
2414
- console.error(
2415
- "[convex-auth/server] refresh-token exchange failed",
2416
- error,
2417
- );
2418
- const errorCode =
2419
- error instanceof ConvexError &&
2420
- typeof error.data === "object" &&
2421
- error.data !== null &&
2422
- typeof (error.data as Record<string, unknown>).code ===
2423
- "string"
2424
- ? ((error.data as Record<string, unknown>)
2425
- .code as string)
2426
- : null;
2427
- if (errorCode === "INVALID_REFRESH_TOKEN") {
2428
- if (verbose) {
2429
- console.debug(
2430
- `${new Date().toISOString()} [convex-auth/server] Refresh token rejected, clearing auth cookies`,
2431
- );
2432
- }
2433
- return Fx.succeed(
2434
- null as
2435
- | { token: string; refreshToken: string }
2436
- | null
2437
- | undefined,
2438
- );
2439
- }
2440
- if (verbose) {
2441
- console.debug(
2442
- `${new Date().toISOString()} [convex-auth/server] Token refresh failed transiently, keeping current cookies`,
2443
- );
2444
- }
2445
- return Fx.succeed(
2446
- undefined as
2447
- | { token: string; refreshToken: string }
2448
- | null
2449
- | undefined,
2450
- );
2451
- }),
2452
- );
2453
- },
2454
- decoded: ({ decodedToken: decodedAccessToken }) => {
2455
- const totalTokenLifetimeMs =
2456
- decodedAccessToken.exp * 1000 -
2457
- decodedAccessToken.iat * 1000;
2458
- const minimumExpiration =
2459
- Date.now() +
2460
- Math.min(
2461
- REQUIRED_TOKEN_LIFETIME_MS,
2462
- Math.max(
2463
- MINIMUM_REQUIRED_TOKEN_LIFETIME_MS,
2464
- totalTokenLifetimeMs / 10,
2465
- ),
2466
- );
2467
- const expirationDispatch =
2468
- decodedAccessToken.exp * 1000 > minimumExpiration
2469
- ? { kind: "skipRefresh" as const }
2470
- : { kind: "refresh" as const };
2471
- return Fx.match(expirationDispatch, expirationDispatch.kind, {
2472
- skipRefresh: () => {
2473
- if (verbose) {
2474
- console.debug(
2475
- `${new Date().toISOString()} [convex-auth/server] Token valid long enough, skipping refresh`,
2476
- );
2477
- }
2478
- return Fx.succeed(undefined);
2479
- },
2480
- refresh: () =>
2481
- Fx.from({
2482
- ok: async () => {
2483
- const client = new ConvexHttpClient(convexUrl);
2484
- const result = (await client.action(signInActionRef, {
2485
- refreshToken: refreshTokenValue,
2486
- })) as SignInActionResult;
2487
- const tokens = await Fx.run(
2488
- Fx.match(result, result.kind, {
2489
- signedIn: (signedInResult) =>
2490
- Fx.succeed(signedInResult.tokens),
2491
- redirect: () =>
2492
- Fx.fatal(
2493
- new Error(
2494
- "Invalid `auth:signIn` result for token refresh",
2495
- ),
2496
- ),
2497
- started: () =>
2498
- Fx.fatal(
2499
- new Error(
2500
- "Invalid `auth:signIn` result for token refresh",
2501
- ),
2502
- ),
2503
- passkeyOptions: () =>
2504
- Fx.fatal(
2505
- new Error(
2506
- "Invalid `auth:signIn` result for token refresh",
2507
- ),
2508
- ),
2509
- totpRequired: () =>
2510
- Fx.fatal(
2511
- new Error(
2512
- "Invalid `auth:signIn` result for token refresh",
2513
- ),
2514
- ),
2515
- totpSetup: () =>
2516
- Fx.fatal(
2517
- new Error(
2518
- "Invalid `auth:signIn` result for token refresh",
2519
- ),
2520
- ),
2521
- deviceCode: () =>
2522
- Fx.fatal(
2523
- new Error(
2524
- "Invalid `auth:signIn` result for token refresh",
2525
- ),
2526
- ),
2527
- }),
2528
- );
2529
- if (verbose) {
2530
- console.debug(
2531
- `${new Date().toISOString()} [convex-auth/server] Refreshed tokens, null=${tokens === null}`,
2532
- );
2533
- }
2534
- return tokens;
2535
- },
2536
- err: (error) => error,
2537
- }).pipe(
2538
- Fx.recover((error: unknown) => {
2539
- console.error(
2540
- "[convex-auth/server] refresh-token exchange failed",
2541
- error,
2542
- );
2543
- const errorCode =
2544
- error instanceof ConvexError &&
2545
- typeof error.data === "object" &&
2546
- error.data !== null &&
2547
- typeof (error.data as Record<string, unknown>)
2548
- .code === "string"
2549
- ? ((error.data as Record<string, unknown>)
2550
- .code as string)
2551
- : null;
2552
- if (errorCode === "INVALID_REFRESH_TOKEN") {
2553
- if (verbose) {
2554
- console.debug(
2555
- `${new Date().toISOString()} [convex-auth/server] Refresh token rejected, clearing auth cookies`,
2556
- );
2557
- }
2558
- return Fx.succeed(
2559
- null as
2560
- | { token: string; refreshToken: string }
2561
- | null
2562
- | undefined,
2563
- );
2564
- }
2565
- if (verbose) {
2566
- console.debug(
2567
- `${new Date().toISOString()} [convex-auth/server] Token refresh failed transiently, keeping current cookies`,
2568
- );
2569
- }
2570
- return Fx.succeed(
2571
- undefined as
2572
- | { token: string; refreshToken: string }
2573
- | null
2574
- | undefined,
2575
- );
2576
- }),
2577
- ),
2578
- });
2579
- },
2580
- });
2581
- },
2582
- });
2583
- }),
2584
- );
2585
- if (tokens === undefined) {
2586
- return { redirect: false, cookies: [], token: currentToken };
2587
- }
2588
-
2589
- return {
2590
- redirect: false,
2591
- cookies: structuredAuthCookies(
2592
- {
2593
- token: tokens?.token ?? null,
2594
- refreshToken: tokens?.refreshToken ?? null,
2595
- verifier: null,
2596
- },
2597
- host,
2598
- cookieConfig,
2599
- cookieNamespace,
2600
- ),
2601
- token: tokens?.token ?? null,
2602
- };
2603
- },
2604
- };
2605
- }
1
+ export { AuthCtx, createAuth } from "./auth";
2
+ export type {
3
+ AuthApi,
4
+ AuthApiBase,
5
+ AuthConfig,
6
+ ConvexAuthResult,
7
+ InferAuth,
8
+ InferClientApi,
9
+ UserDoc,
10
+ } from "./auth";
11
+ export type {
12
+ EnterpriseAdminAuthorizationInput,
13
+ EnterpriseAdminPermission,
14
+ EnterpriseAuthorizer,
15
+ EnterpriseMountOptions,
16
+ } from "./mounts";
17
+ export { enterprise, scim, sso } from "./mounts";
18
+ export type {
19
+ AuthCookie,
20
+ AuthCookieConfig,
21
+ AuthCookies,
22
+ RefreshResult,
23
+ ServerOptions,
24
+ } from "./ssr";
25
+ export {
26
+ authCookieNames,
27
+ parseAuthCookies,
28
+ serializeAuthCookies,
29
+ server,
30
+ shouldProxyAuthAction,
31
+ structuredAuthCookies,
32
+ } from "./ssr";