From 67390510e1cac79cda0a8acf915078b7270778e3 Mon Sep 17 00:00:00 2001 From: divyanshujethi Date: Wed, 18 Nov 2026 09:18:04 +0530 Subject: [PATCH 1/2] security(proxy,approval): enforce PG Extended Query AST framing and replay-proof HMAC approval tokens (SEC-08) --- src/approval/index.ts | 1 + src/approval/replay-guard.ts | 159 +++++++++++++ src/proxy/protocol.ts | 104 +++++++++ src/proxy/server.ts | 72 +++++- ...e7-extended-query-and-replay-guard.test.ts | 211 ++++++++++++++++++ 5 files changed, 546 insertions(+), 1 deletion(-) create mode 100644 src/approval/replay-guard.ts create mode 100644 tests/phase7-extended-query-and-replay-guard.test.ts diff --git a/src/approval/index.ts b/src/approval/index.ts index ab71ae6..464a78c 100644 --- a/src/approval/index.ts +++ b/src/approval/index.ts @@ -1,2 +1,3 @@ export * from "./queue.js"; export * from "./chatops.js"; +export * from "./replay-guard.js"; diff --git a/src/approval/replay-guard.ts b/src/approval/replay-guard.ts new file mode 100644 index 0000000..8728d58 --- /dev/null +++ b/src/approval/replay-guard.ts @@ -0,0 +1,159 @@ +/** + * Replay-Proof Cryptographic Approval Token Manager (SEC-08) + * + * Binds every ChatOps 1-click Slack / MS Teams approval token to: + * HMAC-SHA256(secret, normalized_sql_ast + "|" + db_id + "|" + expires_at + "|" + single_use_nonce) + * Enforces short TTL (default 10 minutes / 600s), timing-safe HMAC verification, + * SQL AST immutability, and strict single-use nonce consumption (`403 Token Already Consumed`). + */ + +import crypto from "node:crypto"; + +export interface IssuedApprovalToken { + requestId: string; + dbId: string; + normalizedSqlHash: string; + expiresAt: number; + nonce: string; + signature: string; + token: string; +} + +export interface ApprovalTokenVerification { + valid: boolean; + statusCode: 200 | 401 | 403; + error?: string; +} + +export function normalizeSqlForAstHash(sql: string): string { + return sql + .replace(/\/\*[\s\S]*?\*\//g, " ") + .replace(/--[^\r\n]*/g, " ") + .replace(/\s+/g, " ") + .trim() + .toLowerCase(); +} + +export class ReplayProofApprovalTokenManager { + private readonly secret: string; + private readonly defaultTtlSeconds: number; + private readonly consumedNonces = new Set(); + + constructor( + secret: string = process.env.DBSHIELD_CHATOPS_SECRET || "dbshield-chatops-replay-secret", + defaultTtlSeconds = 600, // 10 minutes + ) { + this.secret = secret; + this.defaultTtlSeconds = defaultTtlSeconds; + } + + private computeSignature( + requestId: string, + normalizedSqlHash: string, + dbId: string, + expiresAt: number, + nonce: string, + ): string { + const canonical = `${requestId}|${normalizedSqlHash}|${dbId}|${expiresAt}|${nonce}`; + return crypto.createHmac("sha256", this.secret).update(canonical).digest("hex"); + } + + public issueToken(options: { + requestId: string; + sql: string; + dbId: string; + ttlSeconds?: number; + }): IssuedApprovalToken { + const normalizedSql = normalizeSqlForAstHash(options.sql); + const normalizedSqlHash = crypto.createHash("sha256").update(normalizedSql).digest("hex"); + const ttl = options.ttlSeconds ?? this.defaultTtlSeconds; + const expiresAt = Math.floor(Date.now() / 1000) + ttl; + const nonce = crypto.randomBytes(16).toString("hex"); + const signature = this.computeSignature( + options.requestId, + normalizedSqlHash, + options.dbId, + expiresAt, + nonce, + ); + const token = Buffer.from( + JSON.stringify({ + requestId: options.requestId, + dbId: options.dbId, + normalizedSqlHash, + expiresAt, + nonce, + signature, + }), + "utf8", + ).toString("base64url"); + + return { + requestId: options.requestId, + dbId: options.dbId, + normalizedSqlHash, + expiresAt, + nonce, + signature, + token, + }; + } + + public verifyAndConsume( + token: string, + expected: { requestId: string; sql: string; dbId: string }, + ): ApprovalTokenVerification { + let decoded: IssuedApprovalToken; + try { + decoded = JSON.parse(Buffer.from(token, "base64url").toString("utf8")) as IssuedApprovalToken; + } catch { + return { valid: false, statusCode: 401, error: "Malformed approval token" }; + } + + if (!decoded.nonce || !decoded.signature || !decoded.expiresAt) { + return { valid: false, statusCode: 401, error: "Incomplete approval token payload" }; + } + + if (this.consumedNonces.has(decoded.nonce)) { + return { valid: false, statusCode: 403, error: "403 Token Already Consumed" }; + } + + const nowSec = Math.floor(Date.now() / 1000); + if (nowSec > decoded.expiresAt) { + return { valid: false, statusCode: 403, error: "403 Approval Token Expired" }; + } + + if (decoded.requestId !== expected.requestId || decoded.dbId !== expected.dbId) { + return { valid: false, statusCode: 403, error: "403 Approval Token Scope Mismatch" }; + } + + const expectedSqlHash = crypto + .createHash("sha256") + .update(normalizeSqlForAstHash(expected.sql)) + .digest("hex"); + if (decoded.normalizedSqlHash !== expectedSqlHash) { + return { + valid: false, + statusCode: 403, + error: "403 SQL AST Hash Mismatch — query tampered after dry-run", + }; + } + + const expectedSig = this.computeSignature( + decoded.requestId, + decoded.normalizedSqlHash, + decoded.dbId, + decoded.expiresAt, + decoded.nonce, + ); + + const a = Buffer.from(decoded.signature, "utf8"); + const b = Buffer.from(expectedSig, "utf8"); + if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) { + return { valid: false, statusCode: 401, error: "Invalid HMAC-SHA256 approval signature" }; + } + + this.consumedNonces.add(decoded.nonce); + return { valid: true, statusCode: 200 }; + } +} diff --git a/src/proxy/protocol.ts b/src/proxy/protocol.ts index 73f8e76..4ecfd8d 100644 --- a/src/proxy/protocol.ts +++ b/src/proxy/protocol.ts @@ -188,6 +188,110 @@ export function parseFrontendFrame( }; } +export interface ParsedParseMessage { + statementName: string; + query: string; +} + +export interface ParsedBindMessage { + portalName: string; + statementName: string; + parameters: Array; +} + +export interface ParsedExecuteMessage { + portalName: string; + maxRows: number; +} + +/** + * Decodes a PostgreSQL Extended Query Parse ('P') frame payload into statementName + query. + */ +export function parseParseMessage(payload: Buffer): ParsedParseMessage | null { + const stmtEnd = payload.indexOf(0); + if (stmtEnd === -1) return null; + const statementName = payload.toString("utf8", 0, stmtEnd); + const queryStart = stmtEnd + 1; + const queryEnd = payload.indexOf(0, queryStart); + if (queryEnd === -1) return null; + const query = payload.toString("utf8", queryStart, queryEnd); + return { statementName, query }; +} + +/** + * Decodes a PostgreSQL Extended Query Bind ('B') frame payload into portalName, statementName, + * and bound parameter string values (supporting NULL parameters with length -1). + */ +export function parseBindMessage(payload: Buffer): ParsedBindMessage | null { + const portalEnd = payload.indexOf(0); + if (portalEnd === -1) return null; + const portalName = payload.toString("utf8", 0, portalEnd); + + const stmtStart = portalEnd + 1; + const stmtEnd = payload.indexOf(0, stmtStart); + if (stmtEnd === -1) return null; + const statementName = payload.toString("utf8", stmtStart, stmtEnd); + + let offset = stmtEnd + 1; + if (offset + 2 > payload.length) { + return { portalName, statementName, parameters: [] }; + } + const formatCount = payload.readInt16BE(offset); + offset += 2 + Math.max(0, formatCount) * 2; + + if (offset + 2 > payload.length) { + return { portalName, statementName, parameters: [] }; + } + const paramCount = payload.readInt16BE(offset); + offset += 2; + + const parameters: Array = []; + for (let i = 0; i < paramCount; i++) { + if (offset + 4 > payload.length) break; + const paramLen = payload.readInt32BE(offset); + offset += 4; + if (paramLen === -1) { + parameters.push(null); + } else if (paramLen >= 0 && offset + paramLen <= payload.length) { + parameters.push(payload.toString("utf8", offset, offset + paramLen)); + offset += paramLen; + } else { + break; + } + } + + return { portalName, statementName, parameters }; +} + +/** + * Decodes a PostgreSQL Extended Query Execute ('E') frame payload into portalName + maxRows. + */ +export function parseExecuteMessage(payload: Buffer): ParsedExecuteMessage | null { + const portalEnd = payload.indexOf(0); + if (portalEnd === -1) return null; + const portalName = payload.toString("utf8", 0, portalEnd); + const maxRows = portalEnd + 5 <= payload.length ? payload.readInt32BE(portalEnd + 1) : 0; + return { portalName, maxRows }; +} + +/** + * Reconstructs parameterized PostgreSQL SQL ($1, $2, ...) with bound values for AST guardrail inspection. + */ +export function reconstructParameterizedSql( + templateSql: string, + params: Array, +): string { + if (!params || params.length === 0) return templateSql; + return templateSql.replace(/\$(\d+)\b/g, (full, idxStr) => { + const idx = Number.parseInt(idxStr, 10) - 1; + if (idx < 0 || idx >= params.length) return full; + const val = params[idx]; + if (val === null) return "NULL"; + if (/^-?\d+(?:\.\d+)?$/.test(val)) return val; + return `'${val.replace(/'/g, "''")}'`; + }); +} + /** * Extract SQL query string from a Query ('Q') or Parse ('P') packet payload. */ diff --git a/src/proxy/server.ts b/src/proxy/server.ts index 4521785..0aaf22f 100644 --- a/src/proxy/server.ts +++ b/src/proxy/server.ts @@ -11,7 +11,11 @@ import { encodeReadyForQuery, encodeSslDenial, extractSqlFromPayload, + parseBindMessage, + parseExecuteMessage, parseFrontendFrame, + parseParseMessage, + reconstructParameterizedSql, } from "./protocol.js"; export interface PostgresWireProxyOptions { @@ -188,6 +192,10 @@ export class PostgresWireProxy { let inErrorState = false; let upstreamConnected = false; const queuedClientPackets: Buffer[] = []; + // Per-connection Extended Query ('P'/'B'/'E') prepared statement & portal tracker (SEC-08) + const preparedStatements = new Map(); + const boundPortals = new Map(); + const blockedPortals = new Set(); // Create upstream connection to target PostgreSQL server const upstreamSocket = new net.Socket(); @@ -325,13 +333,18 @@ export class PostgresWireProxy { // Post-startup message handling if (message.type === "Query" || message.type === "Parse") { this.stats.queriesProcessed++; - const sql = extractSqlFromPayload(message.type, message.payload); + const parsedStmt = message.type === "Parse" ? parseParseMessage(message.payload) : null; + const sql = parsedStmt?.query ?? extractSqlFromPayload(message.type, message.payload); if (!sql || !sql.trim()) { forwardToUpstream(message.raw); continue; } + if (parsedStmt) { + preparedStatements.set(parsedStmt.statementName, parsedStmt.query); + } + // Evaluate SQL with DBShield guardrails const startTime = Date.now(); const evaluation = this.evaluateQuery(sql); @@ -453,11 +466,68 @@ export class PostgresWireProxy { // Reset error state and send ReadyForQuery clientSocket.write(encodeReadyForQuery("I")); inErrorState = false; + blockedPortals.clear(); } // Discard Bind, Execute, Describe while in error state continue; } + // Extended Query Bind ('B'): reconstruct bound SQL ($1, $2, ...) & re-evaluate guardrails (SEC-08) + if (message.type === "Bind") { + const bindMsg = parseBindMessage(message.payload); + if (bindMsg) { + const templateSql = preparedStatements.get(bindMsg.statementName); + if (templateSql) { + const reconstructedSql = reconstructParameterizedSql(templateSql, bindMsg.parameters); + boundPortals.set(bindMsg.portalName, { + statementName: bindMsg.statementName, + reconstructedSql, + }); + const bindEval = this.evaluateQuery(reconstructedSql); + if (!bindEval.allowed) { + this.stats.queriesIntercepted++; + inErrorState = true; + blockedPortals.add(bindMsg.portalName); + const primaryViolation = bindEval.violations[0]; + this.logger.log({ + auditId: `audit-proxy-bind-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`, + timestamp: new Date().toISOString(), + sql: reconstructedSql, + status: "BLOCKED", + riskLevel: bindEval.riskLevel, + riskScore: bindEval.riskScore, + operation: bindEval.operation, + violations: bindEval.violations.map((v) => `${v.code}: ${v.message}`), + }); + clientSocket.write( + encodeErrorResponse({ + severity: "ERROR", + code: "42501", + message: `[DBSHIELD_INTERCEPTED] Extended Query Bind blocked: ${primaryViolation?.message || "Policy violation"}`, + detail: `Risk Level: ${bindEval.riskLevel} | Statement: ${bindMsg.statementName || "(unnamed)"}`, + }), + ); + continue; + } + } + } + } + + // Extended Query Execute ('E'): enforce block if portal was flagged + if (message.type === "Execute") { + const execMsg = parseExecuteMessage(message.payload); + if (execMsg && blockedPortals.has(execMsg.portalName)) { + clientSocket.write( + encodeErrorResponse({ + severity: "ERROR", + code: "42501", + message: "[DBSHIELD_INTERCEPTED] Extended Query Execute blocked by DBShield policy", + }), + ); + continue; + } + } + // Forward all other protocol packets (Sync, Bind, Execute, Terminate, Password, etc.) forwardToUpstream(message.raw); } diff --git a/tests/phase7-extended-query-and-replay-guard.test.ts b/tests/phase7-extended-query-and-replay-guard.test.ts new file mode 100644 index 0000000..015d57c --- /dev/null +++ b/tests/phase7-extended-query-and-replay-guard.test.ts @@ -0,0 +1,211 @@ +import assert from "node:assert/strict"; +import net from "node:net"; +import test from "node:test"; +import { ReplayProofApprovalTokenManager } from "../src/approval/replay-guard.js"; +import { + parseBindMessage, + parseExecuteMessage, + parseParseMessage, + reconstructParameterizedSql, +} from "../src/proxy/protocol.js"; +import { PostgresWireProxy } from "../src/proxy/server.js"; + +function encodeStartupPacket(user = "agent", database = "prod"): Buffer { + const body = Buffer.from(`user\0${user}\0database\0${database}\0\0`, "utf8"); + const buf = Buffer.alloc(8 + body.length); + buf.writeInt32BE(8 + body.length, 0); + buf.writeInt32BE(196608, 4); + body.copy(buf, 8); + return buf; +} + +function encodeParseFrame(statementName: string, query: string): Buffer { + const stmtBuf = Buffer.from(`${statementName}\0`, "utf8"); + const queryBuf = Buffer.from(`${query}\0`, "utf8"); + const paramCount = Buffer.alloc(2); + paramCount.writeInt16BE(0, 0); + const body = Buffer.concat([stmtBuf, queryBuf, paramCount]); + const header = Buffer.alloc(5); + header.writeUInt8(0x50, 0); // 'P' + header.writeInt32BE(4 + body.length, 1); + return Buffer.concat([header, body]); +} + +function encodeBindFrame(portalName: string, statementName: string, params: string[]): Buffer { + const parts: Buffer[] = [ + Buffer.from(`${portalName}\0`, "utf8"), + Buffer.from(`${statementName}\0`, "utf8"), + ]; + const fmtCount = Buffer.alloc(2); + fmtCount.writeInt16BE(0, 0); + parts.push(fmtCount); + + const pCount = Buffer.alloc(2); + pCount.writeInt16BE(params.length, 0); + parts.push(pCount); + + for (const p of params) { + const valBuf = Buffer.from(p, "utf8"); + const lenBuf = Buffer.alloc(4); + lenBuf.writeInt32BE(valBuf.length, 0); + parts.push(lenBuf, valBuf); + } + + const resFmtCount = Buffer.alloc(2); + resFmtCount.writeInt16BE(0, 0); + parts.push(resFmtCount); + + const body = Buffer.concat(parts); + const header = Buffer.alloc(5); + header.writeUInt8(0x42, 0); // 'B' + header.writeInt32BE(4 + body.length, 1); + return Buffer.concat([header, body]); +} + +function encodeExecuteFrame(portalName = "", maxRows = 0): Buffer { + const portalBuf = Buffer.from(`${portalName}\0`, "utf8"); + const rowsBuf = Buffer.alloc(4); + rowsBuf.writeInt32BE(maxRows, 0); + const body = Buffer.concat([portalBuf, rowsBuf]); + const header = Buffer.alloc(5); + header.writeUInt8(0x45, 0); // 'E' + header.writeInt32BE(4 + body.length, 1); + return Buffer.concat([header, body]); +} + +function encodeSyncFrame(): Buffer { + const buf = Buffer.alloc(5); + buf.writeUInt8(0x53, 0); // 'S' + buf.writeInt32BE(4, 1); + return buf; +} + +test("Phase 7 (SEC-08): Decodes PostgreSQL Extended Query P/B/E frames & reconstructs bound SQL", () => { + const parseFrame = encodeParseFrame("stmt_1", "DELETE FROM orders WHERE status = $1 AND id = $2"); + const parsedP = parseParseMessage(parseFrame.subarray(5)); + assert.deepEqual(parsedP, { + statementName: "stmt_1", + query: "DELETE FROM orders WHERE status = $1 AND id = $2", + }); + + const bindFrame = encodeBindFrame("portal_1", "stmt_1", ["archived", "42"]); + const parsedB = parseBindMessage(bindFrame.subarray(5)); + assert.deepEqual(parsedB, { + portalName: "portal_1", + statementName: "stmt_1", + parameters: ["archived", "42"], + }); + + const reconstructed = reconstructParameterizedSql(parsedP!.query, parsedB!.parameters); + assert.equal(reconstructed, "DELETE FROM orders WHERE status = 'archived' AND id = 42"); + + const execFrame = encodeExecuteFrame("portal_1", 10); + const parsedE = parseExecuteMessage(execFrame.subarray(5)); + assert.deepEqual(parsedE, { portalName: "portal_1", maxRows: 10 }); +}); + +test("Phase 7 (SEC-08): PostgresWireProxy intercepts destructive Extended Query DROP TABLE & bound tautology", async () => { + const upstreamReceived: Buffer[] = []; + const mockUpstream = net.createServer((sock) => { + sock.on("data", (d) => upstreamReceived.push(d)); + }); + await new Promise((resolve) => mockUpstream.listen(0, "127.0.0.1", resolve)); + const upstreamPort = (mockUpstream.address() as net.AddressInfo).port; + + const proxyPort = 54000 + Math.floor(Math.random() * 5000); + const proxy = new PostgresWireProxy({ + listenHost: "127.0.0.1", + listenPort: proxyPort, + upstreamHost: "127.0.0.1", + upstreamPort, + config: { + dialect: "postgres", + safetyTier: "STRICT", + maxRowsPerMutation: 50, + allowDestructiveDDL: false, + enablePiiMasking: true, + customPiiColumns: [], + }, + }); + + await proxy.start(); + try { + const client = net.createConnection({ host: "127.0.0.1", port: proxyPort }); + const responses: Buffer[] = []; + + await new Promise((resolve, reject) => { + client.on("connect", () => { + client.write(encodeStartupPacket()); + // Send ORM-style Extended Query: Parse('DROP TABLE users') + Bind + Execute + Sync + client.write(encodeParseFrame("orm_drop", "DROP TABLE users;")); + client.write(encodeBindFrame("p1", "orm_drop", [])); + client.write(encodeExecuteFrame("p1", 0)); + client.write(encodeSyncFrame()); + }); + client.on("data", (d) => { + responses.push(d); + const combined = Buffer.concat(responses).toString("utf8"); + if (combined.includes("DBSHIELD_INTERCEPTED")) { + client.end(); + resolve(); + } + }); + client.on("error", reject); + setTimeout(() => reject(new Error("Timed out waiting for proxy ErrorResponse")), 3000); + }); + + const wireText = Buffer.concat(responses).toString("utf8"); + assert.match(wireText, /DBSHIELD_INTERCEPTED/); + assert.equal(proxy.getStats().queriesIntercepted >= 1, true); + // Upstream must NEVER receive the DROP TABLE statement + const upstreamText = Buffer.concat(upstreamReceived).toString("utf8"); + assert.equal(upstreamText.includes("DROP TABLE users"), false); + } finally { + await proxy.stop(); + await new Promise((resolve) => mockUpstream.close(() => resolve())); + } +}); + +test("Phase 7 (SEC-08): ReplayProofApprovalTokenManager rejects replayed Slack webhooks with 403 Token Already Consumed", () => { + const mgr = new ReplayProofApprovalTokenManager("test-replay-secret-key", 600); + const sql = "DELETE FROM sessions WHERE expired = true;"; + const issued = mgr.issueToken({ + requestId: "appr_abc123def456", + sql, + dbId: "prod-pg-01", + }); + + // 1st consumption: 200 OK (whitespace/comment normalization preserved) + const first = mgr.verifyAndConsume(issued.token, { + requestId: "appr_abc123def456", + sql: "DELETE FROM sessions /* cleanup */ WHERE expired = true;", + dbId: "prod-pg-01", + }); + assert.equal(first.valid, true); + assert.equal(first.statusCode, 200); + + // 2nd consumption (Replay Attack): 403 Token Already Consumed + const replay = mgr.verifyAndConsume(issued.token, { + requestId: "appr_abc123def456", + sql, + dbId: "prod-pg-01", + }); + assert.equal(replay.valid, false); + assert.equal(replay.statusCode, 403); + assert.match(replay.error || "", /403 Token Already Consumed/); + + // Tampered SQL AST rejected with 403 + const fresh = mgr.issueToken({ + requestId: "appr_999", + sql: "UPDATE users SET role = 'viewer' WHERE id = 5;", + dbId: "prod-pg-01", + }); + const tampered = mgr.verifyAndConsume(fresh.token, { + requestId: "appr_999", + sql: "UPDATE users SET role = 'superadmin' WHERE id = 5;", + dbId: "prod-pg-01", + }); + assert.equal(tampered.valid, false); + assert.equal(tampered.statusCode, 403); + assert.match(tampered.error || "", /AST Hash Mismatch/); +}); From caf41ba443afd61203a1d567e8ec0290d7246fc9 Mon Sep 17 00:00:00 2001 From: divyanshujethi Date: Wed, 18 Nov 2026 09:21:13 +0530 Subject: [PATCH 2/2] security(approval): replace comment regex with O(n) single-pass scanner to eliminate ReDoS --- src/approval/replay-guard.ts | 68 ++++++++++++++++++++++++++++++++---- 1 file changed, 62 insertions(+), 6 deletions(-) diff --git a/src/approval/replay-guard.ts b/src/approval/replay-guard.ts index 8728d58..8cffde7 100644 --- a/src/approval/replay-guard.ts +++ b/src/approval/replay-guard.ts @@ -26,12 +26,68 @@ export interface ApprovalTokenVerification { } export function normalizeSqlForAstHash(sql: string): string { - return sql - .replace(/\/\*[\s\S]*?\*\//g, " ") - .replace(/--[^\r\n]*/g, " ") - .replace(/\s+/g, " ") - .trim() - .toLowerCase(); + // Single-pass O(n) SQL comment stripper & whitespace normalizer (immune to ReDoS) + const out: string[] = []; + let inBlockComment = false; + let inLineComment = false; + let lastWasSpace = true; + + for (let i = 0; i < sql.length; i++) { + const ch = sql[i]; + const next = i + 1 < sql.length ? sql[i + 1] : ""; + + if (inBlockComment) { + if (ch === "*" && next === "/") { + inBlockComment = false; + i++; + } + continue; + } + + if (inLineComment) { + if (ch === "\n" || ch === "\r") { + inLineComment = false; + if (!lastWasSpace) { + out.push(" "); + lastWasSpace = true; + } + } + continue; + } + + if (ch === "/" && next === "*") { + inBlockComment = true; + if (!lastWasSpace) { + out.push(" "); + lastWasSpace = true; + } + i++; + continue; + } + + if (ch === "-" && next === "-") { + inLineComment = true; + if (!lastWasSpace) { + out.push(" "); + lastWasSpace = true; + } + i++; + continue; + } + + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r" || ch === "\f") { + if (!lastWasSpace) { + out.push(" "); + lastWasSpace = true; + } + continue; + } + + out.push(ch.toLowerCase()); + lastWasSpace = false; + } + + return out.join("").trim(); } export class ReplayProofApprovalTokenManager {