Docs / 자동화와 확장
Script SDK 참조
구현된 1.0.0 계약을 기준으로 코드를 작성하세요. 이 문서는 런타임에 없는 API를 추측하지 않고 입력과 결과를 연결하기 위한 참조입니다.
Pro BetaWireSnare 1.0.0 · 출시 예정이 기능을 사용하려면 Pro Beta가 필요합니다.
이 문서의 목차
코드를 넣는 곳과 실행 조건
Script Studio에서 스크립트를 만들고 Inspector의 Trigger·Capability·한도를 설정합니다. 설정은 소스 안의 주석이나 export 객체로 선언하지 않습니다. 아래 TypeScript 타입은 참조용이며, 실제 붙여넣기는 완성 예제의 전체 코드를 사용하세요.
진입점은 이름 있는 export function run(context) 또는 export async function run(context, ws)입니다. default export·화살표 export로 대체하지 마세요. 타입 import는 import type … from "@wiresnare/sdk"로 작성하며 실행 때 제거됩니다. npm 패키지를 설치하거나 다른 런타임 모듈을 import하지 않습니다.
Trigger와 입력 선택
manual은 사용자가 테스트하거나 메뉴에서 실행합니다. http-request, http-response, websocket-frame, dns-message, tcp-chunk, udp-datagram은 해당하는 새 트래픽에서 실행합니다. 응답이나 전체 본문이 항상 존재한다고 가정하지 마세요.
Context 필드 사전
| 필드 | 사용 규칙 |
|---|---|
selection | 항상 사용. kind/id가 Action의 대상. frameSeq/recordId는 있을 때만 사용 |
event | 합성 Test에는 없을 수 있음. trigger·source·capturedAt 등은 선택 필드 |
http.request | method/url/headers. text·base64·partial·totalBytes는 입력별로 선택적 |
http.response | 있을 때만 status/headers/본문을 읽음. 요청 시점에 가정 금지 |
raw | bytes:number[]는 0–255. protocol/transport/boundary/messageBoundary/partial을 확인 |
websocket.frame | opcode/final/partial/text/bytes. fin·websocket.text가 아님 |
intercept | 보류 명령만 제공. id/revision/bytes와 현재 편집 표현 |
panelAction | 콜백에서 panelId/actionId/values. values는 string 맵 |
입력은 보존 데이터의 제한된 스냅샷입니다. 값 변경이 캡처나 편집기에 반영되는 쓰기 API는 아닙니다. 전역 변수는 다음 실행까지 보관되지 않습니다. 선택하지 않은 다른 연결·전체 프로젝트·파일을 열거하는 API는 없습니다.
HTTP 헤더·본문·바이트
headers는 브라우저 Headers나 단순 JSON 객체가 아닌 어댑터입니다. has(name)·get(name)·entries()·toJSON()만 사용합니다. 이름은 대소문자를 구분하지 않으며 get의 없는 값은 undefined입니다. entries는 배열이므로 바로 map/filter할 수 있습니다. forEach·getAll·entries().next()·headers["host"]를 가정하지 마세요.
헤더 맵은 중복·원래 순서를 보장하는 wire 뷰가 아닙니다. 본문이 partial=true이면 전체 메시지 파싱·재구성에 사용하지 마세요. base64가 있으면 text만으로 바이너리를 대신하지 않습니다. bytes는 이미 숫자 배열이므로 atob·Buffer로 다시 디코딩하지 않아도 됩니다.
일반 TCP의 read-chunk를 완전한 메시지로 취급하지 마세요. DNS-over-TCP 입력은 길이 접두부가 제거된 DNS 메시지입니다. WebSocket은 frame.final과 opcode, 압축·표현·원본 가용성까지 확인하고 여러 프레임의 애플리케이션 메시지 재조립을 가정하지 않습니다.
반환값과 정확한 필드명
| 필드 | 계약 |
|---|---|
summary | 필수 string · 비어 있지 않은 결과 요약. 최대 2,000자 |
notes | string[] · 화면 진단. History 메모를 쓰지 않음 |
annotations | {target:{kind,id},text,color?}[] · history.annotate |
findings | {title,evidence:{kind,id},summary?,severity?,confidence?}[] · findings.create |
requestLab | {title,rawText,target,useTls,groupName?}[] · requestlab.write · 전송 전 초안 |
requests | {title,rawText,target,useTls}[] · network.send · 최대 1개 · 확인 후 송신 |
panels | 텍스트/표 Panel[] · ui.panels · 입력/버튼은 controls |
patches | {sourceId,sourceRevision,offset,deleteLength,insertBytes}[] · traffic.proposePatch |
return { summary: "…" }부터 시작하세요. History 메모는 notes가 아니라 annotations, Finding 대상은 target이 아니라 evidence, Request Lab 필드는 대소문자를 구분하는 requestLab입니다. 대상은 선택 입력의 kind/id를 그대로 사용하세요. 다른 연결의 ID를 만들지 않습니다.
JSON으로 직렬화할 수 있는 작은 값만 반환합니다. 함수·순환 참조·BigInt·undefined를 반환하지 마세요. 알 수 없는 필드는 Action이 되지 않습니다. data는 일반 스크립트의 영구 저장이나 자동 전송을 의미하지 않습니다.
권한 조합과 원자적 거부
| 실행 경로 | 허용 결과 |
|---|---|
| 관찰 / Observation | summary·notes·annotations·findings·requestLab·panels. 선언 권한 필요 |
| 보류 / Held | summary·notes·patches만. 다른 Action/문제 섞이면 전체 거부 |
| network.send | summary·notes·requests 최대 1개. 메모·패널·Patch 혼합 금지 |
| panel-action | summary·notes·panels만. notes는 화면 표시이며 History 쓰기가 아님 |
보류 Hook은 traffic.read + traffic.proposePatch가 필수입니다. traffic.applyPatch는 intercept-hook에서만 추가하며 열린 원본 초안에만 적용합니다. Forward·Drop은 스크립트 API가 아닙니다. network.send는 traffic.read가 있는 context-action만 허용합니다. storage.project는 context-action만 가능하고 network.send·traffic.proposePatch와 함께 선언할 수 없습니다.
일반 관찰 결과는 일부 잘못된 항목을 제외하고 유효한 항목을 표시할 수 있습니다. 반면 보류·전송·패널 콜백의 혼합/잘못된 결과는 전체 거부 경로가 있습니다. 정상처럼 보이는 일부 출력만으로 성공을 판단하지 말고 Problems·Runs의 issues도 확인하세요.
문자열 탐색 도우미
두 번째 인수 sdk의 text.firstMatch(), text.findAll(), text.findDistinct()는 제한된 문자열에서 일치를 찾는 동기 함수입니다. findDistinct는 중복 값을 건너뛰며 그룹 0은 전체 일치, 1~8은 캡처 그룹을 선택합니다. 반환 위치는 입력 문자열의 UTF-8 바이트 오프셋입니다. 미리보기나 디코딩한 문자열에서는 원본 패킷 바이트 위치와 다를 수 있습니다.
문자열은 최대 8 KiB, 정규식 패턴은 1~512 UTF-8 바이트, 여러 일치 결과의 한도는 1~16입니다. Go RE2 호환 정규식이므로 전후방 탐색·역참조를 쓰지 마세요. 잘못된 패턴은 TypeError이며, 사용자 지정 패턴은 오류를 처리하세요. 이 함수는 패킷을 추가로 읽거나 전송하지 않습니다. Plugin 백엔드의 동일한 계약도 참고하세요.
ws.storage 메서드와 실패 의미
available: 활성 context-action에 storage.project가 바인딩되었을 때만 true. Test·패널 콜백·관찰/보류 Trigger에는 false입니다.await get(key): JSON 값 또는 없는 키의 null. 저장된 null과 없는 키는 get만으로 구분하지 않습니다.await set(key,value): Core가 확인한 저장이면 true. JSON으로 표현할 수 없는 값은 사용하지 않습니다.await delete(key): 삭제 전 키가 있으면 true, 없으면 false.await keys(): 현재 네임스페이스의 정렬된 이름 배열. 다른 Script나 다른 프로젝트 키를 조회할 수 없습니다.
호출마다 프로젝트·저장 코드·활성 상태·권한·세션을 다시 검증합니다. 다시 열기·다른 이름 저장·Core 재시작은 이전 세션을 무효화합니다. 한 호출의 저장과 전체 Script 트랜잭션은 다릅니다. 나중의 오류/취소는 이미 확인된 쓰기를 되돌리지 않으며, 불확실한 쓰기는 자동 재시도하지 않습니다.
키 및 컨트롤 입력/버튼 ID에서 __proto__·constructor·prototype을 사용하지 마세요. 저장 JSON의 이스케이프 후 바이트도 용량 한도에 포함됩니다.
실행 한도와 결과 크기
- 설정: 시간 100–10,000ms, 메모리 8–128MB, 입력 16–4,096KB. 기본값은 1,500ms·32MB·512KB입니다. 메모리는 선언 예산이며 호스트 전체 프로세스 사용량과 같지 않습니다.
- 소스 512 KiB, Host 전체 결과 1 MiB. 결과 미리보기는 32,000자에서 잘리며 issues가 추가되므로 엄격한 명령에서는 실패할 수 있습니다. 최대값까지 채우지 말고 작은 결과를 만드세요.
- notes·annotations·findings·requestLab 목록은 각각 50개, 일반 text 8,192자, 제목 160자. 보류 Patch는 16개 범위·입출력 64 KiB, Request Lab/전송 rawText는 UTF-8 48 KiB입니다.
- 패널: 실행당 8개, 보관 32개 Script, text 8,192자, 표 12열·100행·셀 2,000자·행 JSON 64 KiB. inputs/actions 각각 최대 4개, actions 최소 1개, select 1–20개 고유 선택지.
- 입력 ID는 1–64자 영문·숫자·밑줄·하이픈. label 80자, 입력 값 512자, select 항목 160자. 초기 select 값은 options 안에 있어야 하며 입력과 버튼 ID는 서로 중복될 수 없습니다.
- 저장: 실행당 64회·8개 대기, 인수 24 KiB·값 응답 20 KiB, 32키·JSON 값 16 KiB·전체 64 KiB. 키는 영문·숫자·밑줄·점·하이픈 1–64자이며 프로토타입 관련 이름은 금지입니다.
런타임에서 사용할 수 없는 것
브라우저나 Node 예제를 그대로 붙여넣지 마세요. URL·TextEncoder·atob·btoa·Buffer·console·setTimeout·fetch·process·crypto는 이 Host에 없습니다. document/window·require/eval/Function·임의 import도 사용할 수 없습니다.
표준 JSON·문자열·배열·숫자·RegExp·Promise·Uint8Array로 제한된 처리를 작성하세요. 로그는 console.log 대신 반환 notes로 표시합니다. 외부 비동기 작업은 임의 Promise가 아니라 바인딩된 ws.storage만 사용합니다. 네트워크 전송은 requests 반환 후 제품 확인 경로로 수행합니다.
외부 편집기에서 타입 검사
선택 사항입니다. 아래 참조 선언을 sdk.d.ts로, 완성 예제를 script.ts로 저장하고 TypeScript가 이미 설치된 개발환경에서 tsc -p tsconfig.json을 실행합니다. DOM·Node 타입을 제외하면 Host에 없는 전역 API를 일찍 발견할 수 있습니다. 타입 통과는 권한·Scope·실제 적용 성공을 보증하지 않습니다.
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"lib": [
"ES2022"
],
"types": [],
"strict": true,
"noEmit": true
},
"files": [
"sdk.d.ts",
"script.ts"
]
}참조용 TypeScript 선언
아래는 이 버전 문서의 타입 계약입니다. 실행 코드나 설치할 npm SDK가 아닙니다. 일부 메타데이터는 합성/프로토콜 입력에 따라 없을 수 있도록 선택 필드로 표시했습니다. 실제 예제는 이 선언을 기준으로 DOM/Node 없는 ES2022 strict 타입 검사와 실제 Host 실행을 검증했습니다.
declare module "@wiresnare/sdk" {
export type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
export interface HeaderView {
has(name: string): boolean;
get(name: string): string | undefined;
entries(): [string, string][];
toJSON(): Record<string, string>;
}
export interface Selection {
kind: string; id: string; recordId?: string; frameSeq?: number;
}
export interface BodyPreview {
headers: HeaderView; text?: string; base64?: string;
partial?: boolean; totalBytes?: number;
}
export interface RawInput {
protocol: string; direction: "client-to-server" | "server-to-client";
bytes: number[]; text?: string; base64?: string;
transport?: "tcp" | "udp";
boundary?: "read-chunk" | "message" | "datagram";
messageBoundary?: boolean; partial?: boolean;
recordId?: string; capturedAt?: string; offset?: number; streamOffset?: number;
capturedBytes?: number; storedBytes?: number; totalBytes?: number; retainedSource?: string;
}
export interface WebSocketFrame {
sequence: number; capturedAt: string;
direction: "client-to-server" | "server-to-client";
opcode: number; opcodeName: string; final: boolean;
boundary: "frame"; messageBoundary: boolean;
payloadRepresentation: string; originalAvailable: boolean; compressed?: boolean;
inflatedBytes?: number; inflateError?: string;
decodedType?: string; decodedName?: string; decodedId?: string;
decodedFields?: Record<string, string>;
bytes: number[]; base64: string; text?: string;
capturedBytes: number; storedBytes: number; totalBytes: number; partial: boolean;
}
export interface HeldInput {
id: string; revision: string; kind: string; boundary: string;
protocol: string; messageBoundary: boolean; host: string; path: string;
bytes: number[]; base64: string; text?: string; byteLength: number;
source: "held-editor-draft" | "held-editor-representation"; partial: false;
}
export interface WireSnareContext {
selection: Selection;
event?: { trigger: string; capturedAt?: string; source?: string; invokedBy?: string; sourceTrigger?: string };
http?: {
request: BodyPreview & { method: string; url: string };
response?: BodyPreview & { status: number };
};
raw?: RawInput;
websocket?: { connection: { url: string; subprotocol?: string }; frame: WebSocketFrame };
intercept?: HeldInput;
panelAction?: { panelId: string; actionId: string; values: Record<string, string> };
}
export interface WireSnareSDK {
readonly text: {
firstMatch(text: string, pattern: string, ignoreCase?: boolean): { match: string; groups: string[] } | null;
findAll(text: string, pattern: string, ignoreCase?: boolean, limit?: number): { match: string; groups: string[]; startByte: number; endByte: number }[];
findDistinct(text: string, pattern: string, ignoreCase?: boolean, limit?: number, group?: number): { value: string; match: string; startByte: number; endByte: number }[];
};
readonly storage: {
readonly available: boolean;
get(key: string): Promise<Json>;
set(key: string, value: Json): Promise<boolean>;
delete(key: string): Promise<boolean>;
keys(): Promise<string[]>;
};
}
export type PanelInput = { id: string; label: string; value: string } &
({ kind: "text" } | { kind: "select"; options: string[] });
export interface PanelControls {
inputs: PanelInput[];
actions: { id: string; label: string }[];
}
export type Panel = { id: string; title: string; controls?: PanelControls } & (
{ kind: "text"; text: string } |
{ kind: "table"; columns: string[]; rows: (string | number | boolean | null)[][] }
);
export interface BytePatch {
sourceId: string; sourceRevision: string;
offset: number; deleteLength: number; insertBytes: number[];
}
export interface HttpProposal {
title: string; rawText: string; target: string; useTls: boolean;
}
export interface ScriptResult {
summary: string; notes?: string[];
annotations?: { target: Selection; text: string; color?: "blue" | "green" | "amber" | "red" | "purple" | "gray" }[];
findings?: { title: string; evidence: Selection; summary?: string; detail?: string;
severity?: "critical" | "high" | "medium" | "low" | "info"; confidence?: string }[];
requestLab?: (HttpProposal & { groupName?: string })[];
requests?: HttpProposal[];
panels?: Panel[]; patches?: BytePatch[];
data?: Json;
}
}