@oxy.so/core 1.18.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (662) hide show
  1. package/README.md +13 -7
  2. package/dist/cjs/HttpService.js +189 -112
  3. package/dist/cjs/OxyServices.errors.js +48 -1
  4. package/dist/cjs/OxyServices.js +263 -60
  5. package/dist/cjs/api/accounts.js +231 -0
  6. package/dist/cjs/api/agency.js +102 -0
  7. package/dist/cjs/api/appData.js +45 -0
  8. package/dist/cjs/api/apps.js +197 -0
  9. package/dist/cjs/api/assets.js +329 -0
  10. package/dist/cjs/api/auth.js +900 -0
  11. package/dist/cjs/api/billing.js +44 -0
  12. package/dist/cjs/api/civic.js +289 -0
  13. package/dist/cjs/api/contacts.js +16 -0
  14. package/dist/cjs/api/devices.js +351 -0
  15. package/dist/cjs/api/follows.js +240 -0
  16. package/dist/cjs/api/identity.js +569 -0
  17. package/dist/cjs/api/linkedAccounts.js +48 -0
  18. package/dist/cjs/api/nodes.js +75 -0
  19. package/dist/cjs/api/notifications.js +75 -0
  20. package/dist/cjs/api/privacy.js +105 -0
  21. package/dist/cjs/api/reputation.js +74 -0
  22. package/dist/cjs/api/session.js +177 -0
  23. package/dist/cjs/api/store.js +199 -0
  24. package/dist/cjs/api/topics.js +66 -0
  25. package/dist/cjs/api/users.js +309 -0
  26. package/dist/cjs/boot/sessionColdBoot.js +4 -4
  27. package/dist/cjs/civic/index.js +16 -0
  28. package/dist/cjs/civic/payloads.js +156 -0
  29. package/dist/cjs/client/context.js +2 -0
  30. package/dist/cjs/crypto/identityLink.js +5 -5
  31. package/dist/cjs/crypto/index.js +44 -0
  32. package/dist/cjs/crypto/internal.js +37 -0
  33. package/dist/cjs/crypto/keyManager.js +2 -2
  34. package/dist/cjs/crypto/polyfill.js +9 -80
  35. package/dist/cjs/crypto/recoveryPhrase.js +1 -0
  36. package/dist/cjs/crypto/registrationPow.js +1 -1
  37. package/dist/cjs/crypto/signatureService.js +1 -0
  38. package/dist/cjs/i18n/accountCategoryLabels.js +3 -3
  39. package/dist/cjs/i18n/accountRoleLabels.js +7 -7
  40. package/dist/cjs/i18n/index.js +130 -52
  41. package/dist/cjs/i18n/locales/{ar-SA.json → ar-SA.js} +134 -52
  42. package/dist/cjs/i18n/locales/{ca-ES.json → ca-ES.js} +134 -52
  43. package/dist/{esm/i18n/locales/de-DE.json → cjs/i18n/locales/de-DE.js} +136 -54
  44. package/dist/{esm/i18n/locales/en-US.json → cjs/i18n/locales/en-US.js} +163 -245
  45. package/dist/{esm/i18n/locales/es-ES.json → cjs/i18n/locales/es-ES.js} +163 -245
  46. package/dist/cjs/i18n/locales/{fr-FR.json → fr-FR.js} +134 -52
  47. package/dist/cjs/i18n/locales/{it-IT.json → it-IT.js} +134 -52
  48. package/dist/{esm/i18n/locales/ja-JP.json → cjs/i18n/locales/ja-JP.js} +134 -52
  49. package/dist/cjs/i18n/locales/{ko-KR.json → ko-KR.js} +134 -52
  50. package/dist/{esm/i18n/locales/pt-PT.json → cjs/i18n/locales/pt-PT.js} +136 -54
  51. package/dist/{esm/i18n/locales/zh-CN.json → cjs/i18n/locales/zh-CN.js} +135 -53
  52. package/dist/cjs/i18n/reputationCategoryLabels.js +2 -2
  53. package/dist/cjs/i18n/trustTierLabels.js +2 -2
  54. package/dist/cjs/index.js +55 -263
  55. package/dist/cjs/inference/index.js +21 -0
  56. package/dist/cjs/server/OxyServer.js +521 -0
  57. package/dist/cjs/server/auth.js +2 -2
  58. package/dist/cjs/server/index.js +23 -6
  59. package/dist/cjs/server/middleware.js +1154 -0
  60. package/dist/cjs/server/namespaces.js +214 -0
  61. package/dist/cjs/server/rateLimit.js +2 -2
  62. package/dist/cjs/server/requesterAssertion.js +5 -5
  63. package/dist/cjs/server/securityHeaders.js +3 -3
  64. package/dist/cjs/server/traffic.js +7 -6
  65. package/dist/cjs/server/trafficNodeHttp.js +9 -3
  66. package/dist/cjs/server/userInvalidation.js +5 -5
  67. package/dist/cjs/session/accountDialogController.js +23 -23
  68. package/dist/cjs/session/authStateStore.js +2 -2
  69. package/dist/cjs/session/identitySession.js +3 -3
  70. package/dist/cjs/session/index.js +131 -0
  71. package/dist/cjs/session/refresh.js +37 -30
  72. package/dist/cjs/session/sessionClientHost.js +5 -5
  73. package/dist/cjs/session/sharedDeviceCredential.js +3 -2
  74. package/dist/cjs/shared/utils/networkUtils.js +2 -2
  75. package/dist/cjs/utils/accountCacheSweep.js +11 -15
  76. package/dist/cjs/utils/asyncUtils.js +22 -163
  77. package/dist/cjs/utils/authHelpers.js +2 -2
  78. package/dist/cjs/utils/authWebUrl.js +3 -4
  79. package/dist/cjs/utils/avatarUtils.js +2 -2
  80. package/dist/cjs/utils/cache.js +32 -2
  81. package/dist/cjs/utils/cacheKey.js +5 -10
  82. package/dist/cjs/utils/deviceManager.js +17 -16
  83. package/dist/cjs/utils/edgeRegion.js +2 -3
  84. package/dist/cjs/utils/identityCacheSweep.js +6 -10
  85. package/dist/cjs/utils/oxyServiceEnvironment.js +3 -7
  86. package/dist/cjs/utils/requestUtils.js +40 -33
  87. package/dist/cjs/utils/sessionUtils.js +0 -2
  88. package/dist/cjs/utils/tokenClaims.js +34 -0
  89. package/dist/esm/HttpService.js +190 -113
  90. package/dist/esm/OxyServices.errors.js +45 -0
  91. package/dist/esm/OxyServices.js +262 -57
  92. package/dist/esm/api/accounts.js +218 -0
  93. package/dist/esm/api/agency.js +95 -0
  94. package/dist/esm/api/appData.js +40 -0
  95. package/dist/esm/api/apps.js +191 -0
  96. package/dist/esm/api/assets.js +324 -0
  97. package/dist/esm/api/auth.js +858 -0
  98. package/dist/esm/api/billing.js +40 -0
  99. package/dist/esm/api/civic.js +250 -0
  100. package/dist/esm/api/contacts.js +12 -0
  101. package/dist/esm/api/devices.js +346 -0
  102. package/dist/esm/api/follows.js +236 -0
  103. package/dist/esm/api/identity.js +527 -0
  104. package/dist/esm/api/linkedAccounts.js +44 -0
  105. package/dist/esm/api/nodes.js +71 -0
  106. package/dist/esm/api/notifications.js +71 -0
  107. package/dist/esm/api/privacy.js +101 -0
  108. package/dist/esm/api/reputation.js +70 -0
  109. package/dist/esm/api/session.js +173 -0
  110. package/dist/esm/api/store.js +192 -0
  111. package/dist/esm/api/topics.js +62 -0
  112. package/dist/esm/api/users.js +272 -0
  113. package/dist/esm/boot/sessionColdBoot.js +4 -4
  114. package/dist/esm/civic/index.js +10 -0
  115. package/dist/esm/civic/payloads.js +118 -0
  116. package/dist/esm/client/context.js +1 -0
  117. package/dist/esm/crypto/identityLink.js +5 -5
  118. package/dist/esm/crypto/index.js +24 -0
  119. package/dist/esm/crypto/internal.js +19 -0
  120. package/dist/esm/crypto/keyManager.js +2 -2
  121. package/dist/esm/crypto/polyfill.js +10 -81
  122. package/dist/esm/crypto/recoveryPhrase.js +1 -0
  123. package/dist/esm/crypto/registrationPow.js +1 -1
  124. package/dist/esm/crypto/signatureService.js +1 -0
  125. package/dist/esm/i18n/accountCategoryLabels.js +2 -2
  126. package/dist/esm/i18n/accountRoleLabels.js +1 -1
  127. package/dist/esm/i18n/index.js +93 -52
  128. package/dist/esm/i18n/locales/{ar-SA.json → ar-SA.js} +132 -52
  129. package/dist/esm/i18n/locales/{ca-ES.json → ca-ES.js} +132 -52
  130. package/dist/{cjs/i18n/locales/de-DE.json → esm/i18n/locales/de-DE.js} +134 -54
  131. package/dist/{cjs/i18n/locales/en-US.json → esm/i18n/locales/en-US.js} +161 -245
  132. package/dist/{cjs/i18n/locales/es-ES.json → esm/i18n/locales/es-ES.js} +161 -245
  133. package/dist/esm/i18n/locales/{fr-FR.json → fr-FR.js} +132 -52
  134. package/dist/esm/i18n/locales/{it-IT.json → it-IT.js} +132 -52
  135. package/dist/{cjs/i18n/locales/ja-JP.json → esm/i18n/locales/ja-JP.js} +132 -52
  136. package/dist/esm/i18n/locales/{ko-KR.json → ko-KR.js} +132 -52
  137. package/dist/{cjs/i18n/locales/pt-PT.json → esm/i18n/locales/pt-PT.js} +134 -54
  138. package/dist/{cjs/i18n/locales/zh-CN.json → esm/i18n/locales/zh-CN.js} +133 -53
  139. package/dist/esm/i18n/reputationCategoryLabels.js +1 -1
  140. package/dist/esm/i18n/trustTierLabels.js +1 -1
  141. package/dist/esm/index.js +30 -166
  142. package/dist/esm/inference/index.js +13 -0
  143. package/dist/esm/server/OxyServer.js +516 -0
  144. package/dist/esm/server/auth.js +2 -2
  145. package/dist/esm/server/index.js +10 -5
  146. package/dist/esm/server/middleware.js +1147 -0
  147. package/dist/esm/server/namespaces.js +206 -0
  148. package/dist/esm/server/rateLimit.js +2 -2
  149. package/dist/esm/server/requesterAssertion.js +5 -5
  150. package/dist/esm/server/securityHeaders.js +3 -3
  151. package/dist/esm/server/traffic.js +7 -6
  152. package/dist/esm/server/trafficNodeHttp.js +9 -3
  153. package/dist/esm/server/userInvalidation.js +5 -5
  154. package/dist/esm/session/accountDialogController.js +23 -23
  155. package/dist/esm/session/authStateStore.js +2 -2
  156. package/dist/esm/session/identitySession.js +3 -3
  157. package/dist/esm/session/index.js +82 -0
  158. package/dist/esm/session/refresh.js +37 -30
  159. package/dist/esm/session/sessionClientHost.js +5 -5
  160. package/dist/esm/session/sharedDeviceCredential.js +3 -2
  161. package/dist/esm/shared/utils/networkUtils.js +2 -2
  162. package/dist/esm/utils/accountCacheSweep.js +11 -15
  163. package/dist/esm/utils/asyncUtils.js +22 -151
  164. package/dist/esm/utils/authHelpers.js +2 -2
  165. package/dist/esm/utils/authWebUrl.js +3 -4
  166. package/dist/esm/utils/avatarUtils.js +2 -2
  167. package/dist/esm/utils/cache.js +32 -2
  168. package/dist/esm/utils/cacheKey.js +5 -10
  169. package/dist/esm/utils/deviceManager.js +17 -16
  170. package/dist/esm/utils/edgeRegion.js +1 -2
  171. package/dist/esm/utils/identityCacheSweep.js +6 -10
  172. package/dist/esm/utils/oxyServiceEnvironment.js +3 -7
  173. package/dist/esm/utils/requestUtils.js +40 -33
  174. package/dist/esm/utils/sessionUtils.js +0 -2
  175. package/dist/esm/utils/tokenClaims.js +31 -0
  176. package/dist/types/HttpService.d.ts +47 -9
  177. package/dist/types/OxyServices.d.ts +160 -131
  178. package/dist/types/OxyServices.errors.d.ts +42 -0
  179. package/dist/types/api/accounts.d.ts +415 -0
  180. package/dist/types/api/agency.d.ts +135 -0
  181. package/dist/types/api/appData.d.ts +27 -0
  182. package/dist/types/api/apps.d.ts +433 -0
  183. package/dist/types/api/assets.d.ts +174 -0
  184. package/dist/types/api/auth.d.ts +766 -0
  185. package/dist/types/api/billing.d.ts +113 -0
  186. package/dist/types/api/civic.d.ts +203 -0
  187. package/dist/types/api/contacts.d.ts +31 -0
  188. package/{src/mixins/OxyServices.deviceBoot.ts → dist/types/api/devices.d.ts} +130 -110
  189. package/dist/types/api/follows.d.ts +236 -0
  190. package/dist/types/api/identity.d.ts +275 -0
  191. package/dist/types/api/linkedAccounts.d.ts +48 -0
  192. package/dist/types/api/nodes.d.ts +102 -0
  193. package/dist/types/api/notifications.d.ts +77 -0
  194. package/dist/types/api/privacy.d.ts +43 -0
  195. package/dist/types/api/reputation.d.ts +50 -0
  196. package/dist/types/api/session.d.ts +85 -0
  197. package/dist/types/api/store.d.ts +278 -0
  198. package/dist/types/api/topics.d.ts +34 -0
  199. package/dist/types/api/users.d.ts +134 -0
  200. package/dist/types/boot/sessionColdBoot.d.ts +1 -1
  201. package/dist/types/civic/index.d.ts +10 -0
  202. package/dist/types/civic/payloads.d.ts +83 -0
  203. package/dist/types/client/context.d.ts +33 -0
  204. package/dist/types/crypto/identityLink.d.ts +5 -5
  205. package/dist/types/crypto/index.d.ts +24 -0
  206. package/dist/types/crypto/internal.d.ts +19 -0
  207. package/dist/types/crypto/polyfill.d.ts +6 -9
  208. package/dist/types/crypto/registrationPow.d.ts +1 -1
  209. package/dist/types/i18n/accountCategoryLabels.d.ts +1 -1
  210. package/dist/types/i18n/accountRoleLabels.d.ts +1 -1
  211. package/dist/types/i18n/index.d.ts +20 -1
  212. package/dist/types/i18n/locales/ar-SA.d.ts +386 -0
  213. package/dist/types/i18n/locales/ca-ES.d.ts +386 -0
  214. package/dist/types/i18n/locales/de-DE.d.ts +386 -0
  215. package/dist/types/i18n/locales/en-US.d.ts +2034 -0
  216. package/dist/types/i18n/locales/es-ES.d.ts +2034 -0
  217. package/dist/types/i18n/locales/fr-FR.d.ts +386 -0
  218. package/dist/types/i18n/locales/it-IT.d.ts +386 -0
  219. package/dist/types/i18n/locales/ja-JP.d.ts +386 -0
  220. package/dist/types/i18n/locales/ko-KR.d.ts +386 -0
  221. package/dist/types/i18n/locales/pt-PT.d.ts +386 -0
  222. package/dist/types/i18n/locales/zh-CN.d.ts +386 -0
  223. package/dist/types/index.d.ts +46 -95
  224. package/dist/types/inference/index.d.ts +22 -0
  225. package/dist/types/models/interfaces.d.ts +1 -1
  226. package/dist/types/server/OxyServer.d.ts +183 -0
  227. package/dist/types/server/auth.d.ts +10 -7
  228. package/dist/types/server/index.d.ts +10 -4
  229. package/dist/types/server/middleware.d.ts +291 -0
  230. package/dist/types/server/namespaces.d.ts +98 -0
  231. package/dist/types/server/rateLimit.d.ts +7 -5
  232. package/dist/types/server/requesterAssertion.d.ts +14 -11
  233. package/dist/types/server/securityHeaders.d.ts +4 -5
  234. package/dist/types/server/userInvalidation.d.ts +10 -8
  235. package/dist/types/session/accountDelegationAccess.d.ts +1 -1
  236. package/dist/types/session/accountDialogController.d.ts +8 -8
  237. package/dist/types/session/accountSwitchTargets.d.ts +1 -1
  238. package/dist/types/session/authStateStore.d.ts +7 -6
  239. package/dist/types/session/index.d.ts +40 -0
  240. package/dist/types/utils/accountCacheSweep.d.ts +7 -10
  241. package/dist/types/utils/apiUtils.d.ts +3 -3
  242. package/dist/types/utils/asyncUtils.d.ts +11 -58
  243. package/dist/types/utils/authWebUrl.d.ts +3 -4
  244. package/dist/types/utils/avatarUtils.d.ts +5 -6
  245. package/dist/types/utils/cache.d.ts +11 -3
  246. package/dist/types/utils/commonsApproval.d.ts +1 -1
  247. package/dist/types/utils/edgeRegion.d.ts +1 -2
  248. package/dist/types/utils/identityCacheSweep.d.ts +6 -4
  249. package/dist/types/utils/oauthPkce.d.ts +2 -2
  250. package/dist/types/utils/oxyServiceEnvironment.d.ts +3 -7
  251. package/dist/types/utils/requestUtils.d.ts +18 -14
  252. package/dist/types/utils/tokenClaims.d.ts +9 -0
  253. package/package.json +68 -7
  254. package/src/HttpService.ts +201 -132
  255. package/src/OxyServices.errors.ts +73 -0
  256. package/src/OxyServices.ts +289 -164
  257. package/src/api/accounts.ts +579 -0
  258. package/src/api/agency.ts +277 -0
  259. package/src/api/appData.ts +63 -0
  260. package/src/api/apps.ts +596 -0
  261. package/src/api/assets.ts +416 -0
  262. package/src/api/auth.ts +1457 -0
  263. package/src/api/billing.ts +144 -0
  264. package/src/api/civic.ts +428 -0
  265. package/src/api/contacts.ts +41 -0
  266. package/src/api/devices.ts +438 -0
  267. package/src/api/follows.ts +414 -0
  268. package/src/api/identity.ts +727 -0
  269. package/src/api/linkedAccounts.ts +78 -0
  270. package/src/api/nodes.ts +169 -0
  271. package/src/api/notifications.ts +135 -0
  272. package/src/api/privacy.ts +120 -0
  273. package/src/api/reputation.ts +134 -0
  274. package/src/api/session.ts +210 -0
  275. package/src/api/store.ts +435 -0
  276. package/src/api/topics.ts +83 -0
  277. package/src/api/users.ts +357 -0
  278. package/src/boot/sessionColdBoot.ts +4 -4
  279. package/src/civic/index.ts +12 -0
  280. package/src/civic/payloads.ts +175 -0
  281. package/src/client/context.ts +34 -0
  282. package/src/crypto/identityLink.ts +5 -5
  283. package/src/crypto/index.ts +39 -0
  284. package/src/crypto/internal.ts +20 -0
  285. package/src/crypto/keyManager.ts +2 -2
  286. package/src/crypto/polyfill.ts +9 -89
  287. package/src/crypto/recoveryPhrase.ts +1 -0
  288. package/src/crypto/registrationPow.ts +1 -1
  289. package/src/crypto/signatureService.ts +1 -0
  290. package/src/i18n/accountCategoryLabels.ts +2 -2
  291. package/src/i18n/accountRoleLabels.ts +2 -2
  292. package/src/i18n/index.ts +105 -54
  293. package/src/i18n/locales/{ar-SA.json → ar-SA.ts} +132 -52
  294. package/src/i18n/locales/{ca-ES.json → ca-ES.ts} +132 -52
  295. package/{dist/cjs/i18n/locales/locales/de-DE.json → src/i18n/locales/de-DE.ts} +134 -54
  296. package/src/i18n/locales/{en-US.json → en-US.ts} +161 -245
  297. package/{dist/cjs/i18n/locales/locales/es-ES.json → src/i18n/locales/es-ES.ts} +161 -245
  298. package/src/i18n/locales/{fr-FR.json → fr-FR.ts} +132 -52
  299. package/src/i18n/locales/{it-IT.json → it-IT.ts} +132 -52
  300. package/{dist/cjs/i18n/locales/locales/ja-JP.json → src/i18n/locales/ja-JP.ts} +132 -52
  301. package/src/i18n/locales/{ko-KR.json → ko-KR.ts} +132 -52
  302. package/src/i18n/locales/{pt-PT.json → pt-PT.ts} +134 -54
  303. package/src/i18n/locales/{zh-CN.json → zh-CN.ts} +133 -53
  304. package/src/i18n/reputationCategoryLabels.ts +1 -1
  305. package/src/i18n/trustTierLabels.ts +1 -1
  306. package/src/index.ts +170 -501
  307. package/src/inference/index.ts +48 -0
  308. package/src/models/interfaces.ts +1 -1
  309. package/src/server/OxyServer.ts +637 -0
  310. package/src/server/auth.ts +12 -8
  311. package/src/server/index.ts +28 -5
  312. package/src/server/middleware.ts +1520 -0
  313. package/src/server/namespaces.ts +257 -0
  314. package/src/server/rateLimit.ts +10 -9
  315. package/src/server/requesterAssertion.ts +13 -10
  316. package/src/server/securityHeaders.ts +7 -8
  317. package/src/server/traffic.ts +6 -6
  318. package/src/server/trafficNodeHttp.ts +7 -3
  319. package/src/server/userInvalidation.ts +9 -9
  320. package/src/session/accountDelegationAccess.ts +1 -1
  321. package/src/session/accountDialogController.ts +24 -24
  322. package/src/session/accountSwitchTargets.ts +1 -1
  323. package/src/session/authStateStore.ts +9 -8
  324. package/src/session/identitySession.ts +3 -3
  325. package/src/session/index.ts +210 -0
  326. package/src/session/refresh.ts +36 -30
  327. package/src/session/sessionClientHost.ts +5 -5
  328. package/src/session/sharedDeviceCredential.ts +3 -2
  329. package/src/shared/utils/networkUtils.ts +2 -2
  330. package/src/utils/accountCacheSweep.ts +11 -15
  331. package/src/utils/apiUtils.ts +3 -3
  332. package/src/utils/asyncUtils.ts +38 -235
  333. package/src/utils/authHelpers.ts +2 -2
  334. package/src/utils/authWebUrl.ts +3 -4
  335. package/src/utils/avatarUtils.ts +4 -7
  336. package/src/utils/cache.ts +36 -5
  337. package/src/utils/cacheKey.ts +5 -9
  338. package/src/utils/commonsApproval.ts +1 -1
  339. package/src/utils/deviceManager.ts +17 -16
  340. package/src/utils/edgeRegion.ts +1 -2
  341. package/src/utils/identityCacheSweep.ts +7 -12
  342. package/src/utils/oauthPkce.ts +2 -2
  343. package/src/utils/oxyServiceEnvironment.ts +3 -7
  344. package/src/utils/requestUtils.ts +48 -44
  345. package/src/utils/sessionUtils.ts +0 -2
  346. package/src/utils/tokenClaims.ts +38 -0
  347. package/dist/cjs/.tsbuildinfo +0 -1
  348. package/dist/cjs/OxyServices.base.js +0 -392
  349. package/dist/cjs/i18n/locales/locales/ar-SA.json +0 -306
  350. package/dist/cjs/i18n/locales/locales/ca-ES.json +0 -306
  351. package/dist/cjs/i18n/locales/locales/en-US.json +0 -2127
  352. package/dist/cjs/i18n/locales/locales/fr-FR.json +0 -306
  353. package/dist/cjs/i18n/locales/locales/it-IT.json +0 -306
  354. package/dist/cjs/i18n/locales/locales/ko-KR.json +0 -306
  355. package/dist/cjs/i18n/locales/locales/pt-PT.json +0 -306
  356. package/dist/cjs/i18n/locales/locales/zh-CN.json +0 -306
  357. package/dist/cjs/mixins/OxyServices.accounts.js +0 -555
  358. package/dist/cjs/mixins/OxyServices.agency.js +0 -154
  359. package/dist/cjs/mixins/OxyServices.analytics.js +0 -49
  360. package/dist/cjs/mixins/OxyServices.appData.js +0 -108
  361. package/dist/cjs/mixins/OxyServices.assets.js +0 -854
  362. package/dist/cjs/mixins/OxyServices.auth.js +0 -1440
  363. package/dist/cjs/mixins/OxyServices.chains.js +0 -73
  364. package/dist/cjs/mixins/OxyServices.civic.js +0 -611
  365. package/dist/cjs/mixins/OxyServices.connectedApps.js +0 -95
  366. package/dist/cjs/mixins/OxyServices.contacts.js +0 -50
  367. package/dist/cjs/mixins/OxyServices.deviceBoot.js +0 -191
  368. package/dist/cjs/mixins/OxyServices.devices.js +0 -116
  369. package/dist/cjs/mixins/OxyServices.features.js +0 -335
  370. package/dist/cjs/mixins/OxyServices.followGraph.js +0 -221
  371. package/dist/cjs/mixins/OxyServices.identity.js +0 -562
  372. package/dist/cjs/mixins/OxyServices.identityBackup.js +0 -172
  373. package/dist/cjs/mixins/OxyServices.inference.js +0 -59
  374. package/dist/cjs/mixins/OxyServices.language.js +0 -125
  375. package/dist/cjs/mixins/OxyServices.linkedAccounts.js +0 -79
  376. package/dist/cjs/mixins/OxyServices.location.js +0 -43
  377. package/dist/cjs/mixins/OxyServices.nodes.js +0 -175
  378. package/dist/cjs/mixins/OxyServices.notifications.js +0 -63
  379. package/dist/cjs/mixins/OxyServices.payment.js +0 -158
  380. package/dist/cjs/mixins/OxyServices.privacy.js +0 -199
  381. package/dist/cjs/mixins/OxyServices.reputation.js +0 -289
  382. package/dist/cjs/mixins/OxyServices.security.js +0 -89
  383. package/dist/cjs/mixins/OxyServices.store.js +0 -266
  384. package/dist/cjs/mixins/OxyServices.topics.js +0 -137
  385. package/dist/cjs/mixins/OxyServices.user.js +0 -954
  386. package/dist/cjs/mixins/OxyServices.utility.js +0 -1402
  387. package/dist/cjs/mixins/index.js +0 -136
  388. package/dist/cjs/mixins/mixinHelpers.js +0 -53
  389. package/dist/cjs/utils/webauthnOrigin.js +0 -51
  390. package/dist/esm/.tsbuildinfo +0 -1
  391. package/dist/esm/OxyServices.base.js +0 -388
  392. package/dist/esm/i18n/locales/locales/ar-SA.json +0 -306
  393. package/dist/esm/i18n/locales/locales/ca-ES.json +0 -306
  394. package/dist/esm/i18n/locales/locales/de-DE.json +0 -306
  395. package/dist/esm/i18n/locales/locales/en-US.json +0 -2127
  396. package/dist/esm/i18n/locales/locales/es-ES.json +0 -2127
  397. package/dist/esm/i18n/locales/locales/fr-FR.json +0 -306
  398. package/dist/esm/i18n/locales/locales/it-IT.json +0 -306
  399. package/dist/esm/i18n/locales/locales/ja-JP.json +0 -306
  400. package/dist/esm/i18n/locales/locales/ko-KR.json +0 -306
  401. package/dist/esm/i18n/locales/locales/pt-PT.json +0 -306
  402. package/dist/esm/i18n/locales/locales/zh-CN.json +0 -306
  403. package/dist/esm/mixins/OxyServices.accounts.js +0 -543
  404. package/dist/esm/mixins/OxyServices.agency.js +0 -151
  405. package/dist/esm/mixins/OxyServices.analytics.js +0 -46
  406. package/dist/esm/mixins/OxyServices.appData.js +0 -103
  407. package/dist/esm/mixins/OxyServices.assets.js +0 -851
  408. package/dist/esm/mixins/OxyServices.auth.js +0 -1400
  409. package/dist/esm/mixins/OxyServices.chains.js +0 -70
  410. package/dist/esm/mixins/OxyServices.civic.js +0 -605
  411. package/dist/esm/mixins/OxyServices.connectedApps.js +0 -92
  412. package/dist/esm/mixins/OxyServices.contacts.js +0 -47
  413. package/dist/esm/mixins/OxyServices.deviceBoot.js +0 -186
  414. package/dist/esm/mixins/OxyServices.devices.js +0 -113
  415. package/dist/esm/mixins/OxyServices.features.js +0 -332
  416. package/dist/esm/mixins/OxyServices.followGraph.js +0 -218
  417. package/dist/esm/mixins/OxyServices.identity.js +0 -558
  418. package/dist/esm/mixins/OxyServices.identityBackup.js +0 -169
  419. package/dist/esm/mixins/OxyServices.inference.js +0 -56
  420. package/dist/esm/mixins/OxyServices.language.js +0 -122
  421. package/dist/esm/mixins/OxyServices.linkedAccounts.js +0 -76
  422. package/dist/esm/mixins/OxyServices.location.js +0 -40
  423. package/dist/esm/mixins/OxyServices.nodes.js +0 -172
  424. package/dist/esm/mixins/OxyServices.notifications.js +0 -60
  425. package/dist/esm/mixins/OxyServices.payment.js +0 -155
  426. package/dist/esm/mixins/OxyServices.privacy.js +0 -196
  427. package/dist/esm/mixins/OxyServices.reputation.js +0 -286
  428. package/dist/esm/mixins/OxyServices.security.js +0 -86
  429. package/dist/esm/mixins/OxyServices.store.js +0 -263
  430. package/dist/esm/mixins/OxyServices.topics.js +0 -134
  431. package/dist/esm/mixins/OxyServices.user.js +0 -951
  432. package/dist/esm/mixins/OxyServices.utility.js +0 -1397
  433. package/dist/esm/mixins/index.js +0 -133
  434. package/dist/esm/mixins/mixinHelpers.js +0 -48
  435. package/dist/esm/utils/webauthnOrigin.js +0 -48
  436. package/dist/types/.tsbuildinfo +0 -1
  437. package/dist/types/OxyServices.base.d.ts +0 -189
  438. package/dist/types/mixins/OxyServices.accounts.d.ts +0 -868
  439. package/dist/types/mixins/OxyServices.agency.d.ts +0 -176
  440. package/dist/types/mixins/OxyServices.analytics.d.ts +0 -72
  441. package/dist/types/mixins/OxyServices.appData.d.ts +0 -108
  442. package/dist/types/mixins/OxyServices.assets.d.ts +0 -371
  443. package/dist/types/mixins/OxyServices.auth.d.ts +0 -965
  444. package/dist/types/mixins/OxyServices.chains.d.ts +0 -156
  445. package/dist/types/mixins/OxyServices.civic.d.ts +0 -520
  446. package/dist/types/mixins/OxyServices.connectedApps.d.ts +0 -184
  447. package/dist/types/mixins/OxyServices.contacts.d.ts +0 -100
  448. package/dist/types/mixins/OxyServices.deviceBoot.d.ts +0 -185
  449. package/dist/types/mixins/OxyServices.devices.d.ts +0 -103
  450. package/dist/types/mixins/OxyServices.features.d.ts +0 -250
  451. package/dist/types/mixins/OxyServices.followGraph.d.ts +0 -223
  452. package/dist/types/mixins/OxyServices.identity.d.ts +0 -337
  453. package/dist/types/mixins/OxyServices.identityBackup.d.ts +0 -129
  454. package/dist/types/mixins/OxyServices.inference.d.ts +0 -95
  455. package/dist/types/mixins/OxyServices.language.d.ts +0 -87
  456. package/dist/types/mixins/OxyServices.linkedAccounts.d.ts +0 -107
  457. package/dist/types/mixins/OxyServices.location.d.ts +0 -70
  458. package/dist/types/mixins/OxyServices.nodes.d.ts +0 -198
  459. package/dist/types/mixins/OxyServices.notifications.d.ts +0 -143
  460. package/dist/types/mixins/OxyServices.payment.d.ts +0 -117
  461. package/dist/types/mixins/OxyServices.privacy.d.ts +0 -146
  462. package/dist/types/mixins/OxyServices.reputation.d.ts +0 -202
  463. package/dist/types/mixins/OxyServices.security.d.ts +0 -84
  464. package/dist/types/mixins/OxyServices.store.d.ts +0 -334
  465. package/dist/types/mixins/OxyServices.topics.d.ts +0 -110
  466. package/dist/types/mixins/OxyServices.user.d.ts +0 -600
  467. package/dist/types/mixins/OxyServices.utility.d.ts +0 -526
  468. package/dist/types/mixins/index.d.ts +0 -87
  469. package/dist/types/mixins/mixinHelpers.d.ts +0 -31
  470. package/dist/types/utils/webauthnOrigin.d.ts +0 -32
  471. package/src/OxyServices.base.ts +0 -480
  472. package/src/__tests__/authSocket.test.ts +0 -96
  473. package/src/__tests__/fixEsmImports.test.ts +0 -132
  474. package/src/__tests__/httpServiceAbort.test.ts +0 -308
  475. package/src/__tests__/httpServiceActivityId.test.ts +0 -49
  476. package/src/__tests__/httpServiceAuthSelfAwait.test.ts +0 -108
  477. package/src/__tests__/httpServiceCache.test.ts +0 -318
  478. package/src/__tests__/httpServiceFormEncoded.test.ts +0 -139
  479. package/src/__tests__/httpServiceQueueDeadlock.test.ts +0 -128
  480. package/src/__tests__/httpServiceRateLimitedRefresh.test.ts +0 -160
  481. package/src/__tests__/httpServiceUnwrapEnvelope.test.ts +0 -115
  482. package/src/__tests__/httpServiceWrites.test.ts +0 -175
  483. package/src/__tests__/inSessionRefresh.test.ts +0 -313
  484. package/src/__tests__/linkedClient.test.ts +0 -363
  485. package/src/__tests__/nearExpiryMintStorm.test.ts +0 -165
  486. package/src/__tests__/parseHttpErrorBody.test.ts +0 -116
  487. package/src/__tests__/publicInterfaceParity.test.ts +0 -75
  488. package/src/__tests__/serverValueImportsDeclared.test.ts +0 -120
  489. package/src/__tests__/serviceTokenWorkloadFallback.test.ts +0 -85
  490. package/src/__tests__/userIdentity.test.ts +0 -143
  491. package/src/boot/__tests__/sessionColdBoot.identity.test.ts +0 -393
  492. package/src/boot/__tests__/sessionColdBoot.sharedDevice.test.ts +0 -325
  493. package/src/boot/__tests__/sessionColdBoot.test.ts +0 -570
  494. package/src/crypto/__tests__/backupMaterial.test.ts +0 -86
  495. package/src/crypto/__tests__/cryptoPrimitives.test.ts +0 -226
  496. package/src/crypto/__tests__/identityLink.test.ts +0 -18
  497. package/src/crypto/__tests__/identityMocks.ts +0 -125
  498. package/src/crypto/__tests__/identityProof.test.ts +0 -81
  499. package/src/crypto/__tests__/keyManager.atomicity.test.ts +0 -272
  500. package/src/crypto/__tests__/keyManager.cacheSafety.test.ts +0 -175
  501. package/src/crypto/__tests__/keyManager.deviceBackup.test.ts +0 -310
  502. package/src/crypto/__tests__/keyManager.identityStatus.test.ts +0 -217
  503. package/src/crypto/__tests__/keyManager.recoveryLadder.test.ts +0 -179
  504. package/src/crypto/__tests__/keyManager.recoveryMnemonic.test.ts +0 -138
  505. package/src/crypto/__tests__/keyManager.sharedSlotSync.test.ts +0 -150
  506. package/src/crypto/__tests__/keyManager.storageMigration.test.ts +0 -227
  507. package/src/crypto/__tests__/keyManager.test.ts +0 -329
  508. package/src/crypto/__tests__/polyfill.test.ts +0 -109
  509. package/src/crypto/__tests__/polyfillOrder.test.ts +0 -114
  510. package/src/crypto/__tests__/recoveryPhrase.test.ts +0 -61
  511. package/src/crypto/__tests__/registrationPow.test.ts +0 -61
  512. package/src/crypto/__tests__/scopedSeed.test.ts +0 -126
  513. package/src/crypto/__tests__/signChallengeShared.test.ts +0 -63
  514. package/src/crypto/__tests__/signedRecord.test.ts +0 -230
  515. package/src/i18n/__tests__/accountCategoryLabels.test.ts +0 -62
  516. package/src/i18n/__tests__/accountRoleLabels.test.ts +0 -54
  517. package/src/i18n/__tests__/reputationCategoryLabels.test.ts +0 -56
  518. package/src/i18n/__tests__/trustTierLabels.test.ts +0 -47
  519. package/src/i18n/locales/de-DE.json +0 -306
  520. package/src/i18n/locales/es-ES.json +0 -2127
  521. package/src/i18n/locales/ja-JP.json +0 -306
  522. package/src/inference/__tests__/OxyInferenceClient.test.ts +0 -899
  523. package/src/logger/__tests__/logger.test.ts +0 -207
  524. package/src/mixins/OxyServices.accounts.ts +0 -1330
  525. package/src/mixins/OxyServices.agency.ts +0 -353
  526. package/src/mixins/OxyServices.analytics.ts +0 -53
  527. package/src/mixins/OxyServices.appData.ts +0 -158
  528. package/src/mixins/OxyServices.assets.ts +0 -964
  529. package/src/mixins/OxyServices.auth.ts +0 -2028
  530. package/src/mixins/OxyServices.chains.ts +0 -134
  531. package/src/mixins/OxyServices.civic.ts +0 -945
  532. package/src/mixins/OxyServices.connectedApps.ts +0 -212
  533. package/src/mixins/OxyServices.contacts.ts +0 -73
  534. package/src/mixins/OxyServices.devices.ts +0 -120
  535. package/src/mixins/OxyServices.features.ts +0 -454
  536. package/src/mixins/OxyServices.followGraph.ts +0 -293
  537. package/src/mixins/OxyServices.identity.ts +0 -787
  538. package/src/mixins/OxyServices.identityBackup.ts +0 -250
  539. package/src/mixins/OxyServices.inference.ts +0 -57
  540. package/src/mixins/OxyServices.language.ts +0 -144
  541. package/src/mixins/OxyServices.linkedAccounts.ts +0 -129
  542. package/src/mixins/OxyServices.location.ts +0 -46
  543. package/src/mixins/OxyServices.nodes.ts +0 -337
  544. package/src/mixins/OxyServices.notifications.ts +0 -142
  545. package/src/mixins/OxyServices.payment.ts +0 -163
  546. package/src/mixins/OxyServices.privacy.ts +0 -219
  547. package/src/mixins/OxyServices.reputation.ts +0 -436
  548. package/src/mixins/OxyServices.security.ts +0 -110
  549. package/src/mixins/OxyServices.store.ts +0 -585
  550. package/src/mixins/OxyServices.topics.ts +0 -169
  551. package/src/mixins/OxyServices.user.ts +0 -1208
  552. package/src/mixins/OxyServices.utility.ts +0 -1803
  553. package/src/mixins/__tests__/OxyServices.civic.test.ts +0 -1095
  554. package/src/mixins/__tests__/OxyServices.deviceBoot.test.ts +0 -124
  555. package/src/mixins/__tests__/OxyServices.identity.test.ts +0 -301
  556. package/src/mixins/__tests__/OxyServices.nodes.test.ts +0 -341
  557. package/src/mixins/__tests__/OxyServices.rotateKey.test.ts +0 -323
  558. package/src/mixins/__tests__/OxyServices.serviceAssetMetadata.test.ts +0 -192
  559. package/src/mixins/__tests__/OxyServices.serviceAssetMetadataBySha.test.ts +0 -135
  560. package/src/mixins/__tests__/OxyServices.serviceLinkedDownloadUrl.test.ts +0 -139
  561. package/src/mixins/__tests__/accountEvents.test.ts +0 -158
  562. package/src/mixins/__tests__/accounts.test.ts +0 -727
  563. package/src/mixins/__tests__/agency.test.ts +0 -120
  564. package/src/mixins/__tests__/appData.test.ts +0 -203
  565. package/src/mixins/__tests__/assetCredentials.test.ts +0 -47
  566. package/src/mixins/__tests__/assetUpload.test.ts +0 -191
  567. package/src/mixins/__tests__/authRefusalObservability.test.ts +0 -396
  568. package/src/mixins/__tests__/backgroundCredential.httpIntegration.test.ts +0 -130
  569. package/src/mixins/__tests__/chains.test.ts +0 -113
  570. package/src/mixins/__tests__/commonsSignIn.test.ts +0 -1147
  571. package/src/mixins/__tests__/connectedApps.test.ts +0 -146
  572. package/src/mixins/__tests__/deviceTokenMintPinned.test.ts +0 -113
  573. package/src/mixins/__tests__/discoveryErrorHandling.test.ts +0 -265
  574. package/src/mixins/__tests__/followCacheInvalidation.test.ts +0 -173
  575. package/src/mixins/__tests__/followGraph.test.ts +0 -147
  576. package/src/mixins/__tests__/followGraphPagination.test.ts +0 -271
  577. package/src/mixins/__tests__/getFileDownloadUrl.test.ts +0 -346
  578. package/src/mixins/__tests__/getFollowStatuses.test.ts +0 -95
  579. package/src/mixins/__tests__/getUsersByIds.test.ts +0 -176
  580. package/src/mixins/__tests__/identityBackup.test.ts +0 -315
  581. package/src/mixins/__tests__/identityLink.test.ts +0 -89
  582. package/src/mixins/__tests__/identityWriteCacheInvalidation.test.ts +0 -407
  583. package/src/mixins/__tests__/inferenceFactory.test.ts +0 -58
  584. package/src/mixins/__tests__/linkedAccounts.test.ts +0 -109
  585. package/src/mixins/__tests__/notifications.read.test.ts +0 -82
  586. package/src/mixins/__tests__/onTokensChanged.test.ts +0 -129
  587. package/src/mixins/__tests__/preSessionSkipAuth.test.ts +0 -284
  588. package/src/mixins/__tests__/privacyCacheInvalidation.test.ts +0 -155
  589. package/src/mixins/__tests__/reputation.test.ts +0 -522
  590. package/src/mixins/__tests__/serviceAuth.test.ts +0 -889
  591. package/src/mixins/__tests__/serviceTokenJwks.test.ts +0 -208
  592. package/src/mixins/__tests__/store.test.ts +0 -304
  593. package/src/mixins/__tests__/topics.test.ts +0 -155
  594. package/src/mixins/__tests__/userReadCacheBypass.test.ts +0 -129
  595. package/src/mixins/__tests__/userTokenAuth.test.ts +0 -746
  596. package/src/mixins/__tests__/verifyChallenge.test.ts +0 -161
  597. package/src/mixins/__tests__/verifyServiceActingAs.test.ts +0 -167
  598. package/src/mixins/__tests__/webauthnAuth.test.ts +0 -279
  599. package/src/mixins/index.ts +0 -203
  600. package/src/mixins/mixinHelpers.ts +0 -69
  601. package/src/server/__tests__/auth.test.ts +0 -78
  602. package/src/server/__tests__/capabilityTicket.test.ts +0 -111
  603. package/src/server/__tests__/cors.socket.test.ts +0 -225
  604. package/src/server/__tests__/cors.test.ts +0 -158
  605. package/src/server/__tests__/rateLimit.test.ts +0 -257
  606. package/src/server/__tests__/requesterAssertion.test.ts +0 -359
  607. package/src/server/__tests__/safeFetch.test.ts +0 -232
  608. package/src/server/__tests__/securityHeaders.test.ts +0 -387
  609. package/src/server/__tests__/serviceTokenAttribution.test.ts +0 -396
  610. package/src/server/__tests__/traffic.test.ts +0 -180
  611. package/src/server/__tests__/trafficNodeHttp.test.ts +0 -38
  612. package/src/server/__tests__/userInvalidation.test.ts +0 -203
  613. package/src/server/__tests__/verifySecret.test.ts +0 -40
  614. package/src/server/__tests__/workloadIdentity.client.test.ts +0 -16
  615. package/src/server/__tests__/workloadIdentity.test.ts +0 -128
  616. package/src/session/__tests__/SessionClient.additive.test.ts +0 -153
  617. package/src/session/__tests__/SessionClient.broadcastChannel.test.ts +0 -114
  618. package/src/session/__tests__/SessionClient.diagnostics.test.ts +0 -91
  619. package/src/session/__tests__/SessionClient.directory.test.ts +0 -688
  620. package/src/session/__tests__/SessionClient.httpIntegration.test.ts +0 -65
  621. package/src/session/__tests__/SessionClient.identityPin.test.ts +0 -175
  622. package/src/session/__tests__/SessionClient.rest.test.ts +0 -119
  623. package/src/session/__tests__/SessionClient.serverEvents.test.ts +0 -72
  624. package/src/session/__tests__/SessionClient.socket.test.ts +0 -202
  625. package/src/session/__tests__/SessionClient.socketFactory.test.ts +0 -81
  626. package/src/session/__tests__/SessionClient.state.test.ts +0 -78
  627. package/src/session/__tests__/SessionClient.switchTokenOrder.test.ts +0 -170
  628. package/src/session/__tests__/accountDelegationAccess.test.ts +0 -104
  629. package/src/session/__tests__/accountDialogController.test.ts +0 -2502
  630. package/src/session/__tests__/accountDialogShape.test.ts +0 -120
  631. package/src/session/__tests__/accountSwitchTargets.test.ts +0 -137
  632. package/src/session/__tests__/authStateStore.test.ts +0 -451
  633. package/src/session/__tests__/deviceDirectory.test.ts +0 -422
  634. package/src/session/__tests__/deviceSwitcherRows.test.ts +0 -223
  635. package/src/session/__tests__/identityPin.test.ts +0 -131
  636. package/src/session/__tests__/identitySession.test.ts +0 -194
  637. package/src/session/__tests__/projectSessionState.test.ts +0 -105
  638. package/src/session/__tests__/refresh.identityPin.test.ts +0 -307
  639. package/src/session/__tests__/refresh.test.ts +0 -606
  640. package/src/session/__tests__/sessionIntegration.test.ts +0 -209
  641. package/src/session/__tests__/sharedDeviceCredential.test.ts +0 -300
  642. package/src/utils/__tests__/accountUtils.test.ts +0 -151
  643. package/src/utils/__tests__/activityId.test.ts +0 -45
  644. package/src/utils/__tests__/asyncUtils.test.ts +0 -279
  645. package/src/utils/__tests__/authWebUrl.test.ts +0 -15
  646. package/src/utils/__tests__/cacheKey.test.ts +0 -0
  647. package/src/utils/__tests__/cacheLifecycle.test.ts +0 -65
  648. package/src/utils/__tests__/coldBoot.test.ts +0 -496
  649. package/src/utils/__tests__/commonsApproval.test.ts +0 -60
  650. package/src/utils/__tests__/identityCacheSweep.test.ts +0 -151
  651. package/src/utils/__tests__/languageUtils.test.ts +0 -244
  652. package/src/utils/__tests__/oauthPkce.test.ts +0 -303
  653. package/src/utils/__tests__/officialOrigins.test.ts +0 -31
  654. package/src/utils/__tests__/oxyServiceEnvironment.test.ts +0 -7
  655. package/src/utils/__tests__/profileLinks.test.ts +0 -180
  656. package/src/utils/__tests__/redactUrl.test.ts +0 -33
  657. package/src/utils/__tests__/registrableApex.test.ts +0 -62
  658. package/src/utils/__tests__/requestUtilsAbort.test.ts +0 -155
  659. package/src/utils/__tests__/textNormalization.test.ts +0 -205
  660. package/src/utils/__tests__/validationUtils.test.ts +0 -703
  661. package/src/utils/__tests__/webauthnOrigin.test.ts +0 -83
  662. package/src/utils/webauthnOrigin.ts +0 -52
@@ -1,1803 +0,0 @@
1
- /**
2
- * Utility Methods Mixin
3
- *
4
- * Provides utility methods including Express.js authentication middleware.
5
- */
6
- import { jwtDecode } from 'jwt-decode';
7
- import type { JsonWebKey } from 'node:crypto';
8
- import type { ApiError, User } from '../models/interfaces';
9
- import type { OxyServicesBase } from '../OxyServices.base';
10
- import { loadNodeCrypto } from '@oxy.so/protocol';
11
- import { buildUrl } from '../utils/apiUtils';
12
- import { logger } from '../logger';
13
- import { CACHE_TIMES } from './mixinHelpers';
14
- import { OXY_SERVICE_ENVIRONMENTS, type OxyServiceEnvironment } from '../utils/oxyServiceEnvironment';
15
-
16
- interface JwtPayload {
17
- exp?: number;
18
- userId?: string;
19
- id?: string;
20
- sessionId?: string;
21
- type?: string;
22
- appId?: string;
23
- credentialId?: string;
24
- ownerAccountId?: string;
25
- appName?: string;
26
- scopes?: string[];
27
- tier?: string;
28
- aud?: string | string[];
29
- iss?: string;
30
- environment?: string;
31
- nbf?: number;
32
- [key: string]: unknown;
33
- }
34
-
35
- /**
36
- * Result from the service-acting-as verification endpoint.
37
- * Confirms that a given service app holds an active delegation grant for
38
- * the supplied user, along with the explicit scope list the grant covers.
39
- *
40
- * The API side stores this as an ordinary `app_grants` row — the SAME revocable
41
- * record the OAuth consent screen writes and the "Connected apps" UI lists and
42
- * deletes — whose `scopes` name `acting-as:offline`. There is deliberately no
43
- * separate delegation table: a second store would be a second revocation
44
- * surface, and a user who disconnects an application in "Connected apps" means
45
- * it, so one revoke has to end everything.
46
- *
47
- * `scopes` is what THAT USER consented to, not what the application may do in
48
- * general. `requireScope` intersects it with the token's own app-wide scopes for
49
- * a delegated request, and the intersection is the effective authority.
50
- *
51
- * The SDK never inspects the grant directly — it round-trips through
52
- * `GET /internal/service-acting-as/verify?appId=...&userId=...` so the
53
- * authoritative store stays server-side.
54
- */
55
- export interface ServiceActingAsVerification {
56
- authorized: boolean;
57
- scopes: string[];
58
- }
59
-
60
- /** The SET `events` member Oxy uses for an account deletion. */
61
- export const OXY_ACCOUNT_DELETED_EVENT_URI = 'https://oxy.so/events/account.deleted';
62
-
63
- /**
64
- * A verified account event from Oxy (OxyHQ/Mention#1169): a person deleted
65
- * their Oxy account and every relying application must erase what it holds
66
- * for them. Returned by `verifyAccountEvent` only after the signature, `typ`,
67
- * issuer and audience all check out.
68
- */
69
- export interface OxyAccountEvent {
70
- /** The event id (`jti`). Stable across webhook retries and the pull feed: dedupe on it. */
71
- eventId: string;
72
- type: 'account.deleted';
73
- /** The deleted Oxy account. */
74
- userId: string;
75
- /**
76
- * The account's handle at deletion time, for relying parties that address
77
- * the person by handle (an ActivityPub actor URI). `null` when the account had
78
- * none, or when the token predates the field.
79
- */
80
- username: string | null;
81
- /** ISO-8601 time the deletion committed. */
82
- occurredAt: string;
83
- /** `true` when Oxy archived the row to keep financial records. Erase either way. */
84
- retained: boolean;
85
- /** The application the event was addressed to (`aud`). */
86
- applicationId: string;
87
- /** Seconds since the epoch the token was issued at (`iat`). */
88
- issuedAt: number;
89
- }
90
-
91
- /** One entry of the account-event pull feed (`GET /account-events`). */
92
- export interface OxyAccountEventFeedItem {
93
- eventId: string;
94
- type: 'account.deleted';
95
- userId: string;
96
- username: string | null;
97
- occurredAt: string;
98
- retained: boolean;
99
- /** The same signed token the webhook carries. Verify it with `verifyAccountEvent`. */
100
- token: string;
101
- }
102
-
103
- export interface OxyAccountEventFeedPage {
104
- events: OxyAccountEventFeedItem[];
105
- /** Pass back as `after` to continue; unchanged when the page is empty. */
106
- nextCursor: string | null;
107
- }
108
-
109
- export interface VerifyAccountEventOptions {
110
- /**
111
- * The application id the token must be addressed to. Defaults to the `appId`
112
- * of this client's configured service credential.
113
- */
114
- audience?: string;
115
- /** Defaults to `/.well-known/jwks.json` on this client's API origin. */
116
- jwksUrl?: string;
117
- }
118
-
119
- /** Why an account event token was refused. `message` never contains the token. */
120
- export class OxyAccountEventError extends Error {
121
- constructor(message: string) {
122
- super(message);
123
- this.name = 'OxyAccountEventError';
124
- }
125
- }
126
-
127
- /**
128
- * Service app metadata attached to requests authenticated with service tokens.
129
- *
130
- * Every field comes from the token's SIGNED payload and is populated only after
131
- * the signature, `iss`/`aud`/`type` binding and expiry all pass — so a verifier
132
- * holding this object can name the responsible principals without a lookup of
133
- * its own. Together with `credentialId` and `ownerAccountId` it is the canonical
134
- * attribution tuple of ADR 0007 minus the delegated user.
135
- *
136
- * `scopes` are the EFFECTIVE scopes: the credential's own scopes intersected
137
- * with the owning application's grant at mint time (the API's `intersectScopes`
138
- * is the single authority for that intersection — nothing re-intersects here).
139
- * Route-level checks narrow further via `requireScope()`.
140
- *
141
- * A delegated end user is NOT a field of this type, and must never become one.
142
- * It lives in `req.serviceActingAs` / `req.userId`, is authorised per request,
143
- * and is attribution only.
144
- */
145
- export interface ServiceApp {
146
- appId: string;
147
- appName: string;
148
- scopes: string[];
149
- /**
150
- * `internal` when the caller is one of Oxy's own applications: app to app it
151
- * is trusted outright — {@link requireScope} passes and it may act for a user
152
- * without a delegation grant. `external` keeps every scope and grant rule.
153
- * What the USER may do (their accounts, plan, limits) is still for the
154
- * receiving service to decide. A token without the claim reads as `external`.
155
- */
156
- tier: 'internal' | 'external';
157
- /** The credentialId of the specific service credential that minted this token. */
158
- credentialId: string;
159
- /**
160
- * The Oxy account that owns `appId` and is financially responsible for it.
161
- * The BILLING principal — never a user id, and never the delegated
162
- * `X-Oxy-User-Id` (ADR 0007).
163
- */
164
- ownerAccountId: string;
165
- /** Test/live isolation (F2.0): which `ApplicationCredential.environment` minted this token. */
166
- environment: OxyServiceEnvironment;
167
- }
168
-
169
- /**
170
- * Why a request's credential was refused, recorded on the request itself.
171
- *
172
- * The middleware answers a fixed, deliberately uninformative body to the
173
- * client; this is the other half of that trade. A refusal is ALWAYS observable
174
- * to the HOST: it is logged at `warn` with a stable `code`, handed to
175
- * `onRefusal`, and left on `req.oxyAuthRefusal` for the host's own logs.
176
- *
177
- * It exists because the opposite cost was measured: Oxy served
178
- * `{"keys":[]}` from `/.well-known/jwks.json` with no Ed25519 signing key
179
- * bound, every service token failed `Oxy service-token key set is unavailable`,
180
- * and on the OPTIONAL path that failure fell straight through to `next()`.
181
- * The host then answered its own generic 401 and logged nothing at all, so the
182
- * one fact that named the fault — an empty key set — existed nowhere. Hours.
183
- *
184
- * **Nothing here is ever sent to a client, and `reason` never contains the
185
- * token, a signature, a secret or a session id.** It carries the SDK's own
186
- * failure message (`kid` unknown, audience mismatch, key set unavailable) plus
187
- * the ids already considered safe to log elsewhere in this middleware.
188
- */
189
- export interface OxyAuthRefusal {
190
- /** Stable, greppable code. Matches the `code` a non-optional refusal answers. */
191
- code: string;
192
- /** Which credential lane refused. */
193
- stage: 'token' | 'service-token' | 'session';
194
- /** Human-readable cause. Never a token, signature, secret or session id. */
195
- reason: string;
196
- /** The status a NON-optional mount would have answered with. */
197
- status: number;
198
- /**
199
- * `true` when the middleware was mounted with `optional: true`, so this
200
- * refusal did not produce a response — the request continued unauthenticated
201
- * and whatever the host does next (typically its own generic 401) is the
202
- * only thing the client sees.
203
- */
204
- optional: boolean;
205
- }
206
-
207
- /**
208
- * Expected JWT audience for tokens issued by the Oxy auth service.
209
- */
210
- const OXY_JWT_AUDIENCE = 'oxy-api';
211
- /**
212
- * Expected JWT issuer for tokens issued by the Oxy auth service.
213
- */
214
- const OXY_JWT_ISSUER = 'oxy-auth';
215
-
216
- /**
217
- * Sentinel error classes for service-token verification. Using classes (not
218
- * message strings) makes the catch site below safe to extend: a new failure
219
- * mode added later cannot silently fall through to the generic 500 branch.
220
- */
221
- class ServiceTokenStructureError extends Error {
222
- constructor(message = 'Service token has malformed structure') {
223
- super(message);
224
- this.name = 'ServiceTokenStructureError';
225
- }
226
- }
227
-
228
- class ServiceTokenSignatureError extends Error {
229
- constructor(message = 'Service token signature is invalid') {
230
- super(message);
231
- this.name = 'ServiceTokenSignatureError';
232
- }
233
- }
234
-
235
- class ServiceTokenConfigurationError extends Error {
236
- constructor(message: string) {
237
- super(message);
238
- this.name = 'ServiceTokenConfigurationError';
239
- }
240
- }
241
-
242
- class ServiceTokenClaimError extends Error {
243
- constructor(message: string) {
244
- super(message);
245
- this.name = 'ServiceTokenClaimError';
246
- }
247
- }
248
-
249
- function isOxyServiceEnvironment(value: unknown): value is OxyServiceEnvironment {
250
- return (
251
- typeof value === 'string' &&
252
- (OXY_SERVICE_ENVIRONMENTS as readonly string[]).includes(value)
253
- );
254
- }
255
-
256
- /**
257
- * Options for oxyClient.auth() middleware
258
- */
259
- interface AuthMiddlewareOptions {
260
- /** Enable debug logging (default: false) */
261
- debug?: boolean;
262
- /** Custom error handler - receives error object, can return response */
263
- onError?: (error: ApiError) => unknown;
264
- /** Load full user profile from API (default: false for performance) */
265
- loadUser?: boolean;
266
- /** Optional auth - attach user if token present but don't block (default: false) */
267
- optional?: boolean;
268
- /**
269
- * Called whenever a PRESENTED credential is refused, on the optional path as
270
- * well as the blocking one. Runs before the response (if any) and after
271
- * `req.oxyAuthRefusal` is set, so a host can raise its own alert or carry the
272
- * code into its request log. Throwing from it is swallowed — an observer must
273
- * not be able to turn a refusal into a 500.
274
- *
275
- * Refusal is about a credential that was offered and rejected: a request with
276
- * NO `Authorization` header is not refused and does not reach this.
277
- */
278
- onRefusal?: (refusal: OxyAuthRefusal) => void;
279
- /**
280
- * Public JWKS endpoint used for Ed25519 service-token verification. Defaults
281
- * to `/.well-known/jwks.json` on this Oxy client's configured API origin.
282
- */
283
- serviceTokenJwksUrl?: string;
284
- /**
285
- * @deprecated Oxy-API-only transition for pre-cutover HS256 service tokens.
286
- * External services omit this option and verify Ed25519 tokens through the
287
- * public JWKS. Never distribute `ACCESS_TOKEN_SECRET`: a host holding it can
288
- * mint user access tokens as well as verify legacy service tokens.
289
- */
290
- jwtSecret?: string;
291
- /**
292
- * Expected JWT issuer. Defaults to `'oxy-auth'`. Override only if you run
293
- * a private fork of the Oxy auth server under a different `iss` claim.
294
- */
295
- expectedIssuer?: string;
296
- /**
297
- * Expected JWT audience. Defaults to `'oxy-api'`. Override only if your
298
- * private fork mints tokens for a different audience.
299
- */
300
- expectedAudience?: string;
301
- }
302
-
303
- export function OxyServicesUtilityMixin<T extends typeof OxyServicesBase>(Base: T) {
304
- return class extends Base {
305
- /**
306
- * In-memory cache for service-acting-as verification.
307
- * Negative results are cached for 1min to avoid hammering the verify
308
- * endpoint when a service is misconfigured; positive grants are cached
309
- * for 5min to amortize the round-trip without holding stale grants too long.
310
- * @internal
311
- */
312
- _serviceActingAsCache = new Map<string, { result: ServiceActingAsVerification | null; expiresAt: number }>();
313
- /** @internal Per-client public-key cache; never contains private material. */
314
- _serviceTokenJwksCache: ServiceTokenJwksCache = { keys: new Map(), expiresAt: 0, lastAttemptAt: 0 };
315
-
316
- // TypeScript's mixin pattern requires `(...args: any[])` here — the
317
- // constructor signature is a structural shape check the compiler enforces.
318
- // Matches every other mixin in this package; do not change without a
319
- // monorepo-wide refactor of the mixin pipeline.
320
- constructor(...args: any[]) {
321
- super(...(args as [any]));
322
- }
323
-
324
- /**
325
- * Verify that a service app holds an active delegation grant authorising
326
- * it to act on behalf of `userId`. Returns the grant (with allowed scopes)
327
- * on success or `null` if no valid grant exists. Negative answers are
328
- * cached briefly to protect the verify endpoint from misconfigured callers.
329
- *
330
- * Implemented as a per-instance Map keyed by `appId:userId`. Cached
331
- * positive grants live for 5 minutes (acceptable staleness window for an
332
- * impersonation grant); revocations propagate within that window.
333
- *
334
- * @internal Used by the auth() middleware — not part of the public API
335
- */
336
- async verifyServiceActingAs(
337
- appId: string,
338
- userId: string,
339
- ): Promise<ServiceActingAsVerification | null> {
340
- const cacheKey = `${appId}:${userId}`;
341
- const now = Date.now();
342
-
343
- const cached = this._serviceActingAsCache.get(cacheKey);
344
- if (cached && cached.expiresAt > now) {
345
- return cached.result;
346
- }
347
-
348
- try {
349
- // The verify endpoint is service-to-service and admits only a
350
- // platform-TRUSTED calling application, so this call must carry the
351
- // VERIFIER's own service token. Sent explicitly rather than through
352
- // `makeServiceRequest`, which would drop `retry: false` and the timeout
353
- // — and those two are not incidental: this runs inside request-handling
354
- // middleware, so an inner retry loop multiplies the latency of every
355
- // delegated request by the number of attempts.
356
- //
357
- // A verifier with no service credentials configured throws here and
358
- // lands in the catch below, which is the correct outcome. A host that
359
- // cannot prove who it is has no business being told which users have
360
- // delegated to which applications, and the 60s negative cache stops a
361
- // misconfigured deployment from turning every request into a round trip.
362
- const serviceToken = await (this as unknown as OxyAuthInstance).getServiceToken();
363
-
364
- const result = await this.makeRequest<ServiceActingAsVerification>(
365
- 'GET',
366
- '/internal/service-acting-as/verify',
367
- { appId, userId },
368
- {
369
- cache: false,
370
- retry: false,
371
- timeout: 5000,
372
- headers: { Authorization: `Bearer ${serviceToken}` },
373
- },
374
- );
375
-
376
- const authorized = Boolean(result && result.authorized);
377
- const verified: ServiceActingAsVerification | null = authorized
378
- ? { authorized: true, scopes: Array.isArray(result.scopes) ? result.scopes : [] }
379
- : null;
380
-
381
- this._serviceActingAsCache.set(cacheKey, {
382
- result: verified,
383
- expiresAt: now + 5 * 60 * 1000,
384
- });
385
-
386
- return verified;
387
- } catch (error) {
388
- logger.warn('[oxy.auth] verifyServiceActingAs lookup failed — caching negative result', {
389
- component: 'auth',
390
- method: 'verifyServiceActingAs',
391
- appId,
392
- userId,
393
- }, error);
394
- // Negative cache prevents a runaway loop if the verify endpoint is
395
- // down, while still letting a real grant become visible within 60s.
396
- this._serviceActingAsCache.set(cacheKey, {
397
- result: null,
398
- expiresAt: now + 1 * 60 * 1000,
399
- });
400
- return null;
401
- }
402
- }
403
-
404
- /**
405
- * Verify an account event token from Oxy — the body of an account-event
406
- * webhook, or an entry's `token` from `listAccountEvents` — and return the
407
- * event. Throws {@link OxyAccountEventError} unless the token is an
408
- * EdDSA-signed `secevent+jwt` from Oxy's published key set, issued by
409
- * `oxy-auth`, addressed to this application, carrying exactly one known
410
- * event. A service token (`typ: JWT`) is refused here, as this token is
411
- * refused as a service token.
412
- *
413
- * Node only (it needs `node:crypto`). The caller must still be idempotent on
414
- * `eventId`: Oxy delivers at least once, by push and by pull.
415
- */
416
- async verifyAccountEvent(
417
- token: string,
418
- options: VerifyAccountEventOptions = {},
419
- ): Promise<OxyAccountEvent> {
420
- if (typeof token !== 'string' || token.length === 0 || token.length > 16 * 1024) {
421
- throw new OxyAccountEventError('Account event token is missing or oversized');
422
- }
423
- const parts = token.split('.');
424
- if (parts.length !== 3 || parts.some((part) => part.length === 0)) {
425
- throw new OxyAccountEventError('Account event token is not a compact JWS');
426
- }
427
- const [headerB64, payloadB64, signatureB64] = parts as [string, string, string];
428
- let header: Record<string, unknown>;
429
- let payload: Record<string, unknown>;
430
- try {
431
- header = parseJsonSegment(headerB64);
432
- payload = parseJsonSegment(payloadB64);
433
- } catch {
434
- throw new OxyAccountEventError('Account event token is malformed');
435
- }
436
- if (
437
- Object.keys(header).length !== 3
438
- || header.alg !== 'EdDSA'
439
- || header.typ !== 'secevent+jwt'
440
- || typeof header.kid !== 'string'
441
- || !/^[A-Za-z0-9._-]{1,128}$/.test(header.kid)
442
- ) {
443
- throw new OxyAccountEventError('Account event token header is not supported');
444
- }
445
-
446
- const nodeCrypto = await loadNodeCrypto();
447
- let jwk: ServiceTokenPublicJwk;
448
- try {
449
- jwk = await resolveServiceTokenPublicKey(
450
- header.kid,
451
- options.jwksUrl ?? new URL('/.well-known/jwks.json', this.getBaseURL()).toString(),
452
- this._serviceTokenJwksCache,
453
- );
454
- } catch (error) {
455
- throw new OxyAccountEventError(
456
- error instanceof Error ? error.message.replace('Service token', 'Account event') : 'Signing key is unavailable',
457
- );
458
- }
459
- const signature = Buffer.from(signatureB64, 'base64url');
460
- if (signature.toString('base64url') !== signatureB64 || signature.length !== 64) {
461
- throw new OxyAccountEventError('Account event token signature is malformed');
462
- }
463
- let verified = false;
464
- try {
465
- const publicKey = nodeCrypto.createPublicKey({ key: jwk as unknown as JsonWebKey, format: 'jwk' });
466
- verified = nodeCrypto.verify(null, Buffer.from(`${headerB64}.${payloadB64}`), publicKey, signature);
467
- } catch {
468
- verified = false;
469
- }
470
- if (!verified) throw new OxyAccountEventError('Account event token signature is invalid');
471
-
472
- if (payload.iss !== OXY_JWT_ISSUER) {
473
- throw new OxyAccountEventError('Account event token issuer is not Oxy');
474
- }
475
- const audience = options.audience ?? await this._configuredServiceAppId();
476
- if (typeof payload.aud !== 'string' || payload.aud !== audience) {
477
- throw new OxyAccountEventError('Account event token is addressed to another application');
478
- }
479
- if (typeof payload.jti !== 'string' || payload.jti.length === 0 || payload.jti.length > 128) {
480
- throw new OxyAccountEventError('Account event token has no event id');
481
- }
482
- if (typeof payload.iat !== 'number' || !Number.isFinite(payload.iat)) {
483
- throw new OxyAccountEventError('Account event token has no issue time');
484
- }
485
- const events = payload.events;
486
- if (typeof events !== 'object' || events === null || Array.isArray(events)) {
487
- throw new OxyAccountEventError('Account event token carries no events');
488
- }
489
- const entries = Object.entries(events as Record<string, unknown>);
490
- const deleted = (events as Record<string, unknown>)[OXY_ACCOUNT_DELETED_EVENT_URI];
491
- if (entries.length !== 1 || typeof deleted !== 'object' || deleted === null || Array.isArray(deleted)) {
492
- throw new OxyAccountEventError('Account event token carries an unknown event');
493
- }
494
- const body = deleted as Record<string, unknown>;
495
- if (typeof body.userId !== 'string' || body.userId.length === 0 || body.userId.length > 128) {
496
- throw new OxyAccountEventError('Account event names no account');
497
- }
498
- if (typeof body.occurredAt !== 'string' || Number.isNaN(Date.parse(body.occurredAt))) {
499
- throw new OxyAccountEventError('Account event has no occurrence time');
500
- }
501
- if (body.username !== undefined && body.username !== null && typeof body.username !== 'string') {
502
- throw new OxyAccountEventError('Account event username is malformed');
503
- }
504
- return {
505
- eventId: payload.jti,
506
- type: 'account.deleted',
507
- userId: body.userId,
508
- username: typeof body.username === 'string' ? body.username : null,
509
- occurredAt: body.occurredAt,
510
- retained: body.retained === true,
511
- applicationId: payload.aud,
512
- issuedAt: payload.iat,
513
- };
514
- }
515
-
516
- /**
517
- * One page of account events addressed to this application, oldest first,
518
- * from Oxy's pull feed — the reconciliation path behind the webhook. Needs
519
- * the service credential (`configureServiceAuth`). Verify each entry's
520
- * `token` with {@link verifyAccountEvent} before acting on it.
521
- */
522
- async listAccountEvents(
523
- options: { after?: string; limit?: number } = {},
524
- ): Promise<OxyAccountEventFeedPage> {
525
- const serviceToken = await (this as unknown as OxyAuthInstance).getServiceToken();
526
- const query: Record<string, string> = {};
527
- if (options.after) query.after = options.after;
528
- if (options.limit !== undefined) query.limit = String(options.limit);
529
- return this.makeRequest<OxyAccountEventFeedPage>('GET', '/account-events', query, {
530
- cache: false,
531
- headers: { Authorization: `Bearer ${serviceToken}` },
532
- });
533
- }
534
-
535
- /** @internal The `appId` claim of this client's own service token. */
536
- async _configuredServiceAppId(): Promise<string> {
537
- const serviceToken = await (this as unknown as OxyAuthInstance).getServiceToken();
538
- const appId = jwtDecode<JwtPayload>(serviceToken).appId;
539
- if (typeof appId !== 'string' || appId.length === 0) {
540
- throw new OxyAccountEventError('No audience given and the service credential names no application');
541
- }
542
- return appId;
543
- }
544
-
545
- /**
546
- * Express.js authentication middleware
547
- *
548
- * Validates JWT tokens against the Oxy API and attaches user data to requests.
549
- * Uses server-side session validation for security (not just JWT decode).
550
- *
551
- * **Design note — jwtDecode vs jwt.verify:**
552
- * This middleware uses `jwtDecode()` (decode-only, NO signature check) for
553
- * user tokens, because third-party apps mounting `oxy.auth()` do not hold
554
- * the Oxy signing secret. **Every claim in a user token is therefore
555
- * attacker-controlled and proves nothing on its own.** The identity comes
556
- * from somewhere else entirely:
557
- * - A user token MUST carry a `sessionId`. That session is validated
558
- * server-side on every request via `validateSession()`, and the user id
559
- * is read off the VALIDATED SESSION — never off the token. A token whose
560
- * `userId` claim disagrees with the session is refused
561
- * (`SESSION_USER_MISMATCH`); a token with no `sessionId` at all is
562
- * refused outright (`SESSION_REQUIRED`). There is no local-claims path.
563
- * - Service tokens (type: 'service') ARE stateless, so they use Ed25519
564
- * verification against Oxy's public JWKS and are additionally checked
565
- * for `aud`, `iss`, `type`, time, attribution and scope claims. The
566
- * `jwtSecret` path exists only for Oxy API's bounded HS256 transition.
567
- * - The backend's own `authMiddleware` uses `jwt.verify()` because it has
568
- * direct access to `ACCESS_TOKEN_SECRET`.
569
- *
570
- * **Why session-less user tokens are refused rather than trusted:**
571
- * every user access token the Oxy API issues carries a `sessionId` (see
572
- * `packages/api/src/utils/sessionUtils.ts`, `generateSessionTokens` — the
573
- * only mint site for user tokens, including the OAuth code exchange). So
574
- * refusing session-less user tokens costs nothing legitimate, while
575
- * accepting them let anyone authenticate as anyone by hand-rolling a JWT
576
- * with a `userId` claim and a garbage signature.
577
- *
578
- * **Why the claimed user id is cross-checked against the session:**
579
- * `GET /session/validate/:sessionId` is UNAUTHENTICATED and does not bind
580
- * the bearer token — it returns whoever owns the session id it was handed.
581
- * Trusting the token's `userId` claim after a successful validation would
582
- * therefore let a caller holding ANY live session id (their own, for
583
- * instance) pair it with a forged `userId` and be trusted as that user.
584
- * `authSocket()` has always cross-checked this; the HTTP middleware now
585
- * does too.
586
- *
587
- * **Service-token delegation (X-Oxy-User-Id):**
588
- * When a service token is accompanied by `X-Oxy-User-Id`, the SDK calls
589
- * `verifyServiceActingAs(appId, userId)` to confirm an explicit delegation
590
- * grant exists before attaching `req.userId`. A missing/expired grant
591
- * results in a 403 — there is no fail-open path.
592
- *
593
- * @example
594
- * ```typescript
595
- * import { OxyServices } from '@oxy.so/core';
596
- *
597
- * const oxy = new OxyServices({ baseURL: 'https://api.oxy.so' });
598
- *
599
- * // Protect all routes under /protected
600
- * app.use('/protected', oxy.auth());
601
- *
602
- * // Access user in route handler
603
- * app.get('/protected/me', (req, res) => {
604
- * res.json({ userId: req.userId, user: req.user });
605
- * });
606
- *
607
- * // Load full user profile from API
608
- * app.use('/admin', oxy.auth({ loadUser: true }));
609
- *
610
- * // Optional auth - attach user if present, don't block if absent
611
- * app.use('/public', oxy.auth({ optional: true }));
612
- *
613
- * // Require a specific scope on a service-token-protected route
614
- * app.use('/internal/files', oxy.serviceAuth(), oxy.requireScope('files:write'));
615
- * ```
616
- *
617
- * @param options Optional configuration
618
- * @returns Express middleware function
619
- */
620
- auth(options: AuthMiddlewareOptions = {}) {
621
- const {
622
- debug = false,
623
- onError,
624
- onRefusal,
625
- loadUser = false,
626
- optional = false,
627
- jwtSecret,
628
- serviceTokenJwksUrl = new URL('/.well-known/jwks.json', this.getBaseURL()).toString(),
629
- expectedIssuer = OXY_JWT_ISSUER,
630
- expectedAudience = OXY_JWT_AUDIENCE,
631
- } = options;
632
- // Cross-mixin method access: typed as a structural subset of the
633
- // composed OxyServices we know we have at runtime.
634
- const oxyInstance = this as unknown as OxyAuthInstance;
635
-
636
- /**
637
- * Make a refusal observable to the HOST, without telling the client
638
- * anything it is not already told.
639
- *
640
- * Called at the top of every branch that rejects a PRESENTED credential,
641
- * including the ones `optional` then swallows — those are the expensive
642
- * ones, because they leave no trace anywhere else. The response bodies
643
- * below are untouched by design: what a client sees does not change.
644
- *
645
- * `warn`, not `debug`: a debug-gated reason is only there for whoever
646
- * already suspects this middleware, and the failure mode this exists for
647
- * is the one where nobody does. The volume is bounded by refusals, and a
648
- * host drowning in them has a fault worth the lines.
649
- */
650
- const recordRefusal = (
651
- req: AuthReq,
652
- refusal: { code: string; stage: OxyAuthRefusal['stage']; reason: string; status: number },
653
- ): void => {
654
- const recorded: OxyAuthRefusal = { ...refusal, optional };
655
- req.oxyAuthRefusal = recorded;
656
- logger.warn(`[oxy.auth] refused ${recorded.code}: ${recorded.reason}`, {
657
- component: 'auth',
658
- method: 'auth',
659
- code: recorded.code,
660
- stage: recorded.stage,
661
- reason: recorded.reason,
662
- status: recorded.status,
663
- // Says whether the client will see this status or the host's own
664
- // generic answer — the difference that made the JWKS outage invisible.
665
- optional: recorded.optional,
666
- path: req.path,
667
- });
668
- if (onRefusal) {
669
- try {
670
- onRefusal(recorded);
671
- } catch (observerError) {
672
- logger.warn('[oxy.auth] onRefusal observer threw', {
673
- component: 'auth',
674
- method: 'auth',
675
- }, observerError);
676
- }
677
- }
678
- };
679
-
680
- // Return an async middleware function
681
- return async (req: AuthReq, res: AuthRes, next: AuthNext) => {
682
- try {
683
- // Extract token from Authorization header.
684
- // Node/Express normalizes `Authorization` to a string; we guard
685
- // against the (legal but unusual) string[] case anyway.
686
- const rawAuthHeader = req.headers.authorization;
687
- const authHeader = Array.isArray(rawAuthHeader) ? rawAuthHeader[0] : rawAuthHeader;
688
- const token = authHeader?.startsWith('Bearer ') ? authHeader.substring(7) : null;
689
-
690
- if (debug) {
691
- logger.debug(`[oxy.auth] ${req.method} ${req.path} | token: ${!!token}`, {
692
- component: 'auth',
693
- method: 'auth',
694
- });
695
- }
696
-
697
- if (!token) {
698
- if (optional) {
699
- req.userId = null;
700
- req.user = null;
701
- return next();
702
- }
703
-
704
- const error = {
705
- error: 'MISSING_TOKEN',
706
- message: 'Access token required',
707
- code: 'MISSING_TOKEN',
708
- status: 401
709
- };
710
- if (onError) return onError(error);
711
- return res.status(401).json(error);
712
- }
713
-
714
- // Decode token to extract claims
715
- let decoded: JwtPayload;
716
- try {
717
- decoded = jwtDecode<JwtPayload>(token);
718
- } catch (decodeError) {
719
- recordRefusal(req, {
720
- code: 'INVALID_TOKEN_FORMAT',
721
- stage: 'token',
722
- reason: 'Bearer credential is not a decodable JWT',
723
- status: 401,
724
- });
725
- if (debug) {
726
- logger.debug('[oxy.auth] Token decode failed', {
727
- component: 'auth',
728
- method: 'auth',
729
- }, decodeError);
730
- }
731
- if (optional) {
732
- req.userId = null;
733
- req.user = null;
734
- return next();
735
- }
736
-
737
- const error = {
738
- error: 'INVALID_TOKEN_FORMAT',
739
- message: 'Invalid token format',
740
- code: 'INVALID_TOKEN_FORMAT',
741
- status: 401
742
- };
743
- if (onError) return onError(error);
744
- return res.status(401).json(error);
745
- }
746
-
747
- // Handle service tokens (internal service-to-service auth)
748
- // Service tokens are stateless JWTs with type: 'service' — requires signature verification
749
- if (decoded.type === 'service') {
750
- // Verify JWT signature, then audience / issuer / type / appId claims.
751
- //
752
- // Signature verification uses Node crypto rather than
753
- // `jsonwebtoken` because this file also ships into RN/web bundles.
754
- // The middleware itself runs on Node hosts; `loadNodeCrypto` is
755
- // per-platform, so Metro never bundles a Node built-in reference.
756
- try {
757
- await verifyServiceTokenSignature(token, {
758
- legacySecret: jwtSecret,
759
- jwksUrl: serviceTokenJwksUrl,
760
- cache: this._serviceTokenJwksCache,
761
- });
762
- verifyServiceTokenClaims(decoded, {
763
- audience: expectedAudience,
764
- issuer: expectedIssuer,
765
- });
766
- } catch (verifyError) {
767
- // Structure + signature + claim errors all map to 401. Anything
768
- // else (e.g. Node crypto failing to load on a misconfigured host)
769
- // genuinely IS a 500.
770
- if (
771
- verifyError instanceof ServiceTokenConfigurationError
772
- ) {
773
- recordRefusal(req, {
774
- code: 'SERVICE_TOKEN_NOT_CONFIGURED',
775
- stage: 'service-token',
776
- reason: verifyError.message,
777
- status: 403,
778
- });
779
- if (optional) {
780
- req.userId = null;
781
- req.user = null;
782
- return next();
783
- }
784
- const error = {
785
- error: 'SERVICE_TOKEN_NOT_CONFIGURED',
786
- message: verifyError.message,
787
- code: 'SERVICE_TOKEN_NOT_CONFIGURED',
788
- status: 403,
789
- };
790
- if (onError) return onError(error);
791
- return res.status(403).json(error);
792
- }
793
- if (
794
- verifyError instanceof ServiceTokenStructureError ||
795
- verifyError instanceof ServiceTokenSignatureError ||
796
- verifyError instanceof ServiceTokenClaimError
797
- ) {
798
- const code = verifyError instanceof ServiceTokenClaimError
799
- ? 'INVALID_SERVICE_TOKEN_CLAIMS'
800
- : 'INVALID_SERVICE_TOKEN';
801
- // The SDK's own message is the whole diagnostic value here —
802
- // "signing key is unknown" (rotated/unpublished kid), "key set
803
- // is unavailable" (JWKS empty, unreachable or malformed) and
804
- // "audience mismatch" are three different outages that answer
805
- // the client identically.
806
- recordRefusal(req, {
807
- code,
808
- stage: 'service-token',
809
- reason: `${verifyError.name}: ${verifyError.message}`,
810
- status: 401,
811
- });
812
- if (debug) {
813
- logger.debug('[oxy.auth] Service token rejected', {
814
- component: 'auth',
815
- method: 'auth.serviceToken',
816
- reason: verifyError.name,
817
- detail: verifyError.message,
818
- });
819
- }
820
- if (optional) {
821
- req.userId = null;
822
- req.user = null;
823
- return next();
824
- }
825
- const error = {
826
- error: code,
827
- message: verifyError.message,
828
- code,
829
- status: 401,
830
- };
831
- if (onError) return onError(error);
832
- return res.status(401).json(error);
833
- }
834
-
835
- logger.error('[oxy.auth] Unexpected error during service token verification', verifyError, {
836
- component: 'auth',
837
- method: 'auth.serviceToken',
838
- });
839
- const error = {
840
- error: 'AUTH_INTERNAL_ERROR',
841
- message: 'Internal authentication error',
842
- code: 'AUTH_INTERNAL_ERROR',
843
- status: 500,
844
- };
845
- if (onError) return onError(error);
846
- return res.status(500).json(error);
847
- }
848
-
849
- // Check expiration — reject tokens at exact expiry second (use <=)
850
- const now = Math.floor(Date.now() / 1000);
851
- if (!Number.isInteger(decoded.exp) || (decoded.exp as number) <= now) {
852
- recordRefusal(req, {
853
- code: 'TOKEN_EXPIRED',
854
- stage: 'service-token',
855
- reason: Number.isInteger(decoded.exp)
856
- ? 'Service token expired'
857
- : 'Service token has no integer exp claim',
858
- status: 401,
859
- });
860
- if (optional) {
861
- req.userId = null;
862
- req.user = null;
863
- return next();
864
- }
865
- const error = { error: 'TOKEN_EXPIRED', message: 'Service token expired', code: 'TOKEN_EXPIRED', status: 401 };
866
- if (onError) return onError(error);
867
- return res.status(401).json(error);
868
- }
869
- if (decoded.nbf !== undefined && (!Number.isInteger(decoded.nbf) || decoded.nbf > now)) {
870
- recordRefusal(req, {
871
- code: 'INVALID_SERVICE_TOKEN_CLAIMS',
872
- stage: 'service-token',
873
- reason: 'Service token is not yet valid (nbf)',
874
- status: 401,
875
- });
876
- const error = { error: 'INVALID_SERVICE_TOKEN_CLAIMS', message: 'Service token is not yet valid', code: 'INVALID_SERVICE_TOKEN_CLAIMS', status: 401 };
877
- if (onError) return onError(error);
878
- return res.status(401).json(error);
879
- }
880
-
881
- // Validate required service token fields. All of them are
882
- // required, `ownerAccountId` included: an optional billing
883
- // principal is one fallback away from being resolved from the
884
- // delegated user, which is the exact confusion ADR 0007 forbids.
885
- const appId = decoded.appId;
886
- const credentialId = decoded.credentialId;
887
- const ownerAccountId = decoded.ownerAccountId;
888
- const environment = decoded.environment;
889
- if (
890
- !isExactNonEmptyServiceClaim(appId) ||
891
- !isExactNonEmptyServiceClaim(decoded.appName) ||
892
- !isExactNonEmptyServiceClaim(credentialId) ||
893
- !isExactNonEmptyServiceClaim(ownerAccountId) ||
894
- !isOxyServiceEnvironment(environment)
895
- || !Array.isArray(decoded.scopes)
896
- || !decoded.scopes.every((scope) => typeof scope === 'string' && scope.length > 0 && scope === scope.trim())
897
- || new Set(decoded.scopes).size !== decoded.scopes.length
898
- ) {
899
- recordRefusal(req, {
900
- code: 'INVALID_SERVICE_TOKEN',
901
- stage: 'service-token',
902
- // Names the field rather than its value: an exact-match claim
903
- // failing on invisible whitespace reads as "present" in a log
904
- // that only says which claims were missing.
905
- reason: `Service token claims unusable (${[
906
- !isExactNonEmptyServiceClaim(appId) ? 'appId' : null,
907
- !isExactNonEmptyServiceClaim(decoded.appName) ? 'appName' : null,
908
- !isExactNonEmptyServiceClaim(credentialId) ? 'credentialId' : null,
909
- !isExactNonEmptyServiceClaim(ownerAccountId) ? 'ownerAccountId' : null,
910
- !isOxyServiceEnvironment(environment) ? 'environment' : null,
911
- !Array.isArray(decoded.scopes) ? 'scopes' : null,
912
- ].filter((field) => field !== null).join(', ') || 'scopes'})`,
913
- status: 401,
914
- });
915
- if (optional) {
916
- req.userId = null;
917
- req.user = null;
918
- return next();
919
- }
920
- const error = { error: 'INVALID_SERVICE_TOKEN', message: 'Invalid service token: missing required claims', code: 'INVALID_SERVICE_TOKEN', status: 401 };
921
- if (onError) return onError(error);
922
- return res.status(401).json(error);
923
- }
924
-
925
- const tier: ServiceApp['tier'] = decoded.tier === 'internal' ? 'internal' : 'external';
926
-
927
- // Read delegated user ID from header
928
- const oxyUserIdRaw = req.headers['x-oxy-user-id'];
929
- const oxyUserId = isExactNonEmptyServiceClaim(oxyUserIdRaw) ? oxyUserIdRaw : null;
930
- if (oxyUserIdRaw !== undefined && oxyUserId === null) {
931
- recordRefusal(req, {
932
- code: 'INVALID_SERVICE_TOKEN_CLAIMS',
933
- stage: 'service-token',
934
- reason: 'X-Oxy-User-Id is not an exact non-empty id',
935
- status: 401,
936
- });
937
- const error = {
938
- error: 'INVALID_SERVICE_TOKEN_CLAIMS',
939
- message: 'Delegated user id must be an exact non-empty id',
940
- code: 'INVALID_SERVICE_TOKEN_CLAIMS',
941
- status: 401,
942
- };
943
- if (onError) return onError(error);
944
- return res.status(401).json(error);
945
- }
946
-
947
- // One of Oxy's own applications acts for a user without a grant:
948
- // inside the ecosystem that is trust, not consent. It still acts
949
- // with the USER's authority only — what that user may do is for the
950
- // receiving service to check.
951
- if (oxyUserId && tier === 'internal') {
952
- req.userId = oxyUserId;
953
- req.user = { id: oxyUserId } as User;
954
- req.serviceActingAs = { userId: oxyUserId, scopes: [] };
955
- } else if (oxyUserId) {
956
- // C3: an EXTERNAL service may only act as a user when an explicit
957
- // ServiceActingAs grant exists for that (appId, userId) pair.
958
- // Without the grant we MUST refuse — silently attaching
959
- // `req.userId = oxyUserId` would let any service impersonate
960
- // any user simply by setting the header.
961
- const grant = await oxyInstance.verifyServiceActingAs(appId, oxyUserId);
962
- if (!grant || !grant.authorized) {
963
- logger.warn('[oxy.auth] Service token rejected — no delegation grant', {
964
- component: 'auth',
965
- method: 'auth.serviceToken',
966
- appId,
967
- attemptedUserId: oxyUserId,
968
- });
969
- // A verifier with no service credentials of its own cannot
970
- // reach the verify endpoint at all, so `null` here can mean
971
- // "no grant" OR "this host cannot ask". Both refuse, and both
972
- // are worth naming on the request.
973
- recordRefusal(req, {
974
- code: 'SERVICE_ACTING_AS_UNAUTHORIZED',
975
- stage: 'service-token',
976
- reason: `No delegation grant for app ${appId} acting as ${oxyUserId} (or this verifier could not reach the grant check)`,
977
- status: 403,
978
- });
979
- const error = {
980
- error: 'SERVICE_ACTING_AS_UNAUTHORIZED',
981
- message: 'Service not authorized to act as this user',
982
- code: 'SERVICE_ACTING_AS_UNAUTHORIZED',
983
- status: 403,
984
- };
985
- if (onError) return onError(error);
986
- return res.status(403).json(error);
987
- }
988
-
989
- // ATTRIBUTION ONLY. `req.userId` answers "on whose behalf", never
990
- // "who pays": the billing principal stays `req.serviceApp
991
- // .ownerAccountId`, which this branch does not touch. Read it
992
- // through `getOxyBillingPrincipal` (`@oxy.so/core/server`), whose
993
- // return type a user id cannot satisfy (ADR 0007).
994
- req.userId = oxyUserId;
995
- req.user = { id: oxyUserId } as User;
996
- req.serviceActingAs = { userId: oxyUserId, scopes: grant.scopes };
997
- } else {
998
- // No X-Oxy-User-Id means the service is acting as itself.
999
- req.userId = null;
1000
- req.user = null;
1001
- }
1002
-
1003
- req.accessToken = token;
1004
- req.serviceApp = {
1005
- appId,
1006
- appName: decoded.appName,
1007
- credentialId,
1008
- ownerAccountId,
1009
- scopes: Array.isArray(decoded.scopes) ? decoded.scopes : [],
1010
- environment,
1011
- tier,
1012
- };
1013
-
1014
- if (debug) {
1015
- logger.debug(`[oxy.auth] Service token OK app=${decoded.appName} delegateUser=${oxyUserId || '(none)'}`, {
1016
- component: 'auth',
1017
- method: 'auth.serviceToken',
1018
- });
1019
- }
1020
-
1021
- return next();
1022
- }
1023
-
1024
- // The CLAIMED user id. Never trusted as an identity — it is only ever
1025
- // compared against the id the validated session resolves to.
1026
- const claimedUserId = readStringClaim(decoded.userId) ?? readStringClaim(decoded.id);
1027
- if (!claimedUserId) {
1028
- recordRefusal(req, {
1029
- code: 'INVALID_TOKEN_PAYLOAD',
1030
- stage: 'token',
1031
- reason: 'Token carries no usable user id claim',
1032
- status: 401,
1033
- });
1034
- if (optional) {
1035
- req.userId = null;
1036
- req.user = null;
1037
- return next();
1038
- }
1039
-
1040
- const error = {
1041
- error: 'INVALID_TOKEN_PAYLOAD',
1042
- message: 'Token missing user ID',
1043
- code: 'INVALID_TOKEN_PAYLOAD',
1044
- status: 401
1045
- };
1046
- if (onError) return onError(error);
1047
- return res.status(401).json(error);
1048
- }
1049
-
1050
- // Check token expiration locally first (fast path)
1051
- // Reject tokens at exact expiry second (use <=)
1052
- if (decoded.exp && decoded.exp <= Math.floor(Date.now() / 1000)) {
1053
- recordRefusal(req, {
1054
- code: 'TOKEN_EXPIRED',
1055
- stage: 'token',
1056
- reason: 'User access token expired',
1057
- status: 401,
1058
- });
1059
- if (optional) {
1060
- req.userId = null;
1061
- req.user = null;
1062
- return next();
1063
- }
1064
-
1065
- const error = {
1066
- error: 'TOKEN_EXPIRED',
1067
- message: 'Token expired',
1068
- code: 'TOKEN_EXPIRED',
1069
- status: 401
1070
- };
1071
- if (onError) return onError(error);
1072
- return res.status(401).json(error);
1073
- }
1074
-
1075
- // A server-validated session is MANDATORY for a user token. The JWT
1076
- // signature is not verified on this path, so a bare decoded token
1077
- // proves nothing: without the session round-trip a forged token could
1078
- // claim any user id. Mirrors `authSocket()`, which has always
1079
- // required this.
1080
- const sessionId = readStringClaim(decoded.sessionId);
1081
- if (!sessionId) {
1082
- recordRefusal(req, {
1083
- code: 'SESSION_REQUIRED',
1084
- stage: 'token',
1085
- reason: 'User access token is not bound to a session',
1086
- status: 401,
1087
- });
1088
- if (optional) {
1089
- req.userId = null;
1090
- req.user = null;
1091
- return next();
1092
- }
1093
-
1094
- const error = {
1095
- error: 'SESSION_REQUIRED',
1096
- message: 'Access token is not bound to a session',
1097
- code: 'SESSION_REQUIRED',
1098
- status: 401
1099
- };
1100
- if (onError) return onError(error);
1101
- return res.status(401).json(error);
1102
- }
1103
-
1104
- // Validate the token against the Oxy API. This proves the session is
1105
- // real and unrevoked, AND yields the identity it belongs to.
1106
- try {
1107
- const validationResult = await oxyInstance.validateSession(sessionId, {
1108
- useHeaderValidation: true,
1109
- });
1110
-
1111
- if (!validationResult || !validationResult.valid || !validationResult.user) {
1112
- recordRefusal(req, {
1113
- code: 'INVALID_SESSION',
1114
- stage: 'session',
1115
- reason: 'Session is invalid, revoked or expired',
1116
- status: 401,
1117
- });
1118
- if (optional) {
1119
- req.userId = null;
1120
- req.user = null;
1121
- return next();
1122
- }
1123
-
1124
- const error = {
1125
- error: 'INVALID_SESSION',
1126
- message: 'Session invalid or expired',
1127
- code: 'INVALID_SESSION',
1128
- status: 401
1129
- };
1130
- if (onError) return onError(error);
1131
- return res.status(401).json(error);
1132
- }
1133
-
1134
- // The session — not the token — is the source of truth for identity.
1135
- const validatedUserId = getUserIdentityId(validationResult.user);
1136
- if (!validatedUserId) {
1137
- recordRefusal(req, {
1138
- code: 'INVALID_SESSION',
1139
- stage: 'session',
1140
- reason: 'Session did not resolve to a usable identity',
1141
- status: 401,
1142
- });
1143
- if (optional) {
1144
- req.userId = null;
1145
- req.user = null;
1146
- return next();
1147
- }
1148
-
1149
- const error = {
1150
- error: 'INVALID_SESSION',
1151
- message: 'Session did not resolve to a usable identity',
1152
- code: 'INVALID_SESSION',
1153
- status: 401
1154
- };
1155
- if (onError) return onError(error);
1156
- return res.status(401).json(error);
1157
- }
1158
-
1159
- if (validatedUserId !== claimedUserId) {
1160
- // Session-id/claim confusion: the caller presented a live session
1161
- // that belongs to somebody else. Worth a warning — it has no
1162
- // benign cause. Ids only; never the token or the payload.
1163
- logger.warn('[oxy.auth] Token rejected — claimed user does not own the session', {
1164
- component: 'auth',
1165
- method: 'auth',
1166
- claimedUserId,
1167
- validatedUserId,
1168
- });
1169
- recordRefusal(req, {
1170
- code: 'SESSION_USER_MISMATCH',
1171
- stage: 'session',
1172
- reason: 'Token user claim does not own the presented session',
1173
- status: 401,
1174
- });
1175
-
1176
- if (optional) {
1177
- req.userId = null;
1178
- req.user = null;
1179
- return next();
1180
- }
1181
-
1182
- const error = {
1183
- error: 'SESSION_USER_MISMATCH',
1184
- message: 'Token user does not match the session',
1185
- code: 'SESSION_USER_MISMATCH',
1186
- status: 401
1187
- };
1188
- if (onError) return onError(error);
1189
- return res.status(401).json(error);
1190
- }
1191
-
1192
- req.userId = validatedUserId;
1193
- req.accessToken = token;
1194
- req.sessionId = sessionId;
1195
- // Session validation already returned the full user, so `loadUser`
1196
- // costs no extra round-trip.
1197
- req.user = loadUser ? validationResult.user : ({ id: validatedUserId } as User);
1198
-
1199
- if (debug) {
1200
- logger.debug(`[oxy.auth] OK user=${validatedUserId} session=${sessionId}`, {
1201
- component: 'auth',
1202
- method: 'auth',
1203
- });
1204
- }
1205
-
1206
- return next();
1207
- } catch (validationError) {
1208
- recordRefusal(req, {
1209
- code: 'SESSION_VALIDATION_ERROR',
1210
- stage: 'session',
1211
- // Name and transport code only. The message of a failed
1212
- // `validateSession` can carry the request URL, and that URL
1213
- // contains the session id — which is a credential.
1214
- reason: `Session validation call failed (${describeErrorSafely(validationError)})`,
1215
- status: 401,
1216
- });
1217
- if (debug) {
1218
- logger.debug('[oxy.auth] Session validation failed', {
1219
- component: 'auth',
1220
- method: 'auth',
1221
- }, validationError);
1222
- }
1223
-
1224
- if (optional) {
1225
- req.userId = null;
1226
- req.user = null;
1227
- return next();
1228
- }
1229
-
1230
- const error = {
1231
- error: 'SESSION_VALIDATION_ERROR',
1232
- message: 'Session validation failed',
1233
- code: 'SESSION_VALIDATION_ERROR',
1234
- status: 401
1235
- };
1236
- if (onError) return onError(error);
1237
- return res.status(401).json(error);
1238
- }
1239
- } catch (error) {
1240
- const handled = oxyInstance.handleError(error) as Error & {
1241
- code?: string;
1242
- status?: number;
1243
- details?: Record<string, unknown>;
1244
- };
1245
- const apiError: ApiError = {
1246
- message: handled.message || 'Authentication error',
1247
- code: handled.code ?? 'AUTH_ERROR',
1248
- status: handled.status ?? 500,
1249
- details: handled.details,
1250
- };
1251
-
1252
- if (debug) {
1253
- logger.debug('[oxy.auth] Error', {
1254
- component: 'auth',
1255
- method: 'auth',
1256
- }, apiError);
1257
- }
1258
-
1259
- if (onError) return onError(apiError);
1260
- return res.status(apiError.status).json(apiError);
1261
- }
1262
- };
1263
- }
1264
-
1265
- /**
1266
- * Socket.IO authentication middleware factory
1267
- *
1268
- * Returns a middleware function for Socket.IO that validates JWT tokens
1269
- * from the handshake auth object and attaches user data to the socket.
1270
- *
1271
- * Uses `jwtDecode()` + API session validation (same rationale as `auth()`).
1272
- *
1273
- * @example
1274
- * ```typescript
1275
- * import { OxyServices } from '@oxy.so/core';
1276
- * import { Server } from 'socket.io';
1277
- *
1278
- * const oxy = new OxyServices({ baseURL: 'https://api.oxy.so' });
1279
- * const io = new Server(server);
1280
- *
1281
- * // Authenticate all socket connections
1282
- * io.use(oxy.authSocket());
1283
- *
1284
- * io.on('connection', (socket) => {
1285
- * console.log('Authenticated user:', socket.data.userId);
1286
- * });
1287
- * ```
1288
- */
1289
- authSocket(options: { debug?: boolean } = {}) {
1290
- const { debug = false } = options;
1291
- // Cross-mixin method access typed via the same structural subset.
1292
- const oxyInstance = this as unknown as OxyAuthInstance;
1293
-
1294
- return async (socket: SocketLike, next: (err?: Error) => void) => {
1295
- try {
1296
- const token = socket.handshake?.auth?.token;
1297
-
1298
- if (!token) {
1299
- return next(new Error('Authentication required'));
1300
- }
1301
-
1302
- let decoded: JwtPayload;
1303
- try {
1304
- decoded = jwtDecode<JwtPayload>(token);
1305
- } catch (decodeError) {
1306
- if (debug) {
1307
- logger.debug('[oxy.authSocket] Token decode failed', {
1308
- component: 'auth',
1309
- method: 'authSocket',
1310
- }, decodeError);
1311
- }
1312
- return next(new Error('Invalid token'));
1313
- }
1314
-
1315
- const claimedUserId = readStringClaim(decoded.userId) ?? readStringClaim(decoded.id);
1316
- if (!claimedUserId) {
1317
- return next(new Error('Invalid token payload'));
1318
- }
1319
-
1320
- // Check expiration — reject tokens at exact expiry second (use <=)
1321
- if (decoded.exp && decoded.exp <= Math.floor(Date.now() / 1000)) {
1322
- return next(new Error('Token expired'));
1323
- }
1324
-
1325
- // A server-validated session is mandatory. A bare decoded JWT proves
1326
- // nothing — the signature is not verified here, so without a session
1327
- // round-trip a forged token could claim any user id.
1328
- const sessionId = readStringClaim(decoded.sessionId);
1329
- if (!sessionId) {
1330
- return next(new Error('Session required'));
1331
- }
1332
-
1333
- let userId = claimedUserId;
1334
- try {
1335
- const result = await oxyInstance.validateSession(sessionId, {
1336
- useHeaderValidation: true,
1337
- });
1338
- if (!result || !result.valid || !result.user) {
1339
- return next(new Error('Session invalid'));
1340
- }
1341
-
1342
- // The session is the source of truth. The client-claimed user id
1343
- // must match the server-validated identity, otherwise a valid
1344
- // session could be paired with a forged user id.
1345
- const validatedUserId = getUserIdentityId(result.user);
1346
- if (!validatedUserId || validatedUserId !== claimedUserId) {
1347
- return next(new Error('Session user mismatch'));
1348
- }
1349
-
1350
- userId = validatedUserId;
1351
- } catch (validateErr) {
1352
- if (debug) {
1353
- logger.debug('[oxy.authSocket] Session validation failed', {
1354
- component: 'auth',
1355
- method: 'authSocket',
1356
- }, validateErr);
1357
- }
1358
- return next(new Error('Session validation failed'));
1359
- }
1360
-
1361
- // Attach user data to socket. We expose BOTH `socket.data.userId`
1362
- // (the official Socket.IO data slot) and `socket.user` because
1363
- // every consumer in this ecosystem (Mention, Allo, api/server.ts)
1364
- // reads from `socket.user.id`.
1365
- socket.data = socket.data || {};
1366
- socket.data.userId = userId;
1367
- socket.data.sessionId = sessionId;
1368
- socket.data.token = token;
1369
-
1370
- socket.user = { id: userId, userId, sessionId };
1371
-
1372
- if (debug) {
1373
- logger.debug(`[oxy.authSocket] OK user=${userId}`, {
1374
- component: 'auth',
1375
- method: 'authSocket',
1376
- });
1377
- }
1378
-
1379
- next();
1380
- } catch (err) {
1381
- if (debug) {
1382
- logger.debug('[oxy.authSocket] Error', {
1383
- component: 'auth',
1384
- method: 'authSocket',
1385
- }, err);
1386
- }
1387
- next(new Error('Authentication error'));
1388
- }
1389
- };
1390
- }
1391
- /**
1392
- * Express.js middleware that only allows service tokens.
1393
- * Use this for internal-only endpoints that should not be accessible
1394
- * to regular users or API key consumers.
1395
- *
1396
- * @example
1397
- * ```typescript
1398
- * // Protect internal endpoints
1399
- * app.use('/internal', oxy.serviceAuth());
1400
- *
1401
- * app.post('/internal/trigger', (req, res) => {
1402
- * console.log('Service app:', req.serviceApp);
1403
- * console.log('Acting on behalf of user:', req.userId);
1404
- * });
1405
- * ```
1406
- */
1407
- serviceAuth(options: {
1408
- debug?: boolean;
1409
- /** Observe refusals on the service lane; forwarded straight to `auth()`. */
1410
- onRefusal?: (refusal: OxyAuthRefusal) => void;
1411
- /** @deprecated Oxy-API-only HS256 transition; external verifiers use JWKS. */
1412
- jwtSecret?: string;
1413
- serviceTokenJwksUrl?: string;
1414
- expectedIssuer?: string;
1415
- expectedAudience?: string;
1416
- } = {}) {
1417
- const innerAuth = this.auth({ ...options });
1418
-
1419
- return async (req: AuthReq, res: AuthRes, next: AuthNext) => {
1420
- await innerAuth(req, res, () => {
1421
- if (!req.serviceApp) {
1422
- return res.status(403).json({
1423
- error: 'Service token required',
1424
- message: 'This endpoint is only accessible to internal services',
1425
- code: 'SERVICE_TOKEN_REQUIRED',
1426
- });
1427
- }
1428
- next();
1429
- });
1430
- };
1431
- }
1432
-
1433
- /**
1434
- * Express.js middleware that enforces a specific service-token scope.
1435
- *
1436
- * Mount AFTER `auth()` / `serviceAuth()` — relies on `req.serviceApp` and
1437
- * (when delegation is in effect) `req.serviceActingAs.scopes`. App-only
1438
- * service requests require the app scope. Delegated user requests require
1439
- * BOTH the app scope and the per-user delegation scope.
1440
- *
1441
- * The intersection is the point, not a redundancy, because the two scope
1442
- * lists answer different questions and neither implies the other:
1443
- *
1444
- * `serviceApp.scopes` what the PLATFORM allows this application to do
1445
- * (credential ∩ application ceiling, at mint time)
1446
- * `serviceActingAs.scopes` what THIS USER allowed it to do (`app_grants`)
1447
- *
1448
- * Requiring only the app scope would let an application do to a user
1449
- * something that user never consented to; requiring only the grant would let
1450
- * a user hand an application authority staff never gave it, so a revoked
1451
- * platform scope would keep working for every user who had already
1452
- * consented. Effective authority is the intersection, and this is where it
1453
- * is taken.
1454
- *
1455
- * Requests authenticated as a regular user (no service token) are rejected
1456
- * with 403 — scope-protected endpoints are service-to-service by design.
1457
- *
1458
- * @example
1459
- * ```typescript
1460
- * app.use(
1461
- * '/internal/files',
1462
- * oxy.serviceAuth(),
1463
- * oxy.requireScope('files:write'),
1464
- * );
1465
- * ```
1466
- */
1467
- requireScope(scope: string) {
1468
- if (typeof scope !== 'string' || scope.length === 0) {
1469
- throw new Error('requireScope: scope must be a non-empty string');
1470
- }
1471
-
1472
- return (req: AuthReq, res: AuthRes, next: AuthNext): void => {
1473
- const appScopes = req.serviceApp?.scopes ?? [];
1474
- const delegatedScopes = req.serviceActingAs?.scopes ?? [];
1475
-
1476
- if (!req.serviceApp) {
1477
- res.status(403).json({
1478
- error: 'SERVICE_TOKEN_REQUIRED',
1479
- message: 'Scope-protected endpoint requires a service token',
1480
- code: 'SERVICE_TOKEN_REQUIRED',
1481
- status: 403,
1482
- });
1483
- return;
1484
- }
1485
-
1486
- // Oxy's own applications are trusted app to app; scopes are the
1487
- // external lane.
1488
- if (req.serviceApp.tier === 'internal') {
1489
- next();
1490
- return;
1491
- }
1492
-
1493
- const appHasScope = appScopes.includes(scope);
1494
- const delegationHasScope = delegatedScopes.includes(scope);
1495
- const hasRequiredScope = req.serviceActingAs
1496
- ? appHasScope && delegationHasScope
1497
- : appHasScope;
1498
-
1499
- if (hasRequiredScope) {
1500
- next();
1501
- return;
1502
- }
1503
-
1504
- logger.warn('[oxy.auth] Service token missing required scope', {
1505
- component: 'auth',
1506
- method: 'requireScope',
1507
- appId: req.serviceApp.appId,
1508
- required: scope,
1509
- });
1510
- res.status(403).json({
1511
- error: 'INSUFFICIENT_SCOPE',
1512
- message: `Required scope '${scope}' not granted`,
1513
- code: 'INSUFFICIENT_SCOPE',
1514
- status: 403,
1515
- });
1516
- };
1517
- }
1518
- };
1519
- }
1520
-
1521
- // ---------------------------------------------------------------------------
1522
- // Service token verification helpers
1523
- // ---------------------------------------------------------------------------
1524
-
1525
- interface ServiceTokenPublicJwk {
1526
- readonly kty: 'OKP';
1527
- readonly crv: 'Ed25519';
1528
- readonly x: string;
1529
- readonly use: 'sig';
1530
- readonly alg: 'EdDSA';
1531
- readonly kid: string;
1532
- }
1533
-
1534
- function isExactNonEmptyServiceClaim(value: unknown): value is string {
1535
- return typeof value === 'string' && value.length > 0 && value.trim() === value;
1536
- }
1537
-
1538
- interface ServiceTokenJwksCache {
1539
- keys: Map<string, ServiceTokenPublicJwk>;
1540
- expiresAt: number;
1541
- lastAttemptAt: number;
1542
- pending?: Promise<void>;
1543
- }
1544
-
1545
- const JWKS_CACHE_MS = 5 * 60 * 1000;
1546
- const JWKS_UNKNOWN_KID_REFRESH_MS = 60 * 1000;
1547
- const JWKS_FETCH_TIMEOUT_MS = 5_000;
1548
- const JWKS_MAX_BYTES = 64 * 1024;
1549
- const JWKS_MAX_KEYS = 20;
1550
-
1551
- function parseJsonSegment(segment: string): Record<string, unknown> {
1552
- if (!/^[A-Za-z0-9_-]+$/.test(segment)) throw new ServiceTokenStructureError('Service token segment is not base64url');
1553
- const bytes = Buffer.from(segment, 'base64url');
1554
- if (bytes.toString('base64url') !== segment) throw new ServiceTokenStructureError('Service token segment is not canonical base64url');
1555
- try {
1556
- const value = JSON.parse(bytes.toString('utf8')) as unknown;
1557
- if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('not an object');
1558
- return value as Record<string, unknown>;
1559
- } catch {
1560
- throw new ServiceTokenStructureError('Service token segment is not a JSON object');
1561
- }
1562
- }
1563
-
1564
- function parseServiceTokenJwks(value: unknown): Map<string, ServiceTokenPublicJwk> {
1565
- if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new ServiceTokenSignatureError('Oxy JWKS is malformed');
1566
- const keys = (value as { keys?: unknown }).keys;
1567
- if (!Array.isArray(keys) || keys.length === 0 || keys.length > JWKS_MAX_KEYS) throw new ServiceTokenSignatureError('Oxy JWKS has an invalid key set');
1568
- const result = new Map<string, ServiceTokenPublicJwk>();
1569
- for (const value of keys) {
1570
- if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new ServiceTokenSignatureError('Oxy JWKS contains a malformed key');
1571
- const key = value as Record<string, unknown>;
1572
- if (
1573
- key.kty !== 'OKP'
1574
- || key.crv !== 'Ed25519'
1575
- || typeof key.x !== 'string'
1576
- || key.x.length === 0
1577
- || key.use !== 'sig'
1578
- || key.alg !== 'EdDSA'
1579
- || typeof key.kid !== 'string'
1580
- || !/^[A-Za-z0-9._-]{1,128}$/.test(key.kid)
1581
- || Object.prototype.hasOwnProperty.call(key, 'd')
1582
- || result.has(key.kid)
1583
- ) throw new ServiceTokenSignatureError('Oxy JWKS contains an unsupported or duplicate key');
1584
- const x = Buffer.from(key.x, 'base64url');
1585
- if (x.length !== 32 || x.toString('base64url') !== key.x) {
1586
- throw new ServiceTokenSignatureError('Oxy JWKS contains an invalid Ed25519 key');
1587
- }
1588
- result.set(key.kid, key as unknown as ServiceTokenPublicJwk);
1589
- }
1590
- return result;
1591
- }
1592
-
1593
- async function refreshServiceTokenJwks(url: string, cache: ServiceTokenJwksCache): Promise<void> {
1594
- if (cache.pending) return cache.pending;
1595
- cache.lastAttemptAt = Date.now();
1596
- cache.pending = (async () => {
1597
- const controller = new AbortController();
1598
- const timeout = setTimeout(() => controller.abort(), JWKS_FETCH_TIMEOUT_MS);
1599
- try {
1600
- const response = await fetch(url, {
1601
- method: 'GET',
1602
- headers: { accept: 'application/json' },
1603
- signal: controller.signal,
1604
- redirect: 'error',
1605
- });
1606
- if (!response.ok) throw new ServiceTokenSignatureError(`Oxy JWKS returned HTTP ${response.status}`);
1607
- const source = await response.text();
1608
- if (Buffer.byteLength(source, 'utf8') > JWKS_MAX_BYTES) throw new ServiceTokenSignatureError('Oxy JWKS exceeds the size limit');
1609
- cache.keys = parseServiceTokenJwks(JSON.parse(source) as unknown);
1610
- cache.expiresAt = Date.now() + JWKS_CACHE_MS;
1611
- } finally {
1612
- clearTimeout(timeout);
1613
- }
1614
- })();
1615
- try {
1616
- await cache.pending;
1617
- } finally {
1618
- cache.pending = undefined;
1619
- }
1620
- }
1621
-
1622
- async function resolveServiceTokenPublicKey(
1623
- kid: string,
1624
- url: string,
1625
- cache: ServiceTokenJwksCache,
1626
- ): Promise<ServiceTokenPublicJwk> {
1627
- const now = Date.now();
1628
- const cached = cache.keys.get(kid);
1629
- if (cached && cache.expiresAt > now) return cached;
1630
- const mayRefresh = cache.expiresAt <= now || now - cache.lastAttemptAt >= JWKS_UNKNOWN_KID_REFRESH_MS;
1631
- if (mayRefresh) {
1632
- try {
1633
- await refreshServiceTokenJwks(url, cache);
1634
- } catch {
1635
- const stillValid = cache.keys.get(kid);
1636
- if (stillValid && cache.expiresAt > Date.now()) return stillValid;
1637
- throw new ServiceTokenSignatureError('Oxy service-token key set is unavailable');
1638
- }
1639
- }
1640
- const resolved = cache.keys.get(kid);
1641
- if (!resolved || cache.expiresAt <= Date.now()) throw new ServiceTokenSignatureError('Service token signing key is unknown');
1642
- return resolved;
1643
- }
1644
-
1645
- /** Ed25519/JWKS verification with an Oxy-API-only HS256 transition. */
1646
- async function verifyServiceTokenSignature(
1647
- token: string,
1648
- options: { legacySecret?: string; jwksUrl: string; cache: ServiceTokenJwksCache },
1649
- ): Promise<void> {
1650
- const nodeCrypto = await loadNodeCrypto();
1651
- const parts = token.split('.');
1652
- if (parts.length !== 3) {
1653
- throw new ServiceTokenStructureError(`Service token must have 3 parts, got ${parts.length}`);
1654
- }
1655
- const [headerB64, payloadB64, signatureB64] = parts;
1656
- if (!headerB64 || !payloadB64 || !signatureB64) {
1657
- throw new ServiceTokenStructureError('Service token has empty segment');
1658
- }
1659
- const header = parseJsonSegment(headerB64);
1660
- if (header.alg === 'HS256') {
1661
- if (!options.legacySecret) throw new ServiceTokenConfigurationError('Legacy service token verification is not configured');
1662
- const expectedSig = nodeCrypto.createHmac('sha256', options.legacySecret)
1663
- .update(`${headerB64}.${payloadB64}`)
1664
- .digest('base64url');
1665
- const sigBuf = Buffer.from(signatureB64);
1666
- const expectedBuf = Buffer.from(expectedSig);
1667
- if (sigBuf.length !== expectedBuf.length || !nodeCrypto.timingSafeEqual(sigBuf, expectedBuf)) throw new ServiceTokenSignatureError();
1668
- return;
1669
- }
1670
- if (
1671
- Object.keys(header).length !== 3
1672
- || header.alg !== 'EdDSA'
1673
- || header.typ !== 'JWT'
1674
- || typeof header.kid !== 'string'
1675
- || !/^[A-Za-z0-9._-]{1,128}$/.test(header.kid)
1676
- ) throw new ServiceTokenStructureError('Service token JOSE header is not supported');
1677
- const jwk = await resolveServiceTokenPublicKey(header.kid, options.jwksUrl, options.cache);
1678
- let publicKey: Awaited<ReturnType<typeof nodeCrypto.createPublicKey>>;
1679
- try {
1680
- publicKey = nodeCrypto.createPublicKey({ key: jwk as unknown as JsonWebKey, format: 'jwk' });
1681
- } catch {
1682
- throw new ServiceTokenSignatureError('Service token public key is invalid');
1683
- }
1684
- const signature = Buffer.from(signatureB64, 'base64url');
1685
- if (signature.toString('base64url') !== signatureB64 || signature.length !== 64) throw new ServiceTokenStructureError('Service token signature is malformed');
1686
- if (!nodeCrypto.verify(null, Buffer.from(`${headerB64}.${payloadB64}`), publicKey, signature)) throw new ServiceTokenSignatureError();
1687
- }
1688
-
1689
- /**
1690
- * Read a JWT claim that is only usable as a non-empty string.
1691
- *
1692
- * A decoded payload is attacker-controlled JSON: a claim the type declares as
1693
- * `string` can arrive as a number, an object, or `null`. Narrowing here keeps
1694
- * those values out of URL construction and identity comparison, so an
1695
- * unexpected shape becomes a 401 rather than a stringified surprise.
1696
- */
1697
- /**
1698
- * A short, log-safe description of a thrown value: its class name and, when the
1699
- * transport attached one, its `code` (`ECONNREFUSED`, `ETIMEDOUT`, `ENOTFOUND`
1700
- * …). Never the message — a failed request's message can quote the URL it was
1701
- * made against, and a session-validation URL contains the session id.
1702
- */
1703
- function describeErrorSafely(error: unknown): string {
1704
- if (!(error instanceof Error)) return typeof error;
1705
- const code = (error as { code?: unknown }).code;
1706
- return typeof code === 'string' && /^[A-Za-z0-9_]{1,40}$/.test(code)
1707
- ? `${error.name}: ${code}`
1708
- : error.name;
1709
- }
1710
-
1711
- function readStringClaim(value: unknown): string | null {
1712
- return typeof value === 'string' && value.length > 0 ? value : null;
1713
- }
1714
-
1715
- /**
1716
- * Resolve the canonical user id from a validated session's user object.
1717
- *
1718
- * The API serializer emits `id`, but some upstream shapes carry the raw Mongo
1719
- * `_id` instead. We accept either, but only a non-empty string — anything else
1720
- * means the validated identity is unusable and the caller must reject.
1721
- */
1722
- function getUserIdentityId(user: User): string | null {
1723
- const candidate = (user as { id?: unknown; _id?: unknown }).id
1724
- ?? (user as { id?: unknown; _id?: unknown })._id;
1725
- return typeof candidate === 'string' && candidate.length > 0 ? candidate : null;
1726
- }
1727
-
1728
- /**
1729
- * Verify that a decoded service-token payload carries the expected `aud`,
1730
- * `iss`, and `type` claims. Throws `ServiceTokenClaimError` on mismatch.
1731
- * This is the defence against the H4 vulnerability where a recovery / 2FA /
1732
- * access token signed by the same shared secret could be replayed as a
1733
- * service token because no claim binding existed.
1734
- */
1735
- function verifyServiceTokenClaims(
1736
- decoded: JwtPayload,
1737
- expected: { audience: string; issuer: string },
1738
- ): void {
1739
- if (decoded.type !== 'service') {
1740
- throw new ServiceTokenClaimError(`Service token has unexpected type '${String(decoded.type)}'`);
1741
- }
1742
- if (decoded.iss !== expected.issuer) {
1743
- throw new ServiceTokenClaimError(`Service token issuer mismatch: expected '${expected.issuer}', got '${String(decoded.iss)}'`);
1744
- }
1745
- const aud = decoded.aud;
1746
- if (Array.isArray(aud)) {
1747
- if (!aud.includes(expected.audience)) {
1748
- throw new ServiceTokenClaimError(`Service token audience does not include '${expected.audience}'`);
1749
- }
1750
- } else if (aud !== expected.audience) {
1751
- throw new ServiceTokenClaimError(`Service token audience mismatch: expected '${expected.audience}', got '${String(aud)}'`);
1752
- }
1753
- }
1754
-
1755
- // ---------------------------------------------------------------------------
1756
- // Local request/response/socket typing
1757
- //
1758
- // Express's types are an optional peer (we don't want to take a hard dep on
1759
- // `@types/express` from a platform-agnostic SDK). The structural subset below
1760
- // captures everything this middleware actually touches, so consumers get type
1761
- // checking without us coupling to Express's full surface.
1762
- // ---------------------------------------------------------------------------
1763
-
1764
- interface AuthReq {
1765
- method?: string;
1766
- path?: string;
1767
- headers: Record<string, string | string[] | undefined>;
1768
- query?: Record<string, unknown>;
1769
- userId?: string | null;
1770
- user?: User | null;
1771
- accessToken?: string;
1772
- sessionId?: string | null;
1773
- serviceApp?: ServiceApp;
1774
- serviceActingAs?: { userId: string; scopes: string[] };
1775
- oxyAuthRefusal?: OxyAuthRefusal;
1776
- }
1777
-
1778
- interface AuthRes {
1779
- status(code: number): AuthRes;
1780
- json(body: unknown): unknown;
1781
- }
1782
-
1783
- type AuthNext = (err?: unknown) => void;
1784
-
1785
- interface SocketLike {
1786
- handshake?: { auth?: { token?: string } };
1787
- data?: Record<string, unknown>;
1788
- user?: { id: string; userId: string; sessionId?: string | null };
1789
- }
1790
-
1791
- interface OxyAuthInstance {
1792
- verifyServiceActingAs(appId: string, userId: string): Promise<ServiceActingAsVerification | null>;
1793
- getServiceToken(apiKey?: string, apiSecret?: string): Promise<string>;
1794
- validateSession(
1795
- sessionId: string,
1796
- options?: { deviceFingerprint?: string; useHeaderValidation?: boolean },
1797
- ): Promise<{
1798
- valid: boolean;
1799
- user?: User;
1800
- [key: string]: unknown;
1801
- } | null>;
1802
- handleError(error: unknown): Error;
1803
- }