Node.js SDK
Node.js와 TypeScript용 CaptchaSonic 공식 라이브러리 — 최신 Promise 기반, 다중 전송 방식(gRPC / ConnectRPC / HTTP).
CaptchaSonic Node.js SDK(captchasonic)는 대규모 CAPTCHA 풀이를 위한 최신 Promise 기반 TypeScript 우선 라이브러리입니다. 모든 메서드는 Promise를 반환하고, 전체 타입 정의를 포함하며, 세 가지 상호 호환되는 전송 방식으로 동작합니다. 네이티브 gRPC(가장 빠름, Node.js 전용), ConnectRPC(Node.js와 브라우저 모두 지원), 일반 HTTP/JSON입니다. 일시적인 오류는 지수 백오프로 자동 재시도됩니다.
Node.js ≥ 18 및 최신 브라우저에서 동작하며, Express, Fastify, Next.js, React, Vue, Vite와 호환됩니다.
설치
npm install captchasonic
# or
yarn add captchasonic
# or
pnpm add captchasonic
요구 사항
| 요구 사항 | 참고 |
|---|---|
| Node.js | ≥ 18.0.0 (grpc 전송 방식에 필요) |
| 모듈 형식 | ES Module — 패키지는 "type": "module"로 배포됩니다 |
| 브라우저 | fetch를 지원하는 최신 브라우저. connect 또는 http 전송 방식 사용 |
이 패키지는 ESM 전용으로 배포됩니다. ESM 프로젝트(package.json에 "type": "module"이 있거나 .mjs 파일을 사용하는 경우)에서는 직접 import하세요:
import { CaptchaSonic } from "captchasonic";
CommonJS 파일에서는 동적 import()로 불러오세요:
// CommonJS (.cjs / "type": "commonjs")
const { CaptchaSonic } = await import("captchasonic");
TIP
TypeScript를 사용한다면 번들된 타입 정의가 올바르게 해석되도록 tsconfig.json에 "module": "NodeNext"(또는 "ESNext")와 "moduleResolution": "NodeNext"를 설정하세요.
인증
CaptchaSonic 대시보드에서 API 키를 만들고 생성자의 첫 번째 인자로 전달하세요:
import { CaptchaSonic } from "captchasonic";
const solver = new CaptchaSonic("YOUR_API_KEY");
키를 소스 코드 저장소에 하드코딩하지 마세요. 대신 환경 변수에서 읽으세요:
import { CaptchaSonic } from "captchasonic";
const solver = new CaptchaSonic(process.env.CAPTCHASONIC_API_KEY);
빠른 시작
CAPTCHA 유형마다 전용 solve* 헬퍼가 있으며, 작업을 제출하고 결과로 resolve됩니다. 이미지 작업에는 별도의 폴링 단계가 없습니다. SDK가 자동으로 처리합니다.
solveRecaptchaV2TokentokenreCAPTCHA v2 (token) — Solve a reCAPTCHA v2 token challenge via browser automation (async — polls until ready).
solveRecaptchaV2Token(…)returnssolution.tokenimport { CaptchaSonic } from "captchasonic";
const solver = new CaptchaSonic(process.env.CAPTCHASONIC_API_KEY);
const result = await solver.solveRecaptchaV2Token({
websiteURL: "https://example.com/login",
websiteKey: "6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
});
console.log(result.solution.gRecaptchaResponse);
// 03AGdBq25SxXT... ← drop into the g-recaptcha-response fieldfrom captchasonic import CaptchaSonic
solver = CaptchaSonic("YOUR_API_KEY")
result = solver.solve_recaptcha_v2_token(
website_url="https://example.com/login",
website_key="6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
)
print(result["token"])
# 03AGdBq25SxXT... ← drop this into the g-recaptcha-response field반환값: 이미지 메서드는 답이
typedSolution아래에 있는 결과로 resolve됩니다(예: 선택한 타일 인덱스인typedSolution.grid.objects). 토큰 메서드는solution맵에 토큰을 담아 반환합니다.
TIP
토큰 기반 메서드(Turnstile, Cloudflare, reCAPTCHA v2/v3 토큰, popular-captcha 토큰)는 브라우저 자동화 작업을 제출한 뒤 토큰이 준비될 때까지 내부적으로 폴링합니다. 기본 대기 시간은 최대 120초입니다.
지원 CAPTCHA 유형
모든 이미지 메서드는 단일 타입 옵션 객체를 받습니다. 이미지는 Uint8Array, Node Buffer, 또는 문자열 파일 경로가 될 수 있습니다(파일 경로는 Node.js 전용).
reCAPTCHA v2 (이미지)
await solver.solveRecaptchaV2({
images: tiles, // typically 9 tiles for a 3×3 grid
question: "traffic lights", // plain text, or a Google class code like "/m/015qff"
});
// → result.typedSolution.grid.objects (number[] — selected tile indices)
PopularCaptcha (hCaptcha 스타일 이미지)
await solver.solvePopularCaptcha({
images: tiles, // 1–64 tiles
question: "Click each image with a cat",
questionType: "objectClassify", // "objectClassify" | "grid" | "objectClick" | "objectDrag"
examples, // optional reference images for objectClick
websiteURL: "https://example.com",
});
// objectClassify/grid → typedSolution.grid.objects
// objectClick → typedSolution.click
// objectDrag → typedSolution.drag
GeeTest
// nine-grid (question + images required)
await solver.solveGeetest({ type: "nine", question: "Select all bicycles", images: tiles });
// click / icon (question + images required)
await solver.solveGeetest({ type: "click", question: "the bear", images: tiles });
// slide puzzle (piece + background)
await solver.solveGeetest({ type: "slide", images: [piece], examples: [background] });
// swap puzzles
await solver.solveGeetest({ type: "match" });
await solver.solveGeetest({ type: "winlinze" });
반환값: grid/click 유형은 typedSolution.grid.objects(또는 typedSolution.click)에 담기고, slide는 typedSolution.slide.x를 반환합니다.
허용되는 type 별칭:
| 정식 이름 | 별칭 |
|---|---|
| nine-grid | "nine", "geetest_nine", "9" |
| click / icon | "click", "geetest_click", "icon" |
| slide | "slide", "geetest_slide" |
| match | "match", "geetest_match" |
| winlinze | "winlinze", "geetest_winlinze" |
OCR / 이미지-텍스트 변환
await solver.solveOcr({ images: [img] }); // general OCR
await solver.solveOcr({ images: [img], module: "mtcaptcha", maxLength: 4 });
await solver.solveOcr({ images: imgs, module: "bls", numeric: true, maxLength: 3 });
// → result.typedSolution.text.texts[0]
| 옵션 | 타입 | 참고 |
|---|---|---|
module | "common" | "mtcaptcha" | "bls" | "morocco" | 기본값 "common" |
numeric | boolean | 숫자만 ("bls"에서 자동 설정) |
caseSensitive | boolean | 영문자 대소문자 유지 |
minLength / maxLength | number | 길이 범위 |
TikTok
await solver.solveTikTok({ type: "click", question: "Select the shape", images });
await solver.solveTikTok({ type: "whirl", question: "Rotate to match", images, examples }); // examples required
await solver.solveTikTok({ type: "slide", question: "Slide to fit", images, examples }); // examples required
반환값: click은 typedSolution.click에 담기고, whirl/slide는 typedSolution.slide.x를 반환합니다.
type은 "click"/"tiktok_click", "whirl"/"tiktok_whirl", "slide"/"tiktok_slide"를 받습니다.
Binance
await solver.solveBinance({ type: "grid", question: "Select the bicycle", images });
await solver.solveBinance({ type: "slide", images: [puzzle], examples: [background] });
반환값: grid는 typedSolution.grid.objects에 담기고, slide는 typedSolution.slide.x를 반환합니다.
type은 "grid"/"binance_grid", "slide"/"binance_slide"를 받습니다.
AWS WAF
solveAwsWaf는 위치 인자를 받습니다. question은 "type:category:target" 형식입니다.
await solver.solveAwsWaf(tiles, "grid:vehicles:cars");
반환값: 선택한 타일 인덱스가 typedSolution.grid.objects에 담깁니다.
슬라이드 이미지 (로컬, AI 미사용)
윤곽선 검출로 슬라이드 오프셋을 로컬에서 계산합니다. 결합된 이미지 한 장 또는 [background, piece]를 받습니다.
const r = await solver.solveSlideImage({ images: ["slide_bg.png", "piece.png"] });
console.log(r.typedSolution?.slide?.x); // pixel offset, e.g. 142
반환값: 슬라이드 오프셋(픽셀)이 typedSolution.slide.x에 담깁니다.
토큰 메서드 (브라우저 자동화)
이 메서드들은 작업을 제출한 뒤 토큰이 반환될 때까지 내부적으로 폴링합니다(기본 폴링 제한 시간 120초까지).
solveTurnstiletokenCloudflare Turnstile — Solve a Cloudflare Turnstile token challenge (async — polls until ready).
solveTurnstile(…)returnssolution.tokenawait solver.solveTurnstile({ websiteURL, websiteKey, proxy }); // proxy optional
await solver.solveRecaptchaV2Token({ websiteURL, websiteKey, proxy }); // proxy optional
await solver.solveRecaptchaV3Token({ websiteURL, websiteKey, proxy }); // proxy optional
await solver.solvePopularCaptchaToken({ websiteURL, websiteKey, proxy, metadata }); // proxy optional
await solver.solveCloudflare({ websiteURL, websiteKey, proxy }); // proxy REQUIREDsolver.solve_turnstile(website_url=..., website_key=..., proxy=...) # proxy optional
solver.solve_recaptcha_v2_token(website_url=..., website_key=..., proxy=...) # proxy optional
solver.solve_recaptcha_v3_token(website_url=..., website_key=..., proxy=...) # proxy optional
solver.solve_popular_captcha_token(website_url=..., website_key=..., proxy=...) # proxy optional
solver.solve_cloudflare(website_url=..., website_key=..., proxy=...) # proxy REQUIRED반환값: 응답의 solution 맵에 토큰이 담깁니다(CAPTCHA에 따라 예를 들어 result.solution.token 또는 result.solution.gRecaptchaResponse).
TypeScript 사용법
SDK는 모든 옵션 객체와 응답에 대한 타입을 내보냅니다. import type으로 가져오세요.
import { CaptchaSonic } from "captchasonic";
import type { SolveGeetestOptions, GetTaskResultResponse } from "captchasonic";
const solver = new CaptchaSonic(process.env.CAPTCHASONIC_API_KEY!);
const opts: SolveGeetestOptions = {
type: "nine",
question: "Select all bicycles",
images: tiles,
};
const result = await solver.solveGeetest(opts);
console.log(result.typedSolution?.grid?.objects);
내보내는 타입
import type {
CaptchaSonicOptions,
ImageInput,
SolvePopularCaptchaOptions,
SolveRecaptchaV2Options,
SolveGeetestOptions,
SolveOcrOptions,
SolveTikTokOptions,
SolveBinanceOptions,
SolveTurnstileOptions,
SolvePopularCaptchaTokenOptions,
SolveRecaptchaV2TokenOptions,
SolveRecaptchaV3TokenOptions,
SolveCloudflareOptions,
SolveSlideImageOptions,
GeetestSubtype,
TikTokSubtype,
BinanceSubtype,
Task,
CreateTaskResponse,
GetTaskResultResponse,
} from "captchasonic";
ImageInput은 Uint8Array | Buffer | string입니다.
프록시 지원
토큰 / 브라우저 자동화 메서드는 http://user:pass@host:port 형식의 선택적 proxy 문자열을 받습니다:
await solver.solveTurnstile({
websiteURL: "https://example.com",
websiteKey: "0x4AAAAAAA...",
proxy: "http://user:[email protected]:8080",
});
WARNING
solveCloudflare는 항상 프록시가 필요합니다. 이 메서드에서 proxy 필드는 필수입니다. 다른 토큰 메서드는 proxy를 생략하면 프록시 없이 실행됩니다.
엔터프라이즈 hCaptcha의 경우 solvePopularCaptchaToken에 metadata(rqdata, rqtoken, fingerprint)를 전달할 수도 있습니다.
설정
생성자의 두 번째 인자로 옵션 객체를 전달하세요. 아래 옵션만 지원됩니다.
const solver = new CaptchaSonic("YOUR_API_KEY", {
transport: "connect", // "grpc" (default) | "connect" | "http"
timeout: 180_000, // max poll wait in ms (alias: timeoutMs); per-call default 30000
pollingInterval: 5_000, // polling frequency in ms (default 2000)
baseUrl: "https://api.captchasonic.com", // override endpoint (alias: url)
});
| 옵션 | 타입 | 기본값 | 설명 |
|---|---|---|---|
transport | "grpc" | "connect" | "http" | "grpc" | 와이어 프로토콜 (아래 표 참고) |
timeout / timeoutMs | number | 호출당 30000 | 요청 제한 시간. timeout은 폴링 대기 시간도 제한합니다 |
pollingInterval | number | 2000 | 토큰 작업을 폴링하는 주기 |
url / baseUrl | string | 전송 방식별 상이 | API 엔드포인트 재정의 |
전송 방식
| 전송 방식 | 환경 | 프로토콜 |
|---|---|---|
grpc | Node.js 전용 | HTTP/2 위의 gRPC 바이너리 — 지연 시간이 가장 짧고, 이미지를 원시 바이너리로 전송 |
connect | Node.js 및 브라우저 | fetch 위의 ConnectRPC |
http | Node.js 및 브라우저 | fetch 위의 일반 REST/JSON |
TIP
브라우저에서는 connect(권장) 또는 http를 사용하세요. 네이티브 gRPC는 Node.js가 필요합니다. connect/http에서는 이미지가 전송 전에 base64로 자동 인코딩되며, grpc에서는 오버헤드 없이 원시 바이너리로 전송됩니다.
오류 처리
API 수준의 모든 실패는 내장 Error를 확장한 SonicError를 던집니다. 숫자형 errorId를 포함하며, name은 해당 오류 이름으로 설정됩니다.
import { CaptchaSonic, SonicError } from "captchasonic";
try {
const result = await solver.solveGeetest({ type: "nine", question: "bicycles", images });
} catch (err) {
if (err instanceof SonicError) {
console.error(err.errorId); // 1–6
console.error(err.name); // e.g. "InvalidApiKeyError"
console.error(err.message);
} else {
throw err; // network / unexpected
}
}
| id | Python exception | Node errorName | Meaning | Action |
|---|---|---|---|---|
0 | SonicError | SonicError | Base class for every SDK error — catches anything below. | Inspect `error.errorId` (Node) / `err.error_id` (Python) and branch. |
1 | InvalidApiKeyError | InvalidApiKeyError | API key is missing, malformed, or revoked. | Verify the key in your dashboard. |
2 | InsufficientBalanceError | InsufficientBalanceError | Account balance can't cover the task. | Add funds. |
3 | DailyLimitExceededError | DailyLimitExceededError | Daily quota exhausted. | Wait for the daily reset or upgrade your plan. |
4 | MinuteLimitExceededError | MinuteLimitExceededError | Per-minute rate limit hit. | Slow down requests / add exponential backoff. |
5 | QuotaExceededError | QuotaExceededError | Plan quota exhausted. | Upgrade your plan. |
6 | PlanExpiredError | PlanExpiredError | Subscription has expired. | Renew your subscription. |
Every concrete row inherits from SonicError — catch it once to handle all SDK failures, or branch on errorId / exception subclass for granular control. Transient gRPC errors are retried automatically with exponential backoff (up to 3 attempts).
TIP
일시적인 gRPC 오류는 지수 백오프로 자동 재시도됩니다(최대 3회). 따라서 보통은 위의 SonicError 경우만 처리하면 됩니다.
계정 헬퍼
const balance = await solver.getBalance(); // → number (USD)
const health = await solver.healthCheck(); // → { healthy: boolean, version: string }
제출과 폴링을 직접 제어해야 한다면 저수준 작업 메서드를 사용할 수 있습니다:
const created = await solver.createTask(task); // submit a Partial<Task>
const result = await solver.getTaskResult(taskId); // poll for a result
문제 해결
require is not defined / Cannot use import statement outside a module — 이 패키지는 ESM 전용입니다. ESM 프로젝트에서는 import를 사용하고, CommonJS에서는 await import("captchasonic")를 사용하세요. 설치를 참고하세요.
브라우저에서 grpc 전송 방식이 실패함 — 네이티브 gRPC는 Node.js 전용입니다. transport: "connect" 또는 transport: "http"로 바꾸세요.
모든 호출에서 InvalidApiKeyError가 발생함 — 키가 생성자의 첫 번째 인자로 전달되었는지, 실수로 undefined(예: 환경 변수 누락)가 되지 않았는지 확인하세요.
토큰 메서드가 시간 초과됨 — 토큰 작업은 timeout ms(기본값 120000)까지 폴링합니다. timeout을 늘리고, websiteURL / websiteKey가 대상 페이지와 일치하는지 확인하세요. Cloudflare는 유효한 proxy가 필요합니다.
파일 경로 이미지가 로드되지 않음 — 문자열 파일 경로는 동기적으로 읽히며 Node.js 전용입니다. 브라우저에서는 대신 Uint8Array를 전달하세요.