diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 087b8a9..b5a7fa4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,7 +4,7 @@ on: workflow_dispatch: inputs: version: - description: Stable version matching package.json (for example 1.0.0) + description: Stable version matching package.json required: true type: string commit: diff --git a/CHANGELOG.md b/CHANGELOG.md index b9729ed..c57796a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.1.0 + +- Add account balance, product catalog and supported-country queries. +- Add read-only setup previews and single/batch proxy helpers with live defaults and dedicated-channel reuse. +- Coordinate default-channel creation within a client; reconcile uncertain creation without blind retries. +- Add the standalone `nstdata-proxy` CLI with hidden key input, explicit confirmation and private file export. +- Preserve the six existing customer API methods and their input contracts. + ## 1.0.0 - Customer proxy generation and channel list, detail, create, update and delete methods. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fd4b50b..af95ca0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,10 +15,10 @@ Build the archive after checks pass, then install it from a separate application ```sh npm pack -npm install /path/to/nstdata-proxy-sdk-node/nstdata-ai-proxy-1.0.0.tgz +npm install /path/to/nstdata-proxy-sdk-node/nstdata-ai-proxy-1.1.0.tgz ``` -Package checks use empty npm caches to verify the exact tarball and default npm installation through a loopback registry. They run installed-client regressions, compile TypeScript declarations, and execute the documented Node.js command and guide operations against loopback API fixtures. Markdown checks cover all public documents; package checks execute the quick start and guide operations. Pass a previously built tarball path after `npm run check:package --` to validate that exact archive. Checks verify bilingual programs, documentation links and package bytes; they do not prove public npm availability or deployed API compatibility. +Package checks use empty npm caches to verify the exact tarball and default npm installation through a loopback registry. They verify the standalone npx/global CLI and run installed-client/CLI regressions, compile TypeScript declarations, and execute the documented Node.js command and guide operations against loopback API fixtures. Markdown checks cover all public documents; package checks execute the quick start and guide operations. Pass a previously built tarball path after `npm run check:package --` to validate that exact archive. Checks verify bilingual programs, documentation links and package bytes; they do not prove public npm availability or deployed API compatibility. Keep customer, reseller and Dashboard authentication separate. Route/payload changes need source-backed contracts and public-client regressions. Preserve cancellation, response limits, error redaction and no-retry behavior for uncertain outcomes. Keep runtime and declarations aligned and update both language guides and the changelog. @@ -28,8 +28,6 @@ Never commit API keys, proxy credentials or account responses. Report vulnerabil The `Publish npm` workflow is started manually from `main`, with a stable version matching `package.json` and the full commit SHA. It checks the source, builds one archive, and records its integrity. The `npm-production` environment reviewer approves publication of that same archive. Successful publication must pass public integrity and default-install checks. -For an existing npm package, configure [trusted publishing](https://docs.npmjs.com/trusted-publishers/) for this repository, `release.yml` and `npm-production`, permitting `npm publish`. The environment must require a reviewer, allow only the `main` branch and disable administrator bypass. No npm token is needed. Configure a new binding near the next release so its first-use deadline is met. - -A new package must exist before trusted publishing can be configured. For its first release, the scope owner publishes the reviewed archive using their own npm login and two-factor authentication, following [npm's public scoped-package instructions](https://docs.npmjs.com/creating-and-publishing-scoped-public-packages/). Use trusted publishing for subsequent versions. The workflow refuses to bootstrap an unpublished package. +Configure [trusted publishing](https://docs.npmjs.com/trusted-publishers/) for this repository, `release.yml` and `npm-production`, permitting `npm publish`. The environment must require a reviewer, allow only the `main` branch and disable administrator bypass. No npm token is needed. Configure a new binding near the next release so its first-use deadline is met. If publication fails or the outcome is uncertain, inspect the registry version and integrity before taking further action. Do not retry publication blindly or change a published version's contents. diff --git a/README.md b/README.md index 93ed96f..6d7784a 100644 --- a/README.md +++ b/README.md @@ -2,34 +2,42 @@ [中文](README_zh.md) -Generate Nstdata proxy connections and manage customer channels. ESM with TypeScript declarations and no runtime dependencies. - -## Features - -| Capability | Guide | -|---|---| -| Proxy generation | [HTTP/SOCKS5 connection strings and session options](docs/guide.md#proxy-generation). | -| Channel reads | [Page-based lists and active-channel details](docs/guide.md#channel-reads). | -| Channel management | [Create, update and soft-delete channels](docs/guide.md#channel-management). | -| Reliability | [Deadlines, cancellation and safe errors](docs/guide.md#configuration-and-errors). | +Generate proxy connections with an API key and available account balance. Use the interactive CLI without a Node.js project, or the ESM SDK in an application. Includes TypeScript declarations; no runtime dependencies. ## Installation -Requires Node.js 22.18+ within 22.x, or Node.js 24.x. +Requires Node.js 22.18+ within 22.x, or Node.js 24.x. To use the SDK: ```sh npm install @nstdata-ai/proxy ``` -## Quick start +## Command line -Get an authorized personal or team API key from the [Nstdata dashboard](https://app.nstdata.io/); accounts using teams require a team key. Save it in a local `.env` file: +Run from any directory. Enter your API key at the hidden prompt, review the selected product and country, then press Enter to generate one connection. Choose Advanced to change the product, country or existing channel. + +```sh +npx --yes --package=@nstdata-ai/proxy nstdata-proxy +``` + +For scripts, save your authorized API key from the [Nstdata dashboard](https://app.nstdata.io/) in a local `.env` file. Use the key for the intended personal or team account: ```dotenv NSTDATA_API_TOKEN=your-api-key ``` -Save the following as `quickstart.mjs`. It reads one channel-list page and prints only its length. +Generate one connection and save it to a new private file: + +```sh +npx --yes --package=@nstdata-ai/proxy \ + nstdata-proxy --env .env --yes --output proxies.json +``` + +`--yes` before `--package` accepts npx installation; the second `--yes` authorizes channel setup and proxy generation. `proxies.json` contains a `proxies` array with complete credential-bearing URLs. It is created with mode `0600` and never overwrites an existing file. Normal terminal output contains only metadata; the API key is never saved. + +## SDK quick start + +Use the same `.env` file. Save this program as `quickstart.mjs`: ```js import { ProxyClient, ProxyAPIError } from '@nstdata-ai/proxy'; @@ -38,8 +46,9 @@ try { const client = new ProxyClient({ apiKey: process.env.NSTDATA_API_TOKEN, }); - const channels = await client.listChannels({ page: 1, pageSize: 10 }); - console.log({ channelsOnPage: channels.length }); + const proxy = await client.getProxy(); + // Pass proxy.url to your proxy-capable HTTP client; it contains credentials. + console.log({ country: proxy.country, protocol: proxy.protocol }); } catch (error) { if (!(error instanceof ProxyAPIError)) throw error; console.error({ code: error.code, statusCode: error.statusCode }); @@ -47,16 +56,23 @@ try { } ``` -Run with the `.env` file in the same directory: - ```sh node --env-file=.env quickstart.mjs ``` -Expected output: `{ channelsOnPage: number }`; an empty channel list has length `0`. Configuration or request failures print an error code and exit with a nonzero status. +The output shows the selected country and protocol. `proxy.url` is the connection to pass to a proxy-capable client. Generating a connection does not test connectivity; actual proxy traffic is metered. + +## Defaults and controls + +| Capability | Behavior | +|---|---| +| First use | Finds a compatible `nstdata-sdk-default` channel or creates one using a random password. Other channels are unchanged. | +| Selection | Uses the account catalog: Residential Lite, then Residential; HTTP, one connection, 10-minute session. Uses a fixed channel country, otherwise US if available, then a supported country. | +| Preview | `prepareProxy()` or CLI `--dry-run` shows the setup without creating a channel or generating connections. | +| Explicit control | `getProxy({ country, channelId, ... })`, `getProxies({ count, ... })`, and the existing channel methods. Unsupported explicit choices fail without fallback. | -Channel records and proxy URLs can contain passwords. Inspect only fields your application needs; do not print complete results. For inputs, results and operation effects, see the [usage guide](docs/guide.md). +An API key and balance are sufficient for the normal pay-per-use flow when the account has compatible products and access. Availability and billing remain service-controlled; the SDK does not purchase or renew packages. -This package calls customer APIs. Proxy network transport, connectivity checks and Proxy Manager are separate capabilities. +[Full guide](docs/guide.md) covers CLI options, results, channel management and recovery. [Contributing](CONTRIBUTING.md) · [Security](SECURITY.md) · [Changes](CHANGELOG.md) · [MIT license](LICENSE) diff --git a/README_zh.md b/README_zh.md index c677517..7d52ea3 100644 --- a/README_zh.md +++ b/README_zh.md @@ -1,35 +1,43 @@ -# Nstdata Node.js Proxy SDK +# Nstdata Proxy SDK for Node.js [English](README.md) -通过 Nstdata 普通用户 API 生成代理连接并管理渠道。ESM 包含 TypeScript 声明,无运行时依赖。 - -## 功能 - -| 能力 | 指南 | -|---|---| -| 代理出号 | [HTTP/SOCKS5 连接串及会话参数](docs/guide_zh.md#代理出号)。 | -| 渠道读取 | [分页列表和活跃渠道详情](docs/guide_zh.md#渠道读取)。 | -| 渠道管理 | [创建、更新和软删除](docs/guide_zh.md#渠道管理)。 | -| 可靠性 | [期限、取消和安全错误](docs/guide_zh.md#配置与错误)。 | +使用 API Key 和可用余额获取代理连接。可直接运行交互式命令行,无需创建 Node.js 项目;也可通过 ESM SDK 集成到应用。提供 TypeScript 类型,无运行时依赖。 ## 安装 -需要 Node.js 22 系列的22.18+,或 Node.js 24 系列。 +需要 Node.js 22 系列的 22.18+ 或 Node.js 24 系列。应用中使用 SDK: ```sh npm install @nstdata-ai/proxy ``` -## 快速开始 +## 命令行使用 -从 [Nstdata 控制台](https://app.nstdata.io/) 获取获准使用的个人或团队 API key;团队账号须使用团队 key。将 Key 保存到本地 `.env` 文件: +在任意目录运行。按提示输入 API Key(不回显),核对产品与国家后按 Enter 获取一条连接;选择 Advanced 可更换产品、国家或已有渠道。 + +```sh +npx --yes --package=@nstdata-ai/proxy nstdata-proxy +``` + +用于脚本时,从 [Nstdata 控制台](https://app.nstdata.io/) 获取获准使用的个人或团队 API Key,保存到本地 `.env` 文件: ```dotenv NSTDATA_API_TOKEN=your-api-key ``` -将以下程序保存为 `quickstart.mjs`。它读取一页渠道列表,只输出本页数量。 +获取一条连接并保存到新的私密文件: + +```sh +npx --yes --package=@nstdata-ai/proxy \ + nstdata-proxy --env .env --yes --output proxies.json +``` + +`--package` 前的 `--yes` 确认 npx 安装,后一个 `--yes` 确认渠道准备与出号。`proxies.json` 中的 `proxies` 数组保存含认证信息的完整连接 URL;文件权限设为 `0600`,已存在时不会覆盖。默认终端输出只含元数据,不保存 API Key。 + +## SDK 快速开始 + +使用上述 `.env` 文件,将以下程序保存为 `quickstart.mjs`: ```js import { ProxyClient, ProxyAPIError } from '@nstdata-ai/proxy'; @@ -38,8 +46,9 @@ try { const client = new ProxyClient({ apiKey: process.env.NSTDATA_API_TOKEN, }); - const channels = await client.listChannels({ page: 1, pageSize: 10 }); - console.log({ channelsOnPage: channels.length }); + const proxy = await client.getProxy(); + // Pass proxy.url to your proxy-capable HTTP client; it contains credentials. + console.log({ country: proxy.country, protocol: proxy.protocol }); } catch (error) { if (!(error instanceof ProxyAPIError)) throw error; console.error({ code: error.code, statusCode: error.statusCode }); @@ -47,16 +56,23 @@ try { } ``` -使用同一目录中的 `.env` 运行: - ```sh node --env-file=.env quickstart.mjs ``` -预期输出 `{ channelsOnPage: 数量 }`;空渠道列表的数量为 `0`。配置或请求失败时输出错误码并以非零状态退出。 +输出显示实际选择的国家和协议。将 `proxy.url` 交给支持代理的客户端使用。出号本身不测试连通性;实际代理流量按服务规则计量。 + +## 默认行为与控制 + +| 能力 | 行为 | +|---|---| +| 首次使用 | 查找兼容的 `nstdata-sdk-default` 渠道,没有时使用随机密码创建;不修改其他渠道。 | +| 自动选择 | 依据实际产品目录,优先 Residential Lite,其次 Residential;默认 HTTP、1 条、10 分钟会话。先遵守渠道固定国家,否则优先可用的 US,再选择支持的国家。 | +| 只读预览 | `prepareProxy()` 或 CLI `--dry-run` 查看方案,不创建渠道、不出号。 | +| 精确控制 | `getProxy({ country, channelId, ... })`、`getProxies({ count, ... })` 及原有渠道方法。显式指定的选择不支持时直接报错,不自动换产品或国家。 | -渠道记录和代理 URL 可能包含密码。只读取应用所需字段,不打印完整结果。各项功能的参数、返回值和操作影响见[使用指南](docs/guide_zh.md)。 +账号具备兼容产品和访问权限时,正常按量流程仅需 API Key 与余额。产品可用性和计费由服务端决定;SDK 不购买或续费套餐。 -本包调用普通用户 API。代理网络传输、连通性检测和 Proxy Manager 属于独立能力。 +[完整指南](docs/guide_zh.md) 提供命令行选项、返回字段、渠道管理与异常恢复说明。 [贡献说明](CONTRIBUTING.md) · [安全反馈](SECURITY.md) · [变更记录](CHANGELOG.md) · [MIT 许可](LICENSE) diff --git a/docs/guide.md b/docs/guide.md index ad6414c..2ca65ac 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -2,12 +2,70 @@ [中文](guide_zh.md) · [Quick start](../README.md) -## Methods +[CLI options](#command-line-options) · [Convenient setup](#convenient-proxy-setup) · [API reference](#customer-api-methods) · [Configuration and errors](#configuration-and-errors) + +## Command-line options + +`nstdata-proxy` runs through npx as shown in the [quick start](../README.md#command-line). For a persistent installation, use `npm install --global @nstdata-ai/proxy`, then run `nstdata-proxy`. Neither mode requires a Node.js project. + +| Option | Behavior | +|---|---| +| No options | Interactive setup: hidden key input, selection summary, confirmation, optional private export. | +| `--env ` | Load this environment file only. Existing environment values take precedence; no implicit `.env` search. | +| `--dry-run` | Read-only preparation; does not create a channel or generate sessions. | +| `--yes` | Authorize setup and generation without prompts. Required for noninteractive generation. | +| `--channel ` | Use only this existing channel. | +| `--type `, `--zone `, `--country ` | Require the selected type, catalog product and supported country. | +| `--protocol ` | Default `http`; SOCKS5 output is a connection string, not a SOCKS5 client. | +| `--duration `, `--count <1–1000>` | Defaults: 10 minutes and one connection. | +| `--json` | Suppress interactive prompts; stdout is one JSON result. | +| `--output ` | Save complete connections to a new JSON file with mode `0600`. Never overwrite. | +| `--show-url` | Explicitly include credential-bearing URLs in stdout; mutually exclusive with `--output`. | +| `--help`, `-h` | Show usage without a key or API requests. | + +File mode `0600` restricts access on POSIX systems; on Windows, use a directory with appropriate access controls. + +Set `NSTDATA_API_TOKEN` in the environment or an explicit env file; interactive mode can prompt for it without echoing or storing it. `NSTDATA_TEAM_ID` is optional team context. `NSTDATA_API_BASE_URL` is an advanced API origin override, not a normal setup requirement or a proxy URL. Defaults use the official API. + +Default stdout contains selection metadata and `count`; `saved: true` confirms file export. Exported JSON adds a `proxies` array. Errors go to stderr as `{ error: { code, message } }`. Exit codes: 0 success, 1 API/setup failure, 2 input/configuration assistance, 130 interruption. API configuration errors returned as `ProxyAPIError` use exit 1. + +## Convenient proxy setup + +| Method | Result and effects | +|---|---| +| `prepareProxy(input?, options?)` | Read-only `ProxyPreparation`: actual product/country, reference price, balance, channel name, `channelAction` (`create` or `reuse`), and `channelId` when known. | +| `getProxy(input?, options?)` | `ProxyConnection`: one complete `url`, selected `channelId`, `type`, `zoneName`, `country`, `protocol`, `sessionDuration`, `priceGB`, and `createdChannel`. May create an SDK default channel. | +| `getProxies(input?, options?)` | Same metadata with `proxies: string[]` instead of `url`; optional `count` (1–1000, default 1). One generation request for the whole batch. | + +Shared inputs are optional `channelId`, `type`, `zoneName`, `country`, `protocol` and `sessionDuration`. Only `getProxies` accepts `count`. `prepareProxy` does not reserve resources or prove connectivity. The generated URL contains credentials; pass it to a compatible client rather than logging it. + +### Selection rules + +1. Read the current account balance and live product catalog. Without a channel ID, use compatible pay-per-use Residential Lite products, then Residential; within each type use reference price and product name as stable tie-breakers. +2. Reuse an active compatible `nstdata-sdk-default` pay-per-use channel before creating one. Other names and package channels are not selected automatically. A caller-specified channel is checked directly and never silently replaced. +3. Honor the requested country or the channel's fixed country. Otherwise prefer US when returned by the country API, then the first supported country code in sorted order. A conflicting fixed country fails; it is not changed. +4. Default to HTTP, one connection and a 10-minute session. Omit gateway selection so the service chooses its default. Session duration is not an IP-stability or uptime guarantee. +5. If needed, create an unrestricted default channel with a cryptographically random password, then generate connections once. Do not rename, reset or delete other channels, purchase packages, or test a destination. + +Explicit products must support the selected protocol and country. ISP requires an existing usable channel; buying or renewing ISP resources is outside this helper. A selected package channel with remaining quota can be used without a positive wallet balance. The service has the final decision on entitlement and available resources. `priceGB` is a reference catalog value, not a final billing guarantee. + +### Reuse and recovery + +Preparation is cached for up to 30 seconds within a `ProxyClient`, with at most 16 selections. Reuse a client for the same account context. Concurrent calls on that client share initialization and default-channel creation, including calls for different countries; they still generate independent sessions. Cancelling one caller does not cancel other waiting callers. `createdChannel` describes shared initialization and is not a per-call creation count. + +Coordination does not span client instances, processes or machines; there is no claimed server-side uniqueness guarantee. Retain a confirmed channel ID for deployment across workers. Default-channel discovery stops after five pages of 100; incomplete or repeated pages fail without creating a channel. + +Creation and generation are never retried automatically. If a creation response is lost, the same client remembers the uncertain outcome, rereads channels on a later call and uses a confirmed matching channel. If none is found, it returns `CHANNEL_CREATION_UNCERTAIN` rather than creating again. Check the dashboard or pass a confirmed `channelId`; restarting a process is not proof that an earlier creation failed. A generation transport failure returns `PROXY_GENERATION_UNCERTAIN`; inspect the result before requesting another session. Local cancellation does not undo a remote operation. + +## Customer API methods Each method returns validated API `data`, preserving extra result fields. All routes are relative to `baseUrl + /api/v1/api`. | Method | Route | Result | |---|---|---| +| `getAccountInfo(options?)` | `GET /user/info` | `AccountInfo`, including numeric `balance` | +| `listPlans(query?, options?)` | `GET /plan/info` | `ProxyPlan[]`; optional product `type` filter | +| `listCountries({ type }, options?)` | `GET /region/country` | `ProxyCountry[]`, using the returned `value` codes | | `generateProxies(input, options?)` | `GET /proxies` | `{ proxies: string[], count: number }` | | `listChannels(query?, options?)` | `GET /channels` | One page of `Channel[]` | | `getChannel(channelId, options?)` | `GET /channel/:channelId` | Active matches as `Channel[]`; `[]` if absent | @@ -17,9 +75,11 @@ Each method returns validated API `data`, preserving extra result fields. All ro Empty lists and boolean false are valid results, not fabricated successes or exceptions. Creation uses HTTP 201 with application code 200. SDK result validation does not establish account entitlements or product availability. +The catalog returns `name`, `type`, `protocols`, reference `priceGB` and `supports`; country records include `value` and may include `label` or `regionId`. Account context comes from the API key and optional team ID. + ## Proxy generation -Use an existing channel ID and permitted region/gateway values from your Nstdata account. The snippets below replace the `listChannels` call and its output statement inside the quick start's `try` block. Run one operation at a time. Add any required `NSTDATA_CHANNEL_ID` or other settings to the same `.env` file. +Use an existing channel ID and permitted region/gateway values from your Nstdata account. The snippets below replace the `getProxy` call, its comment and output statement inside the quick start's `try` block. Run one operation at a time. Add any required `NSTDATA_CHANNEL_ID` or other settings to the same `.env` file. ```js const generated = await client.generateProxies({ @@ -43,7 +103,7 @@ Generation can create new sessions even though it uses GET. Save returned connec ## Channel reads -`listChannels` reads only the requested page. Optional inputs are `page`, `pageSize`(1–100), `type`, `regionType`(`country`/`state`/`city`), `status`(0–4), `createType`(`package`/`balance`) and search text `s`. +`listChannels` reads only the requested page. Use `page`, `pageSize` (1–100), `type`, `regionType` (`country`/`state`/`city`) and `status` (0–4) to constrain it. For exact channel names or pay-per-use selection, filter the returned rows locally; the setup helpers already do this. Legacy `s` and `createType` inputs remain forwarded for compatibility, but require endpoint support and are not used for automatic channel discovery. The service defaults to 50 items and descending creation time. No total count or next-page cursor is returned. Page lengths alone do not guarantee a stable snapshot while channels change; choose an explicit page limit when iterating. @@ -115,7 +175,13 @@ Pass `{ signal: AbortSignal }` as the final method argument. An already-aborted | `HTTP_ERROR`, `API_ERROR` | Unsuccessful HTTP status or failed API envelope. | | `INVALID_RESPONSE` | Invalid UTF-8/JSON/envelope or method result shape. | | `RESPONSE_TOO_LARGE` | Response exceeds the configured byte cap. | +| `INSUFFICIENT_BALANCE` | No usable balance or selected package quota. | +| `NO_COMPATIBLE_PLAN`, `COUNTRY_UNAVAILABLE` | The requested/default product or country cannot be resolved. | +| `CHANNEL_UNAVAILABLE`, `CHANNEL_REQUIRED` | Selected channel cannot be used, or the product requires an existing channel. | +| `CHANNEL_DISCOVERY_LIMIT` | Incomplete discovery; supply a confirmed channel ID. | +| `CHANNEL_CREATION_UNCERTAIN`, `PROXY_GENERATION_UNCERTAIN` | The remote operation may have succeeded; no automatic retry. | +| `NO_PROXY_GENERATED` | The API returned an empty proxy list. | HTTP/API failures expose `statusCode`; application errors also expose `applicationCode`. Error messages exclude raw bodies, credentials, transport details and cancellation reasons. Generation/write outcomes can be uncertain after transport failure: inspect actual state before deciding on another call. -The scope is the six customer methods above. Reseller `/api/v1/service`, Dashboard sessions, ISP purchasing/renewal and framework integrations use separate contracts. Keep keys, proxy URLs and channel records out of published examples and logs. +The scope is the customer methods and setup helpers above. Reseller `/api/v1/service`, Dashboard sessions, ISP purchasing/renewal and framework integrations use separate contracts. Keep keys, proxy URLs and channel records out of published examples and logs. diff --git a/docs/guide_zh.md b/docs/guide_zh.md index 2b6e3c5..a339e13 100644 --- a/docs/guide_zh.md +++ b/docs/guide_zh.md @@ -2,12 +2,70 @@ [English](guide.md) · [快速开始](../README_zh.md) -## 方法 +[命令行选项](#命令行选项) · [便捷出号](#便捷出号) · [API 参考](#普通用户-api-方法) · [配置与错误](#配置与错误) + +## 命令行选项 + +按[快速开始](../README_zh.md#命令行使用)通过 npx 运行 `nstdata-proxy`。需要长期使用时,可执行 `npm install --global @nstdata-ai/proxy`,再运行 `nstdata-proxy`;两种方式均无需创建 Node.js 项目。 + +| 选项 | 行为 | +|---|---| +| 不传选项 | 交互式流程:隐藏输入 Key、查看选择摘要、确认、按需私密导出。 | +| `--env ` | 只加载指定环境文件;已有环境变量优先,不自动搜索 `.env`。 | +| `--dry-run` | 只读准备,不创建渠道、不生成会话。 | +| `--yes` | 无提示确认准备与出号;非交互式出号必须明确指定。 | +| `--channel ` | 只使用此已有渠道。 | +| `--type `、`--zone `、`--country ` | 要求指定产品类型、实际产品名称和支持的国家。 | +| `--protocol ` | 默认 `http`;SOCKS5 输出仅为连接字符串,不包含 SOCKS5 客户端。 | +| `--duration `、`--count <1–1000>` | 默认 10 分钟、1 条连接。 | +| `--json` | 关闭交互提示;stdout 输出一条 JSON 结果。 | +| `--output ` | 将完整连接保存到新的 JSON 文件,权限 `0600`,不覆盖已有文件。 | +| `--show-url` | 明确允许 stdout 包含带认证信息的 URL;与 `--output` 互斥。 | +| `--help`、`-h` | 查看帮助,不需要 Key、不发 API 请求。 | + +文件模式 `0600` 在 POSIX 系统限制访问权限;Windows 应使用具有适当访问控制的目录。 + +`NSTDATA_API_TOKEN` 来自环境变量或显式指定的环境文件;交互模式可隐藏输入,不回显、不保存。`NSTDATA_TEAM_ID` 是可选团队上下文。`NSTDATA_API_BASE_URL` 仅用于高级 API 服务地址覆盖,不是常规必填参数,也不是代理 URL;默认使用官方 API。 + +默认 stdout 包含选择元数据和 `count`;`saved: true` 表示文件已保存。导出的 JSON 另含 `proxies` 数组。错误以 `{ error: { code, message } }` 写入 stderr。退出码:0 成功,1 API/准备失败,2 命令行输入需修正,130 中断;以 `ProxyAPIError` 返回的 API 配置错误使用退出码 1。 + +## 便捷出号 + +| 方法 | 结果与副作用 | +|---|---| +| `prepareProxy(input?, options?)` | 只读 `ProxyPreparation`:实际产品/国家、参考价、余额、渠道名、`channelAction`(`create` 或 `reuse`)以及已知时的 `channelId`。 | +| `getProxy(input?, options?)` | `ProxyConnection`:一条完整 `url`,以及 `channelId`、`type`、`zoneName`、`country`、`protocol`、`sessionDuration`、`priceGB`、`createdChannel`。可能创建 SDK 默认渠道。 | +| `getProxies(input?, options?)` | 同样的元数据,使用 `proxies: string[]` 替代 `url`;可传 `count`(1–1000,默认 1),整批只发一次出号请求。 | + +共同可选输入为 `channelId`、`type`、`zoneName`、`country`、`protocol`、`sessionDuration`;仅 `getProxies` 接受 `count`。`prepareProxy` 不预留资源,也不证明连通性。返回 URL 含认证信息,应交给兼容的客户端使用,不要直接打印。 + +### 选择规则 + +1. 读取当前账号余额与实际产品目录。未指定渠道时,按量产品优先 Residential Lite,其次 Residential;同类型按参考价、产品名称稳定排序。 +2. 优先复用活跃且兼容的 `nstdata-sdk-default` 按量渠道,没有时才创建。不自动选取其他名称或套餐渠道;显式指定的渠道单独核对,不会被悄悄替换。 +3. 遵守指定国家或渠道固定国家;否则优先地区接口返回的 US,再按代码排序选取支持的国家。与渠道固定国家冲突时失败,不修改原渠道。 +4. 默认 HTTP、1 条、10 分钟会话;不指定网关,由服务端选择默认值。会话时长不代表 IP 固定或在线时长保证。 +5. 需要时使用密码学随机密码创建不限国家的默认渠道,再执行一次出号。不改名、重置或删除其他渠道,不购买套餐,不访问检测目标。 + +显式选择的产品须支持所选协议和国家。ISP 必须提供已有可用渠道,便捷方法不购买或续费 ISP 资源。指定仍有配额的套餐渠道时,无需钱包余额为正;实际权限和可用资源由服务端最终判定。`priceGB` 是产品目录参考值,不是最终账单保证。 + +### 复用与恢复 + +同一 `ProxyClient` 内准备结果最多缓存 30 秒、16 组选项;同一账号上下文应复用客户端。并发调用共享初始化和默认渠道创建,包括不同国家的调用;出号仍分别执行。取消一个调用不会中断其他等待者。`createdChannel` 描述共享初始化是否创建过渠道,不是每次调用的创建计数。 + +协调不跨客户端实例、进程或机器,也不承诺服务端渠道唯一性。多 worker 部署可保存已确认的渠道 ID。默认渠道最多搜索 5 页、每页 100 条;分页不完整或重复时停止,不据此创建渠道。 + +创建和出号均不自动重试。创建响应丢失后,同一客户端记录未知结果;后续调用先只读查找并复用已确认的匹配渠道,找不到则返回 `CHANNEL_CREATION_UNCERTAIN`,不再次创建。应查看控制台或传入已确认的 `channelId`;重启进程不证明上一次创建失败。出号传输失败返回 `PROXY_GENERATION_UNCERTAIN`,再次请求会话前须核对结果。取消本地等待不会撤销远端操作。 + +## 普通用户 API 方法 各方法返回 API 响应中已校验的 `data`,保留额外结果字段。下列路由相对于 `baseUrl + /api/v1/api`。 | 方法 | 路由 | 结果 | |---|---|---| +| `getAccountInfo(options?)` | `GET /user/info` | `AccountInfo`,包含数值 `balance` | +| `listPlans(query?, options?)` | `GET /plan/info` | `ProxyPlan[]`,可按产品 `type` 过滤 | +| `listCountries({ type }, options?)` | `GET /region/country` | `ProxyCountry[]`,以返回的 `value` 作为地区值 | | `generateProxies(input, options?)` | `GET /proxies` | `{ proxies: string[], count: number }` | | `listChannels(query?, options?)` | `GET /channels` | 单页 `Channel[]` | | `getChannel(channelId, options?)` | `GET /channel/:channelId` | 活跃渠道 `Channel[]`,不存在为 `[]` | @@ -17,9 +75,11 @@ 空列表和布尔值 false 都是有效结果,不伪造成成功或异常。创建使用 HTTP 201、业务 code 200。结果结构校验不证明账号权限或产品可用性。 +产品目录返回 `name`、`type`、`protocols`、参考 `priceGB` 和 `supports`;地区记录包含 `value`,并可能包含 `label`、`regionId`。API Key 和可选团队 ID 决定账号上下文。 + ## 代理出号 -使用现有渠道 ID,以及账号支持的地区/网关值。以下片段替换快速开始 `try` 块中的 `listChannels` 调用及其输出语句,每次只执行一项操作;需要的 `NSTDATA_CHANNEL_ID` 等变量添加到同一 `.env` 文件。 +使用现有渠道 ID,以及账号支持的地区/网关值。以下片段替换快速开始 `try` 块中的 `getProxy` 调用、紧接的注释与输出语句,每次只执行一项操作;需要的 `NSTDATA_CHANNEL_ID` 等变量添加到同一 `.env` 文件。 ```js const generated = await client.generateProxies({ @@ -43,7 +103,7 @@ console.log({ count: generated.count }); ## 渠道读取 -`listChannels` 只读取指定页。可选输入为 `page`、`pageSize`(1–100)、`type`、`regionType`(`country`/`state`/`city`)、`status`(0–4)、`createType`(`package`/`balance`)和搜索文本 `s`。 +`listChannels` 只读取指定页。使用 `page`、`pageSize`(1–100)、`type`、`regionType`(`country`/`state`/`city`)和 `status`(0–4)限定列表。精确名称和按量渠道在返回行中本地筛选,便捷入口已包含此逻辑。为保持兼容,仍转发已有 `s`、`createType` 输入,但需要接口支持,不用于自动渠道发现。 服务默认每页50条、按创建时间倒序,不返回总数或下一游标。渠道变更时,页长度不能保证读取到一致快照;自行遍历时须设置明确页数上限。 @@ -115,7 +175,13 @@ console.log({ deleted }); | `HTTP_ERROR`、`API_ERROR` | HTTP 状态失败或 API 外层业务错误。 | | `INVALID_RESPONSE` | UTF-8/JSON/外层包装或方法结果结构不合法。 | | `RESPONSE_TOO_LARGE` | 响应超出配置字节上限。 | +| `INSUFFICIENT_BALANCE` | 无可用余额或指定渠道配额。 | +| `NO_COMPATIBLE_PLAN`、`COUNTRY_UNAVAILABLE` | 无法确定符合要求的产品或国家。 | +| `CHANNEL_UNAVAILABLE`、`CHANNEL_REQUIRED` | 指定渠道不可用,或该产品需要已有渠道。 | +| `CHANNEL_DISCOVERY_LIMIT` | 渠道发现不完整,应指定已确认的渠道 ID。 | +| `CHANNEL_CREATION_UNCERTAIN`、`PROXY_GENERATION_UNCERTAIN` | 远端操作可能已成功,未自动重试。 | +| `NO_PROXY_GENERATED` | API 返回空代理列表。 | HTTP/业务失败提供 `statusCode`,业务错误另提供 `applicationCode`。错误文字不包含原始正文、凭据、传输详情或取消原因。传输失败后的出号/写入结果可能未知,应核对实际状态,再决定是否重新调用。 -本包范围为上述六个普通用户方法。分销 `/api/v1/service`、Dashboard 会话、ISP 购买续费和框架集成使用独立契约。公开示例和日志不记录 Key、代理连接或完整渠道记录。 +本包范围为上述普通用户方法和便捷入口。分销 `/api/v1/service`、Dashboard 会话、ISP 购买续费和框架集成使用独立契约。公开示例和日志不记录 Key、代理连接或完整渠道记录。 diff --git a/package-lock.json b/package-lock.json index f014df4..d73b102 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@nstdata-ai/proxy", - "version": "1.0.0", + "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@nstdata-ai/proxy", - "version": "1.0.0", + "version": "1.1.0", "engines": { "node": "^22.18.0 || ^24.0.0" }, @@ -15,6 +15,9 @@ "@types/node": "22.18.0", "typescript": "5.9.3", "marked": "18.1.1" + }, + "bin": { + "nstdata-proxy": "src/cli.js" } }, "node_modules/@types/node": { diff --git a/package.json b/package.json index 48ea7b9..6b026db 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@nstdata-ai/proxy", - "version": "1.0.0", + "version": "1.1.0", "description": "Node.js client for Nstdata proxy generation and customer channel APIs", "type": "module", "exports": { @@ -40,5 +40,8 @@ "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org" + }, + "bin": { + "nstdata-proxy": "src/cli.js" } } diff --git a/scripts/check-documentation.mjs b/scripts/check-documentation.mjs index 0a18335..c1e051b 100644 --- a/scripts/check-documentation.mjs +++ b/scripts/check-documentation.mjs @@ -4,13 +4,14 @@ import { createHash } from 'node:crypto'; import { once } from 'node:events'; import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import http from 'node:http'; -import { join } from 'node:path'; +import { join, dirname } from 'node:path'; import { promisify } from 'node:util'; import { codeBlocks, shellCommands } from './documentation.mjs'; const execute = promisify(execFile); -const listOperation = ' const channels = await client.listChannels({ page: 1, pageSize: 10 });\n' + - ' console.log({ channelsOnPage: channels.length });'; +const setupOperation = ' const proxy = await client.getProxy();\n' + + ' // Pass proxy.url to your proxy-capable HTTP client; it contains credentials.\n' + + ' console.log({ country: proxy.country, protocol: proxy.protocol });'; export async function checkDocumentedCommands({ root, temp, archive, manifest, files, environment }) { const registryRequests = []; @@ -40,6 +41,24 @@ export async function checkDocumentedCommands({ root, temp, archive, manifest, f requests.push({ method: request.method, path: url.pathname, query: Object.fromEntries(url.searchParams), body: Buffer.concat(body).toString() }); assert.equal(request.headers['x-api-key'], 'fixture-api-key'); + if (operation === 'setup') { + if (mode === 'http') { response.writeHead(503); response.end('fixture-private-body'); return; } + if (mode === 'api') { response.end(JSON.stringify({ code: 403, err: true, data: null })); return; } + assert.equal(request.method, 'GET'); + let data; + if (url.pathname.endsWith('/user/info')) data = { balance: 20 }; + else if (url.pathname.endsWith('/plan/info')) data = [{ name: 'sample-zone', + type: 'residential_lite', priceGB: 2, protocols: ['http'], supports: ['country'] }]; + else if (url.pathname.endsWith('/region/country')) data = [{ value: 'US' }]; + else if (url.pathname.endsWith('/channels')) data = [{ channelId: 'sample-channel', + name: 'nstdata-sdk-default', type: 'residential_lite', zoneName: 'sample-zone', status: 1 }]; + else if (url.pathname.endsWith('/proxies')) { + const count = Number(url.searchParams.get('count')); + data = mode === 'empty' ? { proxies: [], count: 0 } : { + proxies: Array.from({ length: count }, () => 'http://fixture:private-password@gateway.invalid:8000'), count }; + } else assert.fail('Unexpected setup route'); + response.end(JSON.stringify({ code: 200, err: false, data })); return; + } const expected = { list: ['GET', '/api/v1/api/channels'], generate: ['GET', '/api/v1/api/proxies'], get: ['GET', '/api/v1/api/channel/sample-channel'], create: ['POST', '/api/v1/api/channel'], @@ -89,7 +108,11 @@ export async function checkDocumentedCommands({ root, temp, archive, manifest, f const readme = readFileSync(join(root, language === 'en' ? 'README.md' : 'README_zh.md'), 'utf8'); const originalCommands = shellCommands(readme); assert.deepEqual(originalCommands, [ - ['npm', 'install', manifest.name], ['node', '--env-file=.env', 'quickstart.mjs'], + ['npm', 'install', manifest.name], + ['npx', '--yes', '--package=' + manifest.name, 'nstdata-proxy'], + ['npx', '--yes', '--package=' + manifest.name, 'nstdata-proxy', '--env', '.env', + '--yes', '--output', 'proxies.json'], + ['node', '--env-file=.env', 'quickstart.mjs'], ]); await execute(process.execPath, [process.env.npm_execpath, ...originalCommands[0].slice(1)], { cwd: application, env: localEnv, timeout: 30000, @@ -104,7 +127,7 @@ export async function checkDocumentedCommands({ root, temp, archive, manifest, f assert.equal(programBlocks.length, 1); assert.equal(settings.length, 1); assert.equal(settings[0].text, 'NSTDATA_API_TOKEN=your-api-key'); const program = programBlocks[0].text; - assert.ok(program.includes(listOperation)); + assert.ok(program.includes(setupOperation)); writeFileSync(join(application, 'quickstart.mjs'), program); // Exercise the default API origin without adding test configuration to the examples. const networkFixture = join(application, 'api-fixture.cjs'); @@ -121,15 +144,17 @@ globalThis.fetch = (input, options) => { }; const run = async (nextOperation, nextMode, filename, expected, errorCode) => { operation = nextOperation; mode = nextMode; - const values = { - NSTDATA_API_TOKEN: 'fixture-api-key', - NSTDATA_CHANNEL_ID: 'sample-channel', NSTDATA_CHANNEL_PASSWORD: 'FixturePass9', - NSTDATA_ZONE_NAME: 'sample-zone', - }; + const values = { NSTDATA_API_TOKEN: 'fixture-api-key' }; + if (['generate', 'get', 'update', 'delete'].includes(nextOperation)) + values.NSTDATA_CHANNEL_ID = 'sample-channel'; + if (['create', 'update'].includes(nextOperation)) values.NSTDATA_CHANNEL_PASSWORD = 'FixturePass9'; + if (nextOperation === 'create') values.NSTDATA_ZONE_NAME = 'sample-zone'; if (mode === 'no-key') delete values.NSTDATA_API_TOKEN; if (mode === 'no-channel') delete values.NSTDATA_CHANNEL_ID; if (mode === 'no-password') delete values.NSTDATA_CHANNEL_PASSWORD; if (mode === 'no-zone') delete values.NSTDATA_ZONE_NAME; + if (nextOperation === 'setup') assert.deepEqual(Object.keys(values), + mode === 'no-key' ? [] : ['NSTDATA_API_TOKEN'], 'Quick start must receive only its documented key'); const dotenv = settings[0].text.replace('your-api-key', values.NSTDATA_API_TOKEN ?? ''); const extra = Object.entries(values).filter(([key]) => key !== 'NSTDATA_API_TOKEN') .map(([key, value]) => `${key}=${value}`).join('\n'); @@ -137,7 +162,7 @@ globalThis.fetch = (input, options) => { const before = requests.length; let result, exitCode = 0; try { - const args = originalCommands[1].slice(1) + const args = originalCommands[3].slice(1) .map(value => value === 'quickstart.mjs' ? filename : value); result = await execute(process.execPath, args, { cwd: application, env: programEnv, timeout: 10000, @@ -145,7 +170,8 @@ globalThis.fetch = (input, options) => { } catch (error) { result = error; exitCode = error.code; } assert.equal(exitCode, errorCode ? 1 : 0, result.stderr); const noRequest = mode.startsWith('no-'); - assert.equal(requests.length - before, noRequest ? 0 : 1); + const expectedRequests = nextOperation === 'setup' && ['normal', 'empty'].includes(nextMode) ? 5 : 1; + assert.equal(requests.length - before, noRequest ? 0 : expectedRequests); assert.doesNotMatch(result.stdout + result.stderr, /fixture-api-key|FixturePass9|private-password|fixture-private-body|sample-channel/); if (errorCode) { @@ -156,10 +182,42 @@ globalThis.fetch = (input, options) => { scenarios++; commands++; }; for (const [variant, expected, errorCode] of [ - ['normal', '{ channelsOnPage: 1 }'], ['empty', '{ channelsOnPage: 0 }'], + ['normal', "{ country: 'US', protocol: 'http' }"], ['empty', '', 'NO_PROXY_GENERATED'], ['api', '', 'API_ERROR'], ['http', '', 'HTTP_ERROR'], ['no-key', '', 'INVALID_CONFIG'], - ]) await run('list', variant, 'quickstart.mjs', expected, errorCode); + ]) await run('setup', variant, 'quickstart.mjs', expected, errorCode); nativePrograms++; + operation = 'setup'; mode = 'normal'; + writeFileSync(join(application, '.env'), 'NSTDATA_API_TOKEN=fixture-api-key\n', { mode: 0o600 }); + // Execute the documented npx commands from a directory with no package.json or node_modules. + const standalone = join(temp, 'standalone-' + language); mkdirSync(standalone); + writeFileSync(join(standalone, '.env'), 'NSTDATA_API_TOKEN=fixture-api-key\n', { mode: 0o600 }); + const cliEnv = { ...programEnv, NSTDATA_API_BASE_URL: 'https://api.nstdata.io', + npm_config_cache: join(standalone, 'cache'), NPM_CONFIG_CACHE: join(standalone, 'cache') }; + const beforeUnconfirmed = requests.length; + await assert.rejects(execute(process.execPath, + [join(dirname(process.env.npm_execpath), 'npx-cli.js'), ...originalCommands[1].slice(1)], { + cwd: standalone, env: cliEnv, timeout: 30000, + }), error => error.code === 2 && error.stderr.includes('MISSING_API_KEY')); + assert.equal(requests.length, beforeUnconfirmed); + const batch = await execute(process.execPath, + [join(dirname(process.env.npm_execpath), 'npx-cli.js'), ...originalCommands[2].slice(1)], { + cwd: standalone, env: cliEnv, timeout: 30000, + }); + assert.equal(JSON.parse(batch.stdout).saved, true); + assert.doesNotMatch(batch.stdout + batch.stderr, /fixture-api-key|private-password/); + const exported = JSON.parse(readFileSync(join(standalone, 'proxies.json'), 'utf8')); + assert.equal(exported.proxies.length, 1); + assert.equal(exported.proxies[0], 'http://fixture:private-password@gateway.invalid:8000'); + // A global installation must expose the same executable independently of any project. + const globalEnv = { ...cliEnv, npm_config_prefix: join(standalone, 'prefix') }; + await execute(process.execPath, [process.env.npm_execpath, 'install', '--global', manifest.name], { + cwd: standalone, env: globalEnv, timeout: 30000, + }); + const globalHelp = await execute(join(globalEnv.npm_config_prefix, 'bin', 'nstdata-proxy'), ['--help'], { + cwd: standalone, env: globalEnv, timeout: 10000, + }); + assert.match(globalHelp.stdout, /Usage: nstdata-proxy/); + commands += 4; const guide = readFileSync(join(root, 'docs', language === 'en' ? 'guide.md' : 'guide_zh.md'), 'utf8'); assert.deepEqual(shellCommands(guide), [], 'Guide fragments must not claim standalone commands'); const fragments = codeBlocks(guide).filter(block => block.lang === 'js'); @@ -179,7 +237,7 @@ globalThis.fetch = (input, options) => { for (const [index, fragment] of fragments.entries()) { const filename = 'operation-' + index + '.mjs'; const code = fragment.text.split('\n').map(line => ' ' + line).join('\n'); - writeFileSync(join(application, filename), program.replace(listOperation, code)); + writeFileSync(join(application, filename), program.replace(setupOperation, code)); const [method, cases] = variants[index]; for (const [variant, expected, errorCode] of cases) await run(method, variant, filename, expected, errorCode); guideFragments++; diff --git a/scripts/check-package.mjs b/scripts/check-package.mjs index 47bd424..b0ad9dd 100644 --- a/scripts/check-package.mjs +++ b/scripts/check-package.mjs @@ -32,6 +32,8 @@ try { assert.equal(lock.packages[''].version, manifest.version); assert.equal(lock.packages[''].name, manifest.name); assert.deepEqual(lock.packages[''].devDependencies, manifest.devDependencies); + assert.deepEqual(manifest.bin, { 'nstdata-proxy': 'src/cli.js' }); + assert.deepEqual(lock.packages[''].bin, manifest.bin); assert.deepEqual(manifest.dependencies ?? {}, {}); assert.deepEqual(manifest.peerDependencies ?? {}, {}); assert.deepEqual(lock.packages[''].dependencies ?? {}, {}); @@ -47,7 +49,8 @@ try { assert.deepEqual(shellCommands(readFileSync(join(root, file), 'utf8'))[0], ['npm', 'install', manifest.name]); } assert.ok(readFileSync(join(root, 'CHANGELOG.md'), 'utf8').split('\n').includes(`## ${manifest.version}`)); - const files = ['package.json', 'src/index.js', 'src/index.d.ts', 'README.md', 'README_zh.md', 'LICENSE', + const files = ['package.json', 'src/index.js', 'src/index.d.ts', 'src/errors.js', 'src/setup.js', 'src/cli.js', + 'README.md', 'README_zh.md', 'LICENSE', 'CHANGELOG.md', 'CONTRIBUTING.md', 'SECURITY.md', 'docs/guide.md', 'docs/guide_zh.md'].sort(); let archive; if (process.argv[2]) archive = resolve(process.argv[2]); @@ -101,8 +104,10 @@ net.Socket.prototype.connect = function (...args) { };\n`); const testEnv = { ...env, NODE_OPTIONS: `--require=${JSON.stringify(guard)}` }; mkdirSync(join(temp, 'test')); - copyFileSync(join(root, 'test/client.test.mjs'), join(temp, 'test/client.test.mjs')); - execFileSync(process.execPath, ['--test', '--test-reporter=tap', 'test/client.test.mjs'], { + for (const file of ['client.test.mjs', 'quickstart.test.mjs', 'cli.test.mjs', 'proxy-fixture.mjs']) + copyFileSync(join(root, 'test', file), join(temp, 'test', file)); + execFileSync(process.execPath, ['--test', '--test-reporter=tap', 'test/client.test.mjs', + 'test/quickstart.test.mjs', 'test/cli.test.mjs'], { cwd: temp, env: { ...testEnv, NSTDATA_PROXY_INSTALLED: '1' }, timeout: 30000, stdio: 'inherit', }); writeFileSync(join(temp, 'consumer.mts'), readFileSync(join(root, 'test/types.ts'), 'utf8').replace('../src/index.js', '@nstdata-ai/proxy')); diff --git a/src/cli.js b/src/cli.js new file mode 100755 index 0000000..3507e33 --- /dev/null +++ b/src/cli.js @@ -0,0 +1,193 @@ +#!/usr/bin/env node +import { parseArgs } from 'node:util'; +import { ProxyClient, ProxyAPIError } from './index.js'; +import { createInterface } from 'node:readline/promises'; +import { Writable } from 'node:stream'; +import { access, lstat, writeFile } from 'node:fs/promises'; +import { constants } from 'node:fs'; +import { dirname, resolve } from 'node:path'; + +const controller = new AbortController(); + +const help = `Usage: nstdata-proxy [options] + +Generate proxy connections using your Nstdata API key and available balance. +No channel ID, product name or country is required for the default setup. + +Options: + --yes Accept default setup without interactive confirmation + --dry-run Show the resolved setup without creating a channel or session + --channel Use an existing channel instead of finding or creating a default + --type Choose a product type + --zone Choose a product returned by the account catalog + --country Require a supported country (default: US, then an available country) + --protocol Connection protocol (default: http) + --duration Session duration (default: 10) + --count <1-1000> Number of connections (default: 1) + --env Load an explicit environment file + --json JSON output without interactive prompts + --show-url Include connection URLs and their credentials in output + --output Save connections to a new JSON file (mode 0600) + -h, --help Show help without contacting the API + +Environment: + NSTDATA_API_TOKEN Required API key; prompted with hidden input in interactive mode + NSTDATA_TEAM_ID Optional explicit account team context + NSTDATA_API_BASE_URL Advanced API origin override; defaults to the official API + +Examples: + nstdata-proxy + nstdata-proxy --dry-run --json + nstdata-proxy --yes --json --output proxies.json + +The default setup may create a reusable nstdata-sdk-default channel. +Generating connections does not test them or buy a package. Proxy use is metered. +Exit codes: 0 success; 1 API/setup failure; 2 invalid input; 130 interrupted.`; + +class InputError extends Error { + constructor(code, message) { super(message); this.code = code; } +} + +async function question(prompt, hidden = false) { + const output = hidden ? new Writable({ write(_chunk, _encoding, done) { done(); } }) : process.stderr; + const reader = createInterface({ input: process.stdin, output, terminal: true }); + reader.once('SIGINT', () => controller.abort()); + const closed = new Promise((_, reject) => reader.once('close', () => reject(new ProxyAPIError('ABORTED')))); + try { + const answer = reader.question('', { signal: controller.signal }); + process.stderr.write(prompt); + return (await Promise.race([answer, closed])).trim(); + } + finally { reader.close(); if (hidden) process.stderr.write('\n'); } +} + +async function choose(label, rows, display) { + if (!rows.length) throw new InputError('NO_OPTIONS', 'No compatible options are available.'); + process.stderr.write(label + '\n'); + rows.forEach((row, i) => process.stderr.write(` ${i + 1}. ${display(row)}\n`)); + while (true) { + const answer = await question('Choose a number [1], or q to cancel: '); + if (answer.toLowerCase() === 'q') throw new ProxyAPIError('ABORTED'); + const index = answer ? Number(answer) - 1 : 0; + if (Number.isInteger(index) && index >= 0 && index < rows.length) return rows[index]; + process.stderr.write('Choose a number from the displayed options.\n'); + } +} + +async function advanced(client, input) { + const source = await question('Use an existing channel [c], or choose a product [Enter]: '); + if (source.toLowerCase() === 'q') throw new ProxyAPIError('ABORTED'); + if (source && source.toLowerCase() !== 'c') + throw new InputError('INVALID_SELECTION', 'Press Enter to choose a product, or c for an existing channel.'); + if (source.toLowerCase() === 'c') { + const rows = await client.listChannels({ status: 1, page: 1, pageSize: 100 }, { signal: controller.signal }); + const channel = await choose('Active channels (first page):', rows, + row => `${row.channelId} (${row.type ?? 'unknown product'})`); + return { country: input.country, protocol: input.protocol, sessionDuration: input.sessionDuration, channelId: channel.channelId }; + } + const rows = (await client.listPlans({}, { signal: controller.signal })) + .filter(row => row.protocols.includes(input.protocol ?? 'http') && + ['residential_lite', 'residential', 'ipv6', 'datacenter', 'mobile'].includes(row.type)); + const plan = await choose('Available products (reference price per GB):', rows, + row => `${row.name} (${row.type}, ${row.priceGB}/GB)`); + const countries = await client.listCountries({ type: plan.type }, { signal: controller.signal }); + const country = await choose('Available countries:', countries, row => row.value); + return { protocol: input.protocol, sessionDuration: input.sessionDuration, + type: plan.type, zoneName: plan.name, country: country.value }; +} + +async function checkOutput(path) { + if (!path || /[\p{Cc}\p{Cf}]/u.test(path)) throw new InputError('OUTPUT_ERROR', 'Choose a new writable output file.'); + try { + await lstat(path); + throw new InputError('OUTPUT_EXISTS', 'Output already exists. Choose another path; existing files are never overwritten.'); + } catch (error) { + if (error.code !== 'ENOENT') { + if (error instanceof InputError) throw error; + throw new InputError('OUTPUT_ERROR', 'Cannot inspect the output path. Choose a new writable file.'); + } + } + try { await access(dirname(resolve(path)), constants.W_OK); } + catch { throw new InputError('OUTPUT_ERROR', 'The output directory is not writable or does not exist.'); } +} + +async function main() { + const { values } = parseArgs({ options: { + yes: { type: 'boolean' }, 'dry-run': { type: 'boolean' }, channel: { type: 'string' }, + type: { type: 'string' }, zone: { type: 'string' }, country: { type: 'string' }, + protocol: { type: 'string' }, duration: { type: 'string' }, count: { type: 'string' }, + 'env': { type: 'string' }, json: { type: 'boolean' }, 'show-url': { type: 'boolean' }, + output: { type: 'string' }, help: { type: 'boolean', short: 'h' }, + }, strict: true }); + if (values.help) { console.log(help); return; } + if (values['env'] !== undefined) { + try { process.loadEnvFile(values['env']); } + catch { throw new InputError('ENV_FILE_ERROR', 'Cannot read the specified environment file. Check its path and permissions.'); } + } + const count = values.count === undefined ? 1 : Number(values.count); + if (!Number.isSafeInteger(count) || count < 1 || count > 1000) + throw new InputError('INVALID_ARGUMENT', '--count must be an integer from 1 to 1000.'); + if ((values.output !== undefined && values['show-url']) || (values['dry-run'] && (values.output !== undefined || values['show-url']))) + throw new InputError('INVALID_ARGUMENT', 'Choose one output mode; --dry-run cannot export connections.'); + const interactive = Boolean(process.stdin.isTTY && process.stderr.isTTY && !values.json && !values.yes); + let apiKey = process.env.NSTDATA_API_TOKEN; + if (!apiKey && interactive) apiKey = await question('Nstdata API key (hidden): ', true); + if (!apiKey) throw new InputError('MISSING_API_KEY', 'Set NSTDATA_API_TOKEN or use --env; interactive input is hidden.'); + if (!interactive && !values.yes && !values['dry-run']) + throw new InputError('CONFIRMATION_REQUIRED', 'Use --dry-run to inspect setup, or --yes to allow channel setup and generation.'); + if (values.output !== undefined) await checkOutput(values.output); + const client = new ProxyClient({ apiKey, baseUrl: process.env.NSTDATA_API_BASE_URL, teamId: process.env.NSTDATA_TEAM_ID }); + apiKey = undefined; + let input = { channelId: values.channel, type: values.type, zoneName: values.zone, country: values.country, + protocol: values.protocol, sessionDuration: values.duration === undefined ? undefined : Number(values.duration) }; + const request = { signal: controller.signal }; + const interrupt = () => controller.abort(); + process.once('SIGINT', interrupt); process.once('SIGTERM', interrupt); + try { + let plan = await client.prepareProxy(input, request); + if (values['dry-run']) { console.log(JSON.stringify(plan)); return; } + while (interactive) { + process.stderr.write(`\nProduct: ${plan.zoneName} (${plan.type})\nCountry: ${plan.country}\n` + + `Reference price: ${plan.priceGB}/GB; balance: ${plan.balance}\n` + + `Channel: ${plan.channelAction === 'create' ? 'create reusable SDK default' : 'reuse selected channel'}\n` + + `Generate ${count} ${plan.protocol} connection(s); no network test or package purchase.\n`); + const answer = (await question('[Enter] Continue, [a] Advanced settings, [q] Cancel: ')).toLowerCase(); + if (answer === 'q') throw new ProxyAPIError('ABORTED'); + if (answer === 'a') { input = await advanced(client, input); plan = await client.prepareProxy(input, request); continue; } + if (answer !== '') { + process.stderr.write('Press Enter, a for advanced settings, or q to cancel.\n'); + continue; + } + break; + } + const result = await client.getProxies({ ...input, count }, request); + let output = values.output, show = Boolean(values['show-url']); + while (interactive && !output && !show) { + const answer = (await question('Generated. [s] Save private file, [v] Show credentials, [Enter] Summary only: ')).toLowerCase(); + if (answer === 's') { + while (!output) { + const path = await question('New output file [proxies.json]: ') || 'proxies.json'; + try { await checkOutput(path); output = path; } + catch (error) { if (!(error instanceof InputError)) throw error; process.stderr.write(error.message + '\n'); } + } + } + else if (answer === 'v') show = true; + else if (answer === '') break; + else process.stderr.write('Choose s, v or Enter; the generated connections are retained.\n'); + } + if (output) { + try { await writeFile(output, JSON.stringify({ ...result, count }, null, 2) + '\n', { flag: 'wx', mode: 0o600 }); } + catch { throw new InputError('OUTPUT_ERROR', 'Generation completed but connections could not be saved. Check the path before another run; no retry was made.'); } + } + const { proxies, ...metadata } = result; + console.log(JSON.stringify({ ...metadata, count, ...(output ? { saved: true } : {}), ...(show ? { proxies } : {}) })); + } finally { process.removeListener('SIGINT', interrupt); process.removeListener('SIGTERM', interrupt); } +} + +main().catch(error => { + if (controller.signal.aborted && !(error instanceof ProxyAPIError)) error = new ProxyAPIError('ABORTED'); + const known = error instanceof InputError || error instanceof ProxyAPIError; + console.error(JSON.stringify({ error: { code: known ? error.code : 'INVALID_INPUT', + message: known ? error.message : 'Invalid command-line input. Run nstdata-proxy --help for usage.' } })); + process.exitCode = controller.signal.aborted || error.code === 'ABORTED' ? 130 : error instanceof ProxyAPIError ? 1 : 2; +}); diff --git a/src/errors.js b/src/errors.js new file mode 100644 index 0000000..1e2f0da --- /dev/null +++ b/src/errors.js @@ -0,0 +1,30 @@ +const messages = { + INVALID_CONFIG: 'Invalid Proxy client configuration.', + INVALID_ARGUMENT: 'Invalid Proxy request arguments.', + TIMEOUT: 'Proxy API request timed out; a submitted operation may still complete.', + ABORTED: 'Local waiting was cancelled; a submitted operation may still complete.', + NETWORK_ERROR: 'Proxy API connection failed; a submitted operation may still complete.', + HTTP_ERROR: 'Proxy API returned an unsuccessful HTTP status.', + API_ERROR: 'Proxy API reported an application error.', + INVALID_RESPONSE: 'Proxy API returned an invalid response.', + RESPONSE_TOO_LARGE: 'Proxy API response exceeded the configured byte limit.', + INSUFFICIENT_BALANCE: 'No usable balance is available in this account context. Check the balance and API key context.', + NO_COMPATIBLE_PLAN: 'No compatible proxy product is available. Choose a supported product or check account access.', + CHANNEL_UNAVAILABLE: 'The selected channel is unavailable or incompatible. Check its status, resources and product.', + CHANNEL_REQUIRED: 'This product requires an existing channel. Supply channelId or use a pay-per-use product.', + COUNTRY_UNAVAILABLE: 'No compatible country is available. Choose a country supported by this product and channel.', + CHANNEL_DISCOVERY_LIMIT: 'Channel discovery reached its safe limit. Supply an existing channelId; no channel was created.', + CHANNEL_CREATION_UNCERTAIN: 'Channel creation outcome is unknown. Check existing channels or supply channelId before another creation. No retry was performed.', + PROXY_GENERATION_UNCERTAIN: 'Proxy generation outcome is unknown; a session may have been generated. No retry was performed.', + NO_PROXY_GENERATED: 'The API returned no proxy connection. Check channel availability before requesting another session.', +}; + +export class ProxyAPIError extends Error { + constructor(code, { statusCode, applicationCode } = {}) { + super(messages[code] ?? messages.INVALID_RESPONSE); + this.name = 'ProxyAPIError'; + this.code = code; + if (statusCode !== undefined) this.statusCode = statusCode; + if (applicationCode !== undefined) this.applicationCode = applicationCode; + } +} diff --git a/src/index.d.ts b/src/index.d.ts index aa2c569..00fa185 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -1,6 +1,9 @@ export type ProxyType = 'residential' | 'residential_lite' | 'ipv6' | 'datacenter' | 'mobile' | 'isp'; export type ProxyErrorCode = 'INVALID_CONFIG' | 'INVALID_ARGUMENT' | 'TIMEOUT' | 'ABORTED' | - 'NETWORK_ERROR' | 'HTTP_ERROR' | 'API_ERROR' | 'INVALID_RESPONSE' | 'RESPONSE_TOO_LARGE'; + 'NETWORK_ERROR' | 'HTTP_ERROR' | 'API_ERROR' | 'INVALID_RESPONSE' | 'RESPONSE_TOO_LARGE' | + 'INSUFFICIENT_BALANCE' | 'NO_COMPATIBLE_PLAN' | 'CHANNEL_UNAVAILABLE' | 'CHANNEL_REQUIRED' | + 'COUNTRY_UNAVAILABLE' | 'CHANNEL_DISCOVERY_LIMIT' | 'CHANNEL_CREATION_UNCERTAIN' | + 'PROXY_GENERATION_UNCERTAIN' | 'NO_PROXY_GENERATED'; export class ProxyAPIError extends Error { readonly code: ProxyErrorCode; @@ -17,6 +20,53 @@ export interface ProxyClientConfig { maxResponseBytes?: number; } export interface RequestOptions { signal?: AbortSignal } +export interface AccountInfo { + balance: number; + email?: string; + referralBalance?: number; + [key: string]: unknown; +} +export interface ProxyPlan { + name: string; + type: string; + protocols: string[]; + priceGB: number; + supports: string[]; + label?: string; + [key: string]: unknown; +} +export interface ProxyCountry { + value: string; + label?: string; + regionId?: string | number; + [key: string]: unknown; +} +export interface ProxySetupInput { + channelId?: string; + type?: ProxyType; + zoneName?: string; + country?: string; + protocol?: 'http' | 'socks5'; + sessionDuration?: number; +} +export interface ProxyPreparation { + channelId?: string; + channelAction: 'create' | 'reuse'; + channelName: string; + type: ProxyType; + zoneName: string; + country: string; + protocol: 'http' | 'socks5'; + sessionDuration: number; + priceGB: number; + balance: number; +} +export interface ProxyConnection extends Omit { + channelId: string; + url: string; + createdChannel: boolean; +} +export interface ProxyConnections extends Omit { proxies: string[] } export interface GenerateProxiesInput { channelId: string; country: string; @@ -71,6 +121,12 @@ export interface CreateChannelInput extends UpdateChannelInput { export class ProxyClient { constructor(config: ProxyClientConfig); + getAccountInfo(options?: RequestOptions): Promise; + listPlans(query?: { type?: ProxyType }, options?: RequestOptions): Promise; + listCountries(query: { type: ProxyType }, options?: RequestOptions): Promise; + prepareProxy(input?: ProxySetupInput, options?: RequestOptions): Promise>; + getProxy(input?: ProxySetupInput, options?: RequestOptions): Promise; + getProxies(input?: ProxySetupInput & { count?: number }, options?: RequestOptions): Promise; generateProxies(input: GenerateProxiesInput, options?: RequestOptions): Promise; listChannels(query?: ListChannelsQuery, options?: RequestOptions): Promise; getChannel(channelId: string, options?: RequestOptions): Promise; diff --git a/src/index.js b/src/index.js index eea42f3..b2dae18 100644 --- a/src/index.js +++ b/src/index.js @@ -1,28 +1,10 @@ import { isIP } from 'node:net'; +import { ProxyAPIError } from './errors.js'; +import { ProxySetup } from './setup.js'; +export { ProxyAPIError } from './errors.js'; const types = ['residential', 'residential_lite', 'ipv6', 'datacenter', 'mobile', 'isp']; const regions = ['country', 'state', 'city']; -const messages = { - INVALID_CONFIG: 'Invalid Proxy client configuration.', - INVALID_ARGUMENT: 'Invalid Proxy request arguments.', - TIMEOUT: 'Proxy API request timed out; a submitted operation may still complete.', - ABORTED: 'Local waiting was cancelled; a submitted operation may still complete.', - NETWORK_ERROR: 'Proxy API connection failed; a submitted operation may still complete.', - HTTP_ERROR: 'Proxy API returned an unsuccessful HTTP status.', - API_ERROR: 'Proxy API reported an application error.', - INVALID_RESPONSE: 'Proxy API returned an invalid response.', - RESPONSE_TOO_LARGE: 'Proxy API response exceeded the configured byte limit.', -}; - -export class ProxyAPIError extends Error { - constructor(code, { statusCode, applicationCode } = {}) { - super(messages[code] ?? messages.INVALID_RESPONSE); - this.name = 'ProxyAPIError'; - this.code = code; - if (statusCode !== undefined) this.statusCode = statusCode; - if (applicationCode !== undefined) this.applicationCode = applicationCode; - } -} function fail(code = 'INVALID_ARGUMENT') { throw new ProxyAPIError(code); } function object(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); } @@ -70,6 +52,7 @@ export class ProxyClient { #teamId; #timeoutMs; #maxResponseBytes; + #setup = new ProxySetup(this); constructor(config) { fields(config, ['apiKey', 'baseUrl', 'teamId', 'timeoutMs', 'maxResponseBytes'], 'INVALID_CONFIG'); @@ -106,6 +89,35 @@ export class ProxyClient { integer(value.count, 0) && value.count === value.proxies.length); } + async prepareProxy(input, options) { return this.#setup.prepare(input, options); } + async getProxy(input, options) { return this.#setup.get(input, options); } + async getProxies(input, options) { return this.#setup.getMany(input, options); } + + async getAccountInfo(options) { + return this.#request('GET', '/user/info', undefined, undefined, options, value => + object(value) && Number.isFinite(value.balance) && + (value.email === undefined || text(value.email)) && + (value.referralBalance === undefined || Number.isFinite(value.referralBalance))); + } + + async listPlans(query = {}, options) { + fields(query, ['type']); + if (query.type !== undefined && !types.includes(query.type)) fail(); + return this.#request('GET', '/plan/info', query, undefined, options, value => + Array.isArray(value) && value.every(plan => object(plan) && text(plan.name) && text(plan.type) && + strings(plan.protocols) && Number.isFinite(plan.priceGB) && plan.priceGB >= 0 && strings(plan.supports) && + (plan.label === undefined || typeof plan.label === 'string'))); + } + + async listCountries(query, options) { + fields(query, ['type']); + if (!types.includes(query.type)) fail(); + return this.#request('GET', '/region/country', query, undefined, options, value => + Array.isArray(value) && value.every(country => object(country) && text(country.value) && + (country.label === undefined || typeof country.label === 'string') && + (country.regionId === undefined || typeof country.regionId === 'string' || Number.isFinite(country.regionId)))); + } + async listChannels(query = {}, options) { fields(query, ['page', 'pageSize', 'type', 'regionType', 'status', 'createType', 's']); if (query.page !== undefined && !integer(query.page)) fail(); diff --git a/src/setup.js b/src/setup.js new file mode 100644 index 0000000..d46b708 --- /dev/null +++ b/src/setup.js @@ -0,0 +1,231 @@ +import { ProxyAPIError } from './errors.js'; +import { randomBytes } from 'node:crypto'; + +const channelName = 'nstdata-sdk-default'; +const productTypes = ['residential_lite', 'residential', 'ipv6', 'datacenter', 'mobile', 'isp']; +const text = value => typeof value === 'string' && value.isWellFormed() && value === value.trim() && + value.length > 0 && value.length <= 256 && !/[\p{Cc}\p{Cf}]/u.test(value); +const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0; +const uncertain = error => ['TIMEOUT', 'ABORTED', 'NETWORK_ERROR', 'INVALID_RESPONSE', 'RESPONSE_TOO_LARGE'].includes(error.code) || + (error.code === 'HTTP_ERROR' && (error.statusCode === 408 || error.statusCode >= 500)) || + (error.code === 'API_ERROR' && error.applicationCode >= 500 && error.applicationCode < 600); + +function normalize(input = {}, options = {}) { + if (!input || typeof input !== 'object' || Array.isArray(input) || + Object.keys(input).some(key => !['channelId', 'type', 'zoneName', 'country', 'protocol', 'sessionDuration'].includes(key)) || + !options || typeof options !== 'object' || Array.isArray(options) || + Object.keys(options).some(key => key !== 'signal') || + (options.signal !== undefined && !(options.signal instanceof AbortSignal))) throw new ProxyAPIError('INVALID_ARGUMENT'); + for (const key of ['channelId', 'zoneName', 'country']) + if (input[key] !== undefined && !text(input[key])) throw new ProxyAPIError('INVALID_ARGUMENT'); + if (input.channelId !== undefined && (/[/?#\\]/.test(input.channelId) || ['.', '..'].includes(input.channelId))) + throw new ProxyAPIError('INVALID_ARGUMENT'); + const { protocol = 'http', sessionDuration = 10 } = input; + if (!['http', 'socks5'].includes(protocol) || !Number.isSafeInteger(sessionDuration) || sessionDuration < 1 || + (input.type !== undefined && !productTypes.includes(input.type))) throw new ProxyAPIError('INVALID_ARGUMENT'); + return { channelId: input.channelId, type: input.type, zoneName: input.zoneName, + country: input.country?.toUpperCase(), protocol, sessionDuration }; +} + +function usable(channel) { + if (channel.status !== 1 || !text(channel.channelId) || !productTypes.includes(channel.type) || !text(channel.zoneName)) return false; + if (channel.exTime != null && (!Number.isFinite(Date.parse(channel.exTime)) || Date.parse(channel.exTime) <= Date.now())) return false; + if (channel.total != null && (!Number.isFinite(channel.total) || !Number.isFinite(channel.used) || channel.total <= channel.used)) return false; + return true; +} + +async function sharedTask(tasks, key, task, signal) { + if (signal?.aborted) throw new ProxyAPIError('ABORTED'); + let entry = tasks.get(key); + if (!entry) { + entry = { controller: new AbortController(), waiters: 0, settled: false }; + tasks.set(key, entry); + entry.promise = Promise.resolve().then(() => task(entry.controller.signal)).finally(() => { + entry.settled = true; + if (tasks.get(key) === entry) tasks.delete(key); + }); + } + const wasAborted = entry.controller.signal.aborted; + try { + return await new Promise((resolve, reject) => { + entry.waiters++; + let done = false; + const finish = (callback, value) => { + if (done) return; + done = true; signal?.removeEventListener('abort', aborted); + entry.waiters--; + if (!entry.waiters && !entry.settled) entry.controller.abort(); + callback(value); + }; + const aborted = () => finish(reject, new ProxyAPIError('ABORTED')); + signal?.addEventListener('abort', aborted, { once: true }); + entry.promise.then(value => finish(resolve, value), error => finish(reject, error)); + if (signal?.aborted) aborted(); + }); + } catch (error) { + // A new caller can wait out an earlier cancelled initialization before resolving its own setup. + if (wasAborted && !signal?.aborted) return sharedTask(tasks, key, task, signal); + throw error; + } +} + +export class ProxySetup { + #client; + #cache = new Map(); + #initializations = new Map(); + #creations = new Map(); + #uncertainCreations = new Set(); + constructor(client) { this.#client = client; } + + async prepare(input, options = {}) { + const settings = normalize(input, options); + if (options.signal?.aborted) throw new ProxyAPIError('ABORTED'); + const key = JSON.stringify(settings); + const cached = this.#cache.get(key); + if (cached && cached.until > Date.now()) return Object.freeze({ ...cached.plan }); + const request = { signal: options.signal }; + const account = await this.#client.getAccountInfo(request); + if (!settings.channelId && account.balance <= 0) throw new ProxyAPIError('INSUFFICIENT_BALANCE'); + const catalog = await this.#client.listPlans({}, request); + const compatible = catalog.filter(plan => productTypes.includes(plan.type) && plan.protocols.includes(settings.protocol) && + (settings.type === undefined ? (settings.channelId || ['residential_lite', 'residential'].includes(plan.type)) : plan.type === settings.type) && + (settings.zoneName === undefined || plan.name === settings.zoneName)).sort((a, b) => + productTypes.indexOf(a.type) - productTypes.indexOf(b.type) || a.priceGB - b.priceGB || compare(a.name, b.name)); + if (!compatible.length) throw new ProxyAPIError('NO_COMPATIBLE_PLAN'); + const channels = settings.channelId ? await this.#client.getChannel(settings.channelId, request) : await this.#defaultChannels(request); + const active = channels.filter(channel => usable(channel) && compatible.some(plan => + plan.name === channel.zoneName && plan.type === channel.type) && + (settings.channelId || settings.country === undefined || !channel.country || + channel.country === 'ANY' || channel.country === settings.country) && + (settings.channelId ? channel.channelId === settings.channelId : + channel.name === channelName && channel.total == null && !channel.packageId)); + active.sort((a, b) => compatible.findIndex(plan => plan.name === a.zoneName && plan.type === a.type) - + compatible.findIndex(plan => plan.name === b.zoneName && plan.type === b.type) || compare(a.channelId, b.channelId)); + const channel = active[0]; + if (settings.channelId && !channel) throw new ProxyAPIError('CHANNEL_UNAVAILABLE'); + const plan = channel ? compatible.find(plan => plan.name === channel.zoneName && plan.type === channel.type) : compatible[0]; + if (!channel && plan.type === 'isp') throw new ProxyAPIError('CHANNEL_REQUIRED'); + if (account.balance <= 0 && !(channel?.total > channel?.used)) throw new ProxyAPIError('INSUFFICIENT_BALANCE'); + const available = await this.#client.listCountries({ type: plan.type }, request); + const values = [...new Set(available.map(row => row.value).filter(text))].sort(compare); + const fixed = channel?.country && channel.country !== 'ANY' ? channel.country : undefined; + const country = settings.country ?? fixed ?? (values.includes('US') ? 'US' : values[0]); + if (!country || !values.includes(country) || (fixed && fixed !== country)) throw new ProxyAPIError('COUNTRY_UNAVAILABLE'); + const result = Object.freeze({ channelId: channel?.channelId, channelAction: channel ? 'reuse' : 'create', + channelName: channel?.name ?? channelName, type: plan.type, zoneName: plan.name, country, + protocol: settings.protocol, sessionDuration: settings.sessionDuration, priceGB: plan.priceGB, balance: account.balance }); + this.#store(key, result); + return Object.freeze({ ...result }); + } + + async get(input, options) { + const { proxies, ...metadata } = await this.#generate(input, options, 1); + return { ...metadata, url: proxies[0] }; + } + + async getMany(input = {}, options) { + if (!input || typeof input !== 'object' || Array.isArray(input)) throw new ProxyAPIError('INVALID_ARGUMENT'); + const { count = 1, ...settings } = input; + if (!Number.isSafeInteger(count) || count < 1 || count > 1000) throw new ProxyAPIError('INVALID_ARGUMENT'); + return this.#generate(settings, options, count); + } + + async #generate(input, options = {}, count) { + const settings = normalize(input, options); + if (options.signal?.aborted) throw new ProxyAPIError('ABORTED'); + const key = JSON.stringify(settings); + const initialized = await sharedTask(this.#initializations, key, + signal => this.#initialize(settings, key, signal), options.signal); + if (options.signal?.aborted) throw new ProxyAPIError('ABORTED'); + let result; + try { + result = await this.#client.generateProxies({ channelId: initialized.plan.channelId, + country: initialized.plan.country, protocol: settings.protocol, + sessionDuration: settings.sessionDuration, count }, { signal: options.signal }); + } catch (error) { + if (uncertain(error)) throw new ProxyAPIError('PROXY_GENERATION_UNCERTAIN', { + statusCode: error.statusCode, applicationCode: error.applicationCode, + }); + throw error; + } + if (!result.proxies.length) throw new ProxyAPIError('NO_PROXY_GENERATED'); + try { + if (result.proxies.length !== count) throw new Error(); + for (const value of result.proxies) { + if (value.length > 8192) throw new Error(); + const url = new URL(value); + decodeURIComponent(url.username); decodeURIComponent(url.password); + if (url.protocol !== settings.protocol + ':' || !url.hostname || + !['', '/'].includes(url.pathname) || url.search || url.hash || + /[\p{Cc}\p{Cf}]/u.test(value)) throw new Error(); + } + } catch { throw new ProxyAPIError('PROXY_GENERATION_UNCERTAIN'); } + const { channelAction, channelName: _name, balance: _balance, ...metadata } = initialized.plan; + return { ...metadata, proxies: result.proxies, createdChannel: initialized.createdChannel }; + } + + async #initialize(settings, key, signal) { + let plan = await this.prepare(settings, { signal }); + let createdChannel = false; + if (plan.channelAction === 'create') { + const channel = await sharedTask(this.#creations, plan.type + ':' + plan.zoneName, + active => this.#createDefault(plan, active), signal); + plan = Object.freeze({ ...plan, channelId: channel.channelId, channelAction: 'reuse' }); + this.#store(key, plan); + createdChannel = channel.created; + } + return { plan, createdChannel }; + } + + async #createDefault(plan, signal) { + const resource = plan.type + ':' + plan.zoneName; + const channels = await this.#defaultChannels({ signal }); + const existing = channels.filter(channel => usable(channel) && channel.name === channelName && + channel.type === plan.type && channel.zoneName === plan.zoneName && channel.total == null && !channel.packageId && + (!channel.country || channel.country === 'ANY')).sort((a, b) => compare(a.channelId, b.channelId))[0]; + if (existing) { + this.#uncertainCreations.delete(resource); + return { channelId: existing.channelId, created: false }; + } + if (this.#uncertainCreations.has(resource) || this.#uncertainCreations.size >= 16) + throw new ProxyAPIError('CHANNEL_CREATION_UNCERTAIN'); + if (signal.aborted) throw new ProxyAPIError('ABORTED'); + try { + const channel = await this.#client.createChannel({ name: channelName, + password: randomBytes(12).toString('hex'), type: plan.type, zoneName: plan.zoneName }, { signal }); + if (!text(channel.channelId) || /[/?#\\]/.test(channel.channelId) || ['.', '..'].includes(channel.channelId)) + throw new ProxyAPIError('INVALID_RESPONSE'); + this.#uncertainCreations.delete(resource); + return { channelId: channel.channelId, created: true }; + } catch (error) { + if (uncertain(error)) { + this.#uncertainCreations.add(resource); + for (const [key, entry] of this.#cache) + if (entry.plan.type === plan.type && entry.plan.zoneName === plan.zoneName) this.#cache.delete(key); + throw new ProxyAPIError('CHANNEL_CREATION_UNCERTAIN', { + statusCode: error.statusCode, applicationCode: error.applicationCode, + }); + } + throw error; + } + } + + #store(key, plan) { + if (!this.#cache.has(key) && this.#cache.size >= 16) this.#cache.delete(this.#cache.keys().next().value); + this.#cache.set(key, { plan, until: Date.now() + 30000 }); + } + + async #defaultChannels(options) { + const rows = [], seen = new Set(); + for (let page = 1; page <= 5; page++) { + // Match names locally: the customer route does not translate s/createType into channel filters. + const batch = await this.#client.listChannels({ status: 1, page, pageSize: 100 }, options); + for (const channel of batch) { + if (seen.has(channel.channelId)) throw new ProxyAPIError('CHANNEL_DISCOVERY_LIMIT'); + seen.add(channel.channelId); rows.push(channel); + } + if (batch.length < 100) return rows; + } + throw new ProxyAPIError('CHANNEL_DISCOVERY_LIMIT'); + } +} diff --git a/test/cli.test.mjs b/test/cli.test.mjs new file mode 100644 index 0000000..1121973 --- /dev/null +++ b/test/cli.test.mjs @@ -0,0 +1,121 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { fileURLToPath } from 'node:url'; +import { mkdtemp, readFile, writeFile, stat, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { fixture, key } from './proxy-fixture.mjs'; + +const cliFile = process.env.NSTDATA_PROXY_INSTALLED === '1' + ? fileURLToPath(new URL('./cli.js', import.meta.resolve('@nstdata-ai/proxy'))) + : fileURLToPath(new URL('../src/cli.js', import.meta.url)); + +async function cli(args, env = {}, input = '') { + const clean = Object.fromEntries(['PATH', 'HOME', 'TMPDIR', 'NODE_OPTIONS'].filter(name => process.env[name]) + .map(name => [name, process.env[name]])); + const child = spawn(process.execPath, [cliFile, ...args], { env: { ...clean, ...env } }); + let stdout = '', stderr = ''; + child.stdout.on('data', data => { stdout += data; }); child.stderr.on('data', data => { stderr += data; }); + child.stdin.end(input); + const [code] = await once(child, 'close'); + return { code, stdout, stderr }; +} + +test('CLI help works without credentials, a project or any account operation', async () => { + const result = await cli(['--help']); + assert.equal(result.code, 0); + assert.equal(result.stderr, ''); + assert.match(result.stdout, /Usage: nstdata-proxy/); + assert.match(result.stdout, /NSTDATA_API_TOKEN/); + assert.match(result.stdout, /--yes/); + assert.ok(result.stdout.split('\n').every(line => line.length <= 100)); +}); + +test('non-interactive CLI requires credentials and explicit consent before any API request', async t => { + const f = await fixture(t); + const missing = await cli(['--yes'], { NSTDATA_API_BASE_URL: f.baseUrl }); + assert.equal(missing.code, 2); assert.equal(JSON.parse(missing.stderr).error.code, 'MISSING_API_KEY'); + const unconfirmed = await cli([], { NSTDATA_API_TOKEN: key, NSTDATA_API_BASE_URL: f.baseUrl }); + assert.equal(unconfirmed.code, 2); + assert.equal(JSON.parse(unconfirmed.stderr).error.code, 'CONFIRMATION_REQUIRED'); + assert.equal(f.state.requests.length, 0); +}); + +test('CLI previews are read-only and confirmed generation hides credentials by default', async t => { + const f = await fixture(t); + const env = { NSTDATA_API_TOKEN: key, NSTDATA_API_BASE_URL: f.baseUrl }; + const preview = await cli(['--dry-run', '--json'], env); + assert.equal(preview.code, 0, preview.stderr); + assert.equal(JSON.parse(preview.stdout).channelAction, 'create'); + assert.equal(f.state.channels.length, 0); + assert.ok(f.state.requests.every(row => row.method === 'GET' && !row.path.endsWith('/proxies'))); + const generated = await cli(['--yes', '--json', '--count', '2'], env); + assert.equal(generated.code, 0, generated.stderr); + assert.equal(JSON.parse(generated.stdout).count, 2); + assert.equal(generated.stderr, ''); + assert.doesNotMatch(generated.stdout, /quickstart-test-key|fixture:password|gateway.invalid/); + assert.equal(f.state.channels.length, 1); + assert.equal(f.state.requests.filter(row => row.path.endsWith('/proxies')).length, 1); +}); + +test('connection export is explicit, private, non-overwriting and separate from API-key storage', async t => { + const dir = await mkdtemp(join(tmpdir(), 'nstdata-proxy-cli-')); + t.after(() => rm(dir, { recursive: true, force: true })); + const f = await fixture(t); + const file = join(dir, 'connections.json'); + const env = { NSTDATA_API_TOKEN: key, NSTDATA_API_BASE_URL: f.baseUrl }; + const saved = await cli(['--yes', '--json', '--output', file], env); + assert.equal(saved.code, 0, saved.stderr); + const output = JSON.parse(await readFile(file, 'utf8')); + assert.equal(output.proxies[0], 'http://fixture:password@gateway.invalid:8000'); + assert.doesNotMatch(JSON.stringify(output), /quickstart-test-key/); + assert.equal((await stat(file)).mode & 0o777, 0o600); + const before = f.state.requests.length; + const existing = await cli(['--yes', '--output', file], env); + assert.equal(existing.code, 2); + assert.equal(f.state.requests.length, before); + assert.deepEqual(JSON.parse(await readFile(file, 'utf8')), output); + const shown = await cli(['--yes', '--show-url', '--json'], env); + assert.equal(shown.code, 0); + assert.equal(JSON.parse(shown.stdout).proxies[0], output.proxies[0]); +}); + +test('CLI loads only an explicit env file and reports input errors without their contents', async t => { + const dir = await mkdtemp(join(tmpdir(), 'nstdata-proxy-env-')); + t.after(() => rm(dir, { recursive: true, force: true })); + const f = await fixture(t); + const file = join(dir, '.env'); + await writeFile(file, `NSTDATA_API_TOKEN=${key}\nNSTDATA_API_BASE_URL=${f.baseUrl}\n`, { mode: 0o600 }); + assert.equal((await cli(['--env', file, '--dry-run', '--json'])).code, 0); + for (const args of [['--count', '0'], ['--unknown-secret-option'], ['--env', '/missing/private-path']]) { + const result = await cli(args); + assert.equal(result.code, 2); + assert.equal(result.stdout, ''); + assert.doesNotMatch(result.stderr, /quickstart-test-key|unknown-secret-option|private-path/); + } +}); + +test('hidden-key prompt is printed only after terminal input is in raw mode', async t => { + const dir = await mkdtemp(join(tmpdir(), 'nstdata-proxy-prompt-')); + t.after(() => rm(dir, { recursive: true, force: true })); + const preload = join(dir, 'terminal.cjs'); + await writeFile(preload, `let raw = false; +Object.defineProperty(process.stdin, 'isTTY', { value: true }); +Object.defineProperty(process.stderr, 'isTTY', { value: true }); +process.stdin.setRawMode = value => { raw = value; return process.stdin; }; +const write = process.stderr.write.bind(process.stderr); +process.stderr.write = (chunk, ...args) => { + if (String(chunk).includes('Nstdata API key (hidden): ')) { + if (!raw) process.stdout.write('PROMPT_BEFORE_RAW_MODE'); + setImmediate(() => process.stdin.emit('data', Buffer.from('\\x03'))); + } + return write(chunk, ...args); +};\n`); + const options = (process.env.NODE_OPTIONS ?? '') + ' --require=' + JSON.stringify(preload); + const result = await cli([], { NODE_OPTIONS: options }); + assert.equal(result.code, 130, result.stderr); + assert.doesNotMatch(result.stdout, /PROMPT_BEFORE_RAW_MODE/); + assert.match(result.stderr, /ABORTED/); +}); diff --git a/test/documentation.test.mjs b/test/documentation.test.mjs index 0683b12..3f78346 100644 --- a/test/documentation.test.mjs +++ b/test/documentation.test.mjs @@ -35,7 +35,11 @@ test('bilingual quick starts specify matching programs, dotenv and exact runnabl fs.readFileSync(new URL('../' + file, import.meta.url), 'utf8')); assert.deepEqual(...readmes.map(shellCommands)); assert.deepEqual(shellCommands(readmes[0]), [ - ['npm', 'install', '@nstdata-ai/proxy'], ['node', '--env-file=.env', 'quickstart.mjs'], + ['npm', 'install', '@nstdata-ai/proxy'], + ['npx', '--yes', '--package=@nstdata-ai/proxy', 'nstdata-proxy'], + ['npx', '--yes', '--package=@nstdata-ai/proxy', 'nstdata-proxy', '--env', '.env', + '--yes', '--output', 'proxies.json'], + ['node', '--env-file=.env', 'quickstart.mjs'], ]); for (const language of ['js', 'dotenv']) { const blocks = readmes.map(text => codeBlocks(text).filter(block => block.lang === language)); diff --git a/test/proxy-fixture.mjs b/test/proxy-fixture.mjs new file mode 100644 index 0000000..a300c6e --- /dev/null +++ b/test/proxy-fixture.mjs @@ -0,0 +1,48 @@ +import http from 'node:http'; +const { ProxyClient } = await import(process.env.NSTDATA_PROXY_INSTALLED === '1' + ? '@nstdata-ai/proxy' : '../src/index.js'); +export const key = 'quickstart-test-key'; +export const plans = [ + { name: 'prime', type: 'residential', protocols: ['http', 'socks5'], priceGB: 5, supports: ['country'] }, + { name: 'lite', type: 'residential_lite', protocols: ['http', 'socks5'], priceGB: 2, supports: ['country'] }, +]; +export const countries = [{ value: 'GB', label: 'United Kingdom' }, { value: 'US', label: 'United States' }]; + +export async function fixture(t, overrides = {}) { + const state = { balance: 20, plans, countries, channels: [], requests: [], ...overrides }; + const server = http.createServer(async (req, res) => { + const url = new URL(req.url, 'http://127.0.0.1'); + let body = ''; for await (const chunk of req) body += chunk; + state.requests.push({ method: req.method, path: url.pathname, query: Object.fromEntries(url.searchParams), + body: body ? JSON.parse(body) : undefined, team: req.headers['x-team-id'] }); + if (state.handle && await state.handle(req, res, url, body, state)) return; + let data; + if (url.pathname.endsWith('/user/info')) data = { balance: state.balance }; + else if (url.pathname.endsWith('/plan/info')) data = state.plans; + else if (url.pathname.endsWith('/region/country')) data = state.countries; + else if (url.pathname.endsWith('/channels')) { + const selectors = [...url.searchParams].filter(([name]) => !['page', 'pageSize'].includes(name)); + const rows = state.channels.filter(row => selectors.every(([name, value]) => String(row[name]) === value)); + const offset = (Number(url.searchParams.get('page') ?? 1) - 1) * Number(url.searchParams.get('pageSize') ?? 50); + data = rows.slice(offset, offset + Number(url.searchParams.get('pageSize') ?? 50)); + } + else if (url.pathname.endsWith('/channel') && req.method === 'POST') { + const input = JSON.parse(body); + data = { ...input, channelId: 'sdk-channel', status: 1, used: 0 }; + state.channels.push(data); + } else if (url.pathname.includes('/channel/')) data = state.channels.filter(row => + row.channelId === decodeURIComponent(url.pathname.split('/').at(-1))); + else if (url.pathname.endsWith('/proxies')) { + const count = Number(url.searchParams.get('count')); + data = { proxies: Array.from({ length: count }, (_, i) => + `${url.searchParams.get('protocol')}://fixture:password@gateway.invalid:${8000 + i}`), count }; + } + else { res.writeHead(404); res.end(); return; } + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ data, err: false, code: 200 })); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + t.after(() => new Promise(resolve => { server.close(resolve); server.closeAllConnections(); })); + const baseUrl = `http://127.0.0.1:${server.address().port}`; + return { state, baseUrl, client: new ProxyClient({ apiKey: key, baseUrl }) }; +} diff --git a/test/quickstart.test.mjs b/test/quickstart.test.mjs new file mode 100644 index 0000000..85b1c26 --- /dev/null +++ b/test/quickstart.test.mjs @@ -0,0 +1,309 @@ +import assert from 'node:assert/strict'; +import { inspect } from 'node:util'; +import test from 'node:test'; +import { fixture, key, plans, countries } from './proxy-fixture.mjs'; + +const { ProxyClient, ProxyAPIError } = await import(process.env.NSTDATA_PROXY_INSTALLED === '1' + ? '@nstdata-ai/proxy' : '../src/index.js'); +test('account lookup exposes a validated balance without changing account resources', async t => { + const f = await fixture(t); + assert.deepEqual(await f.client.getAccountInfo(), { balance: 20 }); + f.state.balance = -1; + assert.deepEqual(await f.client.getAccountInfo(), { balance: -1 }); + for (const balance of [null, '20']) { + f.state.balance = balance; + await assert.rejects(f.client.getAccountInfo(), { code: 'INVALID_RESPONSE' }); + } + assert.ok(f.state.requests.every(row => row.method === 'GET' && row.path.endsWith('/user/info'))); +}); + +test('catalog queries preserve live products and country values and validate inputs before traffic', async t => { + const f = await fixture(t); + assert.deepEqual(await f.client.listPlans({ type: 'residential_lite' }), plans); + assert.deepEqual(await f.client.listCountries({ type: 'residential_lite' }), countries); + assert.equal(f.state.requests[0].query.type, 'residential_lite'); + assert.equal(f.state.requests[1].query.type, 'residential_lite'); + for (const call of [() => f.client.listPlans({ token: key }), () => f.client.listCountries(), + () => f.client.listCountries({ type: 'not-a-type' })]) + await assert.rejects(call(), { code: 'INVALID_ARGUMENT' }); + assert.equal(f.state.requests.length, 2); + f.state.plans = [{ ...plans[0], priceGB: 'unknown' }]; + await assert.rejects(f.client.listPlans(), { code: 'INVALID_RESPONSE' }); + f.state.countries = [{ label: 'Missing value' }]; + await assert.rejects(f.client.listCountries({ type: 'residential' }), { code: 'INVALID_RESPONSE' }); +}); + +test('preparing a proxy with only a key selects live defaults without creating resources', async t => { + const f = await fixture(t); + const plan = await f.client.prepareProxy(); + assert.equal(plan.type, 'residential_lite'); + assert.equal(plan.zoneName, 'lite'); + assert.equal(plan.country, 'US'); + assert.equal(plan.protocol, 'http'); + assert.equal(plan.sessionDuration, 10); + assert.equal(plan.channelAction, 'create'); + assert.equal(plan.channelId, undefined); + assert.equal(plan.priceGB, 2); + assert.equal(f.state.channels.length, 0); + assert.ok(f.state.requests.every(row => row.method === 'GET' && !row.path.endsWith('/proxies'))); + assert.doesNotMatch(inspect(plan), /quickstart-test-key|password/); +}); + +test('a key-only user can generate one connection and reuse the confirmed default channel', async t => { + const f = await fixture(t); + const first = await f.client.getProxy(); + const second = await f.client.getProxy(); + assert.equal(first.url, 'http://fixture:password@gateway.invalid:8000'); + assert.equal(first.channelId, 'sdk-channel'); + assert.equal(first.createdChannel, true); + assert.equal(second.createdChannel, false); + const writes = f.state.requests.filter(row => row.method === 'POST'); + assert.equal(writes.length, 1); + assert.equal(writes[0].body.name, 'nstdata-sdk-default'); + assert.match(writes[0].body.password, /^[a-zA-Z0-9]{24}$/); + assert.equal(writes[0].body.zoneName, 'lite'); + assert.equal(writes[0].body.type, 'residential_lite'); + const generations = f.state.requests.filter(row => row.path.endsWith('/proxies')); + assert.equal(generations.length, 2); + for (const row of generations) assert.deepEqual(row.query, { + channelId: 'sdk-channel', country: 'US', protocol: 'http', sessionDuration: '10', count: '1', + }); +}); + +test('existing defaults are reused without touching business channels or credentials', async t => { + const own = { channelId: 'existing', name: 'nstdata-sdk-default', type: 'residential_lite', zoneName: 'lite', status: 1 }; + const f = await fixture(t, { channels: [{ ...own, name: 'production', channelId: 'business' }, own] }); + assert.equal((await f.client.getProxy()).channelId, 'existing'); + assert.equal(f.state.requests.filter(row => row.method !== 'GET').length, 0); + assert.deepEqual(f.state.channels, [{ ...own, name: 'production', channelId: 'business' }, own]); +}); + +test('a fresh client rediscovers the default without unsupported search or creation-type filters', async t => { + const f = await fixture(t); + const first = await f.client.getProxy(); + const second = await new ProxyClient({ apiKey: key, baseUrl: f.baseUrl }).getProxy(); + assert.equal(second.channelId, first.channelId); + assert.equal(second.createdChannel, false); + assert.equal(f.state.requests.filter(row => row.method === 'POST').length, 1); + assert.equal(f.state.requests.filter(row => row.path.endsWith('/proxies')).length, 2); + for (const row of f.state.requests.filter(row => row.path.endsWith('/channels'))) + assert.deepEqual(Object.keys(row.query).sort(), ['page', 'pageSize', 'status']); +}); + +test('unsupported prerequisites stop before creating or generating anything', async t => { + for (const [changes, code] of [[{ balance: 0 }, 'INSUFFICIENT_BALANCE'], [{ plans: [] }, 'NO_COMPATIBLE_PLAN'], + [{ countries: [] }, 'COUNTRY_UNAVAILABLE']]) { + const f = await fixture(t, changes); + await assert.rejects(f.client.getProxy(), { code }); + assert.ok(f.state.requests.every(row => row.method === 'GET' && !row.path.endsWith('/proxies'))); + } +}); + +test('explicit choices are respected and incompatible selections never trigger fallback creation', async t => { + const f = await fixture(t); + const selected = await f.client.getProxy({ country: 'gb', type: 'residential', sessionDuration: 5 }); + assert.equal(selected.country, 'GB'); assert.equal(selected.zoneName, 'prime'); + assert.equal(f.state.requests.find(row => row.path.endsWith('/proxies')).query.sessionDuration, '5'); + const before = f.state.requests.length; + await assert.rejects(f.client.getProxy({ channelId: 'absent' }), { code: 'CHANNEL_UNAVAILABLE' }); + await assert.rejects(f.client.getProxy({ country: 'ZZ' }), { code: 'COUNTRY_UNAVAILABLE' }); + assert.ok(f.state.requests.slice(before).every(row => row.method === 'GET' && !row.path.endsWith('/proxies'))); + for (const input of [{ unknown: true }, { country: '' }, { channelId: '../secret' }, { sessionDuration: 0 }, { protocol: 'https' }]) { + const count = f.state.requests.length; + await assert.rejects(f.client.getProxy(input), { code: 'INVALID_ARGUMENT' }); + assert.equal(f.state.requests.length, count); + } +}); + +test('a fixed-region default is not reused for another requested region', async t => { + const f = await fixture(t, { channels: [{ channelId: 'fixed', name: 'nstdata-sdk-default', + type: 'residential_lite', zoneName: 'lite', status: 1, country: 'GB' }] }); + const proxy = await f.client.getProxy({ country: 'US' }); + assert.equal(proxy.country, 'US'); assert.notEqual(proxy.channelId, 'fixed'); + assert.equal(f.state.channels[0].country, 'GB'); +}); + +test('concurrent callers share channel initialization but get separate generated sessions', async t => { + const f = await fixture(t); + const results = await Promise.all([f.client.getProxy(), f.client.getProxy(), f.client.getProxy()]); + assert.ok(results.every(result => result.channelId === 'sdk-channel')); + assert.equal(f.state.requests.filter(row => row.method === 'POST').length, 1); + assert.equal(f.state.requests.filter(row => row.path.endsWith('/proxies')).length, 3); +}); + +test('cancelling one waiter does not cancel another caller or generate the cancelled session', async t => { + let started, release; + const received = new Promise(resolve => { started = resolve; }); + const gate = new Promise(resolve => { release = resolve; }); + const f = await fixture(t, { handle: async (req, _res, url) => { + if (req.method === 'POST' && url.pathname.endsWith('/channel')) { started(); await gate; } + return false; + } }); + const controller = new AbortController(); + const first = f.client.getProxy({}, { signal: controller.signal }); + const second = f.client.getProxy(); + const rejected = assert.rejects(first, { code: 'ABORTED' }); + await received; controller.abort(); release(); + await rejected; + assert.equal((await second).channelId, 'sdk-channel'); + assert.equal(f.state.requests.filter(row => row.method === 'POST').length, 1); + assert.equal(f.state.requests.filter(row => row.path.endsWith('/proxies')).length, 1); +}); + +test('unknown channel creation is reconciled by reads and is never blindly resubmitted', async t => { + const f = await fixture(t, { handle: async (req, res, url) => { + if (req.method === 'POST' && url.pathname.endsWith('/channel')) { res.destroy(); return true; } + return false; + } }); + await assert.rejects(f.client.getProxy(), error => { + assert.equal(error.code, 'CHANNEL_CREATION_UNCERTAIN'); + assert.doesNotMatch(inspect(error), /quickstart-test-key|password|cause/); + return true; + }); + await assert.rejects(f.client.getProxy(), { code: 'CHANNEL_CREATION_UNCERTAIN' }); + assert.equal(f.state.requests.filter(row => row.method === 'POST').length, 1); + f.state.channels.push({ channelId: 'recovered', name: 'nstdata-sdk-default', status: 1, + type: 'residential_lite', zoneName: 'lite' }); + assert.equal((await f.client.getProxy()).channelId, 'recovered'); + assert.equal(f.state.requests.filter(row => row.method === 'POST').length, 1); +}); + +test('a batch uses one generation request and shares initialization with single-connection calls', async t => { + const f = await fixture(t); + const result = await f.client.getProxies({ count: 3 }); + assert.equal(result.proxies.length, 3); + assert.equal(result.channelId, 'sdk-channel'); + assert.equal(f.state.requests.filter(row => row.path.endsWith('/proxies')).length, 1); + assert.equal(f.state.requests.find(row => row.path.endsWith('/proxies')).query.count, '3'); + await f.client.getProxy(); + assert.equal(f.state.requests.filter(row => row.method === 'POST').length, 1); + for (const count of [0, 1001, 1.5]) await assert.rejects(f.client.getProxies({ count }), { code: 'INVALID_ARGUMENT' }); +}); + +test('channel discovery is bounded and cannot convert an incomplete search into a creation', async t => { + const f = await fixture(t, { handle: async (_req, res, url) => { + if (!url.pathname.endsWith('/channels')) return false; + const page = Number(url.searchParams.get('page')); + res.end(JSON.stringify({ err: false, code: 200, data: Array.from({ length: 100 }, (_, i) => + ({ channelId: `other-${page}-${i}`, name: 'business' })) })); + return true; + } }); + await assert.rejects(f.client.getProxy(), { code: 'CHANNEL_DISCOVERY_LIMIT' }); + assert.equal(f.state.requests.filter(row => row.path.endsWith('/channels')).length, 5); + assert.equal(f.state.requests.filter(row => row.method !== 'GET' || row.path.endsWith('/proxies')).length, 0); +}); + +test('expired, banned and exhausted channels are not silently used as selected resources', async t => { + for (const change of [{ status: 3 }, { exTime: '2000-01-01T00:00:00Z' }, { total: 100, used: 100 }]) { + const f = await fixture(t, { channels: [{ channelId: 'selected', status: 1, type: 'residential', + zoneName: 'prime', name: 'business', ...change }] }); + await assert.rejects(f.client.getProxy({ channelId: 'selected' }), { code: 'CHANNEL_UNAVAILABLE' }); + assert.ok(f.state.requests.every(row => row.method === 'GET' && !row.path.endsWith('/proxies'))); + } +}); + +test('generation errors, empty results and invalid connection URLs are not retried or exposed', async t => { + for (const mode of ['unavailable', 'empty', 'invalid']) { + const f = await fixture(t, { handle: async (_req, res, url) => { + if (!url.pathname.endsWith('/proxies')) return false; + if (mode === 'unavailable') { res.writeHead(503); res.end(key); } + else res.end(JSON.stringify({ err: false, code: 200, + data: mode === 'empty' ? { proxies: [], count: 0 } : { proxies: ['socks5://secret:secret@gateway.invalid:8000'], count: 1 } })); + return true; + } }); + await assert.rejects(f.client.getProxy(), error => { + assert.ok(error instanceof ProxyAPIError); + assert.equal(error.code, mode === 'empty' ? 'NO_PROXY_GENERATED' : 'PROXY_GENERATION_UNCERTAIN'); + assert.doesNotMatch(inspect(error), /quickstart-test-key|secret|cause/); + return true; + }); + assert.equal(f.state.requests.filter(row => row.path.endsWith('/proxies')).length, 1); + } +}); + +test('cancelled callers do not start discovery or resource requests', async t => { + const f = await fixture(t); + const signal = AbortSignal.abort(); + await assert.rejects(f.client.getProxy({}, { signal }), { code: 'ABORTED' }); + await assert.rejects(f.client.prepareProxy({}, { signal }), { code: 'ABORTED' }); + assert.equal(f.state.requests.length, 0); +}); + +test('concurrent country selections share one unrestricted default channel', async t => { + const f = await fixture(t); + const results = await Promise.all([f.client.getProxy({ country: 'US' }), f.client.getProxy({ country: 'GB' })]); + assert.deepEqual(results.map(row => row.country), ['US', 'GB']); + assert.equal(new Set(results.map(row => row.channelId)).size, 1); + assert.equal(f.state.requests.filter(row => row.method === 'POST').length, 1); +}); + +test('SOCKS5 connections remain usable without adding a synthetic URL path', async t => { + const f = await fixture(t); + const result = await f.client.getProxy({ protocol: 'socks5' }); + assert.equal(result.url, 'socks5://fixture:password@gateway.invalid:8000'); + assert.equal(result.protocol, 'socks5'); + assert.equal(f.state.requests.filter(row => row.path.endsWith('/proxies')).length, 1); +}); + +test('new query methods reject malformed declared optional fields instead of contradicting their types', async t => { + for (const [path, data, call] of [ + ['/user/info', { balance: 20, email: 42 }, client => client.getAccountInfo()], + ['/user/info', { balance: 20, referralBalance: '10' }, client => client.getAccountInfo()], + ['/plan/info', [{ ...plans[0], label: {} }], client => client.listPlans()], + ['/region/country', [{ value: 'US', label: 1 }], client => client.listCountries({ type: 'residential' })], + ['/region/country', [{ value: 'US', regionId: {} }], client => client.listCountries({ type: 'residential' })], + ]) { + const f = await fixture(t, { handle: async (_req, res, url) => { + if (!url.pathname.endsWith(path)) return false; + res.end(JSON.stringify({ err: false, code: 200, data })); return true; + } }); + await assert.rejects(call(f.client), { code: 'INVALID_RESPONSE' }); + assert.equal(f.state.requests.length, 1); + } +}); + +test('server failures preserve unknown write outcomes without resubmission', async t => { + for (const operation of ['create', 'generate']) { + for (const failure of ['application', 'http-timeout']) { + const f = await fixture(t, { handle: async (req, res, url) => { + if (operation === 'create' ? req.method !== 'POST' : !url.pathname.endsWith('/proxies')) return false; + if (failure === 'http-timeout') res.writeHead(408); + res.end(JSON.stringify({ err: true, code: 500, data: null })); return true; + } }); + const code = operation === 'create' ? 'CHANNEL_CREATION_UNCERTAIN' : 'PROXY_GENERATION_UNCERTAIN'; + await assert.rejects(f.client.getProxy(), error => { + assert.equal(error.code, code); + assert.equal(error.statusCode, failure === 'application' ? 200 : 408); + assert.equal(error.applicationCode, failure === 'application' ? 500 : undefined); + return true; + }); + if (operation === 'create') await assert.rejects(f.client.getProxy(), { code }); + assert.equal(f.state.requests.filter(row => row.method === 'POST').length, 1); + assert.equal(f.state.requests.filter(row => row.path.endsWith('/proxies')).length, + operation === 'generate' ? 1 : 0); + } + } +}); + +test('separate team clients retain their own initialization, cache and request context', async t => { + const channels = new Map(); + const f = await fixture(t, { handle: async (req, res, url, body) => { + const team = req.headers['x-team-id']; + let data; + if (url.pathname.endsWith('/channels')) data = channels.get(team) ?? []; + else if (req.method === 'POST' && url.pathname.endsWith('/channel')) { + data = { ...JSON.parse(body), channelId: team + '-channel', status: 1 }; + channels.set(team, [data]); + } else { + if (url.pathname.endsWith('/proxies')) assert.equal(url.searchParams.get('channelId'), team + '-channel'); + return false; + } + res.end(JSON.stringify({ err: false, code: 200, data })); return true; + } }); + const clients = ['team-one', 'team-two'].map(teamId => new ProxyClient({ apiKey: key, baseUrl: f.baseUrl, teamId })); + const result = await Promise.all(clients.map(client => client.getProxy())); + assert.deepEqual(result.map(row => row.channelId), ['team-one-channel', 'team-two-channel']); + assert.equal((await clients[0].getProxy()).channelId, 'team-one-channel'); + assert.equal(f.state.requests.filter(row => row.method === 'POST').length, 2); + assert.ok(f.state.requests.every(row => ['team-one', 'team-two'].includes(row.team))); +}); diff --git a/test/types.ts b/test/types.ts index 83418ff..f000805 100644 --- a/test/types.ts +++ b/test/types.ts @@ -3,6 +3,18 @@ import { ProxyClient, ProxyAPIError, type Channel, type GeneratedProxies } from async function consumer() { const client = new ProxyClient({ apiKey: 'test-only-api-key', timeoutMs: 15000 }); const options = { signal: new AbortController().signal }; + const account = await client.getAccountInfo(options); + const plans = await client.listPlans({}, options); + const countries = await client.listCountries({ type: 'residential_lite' }, options); + const preparation = await client.prepareProxy({}, options); + const connection = await client.getProxy({ country: 'US' }, options); + const batch = await client.getProxies({ count: 3 }, options); + const balance: number = account.balance; + const unitPrice: number = plans[0].priceGB; + const countryCode: string = countries[0].value; + const url: string = connection.url; + const urls: string[] = batch.proxies; + const action: 'reuse' | 'create' = preparation.channelAction; const list: Channel[] = await client.listChannels({ page: 1, pageSize: 10, createType: 'balance' }, options); const detail: Channel[] = await client.getChannel('sample-channel', options); const generated: GeneratedProxies = await client.generateProxies({ @@ -19,7 +31,7 @@ async function consumer() { const single: Channel = await client.getChannel('sample-channel'); // @ts-expect-error Unsupported generation protocol. void client.generateProxies({ channelId: 'sample', country: 'US', protocol: 'https', sessionDuration: 10, count: 1 }); - return { list, detail, generated, channel, updated, deleted, single }; + return { list, detail, generated, channel, updated, deleted, single, balance, unitPrice, countryCode, url, urls, action }; } const code: string = new ProxyAPIError('TIMEOUT').code; void consumer; void code;