@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
@@ -0,0 +1,1520 @@
1
+ /**
2
+ * The Express and Socket.IO middleware `OxyServer` mounts
3
+ * (`server.middleware.auth()`, `.socket()`, `.service()`, `.requireScope()`),
4
+ * and the Ed25519 service-token and account-event verification they share.
5
+ *
6
+ * Node only; reachable solely from `@oxy.so/core/server`.
7
+ */
8
+ import { jwtDecode } from 'jwt-decode';
9
+ import type { JsonWebKey } from 'node:crypto';
10
+ import type { ApiError, User } from '../models/interfaces';
11
+ import { loadNodeCrypto } from '@oxy.so/protocol';
12
+ import { logger } from '../logger';
13
+ import { toOxyApiError } from '../OxyServices.errors';
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
+ export 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 ServiceTokenClaimError extends Error {
236
+ constructor(message: string) {
237
+ super(message);
238
+ this.name = 'ServiceTokenClaimError';
239
+ }
240
+ }
241
+
242
+ function isOxyServiceEnvironment(value: unknown): value is OxyServiceEnvironment {
243
+ return (
244
+ typeof value === 'string' &&
245
+ (OXY_SERVICE_ENVIRONMENTS as readonly string[]).includes(value)
246
+ );
247
+ }
248
+
249
+ /**
250
+ * Options for `server.middleware.auth()`.
251
+ */
252
+ export interface AuthMiddlewareOptions {
253
+ /** Enable debug logging (default: false) */
254
+ debug?: boolean;
255
+ /** Custom error handler - receives error object, can return response */
256
+ onError?: (error: ApiError) => unknown;
257
+ /** Load full user profile from API (default: false for performance) */
258
+ loadUser?: boolean;
259
+ /** Optional auth - attach user if token present but don't block (default: false) */
260
+ optional?: boolean;
261
+ /**
262
+ * Called whenever a PRESENTED credential is refused, on the optional path as
263
+ * well as the blocking one. Runs before the response (if any) and after
264
+ * `req.oxyAuthRefusal` is set, so a host can raise its own alert or carry the
265
+ * code into its request log. Throwing from it is swallowed — an observer must
266
+ * not be able to turn a refusal into a 500.
267
+ *
268
+ * Refusal is about a credential that was offered and rejected: a request with
269
+ * NO `Authorization` header is not refused and does not reach this.
270
+ */
271
+ onRefusal?: (refusal: OxyAuthRefusal) => void;
272
+ /**
273
+ * Public JWKS endpoint used for Ed25519 service-token verification. Defaults
274
+ * to `/.well-known/jwks.json` on this Oxy client's configured API origin.
275
+ */
276
+ serviceTokenJwksUrl?: string;
277
+ /**
278
+ * Expected JWT issuer. Defaults to `'oxy-auth'`. Override only if you run
279
+ * a private fork of the Oxy auth server under a different `iss` claim.
280
+ */
281
+ expectedIssuer?: string;
282
+ /**
283
+ * Expected JWT audience. Defaults to `'oxy-api'`. Override only if your
284
+ * private fork mints tokens for a different audience.
285
+ */
286
+ expectedAudience?: string;
287
+ }
288
+
289
+
290
+ /**
291
+ * What the middleware needs from the server it is mounted on. `OxyServer`
292
+ * builds it; every member is resolved at call time, so a test can spy on the
293
+ * server's own methods.
294
+ */
295
+ export interface OxyMiddlewareHost {
296
+ readonly baseURL: string;
297
+ readonly jwksCache: ServiceTokenJwksCache;
298
+ validateSession(
299
+ sessionId: string,
300
+ options?: { deviceFingerprint?: string; useHeaderValidation?: boolean },
301
+ ): Promise<{ valid: boolean; user?: User } | null>;
302
+ verifyActingAs(appId: string, userId: string): Promise<ServiceActingAsVerification | null>;
303
+ }
304
+
305
+ /** Build the middleware set for one server. See `OxyServer.middleware`. */
306
+ export function createOxyMiddleware(host: OxyMiddlewareHost) {
307
+ /**
308
+ * Express.js authentication middleware
309
+ *
310
+ * Validates JWT tokens against the Oxy API and attaches user data to requests.
311
+ * Uses server-side session validation for security (not just JWT decode).
312
+ *
313
+ * **Design note — jwtDecode vs jwt.verify:**
314
+ * This middleware uses `jwtDecode()` (decode-only, NO signature check) for
315
+ * user tokens, because third-party apps mounting `server.middleware.auth()` do not hold
316
+ * the Oxy signing secret. **Every claim in a user token is therefore
317
+ * attacker-controlled and proves nothing on its own.** The identity comes
318
+ * from somewhere else entirely:
319
+ * - A user token MUST carry a `sessionId`. That session is validated
320
+ * server-side on every request via `session.validate()`, and the user id
321
+ * is read off the VALIDATED SESSION — never off the token. A token whose
322
+ * `userId` claim disagrees with the session is refused
323
+ * (`SESSION_USER_MISMATCH`); a token with no `sessionId` at all is
324
+ * refused outright (`SESSION_REQUIRED`). There is no local-claims path.
325
+ * - Service tokens (type: 'service') ARE stateless, so they use Ed25519
326
+ * verification against Oxy's public JWKS and are additionally checked
327
+ * for `aud`, `iss`, `type`, time, attribution and scope claims. The
328
+ * algorithm is pinned to EdDSA and never read from the token: an HS256,
329
+ * `none` or any other JOSE header is refused before any key lookup.
330
+ * - The backend's own `authMiddleware` uses `jwt.verify()` because it has
331
+ * direct access to `ACCESS_TOKEN_SECRET`.
332
+ *
333
+ * **Why session-less user tokens are refused rather than trusted:**
334
+ * every user access token the Oxy API issues carries a `sessionId` (see
335
+ * `packages/api/src/utils/sessionUtils.ts`, `generateSessionTokens` — the
336
+ * only mint site for user tokens, including the OAuth code exchange). So
337
+ * refusing session-less user tokens costs nothing legitimate, while
338
+ * accepting them let anyone authenticate as anyone by hand-rolling a JWT
339
+ * with a `userId` claim and a garbage signature.
340
+ *
341
+ * **Why the claimed user id is cross-checked against the session:**
342
+ * `GET /session/validate/:sessionId` is UNAUTHENTICATED and does not bind
343
+ * the bearer token — it returns whoever owns the session id it was handed.
344
+ * Trusting the token's `userId` claim after a successful validation would
345
+ * therefore let a caller holding ANY live session id (their own, for
346
+ * instance) pair it with a forged `userId` and be trusted as that user.
347
+ * `authSocket()` has always cross-checked this; the HTTP middleware now
348
+ * does too.
349
+ *
350
+ * **Service-token delegation (X-Oxy-User-Id):**
351
+ * When a service token is accompanied by `X-Oxy-User-Id`, the SDK calls
352
+ * `verifyActingAs(appId, userId)` to confirm an explicit delegation
353
+ * grant exists before attaching `req.userId`. A missing/expired grant
354
+ * results in a 403 — there is no fail-open path.
355
+ *
356
+ * @example
357
+ * ```typescript
358
+ * import { OxyServer } from '@oxy.so/core/server';
359
+ *
360
+ * const server = new OxyServer({ baseURL: 'https://api.oxy.so' });
361
+ *
362
+ * // Protect all routes under /protected
363
+ * app.use('/protected', server.middleware.auth());
364
+ *
365
+ * // Access user in route handler
366
+ * app.get('/protected/me', (req, res) => {
367
+ * res.json({ userId: req.userId, user: req.user });
368
+ * });
369
+ *
370
+ * // Load full user profile from API
371
+ * app.use('/admin', server.middleware.auth({ loadUser: true }));
372
+ *
373
+ * // Optional auth - attach user if present, don't block if absent
374
+ * app.use('/public', server.middleware.auth({ optional: true }));
375
+ *
376
+ * // Require a specific scope on a service-token-protected route
377
+ * app.use('/internal/files', server.middleware.service(), server.middleware.requireScope('files:write'));
378
+ * ```
379
+ *
380
+ * @param options Optional configuration
381
+ * @returns Express middleware function
382
+ */
383
+ function auth(options: AuthMiddlewareOptions = {}) {
384
+ const {
385
+ debug = false,
386
+ onError,
387
+ onRefusal,
388
+ loadUser = false,
389
+ optional = false,
390
+ serviceTokenJwksUrl = new URL('/.well-known/jwks.json', host.baseURL).toString(),
391
+ expectedIssuer = OXY_JWT_ISSUER,
392
+ expectedAudience = OXY_JWT_AUDIENCE,
393
+ } = options;
394
+
395
+ /**
396
+ * Make a refusal observable to the HOST, without telling the client
397
+ * anything it is not already told.
398
+ *
399
+ * Called at the top of every branch that rejects a PRESENTED credential,
400
+ * including the ones `optional` then swallows — those are the expensive
401
+ * ones, because they leave no trace anywhere else. The response bodies
402
+ * below are untouched by design: what a client sees does not change.
403
+ *
404
+ * `warn`, not `debug`: a debug-gated reason is only there for whoever
405
+ * already suspects this middleware, and the failure mode this exists for
406
+ * is the one where nobody does. The volume is bounded by refusals, and a
407
+ * host drowning in them has a fault worth the lines.
408
+ */
409
+ const recordRefusal = (
410
+ req: AuthReq,
411
+ refusal: { code: string; stage: OxyAuthRefusal['stage']; reason: string; status: number },
412
+ ): void => {
413
+ const recorded: OxyAuthRefusal = { ...refusal, optional };
414
+ req.oxyAuthRefusal = recorded;
415
+ logger.warn(`[oxy.auth] refused ${recorded.code}: ${recorded.reason}`, {
416
+ component: 'auth',
417
+ method: 'auth',
418
+ code: recorded.code,
419
+ stage: recorded.stage,
420
+ reason: recorded.reason,
421
+ status: recorded.status,
422
+ // Says whether the client will see this status or the host's own
423
+ // generic answer — the difference that made the JWKS outage invisible.
424
+ optional: recorded.optional,
425
+ path: req.path,
426
+ });
427
+ if (onRefusal) {
428
+ try {
429
+ onRefusal(recorded);
430
+ } catch (observerError) {
431
+ logger.warn('[oxy.auth] onRefusal observer threw', {
432
+ component: 'auth',
433
+ method: 'auth',
434
+ }, observerError);
435
+ }
436
+ }
437
+ };
438
+
439
+ // Return an async middleware function
440
+ return async (req: AuthReq, res: AuthRes, next: AuthNext) => {
441
+ try {
442
+ // Extract token from Authorization header.
443
+ // Node/Express normalizes `Authorization` to a string; we guard
444
+ // against the (legal but unusual) string[] case anyway.
445
+ const rawAuthHeader = req.headers.authorization;
446
+ const authHeader = Array.isArray(rawAuthHeader) ? rawAuthHeader[0] : rawAuthHeader;
447
+ const token = authHeader?.startsWith('Bearer ') ? authHeader.substring(7) : null;
448
+
449
+ if (debug) {
450
+ logger.debug(`[oxy.auth] ${req.method} ${req.path} | token: ${!!token}`, {
451
+ component: 'auth',
452
+ method: 'auth',
453
+ });
454
+ }
455
+
456
+ if (!token) {
457
+ if (optional) {
458
+ req.userId = null;
459
+ req.user = null;
460
+ return next();
461
+ }
462
+
463
+ const error = {
464
+ error: 'MISSING_TOKEN',
465
+ message: 'Access token required',
466
+ code: 'MISSING_TOKEN',
467
+ status: 401
468
+ };
469
+ if (onError) return onError(error);
470
+ return res.status(401).json(error);
471
+ }
472
+
473
+ // Decode token to extract claims
474
+ let decoded: JwtPayload;
475
+ try {
476
+ decoded = jwtDecode<JwtPayload>(token);
477
+ } catch (decodeError) {
478
+ recordRefusal(req, {
479
+ code: 'INVALID_TOKEN_FORMAT',
480
+ stage: 'token',
481
+ reason: 'Bearer credential is not a decodable JWT',
482
+ status: 401,
483
+ });
484
+ if (debug) {
485
+ logger.debug('[oxy.auth] Token decode failed', {
486
+ component: 'auth',
487
+ method: 'auth',
488
+ }, decodeError);
489
+ }
490
+ if (optional) {
491
+ req.userId = null;
492
+ req.user = null;
493
+ return next();
494
+ }
495
+
496
+ const error = {
497
+ error: 'INVALID_TOKEN_FORMAT',
498
+ message: 'Invalid token format',
499
+ code: 'INVALID_TOKEN_FORMAT',
500
+ status: 401
501
+ };
502
+ if (onError) return onError(error);
503
+ return res.status(401).json(error);
504
+ }
505
+
506
+ // Handle service tokens (internal service-to-service auth)
507
+ // Service tokens are stateless JWTs with type: 'service' — requires signature verification
508
+ if (decoded.type === 'service') {
509
+ // Verify JWT signature, then audience / issuer / type / appId claims.
510
+ //
511
+ // Signature verification uses Node crypto rather than
512
+ // `jsonwebtoken` because this file also ships into RN/web bundles.
513
+ // The middleware itself runs on Node hosts; `loadNodeCrypto` is
514
+ // per-platform, so Metro never bundles a Node built-in reference.
515
+ try {
516
+ await verifyServiceTokenSignature(token, {
517
+ jwksUrl: serviceTokenJwksUrl,
518
+ cache: host.jwksCache,
519
+ });
520
+ verifyServiceTokenClaims(decoded, {
521
+ audience: expectedAudience,
522
+ issuer: expectedIssuer,
523
+ });
524
+ } catch (verifyError) {
525
+ // Structure + signature + claim errors all map to 401. Anything
526
+ // else (e.g. Node crypto failing to load on a misconfigured host)
527
+ // genuinely IS a 500.
528
+ if (
529
+ verifyError instanceof ServiceTokenStructureError ||
530
+ verifyError instanceof ServiceTokenSignatureError ||
531
+ verifyError instanceof ServiceTokenClaimError
532
+ ) {
533
+ const code = verifyError instanceof ServiceTokenClaimError
534
+ ? 'INVALID_SERVICE_TOKEN_CLAIMS'
535
+ : 'INVALID_SERVICE_TOKEN';
536
+ // The SDK's own message is the whole diagnostic value here —
537
+ // "signing key is unknown" (rotated/unpublished kid), "key set
538
+ // is unavailable" (JWKS empty, unreachable or malformed) and
539
+ // "audience mismatch" are three different outages that answer
540
+ // the client identically.
541
+ recordRefusal(req, {
542
+ code,
543
+ stage: 'service-token',
544
+ reason: `${verifyError.name}: ${verifyError.message}`,
545
+ status: 401,
546
+ });
547
+ if (debug) {
548
+ logger.debug('[oxy.auth] Service token rejected', {
549
+ component: 'auth',
550
+ method: 'auth.serviceToken',
551
+ reason: verifyError.name,
552
+ detail: verifyError.message,
553
+ });
554
+ }
555
+ if (optional) {
556
+ req.userId = null;
557
+ req.user = null;
558
+ return next();
559
+ }
560
+ const error = {
561
+ error: code,
562
+ message: verifyError.message,
563
+ code,
564
+ status: 401,
565
+ };
566
+ if (onError) return onError(error);
567
+ return res.status(401).json(error);
568
+ }
569
+
570
+ logger.error('[oxy.auth] Unexpected error during service token verification', verifyError, {
571
+ component: 'auth',
572
+ method: 'auth.serviceToken',
573
+ });
574
+ const error = {
575
+ error: 'AUTH_INTERNAL_ERROR',
576
+ message: 'Internal authentication error',
577
+ code: 'AUTH_INTERNAL_ERROR',
578
+ status: 500,
579
+ };
580
+ if (onError) return onError(error);
581
+ return res.status(500).json(error);
582
+ }
583
+
584
+ // Check expiration — reject tokens at exact expiry second (use <=)
585
+ const now = Math.floor(Date.now() / 1000);
586
+ if (!Number.isInteger(decoded.exp) || (decoded.exp as number) <= now) {
587
+ recordRefusal(req, {
588
+ code: 'TOKEN_EXPIRED',
589
+ stage: 'service-token',
590
+ reason: Number.isInteger(decoded.exp)
591
+ ? 'Service token expired'
592
+ : 'Service token has no integer exp claim',
593
+ status: 401,
594
+ });
595
+ if (optional) {
596
+ req.userId = null;
597
+ req.user = null;
598
+ return next();
599
+ }
600
+ const error = { error: 'TOKEN_EXPIRED', message: 'Service token expired', code: 'TOKEN_EXPIRED', status: 401 };
601
+ if (onError) return onError(error);
602
+ return res.status(401).json(error);
603
+ }
604
+ if (decoded.nbf !== undefined && (!Number.isInteger(decoded.nbf) || decoded.nbf > now)) {
605
+ recordRefusal(req, {
606
+ code: 'INVALID_SERVICE_TOKEN_CLAIMS',
607
+ stage: 'service-token',
608
+ reason: 'Service token is not yet valid (nbf)',
609
+ status: 401,
610
+ });
611
+ const error = { error: 'INVALID_SERVICE_TOKEN_CLAIMS', message: 'Service token is not yet valid', code: 'INVALID_SERVICE_TOKEN_CLAIMS', status: 401 };
612
+ if (onError) return onError(error);
613
+ return res.status(401).json(error);
614
+ }
615
+
616
+ // Validate required service token fields. All of them are
617
+ // required, `ownerAccountId` included: an optional billing
618
+ // principal is one fallback away from being resolved from the
619
+ // delegated user, which is the exact confusion ADR 0007 forbids.
620
+ const appId = decoded.appId;
621
+ const credentialId = decoded.credentialId;
622
+ const ownerAccountId = decoded.ownerAccountId;
623
+ const environment = decoded.environment;
624
+ if (
625
+ !isExactNonEmptyServiceClaim(appId) ||
626
+ !isExactNonEmptyServiceClaim(decoded.appName) ||
627
+ !isExactNonEmptyServiceClaim(credentialId) ||
628
+ !isExactNonEmptyServiceClaim(ownerAccountId) ||
629
+ !isOxyServiceEnvironment(environment)
630
+ || !Array.isArray(decoded.scopes)
631
+ || !decoded.scopes.every((scope) => typeof scope === 'string' && scope.length > 0 && scope === scope.trim())
632
+ || new Set(decoded.scopes).size !== decoded.scopes.length
633
+ ) {
634
+ recordRefusal(req, {
635
+ code: 'INVALID_SERVICE_TOKEN',
636
+ stage: 'service-token',
637
+ // Names the field rather than its value: an exact-match claim
638
+ // failing on invisible whitespace reads as "present" in a log
639
+ // that only says which claims were missing.
640
+ reason: `Service token claims unusable (${[
641
+ !isExactNonEmptyServiceClaim(appId) ? 'appId' : null,
642
+ !isExactNonEmptyServiceClaim(decoded.appName) ? 'appName' : null,
643
+ !isExactNonEmptyServiceClaim(credentialId) ? 'credentialId' : null,
644
+ !isExactNonEmptyServiceClaim(ownerAccountId) ? 'ownerAccountId' : null,
645
+ !isOxyServiceEnvironment(environment) ? 'environment' : null,
646
+ !Array.isArray(decoded.scopes) ? 'scopes' : null,
647
+ ].filter((field) => field !== null).join(', ') || 'scopes'})`,
648
+ status: 401,
649
+ });
650
+ if (optional) {
651
+ req.userId = null;
652
+ req.user = null;
653
+ return next();
654
+ }
655
+ const error = { error: 'INVALID_SERVICE_TOKEN', message: 'Invalid service token: missing required claims', code: 'INVALID_SERVICE_TOKEN', status: 401 };
656
+ if (onError) return onError(error);
657
+ return res.status(401).json(error);
658
+ }
659
+
660
+ const tier: ServiceApp['tier'] = decoded.tier === 'internal' ? 'internal' : 'external';
661
+
662
+ // Read delegated user ID from header
663
+ const oxyUserIdRaw = req.headers['x-oxy-user-id'];
664
+ const oxyUserId = isExactNonEmptyServiceClaim(oxyUserIdRaw) ? oxyUserIdRaw : null;
665
+ if (oxyUserIdRaw !== undefined && oxyUserId === null) {
666
+ recordRefusal(req, {
667
+ code: 'INVALID_SERVICE_TOKEN_CLAIMS',
668
+ stage: 'service-token',
669
+ reason: 'X-Oxy-User-Id is not an exact non-empty id',
670
+ status: 401,
671
+ });
672
+ const error = {
673
+ error: 'INVALID_SERVICE_TOKEN_CLAIMS',
674
+ message: 'Delegated user id must be an exact non-empty id',
675
+ code: 'INVALID_SERVICE_TOKEN_CLAIMS',
676
+ status: 401,
677
+ };
678
+ if (onError) return onError(error);
679
+ return res.status(401).json(error);
680
+ }
681
+
682
+ // One of Oxy's own applications acts for a user without a grant:
683
+ // inside the ecosystem that is trust, not consent. It still acts
684
+ // with the USER's authority only — what that user may do is for the
685
+ // receiving service to check.
686
+ if (oxyUserId && tier === 'internal') {
687
+ req.userId = oxyUserId;
688
+ req.user = { id: oxyUserId } as User;
689
+ req.serviceActingAs = { userId: oxyUserId, scopes: [] };
690
+ } else if (oxyUserId) {
691
+ // C3: an EXTERNAL service may only act as a user when an explicit
692
+ // ServiceActingAs grant exists for that (appId, userId) pair.
693
+ // Without the grant we MUST refuse — silently attaching
694
+ // `req.userId = oxyUserId` would let any service impersonate
695
+ // any user simply by setting the header.
696
+ const grant = await host.verifyActingAs(appId, oxyUserId);
697
+ if (!grant || !grant.authorized) {
698
+ logger.warn('[oxy.auth] Service token rejected — no delegation grant', {
699
+ component: 'auth',
700
+ method: 'auth.serviceToken',
701
+ appId,
702
+ attemptedUserId: oxyUserId,
703
+ });
704
+ // A verifier with no service credentials of its own cannot
705
+ // reach the verify endpoint at all, so `null` here can mean
706
+ // "no grant" OR "this host cannot ask". Both refuse, and both
707
+ // are worth naming on the request.
708
+ recordRefusal(req, {
709
+ code: 'SERVICE_ACTING_AS_UNAUTHORIZED',
710
+ stage: 'service-token',
711
+ reason: `No delegation grant for app ${appId} acting as ${oxyUserId} (or this verifier could not reach the grant check)`,
712
+ status: 403,
713
+ });
714
+ const error = {
715
+ error: 'SERVICE_ACTING_AS_UNAUTHORIZED',
716
+ message: 'Service not authorized to act as this user',
717
+ code: 'SERVICE_ACTING_AS_UNAUTHORIZED',
718
+ status: 403,
719
+ };
720
+ if (onError) return onError(error);
721
+ return res.status(403).json(error);
722
+ }
723
+
724
+ // ATTRIBUTION ONLY. `req.userId` answers "on whose behalf", never
725
+ // "who pays": the billing principal stays `req.serviceApp
726
+ // .ownerAccountId`, which this branch does not touch. Read it
727
+ // through `getOxyBillingPrincipal` (`@oxy.so/core/server`), whose
728
+ // return type a user id cannot satisfy (ADR 0007).
729
+ req.userId = oxyUserId;
730
+ req.user = { id: oxyUserId } as User;
731
+ req.serviceActingAs = { userId: oxyUserId, scopes: grant.scopes };
732
+ } else {
733
+ // No X-Oxy-User-Id means the service is acting as itself.
734
+ req.userId = null;
735
+ req.user = null;
736
+ }
737
+
738
+ req.accessToken = token;
739
+ req.serviceApp = {
740
+ appId,
741
+ appName: decoded.appName,
742
+ credentialId,
743
+ ownerAccountId,
744
+ scopes: Array.isArray(decoded.scopes) ? decoded.scopes : [],
745
+ environment,
746
+ tier,
747
+ };
748
+
749
+ if (debug) {
750
+ logger.debug(`[oxy.auth] Service token OK app=${decoded.appName} delegateUser=${oxyUserId || '(none)'}`, {
751
+ component: 'auth',
752
+ method: 'auth.serviceToken',
753
+ });
754
+ }
755
+
756
+ return next();
757
+ }
758
+
759
+ // The CLAIMED user id. Never trusted as an identity — it is only ever
760
+ // compared against the id the validated session resolves to.
761
+ const claimedUserId = readStringClaim(decoded.userId) ?? readStringClaim(decoded.id);
762
+ if (!claimedUserId) {
763
+ recordRefusal(req, {
764
+ code: 'INVALID_TOKEN_PAYLOAD',
765
+ stage: 'token',
766
+ reason: 'Token carries no usable user id claim',
767
+ status: 401,
768
+ });
769
+ if (optional) {
770
+ req.userId = null;
771
+ req.user = null;
772
+ return next();
773
+ }
774
+
775
+ const error = {
776
+ error: 'INVALID_TOKEN_PAYLOAD',
777
+ message: 'Token missing user ID',
778
+ code: 'INVALID_TOKEN_PAYLOAD',
779
+ status: 401
780
+ };
781
+ if (onError) return onError(error);
782
+ return res.status(401).json(error);
783
+ }
784
+
785
+ // Check token expiration locally first (fast path)
786
+ // Reject tokens at exact expiry second (use <=)
787
+ if (decoded.exp && decoded.exp <= Math.floor(Date.now() / 1000)) {
788
+ recordRefusal(req, {
789
+ code: 'TOKEN_EXPIRED',
790
+ stage: 'token',
791
+ reason: 'User access token expired',
792
+ status: 401,
793
+ });
794
+ if (optional) {
795
+ req.userId = null;
796
+ req.user = null;
797
+ return next();
798
+ }
799
+
800
+ const error = {
801
+ error: 'TOKEN_EXPIRED',
802
+ message: 'Token expired',
803
+ code: 'TOKEN_EXPIRED',
804
+ status: 401
805
+ };
806
+ if (onError) return onError(error);
807
+ return res.status(401).json(error);
808
+ }
809
+
810
+ // A server-validated session is MANDATORY for a user token. The JWT
811
+ // signature is not verified on this path, so a bare decoded token
812
+ // proves nothing: without the session round-trip a forged token could
813
+ // claim any user id. Mirrors `authSocket()`, which has always
814
+ // required this.
815
+ const sessionId = readStringClaim(decoded.sessionId);
816
+ if (!sessionId) {
817
+ recordRefusal(req, {
818
+ code: 'SESSION_REQUIRED',
819
+ stage: 'token',
820
+ reason: 'User access token is not bound to a session',
821
+ status: 401,
822
+ });
823
+ if (optional) {
824
+ req.userId = null;
825
+ req.user = null;
826
+ return next();
827
+ }
828
+
829
+ const error = {
830
+ error: 'SESSION_REQUIRED',
831
+ message: 'Access token is not bound to a session',
832
+ code: 'SESSION_REQUIRED',
833
+ status: 401
834
+ };
835
+ if (onError) return onError(error);
836
+ return res.status(401).json(error);
837
+ }
838
+
839
+ // Validate the token against the Oxy API. This proves the session is
840
+ // real and unrevoked, AND yields the identity it belongs to.
841
+ try {
842
+ const validationResult = await host.validateSession(sessionId, {
843
+ useHeaderValidation: true,
844
+ });
845
+
846
+ if (!validationResult || !validationResult.valid || !validationResult.user) {
847
+ recordRefusal(req, {
848
+ code: 'INVALID_SESSION',
849
+ stage: 'session',
850
+ reason: 'Session is invalid, revoked or expired',
851
+ status: 401,
852
+ });
853
+ if (optional) {
854
+ req.userId = null;
855
+ req.user = null;
856
+ return next();
857
+ }
858
+
859
+ const error = {
860
+ error: 'INVALID_SESSION',
861
+ message: 'Session invalid or expired',
862
+ code: 'INVALID_SESSION',
863
+ status: 401
864
+ };
865
+ if (onError) return onError(error);
866
+ return res.status(401).json(error);
867
+ }
868
+
869
+ // The session — not the token — is the source of truth for identity.
870
+ const validatedUserId = getUserIdentityId(validationResult.user);
871
+ if (!validatedUserId) {
872
+ recordRefusal(req, {
873
+ code: 'INVALID_SESSION',
874
+ stage: 'session',
875
+ reason: 'Session did not resolve to a usable identity',
876
+ status: 401,
877
+ });
878
+ if (optional) {
879
+ req.userId = null;
880
+ req.user = null;
881
+ return next();
882
+ }
883
+
884
+ const error = {
885
+ error: 'INVALID_SESSION',
886
+ message: 'Session did not resolve to a usable identity',
887
+ code: 'INVALID_SESSION',
888
+ status: 401
889
+ };
890
+ if (onError) return onError(error);
891
+ return res.status(401).json(error);
892
+ }
893
+
894
+ if (validatedUserId !== claimedUserId) {
895
+ // Session-id/claim confusion: the caller presented a live session
896
+ // that belongs to somebody else. Worth a warning — it has no
897
+ // benign cause. Ids only; never the token or the payload.
898
+ logger.warn('[oxy.auth] Token rejected — claimed user does not own the session', {
899
+ component: 'auth',
900
+ method: 'auth',
901
+ claimedUserId,
902
+ validatedUserId,
903
+ });
904
+ recordRefusal(req, {
905
+ code: 'SESSION_USER_MISMATCH',
906
+ stage: 'session',
907
+ reason: 'Token user claim does not own the presented session',
908
+ status: 401,
909
+ });
910
+
911
+ if (optional) {
912
+ req.userId = null;
913
+ req.user = null;
914
+ return next();
915
+ }
916
+
917
+ const error = {
918
+ error: 'SESSION_USER_MISMATCH',
919
+ message: 'Token user does not match the session',
920
+ code: 'SESSION_USER_MISMATCH',
921
+ status: 401
922
+ };
923
+ if (onError) return onError(error);
924
+ return res.status(401).json(error);
925
+ }
926
+
927
+ req.userId = validatedUserId;
928
+ req.accessToken = token;
929
+ req.sessionId = sessionId;
930
+ // Session validation already returned the full user, so `loadUser`
931
+ // costs no extra round-trip.
932
+ req.user = loadUser ? validationResult.user : ({ id: validatedUserId } as User);
933
+
934
+ if (debug) {
935
+ logger.debug(`[oxy.auth] OK user=${validatedUserId} session=${sessionId}`, {
936
+ component: 'auth',
937
+ method: 'auth',
938
+ });
939
+ }
940
+
941
+ return next();
942
+ } catch (validationError) {
943
+ recordRefusal(req, {
944
+ code: 'SESSION_VALIDATION_ERROR',
945
+ stage: 'session',
946
+ // Name and transport code only. The message of a failed
947
+ // `validateSession` can carry the request URL, and that URL
948
+ // contains the session id — which is a credential.
949
+ reason: `Session validation call failed (${describeErrorSafely(validationError)})`,
950
+ status: 401,
951
+ });
952
+ if (debug) {
953
+ logger.debug('[oxy.auth] Session validation failed', {
954
+ component: 'auth',
955
+ method: 'auth',
956
+ }, validationError);
957
+ }
958
+
959
+ if (optional) {
960
+ req.userId = null;
961
+ req.user = null;
962
+ return next();
963
+ }
964
+
965
+ const error = {
966
+ error: 'SESSION_VALIDATION_ERROR',
967
+ message: 'Session validation failed',
968
+ code: 'SESSION_VALIDATION_ERROR',
969
+ status: 401
970
+ };
971
+ if (onError) return onError(error);
972
+ return res.status(401).json(error);
973
+ }
974
+ } catch (error) {
975
+ const handled = toOxyApiError(error) as Error & {
976
+ code?: string;
977
+ status?: number;
978
+ details?: Record<string, unknown>;
979
+ };
980
+ const apiError: ApiError = {
981
+ message: handled.message || 'Authentication error',
982
+ code: handled.code ?? 'AUTH_ERROR',
983
+ status: handled.status ?? 500,
984
+ details: handled.details,
985
+ };
986
+
987
+ if (debug) {
988
+ logger.debug('[oxy.auth] Error', {
989
+ component: 'auth',
990
+ method: 'auth',
991
+ }, apiError);
992
+ }
993
+
994
+ if (onError) return onError(apiError);
995
+ return res.status(apiError.status).json(apiError);
996
+ }
997
+ };
998
+ }
999
+
1000
+ /**
1001
+ * Socket.IO authentication middleware factory
1002
+ *
1003
+ * Returns a middleware function for Socket.IO that validates JWT tokens
1004
+ * from the handshake auth object and attaches user data to the socket.
1005
+ *
1006
+ * Uses `jwtDecode()` + API session validation (same rationale as `auth()`).
1007
+ *
1008
+ * @example
1009
+ * ```typescript
1010
+ * import { OxyServer } from '@oxy.so/core/server';
1011
+ * import { Server } from 'socket.io';
1012
+ *
1013
+ * const server = new OxyServer({ baseURL: 'https://api.oxy.so' });
1014
+ * const io = new Server(server);
1015
+ *
1016
+ * // Authenticate all socket connections
1017
+ * io.use(server.middleware.socket());
1018
+ *
1019
+ * io.on('connection', (socket) => {
1020
+ * console.log('Authenticated user:', socket.data.userId);
1021
+ * });
1022
+ * ```
1023
+ */
1024
+ function socket(options: { debug?: boolean } = {}) {
1025
+ const { debug = false } = options;
1026
+
1027
+ return async (socket: SocketLike, next: (err?: Error) => void) => {
1028
+ try {
1029
+ const token = socket.handshake?.auth?.token;
1030
+
1031
+ if (!token) {
1032
+ return next(new Error('Authentication required'));
1033
+ }
1034
+
1035
+ let decoded: JwtPayload;
1036
+ try {
1037
+ decoded = jwtDecode<JwtPayload>(token);
1038
+ } catch (decodeError) {
1039
+ if (debug) {
1040
+ logger.debug('[oxy.authSocket] Token decode failed', {
1041
+ component: 'auth',
1042
+ method: 'authSocket',
1043
+ }, decodeError);
1044
+ }
1045
+ return next(new Error('Invalid token'));
1046
+ }
1047
+
1048
+ const claimedUserId = readStringClaim(decoded.userId) ?? readStringClaim(decoded.id);
1049
+ if (!claimedUserId) {
1050
+ return next(new Error('Invalid token payload'));
1051
+ }
1052
+
1053
+ // Check expiration — reject tokens at exact expiry second (use <=)
1054
+ if (decoded.exp && decoded.exp <= Math.floor(Date.now() / 1000)) {
1055
+ return next(new Error('Token expired'));
1056
+ }
1057
+
1058
+ // A server-validated session is mandatory. A bare decoded JWT proves
1059
+ // nothing — the signature is not verified here, so without a session
1060
+ // round-trip a forged token could claim any user id.
1061
+ const sessionId = readStringClaim(decoded.sessionId);
1062
+ if (!sessionId) {
1063
+ return next(new Error('Session required'));
1064
+ }
1065
+
1066
+ let userId = claimedUserId;
1067
+ try {
1068
+ const result = await host.validateSession(sessionId, {
1069
+ useHeaderValidation: true,
1070
+ });
1071
+ if (!result || !result.valid || !result.user) {
1072
+ return next(new Error('Session invalid'));
1073
+ }
1074
+
1075
+ // The session is the source of truth. The client-claimed user id
1076
+ // must match the server-validated identity, otherwise a valid
1077
+ // session could be paired with a forged user id.
1078
+ const validatedUserId = getUserIdentityId(result.user);
1079
+ if (!validatedUserId || validatedUserId !== claimedUserId) {
1080
+ return next(new Error('Session user mismatch'));
1081
+ }
1082
+
1083
+ userId = validatedUserId;
1084
+ } catch (validateErr) {
1085
+ if (debug) {
1086
+ logger.debug('[oxy.authSocket] Session validation failed', {
1087
+ component: 'auth',
1088
+ method: 'authSocket',
1089
+ }, validateErr);
1090
+ }
1091
+ return next(new Error('Session validation failed'));
1092
+ }
1093
+
1094
+ // Attach user data to socket. We expose BOTH `socket.data.userId`
1095
+ // (the official Socket.IO data slot) and `socket.user` because
1096
+ // every consumer in this ecosystem (Mention, Allo, api/server.ts)
1097
+ // reads from `socket.user.id`.
1098
+ socket.data = socket.data || {};
1099
+ socket.data.userId = userId;
1100
+ socket.data.sessionId = sessionId;
1101
+ socket.data.token = token;
1102
+
1103
+ socket.user = { id: userId, userId, sessionId };
1104
+
1105
+ if (debug) {
1106
+ logger.debug(`[oxy.authSocket] OK user=${userId}`, {
1107
+ component: 'auth',
1108
+ method: 'authSocket',
1109
+ });
1110
+ }
1111
+
1112
+ next();
1113
+ } catch (err) {
1114
+ if (debug) {
1115
+ logger.debug('[oxy.authSocket] Error', {
1116
+ component: 'auth',
1117
+ method: 'authSocket',
1118
+ }, err);
1119
+ }
1120
+ next(new Error('Authentication error'));
1121
+ }
1122
+ };
1123
+ }
1124
+ /**
1125
+ * Express.js middleware that only allows service tokens.
1126
+ * Use this for internal-only endpoints that should not be accessible
1127
+ * to regular users or API key consumers.
1128
+ *
1129
+ * @example
1130
+ * ```typescript
1131
+ * // Protect internal endpoints
1132
+ * app.use('/internal', server.middleware.service());
1133
+ *
1134
+ * app.post('/internal/trigger', (req, res) => {
1135
+ * console.log('Service app:', req.serviceApp);
1136
+ * console.log('Acting on behalf of user:', req.userId);
1137
+ * });
1138
+ * ```
1139
+ */
1140
+ function service(options: {
1141
+ debug?: boolean;
1142
+ /** Observe refusals on the service lane; forwarded straight to `auth()`. */
1143
+ onRefusal?: (refusal: OxyAuthRefusal) => void;
1144
+ serviceTokenJwksUrl?: string;
1145
+ expectedIssuer?: string;
1146
+ expectedAudience?: string;
1147
+ } = {}) {
1148
+ const innerAuth = auth({ ...options });
1149
+
1150
+ return async (req: AuthReq, res: AuthRes, next: AuthNext) => {
1151
+ await innerAuth(req, res, () => {
1152
+ if (!req.serviceApp) {
1153
+ return res.status(403).json({
1154
+ error: 'Service token required',
1155
+ message: 'This endpoint is only accessible to internal services',
1156
+ code: 'SERVICE_TOKEN_REQUIRED',
1157
+ });
1158
+ }
1159
+ next();
1160
+ });
1161
+ };
1162
+ }
1163
+
1164
+ /**
1165
+ * Express.js middleware that enforces a specific service-token scope.
1166
+ *
1167
+ * Mount AFTER `auth()` / `serviceAuth()` — relies on `req.serviceApp` and
1168
+ * (when delegation is in effect) `req.serviceActingAs.scopes`. App-only
1169
+ * service requests require the app scope. Delegated user requests require
1170
+ * BOTH the app scope and the per-user delegation scope.
1171
+ *
1172
+ * The intersection is the point, not a redundancy, because the two scope
1173
+ * lists answer different questions and neither implies the other:
1174
+ *
1175
+ * `serviceApp.scopes` what the PLATFORM allows this application to do
1176
+ * (credential ∩ application ceiling, at mint time)
1177
+ * `serviceActingAs.scopes` what THIS USER allowed it to do (`app_grants`)
1178
+ *
1179
+ * Requiring only the app scope would let an application do to a user
1180
+ * something that user never consented to; requiring only the grant would let
1181
+ * a user hand an application authority staff never gave it, so a revoked
1182
+ * platform scope would keep working for every user who had already
1183
+ * consented. Effective authority is the intersection, and this is where it
1184
+ * is taken.
1185
+ *
1186
+ * Requests authenticated as a regular user (no service token) are rejected
1187
+ * with 403 — scope-protected endpoints are service-to-service by design.
1188
+ *
1189
+ * @example
1190
+ * ```typescript
1191
+ * app.use(
1192
+ * '/internal/files',
1193
+ * server.middleware.service(),
1194
+ * server.middleware.requireScope('files:write'),
1195
+ * );
1196
+ * ```
1197
+ */
1198
+ function requireScope(scope: string) {
1199
+ if (typeof scope !== 'string' || scope.length === 0) {
1200
+ throw new Error('requireScope: scope must be a non-empty string');
1201
+ }
1202
+
1203
+ return (req: AuthReq, res: AuthRes, next: AuthNext): void => {
1204
+ const appScopes = req.serviceApp?.scopes ?? [];
1205
+ const delegatedScopes = req.serviceActingAs?.scopes ?? [];
1206
+
1207
+ if (!req.serviceApp) {
1208
+ res.status(403).json({
1209
+ error: 'SERVICE_TOKEN_REQUIRED',
1210
+ message: 'Scope-protected endpoint requires a service token',
1211
+ code: 'SERVICE_TOKEN_REQUIRED',
1212
+ status: 403,
1213
+ });
1214
+ return;
1215
+ }
1216
+
1217
+ // Oxy's own applications are trusted app to app; scopes are the
1218
+ // external lane.
1219
+ if (req.serviceApp.tier === 'internal') {
1220
+ next();
1221
+ return;
1222
+ }
1223
+
1224
+ const appHasScope = appScopes.includes(scope);
1225
+ const delegationHasScope = delegatedScopes.includes(scope);
1226
+ const hasRequiredScope = req.serviceActingAs
1227
+ ? appHasScope && delegationHasScope
1228
+ : appHasScope;
1229
+
1230
+ if (hasRequiredScope) {
1231
+ next();
1232
+ return;
1233
+ }
1234
+
1235
+ logger.warn('[oxy.auth] Service token missing required scope', {
1236
+ component: 'auth',
1237
+ method: 'requireScope',
1238
+ appId: req.serviceApp.appId,
1239
+ required: scope,
1240
+ });
1241
+ res.status(403).json({
1242
+ error: 'INSUFFICIENT_SCOPE',
1243
+ message: `Required scope '${scope}' not granted`,
1244
+ code: 'INSUFFICIENT_SCOPE',
1245
+ status: 403,
1246
+ });
1247
+ };
1248
+ }
1249
+
1250
+ return { auth, socket, service, requireScope };
1251
+ }
1252
+
1253
+ /** The middleware set `OxyServer.middleware` exposes. */
1254
+ export type OxyMiddleware = ReturnType<typeof createOxyMiddleware>;
1255
+
1256
+
1257
+ // ---------------------------------------------------------------------------
1258
+ // Service token verification helpers
1259
+ // ---------------------------------------------------------------------------
1260
+
1261
+ export interface ServiceTokenPublicJwk {
1262
+ readonly kty: 'OKP';
1263
+ readonly crv: 'Ed25519';
1264
+ readonly x: string;
1265
+ readonly use: 'sig';
1266
+ readonly alg: 'EdDSA';
1267
+ readonly kid: string;
1268
+ }
1269
+
1270
+ function isExactNonEmptyServiceClaim(value: unknown): value is string {
1271
+ return typeof value === 'string' && value.length > 0 && value.trim() === value;
1272
+ }
1273
+
1274
+ export interface ServiceTokenJwksCache {
1275
+ keys: Map<string, ServiceTokenPublicJwk>;
1276
+ expiresAt: number;
1277
+ lastAttemptAt: number;
1278
+ pending?: Promise<void>;
1279
+ }
1280
+
1281
+ const JWKS_CACHE_MS = 5 * 60 * 1000;
1282
+ const JWKS_UNKNOWN_KID_REFRESH_MS = 60 * 1000;
1283
+ const JWKS_FETCH_TIMEOUT_MS = 5_000;
1284
+ const JWKS_MAX_BYTES = 64 * 1024;
1285
+ const JWKS_MAX_KEYS = 20;
1286
+
1287
+ export function parseJsonSegment(segment: string): Record<string, unknown> {
1288
+ if (!/^[A-Za-z0-9_-]+$/.test(segment)) throw new ServiceTokenStructureError('Service token segment is not base64url');
1289
+ const bytes = Buffer.from(segment, 'base64url');
1290
+ if (bytes.toString('base64url') !== segment) throw new ServiceTokenStructureError('Service token segment is not canonical base64url');
1291
+ try {
1292
+ const value = JSON.parse(bytes.toString('utf8')) as unknown;
1293
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('not an object');
1294
+ return value as Record<string, unknown>;
1295
+ } catch {
1296
+ throw new ServiceTokenStructureError('Service token segment is not a JSON object');
1297
+ }
1298
+ }
1299
+
1300
+ function parseServiceTokenJwks(value: unknown): Map<string, ServiceTokenPublicJwk> {
1301
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new ServiceTokenSignatureError('Oxy JWKS is malformed');
1302
+ const keys = (value as { keys?: unknown }).keys;
1303
+ if (!Array.isArray(keys) || keys.length === 0 || keys.length > JWKS_MAX_KEYS) throw new ServiceTokenSignatureError('Oxy JWKS has an invalid key set');
1304
+ const result = new Map<string, ServiceTokenPublicJwk>();
1305
+ for (const value of keys) {
1306
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new ServiceTokenSignatureError('Oxy JWKS contains a malformed key');
1307
+ const key = value as Record<string, unknown>;
1308
+ if (
1309
+ key.kty !== 'OKP'
1310
+ || key.crv !== 'Ed25519'
1311
+ || typeof key.x !== 'string'
1312
+ || key.x.length === 0
1313
+ || key.use !== 'sig'
1314
+ || key.alg !== 'EdDSA'
1315
+ || typeof key.kid !== 'string'
1316
+ || !/^[A-Za-z0-9._-]{1,128}$/.test(key.kid)
1317
+ || Object.prototype.hasOwnProperty.call(key, 'd')
1318
+ || result.has(key.kid)
1319
+ ) throw new ServiceTokenSignatureError('Oxy JWKS contains an unsupported or duplicate key');
1320
+ const x = Buffer.from(key.x, 'base64url');
1321
+ if (x.length !== 32 || x.toString('base64url') !== key.x) {
1322
+ throw new ServiceTokenSignatureError('Oxy JWKS contains an invalid Ed25519 key');
1323
+ }
1324
+ result.set(key.kid, key as unknown as ServiceTokenPublicJwk);
1325
+ }
1326
+ return result;
1327
+ }
1328
+
1329
+ async function refreshServiceTokenJwks(url: string, cache: ServiceTokenJwksCache): Promise<void> {
1330
+ if (cache.pending) return cache.pending;
1331
+ cache.lastAttemptAt = Date.now();
1332
+ cache.pending = (async () => {
1333
+ const controller = new AbortController();
1334
+ const timeout = setTimeout(() => controller.abort(), JWKS_FETCH_TIMEOUT_MS);
1335
+ try {
1336
+ const response = await fetch(url, {
1337
+ method: 'GET',
1338
+ headers: { accept: 'application/json' },
1339
+ signal: controller.signal,
1340
+ redirect: 'error',
1341
+ });
1342
+ if (!response.ok) throw new ServiceTokenSignatureError(`Oxy JWKS returned HTTP ${response.status}`);
1343
+ const source = await response.text();
1344
+ if (Buffer.byteLength(source, 'utf8') > JWKS_MAX_BYTES) throw new ServiceTokenSignatureError('Oxy JWKS exceeds the size limit');
1345
+ cache.keys = parseServiceTokenJwks(JSON.parse(source) as unknown);
1346
+ cache.expiresAt = Date.now() + JWKS_CACHE_MS;
1347
+ } finally {
1348
+ clearTimeout(timeout);
1349
+ }
1350
+ })();
1351
+ try {
1352
+ await cache.pending;
1353
+ } finally {
1354
+ cache.pending = undefined;
1355
+ }
1356
+ }
1357
+
1358
+ export async function resolveServiceTokenPublicKey(
1359
+ kid: string,
1360
+ url: string,
1361
+ cache: ServiceTokenJwksCache,
1362
+ ): Promise<ServiceTokenPublicJwk> {
1363
+ const now = Date.now();
1364
+ const cached = cache.keys.get(kid);
1365
+ if (cached && cache.expiresAt > now) return cached;
1366
+ const mayRefresh = cache.expiresAt <= now || now - cache.lastAttemptAt >= JWKS_UNKNOWN_KID_REFRESH_MS;
1367
+ if (mayRefresh) {
1368
+ try {
1369
+ await refreshServiceTokenJwks(url, cache);
1370
+ } catch {
1371
+ const stillValid = cache.keys.get(kid);
1372
+ if (stillValid && cache.expiresAt > Date.now()) return stillValid;
1373
+ throw new ServiceTokenSignatureError('Oxy service-token key set is unavailable');
1374
+ }
1375
+ }
1376
+ const resolved = cache.keys.get(kid);
1377
+ if (!resolved || cache.expiresAt <= Date.now()) throw new ServiceTokenSignatureError('Service token signing key is unknown');
1378
+ return resolved;
1379
+ }
1380
+
1381
+ /**
1382
+ * Ed25519 verification against Oxy's published JWKS (ADR 0012). The algorithm
1383
+ * is pinned: the header must be exactly `{ alg: 'EdDSA', typ: 'JWT', kid }`,
1384
+ * so HS256, `none` and every other header is refused before any key lookup.
1385
+ */
1386
+ async function verifyServiceTokenSignature(
1387
+ token: string,
1388
+ options: { jwksUrl: string; cache: ServiceTokenJwksCache },
1389
+ ): Promise<void> {
1390
+ const nodeCrypto = await loadNodeCrypto();
1391
+ const parts = token.split('.');
1392
+ if (parts.length !== 3) {
1393
+ throw new ServiceTokenStructureError(`Service token must have 3 parts, got ${parts.length}`);
1394
+ }
1395
+ const [headerB64, payloadB64, signatureB64] = parts;
1396
+ if (!headerB64 || !payloadB64 || !signatureB64) {
1397
+ throw new ServiceTokenStructureError('Service token has empty segment');
1398
+ }
1399
+ const header = parseJsonSegment(headerB64);
1400
+ if (
1401
+ Object.keys(header).length !== 3
1402
+ || header.alg !== 'EdDSA'
1403
+ || header.typ !== 'JWT'
1404
+ || typeof header.kid !== 'string'
1405
+ || !/^[A-Za-z0-9._-]{1,128}$/.test(header.kid)
1406
+ ) throw new ServiceTokenStructureError('Service token JOSE header is not supported');
1407
+ const jwk = await resolveServiceTokenPublicKey(header.kid, options.jwksUrl, options.cache);
1408
+ let publicKey: Awaited<ReturnType<typeof nodeCrypto.createPublicKey>>;
1409
+ try {
1410
+ publicKey = nodeCrypto.createPublicKey({ key: jwk as unknown as JsonWebKey, format: 'jwk' });
1411
+ } catch {
1412
+ throw new ServiceTokenSignatureError('Service token public key is invalid');
1413
+ }
1414
+ const signature = Buffer.from(signatureB64, 'base64url');
1415
+ if (signature.toString('base64url') !== signatureB64 || signature.length !== 64) throw new ServiceTokenStructureError('Service token signature is malformed');
1416
+ if (!nodeCrypto.verify(null, Buffer.from(`${headerB64}.${payloadB64}`), publicKey, signature)) throw new ServiceTokenSignatureError();
1417
+ }
1418
+
1419
+ /**
1420
+ * Read a JWT claim that is only usable as a non-empty string.
1421
+ *
1422
+ * A decoded payload is attacker-controlled JSON: a claim the type declares as
1423
+ * `string` can arrive as a number, an object, or `null`. Narrowing here keeps
1424
+ * those values out of URL construction and identity comparison, so an
1425
+ * unexpected shape becomes a 401 rather than a stringified surprise.
1426
+ */
1427
+ /**
1428
+ * A short, log-safe description of a thrown value: its class name and, when the
1429
+ * transport attached one, its `code` (`ECONNREFUSED`, `ETIMEDOUT`, `ENOTFOUND`
1430
+ * …). Never the message — a failed request's message can quote the URL it was
1431
+ * made against, and a session-validation URL contains the session id.
1432
+ */
1433
+ function describeErrorSafely(error: unknown): string {
1434
+ if (!(error instanceof Error)) return typeof error;
1435
+ const code = (error as { code?: unknown }).code;
1436
+ return typeof code === 'string' && /^[A-Za-z0-9_]{1,40}$/.test(code)
1437
+ ? `${error.name}: ${code}`
1438
+ : error.name;
1439
+ }
1440
+
1441
+ function readStringClaim(value: unknown): string | null {
1442
+ return typeof value === 'string' && value.length > 0 ? value : null;
1443
+ }
1444
+
1445
+ /**
1446
+ * Resolve the canonical user id from a validated session's user object.
1447
+ *
1448
+ * The API serializer emits `id`, but some upstream shapes carry the raw Mongo
1449
+ * `_id` instead. We accept either, but only a non-empty string — anything else
1450
+ * means the validated identity is unusable and the caller must reject.
1451
+ */
1452
+ function getUserIdentityId(user: User): string | null {
1453
+ const candidate = (user as { id?: unknown; _id?: unknown }).id
1454
+ ?? (user as { id?: unknown; _id?: unknown })._id;
1455
+ return typeof candidate === 'string' && candidate.length > 0 ? candidate : null;
1456
+ }
1457
+
1458
+ /**
1459
+ * Verify that a decoded service-token payload carries the expected `aud`,
1460
+ * `iss`, and `type` claims. Throws `ServiceTokenClaimError` on mismatch.
1461
+ * This is the defence against the H4 vulnerability where a recovery / 2FA /
1462
+ * access token signed by the same shared secret could be replayed as a
1463
+ * service token because no claim binding existed.
1464
+ */
1465
+ function verifyServiceTokenClaims(
1466
+ decoded: JwtPayload,
1467
+ expected: { audience: string; issuer: string },
1468
+ ): void {
1469
+ if (decoded.type !== 'service') {
1470
+ throw new ServiceTokenClaimError(`Service token has unexpected type '${String(decoded.type)}'`);
1471
+ }
1472
+ if (decoded.iss !== expected.issuer) {
1473
+ throw new ServiceTokenClaimError(`Service token issuer mismatch: expected '${expected.issuer}', got '${String(decoded.iss)}'`);
1474
+ }
1475
+ const aud = decoded.aud;
1476
+ if (Array.isArray(aud)) {
1477
+ if (!aud.includes(expected.audience)) {
1478
+ throw new ServiceTokenClaimError(`Service token audience does not include '${expected.audience}'`);
1479
+ }
1480
+ } else if (aud !== expected.audience) {
1481
+ throw new ServiceTokenClaimError(`Service token audience mismatch: expected '${expected.audience}', got '${String(aud)}'`);
1482
+ }
1483
+ }
1484
+
1485
+ // ---------------------------------------------------------------------------
1486
+ // Local request/response/socket typing
1487
+ //
1488
+ // Express's types are an optional peer (we don't want to take a hard dep on
1489
+ // `@types/express` from a platform-agnostic SDK). The structural subset below
1490
+ // captures everything this middleware actually touches, so consumers get type
1491
+ // checking without us coupling to Express's full surface.
1492
+ // ---------------------------------------------------------------------------
1493
+
1494
+ interface AuthReq {
1495
+ method?: string;
1496
+ path?: string;
1497
+ headers: Record<string, string | string[] | undefined>;
1498
+ query?: Record<string, unknown>;
1499
+ userId?: string | null;
1500
+ user?: User | null;
1501
+ accessToken?: string;
1502
+ sessionId?: string | null;
1503
+ serviceApp?: ServiceApp;
1504
+ serviceActingAs?: { userId: string; scopes: string[] };
1505
+ oxyAuthRefusal?: OxyAuthRefusal;
1506
+ }
1507
+
1508
+ interface AuthRes {
1509
+ status(code: number): AuthRes;
1510
+ json(body: unknown): unknown;
1511
+ }
1512
+
1513
+ type AuthNext = (err?: unknown) => void;
1514
+
1515
+ interface SocketLike {
1516
+ handshake?: { auth?: { token?: string } };
1517
+ data?: Record<string, unknown>;
1518
+ user?: { id: string; userId: string; sessionId?: string | null };
1519
+ }
1520
+