Query files (pgq)
A .pgq file is a TypeScript module of Cypher queries, built up from two kinds of object:
- A selector (
PGSelector) is a set of nodes, such as "every URL read" or "everyinnerHTMLwrite". On its own a selector isn't a finding, so query packs keep their selectors in library files and share them between rules. - A rule (
PGRule) adds a severity and a message, and lists the selectors whose rows are its findings.
Selectors describe both ends of a flow: sources, such as URL reads, and sinks, such as innerHTML writes. Taint flow belongs to the sink selector: its from names the source selectors, and it keeps only the sinks that a source value reaches. A selector can also describe something in between, such as message listeners, which another selector consumes through uses. The rule does no matching itself. It labels the selectors whose rows are findings, usually one sink selector with from, and gives them a severity and a message.
taintwire loads .pgq files in a sandbox, validates them and runs them against a PookieGraph (.pg). js-recon runs them with js-recon taintwire analyze, and taintwire-queries is the public query pack.
Example
A library file (lib/sources.pgq) has named exports only:
import type { PGSelector } from "@js-recon/taintwire";
const AT = "n.file AS file, n.line AS line, n.col AS col";
export const urlRead: PGSelector = {
cypher: {
query: `MATCH (n:MemberExpression)-[:SON {key: 'property'}]->(p:Identifier), (n)-[:SON {key: 'object'}]->(o)
WHERE p.name IN ['hash', 'search', 'href'] AND o.name = 'location'
RETURN n.id AS id, p.name AS kind, ${AT}`,
},
};
A rule file (rules/dom_xss_url.pgq) default-exports a rule, or a list of rules. Here the sink queries come from a shared sink set, and the rule adds one query of its own:
import type { PGRule } from "@js-recon/taintwire";
import { urlRead } from "../lib/sources.pgq";
import { htmlSinks } from "../lib/sinks.pgq";
export default {
id: "dom_xss_url",
name: "DOM XSS: URL value written as HTML",
severity: "high",
message: "URL value reaches an HTML sink",
return: [
{
from: urlRead,
mode: "deep",
maxHops: 8,
cypher: [
...htmlSinks,
{
query: `MATCH (c:CallExpression)-[:SON {key: 'callee'}]->(:MemberExpression)-[:SON {key: 'property'}]->(p:Identifier), (c)-[a:SON {key: 'arguments'}]->(n)
WHERE p.name = 'insertAdjacentHTML' AND a.idx = 1
RETURN n.id AS id, p.name AS kind, n.file AS file, n.line AS line, n.col AS col`,
},
],
},
],
} satisfies PGRule;
The taintwire-queries pack writes these fragments with short aliases instead, such as ${pga.methodCall()} and ${pga.ret("p.name")}, and keeps its shared sink sets in lib/sinks.pgq. PookieGraph aliases (pga) lists them.
Types
type PGSeverity = "info" | "low" | "medium" | "high" | "critical";
interface PGCypher {
query: string; // must RETURN id (plus file, line, col in return/from selectors); may RETURN kind
}
interface PGSelector {
cypher: PGCypher | PGCypher[];
uses?: Record<string, PGSelector>;
from?: PGSelector | PGSelector[];
mode?: "strict" | "lenient" | "deep";
maxHops?: number;
interceptors?: PGCypher[];
confinements?: PGCypher[];
exclusions?: PGCypher[];
}
interface PGRule {
id: string;
name: string;
severity: PGSeverity;
message: string;
description?: string;
author?: string;
tags?: string[];
return: (PGSelector | PGCypher)[];
}
| Field | Meaning |
|---|---|
cypher | The queries. A list runs every variant, concatenates the rows and drops duplicate ids. Lists are useful because every start pattern should be labelled: a string constant, for example, needs a StringLiteral variant and a TemplateLiteral variant. |
uses | $name in a query is the list of ids of that selector's rows. This is how you chain selectors: message handlers to listener functions to event.data reads. If any selector in uses has no rows, this selector has none either, and its queries don't run. |
from | Keep only the rows that a value from one of these selectors flows into. Each finding then carries the source row and the number of hops. |
mode | How from flows are followed. strict follows FLOWS_TO, ARGUMENT_TO and RETURNS_TO from the source node to the sink node. lenient also widens both ends through up to 3 wrapping expressions, such as location.hash.slice(1) or el.innerHTML = tpl(x). deep (the default) repeats lenient for 4 rounds, which gets past opaque calls such as new URLSearchParams(location.search).get("q"). |
maxHops | The longest flow kept. Defaults to 8. |
interceptors | What could stop a value at this sink. The queries run once per finding of a selector in return that has from, and their rows go on the finding as interceptors. See Interceptors. |
confinements | How the value ends up in this sink: the fixed structure around the tainted part, such as a same-origin path or a query string. Run like interceptors, and their rows go on the finding as confinements. See Confinements. |
exclusions | What makes a finding moot: a flow that can't run, such as a sink in a fallback branch for browsers without JSON. Run like interceptors, with the same parameters; any row drops the finding for that source. See Exclusions. |
return | A rule's findings: the union of these selectors' rows, without duplicates. A bare PGCypher counts as a selector of one query. |
Every query must RETURN id. A selector whose rows become findings (in return) or sources (in from) must also return file, line, col; one used only through uses can return just id. A missing column is a runtime error for its rule. A label with no table in the graph (an AST type that never occurs in it) gives no rows, not an error.
Interceptors
An interceptor is something on the path that could stop a value from reaching the sink in a usable form: a guard condition, or a sanitizer. A sink selector lists them in interceptors, because they belong to that sink. Each query gets these parameters:
| Parameter | Value |
|---|---|
$sink | The finding's node id. |
$source | The source node id. |
$flow | The source, the expressions wrapping it (as lenient widens a source), and every node they reach. |
$found | The ids that the selector's earlier interceptor queries returned, in order. |
$path | The node ids from the source to the sink, in order, as for confinements. Traced only when a query names it. |
An interceptor query must RETURN id, file, line, col, kind, text. Rows are deduplicated and sorted by position. $found lets a query build on the earlier ones: one query finds the if tests that read the tainted value, and a later one looks inside them for x.indexOf("http:") > -1. The taintwire-queries pack's lib/interceptors.pgq is a full set.
export const sink: PGSelector = {
from: urlRead,
interceptors: [
{
query: `MATCH (g:IfStatement)-[:SON {key: 'consequent'}]->(br)-[:SON*0..30]->(k), (g)-[:SON {key: 'test'}]->(t)
WHERE k.id = $sink AND EXISTS { MATCH (t)-[:SON*0..30]->(x) WHERE x.id IN $flow }
RETURN t.id AS id, 'if' AS kind, 'must be true' AS text, t.file AS file, t.line AS line, t.col AS col`,
},
],
cypher: [/* ... */],
};
$flow follows one widening round, not the four of deep, so a value that passes two opaque calls before the condition isn't in it.
$path is for sanitizers: $flow holds every node the source reaches, so a call such as Number(x) in it may sit on a different branch than the sink's value. A query that requires the call on $path (or between two consecutive $path nodes, where the flow jumped over a call that wraps the value) only reports a sanitizer the value really passes. The pack's lib/interceptors.pgq reports guards (if, ternary, and-or, early-exit, switch, parse, string), checks on the tainted value in them (check), and sanitizers on $path (sanitizer: number, html, url-encoded, regex-escaped, fixed alternatives).
Confinements
A confinement describes how the value ends up in the sink: the fixed structure around the tainted part that limits what it can do. "/login?next=" + v puts v in a same-origin query string, and $(`#item-${v}`) makes it part of a selector that can't start with <. An interceptor is a condition on the path or a change to the value; a confinement is a position. A sink selector lists them in confinements. They run once per finding, like interceptors, with these parameters:
| Parameter | Value |
|---|---|
$sink | The finding's node id. |
$source | The source node id. |
$flow | Every node the source reaches, as deep follows it: a source behind new URLSearchParams(location.search).get("q") reaches the same nodes as the rule. |
$path | The node ids from the source to the sink, in order. When the flow ends inside the sink expression, the path closes with the expressions up to the sink. |
A confinement query must RETURN id, file, line, col, kind, text. Rows are deduplicated and sorted by position. $path lets a query look at a string join anywhere on the way, not only at the sink: list_position($path, n.id) gives a node's place on it, so a query can pick the join nearest the sink. The taintwire-queries pack's lib/confinements.pgq reports path, query, fragment, origin, selector and sink confinements.
export const sink: PGSelector = {
from: urlRead,
confinements: [
{
query: `MATCH (c)-[:SON {key: 'callee'}]->(m)-[:SON {key: 'property'}]->(p), (c)-[a:SON {key: 'arguments'}]->(k)
WHERE k.id = $sink AND a.idx = 2 AND p.name IN ['pushState', 'replaceState']
RETURN c.id AS id, 'sink' AS kind, p.name + ': same-origin URLs only' AS text, c.file AS file, c.line AS line, c.col AS col`,
},
],
cypher: [/* ... */],
};
Writing pgq files
- A
.pgqfile is TypeScript. Its types are stripped as in Node's type stripping, so the TypeScript-only features that would need code generation (enum,namespace, parameter properties) aren't allowed. - A
.pgqfile may import only other.pgqfiles from the same query pack. A pack is the nearest folder above the files that has apackage.json. Import taintwire's types withimport type, which is erased; a plainimportof@js-recon/taintwireis rejected. - Helper functions are fine, for example one that builds the
StringLiteralandTemplateLiteralvariants of a query, or the pga aliases that expand to query fragments. What a file exports must be data, though: plain objects, arrays, strings, numbers and booleans. A function in an exported rule is an error. A selector object shared between rules stays one object, so it's evaluated once per run. console.logoutput from a pgq file goes to stderr.- To have editors treat
.pgqas TypeScript, add"files.associations": { "*.pgq": "typescript" }to.vscode/settings.json.
Sandbox
A .pgq file is code, so loadPgq() evaluates it in a separate Node process:
- The process runs under Node's permission model with read access to the query pack only. That denies file writes, child processes, worker threads and native addons.
- An import hook allows only
.pgqfiles inside the pack.node:builtins and npm packages are rejected, including through dynamicimport(). fetch,WebSocket,EventSource,process.getBuiltinModule,process.killandprocess.bindingare removed before any query code runs.- The process gets 256 MB of heap and 30 seconds by default.
On Node 22 and 24 the permission model doesn't restrict the network. There, the import hook and the removed globals are the network barrier. On Node 25 and later, the permission model blocks the network too.
Loading .pgq files needs Node 22.15 or newer. On Node 22.18 or newer, TypeScript type stripping is enabled by default.
API
These are exported from @js-recon/taintwire. loadPgq() is Node-only; the rest also work from @js-recon/taintwire/browser.
loadPgq()
loadPgq(files: string[], opts?: { root?: string; timeoutMs?: number }): Promise<{ rules: PGRule[]; errors: string[] }>;
Evaluates the files in the sandbox and validates each file's default export. A file without a default export is a library: it contributes no rules, but its errors are still reported. Rules from a file with any error are left out. Every message in errors starts with the file path. A rule id that two files share is an error. root overrides the query pack folder.
Exclusions
An exclusion drops a finding whose flow can't run: the sink sits in the branch a current browser never takes, or inside a library entry point the app never calls. A sink selector lists them in exclusions. Each query runs once per finding with the interceptor parameters ($sink, $source, $flow, $found, $path) and must RETURN id, file, line, col, kind, text. If any query returns a row, the finding is dropped for that source; another source that reaches the same sink can still report it. The pack's lib/env.pgq drops sinks in fallbacks for missing browser features (X.JSON ? X.JSON.parse(r) : eval(r)), under old-IE tests, and inside a .load(url) implementation that nothing calls with a URL.
Use exclusions only for flows that can't run. A condition an attacker might meet belongs in interceptors, where the finding stays visible.
validatePgq()
validatePgq(input: unknown): string[];
Checks a rule, or a list of rules, that you built yourself. An empty array means the input is valid. It checks:
- the field types and the severity
- that queries are non-empty
- that
maxHopsis a non-negative integer, and thatmode,maxHops,interceptors,confinementsandexclusionsonly appear withfrom - that an interceptor or exclusion query uses no parameters other than
$sink,$source,$flow,$foundand$path, and a confinement query none other than$sink,$source,$flowand$path - that every
$namein a query has an entry inuses(names inside strings and comments don't count) - that no selector depends on itself through
usesorfrom - that rule ids are unique
checkPgqCypher()
checkPgqCypher(graph: PookieGraph, rules: PGRule[]): Promise<string[]>;
Prepares every query against graph and returns the ones that don't compile, for example syntax errors. An error about a table that doesn't exist in graph is ignored, because that label may exist in another graph.
runPgq()
runPgq(
graph: PookieGraph,
rules: PGRule[],
onRule?: (done: number, rule: PGRule) => void
): Promise<{ findings: PgqFinding[]; errors: { ruleId: string; message: string }[] }>;
interface PgqFinding {
ruleId: string;
severity: PGSeverity;
message: string;
id: string;
file: string;
line: number;
col: number;
kind?: string;
source?: { id: string; file: string; line: number; col: number; kind?: string };
hops?: number;
interceptors?: { id: string; file: string; line: number; col: number; kind: string; text: string }[];
confinements?: { id: string; file: string; line: number; col: number; kind: string; text: string }[];
}
Runs rules on graph. Each selector is evaluated once per call, however many rules use it. A rule that fails goes into errors, and the remaining rules still run. onRule is called after each rule, failed or not, with the number of rules done so far. graph.code(finding.id) returns the finding's source text.
For a big graph, open the saved file read-only: PookieGraph.open("app.pg", { readOnly: true }).