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.
- package/LICENSE +21 -0
- package/README.md +65 -2
- package/dist/cjs/client.d.ts +100 -0
- package/dist/cjs/client.js +454 -0
- package/dist/cjs/errors.d.ts +27 -0
- package/dist/cjs/errors.js +118 -0
- package/dist/cjs/http.d.ts +45 -0
- package/dist/cjs/http.js +131 -0
- package/dist/cjs/index.d.ts +5 -0
- package/dist/cjs/index.js +26 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/types.d.ts +195 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/version.d.ts +1 -0
- package/dist/cjs/version.js +4 -0
- package/dist/esm/client.d.ts +100 -0
- package/dist/esm/client.js +448 -0
- package/dist/esm/errors.d.ts +27 -0
- package/dist/esm/errors.js +113 -0
- package/dist/esm/http.d.ts +45 -0
- package/dist/esm/http.js +126 -0
- package/dist/esm/index.d.ts +5 -0
- package/dist/esm/index.js +4 -0
- package/dist/esm/types.d.ts +195 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/version.d.ts +1 -0
- package/dist/esm/version.js +1 -0
- package/package.json +32 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Proxy302
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,66 @@
|
|
|
1
|
-
#
|
|
1
|
+
# proxy302-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Official [Proxy302](https://proxy302.com) SDK for Node.js: add residential proxies to your own product. For Node.js 18+, your backend, and the Electron main process. No dependencies, ESM and CommonJS, types included.
|
|
4
|
+
|
|
5
|
+
The API key is your wallet: keep it on your server. Never ship it in a client, a web page or an Electron renderer.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install proxy302-sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
import { Proxy302 } from 'proxy302-sdk';
|
|
13
|
+
|
|
14
|
+
const sdk = new Proxy302({ apiKey: process.env.PROXY302_API_KEY, lang: 'en' }); // "<key id>:<secret>"
|
|
15
|
+
|
|
16
|
+
console.log(await sdk.getBalance());
|
|
17
|
+
const proxy = await sdk.getDynamicProxy({ country: 'US' });
|
|
18
|
+
console.log(proxy.connection.url); // http://user:pass@host:port
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Methods
|
|
22
|
+
|
|
23
|
+
| Method | What it does |
|
|
24
|
+
| --- | --- |
|
|
25
|
+
| `getAccount()`, `getBalance()` | Account and wallet (PTC, 1 PTC = US$1) |
|
|
26
|
+
| `listCountries(name?)`, `listStates(country)`, `listCities(stateId)`, `listIsps(country)` | Places you can choose |
|
|
27
|
+
| `getPrices()` | Prices for this account: per GB, traffic packages, static IP plans |
|
|
28
|
+
| `getDynamicProxy({ country, ... })` | A ready connection: reuses a matching proxy of the account, or creates one |
|
|
29
|
+
| `createDynamicProxy({ country, idempotencyKey, ... })` | One proxy per end user: the same key returns the same proxy until it is deleted |
|
|
30
|
+
| `rotateIp(tokenIds)` | New IP for sticky dynamic proxies |
|
|
31
|
+
| `buyStaticIp({ country, days, ... })` | Buys one static IP (charges the wallet) |
|
|
32
|
+
| `renewStaticIp(tokenId, { days, ... })`, `setAutoRenew(tokenId, on)` | Renewal (charges the wallet), auto-renewal on or off |
|
|
33
|
+
| `listProxies({ kind, ... })`, `getProxy(tokenId)` | My proxies |
|
|
34
|
+
| `getTraffic()`, `getUsage({ days })`, `getProxyUsage(tokenId)` | Remaining traffic, usage per day, usage of one proxy |
|
|
35
|
+
| `request(method, path, { query, body })` | Any other open API call |
|
|
36
|
+
|
|
37
|
+
Dynamic options: `state`, `city`, `isp` (premium line), `line` (`budget`, `premium`), `protocol` (`http`, `socks5`), `session` (`sticky`, `rotating`), `sessionMinutes` (budget line), `billing` (`auto`, `package`, `wallet`).
|
|
38
|
+
|
|
39
|
+
## Orders are never placed twice
|
|
40
|
+
|
|
41
|
+
Purchases and renewals take an `idempotencyKey` (generated when left out; returned with the result and on the error). Queries are repeated after a network failure; purchases and renewals never are. If one ends without an answer, call again with the same key: you are not charged twice.
|
|
42
|
+
|
|
43
|
+
```js
|
|
44
|
+
import { newIdempotencyKey } from 'proxy302-sdk';
|
|
45
|
+
|
|
46
|
+
const idempotencyKey = newIdempotencyKey('order'); // save it with your order first
|
|
47
|
+
const ip = await sdk.buyStaticIp({ country: 'US', days: 30, idempotencyKey });
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Errors
|
|
51
|
+
|
|
52
|
+
Every failure is a `Proxy302Error` with `code` (for example `insufficient_balance`), `message`, `nextStep` (one sentence for the user), `retryable`, and for logs `apiCode` and `apiMessage`. Messages are Chinese by default; pass `lang: 'en'` for English.
|
|
53
|
+
|
|
54
|
+
## Your own domain
|
|
55
|
+
|
|
56
|
+
Point a CNAME at our entry domain, then connection strings carry your domain. Only the host name changes.
|
|
57
|
+
|
|
58
|
+
```js
|
|
59
|
+
new Proxy302({ apiKey, entryDomains: { 'proxy.proxy302.com': 'ip.your-domain.com' } });
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Not in this version
|
|
63
|
+
|
|
64
|
+
Top-ups, UI components, calls from a web page, sub-accounts, revenue accounting, read-only keys, and a traffic cap per proxy (not supported in this version).
|
|
65
|
+
|
|
66
|
+
MIT
|
|
@@ -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,454 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Proxy302 = void 0;
|
|
4
|
+
exports.proxyUrl = proxyUrl;
|
|
5
|
+
exports.newIdempotencyKey = newIdempotencyKey;
|
|
6
|
+
const node_crypto_1 = require("node:crypto");
|
|
7
|
+
const errors_js_1 = require("./errors.js");
|
|
8
|
+
const http_js_1 = require("./http.js");
|
|
9
|
+
const DAY = 86400;
|
|
10
|
+
const PAGE_SIZE = 200;
|
|
11
|
+
const MAX_PAGES = 500;
|
|
12
|
+
const num = (v) => { const n = Number(v ?? 0); return Number.isFinite(n) ? n : 0; };
|
|
13
|
+
const str = (v) => (v === undefined || v === null ? '' : String(v));
|
|
14
|
+
const bool = (v) => v === true || v === 1 || v === '1' || v === 'true';
|
|
15
|
+
const protocolOf = (v) => (/^sock/i.test(str(v)) ? 'socks5' : 'http'); // rows say "socket" for SOCKS5
|
|
16
|
+
const newSessionId = () => (0, node_crypto_1.randomBytes)(6).toString('hex');
|
|
17
|
+
const sameArea = (area, label) => area.split(' - ').map(part => part.trim().toLowerCase()).filter(part => part && part !== '-').join(' - ') === label.toLowerCase();
|
|
18
|
+
/** s 1/2 = premium line, 3/4 = budget line. */
|
|
19
|
+
function lineOf(s) {
|
|
20
|
+
const n = Number(s);
|
|
21
|
+
return n === 1 || n === 2 ? 'premium' : n === 3 || n === 4 ? 'budget' : null;
|
|
22
|
+
}
|
|
23
|
+
function proxyUrl(protocol, username, password, host, port) {
|
|
24
|
+
return `${protocol}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${port}`;
|
|
25
|
+
}
|
|
26
|
+
/** A new key for one order. Save it before you place the order. */
|
|
27
|
+
function newIdempotencyKey(prefix = 'sdk') {
|
|
28
|
+
return `${prefix}-${(0, node_crypto_1.randomBytes)(12).toString('hex')}`;
|
|
29
|
+
}
|
|
30
|
+
class Proxy302 {
|
|
31
|
+
http;
|
|
32
|
+
domains = new Map();
|
|
33
|
+
constructor(options) {
|
|
34
|
+
this.http = new http_js_1.Transport(options);
|
|
35
|
+
const host = /^(?=.{1,253}$)[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
|
|
36
|
+
for (const [from, to] of Object.entries(options.entryDomains ?? {})) {
|
|
37
|
+
if (!host.test(from) || !host.test(to))
|
|
38
|
+
throw this.bad(`entryDomains: "${from}" -> "${to}" must be host names without protocol or port`);
|
|
39
|
+
this.domains.set(from.toLowerCase(), to);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** Any open API call with your key. Only GET is repeated after a network failure. */
|
|
43
|
+
request(method, path, options = {}) {
|
|
44
|
+
return this.http.request(method, path, options);
|
|
45
|
+
}
|
|
46
|
+
// ---------- account, places, prices ----------
|
|
47
|
+
async getAccount() {
|
|
48
|
+
const r = await this.get('user/users/me');
|
|
49
|
+
return { uid: str(r.uid), name: str(r.name), email: str(r.email), active: num(r.is_use) === 1 };
|
|
50
|
+
}
|
|
51
|
+
async getBalance() {
|
|
52
|
+
const r = await this.get('user/users/wallet');
|
|
53
|
+
return { balancePtc: num(r.balance), currency: str(r.currency) || 'PTC' };
|
|
54
|
+
}
|
|
55
|
+
listCountries(name) { return this.areas('country', undefined, name); }
|
|
56
|
+
async listStates(country, name) {
|
|
57
|
+
const c = await this.resolveArea('country', country);
|
|
58
|
+
return this.areas('state', c.id, name);
|
|
59
|
+
}
|
|
60
|
+
listCities(stateId, name) { return this.areas('city', this.id(stateId, 'stateId'), name); }
|
|
61
|
+
/** ISPs the premium line can target in a country. */
|
|
62
|
+
async listIsps(country) {
|
|
63
|
+
const c = await this.resolveArea('country', country);
|
|
64
|
+
return this.isps(c.id);
|
|
65
|
+
}
|
|
66
|
+
/** Prices for this account. */
|
|
67
|
+
async getPrices() {
|
|
68
|
+
const p = await this.get('proxy/prices');
|
|
69
|
+
const plans = (rows) => (rows ?? []).map(r => ({ paywayId: num(r.payway_id), days: num(r.days), pricePtc: num(r.price_ptc), name: str(r.name) }));
|
|
70
|
+
return {
|
|
71
|
+
usdPerPtc: num(p.usd_per_ptc ?? 1),
|
|
72
|
+
dynamic: {
|
|
73
|
+
payAsYouGo: (p.dynamic?.pay_as_you_go ?? []).map(r => ({ line: str(r.line), perGbPtc: num(r.per_gb_ptc) })),
|
|
74
|
+
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) })),
|
|
75
|
+
},
|
|
76
|
+
static: { residential: plans(p.static?.residential), datacenter: plans(p.static?.data_center) },
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
// ---------- dynamic proxies ----------
|
|
80
|
+
/**
|
|
81
|
+
* Creates a dynamic proxy (free; traffic is billed when used). For one proxy per end user, pass a key made from your
|
|
82
|
+
* user id: the same key returns that user's proxy until it is deleted (then a new one is created); with other
|
|
83
|
+
* parameters it is refused with idempotency_conflict.
|
|
84
|
+
*/
|
|
85
|
+
async createDynamicProxy(options) {
|
|
86
|
+
const place = await this.resolvePlace(options);
|
|
87
|
+
const key = this.key(options.idempotencyKey, 'dyn', 100);
|
|
88
|
+
// The plain key also for the wallet: the same key with another billing is then refused instead of making a second proxy.
|
|
89
|
+
return this.generate(options, place, key, options.billing === 'wallet' ? key : undefined);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* A ready connection for a place: reuses a proxy of this account of the same line, place and protocol, or creates one.
|
|
93
|
+
* Do not use it to give each of your users an own proxy; use createDynamicProxy for that.
|
|
94
|
+
*/
|
|
95
|
+
async getDynamicProxy(options) {
|
|
96
|
+
const place = await this.resolvePlace(options);
|
|
97
|
+
const protocol = options.protocol ?? 'http';
|
|
98
|
+
// ISP proxies, and rotating ones below country level, are found again by their idempotency key.
|
|
99
|
+
if (!this.needsOwnCredential(options, place)) {
|
|
100
|
+
for await (const proxy of this.iterateProxies('dynamic', 'traffic')) {
|
|
101
|
+
if (!proxy.active || proxy.line !== place.line || proxy.protocol !== protocol || !proxy.connection || !sameArea(proxy.area, place.label))
|
|
102
|
+
continue;
|
|
103
|
+
return {
|
|
104
|
+
tokenId: proxy.tokenId, reused: true, billedFrom: null, area: place.label, line: place.line, session: options.session ?? 'sticky',
|
|
105
|
+
idempotencyKey: null, connection: await this.withSession(proxy.connection, options, place),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (options.createIfMissing === false)
|
|
110
|
+
throw this.http.error('not_found', { detail: `${protocol} ${place.line} ${place.label}` });
|
|
111
|
+
const rotating = this.needsOwnCredential(options, place) && options.session === 'rotating' ? '-rotating' : '';
|
|
112
|
+
const key = `sdk-${place.country.id}-${place.state?.id ?? 0}-${place.city?.id ?? 0}-${protocol}-${place.line}${place.isp ? `-${place.isp.key}` : ''}${rotating}`;
|
|
113
|
+
return this.generate(options, place, key);
|
|
114
|
+
}
|
|
115
|
+
/** New IP for sticky dynamic proxies (1-100). Free. */
|
|
116
|
+
async rotateIp(tokenIds) {
|
|
117
|
+
const ids = [...new Set((typeof tokenIds === 'number' ? [tokenIds] : tokenIds).map(i => this.id(i, 'tokenIds')))];
|
|
118
|
+
if (!ids.length || ids.length > 100)
|
|
119
|
+
throw this.bad('tokenIds: 1-100 ids');
|
|
120
|
+
const connections = [];
|
|
121
|
+
const wanted = new Set(ids);
|
|
122
|
+
for await (const proxy of this.iterateProxies('dynamic', 'traffic')) {
|
|
123
|
+
if (!wanted.delete(proxy.tokenId))
|
|
124
|
+
continue;
|
|
125
|
+
if (proxy.connection)
|
|
126
|
+
connections.push({ tokenId: proxy.tokenId, connection: this.rename(proxy.connection, `${proxy.connection.username}-session-${newSessionId()}`) });
|
|
127
|
+
if (!wanted.size)
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
const reset = (list) => this.request('POST', 'proxy/sessions', { body: { token_ids: list }, headers: { 'x-http-method-override': 'DELETE' } });
|
|
131
|
+
const results = [];
|
|
132
|
+
let applyWithinSeconds = 0;
|
|
133
|
+
const add = (out) => {
|
|
134
|
+
applyWithinSeconds = Math.max(applyWithinSeconds, num(out.apply_within_seconds));
|
|
135
|
+
for (const r of out.results ?? [])
|
|
136
|
+
results.push({ tokenId: num(r.token_id), rotatedSessions: num(r.rotated_sessions) });
|
|
137
|
+
};
|
|
138
|
+
try {
|
|
139
|
+
add(await reset(ids));
|
|
140
|
+
}
|
|
141
|
+
catch (e) {
|
|
142
|
+
// All or nothing, and a rotating proxy has no sticky session to reset: on a refusal reset one by one.
|
|
143
|
+
const refused = e instanceof errors_js_1.Proxy302Error && e.apiCode !== undefined && e.code !== 'unauthorized';
|
|
144
|
+
if (!refused || (ids.length === 1 && !/no sticky session/i.test(e.apiMessage ?? '')))
|
|
145
|
+
throw e;
|
|
146
|
+
for (const id of ids) {
|
|
147
|
+
try {
|
|
148
|
+
add(await reset([id]));
|
|
149
|
+
}
|
|
150
|
+
catch (each) {
|
|
151
|
+
if (!(each instanceof errors_js_1.Proxy302Error))
|
|
152
|
+
throw each;
|
|
153
|
+
results.push({ tokenId: id, rotatedSessions: 0, note: each.apiMessage || each.message });
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return { connections, results, applyWithinSeconds };
|
|
158
|
+
}
|
|
159
|
+
// ---------- static IPs ----------
|
|
160
|
+
/** Buys one static IP and charges the wallet. Never repeated automatically; repeat it yourself with the same idempotencyKey. */
|
|
161
|
+
async buyStaticIp(options) {
|
|
162
|
+
const idempotencyKey = this.key(options.idempotencyKey, 'buy', 128);
|
|
163
|
+
const datacenter = options.type === 'datacenter';
|
|
164
|
+
if (datacenter && options.entry)
|
|
165
|
+
throw this.bad('entry is for residential static IPs');
|
|
166
|
+
if (options.city !== undefined && options.state === undefined)
|
|
167
|
+
throw this.bad('city needs state');
|
|
168
|
+
const country = await this.resolveArea('country', options.country);
|
|
169
|
+
const state = options.state !== undefined ? await this.resolveArea('state', options.state, country.id) : undefined;
|
|
170
|
+
const city = options.city !== undefined ? await this.resolveArea('city', options.city, state.id) : undefined;
|
|
171
|
+
const plan = await this.choosePlan(options, datacenter);
|
|
172
|
+
const protocol = options.protocol ?? 'http';
|
|
173
|
+
const out = await this.request('POST', 'proxy/api/proxy/static/ip', {
|
|
174
|
+
idempotencyKey,
|
|
175
|
+
body: {
|
|
176
|
+
protocol, country_id: country.id, state_id: state?.id ?? 0, city_id: city?.id ?? 0, payway_id: plan.paywayId, is_data_center: datacenter,
|
|
177
|
+
...(options.entry ? { entry: options.entry } : {}), idempotency_key: idempotencyKey,
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
return {
|
|
181
|
+
tokenId: num(out.token_id), area: [country.name, state?.name, city?.name].filter(Boolean).join(' - '), days: plan.days, pricePtc: plan.pricePtc,
|
|
182
|
+
idempotencyKey, connection: this.created(out, protocol, idempotencyKey),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
/** Renews a static IP and charges the wallet. Never repeated automatically. */
|
|
186
|
+
async renewStaticIp(tokenId, options) {
|
|
187
|
+
const id = this.id(tokenId, 'tokenId');
|
|
188
|
+
const idempotencyKey = this.key(options.idempotencyKey, 'renew', 128);
|
|
189
|
+
// The API turns auto-renewal off when is_auto_renew is left out, so the current setting is sent unless the caller sets one.
|
|
190
|
+
const row = options.paywayId === undefined || options.autoRenew === undefined ? await this.staticRow(id) : undefined;
|
|
191
|
+
const plan = await this.choosePlan(options, options.paywayId !== undefined ? false : row.datacenter);
|
|
192
|
+
const autoRenew = options.autoRenew ?? row.autoRenew;
|
|
193
|
+
const out = await this.request('POST', `proxy/token/renew/${id}`, {
|
|
194
|
+
idempotencyKey,
|
|
195
|
+
body: { payway_id: plan.paywayId, idempotency_key: idempotencyKey, is_auto_renew: autoRenew },
|
|
196
|
+
});
|
|
197
|
+
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 };
|
|
198
|
+
}
|
|
199
|
+
/** Turns auto-renewal of a static IP on or off. The API only toggles, so the current state is read first. */
|
|
200
|
+
async setAutoRenew(tokenId, enabled) {
|
|
201
|
+
const id = this.id(tokenId, 'tokenId');
|
|
202
|
+
if (typeof enabled !== 'boolean')
|
|
203
|
+
throw this.bad('enabled must be true or false');
|
|
204
|
+
if ((await this.staticRow(id)).autoRenew === enabled)
|
|
205
|
+
return { tokenId: id, autoRenew: enabled, changed: false };
|
|
206
|
+
const out = await this.request('PUT', `proxy/token/renew/${id}`);
|
|
207
|
+
if (bool(out.is_auto_renew) !== enabled)
|
|
208
|
+
throw this.http.error('state_conflict');
|
|
209
|
+
return { tokenId: id, autoRenew: enabled, changed: true };
|
|
210
|
+
}
|
|
211
|
+
// ---------- my proxies ----------
|
|
212
|
+
async listProxies(options = {}) {
|
|
213
|
+
const kind = options.kind ?? 'static';
|
|
214
|
+
const billing = options.billing ?? (kind === 'dynamic' ? 'traffic' : 'ip');
|
|
215
|
+
const query = { page: options.cursor ? undefined : options.page ?? 1, page_size: options.pageSize ?? 20, cursor: options.cursor };
|
|
216
|
+
// The active state is 5 for traffic-billed proxies and 1 for IP-billed ones.
|
|
217
|
+
if (options.activeOnly ?? true)
|
|
218
|
+
query.status = billing === 'traffic' ? 5 : 1;
|
|
219
|
+
if (options.username) {
|
|
220
|
+
query.text = options.username;
|
|
221
|
+
query.filter_type = 'username';
|
|
222
|
+
}
|
|
223
|
+
const r = await this.get(`proxy/tokens/${kind}/${billing}`, query);
|
|
224
|
+
return {
|
|
225
|
+
total: num(r.total), page: num(r.page), hasMore: bool(r.has_more), nextCursor: str(r.next_cursor) || null,
|
|
226
|
+
proxies: (r.data ?? []).map(row => this.toProxy(row, kind, billing)),
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
/** One of my proxies by id. Pass username (without session part) when you know it: far fewer rows to read. */
|
|
230
|
+
async getProxy(tokenId, options = {}) {
|
|
231
|
+
const id = this.id(tokenId, 'tokenId');
|
|
232
|
+
const lists = [['dynamic', 'traffic'], ['static', 'ip'], ['static', 'traffic']];
|
|
233
|
+
for (const [kind, billing] of lists) {
|
|
234
|
+
if (options.kind && options.kind !== kind)
|
|
235
|
+
continue;
|
|
236
|
+
for await (const proxy of this.iterateProxies(kind, billing, options.username))
|
|
237
|
+
if (proxy.tokenId === id)
|
|
238
|
+
return proxy;
|
|
239
|
+
}
|
|
240
|
+
throw this.http.error('not_found', { detail: `proxy ${id}` });
|
|
241
|
+
}
|
|
242
|
+
// ---------- traffic ----------
|
|
243
|
+
/** Remaining prepaid traffic. */
|
|
244
|
+
async getTraffic() {
|
|
245
|
+
const r = await this.get('proxy/traffic/pool/remaining');
|
|
246
|
+
return {
|
|
247
|
+
remainingBytes: num(r.remaining_traffic),
|
|
248
|
+
pools: (r.traffic_pools ?? []).map(p => ({
|
|
249
|
+
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,
|
|
250
|
+
})),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
/** Traffic used by the account, by day. Pass days (default 7), or startTime and endTime in Unix seconds; at most 31 days. */
|
|
254
|
+
async getUsage(options = {}) {
|
|
255
|
+
const endTime = options.endTime ?? Math.floor(Date.now() / 1000);
|
|
256
|
+
const startTime = options.startTime ?? endTime - (options.days ?? 7) * DAY;
|
|
257
|
+
if (!Number.isInteger(startTime) || !Number.isInteger(endTime) || startTime >= endTime || endTime - startTime > 31 * DAY)
|
|
258
|
+
throw this.bad('usage period: 1 second to 31 days');
|
|
259
|
+
const r = await this.get('proxy/traffic/consume/log/summary', { start_time: startTime, end_time: endTime });
|
|
260
|
+
return {
|
|
261
|
+
startTime, endTime, days: r.keys ?? [],
|
|
262
|
+
totalBytes: Object.fromEntries(Object.entries(r.summary ?? {}).map(([k, v]) => [k, num(v)])),
|
|
263
|
+
dailyBytes: Object.fromEntries(Object.entries(r.values ?? {}).map(([k, v]) => [k, v.map(num)])),
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
/** Total traffic one proxy has used. */
|
|
267
|
+
async getProxyUsage(tokenId, options = {}) {
|
|
268
|
+
const proxy = await this.getProxy(tokenId, options);
|
|
269
|
+
return { tokenId: proxy.tokenId, usedBytes: proxy.trafficUsedBytes };
|
|
270
|
+
}
|
|
271
|
+
// ---------- internals ----------
|
|
272
|
+
get(path, query) { return this.http.request('GET', path, { query }); }
|
|
273
|
+
bad(detail) { return this.http.error('bad_argument', { detail }); }
|
|
274
|
+
id(value, name) {
|
|
275
|
+
const n = Number(value);
|
|
276
|
+
if (!Number.isSafeInteger(n) || n <= 0)
|
|
277
|
+
throw this.bad(`${name}: ${str(value)}`);
|
|
278
|
+
return n;
|
|
279
|
+
}
|
|
280
|
+
key(given, prefix, max) {
|
|
281
|
+
const key = given ?? newIdempotencyKey(`sdk-${prefix}`);
|
|
282
|
+
if (!/^[A-Za-z0-9_-]+$/.test(key) || key.length < 8 || key.length > max)
|
|
283
|
+
throw this.bad(`idempotencyKey: 8-${max} letters, digits, _ or -`);
|
|
284
|
+
return key;
|
|
285
|
+
}
|
|
286
|
+
async areas(type, pid, name) {
|
|
287
|
+
const r = await this.get(`proxy/area/${type}`, { pid, name });
|
|
288
|
+
return (r.data ?? []).map(a => ({
|
|
289
|
+
id: num(a.id), name: str(a.name), ...(a.code ? { code: str(a.code) } : {}), ...(a.pid !== undefined && a.pid !== null ? { pid: num(a.pid) } : {}),
|
|
290
|
+
}));
|
|
291
|
+
}
|
|
292
|
+
async isps(countryId) {
|
|
293
|
+
const r = await this.get('proxy/isp/catalog', { country_id: countryId });
|
|
294
|
+
return (r.data ?? []).map(o => ({ key: str(o.key), name: str(o.label) }));
|
|
295
|
+
}
|
|
296
|
+
async resolveArea(type, input, pid) {
|
|
297
|
+
const text = str(input).trim();
|
|
298
|
+
if (!text)
|
|
299
|
+
throw this.bad(type);
|
|
300
|
+
if (/^\d+$/.test(text)) {
|
|
301
|
+
// The name is needed to recognise proxies of this place.
|
|
302
|
+
const found = (await this.areas(type, pid)).find(a => a.id === Number(text));
|
|
303
|
+
if (!found)
|
|
304
|
+
throw this.bad(`${type} ${text}`);
|
|
305
|
+
return found;
|
|
306
|
+
}
|
|
307
|
+
const q = text.toLowerCase();
|
|
308
|
+
const code = type === 'country' && q === 'uk' ? 'gb' : q;
|
|
309
|
+
const rows = await this.areas(type, pid, text);
|
|
310
|
+
let pick = rows.filter(a => a.name.toLowerCase() === q || a.code?.toLowerCase() === code);
|
|
311
|
+
// The API filters on the name, so "US" finds Australia and Russia but not United States: look codes up in the full list.
|
|
312
|
+
if (!pick.length && /^[a-z]{2,3}$/.test(code))
|
|
313
|
+
pick = (await this.areas(type, pid)).filter(a => a.code?.toLowerCase() === code);
|
|
314
|
+
if (!pick.length && rows.length === 1)
|
|
315
|
+
pick = rows;
|
|
316
|
+
if (pick.length === 1)
|
|
317
|
+
return pick[0];
|
|
318
|
+
const options = (pick.length ? pick : rows).slice(0, 10).map(a => `${a.name} (${a.id})`).join(', ');
|
|
319
|
+
throw this.bad(options ? `${type} "${text}": ${options}` : `${type} "${text}"`);
|
|
320
|
+
}
|
|
321
|
+
async resolvePlace(o) {
|
|
322
|
+
const targeted = o.state !== undefined || o.city !== undefined || o.isp !== undefined;
|
|
323
|
+
const line = o.line ?? (targeted ? 'premium' : 'budget');
|
|
324
|
+
if (line !== 'budget' && line !== 'premium')
|
|
325
|
+
throw this.bad('line: budget or premium');
|
|
326
|
+
if (targeted && line !== 'premium')
|
|
327
|
+
throw this.bad('state, city and isp need line premium');
|
|
328
|
+
if (o.city !== undefined && o.state === undefined)
|
|
329
|
+
throw this.bad('city needs state');
|
|
330
|
+
if (o.session !== undefined && o.session !== 'sticky' && o.session !== 'rotating')
|
|
331
|
+
throw this.bad('session: sticky or rotating');
|
|
332
|
+
if (o.protocol !== undefined && o.protocol !== 'http' && o.protocol !== 'socks5')
|
|
333
|
+
throw this.bad('protocol: http or socks5');
|
|
334
|
+
if (o.billing !== undefined && !['auto', 'package', 'wallet'].includes(o.billing))
|
|
335
|
+
throw this.bad('billing: auto, package or wallet');
|
|
336
|
+
if (o.sessionMinutes !== undefined) {
|
|
337
|
+
if (o.session === 'rotating')
|
|
338
|
+
throw this.bad('sessionMinutes is for sticky sessions');
|
|
339
|
+
if (line !== 'budget')
|
|
340
|
+
throw this.bad('sessionMinutes is for line budget');
|
|
341
|
+
if (!Number.isInteger(o.sessionMinutes) || o.sessionMinutes < 1 || o.sessionMinutes > 120)
|
|
342
|
+
throw this.bad('sessionMinutes: 1-120');
|
|
343
|
+
}
|
|
344
|
+
const country = await this.resolveArea('country', o.country);
|
|
345
|
+
let isp;
|
|
346
|
+
if (o.isp !== undefined) {
|
|
347
|
+
const isps = await this.isps(country.id);
|
|
348
|
+
isp = isps.find(i => i.key === o.isp.trim().toLowerCase());
|
|
349
|
+
if (!isp)
|
|
350
|
+
throw this.bad(`isp "${o.isp}": ${isps.map(i => i.key).join(', ') || country.name}`);
|
|
351
|
+
}
|
|
352
|
+
const state = o.state !== undefined ? await this.resolveArea('state', o.state, country.id) : undefined;
|
|
353
|
+
const city = o.city !== undefined ? await this.resolveArea('city', o.city, state.id) : undefined;
|
|
354
|
+
return { country, state, city, isp, line, label: [country.name, state?.name, city?.name].filter(Boolean).join(' - ') };
|
|
355
|
+
}
|
|
356
|
+
/** "-country-xx" would widen a state, city or ISP proxy to the country: those rotate by session_mode at creation. */
|
|
357
|
+
needsOwnCredential(o, place) {
|
|
358
|
+
return !!place.isp || (o.session === 'rotating' && !!place.state);
|
|
359
|
+
}
|
|
360
|
+
async generate(o, place, key, walletKey = `${key}-payg`) {
|
|
361
|
+
const protocol = o.protocol ?? 'http';
|
|
362
|
+
const rotating = o.session === 'rotating';
|
|
363
|
+
const ownRotation = rotating && (!!place.isp || !!place.state);
|
|
364
|
+
const body = {
|
|
365
|
+
s: place.line === 'premium' ? 1 : 3, protocol, country_id: place.country.id, state_id: place.state?.id ?? 0, city_id: place.city?.id ?? 0,
|
|
366
|
+
...(place.isp ? { isp: place.isp.key } : {}), ...(ownRotation ? { session_mode: 'rotating' } : {}),
|
|
367
|
+
};
|
|
368
|
+
const create = (idempotencyKey, extra) => this.request('POST', 'proxy/api/proxy/dynamic/traffic', { idempotencyKey: key, body: { ...body, ...extra, idempotency_key: idempotencyKey } });
|
|
369
|
+
const fromWallet = () => create(walletKey, { billing_mode: 'payg_wallet' });
|
|
370
|
+
let billedFrom = 'traffic_package';
|
|
371
|
+
let out;
|
|
372
|
+
if (o.billing === 'wallet') {
|
|
373
|
+
billedFrom = 'wallet';
|
|
374
|
+
out = await fromWallet();
|
|
375
|
+
}
|
|
376
|
+
else {
|
|
377
|
+
try {
|
|
378
|
+
out = await create(key, {});
|
|
379
|
+
}
|
|
380
|
+
catch (e) {
|
|
381
|
+
// Like the Proxy302 console: with no traffic package for this line the wallet pays per GB.
|
|
382
|
+
if (o.billing === 'package' || !(e instanceof errors_js_1.Proxy302Error) || e.code !== 'no_traffic_package')
|
|
383
|
+
throw e;
|
|
384
|
+
billedFrom = 'wallet';
|
|
385
|
+
out = await fromWallet();
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
const plain = this.created(out, protocol, key);
|
|
389
|
+
return {
|
|
390
|
+
tokenId: num(out.token_id), reused: false, billedFrom, area: [place.label, place.isp?.name].filter(Boolean).join(' - '), line: place.line,
|
|
391
|
+
session: rotating ? 'rotating' : 'sticky', idempotencyKey: key, connection: ownRotation ? plain : await this.withSession(plain, o, place),
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
/** Username parameters: -country-<cc> without a session = new IP per connection; -session-<id> keeps one IP. */
|
|
395
|
+
async withSession(c, o, place) {
|
|
396
|
+
if (o.session !== 'rotating')
|
|
397
|
+
return this.rename(c, `${c.username}-session-${newSessionId()}${o.sessionMinutes ? `-sessTime-${o.sessionMinutes}` : ''}`);
|
|
398
|
+
const code = place.country.code ?? (await this.areas('country')).find(a => a.id === place.country.id)?.code;
|
|
399
|
+
if (!code || !/^[A-Za-z]{2}$/.test(code))
|
|
400
|
+
throw this.bad(`country code of ${place.country.name}`);
|
|
401
|
+
return this.rename(c, `${c.username}-country-${code.toLowerCase()}`);
|
|
402
|
+
}
|
|
403
|
+
connection(protocol, host, port, username, password) {
|
|
404
|
+
const mapped = this.domains.get(host.toLowerCase()) ?? host;
|
|
405
|
+
return { protocol, host: mapped, port, username, password, url: proxyUrl(protocol, username, password, mapped, port) };
|
|
406
|
+
}
|
|
407
|
+
rename(c, username) {
|
|
408
|
+
return { ...c, username, url: proxyUrl(c.protocol, username, c.password, c.host, c.port) };
|
|
409
|
+
}
|
|
410
|
+
created(raw, protocol, idempotencyKey) {
|
|
411
|
+
if (!raw?.host || !raw.port || !raw.username || !raw.password)
|
|
412
|
+
throw this.http.error('bad_response', { idempotencyKey });
|
|
413
|
+
return this.connection(raw.protocol ? protocolOf(raw.protocol) : protocol, str(raw.host), num(raw.port), str(raw.username), str(raw.password));
|
|
414
|
+
}
|
|
415
|
+
toProxy(row, kind, billing) {
|
|
416
|
+
const protocol = protocolOf(row.network);
|
|
417
|
+
const status = num(row.status);
|
|
418
|
+
return {
|
|
419
|
+
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,
|
|
420
|
+
datacenter: bool(row.is_data_center) || /data ?center/i.test(str(row.proxy_type)), status, active: status === 1 || status === 5,
|
|
421
|
+
expiresAt: num(row.expired_on) || null, autoRenew: bool(row.is_auto_renew), trafficUsedBytes: num(row.traffic_usage), remark: str(row.remark), protocol,
|
|
422
|
+
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,
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
async *iterateProxies(kind, billing, username) {
|
|
426
|
+
let cursor;
|
|
427
|
+
for (let page = 1; page <= MAX_PAGES; page += 1) {
|
|
428
|
+
const r = await this.listProxies({ kind, billing, activeOnly: false, page, pageSize: PAGE_SIZE, cursor, username });
|
|
429
|
+
yield* r.proxies;
|
|
430
|
+
if (!r.hasMore || !r.proxies.length)
|
|
431
|
+
return;
|
|
432
|
+
cursor = r.nextCursor ?? undefined;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
async staticRow(id) {
|
|
436
|
+
for await (const proxy of this.iterateProxies('static', 'ip'))
|
|
437
|
+
if (proxy.tokenId === id)
|
|
438
|
+
return proxy;
|
|
439
|
+
throw this.http.error('not_found', { detail: `static IP ${id}` });
|
|
440
|
+
}
|
|
441
|
+
async choosePlan(o, datacenter) {
|
|
442
|
+
if (o.paywayId !== undefined)
|
|
443
|
+
return { paywayId: this.id(o.paywayId, 'paywayId'), days: null, pricePtc: null };
|
|
444
|
+
if (o.days === undefined)
|
|
445
|
+
throw this.bad('days or paywayId');
|
|
446
|
+
const prices = await this.getPrices();
|
|
447
|
+
const plans = datacenter ? prices.static.datacenter : prices.static.residential;
|
|
448
|
+
const plan = plans.filter(p => p.days === o.days && p.paywayId > 0).sort((a, b) => a.pricePtc - b.pricePtc)[0];
|
|
449
|
+
if (!plan)
|
|
450
|
+
throw this.bad(`days ${o.days}: ${[...new Set(plans.map(p => p.days))].join(', ')}`);
|
|
451
|
+
return plan;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
exports.Proxy302 = Proxy302;
|