@blazedpath/commons 0.2.2 → 0.3.1

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 (626) hide show
  1. package/README.md +4 -1
  2. package/dist/blz-base/health/index.d.ts +1 -0
  3. package/dist/blz-base/health/index.js +1 -0
  4. package/dist/blz-base/index.d.ts +108 -0
  5. package/dist/blz-base/index.js +1 -0
  6. package/dist/blz-cache/LruCache.d.ts +31 -0
  7. package/dist/blz-cache/LruCache.js +1 -0
  8. package/dist/blz-cache/index.d.ts +2 -0
  9. package/dist/blz-cache/index.js +1 -0
  10. package/dist/blz-config/index.d.ts +16 -0
  11. package/dist/blz-config/index.js +1 -0
  12. package/dist/blz-core/index.d.ts +32 -0
  13. package/dist/blz-core/index.js +1 -0
  14. package/dist/blz-cryptography/index.d.ts +2 -0
  15. package/dist/blz-cryptography/index.js +1 -0
  16. package/dist/blz-datetimes/index.d.ts +35 -0
  17. package/dist/blz-datetimes/index.js +1 -0
  18. package/dist/blz-file/fileService.d.ts +25 -0
  19. package/dist/blz-file/fileService.js +1 -0
  20. package/dist/blz-file/index.d.ts +2 -0
  21. package/dist/blz-file/index.js +1 -0
  22. package/dist/blz-file/index.test.js +1 -0
  23. package/dist/blz-file/lab.js +1 -0
  24. package/dist/blz-hazelcast/index.d.ts +25 -0
  25. package/dist/blz-hazelcast/index.js +1 -0
  26. package/dist/blz-hazelcast/lib/credentials.d.ts +10 -0
  27. package/dist/blz-hazelcast/lib/credentials.js +1 -0
  28. package/dist/blz-hazelcast/lib/credentialsFactory.d.ts +1 -0
  29. package/dist/blz-hazelcast/lib/credentialsFactory.js +1 -0
  30. package/dist/blz-hazelcast/lib/hazelcastCache.d.ts +27 -0
  31. package/dist/blz-hazelcast/lib/hazelcastCache.js +1 -0
  32. package/dist/blz-iterable/index.d.ts +49 -0
  33. package/dist/blz-iterable/index.js +1 -0
  34. package/dist/blz-json-schema/index.d.ts +1 -0
  35. package/dist/blz-json-schema/index.js +1 -0
  36. package/dist/blz-jwt/index.d.ts +12 -0
  37. package/dist/blz-jwt/index.js +1 -0
  38. package/dist/blz-kafka/index.d.ts +9 -0
  39. package/dist/blz-kafka/index.js +1 -0
  40. package/dist/blz-math/index.d.ts +22 -0
  41. package/dist/blz-math/index.js +1 -0
  42. package/dist/blz-mongodb/index.d.ts +28 -0
  43. package/dist/blz-mongodb/index.js +1 -0
  44. package/dist/blz-rds/__test__/scape.test.js +1 -0
  45. package/dist/blz-rds/blz-rds-executor.d.ts +4 -0
  46. package/dist/blz-rds/blz-rds-executor.js +1 -0
  47. package/dist/blz-rds/blz-rds-helper.d.ts +5 -0
  48. package/dist/blz-rds/blz-rds-helper.js +1 -0
  49. package/dist/blz-rds/commands/core/add.d.ts +2 -0
  50. package/dist/blz-rds/commands/core/add.js +1 -0
  51. package/dist/blz-rds/commands/core/and.d.ts +3 -0
  52. package/dist/blz-rds/commands/core/and.js +1 -0
  53. package/dist/blz-rds/commands/core/asc.d.ts +2 -0
  54. package/dist/blz-rds/commands/core/asc.js +1 -0
  55. package/dist/blz-rds/commands/core/avg.d.ts +2 -0
  56. package/dist/blz-rds/commands/core/avg.js +1 -0
  57. package/dist/blz-rds/commands/core/column-ref.d.ts +2 -0
  58. package/dist/blz-rds/commands/core/column-ref.js +1 -0
  59. package/dist/blz-rds/commands/core/count-distinct.d.ts +2 -0
  60. package/dist/blz-rds/commands/core/count-distinct.js +1 -0
  61. package/dist/blz-rds/commands/core/count.d.ts +2 -0
  62. package/dist/blz-rds/commands/core/count.js +1 -0
  63. package/dist/blz-rds/commands/core/decimal.d.ts +2 -0
  64. package/dist/blz-rds/commands/core/decimal.js +1 -0
  65. package/dist/blz-rds/commands/core/desc.d.ts +2 -0
  66. package/dist/blz-rds/commands/core/desc.js +1 -0
  67. package/dist/blz-rds/commands/core/distinct.d.ts +2 -0
  68. package/dist/blz-rds/commands/core/distinct.js +1 -0
  69. package/dist/blz-rds/commands/core/divide.d.ts +2 -0
  70. package/dist/blz-rds/commands/core/divide.js +1 -0
  71. package/dist/blz-rds/commands/core/embedded-exists.d.ts +3 -0
  72. package/dist/blz-rds/commands/core/embedded-exists.js +1 -0
  73. package/dist/blz-rds/commands/core/embedded-select.d.ts +2 -0
  74. package/dist/blz-rds/commands/core/embedded-select.js +1 -0
  75. package/dist/blz-rds/commands/core/equals.d.ts +3 -0
  76. package/dist/blz-rds/commands/core/equals.js +1 -0
  77. package/dist/blz-rds/commands/core/false.d.ts +2 -0
  78. package/dist/blz-rds/commands/core/false.js +1 -0
  79. package/dist/blz-rds/commands/core/greater-or-equal.d.ts +3 -0
  80. package/dist/blz-rds/commands/core/greater-or-equal.js +1 -0
  81. package/dist/blz-rds/commands/core/greater.d.ts +3 -0
  82. package/dist/blz-rds/commands/core/greater.js +1 -0
  83. package/dist/blz-rds/commands/core/in.d.ts +3 -0
  84. package/dist/blz-rds/commands/core/in.js +1 -0
  85. package/dist/blz-rds/commands/core/integer.d.ts +2 -0
  86. package/dist/blz-rds/commands/core/integer.js +1 -0
  87. package/dist/blz-rds/commands/core/is-not-null.d.ts +3 -0
  88. package/dist/blz-rds/commands/core/is-not-null.js +1 -0
  89. package/dist/blz-rds/commands/core/is-null-or-value.d.ts +3 -0
  90. package/dist/blz-rds/commands/core/is-null-or-value.js +1 -0
  91. package/dist/blz-rds/commands/core/is-null.d.ts +3 -0
  92. package/dist/blz-rds/commands/core/is-null.js +1 -0
  93. package/dist/blz-rds/commands/core/less-or-equal.d.ts +3 -0
  94. package/dist/blz-rds/commands/core/less-or-equal.js +1 -0
  95. package/dist/blz-rds/commands/core/less-unary.d.ts +2 -0
  96. package/dist/blz-rds/commands/core/less-unary.js +1 -0
  97. package/dist/blz-rds/commands/core/less.d.ts +3 -0
  98. package/dist/blz-rds/commands/core/less.js +1 -0
  99. package/dist/blz-rds/commands/core/like.d.ts +3 -0
  100. package/dist/blz-rds/commands/core/like.js +1 -0
  101. package/dist/blz-rds/commands/core/max.d.ts +2 -0
  102. package/dist/blz-rds/commands/core/max.js +1 -0
  103. package/dist/blz-rds/commands/core/min.d.ts +2 -0
  104. package/dist/blz-rds/commands/core/min.js +1 -0
  105. package/dist/blz-rds/commands/core/multiply.d.ts +2 -0
  106. package/dist/blz-rds/commands/core/multiply.js +1 -0
  107. package/dist/blz-rds/commands/core/not-equals.d.ts +3 -0
  108. package/dist/blz-rds/commands/core/not-equals.js +1 -0
  109. package/dist/blz-rds/commands/core/not-in.d.ts +3 -0
  110. package/dist/blz-rds/commands/core/not-in.js +1 -0
  111. package/dist/blz-rds/commands/core/not.d.ts +3 -0
  112. package/dist/blz-rds/commands/core/not.js +1 -0
  113. package/dist/blz-rds/commands/core/null.d.ts +2 -0
  114. package/dist/blz-rds/commands/core/null.js +1 -0
  115. package/dist/blz-rds/commands/core/nvl.d.ts +2 -0
  116. package/dist/blz-rds/commands/core/nvl.js +1 -0
  117. package/dist/blz-rds/commands/core/or.d.ts +3 -0
  118. package/dist/blz-rds/commands/core/or.js +1 -0
  119. package/dist/blz-rds/commands/core/parameter.d.ts +2 -0
  120. package/dist/blz-rds/commands/core/parameter.js +1 -0
  121. package/dist/blz-rds/commands/core/remainder.d.ts +2 -0
  122. package/dist/blz-rds/commands/core/remainder.js +1 -0
  123. package/dist/blz-rds/commands/core/string.d.ts +2 -0
  124. package/dist/blz-rds/commands/core/string.js +1 -0
  125. package/dist/blz-rds/commands/core/subtract.d.ts +2 -0
  126. package/dist/blz-rds/commands/core/subtract.js +1 -0
  127. package/dist/blz-rds/commands/core/sum.d.ts +2 -0
  128. package/dist/blz-rds/commands/core/sum.js +1 -0
  129. package/dist/blz-rds/commands/core/true.d.ts +2 -0
  130. package/dist/blz-rds/commands/core/true.js +1 -0
  131. package/dist/blz-rds/commands/core/tuple.d.ts +2 -0
  132. package/dist/blz-rds/commands/core/tuple.js +1 -0
  133. package/dist/blz-rds/commands/datetimes/add-days.d.ts +2 -0
  134. package/dist/blz-rds/commands/datetimes/add-days.js +1 -0
  135. package/dist/blz-rds/commands/datetimes/add-hours.d.ts +2 -0
  136. package/dist/blz-rds/commands/datetimes/add-hours.js +1 -0
  137. package/dist/blz-rds/commands/datetimes/add-milliseconds.d.ts +2 -0
  138. package/dist/blz-rds/commands/datetimes/add-milliseconds.js +1 -0
  139. package/dist/blz-rds/commands/datetimes/add-minutes.d.ts +2 -0
  140. package/dist/blz-rds/commands/datetimes/add-minutes.js +1 -0
  141. package/dist/blz-rds/commands/datetimes/add-months.d.ts +2 -0
  142. package/dist/blz-rds/commands/datetimes/add-months.js +1 -0
  143. package/dist/blz-rds/commands/datetimes/add-seconds.d.ts +2 -0
  144. package/dist/blz-rds/commands/datetimes/add-seconds.js +1 -0
  145. package/dist/blz-rds/commands/datetimes/add-years.d.ts +2 -0
  146. package/dist/blz-rds/commands/datetimes/add-years.js +1 -0
  147. package/dist/blz-rds/commands/datetimes/date-diff.d.ts +2 -0
  148. package/dist/blz-rds/commands/datetimes/date-diff.js +1 -0
  149. package/dist/blz-rds/commands/datetimes/date.d.ts +2 -0
  150. package/dist/blz-rds/commands/datetimes/date.js +1 -0
  151. package/dist/blz-rds/commands/datetimes/datetime-diff.d.ts +2 -0
  152. package/dist/blz-rds/commands/datetimes/datetime-diff.js +1 -0
  153. package/dist/blz-rds/commands/datetimes/datetime.d.ts +2 -0
  154. package/dist/blz-rds/commands/datetimes/datetime.js +1 -0
  155. package/dist/blz-rds/commands/datetimes/day.d.ts +2 -0
  156. package/dist/blz-rds/commands/datetimes/day.js +1 -0
  157. package/dist/blz-rds/commands/datetimes/hour.d.ts +2 -0
  158. package/dist/blz-rds/commands/datetimes/hour.js +1 -0
  159. package/dist/blz-rds/commands/datetimes/millisecond.d.ts +2 -0
  160. package/dist/blz-rds/commands/datetimes/millisecond.js +1 -0
  161. package/dist/blz-rds/commands/datetimes/minute.d.ts +2 -0
  162. package/dist/blz-rds/commands/datetimes/minute.js +1 -0
  163. package/dist/blz-rds/commands/datetimes/month-text.d.ts +2 -0
  164. package/dist/blz-rds/commands/datetimes/month-text.js +1 -0
  165. package/dist/blz-rds/commands/datetimes/month.d.ts +2 -0
  166. package/dist/blz-rds/commands/datetimes/month.js +1 -0
  167. package/dist/blz-rds/commands/datetimes/now.d.ts +2 -0
  168. package/dist/blz-rds/commands/datetimes/now.js +1 -0
  169. package/dist/blz-rds/commands/datetimes/second.d.ts +2 -0
  170. package/dist/blz-rds/commands/datetimes/second.js +1 -0
  171. package/dist/blz-rds/commands/datetimes/subtract-days.d.ts +2 -0
  172. package/dist/blz-rds/commands/datetimes/subtract-days.js +1 -0
  173. package/dist/blz-rds/commands/datetimes/subtract-hours.d.ts +2 -0
  174. package/dist/blz-rds/commands/datetimes/subtract-hours.js +1 -0
  175. package/dist/blz-rds/commands/datetimes/subtract-milliseconds.d.ts +2 -0
  176. package/dist/blz-rds/commands/datetimes/subtract-milliseconds.js +1 -0
  177. package/dist/blz-rds/commands/datetimes/subtract-minutes.d.ts +2 -0
  178. package/dist/blz-rds/commands/datetimes/subtract-minutes.js +1 -0
  179. package/dist/blz-rds/commands/datetimes/subtract-seconds.d.ts +2 -0
  180. package/dist/blz-rds/commands/datetimes/subtract-seconds.js +1 -0
  181. package/dist/blz-rds/commands/datetimes/time-diff.d.ts +2 -0
  182. package/dist/blz-rds/commands/datetimes/time-diff.js +1 -0
  183. package/dist/blz-rds/commands/datetimes/time.d.ts +2 -0
  184. package/dist/blz-rds/commands/datetimes/time.js +1 -0
  185. package/dist/blz-rds/commands/datetimes/today.d.ts +2 -0
  186. package/dist/blz-rds/commands/datetimes/today.js +1 -0
  187. package/dist/blz-rds/commands/datetimes/week-day-text.d.ts +2 -0
  188. package/dist/blz-rds/commands/datetimes/week-day-text.js +1 -0
  189. package/dist/blz-rds/commands/datetimes/week-day.d.ts +2 -0
  190. package/dist/blz-rds/commands/datetimes/week-day.js +1 -0
  191. package/dist/blz-rds/commands/datetimes/week.d.ts +2 -0
  192. package/dist/blz-rds/commands/datetimes/week.js +1 -0
  193. package/dist/blz-rds/commands/datetimes/year.d.ts +2 -0
  194. package/dist/blz-rds/commands/datetimes/year.js +1 -0
  195. package/dist/blz-rds/commands/math/abs.d.ts +2 -0
  196. package/dist/blz-rds/commands/math/abs.js +1 -0
  197. package/dist/blz-rds/commands/math/acos.d.ts +2 -0
  198. package/dist/blz-rds/commands/math/acos.js +1 -0
  199. package/dist/blz-rds/commands/math/asin.d.ts +2 -0
  200. package/dist/blz-rds/commands/math/asin.js +1 -0
  201. package/dist/blz-rds/commands/math/atan.d.ts +2 -0
  202. package/dist/blz-rds/commands/math/atan.js +1 -0
  203. package/dist/blz-rds/commands/math/atan2.d.ts +2 -0
  204. package/dist/blz-rds/commands/math/atan2.js +1 -0
  205. package/dist/blz-rds/commands/math/ceil.d.ts +2 -0
  206. package/dist/blz-rds/commands/math/ceil.js +1 -0
  207. package/dist/blz-rds/commands/math/cos.d.ts +2 -0
  208. package/dist/blz-rds/commands/math/cos.js +1 -0
  209. package/dist/blz-rds/commands/math/cosh.d.ts +2 -0
  210. package/dist/blz-rds/commands/math/cosh.js +1 -0
  211. package/dist/blz-rds/commands/math/exp.d.ts +2 -0
  212. package/dist/blz-rds/commands/math/exp.js +1 -0
  213. package/dist/blz-rds/commands/math/floor.d.ts +2 -0
  214. package/dist/blz-rds/commands/math/floor.js +1 -0
  215. package/dist/blz-rds/commands/math/log.d.ts +2 -0
  216. package/dist/blz-rds/commands/math/log.js +1 -0
  217. package/dist/blz-rds/commands/math/log10.d.ts +2 -0
  218. package/dist/blz-rds/commands/math/log10.js +1 -0
  219. package/dist/blz-rds/commands/math/pow.d.ts +2 -0
  220. package/dist/blz-rds/commands/math/pow.js +1 -0
  221. package/dist/blz-rds/commands/math/random.d.ts +2 -0
  222. package/dist/blz-rds/commands/math/random.js +1 -0
  223. package/dist/blz-rds/commands/math/round.d.ts +2 -0
  224. package/dist/blz-rds/commands/math/round.js +1 -0
  225. package/dist/blz-rds/commands/math/sign.d.ts +2 -0
  226. package/dist/blz-rds/commands/math/sign.js +1 -0
  227. package/dist/blz-rds/commands/math/sin.d.ts +2 -0
  228. package/dist/blz-rds/commands/math/sin.js +1 -0
  229. package/dist/blz-rds/commands/math/sinh.d.ts +2 -0
  230. package/dist/blz-rds/commands/math/sinh.js +1 -0
  231. package/dist/blz-rds/commands/math/sqrt.d.ts +2 -0
  232. package/dist/blz-rds/commands/math/sqrt.js +1 -0
  233. package/dist/blz-rds/commands/math/tan.d.ts +2 -0
  234. package/dist/blz-rds/commands/math/tan.js +1 -0
  235. package/dist/blz-rds/commands/math/tanh.d.ts +2 -0
  236. package/dist/blz-rds/commands/math/tanh.js +1 -0
  237. package/dist/blz-rds/commands/math/trunc.d.ts +2 -0
  238. package/dist/blz-rds/commands/math/trunc.js +1 -0
  239. package/dist/blz-rds/commands/strings/concat.d.ts +2 -0
  240. package/dist/blz-rds/commands/strings/concat.js +1 -0
  241. package/dist/blz-rds/commands/strings/contains.d.ts +3 -0
  242. package/dist/blz-rds/commands/strings/contains.js +1 -0
  243. package/dist/blz-rds/commands/strings/ends-with.d.ts +3 -0
  244. package/dist/blz-rds/commands/strings/ends-with.js +1 -0
  245. package/dist/blz-rds/commands/strings/index-of.d.ts +2 -0
  246. package/dist/blz-rds/commands/strings/index-of.js +1 -0
  247. package/dist/blz-rds/commands/strings/is-null-or-empty.d.ts +3 -0
  248. package/dist/blz-rds/commands/strings/is-null-or-empty.js +1 -0
  249. package/dist/blz-rds/commands/strings/is-null-or-white-space.d.ts +3 -0
  250. package/dist/blz-rds/commands/strings/is-null-or-white-space.js +1 -0
  251. package/dist/blz-rds/commands/strings/join.d.ts +2 -0
  252. package/dist/blz-rds/commands/strings/join.js +1 -0
  253. package/dist/blz-rds/commands/strings/last-index-of.d.ts +2 -0
  254. package/dist/blz-rds/commands/strings/last-index-of.js +1 -0
  255. package/dist/blz-rds/commands/strings/length.d.ts +2 -0
  256. package/dist/blz-rds/commands/strings/length.js +1 -0
  257. package/dist/blz-rds/commands/strings/pad-left.d.ts +2 -0
  258. package/dist/blz-rds/commands/strings/pad-left.js +1 -0
  259. package/dist/blz-rds/commands/strings/pad-right.d.ts +2 -0
  260. package/dist/blz-rds/commands/strings/pad-right.js +1 -0
  261. package/dist/blz-rds/commands/strings/replace.d.ts +2 -0
  262. package/dist/blz-rds/commands/strings/replace.js +1 -0
  263. package/dist/blz-rds/commands/strings/starts-with.d.ts +3 -0
  264. package/dist/blz-rds/commands/strings/starts-with.js +1 -0
  265. package/dist/blz-rds/commands/strings/substring.d.ts +2 -0
  266. package/dist/blz-rds/commands/strings/substring.js +1 -0
  267. package/dist/blz-rds/commands/strings/to-lower.d.ts +2 -0
  268. package/dist/blz-rds/commands/strings/to-lower.js +1 -0
  269. package/dist/blz-rds/commands/strings/to-upper.d.ts +2 -0
  270. package/dist/blz-rds/commands/strings/to-upper.js +1 -0
  271. package/dist/blz-rds/commands/strings/trim-end.d.ts +2 -0
  272. package/dist/blz-rds/commands/strings/trim-end.js +1 -0
  273. package/dist/blz-rds/commands/strings/trim-start.d.ts +2 -0
  274. package/dist/blz-rds/commands/strings/trim-start.js +1 -0
  275. package/dist/blz-rds/commands/strings/trim.d.ts +2 -0
  276. package/dist/blz-rds/commands/strings/trim.js +1 -0
  277. package/dist/blz-rds/index.d.ts +53 -0
  278. package/dist/blz-rds/index.js +1 -0
  279. package/dist/blz-rds-mysql/base.d.ts +83 -0
  280. package/dist/blz-rds-mysql/base.js +1 -0
  281. package/dist/blz-rds-mysql/connection-manager.d.ts +8 -0
  282. package/dist/blz-rds-mysql/connection-manager.js +1 -0
  283. package/dist/blz-rds-mysql/execute-bulk-insert.d.ts +2 -0
  284. package/dist/blz-rds-mysql/execute-bulk-insert.js +1 -0
  285. package/dist/blz-rds-mysql/execute-bulk-merge.d.ts +2 -0
  286. package/dist/blz-rds-mysql/execute-bulk-merge.js +1 -0
  287. package/dist/blz-rds-mysql/execute-non-query.d.ts +14 -0
  288. package/dist/blz-rds-mysql/execute-non-query.js +1 -0
  289. package/dist/blz-rds-mysql/execute-query.d.ts +11 -0
  290. package/dist/blz-rds-mysql/execute-query.js +1 -0
  291. package/dist/blz-rds-mysql/index.d.ts +9 -0
  292. package/dist/blz-rds-mysql/index.js +1 -0
  293. package/dist/blz-rds-mysql/stored-procedure.d.ts +19 -0
  294. package/dist/blz-rds-mysql/stored-procedure.js +1 -0
  295. package/dist/blz-rds-mysqlx/base.d.ts +83 -0
  296. package/dist/blz-rds-mysqlx/base.js +1 -0
  297. package/dist/blz-rds-mysqlx/connection-manager.d.ts +6 -0
  298. package/dist/blz-rds-mysqlx/connection-manager.js +1 -0
  299. package/dist/blz-rds-mysqlx/execute-bulk-insert.d.ts +2 -0
  300. package/dist/blz-rds-mysqlx/execute-bulk-insert.js +1 -0
  301. package/dist/blz-rds-mysqlx/execute-bulk-merge.d.ts +2 -0
  302. package/dist/blz-rds-mysqlx/execute-bulk-merge.js +1 -0
  303. package/dist/blz-rds-mysqlx/execute-non-query.d.ts +4 -0
  304. package/dist/blz-rds-mysqlx/execute-non-query.js +1 -0
  305. package/dist/blz-rds-mysqlx/execute-query.d.ts +7 -0
  306. package/dist/blz-rds-mysqlx/execute-query.js +1 -0
  307. package/dist/blz-rds-mysqlx/index.d.ts +9 -0
  308. package/dist/blz-rds-mysqlx/index.js +1 -0
  309. package/dist/blz-rds-mysqlx/stored-procedure.d.ts +20 -0
  310. package/dist/blz-rds-mysqlx/stored-procedure.js +1 -0
  311. package/dist/blz-rds-oracle/index.d.ts +25 -0
  312. package/dist/blz-rds-oracle/index.js +1 -0
  313. package/dist/blz-rds-postgres/base.d.ts +94 -0
  314. package/dist/blz-rds-postgres/base.js +1 -0
  315. package/dist/blz-rds-postgres/connection-manager.d.ts +6 -0
  316. package/dist/blz-rds-postgres/connection-manager.js +1 -0
  317. package/dist/blz-rds-postgres/execute-bulk-insert.d.ts +5 -0
  318. package/dist/blz-rds-postgres/execute-bulk-insert.js +1 -0
  319. package/dist/blz-rds-postgres/execute-bulk-merge.d.ts +4 -0
  320. package/dist/blz-rds-postgres/execute-bulk-merge.js +1 -0
  321. package/dist/blz-rds-postgres/execute-non-query.d.ts +12 -0
  322. package/dist/blz-rds-postgres/execute-non-query.js +1 -0
  323. package/dist/blz-rds-postgres/execute-query.d.ts +4 -0
  324. package/dist/blz-rds-postgres/execute-query.js +1 -0
  325. package/dist/blz-rds-postgres/index.d.ts +9 -0
  326. package/dist/blz-rds-postgres/index.js +1 -0
  327. package/dist/blz-rds-postgres/result-set.js +1 -0
  328. package/dist/blz-rds-postgres/stored-procedure.d.ts +19 -0
  329. package/dist/blz-rds-postgres/stored-procedure.js +1 -0
  330. package/dist/blz-redis/index.d.ts +31 -0
  331. package/dist/blz-redis/index.js +1 -0
  332. package/dist/blz-redis/lib/redisCache.d.ts +33 -0
  333. package/dist/blz-redis/lib/redisCache.js +1 -0
  334. package/dist/blz-regex/index.d.ts +3 -0
  335. package/dist/blz-regex/index.js +1 -0
  336. package/dist/blz-security/__test__/autorization.test.js +1 -0
  337. package/dist/blz-security/__test__/autorizationKpn.test.js +1 -0
  338. package/dist/blz-security/__test__/orderManagement.test.js +1 -0
  339. package/dist/blz-security/__test__/secureUrl.test.js +1 -0
  340. package/dist/blz-security/__test__/solveMergeRule.test.js +1 -0
  341. package/dist/blz-security/__test__/sqlInjectionGuard.test.js +1 -0
  342. package/dist/blz-security/__test__/xssGuard.test.js +1 -0
  343. package/dist/blz-security/authorizationService.d.ts +42 -0
  344. package/dist/blz-security/authorizationService.js +2 -0
  345. package/dist/blz-security/config/global.js +1 -0
  346. package/dist/blz-security/filescanner/index.d.ts +24 -0
  347. package/dist/blz-security/filescanner/index.js +1 -0
  348. package/dist/blz-security/helpers/consts.d.ts +28 -0
  349. package/dist/blz-security/helpers/consts.js +1 -0
  350. package/dist/blz-security/helpers/utils.d.ts +82 -0
  351. package/dist/blz-security/helpers/utils.js +1 -0
  352. package/dist/blz-security/implementations/cache.d.ts +58 -0
  353. package/dist/blz-security/implementations/cache.js +1 -0
  354. package/dist/blz-security/implementations/oidc.d.ts +100 -0
  355. package/dist/blz-security/implementations/oidc.js +1 -0
  356. package/dist/blz-security/implementations/pkceCacheStore.d.ts +2 -0
  357. package/dist/blz-security/implementations/pkceCacheStore.js +1 -0
  358. package/dist/blz-security/implementations/saml.js +1 -0
  359. package/dist/blz-security/implementations/uma.d.ts +31 -0
  360. package/dist/blz-security/implementations/uma.js +1 -0
  361. package/dist/blz-security/implementations/webAuthn.js +1 -0
  362. package/dist/blz-security/implementations/wstg.js +1 -0
  363. package/dist/blz-security/index.d.ts +4 -0
  364. package/dist/blz-security/index.js +2 -0
  365. package/dist/blz-security/lab/index.js +1 -0
  366. package/dist/blz-security/middleware/HapiServerAzureAd.d.ts +26 -0
  367. package/dist/blz-security/middleware/HapiServerAzureAd.js +1 -0
  368. package/dist/blz-security/middleware/HapiServerKeycloak.d.ts +47 -0
  369. package/dist/blz-security/middleware/HapiServerKeycloak.js +1 -0
  370. package/dist/blz-security/middleware/HapiServerSimToken.d.ts +13 -0
  371. package/dist/blz-security/middleware/HapiServerSimToken.js +1 -0
  372. package/dist/blz-security/middleware/hapi.d.ts +14 -0
  373. package/dist/blz-security/middleware/hapi.js +1 -0
  374. package/dist/blz-security/middleware/hapiServer.js +1 -0
  375. package/dist/blz-security/navigationMemoryRepository.d.ts +6 -0
  376. package/dist/blz-security/navigationMemoryRepository.js +1 -0
  377. package/dist/blz-security/navigationMongoDbRepository.d.ts +15 -0
  378. package/dist/blz-security/navigationMongoDbRepository.js +1 -0
  379. package/dist/blz-security/secureUrlService.d.ts +7 -0
  380. package/dist/blz-security/secureUrlService.js +1 -0
  381. package/dist/blz-security/securityService.d.ts +72 -0
  382. package/dist/blz-security/securityService.js +1 -0
  383. package/dist/blz-security/sqlInjectionGuard.d.ts +37 -0
  384. package/dist/blz-security/sqlInjectionGuard.js +1 -0
  385. package/dist/blz-security/xssGuard.d.ts +14 -0
  386. package/dist/blz-security/xssGuard.js +1 -0
  387. package/dist/blz-strings/index.d.ts +42 -0
  388. package/dist/blz-strings/index.js +1 -0
  389. package/dist/blz-uuid/index.d.ts +1 -0
  390. package/dist/blz-uuid/index.js +1 -0
  391. package/dist/blz-yaml/index.d.ts +2 -0
  392. package/dist/blz-yaml/index.js +1 -0
  393. package/dist/index.d.ts +34 -0
  394. package/dist/index.js +1 -0
  395. package/dist/process-managers/index.d.ts +25 -0
  396. package/dist/process-managers/index.js +1 -0
  397. package/package.json +52 -41
  398. package/blz-base/health/index.js +0 -215
  399. package/blz-base/index.js +0 -1466
  400. package/blz-cache/LruCache.js +0 -44
  401. package/blz-cache/index.js +0 -29
  402. package/blz-config/index.js +0 -434
  403. package/blz-core/index.js +0 -364
  404. package/blz-cryptography/index.js +0 -54
  405. package/blz-datetimes/index.js +0 -356
  406. package/blz-file/example.dat +0 -2545
  407. package/blz-file/fileService.js +0 -205
  408. package/blz-file/index.js +0 -94
  409. package/blz-file/index.test.js +0 -31
  410. package/blz-file/lab.js +0 -33
  411. package/blz-hazelcast/index.js +0 -189
  412. package/blz-hazelcast/lib/credentials.js +0 -25
  413. package/blz-hazelcast/lib/credentialsFactory.js +0 -12
  414. package/blz-hazelcast/lib/hazelcastCache.js +0 -234
  415. package/blz-iterable/index.js +0 -446
  416. package/blz-json-schema/index.js +0 -11
  417. package/blz-jwt/index.js +0 -121
  418. package/blz-kafka/index.js +0 -522
  419. package/blz-math/index.js +0 -131
  420. package/blz-mongodb/index.js +0 -326
  421. package/blz-rds/__test__/scape.test.js +0 -58
  422. package/blz-rds/blz-rds-executor.js +0 -578
  423. package/blz-rds/blz-rds-helper.js +0 -310
  424. package/blz-rds/commands/core/add.js +0 -13
  425. package/blz-rds/commands/core/and.js +0 -18
  426. package/blz-rds/commands/core/asc.js +0 -10
  427. package/blz-rds/commands/core/avg.js +0 -10
  428. package/blz-rds/commands/core/column-ref.js +0 -8
  429. package/blz-rds/commands/core/count-distinct.js +0 -10
  430. package/blz-rds/commands/core/count.js +0 -10
  431. package/blz-rds/commands/core/decimal.js +0 -8
  432. package/blz-rds/commands/core/desc.js +0 -10
  433. package/blz-rds/commands/core/distinct.js +0 -10
  434. package/blz-rds/commands/core/divide.js +0 -11
  435. package/blz-rds/commands/core/embedded-exists.js +0 -17
  436. package/blz-rds/commands/core/embedded-select.js +0 -17
  437. package/blz-rds/commands/core/equals.js +0 -9
  438. package/blz-rds/commands/core/false.js +0 -8
  439. package/blz-rds/commands/core/greater-or-equal.js +0 -9
  440. package/blz-rds/commands/core/greater.js +0 -9
  441. package/blz-rds/commands/core/in.js +0 -9
  442. package/blz-rds/commands/core/integer.js +0 -8
  443. package/blz-rds/commands/core/is-not-null.js +0 -11
  444. package/blz-rds/commands/core/is-null-or-value.js +0 -10
  445. package/blz-rds/commands/core/is-null.js +0 -11
  446. package/blz-rds/commands/core/less-or-equal.js +0 -9
  447. package/blz-rds/commands/core/less-unary.js +0 -12
  448. package/blz-rds/commands/core/less.js +0 -9
  449. package/blz-rds/commands/core/like.js +0 -12
  450. package/blz-rds/commands/core/max.js +0 -10
  451. package/blz-rds/commands/core/min.js +0 -10
  452. package/blz-rds/commands/core/multiply.js +0 -13
  453. package/blz-rds/commands/core/not-equals.js +0 -9
  454. package/blz-rds/commands/core/not-in.js +0 -9
  455. package/blz-rds/commands/core/not.js +0 -13
  456. package/blz-rds/commands/core/null.js +0 -8
  457. package/blz-rds/commands/core/nvl.js +0 -11
  458. package/blz-rds/commands/core/or.js +0 -13
  459. package/blz-rds/commands/core/parameter.js +0 -34
  460. package/blz-rds/commands/core/remainder.js +0 -16
  461. package/blz-rds/commands/core/string.js +0 -8
  462. package/blz-rds/commands/core/subtract.js +0 -13
  463. package/blz-rds/commands/core/sum.js +0 -10
  464. package/blz-rds/commands/core/true.js +0 -8
  465. package/blz-rds/commands/core/tuple.js +0 -13
  466. package/blz-rds/commands/datetimes/add-days.js +0 -11
  467. package/blz-rds/commands/datetimes/add-hours.js +0 -11
  468. package/blz-rds/commands/datetimes/add-milliseconds.js +0 -11
  469. package/blz-rds/commands/datetimes/add-minutes.js +0 -11
  470. package/blz-rds/commands/datetimes/add-months.js +0 -11
  471. package/blz-rds/commands/datetimes/add-seconds.js +0 -11
  472. package/blz-rds/commands/datetimes/add-years.js +0 -11
  473. package/blz-rds/commands/datetimes/date-diff.js +0 -11
  474. package/blz-rds/commands/datetimes/date.js +0 -12
  475. package/blz-rds/commands/datetimes/datetime-diff.js +0 -11
  476. package/blz-rds/commands/datetimes/datetime.js +0 -15
  477. package/blz-rds/commands/datetimes/day.js +0 -10
  478. package/blz-rds/commands/datetimes/hour.js +0 -10
  479. package/blz-rds/commands/datetimes/millisecond.js +0 -10
  480. package/blz-rds/commands/datetimes/minute.js +0 -10
  481. package/blz-rds/commands/datetimes/month-text.js +0 -10
  482. package/blz-rds/commands/datetimes/month.js +0 -10
  483. package/blz-rds/commands/datetimes/now.js +0 -9
  484. package/blz-rds/commands/datetimes/second.js +0 -10
  485. package/blz-rds/commands/datetimes/subtract-days.js +0 -11
  486. package/blz-rds/commands/datetimes/subtract-hours.js +0 -11
  487. package/blz-rds/commands/datetimes/subtract-milliseconds.js +0 -11
  488. package/blz-rds/commands/datetimes/subtract-minutes.js +0 -11
  489. package/blz-rds/commands/datetimes/subtract-seconds.js +0 -11
  490. package/blz-rds/commands/datetimes/time-diff.js +0 -11
  491. package/blz-rds/commands/datetimes/time.js +0 -13
  492. package/blz-rds/commands/datetimes/today.js +0 -9
  493. package/blz-rds/commands/datetimes/week-day-text.js +0 -10
  494. package/blz-rds/commands/datetimes/week-day.js +0 -10
  495. package/blz-rds/commands/datetimes/week.js +0 -10
  496. package/blz-rds/commands/datetimes/year.js +0 -10
  497. package/blz-rds/commands/math/abs.js +0 -10
  498. package/blz-rds/commands/math/acos.js +0 -10
  499. package/blz-rds/commands/math/asin.js +0 -10
  500. package/blz-rds/commands/math/atan.js +0 -10
  501. package/blz-rds/commands/math/atan2.js +0 -11
  502. package/blz-rds/commands/math/ceil.js +0 -10
  503. package/blz-rds/commands/math/cos.js +0 -10
  504. package/blz-rds/commands/math/cosh.js +0 -10
  505. package/blz-rds/commands/math/exp.js +0 -10
  506. package/blz-rds/commands/math/floor.js +0 -10
  507. package/blz-rds/commands/math/log.js +0 -18
  508. package/blz-rds/commands/math/log10.js +0 -10
  509. package/blz-rds/commands/math/pow.js +0 -11
  510. package/blz-rds/commands/math/random.js +0 -9
  511. package/blz-rds/commands/math/round.js +0 -18
  512. package/blz-rds/commands/math/sign.js +0 -10
  513. package/blz-rds/commands/math/sin.js +0 -10
  514. package/blz-rds/commands/math/sinh.js +0 -10
  515. package/blz-rds/commands/math/sqrt.js +0 -10
  516. package/blz-rds/commands/math/tan.js +0 -10
  517. package/blz-rds/commands/math/tanh.js +0 -10
  518. package/blz-rds/commands/math/trunc.js +0 -18
  519. package/blz-rds/commands/strings/concat.js +0 -20
  520. package/blz-rds/commands/strings/contains.js +0 -12
  521. package/blz-rds/commands/strings/ends-with.js +0 -12
  522. package/blz-rds/commands/strings/index-of.js +0 -11
  523. package/blz-rds/commands/strings/is-null-or-empty.js +0 -11
  524. package/blz-rds/commands/strings/is-null-or-white-space.js +0 -11
  525. package/blz-rds/commands/strings/join.js +0 -22
  526. package/blz-rds/commands/strings/last-index-of.js +0 -11
  527. package/blz-rds/commands/strings/length.js +0 -10
  528. package/blz-rds/commands/strings/pad-left.js +0 -20
  529. package/blz-rds/commands/strings/pad-right.js +0 -20
  530. package/blz-rds/commands/strings/replace.js +0 -12
  531. package/blz-rds/commands/strings/starts-with.js +0 -12
  532. package/blz-rds/commands/strings/substring.js +0 -12
  533. package/blz-rds/commands/strings/to-lower.js +0 -10
  534. package/blz-rds/commands/strings/to-upper.js +0 -10
  535. package/blz-rds/commands/strings/trim-end.js +0 -10
  536. package/blz-rds/commands/strings/trim-start.js +0 -10
  537. package/blz-rds/commands/strings/trim.js +0 -10
  538. package/blz-rds/index.js +0 -744
  539. package/blz-rds-mysql/base.js +0 -857
  540. package/blz-rds-mysql/connection-manager.js +0 -129
  541. package/blz-rds-mysql/execute-bulk-insert.js +0 -35
  542. package/blz-rds-mysql/execute-bulk-merge.js +0 -45
  543. package/blz-rds-mysql/execute-non-query.js +0 -34
  544. package/blz-rds-mysql/execute-query.js +0 -50
  545. package/blz-rds-mysql/index.js +0 -41
  546. package/blz-rds-mysql/stored-procedure.js +0 -207
  547. package/blz-rds-mysqlx/base.js +0 -846
  548. package/blz-rds-mysqlx/connection-manager.js +0 -141
  549. package/blz-rds-mysqlx/execute-bulk-insert.js +0 -35
  550. package/blz-rds-mysqlx/execute-bulk-merge.js +0 -45
  551. package/blz-rds-mysqlx/execute-non-query.js +0 -29
  552. package/blz-rds-mysqlx/execute-query.js +0 -39
  553. package/blz-rds-mysqlx/index.js +0 -41
  554. package/blz-rds-mysqlx/stored-procedure.js +0 -179
  555. package/blz-rds-oracle/index.js +0 -539
  556. package/blz-rds-postgres/base.js +0 -861
  557. package/blz-rds-postgres/connection-manager.js +0 -225
  558. package/blz-rds-postgres/execute-bulk-insert.js +0 -81
  559. package/blz-rds-postgres/execute-bulk-merge.js +0 -93
  560. package/blz-rds-postgres/execute-non-query.js +0 -23
  561. package/blz-rds-postgres/execute-query.js +0 -37
  562. package/blz-rds-postgres/index.js +0 -41
  563. package/blz-rds-postgres/result-set.js +0 -51
  564. package/blz-rds-postgres/stored-procedure.js +0 -116
  565. package/blz-redis/index.js +0 -217
  566. package/blz-redis/lib/redisCache.js +0 -265
  567. package/blz-regex/index.js +0 -25
  568. package/blz-security/.eslintrc.js +0 -15
  569. package/blz-security/__test__/AuthorizationKpn.yaml +0 -1149
  570. package/blz-security/__test__/FinancingSetting.yaml +0 -177
  571. package/blz-security/__test__/KpnConfigPortal.yaml +0 -330
  572. package/blz-security/__test__/OrderManagement.yaml +0 -5190
  573. package/blz-security/__test__/Security.yaml +0 -128
  574. package/blz-security/__test__/autorization.test.js +0 -105
  575. package/blz-security/__test__/autorizationKpn.test.js +0 -42
  576. package/blz-security/__test__/orderManagement.test.js +0 -26
  577. package/blz-security/__test__/secureUrl.test.js +0 -79
  578. package/blz-security/__test__/solveMergeRule.test.js +0 -109
  579. package/blz-security/__test__/sqlInjectionGuard.test.js +0 -203
  580. package/blz-security/__test__/xssGuard.test.js +0 -204
  581. package/blz-security/authorizationService.js +0 -537
  582. package/blz-security/config/global.js +0 -8
  583. package/blz-security/config/welcome +0 -8
  584. package/blz-security/doc/README.md +0 -75
  585. package/blz-security/filescanner/index.js +0 -46
  586. package/blz-security/helpers/consts.js +0 -229
  587. package/blz-security/helpers/utils.js +0 -267
  588. package/blz-security/implementations/cache.js +0 -90
  589. package/blz-security/implementations/oidc.js +0 -404
  590. package/blz-security/implementations/pkceCacheStore.js +0 -23
  591. package/blz-security/implementations/saml.js +0 -10
  592. package/blz-security/implementations/uma.js +0 -63
  593. package/blz-security/implementations/webAuthn.js +0 -9
  594. package/blz-security/implementations/wstg.js +0 -72
  595. package/blz-security/index.js +0 -77
  596. package/blz-security/lab/index.js +0 -43
  597. package/blz-security/middleware/HapiServerAzureAd.js +0 -681
  598. package/blz-security/middleware/HapiServerKeycloak.js +0 -876
  599. package/blz-security/middleware/HapiServerSimToken.js +0 -286
  600. package/blz-security/middleware/hapi.js +0 -555
  601. package/blz-security/middleware/hapiServer.js +0 -1008
  602. package/blz-security/navigationMemoryRepository.js +0 -15
  603. package/blz-security/navigationMongoDbRepository.js +0 -73
  604. package/blz-security/secureUrlService.js +0 -47
  605. package/blz-security/securityService.js +0 -413
  606. package/blz-security/sqlInjectionGuard.js +0 -162
  607. package/blz-security/templates/forbidden.html +0 -0
  608. package/blz-security/templates/session-iframe-azure-ad.html +0 -7
  609. package/blz-security/templates/session-iframe.html +0 -73
  610. package/blz-security/templates/unauthorized.html +0 -1
  611. package/blz-security/xssGuard.js +0 -87
  612. package/blz-strings/index.js +0 -167
  613. package/blz-uuid/index.js +0 -7
  614. package/blz-yaml/index.js +0 -19
  615. package/index.js +0 -84
  616. package/process-managers/index.js +0 -422
  617. /package/{blz-rds-mysql → dist/blz-rds-mysql}/syntaxis.json +0 -0
  618. /package/{blz-rds-mysqlx → dist/blz-rds-mysqlx}/syntaxis.json +0 -0
  619. /package/{blz-rds-oracle → dist/blz-rds-oracle}/syntaxis.json +0 -0
  620. /package/{blz-rds-postgres → dist/blz-rds-postgres}/syntaxis.json +0 -0
  621. /package/{blz-security → dist/blz-security}/lab/ConfigurationAdmin.agent.json +0 -0
  622. /package/{blz-security → dist/blz-security}/lab/frontend.json +0 -0
  623. /package/{blz-security → dist/blz-security}/lab/result.json +0 -0
  624. /package/{blz-security → dist/blz-security}/lab/resultOnWeb.json +0 -0
  625. /package/{blz-security → dist/blz-security}/lab/rules.json +0 -0
  626. /package/{blz-security → dist/blz-security}/lab/securityRules.json +0 -0
@@ -0,0 +1 @@
1
+ const Uma=require("../implementations/uma"),Jsonwebtoken=require("jsonwebtoken"),{Exception:Exception,getFullUrl:getFullUrl,getHost:getHost,getProtocol:getProtocol,getPathname:getPathname,getTemplate:getTemplate,getTokenTolerance:getTokenTolerance,trace:trace,errorResponse:errorResponse}=require("../helpers/utils"),hapiYar=require("@hapi/yar"),hapiJwt=require("@hapi/jwt"),hapiCookie=require("@hapi/cookie"),axios=require("axios"),crypto=require("crypto"),{Issuer:Issuer}=require("openid-client"),{METADATA:METADATA}=require("../helpers/consts"),jwksClient=require("jwks-rsa");let contextConfig={},securityService=null;class HapiServerKeycloak{constructor(e,t,r){this.openIdConnect=e,this.COOKIE_NAMES=t,this.activateTraceApiMethod=!1,this.queryStringLimit=null,this.securityLoginTokenExpToleranceSeconds=18e3,this.authServerConfig=null,this.authServerFullLoginUrl=null,this.cache=r,this.clientOidc=null,this.clientJwk=null,this.publicKeyFetch=null,this.securityService=null,this.securityUrlCookieKey=null}async generateGuid(){return crypto.randomUUID()}async connect(e,t,r){contextConfig=r,this.authServerConfig=contextConfig,securityService=e;const{authServer:o,activateTraceApiMethod:i}=r;i&&(this.activateTraceApiMethod=i);let n={};const s={clearInvalid:!0,encoding:"base64",isSecure:!0,isHttpOnly:!0,isSameSite:"Lax",path:"/",strictHeader:!0};try{o.sessionCookiesDomain&&(s.domain=o.sessionCookiesDomain),s.isHttpOnly=o.isHttpOnlyForSessionState??!1,t.state(this.COOKIE_NAMES.SESSION_STATE,s),n=await this.configuration(o),n.clientOidc&&(this.clientOidc=n.clientOidc),o.scope&&o.scope.split(" ").some(e=>"openid"===e)||(o.scope=`openid ${o.scope||""}`,o.scope.trim()),o.tokenEndpoint&&!o.tokenEndpoint.match(/https.*/)&&(t.states.cookies[this.COOKIE_NAMES.SID].isSecure=!1,t.states.cookies[this.COOKIE_NAMES.SESSION_STATE].isSecure=!1),trace("INFO","The following configuration was initialized");const e=Object.fromEntries(Object.entries(o).filter(e=>!["clientSecret","PrivateKey","PublicKey"].includes(e[0])));if(trace("INFO",n.tokenEndpoint?n:e),this.securityUrlCookieKey=securityService.getSecureUrlCookieKey(),this.securityUrlCookieKey){const e={...s,isHttpOnly:!1,ttl:null};t.state(this.securityUrlCookieKey,e)}}catch(e){trace("ERROR",`Exception ${e.message}`),trace("ERROR",e.stack)}const a=this;this.configurePlugins(t),t.ext("onPreAuth",async(e,t)=>{if(this.securityUrlCookieKey){if(!e.state[this.securityUrlCookieKey]){const e=await this.generateGuid();t.state(this.securityUrlCookieKey,e)}}let r=e.yar.get("jwtToken");if(r){if(await a.tokenAboutToExpire(r.token,10)){if(await this.isRefreshTokenExpired(r.refreshToken)&&"refreshToken"in r)return e.yar.get("jwtToken",!0),delete e.headers.authorization,await e.yar.commit(t),t.continue;{let o=await this.refreshToken(r.refreshToken);if(!(o&&o.token_type&&(o.id_token||o.access_token)&&o.session_state&&o.refresh_token))return e.yar.get("jwtToken",!0),delete e.headers.authorization,await e.yar.commit(t),t.continue;{let i={tokenType:"Bearer",token:o.id_token,tokenSubType:"id_token",refreshToken:o.refresh_token};e.yar.set("jwtToken",i),await e.yar.commit(t),r=i}}}switch(r.tokenType){case"Bearer":case"bearer":e.headers.authorization=`Bearer ${r.token}`}}return t.continue}),t.ext("onPreResponse",async(e,t)=>{const r=e.response;let i=e.yar.get("authError",!0);if(await e.yar.commit(t),r.isBoom&&401===r.output.statusCode&&!e.path.startsWith("/auth/callback")&&!i){const r=crypto.randomBytes(32).toString("base64url");e.yar.set("code_verifier",r),e.yar.set("originalUrlPathName",a.getFullUrl(e)),await e.yar.commit(t);const i=crypto.createHash("sha256").update(r).digest("base64url"),n="code",s=a.getRedirectUriPath(e,"auth/callback"),c="S256",h=o.scope?o.scope.trim().replace(/\s+/g,"%20"):"openid",u=new URL(o.authorizationEndpoint);return u.searchParams.set("client_id",a.authServerConfig.authServer.clientId),u.searchParams.set("response_type",n),u.searchParams.set("redirect_uri",s),u.searchParams.set("scope",h),u.searchParams.set("code_challenge",i),u.searchParams.set("code_challenge_method",c),t.redirect(u.toString()).takeover()}return t.continue}),t.route({method:"GET",path:"/auth/callback",options:{auth:!1},handler:async(e,t)=>{const r=e.query.code;if(!r)return t.response("Authorization code missing").code(400);try{let o=e.yar.get("code_verifier",!0),i=await axios.post(a.authServerConfig.authServer.tokenEndpoint,new URLSearchParams({grant_type:"authorization_code",client_id:a.authServerConfig.authServer.clientId,client_secret:a.authServerConfig.authServer.clientSecret,code:r,redirect_uri:a.getRedirectUriPath(e,"auth/callback"),code_verifier:o}).toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded"}});if("OK"===!i.statusText)throw new Error("Failed to exchange code for tokens");let n={tokenType:"Bearer"};i.data.id_token?(n.token=i.data.id_token,n.tokenSubType="id_token"):(n.token=i.data.access_token,n.tokenSubType="access_token"),n.refreshToken=i.data.refresh_token;let s=e.yar.get("originalUrlPathName")??"/";const c=e.query.session_state;switch(t.state(this.COOKIE_NAMES.SESSION_STATE,c),n.tokenType){case"Bearer":case"bearer":return e.yar.set("jwtToken",n),await e.yar.commit(t),t.redirect(s).takeover()}return t.continue}catch(r){return e.yar.set("authError",!1),await e.yar.commit(t),console.error("Failed to exchange code for token:",r.response?.data||r.message),t.response("Failed to authenticate").code(500).takeover()}}}),t.route({method:"GET",path:"/get-authorization",handler:async(e,t)=>{try{const{session_state:r}=e.state;if(!r)throw new Exception("Keycloack get-authorization: Session cookie doesn't exist.","CookiesError",404);const i=await a.openIdConnect.tokenSet(),n=await i.tokens(r),s=await Uma.permission(),c=await s.ticket({tokenUrl:o.tokenEndpoint||o.tokenUrl,token:n.access_token,audience:o.clientId}),h=Jsonwebtoken.decode(c.access_token);return t.response(JSON.stringify(h.authorization)).takeover()}catch(e){return errorResponse(t,e,401)}}}),t.route({method:"GET",path:"/get-security-rules",handler:async(e,t)=>{try{const r=await securityService.getFrontendSecurityRules(e);return t.response(JSON.stringify(r)).takeover()}catch(e){return errorResponse(t,e,401)}}}),t.route({method:"GET",path:"/get-permissions",handler:async(e,t)=>{try{const e=await securityService.getPermissions();return t.response(JSON.stringify(e)).takeover()}catch(e){return errorResponse(t,e,401)}}}),t.route({method:"GET",path:"/check-authorize",handler:async(e,t)=>{try{const r=e.query.path,o=e.query.action,i=e.query.roles,n=e.query.domains;let s,a;s=Array.isArray(i)?i:"string"==typeof i?i.split(",").map(e=>e.trim()):[],a=Array.isArray(n)?n:"string"==typeof n?n.split(",").map(e=>e.trim()):[];const c=await securityService.checkAuthorize(r,o,s,a);return t.response(JSON.stringify(c)).takeover()}catch(e){return errorResponse(t,e,401)}}}),t.route({method:"GET",path:"/get-user-info",handler:async(e,t)=>{try{const r=await securityService.getUserInfo(e);return t.response(JSON.stringify(r)).takeover()}catch(e){return errorResponse(t,e,500)}}}),t.route({path:"/logout",method:"GET",options:{auth:!1},handler:async(e,t)=>{try{e.state[this.COOKIE_NAMES.SESSION_STATE];e.yar.clear("jwtToken"),await e.yar.commit(t);let r=await a.endSessionUrl(a.getRedirectUri(e),a.clientOidc);return t.response().unstate(this.COOKIE_NAMES.SID).unstate(this.COOKIE_NAMES.SESSION_STATE).unstate(this.COOKIE_NAMES.AUTH_TOKEN).redirect(r).takeover()}catch(e){return errorResponse(t,e,500)}}}),t.route({path:"/invalid-session",method:"GET",handler:async(e,t)=>{try{const r=await a.openIdConnect.endSessionUrl({redirectUri:this.getRedirectUri(e),sessionState:e.state[this.COOKIE_NAMES.SESSION_STATE]});return t.response().unstate(this.COOKIE_NAMES.SID).unstate(this.COOKIE_NAMES.SESSION_STATE).redirect(r).takeover()}catch(e){return errorResponse(t,e,500)}}}),t.route({path:"/check-session-iframe.html",method:"GET",handler:async(e,t)=>{try{let e="<html/>";if(o&&o.checkSessionIframe){const{checkSessionIframe:t,clientId:r,sessionCookiesPrefix:i}=o;t&&t.includes("https://")?(trace("INFO",`Session management url: ${t}`),e=getTemplate("session-iframe",{sessionIframeUrl:t,clientId:r,sessionCookiesPrefix:i||""})):trace("WARN","For session management, it is necessary to get the value from a cookie called session_state, and as a good practice, it should have reached a secure context [TLS].")}return t.response(e).header("Content-Type","text/html")}catch(e){return errorResponse(t,e,500)}}}),t.route({path:"/check-session",options:{auth:!1},method:"GET",handler:async(e,t)=>{let r=e.yar.get("jwtToken"),o={expired:!1};return r&&(o.expired=await this.tokenAboutToExpire(r.refreshToken,.5),o.expired&&(o.redirectUrl=await this.getFullKeycloakLoginUri(e,t),e.yar.clear("jwtToken"),e.yar.clear("userRelog"))),t.response(o)}})}async getFullKeycloakLoginUri(e,t){const r=crypto.randomBytes(32).toString("base64url");e.yar.set("code_verifier",r),e.yar.set("originalUrlPathName",this.getBaseUrl(e)),await e.yar.commit(t);const o=this.getRedirectUriPath(e,"auth/callback"),i=this.authServerConfig.authServer.scope,n=crypto.createHash("sha256").update(r).digest("base64url"),s=new URL(this.authServerConfig.authServer.authorizationEndpoint);return s.searchParams.set("client_id",this.authServerConfig.authServer.clientId),s.searchParams.set("response_type","code"),s.searchParams.set("redirect_uri",o),s.searchParams.set("scope",i),s.searchParams.set("code_challenge",n),s.searchParams.set("code_challenge_method","S256"),s.toString()}getRedirectUri(e){return contextConfig.authServer.redirectUri||getFullUrl(e)}getRedirectUriPath(e,t){const r=this.getBaseUrl(e),o=t??this.getPathname(e);let i=new URL(o,r);return"localhost"!==i.hostname&&(i.protocol="https:"),i.toString()}getFullUrl(e){return`${getProtocol(e)}://${getHost(e)}${getPathname(e)}`}getBaseUrl(e){return`${getProtocol(e)}://${getHost(e)}/`}async authenticate(e,t){const{request:r}=e,o=await this.openIdConnect.pkceCode(),i=getFullUrl(r);let n=await this.openIdConnect.oidcMetadata();if(n&&n.openid_configuration||(n=await this.configuration(contextConfig.authServer)),i.match(new RegExp(/^(https?:\/{2}.*):?(\d*)/.source+getHost(r)+/\/?$/.source))){const i=await this.openIdConnect.authorizationUrl({scope:t,redirectUri:this.getRedirectUri(r),pkceCode:o});return trace("INFO",`Authenticate redirecting to ${i}`),e.response().state(this.COOKIE_NAMES.SID,o).redirect(i).takeover()}if("/logout"===getPathname(r))return e.continue;{const t=await this.openIdConnect.tokenSet(),{state:o}=r;if(t&&o&&o[this.COOKIE_NAMES.SESSION_STATE]){const r=await t.tokens(o[this.COOKIE_NAMES.SESSION_STATE]);if(!r||r.refresh_expires_in<=getTokenTolerance(0))throw new Exception("Error when getting token","ExpirationError",403);return e.continue}return e.response().code(401).takeover()}}async configurePlugins(e){const t=process.env.blz_hapiYarPassword||"your-super-secure-yar-atleast-32-bytes-password";await e.register({plugin:hapiYar,options:{cookieOptions:{password:t,isSecure:!0,isHttpOnly:!0,isSameSite:"Lax",clearInvalid:!0,ignoreErrors:!0},storeBlank:!1,maxCookieSize:0}}),await e.register(hapiJwt),this.startupJwksClient(),this.startupPublickKeyFetch(),e.auth.strategy("jwtAuth","jwt",{keys:this.publicKeyFetch,verify:{aud:this.authServerConfig.authServer.audience??!1,iss:this.authServerConfig.authServer.issuer,exp:!0,sub:!1},validate:!1}),await e.register(hapiCookie);const r=process.env.blz_hapiCookiePassword||"supersecretpasswordmustbeatleast32characterslong";e.auth.strategy("cookieAuth","cookie",{cookie:{name:"sid",password:r,isSecure:!0,isHttpOnly:!0,isSameSite:"Lax"},keepAlive:!0,redirectTo:!1}),e.auth.default({strategies:["jwtAuth","cookieAuth"]})}async configuration(e){if(!e)throw new Exception("Error when getting configuration attributes ");const{clientId:t,clientSecret:r}=e;return await this.openIdConnect.client({clientId:t,clientSecret:r}),e.openIdConfigurationEndpoint?await this.openIdConnect.configuration(e.openIdConfigurationEndpoint):await this.openIdConnect.configuration({issuer:e.issuer,authorization_endpoint:e.authorizationEndpoint,token_endpoint:e.tokenEndpoint,userinfo_endpoint:e.userinfoEndpoint,end_session_endpoint:e.endSessionEndpoint,jwks_uri:e.jwksUri})}async endSessionUrl(e,t){if(e=e.replace(/logout|invalid-session/gim,""),!t)throw new Error("Unable to get configuration from identity provider","ConfigurationError",404);return t.endSessionUrl({post_logout_redirect_uri:e})}oidcMetadataKey(){return this.authServerConfig.authServer.sessionCookiesDomain||"oidcMetadata"}async configuration(e){let t=await this.cache.get(this.oidcMetadataKey());if("string"==typeof e&&!e.match(/(https?:\/\/.*):?(\d*)\/?(.*)/gi))throw new Exception("Wrong OpenId Provider configuration URI entered","AttributeError",403);return t&&t.issuer||(e.issuer?t={...t||{},...e}:(t=t||{},t.openid_configuration=e,t={...t,...await Issuer.discover(e.issuer)}),await this.cache.set(this.oidcMetadataKey(),t,864e5)),new Iss(t)}async refreshToken(e){const t=await axios.post(this.authServerConfig.authServer.tokenEndpoint,new URLSearchParams({grant_type:"refresh_token",client_id:this.authServerConfig.authServer.clientId,client_secret:this.authServerConfig.authServer.clientSecret,refresh_token:e}).toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(200!==t.status){const e=await t.json();return console.error("Error refreshing token:",e),e}try{return await t.json()}catch(e){}try{return t.data}catch{}}async decodeJwtToken(e){return hapiJwt.token.decode(e)}async tokenAboutToExpire(e,t=0){if(!e)return!0;return 1e3*hapiJwt.token.decode(e).decoded.payload.exp-Date.now()<=60*t*1e3}async isRefreshTokenExpired(e){try{const t=hapiJwt.token.decode(e),r=Math.floor(Date.now()/1e3);return!(t&&t.decoded&&t.decoded.payload&&t.decoded.payload.exp)||t.decoded.payload.exp<r}catch(e){return console.error("Failed to decode the token: Invalid Refresh token format",e),!0}}async startupJwksClient(){this.clientJwk=jwksClient({jwksUri:this.authServerConfig.authServer.jwksUri,cache:!0,rateLimit:!0,jwksRequestsPerMinute:10})}async startupPublickKeyFetch(){const e=async e=>new Promise((t,r)=>{this.clientJwk.getSigningKey(e,(e,o)=>{if(e)return r(e);const i=o.getPublicKey();t(i)})});this.publicKeyFetch=async t=>{const r=t.decoded.header.kid;return e(r)}}}class Iss{constructor(e){e.id_token_signing_alg_values_supported||(e.id_token_signing_alg_values_supported=["RS256"]),e.response_types_supported||(e.response_types_supported=["code","none","id_token","token","id_token token","code id_token","code token","code id_token token"]),e.subject_types_supported||(e.subject_types_supported=["public"]);const t=METADATA.filter(({type:e})=>"REQUIRED"===e),r=[];for(const o of t){const t=e[o.name.toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase())];e[o.name]||t||r.push(o)}if(r.length>0)throw console.error(JSON.stringify(r)),new Error(JSON.stringify(r));const o=e.Client?e:new Issuer(this.#e(e)),i={client_id:e.clientId,response_type:"code"};e.clientSecret&&(i.client_secret=e.clientSecret),this.clientOidc=new o.Client(i)}#e(e){return"object"!=typeof e||null===e?e:Array.isArray(e)?e.map(e=>this.#e(e)):Object.entries(e).reduce((e,[t,r])=>(e[t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)]="object"==typeof r&&null!==r?this.#e(r):r,e),{})}}module.exports={HapiServerKeycloak:HapiServerKeycloak};
@@ -0,0 +1,13 @@
1
+ export class HapiServerSimToken {
2
+ constructor(openIdConnect: any, cookiesName: any, cache: any);
3
+ openIdConnect: any;
4
+ COOKIE_NAMES: any;
5
+ authServerConfig: any;
6
+ cache: any;
7
+ clientOidc: any;
8
+ connect(_securityService: any, hapiServer: any, config: any): Promise<void>;
9
+ authServerSimulation(hapiServer: any): void;
10
+ authenticate(h: any, scope: any): Promise<any>;
11
+ oidcMetadataKey(): any;
12
+ configuration(authServer: any): Promise<any>;
13
+ }
@@ -0,0 +1 @@
1
+ const{Exception:Exception,getFullUrl:getFullUrl,getHost:getHost,getPathname:getPathname,getTokenTolerance:getTokenTolerance,trace:trace}=require("../helpers/utils"),{Issuer:Issuer}=require("openid-client"),jwToken=require("jsonwebtoken");let securityService=null;class HapiServerSimToken{constructor(e,t,n){this.openIdConnect=e,this.COOKIE_NAMES=t,this.authServerConfig=null,this.cache=n,this.clientOidc=null}async connect(e,t,n){this.authServerConfig=n,securityService=e;t.config=n,t.state(this.COOKIE_NAMES.ACCESS_TOKEN,{clearInvalid:!0,encoding:"base64",isSecure:!0,isHttpOnly:!0,isSameSite:"Lax",path:"/",strictHeader:!0}),this.authServerSimulation(t)}authServerSimulation(e){if(!e.config||!e.config.accessTokenSimulation)throw new Exception("Error parsing metadata for simulation","ConfigurationError",404);let{simaAlgorithm:t,payload:n,secret:i}=e.config.accessTokenSimulation;const r=this;e.ext("onPreAuth",async function(e,o){if(e.state&&e.state[r.COOKIE_NAMES.ACCESS_TOKEN])return o.continue;{switch(t){case"HMAC-SHA384":t="HS384";break;case"HMAC-SHA512":t="HS512";break;default:t="HS256"}const s=jwToken.sign(n,i,{expiresIn:"1h",algorithm:t});return o.response().state(r.COOKIE_NAMES.ACCESS_TOKEN,s).redirect(getFullUrl(e)).takeover()}}),e.route({path:"/get-authorization",method:"GET",handler:async function(e,t){return t.response("[]").code(200)}}),e.route({path:"/get-security-rules",method:"GET",handler:async function(t,n){let i=[];if(securityService&&e.config.accessTokenSimulation.playload){const t=securityService.getGroups(e.config.accessTokenSimulation.playload);i=securityService.getFrontendSecurityRules([t])}return n.response(JSON.stringify(i)).code(200)}}),e.route({path:"/get-permissions",method:"GET",handler:async function(e,t){const n=securityService?securityService.getPermissions():[];return t.response(JSON.stringify(n)).code(200)}}),e.route({method:"GET",path:"/check-authorize",handler:async(e,t)=>{try{const n=e.query.path,i=e.query.action,r=e.query.roles,o=e.query.domains;let s,a;s=Array.isArray(r)?r:"string"==typeof r?r.split(",").map(e=>e.trim()):[],a=Array.isArray(o)?o:"string"==typeof o?o.split(",").map(e=>e.trim()):[];const c=await securityService.checkAuthorize(n,i,s,a);return t.response(JSON.stringify(c)).takeover()}catch(e){return errorResponse(t,e,401)}}}),e.route({path:"/get-user-info",method:"GET",handler:async function(e,t){return t.response(JSON.stringify(n)).code(200)}}),e.route({path:"/logout",method:"GET",handler:async function(e,t){return t.response().unstate(r.COOKIE_NAMES.ACCESS_TOKEN).takeover()}})}async authenticate(e,t){const{request:n}=e,i=await this.openIdConnect.pkceCode(),r=getFullUrl(n);let o=await this.openIdConnect.oidcMetadata();if(o&&o.openid_configuration||(o=await this.configuration(this.authServerConfig.authServer)),r.match(new RegExp(/^(https?:\/{2}.*):?(\d*)/.source+getHost(n)+/\/?$/.source))){const r=await this.openIdConnect.authorizationUrl({scope:t,redirectUri:getFullUrl(n),pkceCode:i});return trace("INFO",`Authenticate redirecting to ${r}`),e.response().state(this.COOKIE_NAMES.SID,i).redirect(r).takeover()}if("/logout"===getPathname(n))return e.continue;{const t=await this.openIdConnect.tokenSet(),{state:i}=n;if(t&&i&&i[this.COOKIE_NAMES.SESSION_STATE]){const n=await t.tokens(i[this.COOKIE_NAMES.SESSION_STATE]);if(!n||n.refresh_expires_in<=getTokenTolerance(0))throw new Exception("Error when getting token","ExpirationError",403);return e.continue}return e.response().code(401).takeover()}}oidcMetadataKey(){return this.authServerConfig.authServer.sessionCookiesDomain||"oidcMetadata"}async configuration(e){if(!e)throw new Exception("Error when getting configuration attributes ");const{clientId:t,clientSecret:n}=e;return await this.openIdConnect.client({clientId:t,clientSecret:n}),e.openIdConfigurationEndpoint?await this.openIdConnect.configuration(e.openIdConfigurationEndpoint):await this.openIdConnect.configuration({issuer:e.issuer,authorization_endpoint:e.authorizationEndpoint,token_endpoint:e.tokenEndpoint,userinfo_endpoint:e.userinfoEndpoint,end_session_endpoint:e.endSessionEndpoint,jwks_uri:e.jwksUri})}async configuration(e){let t=await this.cache.get(this.oidcMetadataKey());if("string"==typeof e&&!e.match(/(https?:\/\/.*):?(\d*)\/?(.*)/gi))throw new Exception("Wrong OpenId Provider configuration URI entered","AttributeError",403);return t&&t.issuer||(e.issuer?t={...t||{},...e}:(t=t||{},t.openid_configuration=e,t={...t,...await Issuer.discover(e.issuer)}),await this.cache.set(this.oidcMetadataKey(),t,864e5)),new Iss(t)}}module.exports={HapiServerSimToken:HapiServerSimToken};
@@ -0,0 +1,14 @@
1
+ export class Hapi {
2
+ constructor(oidc: any, cookiesName: any);
3
+ oidc: any;
4
+ COOKIE_NAMES: any;
5
+ activateTraceApiMethod: boolean;
6
+ queryStringLimit: any;
7
+ securityLoginTokenExpToleranceSeconds: number;
8
+ connect(_securityService: any, context: any, config: any): Promise<void>;
9
+ validSid(sid: any): boolean;
10
+ authServerSimulation(context: any): void;
11
+ getRedirectUri(request: any): any;
12
+ authenticate(h: any, scope: any): Promise<any>;
13
+ configuration(authServer: any): Promise<any>;
14
+ }
@@ -0,0 +1 @@
1
+ const Uma=require("../implementations/uma"),Jsonwebtoken=require("jsonwebtoken"),{Exception:Exception,getFullUrl:getFullUrl,getHost:getHost,getPathname:getPathname,getTemplate:getTemplate,getTokenTolerance:getTokenTolerance,trace:trace,errorResponse:errorResponse}=require("../helpers/utils");let contextConfig={},securityService=null;class Hapi{constructor(e,t){this.oidc=e,this.COOKIE_NAMES=t,this.activateTraceApiMethod=!1,this.queryStringLimit=null,this.securityLoginTokenExpToleranceSeconds=18e3}async connect(e,t,i){contextConfig=i,securityService=e;const{authServer:s,accessTokenSimulation:r,activateTraceApiMethod:n}=i;n&&(this.activateTraceApiMethod=n);let o={};const a={clearInvalid:!0,encoding:"base64",isSecure:!0,isHttpOnly:!0,isSameSite:"Lax",path:"/",strictHeader:!0};if(r&&!s)t.config=i,t.state(this.COOKIE_NAMES.ACCESS_TOKEN,a),this.authServerSimulation(t);else{try{s.sessionCookiesDomain&&(a.domain=s.sessionCookiesDomain);const e=void 0!==s.isHttpOnlyForSessionState&&s.isHttpOnlyForSessionState;t.state(this.COOKIE_NAMES.SID,a),a.encoding="none",a.strictHeader=!1,a.isHttpOnly=e,t.state(this.COOKIE_NAMES.SESSION_STATE,a),o=await this.configuration(s),s.scope&&s.scope.split(" ").some(e=>"openid"===e)||(s.scope=`openid ${s.scope||""}`),s.tokenEndpoint&&!s.tokenEndpoint.match(/https.*/)&&(t.states.cookies[this.COOKIE_NAMES.SID].isSecure=!1,t.states.cookies[this.COOKIE_NAMES.SESSION_STATE].isSecure=!1),trace("INFO","The following configuration was initialized");const i=Object.fromEntries(Object.entries(s).filter(e=>!["clientSecret","PrivateKey","PublicKey"].includes(e[0])));trace("INFO",o.tokenEndpoint?o:i)}catch(e){trace("ERROR",`Exception ${e.message}`),trace("ERROR",e.stack)}t.ext("onPreHandler",async(e,i)=>{const r=[/\/health/,/\/metrics/],n=[".ico",".jpg",".jpeg",".gif",".png",".pdf",".svg",".html",".htm",".css",".js",".js.map",".json",".woff",".woff2"],o=getFullUrl(e);this.activateTraceApiMethod&&o.includes("/api/")&&console.log(o+" - "+e.method.toUpperCase());try{const{session_state:a,code:c}=e.query,u=e.state[this.COOKIE_NAMES.SESSION_STATE],S=e.state[this.COOKIE_NAMES.SID],h=await this.oidc.tokenSet(),d=await Uma.permission(),E=i.request.url.href||o;if(this.queryStringLimit){const{limit:t}=e.query;if(t&&parseInt(t,10)>this.queryStringLimit){const e=new Error("Bad Request.");throw e.name="BadRequest",e.code=400,e}}if(r.some(t=>t.test(e.path))||n.some(e=>o.endsWith(e)))return i.continue;if(getHost(e).includes("0.0.0.0")&&t.states.cookies[this.COOKIE_NAMES.SID].isSecure&&(trace("WARN",`Accessing ${getHost(e)} doesn't ensure a secure context for writing cookies.`),t.states.cookies[this.COOKIE_NAMES.SID].isSecure=!1,t.states.cookies[this.COOKIE_NAMES.SESSION_STATE].isSecure=!1),trace("INFO",`Navigating to ${o}`),e.state){if(c&&u&&a&&a!==u)return trace("ERROR",`The Session cookie ${u} doesn't match with the query session ${a}`),i.response().unstate(this.COOKIE_NAMES.SID).unstate(this.COOKIE_NAMES.SESSION_STATE).redirect(o).takeover();if(u&&S){const e=await h.tokens(u);if(s.umaUri){let t=!1;const i=E.split("/");if(i.length>0){t=-1!==i[i.length-1].indexOf(".")}t||(e.access_token=await d.ticket({tokenUrl:s.tokenEndpoint,token:e.access_token,audience:s.clientId}),trace("INFO","Generating uma ticket:"))}if(this.validSid(S))return i.continue;{const e=new Error("Invalid sid.");throw e.name="ExpiredSid",e.code=401,e}}if(c&&S){trace("INFO","Generating token:");const t=await h.generate({code:c,scope:s.scope,redirectUri:this.getRedirectUri(e),sid:S});return t?(trace("INFO",`Set token for session_state:${t.session_state}`),i.response().state(this.COOKIE_NAMES.SID,S).state(this.COOKIE_NAMES.SESSION_STATE,t.session_state).redirect(o).takeover()):await this.authenticate(i,s.scope)}if(!S&&u||!u&&S){const e=new Error("Token is Invalid.");throw e.name="TokenInvalid",e.code=401,e}return await this.authenticate(i,s.scope)}throw new Exception("Error when getting cookies","CookiesError",404)}catch(t){let{code:s,name:r,message:n}=t;trace("ERROR",`${r}:${n}`),s=parseInt(s)||(t.response?t.response.statusCode:500);return["pkce","code","jwt"].some(e=>n.includes(e))&&403!==s?(trace("ERROR",`Forbidden ${n}`),i.response().unstate(this.COOKIE_NAMES.SID).unstate(this.COOKIE_NAMES.SESSION_STATE).redirect(o).takeover()):403===s||401===s?"ExpirationError"===r||"TokenInvalid"===r||"TokenError"===r&&"/"===getPathname(e)?i.response().unstate(this.COOKIE_NAMES.SID).unstate(this.COOKIE_NAMES.SESSION_STATE).redirect("/logout").takeover():"ExpiredSid"===r?i.response().unstate(this.COOKIE_NAMES.SID).unstate(this.COOKIE_NAMES.SESSION_STATE).code(401).redirect("/logout").takeover():i.response().code(401).unstate(this.COOKIE_NAMES.SID).unstate(this.COOKIE_NAMES.SESSION_STATE).takeover():i.response({name:r,message:n}).code(s||500).unstate(this.COOKIE_NAMES.SID).unstate(this.COOKIE_NAMES.SESSION_STATE).takeover()}});const e=this;t.route({method:"GET",path:"/get-authorization",handler:async(t,i)=>{try{const{session_state:r}=t.state;if(!r)throw new Exception("old Hapi get-authorization: Session cookie doesn't exist.","CookiesError",404);const n=await e.oidc.tokenSet(),o=await n.tokens(r),a=await Uma.permission(),c=await a.ticket({tokenUrl:s.tokenEndpoint||s.tokenUrl,token:o.access_token,audience:s.clientId}),u=Jsonwebtoken.decode(c.access_token);return i.response(JSON.stringify(u.authorization)).takeover()}catch(e){return errorResponse(i,e,401)}}}),t.route({method:"GET",path:"/get-security-rules",handler:async(e,t)=>{try{const i=await securityService.getFrontendSecurityRules(e);return t.response(JSON.stringify(i)).takeover()}catch(e){return errorResponse(t,e,401)}}}),t.route({method:"GET",path:"/get-permissions",handler:async(e,t)=>{try{const e=await securityService.getPermissions();return t.response(JSON.stringify(e)).takeover()}catch(e){return errorResponse(t,e,401)}}}),t.route({method:"GET",path:"/check-authorize",handler:async(e,t)=>{try{const i=e.query.path,s=e.query.action,r=e.query.roles,n=e.query.domains;let o,a;o=Array.isArray(r)?r:"string"==typeof r?r.split(",").map(e=>e.trim()):[],a=Array.isArray(n)?n:"string"==typeof n?n.split(",").map(e=>e.trim()):[];const c=await securityService.checkAuthorize(i,s,o,a);return t.response(JSON.stringify(c)).takeover()}catch(e){return errorResponse(t,e,401)}}}),t.route({method:"GET",path:"/get-user-info",handler:async(e,t)=>{try{const i=await securityService.getUserInfo(e);return t.response(JSON.stringify(i)).takeover()}catch(e){return errorResponse(t,e,500)}}}),t.route({path:"/logout",method:"GET",handler:async(t,i)=>{try{const s=t.state[this.COOKIE_NAMES.SESSION_STATE];return i.response().unstate(this.COOKIE_NAMES.SID).unstate(this.COOKIE_NAMES.SESSION_STATE).redirect(await e.oidc.endSessionUrl({sessionState:s,redirectUri:this.getRedirectUri(t)})).takeover()}catch(e){return errorResponse(i,e,500)}}}),t.route({path:"/invalid-session",method:"GET",handler:async(t,i)=>{try{const s=await e.oidc.endSessionUrl({redirectUri:this.getRedirectUri(t),sessionState:t.state[this.COOKIE_NAMES.SESSION_STATE]});return i.response().unstate(this.COOKIE_NAMES.SID).unstate(this.COOKIE_NAMES.SESSION_STATE).redirect(s).takeover()}catch(e){return errorResponse(i,e,500)}}}),t.route({path:"/check-session-iframe.html",method:"GET",handler:async(e,t)=>{try{let e="<html/>";if(s&&s.checkSessionIframe){const{checkSessionIframe:t,clientId:i,sessionCookiesPrefix:r}=s;t&&t.includes("https://")?(trace("INFO",`Session management url: ${t}`),e=getTemplate("session-iframe",{sessionIframeUrl:t,clientId:i,sessionCookiesPrefix:r||""})):trace("WARN","For session management, it is necessary to get the value from a cookie called session_state, and as a good practice, it should have reached a secure context [TLS].")}return t.response(e).header("Content-Type","text/html")}catch(e){return errorResponse(t,e,500)}}})}}validSid(e){let t=Jsonwebtoken.decode(e);return!!t&&(!!t.exp&&t.exp+this.securityLoginTokenExpToleranceSeconds>Date.now()/1e3)}authServerSimulation(e){if(!e.config||!e.config.accessTokenSimulation)throw new Exception("Error parsing metadata for simulation","ConfigurationError",404);let{algorithm:t,payload:i,secret:s}=e.config.accessTokenSimulation;const r=this;e.ext("onPreAuth",async function(e,n){if(e.state&&e.state[r.COOKIE_NAMES.ACCESS_TOKEN])return n.continue;{switch(t){case"HMAC-SHA384":t="HS384";break;case"HMAC-SHA512":t="HS512";break;default:t="HS256"}const o=r.oidc.jwt().sign({payload:i,secret:s,algorithm:t});return n.response().state(r.COOKIE_NAMES.ACCESS_TOKEN,o).redirect(r.getRedirectUri(e)).takeover()}}),e.route({path:"/get-authorization",method:"GET",handler:async function(e,t){return t.response("[]").code(200)}}),e.route({path:"/get-security-rules",method:"GET",handler:async function(t,i){let s=[];if(securityService&&e.config.accessTokenSimulation.playload){const t=securityService.getGroups(e.config.accessTokenSimulation.playload);s=securityService.getFrontendSecurityRules([t])}return i.response(JSON.stringify(s)).code(200)}}),e.route({path:"/get-permissions",method:"GET",handler:async function(e,t){const i=securityService?securityService.getPermissions():[];return t.response(JSON.stringify(i)).code(200)}}),e.route({path:"/get-user-info",method:"GET",handler:async function(e,t){return t.response(JSON.stringify(i)).code(200)}}),e.route({path:"/logout",method:"GET",handler:async function(e,t){return t.response().unstate(this.COOKIE_NAMES.ACCESS_TOKEN).takeover()}})}getRedirectUri(e){return contextConfig.authServer.redirectUri||getFullUrl(e)}async authenticate(e,t){const{request:i}=e,s=await this.oidc.pkceCode(),r=getFullUrl(i);let n=await this.oidc.oidcMetadata();if(n&&n.openid_configuration||(n=await this.configuration(contextConfig.authServer)),r.match(new RegExp(/^(https?:\/{2}.*):?(\d*)/.source+getHost(i)+/\/?$/.source))){const r=await this.oidc.authorizationUrl({scope:t,redirectUri:this.getRedirectUri(i),pkceCode:s});return trace("INFO",`Authenticate redirecting to ${r}`),e.response().state(this.COOKIE_NAMES.SID,s).redirect(r).takeover()}if("/logout"===getPathname(i))return e.continue;{const t=await this.oidc.tokenSet(),{state:s}=i;if(t&&s&&s[this.COOKIE_NAMES.SESSION_STATE]){const i=await t.tokens(s[this.COOKIE_NAMES.SESSION_STATE]);if(!i||i.refresh_expires_in<=getTokenTolerance(0))throw new Exception("Error when getting token","ExpirationError",403);return e.continue}return e.response().code(401).takeover()}}async configuration(e){if(!e)throw new Exception("Error when getting configuration attributes ");const{clientId:t,clientSecret:i}=e;return await this.oidc.client({clientId:t,clientSecret:i}),e.openIdConfigurationEndpoint?await this.oidc.configuration(e.openIdConfigurationEndpoint):await this.oidc.configuration({issuer:e.issuer,authorization_endpoint:e.authorizationEndpoint,token_endpoint:e.tokenEndpoint,userinfo_endpoint:e.userinfoEndpoint,end_session_endpoint:e.endSessionEndpoint,jwks_uri:e.jwksUri})}}module.exports={Hapi:Hapi};
@@ -0,0 +1 @@
1
+ const Uma=require("../implementations/uma"),Jsonwebtoken=require("jsonwebtoken"),{Exception:Exception,getFullUrl:getFullUrl,getHost:getHost,getProtocol:getProtocol,getPathname:getPathname,getTemplate:getTemplate,getTokenTolerance:getTokenTolerance,trace:trace,errorResponse:errorResponse}=require("../helpers/utils"),hapiYar=require("@hapi/yar"),hapiJwt=require("@hapi/jwt"),hapiCookie=require("@hapi/cookie"),axios=require("axios"),crypto=require("crypto");var jwkToPem=require("jwk-to-pem");const{Issuer:Issuer,generators:generators,custom:custom}=require("openid-client"),{METADATA:METADATA}=require("../helpers/consts"),jwksClient=require("jwks-rsa"),{ConfidentialClientApplication:ConfidentialClientApplication}=require("@azure/msal-node");let contextConfig={},securityService=null;class HapiServer{constructor(e,t,r){this.openIdConnect=e,this.COOKIE_NAMES=t,this.activateTraceApiMethod=!1,this.queryStringLimit=null,this.securityLoginTokenExpToleranceSeconds=18e3,this.authServerConfig=null,this.authServerFullLoginUrl=null,this.cache=r,this.clientOidc=null,this.clientJwk=null,this.publicKeyFetch=null}async connect(e,t,r){contextConfig=r,this.authServerConfig=contextConfig,securityService=e;const{authServer:o,accessTokenSimulation:n,activateTraceApiMethod:i}=r;i&&(this.activateTraceApiMethod=i);let s={};const a={clearInvalid:!0,encoding:"base64",isSecure:!0,isHttpOnly:!0,isSameSite:"Lax",path:"/",strictHeader:!0};if(n&&!o)t.config=r,t.state(this.COOKIE_NAMES.ACCESS_TOKEN,a),this.authServerSimulation(context);else{try{o.sessionCookiesDomain&&(a.domain=o.sessionCookiesDomain);void 0!==o.isHttpOnlyForSessionState&&o.isHttpOnlyForSessionState;t.state(this.COOKIE_NAMES.SESSION_STATE,a),s=await this.configuration(o),s.clientOidc&&(this.clientOidc=s.clientOidc),o.scope&&o.scope.split(" ").some(e=>"openid"===e)||(o.scope=`openid ${o.scope||""}`),o.tokenEndpoint&&!o.tokenEndpoint.match(/https.*/)&&(t.states.cookies[this.COOKIE_NAMES.SID].isSecure=!1,t.states.cookies[this.COOKIE_NAMES.SESSION_STATE].isSecure=!1),trace("INFO","The following configuration was initialized");const e=Object.fromEntries(Object.entries(o).filter(e=>!["clientSecret","PrivateKey","PublicKey"].includes(e[0])));trace("INFO",s.tokenEndpoint?s:e)}catch(e){trace("ERROR",`Exception ${e.message}`),trace("ERROR",e.stack)}this.prepareMemoryValues(),this.configurePlugins(t),t.ext("onPreAuth",async(t,r)=>{let o=t.yar.get("jwtToken");if(o){if(await e.tokenAboutToExpire(o.token,10))if(e.authServerConfig.authServer.msalClient){const n=await e.authServerConfig.authServer.msalClient.acquireTokenSilent({account:o.account,scopes:["User.Read"]});if(!n||!n.idToken)return t.yar.get("jwtToken",!0),await t.yar.commit(r),delete t.headers.authorization,r.continue;{const e=t.yar.get("session");t.yar.set("session",{...e,token:n.accessToken});const o={tokenType:"Bearer"};o.token=n.idToken,o.tokenSubType="id_token",o.account=n.account,t.yar.set("jwtToken",o),await t.yar.commit(r)}}else{if(await this.isRefreshTokenExpired(o.refreshToken)&&"refreshToken"in o)return t.yar.get("jwtToken",!0),delete t.headers.authorization,await t.yar.commit(r),r.continue;{let e=await this.refreshToken(o.refreshToken);if(!(e&&e.token_type&&e.id_token&&e.session_state&&e.access_token&&e.refresh_token))return t.yar.get("jwtToken",!0),delete t.headers.authorization,await t.yar.commit(r),r.continue;{let n={tokenType:"Bearer",token:e.id_token,tokenSubType:"id_token",refreshToken:e.refresh_token};t.yar.set("jwtToken",n),await t.yar.commit(r),o=n}}}switch(o.tokenType){case"Bearer":case"bearer":t.headers.authorization=`Bearer ${o.token}`}}return r.continue}),t.ext("onPreResponse",async(t,r)=>{const n=t.response;let i=t.yar.get("authError",!0);if(n.isBoom&&401===n.output.statusCode&&!t.path.startsWith("/auth/callback")&&!i){if("ad-azure"===this.authServerConfig.authServer.provider)return r.redirect("/login").takeover();const n=crypto.randomBytes(32).toString("base64url");t.yar.set("code_verifier",n),t.yar.set("originalUrlPathName",e.getFullUrl(t)),await t.yar.commit(r);const i=crypto.createHash("sha256").update(n).digest("base64url"),s="code",a=e.getBaseUrl(t)+"auth/callback",c="S256",u=o.scope?o.scope.replace(/\s+/g,"%20"):"openid",h=new URL(o.authorizationEndpoint);return h.searchParams.set("client_id",e.authServerConfig.authServer.clientId),h.searchParams.set("response_type",s),h.searchParams.set("redirect_uri",a),h.searchParams.set("scope",u),h.searchParams.set("code_challenge",i),h.searchParams.set("code_challenge_method",c),r.redirect(h.toString()).takeover()}return r.continue}),t.route({method:"GET",path:"/login",options:{auth:!1},handler:async(t,r)=>{const o=await e.authServerConfig.authServer.msalClient.getAuthCodeUrl({redirectUri:e.getBaseUrl(t)+"auth/callback",scopes:["user.read"]});return r.redirect(o)}}),t.route({method:"GET",path:"/auth/callback",options:{auth:!1},handler:async(t,r)=>{const o=t.query.code;if(!o)return r.response("Authorization code missing").code(400);try{let n={};if(e.authServerConfig.authServer.msalClient){if(!o)return r.response("Missing authorization code").code(400);try{const r=await e.authServerConfig.authServer.msalClient.acquireTokenByCode({code:o,redirectUri:e.getBaseUrl(t)+"auth/callback",scopes:["user.read"]});t.yar.set("session",{token:r.accessToken,user:r.account}),n.tokenType="Bearer",n.token=r.idToken,n.tokenSubType="id_token",n.account=r.account}catch(e){return console.error("Auth error:",e),r.response("Authentication failed").code(500)}}else{let r=t.yar.get("code_verifier",!0);if(tokenResponse=await axios.post(e.authServerConfig.authServer.tokenEndpoint,new URLSearchParams({grant_type:"authorization_code",client_id:e.authServerConfig.authServer.clientId,client_secret:e.authServerConfig.authServer.clientSecret,code:o,redirect_uri:e.getRedirectUri(t),code_verifier:r}).toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded"}}),"OK"==!tokenResponse.statusText)throw new Error("Failed to exchange code for tokens");n.tokenType="Bearer",n.token=tokenResponse.data.id_token,n.tokenSubType="id_token",n.refreshToken=tokenResponse.data.refresh_token}let i=t.yar.get("originalUrlPathName")??"/";const s=t.query.session_state;switch(r.state(this.COOKIE_NAMES.SESSION_STATE,s),n.tokenType){case"Bearer":case"bearer":return t.yar.set("jwtToken",n),await t.yar.commit(r),r.redirect(i).takeover()}return r.continue}catch(e){return t.yar.set("authError",!0),await t.yar.commit(r),console.error("Failed to exchange code for token:",e.response?.data||e.message),r.response("Failed to authenticate").code(500).takeover()}}});const e=this;t.route({method:"GET",path:"/get-authorization",handler:async(t,r)=>{try{const{session_state:n}=t.state;if(!n)throw new Exception("Hapi get-authorization: Session cookie doesn't exist.","CookiesError",404);const i=await e.openIdConnect.tokenSet(),s=await i.tokens(n),a=await Uma.permission(),c=await a.ticket({tokenUrl:o.tokenEndpoint||o.tokenUrl,token:s.access_token,audience:o.clientId}),u=Jsonwebtoken.decode(c.access_token);return r.response(JSON.stringify(u.authorization)).takeover()}catch(e){return errorResponse(r,e,401)}}}),t.route({method:"GET",path:"/get-security-rules",handler:async(e,t)=>{try{const r=await securityService.getFrontendSecurityRules(e);return t.response(JSON.stringify(r)).takeover()}catch(e){return errorResponse(t,e,401)}}}),t.route({method:"GET",path:"/get-permissions",handler:async(e,t)=>{try{const e=await securityService.getPermissions();return t.response(JSON.stringify(e)).takeover()}catch(e){return errorResponse(t,e,401)}}}),context.route({method:"GET",path:"/check-authorize",handler:async(e,t)=>{try{const r=e.query.path,o=e.query.action,n=e.query.roles,i=e.query.domains;let s,a;s=Array.isArray(n)?n:"string"==typeof n?n.split(",").map(e=>e.trim()):[],a=Array.isArray(i)?i:"string"==typeof i?i.split(",").map(e=>e.trim()):[];const c=await securityService.checkAuthorize(r,o,s,a);return t.response(JSON.stringify(c)).takeover()}catch(e){return errorResponse(t,e,401)}}}),t.route({method:"GET",path:"/get-user-info",handler:async(e,t)=>{try{const r=await securityService.getUserInfo(e);return t.response(JSON.stringify(r)).takeover()}catch(e){return errorResponse(t,e,500)}}}),t.route({path:"/logout",method:"GET",handler:async(t,r)=>{try{t.state[this.COOKIE_NAMES.SESSION_STATE];t.yar.clear("jwtToken"),await t.yar.commit(r);let o=await e.endSessionUrl(e.getRedirectUri(t),e.clientOidc);return r.response().unstate(this.COOKIE_NAMES.SID).unstate(this.COOKIE_NAMES.SESSION_STATE).unstate(this.COOKIE_NAMES.AUTH_TOKEN).redirect(o).takeover()}catch(e){return errorResponse(r,e,500)}}}),t.route({path:"/invalid-session",method:"GET",handler:async(t,r)=>{try{const o=await e.openIdConnect.endSessionUrl({redirectUri:this.getRedirectUri(t),sessionState:t.state[this.COOKIE_NAMES.SESSION_STATE]});return r.response().unstate(this.COOKIE_NAMES.SID).unstate(this.COOKIE_NAMES.SESSION_STATE).redirect(o).takeover()}catch(e){return errorResponse(r,e,500)}}}),t.route({path:"/check-session-iframe.html",method:"GET",handler:async(e,t)=>{try{let e="<html/>";if(o&&o.checkSessionIframe){const{checkSessionIframe:t,clientId:r,sessionCookiesPrefix:n}=o;t&&t.includes("https://")?(trace("INFO",`Session management url: ${t}`),e=getTemplate("session-iframe",{sessionIframeUrl:t,clientId:r,sessionCookiesPrefix:n||""})):trace("WARN","For session management, it is necessary to get the value from a cookie called session_state, and as a good practice, it should have reached a secure context [TLS].")}return t.response(e).header("Content-Type","text/html")}catch(e){return errorResponse(t,e,500)}}})}}authServerSimulation(e){if(!e.config||!e.config.accessTokenSimulation)throw new Exception("Error parsing metadata for simulation","ConfigurationError",404);let{algorithm:t,payload:r,secret:o}=e.config.accessTokenSimulation;const n=this;e.ext("onPreAuth",async function(e,i){if(e.state&&e.state[n.COOKIE_NAMES.ACCESS_TOKEN])return i.continue;{switch(t){case"HMAC-SHA384":t="HS384";break;case"HMAC-SHA512":t="HS512";break;default:t="HS256"}const s=n.openIdConnect.jwt().sign({payload:r,secret:o,algorithm:t});return i.response().state(n.COOKIE_NAMES.ACCESS_TOKEN,s).redirect(n.getRedirectUri(e)).takeover()}}),e.route({path:"/get-authorization",method:"GET",handler:async function(e,t){return t.response("[]").code(200)}}),e.route({path:"/get-security-rules",method:"GET",handler:async function(t,r){let o=[];if(securityService&&e.config.accessTokenSimulation.playload){const t=securityService.getGroups(e.config.accessTokenSimulation.playload);o=securityService.getFrontendSecurityRules([t])}return r.response(JSON.stringify(o)).code(200)}}),e.route({path:"/get-permissions",method:"GET",handler:async function(e,t){const r=securityService?securityService.getPermissions():[];return t.response(JSON.stringify(r)).code(200)}}),e.route({path:"/get-user-info",method:"GET",handler:async function(e,t){return t.response(JSON.stringify(r)).code(200)}}),e.route({path:"/logout",method:"GET",handler:async function(e,t){return t.response().unstate(this.COOKIE_NAMES.ACCESS_TOKEN).takeover()}})}getRedirectUri(e){return contextConfig.authServer.redirectUri||getFullUrl(e)}getFullUrl(e){return`${getProtocol(e)}://${getHost(e)}${getPathname(e)}`}getBaseUrl(e){return`${getProtocol(e)}://${getHost(e)}/`}async authenticate(e,t){const{request:r}=e,o=await this.openIdConnect.pkceCode(),n=getFullUrl(r);let i=await this.openIdConnect.oidcMetadata();if(i&&i.openid_configuration||(i=await this.configuration(contextConfig.authServer)),n.match(new RegExp(/^(https?:\/{2}.*):?(\d*)/.source+getHost(r)+/\/?$/.source))){const n=await this.openIdConnect.authorizationUrl({scope:t,redirectUri:this.getRedirectUri(r),pkceCode:o});return trace("INFO",`Authenticate redirecting to ${n}`),e.response().state(this.COOKIE_NAMES.SID,o).redirect(n).takeover()}if("/logout"===getPathname(r))return e.continue;{const t=await this.openIdConnect.tokenSet(),{state:o}=r;if(t&&o&&o[this.COOKIE_NAMES.SESSION_STATE]){const r=await t.tokens(o[this.COOKIE_NAMES.SESSION_STATE]);if(!r||r.refresh_expires_in<=getTokenTolerance(0))throw new Exception("Error when getting token","ExpirationError",403);return e.continue}return e.response().code(401).takeover()}}async configurePlugins(e){const t=process.env.blz_hapiYarPassword||"your-super-secure-yar-atleast-32-bytes-password";await e.register({plugin:hapiYar,options:{cookieOptions:{password:t,isSecure:!0,isHttpOnly:!0,isSameSite:"Lax",clearInvalid:!0,ignoreErrors:!0},storeBlank:!1,maxCookieSize:0}}),await e.register(hapiJwt);let r=!0;if(this.startupJwksClient(),this.startupPublickKeyFetch(),r=this.publicKeyFetch,"ad-azure"===this.authServerConfig.authServer.provider){const e=this.authServerConfig.authServer.issuer.match(/login\.microsoftonline\.com\/([^/]+)/)?.[1];this.authServerConfig.authServer.msalConfig={auth:{clientId:this.authServerConfig.authServer.clientId,authority:`https://login.microsoftonline.com/${e}`,clientSecret:this.authServerConfig.authServer.clientSecret}};const t=new ConfidentialClientApplication(this.authServerConfig.authServer.msalConfig);this.authServerConfig.authServer.msalClient=t}e.auth.strategy("jwtAuth","jwt",{keys:r,verify:{aud:this.authServerConfig.authServer.clientId,iss:this.authServerConfig.authServer.issuer,exp:!0,sub:!1},validate:!1}),await e.register(hapiCookie);const o=process.env.blz_hapiCookiePassword||"supersecretpasswordmustbeatleast32characterslong";e.auth.strategy("cookieAuth","cookie",{cookie:{name:"sid",password:o,isSecure:!0,isHttpOnly:!0,isSameSite:"Lax"},keepAlive:!0,redirectTo:!1}),e.auth.default({strategies:["jwtAuth","cookieAuth"]})}async configuration(e){if(!e)throw new Exception("Error when getting configuration attributes ");const{clientId:t,clientSecret:r}=e;return await this.openIdConnect.client({clientId:t,clientSecret:r}),e.openIdConfigurationEndpoint?await this.openIdConnect.configuration(e.openIdConfigurationEndpoint):await this.openIdConnect.configuration({issuer:e.issuer,authorization_endpoint:e.authorizationEndpoint,token_endpoint:e.tokenEndpoint,userinfo_endpoint:e.userinfoEndpoint,end_session_endpoint:e.endSessionEndpoint,jwks_uri:e.jwksUri})}async prepareMemoryValues(){}async endSessionUrl(e,t){if(e=e.replace(/logout|invalid-session/gim,""),!t)throw new Error("Unable to get configuration from identity provider","ConfigurationError",404);return t.endSessionUrl({post_logout_redirect_uri:e})}oidcMetadataKey(){return this.authServerConfig.authServer.sessionCookiesDomain||"oidcMetadata"}async configuration(e){let t=await this.cache.get(this.oidcMetadataKey());if("string"==typeof e&&!e.match(/(https?:\/\/.*):?(\d*)\/?(.*)/gi))throw new Exception("Wrong OpenId Provider configuration URI entered","AttributeError",403);return t&&t.issuer||(e.issuer?t={...t||{},...e}:(t=t||{},t.openid_configuration=e,t={...t,...await Issuer.discover(e.issuer)}),await this.cache.set(this.oidcMetadataKey(),t,864e5)),new Iss(t)}async refreshToken(e){const t=await axios.post(this.authServerConfig.authServer.tokenEndpoint,new URLSearchParams({grant_type:"refresh_token",client_id:this.authServerConfig.authServer.clientId,client_secret:this.authServerConfig.authServer.clientSecret,refresh_token:e}).toString(),{headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(200!==t.status){const e=await t.json();return console.error("Error refreshing token:",e),e}try{return await t.json()}catch(e){}try{return t.data}catch{}}async decodeJwtToken(e){return hapiJwt.token.decode(e)}async tokenAboutToExpire(e,t=0){return 1e3*hapiJwt.token.decode(e).decoded.payload.exp-Date.now()<=60*t*1e3}async isRefreshTokenExpired(e){try{const t=hapiJwt.token.decode(e),r=Math.floor(Date.now()/1e3);return!(t&&t.decoded&&t.decoded.payload&&t.decoded.payload.exp)||t.decoded.payload.exp<r}catch(e){return console.error("Failed to decode the token: Invalid Refresh token format",e),!0}}async silentAuthenticationAzure({redirectUri:e,idToken:t}){const r=this.authServerConfig.authServer.authorizationEndpoint,o=await this.decodeJwtToken(t);try{const t=(await axios.get(r,{params:{client_id:this.authServerConfig.authServer.clientId,response_type:"id_token",redirect_uri:e,scope:this.authServerConfig.authServer.scope??"openid",prompt:"none",response_mode:"fragment",nonce:"random_nonce",login_hint:o.decoded.payload.preferred_username},maxRedirects:0,validateStatus:e=>302===e})).headers.location;if(!t)throw new Error("No redirect location found");const n=new URLSearchParams(t.split("#")[1]);if(n.has("id_token"))return{idToken:n.get("id_token")};throw new Error("No ID token returned")}catch(e){return console.error("Silent authentication failed:",e.response?.data||e.message),null}}async startupJwksClient(){this.clientJwk=jwksClient({jwksUri:this.authServerConfig.authServer.jwksUri,cache:!0,rateLimit:!0,jwksRequestsPerMinute:10})}async startupPublickKeyFetch(){const e=async e=>new Promise((t,r)=>{this.clientJwk.getSigningKey(e,(e,o)=>{if(e)return r(e);const n=o.getPublicKey();t(n)})});this.publicKeyFetch=async t=>{const r=t.decoded.header.kid;return e(r)}}}class Iss{constructor(e){e.id_token_signing_alg_values_supported||(e.id_token_signing_alg_values_supported=["RS256"]),e.response_types_supported||(e.response_types_supported=["code","none","id_token","token","id_token token","code id_token","code token","code id_token token"]),e.subject_types_supported||(e.subject_types_supported=["public"]);const t=METADATA.filter(({type:e})=>"REQUIRED"===e),r=[];for(const o of t){const t=e[o.name.toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase())];e[o.name]||t||r.push(o)}if(r.length>0)throw console.error(JSON.stringify(r)),new Error(JSON.stringify(r));const o=e.Client?e:new Issuer(this.#e(e)),n={client_id:e.clientId,response_type:"code"};e.clientSecret&&(n.client_secret=e.clientSecret),this.clientOidc=new o.Client(n)}#e(e){return"object"!=typeof e||null===e?e:Array.isArray(e)?e.map(e=>this.#e(e)):Object.entries(e).reduce((e,[t,r])=>(e[t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)]="object"==typeof r&&null!==r?this.#e(r):r,e),{})}}module.exports={HapiServer:HapiServer};
@@ -0,0 +1,6 @@
1
+ export = NavigationMemoryRepository;
2
+ declare class NavigationMemoryRepository {
3
+ _navigation: any[];
4
+ push(navigation: any): Promise<void>;
5
+ get(): Promise<any[]>;
6
+ }
@@ -0,0 +1 @@
1
+ module.exports=class{constructor(){this._navigation=[]}async push(t){this._navigation.push(t)}async get(){return structuredClone(this._navigation)}};
@@ -0,0 +1,15 @@
1
+ export = NavigationMongoDbRepository;
2
+ declare class NavigationMongoDbRepository {
3
+ constructor(url: any, database: any, collectionName: any, certificate: any);
4
+ client: MongoClient;
5
+ database: any;
6
+ collectionName: any;
7
+ connected: boolean;
8
+ connect(): Promise<void>;
9
+ db: import("mongodb").Db;
10
+ collection: import("mongodb").Collection<import("bson").Document>;
11
+ close(): Promise<void>;
12
+ push(navigation: any): Promise<string>;
13
+ get(): Promise<import("mongodb").WithId<import("bson").Document>[]>;
14
+ }
15
+ import { MongoClient } from "mongodb";
@@ -0,0 +1 @@
1
+ const{MongoClient:MongoClient}=require("mongodb"),fs=require("fs");module.exports=class{constructor(t,o,n,e){if(e){const o="/tmp/mongo-cert.pem";fs.writeFileSync(o,e),this.client=new MongoClient(t,{tls:!0,tlsCAFile:o})}else this.client=new MongoClient(t);this.database=o,this.collectionName=n,this.connected=!1}async connect(){if(!this.connected)try{await this.client.connect(),this.db=this.client.db(this.database),this.collection=this.db.collection(this.collectionName),this.connected=!0,console.log("Navigation info Connected to MongoDB.")}catch(t){throw console.error("Failed Navigation info to connect to MongoDB:",t),t}}async close(){if(this.connected)try{await this.client.close(),this.connected=!1,console.log("Connection to MongoDB closed.")}catch(t){throw console.error("Failed to close MongoDB connection:",t),t}}async push(t){this.connected||await this.connect();try{return(await this.collection.insertOne(t)).insertedId.toString()}catch(t){throw console.error("Failed to insert navigation:",t),t}}async get(){this.connected||await this.connect();try{const t=this.collection.find({});return await t.toArray()}catch(t){throw console.error("Failed to get navigation:",t),t}}};
@@ -0,0 +1,7 @@
1
+ export = SecureUrlService;
2
+ declare class SecureUrlService {
3
+ constructor(logger?: Console);
4
+ logger: Console;
5
+ validate(url: any, token: any, _session_key: any, timeoutMs: any): void;
6
+ createToken(url: any, _session_key: any): string;
7
+ }
@@ -0,0 +1 @@
1
+ const{Exception:Exception,isBase64:isBase64}=require("./helpers/utils"),CryptoJS=require("crypto-js");module.exports=class{constructor(e=console){this.logger=e}validate(e,r,t,o){const n=decodeURIComponent(e.split("?")[0]);if(!r)throw this.logger.error(`Token parameter 'sut' is missing in the URL. path:${n}`),new Exception("Token parameter 'sut' is missing in the URL.","SecureUrlError",404);const i=isBase64(t)?atob(t):t,s=`${i}${btoa(n)}`,a=CryptoJS.AES.decrypt(decodeURIComponent(r),s).toString(CryptoJS.enc.Utf8);if(!a)throw this.logger.error(`Token decryption failed or is invalid. token:${r} path:${n} session: ${i}`),new Exception("Token decryption failed or is invalid.","SecureUrlError",404);let c;try{c=parseInt(JSON.parse(a))}catch(e){throw this.logger.error(`Malformed token content. path:${n} error: ${e.message}`),new Exception("Malformed token content.","SecureUrlError",400)}const p=Date.now(),l=Math.abs(p-c),h=parseInt(o,10);if(!(l<=h))throw this.logger.error(`The token has expired. path:${n} requestTime:${c} now: ${p} limit:${h} diff:${l}`),new Exception("The token has expired.","SecureUrlError",410)}createToken(e,r){const t=e.split("?")[0],o=`${isBase64(r)?atob(r):r}${btoa(decodeURIComponent(t))}`,n=CryptoJS.AES.encrypt(Date.now().toString(),o).toString();return encodeURIComponent(n)}};
@@ -0,0 +1,72 @@
1
+ export = SecurityService;
2
+ declare class SecurityService {
3
+ constructor(authorizationService: any, sqlInjectionGuard: any, xssGuard: any, navigationRepository: any, secureUrlService: any, logger: any);
4
+ authorizationService: any;
5
+ sqlInjectionGuard: any;
6
+ xssGuard: any;
7
+ navigationRepository: any;
8
+ secureUrlService: any;
9
+ logger: any;
10
+ cookiesName: {
11
+ ACCESS_TOKEN: string;
12
+ SID: string;
13
+ SESSION_STATE: string;
14
+ SESSION: string;
15
+ };
16
+ blzConfig: any;
17
+ oidc: Oidc;
18
+ hapi: Hapi;
19
+ config: any;
20
+ middleware: any;
21
+ protected: boolean;
22
+ unProtected: any[];
23
+ useHapiServerFullStack: boolean;
24
+ pushNavigation(navigation: any): Promise<any>;
25
+ getNavigation(): Promise<any>;
26
+ setBlzConfig(blzConfig: any): void;
27
+ sanitizeSqlParams(params: any): any;
28
+ sanitizeSql(sql: any): any;
29
+ isExcludedFromSanitize(method: any, path: any): boolean;
30
+ validateObject(obj: any): any;
31
+ validateSqlObject(obj: any): any;
32
+ initializeCookiesNames(): void;
33
+ getRoleProperty(): any;
34
+ getUseTonkenName(): any;
35
+ getRoles(request: any): Promise<any>;
36
+ getCookieName(cookieName?: string): string;
37
+ getCache(config: any): LruCache | RedisCache;
38
+ protect(middleware: any, config: any): Promise<void>;
39
+ openIdConnect: Oidc;
40
+ hapiServer: HapiServerSimToken | HapiServerKeycloak | HapiServerAzureAd;
41
+ protectExperimental(cache: any): Promise<void>;
42
+ tokenSet(): Promise<{
43
+ tokens: (sessionState: any) => Promise<any>;
44
+ generate: ({ code, scope, redirectUri, sid }: any) => Promise<any>;
45
+ userInfo: (sessionState: string) => Promise<{
46
+ user_name: any;
47
+ }>;
48
+ }>;
49
+ getUseToken(sessionState: any, request: any): Promise<any>;
50
+ getSessionState(request: any): any;
51
+ getSecureUrlSessionKey(request: any): any;
52
+ enableSecureUrl(): boolean;
53
+ getSecureUrlCookieKey(): any;
54
+ validateSecureRequest(request: any): void;
55
+ getUserInfo(request: any): Promise<{}>;
56
+ extractAndDecodeToken(request: any, secretOrPublicKey: any): Promise<string | Jsonwebtoken.JwtPayload>;
57
+ extractTokenhNoDecode(request: any): Promise<any>;
58
+ importSecurityConfig(config: any): void;
59
+ getFrontendSecurityRules(request: any): Promise<any>;
60
+ getPermissions(): Promise<any>;
61
+ authorized(request: any): Promise<any>;
62
+ logUnProtected(): void;
63
+ checkAuthorize(path: any, action: any, roles: any, domains: any): Promise<any>;
64
+ }
65
+ import { Oidc } from "./implementations/oidc";
66
+ import { Hapi } from "./middleware/hapi";
67
+ import { LruCache } from "./implementations/cache";
68
+ import { RedisCache } from "./implementations/cache";
69
+ import { HapiServerSimToken } from "./middleware/HapiServerSimToken";
70
+ import { HapiServerKeycloak } from "./middleware/HapiServerKeycloak";
71
+ import { HapiServerAzureAd } from "./middleware/HapiServerAzureAd";
72
+ import Jsonwebtoken = require("jsonwebtoken");
@@ -0,0 +1 @@
1
+ const{Hapi:Hapi}=require("./middleware/hapi"),{Oidc:Oidc}=require("./implementations/oidc"),{HapiServerSimToken:HapiServerSimToken}=require("./middleware/HapiServerSimToken"),{HapiServerKeycloak:HapiServerKeycloak}=require("./middleware/HapiServerKeycloak"),{HapiServerAzureAd:HapiServerAzureAd}=require("./middleware/HapiServerAzureAd"),{RedisCache:RedisCache,LruCache:LruCache}=require("./implementations/cache"),{Exception:Exception,getMappingValues:getMappingValues}=require("./helpers/utils"),Jsonwebtoken=require("jsonwebtoken"),micromatch=require("micromatch");module.exports=class{constructor(e,t,i,r,o,s){this.authorizationService=e,this.sqlInjectionGuard=t,this.xssGuard=i,this.navigationRepository=r,this.secureUrlService=o,this.logger=s,this.cookiesName=null,this.blzConfig=null,this.oidc=null,this.hapi=null,this.config=null,this.middleware=null,this.protected=!1,this.unProtected=[],this.useHapiServerFullStack=!1}async pushNavigation(e){return this.navigationRepository?this.navigationRepository.push(e):null}async getNavigation(){return this.navigationRepository?this.navigationRepository.get():{}}setBlzConfig(e){this.blzConfig=e}sanitizeSqlParams(e){return this.sqlInjectionGuard.validateParamList(e)}sanitizeSql(e){return this.sqlInjectionGuard.validateRawSql(e)}isExcludedFromSanitize(e,t){const i=process.env.blz_securityExcludeSanitizePaths;if(!i||!i.trim())return!1;const r=i.split(",").map(e=>e.trim().toLowerCase()).filter(Boolean);return 0!==r.length&&r.some(i=>{let[r,o]=i.includes(":")?i.split(":"):[null,i];r=r?.toLowerCase();const s=o.replace(/\*\*/g,"**").replace(/\*/g,"*");return(!r||r===e.toLowerCase())&&micromatch.isMatch(t.toLowerCase(),s)})}validateObject(e){return this.sqlInjectionGuard.validateObject(this.xssGuard.sanitizeObject(e))}validateSqlObject(e){return this.sqlInjectionGuard.validateObject(e)}initializeCookiesNames(){this.cookiesName={ACCESS_TOKEN:this.getCookieName("access_token"),SID:this.getCookieName("sid"),SESSION_STATE:this.getCookieName("session_state"),SESSION:this.getCookieName("session")}}getRoleProperty(){const e=this.blzConfig.getConfig()||{};return e&&e.authServer&&e.authServer.roleProperty&&""!==e.authServer.roleProperty.trim()?e.authServer.roleProperty:"authorities"}getUseTonkenName(){return this.config.authServer.useTokenType||"access_token"}async getRoles(e){if(this.useHapiServerFullStack){const t=e.headers.authorization?.replace("Bearer ","");return Jsonwebtoken.decode(t)[this.getRoleProperty()]||[]}{const t=this.getSessionState(e),i=await this.tokenSet(),r=(await i.tokens(t))[this.getUseTonkenName()];return Jsonwebtoken.decode(r)[this.getRoleProperty()]||[]}}getCookieName(e=""){const t=this.blzConfig.getConfig()||{};return(t.authServer&&t.authServer.sessionCookiesPrefix||"")+e}getCache(e){if(process.env.SECURITY_REDIS_CACHE)return new RedisCache(process.env.SECURITY_REDIS_CACHE);if(e&&e.securityCache){const t=e.connections[e.securityCache];if(t&&"Redis"===t.type){const e=`redis://${t.user||""}:${t.password}@${t.host}:${t.port||"6379"}/${t.db||"0"}`;return new RedisCache(e)}return new LruCache}return new LruCache}async protect(e,t){if(!e)throw this.logger.error("The middleware context could not be analyzed"),new Exception("The middleware context could not be analyzed","MiddlewareError",403);if(!t||!t.callee&&!t.authServer&&!t.accessTokenSimulation)throw this.logger.error("Authorization server configuration is mandatory"),new Exception("Authorization server configuration is mandatory","ConfigurationError",403);this.config=t,this.middleware=e;const i=this.getCache(this.config);if(this.config.accessTokenSimulation)this.oidc=new Oidc(i,this.config),this.openIdConnect=new Oidc(this.getCache(this.config),this.config),this.hapiServer=new HapiServerSimToken(this.openIdConnect,this.cookiesName,i),await this.hapiServer.connect(this,this.middleware,this.config);else{if(t.authServer.useHapiServerFullStack)return this.useHapiServerFullStack=!0,this.oidc=new Oidc(i,this.config),await this.protectExperimental(i),void(this.protected=!0);this.oidc=new Oidc(i,this.config),this.hapi=new Hapi(this.oidc,this.cookiesName),this.protected=!0,this.config.queryStringLimit&&(this.hapi.queryStringLimit=this.config.queryStringLimit),this.config.securityLoginTokenExpToleranceSeconds&&(this.hapi.securityLoginTokenExpToleranceSeconds=this.config.securityLoginTokenExpToleranceSeconds),await this.hapi.connect(this,this.middleware,this.config),this.protected=!0}}async protectExperimental(e){"ad-azure"!==this.config.authServer.provider?this.hapiServer=new HapiServerKeycloak(this.openIdConnect,this.cookiesName,e):this.hapiServer=new HapiServerAzureAd(this.openIdConnect,this.cookiesName,e),this.openIdConnect=null,this.config.queryStringLimit&&(this.hapiServer.queryStringLimit=this.config.queryStringLimit),this.config.securityLoginTokenExpToleranceSeconds&&(this.hapiServer.securityLoginTokenExpToleranceSeconds=this.config.securityLoginTokenExpToleranceSeconds),await this.hapiServer.connect(this,this.middleware,this.config)}async tokenSet(){if(!this.oidc)throw this.logger.error("authServer and accessTokenSimulation undefined"),new Error("authServer and accessTokenSimulation undefined");return await this.oidc.tokenSet()}async getUseToken(e,t){return this.useHapiServerFullStack?this.extractTokenhNoDecode(t,this.config.authServer.PublicKey):this.config.accessTokenSimulation?void 0:this.oidc.getUseToken(e)}getSessionState(e){const t=e.state[this.cookiesName.SESSION_STATE],i=e.state[this.cookiesName.SESSION];if(t)return t;if(i)return i.id;throw this.logger.error("getSessionState: Session cookie doesn't exist."),new Exception("getSessionState: Session cookie doesn't exist.","CookiesError",404)}getSecureUrlSessionKey(e){const t=e.state[this.blzConfig.getConfig()?.parameters?.SecureUrlCookieKey];if(t)return t;throw this.logger.error("getSecureUrlSessionKey: Session cookie doesn't exist."),new Exception("getSecureUrlSessionKey: Session cookie doesn't exist.","CookiesError",404)}enableSecureUrl(){const e=this.blzConfig.getConfig()?.parameters?.SecureUrlCookieKey;return!!e&&"none"!==e}getSecureUrlCookieKey(){if(this.enableSecureUrl())return this.blzConfig.getConfig()?.parameters?.SecureUrlCookieKey}validateSecureRequest(e){if(!e)return;if(!this.enableSecureUrl())return;let t=this.getSecureUrlSessionKey(e);const i=new URLSearchParams(e.query).get("sut"),r=this.blzConfig.getConfig()?.parameters?.SecureUrlTimeoutMs||15e3;this.secureUrlService.validate(e.path,i,t,r)}async getUserInfo(e){let t=null,i={};if(this.useHapiServerFullStack)return t=await this.extractAndDecodeToken(e,this.config.authServer.PublicKey),t;{const r=this.getSessionState(e),o=await this.tokenSet();if(this.config.parameters&&this.config.parameters.UserInfoSource){const e=await o.tokens(r);t=Jsonwebtoken.decode(e[this.config.parameters.UserInfoSource])}else i=await o.userInfo(r),t=i}if(this.config.parameters&&this.config.parameters.UserInfoMapping){const e=JSON.parse(this.config.parameters.UserInfoMapping),r=getMappingValues(t,e);return{...i,...r}}return i}async extractAndDecodeToken(e,t){const i=e.headers.authorization;if(!i)throw this.logger.error("Authorization header is missing"),new Error("Authorization header is missing");const[r,o]=i.split(" ");if("Bearer"!==r&&"bearer"!==r||!o)throw this.logger.error("Authorization header must be in the format: Bearer <token>"),new Error("Authorization header must be in the format: Bearer <token>");if("ad-azure"!==this.hapiServer.authServerConfig.authServer.provider){const{artifacts:t}=e.auth;await this.hapiServer.publicKeyFetch(t)}try{return Jsonwebtoken.decode(o)}catch(e){throw this.logger.error(`Failed to decode token: ${e.message}`),new Error(`Failed to decode token: ${e.message}`)}}async extractTokenhNoDecode(e){const t=e.headers.authorization;if(!t)throw this.logger.error("Authorization header is missing"),new Error("Authorization header is missing");const[i,r]=t.split(" ");if("Bearer"!==i&&"bearer"!==i||!r)throw this.logger.error("Authorization header must be in the format: Bearer <token>"),new Error("Authorization header must be in the format: Bearer <token>");return r}importSecurityConfig(e){this.authorizationService.importSecurityConfig(e)}async getFrontendSecurityRules(e){if(!this.protected)throw this.logger.error("Cannot get the security rules if the application is not using JWt."),new Exception("Cannot get the security rules if the application is not using JWt.","SecurityRulesError",500);const t=e.headers.domains?e.headers.domains.split(","):[],i=await this.getRoles(e);return this.authorizationService.getFrontendSecurityRules(i,t)}async getPermissions(){return this.authorizationService.getPermissions()}async authorized(e){if(!this.protected)return!0;let t=null;if(this.useHapiServerFullStack){t=(await this.getUserInfo(e))[this.getRoleProperty()]}else t=await this.getRoles(e);const i=this.authorizationService.authorized(e.path,e.method,t);return null!=i?i:(this.config.activateTraceApiMethod&&!this.unProtected.some(t=>t.path===e.path&&t.method===e.method)&&this.unProtected.push({path:e.path,method:e.method}),!0)}logUnProtected(){this.logger.info("unprotected: "+JSON.stringify(this.unProtected))}async checkAuthorize(e,t,i,r){return this.authorizationService.checkAuthorize(e,t,i,r)}};
@@ -0,0 +1,37 @@
1
+ export = SqlInjectionGuard;
2
+ declare class SqlInjectionGuard {
3
+ constructor(logger?: Console);
4
+ logger: Console;
5
+ _initialized: boolean;
6
+ _initialize(): void;
7
+ onlyLog: boolean;
8
+ dangerousParamPatterns: any;
9
+ dangerousSqlPatterns: any;
10
+ allowedInputPatterns: any;
11
+ paramSchema: z.ZodObject<{
12
+ name: z.ZodString;
13
+ value: z.ZodAny;
14
+ }, "strip", z.ZodTypeAny, {
15
+ name?: string;
16
+ value?: any;
17
+ }, {
18
+ name?: string;
19
+ value?: any;
20
+ }>;
21
+ paramsSchema: z.ZodArray<z.ZodObject<{
22
+ name: z.ZodString;
23
+ value: z.ZodAny;
24
+ }, "strip", z.ZodTypeAny, {
25
+ name?: string;
26
+ value?: any;
27
+ }, {
28
+ name?: string;
29
+ value?: any;
30
+ }>, "many">;
31
+ isAllowedByWhitelist(value: any): any;
32
+ validateParamValue(name: any, value: any): void;
33
+ validateParamList(params: any): any;
34
+ validateRawSql(sql: any): string | false;
35
+ validateObject(obj: any): any;
36
+ }
37
+ import { z } from "zod";
@@ -0,0 +1 @@
1
+ const{z:z}=require("zod");module.exports=class{constructor(t=console){this.logger=t,this._initialized=!1}_initialize(){if(this._initialized)return;this._initialized=!0;const t=process.env.blz_securityApiSanitizeAllowedSqlInputPatterns,i=process.env.blz_securityApiSanitizeDangerousParamPatterns,e=process.env.blz_securityApiSanitizeDangerousSqlPatterns;this.onlyLog="true"===process.env.blz_securityApiSanitizeOnlyLog;const s=t=>{try{if(null==t||null==t)return null;return JSON.parse(t).map(t=>new RegExp(t,"i"))}catch{return null}};this.dangerousParamPatterns=s(i)||[/--/i,/\/\*/i,/\*\//i,/\bor\b\s+\w+\s*=/i,/\bor\b\s+.*?=.*?/i,/\bor\b\s+'.*?'\s*=\s*'.*?'/i,/\bor\b\s+\w+\s*like/i,/\band\b\s+\w+\s*=/i,/\band\b\s+\w+\s*like/i,/\bselect\b[\s\S]+?\bfrom\b/i,/\bunion\s+select\b/i,/\bdrop\s+table\b/i,/\binsert\s+into\b/i,/\bupdate\b\s+\w+\s+\bset\b[\s\S]*?=/i,/\bdelete\s+from\b/i,/\bpg_sleep\s*\(/i,/\bdbms_lock\.sleep\s*\(/i,/\bexec\s*\(/i,/\bexecute\s*\(/i],this.dangerousSqlPatterns=s(e)||[/;\s*drop\b/i,/;\s*truncate\b/i,/\bpg_sleep\s*\(/i,/\bdbms_lock\.sleep\s*\(/i,/\bexec(ute)?\s*(\(|\s)/i,/\binformation_schema\b/i,/\bpg_catalog\b/i],this.allowedInputPatterns=s(t)||[new RegExp("^[^<>]*<$","i"),new RegExp("^>[^<>]*$","i")],this.paramSchema=z.object({name:z.string(),value:z.any()}),this.paramsSchema=z.array(this.paramSchema)}isAllowedByWhitelist(t){return this.allowedInputPatterns.some(i=>i.test(t))}validateParamValue(t,i){if(this._initialize(),"string"!=typeof i)return;const e=i.trim();if(!this.isAllowedByWhitelist(e))for(const s of this.dangerousParamPatterns)if(s.test(e)){const e=`Potential SQL injection in parameter "${t}": ${i}`;if(!this.onlyLog){const t=new Error("Potential SQL injection");throw t.code="SQLInjection",t.data=e,t}this.logger?.warn?.(`[SQLInjectionGuard] ${e}`)}}validateParamList(t){this._initialize(),this.paramsSchema.parse(t);for(const i of t)this.validateParamValue(i.name,i.value);return t}validateRawSql(t){if(this._initialize(),"string"!=typeof t)return!1;for(const i of this.dangerousSqlPatterns)if(i.test(t.toLowerCase())){const e=`Potential SQL injection in "${t}" pattern:${i}`;if(!this.onlyLog){const t=new Error("Potential SQL injection");throw t.code="SQLInjection",t.data=e,t}this.logger.warn(`[SQLInjectionGuard] ${e}`)}return t}validateObject(t){this._initialize();const i=t=>{if("string"==typeof t){const i=t.trim();if(!this.isAllowedByWhitelist(i))for(const e of this.dangerousParamPatterns)if(e.test(i)){const i=`Value "${t}" violates SQL injection policy.`;if(!this.onlyLog){const t=new Error("Potential SQL injection");throw t.code="BadRequest",t.data=i,t}this.logger.warn(`[SQLInjectionGuard] ${i}`)}}else if(Array.isArray(t))for(const e of t)i(e);else if("object"==typeof t&&null!==t)for(const e in t)Object.hasOwn(t,e)&&i(t[e])};return i(t),t}};
@@ -0,0 +1,14 @@
1
+ export = XssGuard;
2
+ declare class XssGuard {
3
+ constructor(logger?: Console);
4
+ logger: Console;
5
+ DOMPurify: createDOMPurify.DOMPurify;
6
+ sanitizeOptions: {
7
+ ALLOWED_TAGS: any[];
8
+ ALLOWED_ATTR: any[];
9
+ };
10
+ isZipString(str: any): any;
11
+ isAllowedBlocklyXml(str: any): boolean;
12
+ sanitizeObject(obj: any): any;
13
+ }
14
+ import createDOMPurify = require("dompurify");
@@ -0,0 +1 @@
1
+ const{JSDOM:JSDOM}=require("jsdom"),createDOMPurify=require("dompurify");module.exports=class{constructor(t=console){this.logger=t;const e=new JSDOM("").window;this.DOMPurify=createDOMPurify(e),this.sanitizeOptions={ALLOWED_TAGS:[],ALLOWED_ATTR:[]}}isZipString(t){return t.startsWith("PK")}isAllowedBlocklyXml(t){return[/^<xml[\s\S]*<\/xml>$/i,/^<block[\s\S]*<\/block>$/i,/^<field name="[\w\-:]+">[\s\S]*<\/field>$/i,/^<value name="[\w\-:]+">[\s\S]*<\/value>$/i].some(e=>e.test(t))}sanitizeObject(t){const e=(t,i="")=>{if(null===t)return null;if(void 0===t)return;const r=toString.call(t);if("[object String]"===r){if(this.isZipString(t))return t;let e;try{e=decodeURIComponent(t)}catch{e=t}const r=e.trim();if(this.isAllowedBlocklyXml(r))return r;const n=this.DOMPurify.sanitize(r,this.sanitizeOptions);if(n!==r){const t=`Sanitized input at path "${i}". Original: "${r}", Cleaned: "${n}".`;this.logger.warn(t)}return n}if("[object Number]"===r)return t;if("[object Boolean]"===r)return t;if("[object Date]"===r)return t;if("[object Object]"===r&&"Buffer"===t.type&&t.data)return t;if(Array.isArray(t))return t.map((t,r)=>e(t,`${i}[${r}]`));if("object"==typeof t&&null!==t){const r={};for(const n in t)if(Object.hasOwn(t,n)){const o=i?`${i}.${n}`:n;r[n]=e(t[n],o)}return r}return t};return e(t)}};
@@ -0,0 +1,42 @@
1
+ export namespace _internal_ {
2
+ let htmlUnescapes: {
3
+ '&amp;': string;
4
+ '&lt;': string;
5
+ '&gt;': string;
6
+ '&quot;': string;
7
+ '&#39;': string;
8
+ };
9
+ let reEscapedHtml: RegExp;
10
+ let reHasEscapedHtml: RegExp;
11
+ let htmlEscapes: {
12
+ '&': string;
13
+ '<': string;
14
+ '>': string;
15
+ '"': string;
16
+ "'": string;
17
+ };
18
+ let reUnescapedHtml: RegExp;
19
+ let reHasUnescapedHtml: RegExp;
20
+ }
21
+ export function concat(...args: any[]): string;
22
+ export function contains(target: any, value: any): boolean;
23
+ export function endsWith(target: any, value: any): boolean;
24
+ export function escapeHtml(value: any): any;
25
+ export function indexOf(target: any, value: any): any;
26
+ export function isNullOrEmpty(target: any): boolean;
27
+ export function isNullOrWhiteSpace(target: any): boolean;
28
+ export function join(target: any, delimiter: any): any;
29
+ export function lastIndexOf(target: any, value: any): any;
30
+ export function length(target: any): any;
31
+ export function padLeft(target: any, totalWidth: any, padding: any): any;
32
+ export function padRight(target: any, totalWidth: any, padding: any): any;
33
+ export function replace(target: any, oldValue: any, newValue: any): any;
34
+ export function split(target: any, delimiter: any): any;
35
+ export function startsWith(target: any, value: any): boolean;
36
+ export function substring(target: any, startIndex: any, length: any): any;
37
+ export function toLower(target: any): any;
38
+ export function toUpper(target: any): any;
39
+ export function trim(target: any): any;
40
+ export function trimEnd(target: any): any;
41
+ export function trimStart(target: any): any;
42
+ export function unescapeHtml(value: any): any;
@@ -0,0 +1 @@
1
+ module.exports={_internal_:{htmlUnescapes:{"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},reEscapedHtml:/&(?:amp|lt|gt|quot|#(0+)?39);/g,reHasEscapedHtml:RegExp("&(?:amp|lt|gt|quot|#(0+)?39);"),htmlEscapes:{"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},reUnescapedHtml:/[&<>"']/g,reHasUnescapedHtml:RegExp("[&<>\"']")},concat:function(){let n="";for(let t=0;t<arguments.length;t++){let l=arguments[t];null!==l&&(n+=l)}return n},contains:function(n,t){return null!=n&&(null!=t&&-1!==n.indexOf(t))},endsWith:function(n,t){return null!=n&&(null!=t&&n.substring(n.length-t.length,n.length)===t)},escapeHtml:function(n){return n&&this._internal_.reHasUnescapedHtml.test(n)?n.replace(this._internal_.reUnescapedHtml,n=>this._internal_.htmlEscapes[n]):n||""},indexOf:function(n,t){return null==n||null==t?-1:n.indexOf(t)},isNullOrEmpty:function(n){return null==n||""===n},isNullOrWhiteSpace:function(n){return null==n||(""===n||n.replace(/\s/g,"").length<1)},join:function(n,t){return null==n?null:t?n.join(t):n.join("")},lastIndexOf:function(n,t){return null==n||null==t?-1:n.lastIndexOf(t)},length:function(n){return null==n?0:n.length},padLeft:function(n,t,l){return null==n?null:null==t?n:l?n.padStart(t,l):n.padStart(t)},padRight:function(n,t,l){return null==n?null:null==t?n:l?n.padEnd(t,l):n.padEnd(t)},replace:function(n,t,l){return null==n?null:null==t||null==l?n:n.replace(new RegExp(t,"g"),l)},split:function(n,t){return null==n?[]:n.split(t)},startsWith:function(n,t){return null!=n&&(null!=t&&n.substring(0,t.length)===t)},substring:function(n,t,l){return null==n||null==t||null==l?null:n.substring(t,t+l)},toLower:function(n){return null==n?null:n.toLowerCase()},toUpper:function(n){return null==n?null:n.toUpperCase()},trim:function(n){return null==n?null:n.trim()},trimEnd:function(n){return null==n?null:n.trimEnd()},trimStart:function(n){return null==n?null:n.trimStart()},unescapeHtml:function(n){return n&&this._internal_.reHasEscapedHtml.test(n)?n.replace(this._internal_.reEscapedHtml,n=>this._internal_.htmlUnescapes[n]||"'"):n||""}};
@@ -0,0 +1 @@
1
+ export function uuid(): any;
@@ -0,0 +1 @@
1
+ const Uuid=require("uuid");module.exports={uuid:function(){return Uuid.v4()}};
@@ -0,0 +1,2 @@
1
+ export function yamlParse(value: any): any;
2
+ export function yamlStringify(value: any): any;
@@ -0,0 +1 @@
1
+ const jsyaml=require("js-yaml");module.exports={yamlParse:function(l){if(void 0===l)throw new Error("value undefined");return null===l?null:jsyaml.load(l)},yamlStringify:function(l){if(void 0===l)throw new Error("value undefined");return null===l?null:jsyaml.dump(l)}};
@@ -0,0 +1,34 @@
1
+ import BlzBase = require("./blz-base/index.js");
2
+ import BlzConfig = require("./blz-config/index.js");
3
+ import BlzSecurity = require("./blz-security/index.js");
4
+ import ProcessManagers = require("./process-managers/index.js");
5
+ import { Exception } from "./blz-security/helpers/utils.js";
6
+ import BlzCache = require("./blz-cache/index.js");
7
+ import BlzCore = require("./blz-core/index.js");
8
+ import BlzCryptography = require("./blz-cryptography/index.js");
9
+ import BlzDatetimes = require("./blz-datetimes/index.js");
10
+ import BlzFile = require("./blz-file/index.js");
11
+ import BlzHazelcast = require("./blz-hazelcast/index.js");
12
+ import BlzIterable = require("./blz-iterable/index.js");
13
+ import BlzJsonSchema = require("./blz-json-schema/index.js");
14
+ import BlzJwt = require("./blz-jwt/index.js");
15
+ import BlzKafka = require("./blz-kafka/index.js");
16
+ import BlzMath = require("./blz-math/index.js");
17
+ import BlzMongodb = require("./blz-mongodb/index.js");
18
+ import BlzRds = require("./blz-rds/index.js");
19
+ import BlzRdsMysql = require("./blz-rds-mysql/index.js");
20
+ import BlzRdsMysqlx = require("./blz-rds-mysqlx/index.js");
21
+ import BlzRdsOracle = require("./blz-rds-oracle/index.js");
22
+ import BlzRdsPostgres = require("./blz-rds-postgres/index.js");
23
+ import BlzRedis = require("./blz-redis/index.js");
24
+ import BlzRegex = require("./blz-regex/index.js");
25
+ import BlzStrings = require("./blz-strings/index.js");
26
+ import BlzUuid = require("./blz-uuid/index.js");
27
+ import BlzYaml = require("./blz-yaml/index.js");
28
+ import { getHealthStatus } from "./blz-base/health/index.js";
29
+ import FileScanner = require("./blz-security/filescanner/index.js");
30
+ export function rdsProvider(providerName: any): any;
31
+ export function getModulesNames(): string[];
32
+ /** @returns {string} */
33
+ export function getVersion(): string;
34
+ export { BlzBase, BlzConfig, BlzSecurity, ProcessManagers, Exception, BlzCache, BlzCore, BlzCryptography, BlzDatetimes, BlzFile, BlzHazelcast, BlzIterable, BlzJsonSchema, BlzJwt, BlzKafka, BlzMath, BlzMongodb, BlzRds, BlzRdsMysql, BlzRdsMysqlx, BlzRdsOracle, BlzRdsPostgres, BlzRedis, BlzRegex, BlzStrings, BlzUuid, BlzYaml, getHealthStatus, FileScanner };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ const BlzBase=require("./blz-base/index.js"),BlzConfig=require("./blz-config/index.js"),BlzSecurity=require("./blz-security/index.js"),FileScanner=require("./blz-security/filescanner/index.js"),ProcessManagers=require("./process-managers/index.js"),{Exception:Exception}=require("./blz-security/helpers/utils.js"),BlzCache=require("./blz-cache/index.js"),BlzCore=require("./blz-core/index.js"),BlzCryptography=require("./blz-cryptography/index.js"),BlzDatetimes=require("./blz-datetimes/index.js"),BlzFile=require("./blz-file/index.js"),BlzHazelcast=require("./blz-hazelcast/index.js"),BlzIterable=require("./blz-iterable/index.js"),BlzJsonSchema=require("./blz-json-schema/index.js"),BlzJwt=require("./blz-jwt/index.js"),BlzKafka=require("./blz-kafka/index.js"),BlzMath=require("./blz-math/index.js"),BlzMongodb=require("./blz-mongodb/index.js"),BlzRds=require("./blz-rds/index.js"),BlzRdsMysql=require("./blz-rds-mysql/index.js"),BlzRdsMysqlx=require("./blz-rds-mysqlx/index.js"),BlzRdsOracle=require("./blz-rds-oracle/index.js"),BlzRdsPostgres=require("./blz-rds-postgres/index.js"),BlzRedis=require("./blz-redis/index.js"),BlzRegex=require("./blz-regex/index.js"),BlzStrings=require("./blz-strings/index.js"),BlzUuid=require("./blz-uuid/index.js"),BlzYaml=require("./blz-yaml/index.js"),{getHealthStatus:getHealthStatus}=require("./blz-base/health/index.js"),rdsProvider=function(e){return require("./blz-rds-"+e.toLowerCase()+"/index.js")},getModulesNames=()=>["blz-base","blz-cache","blz-config","blz-core","blz-cryptography","blz-datetimes","blz-file","blz-hazelcast","blz-iterable","blz-json-schema","blz-jwt","blz-kafka","blz-math","blz-mongodb","blz-rds","blz-rds-mysql","blz-rds-mysqlx","blz-rds-oracle","blz-rds-postgres","blz-redis","blz-regex","blz-security","blz-strings","blz-uuid","blz-yaml"],__BLZ_VERSION__="0.3.1",getVersion=()=>"0.3.1";module.exports={BlzBase:BlzBase,BlzConfig:BlzConfig,BlzSecurity:BlzSecurity,ProcessManagers:ProcessManagers,Exception:Exception,BlzCache:BlzCache,BlzCore:BlzCore,BlzCryptography:BlzCryptography,BlzDatetimes:BlzDatetimes,BlzFile:BlzFile,BlzHazelcast:BlzHazelcast,BlzIterable:BlzIterable,BlzJsonSchema:BlzJsonSchema,BlzJwt:BlzJwt,BlzKafka:BlzKafka,BlzMath:BlzMath,BlzMongodb:BlzMongodb,BlzRds:BlzRds,BlzRdsMysql:BlzRdsMysql,BlzRdsMysqlx:BlzRdsMysqlx,BlzRdsOracle:BlzRdsOracle,BlzRdsPostgres:BlzRdsPostgres,BlzRedis:BlzRedis,BlzRegex:BlzRegex,BlzStrings:BlzStrings,BlzUuid:BlzUuid,BlzYaml:BlzYaml,getHealthStatus:getHealthStatus,FileScanner:FileScanner,rdsProvider:rdsProvider,getModulesNames:getModulesNames,getVersion:getVersion};
@@ -0,0 +1,25 @@
1
+ export function setConnection(connection: any, tokenProcessor: any, config: any): Promise<void>;
2
+ export function start(processName: any, startModel: any, startNodeName: any): Promise<string>;
3
+ export function resume(processName: any, instanceId: any): Promise<any>;
4
+ export function killAgendaJob(agenda: any, jobId: any, options?: {}): Promise<void>;
5
+ export function scheduleStart(processName: any, startNodeName: any, datetime: any): Promise<void>;
6
+ export function killInstance(processName: any, instanceId: any, instanceFinisher: any): Promise<void>;
7
+ export function createToken(processName: any, instanceId: any, nodeName: any, parentTokenId: any): Promise<void>;
8
+ export function moveToken(processName: any, instanceId: any, tokenId: any, targets: any, newGatewayNumber: any, tokenProcessor: any): Promise<void>;
9
+ export function killToken(processName: any, instanceId: any, tokenId: any, subProcessFinisher: any, instanceFinisher: any, err: any): Promise<void>;
10
+ export function readModel(processName: any, instanceId: any, variableName: any): Promise<any>;
11
+ export function writeModel(processName: any, instanceId: any, variableName: any, value: any): Promise<any>;
12
+ export function getNodeName(processName: any, instanceId: any, tokenId: any): Promise<any>;
13
+ export function getReceivers(processName: any, instanceId: any, messageKey: any, signalName: any): Promise<{
14
+ tokenId: string;
15
+ nodeName: any;
16
+ }[]>;
17
+ export function enqueueCompensation(processName: any, instanceId: any, compensationKey: any, nodeName: any): Promise<void>;
18
+ export function compensate(processName: any, instanceId: any, compensationKey: any, instanceCompensator: any): Promise<void>;
19
+ export function listInstances(processName: any, offset: any, limit: any): Promise<any>;
20
+ export function getInstance(processName: any, instanceId: any): Promise<{
21
+ processName: any;
22
+ instanceId: any;
23
+ model: any;
24
+ tokens: any[];
25
+ }>;
@@ -0,0 +1 @@
1
+ const{MongoClient:MongoClient,ObjectId:ObjectId}=require("mongodb");let Agenda=require("agenda");const AsyncRetry=require("async-retry"),logger=require("pino")();let removeTokenAndChilds=function(e,n,t){delete e.tokens[n],t["tokens."+n]="";for(let a in e.tokens){e.tokens[a].parentTokenId===n&&removeTokenAndChilds(e,a,t)}},getInstance=function(e){let n={processName:e.processName,instanceId:e._id,model:e.model,tokens:[]};for(let t in e.tokens){let a=e.tokens[t],o={tokenId:t,nodeName:a.nodeName,hasError:a.hasError??void 0};a.parentTokenId&&(o.parentTokenId=a.parentTokenId),n.tokens.push(o)}return n},writeMongo=async function(e,n,t,a){let o={};return o[t]=a,await _mongodbCollectionInstances.updateOne({_id:{$eq:ObjectId(n)}},{$set:o}),null},tokenProcessorFn=null;module.exports={setConnection:async function(e,n,t){tokenProcessorFn=n,_processorConfig=t;let a=null;e.useRetries?await AsyncRetry(async()=>{a=new MongoClient(e.url,{useUnifiedTopology:!0});try{await a.connect()}catch(e){throw console.error("Error connecting to MongoDB:",e),e}},{retries:e.retryCount,minTimeout:1e3*e.minRetryInterval,maxTimeout:1e3*e.maxRetryInterval}):(a=new MongoClient(e.url,{useUnifiedTopology:!0}),await a.connect());let o=a.db(e.databaseName);_mongodbCollectionInstances=o.collection("blz-instances"),_agenda=new Agenda({mongo:o,db:{collection:"blz-jobs"},name:`worker-${process.pid}`}),_agenda.define("start",async function(e){module.exports.start(e.attrs.data.processName,{},e.attrs.data.startNodeName,n),await e.remove()}),_agenda.define("process-token",{concurrency:1,lockLimit:1,lockLifetime:12e4},async function(e){if("done"===e.attrs.data.status||e.attrs.data.running)return void("done"===e.attrs.data.status&&(logger.info(`process-token skipped: already executed for token ${o}`),await e.remove()));e.attrs.data.running=!0,await e.save();const{processName:t,instanceId:a,tokenId:o,nodeName:s,inboundTransaction:i}=e.attrs.data;let r=null;try{r=await _mongodbCollectionInstances.findOne({_id:new ObjectId(a)}),r&&r.tokens[o]&&await n(t,a,o,s,i),e.attrs.data.status="done",e.attrs.data.running=!1,await e.save(),await e.remove()}catch(n){const i=n instanceof Error?{message:n.message??n.data,stack:n.stack}:{...n};if(e.attrs.failCount=(e.attrs.failCount||0)+1,e.attrs.failCount>=_processorConfig.retriesAfterError){logger.error({msg:"process-token failed maximum times, disabling job",processName:t,instanceId:a,tokenId:o,nodeName:s,failCount:e.attrs.failCount,error:i}),e.attrs.disabled=!0;const n={...r.tokens};n[o]&&(n[o]={...n[o],hasError:!0}),await writeMongo(t,a,"tokens",n)}else{const n=5e3;logger.warn({msg:`process-token failed, scheduled new retry (attempt ${e.attrs.failCount}/${_processorConfig.retriesAfterError})`,processName:t,instanceId:a,tokenId:o,nodeName:s,failCount:e.attrs.failCount,nextRetryInMs:n,error:i}),e.attrs.nextRunAt=new Date(Date.now()+n)}return e.attrs.data.running=!1,void await e.save()}}),await _agenda.start()},start:async function(e,n,t){let a=new ObjectId,o=a.toHexString(),s=(new ObjectId).toHexString(),i={_id:a,processName:e,model:n,tokens:{},compensations:{}};return i.tokens[s]={nodeName:t},await _mongodbCollectionInstances.insertOne(i),console.log("Creating job for tokenId:",s),await _agenda.now("process-token",{processName:e,instanceId:o,tokenId:s,nodeName:t},{unique:{"data.tokenId":s},insertOnly:!0}),o},resume:async function(e,n){let t=await module.exports.getInstance(e,n),a=null;for(let e=0;e<t.tokens.length;++e){t.tokens[e].hasError&&(a=t.tokens[0].tokenId)}if(!a)return logger.warn(`No bpm mongoInstance.token found with errors for mongoInstance ${n}`),null;const o=(await _agenda.jobs({"data.tokenId":a}))[0];return o?(o.attrs.disabled=!1,o.attrs.lockedAt=null,o.attrs.lastFinishedAt=null,o.attrs.failedAt=null,o.attrs.failReason=null,await o.save(),await o.run(),logger.info(`BPM instance: ${n} has been re-enabled, and is attempting to run again.`),null):(logger.warn(`No job found with id ${a}`),null)},killAgendaJob:async function(e,n,t={}){},scheduleStart:async function(e,n,t){let a=new Date(Date.now());a=new Date(Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate(),a.getUTCHours(),a.getUTCMinutes(),a.getUTCSeconds(),a.getUTCMilliseconds())),await _agenda.schedule(t,"start",{processName:e,startNodeName:n})},killInstance:async function(e,n,t){await _mongodbCollectionInstances.deleteOne({_id:{$eq:ObjectId(n)}}),t(e)},createToken:async function(e,n,t,a){let o=(new ObjectId).toHexString(),s={nodeName:t};a&&(s.parentTokenId=a);let i={};i["tokens."+o]=s,await _mongodbCollectionInstances.updateOne({_id:{$eq:ObjectId(n)}},{$set:i}),await _agenda.now("process-token",{processName:e,instanceId:n,tokenId:o,nodeName:t})},moveToken:async function(e,n,t,a,o,s){var i=await _mongodbCollectionInstances.findOne({_id:{$eq:ObjectId(n)}});let r=i.tokens[t];if(r){let d=r.parentTokenId,l=r.gatewayNumbers,c={},m={};removeTokenAndChilds(i,t,c),await _mongodbCollectionInstances.updateOne({_id:{$eq:ObjectId(n)}},{$unset:c}),i=await _mongodbCollectionInstances.findOne({_id:{$eq:ObjectId(n)}});for(let e=0;e<a.length;e++){let n=a[e],t=!0;if(n.filterGatewayNumber)for(let e in i.tokens){let a=i.tokens[e];a.gatewayNumbers&&-1!==a.gatewayNumbers.indexOf(n.filterGatewayNumber)&&(t=!1)}if(t){if(n.newTokenId=(new ObjectId).toHexString(),n.newTokenData={nodeName:n.nodeName},d&&(n.newTokenData.parentTokenId=d),l||o){if(n.newTokenData.gatewayNumbers=[],l)for(let e=0;e<l.length;e++){let t=l[e];t!==n.filterGatewayNumber&&n.newTokenData.gatewayNumbers.push(t)}o&&n.newTokenData.gatewayNumbers.push(o)}n.waitMessages&&(n.newTokenData.waitMessages=n.waitMessages),n.waitSignals&&(n.newTokenData.waitSignals=n.waitSignals),m["tokens."+n.newTokenId]=n.newTokenData}}0===Object.keys(m).length?await _mongodbCollectionInstances.updateOne({_id:{$eq:ObjectId(n)}},{$unset:c}):await _mongodbCollectionInstances.updateOne({_id:{$eq:ObjectId(n)}},{$unset:c,$set:m});for(let t=0;t<a.length;t++){let o=a[t];if(o.newTokenId&&(o.immediateNodeName&&(o.immediateSchedule?await _agenda.now("process-token",{processName:e,instanceId:n,tokenId:o.newTokenId,nodeName:o.immediateNodeName,inboundTransaction:o.inbound}):await s(e,n,o.newTokenId,o.immediateNodeName,o.inbound)),o.waitTimers))for(let t=0;t<o.waitTimers.length;t++){let a=o.waitTimers[t];await _agenda.schedule(a.datetime,"process-token",{processName:e,instanceId:n,tokenId:o.newTokenId,nodeName:a.nodeName,inboundTransaction:o.inbound})}}}},killToken:async function(e,n,t,a,o,s){var i=await _mongodbCollectionInstances.findOne({_id:{$eq:ObjectId(n)}});let r=i.tokens[t];if(r){let d=r.parentTokenId,l={};if(removeTokenAndChilds(i,t,l),s)for(let e in i.tokens){i.tokens[e].parentTokenId===d&&removeTokenAndChilds(i,e,l)}if(0===Object.keys(i.tokens).length)await _mongodbCollectionInstances.deleteOne({_id:{$eq:ObjectId(n)}}),o(e,s);else if(await _mongodbCollectionInstances.updateOne({_id:{$eq:ObjectId(n)}},{$unset:l}),d){let t=!0;for(let e in i.tokens){i.tokens[e].parentTokenId===d&&(t=!1)}t&&a(e,n,d,s)}}},readModel:async function(e,n,t){var a=await _mongodbCollectionInstances.findOne({_id:{$eq:ObjectId(n)}});return a?null==t?a.model:a.model[t]:null},writeModel:async function(e,n,t,a){let o={};return o["model."+t]=a,await _mongodbCollectionInstances.updateOne({_id:{$eq:ObjectId(n)}},{$set:o}),null},getNodeName:async function(e,n,t){var a=await _mongodbCollectionInstances.findOne({_id:{$eq:ObjectId(n)}});let o=null;if(a){let e=a.tokens[t];e&&(o=e.nodeName)}return o},getReceivers:async function(e,n,t,a){var o=await _mongodbCollectionInstances.findOne({_id:{$eq:ObjectId(n)}});let s=[];if(o)for(let e in o.tokens){let n=o.tokens[e];if(n.waitMessages)for(let a=0;a<n.waitMessages.length;a++){let o=n.waitMessages[a];o.messageKey===t&&s.push({tokenId:e,nodeName:o.nodeName})}if(n.waitSignals)for(let t=0;t<n.waitSignals.length;t++){let o=n.waitSignals[t];o.signalName===a&&s.push({tokenId:e,nodeName:o.nodeName})}}return s},enqueueCompensation:async function(e,n,t,a){var o=await _mongodbCollectionInstances.findOne({_id:{$eq:ObjectId(n)}});let s=o.compensations[t];null==s&&(s=[],o.compensations[t]=s),s.push({nodeName:a,model:JSON.parse(JSON.stringify(o.model))});let i={};i["compensations."+t]=s,await _mongodbCollectionInstances.updateOne({_id:{$eq:ObjectId(n)}},{$set:i})},compensate:async function(e,n,t,a){let o=(await _mongodbCollectionInstances.findOne({_id:{$eq:ObjectId(n)}})).compensations[t];if(o)for(;o.length>0;){let s=o.pop();a(e,n,t,s.nodeName,s.model)}let s={};s["compensations."+t]=[],await _mongodbCollectionInstances.updateOne({_id:{$eq:ObjectId(n)}},{$set:s})},listInstances:async function(e,n,t){var a=await _mongodbCollectionInstances.find({processName:{$eq:e}},{skip:n,limit:t});return await a.map(function(e){return getInstance(e)}).toArray()},getInstance:async function(e,n){var t=await _mongodbCollectionInstances.findOne({_id:{$eq:ObjectId(n)}});let a=null;return t&&(a=getInstance(t)),a}};