@flytedesk/app-kit 11.1.0 → 11.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ /**
2
+ * An in-process memo of at most `maxEntries` values by key, synchronous. Reading a key makes it the most recently
3
+ * used; storing a new key past the bound drops the one used longest ago. For answers that depend only on their key
4
+ * (a dry run's verdict on one SQL text, what one compiler-written text parses to), so a stream of distinct keys can
5
+ * never grow it without limit.
6
+ */
7
+ export declare class BoundedLru<V> {
8
+ private readonly maxEntries;
9
+ private readonly entries;
10
+ constructor(maxEntries: number);
11
+ /** The value kept for `key`, now the most recently used, or undefined. */
12
+ get(key: string): V | undefined;
13
+ /** Keeps `value` for `key` as the most recently used, dropping the entry used longest ago past the bound. */
14
+ set(key: string, value: V): void;
15
+ delete(key: string): void;
16
+ /** Every key held with its value, the one used longest ago first. Iterating does not count as a use. */
17
+ [Symbol.iterator](): IterableIterator<[string, V]>;
18
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * An in-process memo of at most `maxEntries` values by key, synchronous. Reading a key makes it the most recently
3
+ * used; storing a new key past the bound drops the one used longest ago. For answers that depend only on their key
4
+ * (a dry run's verdict on one SQL text, what one compiler-written text parses to), so a stream of distinct keys can
5
+ * never grow it without limit.
6
+ */
7
+ export class BoundedLru {
8
+ maxEntries;
9
+ entries = new Map();
10
+ constructor(maxEntries) {
11
+ this.maxEntries = maxEntries;
12
+ if (!Number.isInteger(maxEntries) || maxEntries < 1) {
13
+ throw new Error(`A bounded memo holds at least one entry, not ${maxEntries}`);
14
+ }
15
+ }
16
+ /** The value kept for `key`, now the most recently used, or undefined. */
17
+ get(key) {
18
+ if (!this.entries.has(key))
19
+ return undefined;
20
+ const value = this.entries.get(key);
21
+ this.entries.delete(key);
22
+ this.entries.set(key, value);
23
+ return value;
24
+ }
25
+ /** Keeps `value` for `key` as the most recently used, dropping the entry used longest ago past the bound. */
26
+ set(key, value) {
27
+ this.entries.delete(key);
28
+ this.entries.set(key, value);
29
+ if (this.entries.size > this.maxEntries)
30
+ this.entries.delete(this.entries.keys().next().value);
31
+ }
32
+ delete(key) {
33
+ this.entries.delete(key);
34
+ }
35
+ /** Every key held with its value, the one used longest ago first. Iterating does not count as a use. */
36
+ [Symbol.iterator]() {
37
+ return this.entries[Symbol.iterator]();
38
+ }
39
+ }
40
+ //# sourceMappingURL=boundedLru.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"boundedLru.js","sourceRoot":"","sources":["../../src/bigquery/boundedLru.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,OAAO,UAAU;IAGQ;IAFZ,OAAO,GAAG,IAAI,GAAG,EAAa,CAAC;IAEhD,YAA6B,UAAkB;QAAlB,eAAU,GAAV,UAAU,CAAQ;QAC7C,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,UAAU,GAAG,CAAC,EAAE,CAAC;YACpD,MAAM,IAAI,KAAK,CAAC,gDAAgD,UAAU,EAAE,CAAC,CAAC;QAChF,CAAC;IACH,CAAC;IAED,0EAA0E;IAC1E,GAAG,CAAC,GAAW;QACb,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,OAAO,SAAS,CAAC;QAC7C,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAE,CAAC;QACrC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACzB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC7B,OAAO,KAAK,CAAC;IACf,CAAC;IAED,6GAA6G;IAC7G,GAAG,CAAC,GAAW,EAAE,KAAQ;QACvB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACzB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC7B,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,UAAU;YAAE,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAM,CAAC,CAAC;IAClG,CAAC;IAED,MAAM,CAAC,GAAW;QAChB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAC3B,CAAC;IAED,wGAAwG;IACxG,CAAC,MAAM,CAAC,QAAQ,CAAC;QACf,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;IACzC,CAAC;CACF"}
@@ -0,0 +1,81 @@
1
+ import type { BigQueryReadClient } from "./client.js";
2
+ import type { BigQueryParamTypes, DryRunEstimate } from "./types.js";
3
+ export declare class QueryRefusedError extends Error {
4
+ readonly reason: "not_select" | "table_not_allowed" | "tables_unknown";
5
+ constructor(reason: "not_select" | "table_not_allowed" | "tables_unknown", message: string);
6
+ }
7
+ export interface GuardedQuery {
8
+ sql: string;
9
+ params: Record<string, unknown>;
10
+ /** Each parameter's BigQuery type: a name, or the one-element list `["STRING"]` for an array parameter. */
11
+ types: BigQueryParamTypes;
12
+ labels: Record<string, string>;
13
+ }
14
+ export interface GuardedQueryResult<T> {
15
+ rows: T[];
16
+ /** The dry run's estimate — what the job was allowed to scan. */
17
+ bytesProcessed: number;
18
+ }
19
+ export interface GuardedRunOptions {
20
+ /** What a failure of the dry run in front of the job is thrown as. Without it the
21
+ * failure is thrown as it is. A failure of the job itself is never passed through
22
+ * this: it is how a caller tells "BigQuery rejected this query" (nothing ran) from
23
+ * "BigQuery failed while running it". */
24
+ dryRunFailure?: (error: unknown) => unknown;
25
+ }
26
+ export interface GuardedBigQuery {
27
+ run<T = Record<string, unknown>>(query: GuardedQuery, options?: GuardedRunOptions): Promise<GuardedQueryResult<T>>;
28
+ /** The same allowlist, statement-type and budget check, without running the job: what a
29
+ * validation that must not spend a query answers with. */
30
+ dryRun(query: Pick<GuardedQuery, "sql" | "params" | "types">, options?: GuardedDryRunCallOptions): Promise<DryRunEstimate>;
31
+ }
32
+ export interface GuardedDryRunCallOptions {
33
+ /**
34
+ * Asks BigQuery again even when a verdict is remembered, and remembers the new one for a full ttl from now: how a warm
35
+ * keeps a verdict from ever expiring in front of a person (a verdict lives ten minutes, a warm repeats inside that).
36
+ * A failed or refused check leaves the remembered verdict as it was. Without a memo, every dry run asks.
37
+ */
38
+ refresh?: boolean;
39
+ }
40
+ export interface GuardedDryRunOptions {
41
+ /** `project.dataset.table` names the query may read. */
42
+ allowedTables: ReadonlySet<string>;
43
+ /** BigQuery `statementType` values this caller may run, e.g. `SELECT` or, for a later
44
+ * slice's export, `CREATE_TABLE_AS_SELECT`. Never implicit — every caller states it. */
45
+ allowedStatementTypes: ReadonlySet<string>;
46
+ maxBytes: number;
47
+ }
48
+ /** How long a dry-run verdict is remembered, and how many are: the memo is bounded in both. */
49
+ export interface DryRunMemoOptions {
50
+ /** Default 10 minutes: the estimate a run reports (what the job was allowed to scan) is never older than this. */
51
+ ttlMs?: number;
52
+ /** Default 500 distinct queries; the one used longest ago is dropped to make room. */
53
+ maxEntries?: number;
54
+ now?: () => number;
55
+ }
56
+ export interface GuardedBigQueryOptions {
57
+ /** `project.dataset.table` names the query may read. */
58
+ allowedTables: ReadonlySet<string>;
59
+ /** The time budget of the whole call, retries and backoffs included; each job BigQuery runs
60
+ * carries what is left of it as its own limit (`configuration.jobTimeoutMs`). The byte
61
+ * budget bounds what a query scans but not what it computes: a cross join over a small
62
+ * table bills almost nothing and still burns slots for as long as it is let run.
63
+ * Required, so no caller of the guard can leave a job unbounded. */
64
+ jobTimeoutMs: number;
65
+ /** Defaults to SELECT-only (`DEFAULT_ALLOWED_STATEMENT_TYPES`) — every caller that
66
+ * existed before this option was added keeps exactly that behavior. */
67
+ allowedStatementTypes?: ReadonlySet<string>;
68
+ maxBytes: number;
69
+ /** Remember each query's dry-run verdict (see this file's header). Set only by a guard whose every query is SQL
70
+ * the app wrote itself; absent, every run is dry-run first. */
71
+ dryRunMemo?: DryRunMemoOptions;
72
+ }
73
+ /**
74
+ * The dry-run + allowlist/statement-type/budget check on its own, returning the
75
+ * estimate it validated so a caller that isn't going through `createGuardedBigQuery`'s
76
+ * own `run()` (a CTAS, run through `client.query()` directly — a later slice) can still
77
+ * get exactly this check, not a reimplementation of it. See this file's own header
78
+ * comment.
79
+ */
80
+ export declare function guardedDryRun(client: BigQueryReadClient, query: Pick<GuardedQuery, "sql" | "params" | "types">, { allowedTables, allowedStatementTypes, maxBytes }: GuardedDryRunOptions): Promise<DryRunEstimate>;
81
+ export declare function createGuardedBigQuery(client: BigQueryReadClient, { allowedTables, allowedStatementTypes, maxBytes, jobTimeoutMs, dryRunMemo, }: GuardedBigQueryOptions): GuardedBigQuery;
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The execution guard every user-shaped BigQuery query passes before it runs (PLN-2
3
+ * R-4: read-only, single statement, allowlisted, budgeted). One dry run answers all
4
+ * three questions BigQuery itself can answer authoritatively:
5
+ * - its `statementType` must be one of the caller's allowed statement types
6
+ * (every existing caller allows only `SELECT` — see `DEFAULT_ALLOWED_STATEMENT_TYPES`);
7
+ * - every table in its `referencedTables` must be on the caller's allowlist;
8
+ * - its estimated bytes must be within the caller's budget (app-kit's
9
+ * `DryRunBudgetExceededError` otherwise, thrown by `estimateQueryBytes` itself since
10
+ * the dry run is called with the same `maxBytesBilled` the real job will carry).
11
+ * The real job then carries the same budget as BigQuery's own `maximumBytesBilled`
12
+ * cap, so data growing between the dry run and the job cannot exceed it either, and
13
+ * `jobTimeoutMs`, the whole call's time budget (every attempt and backoff of a retried
14
+ * job included, each job carrying what is left of it as BigQuery's own `jobTimeoutMs`),
15
+ * so a query that scans little but computes a lot is stopped too (app-kit raises
16
+ * `JobTimeoutError`).
17
+ *
18
+ * The budget must be a positive safe integer number of bytes: app-kit's client refuses any other `maxBytesBilled`
19
+ * with a `BadQueryError` before any BigQuery call, on the dry run and on the job alike.
20
+ *
21
+ * A guard whose every query is SQL the app wrote itself (never a person's) may remember the dry run's verdict
22
+ * (`dryRunMemo`): the statement type, the tables it reads and the allowlist depend only on the SQL text and its
23
+ * parameter types, so the same compiler-written query need not be dry-run again, and the dry run's 100 to 400 ms
24
+ * is not paid in front of every identical job. The job's `maximumBytesBilled` stays the real budget cap, and a
25
+ * job BigQuery stops for it forgets the verdict, so the next run is dry-run again and answered with the real
26
+ * estimate. A guard that can be handed an analyst's SQL does not set it: that SQL is dry-run every time.
27
+ *
28
+ * `guardedDryRun` below is this whole check, extracted to its own export (SMS-13 design
29
+ * corrections comment, §8) so a caller that needs to run something other than a plain
30
+ * SELECT through `client.query()` itself (SMS-13's export CTAS) can reuse the identical
31
+ * allowlist/statement-type/budget check without duplicating it —
32
+ * `createGuardedBigQuery(...).run()` below is `guardedDryRun` followed by the real
33
+ * `client.query()` call. The default `allowedStatementTypes` is SELECT-only, and the
34
+ * `not_select` refusal's message on that default path names just `SELECT`.
35
+ */
36
+ import { MaximumBytesBilledExceededError } from "./errors.js";
37
+ import { BoundedLru } from "./boundedLru.js";
38
+ export class QueryRefusedError extends Error {
39
+ reason;
40
+ constructor(reason, message) {
41
+ super(message);
42
+ this.reason = reason;
43
+ this.name = "QueryRefusedError";
44
+ }
45
+ }
46
+ const DEFAULT_MEMO_TTL_MS = 10 * 60 * 1000;
47
+ const DEFAULT_MEMO_MAX_ENTRIES = 500;
48
+ /** What a dry run's verdict depends on: the SQL text and the types of its parameters (never their values). */
49
+ function dryRunKey({ sql, types }) {
50
+ const typed = Object.entries(types).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
51
+ return JSON.stringify([sql, typed]);
52
+ }
53
+ /** What every caller got before `allowedStatementTypes` existed, and what every caller
54
+ * that doesn't pass one still gets — read-only, single-statement (PLN-2 R-4). */
55
+ const DEFAULT_ALLOWED_STATEMENT_TYPES = new Set(["SELECT"]);
56
+ function qualifiedName(table) {
57
+ return `${table.projectId}.${table.datasetId}.${table.tableId}`;
58
+ }
59
+ /**
60
+ * The dry-run + allowlist/statement-type/budget check on its own, returning the
61
+ * estimate it validated so a caller that isn't going through `createGuardedBigQuery`'s
62
+ * own `run()` (a CTAS, run through `client.query()` directly — a later slice) can still
63
+ * get exactly this check, not a reimplementation of it. See this file's own header
64
+ * comment.
65
+ */
66
+ export async function guardedDryRun(client, query, { allowedTables, allowedStatementTypes, maxBytes }) {
67
+ const estimate = await client.estimateQueryBytes({
68
+ sql: query.sql,
69
+ params: query.params,
70
+ types: query.types,
71
+ maxBytesBilled: maxBytes,
72
+ });
73
+ if (estimate.statementType === undefined || !allowedStatementTypes.has(estimate.statementType)) {
74
+ throw new QueryRefusedError("not_select", `Refused a ${estimate.statementType ?? "statement of unknown type"}: only ${[...allowedStatementTypes].join(" or ")} may run`);
75
+ }
76
+ if (estimate.referencedTables === undefined) {
77
+ throw new QueryRefusedError("tables_unknown", "Refused a query whose dry run did not report the tables it reads");
78
+ }
79
+ const disallowed = estimate.referencedTables
80
+ .map(qualifiedName)
81
+ .filter((name) => !allowedTables.has(name));
82
+ if (disallowed.length > 0) {
83
+ throw new QueryRefusedError("table_not_allowed", `Refused a query reading tables outside the allowlist: ${disallowed.join(", ")}`);
84
+ }
85
+ return estimate;
86
+ }
87
+ export function createGuardedBigQuery(client, { allowedTables, allowedStatementTypes = DEFAULT_ALLOWED_STATEMENT_TYPES, maxBytes, jobTimeoutMs, dryRunMemo, }) {
88
+ const check = (query) => guardedDryRun(client, query, { allowedTables, allowedStatementTypes, maxBytes });
89
+ const { ttlMs = DEFAULT_MEMO_TTL_MS, maxEntries = DEFAULT_MEMO_MAX_ENTRIES, now = Date.now, } = dryRunMemo ?? {};
90
+ const verdicts = new BoundedLru(maxEntries);
91
+ /** The refresh: the old verdict keeps answering until the new one is in, and stays when the new one fails. */
92
+ const renewed = (key, query) => {
93
+ const estimate = check(query);
94
+ void estimate.then(() => verdicts.set(key, { expiresAt: now() + ttlMs, estimate }), () => undefined);
95
+ return estimate;
96
+ };
97
+ const dryRun = dryRunMemo === undefined
98
+ ? check
99
+ : (query, { refresh = false } = {}) => {
100
+ const key = dryRunKey(query);
101
+ const at = now();
102
+ if (refresh)
103
+ return renewed(key, query);
104
+ const kept = verdicts.get(key);
105
+ if (kept !== undefined && kept.expiresAt > at)
106
+ return kept.estimate;
107
+ const entry = { expiresAt: at + ttlMs, estimate: check(query) };
108
+ // A refusal or failure is never kept: the next run asks again.
109
+ entry.estimate.catch(() => {
110
+ if (verdicts.get(key) === entry)
111
+ verdicts.delete(key);
112
+ });
113
+ verdicts.set(key, entry);
114
+ return entry.estimate;
115
+ };
116
+ return {
117
+ dryRun,
118
+ async run({ sql, params, types, labels }, { dryRunFailure } = {}) {
119
+ const estimate = await dryRun({ sql, params, types }).catch((error) => {
120
+ throw dryRunFailure ? dryRunFailure(error) : error;
121
+ });
122
+ try {
123
+ const page = await client.query({
124
+ sql,
125
+ params,
126
+ types,
127
+ labels,
128
+ maximumBytesBilled: maxBytes,
129
+ jobTimeoutMs,
130
+ });
131
+ return { rows: page.rows, bytesProcessed: estimate.totalBytesProcessed };
132
+ }
133
+ catch (error) {
134
+ // BigQuery stopped the job at the budget the remembered estimate said it would fit: that estimate is
135
+ // out of date, so it is forgotten and the next run is dry-run again.
136
+ if (error instanceof MaximumBytesBilledExceededError) {
137
+ verdicts.delete(dryRunKey({ sql, types }));
138
+ }
139
+ throw error;
140
+ }
141
+ },
142
+ };
143
+ }
144
+ //# sourceMappingURL=guarded.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guarded.js","sourceRoot":"","sources":["../../src/bigquery/guarded.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,OAAO,EAAE,+BAA+B,EAAE,MAAM,aAAa,CAAC;AAO9D,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAE7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5 @@ export { unwrapBigQueryCount, unwrapBigQueryRow, unwrapBigQueryValue, } from "./
56
56
  export { BadQueryError, BigQueryReadError, DryRunBudgetExceededError, InsertRowsPartialFailureError, JobTimeoutError, MalformedResultSchemaError, MaximumBytesBilledExceededError, PermissionDeniedError, RateLimitExceededError, TransientBackendError, classifyBigQueryError, } from "./errors.js";
57
57
  export type { InsertRowError } from "./errors.js";
58
58
  export type { BigQueryApiErrorDetail, BigQueryCreateQueryJobOptions, BigQueryDatasetLike, BigQueryExtractOptions, BigQueryInsertOptions, BigQueryJobLike, BigQueryJobMetadata, BigQueryLike, BigQueryLoadOptions, BigQueryLoadJobLike, BigQueryNextQuery, BigQueryParamTypes, BigQueryParamTypeStruct, BigQueryQueryResultsOptions, BigQueryRawSchema, BigQueryRawSchemaField, BigQueryResultSchemaField, BigQuerySchemaField, BigQueryTableDeleteOptions, BigQueryTableLike, BigQueryTableMetadata, BigQueryTableReference, DryRunEstimate, EstimateQueryBytesOptions, ExtractJobHandle, ExtractJobState, ExtractJobStatus, ExtractTableToGCSInput, GcsFileLike, JobLabelInput, QueryPage, RunQueryOptions, WaitForExtractJobOptions, } from "./types.js";
59
+ export { createGuardedBigQuery, guardedDryRun, QueryRefusedError } from "./guarded.js";
60
+ export type { DryRunMemoOptions, GuardedBigQuery, GuardedBigQueryOptions, GuardedDryRunCallOptions, GuardedDryRunOptions, GuardedQuery, GuardedQueryResult, GuardedRunOptions, } from "./guarded.js";
@@ -49,4 +49,5 @@ export { insertRows } from "./insert.js";
49
49
  export { createTable, deleteTable } from "./tableAdmin.js";
50
50
  export { unwrapBigQueryCount, unwrapBigQueryRow, unwrapBigQueryValue, } from "./values.js";
51
51
  export { BadQueryError, BigQueryReadError, DryRunBudgetExceededError, InsertRowsPartialFailureError, JobTimeoutError, MalformedResultSchemaError, MaximumBytesBilledExceededError, PermissionDeniedError, RateLimitExceededError, TransientBackendError, classifyBigQueryError, } from "./errors.js";
52
+ export { createGuardedBigQuery, guardedDryRun, QueryRefusedError } from "./guarded.js";
52
53
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/bigquery/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAMvD,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAE5E,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAWrE,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG3D,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,yBAAyB,EACzB,6BAA6B,EAC7B,eAAe,EACf,0BAA0B,EAC1B,+BAA+B,EAC/B,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,aAAa,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/bigquery/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAMvD,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAE5E,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,iBAAiB,GAClB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAWrE,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG3D,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,yBAAyB,EACzB,6BAA6B,EAC7B,eAAe,EACf,0BAA0B,EAC1B,+BAA+B,EAC/B,qBAAqB,EACrB,sBAAsB,EACtB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,aAAa,CAAC;AAwCrB,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,6 @@
1
+ /** Why the guard refused a statement. Each is a stable code a caller can branch on; the message is for a person. */
2
+ export type SqlRefusalReason = "unparseable" | "multiple_statements" | "not_select" | "executable_comment" | "writes_data" | "locking_read" | "forbidden_function" | "table_not_allowed";
3
+ export declare class SqlRefusedError extends Error {
4
+ readonly reason: SqlRefusalReason;
5
+ constructor(reason: SqlRefusalReason, message: string);
6
+ }
@@ -0,0 +1,9 @@
1
+ export class SqlRefusedError extends Error {
2
+ reason;
3
+ constructor(reason, message) {
4
+ super(message);
5
+ this.reason = reason;
6
+ this.name = "SqlRefusedError";
7
+ }
8
+ }
9
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/sql-guard/errors.ts"],"names":[],"mappings":"AAWA,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAE7B;IADX,YACW,MAAwB,EACjC,OAAe;QAEf,KAAK,CAAC,OAAO,CAAC,CAAC;QAHN,WAAM,GAAN,MAAM,CAAkB;QAIjC,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAChC,CAAC;CACF"}
@@ -0,0 +1,27 @@
1
+ export type SqlDialect = "mysql" | "postgres";
2
+ export interface GuardSqlOptions {
3
+ dialect: SqlDialect;
4
+ /** Qualified `schema.table` names (Postgres) or `database.table` names (MySQL) the statement may read. */
5
+ allowedTables: ReadonlySet<string>;
6
+ /** The schema (Postgres, usually `public`) or database (MySQL) an unqualified table name belongs to. */
7
+ defaultSchema: string;
8
+ }
9
+ /** What a dialect's analysis reports about one parsed statement; every refusal is thrown from it. */
10
+ export interface Analysis {
11
+ /** Qualified names of the real tables the statement reads, CTE names excluded. */
12
+ tables: string[];
13
+ }
14
+ /**
15
+ * A statement the guard accepted. Only `guardSql` makes one, and the runners take only this,
16
+ * so a statement cannot reach a database without having passed the guard.
17
+ */
18
+ export declare class GuardedSql {
19
+ #private;
20
+ readonly sql: string;
21
+ readonly dialect: SqlDialect;
22
+ readonly tables: readonly string[];
23
+ private constructor();
24
+ static accept(sql: string, dialect: SqlDialect, tables: readonly string[]): GuardedSql;
25
+ static is(value: unknown): value is GuardedSql;
26
+ }
27
+ export declare function guardSql(sql: string, options: GuardSqlOptions): GuardedSql;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The read-only SQL guard (AK-57): decides, from a real parse (never a pattern match), whether
3
+ * one statement an agent wrote may run against a production MySQL or Postgres database, and
4
+ * names the tables it reads. It refuses what it cannot parse, so a construct the parsers do not
5
+ * know is refused, never waved through.
6
+ *
7
+ * It is the first of two layers: `runReadOnlyPostgres` / `runReadOnlyMysql` then execute the
8
+ * statement inside a read-only transaction with a timeout and a row cap, so a parser/server
9
+ * disagreement still cannot write.
10
+ */
11
+ import { SqlRefusedError } from "./errors.js";
12
+ import { analyzeMysql } from "./mysql.js";
13
+ import { analyzePostgres } from "./postgres.js";
14
+ /**
15
+ * A statement the guard accepted. Only `guardSql` makes one, and the runners take only this,
16
+ * so a statement cannot reach a database without having passed the guard.
17
+ */
18
+ export class GuardedSql {
19
+ sql;
20
+ dialect;
21
+ tables;
22
+ #accepted = true;
23
+ constructor(sql, dialect, tables) {
24
+ this.sql = sql;
25
+ this.dialect = dialect;
26
+ this.tables = tables;
27
+ }
28
+ static accept(sql, dialect, tables) {
29
+ return new GuardedSql(sql, dialect, tables);
30
+ }
31
+ static is(value) {
32
+ return value instanceof GuardedSql && value.#accepted;
33
+ }
34
+ }
35
+ // MySQL and MariaDB run the body of a slash-star-bang comment (and the MariaDB M-bang form) as SQL, while a parser reads it as a comment.
36
+ const EXECUTABLE_COMMENT = /\/\*\s*M?!/i;
37
+ export function guardSql(sql, options) {
38
+ if (options.dialect === "mysql" && EXECUTABLE_COMMENT.test(sql)) {
39
+ throw new SqlRefusedError("executable_comment", "Refused: a /*! ... */ comment is executed by MySQL, so it can hide a statement from the guard");
40
+ }
41
+ const { tables } = options.dialect === "mysql"
42
+ ? analyzeMysql(sql, options.defaultSchema)
43
+ : analyzePostgres(sql, options.defaultSchema);
44
+ const unique = [...new Set(tables)].sort();
45
+ const disallowed = unique.filter((name) => !options.allowedTables.has(name));
46
+ if (disallowed.length > 0) {
47
+ throw new SqlRefusedError("table_not_allowed", `Refused: the statement reads tables outside the allowlist: ${disallowed.join(", ")}`);
48
+ }
49
+ return GuardedSql.accept(sql, options.dialect, unique);
50
+ }
51
+ //# sourceMappingURL=guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guard.js","sourceRoot":"","sources":["../../src/sql-guard/guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAkBhD;;;GAGG;AACH,MAAM,OAAO,UAAU;IAGV;IACA;IACA;IAJF,SAAS,GAAG,IAAI,CAAC;IAC1B,YACW,GA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AU,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACtF,CAAC;IACJ,CAAC;IACD,OAAO,UAAU,CAAC,MAAM,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AACzD,CAAC"}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Read-only SQL guard for agent-written MySQL and Postgres statements (AK-57).
3
+ *
4
+ * import { guardSql, runReadOnlyPostgres } from "@flytedesk/app-kit/sql-guard";
5
+ *
6
+ * const statement = guardSql(agentSql, {
7
+ * dialect: "postgres",
8
+ * allowedTables: new Set(["public.orders", "public.customers"]),
9
+ * defaultSchema: "public",
10
+ * }); // throws SqlRefusedError (with a readable message) unless it is one plain SELECT/WITH
11
+ * statement.tables; // ["public.orders"]
12
+ * const { rows, truncated } = await runReadOnlyPostgres(pgClient, statement, {
13
+ * timeoutMs: 10_000,
14
+ * maxRows: 1000,
15
+ * });
16
+ *
17
+ * MySQL is the same with `dialect: "mysql"`, `defaultSchema` the database name, and
18
+ * `runReadOnlyMysql(mysql2Connection, ...)`.
19
+ *
20
+ * Limits: the guard refuses what its parsers cannot read (Postgres `WITH RECURSIVE`, `TABLESAMPLE`
21
+ * and `SELECT ... INTO` are among them), and a connection should also be a database role that can
22
+ * only read; the read-only transaction is a second layer, not a substitute.
23
+ */
24
+ export { guardSql, GuardedSql } from "./guard.js";
25
+ export type { GuardSqlOptions, SqlDialect } from "./guard.js";
26
+ export { SqlRefusedError } from "./errors.js";
27
+ export type { SqlRefusalReason } from "./errors.js";
28
+ export { runReadOnlyMysql, runReadOnlyPostgres } from "./run.js";
29
+ export type { MysqlConnectionLike, PostgresClientLike, ReadOnlyResult, ReadOnlyRunOptions, } from "./run.js";
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Read-only SQL guard for agent-written MySQL and Postgres statements (AK-57).
3
+ *
4
+ * import { guardSql, runReadOnlyPostgres } from "@flytedesk/app-kit/sql-guard";
5
+ *
6
+ * const statement = guardSql(agentSql, {
7
+ * dialect: "postgres",
8
+ * allowedTables: new Set(["public.orders", "public.customers"]),
9
+ * defaultSchema: "public",
10
+ * }); // throws SqlRefusedError (with a readable message) unless it is one plain SELECT/WITH
11
+ * statement.tables; // ["public.orders"]
12
+ * const { rows, truncated } = await runReadOnlyPostgres(pgClient, statement, {
13
+ * timeoutMs: 10_000,
14
+ * maxRows: 1000,
15
+ * });
16
+ *
17
+ * MySQL is the same with `dialect: "mysql"`, `defaultSchema` the database name, and
18
+ * `runReadOnlyMysql(mysql2Connection, ...)`.
19
+ *
20
+ * Limits: the guard refuses what its parsers cannot read (Postgres `WITH RECURSIVE`, `TABLESAMPLE`
21
+ * and `SELECT ... INTO` are among them), and a connection should also be a database role that can
22
+ * only read; the read-only transaction is a second layer, not a substitute.
23
+ */
24
+ export { guardSql, GuardedSql } from "./guard.js";
25
+ export { SqlRefusedError } from "./errors.js";
26
+ export { runReadOnlyMysql, runReadOnlyPostgres } from "./run.js";
27
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/sql-guard/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE9C,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC"}
@@ -0,0 +1,2 @@
1
+ import type { Analysis } from "./guard.js";
2
+ export declare function analyzeMysql(sql: string, defaultSchema: string): Analysis;
@@ -0,0 +1,128 @@
1
+ import { Parser } from "node-sql-parser";
2
+ import { SqlRefusedError } from "./errors.js";
3
+ import { walkNodes } from "./walk.js";
4
+ const parser = new Parser();
5
+ /** Functions that sleep, read the server's files, take locks or run commands. */
6
+ const FORBIDDEN_FUNCTION = new Set([
7
+ "sleep",
8
+ "benchmark",
9
+ "load_file",
10
+ "get_lock",
11
+ "release_lock",
12
+ "release_all_locks",
13
+ "master_pos_wait",
14
+ "source_pos_wait",
15
+ "wait_for_executed_gtid_set",
16
+ "wait_until_sql_thread_after_gtids",
17
+ "sys_exec",
18
+ "sys_eval",
19
+ "sys_get",
20
+ "sys_set",
21
+ "sys_bineval",
22
+ ]);
23
+ const WRITING_NODES = new Set([
24
+ "insert",
25
+ "replace",
26
+ "update",
27
+ "delete",
28
+ "create",
29
+ "drop",
30
+ "alter",
31
+ "truncate",
32
+ "rename",
33
+ "set",
34
+ "show",
35
+ "use",
36
+ "lock",
37
+ "unlock",
38
+ "call",
39
+ "grant",
40
+ "load_data",
41
+ "transaction",
42
+ "desc",
43
+ "explain",
44
+ "exec",
45
+ "prepare",
46
+ ]);
47
+ function refusal(error) {
48
+ const firstLine = error instanceof Error ? error.message.split("\n")[0] : String(error);
49
+ return new SqlRefusedError("unparseable", `Refused: not a MySQL SELECT the guard can verify (${firstLine})`);
50
+ }
51
+ export function analyzeMysql(sql, defaultSchema) {
52
+ let ast;
53
+ try {
54
+ ast = parser.astify(sql, { database: "mysql" });
55
+ }
56
+ catch (error) {
57
+ throw refusal(error);
58
+ }
59
+ const statements = Array.isArray(ast) ? ast : [ast];
60
+ if (statements.length !== 1) {
61
+ throw new SqlRefusedError("multiple_statements", `Refused: ${statements.length === 0 ? "no statement" : `${statements.length} statements`}; exactly one SELECT or WITH is allowed`);
62
+ }
63
+ const root = statements[0];
64
+ if (root.type !== "select") {
65
+ throw new SqlRefusedError("not_select", `Refused a ${String(root.type)} statement: only SELECT or WITH may run`);
66
+ }
67
+ const tables = [];
68
+ collectTables(root, new Set(), defaultSchema, tables);
69
+ walkNodes(root, (node) => {
70
+ const type = typeof node.type === "string" ? node.type : undefined;
71
+ if (type !== undefined && WRITING_NODES.has(type)) {
72
+ throw new SqlRefusedError("writes_data", `Refused: the statement contains a ${type}, which writes or changes state`);
73
+ }
74
+ if (type === "select") {
75
+ const into = node.into;
76
+ if (into && (into.position != null || into.keyword != null || into.expr != null)) {
77
+ throw new SqlRefusedError("writes_data", "Refused: SELECT ... INTO writes a file or a variable");
78
+ }
79
+ if (node.locking_read != null) {
80
+ throw new SqlRefusedError("locking_read", "Refused: FOR UPDATE / FOR SHARE / LOCK IN SHARE MODE takes row locks");
81
+ }
82
+ }
83
+ if (type === "function") {
84
+ const parts = node.name?.name ?? [];
85
+ const name = (parts[parts.length - 1]?.value ?? "").toLowerCase();
86
+ if (FORBIDDEN_FUNCTION.has(name)) {
87
+ throw new SqlRefusedError("forbidden_function", `Refused: the function ${name}() is not allowed`);
88
+ }
89
+ }
90
+ });
91
+ return { tables };
92
+ }
93
+ /** Same scoping rule as Postgres: a CTE name is visible to the CTEs after it (and itself when RECURSIVE) and to the main query. */
94
+ function collectTables(node, ctes, defaultSchema, out) {
95
+ if (Array.isArray(node)) {
96
+ for (const item of node)
97
+ collectTables(item, ctes, defaultSchema, out);
98
+ return;
99
+ }
100
+ if (typeof node !== "object" || node === null)
101
+ return;
102
+ const record = node;
103
+ let visible = ctes;
104
+ if (record.type === "select" && Array.isArray(record.with)) {
105
+ const recursive = record.with.some((cte) => cte.recursive === true);
106
+ const defined = new Set(ctes);
107
+ for (const cte of record.with) {
108
+ collectTables(cte.stmt, recursive ? new Set([...defined, cte.name.value]) : defined, defaultSchema, out);
109
+ defined.add(cte.name.value);
110
+ }
111
+ visible = defined;
112
+ }
113
+ for (const [key, value] of Object.entries(record)) {
114
+ if (key === "with")
115
+ continue;
116
+ if (key === "from" && Array.isArray(value)) {
117
+ for (const item of value) {
118
+ if (typeof item.table === "string") {
119
+ if (item.db != null || !visible.has(item.table)) {
120
+ out.push(`${item.db ?? defaultSchema}.${item.table}`);
121
+ }
122
+ }
123
+ }
124
+ }
125
+ collectTables(value, visible, defaultSchema, out);
126
+ }
127
+ }
128
+ //# sourceMappingURL=mysql.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mysql.js","sourceRoot":"","sources":["../../src/sql-guard/mysql.ts"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AC,EAAE,CAAC;wBAChD,GAAG,CAAC,IAAI,CAAC,GAAI,IAAI,CAAC,EAAoB,IAAI,aAAa,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;oBAC3E,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QACD,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;IACpD,CAAC;AACH,CAAC"}
@@ -0,0 +1,2 @@
1
+ import type { Analysis } from "./guard.js";
2
+ export declare function analyzePostgres(sql: string, defaultSchema: string): Analysis;
@@ -0,0 +1,121 @@
1
+ import { parse } from "pgsql-ast-parser";
2
+ import { SqlRefusedError } from "./errors.js";
3
+ import { walkNodes } from "./walk.js";
4
+ const READ_TOP_LEVEL = new Set(["select", "union", "union all", "with", "with recursive"]);
5
+ /** Statement kinds that write or change state; one anywhere (a `WITH d AS (DELETE ...)`) is refused. */
6
+ const WRITING_NODES = new Set([
7
+ "insert",
8
+ "update",
9
+ "delete",
10
+ "truncate",
11
+ "create table",
12
+ "create index",
13
+ "create view",
14
+ "create materialized view",
15
+ "create extension",
16
+ "create sequence",
17
+ "create schema",
18
+ "create enum",
19
+ "create composite type",
20
+ "create function",
21
+ "drop table",
22
+ "drop index",
23
+ "drop sequence",
24
+ "drop type",
25
+ "drop view",
26
+ "drop function",
27
+ "drop extension",
28
+ "alter table",
29
+ "alter index",
30
+ "alter sequence",
31
+ "set",
32
+ "show",
33
+ "begin",
34
+ "commit",
35
+ "rollback",
36
+ "start transaction",
37
+ "prepare",
38
+ "deallocate",
39
+ "tablespace",
40
+ "comment",
41
+ "do",
42
+ "copy",
43
+ "raise",
44
+ "refresh materialized view",
45
+ ]);
46
+ /** Functions that sleep, read the server's files, take locks, change settings or sequences, or run SQL text the guard cannot see. */
47
+ const FORBIDDEN_FUNCTION = /^(pg_sleep|pg_read_|pg_ls_|pg_stat_file|pg_file_|pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile|pg_advisory_|pg_try_advisory_|pg_switch_wal|pg_create_|pg_drop_|pg_logical_|pg_replication_|pg_promote|pg_import_system_collations|lo_|dblink|set_config|nextval|setval|query_to_xml|cursor_to_xml|table_to_xml|schema_to_xml|database_to_xml|ts_debug|xmlquery|pg_notify)/;
48
+ function unsupportedParse(error) {
49
+ const firstLine = error instanceof Error ? error.message.split("\n")[0] : String(error);
50
+ return new SqlRefusedError("unparseable", `Refused: not a PostgreSQL SELECT the guard can verify (${firstLine})`);
51
+ }
52
+ export function analyzePostgres(sql, defaultSchema) {
53
+ let statements;
54
+ try {
55
+ statements = parse(sql);
56
+ }
57
+ catch (error) {
58
+ throw unsupportedParse(error);
59
+ }
60
+ if (statements.length !== 1) {
61
+ throw new SqlRefusedError("multiple_statements", `Refused: ${statements.length === 0 ? "no statement" : `${statements.length} statements`}; exactly one SELECT or WITH is allowed`);
62
+ }
63
+ const root = statements[0];
64
+ if (!READ_TOP_LEVEL.has(String(root.type))) {
65
+ throw new SqlRefusedError("not_select", `Refused a ${String(root.type)} statement: only SELECT or WITH may run`);
66
+ }
67
+ const tables = [];
68
+ collectTables(root, new Set(), defaultSchema, tables);
69
+ walkNodes(root, (node) => {
70
+ const type = typeof node.type === "string" ? node.type : undefined;
71
+ if (type !== undefined && WRITING_NODES.has(type)) {
72
+ throw new SqlRefusedError("writes_data", `Refused: the statement contains a ${type}, which writes or changes state`);
73
+ }
74
+ if (node.for !== undefined && node.for !== null) {
75
+ throw new SqlRefusedError("locking_read", "Refused: FOR UPDATE / FOR SHARE takes row locks");
76
+ }
77
+ if (type === "call") {
78
+ const fn = node.function;
79
+ const name = (fn?.name ?? "").toLowerCase();
80
+ if (FORBIDDEN_FUNCTION.test(name)) {
81
+ throw new SqlRefusedError("forbidden_function", `Refused: the function ${name}() is not allowed`);
82
+ }
83
+ }
84
+ });
85
+ return { tables };
86
+ }
87
+ /**
88
+ * Collects every real table under `node`. A `WITH` name hides a table of the same name only inside
89
+ * what it scopes: a CTE body sees the CTEs defined before it, the main query sees them all.
90
+ */
91
+ function collectTables(node, ctes, defaultSchema, out) {
92
+ if (Array.isArray(node)) {
93
+ for (const item of node)
94
+ collectTables(item, ctes, defaultSchema, out);
95
+ return;
96
+ }
97
+ if (typeof node !== "object" || node === null)
98
+ return;
99
+ const record = node;
100
+ if (record.type === "with" || record.type === "with recursive") {
101
+ const recursive = record.type === "with recursive";
102
+ const visible = new Set(ctes);
103
+ for (const bind of record.bind) {
104
+ const name = bind.alias.name;
105
+ collectTables(bind.statement, recursive ? new Set([...visible, name]) : visible, defaultSchema, out);
106
+ visible.add(name);
107
+ }
108
+ collectTables(record.in, visible, defaultSchema, out);
109
+ return;
110
+ }
111
+ if (record.type === "table") {
112
+ const name = record.name;
113
+ if (name.schema !== undefined || !ctes.has(name.name)) {
114
+ out.push(`${name.schema ?? defaultSchema}.${name.name}`);
115
+ }
116
+ return;
117
+ }
118
+ for (const value of Object.values(record))
119
+ collectTables(value, ctes, defaultSchema, out);
120
+ }
121
+ //# sourceMappingURL=postgres.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.js","sourceRoot":"","sources":["../../src/sql-guard/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE9C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,CAAC,QAAQ,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC;AAE3F,wGAAwG;AACxG,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC;IAC5B,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,UAAU;IACV,cAAc;IACd,cAAc;IACd,aAAa;IACb,0BAA0B;IAC1B,kBAAkB;IAClB,iBAAiB;IACjB,eAAe;IACf,aAAa;IACb,uBAAuB;IACvB,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,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YACtD,GAAG,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,IAAI,aAAa,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;QAC3D,CAAC;QACD,OAAO;IACT,CAAC;IACD,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;QAAE,aAAa,CAAC,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;AAC5F,CAAC"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Runs a guarded statement in a read-only transaction with a timeout and a row cap. Structural
3
+ * client types (like the BigQuery module's), so app-kit adds no driver dependency: a `pg`
4
+ * `Client`/`PoolClient` and a `mysql2/promise` `Connection`/`PoolConnection` already satisfy them.
5
+ * The client must be one connection nobody else is using for the call (a pool checkout).
6
+ */
7
+ import { GuardedSql } from "./guard.js";
8
+ export interface ReadOnlyRunOptions {
9
+ /** Server-side time limit for the statement, in whole milliseconds (> 0). */
10
+ timeoutMs: number;
11
+ /** The most rows returned (> 0); one more is read to tell whether the result was cut. */
12
+ maxRows: number;
13
+ }
14
+ export interface ReadOnlyResult<Row> {
15
+ rows: Row[];
16
+ /** True when the statement had more than `maxRows` rows; `rows` holds the first `maxRows`. */
17
+ truncated: boolean;
18
+ }
19
+ export interface PostgresClientLike {
20
+ query(text: string): Promise<{
21
+ rows: unknown[];
22
+ }>;
23
+ }
24
+ export interface MysqlConnectionLike {
25
+ query(sql: string): Promise<[unknown, unknown]>;
26
+ }
27
+ /**
28
+ * Postgres: `BEGIN READ ONLY`, `SET LOCAL statement_timeout`, then the statement as a `NO SCROLL`
29
+ * cursor from which `maxRows + 1` rows are fetched, so the cap needs no rewrite of the SQL.
30
+ * Always rolled back.
31
+ */
32
+ export declare function runReadOnlyPostgres<Row = Record<string, unknown>>(client: PostgresClientLike, statement: GuardedSql, options: ReadOnlyRunOptions): Promise<ReadOnlyResult<Row>>;
33
+ /**
34
+ * MySQL: `START TRANSACTION READ ONLY` with the session's `max_execution_time` and
35
+ * `sql_select_limit` (the row cap, `maxRows + 1`, applied by the server to the top-level SELECT)
36
+ * set for the call and put back after it. Always rolled back.
37
+ */
38
+ export declare function runReadOnlyMysql<Row = Record<string, unknown>>(connection: MysqlConnectionLike, statement: GuardedSql, options: ReadOnlyRunOptions): Promise<ReadOnlyResult<Row>>;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Runs a guarded statement in a read-only transaction with a timeout and a row cap. Structural
3
+ * client types (like the BigQuery module's), so app-kit adds no driver dependency: a `pg`
4
+ * `Client`/`PoolClient` and a `mysql2/promise` `Connection`/`PoolConnection` already satisfy them.
5
+ * The client must be one connection nobody else is using for the call (a pool checkout).
6
+ */
7
+ import { GuardedSql } from "./guard.js";
8
+ function validate({ timeoutMs, maxRows }) {
9
+ for (const [name, value] of [["timeoutMs", timeoutMs], ["maxRows", maxRows]]) {
10
+ if (!Number.isSafeInteger(value) || value <= 0) {
11
+ throw new RangeError(`${name} must be a positive integer, not ${value}`);
12
+ }
13
+ }
14
+ }
15
+ function requireGuarded(statement, dialect) {
16
+ if (!GuardedSql.is(statement))
17
+ throw new TypeError("Only a statement returned by guardSql may be run");
18
+ if (statement.dialect !== dialect) {
19
+ throw new TypeError(`A ${statement.dialect} statement cannot run on a ${dialect} connection`);
20
+ }
21
+ }
22
+ /**
23
+ * Postgres: `BEGIN READ ONLY`, `SET LOCAL statement_timeout`, then the statement as a `NO SCROLL`
24
+ * cursor from which `maxRows + 1` rows are fetched, so the cap needs no rewrite of the SQL.
25
+ * Always rolled back.
26
+ */
27
+ export async function runReadOnlyPostgres(client, statement, options) {
28
+ requireGuarded(statement, "postgres");
29
+ validate(options);
30
+ await client.query("BEGIN READ ONLY");
31
+ try {
32
+ await client.query(`SET LOCAL statement_timeout = ${options.timeoutMs}`);
33
+ await client.query(`DECLARE guarded_rows NO SCROLL CURSOR FOR ${statement.sql}\n`);
34
+ const fetched = await client.query(`FETCH FORWARD ${options.maxRows + 1} FROM guarded_rows`);
35
+ return capped(fetched.rows, options.maxRows);
36
+ }
37
+ finally {
38
+ await client.query("ROLLBACK");
39
+ }
40
+ }
41
+ /**
42
+ * MySQL: `START TRANSACTION READ ONLY` with the session's `max_execution_time` and
43
+ * `sql_select_limit` (the row cap, `maxRows + 1`, applied by the server to the top-level SELECT)
44
+ * set for the call and put back after it. Always rolled back.
45
+ */
46
+ export async function runReadOnlyMysql(connection, statement, options) {
47
+ requireGuarded(statement, "mysql");
48
+ validate(options);
49
+ const [before] = await connection.query("SELECT CAST(@@session.max_execution_time AS CHAR) AS t, CAST(@@session.sql_select_limit AS CHAR) AS l");
50
+ const { t, l } = before[0];
51
+ await connection.query(`SET SESSION max_execution_time = ${options.timeoutMs}, sql_select_limit = ${options.maxRows + 1}`);
52
+ let outcome;
53
+ try {
54
+ await connection.query("START TRANSACTION READ ONLY");
55
+ const [rows] = await connection.query(statement.sql);
56
+ outcome = { rows: rows };
57
+ }
58
+ catch (error) {
59
+ outcome = { error };
60
+ }
61
+ // The session settings and the transaction are undone whatever the statement did; a failure of
62
+ // the statement is the one reported.
63
+ try {
64
+ await connection.query("ROLLBACK");
65
+ }
66
+ finally {
67
+ await connection.query(`SET SESSION max_execution_time = ${t}, sql_select_limit = ${l}`);
68
+ }
69
+ if ("error" in outcome)
70
+ throw outcome.error;
71
+ return capped(outcome.rows, options.maxRows);
72
+ }
73
+ function capped(rows, maxRows) {
74
+ return rows.length > maxRows
75
+ ? { rows: rows.slice(0, maxRows), truncated: true }
76
+ : { rows, truncated: false };
77
+ }
78
+ //# sourceMappingURL=run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.js","sourceRoot":"","sources":["../../src/sql-guard/run.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAuBxC,SAAS,QAAQ,CAAC,EAAE,SAAS,EAAE,OA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C;IAC5C,OAAO,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;AAC/C,CAAC;AAED,SAAS,MAAM,CAAM,IAAW,EAAE,OAAe;IAC/C,OAAO,IAAI,CAAC,MAAM,GAAG,OAAO;QAC1B,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE;QACnD,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;AACjC,CAAC"}
@@ -0,0 +1,2 @@
1
+ /** Calls `visit` on every plain object reachable from a parsed AST (arrays and nested objects included). */
2
+ export declare function walkNodes(root: unknown, visit: (node: Record<string, unknown>) => void): void;
@@ -0,0 +1,16 @@
1
+ /** Calls `visit` on every plain object reachable from a parsed AST (arrays and nested objects included). */
2
+ export function walkNodes(root, visit) {
3
+ const stack = [root];
4
+ while (stack.length > 0) {
5
+ const value = stack.pop();
6
+ if (Array.isArray(value)) {
7
+ stack.push(...value);
8
+ }
9
+ else if (typeof value === "object" && value !== null) {
10
+ const node = value;
11
+ visit(node);
12
+ stack.push(...Object.values(node));
13
+ }
14
+ }
15
+ }
16
+ //# sourceMappingURL=walk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"walk.js","sourceRoot":"","sources":["../../src/sql-guard/walk.ts"],"names":[],"mappings":"AAAA,4GAA4G;AAC5G,MAAM,UAAU,SAAS,CAAC,IAAa,EAAE,KAA8C;IACrF,MAAM,KAAK,GAAc,CAAC,IAAI,CAAC,CAAC;IAChC,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACxB,MAAM,KAAK,GAAG,KAAK,CAAC,GAAG,EAAE,CAAC;QAC1B,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,KAAK,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;QACvB,CAAC;aAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YACvD,MAAM,IAAI,GAAG,KAAgC,CAAC;YAC9C,KAAK,CAAC,IAAI,CAAC,CAAC;YACZ,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QACrC,CAAC;IACH,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flytedesk/app-kit",
3
- "version": "11.1.0",
3
+ "version": "11.2.0",
4
4
  "description": "Shared platform kit for flytedesk apps: flytedesk-id auth (BFF/OIDC client) and a Postgres-native trace/audit layer.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -90,6 +90,10 @@
90
90
  "./postgres": {
91
91
  "types": "./dist/postgres/index.d.ts",
92
92
  "import": "./dist/postgres/index.js"
93
+ },
94
+ "./sql-guard": {
95
+ "types": "./dist/sql-guard/index.d.ts",
96
+ "import": "./dist/sql-guard/index.js"
93
97
  }
94
98
  },
95
99
  "scripts": {
@@ -133,6 +137,7 @@
133
137
  "@google-cloud/bigquery": "^9.1.0",
134
138
  "@playwright/test": "^1.63.0",
135
139
  "@prisma/client": "^7.10.0",
140
+ "@testcontainers/mysql": "^12.2.1",
136
141
  "@testcontainers/postgresql": "^12.1.0",
137
142
  "@testing-library/react": "^16.3.3",
138
143
  "@types/cross-spawn": "^6.0.6",
@@ -149,6 +154,7 @@
149
154
  "fastify": "^5.12.0",
150
155
  "globals": "^17.12.0",
151
156
  "jsdom": "^30.1.1",
157
+ "mysql2": "^3.24.6",
152
158
  "pg": "^8.23.0",
153
159
  "prettier": "^3.9.6",
154
160
  "publint": "^0.3.24",
@@ -165,6 +171,8 @@
165
171
  "cross-spawn": "^7.0.6",
166
172
  "fastify-plugin": "^6.0.0",
167
173
  "jose": "^6.2.10",
174
+ "node-sql-parser": "^5.4.0",
175
+ "pgsql-ast-parser": "^12.0.2",
168
176
  "sirv": "^3.0.2"
169
177
  }
170
178
  }