@thunderid/nextjs 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (349) hide show
  1. package/dist/{types/ThunderIDNextClient.d.ts → ThunderIDNextClient.d.ts} +2 -9
  2. package/dist/ThunderIDNextClient.d.ts.map +1 -0
  3. package/dist/ThunderIDNextClient.js +161 -0
  4. package/dist/ThunderIDNextClient.js.map +1 -0
  5. package/dist/cjs/ThunderIDNextClient.cjs +163 -0
  6. package/dist/cjs/ThunderIDNextClient.cjs.map +1 -0
  7. package/dist/cjs/_virtual/rolldown_runtime.cjs +25 -0
  8. package/dist/cjs/client/components/actions/SignInButton/SignInButton.cjs +79 -0
  9. package/dist/cjs/client/components/actions/SignInButton/SignInButton.cjs.map +1 -0
  10. package/dist/cjs/client/components/actions/SignOutButton/SignOutButton.cjs +61 -0
  11. package/dist/cjs/client/components/actions/SignOutButton/SignOutButton.cjs.map +1 -0
  12. package/dist/cjs/client/components/actions/SignUpButton/SignUpButton.cjs +91 -0
  13. package/dist/cjs/client/components/actions/SignUpButton/SignUpButton.cjs.map +1 -0
  14. package/dist/cjs/client/components/control/SignedIn/SignedIn.cjs +34 -0
  15. package/dist/cjs/client/components/control/SignedIn/SignedIn.cjs.map +1 -0
  16. package/dist/cjs/client/components/control/SignedOut/SignedOut.cjs +34 -0
  17. package/dist/cjs/client/components/control/SignedOut/SignedOut.cjs.map +1 -0
  18. package/dist/cjs/client/components/presentation/SignIn/SignIn.cjs +37 -0
  19. package/dist/cjs/client/components/presentation/SignIn/SignIn.cjs.map +1 -0
  20. package/dist/cjs/client/components/presentation/SignUp/SignUp.cjs +79 -0
  21. package/dist/cjs/client/components/presentation/SignUp/SignUp.cjs.map +1 -0
  22. package/dist/cjs/client/components/presentation/User/User.cjs +49 -0
  23. package/dist/cjs/client/components/presentation/User/User.cjs.map +1 -0
  24. package/dist/cjs/client/components/presentation/UserDropdown/UserDropdown.cjs +114 -0
  25. package/dist/cjs/client/components/presentation/UserDropdown/UserDropdown.cjs.map +1 -0
  26. package/dist/cjs/client/components/presentation/UserProfile/UserProfile.cjs +52 -0
  27. package/dist/cjs/client/components/presentation/UserProfile/UserProfile.cjs.map +1 -0
  28. package/dist/cjs/client/contexts/ThunderID/ThunderIDContext.cjs +34 -0
  29. package/dist/cjs/client/contexts/ThunderID/ThunderIDContext.cjs.map +1 -0
  30. package/dist/cjs/client/contexts/ThunderID/ThunderIDProvider.cjs +165 -0
  31. package/dist/cjs/client/contexts/ThunderID/ThunderIDProvider.cjs.map +1 -0
  32. package/dist/cjs/client/contexts/ThunderID/useThunderID.cjs +19 -0
  33. package/dist/cjs/client/contexts/ThunderID/useThunderID.cjs.map +1 -0
  34. package/dist/cjs/client/index.cjs +11 -0
  35. package/dist/cjs/constants/sessionConstants.cjs +55 -0
  36. package/dist/cjs/constants/sessionConstants.cjs.map +1 -0
  37. package/dist/cjs/index.cjs +35 -1037
  38. package/dist/cjs/server/ThunderIDProvider.cjs +114 -0
  39. package/dist/cjs/server/ThunderIDProvider.cjs.map +1 -0
  40. package/dist/cjs/server/actions/clearSession.cjs +41 -0
  41. package/dist/cjs/server/actions/clearSession.cjs.map +1 -0
  42. package/dist/cjs/server/actions/getAccessToken.cjs +27 -0
  43. package/dist/cjs/server/actions/getAccessToken.cjs.map +1 -0
  44. package/dist/cjs/server/actions/getClientOrigin.cjs +18 -0
  45. package/dist/cjs/server/actions/getClientOrigin.cjs.map +1 -0
  46. package/dist/cjs/server/actions/getSessionId.cjs +28 -0
  47. package/dist/cjs/server/actions/getSessionId.cjs.map +1 -0
  48. package/dist/cjs/server/actions/getSessionPayload.cjs +29 -0
  49. package/dist/cjs/server/actions/getSessionPayload.cjs.map +1 -0
  50. package/dist/cjs/server/actions/getUserAction.cjs +30 -0
  51. package/dist/cjs/server/actions/getUserAction.cjs.map +1 -0
  52. package/dist/cjs/server/actions/getUserProfileAction.cjs +34 -0
  53. package/dist/cjs/server/actions/getUserProfileAction.cjs.map +1 -0
  54. package/dist/cjs/server/actions/handleOAuthCallbackAction.cjs +89 -0
  55. package/dist/cjs/server/actions/handleOAuthCallbackAction.cjs.map +1 -0
  56. package/dist/cjs/server/actions/isSignedIn.cjs +40 -0
  57. package/dist/cjs/server/actions/isSignedIn.cjs.map +1 -0
  58. package/dist/cjs/server/actions/refreshToken.cjs +61 -0
  59. package/dist/cjs/server/actions/refreshToken.cjs.map +1 -0
  60. package/dist/cjs/server/actions/signInAction.cjs +95 -0
  61. package/dist/cjs/server/actions/signInAction.cjs.map +1 -0
  62. package/dist/cjs/server/actions/signOutAction.cjs +57 -0
  63. package/dist/cjs/server/actions/signOutAction.cjs.map +1 -0
  64. package/dist/cjs/server/actions/signUpAction.cjs +27 -0
  65. package/dist/cjs/server/actions/signUpAction.cjs.map +1 -0
  66. package/dist/cjs/server/actions/updateUserProfileAction.cjs +30 -0
  67. package/dist/cjs/server/actions/updateUserProfileAction.cjs.map +1 -0
  68. package/dist/cjs/server/getClient.cjs +19 -0
  69. package/dist/cjs/server/getClient.cjs.map +1 -0
  70. package/dist/cjs/server/index.cjs +9 -0
  71. package/dist/cjs/server/proxy/createRouteMatcher.cjs +36 -0
  72. package/dist/cjs/server/proxy/createRouteMatcher.cjs.map +1 -0
  73. package/dist/cjs/server/proxy/thunderIDProxy.cjs +182 -0
  74. package/dist/cjs/server/proxy/thunderIDProxy.cjs.map +1 -0
  75. package/dist/cjs/server/thunderid.cjs +27 -0
  76. package/dist/cjs/server/thunderid.cjs.map +1 -0
  77. package/dist/cjs/utils/SessionManager.cjs +150 -0
  78. package/dist/cjs/utils/SessionManager.cjs.map +1 -0
  79. package/dist/cjs/utils/decorateConfigWithNextEnv.cjs +28 -0
  80. package/dist/cjs/utils/decorateConfigWithNextEnv.cjs.map +1 -0
  81. package/dist/cjs/utils/handleRefreshToken.cjs +62 -0
  82. package/dist/cjs/utils/handleRefreshToken.cjs.map +1 -0
  83. package/dist/cjs/utils/logger.cjs +11 -0
  84. package/dist/cjs/utils/logger.cjs.map +1 -0
  85. package/dist/cjs/utils/sessionUtils.cjs +40 -0
  86. package/dist/cjs/utils/sessionUtils.cjs.map +1 -0
  87. package/dist/client/components/actions/SignInButton/SignInButton.d.ts.map +1 -0
  88. package/dist/client/components/actions/SignInButton/SignInButton.js +73 -0
  89. package/dist/client/components/actions/SignInButton/SignInButton.js.map +1 -0
  90. package/dist/client/components/actions/SignOutButton/SignOutButton.d.ts.map +1 -0
  91. package/dist/client/components/actions/SignOutButton/SignOutButton.js +57 -0
  92. package/dist/client/components/actions/SignOutButton/SignOutButton.js.map +1 -0
  93. package/dist/client/components/actions/SignUpButton/SignUpButton.d.ts.map +1 -0
  94. package/dist/client/components/actions/SignUpButton/SignUpButton.js +85 -0
  95. package/dist/client/components/actions/SignUpButton/SignUpButton.js.map +1 -0
  96. package/dist/client/components/control/Loading/Loading.d.ts.map +1 -0
  97. package/dist/client/components/control/SignedIn/SignedIn.d.ts.map +1 -0
  98. package/dist/client/components/control/SignedIn/SignedIn.js +32 -0
  99. package/dist/client/components/control/SignedIn/SignedIn.js.map +1 -0
  100. package/dist/client/components/control/SignedOut/SignedOut.d.ts.map +1 -0
  101. package/dist/client/components/control/SignedOut/SignedOut.js +32 -0
  102. package/dist/client/components/control/SignedOut/SignedOut.js.map +1 -0
  103. package/dist/{types/client → client}/components/presentation/SignIn/SignIn.d.ts +0 -38
  104. package/dist/client/components/presentation/SignIn/SignIn.d.ts.map +1 -0
  105. package/dist/client/components/presentation/SignIn/SignIn.js +33 -0
  106. package/dist/client/components/presentation/SignIn/SignIn.js.map +1 -0
  107. package/dist/client/components/presentation/SignUp/SignUp.d.ts.map +1 -0
  108. package/dist/client/components/presentation/SignUp/SignUp.js +75 -0
  109. package/dist/client/components/presentation/SignUp/SignUp.js.map +1 -0
  110. package/dist/client/components/presentation/User/User.d.ts.map +1 -0
  111. package/dist/client/components/presentation/User/User.js +46 -0
  112. package/dist/client/components/presentation/User/User.js.map +1 -0
  113. package/dist/client/components/presentation/UserDropdown/UserDropdown.d.ts.map +1 -0
  114. package/dist/client/components/presentation/UserDropdown/UserDropdown.js +110 -0
  115. package/dist/client/components/presentation/UserDropdown/UserDropdown.js.map +1 -0
  116. package/dist/client/components/presentation/UserProfile/UserProfile.d.ts.map +1 -0
  117. package/dist/client/components/presentation/UserProfile/UserProfile.js +49 -0
  118. package/dist/client/components/presentation/UserProfile/UserProfile.js.map +1 -0
  119. package/dist/client/contexts/ThunderID/ThunderIDContext.d.ts.map +1 -0
  120. package/dist/client/contexts/ThunderID/ThunderIDContext.js +32 -0
  121. package/dist/client/contexts/ThunderID/ThunderIDContext.js.map +1 -0
  122. package/dist/{types/client → client}/contexts/ThunderID/ThunderIDProvider.d.ts +1 -8
  123. package/dist/client/contexts/ThunderID/ThunderIDProvider.d.ts.map +1 -0
  124. package/dist/client/contexts/ThunderID/ThunderIDProvider.js +159 -0
  125. package/dist/client/contexts/ThunderID/ThunderIDProvider.js.map +1 -0
  126. package/dist/client/contexts/ThunderID/useThunderID.d.ts.map +1 -0
  127. package/dist/client/contexts/ThunderID/useThunderID.js +17 -0
  128. package/dist/client/contexts/ThunderID/useThunderID.js.map +1 -0
  129. package/dist/{types/client → client}/index.d.ts +2 -10
  130. package/dist/client/index.d.ts.map +1 -0
  131. package/dist/client/index.js +13 -0
  132. package/dist/configs/InternalAuthAPIRoutesConfig.d.ts.map +1 -0
  133. package/dist/constants/sessionConstants.d.ts.map +1 -0
  134. package/dist/constants/sessionConstants.js +53 -0
  135. package/dist/constants/sessionConstants.js.map +1 -0
  136. package/dist/index.d.ts.map +1 -0
  137. package/dist/index.js +20 -981
  138. package/dist/models/api.d.ts.map +1 -0
  139. package/dist/models/config.d.ts.map +1 -0
  140. package/dist/server/ThunderIDProvider.d.ts.map +1 -0
  141. package/dist/server/ThunderIDProvider.js +111 -0
  142. package/dist/server/ThunderIDProvider.js.map +1 -0
  143. package/dist/server/actions/clearSession.d.ts.map +1 -0
  144. package/dist/server/actions/clearSession.js +39 -0
  145. package/dist/server/actions/clearSession.js.map +1 -0
  146. package/dist/server/actions/getAccessToken.d.ts.map +1 -0
  147. package/dist/{getAccessToken-DCP_zasP.js → server/actions/getAccessToken.js} +8 -5
  148. package/dist/server/actions/getAccessToken.js.map +1 -0
  149. package/dist/server/actions/getClientOrigin.d.ts.map +1 -0
  150. package/dist/server/actions/getClientOrigin.js +16 -0
  151. package/dist/server/actions/getClientOrigin.js.map +1 -0
  152. package/dist/server/actions/getSessionId.d.ts.map +1 -0
  153. package/dist/{getSessionId-Ctmvpfgp.js → server/actions/getSessionId.js} +8 -5
  154. package/dist/server/actions/getSessionId.js.map +1 -0
  155. package/dist/server/actions/getSessionPayload.d.ts.map +1 -0
  156. package/dist/server/actions/getSessionPayload.js +27 -0
  157. package/dist/server/actions/getSessionPayload.js.map +1 -0
  158. package/dist/server/actions/getUserAction.d.ts.map +1 -0
  159. package/dist/server/actions/getUserAction.js +30 -0
  160. package/dist/server/actions/getUserAction.js.map +1 -0
  161. package/dist/server/actions/getUserProfileAction.d.ts.map +1 -0
  162. package/dist/server/actions/getUserProfileAction.js +34 -0
  163. package/dist/server/actions/getUserProfileAction.js.map +1 -0
  164. package/dist/server/actions/handleOAuthCallbackAction.d.ts.map +1 -0
  165. package/dist/server/actions/handleOAuthCallbackAction.js +87 -0
  166. package/dist/server/actions/handleOAuthCallbackAction.js.map +1 -0
  167. package/dist/server/actions/isSignedIn.d.ts.map +1 -0
  168. package/dist/server/actions/isSignedIn.js +40 -0
  169. package/dist/server/actions/isSignedIn.js.map +1 -0
  170. package/dist/server/actions/refreshToken.d.ts.map +1 -0
  171. package/dist/server/actions/refreshToken.js +58 -0
  172. package/dist/server/actions/refreshToken.js.map +1 -0
  173. package/dist/{types/server → server}/actions/signInAction.d.ts +3 -3
  174. package/dist/server/actions/signInAction.d.ts.map +1 -0
  175. package/dist/server/actions/signInAction.js +92 -0
  176. package/dist/server/actions/signInAction.js.map +1 -0
  177. package/dist/server/actions/signOutAction.d.ts.map +1 -0
  178. package/dist/server/actions/signOutAction.js +55 -0
  179. package/dist/server/actions/signOutAction.js.map +1 -0
  180. package/dist/{types/server/actions/getMyOrganizations.d.ts → server/actions/signUpAction.d.ts} +10 -5
  181. package/dist/server/actions/signUpAction.d.ts.map +1 -0
  182. package/dist/server/actions/signUpAction.js +27 -0
  183. package/dist/server/actions/signUpAction.js.map +1 -0
  184. package/dist/server/actions/updateUserProfileAction.d.ts.map +1 -0
  185. package/dist/server/actions/updateUserProfileAction.js +30 -0
  186. package/dist/server/actions/updateUserProfileAction.js.map +1 -0
  187. package/dist/server/getClient.d.ts.map +1 -0
  188. package/dist/server/getClient.js +19 -0
  189. package/dist/server/getClient.js.map +1 -0
  190. package/dist/{types/server → server}/index.d.ts +3 -0
  191. package/dist/server/index.d.ts.map +1 -0
  192. package/dist/server/index.js +6 -0
  193. package/dist/server/proxy/createRouteMatcher.d.ts.map +1 -0
  194. package/dist/server/proxy/createRouteMatcher.js +35 -0
  195. package/dist/server/proxy/createRouteMatcher.js.map +1 -0
  196. package/dist/{types/server/middleware/thunderIDMiddleware.d.ts → server/proxy/thunderIDProxy.d.ts} +13 -13
  197. package/dist/server/proxy/thunderIDProxy.d.ts.map +1 -0
  198. package/dist/server/proxy/thunderIDProxy.js +180 -0
  199. package/dist/server/proxy/thunderIDProxy.js.map +1 -0
  200. package/dist/server/thunderid.d.ts.map +1 -0
  201. package/dist/server/thunderid.js +27 -0
  202. package/dist/server/thunderid.js.map +1 -0
  203. package/dist/utils/SessionManager.d.ts.map +1 -0
  204. package/dist/utils/SessionManager.js +147 -0
  205. package/dist/utils/SessionManager.js.map +1 -0
  206. package/dist/utils/createRouteMatcher.d.ts.map +1 -0
  207. package/dist/utils/decorateConfigWithNextEnv.d.ts.map +1 -0
  208. package/dist/utils/decorateConfigWithNextEnv.js +27 -0
  209. package/dist/utils/decorateConfigWithNextEnv.js.map +1 -0
  210. package/dist/utils/handleRefreshToken.d.ts.map +1 -0
  211. package/dist/utils/handleRefreshToken.js +62 -0
  212. package/dist/utils/handleRefreshToken.js.map +1 -0
  213. package/dist/utils/logger.d.ts.map +1 -0
  214. package/dist/utils/logger.js +9 -0
  215. package/dist/utils/logger.js.map +1 -0
  216. package/dist/utils/sessionUtils.d.ts.map +1 -0
  217. package/dist/utils/sessionUtils.js +39 -0
  218. package/dist/utils/sessionUtils.js.map +1 -0
  219. package/package.json +12 -22
  220. package/dist/SessionManager-BPpyyzfa.js +0 -1384
  221. package/dist/cache-B9tFVOO5.js +0 -8047
  222. package/dist/cjs/SessionManager-SBxwYnwV.js +0 -1397
  223. package/dist/cjs/cache-0QwhuLuy.js +0 -8050
  224. package/dist/cjs/dynamic-rendering-W7rdgerZ.js +0 -1540
  225. package/dist/cjs/getAccessToken-EiHUciAb.js +0 -22
  226. package/dist/cjs/getSessionId-BUDHvxX2.js +0 -5
  227. package/dist/cjs/getSessionId-Do242Vmz.js +0 -28
  228. package/dist/cjs/index2.cjs +0 -8
  229. package/dist/cjs/middleware.cjs +0 -5151
  230. package/dist/cjs/segment-CPZPzHDj.js +0 -52
  231. package/dist/cjs/server-BAGHs6kk.js +0 -2468
  232. package/dist/dynamic-rendering-CkPpk5pF.js +0 -1441
  233. package/dist/getSessionId-pG-rZbaH.js +0 -5
  234. package/dist/index2.js +0 -7
  235. package/dist/middleware.js +0 -5152
  236. package/dist/segment-D3vdYYI5.js +0 -47
  237. package/dist/server-Bn2BrWaL.js +0 -2418
  238. package/dist/types/ThunderIDNextClient.d.ts.map +0 -1
  239. package/dist/types/client/components/actions/SignInButton/SignInButton.d.ts.map +0 -1
  240. package/dist/types/client/components/actions/SignOutButton/SignOutButton.d.ts.map +0 -1
  241. package/dist/types/client/components/actions/SignUpButton/SignUpButton.d.ts.map +0 -1
  242. package/dist/types/client/components/control/Loading/Loading.d.ts.map +0 -1
  243. package/dist/types/client/components/control/SignedIn/SignedIn.d.ts.map +0 -1
  244. package/dist/types/client/components/control/SignedOut/SignedOut.d.ts.map +0 -1
  245. package/dist/types/client/components/presentation/CreateOrganization/CreateOrganization.d.ts +0 -68
  246. package/dist/types/client/components/presentation/CreateOrganization/CreateOrganization.d.ts.map +0 -1
  247. package/dist/types/client/components/presentation/Organization/Organization.d.ts +0 -67
  248. package/dist/types/client/components/presentation/Organization/Organization.d.ts.map +0 -1
  249. package/dist/types/client/components/presentation/OrganizationList/OrganizationList.d.ts +0 -93
  250. package/dist/types/client/components/presentation/OrganizationList/OrganizationList.d.ts.map +0 -1
  251. package/dist/types/client/components/presentation/OrganizationProfile/OrganizationProfile.d.ts +0 -120
  252. package/dist/types/client/components/presentation/OrganizationProfile/OrganizationProfile.d.ts.map +0 -1
  253. package/dist/types/client/components/presentation/OrganizationSwitcher/OrganizationSwitcher.d.ts +0 -72
  254. package/dist/types/client/components/presentation/OrganizationSwitcher/OrganizationSwitcher.d.ts.map +0 -1
  255. package/dist/types/client/components/presentation/SignIn/SignIn.d.ts.map +0 -1
  256. package/dist/types/client/components/presentation/SignUp/SignUp.d.ts.map +0 -1
  257. package/dist/types/client/components/presentation/User/User.d.ts.map +0 -1
  258. package/dist/types/client/components/presentation/UserDropdown/UserDropdown.d.ts.map +0 -1
  259. package/dist/types/client/components/presentation/UserProfile/UserProfile.d.ts.map +0 -1
  260. package/dist/types/client/contexts/ThunderID/ThunderIDContext.d.ts.map +0 -1
  261. package/dist/types/client/contexts/ThunderID/ThunderIDProvider.d.ts.map +0 -1
  262. package/dist/types/client/contexts/ThunderID/useThunderID.d.ts.map +0 -1
  263. package/dist/types/client/index.d.ts.map +0 -1
  264. package/dist/types/configs/InternalAuthAPIRoutesConfig.d.ts.map +0 -1
  265. package/dist/types/constants/sessionConstants.d.ts.map +0 -1
  266. package/dist/types/index.d.ts.map +0 -1
  267. package/dist/types/middleware.d.ts +0 -35
  268. package/dist/types/middleware.d.ts.map +0 -1
  269. package/dist/types/models/api.d.ts.map +0 -1
  270. package/dist/types/models/config.d.ts.map +0 -1
  271. package/dist/types/server/ThunderIDProvider.d.ts.map +0 -1
  272. package/dist/types/server/actions/clearSession.d.ts.map +0 -1
  273. package/dist/types/server/actions/createOrganization.d.ts +0 -24
  274. package/dist/types/server/actions/createOrganization.d.ts.map +0 -1
  275. package/dist/types/server/actions/getAccessToken.d.ts.map +0 -1
  276. package/dist/types/server/actions/getAllOrganizations.d.ts +0 -24
  277. package/dist/types/server/actions/getAllOrganizations.d.ts.map +0 -1
  278. package/dist/types/server/actions/getBrandingPreference.d.ts +0 -24
  279. package/dist/types/server/actions/getBrandingPreference.d.ts.map +0 -1
  280. package/dist/types/server/actions/getClientOrigin.d.ts.map +0 -1
  281. package/dist/types/server/actions/getCurrentOrganizationAction.d.ts +0 -31
  282. package/dist/types/server/actions/getCurrentOrganizationAction.d.ts.map +0 -1
  283. package/dist/types/server/actions/getMyOrganizations.d.ts.map +0 -1
  284. package/dist/types/server/actions/getOrganizationAction.d.ts +0 -31
  285. package/dist/types/server/actions/getOrganizationAction.d.ts.map +0 -1
  286. package/dist/types/server/actions/getSessionId.d.ts.map +0 -1
  287. package/dist/types/server/actions/getSessionPayload.d.ts.map +0 -1
  288. package/dist/types/server/actions/getUserAction.d.ts.map +0 -1
  289. package/dist/types/server/actions/getUserProfileAction.d.ts.map +0 -1
  290. package/dist/types/server/actions/handleOAuthCallbackAction.d.ts.map +0 -1
  291. package/dist/types/server/actions/isSignedIn.d.ts.map +0 -1
  292. package/dist/types/server/actions/refreshToken.d.ts.map +0 -1
  293. package/dist/types/server/actions/signInAction.d.ts.map +0 -1
  294. package/dist/types/server/actions/signOutAction.d.ts.map +0 -1
  295. package/dist/types/server/actions/signUpAction.d.ts +0 -36
  296. package/dist/types/server/actions/signUpAction.d.ts.map +0 -1
  297. package/dist/types/server/actions/switchOrganization.d.ts +0 -24
  298. package/dist/types/server/actions/switchOrganization.d.ts.map +0 -1
  299. package/dist/types/server/actions/updateUserProfileAction.d.ts.map +0 -1
  300. package/dist/types/server/getClient.d.ts.map +0 -1
  301. package/dist/types/server/index.d.ts.map +0 -1
  302. package/dist/types/server/middleware/createRouteMatcher.d.ts.map +0 -1
  303. package/dist/types/server/middleware/thunderIDMiddleware.d.ts.map +0 -1
  304. package/dist/types/server/thunderid.d.ts.map +0 -1
  305. package/dist/types/utils/SessionManager.d.ts.map +0 -1
  306. package/dist/types/utils/createRouteMatcher.d.ts.map +0 -1
  307. package/dist/types/utils/decorateConfigWithNextEnv.d.ts.map +0 -1
  308. package/dist/types/utils/handleRefreshToken.d.ts.map +0 -1
  309. package/dist/types/utils/logger.d.ts.map +0 -1
  310. package/dist/types/utils/sessionUtils.d.ts.map +0 -1
  311. /package/dist/{types/client → client}/components/actions/SignInButton/SignInButton.d.ts +0 -0
  312. /package/dist/{types/client → client}/components/actions/SignOutButton/SignOutButton.d.ts +0 -0
  313. /package/dist/{types/client → client}/components/actions/SignUpButton/SignUpButton.d.ts +0 -0
  314. /package/dist/{types/client → client}/components/control/Loading/Loading.d.ts +0 -0
  315. /package/dist/{types/client → client}/components/control/SignedIn/SignedIn.d.ts +0 -0
  316. /package/dist/{types/client → client}/components/control/SignedOut/SignedOut.d.ts +0 -0
  317. /package/dist/{types/client → client}/components/presentation/SignUp/SignUp.d.ts +0 -0
  318. /package/dist/{types/client → client}/components/presentation/User/User.d.ts +0 -0
  319. /package/dist/{types/client → client}/components/presentation/UserDropdown/UserDropdown.d.ts +0 -0
  320. /package/dist/{types/client → client}/components/presentation/UserProfile/UserProfile.d.ts +0 -0
  321. /package/dist/{types/client → client}/contexts/ThunderID/ThunderIDContext.d.ts +0 -0
  322. /package/dist/{types/client → client}/contexts/ThunderID/useThunderID.d.ts +0 -0
  323. /package/dist/{types/configs → configs}/InternalAuthAPIRoutesConfig.d.ts +0 -0
  324. /package/dist/{types/constants → constants}/sessionConstants.d.ts +0 -0
  325. /package/dist/{types/index.d.ts → index.d.ts} +0 -0
  326. /package/dist/{types/models → models}/api.d.ts +0 -0
  327. /package/dist/{types/models → models}/config.d.ts +0 -0
  328. /package/dist/{types/server → server}/ThunderIDProvider.d.ts +0 -0
  329. /package/dist/{types/server → server}/actions/clearSession.d.ts +0 -0
  330. /package/dist/{types/server → server}/actions/getAccessToken.d.ts +0 -0
  331. /package/dist/{types/server → server}/actions/getClientOrigin.d.ts +0 -0
  332. /package/dist/{types/server → server}/actions/getSessionId.d.ts +0 -0
  333. /package/dist/{types/server → server}/actions/getSessionPayload.d.ts +0 -0
  334. /package/dist/{types/server → server}/actions/getUserAction.d.ts +0 -0
  335. /package/dist/{types/server → server}/actions/getUserProfileAction.d.ts +0 -0
  336. /package/dist/{types/server → server}/actions/handleOAuthCallbackAction.d.ts +0 -0
  337. /package/dist/{types/server → server}/actions/isSignedIn.d.ts +0 -0
  338. /package/dist/{types/server → server}/actions/refreshToken.d.ts +0 -0
  339. /package/dist/{types/server → server}/actions/signOutAction.d.ts +0 -0
  340. /package/dist/{types/server → server}/actions/updateUserProfileAction.d.ts +0 -0
  341. /package/dist/{types/server → server}/getClient.d.ts +0 -0
  342. /package/dist/{types/server/middleware → server/proxy}/createRouteMatcher.d.ts +0 -0
  343. /package/dist/{types/server → server}/thunderid.d.ts +0 -0
  344. /package/dist/{types/utils → utils}/SessionManager.d.ts +0 -0
  345. /package/dist/{types/utils → utils}/createRouteMatcher.d.ts +0 -0
  346. /package/dist/{types/utils → utils}/decorateConfigWithNextEnv.d.ts +0 -0
  347. /package/dist/{types/utils → utils}/handleRefreshToken.d.ts +0 -0
  348. /package/dist/{types/utils → utils}/logger.d.ts +0 -0
  349. /package/dist/{types/utils → utils}/sessionUtils.d.ts +0 -0
@@ -0,0 +1,180 @@
1
+ import { REFRESH_BUFFER_SECONDS } from "../../constants/sessionConstants.js";
2
+ import SessionManager_default from "../../utils/SessionManager.js";
3
+ import decorateConfigWithNextEnv_default from "../../utils/decorateConfigWithNextEnv.js";
4
+ import handleRefreshToken_default from "../../utils/handleRefreshToken.js";
5
+ import { getSessionFromRequest, getSessionIdFromRequest } from "../../utils/sessionUtils.js";
6
+ import { NextResponse } from "next/server";
7
+
8
+ //#region src/server/proxy/thunderIDProxy.ts
9
+ /**
10
+ * Removes a named cookie from a raw Cookie header string.
11
+ */
12
+ const removeCookieFromHeader = (cookieHeader, name) => cookieHeader.split(";").map((p) => p.trim()).filter((p) => {
13
+ const eqIdx = p.indexOf("=");
14
+ return (eqIdx === -1 ? p : p.slice(0, eqIdx).trim()) !== name;
15
+ }).join("; ");
16
+ /**
17
+ * Replaces the value of a named cookie inside a raw Cookie header string.
18
+ * If the cookie does not already appear in the header it is appended.
19
+ */
20
+ const replaceCookieInHeader = (cookieHeader, name, value) => {
21
+ const parts = cookieHeader.split(";").map((p) => p.trim()).filter(Boolean);
22
+ let found = false;
23
+ const updated = parts.map((part) => {
24
+ const eqIdx = part.indexOf("=");
25
+ if ((eqIdx === -1 ? part : part.slice(0, eqIdx).trim()) === name) {
26
+ found = true;
27
+ return `${name}=${value}`;
28
+ }
29
+ return part;
30
+ });
31
+ if (!found) updated.push(`${name}=${value}`);
32
+ return updated.join("; ");
33
+ };
34
+ /**
35
+ * ThunderID proxy that integrates authentication into your Next.js application.
36
+ * Similar to Clerk's clerkMiddleware pattern.
37
+ *
38
+ * Proactively refreshes the access token when it is within REFRESH_BUFFER_SECONDS of
39
+ * expiry so that Server Components always receive a fresh session. The refresh also
40
+ * recovers expired tokens as long as a refresh token is present.
41
+ *
42
+ * The updated session cookie is written to:
43
+ * - The response → browser stores the new cookie for subsequent requests.
44
+ * - The forwarded request headers → the same-request Server Component render sees
45
+ * the fresh token immediately without waiting for the next navigation.
46
+ *
47
+ * Token refresh requires baseUrl, clientId, and clientSecret. These are resolved from
48
+ * the options argument first, then from the standard ThunderID environment variables
49
+ * (NEXT_PUBLIC_THUNDERID_BASE_URL, NEXT_PUBLIC_THUNDERID_CLIENT_ID,
50
+ * THUNDERID_CLIENT_SECRET). If none are available the refresh step is skipped silently.
51
+ *
52
+ * @param handler - Optional handler function to customize proxy behavior
53
+ * @param options - Configuration options for the proxy
54
+ * @returns Next.js middleware function
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * // middleware.ts - Basic usage (config read from env vars automatically)
59
+ * import { thunderIDProxy } from '@thunderid/nextjs/server';
60
+ *
61
+ * export default thunderIDProxy();
62
+ *
63
+ * export const config = {
64
+ * matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
65
+ * };
66
+ * ```
67
+ *
68
+ * @example
69
+ * ```typescript
70
+ * // With route protection
71
+ * import { thunderIDProxy, createRouteMatcher } from '@thunderid/nextjs/server';
72
+ *
73
+ * const isProtectedRoute = createRouteMatcher(['/dashboard(.*)']);
74
+ *
75
+ * export default thunderIDProxy(async (thunderid, req) => {
76
+ * if (isProtectedRoute(req)) {
77
+ * await thunderid.protectRoute();
78
+ * }
79
+ * });
80
+ * ```
81
+ */
82
+ const thunderIDProxy = (handler, options) => async (request) => {
83
+ const resolvedConfig = decorateConfigWithNextEnv_default(typeof options === "function" ? options(request) : options || {});
84
+ const url = new URL(request.url);
85
+ const hasCallbackParams = url.searchParams.has("code") && url.searchParams.has("state");
86
+ let isValidOAuthCallback = false;
87
+ if (hasCallbackParams && !url.searchParams.has("error")) {
88
+ const tempSessionToken = request.cookies.get(SessionManager_default.getTempSessionCookieName())?.value;
89
+ if (tempSessionToken) try {
90
+ await SessionManager_default.verifyTempSession(tempSessionToken);
91
+ isValidOAuthCallback = true;
92
+ } catch {
93
+ isValidOAuthCallback = false;
94
+ }
95
+ }
96
+ const verifiedSession = await getSessionFromRequest(request);
97
+ let expiredSession;
98
+ if (!verifiedSession) {
99
+ const rawToken = request.cookies.get(SessionManager_default.getSessionCookieName())?.value;
100
+ if (rawToken) try {
101
+ const decoded = await SessionManager_default.verifySessionTokenForRefresh(rawToken);
102
+ if (decoded.refreshToken) expiredSession = decoded;
103
+ } catch {}
104
+ }
105
+ const now = Math.floor(Date.now() / 1e3);
106
+ const candidateSession = verifiedSession ?? expiredSession;
107
+ const hasRefreshConfig = !!(resolvedConfig.baseUrl && resolvedConfig.clientId && resolvedConfig.clientSecret);
108
+ const needsRefresh = !isValidOAuthCallback && hasRefreshConfig && !!candidateSession?.refreshToken && (!!verifiedSession && verifiedSession.exp <= now + REFRESH_BUFFER_SECONDS || !!expiredSession);
109
+ let activeSession = verifiedSession;
110
+ let refreshCookieUpdate;
111
+ if (needsRefresh && candidateSession) try {
112
+ const { newSessionToken, sessionCookieExpiryTime } = await handleRefreshToken_default(candidateSession, {
113
+ baseUrl: resolvedConfig.baseUrl,
114
+ clientId: resolvedConfig.clientId,
115
+ clientSecret: resolvedConfig.clientSecret,
116
+ sessionCookie: resolvedConfig.sessionCookie
117
+ });
118
+ activeSession = await SessionManager_default.verifySessionToken(newSessionToken);
119
+ refreshCookieUpdate = {
120
+ expiry: sessionCookieExpiryTime,
121
+ token: newSessionToken
122
+ };
123
+ } catch {
124
+ activeSession = void 0;
125
+ }
126
+ const rawSessionCookie = request.cookies.get(SessionManager_default.getSessionCookieName())?.value;
127
+ let shouldClearCookie = false;
128
+ if (!isValidOAuthCallback && rawSessionCookie && !activeSession && !refreshCookieUpdate) shouldClearCookie = true;
129
+ const sessionId = activeSession?.sessionId ?? await getSessionIdFromRequest(request);
130
+ const isAuthenticated = !!activeSession;
131
+ const handlerResponse = handler ? await handler({
132
+ getSession: async () => activeSession,
133
+ getSessionId: () => sessionId,
134
+ isSignedIn: () => isAuthenticated,
135
+ protectRoute: async (routeOptions) => {
136
+ if (isValidOAuthCallback) return;
137
+ if (!isAuthenticated) {
138
+ const referer = request.headers.get("referer");
139
+ let fallbackRedirect = "/";
140
+ if (referer) try {
141
+ const refererUrl = new URL(referer);
142
+ const requestUrl = new URL(request.url);
143
+ if (refererUrl.origin === requestUrl.origin) fallbackRedirect = refererUrl.pathname + refererUrl.search;
144
+ } catch {}
145
+ const redirectUrl = routeOptions?.redirect ?? resolvedConfig.signInUrl ?? fallbackRedirect;
146
+ return NextResponse.redirect(new URL(redirectUrl, request.url));
147
+ }
148
+ }
149
+ }, request) : void 0;
150
+ if (shouldClearCookie) {
151
+ const cookieName$1 = SessionManager_default.getSessionCookieName();
152
+ if (handlerResponse) {
153
+ handlerResponse.cookies.delete(cookieName$1);
154
+ return handlerResponse;
155
+ }
156
+ const requestHeaders$1 = new Headers(request.headers);
157
+ requestHeaders$1.set("cookie", removeCookieFromHeader(request.headers.get("cookie") ?? "", cookieName$1));
158
+ const cleanResponse = NextResponse.next({ request: { headers: requestHeaders$1 } });
159
+ cleanResponse.cookies.delete(cookieName$1);
160
+ return cleanResponse;
161
+ }
162
+ if (!refreshCookieUpdate) return handlerResponse ?? NextResponse.next();
163
+ const cookieName = SessionManager_default.getSessionCookieName();
164
+ const cookieOptions = SessionManager_default.getSessionCookieOptions(refreshCookieUpdate.expiry);
165
+ if (handlerResponse) {
166
+ handlerResponse.cookies.set(cookieName, refreshCookieUpdate.token, cookieOptions);
167
+ return handlerResponse;
168
+ }
169
+ const requestHeaders = new Headers(request.headers);
170
+ const updatedCookieHeader = replaceCookieInHeader(request.headers.get("cookie") ?? "", cookieName, refreshCookieUpdate.token);
171
+ requestHeaders.set("cookie", updatedCookieHeader);
172
+ const response = NextResponse.next({ request: { headers: requestHeaders } });
173
+ response.cookies.set(cookieName, refreshCookieUpdate.token, cookieOptions);
174
+ return response;
175
+ };
176
+ var thunderIDProxy_default = thunderIDProxy;
177
+
178
+ //#endregion
179
+ export { thunderIDProxy_default as default };
180
+ //# sourceMappingURL=thunderIDProxy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"thunderIDProxy.js","names":["eqIdx: number","parts: string[]","updated: string[]","resolvedConfig: ThunderIDNextConfig","decorateConfigWithNextEnv","url: URL","hasCallbackParams: boolean","tempSessionToken: string | undefined","SessionManager","verifiedSession: SessionTokenPayload | undefined","expiredSession: SessionTokenPayload | undefined","rawToken: string | undefined","decoded: SessionTokenPayload","now: number","candidateSession: SessionTokenPayload | undefined","needsRefresh: boolean","activeSession: SessionTokenPayload | undefined","refreshCookieUpdate: {expiry: number; token: string} | undefined","handleRefreshToken","rawSessionCookie: string | undefined","sessionId: string | undefined","handlerResponse: NextResponse | void","referer: string | null","refererUrl: URL","requestUrl: URL","redirectUrl: string","cookieName: string","cookieName","requestHeaders: Headers","cleanResponse: NextResponse","requestHeaders","cookieOptions: ReturnType<typeof SessionManager.getSessionCookieOptions>","updatedCookieHeader: string","response: NextResponse"],"sources":["../../../src/server/proxy/thunderIDProxy.ts"],"sourcesContent":["/**\n * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport {NextRequest, NextResponse} from 'next/server';\nimport {REFRESH_BUFFER_SECONDS} from '../../constants/sessionConstants';\nimport {ThunderIDNextConfig} from '../../models/config';\nimport decorateConfigWithNextEnv from '../../utils/decorateConfigWithNextEnv';\nimport handleRefreshToken from '../../utils/handleRefreshToken';\nimport SessionManager, {SessionTokenPayload} from '../../utils/SessionManager';\nimport {getSessionFromRequest, getSessionIdFromRequest} from '../../utils/sessionUtils';\n\nexport type ThunderIDProxyOptions = Partial<ThunderIDNextConfig>;\n\nexport interface ThunderIDProxyContext {\n /** Get the session payload from JWT session if available */\n getSession: () => Promise<SessionTokenPayload | undefined>;\n /** Get the session ID from the current request */\n getSessionId: () => string | undefined;\n /** Check if the current request has a valid ThunderID session */\n isSignedIn: () => boolean;\n /**\n * Protect a route by redirecting unauthenticated users.\n * Redirect URL fallback order:\n * 1. options.redirect\n * 2. resolvedOptions.signInUrl\n * 3. resolvedOptions.defaultRedirect\n * 4. referer (if from same origin)\n * If none are available, falls back to '/'.\n */\n protectRoute: (routeOptions?: {redirect?: string}) => Promise<NextResponse | void>;\n}\n\ntype ThunderIDProxyHandler = (\n thunderid: ThunderIDProxyContext,\n req: NextRequest,\n) => Promise<NextResponse | void> | NextResponse | void;\n\n/**\n * Removes a named cookie from a raw Cookie header string.\n */\nconst removeCookieFromHeader = (cookieHeader: string, name: string): string =>\n cookieHeader\n .split(';')\n .map((p: string) => p.trim())\n .filter((p: string) => {\n const eqIdx: number = p.indexOf('=');\n const partName: string = eqIdx === -1 ? p : p.slice(0, eqIdx).trim();\n return partName !== name;\n })\n .join('; ');\n\n/**\n * Replaces the value of a named cookie inside a raw Cookie header string.\n * If the cookie does not already appear in the header it is appended.\n */\nconst replaceCookieInHeader = (cookieHeader: string, name: string, value: string): string => {\n const parts: string[] = cookieHeader\n .split(';')\n .map((p: string) => p.trim())\n .filter(Boolean);\n\n let found = false;\n const updated: string[] = parts.map((part: string) => {\n const eqIdx: number = part.indexOf('=');\n const partName: string = eqIdx === -1 ? part : part.slice(0, eqIdx).trim();\n if (partName === name) {\n found = true;\n return `${name}=${value}`;\n }\n return part;\n });\n\n if (!found) {\n updated.push(`${name}=${value}`);\n }\n\n return updated.join('; ');\n};\n\n/**\n * ThunderID proxy that integrates authentication into your Next.js application.\n * Similar to Clerk's clerkMiddleware pattern.\n *\n * Proactively refreshes the access token when it is within REFRESH_BUFFER_SECONDS of\n * expiry so that Server Components always receive a fresh session. The refresh also\n * recovers expired tokens as long as a refresh token is present.\n *\n * The updated session cookie is written to:\n * - The response → browser stores the new cookie for subsequent requests.\n * - The forwarded request headers → the same-request Server Component render sees\n * the fresh token immediately without waiting for the next navigation.\n *\n * Token refresh requires baseUrl, clientId, and clientSecret. These are resolved from\n * the options argument first, then from the standard ThunderID environment variables\n * (NEXT_PUBLIC_THUNDERID_BASE_URL, NEXT_PUBLIC_THUNDERID_CLIENT_ID,\n * THUNDERID_CLIENT_SECRET). If none are available the refresh step is skipped silently.\n *\n * @param handler - Optional handler function to customize proxy behavior\n * @param options - Configuration options for the proxy\n * @returns Next.js middleware function\n *\n * @example\n * ```typescript\n * // middleware.ts - Basic usage (config read from env vars automatically)\n * import { thunderIDProxy } from '@thunderid/nextjs/server';\n *\n * export default thunderIDProxy();\n *\n * export const config = {\n * matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],\n * };\n * ```\n *\n * @example\n * ```typescript\n * // With route protection\n * import { thunderIDProxy, createRouteMatcher } from '@thunderid/nextjs/server';\n *\n * const isProtectedRoute = createRouteMatcher(['/dashboard(.*)']);\n *\n * export default thunderIDProxy(async (thunderid, req) => {\n * if (isProtectedRoute(req)) {\n * await thunderid.protectRoute();\n * }\n * });\n * ```\n */\nconst thunderIDProxy =\n (\n handler?: ThunderIDProxyHandler,\n options?: ThunderIDProxyOptions | ((req: NextRequest) => ThunderIDProxyOptions),\n ): ((request: NextRequest) => Promise<NextResponse>) =>\n async (request: NextRequest): Promise<NextResponse> => {\n const resolvedOptions: ThunderIDProxyOptions = typeof options === 'function' ? options(request) : options || {};\n\n // Resolve full config from passed options + environment variable fallbacks.\n const resolvedConfig: ThunderIDNextConfig = decorateConfigWithNextEnv(resolvedOptions as ThunderIDNextConfig);\n\n // ── OAuth callback detection ──────────────────────────────────────────────\n const url: URL = new URL(request.url);\n const hasCallbackParams: boolean = url.searchParams.has('code') && url.searchParams.has('state');\n\n let isValidOAuthCallback = false;\n if (hasCallbackParams && !url.searchParams.has('error')) {\n const tempSessionToken: string | undefined = request.cookies.get(\n SessionManager.getTempSessionCookieName(),\n )?.value;\n if (tempSessionToken) {\n try {\n await SessionManager.verifyTempSession(tempSessionToken);\n isValidOAuthCallback = true;\n } catch {\n isValidOAuthCallback = false;\n }\n }\n }\n\n // ── Session resolution ────────────────────────────────────────────────────\n // Step 1: Attempt to get a fully verified (signature + expiry) session.\n const verifiedSession: SessionTokenPayload | undefined = await getSessionFromRequest(request);\n\n // Step 2: If no verified session exists, verify the raw cookie's signature\n // without enforcing expiry. This allows the proxy to recover from an\n // expired access token as long as the JWT is authentic and a refresh token\n // is present. Skipping the signature check here would let a tampered cookie\n // drive identity-confusion attacks since handleRefreshToken reuses `sub`,\n // `sessionId`, and `organizationId` from the input payload when minting the\n // new session JWT.\n let expiredSession: SessionTokenPayload | undefined;\n if (!verifiedSession) {\n const rawToken: string | undefined = request.cookies.get(SessionManager.getSessionCookieName())?.value;\n if (rawToken) {\n try {\n const decoded: SessionTokenPayload = await SessionManager.verifySessionTokenForRefresh(rawToken);\n if (decoded.refreshToken) {\n expiredSession = decoded;\n }\n } catch {\n // Forged, tampered, wrong type, or malformed — ignore.\n }\n }\n }\n\n // ── Token refresh ─────────────────────────────────────────────────────────\n const now: number = Math.floor(Date.now() / 1000);\n const candidateSession: SessionTokenPayload | undefined = verifiedSession ?? expiredSession;\n\n // Config is required to call the token endpoint.\n const hasRefreshConfig = !!(resolvedConfig.baseUrl && resolvedConfig.clientId && resolvedConfig.clientSecret);\n\n // Refresh when:\n // a) Token is verified but within the proactive buffer window, OR\n // b) Token has already expired but a refresh token is available.\n const needsRefresh: boolean =\n !isValidOAuthCallback &&\n hasRefreshConfig &&\n !!candidateSession?.refreshToken &&\n ((!!verifiedSession && verifiedSession.exp <= now + REFRESH_BUFFER_SECONDS) || !!expiredSession);\n\n let activeSession: SessionTokenPayload | undefined = verifiedSession;\n let refreshCookieUpdate: {expiry: number; token: string} | undefined;\n\n if (needsRefresh && candidateSession) {\n try {\n const {newSessionToken, sessionCookieExpiryTime} = await handleRefreshToken(candidateSession, {\n baseUrl: resolvedConfig.baseUrl!,\n clientId: resolvedConfig.clientId!,\n clientSecret: resolvedConfig.clientSecret!,\n sessionCookie: resolvedConfig.sessionCookie,\n });\n // Verify the newly minted token so activeSession reflects fresh claims.\n activeSession = await SessionManager.verifySessionToken(newSessionToken);\n refreshCookieUpdate = {expiry: sessionCookieExpiryTime, token: newSessionToken};\n } catch {\n // Refresh failed — clear the irrecoverable session.\n activeSession = undefined;\n }\n }\n\n // ── Session cleanup detection ─────────────────────────────────────────────\n // Mark stale cookies for deletion when the session is irrecoverable. Skipped\n // during OAuth callbacks where a session cookie may not exist yet.\n const rawSessionCookie: string | undefined = request.cookies.get(SessionManager.getSessionCookieName())?.value;\n\n let shouldClearCookie = false;\n\n if (!isValidOAuthCallback && rawSessionCookie && !activeSession && !refreshCookieUpdate) {\n // A cookie was present but all resolution paths (verify, decode, refresh)\n // failed — the session is dead and cannot be recovered.\n shouldClearCookie = true;\n }\n\n const sessionId: string | undefined = activeSession?.sessionId ?? (await getSessionIdFromRequest(request));\n const isAuthenticated = !!activeSession;\n\n // ── Proxy context ─────────────────────────────────────────────────────────\n const thunderid: ThunderIDProxyContext = {\n getSession: async (): Promise<SessionTokenPayload | undefined> => activeSession,\n getSessionId: (): string | undefined => sessionId,\n isSignedIn: (): boolean => isAuthenticated,\n protectRoute: async (routeOptions?: {redirect?: string}): Promise<NextResponse | void> => {\n // Skip during a valid OAuth callback to avoid redirecting before the\n // callback action has had a chance to complete.\n if (isValidOAuthCallback) {\n return undefined;\n }\n\n if (!isAuthenticated) {\n const referer: string | null = request.headers.get('referer');\n let fallbackRedirect = '/';\n\n if (referer) {\n try {\n const refererUrl: URL = new URL(referer);\n const requestUrl: URL = new URL(request.url);\n if (refererUrl.origin === requestUrl.origin) {\n fallbackRedirect = refererUrl.pathname + refererUrl.search;\n }\n } catch {\n // Invalid referer — ignore.\n }\n }\n\n const redirectUrl: string = routeOptions?.redirect ?? resolvedConfig.signInUrl! ?? fallbackRedirect;\n\n return NextResponse.redirect(new URL(redirectUrl, request.url));\n }\n\n return undefined;\n },\n };\n\n // ── Handler ───────────────────────────────────────────────────────────────\n const handlerResponse: NextResponse | void = handler ? await handler(thunderid, request) : undefined;\n\n // ── Build final response ──────────────────────────────────────────────────\n if (shouldClearCookie) {\n const cookieName: string = SessionManager.getSessionCookieName();\n\n if (handlerResponse) {\n // Handler returned a response (e.g. a redirect from protectRoute).\n // Attach the deletion so the browser discards the stale cookie.\n handlerResponse.cookies.delete(cookieName);\n return handlerResponse;\n }\n\n // Pass-through: strip the dead cookie from the forwarded request headers\n // so the same-request Server Component render sees no session at all.\n const requestHeaders: Headers = new Headers(request.headers);\n requestHeaders.set('cookie', removeCookieFromHeader(request.headers.get('cookie') ?? '', cookieName));\n const cleanResponse: NextResponse = NextResponse.next({request: {headers: requestHeaders}});\n cleanResponse.cookies.delete(cookieName);\n return cleanResponse;\n }\n\n if (!refreshCookieUpdate) {\n return handlerResponse ?? NextResponse.next();\n }\n\n // A token refresh occurred — the new session cookie must be applied to:\n // 1. The HTTP response so the browser stores the updated cookie.\n // 2. The forwarded request headers so the same-request Server Component\n // render reads the fresh session token instead of the expired one.\n const cookieName: string = SessionManager.getSessionCookieName();\n const cookieOptions: ReturnType<typeof SessionManager.getSessionCookieOptions> =\n SessionManager.getSessionCookieOptions(refreshCookieUpdate.expiry);\n\n if (handlerResponse) {\n // Handler returned a response (e.g. a redirect from protectRoute).\n // Attach the refresh cookie so the browser receives it even on redirects.\n handlerResponse.cookies.set(cookieName, refreshCookieUpdate.token, cookieOptions);\n return handlerResponse;\n }\n\n // Default pass-through: update both the response cookie and the request\n // Cookie header so the downstream Server Component render is not stale.\n const requestHeaders: Headers = new Headers(request.headers);\n const updatedCookieHeader: string = replaceCookieInHeader(\n request.headers.get('cookie') ?? '',\n cookieName,\n refreshCookieUpdate.token,\n );\n requestHeaders.set('cookie', updatedCookieHeader);\n\n const response: NextResponse = NextResponse.next({request: {headers: requestHeaders}});\n response.cookies.set(cookieName, refreshCookieUpdate.token, cookieOptions);\n return response;\n };\n\nexport default thunderIDProxy;\n"],"mappings":";;;;;;;;;;;AAuDA,MAAM,0BAA0B,cAAsB,SACpD,aACG,MAAM,IAAI,CACV,KAAK,MAAc,EAAE,MAAM,CAAC,CAC5B,QAAQ,MAAc;CACrB,MAAMA,QAAgB,EAAE,QAAQ,IAAI;AAEpC,SADyB,UAAU,KAAK,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,MAChD;EACpB,CACD,KAAK,KAAK;;;;;AAMf,MAAM,yBAAyB,cAAsB,MAAc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":["../../src/server/thunderid.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAC,0BAA0B,EAAE,aAAa,EAAC,MAAM,iBAAiB,CAAC;AAG1E,OAAO,EAAC,mBAAmB,EAAC,MAAM,kBAAkB,CAAC;AAErD,QAAA,MAAM,SAAS,QAAa,OAAO,CAAC;IAClC,aAAa,EAAE,CAAC,MAAM,EAAE,0BAA0B,EAAE,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,aAAa,GAAG,QAAQ,CAAC,CAAC;IAC5G,cAAc,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACvD,YAAY,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAChD,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,mBAAmB,CAAC,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;CAC1E,CA2BA,CAAC;AAEF,eAAe,SAAS,CAAC"}
@@ -0,0 +1,27 @@
1
+ import getSessionId_default from "./actions/getSessionId.js";
2
+ import getClient_default from "./getClient.js";
3
+
4
+ //#region src/server/thunderid.ts
5
+ const thunderid = async () => {
6
+ const getAccessToken = async (sessionId) => {
7
+ return getClient_default().getAccessToken(sessionId);
8
+ };
9
+ const getSessionId = async () => getSessionId_default();
10
+ const exchangeToken = async (config, sessionId) => {
11
+ return getClient_default().exchangeToken(config, sessionId);
12
+ };
13
+ const reInitialize = async (config) => {
14
+ return getClient_default().reInitialize(config);
15
+ };
16
+ return {
17
+ exchangeToken,
18
+ getAccessToken,
19
+ getSessionId,
20
+ reInitialize
21
+ };
22
+ };
23
+ var thunderid_default = thunderid;
24
+
25
+ //#endregion
26
+ export { thunderid_default as default };
27
+ //# sourceMappingURL=thunderid.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"thunderid.js","names":["getClient","getSessionIdAction"],"sources":["../../src/server/thunderid.ts"],"sourcesContent":["/**\n * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport {TokenExchangeRequestConfig, TokenResponse} from '@thunderid/node';\nimport getSessionIdAction from './actions/getSessionId';\nimport getClient from './getClient';\nimport {ThunderIDNextConfig} from '../models/config';\n\nconst thunderid = async (): Promise<{\n exchangeToken: (config: TokenExchangeRequestConfig, sessionId: string) => Promise<TokenResponse | Response>;\n getAccessToken: (sessionId: string) => Promise<string>;\n getSessionId: () => Promise<string | undefined>;\n reInitialize: (config: Partial<ThunderIDNextConfig>) => Promise<boolean>;\n}> => {\n const getAccessToken = async (sessionId: string): Promise<string> => {\n const client = getClient();\n return client.getAccessToken(sessionId);\n };\n\n const getSessionId = async (): Promise<string | undefined> => getSessionIdAction();\n\n const exchangeToken = async (\n config: TokenExchangeRequestConfig,\n sessionId: string,\n ): Promise<TokenResponse | Response> => {\n const client = getClient();\n return client.exchangeToken(config, sessionId);\n };\n\n const reInitialize = async (config: Partial<ThunderIDNextConfig>): Promise<boolean> => {\n const client = getClient();\n return client.reInitialize(config);\n };\n\n return {\n exchangeToken,\n getAccessToken,\n getSessionId,\n reInitialize,\n };\n};\n\nexport default thunderid;\n"],"mappings":";;;;AAuBA,MAAM,YAAY,YAKZ;CACJ,MAAM,iBAAiB,OAAO,cAAuC;AAEnE,SADeA,mBAAW,CACZ,eAAe,UAAU;;CAGzC,MAAM,eAAe,YAAyCC,sBAAoB;CAElF,MAAM,gBAAgB,OACpB,QACA,cACsC;AAEtC,SADeD,mBAAW,CACZ,cAAc,QAAQ,UAAU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B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAoB5E;;;;;;;;;;OAUG;WACU,4BAA4B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAqBtF;;OAEG;WACU,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAC,CAAC;IAoB3E;;OAEG;IACH,MAAM,CAAC,uBAAuB,CAAC,MAAM,EAAE,MAAM,GAAG;QAC9C,QAAQ,EAAE,OAAO,CAAC;QAClB,MAAM,EAAE,MAAM,CAAC;QACf,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,KAAK,CAAC;QAChB,MAAM,EAAE,OAAO,CAAC;KACjB;IAUD;;OAEG;IACH,MAAM,CAAC,2BAA2B,IAAI;QACpC,QAAQ,EAAE,OAAO,CAAC;QAClB,MAAM,EAAE,MAAM,CAAC;QACf,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,KAAK,CAAC;QAChB,MAAM,EAAE,OAAO,CAAC;KACjB;IAUD;;OAEG;IACH,MAAM,CAAC,oBAAoB,IAAI,MAAM;IAIrC;;OAEG;IACH,MAAM,CAAC,wBAAwB,IAAI,MAAM;CAG1C;AAED,eAAe,cAAc,CAAC"}
@@ -0,0 +1,147 @@
1
+ import { DEFAULT_SESSION_COOKIE_EXPIRY_TIME } from "../constants/sessionConstants.js";
2
+ import { CookieConfig, ThunderIDRuntimeError } from "@thunderid/node";
3
+ import { SignJWT, compactVerify, jwtVerify } from "jose";
4
+
5
+ //#region src/utils/SessionManager.ts
6
+ /**
7
+ * Session management utility class for JWT-based session cookies
8
+ */
9
+ var SessionManager = class {
10
+ /**
11
+ * Get the signing secret from environment variable
12
+ * Throws error in production if not set
13
+ */
14
+ static getSecret() {
15
+ const secret = process.env["THUNDERID_SECRET"];
16
+ if (!secret) {
17
+ if (process.env["NODE_ENV"] === "production") throw new ThunderIDRuntimeError("THUNDERID_SECRET environment variable is required in production", "session-secret-required", "nextjs", "Set the THUNDERID_SECRET environment variable with a secure random string");
18
+ console.warn("Using default secret for development. Set THUNDERID_SECRET for production!");
19
+ return new TextEncoder().encode("development-secret-not-for-production");
20
+ }
21
+ return new TextEncoder().encode(secret);
22
+ }
23
+ /**
24
+ * Create a temporary session cookie for login initiation
25
+ */
26
+ static async createTempSession(sessionId) {
27
+ const secret = this.getSecret();
28
+ return await new SignJWT({
29
+ sessionId,
30
+ type: "temp"
31
+ }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime("15m").sign(secret);
32
+ }
33
+ /**
34
+ * Resolve the session cookie expiry time in seconds.
35
+ *
36
+ * Resolution order (first defined value wins):
37
+ * 1. `configuredExpiry` — value from `ThunderIDNodeConfig.sessionCookie?.expiryTime`
38
+ * 2. `THUNDERID_SESSION_COOKIE_EXPIRY_TIME` environment variable
39
+ * 3. `DEFAULT_SESSION_COOKIE_EXPIRY_TIME` (24 hours)
40
+ */
41
+ static resolveSessionCookieExpiry(configuredExpiry) {
42
+ if (configuredExpiry != null && configuredExpiry > 0) return configuredExpiry;
43
+ const envValue = process.env["THUNDERID_SESSION_COOKIE_EXPIRY_TIME"];
44
+ if (envValue) {
45
+ const parsed = parseInt(envValue, 10);
46
+ if (!Number.isNaN(parsed) && parsed > 0) return parsed;
47
+ }
48
+ return DEFAULT_SESSION_COOKIE_EXPIRY_TIME;
49
+ }
50
+ static async createSessionToken(accessToken, userId, sessionId, scopes, accessTokenTtlSeconds, refreshToken, organizationId) {
51
+ const secret = this.getSecret();
52
+ return await new SignJWT({
53
+ accessToken,
54
+ organizationId,
55
+ refreshToken,
56
+ scopes,
57
+ sessionId,
58
+ type: "session"
59
+ }).setProtectedHeader({ alg: "HS256" }).setSubject(userId).setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1e3) + accessTokenTtlSeconds).sign(secret);
60
+ }
61
+ /**
62
+ * Verify and decode a session token
63
+ */
64
+ static async verifySessionToken(token) {
65
+ try {
66
+ const { payload } = await jwtVerify(token, this.getSecret());
67
+ if (payload["type"] !== "session") throw new Error("Invalid token type");
68
+ return payload;
69
+ } catch (error) {
70
+ throw new ThunderIDRuntimeError(`Invalid session token: ${error instanceof Error ? error.message : "Unknown error"}`, "invalid-session-token", "nextjs", "Session token verification failed");
71
+ }
72
+ }
73
+ /**
74
+ * Verify a session token for refresh. Validates the HMAC signature and the
75
+ * `type === 'session'` discriminant but intentionally skips the `exp` check
76
+ * so an expired access token can still be exchanged for a new one.
77
+ *
78
+ * Session lifetime is still bounded — the cookie's `maxAge` is set from
79
+ * `sessionCookieExpiryTime`, so the browser drops an over-age session regardless
80
+ * of the access-token exp embedded in the JWT.
81
+ *
82
+ * Never use the returned payload for authorization.
83
+ */
84
+ static async verifySessionTokenForRefresh(token) {
85
+ try {
86
+ const { payload: rawPayload } = await compactVerify(token, this.getSecret());
87
+ const payload = JSON.parse(new TextDecoder().decode(rawPayload));
88
+ if (payload.type !== "session") throw new Error("Invalid token type");
89
+ return payload;
90
+ } catch (error) {
91
+ throw new ThunderIDRuntimeError(`Invalid session token: ${error instanceof Error ? error.message : "Unknown error"}`, "invalid-session-token-for-refresh", "nextjs", "Session token signature or type check failed during refresh");
92
+ }
93
+ }
94
+ /**
95
+ * Verify and decode a temporary session token
96
+ */
97
+ static async verifyTempSession(token) {
98
+ try {
99
+ const { payload } = await jwtVerify(token, this.getSecret());
100
+ if (payload["type"] !== "temp") throw new Error("Invalid token type");
101
+ return { sessionId: payload["sessionId"] };
102
+ } catch (error) {
103
+ throw new ThunderIDRuntimeError(`Invalid temporary session token: ${error instanceof Error ? error.message : "Unknown error"}`, "invalid-temp-session-token", "nextjs", "Temporary session token verification failed");
104
+ }
105
+ }
106
+ /**
107
+ * Get session cookie options
108
+ */
109
+ static getSessionCookieOptions(maxAge) {
110
+ return {
111
+ httpOnly: true,
112
+ maxAge,
113
+ path: "/",
114
+ sameSite: "lax",
115
+ secure: process.env["NODE_ENV"] === "production"
116
+ };
117
+ }
118
+ /**
119
+ * Get temporary session cookie options
120
+ */
121
+ static getTempSessionCookieOptions() {
122
+ return {
123
+ httpOnly: true,
124
+ maxAge: 900,
125
+ path: "/",
126
+ sameSite: "lax",
127
+ secure: process.env["NODE_ENV"] === "production"
128
+ };
129
+ }
130
+ /**
131
+ * Get session cookie name
132
+ */
133
+ static getSessionCookieName() {
134
+ return CookieConfig.SESSION_COOKIE_NAME;
135
+ }
136
+ /**
137
+ * Get temporary session cookie name
138
+ */
139
+ static getTempSessionCookieName() {
140
+ return CookieConfig.TEMP_SESSION_COOKIE_NAME;
141
+ }
142
+ };
143
+ var SessionManager_default = SessionManager;
144
+
145
+ //#endregion
146
+ export { SessionManager_default as default };
147
+ //# sourceMappingURL=SessionManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SessionManager.js","names":["secret: string | undefined","secret: Uint8Array","envValue: string | undefined","parsed: number","payload: SessionTokenPayload"],"sources":["../../src/utils/SessionManager.ts"],"sourcesContent":["/**\n * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport {ThunderIDRuntimeError, CookieConfig} from '@thunderid/node';\nimport {SignJWT, jwtVerify, compactVerify, JWTPayload} from 'jose';\nimport {DEFAULT_SESSION_COOKIE_EXPIRY_TIME} from '../constants/sessionConstants';\n\n/**\n * Session token payload interface\n */\nexport interface SessionTokenPayload extends JWTPayload {\n /** Expiration timestamp — doubles as the access token expiry (JWT exp == access token exp) */\n exp: number;\n /** Issued at timestamp */\n iat: number;\n /** Organization ID if applicable */\n organizationId?: string;\n /** The refresh token; empty string if not provided by the auth server */\n refreshToken: string;\n /** OAuth scopes */\n scopes: string[];\n /** Session ID */\n sessionId: string;\n /** User ID */\n sub: string;\n /** Token type discriminant — must be 'session' for access-session JWTs */\n type: 'session';\n}\n\n/**\n * Session management utility class for JWT-based session cookies\n */\nclass SessionManager {\n /**\n * Get the signing secret from environment variable\n * Throws error in production if not set\n */\n private static getSecret(): Uint8Array {\n const secret: string | undefined = process.env['THUNDERID_SECRET'];\n\n if (!secret) {\n if (process.env['NODE_ENV'] === 'production') {\n throw new ThunderIDRuntimeError(\n 'THUNDERID_SECRET environment variable is required in production',\n 'session-secret-required',\n 'nextjs',\n 'Set the THUNDERID_SECRET environment variable with a secure random string',\n );\n }\n // Use a default secret for development (not secure)\n // eslint-disable-next-line no-console\n console.warn('Using default secret for development. Set THUNDERID_SECRET for production!');\n return new TextEncoder().encode('development-secret-not-for-production');\n }\n\n return new TextEncoder().encode(secret);\n }\n\n /**\n * Create a temporary session cookie for login initiation\n */\n static async createTempSession(sessionId: string): Promise<string> {\n const secret: Uint8Array = this.getSecret();\n\n const jwt: string = await new SignJWT({\n sessionId,\n type: 'temp',\n })\n .setProtectedHeader({alg: 'HS256'})\n .setIssuedAt()\n .setExpirationTime('15m')\n .sign(secret);\n\n return jwt;\n }\n\n /**\n * Resolve the session cookie expiry time in seconds.\n *\n * Resolution order (first defined value wins):\n * 1. `configuredExpiry` — value from `ThunderIDNodeConfig.sessionCookie?.expiryTime`\n * 2. `THUNDERID_SESSION_COOKIE_EXPIRY_TIME` environment variable\n * 3. `DEFAULT_SESSION_COOKIE_EXPIRY_TIME` (24 hours)\n */\n static resolveSessionCookieExpiry(configuredExpiry?: number): number {\n if (configuredExpiry != null && configuredExpiry > 0) {\n return configuredExpiry;\n }\n\n const envValue: string | undefined = process.env['THUNDERID_SESSION_COOKIE_EXPIRY_TIME'];\n\n if (envValue) {\n const parsed: number = parseInt(envValue, 10);\n\n if (!Number.isNaN(parsed) && parsed > 0) {\n return parsed;\n }\n }\n\n return DEFAULT_SESSION_COOKIE_EXPIRY_TIME;\n }\n\n static async createSessionToken(\n accessToken: string,\n userId: string,\n sessionId: string,\n scopes: string,\n accessTokenTtlSeconds: number,\n refreshToken: string,\n organizationId?: string,\n ): Promise<string> {\n const secret: Uint8Array = this.getSecret();\n\n const jwt: string = await new SignJWT({\n accessToken,\n organizationId,\n refreshToken,\n scopes,\n sessionId,\n type: 'session',\n } as Omit<SessionTokenPayload, 'sub' | 'iat' | 'exp'>)\n .setProtectedHeader({alg: 'HS256'})\n .setSubject(userId)\n .setIssuedAt()\n .setExpirationTime(Math.floor(Date.now() / 1000) + accessTokenTtlSeconds)\n .sign(secret);\n\n return jwt;\n }\n\n /**\n * Verify and decode a session token\n */\n static async verifySessionToken(token: string): Promise<SessionTokenPayload> {\n try {\n const secret: Uint8Array = this.getSecret();\n const {payload} = await jwtVerify(token, secret);\n\n if (payload['type'] !== 'session') {\n throw new Error('Invalid token type');\n }\n\n return payload as SessionTokenPayload;\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Invalid session token: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'invalid-session-token',\n 'nextjs',\n 'Session token verification failed',\n );\n }\n }\n\n /**\n * Verify a session token for refresh. Validates the HMAC signature and the\n * `type === 'session'` discriminant but intentionally skips the `exp` check\n * so an expired access token can still be exchanged for a new one.\n *\n * Session lifetime is still bounded — the cookie's `maxAge` is set from\n * `sessionCookieExpiryTime`, so the browser drops an over-age session regardless\n * of the access-token exp embedded in the JWT.\n *\n * Never use the returned payload for authorization.\n */\n static async verifySessionTokenForRefresh(token: string): Promise<SessionTokenPayload> {\n try {\n const secret: Uint8Array = this.getSecret();\n const {payload: rawPayload} = await compactVerify(token, secret);\n const payload: SessionTokenPayload = JSON.parse(new TextDecoder().decode(rawPayload)) as SessionTokenPayload;\n\n if (payload.type !== 'session') {\n throw new Error('Invalid token type');\n }\n\n return payload;\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Invalid session token: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'invalid-session-token-for-refresh',\n 'nextjs',\n 'Session token signature or type check failed during refresh',\n );\n }\n }\n\n /**\n * Verify and decode a temporary session token\n */\n static async verifyTempSession(token: string): Promise<{sessionId: string}> {\n try {\n const secret: Uint8Array = this.getSecret();\n const {payload} = await jwtVerify(token, secret);\n\n if (payload['type'] !== 'temp') {\n throw new Error('Invalid token type');\n }\n\n return {sessionId: payload['sessionId'] as string};\n } catch (error) {\n throw new ThunderIDRuntimeError(\n `Invalid temporary session token: ${error instanceof Error ? error.message : 'Unknown error'}`,\n 'invalid-temp-session-token',\n 'nextjs',\n 'Temporary session token verification failed',\n );\n }\n }\n\n /**\n * Get session cookie options\n */\n static getSessionCookieOptions(maxAge: number): {\n httpOnly: boolean;\n maxAge: number;\n path: string;\n sameSite: 'lax';\n secure: boolean;\n } {\n return {\n httpOnly: true,\n maxAge,\n path: '/',\n sameSite: 'lax' as const,\n secure: process.env['NODE_ENV'] === 'production',\n };\n }\n\n /**\n * Get temporary session cookie options\n */\n static getTempSessionCookieOptions(): {\n httpOnly: boolean;\n maxAge: number;\n path: string;\n sameSite: 'lax';\n secure: boolean;\n } {\n return {\n httpOnly: true,\n maxAge: 15 * 60,\n path: '/',\n sameSite: 'lax' as const,\n secure: process.env['NODE_ENV'] === 'production',\n };\n }\n\n /**\n * Get session cookie name\n */\n static getSessionCookieName(): string {\n return CookieConfig.SESSION_COOKIE_NAME;\n }\n\n /**\n * Get temporary session cookie name\n */\n static getTempSessionCookieName(): string {\n return CookieConfig.TEMP_SESSION_COOKIE_NAME;\n }\n}\n\nexport default SessionManager;\n"],"mappings":";;;;;;;;AA+CA,IAAM,iBAAN,MAAqB;;;;;CAKnB,OAAe,YAAwB;EACrC,MAAMA,SAA6B,QAAQ,IAAI;AAE/C,MAAI,CAAC,QAAQ;AACX,OAAI,QAAQ,IAAI,gBAAgB,aAC9B,OAAM,IAAI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U,MAAM,EAAE,KAAG,CAAC,CAAC,GAAG,EAAE,WAAW,KAAK,OAAO,CAerF,CAAC"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorateConfigWithNextEnv.d.ts","sourceRoot":"","sources":["../../src/utils/decorateConfigWithNextEnv.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAC,mBAAmB,EAAC,MAAM,kBAAkB,CAAC;AAErD,QAAA,MAAM,yBAAyB,GAAI,QAAQ,mBAAmB,KAAG,mBAoChE,CAAC;AAEF,eAAe,yBAAyB,CAAC"}
@@ -0,0 +1,27 @@
1
+ //#region src/utils/decorateConfigWithNextEnv.ts
2
+ const decorateConfigWithNextEnv = (config) => {
3
+ const { organizationHandle, scopes, applicationId, baseUrl, clientId, clientSecret, signInUrl, signUpUrl, afterSignInUrl, afterSignOutUrl,...rest } = config;
4
+ const envExpiryTime = process.env["THUNDERID_SESSION_COOKIE_EXPIRY_TIME"] ? parseInt(process.env["THUNDERID_SESSION_COOKIE_EXPIRY_TIME"], 10) : void 0;
5
+ return {
6
+ ...rest,
7
+ afterSignInUrl: afterSignInUrl || process.env["NEXT_PUBLIC_THUNDERID_AFTER_SIGN_IN_URL"],
8
+ afterSignOutUrl: afterSignOutUrl || process.env["NEXT_PUBLIC_THUNDERID_AFTER_SIGN_OUT_URL"],
9
+ applicationId: applicationId || process.env["NEXT_PUBLIC_THUNDERID_APPLICATION_ID"],
10
+ baseUrl: baseUrl || process.env["NEXT_PUBLIC_THUNDERID_BASE_URL"],
11
+ clientId: clientId || process.env["NEXT_PUBLIC_THUNDERID_CLIENT_ID"],
12
+ clientSecret: clientSecret || process.env["THUNDERID_CLIENT_SECRET"],
13
+ organizationHandle: organizationHandle || process.env["NEXT_PUBLIC_THUNDERID_ORGANIZATION_HANDLE"],
14
+ scopes: scopes || process.env["NEXT_PUBLIC_THUNDERID_SCOPES"],
15
+ sessionCookie: {
16
+ ...rest.sessionCookie,
17
+ expiryTime: rest.sessionCookie?.expiryTime || envExpiryTime
18
+ },
19
+ signInUrl: signInUrl || process.env["NEXT_PUBLIC_THUNDERID_SIGN_IN_URL"],
20
+ signUpUrl: signUpUrl || process.env["NEXT_PUBLIC_THUNDERID_SIGN_UP_URL"]
21
+ };
22
+ };
23
+ var decorateConfigWithNextEnv_default = decorateConfigWithNextEnv;
24
+
25
+ //#endregion
26
+ export { decorateConfigWithNextEnv_default as default };
27
+ //# sourceMappingURL=decorateConfigWithNextEnv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorateConfigWithNextEnv.js","names":[],"sources":["../../src/utils/decorateConfigWithNextEnv.ts"],"sourcesContent":["/**\n * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport {ThunderIDNextConfig} from '../models/config';\n\nconst decorateConfigWithNextEnv = (config: ThunderIDNextConfig): ThunderIDNextConfig => {\n const {\n organizationHandle,\n scopes,\n applicationId,\n baseUrl,\n clientId,\n clientSecret,\n signInUrl,\n signUpUrl,\n afterSignInUrl,\n afterSignOutUrl,\n ...rest\n } = config;\n\n const envExpiryTime = process.env['THUNDERID_SESSION_COOKIE_EXPIRY_TIME']\n ? parseInt(process.env['THUNDERID_SESSION_COOKIE_EXPIRY_TIME'], 10)\n : undefined;\n\n return {\n ...rest,\n afterSignInUrl: afterSignInUrl || process.env['NEXT_PUBLIC_THUNDERID_AFTER_SIGN_IN_URL']!,\n afterSignOutUrl: afterSignOutUrl || process.env['NEXT_PUBLIC_THUNDERID_AFTER_SIGN_OUT_URL']!,\n applicationId: applicationId || process.env['NEXT_PUBLIC_THUNDERID_APPLICATION_ID']!,\n baseUrl: baseUrl || process.env['NEXT_PUBLIC_THUNDERID_BASE_URL']!,\n clientId: clientId || process.env['NEXT_PUBLIC_THUNDERID_CLIENT_ID']!,\n clientSecret: clientSecret || process.env['THUNDERID_CLIENT_SECRET']!,\n organizationHandle: organizationHandle || process.env['NEXT_PUBLIC_THUNDERID_ORGANIZATION_HANDLE']!,\n scopes: scopes || process.env['NEXT_PUBLIC_THUNDERID_SCOPES']!,\n sessionCookie: {\n ...rest.sessionCookie,\n expiryTime: rest.sessionCookie?.expiryTime || envExpiryTime,\n },\n signInUrl: signInUrl || process.env['NEXT_PUBLIC_THUNDERID_SIGN_IN_URL']!,\n signUpUrl: signUpUrl || process.env['NEXT_PUBLIC_THUNDERID_SIGN_UP_URL']!,\n };\n};\n\nexport default decorateConfigWithNextEnv;\n"],"mappings":";AAoBA,MAAM,6BAA6B,WAAqD;CACtF,MAAM,EACJ,oBACA,QACA,eACA,SACA,UACA,cACA,WACA,WACA,gBACA,gBACA,GAAG,SACD;CAEJ,MAAM,gBAAgB,QAAQ,IAAI,0CAC9B,SAAS,QAAQ,IAAI,yCAAyC,GAAG,GACjE;AAEJ,QAAO;EACL,GAAG;EACH,gBAAgB,kBAAkB,QAAQ,IAAI;EAC9C,iBAAiB,mBAAmB,QAAQ,IAAI;EAChD,eAAe,iBAAiB,QAAQ,IAAI;EAC5C,SAAS,WAAW,QAAQ,IAAI;EAChC,UAAU,YAAY,QAAQ,IAAI;EAClC,cAAc,gBAAgB,QAAQ,IAAI;EAC1C,oBAAoB,sBAAsB,QAAQ,IAAI;EACtD,QAAQ,UAAU,QAAQ,IAAI;EAC9B,eAAe;GACb,GAAG,KAAK;GACR,YAAY,KAAK,eAAe,cAAc;GAC/C;EACD,WAAW,aAAa,QAAQ,IAAI;EACpC,WAAW,aAAa,QAAQ,IAAI;EACrC;;AAGH,wCAAe"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handleRefreshToken.d.ts","sourceRoot":"","sources":["../../src/utils/handleRefreshToken.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,KAAK,EAAC,aAAa,EAAE,mBAAmB,EAAC,MAAM,iBAAiB,CAAC;AACxE,OAAuB,EAAC,mBAAmB,EAAC,MAAM,kBAAkB,CAAC;AAErE;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,mBAAmB,CAAC;CACrC;AAED;;;GAGG;AACH,MAAM,WAAW,wBAAwB;IACvC,eAAe,EAAE,MAAM,CAAC;IACxB,uBAAuB,EAAE,MAAM,CAAC;IAChC,aAAa,EAAE,aAAa,CAAC;CAC9B;AAED;;;;;;GAMG;AACH,QAAA,MAAM,kBAAkB,GACtB,gBAAgB,mBAAmB,EACnC,QAAQ,wBAAwB,KAC/B,OAAO,CAAC,wBAAwB,CA2ElC,CAAC;AAEF,eAAe,kBAAkB,CAAC"}
@@ -0,0 +1,62 @@
1
+ import SessionManager_default from "./SessionManager.js";
2
+
3
+ //#region src/utils/handleRefreshToken.ts
4
+ /**
5
+ * Handles the OAuth refresh_token grant and builds a new session JWT string.
6
+ *
7
+ * Intentionally decoupled from cookie APIs so it can be called from both the Edge
8
+ * Runtime (Next.js middleware) and the Node.js Runtime (server actions).
9
+ * Cookie persistence is the caller's responsibility.
10
+ */
11
+ const handleRefreshToken = async (sessionPayload, config) => {
12
+ const { baseUrl, clientId, clientSecret, sessionCookie } = config;
13
+ const { refreshToken: storedRefreshToken, sessionId, sub, scopes, organizationId } = sessionPayload;
14
+ if (!storedRefreshToken) throw new Error("No refresh token found in session payload.");
15
+ const tokenEndpoint = `${baseUrl}/oauth2/token`;
16
+ const body = new URLSearchParams({
17
+ client_id: clientId ?? "",
18
+ client_secret: clientSecret ?? "",
19
+ grant_type: "refresh_token",
20
+ refresh_token: storedRefreshToken
21
+ });
22
+ let response;
23
+ try {
24
+ response = await fetch(tokenEndpoint, {
25
+ body: body.toString(),
26
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
27
+ method: "POST"
28
+ });
29
+ } catch (fetchError) {
30
+ throw new Error(`Token refresh network error: ${fetchError instanceof Error ? fetchError.message : String(fetchError)}`);
31
+ }
32
+ if (!response.ok) throw new Error(`Token endpoint rejected refresh (HTTP ${response.status}).`);
33
+ let tokenData;
34
+ try {
35
+ tokenData = await response.json();
36
+ } catch {
37
+ throw new Error("Failed to parse token endpoint response as JSON.");
38
+ }
39
+ const newAccessToken = tokenData["access_token"];
40
+ const expiresIn = tokenData["expires_in"];
41
+ const newRefreshToken = tokenData["refresh_token"] ?? storedRefreshToken;
42
+ const newScopes = tokenData["scope"] ?? (Array.isArray(scopes) ? scopes.join(" ") : scopes ?? "");
43
+ const resolvedSessionCookieExpiry = SessionManager_default.resolveSessionCookieExpiry(sessionCookie?.expiryTime);
44
+ return {
45
+ newSessionToken: await SessionManager_default.createSessionToken(newAccessToken, sub, sessionId, newScopes, expiresIn, newRefreshToken, organizationId),
46
+ sessionCookieExpiryTime: resolvedSessionCookieExpiry,
47
+ tokenResponse: {
48
+ accessToken: newAccessToken,
49
+ createdAt: Math.floor(Date.now() / 1e3),
50
+ expiresIn: String(expiresIn),
51
+ idToken: tokenData["id_token"] ?? "",
52
+ refreshToken: newRefreshToken,
53
+ scope: newScopes,
54
+ tokenType: tokenData["token_type"] ?? "Bearer"
55
+ }
56
+ };
57
+ };
58
+ var handleRefreshToken_default = handleRefreshToken;
59
+
60
+ //#endregion
61
+ export { handleRefreshToken_default as default };
62
+ //# sourceMappingURL=handleRefreshToken.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handleRefreshToken.js","names":["body: URLSearchParams","response: Response","tokenData: Record<string, unknown>","newAccessToken: string","expiresIn: number","newRefreshToken: string","newScopes: string","resolvedSessionCookieExpiry: number","SessionManager"],"sources":["../../src/utils/handleRefreshToken.ts"],"sourcesContent":["/**\n * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport type {TokenResponse, SessionCookieConfig} from '@thunderid/node';\nimport SessionManager, {SessionTokenPayload} from './SessionManager';\n\n/**\n * Config required to call the token endpoint.\n */\nexport interface HandleRefreshTokenConfig {\n baseUrl: string;\n clientId: string;\n clientSecret: string;\n sessionCookie?: SessionCookieConfig;\n}\n\n/**\n * Result returned by handleRefreshToken.\n * Callers are responsible for persisting newSessionToken in the appropriate cookie context.\n */\nexport interface HandleRefreshTokenResult {\n newSessionToken: string;\n sessionCookieExpiryTime: number;\n tokenResponse: TokenResponse;\n}\n\n/**\n * Handles the OAuth refresh_token grant and builds a new session JWT string.\n *\n * Intentionally decoupled from cookie APIs so it can be called from both the Edge\n * Runtime (Next.js middleware) and the Node.js Runtime (server actions).\n * Cookie persistence is the caller's responsibility.\n */\nconst handleRefreshToken = async (\n sessionPayload: SessionTokenPayload,\n config: HandleRefreshTokenConfig,\n): Promise<HandleRefreshTokenResult> => {\n const {baseUrl, clientId, clientSecret, sessionCookie} = config;\n const {refreshToken: storedRefreshToken, sessionId, sub, scopes, organizationId} = sessionPayload;\n\n if (!storedRefreshToken) {\n throw new Error('No refresh token found in session payload.');\n }\n\n const tokenEndpoint = `${baseUrl}/oauth2/token`;\n const body: URLSearchParams = new URLSearchParams({\n client_id: clientId ?? '',\n client_secret: clientSecret ?? '',\n grant_type: 'refresh_token',\n refresh_token: storedRefreshToken,\n });\n\n let response: Response;\n\n try {\n response = await fetch(tokenEndpoint, {\n body: body.toString(),\n headers: {'Content-Type': 'application/x-www-form-urlencoded'},\n method: 'POST',\n });\n } catch (fetchError) {\n throw new Error(\n `Token refresh network error: ${fetchError instanceof Error ? fetchError.message : String(fetchError)}`,\n );\n }\n\n if (!response.ok) {\n throw new Error(`Token endpoint rejected refresh (HTTP ${response.status}).`);\n }\n\n let tokenData: Record<string, unknown>;\n\n try {\n tokenData = (await response.json()) as Record<string, unknown>;\n } catch {\n throw new Error('Failed to parse token endpoint response as JSON.');\n }\n\n const newAccessToken: string = tokenData['access_token'] as string;\n const expiresIn: number = tokenData['expires_in'] as number;\n // Use the rotated refresh token if the server provided one; otherwise keep the existing one.\n const newRefreshToken: string = (tokenData['refresh_token'] as string | undefined) ?? storedRefreshToken;\n const newScopes: string =\n (tokenData['scope'] as string | undefined) ??\n (Array.isArray(scopes) ? scopes.join(' ') : ((scopes as string) ?? ''));\n\n const resolvedSessionCookieExpiry: number = SessionManager.resolveSessionCookieExpiry(sessionCookie?.expiryTime);\n\n const newSessionToken: string = await SessionManager.createSessionToken(\n newAccessToken,\n sub,\n sessionId,\n newScopes,\n expiresIn,\n newRefreshToken,\n organizationId,\n );\n\n return {\n newSessionToken,\n sessionCookieExpiryTime: resolvedSessionCookieExpiry,\n tokenResponse: {\n accessToken: newAccessToken,\n createdAt: Math.floor(Date.now() / 1000),\n expiresIn: String(expiresIn),\n idToken: (tokenData['id_token'] as string | undefined) ?? '',\n refreshToken: newRefreshToken,\n scope: newScopes,\n tokenType: (tokenData['token_type'] as string | undefined) ?? 'Bearer',\n },\n };\n};\n\nexport default handleRefreshToken;\n"],"mappings":";;;;;;;;;;AAgDA,MAAM,qBAAqB,OACzB,gBACA,WACsC;CACtC,MAAM,EAAC,SAAS,UAAU,cAAc,kBAAiB;CACzD,MAAM,EAAC,cAAc,oBAAoB,WAAW,KAAK,QAAQ,mBAAkB;AAEnF,KAAI,CAAC,mBACH,OAAM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AAM,EAAE,GAEZ,CAAC;AAEH,eAAe,MAAM,CAAC"}
@@ -0,0 +1,9 @@
1
+ import { createLogger } from "@thunderid/node";
2
+
3
+ //#region src/utils/logger.ts
4
+ const logger$1 = createLogger({ level: "error" });
5
+ var logger_default = logger$1;
6
+
7
+ //#endregion
8
+ export { logger_default as default };
9
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.js","names":["logger: any","logger"],"sources":["../../src/utils/logger.ts"],"sourcesContent":["/**\n * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).\n *\n * WSO2 LLC. licenses this file to you under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\n\nimport {createLogger} from '@thunderid/node';\n\nconst logger: any = createLogger({\n level: 'error',\n});\n\nexport default logger;\n"],"mappings":";;;AAoBA,MAAMA,WAAc,aAAa,EAC/B,OAAO,SACR,CAAC;AAEF,qBAAeC"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sessionUtils.d.ts","sourceRoot":"","sources":["../../src/utils/sessionUtils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAC,WAAW,EAAC,MAAM,aAAa,CAAC;AACxC,OAAuB,EAAC,mBAAmB,EAAC,MAAM,kBAAkB,CAAC;AAErE;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,GAAU,SAAS,WAAW,KAAG,OAAO,CAAC,OAAO,CAY3E,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,GAAU,SAAS,WAAW,KAAG,OAAO,CAAC,mBAAmB,GAAG,SAAS,CAWzG,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,uBAAuB,GAAU,SAAS,WAAW,KAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAY9F,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,GAAU,SAAS,WAAW,KAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAYhG,CAAC"}
@@ -0,0 +1,39 @@
1
+ import SessionManager_default from "./SessionManager.js";
2
+
3
+ //#region src/utils/sessionUtils.ts
4
+ /**
5
+ * Gets the session payload from the request cookies.
6
+ * This includes user ID, session ID, and scopes.
7
+ *
8
+ * @param request - The Next.js request object
9
+ * @returns The session payload if valid, undefined otherwise
10
+ */
11
+ const getSessionFromRequest = async (request) => {
12
+ try {
13
+ const sessionToken = request.cookies.get(SessionManager_default.getSessionCookieName())?.value;
14
+ if (!sessionToken) return;
15
+ return await SessionManager_default.verifySessionToken(sessionToken);
16
+ } catch {
17
+ return;
18
+ }
19
+ };
20
+ /**
21
+ * Gets the session ID from the request cookies (legacy support).
22
+ * First tries to get from JWT session, then falls back to legacy session ID cookie.
23
+ *
24
+ * @param request - The Next.js request object
25
+ * @returns The session ID if it exists, undefined otherwise
26
+ */
27
+ const getSessionIdFromRequest = async (request) => {
28
+ try {
29
+ const sessionPayload = await getSessionFromRequest(request);
30
+ if (sessionPayload) return sessionPayload.sessionId;
31
+ return await Promise.resolve(void 0);
32
+ } catch {
33
+ return Promise.resolve(void 0);
34
+ }
35
+ };
36
+
37
+ //#endregion
38
+ export { getSessionFromRequest, getSessionIdFromRequest };
39
+ //# sourceMappingURL=sessionUtils.js.map