proxy302-sdk 0.0.0-stage → 0.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.
@@ -0,0 +1,100 @@
1
+ import { type RequestOptions, type TransportOptions } from './http.js';
2
+ import type { Account, Area, Balance, BuyStaticOptions, CreateDynamicOptions, DynamicProxy, GetDynamicOptions, Isp, Prices, Protocol, Proxy, ProxyPage, Renewal, RenewOptions, RotateResult, StaticPurchase, Traffic, Usage } from './types.js';
3
+ export interface Proxy302Options extends TransportOptions {
4
+ /** Our entry domain -> your domain (CNAME to ours). Only the host name changes; port, username and password stay. */
5
+ entryDomains?: Record<string, string> | undefined;
6
+ }
7
+ type Kind = 'dynamic' | 'static';
8
+ type Billing = 'traffic' | 'ip';
9
+ export declare function proxyUrl(protocol: Protocol, username: string, password: string, host: string, port: number): string;
10
+ /** A new key for one order. Save it before you place the order. */
11
+ export declare function newIdempotencyKey(prefix?: string): string;
12
+ export declare class Proxy302 {
13
+ private readonly http;
14
+ private readonly domains;
15
+ constructor(options: Proxy302Options);
16
+ /** Any open API call with your key. Only GET is repeated after a network failure. */
17
+ request<T = unknown>(method: 'GET' | 'POST' | 'PUT', path: string, options?: RequestOptions): Promise<T>;
18
+ getAccount(): Promise<Account>;
19
+ getBalance(): Promise<Balance>;
20
+ listCountries(name?: string): Promise<Area[]>;
21
+ listStates(country: string | number, name?: string): Promise<Area[]>;
22
+ listCities(stateId: number, name?: string): Promise<Area[]>;
23
+ /** ISPs the premium line can target in a country. */
24
+ listIsps(country: string | number): Promise<Isp[]>;
25
+ /** Prices for this account. */
26
+ getPrices(): Promise<Prices>;
27
+ /**
28
+ * Creates a dynamic proxy (free; traffic is billed when used). For one proxy per end user, pass a key made from your
29
+ * user id: the same key returns that user's proxy until it is deleted (then a new one is created); with other
30
+ * parameters it is refused with idempotency_conflict.
31
+ */
32
+ createDynamicProxy(options: CreateDynamicOptions): Promise<DynamicProxy>;
33
+ /**
34
+ * A ready connection for a place: reuses a proxy of this account of the same line, place and protocol, or creates one.
35
+ * Do not use it to give each of your users an own proxy; use createDynamicProxy for that.
36
+ */
37
+ getDynamicProxy(options: GetDynamicOptions): Promise<DynamicProxy>;
38
+ /** New IP for sticky dynamic proxies (1-100). Free. */
39
+ rotateIp(tokenIds: number | readonly number[]): Promise<RotateResult>;
40
+ /** Buys one static IP and charges the wallet. Never repeated automatically; repeat it yourself with the same idempotencyKey. */
41
+ buyStaticIp(options: BuyStaticOptions): Promise<StaticPurchase>;
42
+ /** Renews a static IP and charges the wallet. Never repeated automatically. */
43
+ renewStaticIp(tokenId: number, options: RenewOptions): Promise<Renewal>;
44
+ /** Turns auto-renewal of a static IP on or off. The API only toggles, so the current state is read first. */
45
+ setAutoRenew(tokenId: number, enabled: boolean): Promise<{
46
+ tokenId: number;
47
+ autoRenew: boolean;
48
+ changed: boolean;
49
+ }>;
50
+ listProxies(options?: {
51
+ kind?: Kind | undefined;
52
+ billing?: Billing | undefined;
53
+ activeOnly?: boolean | undefined;
54
+ page?: number | undefined;
55
+ pageSize?: number | undefined;
56
+ cursor?: string | undefined;
57
+ username?: string | undefined;
58
+ }): Promise<ProxyPage>;
59
+ /** One of my proxies by id. Pass username (without session part) when you know it: far fewer rows to read. */
60
+ getProxy(tokenId: number, options?: {
61
+ kind?: Kind | undefined;
62
+ username?: string | undefined;
63
+ }): Promise<Proxy>;
64
+ /** Remaining prepaid traffic. */
65
+ getTraffic(): Promise<Traffic>;
66
+ /** Traffic used by the account, by day. Pass days (default 7), or startTime and endTime in Unix seconds; at most 31 days. */
67
+ getUsage(options?: {
68
+ days?: number | undefined;
69
+ startTime?: number | undefined;
70
+ endTime?: number | undefined;
71
+ }): Promise<Usage>;
72
+ /** Total traffic one proxy has used. */
73
+ getProxyUsage(tokenId: number, options?: {
74
+ username?: string | undefined;
75
+ }): Promise<{
76
+ tokenId: number;
77
+ usedBytes: number;
78
+ }>;
79
+ private get;
80
+ private bad;
81
+ private id;
82
+ private key;
83
+ private areas;
84
+ private isps;
85
+ private resolveArea;
86
+ private resolvePlace;
87
+ /** "-country-xx" would widen a state, city or ISP proxy to the country: those rotate by session_mode at creation. */
88
+ private needsOwnCredential;
89
+ private generate;
90
+ /** Username parameters: -country-<cc> without a session = new IP per connection; -session-<id> keeps one IP. */
91
+ private withSession;
92
+ private connection;
93
+ private rename;
94
+ private created;
95
+ private toProxy;
96
+ private iterateProxies;
97
+ private staticRow;
98
+ private choosePlan;
99
+ }
100
+ export {};
@@ -0,0 +1,448 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { Proxy302Error } from './errors.js';
3
+ import { Transport } from './http.js';
4
+ const DAY = 86400;
5
+ const PAGE_SIZE = 200;
6
+ const MAX_PAGES = 500;
7
+ const num = (v) => { const n = Number(v ?? 0); return Number.isFinite(n) ? n : 0; };
8
+ const str = (v) => (v === undefined || v === null ? '' : String(v));
9
+ const bool = (v) => v === true || v === 1 || v === '1' || v === 'true';
10
+ const protocolOf = (v) => (/^sock/i.test(str(v)) ? 'socks5' : 'http'); // rows say "socket" for SOCKS5
11
+ const newSessionId = () => randomBytes(6).toString('hex');
12
+ const sameArea = (area, label) => area.split(' - ').map(part => part.trim().toLowerCase()).filter(part => part && part !== '-').join(' - ') === label.toLowerCase();
13
+ /** s 1/2 = premium line, 3/4 = budget line. */
14
+ function lineOf(s) {
15
+ const n = Number(s);
16
+ return n === 1 || n === 2 ? 'premium' : n === 3 || n === 4 ? 'budget' : null;
17
+ }
18
+ export function proxyUrl(protocol, username, password, host, port) {
19
+ return `${protocol}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${port}`;
20
+ }
21
+ /** A new key for one order. Save it before you place the order. */
22
+ export function newIdempotencyKey(prefix = 'sdk') {
23
+ return `${prefix}-${randomBytes(12).toString('hex')}`;
24
+ }
25
+ export class Proxy302 {
26
+ http;
27
+ domains = new Map();
28
+ constructor(options) {
29
+ this.http = new Transport(options);
30
+ const host = /^(?=.{1,253}$)[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
31
+ for (const [from, to] of Object.entries(options.entryDomains ?? {})) {
32
+ if (!host.test(from) || !host.test(to))
33
+ throw this.bad(`entryDomains: "${from}" -> "${to}" must be host names without protocol or port`);
34
+ this.domains.set(from.toLowerCase(), to);
35
+ }
36
+ }
37
+ /** Any open API call with your key. Only GET is repeated after a network failure. */
38
+ request(method, path, options = {}) {
39
+ return this.http.request(method, path, options);
40
+ }
41
+ // ---------- account, places, prices ----------
42
+ async getAccount() {
43
+ const r = await this.get('user/users/me');
44
+ return { uid: str(r.uid), name: str(r.name), email: str(r.email), active: num(r.is_use) === 1 };
45
+ }
46
+ async getBalance() {
47
+ const r = await this.get('user/users/wallet');
48
+ return { balancePtc: num(r.balance), currency: str(r.currency) || 'PTC' };
49
+ }
50
+ listCountries(name) { return this.areas('country', undefined, name); }
51
+ async listStates(country, name) {
52
+ const c = await this.resolveArea('country', country);
53
+ return this.areas('state', c.id, name);
54
+ }
55
+ listCities(stateId, name) { return this.areas('city', this.id(stateId, 'stateId'), name); }
56
+ /** ISPs the premium line can target in a country. */
57
+ async listIsps(country) {
58
+ const c = await this.resolveArea('country', country);
59
+ return this.isps(c.id);
60
+ }
61
+ /** Prices for this account. */
62
+ async getPrices() {
63
+ const p = await this.get('proxy/prices');
64
+ const plans = (rows) => (rows ?? []).map(r => ({ paywayId: num(r.payway_id), days: num(r.days), pricePtc: num(r.price_ptc), name: str(r.name) }));
65
+ return {
66
+ usdPerPtc: num(p.usd_per_ptc ?? 1),
67
+ dynamic: {
68
+ payAsYouGo: (p.dynamic?.pay_as_you_go ?? []).map(r => ({ line: str(r.line), perGbPtc: num(r.per_gb_ptc) })),
69
+ packages: (p.dynamic?.packages ?? []).map(r => ({ line: str(r.line), gb: num(r.gb), perGbPtc: num(r.per_gb_ptc), totalPtc: num(r.total_ptc) })),
70
+ },
71
+ static: { residential: plans(p.static?.residential), datacenter: plans(p.static?.data_center) },
72
+ };
73
+ }
74
+ // ---------- dynamic proxies ----------
75
+ /**
76
+ * Creates a dynamic proxy (free; traffic is billed when used). For one proxy per end user, pass a key made from your
77
+ * user id: the same key returns that user's proxy until it is deleted (then a new one is created); with other
78
+ * parameters it is refused with idempotency_conflict.
79
+ */
80
+ async createDynamicProxy(options) {
81
+ const place = await this.resolvePlace(options);
82
+ const key = this.key(options.idempotencyKey, 'dyn', 100);
83
+ // The plain key also for the wallet: the same key with another billing is then refused instead of making a second proxy.
84
+ return this.generate(options, place, key, options.billing === 'wallet' ? key : undefined);
85
+ }
86
+ /**
87
+ * A ready connection for a place: reuses a proxy of this account of the same line, place and protocol, or creates one.
88
+ * Do not use it to give each of your users an own proxy; use createDynamicProxy for that.
89
+ */
90
+ async getDynamicProxy(options) {
91
+ const place = await this.resolvePlace(options);
92
+ const protocol = options.protocol ?? 'http';
93
+ // ISP proxies, and rotating ones below country level, are found again by their idempotency key.
94
+ if (!this.needsOwnCredential(options, place)) {
95
+ for await (const proxy of this.iterateProxies('dynamic', 'traffic')) {
96
+ if (!proxy.active || proxy.line !== place.line || proxy.protocol !== protocol || !proxy.connection || !sameArea(proxy.area, place.label))
97
+ continue;
98
+ return {
99
+ tokenId: proxy.tokenId, reused: true, billedFrom: null, area: place.label, line: place.line, session: options.session ?? 'sticky',
100
+ idempotencyKey: null, connection: await this.withSession(proxy.connection, options, place),
101
+ };
102
+ }
103
+ }
104
+ if (options.createIfMissing === false)
105
+ throw this.http.error('not_found', { detail: `${protocol} ${place.line} ${place.label}` });
106
+ const rotating = this.needsOwnCredential(options, place) && options.session === 'rotating' ? '-rotating' : '';
107
+ const key = `sdk-${place.country.id}-${place.state?.id ?? 0}-${place.city?.id ?? 0}-${protocol}-${place.line}${place.isp ? `-${place.isp.key}` : ''}${rotating}`;
108
+ return this.generate(options, place, key);
109
+ }
110
+ /** New IP for sticky dynamic proxies (1-100). Free. */
111
+ async rotateIp(tokenIds) {
112
+ const ids = [...new Set((typeof tokenIds === 'number' ? [tokenIds] : tokenIds).map(i => this.id(i, 'tokenIds')))];
113
+ if (!ids.length || ids.length > 100)
114
+ throw this.bad('tokenIds: 1-100 ids');
115
+ const connections = [];
116
+ const wanted = new Set(ids);
117
+ for await (const proxy of this.iterateProxies('dynamic', 'traffic')) {
118
+ if (!wanted.delete(proxy.tokenId))
119
+ continue;
120
+ if (proxy.connection)
121
+ connections.push({ tokenId: proxy.tokenId, connection: this.rename(proxy.connection, `${proxy.connection.username}-session-${newSessionId()}`) });
122
+ if (!wanted.size)
123
+ break;
124
+ }
125
+ const reset = (list) => this.request('POST', 'proxy/sessions', { body: { token_ids: list }, headers: { 'x-http-method-override': 'DELETE' } });
126
+ const results = [];
127
+ let applyWithinSeconds = 0;
128
+ const add = (out) => {
129
+ applyWithinSeconds = Math.max(applyWithinSeconds, num(out.apply_within_seconds));
130
+ for (const r of out.results ?? [])
131
+ results.push({ tokenId: num(r.token_id), rotatedSessions: num(r.rotated_sessions) });
132
+ };
133
+ try {
134
+ add(await reset(ids));
135
+ }
136
+ catch (e) {
137
+ // All or nothing, and a rotating proxy has no sticky session to reset: on a refusal reset one by one.
138
+ const refused = e instanceof Proxy302Error && e.apiCode !== undefined && e.code !== 'unauthorized';
139
+ if (!refused || (ids.length === 1 && !/no sticky session/i.test(e.apiMessage ?? '')))
140
+ throw e;
141
+ for (const id of ids) {
142
+ try {
143
+ add(await reset([id]));
144
+ }
145
+ catch (each) {
146
+ if (!(each instanceof Proxy302Error))
147
+ throw each;
148
+ results.push({ tokenId: id, rotatedSessions: 0, note: each.apiMessage || each.message });
149
+ }
150
+ }
151
+ }
152
+ return { connections, results, applyWithinSeconds };
153
+ }
154
+ // ---------- static IPs ----------
155
+ /** Buys one static IP and charges the wallet. Never repeated automatically; repeat it yourself with the same idempotencyKey. */
156
+ async buyStaticIp(options) {
157
+ const idempotencyKey = this.key(options.idempotencyKey, 'buy', 128);
158
+ const datacenter = options.type === 'datacenter';
159
+ if (datacenter && options.entry)
160
+ throw this.bad('entry is for residential static IPs');
161
+ if (options.city !== undefined && options.state === undefined)
162
+ throw this.bad('city needs state');
163
+ const country = await this.resolveArea('country', options.country);
164
+ const state = options.state !== undefined ? await this.resolveArea('state', options.state, country.id) : undefined;
165
+ const city = options.city !== undefined ? await this.resolveArea('city', options.city, state.id) : undefined;
166
+ const plan = await this.choosePlan(options, datacenter);
167
+ const protocol = options.protocol ?? 'http';
168
+ const out = await this.request('POST', 'proxy/api/proxy/static/ip', {
169
+ idempotencyKey,
170
+ body: {
171
+ protocol, country_id: country.id, state_id: state?.id ?? 0, city_id: city?.id ?? 0, payway_id: plan.paywayId, is_data_center: datacenter,
172
+ ...(options.entry ? { entry: options.entry } : {}), idempotency_key: idempotencyKey,
173
+ },
174
+ });
175
+ return {
176
+ tokenId: num(out.token_id), area: [country.name, state?.name, city?.name].filter(Boolean).join(' - '), days: plan.days, pricePtc: plan.pricePtc,
177
+ idempotencyKey, connection: this.created(out, protocol, idempotencyKey),
178
+ };
179
+ }
180
+ /** Renews a static IP and charges the wallet. Never repeated automatically. */
181
+ async renewStaticIp(tokenId, options) {
182
+ const id = this.id(tokenId, 'tokenId');
183
+ const idempotencyKey = this.key(options.idempotencyKey, 'renew', 128);
184
+ // The API turns auto-renewal off when is_auto_renew is left out, so the current setting is sent unless the caller sets one.
185
+ const row = options.paywayId === undefined || options.autoRenew === undefined ? await this.staticRow(id) : undefined;
186
+ const plan = await this.choosePlan(options, options.paywayId !== undefined ? false : row.datacenter);
187
+ const autoRenew = options.autoRenew ?? row.autoRenew;
188
+ const out = await this.request('POST', `proxy/token/renew/${id}`, {
189
+ idempotencyKey,
190
+ body: { payway_id: plan.paywayId, idempotency_key: idempotencyKey, is_auto_renew: autoRenew },
191
+ });
192
+ return { tokenId: num(out.token_id ?? id), orderId: str(out.order_id), expiresAt: num(out.expires_at), days: num(out.days), replayed: bool(out.replayed), idempotencyKey };
193
+ }
194
+ /** Turns auto-renewal of a static IP on or off. The API only toggles, so the current state is read first. */
195
+ async setAutoRenew(tokenId, enabled) {
196
+ const id = this.id(tokenId, 'tokenId');
197
+ if (typeof enabled !== 'boolean')
198
+ throw this.bad('enabled must be true or false');
199
+ if ((await this.staticRow(id)).autoRenew === enabled)
200
+ return { tokenId: id, autoRenew: enabled, changed: false };
201
+ const out = await this.request('PUT', `proxy/token/renew/${id}`);
202
+ if (bool(out.is_auto_renew) !== enabled)
203
+ throw this.http.error('state_conflict');
204
+ return { tokenId: id, autoRenew: enabled, changed: true };
205
+ }
206
+ // ---------- my proxies ----------
207
+ async listProxies(options = {}) {
208
+ const kind = options.kind ?? 'static';
209
+ const billing = options.billing ?? (kind === 'dynamic' ? 'traffic' : 'ip');
210
+ const query = { page: options.cursor ? undefined : options.page ?? 1, page_size: options.pageSize ?? 20, cursor: options.cursor };
211
+ // The active state is 5 for traffic-billed proxies and 1 for IP-billed ones.
212
+ if (options.activeOnly ?? true)
213
+ query.status = billing === 'traffic' ? 5 : 1;
214
+ if (options.username) {
215
+ query.text = options.username;
216
+ query.filter_type = 'username';
217
+ }
218
+ const r = await this.get(`proxy/tokens/${kind}/${billing}`, query);
219
+ return {
220
+ total: num(r.total), page: num(r.page), hasMore: bool(r.has_more), nextCursor: str(r.next_cursor) || null,
221
+ proxies: (r.data ?? []).map(row => this.toProxy(row, kind, billing)),
222
+ };
223
+ }
224
+ /** One of my proxies by id. Pass username (without session part) when you know it: far fewer rows to read. */
225
+ async getProxy(tokenId, options = {}) {
226
+ const id = this.id(tokenId, 'tokenId');
227
+ const lists = [['dynamic', 'traffic'], ['static', 'ip'], ['static', 'traffic']];
228
+ for (const [kind, billing] of lists) {
229
+ if (options.kind && options.kind !== kind)
230
+ continue;
231
+ for await (const proxy of this.iterateProxies(kind, billing, options.username))
232
+ if (proxy.tokenId === id)
233
+ return proxy;
234
+ }
235
+ throw this.http.error('not_found', { detail: `proxy ${id}` });
236
+ }
237
+ // ---------- traffic ----------
238
+ /** Remaining prepaid traffic. */
239
+ async getTraffic() {
240
+ const r = await this.get('proxy/traffic/pool/remaining');
241
+ return {
242
+ remainingBytes: num(r.remaining_traffic),
243
+ pools: (r.traffic_pools ?? []).map(p => ({
244
+ id: p.id, name: str(p.en_name ?? p.name), usedBytes: num(p.current_cost_traffic), totalBytes: num(p.total_traffic), expiresAt: num(p.expired_on) || null,
245
+ })),
246
+ };
247
+ }
248
+ /** Traffic used by the account, by day. Pass days (default 7), or startTime and endTime in Unix seconds; at most 31 days. */
249
+ async getUsage(options = {}) {
250
+ const endTime = options.endTime ?? Math.floor(Date.now() / 1000);
251
+ const startTime = options.startTime ?? endTime - (options.days ?? 7) * DAY;
252
+ if (!Number.isInteger(startTime) || !Number.isInteger(endTime) || startTime >= endTime || endTime - startTime > 31 * DAY)
253
+ throw this.bad('usage period: 1 second to 31 days');
254
+ const r = await this.get('proxy/traffic/consume/log/summary', { start_time: startTime, end_time: endTime });
255
+ return {
256
+ startTime, endTime, days: r.keys ?? [],
257
+ totalBytes: Object.fromEntries(Object.entries(r.summary ?? {}).map(([k, v]) => [k, num(v)])),
258
+ dailyBytes: Object.fromEntries(Object.entries(r.values ?? {}).map(([k, v]) => [k, v.map(num)])),
259
+ };
260
+ }
261
+ /** Total traffic one proxy has used. */
262
+ async getProxyUsage(tokenId, options = {}) {
263
+ const proxy = await this.getProxy(tokenId, options);
264
+ return { tokenId: proxy.tokenId, usedBytes: proxy.trafficUsedBytes };
265
+ }
266
+ // ---------- internals ----------
267
+ get(path, query) { return this.http.request('GET', path, { query }); }
268
+ bad(detail) { return this.http.error('bad_argument', { detail }); }
269
+ id(value, name) {
270
+ const n = Number(value);
271
+ if (!Number.isSafeInteger(n) || n <= 0)
272
+ throw this.bad(`${name}: ${str(value)}`);
273
+ return n;
274
+ }
275
+ key(given, prefix, max) {
276
+ const key = given ?? newIdempotencyKey(`sdk-${prefix}`);
277
+ if (!/^[A-Za-z0-9_-]+$/.test(key) || key.length < 8 || key.length > max)
278
+ throw this.bad(`idempotencyKey: 8-${max} letters, digits, _ or -`);
279
+ return key;
280
+ }
281
+ async areas(type, pid, name) {
282
+ const r = await this.get(`proxy/area/${type}`, { pid, name });
283
+ return (r.data ?? []).map(a => ({
284
+ id: num(a.id), name: str(a.name), ...(a.code ? { code: str(a.code) } : {}), ...(a.pid !== undefined && a.pid !== null ? { pid: num(a.pid) } : {}),
285
+ }));
286
+ }
287
+ async isps(countryId) {
288
+ const r = await this.get('proxy/isp/catalog', { country_id: countryId });
289
+ return (r.data ?? []).map(o => ({ key: str(o.key), name: str(o.label) }));
290
+ }
291
+ async resolveArea(type, input, pid) {
292
+ const text = str(input).trim();
293
+ if (!text)
294
+ throw this.bad(type);
295
+ if (/^\d+$/.test(text)) {
296
+ // The name is needed to recognise proxies of this place.
297
+ const found = (await this.areas(type, pid)).find(a => a.id === Number(text));
298
+ if (!found)
299
+ throw this.bad(`${type} ${text}`);
300
+ return found;
301
+ }
302
+ const q = text.toLowerCase();
303
+ const code = type === 'country' && q === 'uk' ? 'gb' : q;
304
+ const rows = await this.areas(type, pid, text);
305
+ let pick = rows.filter(a => a.name.toLowerCase() === q || a.code?.toLowerCase() === code);
306
+ // The API filters on the name, so "US" finds Australia and Russia but not United States: look codes up in the full list.
307
+ if (!pick.length && /^[a-z]{2,3}$/.test(code))
308
+ pick = (await this.areas(type, pid)).filter(a => a.code?.toLowerCase() === code);
309
+ if (!pick.length && rows.length === 1)
310
+ pick = rows;
311
+ if (pick.length === 1)
312
+ return pick[0];
313
+ const options = (pick.length ? pick : rows).slice(0, 10).map(a => `${a.name} (${a.id})`).join(', ');
314
+ throw this.bad(options ? `${type} "${text}": ${options}` : `${type} "${text}"`);
315
+ }
316
+ async resolvePlace(o) {
317
+ const targeted = o.state !== undefined || o.city !== undefined || o.isp !== undefined;
318
+ const line = o.line ?? (targeted ? 'premium' : 'budget');
319
+ if (line !== 'budget' && line !== 'premium')
320
+ throw this.bad('line: budget or premium');
321
+ if (targeted && line !== 'premium')
322
+ throw this.bad('state, city and isp need line premium');
323
+ if (o.city !== undefined && o.state === undefined)
324
+ throw this.bad('city needs state');
325
+ if (o.session !== undefined && o.session !== 'sticky' && o.session !== 'rotating')
326
+ throw this.bad('session: sticky or rotating');
327
+ if (o.protocol !== undefined && o.protocol !== 'http' && o.protocol !== 'socks5')
328
+ throw this.bad('protocol: http or socks5');
329
+ if (o.billing !== undefined && !['auto', 'package', 'wallet'].includes(o.billing))
330
+ throw this.bad('billing: auto, package or wallet');
331
+ if (o.sessionMinutes !== undefined) {
332
+ if (o.session === 'rotating')
333
+ throw this.bad('sessionMinutes is for sticky sessions');
334
+ if (line !== 'budget')
335
+ throw this.bad('sessionMinutes is for line budget');
336
+ if (!Number.isInteger(o.sessionMinutes) || o.sessionMinutes < 1 || o.sessionMinutes > 120)
337
+ throw this.bad('sessionMinutes: 1-120');
338
+ }
339
+ const country = await this.resolveArea('country', o.country);
340
+ let isp;
341
+ if (o.isp !== undefined) {
342
+ const isps = await this.isps(country.id);
343
+ isp = isps.find(i => i.key === o.isp.trim().toLowerCase());
344
+ if (!isp)
345
+ throw this.bad(`isp "${o.isp}": ${isps.map(i => i.key).join(', ') || country.name}`);
346
+ }
347
+ const state = o.state !== undefined ? await this.resolveArea('state', o.state, country.id) : undefined;
348
+ const city = o.city !== undefined ? await this.resolveArea('city', o.city, state.id) : undefined;
349
+ return { country, state, city, isp, line, label: [country.name, state?.name, city?.name].filter(Boolean).join(' - ') };
350
+ }
351
+ /** "-country-xx" would widen a state, city or ISP proxy to the country: those rotate by session_mode at creation. */
352
+ needsOwnCredential(o, place) {
353
+ return !!place.isp || (o.session === 'rotating' && !!place.state);
354
+ }
355
+ async generate(o, place, key, walletKey = `${key}-payg`) {
356
+ const protocol = o.protocol ?? 'http';
357
+ const rotating = o.session === 'rotating';
358
+ const ownRotation = rotating && (!!place.isp || !!place.state);
359
+ const body = {
360
+ s: place.line === 'premium' ? 1 : 3, protocol, country_id: place.country.id, state_id: place.state?.id ?? 0, city_id: place.city?.id ?? 0,
361
+ ...(place.isp ? { isp: place.isp.key } : {}), ...(ownRotation ? { session_mode: 'rotating' } : {}),
362
+ };
363
+ const create = (idempotencyKey, extra) => this.request('POST', 'proxy/api/proxy/dynamic/traffic', { idempotencyKey: key, body: { ...body, ...extra, idempotency_key: idempotencyKey } });
364
+ const fromWallet = () => create(walletKey, { billing_mode: 'payg_wallet' });
365
+ let billedFrom = 'traffic_package';
366
+ let out;
367
+ if (o.billing === 'wallet') {
368
+ billedFrom = 'wallet';
369
+ out = await fromWallet();
370
+ }
371
+ else {
372
+ try {
373
+ out = await create(key, {});
374
+ }
375
+ catch (e) {
376
+ // Like the Proxy302 console: with no traffic package for this line the wallet pays per GB.
377
+ if (o.billing === 'package' || !(e instanceof Proxy302Error) || e.code !== 'no_traffic_package')
378
+ throw e;
379
+ billedFrom = 'wallet';
380
+ out = await fromWallet();
381
+ }
382
+ }
383
+ const plain = this.created(out, protocol, key);
384
+ return {
385
+ tokenId: num(out.token_id), reused: false, billedFrom, area: [place.label, place.isp?.name].filter(Boolean).join(' - '), line: place.line,
386
+ session: rotating ? 'rotating' : 'sticky', idempotencyKey: key, connection: ownRotation ? plain : await this.withSession(plain, o, place),
387
+ };
388
+ }
389
+ /** Username parameters: -country-<cc> without a session = new IP per connection; -session-<id> keeps one IP. */
390
+ async withSession(c, o, place) {
391
+ if (o.session !== 'rotating')
392
+ return this.rename(c, `${c.username}-session-${newSessionId()}${o.sessionMinutes ? `-sessTime-${o.sessionMinutes}` : ''}`);
393
+ const code = place.country.code ?? (await this.areas('country')).find(a => a.id === place.country.id)?.code;
394
+ if (!code || !/^[A-Za-z]{2}$/.test(code))
395
+ throw this.bad(`country code of ${place.country.name}`);
396
+ return this.rename(c, `${c.username}-country-${code.toLowerCase()}`);
397
+ }
398
+ connection(protocol, host, port, username, password) {
399
+ const mapped = this.domains.get(host.toLowerCase()) ?? host;
400
+ return { protocol, host: mapped, port, username, password, url: proxyUrl(protocol, username, password, mapped, port) };
401
+ }
402
+ rename(c, username) {
403
+ return { ...c, username, url: proxyUrl(c.protocol, username, c.password, c.host, c.port) };
404
+ }
405
+ created(raw, protocol, idempotencyKey) {
406
+ if (!raw?.host || !raw.port || !raw.username || !raw.password)
407
+ throw this.http.error('bad_response', { idempotencyKey });
408
+ return this.connection(raw.protocol ? protocolOf(raw.protocol) : protocol, str(raw.host), num(raw.port), str(raw.username), str(raw.password));
409
+ }
410
+ toProxy(row, kind, billing) {
411
+ const protocol = protocolOf(row.network);
412
+ const status = num(row.status);
413
+ return {
414
+ tokenId: num(row.token_id ?? row.id), kind, billing, area: str(row.proxy_area), ip: str(row.ip_addr), line: kind === 'dynamic' ? lineOf(row.s) : null,
415
+ datacenter: bool(row.is_data_center) || /data ?center/i.test(str(row.proxy_type)), status, active: status === 1 || status === 5,
416
+ expiresAt: num(row.expired_on) || null, autoRenew: bool(row.is_auto_renew), trafficUsedBytes: num(row.traffic_usage), remark: str(row.remark), protocol,
417
+ connection: row.username && row.passwd && row.host && row.port ? this.connection(protocol, str(row.host), num(row.port), str(row.username), str(row.passwd)) : null,
418
+ };
419
+ }
420
+ async *iterateProxies(kind, billing, username) {
421
+ let cursor;
422
+ for (let page = 1; page <= MAX_PAGES; page += 1) {
423
+ const r = await this.listProxies({ kind, billing, activeOnly: false, page, pageSize: PAGE_SIZE, cursor, username });
424
+ yield* r.proxies;
425
+ if (!r.hasMore || !r.proxies.length)
426
+ return;
427
+ cursor = r.nextCursor ?? undefined;
428
+ }
429
+ }
430
+ async staticRow(id) {
431
+ for await (const proxy of this.iterateProxies('static', 'ip'))
432
+ if (proxy.tokenId === id)
433
+ return proxy;
434
+ throw this.http.error('not_found', { detail: `static IP ${id}` });
435
+ }
436
+ async choosePlan(o, datacenter) {
437
+ if (o.paywayId !== undefined)
438
+ return { paywayId: this.id(o.paywayId, 'paywayId'), days: null, pricePtc: null };
439
+ if (o.days === undefined)
440
+ throw this.bad('days or paywayId');
441
+ const prices = await this.getPrices();
442
+ const plans = datacenter ? prices.static.datacenter : prices.static.residential;
443
+ const plan = plans.filter(p => p.days === o.days && p.paywayId > 0).sort((a, b) => a.pricePtc - b.pricePtc)[0];
444
+ if (!plan)
445
+ throw this.bad(`days ${o.days}: ${[...new Set(plans.map(p => p.days))].join(', ')}`);
446
+ return plan;
447
+ }
448
+ }
@@ -0,0 +1,27 @@
1
+ /** Errors carry a stable code and one plain-language next step. */
2
+ export type Lang = 'zh' | 'en';
3
+ export type ErrorCode = 'no_key' | 'invalid_key' | 'bad_argument' | 'unauthorized' | 'account_not_linked' | 'not_found' | 'invalid_request' | 'conflict' | 'rate_limited' | 'insufficient_balance' | 'no_traffic_package' | 'ip_unavailable' | 'not_ready' | 'idempotency_conflict' | 'feature_unavailable' | 'service_unavailable' | 'state_conflict' | 'network' | 'timeout' | 'bad_response' | 'api_error';
4
+ export interface ErrorInfo {
5
+ detail?: string | undefined;
6
+ apiCode?: number | undefined;
7
+ apiMessage?: string | undefined;
8
+ httpStatus?: number | undefined;
9
+ idempotencyKey?: string | undefined;
10
+ lang?: Lang | undefined;
11
+ }
12
+ export declare class Proxy302Error extends Error {
13
+ readonly code: ErrorCode;
14
+ /** One sentence for the user: what to do next. */
15
+ readonly nextStep: string;
16
+ /** Envelope code and text of the API, for logs. */
17
+ readonly apiCode: number | undefined;
18
+ readonly apiMessage: string | undefined;
19
+ readonly httpStatus: number | undefined;
20
+ /** Set on purchases and renewals: call again with it and the order is not placed twice. */
21
+ readonly idempotencyKey: string | undefined;
22
+ constructor(code: ErrorCode, info?: ErrorInfo);
23
+ /** True when the same call can succeed later (purchases: with the same idempotencyKey). */
24
+ get retryable(): boolean;
25
+ }
26
+ /** Maps an API envelope (code, msg) to an error code. Business refusals share one envelope code, so the text decides. */
27
+ export declare function classify(apiCode: number | undefined, msg: string): ErrorCode;