nodejs-insta-private-api-mqt 1.3.83 → 1.3.84

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 (392) hide show
  1. package/dist-ts/dist/constants/constants.js +341 -0
  2. package/dist-ts/dist/constants/index.js +53 -0
  3. package/dist-ts/dist/core/client.js +437 -0
  4. package/dist-ts/dist/core/nav-chain.js +252 -0
  5. package/dist-ts/dist/core/repository.js +6 -0
  6. package/dist-ts/dist/core/request.js +358 -0
  7. package/dist-ts/dist/core/state.js +1428 -0
  8. package/dist-ts/dist/core/utils.js +723 -0
  9. package/dist-ts/dist/downloadMedia.js +336 -0
  10. package/dist-ts/dist/errors/index.js +37 -0
  11. package/dist-ts/dist/extend.js +157 -0
  12. package/dist-ts/dist/fbns/fbns.client.events.js +2 -0
  13. package/dist-ts/dist/fbns/fbns.client.js +237 -0
  14. package/dist-ts/dist/fbns/fbns.device-auth.js +59 -0
  15. package/dist-ts/dist/fbns/fbns.types.js +2 -0
  16. package/dist-ts/dist/fbns/fbns.utilities.js +78 -0
  17. package/dist-ts/dist/fbns/index.js +24 -0
  18. package/dist-ts/dist/index.js +137 -0
  19. package/dist-ts/dist/mqtt-shim.js +14 -0
  20. package/dist-ts/dist/mqttot/index.js +24 -0
  21. package/dist-ts/dist/mqttot/mqttot.client.js +322 -0
  22. package/dist-ts/dist/mqttot/mqttot.connect.request.packet.js +8 -0
  23. package/dist-ts/dist/mqttot/mqttot.connect.response.packet.js +23 -0
  24. package/dist-ts/dist/mqttot/mqttot.connection.js +68 -0
  25. package/dist-ts/dist/realtime/commands/commands.js +67 -0
  26. package/dist-ts/dist/realtime/commands/direct.commands.js +415 -0
  27. package/dist-ts/dist/realtime/commands/enhanced.direct.commands.js +1529 -0
  28. package/dist-ts/dist/realtime/commands/index.js +23 -0
  29. package/dist-ts/dist/realtime/delta-sync.manager.js +260 -0
  30. package/dist-ts/dist/realtime/features/dm-sender.js +94 -0
  31. package/dist-ts/dist/realtime/features/error-handler.js +167 -0
  32. package/dist-ts/dist/realtime/features/gap-handler.js +60 -0
  33. package/dist-ts/dist/realtime/features/persistent-logger.js +174 -0
  34. package/dist-ts/dist/realtime/features/presence.manager.js +68 -0
  35. package/dist-ts/dist/realtime/features/session-health-monitor.js +327 -0
  36. package/dist-ts/dist/realtime/index.js +21 -0
  37. package/dist-ts/dist/realtime/messages/app-presence.event.js +2 -0
  38. package/dist-ts/dist/realtime/messages/index.js +23 -0
  39. package/dist-ts/dist/realtime/messages/message-sync.message.js +42 -0
  40. package/dist-ts/dist/realtime/messages/realtime-sub.direct.data.js +2 -0
  41. package/dist-ts/dist/realtime/messages/thread-update.message.js +2 -0
  42. package/dist-ts/dist/realtime/mixins/index.js +23 -0
  43. package/dist-ts/dist/realtime/mixins/message-sync.mixin.js +585 -0
  44. package/dist-ts/dist/realtime/mixins/mixin.js +40 -0
  45. package/dist-ts/dist/realtime/mixins/presence-typing.mixin.js +29 -0
  46. package/dist-ts/dist/realtime/mixins/realtime-sub.mixin.js +171 -0
  47. package/dist-ts/dist/realtime/parsers/graphql-parser.js +43 -0
  48. package/dist-ts/dist/realtime/parsers/graphql.parser.js +22 -0
  49. package/dist-ts/dist/realtime/parsers/index.js +26 -0
  50. package/dist-ts/dist/realtime/parsers/iris-parser.js +43 -0
  51. package/dist-ts/dist/realtime/parsers/iris.parser.js +9 -0
  52. package/dist-ts/dist/realtime/parsers/json-parser.js +43 -0
  53. package/dist-ts/dist/realtime/parsers/json.parser.js +9 -0
  54. package/dist-ts/dist/realtime/parsers/parser.js +2 -0
  55. package/dist-ts/dist/realtime/parsers/region-hint-parser.js +43 -0
  56. package/dist-ts/dist/realtime/parsers/region-hint.parser.js +14 -0
  57. package/dist-ts/dist/realtime/parsers/skywalker-parser.js +43 -0
  58. package/dist-ts/dist/realtime/parsers/skywalker.parser.js +14 -0
  59. package/dist-ts/dist/realtime/parsers-advanced.js +138 -0
  60. package/dist-ts/dist/realtime/proto-parser.js +186 -0
  61. package/dist-ts/dist/realtime/protocols/iris.handshake.js +76 -0
  62. package/dist-ts/dist/realtime/protocols/skywalker.protocol.js +96 -0
  63. package/dist-ts/dist/realtime/realtime.client.events.js +2 -0
  64. package/dist-ts/dist/realtime/realtime.client.js +2117 -0
  65. package/dist-ts/dist/realtime/realtime.service.js +408 -0
  66. package/dist-ts/dist/realtime/reconnect.manager.js +72 -0
  67. package/dist-ts/dist/realtime/session.manager.js +106 -0
  68. package/dist-ts/dist/realtime/subscriptions/graphql.subscription.js +98 -0
  69. package/dist-ts/dist/realtime/subscriptions/index.js +22 -0
  70. package/dist-ts/dist/realtime/subscriptions/skywalker.subscription.js +12 -0
  71. package/dist-ts/dist/realtime/topic-map.js +57 -0
  72. package/dist-ts/dist/realtime/topic.js +76 -0
  73. package/dist-ts/dist/repositories/account.repository.js +1267 -0
  74. package/dist-ts/dist/repositories/bloks.repository.js +66 -0
  75. package/dist-ts/dist/repositories/captcha.repository.js +40 -0
  76. package/dist-ts/dist/repositories/challenge.repository.js +108 -0
  77. package/dist-ts/dist/repositories/clip.repository.js +134 -0
  78. package/dist-ts/dist/repositories/close-friends.repository.js +41 -0
  79. package/dist-ts/dist/repositories/collection.repository.js +64 -0
  80. package/dist-ts/dist/repositories/direct-thread.repository.js +423 -0
  81. package/dist-ts/dist/repositories/direct.repository.js +246 -0
  82. package/dist-ts/dist/repositories/explore.repository.js +60 -0
  83. package/dist-ts/dist/repositories/fbsearch.repository.js +124 -0
  84. package/dist-ts/dist/repositories/feed.repository.js +237 -0
  85. package/dist-ts/dist/repositories/friendship.repository.js +277 -0
  86. package/dist-ts/dist/repositories/fundraiser.repository.js +38 -0
  87. package/dist-ts/dist/repositories/hashtag.repository.js +80 -0
  88. package/dist-ts/dist/repositories/highlights.repository.js +100 -0
  89. package/dist-ts/dist/repositories/insights.repository.js +66 -0
  90. package/dist-ts/dist/repositories/location.repository.js +67 -0
  91. package/dist-ts/dist/repositories/media.repository.js +370 -0
  92. package/dist-ts/dist/repositories/multiple-accounts.repository.js +36 -0
  93. package/dist-ts/dist/repositories/news.repository.js +32 -0
  94. package/dist-ts/dist/repositories/note.repository.js +51 -0
  95. package/dist-ts/dist/repositories/notification.repository.js +77 -0
  96. package/dist-ts/dist/repositories/share.repository.js +34 -0
  97. package/dist-ts/dist/repositories/signup.repository.js +178 -0
  98. package/dist-ts/dist/repositories/story.repository.js +268 -0
  99. package/dist-ts/dist/repositories/timeline.repository.js +57 -0
  100. package/dist-ts/dist/repositories/totp.repository.js +124 -0
  101. package/dist-ts/dist/repositories/track.repository.js +50 -0
  102. package/dist-ts/dist/repositories/upload.repository.js +191 -0
  103. package/dist-ts/dist/repositories/user.repository.js +332 -0
  104. package/dist-ts/dist/sendmedia/index.js +24 -0
  105. package/dist-ts/dist/sendmedia/sendFile.js +56 -0
  106. package/dist-ts/dist/sendmedia/sendPhoto.js +132 -0
  107. package/dist-ts/dist/sendmedia/sendRavenPhoto.js +133 -0
  108. package/dist-ts/dist/sendmedia/sendRavenVideo.js +136 -0
  109. package/dist-ts/dist/sendmedia/uploadPhoto.js +89 -0
  110. package/dist-ts/dist/sendmedia/uploadfFile.js +108 -0
  111. package/dist-ts/dist/services/live.service.js +113 -0
  112. package/dist-ts/dist/services/search.service.js +91 -0
  113. package/dist-ts/dist/shared/index.js +98 -0
  114. package/dist-ts/dist/shared/shared.js +85 -0
  115. package/dist-ts/dist/thrift/index.js +23 -0
  116. package/dist-ts/dist/thrift/thrift.js +105 -0
  117. package/dist-ts/dist/thrift/thrift.reading.js +339 -0
  118. package/dist-ts/dist/thrift/thrift.writing.js +393 -0
  119. package/dist-ts/dist/types/index.js +276 -0
  120. package/dist-ts/dist/useMultiFileAuthState.js +1878 -0
  121. package/dist-ts/dist/utils/index.js +244 -0
  122. package/dist-ts/examples/listen-to-messages.js +73 -0
  123. package/package.json +1 -1
  124. package/src-ts/dist/realtime/protocols/proto-definitions.ts +80 -0
  125. package/src-ts/dist/utils/helper-1.ts +1 -0
  126. package/src-ts/dist/utils/helper-10.ts +1 -0
  127. package/src-ts/dist/utils/helper-11.ts +1 -0
  128. package/src-ts/dist/utils/helper-12.ts +1 -0
  129. package/src-ts/dist/utils/helper-13.ts +1 -0
  130. package/src-ts/dist/utils/helper-14.ts +1 -0
  131. package/src-ts/dist/utils/helper-15.ts +1 -0
  132. package/src-ts/dist/utils/helper-16.ts +1 -0
  133. package/src-ts/dist/utils/helper-17.ts +1 -0
  134. package/src-ts/dist/utils/helper-18.ts +1 -0
  135. package/src-ts/dist/utils/helper-19.ts +1 -0
  136. package/src-ts/dist/utils/helper-2.ts +1 -0
  137. package/src-ts/dist/utils/helper-20.ts +1 -0
  138. package/src-ts/dist/utils/helper-21.ts +1 -0
  139. package/src-ts/dist/utils/helper-22.ts +1 -0
  140. package/src-ts/dist/utils/helper-23.ts +1 -0
  141. package/src-ts/dist/utils/helper-24.ts +1 -0
  142. package/src-ts/dist/utils/helper-25.ts +1 -0
  143. package/src-ts/dist/utils/helper-26.ts +1 -0
  144. package/src-ts/dist/utils/helper-27.ts +1 -0
  145. package/src-ts/dist/utils/helper-28.ts +1 -0
  146. package/src-ts/dist/utils/helper-29.ts +1 -0
  147. package/src-ts/dist/utils/helper-3.ts +1 -0
  148. package/src-ts/dist/utils/helper-30.ts +1 -0
  149. package/src-ts/dist/utils/helper-4.ts +1 -0
  150. package/src-ts/dist/utils/helper-5.ts +1 -0
  151. package/src-ts/dist/utils/helper-6.ts +1 -0
  152. package/src-ts/dist/utils/helper-7.ts +1 -0
  153. package/src-ts/dist/utils/helper-8.ts +1 -0
  154. package/src-ts/dist/utils/helper-9.ts +1 -0
  155. package/src-ts/dist/utils/insta-mqtt-helper.ts +128 -0
  156. package/src-ts/examples/listen-to-messages.ts +86 -0
  157. package/dist/errors/index.d.ts +0 -16
  158. package/dist/errors/index.js.map +0 -1
  159. package/dist/fbns/fbns.client.d.ts +0 -32
  160. package/dist/fbns/fbns.client.events.d.ts +0 -41
  161. package/dist/fbns/fbns.client.events.js.map +0 -1
  162. package/dist/fbns/fbns.client.js.map +0 -1
  163. package/dist/fbns/fbns.device-auth.d.ts +0 -17
  164. package/dist/fbns/fbns.device-auth.js.map +0 -1
  165. package/dist/fbns/fbns.types.d.ts +0 -83
  166. package/dist/fbns/fbns.types.js.map +0 -1
  167. package/dist/fbns/fbns.utilities.d.ts +0 -2
  168. package/dist/fbns/fbns.utilities.js.map +0 -1
  169. package/dist/fbns/index.d.ts +0 -4
  170. package/dist/fbns/index.js.map +0 -1
  171. package/dist/mqtt-shim.d.ts +0 -96
  172. package/dist/mqttot/index.d.ts +0 -4
  173. package/dist/mqttot/index.js.map +0 -1
  174. package/dist/mqttot/mqttot.client.d.ts +0 -39
  175. package/dist/mqttot/mqttot.client.js.map +0 -1
  176. package/dist/mqttot/mqttot.connect.request.packet.d.ts +0 -7
  177. package/dist/mqttot/mqttot.connect.request.packet.js.map +0 -1
  178. package/dist/mqttot/mqttot.connect.response.packet.d.ts +0 -7
  179. package/dist/mqttot/mqttot.connect.response.packet.js.map +0 -1
  180. package/dist/mqttot/mqttot.connection.d.ts +0 -57
  181. package/dist/mqttot/mqttot.connection.js.map +0 -1
  182. package/dist/package.json +0 -59
  183. package/dist/realtime/commands/commands.d.ts +0 -15
  184. package/dist/realtime/commands/commands.js.map +0 -1
  185. package/dist/realtime/commands/direct.commands.d.ts +0 -75
  186. package/dist/realtime/commands/direct.commands.js.map +0 -1
  187. package/dist/realtime/commands/enhanced.direct.commands.js.bak +0 -967
  188. package/dist/realtime/commands/index.d.ts +0 -2
  189. package/dist/realtime/commands/index.js.map +0 -1
  190. package/dist/realtime/messages/app-presence.event.d.ts +0 -9
  191. package/dist/realtime/messages/app-presence.event.js.map +0 -1
  192. package/dist/realtime/messages/index.d.ts +0 -3
  193. package/dist/realtime/messages/index.js.map +0 -1
  194. package/dist/realtime/messages/message-sync.message.d.ts +0 -222
  195. package/dist/realtime/messages/message-sync.message.js.map +0 -1
  196. package/dist/realtime/messages/realtime-sub.direct.data.d.ts +0 -11
  197. package/dist/realtime/messages/realtime-sub.direct.data.js.map +0 -1
  198. package/dist/realtime/messages/thread-update.message.d.ts +0 -68
  199. package/dist/realtime/messages/thread-update.message.js.map +0 -1
  200. package/dist/realtime/mixins/index.d.ts +0 -3
  201. package/dist/realtime/mixins/index.js.map +0 -1
  202. package/dist/realtime/mixins/message-sync.mixin.d.ts +0 -8
  203. package/dist/realtime/mixins/message-sync.mixin.js.map +0 -1
  204. package/dist/realtime/mixins/mixin.d.ts +0 -19
  205. package/dist/realtime/mixins/mixin.js.map +0 -1
  206. package/dist/realtime/mixins/realtime-sub.mixin.d.ts +0 -8
  207. package/dist/realtime/mixins/realtime-sub.mixin.js.map +0 -1
  208. package/dist/realtime/parsers/graphql.parser.d.ts +0 -15
  209. package/dist/realtime/parsers/graphql.parser.js.map +0 -1
  210. package/dist/realtime/parsers/index.d.ts +0 -6
  211. package/dist/realtime/parsers/index.js.map +0 -1
  212. package/dist/realtime/parsers/iris.parser.d.ts +0 -17
  213. package/dist/realtime/parsers/iris.parser.js.map +0 -1
  214. package/dist/realtime/parsers/json.parser.d.ts +0 -6
  215. package/dist/realtime/parsers/json.parser.js.map +0 -1
  216. package/dist/realtime/parsers/parser.d.ts +0 -9
  217. package/dist/realtime/parsers/parser.js.map +0 -1
  218. package/dist/realtime/parsers/region-hint.parser.d.ts +0 -12
  219. package/dist/realtime/parsers/region-hint.parser.js.map +0 -1
  220. package/dist/realtime/parsers/skywalker.parser.d.ts +0 -12
  221. package/dist/realtime/parsers/skywalker.parser.js.map +0 -1
  222. package/dist/realtime/proto/common.proto +0 -38
  223. package/dist/realtime/proto/direct.proto +0 -65
  224. package/dist/realtime/proto/ig-messages.proto +0 -83
  225. package/dist/realtime/proto/iris.proto +0 -188
  226. package/dist/realtime/subscriptions/graphql.subscription.d.ts +0 -47
  227. package/dist/realtime/subscriptions/graphql.subscription.js.map +0 -1
  228. package/dist/realtime/subscriptions/index.d.ts +0 -2
  229. package/dist/realtime/subscriptions/index.js.map +0 -1
  230. package/dist/realtime/subscriptions/skywalker.subscription.d.ts +0 -4
  231. package/dist/realtime/subscriptions/skywalker.subscription.js.map +0 -1
  232. package/dist/thrift/index.d.ts +0 -3
  233. package/dist/thrift/index.js.map +0 -1
  234. package/dist/thrift/thrift.d.ts +0 -59
  235. package/dist/thrift/thrift.js.map +0 -1
  236. package/dist/thrift/thrift.reading.d.ts +0 -41
  237. package/dist/thrift/thrift.reading.js.map +0 -1
  238. package/dist/thrift/thrift.writing.d.ts +0 -44
  239. package/dist/thrift/thrift.writing.js.map +0 -1
  240. /package/{dist → dist-ts/dist}/realtime/protocols/proto-definitions.js +0 -0
  241. /package/{dist → dist-ts/dist}/utils/helper-1.js +0 -0
  242. /package/{dist → dist-ts/dist}/utils/helper-10.js +0 -0
  243. /package/{dist → dist-ts/dist}/utils/helper-11.js +0 -0
  244. /package/{dist → dist-ts/dist}/utils/helper-12.js +0 -0
  245. /package/{dist → dist-ts/dist}/utils/helper-13.js +0 -0
  246. /package/{dist → dist-ts/dist}/utils/helper-14.js +0 -0
  247. /package/{dist → dist-ts/dist}/utils/helper-15.js +0 -0
  248. /package/{dist → dist-ts/dist}/utils/helper-16.js +0 -0
  249. /package/{dist → dist-ts/dist}/utils/helper-17.js +0 -0
  250. /package/{dist → dist-ts/dist}/utils/helper-18.js +0 -0
  251. /package/{dist → dist-ts/dist}/utils/helper-19.js +0 -0
  252. /package/{dist → dist-ts/dist}/utils/helper-2.js +0 -0
  253. /package/{dist → dist-ts/dist}/utils/helper-20.js +0 -0
  254. /package/{dist → dist-ts/dist}/utils/helper-21.js +0 -0
  255. /package/{dist → dist-ts/dist}/utils/helper-22.js +0 -0
  256. /package/{dist → dist-ts/dist}/utils/helper-23.js +0 -0
  257. /package/{dist → dist-ts/dist}/utils/helper-24.js +0 -0
  258. /package/{dist → dist-ts/dist}/utils/helper-25.js +0 -0
  259. /package/{dist → dist-ts/dist}/utils/helper-26.js +0 -0
  260. /package/{dist → dist-ts/dist}/utils/helper-27.js +0 -0
  261. /package/{dist → dist-ts/dist}/utils/helper-28.js +0 -0
  262. /package/{dist → dist-ts/dist}/utils/helper-29.js +0 -0
  263. /package/{dist → dist-ts/dist}/utils/helper-3.js +0 -0
  264. /package/{dist → dist-ts/dist}/utils/helper-30.js +0 -0
  265. /package/{dist → dist-ts/dist}/utils/helper-4.js +0 -0
  266. /package/{dist → dist-ts/dist}/utils/helper-5.js +0 -0
  267. /package/{dist → dist-ts/dist}/utils/helper-6.js +0 -0
  268. /package/{dist → dist-ts/dist}/utils/helper-7.js +0 -0
  269. /package/{dist → dist-ts/dist}/utils/helper-8.js +0 -0
  270. /package/{dist → dist-ts/dist}/utils/helper-9.js +0 -0
  271. /package/{dist → dist-ts/dist}/utils/insta-mqtt-helper.js +0 -0
  272. /package/{dist/constants/constants.js → src-ts/dist/constants/constants.ts} +0 -0
  273. /package/{dist/constants/index.js → src-ts/dist/constants/index.ts} +0 -0
  274. /package/{dist/core/client.js → src-ts/dist/core/client.ts} +0 -0
  275. /package/{dist/core/nav-chain.js → src-ts/dist/core/nav-chain.ts} +0 -0
  276. /package/{dist/core/repository.js → src-ts/dist/core/repository.ts} +0 -0
  277. /package/{dist/core/request.js → src-ts/dist/core/request.ts} +0 -0
  278. /package/{dist/core/state.js → src-ts/dist/core/state.ts} +0 -0
  279. /package/{dist/core/utils.js → src-ts/dist/core/utils.ts} +0 -0
  280. /package/{dist/downloadMedia.js → src-ts/dist/downloadMedia.ts} +0 -0
  281. /package/{dist/errors/index.js → src-ts/dist/errors/index.ts} +0 -0
  282. /package/{dist/extend.js → src-ts/dist/extend.ts} +0 -0
  283. /package/{dist/fbns/fbns.client.events.js → src-ts/dist/fbns/fbns.client.events.ts} +0 -0
  284. /package/{dist/fbns/fbns.client.js → src-ts/dist/fbns/fbns.client.ts} +0 -0
  285. /package/{dist/fbns/fbns.device-auth.js → src-ts/dist/fbns/fbns.device-auth.ts} +0 -0
  286. /package/{dist/fbns/fbns.types.js → src-ts/dist/fbns/fbns.types.ts} +0 -0
  287. /package/{dist/fbns/fbns.utilities.js → src-ts/dist/fbns/fbns.utilities.ts} +0 -0
  288. /package/{dist/fbns/index.js → src-ts/dist/fbns/index.ts} +0 -0
  289. /package/{dist/index.js → src-ts/dist/index.ts} +0 -0
  290. /package/{dist/mqtt-shim.js → src-ts/dist/mqtt-shim.ts} +0 -0
  291. /package/{dist/mqttot/index.js → src-ts/dist/mqttot/index.ts} +0 -0
  292. /package/{dist/mqttot/mqttot.client.js → src-ts/dist/mqttot/mqttot.client.ts} +0 -0
  293. /package/{dist/mqttot/mqttot.connect.request.packet.js → src-ts/dist/mqttot/mqttot.connect.request.packet.ts} +0 -0
  294. /package/{dist/mqttot/mqttot.connect.response.packet.js → src-ts/dist/mqttot/mqttot.connect.response.packet.ts} +0 -0
  295. /package/{dist/mqttot/mqttot.connection.js → src-ts/dist/mqttot/mqttot.connection.ts} +0 -0
  296. /package/{dist/realtime/commands/commands.js → src-ts/dist/realtime/commands/commands.ts} +0 -0
  297. /package/{dist/realtime/commands/direct.commands.js → src-ts/dist/realtime/commands/direct.commands.ts} +0 -0
  298. /package/{dist/realtime/commands/enhanced.direct.commands.js → src-ts/dist/realtime/commands/enhanced.direct.commands.ts} +0 -0
  299. /package/{dist/realtime/commands/index.js → src-ts/dist/realtime/commands/index.ts} +0 -0
  300. /package/{dist/realtime/delta-sync.manager.js → src-ts/dist/realtime/delta-sync.manager.ts} +0 -0
  301. /package/{dist/realtime/features/dm-sender.js → src-ts/dist/realtime/features/dm-sender.ts} +0 -0
  302. /package/{dist/realtime/features/error-handler.js → src-ts/dist/realtime/features/error-handler.ts} +0 -0
  303. /package/{dist/realtime/features/gap-handler.js → src-ts/dist/realtime/features/gap-handler.ts} +0 -0
  304. /package/{dist/realtime/features/persistent-logger.js → src-ts/dist/realtime/features/persistent-logger.ts} +0 -0
  305. /package/{dist/realtime/features/presence.manager.js → src-ts/dist/realtime/features/presence.manager.ts} +0 -0
  306. /package/{dist/realtime/features/session-health-monitor.js → src-ts/dist/realtime/features/session-health-monitor.ts} +0 -0
  307. /package/{dist/realtime/index.js → src-ts/dist/realtime/index.ts} +0 -0
  308. /package/{dist/realtime/messages/app-presence.event.js → src-ts/dist/realtime/messages/app-presence.event.ts} +0 -0
  309. /package/{dist/realtime/messages/index.js → src-ts/dist/realtime/messages/index.ts} +0 -0
  310. /package/{dist/realtime/messages/message-sync.message.js → src-ts/dist/realtime/messages/message-sync.message.ts} +0 -0
  311. /package/{dist/realtime/messages/realtime-sub.direct.data.js → src-ts/dist/realtime/messages/realtime-sub.direct.data.ts} +0 -0
  312. /package/{dist/realtime/messages/thread-update.message.js → src-ts/dist/realtime/messages/thread-update.message.ts} +0 -0
  313. /package/{dist/realtime/mixins/index.js → src-ts/dist/realtime/mixins/index.ts} +0 -0
  314. /package/{dist/realtime/mixins/message-sync.mixin.js → src-ts/dist/realtime/mixins/message-sync.mixin.ts} +0 -0
  315. /package/{dist/realtime/mixins/mixin.js → src-ts/dist/realtime/mixins/mixin.ts} +0 -0
  316. /package/{dist/realtime/mixins/presence-typing.mixin.js → src-ts/dist/realtime/mixins/presence-typing.mixin.ts} +0 -0
  317. /package/{dist/realtime/mixins/realtime-sub.mixin.js → src-ts/dist/realtime/mixins/realtime-sub.mixin.ts} +0 -0
  318. /package/{dist/realtime/parsers/graphql-parser.js → src-ts/dist/realtime/parsers/graphql-parser.ts} +0 -0
  319. /package/{dist/realtime/parsers/graphql.parser.js → src-ts/dist/realtime/parsers/graphql.parser.ts} +0 -0
  320. /package/{dist/realtime/parsers/index.js → src-ts/dist/realtime/parsers/index.ts} +0 -0
  321. /package/{dist/realtime/parsers/iris-parser.js → src-ts/dist/realtime/parsers/iris-parser.ts} +0 -0
  322. /package/{dist/realtime/parsers/iris.parser.js → src-ts/dist/realtime/parsers/iris.parser.ts} +0 -0
  323. /package/{dist/realtime/parsers/json-parser.js → src-ts/dist/realtime/parsers/json-parser.ts} +0 -0
  324. /package/{dist/realtime/parsers/json.parser.js → src-ts/dist/realtime/parsers/json.parser.ts} +0 -0
  325. /package/{dist/realtime/parsers/parser.js → src-ts/dist/realtime/parsers/parser.ts} +0 -0
  326. /package/{dist/realtime/parsers/region-hint-parser.js → src-ts/dist/realtime/parsers/region-hint-parser.ts} +0 -0
  327. /package/{dist/realtime/parsers/region-hint.parser.js → src-ts/dist/realtime/parsers/region-hint.parser.ts} +0 -0
  328. /package/{dist/realtime/parsers/skywalker-parser.js → src-ts/dist/realtime/parsers/skywalker-parser.ts} +0 -0
  329. /package/{dist/realtime/parsers/skywalker.parser.js → src-ts/dist/realtime/parsers/skywalker.parser.ts} +0 -0
  330. /package/{dist/realtime/parsers-advanced.js → src-ts/dist/realtime/parsers-advanced.ts} +0 -0
  331. /package/{dist/realtime/proto-parser.js → src-ts/dist/realtime/proto-parser.ts} +0 -0
  332. /package/{dist/realtime/protocols/iris.handshake.js → src-ts/dist/realtime/protocols/iris.handshake.ts} +0 -0
  333. /package/{dist/realtime/protocols/skywalker.protocol.js → src-ts/dist/realtime/protocols/skywalker.protocol.ts} +0 -0
  334. /package/{dist/realtime/realtime.client.events.js → src-ts/dist/realtime/realtime.client.events.ts} +0 -0
  335. /package/{dist/realtime/realtime.client.js → src-ts/dist/realtime/realtime.client.ts} +0 -0
  336. /package/{dist/realtime/realtime.service.js → src-ts/dist/realtime/realtime.service.ts} +0 -0
  337. /package/{dist/realtime/reconnect.manager.js → src-ts/dist/realtime/reconnect.manager.ts} +0 -0
  338. /package/{dist/realtime/session.manager.js → src-ts/dist/realtime/session.manager.ts} +0 -0
  339. /package/{dist/realtime/subscriptions/graphql.subscription.js → src-ts/dist/realtime/subscriptions/graphql.subscription.ts} +0 -0
  340. /package/{dist/realtime/subscriptions/index.js → src-ts/dist/realtime/subscriptions/index.ts} +0 -0
  341. /package/{dist/realtime/subscriptions/skywalker.subscription.js → src-ts/dist/realtime/subscriptions/skywalker.subscription.ts} +0 -0
  342. /package/{dist/realtime/topic-map.js → src-ts/dist/realtime/topic-map.ts} +0 -0
  343. /package/{dist/realtime/topic.js → src-ts/dist/realtime/topic.ts} +0 -0
  344. /package/{dist/repositories/account.repository.js → src-ts/dist/repositories/account.repository.ts} +0 -0
  345. /package/{dist/repositories/bloks.repository.js → src-ts/dist/repositories/bloks.repository.ts} +0 -0
  346. /package/{dist/repositories/captcha.repository.js → src-ts/dist/repositories/captcha.repository.ts} +0 -0
  347. /package/{dist/repositories/challenge.repository.js → src-ts/dist/repositories/challenge.repository.ts} +0 -0
  348. /package/{dist/repositories/clip.repository.js → src-ts/dist/repositories/clip.repository.ts} +0 -0
  349. /package/{dist/repositories/close-friends.repository.js → src-ts/dist/repositories/close-friends.repository.ts} +0 -0
  350. /package/{dist/repositories/collection.repository.js → src-ts/dist/repositories/collection.repository.ts} +0 -0
  351. /package/{dist/repositories/direct-thread.repository.js → src-ts/dist/repositories/direct-thread.repository.ts} +0 -0
  352. /package/{dist/repositories/direct.repository.js → src-ts/dist/repositories/direct.repository.ts} +0 -0
  353. /package/{dist/repositories/explore.repository.js → src-ts/dist/repositories/explore.repository.ts} +0 -0
  354. /package/{dist/repositories/fbsearch.repository.js → src-ts/dist/repositories/fbsearch.repository.ts} +0 -0
  355. /package/{dist/repositories/feed.repository.js → src-ts/dist/repositories/feed.repository.ts} +0 -0
  356. /package/{dist/repositories/friendship.repository.js → src-ts/dist/repositories/friendship.repository.ts} +0 -0
  357. /package/{dist/repositories/fundraiser.repository.js → src-ts/dist/repositories/fundraiser.repository.ts} +0 -0
  358. /package/{dist/repositories/hashtag.repository.js → src-ts/dist/repositories/hashtag.repository.ts} +0 -0
  359. /package/{dist/repositories/highlights.repository.js → src-ts/dist/repositories/highlights.repository.ts} +0 -0
  360. /package/{dist/repositories/insights.repository.js → src-ts/dist/repositories/insights.repository.ts} +0 -0
  361. /package/{dist/repositories/location.repository.js → src-ts/dist/repositories/location.repository.ts} +0 -0
  362. /package/{dist/repositories/media.repository.js → src-ts/dist/repositories/media.repository.ts} +0 -0
  363. /package/{dist/repositories/multiple-accounts.repository.js → src-ts/dist/repositories/multiple-accounts.repository.ts} +0 -0
  364. /package/{dist/repositories/news.repository.js → src-ts/dist/repositories/news.repository.ts} +0 -0
  365. /package/{dist/repositories/note.repository.js → src-ts/dist/repositories/note.repository.ts} +0 -0
  366. /package/{dist/repositories/notification.repository.js → src-ts/dist/repositories/notification.repository.ts} +0 -0
  367. /package/{dist/repositories/share.repository.js → src-ts/dist/repositories/share.repository.ts} +0 -0
  368. /package/{dist/repositories/signup.repository.js → src-ts/dist/repositories/signup.repository.ts} +0 -0
  369. /package/{dist/repositories/story.repository.js → src-ts/dist/repositories/story.repository.ts} +0 -0
  370. /package/{dist/repositories/timeline.repository.js → src-ts/dist/repositories/timeline.repository.ts} +0 -0
  371. /package/{dist/repositories/totp.repository.js → src-ts/dist/repositories/totp.repository.ts} +0 -0
  372. /package/{dist/repositories/track.repository.js → src-ts/dist/repositories/track.repository.ts} +0 -0
  373. /package/{dist/repositories/upload.repository.js → src-ts/dist/repositories/upload.repository.ts} +0 -0
  374. /package/{dist/repositories/user.repository.js → src-ts/dist/repositories/user.repository.ts} +0 -0
  375. /package/{dist/sendmedia/index.js → src-ts/dist/sendmedia/index.ts} +0 -0
  376. /package/{dist/sendmedia/sendFile.js → src-ts/dist/sendmedia/sendFile.ts} +0 -0
  377. /package/{dist/sendmedia/sendPhoto.js → src-ts/dist/sendmedia/sendPhoto.ts} +0 -0
  378. /package/{dist/sendmedia/sendRavenPhoto.js → src-ts/dist/sendmedia/sendRavenPhoto.ts} +0 -0
  379. /package/{dist/sendmedia/sendRavenVideo.js → src-ts/dist/sendmedia/sendRavenVideo.ts} +0 -0
  380. /package/{dist/sendmedia/uploadPhoto.js → src-ts/dist/sendmedia/uploadPhoto.ts} +0 -0
  381. /package/{dist/sendmedia/uploadfFile.js → src-ts/dist/sendmedia/uploadfFile.ts} +0 -0
  382. /package/{dist/services/live.service.js → src-ts/dist/services/live.service.ts} +0 -0
  383. /package/{dist/services/search.service.js → src-ts/dist/services/search.service.ts} +0 -0
  384. /package/{dist/shared/index.js → src-ts/dist/shared/index.ts} +0 -0
  385. /package/{dist/shared/shared.js → src-ts/dist/shared/shared.ts} +0 -0
  386. /package/{dist/thrift/index.js → src-ts/dist/thrift/index.ts} +0 -0
  387. /package/{dist/thrift/thrift.reading.js → src-ts/dist/thrift/thrift.reading.ts} +0 -0
  388. /package/{dist/thrift/thrift.js → src-ts/dist/thrift/thrift.ts} +0 -0
  389. /package/{dist/thrift/thrift.writing.js → src-ts/dist/thrift/thrift.writing.ts} +0 -0
  390. /package/{dist/types/index.js → src-ts/dist/types/index.ts} +0 -0
  391. /package/{dist/useMultiFileAuthState.js → src-ts/dist/useMultiFileAuthState.ts} +0 -0
  392. /package/{dist/utils/index.js → src-ts/dist/utils/index.ts} +0 -0
@@ -0,0 +1,1267 @@
1
+ const Repository = require('../core/repository');
2
+ const crypto = require('crypto');
3
+ class AccountRepository extends Repository {
4
+ constructor(client) {
5
+ super(client);
6
+ this.maxRetries = 3;
7
+ }
8
+ async requestWithRetry(requestFn, retries = 0) {
9
+ var _a, _b;
10
+ try {
11
+ const result = await requestFn();
12
+ return result;
13
+ }
14
+ catch (error) {
15
+ const shouldRetry = (((_a = error.data) === null || _a === void 0 ? void 0 : _a.error_type) === 'server_error' ||
16
+ ((_b = error.data) === null || _b === void 0 ? void 0 : _b.error_type) === 'rate_limited') &&
17
+ retries < this.maxRetries;
18
+ if (shouldRetry) {
19
+ const delay = 1000 * (retries + 1);
20
+ await new Promise(resolve => setTimeout(resolve, delay));
21
+ return this.requestWithRetry(requestFn, retries + 1);
22
+ }
23
+ throw error;
24
+ }
25
+ }
26
+ /**
27
+ * Helper: try to extract an IGT bearer token from various sources:
28
+ * - response.headers (IG-Set-Authorization or ig-set-authorization)
29
+ * - response.body top-level fields
30
+ * - body.layout (stringified layout)
31
+ * - any embedded login_response.headers JSON inside layout or body
32
+ *
33
+ * When found, sets this.client.state.authorization and calls updateAuthorization().
34
+ */
35
+ _extractAndSaveAuthorization(response) {
36
+ var _a;
37
+ if (!response)
38
+ return null;
39
+ // Normalize headers (case-insensitive)
40
+ const headers = {};
41
+ if (response.headers && typeof response.headers === 'object') {
42
+ for (const k of Object.keys(response.headers)) {
43
+ headers[k.toLowerCase()] = response.headers[k];
44
+ }
45
+ }
46
+ // Simpler: look for any header that contains ig-set-authorization
47
+ for (const key of Object.keys(headers)) {
48
+ const val = headers[key];
49
+ if (!val)
50
+ continue;
51
+ if (key.includes('ig-set-authorization')) {
52
+ const token = this._normalizeTokenString(val);
53
+ if (token) {
54
+ this.client.state.authorization = token;
55
+ try {
56
+ this.client.state.updateAuthorization();
57
+ }
58
+ catch (e) { }
59
+ return token;
60
+ }
61
+ }
62
+ // Some servers include the header value inside a JSON-like string in other headers
63
+ if (typeof val === 'string' && val.includes('Bearer IGT:2:')) {
64
+ const token = this._findBearerInString(val);
65
+ if (token) {
66
+ this.client.state.authorization = token;
67
+ try {
68
+ this.client.state.updateAuthorization();
69
+ }
70
+ catch (e) { }
71
+ return token;
72
+ }
73
+ }
74
+ }
75
+ // Extract IG-U headers (user id, region, claim) when present
76
+ const dsUserIdHeader = headers['ig-set-ig-u-ds-user-id'] ||
77
+ headers['ig-u-ds-user-id'] ||
78
+ headers['x-ig-set-ig-u-ds-user-id'];
79
+ if (dsUserIdHeader) {
80
+ const m = String(dsUserIdHeader).match(/(\d{3,})/);
81
+ if (m) {
82
+ const uid = m[1];
83
+ this.client.state.cookieUserId = uid;
84
+ this.client.state._userId = uid;
85
+ }
86
+ }
87
+ const rurHeader = headers['ig-set-ig-u-rur'] ||
88
+ headers['ig-u-rur'] ||
89
+ headers['x-ig-set-ig-u-rur'];
90
+ if (rurHeader) {
91
+ const rur = String(rurHeader).trim().replace(/^"|"$/g, '');
92
+ if (rur) {
93
+ this.client.state.igURur = rur;
94
+ }
95
+ }
96
+ const wwwClaimHeader = headers['x-ig-set-www-claim'] ||
97
+ headers['ig-set-www-claim'] ||
98
+ headers['ig-u-www-claim'];
99
+ if (wwwClaimHeader) {
100
+ const claim = String(wwwClaimHeader).trim().replace(/^"|"$/g, '');
101
+ if (claim) {
102
+ this.client.state.igWWWClaim = claim;
103
+ }
104
+ }
105
+ const midHeader = headers['ig-set-x-mid'] ||
106
+ headers['x-mid'] ||
107
+ headers['ig-set-mid'];
108
+ if (midHeader) {
109
+ const mid = String(midHeader).trim().replace(/^"|"$/g, '');
110
+ if (mid) {
111
+ this.client.state.mid = mid;
112
+ }
113
+ }
114
+ // 2) Check response.body for common fields
115
+ const body = response.body;
116
+ if (body) {
117
+ // If body has headers string (some responses embed headers JSON as a string)
118
+ if (body.headers && typeof body.headers === 'string') {
119
+ const token = this._findBearerInString(body.headers);
120
+ if (token) {
121
+ this.client.state.authorization = token;
122
+ try {
123
+ this.client.state.updateAuthorization();
124
+ }
125
+ catch (e) { }
126
+ return token;
127
+ }
128
+ }
129
+ // If body contains a layout object or string, stringify and search it
130
+ try {
131
+ let layoutStr = null;
132
+ if (body.layout) {
133
+ layoutStr = typeof body.layout === 'string' ? body.layout : JSON.stringify(body.layout);
134
+ }
135
+ else if ((_a = body === null || body === void 0 ? void 0 : body.layout) === null || _a === void 0 ? void 0 : _a.bloks_payload) {
136
+ layoutStr = JSON.stringify(body.layout.bloks_payload);
137
+ }
138
+ else if (body === null || body === void 0 ? void 0 : body.bloks_payload) {
139
+ layoutStr = JSON.stringify(body.bloks_payload);
140
+ }
141
+ if (!layoutStr && typeof body === 'string') {
142
+ layoutStr = body;
143
+ }
144
+ if (layoutStr) {
145
+ const token = this._findBearerInString(layoutStr);
146
+ if (token) {
147
+ this.client.state.authorization = token;
148
+ try {
149
+ this.client.state.updateAuthorization();
150
+ }
151
+ catch (e) { }
152
+ return token;
153
+ }
154
+ // Some responses embed a login_response JSON string inside layout; try to extract it
155
+ const loginResponseMatch = layoutStr.match(/"login_response"\s*:\s*"(\\?{.*?\\?})"/s);
156
+ if (loginResponseMatch) {
157
+ // Unescape JSON string
158
+ let jsonStr = loginResponseMatch[1];
159
+ try {
160
+ jsonStr = jsonStr.replace(/\\"/g, '"').replace(/\\n/g, '');
161
+ const parsed = JSON.parse(jsonStr);
162
+ if (parsed && parsed.headers) {
163
+ const token = this._findBearerInString(parsed.headers);
164
+ if (token) {
165
+ this.client.state.authorization = token;
166
+ try {
167
+ this.client.state.updateAuthorization();
168
+ }
169
+ catch (e) { }
170
+ return token;
171
+ }
172
+ }
173
+ }
174
+ catch (e) {
175
+ // ignore parse errors
176
+ }
177
+ }
178
+ // Also try to find IG-Set-Password-Encryption headers (not token but useful)
179
+ const encKeyIdMatch = layoutStr.match(/IG-Set-Password-Encryption-Key-Id[\\"\s:]+(\d+)/i) ||
180
+ layoutStr.match(/password.encryption.key.id[\\"\s:]+(\d+)/i);
181
+ if (encKeyIdMatch) {
182
+ this.client.state.passwordEncryptionKeyId = parseInt(encKeyIdMatch[1]);
183
+ }
184
+ const encPubKeyMatch = layoutStr.match(/IG-Set-Password-Encryption-Pub-Key[\\"\s:]+([A-Za-z0-9+\/=]+)/i) ||
185
+ layoutStr.match(/password.encryption.pub.key[\\"\s:]+([A-Za-z0-9+\/=]+)/i);
186
+ if (encPubKeyMatch) {
187
+ this.client.state.passwordEncryptionPubKey = encPubKeyMatch[1];
188
+ }
189
+ // Extract user/account identifiers from layout string
190
+ const dsIdMatch = layoutStr.match(/ig-set-ig-u-ds-user-id[\\"\s:]+(\d+)/i) ||
191
+ layoutStr.match(/ig-u-ds-user-id[\\"\s:]+(\d+)/i) ||
192
+ layoutStr.match(/"strong_id__"\s*:\s*"(\d+)"/i) ||
193
+ layoutStr.match(/"pk_id"\s*:\s*"(\d+)"/i) ||
194
+ layoutStr.match(/"pk"\s*:\s*(\d+)/i);
195
+ if (dsIdMatch) {
196
+ const uid = String(dsIdMatch[1]);
197
+ this.client.state.cookieUserId = uid;
198
+ this.client.state._userId = uid;
199
+ }
200
+ const rurMatch = layoutStr.match(/ig-set-ig-u-rur[\\"\s:]+"([^"\\]+)/i) ||
201
+ layoutStr.match(/ig-u-rur[\\"\s:]+"([^"\\]+)/i);
202
+ if (rurMatch) {
203
+ this.client.state.igURur = rurMatch[1];
204
+ }
205
+ const wwwClaimMatch = layoutStr.match(/x-ig-set-www-claim[\\"\s:]+"([^"\\]+)/i);
206
+ if (wwwClaimMatch) {
207
+ this.client.state.igWWWClaim = wwwClaimMatch[1];
208
+ }
209
+ const midMatch = layoutStr.match(/"mid"\s*:\s*"([^"\\]+)"/i);
210
+ if (midMatch) {
211
+ this.client.state.mid = midMatch[1];
212
+ }
213
+ }
214
+ }
215
+ catch (e) {
216
+ // ignore
217
+ }
218
+ // 3) If body.logged_in_user exists and we have authorization already, return it
219
+ if (body.logged_in_user && this.client.state.authorization) {
220
+ return this.client.state.authorization;
221
+ }
222
+ }
223
+ return null;
224
+ }
225
+ // Normalize token string: accept either raw token or "Bearer IGT:2:..." and return trimmed token string
226
+ _normalizeTokenString(val) {
227
+ if (!val || typeof val !== 'string')
228
+ return null;
229
+ // If header already contains "Bearer IGT:2:..."
230
+ const bearer = this._findBearerInString(val);
231
+ if (bearer)
232
+ return bearer;
233
+ // If header contains JSON with IG-Set-Authorization field
234
+ try {
235
+ const maybeJson = JSON.parse(val);
236
+ if (maybeJson['IG-Set-Authorization']) {
237
+ return this._findBearerInString(maybeJson['IG-Set-Authorization']);
238
+ }
239
+ }
240
+ catch (e) {
241
+ // not JSON
242
+ }
243
+ // fallback: return trimmed value
244
+ return val.trim();
245
+ }
246
+ // Find bearer token in arbitrary string using multiple patterns
247
+ _findBearerInString(str) {
248
+ if (!str || typeof str !== 'string')
249
+ return null;
250
+ // Patterns to match the Bearer token in many possible encodings/escapes
251
+ const bearerPatterns = [
252
+ /Bearer IGT:2:[A-Za-z0-9+\/=]+/,
253
+ /Bearer\s+IGT:2:[A-Za-z0-9+\/=]+/,
254
+ /\?"Bearer IGT:2:([A-Za-z0-9+\/=]+)\?"/,
255
+ /ig-set-authorization[\\"\s:]*Bearer IGT:2:([A-Za-z0-9+\/=]+)/i,
256
+ /"IG-Set-Authorization"\s*:\s*"(Bearer IGT:2:[A-Za-z0-9+\/=]+)"/i,
257
+ /IG-Set-Authorization[\s:]+(Bearer IGT:2:[A-Za-z0-9+\/=]+)/i,
258
+ /Bearer IGT:2:([A-Za-z0-9+\/=]+)/,
259
+ ];
260
+ for (const pattern of bearerPatterns) {
261
+ const m = str.match(pattern);
262
+ if (m) {
263
+ // If capturing group present, prefer it
264
+ if (m[1]) {
265
+ const token = m[1].includes('Bearer IGT:2:') ? m[1] : `Bearer IGT:2:${m[1]}`;
266
+ return token.replace(/\?"/g, '').trim();
267
+ }
268
+ // Otherwise m[0] contains the full token
269
+ return m[0].replace(/\?"/g, '').trim();
270
+ }
271
+ }
272
+ return null;
273
+ }
274
+ // Ensure we have a valid csrftoken cookie (and mid) before sensitive endpoints.
275
+ // Instagram typically sets csrftoken via /api/v1/si/fetch_headers/.
276
+ async ensureCsrfToken() {
277
+ const cookieToken = this.client.state.cookieCsrfToken;
278
+ if (cookieToken && cookieToken !== 'missing' && cookieToken !== 'pending') {
279
+ try {
280
+ this.client.state.csrfToken = cookieToken;
281
+ }
282
+ catch { }
283
+ return cookieToken;
284
+ }
285
+ // Warmup endpoint that returns/set cookies (csrftoken, mid, etc.)
286
+ try {
287
+ await this.client.request.send({
288
+ method: 'GET',
289
+ url: `/api/v1/si/fetch_headers/?challenge_type=signup&guid=${this.client.state.uuid}`,
290
+ });
291
+ }
292
+ catch (e) {
293
+ // ignore warmup failures
294
+ }
295
+ const token = this.client.state.cookieCsrfToken;
296
+ if (token && token !== 'missing' && token !== 'pending') {
297
+ try {
298
+ this.client.state.csrfToken = token;
299
+ }
300
+ catch { }
301
+ return token;
302
+ }
303
+ return null;
304
+ }
305
+ async login(credentialsOrUsername, passwordArg) {
306
+ let username, password;
307
+ if (typeof credentialsOrUsername === 'object' && credentialsOrUsername !== null) {
308
+ username = credentialsOrUsername.username;
309
+ password = credentialsOrUsername.password;
310
+ }
311
+ else {
312
+ username = credentialsOrUsername;
313
+ password = passwordArg;
314
+ }
315
+ if (!username || !password) {
316
+ throw new Error('Username and password are required');
317
+ }
318
+ if (!this.client.state.passwordEncryptionPubKey) {
319
+ await this.syncLoginExperiments();
320
+ }
321
+ const { encrypted, time } = this.encryptPassword(password);
322
+ // optional CSRF warmup (like app does before login)
323
+ await this.ensureCsrfToken();
324
+ return this.requestWithRetry(async () => {
325
+ // ====== client_input_params (oglindă după traficul real) ======
326
+ const nowSec = Math.floor(Date.now() / 1000);
327
+ const aacInitTimestamp = nowSec - Math.floor(Math.random() * 50);
328
+ const aacjid = crypto.randomUUID ? crypto.randomUUID() : require('uuid').v4();
329
+ const aaccs = crypto.randomBytes(32).toString('base64').replace(/=/g, '');
330
+ const androidDeviceId = this.client.state.androidDeviceId ||
331
+ this.client.state.deviceId ||
332
+ `android-${crypto.randomBytes(8).toString('hex')}`;
333
+ const machineId = this.client.state.mid ||
334
+ this.client.state.machineId ||
335
+ `aZ${crypto.randomBytes(8).toString('hex')}`;
336
+ const familyDeviceId = this.client.state.phoneId ||
337
+ this.client.state.familyDeviceId ||
338
+ crypto.randomUUID
339
+ ? crypto.randomUUID()
340
+ : require('uuid').v4();
341
+ const qeDeviceId = this.client.state.deviceId ||
342
+ this.client.state.qeDeviceId ||
343
+ crypto.randomUUID
344
+ ? crypto.randomUUID()
345
+ : require('uuid').v4();
346
+ const accountsList = this.client.state.accountsList || [];
347
+ const flashCallPermissionStatus = {
348
+ READ_PHONE_STATE: 'GRANTED',
349
+ READ_CALL_LOG: 'GRANTED',
350
+ ANSWER_PHONE_CALLS: 'GRANTED',
351
+ };
352
+ const clientInputParams = {
353
+ aac: JSON.stringify({
354
+ aac_init_timestamp: aacInitTimestamp,
355
+ aacjid,
356
+ aaccs,
357
+ }),
358
+ sim_phones: [],
359
+ aymh_accounts: [],
360
+ network_bssid: null,
361
+ secure_family_device_id: '',
362
+ has_granted_read_contacts_permissions: 0,
363
+ auth_secure_device_id: '',
364
+ has_whatsapp_installed: 1,
365
+ password: `#PWD_INSTAGRAM:4:${time}:${encrypted}`,
366
+ sso_token_map_json_string: JSON.stringify({
367
+ [this.client.state.cookieUserId || '0']: [],
368
+ }),
369
+ block_store_machine_id: '',
370
+ ig_vetted_device_nonces: JSON.stringify({}),
371
+ cloud_trust_token: null,
372
+ event_flow: 'login_manual',
373
+ password_contains_non_ascii: 'false',
374
+ client_known_key_hash: '',
375
+ encrypted_msisdn: '',
376
+ has_granted_read_phone_permissions: 0,
377
+ app_manager_id: '',
378
+ should_show_nested_nta_from_aymh: 0,
379
+ device_id: androidDeviceId,
380
+ zero_balance_state: '',
381
+ login_attempt_count: 1,
382
+ machine_id: machineId,
383
+ flash_call_permission_status: flashCallPermissionStatus,
384
+ accounts_list: accountsList,
385
+ gms_incoming_call_retriever_eligibility: 'client_not_supported',
386
+ family_device_id: familyDeviceId,
387
+ fb_ig_device_id: [],
388
+ device_emails: [],
389
+ try_num: 1,
390
+ lois_settings: { lois_token: '' },
391
+ event_step: 'home_page',
392
+ headers_infra_flow_id: '',
393
+ openid_tokens: {},
394
+ contact_point: username,
395
+ };
396
+ // ====== server_params (oglindă după traficul real) ======
397
+ const waterfallId = crypto.randomUUID ? crypto.randomUUID() : require('uuid').v4();
398
+ const latencyMarkerId = 36707139;
399
+ const latencyInstanceId = Number(`${Date.now()}${Math.floor(Math.random() * 1000)}`);
400
+ const serverParams = {
401
+ should_trigger_override_login_2fa_action: 0,
402
+ is_vanilla_password_page_empty_password: 0,
403
+ is_from_logged_out: 0,
404
+ should_trigger_override_login_success_action: 0,
405
+ login_credential_type: 'none',
406
+ server_login_source: 'login',
407
+ waterfall_id: waterfallId,
408
+ two_step_login_type: 'one_step_login',
409
+ login_source: 'Login',
410
+ is_platform_login: 0,
411
+ INTERNAL__latency_qpl_marker_id: latencyMarkerId,
412
+ is_from_aymh: 0,
413
+ offline_experiment_group: 'caa_iteration_v3_perf_ig_4',
414
+ is_from_landing_page: 0,
415
+ left_nav_button_action: 'NONE',
416
+ password_text_input_id: 'z0jejq:194',
417
+ is_from_empty_password: 0,
418
+ is_from_msplit_fallback: 0,
419
+ ar_event_source: 'login_home_page',
420
+ qe_device_id: qeDeviceId,
421
+ username_text_input_id: 'z0jejq:193',
422
+ layered_homepage_experiment_group: null,
423
+ device_id: androidDeviceId,
424
+ login_surface: 'switcher',
425
+ INTERNAL__latency_qpl_instance_id: latencyInstanceId,
426
+ reg_flow_source: 'login_home_native_integration_point',
427
+ is_caa_perf_enabled: 1,
428
+ credential_type: 'password',
429
+ is_from_password_entry_page: 0,
430
+ caller: 'gslr',
431
+ family_device_id: familyDeviceId,
432
+ is_from_assistive_id: 0,
433
+ access_flow_version: 'pre_mt_behavior',
434
+ is_from_logged_in_switcher: 1,
435
+ };
436
+ const paramsJson = JSON.stringify({
437
+ client_input_params: clientInputParams,
438
+ server_params: serverParams,
439
+ });
440
+ const attestParams = AccountRepository.generateAttestParams(this.client.state);
441
+ const bkClientContext = JSON.stringify({
442
+ bloks_version: this.client.state.bloksVersionId,
443
+ styles_id: 'instagram',
444
+ });
445
+ // ====== HEADERS – modelate după request_i.instagram.com_mlwzj8x1.txt ======
446
+ const lang = (this.client.state.language || 'ro_RO');
447
+ const acceptLanguage = `${lang.replace('_', '-')}, en-US`;
448
+ const userAgent = this.client.state.userAgent ||
449
+ 'Instagram 371.0.0.0.23 Android (30/11; 320dpi; 720x1449; Xiaomi/Redmi; M2006C3MNG; angelican; mt6765; ro_RO; 703217507)';
450
+ const bloksHeaders = {
451
+ 'accept-language': acceptLanguage,
452
+ 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
453
+ 'ig-intended-user-id': '0',
454
+ 'priority': 'u=3',
455
+ 'x-bloks-is-layout-rtl': 'false',
456
+ 'x-bloks-prism-ax-base-colors-enabled': 'false',
457
+ 'x-bloks-prism-button-version': 'CONTROL',
458
+ 'x-bloks-prism-colors-enabled': 'true',
459
+ 'x-bloks-prism-font-enabled': 'false',
460
+ 'x-bloks-prism-indigo-link-version': '0',
461
+ 'x-bloks-version-id': this.client.state.bloksVersionId,
462
+ 'x-fb-client-ip': 'True',
463
+ 'x-fb-connection-type': 'WIFI',
464
+ 'x-fb-friendly-name': 'IgApi: bloks/async_action/com.bloks.www.bloks.caa.login.async.send_login_request/',
465
+ 'x-fb-network-properties': 'VPN;Validated;LocalAddrs=/10.0.0.2,;',
466
+ 'x-fb-request-analytics-tags': JSON.stringify({
467
+ network_tags: {
468
+ product: String(this.client.state.fbAnalyticsApplicationId || '567067343352427'),
469
+ purpose: 'fetch',
470
+ surface: 'undefined',
471
+ request_category: 'api',
472
+ retry_attempt: '0',
473
+ },
474
+ }),
475
+ 'x-fb-server-cluster': 'True',
476
+ 'x-ig-android-id': androidDeviceId,
477
+ 'x-ig-app-id': String(this.client.state.fbAnalyticsApplicationId || '567067343352427'),
478
+ 'x-ig-app-locale': lang,
479
+ 'x-ig-attest-params': JSON.stringify(attestParams),
480
+ 'x-ig-bandwidth-speed-kbps': (Math.random() * 1500 + 800).toFixed(3),
481
+ 'x-ig-bandwidth-totalbytes-b': '0',
482
+ 'x-ig-bandwidth-totaltime-ms': '0',
483
+ 'x-ig-client-endpoint': 'com.bloks.www.caa.login.aymh_single_profile_screen_entry',
484
+ 'x-ig-capabilities': '3brTv10=',
485
+ 'x-ig-connection-type': 'WIFI',
486
+ 'x-ig-device-id': qeDeviceId,
487
+ 'x-ig-device-locale': lang,
488
+ 'x-ig-family-device-id': familyDeviceId,
489
+ 'x-ig-mapped-locale': lang,
490
+ 'x-ig-nav-chain': 'LockoutFragment:dogfooding_lockout:1:cold_start:...,' +
491
+ 'com.bloks.www.caa.login.aymh_single_profile_screen_entry:com.bloks.www.caa.login.aymh_single_profile_screen_entry:14:button:0:::0',
492
+ 'x-ig-timezone-offset': String(typeof this.client.state.timezoneOffset === 'number'
493
+ ? this.client.state.timezoneOffset
494
+ : 7200),
495
+ 'x-ig-www-claim': this.client.state.igWWWClaim || '0',
496
+ 'x-mid': machineId,
497
+ 'x-pigeon-rawclienttime': `${nowSec}.${Math.floor(Math.random() * 1000)
498
+ .toString()
499
+ .padStart(3, '0')}`,
500
+ 'x-pigeon-session-id': this.client.state.pigeonSessionId ||
501
+ `UFS-${crypto.randomBytes(16).toString('hex')}-1`,
502
+ 'x-tigon-is-retry': 'False',
503
+ // ...
504
+ 'accept-encoding': 'gzip, deflate, br',
505
+ // ...
506
+ 'user-agent': userAgent,
507
+ 'x-fb-conn-uuid-client': crypto.randomBytes(16).toString('hex'),
508
+ 'x-fb-http-engine': 'MNS/TCP',
509
+ 'x-fb-rmd': 'state=URL_ELIGIBLE',
510
+ };
511
+ const response = await this.client.request.send({
512
+ method: 'POST',
513
+ url: '/api/v1/bloks/async_action/com.bloks.www.bloks.caa.login.async.send_login_request/',
514
+ form: {
515
+ params: paramsJson,
516
+ bk_client_context: bkClientContext,
517
+ bloks_versioning_id: this.client.state.bloksVersionId,
518
+ },
519
+ headers: bloksHeaders,
520
+ });
521
+ // === DEBUG LOGIN: salvăm răspunsul pentru analiză ===
522
+ try {
523
+ const fs = require('fs');
524
+ const path = require('path');
525
+ const debugDir = path.join(process.cwd(), 'authinfo_instagram');
526
+ const debugFile = path.join(debugDir, 'login-debug.json');
527
+ try {
528
+ fs.mkdirSync(debugDir, { recursive: true });
529
+ }
530
+ catch (e) { }
531
+ const debugPayload = {
532
+ at: new Date().toISOString(),
533
+ statusCode: response.statusCode || response.status || null,
534
+ headers: response.headers || null,
535
+ body: response.body || null,
536
+ };
537
+ fs.writeFileSync(debugFile, JSON.stringify(debugPayload, null, 2), 'utf8');
538
+ }
539
+ catch (e) {
540
+ // nu stricăm login-ul dacă nu merge debug-ul
541
+ }
542
+ // === SFÂRȘIT DEBUG LOGIN ===
543
+ const body = response.body;
544
+ // Immediately attempt to extract and save authorization token from the response
545
+ this._extractAndSaveAuthorization(response);
546
+ if (body && body.two_factor_required) {
547
+ const err = new Error('Two factor authentication required');
548
+ err.name = 'IgLoginTwoFactorRequiredError';
549
+ err.twoFactorInfo = body.two_factor_info;
550
+ throw err;
551
+ }
552
+ if (body && body.error_type === 'bad_password') {
553
+ const err = new Error('Bad password');
554
+ err.name = 'IgLoginBadPasswordError';
555
+ throw err;
556
+ }
557
+ if (body && body.error_type === 'invalid_user') {
558
+ const err = new Error('Invalid user');
559
+ err.name = 'IgLoginInvalidUserError';
560
+ throw err;
561
+ }
562
+ if (body && body.message === 'challenge_required') {
563
+ const err = new Error('Challenge required');
564
+ err.name = 'IgCheckpointError';
565
+ err.challengeInfo = body.challenge;
566
+ throw err;
567
+ }
568
+ if (body && body.layout) {
569
+ const layoutStr = typeof body.layout === 'string' ? body.layout : JSON.stringify(body.layout);
570
+ // If layout contains two-factor markers, parse and throw
571
+ if (layoutStr.includes('two_factor_required') || layoutStr.includes('"two_factor_info"')) {
572
+ let twoFactorInfo = null;
573
+ try {
574
+ const match = layoutStr.match(/"two_factor_info"\s*:\s*(\{[^}]+\})/);
575
+ if (match)
576
+ twoFactorInfo = JSON.parse(match[1]);
577
+ }
578
+ catch (e) { }
579
+ const err = new Error('Two factor authentication required');
580
+ err.name = 'IgLoginTwoFactorRequiredError';
581
+ err.twoFactorInfo = twoFactorInfo;
582
+ throw err;
583
+ }
584
+ if (layoutStr.includes('bad_password') || layoutStr.includes('incorrect_password')) {
585
+ const err = new Error('Bad password');
586
+ err.name = 'IgLoginBadPasswordError';
587
+ throw err;
588
+ }
589
+ if (layoutStr.includes('invalid_user') || layoutStr.includes('user_not_found')) {
590
+ const err = new Error('Invalid user');
591
+ err.name = 'IgLoginInvalidUserError';
592
+ throw err;
593
+ }
594
+ if (layoutStr.includes('challenge_required')) {
595
+ const err = new Error('Challenge required');
596
+ err.name = 'IgCheckpointError';
597
+ err.challengeInfo = body.challenge || null;
598
+ throw err;
599
+ }
600
+ // Additional attempt to extract token from layout string (redundant but robust)
601
+ const tokenFromLayout = this._findBearerInString(layoutStr);
602
+ if (tokenFromLayout) {
603
+ this.client.state.authorization = tokenFromLayout;
604
+ try {
605
+ this.client.state.updateAuthorization();
606
+ }
607
+ catch (e) { }
608
+ }
609
+ // Extract pk (user id) from layout if present
610
+ const pkPatterns = [
611
+ /\\"pk\\":\s*(\d+)/,
612
+ /"pk":\s*(\d+)/,
613
+ /\\"pk_id\\":\s*\\"(\d+)\\"/,
614
+ /"pk_id":\s*"(\d+)"/,
615
+ /logged_in_user.*?"pk":\s*(\d+)/,
616
+ /logged_in_user.*?\\"pk\\":\s*(\d+)/,
617
+ ];
618
+ let extractedPk = null;
619
+ for (const pattern of pkPatterns) {
620
+ const pkMatch = layoutStr.match(pattern);
621
+ if (pkMatch) {
622
+ extractedPk = pkMatch[1];
623
+ this.client.state.cookieUserId = extractedPk;
624
+ this.client.state._userId = extractedPk;
625
+ break;
626
+ }
627
+ }
628
+ // Extract IG-Set-WWW-Claim if present
629
+ const wwwClaimPatterns = [
630
+ /IG-Set-WWW-Claim[\\"\s:]+([a-f0-9]+)/i,
631
+ /ig-set-www-claim[\\"\s:]+([a-f0-9]+)/i,
632
+ /www.claim[\\"\s:]+([a-f0-9]+)/i,
633
+ /x-ig-set-www-claim[\\"\s:]+([a-f0-9]+)/i,
634
+ ];
635
+ for (const pattern of wwwClaimPatterns) {
636
+ const wwwClaimMatch = layoutStr.match(pattern);
637
+ if (wwwClaimMatch) {
638
+ this.client.state.igWWWClaim = wwwClaimMatch[1];
639
+ break;
640
+ }
641
+ }
642
+ // Extract encryption key id and pub key (already attempted earlier in _extractAndSaveAuthorization)
643
+ const encKeyIdMatch = layoutStr.match(/IG-Set-Password-Encryption-Key-Id[\\"\s:]+(\d+)/i) ||
644
+ layoutStr.match(/password.encryption.key.id[\\"\s:]+(\d+)/i);
645
+ if (encKeyIdMatch) {
646
+ this.client.state.passwordEncryptionKeyId = parseInt(encKeyIdMatch[1]);
647
+ }
648
+ const encPubKeyMatch = layoutStr.match(/IG-Set-Password-Encryption-Pub-Key[\\"\s:]+([A-Za-z0-9+\/=]+)/i) ||
649
+ layoutStr.match(/password.encryption.pub.key[\\"\s:]+([A-Za-z0-9+\/=]+)/i);
650
+ if (encPubKeyMatch) {
651
+ this.client.state.passwordEncryptionPubKey = encPubKeyMatch[1];
652
+ }
653
+ const midMatch = layoutStr.match(/ig-set-x-mid[\\"\s:]+([A-Za-z0-9+\/=_-]+)/i) ||
654
+ layoutStr.match(/\\"x-mid\\"[\\"\s:]+([A-Za-z0-9+\/=_-]+)/i);
655
+ if (midMatch) {
656
+ this.client.state.mid = midMatch[1];
657
+ }
658
+ // If layout contains a direct logged_in_user JSON, extract and return it
659
+ const loginResponsePatterns = [
660
+ /\\"logged_in_user\\":\{[^}]*\\"pk\\":(\d+)[^}]*\\"username\\":\\"([^"\\]+)\\"/,
661
+ /"logged_in_user":\{[^}]*"pk":(\d+)[^}]*"username":"([^"]+)"/,
662
+ /\\"logged_in_user\\".*?\\"pk\\":\s*(\d+).*?\\"username\\":\s*\\"([^"\\]+)\\"/s,
663
+ ];
664
+ for (const pattern of loginResponsePatterns) {
665
+ const loginResponseMatch = layoutStr.match(pattern);
666
+ if (loginResponseMatch) {
667
+ this.client.state.cookieUserId = loginResponseMatch[1];
668
+ this.client.state._userId = loginResponseMatch[1];
669
+ return {
670
+ pk: parseInt(loginResponseMatch[1]),
671
+ pk_id: loginResponseMatch[1],
672
+ username: loginResponseMatch[2],
673
+ };
674
+ }
675
+ }
676
+ // If we have extracted a pk and we also have authorization, try to fetch current user
677
+ if (extractedPk && this.client.state.authorization) {
678
+ try {
679
+ const userInfo = await this.currentUser();
680
+ const user = userInfo.user || userInfo;
681
+ if (user && user.pk) {
682
+ this.client.state.cookieUserId = String(user.pk);
683
+ this.client.state._userId = String(user.pk);
684
+ }
685
+ return user;
686
+ }
687
+ catch (e) {
688
+ return { pk: parseInt(extractedPk), pk_id: extractedPk };
689
+ }
690
+ }
691
+ }
692
+ // If server returned logged_in_user directly in body
693
+ if (body && body.logged_in_user) {
694
+ const lu = body.logged_in_user;
695
+ if (lu.pk) {
696
+ this.client.state.cookieUserId = String(lu.pk);
697
+ this.client.state._userId = String(lu.pk);
698
+ }
699
+ // Ensure authorization is saved if present in response headers
700
+ this._extractAndSaveAuthorization(response);
701
+ return lu;
702
+ }
703
+ // If we already have authorization, try to fetch current user to populate state
704
+ if (this.client.state.authorization) {
705
+ try {
706
+ const userInfo = await this.currentUser();
707
+ const user = userInfo.user || userInfo;
708
+ if (user && user.pk) {
709
+ this.client.state.cookieUserId = String(user.pk);
710
+ this.client.state._userId = String(user.pk);
711
+ }
712
+ return user;
713
+ }
714
+ catch (e) {
715
+ // fallback: return raw body
716
+ return body;
717
+ }
718
+ }
719
+ return body;
720
+ });
721
+ }
722
+ async twoFactorLogin(username, verificationCode, twoFactorIdentifier, verificationMethod = '1') {
723
+ return this.requestWithRetry(async () => {
724
+ const response = await this.client.request.send({
725
+ method: 'POST',
726
+ url: '/api/v1/accounts/two_factor_login/',
727
+ form: this.client.request.sign({
728
+ username,
729
+ verification_code: verificationCode,
730
+ two_factor_identifier: twoFactorIdentifier,
731
+ verification_method: verificationMethod,
732
+ trust_this_device: '1',
733
+ guid: this.client.state.uuid,
734
+ device_id: this.client.state.deviceId,
735
+ phone_id: this.client.state.phoneId,
736
+ }),
737
+ });
738
+ // Save authorization if present in two-factor response
739
+ this._extractAndSaveAuthorization(response);
740
+ return response.body;
741
+ });
742
+ }
743
+ async logout() {
744
+ return this.requestWithRetry(async () => {
745
+ const response = await this.client.request.send({
746
+ method: 'POST',
747
+ url: '/api/v1/accounts/logout/',
748
+ form: this.client.request.sign({
749
+ _uuid: this.client.state.uuid,
750
+ }),
751
+ });
752
+ return response.body;
753
+ });
754
+ }
755
+ async currentUser() {
756
+ return this.requestWithRetry(async () => {
757
+ const response = await this.client.request.send({
758
+ method: 'GET',
759
+ url: '/api/v1/accounts/current_user/',
760
+ qs: { edit: true },
761
+ });
762
+ return response.body;
763
+ });
764
+ }
765
+ async accountInfo() {
766
+ return this.currentUser();
767
+ }
768
+ async editProfile({ externalUrl, phoneNumber, username, fullName, biography, email } = {}) {
769
+ return this.requestWithRetry(async () => {
770
+ const current = await this.currentUser();
771
+ const user = current.user || current;
772
+ const response = await this.client.request.send({
773
+ method: 'POST',
774
+ url: '/api/v1/accounts/edit_profile/',
775
+ form: this.client.request.sign({
776
+ _uuid: this.client.state.uuid,
777
+ external_url: externalUrl !== undefined ? externalUrl : (user.external_url || ''),
778
+ phone_number: phoneNumber !== undefined ? phoneNumber : (user.phone_number || ''),
779
+ username: username !== undefined ? username : user.username,
780
+ full_name: fullName !== undefined ? fullName : (user.full_name || ''),
781
+ biography: biography !== undefined ? biography : (user.biography || ''),
782
+ email: email !== undefined ? email : (user.email || ''),
783
+ }),
784
+ });
785
+ return response.body;
786
+ });
787
+ }
788
+ async setBiography(biography) {
789
+ return this.editProfile({ biography });
790
+ }
791
+ async setExternalUrl(url) {
792
+ return this.editProfile({ externalUrl: url });
793
+ }
794
+ async removeBioLinks() {
795
+ return this.editProfile({ externalUrl: '' });
796
+ }
797
+ async setGender(gender) {
798
+ return this.requestWithRetry(async () => {
799
+ const response = await this.client.request.send({
800
+ method: 'POST',
801
+ url: '/api/v1/accounts/set_gender/',
802
+ form: this.client.request.sign({
803
+ _uuid: this.client.state.uuid,
804
+ gender,
805
+ }),
806
+ });
807
+ return response.body;
808
+ });
809
+ }
810
+ async setPrivate() {
811
+ return this.requestWithRetry(async () => {
812
+ const response = await this.client.request.send({
813
+ method: 'POST',
814
+ url: '/api/v1/accounts/set_private/',
815
+ form: this.client.request.sign({
816
+ _uuid: this.client.state.uuid,
817
+ }),
818
+ });
819
+ return response.body;
820
+ });
821
+ }
822
+ async setPublic() {
823
+ return this.requestWithRetry(async () => {
824
+ const response = await this.client.request.send({
825
+ method: 'POST',
826
+ url: '/api/v1/accounts/set_public/',
827
+ form: this.client.request.sign({
828
+ _uuid: this.client.state.uuid,
829
+ }),
830
+ });
831
+ return response.body;
832
+ });
833
+ }
834
+ async changePassword(oldPassword, newPassword) {
835
+ const oldEnc = this.encryptPassword(oldPassword);
836
+ const newEnc = this.encryptPassword(newPassword);
837
+ return this.requestWithRetry(async () => {
838
+ const response = await this.client.request.send({
839
+ method: 'POST',
840
+ url: '/api/v1/accounts/change_password/',
841
+ form: this.client.request.sign({
842
+ _uuid: this.client.state.uuid,
843
+ enc_old_password: `#PWD_INSTAGRAM:4:${oldEnc.time}:${oldEnc.encrypted}`,
844
+ enc_new_password1: `#PWD_INSTAGRAM:4:${newEnc.time}:${newEnc.encrypted}`,
845
+ enc_new_password2: `#PWD_INSTAGRAM:4:${newEnc.time}:${newEnc.encrypted}`,
846
+ }),
847
+ });
848
+ return response.body;
849
+ });
850
+ }
851
+ async sendConfirmEmail() {
852
+ return this.requestWithRetry(async () => {
853
+ const response = await this.client.request.send({
854
+ method: 'POST',
855
+ url: '/api/v1/accounts/send_confirm_email/',
856
+ form: this.client.request.sign({
857
+ _uuid: this.client.state.uuid,
858
+ send_source: 'edit_profile',
859
+ }),
860
+ });
861
+ return response.body;
862
+ });
863
+ }
864
+ async sendConfirmPhoneNumber(phoneNumber) {
865
+ return this.requestWithRetry(async () => {
866
+ const response = await this.client.request.send({
867
+ method: 'POST',
868
+ url: '/api/v1/accounts/send_confirm_phone_number/',
869
+ form: this.client.request.sign({
870
+ _uuid: this.client.state.uuid,
871
+ phone_number: phoneNumber,
872
+ }),
873
+ });
874
+ return response.body;
875
+ });
876
+ }
877
+ async profilePictureChange(uploadId) {
878
+ return this.requestWithRetry(async () => {
879
+ const response = await this.client.request.send({
880
+ method: 'POST',
881
+ url: '/api/v1/accounts/change_profile_picture/',
882
+ form: this.client.request.sign({
883
+ _uuid: this.client.state.uuid,
884
+ use_fbuploader: 'true',
885
+ upload_id: uploadId,
886
+ }),
887
+ });
888
+ return response.body;
889
+ });
890
+ }
891
+ async profilePictureRemove() {
892
+ return this.requestWithRetry(async () => {
893
+ const response = await this.client.request.send({
894
+ method: 'POST',
895
+ url: '/api/v1/accounts/remove_profile_picture/',
896
+ form: this.client.request.sign({
897
+ _uuid: this.client.state.uuid,
898
+ }),
899
+ });
900
+ return response.body;
901
+ });
902
+ }
903
+ async newsInbox() {
904
+ return this.requestWithRetry(async () => {
905
+ const response = await this.client.request.send({
906
+ method: 'GET',
907
+ url: '/api/v1/news/inbox/',
908
+ });
909
+ return response.body;
910
+ });
911
+ }
912
+ async syncLoginExperiments() {
913
+ return this.requestWithRetry(async () => {
914
+ const response = await this.client.request.send({
915
+ method: 'POST',
916
+ url: '/api/v1/qe/sync/',
917
+ form: this.client.request.sign({
918
+ id: this.client.state.uuid,
919
+ server_config_retrieval: '1',
920
+ experiments: this.client.state.constants.LOGIN_EXPERIMENTS,
921
+ }),
922
+ });
923
+ return response.body;
924
+ });
925
+ }
926
+ async syncPostLoginExperiments() {
927
+ let userId;
928
+ try {
929
+ userId = this.client.state.cookieUserId;
930
+ }
931
+ catch {
932
+ userId = '0';
933
+ }
934
+ return this.requestWithRetry(async () => {
935
+ const response = await this.client.request.send({
936
+ method: 'POST',
937
+ url: '/api/v1/qe/sync/',
938
+ form: this.client.request.sign({
939
+ id: userId,
940
+ _uid: userId,
941
+ _uuid: this.client.state.uuid,
942
+ server_config_retrieval: '1',
943
+ experiments: this.client.state.constants.EXPERIMENTS,
944
+ }),
945
+ });
946
+ return response.body;
947
+ });
948
+ }
949
+ async syncLauncher(preLogin = true) {
950
+ const data = {
951
+ id: this.client.state.uuid,
952
+ server_config_retrieval: '1',
953
+ };
954
+ if (!preLogin) {
955
+ try {
956
+ data._uid = this.client.state.cookieUserId;
957
+ data._uuid = this.client.state.uuid;
958
+ }
959
+ catch { }
960
+ }
961
+ return this.requestWithRetry(async () => {
962
+ const response = await this.client.request.send({
963
+ method: 'POST',
964
+ url: '/api/v1/launcher/sync/',
965
+ form: this.client.request.sign(data),
966
+ });
967
+ return response.body;
968
+ });
969
+ }
970
+ async syncDeviceFeatures() {
971
+ return this.requestWithRetry(async () => {
972
+ const response = await this.client.request.send({
973
+ method: 'POST',
974
+ url: '/api/v1/devices/sync/',
975
+ form: this.client.request.sign({
976
+ id: this.client.state.uuid,
977
+ server_config_retrieval: '1',
978
+ }),
979
+ });
980
+ return response.body;
981
+ });
982
+ }
983
+ async getPrefillCandidates() {
984
+ return this.requestWithRetry(async () => {
985
+ const response = await this.client.request.send({
986
+ method: 'POST',
987
+ url: '/api/v1/accounts/get_prefill_candidates/',
988
+ form: this.client.request.sign({
989
+ android_device_id: this.client.state.deviceId,
990
+ phone_id: this.client.state.phoneId,
991
+ usages: '["account_recovery_omnibox"]',
992
+ device_id: this.client.state.uuid,
993
+ }),
994
+ });
995
+ return response.body;
996
+ });
997
+ }
998
+ async contactPointPrefill(usage = 'prefill') {
999
+ return this.requestWithRetry(async () => {
1000
+ const response = await this.client.request.send({
1001
+ method: 'POST',
1002
+ url: '/api/v1/accounts/contact_point_prefill/',
1003
+ form: this.client.request.sign({
1004
+ phone_id: this.client.state.phoneId,
1005
+ usage,
1006
+ }),
1007
+ });
1008
+ return response.body;
1009
+ });
1010
+ }
1011
+ async getZrToken(params = {}) {
1012
+ return this.requestWithRetry(async () => {
1013
+ const response = await this.client.request.send({
1014
+ method: 'GET',
1015
+ url: '/api/v1/zr/token/result/',
1016
+ qs: {
1017
+ device_id: this.client.state.deviceId,
1018
+ custom_device_id: this.client.state.uuid,
1019
+ fetch_reason: 'token_expired',
1020
+ token_hash: '',
1021
+ ...params,
1022
+ },
1023
+ });
1024
+ return response.body;
1025
+ });
1026
+ }
1027
+ async getConsentSignupConfig() {
1028
+ return this.requestWithRetry(async () => {
1029
+ const response = await this.client.request.send({
1030
+ method: 'GET',
1031
+ url: '/api/v1/consent/get_signup_config/',
1032
+ qs: {
1033
+ guid: this.client.state.uuid,
1034
+ main_account_selected: false,
1035
+ },
1036
+ });
1037
+ return response.body;
1038
+ });
1039
+ }
1040
+ async sendRecoveryFlowEmail(query) {
1041
+ return this.requestWithRetry(async () => {
1042
+ const response = await this.client.request.send({
1043
+ url: '/api/v1/accounts/send_recovery_flow_email/',
1044
+ method: 'POST',
1045
+ form: this.client.request.sign({
1046
+ adid: '',
1047
+ guid: this.client.state.uuid,
1048
+ device_id: this.client.state.deviceId,
1049
+ query,
1050
+ }),
1051
+ });
1052
+ return response.body;
1053
+ });
1054
+ }
1055
+ async sendRecoveryFlowSms(query) {
1056
+ return this.requestWithRetry(async () => {
1057
+ const response = await this.client.request.send({
1058
+ url: '/api/v1/accounts/send_recovery_flow_sms/',
1059
+ method: 'POST',
1060
+ form: this.client.request.sign({
1061
+ adid: '',
1062
+ guid: this.client.state.uuid,
1063
+ device_id: this.client.state.deviceId,
1064
+ query,
1065
+ }),
1066
+ });
1067
+ return response.body;
1068
+ });
1069
+ }
1070
+ static generateAttestParams(state) {
1071
+ // Emulate Instagram's keystore attestation as closely as possible:
1072
+ // - version: 2
1073
+ // - type: "keystore"
1074
+ // - errors: [0]
1075
+ // - challenge_nonce: random base64url
1076
+ // - signed_nonce: ECDSA signature over the nonce
1077
+ // - key_hash: sha256(spki(publicKey))
1078
+ // - certificate_chain: 4 PEM certificates concatenated (leaf + 2 intermediates + root)
1079
+ //
1080
+ // NOTE: This is *not* a real hardware-backed attestation chain, but it mirrors
1081
+ // the structure of the official app very closely so the server sees the same
1082
+ // shape: a single attestation object with a 4‑certificate chain.
1083
+ const challengeNonce = crypto.randomBytes(24).toString('base64url');
1084
+ const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
1085
+ namedCurve: 'prime256v1',
1086
+ });
1087
+ // Sign the challenge nonce with the private key (simulating TEE signing).
1088
+ const signedData = crypto.sign(null, Buffer.from(challengeNonce), privateKey);
1089
+ const signedNonce = signedData.toString('base64');
1090
+ const publicKeyDer = publicKey.export({ type: 'spki', format: 'der' });
1091
+ const keyHash = crypto.createHash('sha256').update(publicKeyDer).digest('hex');
1092
+ // Build a 4‑certificate chain (leaf + 2 intermediates + root), just like
1093
+ // what we saw in the captured traffic from the real Instagram app.
1094
+ const leafCertPem = AccountRepository._generateSelfSignedCert(privateKey, publicKey, 'Android Keystore Key');
1095
+ const intermediate1Pem = AccountRepository._generateSelfSignedCert(privateKey, publicKey, 'Android Keystore Key Attestation');
1096
+ const intermediate2Pem = AccountRepository._generateSelfSignedCert(privateKey, publicKey, 'Android Hardware Keystore');
1097
+ const rootCertPem = AccountRepository._generateSelfSignedCert(privateKey, publicKey, 'Android Keystore Root');
1098
+ const certificateChain = [
1099
+ leafCertPem,
1100
+ intermediate1Pem,
1101
+ intermediate2Pem,
1102
+ rootCertPem,
1103
+ ].join('\n');
1104
+ return {
1105
+ attestation: [
1106
+ {
1107
+ version: 2,
1108
+ type: 'keystore',
1109
+ errors: [0],
1110
+ challenge_nonce: challengeNonce,
1111
+ signed_nonce: signedNonce,
1112
+ key_hash: keyHash,
1113
+ certificate_chain: certificateChain,
1114
+ },
1115
+ ],
1116
+ };
1117
+ }
1118
+ static _generateSelfSignedCert(privateKey, publicKey, cn) {
1119
+ const publicKeyDer = publicKey.export({ type: 'spki', format: 'der' });
1120
+ const serialNumber = crypto.randomBytes(8);
1121
+ const now = new Date();
1122
+ const notBefore = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);
1123
+ const notAfter = new Date(now.getTime() + 10 * 365 * 24 * 60 * 60 * 1000);
1124
+ const cnBytes = Buffer.from(cn, 'utf8');
1125
+ const cnSeq = Buffer.concat([
1126
+ Buffer.from([0x30, cnBytes.length + 13]),
1127
+ Buffer.from([0x31, cnBytes.length + 11]),
1128
+ Buffer.from([0x30, cnBytes.length + 9]),
1129
+ Buffer.from([0x06, 0x03, 0x55, 0x04, 0x03]),
1130
+ Buffer.from([0x0c, cnBytes.length]),
1131
+ cnBytes,
1132
+ ]);
1133
+ function encodeTime(date) {
1134
+ const str = date.toISOString().replace(/[-:T]/g, '').slice(2, 14) + 'Z';
1135
+ return Buffer.concat([Buffer.from([0x17, str.length]), Buffer.from(str)]);
1136
+ }
1137
+ const validityBuf = Buffer.concat([
1138
+ encodeTime(notBefore),
1139
+ encodeTime(notAfter),
1140
+ ]);
1141
+ const validity = Buffer.concat([Buffer.from([0x30, validityBuf.length]), validityBuf]);
1142
+ const tbs = Buffer.concat([
1143
+ Buffer.from([0xa0, 0x03, 0x02, 0x01, 0x02]),
1144
+ Buffer.from([0x02, serialNumber.length]), serialNumber,
1145
+ Buffer.from([0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02]),
1146
+ cnSeq,
1147
+ validity,
1148
+ cnSeq,
1149
+ publicKeyDer,
1150
+ ]);
1151
+ const tbsSeq = Buffer.concat([Buffer.from([0x30, 0x82]), Buffer.alloc(2), tbs]);
1152
+ tbsSeq.writeUInt16BE(tbs.length, 2);
1153
+ const signature = crypto.sign(null, tbsSeq, privateKey);
1154
+ const sigBitString = Buffer.concat([
1155
+ Buffer.from([0x03, signature.length + 1, 0x00]),
1156
+ signature,
1157
+ ]);
1158
+ const algId = Buffer.from([0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02]);
1159
+ const certBody = Buffer.concat([tbsSeq, algId, sigBitString]);
1160
+ const cert = Buffer.concat([Buffer.from([0x30, 0x82]), Buffer.alloc(2), certBody]);
1161
+ cert.writeUInt16BE(certBody.length, 2);
1162
+ const b64 = cert.toString('base64');
1163
+ const lines = b64.match(/.{1,76}/g) || [b64];
1164
+ return '-----BEGIN CERTIFICATE-----\n' + lines.join('\n') + '\n-----END CERTIFICATE-----';
1165
+ }
1166
+ static createJazoest(input) {
1167
+ const buf = Buffer.from(input || '', 'ascii');
1168
+ let sum = 0;
1169
+ for (let i = 0; i < buf.byteLength; i++) {
1170
+ sum += buf.readUInt8(i);
1171
+ }
1172
+ return `2${sum}`;
1173
+ }
1174
+ encryptPassword(password) {
1175
+ if (!this.client.state.passwordEncryptionPubKey) {
1176
+ return { time: Math.floor(Date.now() / 1000).toString(), encrypted: password };
1177
+ }
1178
+ const randKey = crypto.randomBytes(32);
1179
+ const iv = crypto.randomBytes(12);
1180
+ const rsaEncrypted = crypto.publicEncrypt({
1181
+ key: Buffer.from(this.client.state.passwordEncryptionPubKey, 'base64').toString(),
1182
+ padding: crypto.constants.RSA_PKCS1_PADDING,
1183
+ }, randKey);
1184
+ const cipher = crypto.createCipheriv('aes-256-gcm', randKey, iv);
1185
+ const time = Math.floor(Date.now() / 1000).toString();
1186
+ cipher.setAAD(Buffer.from(time));
1187
+ const aesEncrypted = Buffer.concat([cipher.update(password, 'utf8'), cipher.final()]);
1188
+ const sizeBuffer = Buffer.alloc(2, 0);
1189
+ sizeBuffer.writeInt16LE(rsaEncrypted.byteLength, 0);
1190
+ const authTag = cipher.getAuthTag();
1191
+ return {
1192
+ time,
1193
+ encrypted: Buffer.concat([
1194
+ Buffer.from([1, this.client.state.passwordEncryptionKeyId || 0]),
1195
+ iv,
1196
+ sizeBuffer,
1197
+ rsaEncrypted,
1198
+ authTag,
1199
+ aesEncrypted
1200
+ ]).toString('base64')
1201
+ };
1202
+ }
1203
+ async passwordPublicKeys() {
1204
+ const response = await this.client.request.send({
1205
+ method: 'GET',
1206
+ url: '/api/v1/qe/sync/',
1207
+ });
1208
+ const headers = response.headers || {};
1209
+ const keyId = parseInt(headers['ig-set-password-encryption-key-id'] || '0');
1210
+ const pubKey = headers['ig-set-password-encryption-pub-key'] || '';
1211
+ return { keyId, pubKey };
1212
+ }
1213
+ async setPresenceDisabled(disabled = true) {
1214
+ return this.requestWithRetry(async () => {
1215
+ const response = await this.client.request.send({
1216
+ method: 'POST',
1217
+ url: '/api/v1/accounts/set_presence_disabled/',
1218
+ form: this.client.request.sign({
1219
+ _uuid: this.client.state.uuid,
1220
+ disabled: disabled ? '1' : '0',
1221
+ }),
1222
+ });
1223
+ return response.body;
1224
+ });
1225
+ }
1226
+ async getCommentFilter() {
1227
+ return this.requestWithRetry(async () => {
1228
+ const response = await this.client.request.send({
1229
+ method: 'GET',
1230
+ url: '/api/v1/accounts/get_comment_filter/',
1231
+ });
1232
+ return response.body;
1233
+ });
1234
+ }
1235
+ async setCommentFilter(configValue = 0) {
1236
+ return this.requestWithRetry(async () => {
1237
+ const response = await this.client.request.send({
1238
+ method: 'POST',
1239
+ url: '/api/v1/accounts/set_comment_filter/',
1240
+ form: this.client.request.sign({
1241
+ _uuid: this.client.state.uuid,
1242
+ config_value: String(configValue),
1243
+ }),
1244
+ });
1245
+ return response.body;
1246
+ });
1247
+ }
1248
+ async pushPreferences(preferences = 'default') {
1249
+ return this.requestWithRetry(async () => {
1250
+ const response = await this.client.request.send({
1251
+ method: 'POST',
1252
+ url: '/api/v1/push/register/',
1253
+ form: this.client.request.sign({
1254
+ _uuid: this.client.state.uuid,
1255
+ device_type: 'android_mqtt',
1256
+ is_main_push_channel: 'true',
1257
+ phone_id: this.client.state.phoneId,
1258
+ device_token: '',
1259
+ guid: this.client.state.uuid,
1260
+ users: preferences,
1261
+ }),
1262
+ });
1263
+ return response.body;
1264
+ });
1265
+ }
1266
+ }
1267
+ module.exports = AccountRepository;