Pentest JS probe format
Applies to the JavaScript probes cxg pentest runs — not to .js
templates in a template directory. Those are loaded by the javascript
template engine and use the
annotation header schema.
A probe written to this schema will not load as a template, and a template
will not run as a probe.
A probe is one JavaScript file defining async function cxgProbe(cxg). The
pipeline evaluates the file inside a page that is already authenticated as
one of the identities under test, calls that function, and reads the array
it returns.
The contract, in the pipeline’s own words
Section titled “The contract, in the pipeline’s own words”From pentest/js_engine.py:
JS template engine — runs JavaScript probe templates inside authenticated browser contexts.
Template contract (copy-paste-able into DevTools console, ALSO runnable by cxg):
// @id: my-probe // @vuln_class: idor // @severity: high // @requires_auth_count: 2 // @description: <one-liner> async function cxgProbe(cxg) { // cxg.profile -> {name, label, index} // cxg.profiles -> [{name, label, index}, ...] all identities in this run // cxg.url(path) -> full target URL // cxg.fetch(path, opts) -> fetch in THIS identity (auto-CSRF on mutations) // cxg.fetchAs(idx, path, opts) -> fetch in another identity (idx into cxg.profiles) const findings = []; // ... probe logic ... return findings; // [{id, severity, confirmed, endpoint, description, evidence, payload}] }
For DevTools console fallback (no cxg bridge), the template can detect: const cxg = (typeof window.__cxg !== 'undefined') ? window.__cxg : { fetch, url:(p)=>p, profile:{name:'console',label:'console',index:0}, profiles:[], fetchAs:(i,p,o)=>fetch(p, {...o, credentials:'include'}) };
cxg's runner wires up the real `window.__cxg` and the cxgProbe is called automatically.Header annotations
Section titled “Header annotations”Read from the whole file — not a fixed window — with one regex, and only
// comments count:
re.compile(r"//\s*@(\w+):\s*(.*)")Required: @id, @vuln_class. A probe
missing one is rejected before it runs, unlike a template, where a
missing annotation only warns.
Every annotation the pipeline reads, and what it uses when one is absent:
| Annotation | Absent → |
|---|---|
@boundary_claim_key |
unset |
@destructive_priority |
0 |
@exposure_asset |
unset |
@exposure_claim_key |
unset |
@exposure_file |
unset |
@exposure_line |
unset |
@exposure_threat |
unset |
@guardlink_threat |
unset |
@id |
the filename without its extension |
@model_vuln_class |
unset |
@protected_endpoint |
unset |
@provides |
`` |
@requires_artifact |
`` |
@requires_capability |
unset |
@route_access |
unset |
@route_access_basis |
unset |
@severity |
medium |
@threat_id |
unset |
@vuln_class |
unknown |
@vuln_class
Section titled “@vuln_class”Required. One of these is expected; another value warns and still runs:
idor, csrf, xss, ssrf, command_injection, session_replay, credential_stuffing, rate_limit_bypass, privilege_escalation, sensitive_data_exposure, metrics_info_disclosure, clickjacking, content_sniffing, auth_api, missing_authentication, denial_of_service, cors_misconfiguration, host_header_injection, request_smuggling, http_desync, websocket_authz, race_condition, open_redirect, sql_injection, nosql_injection, ldap_injection, xxe, path_traversal, ssti, deserialization, mass_assignment, cache_poisoning, sse_authz, jwt_attack, graphql_abuse, unrestricted_upload, oauth_flow_abuse, user_enumeration, ip_header_bypass, business_logic.
@requires_capability
Section titled “@requires_capability”One of http, ipc, host_fs, http_raw, attacker_origin, dom, websocket, raw_socket, sse, dom_frame, grpc, mail, totp, ask, naming what
the probe needs of the surface it runs against. A probe demanding a
capability the surface lacks is skipped rather than run — an undefined
namespace would throw, and a throw is indistinguishable from a genuine
refutation.
Calling cxg.ipc.* without declaring @requires_capability: ipc is a
rejection, not a warning.
@requires_auth_count
Section titled “@requires_auth_count”How many identities the probe needs. A value that is not an integer is a rejection; an integer outside 1–5 warns.
How the probe is invoked
Section titled “How the probe is invoked”The file is evaluated inside this wrapper, in the page. %s is where the
probe’s own source is substituted:
async () => { try { %s if (typeof cxgProbe !== 'function') { return {__cxg_err: 'template did not define async function cxgProbe(cxg)'}; } window.__cxg.identities = Object.fromEntries( Object.entries(%s).map(([role, index]) => [role, window.__cxg.profiles[index]])); const result = await cxgProbe(window.__cxg); return {__cxg_ok: true, findings: result || []}; } catch (e) { return {__cxg_err: String(e && e.stack || e), __cxg_primitive_argument_error: e && e.name === 'CxgPrimitiveArgumentError'}; }}A file that does not define cxgProbe is rejected by the validator before
this point. A cxgProbe that throws is reported and contributes no
findings.
What cxg hands the probe
Section titled “What cxg hands the probe”The bridge, installed as a page init script so it survives navigation, from
pentest/targets/bridge.py:
window.__cxg = { profile: PROFILE, jwt: cxgJwt, race: cxgRace, raceAs: cxgRaceAs, profiles: PROFILES, // Which identity is privileged, decided from operator-set --tier rather // than from position in `profiles`. null when the roster cannot be ranked // (no --tier on some identity, or a tie at that extreme) — in that case // report outcome 'unevaluated'; do NOT fall back to an index. lowestPrivilege: LOWEST_PRIVILEGE, highestPrivilege: HIGHEST_PRIVILEGE, url: (p) => p.startsWith('http') ? p : TARGET + (p.startsWith('/') ? p : '/' + p), fetch: cxgFetch, fetchAs: cxgFetchAs, // THIS identity's raw bearer token, or null when the application // does not use one. Exposed so a jwt_attack template can decode it // with cxg.jwt.decode(cxg.authToken), re-sign a modified payload and // send the forgery with an explicit Authorization header — the // header cxg would otherwise have filled in with the genuine token. authToken: AUTH_TOKEN, // ANOTHER identity's token, for a cross-identity forgery or replay // (sign a token claiming to be identity A, send it as identity B). // null when that identity has none or the index is out of range. authTokenAs: (idx) => (AUTH_TOKENS[idx] === undefined ? null : AUTH_TOKENS[idx]), // Cookie API (HttpOnly-aware — uses Playwright cookie jar, not document.cookie) getCookies: cxgGetCookies, getCookiesAs: cxgGetCookiesAs, getCookie: cxgGetCookie, setCookies: cxgSetCookies, addCookies: cxgAddCookies, clearCookies: cxgClearCookies, // Out-of-band callback API for blind-vuln confirmation (SSRF, blind SQLi, // blind XXE, blind cmd injection). host is null when --oast was not // passed; pollable is false unless cxg can read interactions back, and // only a poll() that RETURNS an interaction confirms anything. oast: cxgOast,};Every request must go through cxg.fetch or cxg.fetchAs. A raw fetch(
is a rejection: it bypasses CSRF injection, the scope check, and the audit
log.
On a desktop surface
Section titled “On a desktop surface”An Electron substrate adds an IPC namespace, from
pentest/targets/electron.py:
window.__cxg.ipc = { invoke: (channel, ...args) => window.__cxg_ipc_call(INDEX, channel, args), invokeAs: (idx, channel, ...args) => window.__cxg_ipc_call(idx, channel, args), channels: () => CHANNELS.slice(),};A raw ipcRenderer.invoke(...) is a rejection for the same reason a raw
fetch( is.
What the probe returns
Section titled “What the probe returns”cxgProbe returns an array of plain objects. Each one becomes a finding
with these fields:
| Field | Type |
|---|---|
id |
str |
vuln_class |
str |
severity |
str |
confirmed |
bool |
target |
str |
endpoint |
str |
description |
str |
evidence |
dict |
payload |
Optional[str] |
hypothesis_id |
Optional[str] |
threat_id |
Optional[str] |
annotation |
Optional[dict] |
asset |
Optional[str] |
threat |
Optional[str] |
claim_key |
Optional[str] |
boundary_claim_key |
Optional[str] |
template_id |
Optional[str] |
model_vuln_class |
Optional[str] |
oracle_routed_from |
Optional[str] |
original_claim |
Optional[dict] |
triage |
str |
triage_reason |
str |
reason_kind |
str |
proof_status |
ProofStatus |
Which keys are read off the object, and what each one falls back to when the
probe omits it — tpl is the probe’s own header:
def _finding_from_dict(self, f: dict, tpl: JsTemplate) -> Finding: # Normalize the same dict triage reads, before selecting any proof predicate. model_class = f.get("vuln_class") f["model_vuln_class"] = (model_class if model_class and model_class != tpl.vuln_class else tpl.meta.get("model_vuln_class")) f["vuln_class"] = tpl.vuln_class return Finding( id=f.get("id") or f"{tpl.vuln_class}-finding", vuln_class=tpl.vuln_class, model_vuln_class=f.get("model_vuln_class"), severity=f.get("severity") or tpl.severity, confirmed=bool(f.get("confirmed", False)), target=self.target, endpoint=f.get("endpoint", ""), description=f.get("description", ""), evidence=f.get("evidence", {}) or {}, payload=str(f.get("payload")) if f.get("payload") is not None else None, hypothesis_id=tpl.id, threat_id=tpl.threat_id, # @comment -- "The exposure this probe was testing, copied off the template that # carries it. Read here rather than looked up from the run's hypotheses because the # header is the only carrier a --template-dir replay has: that path never loads a # SARIF at all, and a finding produced there must still be able to say what it tested." annotation=tpl.exposure_annotation, asset=tpl.exposure_asset, threat=tpl.exposure_threat, claim_key=tpl.exposure_claim_key, boundary_claim_key=tpl.boundary_claim_key, template_id=tpl.id, )confirmed: true with nothing to show for it is not believed:
_has_probe_evidence in pentest/mutator.py
ignores empty values and _-prefixed bookkeeping keys, and triage downgrades
the finding.
What the validator refuses to run
Section titled “What the validator refuses to run”From pentest/validator.py:
Pre-execution validator for AI-generated JS pentest templates.
Catches templates that would: - silently misbehave (no @id, no @vuln_class, no cxgProbe function) - violate the contract (raw fetch() instead of cxg.fetch — credentials lost) - target destructive routes (regex check on string literals in the source) - exceed declared request budget
Static analysis is intentionally conservative — better to flag a benign templatethan to run a bad one. The runtime ScopeGuard provides the backstop.Rejections stop the probe from running at all; warnings do not. More than 12 fetch call sites combined with a loop warns. The checks in full, in the order they run:
Show validate()
def validate(source: str, destructive_ok: bool = False) -> ValidationResult: errors: list[str] = [] warnings: list[str] = [] meta = parse_meta(source)
# 1. Required metadata for k in REQUIRED_META: if k not in meta: errors.append(f"missing required metadata: @{k}")
if "vuln_class" in meta and meta["vuln_class"] not in ALLOWED_VULN_CLASSES: warnings.append(f"unusual vuln_class '{meta['vuln_class']}' (not in standard set)")
# @comment -- "Warns rather than rejects on an unrecognised @requires_capability: the capability set grows as new substrates are added, and a typo here should not hard-fail a template the way a missing @id does." required_capabilities = parse_capability_names(meta.get("requires_capability", "")) for capability in sorted(required_capabilities - ALLOWED_CAPABILITIES): warnings.append( f"unusual requires_capability '{capability}' " f"(known: {', '.join(sorted(ALLOWED_CAPABILITIES))})")
# @comment -- "Sanity-checks the two chaining headers. A rejection rather than a warning: the engine's dependency scheduler orders the entire run off these declarations and the router matches every runtime cxg.chain.put/get against them verbatim, so a name the header spells one way and the call spells another is a chain that silently never forms — the provider runs, puts nothing the consumer can read, and the consumer is skipped as though the application had defeated it. A loud error the operator can fix is strictly better than a coverage gap that reads as a result." # @comment -- "Only the SHAPE is checked, never the vocabulary: an artifact name is a free-form key a template invents for the fact it discovered, so an unrecognised name is legal and must stay legal. An allowlist here would reject exactly the novel chains this feature exists to express." for key in _CHAIN_META_KEYS: if key not in meta: continue names = parse_artifact_names(meta[key]) if not names: errors.append( f"@{key} is present but names no artifact. Either name at least one " f"artifact (comma-separated) or remove the header — an empty " f"declaration means the engine schedules nothing around this template " f"while its cxg.chain calls are refused as undeclared.") continue for name in names: if not _ARTIFACT_NAME_RX.match(name): errors.append( f"invalid artifact name '{name[:60]}' in @{key}: artifact names " f"must match [a-z0-9_]{{1,40}}. The name is matched verbatim " f"against every cxg.chain.put/get, so a name that differs by a " f"character is a chain that never forms.")
# @comment -- "Hard-rejects raw ipcRenderer calls: they bypass cxg.ipc.invoke/invokeAs and therefore the scope budget and audit log, mirroring the raw fetch() ban below." if _RAW_IPC_PATTERN.search(source): errors.append( "raw ipcRenderer call detected. Templates must use cxg.ipc.invoke(channel, ...) " "or cxg.ipc.invokeAs(idx, channel, ...) — raw ipcRenderer bypasses the scope " "budget and the audit log.")
# @comment -- "Missing namespace declarations are advisory because JsTemplate derives the requirements from this same detector. The capability gate still skips unsupported substrates. Raw fetch and ipcRenderer calls remain errors because they bypass the audit and scope controls." for capability in sorted(derive_namespace_capabilities(source) - required_capabilities): label = _CAPABILITY_LABELS.get(capability, f"cxg.{capability}") warnings.append( f"template uses {label} without '@requires_capability: {capability}'; " f"the engine derives it from the source, but declaring it is clearer")
# 2. Must define cxgProbe if not has_probe_entrypoint(source): errors.append("missing required `async function cxgProbe(cxg)` definition")
# 3. Native network APIs bypass engine scope, budgets, CSRF and auditing. errors.extend(_literal_http_argument_errors(source)) network_source = _network_source(source) for pattern, primitive in _NATIVE_NETWORK: match = pattern.search(network_source) if match: errors.append(f"native network access ({match.group()}) " f"is forbidden; use {primitive} instead")
# 4. Destructive literals if not destructive_ok: for pat in _DESTRUCTIVE_LITERAL_PATTERNS: m = re.search(pat, source, re.IGNORECASE) if m: errors.append( f"template contains destructive endpoint literal: {m.group(0)[:80]} — " f"pass --destructive-ok to allow" )
# 5. Cheap explosion heuristic: many fetch sites + a loop = potential runaway callsite_count = len(_FETCH_CALLSITES.findall(source)) has_loop = bool(_LOOP_PATTERN.search(source)) if callsite_count > _MAX_FETCH_CALLSITES and has_loop: warnings.append( f"template has {callsite_count} fetch call sites AND a loop — potential request flood. " f"ScopeGuard budget will halt it, but consider rewriting." )
try: identity_requirements(meta) except ValueError as exc: errors.append(str(exc))
# 6. requires_auth_count sanity. 0 is VALID and means an anonymous-capable probe — # it needs one transport, not an authenticated identity — so it is accepted without a # warning; a negative count is nonsense and rejected; >5 is accepted but flagged as # unusual. Default (header absent) stays 1 via JsTemplate.requires_auth_count. if "requires_auth_count" in meta: try: n = int(meta["requires_auth_count"]) if n < 0: errors.append(f"requires_auth_count must be >= 0, got: {n}") elif n > 5: warnings.append(f"requires_auth_count={n} is unusual; prefer requires_identities for named roles") except ValueError: errors.append(f"requires_auth_count must be an int, got: {meta['requires_auth_count']}")
return ValidationResult(ok=not errors, errors=errors, warnings=warnings, meta=meta)
