@rebasepro/server 0.29.0-canary.g0e3a0e7 → 0.29.1
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.
- package/dist/{GCSStorageController-Ch3Ridyt.js → GCSStorageController-Crdllv9A.js} +2 -2
- package/dist/{GCSStorageController-Ch3Ridyt.js.map → GCSStorageController-Crdllv9A.js.map} +1 -1
- package/dist/{S3StorageController-CmNMg7Gu.js → S3StorageController-C7x2Yaiz.js} +2 -2
- package/dist/{S3StorageController-CmNMg7Gu.js.map → S3StorageController-C7x2Yaiz.js.map} +1 -1
- package/dist/{access-BZjeLhf5.js → access-BNZBi9yL.js} +5 -5
- package/dist/{access-BZjeLhf5.js.map → access-BNZBi9yL.js.map} +1 -1
- package/dist/api/rest/query-parser.d.ts +13 -14
- package/dist/{ast-schema-editor-Dg7BWKE3.js → ast-schema-editor-D56sGr0L.js} +2 -2
- package/dist/{ast-schema-editor-Dg7BWKE3.js.map → ast-schema-editor-D56sGr0L.js.map} +1 -1
- package/dist/{auth-CSWKaSgJ.js → auth-CV82Wvq1.js} +18 -10
- package/dist/auth-CV82Wvq1.js.map +1 -0
- package/dist/{backup-woinIDjt.js → backup-BiAhhHKV.js} +6 -6
- package/dist/{backup-woinIDjt.js.map → backup-BiAhhHKV.js.map} +1 -1
- package/dist/{branch-routes-F5VIJrZp.js → branch-routes-DqKPRFtb.js} +2 -2
- package/dist/{branch-routes-F5VIJrZp.js.map → branch-routes-DqKPRFtb.js.map} +1 -1
- package/dist/{contract-routes-D8Vsxjx8.js → contract-routes-AD3hi7ad.js} +2 -2
- package/dist/{contract-routes-D8Vsxjx8.js.map → contract-routes-AD3hi7ad.js.map} +1 -1
- package/dist/{cron-loader-n9Uh_E1a.js → cron-loader-D1zNARNU.js} +2 -2
- package/dist/{cron-loader-n9Uh_E1a.js.map → cron-loader-D1zNARNU.js.map} +1 -1
- package/dist/{cron-routes-mLexIC9F.js → cron-routes-BtB2VVTk.js} +3 -3
- package/dist/{cron-routes-mLexIC9F.js.map → cron-routes-BtB2VVTk.js.map} +1 -1
- package/dist/{cron-scheduler-DhxuCDuI.js → cron-scheduler-DEKiJh_G.js} +2 -2
- package/dist/{cron-scheduler-DhxuCDuI.js.map → cron-scheduler-DEKiJh_G.js.map} +1 -1
- package/dist/{cron-store-DzKz7jXF.js → cron-store-DcaNQIAr.js} +5 -5
- package/dist/cron-store-DcaNQIAr.js.map +1 -0
- package/dist/data_driver-D0mg1Y_x.js.map +1 -1
- package/dist/dist-BpP9FwVH.js +19359 -0
- package/dist/dist-BpP9FwVH.js.map +1 -0
- package/dist/{field-access-CzKjatID.js → field-access-BHi-4uSo.js} +2 -2
- package/dist/{field-access-CzKjatID.js.map → field-access-BHi-4uSo.js.map} +1 -1
- package/dist/{filter-dialect-C5wfpopB.js → filter-dialect-Cbzt7lO9.js} +2 -2
- package/dist/filter-dialect-Cbzt7lO9.js.map +1 -0
- package/dist/{function-routes-CQ0z3WDt.js → function-routes-CdtIKSV8.js} +28 -2
- package/dist/function-routes-CdtIKSV8.js.map +1 -0
- package/dist/functions/context.d.ts +23 -1
- package/dist/functions/index.d.ts +1 -1
- package/dist/functions/index.js +27 -1
- package/dist/functions/index.js.map +1 -1
- package/dist/{history-recorder-wkBuX7Np.js → history-recorder-C8FBGUa9.js} +3 -3
- package/dist/{history-recorder-wkBuX7Np.js.map → history-recorder-C8FBGUa9.js.map} +1 -1
- package/dist/{history-store-D-jDz4Nv.js → history-store-DL-ydprp.js} +2 -2
- package/dist/{history-store-D-jDz4Nv.js.map → history-store-DL-ydprp.js.map} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.es.js +186 -83
- package/dist/index.es.js.map +1 -1
- package/dist/{internal-tables-CRaBxJeE.js → internal-tables-D2IdQlUW.js} +75 -15
- package/dist/internal-tables-D2IdQlUW.js.map +1 -0
- package/dist/jobs/job-queue.d.ts +10 -0
- package/dist/{jobs-D61qYEGt.js → jobs-DK9ra01Y.js} +6 -11
- package/dist/jobs-DK9ra01Y.js.map +1 -0
- package/dist/{jwt-CBmQXYs-.js → jwt-iiP_ZZzR.js} +2 -2
- package/dist/{jwt-CBmQXYs-.js.map → jwt-iiP_ZZzR.js.map} +1 -1
- package/dist/{keys-Cd_4l48g.js → keys-krxEEEj4.js} +2 -2
- package/dist/{keys-Cd_4l48g.js.map → keys-krxEEEj4.js.map} +1 -1
- package/dist/mcp/mcp-tools.d.ts +13 -2
- package/dist/mcp/show-app-guide.d.ts +19 -0
- package/dist/{offline-BjJdcVBb-B_bOcnDC.js → offline-Cy6woFyt-CbjOQGD1.js} +14 -5
- package/dist/offline-Cy6woFyt-CbjOQGD1.js.map +1 -0
- package/dist/{offline-store-Cxhh99Q--DQ-M1M8d.js → offline-store-C2Sy3Kwl-C8KIwabG.js} +16 -6
- package/dist/offline-store-C2Sy3Kwl-C8KIwabG.js.map +1 -0
- package/dist/{openapi-generator-B3LsKCon.js → openapi-generator-Cn-ytCH8.js} +4 -4
- package/dist/{openapi-generator-B3LsKCon.js.map → openapi-generator-Cn-ytCH8.js.map} +1 -1
- package/dist/{query-parser-C90z8csB.js → query-parser-CTiEg64k.js} +135 -29
- package/dist/query-parser-CTiEg64k.js.map +1 -0
- package/dist/{rls-simulator-routes-igGu-giT.js → rls-simulator-routes-5nbuDwWR.js} +3 -3
- package/dist/{rls-simulator-routes-igGu-giT.js.map → rls-simulator-routes-5nbuDwWR.js.map} +1 -1
- package/dist/{schema-editor-routes-kF1ZKCB2.js → schema-editor-routes-Bi8S1gn7.js} +3 -3
- package/dist/{schema-editor-routes-kF1ZKCB2.js.map → schema-editor-routes-Bi8S1gn7.js.map} +1 -1
- package/dist/{sql-export-routes-DObpbf8x.js → sql-export-routes-XkcXbxw5.js} +2 -2
- package/dist/{sql-export-routes-DObpbf8x.js.map → sql-export-routes-XkcXbxw5.js.map} +1 -1
- package/dist/{src-BXDkXOtq.js → src-0nCWajy7.js} +56 -15
- package/dist/src-0nCWajy7.js.map +1 -0
- package/package.json +5 -5
- package/dist/auth-CSWKaSgJ.js.map +0 -1
- package/dist/cron-store-DzKz7jXF.js.map +0 -1
- package/dist/dist-B4YtgTMh.js +0 -19359
- package/dist/dist-B4YtgTMh.js.map +0 -1
- package/dist/filter-dialect-C5wfpopB.js.map +0 -1
- package/dist/function-routes-CQ0z3WDt.js.map +0 -1
- package/dist/internal-tables-CRaBxJeE.js.map +0 -1
- package/dist/jobs-D61qYEGt.js.map +0 -1
- package/dist/offline-BjJdcVBb-B_bOcnDC.js.map +0 -1
- package/dist/offline-store-Cxhh99Q--DQ-M1M8d.js.map +0 -1
- package/dist/query-parser-C90z8csB.js.map +0 -1
- package/dist/src-BXDkXOtq.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-editor-routes-
|
|
1
|
+
{"version":3,"file":"schema-editor-routes-Bi8S1gn7.js","names":[],"sources":["../src/schema-edit/source-editor.ts","../src/api/schema-editor-routes.ts"],"sourcesContent":["import type { AstSchemaEditor } from \"../api/ast-schema-editor\";\n\n/**\n * The process's editor of the collection source files, one edit at a time.\n *\n * Two routers rewrite those files: the source-only editor\n * (`/api/schema-editor/*`) and live schema editing's `/apply`. Both go through\n * this one {@link AstSchemaEditor}, so the ts-morph project over the\n * collections directory is parsed once per process rather than once per\n * apply — 180–250 ms of blocked event loop at 200 collection files, on every\n * save. The editor re-reads the disk at the start of each edit\n * (`syncWithDisk`): a file changed since — by the IDE, by a commit being put\n * back — is refreshed, a new one is added, a deleted one is dropped.\n *\n * One project cannot take two edits at once. An edit holds unsaved changes in\n * memory across `await project.save()`, and a second edit arriving meanwhile\n * would refresh those files from disk under it, or save them with its own.\n * So every edit, from either router, waits in one queue for the edits before\n * it to settle — a refused one included — and anything an edit does with the\n * files it wrote (reading them back for a commit) belongs inside the same\n * {@link run}, before the next edit can touch them.\n */\nexport class SchemaSourceEditor {\n private settled: Promise<unknown> = Promise.resolve();\n\n constructor(private readonly editor: AstSchemaEditor) {\n }\n\n /** Run `edit` once every edit queued before it has finished. */\n run<T>(edit: (editor: AstSchemaEditor) => Promise<T>): Promise<T> {\n const result = this.settled.then(() => edit(this.editor));\n this.settled = result.then(() => undefined, () => undefined);\n return result;\n }\n}\n","import { Hono } from \"hono\";\nimport { z } from \"zod\";\nimport { collectionPatchProblems, isCollectionPatch } from \"@rebasepro/types\";\nimport { AstSchemaEditor } from \"./ast-schema-editor\";\nimport { SchemaSourceEditor } from \"../schema-edit/source-editor\";\nimport { ApiError, errorHandler } from \"./errors\";\nimport { HonoEnv } from \"./types\";\n\n/**\n * Rewriting collection source from the admin panel.\n *\n * Every refusal in `AstSchemaEditor` is written for the person who will read it\n * — \"Collection X has no file at …\", \"Relation Y has no target collection. Pick\n * one before saving.\" — and every one of them was a plain `Error`, which\n * `errorHandler` treats as an unexpected failure: 500, and a body that says\n * \"Internal Server Error\". The messages never left the server. They are 400s\n * now, so the panel can show what it was told.\n */\nfunction refusalsAsBadRequest<T>(run: () => Promise<T>): Promise<T> {\n return run().catch((error: unknown) => {\n if (error instanceof ApiError) throw error;\n throw ApiError.badRequest(\n error instanceof Error ? error.message : String(error),\n \"SCHEMA_EDIT_REFUSED\"\n );\n });\n}\n\n/** The identifier half of every payload here, checked once. */\nconst collectionIdSchema = z.string().min(1, \"`collectionId` is required\");\nconst propertyKeySchema = z.string().min(1, \"`propertyKey` is required\");\n\nconst propertySaveSchema = z.object({\n collectionId: collectionIdSchema,\n propertyKey: propertyKeySchema,\n propertyConfig: z.record(z.string(), z.unknown())\n});\nconst propertyDeleteSchema = z.object({\n collectionId: collectionIdSchema,\n propertyKey: propertyKeySchema\n});\nconst collectionSaveSchema = z.object({\n collectionId: collectionIdSchema,\n collectionData: z.record(z.string(), z.unknown()).optional(),\n /** What changed about an existing collection — see `collection_patch.ts`. */\n patch: z.array(z.unknown()).optional(),\n partial: z.boolean().optional()\n}).refine(\n save => (save.collectionData === undefined) !== (save.patch === undefined),\n { message: \"send `patch` (what changed) or `collectionData` (a new collection), not both\" }\n);\nconst collectionDeleteSchema = z.object({\n collectionId: collectionIdSchema\n});\n\n/** Parse a body against a schema, or 400 naming the field. */\nasync function body<S extends z.ZodType>(c: { req: { json: () => Promise<unknown> } }, schema: S): Promise<z.infer<S>> {\n const raw = await c.req.json().catch(() => undefined);\n const parsed = schema.safeParse(raw);\n if (!parsed.success) {\n throw ApiError.badRequest(\n parsed.error.issues.map(i => `${i.path.join(\".\") || \"body\"}: ${i.message}`).join(\"; \"),\n \"INVALID_INPUT\"\n );\n }\n return parsed.data;\n}\n\n/**\n * The editor for `collectionsDir`: one per process, shared by these routes\n * and live schema editing's `/apply`. See {@link SchemaSourceEditor}.\n *\n * Here rather than beside the class because building it loads `ts-morph`, an\n * optional peer dependency this module is imported to probe for.\n */\nexport function createSchemaSourceEditor(collectionsDir: string): SchemaSourceEditor {\n return new SchemaSourceEditor(new AstSchemaEditor(collectionsDir));\n}\n\nexport function createSchemaEditorRoutes(source: SchemaSourceEditor): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n router.onError(errorHandler);\n\n router.post(\"/property/save\", async (c) => {\n const { collectionId, propertyKey, propertyConfig } = await body(c, propertySaveSchema);\n await refusalsAsBadRequest(() => source.run(editor => editor.saveProperty(collectionId, propertyKey, propertyConfig)));\n return c.json({ success: true });\n });\n\n router.post(\"/property/delete\", async (c) => {\n const { collectionId, propertyKey } = await body(c, propertyDeleteSchema);\n await refusalsAsBadRequest(() => source.run(editor => editor.deleteProperty(collectionId, propertyKey)));\n return c.json({ success: true });\n });\n\n /**\n * `partial: true` means \"this payload is what changed\", not \"this is the\n * collection\". Without it a one-key patch — which is what adding a column\n * posts — is read as a whole-collection save and deletes everything it does\n * not mention, `securityRules` included. Absent, it defaults to a full save,\n * so an older panel keeps the behaviour it was written against.\n */\n router.post(\"/collection/save\", async (c) => {\n const { collectionId, collectionData, patch, partial } = await body(c, collectionSaveSchema);\n if (patch !== undefined && !isCollectionPatch(patch)) {\n throw ApiError.badRequest(collectionPatchProblems(patch).join(\" \"), \"INVALID_INPUT\");\n }\n await refusalsAsBadRequest(() => source.run(editor => patch\n ? editor.applyPatch(collectionId, patch)\n : editor.saveCollection(collectionId, collectionData ?? {}, { partial: partial === true })));\n return c.json({ success: true });\n });\n\n router.post(\"/collection/delete\", async (c) => {\n const { collectionId } = await body(c, collectionDeleteSchema);\n await refusalsAsBadRequest(() => source.run(editor => editor.deleteCollection(collectionId)));\n return c.json({ success: true });\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,qBAAb,MAAgC;CAGC;CAF7B,UAAoC,QAAQ,QAAQ;CAEpD,YAAY,QAA0C;EAAzB,KAAA,SAAA;CAC7B;;CAGA,IAAO,MAA2D;EAC9D,MAAM,SAAS,KAAK,QAAQ,WAAW,KAAK,KAAK,MAAM,CAAC;EACxD,KAAK,UAAU,OAAO,WAAW,KAAA,SAAiB,KAAA,CAAS;EAC3D,OAAO;CACX;AACJ;;;;;;;;;;;;;AChBA,SAAS,qBAAwB,KAAmC;CAChE,OAAO,IAAI,CAAC,CAAC,OAAO,UAAmB;EACnC,IAAI,iBAAiB,UAAU,MAAM;EACrC,MAAM,SAAS,WACX,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACrD,qBACJ;CACJ,CAAC;AACL;;AAGA,IAAM,qBAAqB,EAAE,OAAO,CAAC,CAAC,IAAI,GAAG,4BAA4B;AACzE,IAAM,oBAAoB,EAAE,OAAO,CAAC,CAAC,IAAI,GAAG,2BAA2B;AAEvE,IAAM,qBAAqB,EAAE,OAAO;CAChC,cAAc;CACd,aAAa;CACb,gBAAgB,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC;AACpD,CAAC;AACD,IAAM,uBAAuB,EAAE,OAAO;CAClC,cAAc;CACd,aAAa;AACjB,CAAC;AACD,IAAM,uBAAuB,EAAE,OAAO;CAClC,cAAc;CACd,gBAAgB,EAAE,OAAO,EAAE,OAAO,GAAG,E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,WAAW,CAAC,CAAC;EACvG,OAAO,EAAE,KAAK,EAAE,SAAS,KAAK,CAAC;CACnC,CAAC;;;;;;;;CASD,OAAO,KAAK,oBAAoB,OAAO,MAAM;EACzC,MAAM,EAAE,cAAc,gBAAgB,OAAO,YAAY,MAAM,KAAK,GAAG,oBAAoB;EAC3F,IAAI,UAAU,KAAA,KAAa,CAAC,kBAAkB,KAAK,GAC/C,MAAM,SAAS,WAAW,wBAAwB,KAAK,CAAC,CAAC,KAAK,GAAG,GAAG,eAAe;EAEvF,MAAM,2BAA2B,OAAO,KAAI,WAAU,QAChD,OAAO,WAAW,cAAc,KAAK,IACrC,OAAO,eAAe,cAAc,kBAAkB,CAAC,GAAG,EAAE,SAAS,YAAY,KAAK,CAAC,CAAC,CAAC;EAC/F,OAAO,EAAE,KAAK,EAAE,SAAS,KAAK,CAAC;CACnC,CAAC;CAED,OAAO,KAAK,sBAAsB,OAAO,MAAM;EAC3C,MAAM,EAAE,iBAAiB,MAAM,KAAK,GAAG,sBAAsB;EAC7D,MAAM,2BAA2B,OAAO,KAAI,WAAU,OAAO,iBAAiB,YAAY,CAAC,CAAC;EAC5F,OAAO,EAAE,KAAK,EAAE,SAAS,KAAK,CAAC;CACnC,CAAC;CAED,OAAO;AACX"}
|
|
@@ -2,7 +2,7 @@ import { createRequire as __rebaseCreateRequire } from "module";
|
|
|
2
2
|
import __rebaseProcess from "process";
|
|
3
3
|
globalThis.process ??= __rebaseProcess;
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
|
-
import "./src-
|
|
5
|
+
import "./src-0nCWajy7.js";
|
|
6
6
|
import { n as isSQLAdmin } from "./backend-CaG_Jyso.js";
|
|
7
7
|
import { a as logger } from "./logger-SigQ2oZJ.js";
|
|
8
8
|
import { t as ApiError } from "./errors-DpTMfX77.js";
|
|
@@ -271,4 +271,4 @@ function createSqlExportRoutes(options) {
|
|
|
271
271
|
//#endregion
|
|
272
272
|
export { createSqlExportRoutes };
|
|
273
273
|
|
|
274
|
-
//# sourceMappingURL=sql-export-routes-
|
|
274
|
+
//# sourceMappingURL=sql-export-routes-XkcXbxw5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sql-export-routes-DObpbf8x.js","names":[],"sources":["../../utils/dist/csv.es.js","../../common/src/util/sql-redaction.ts","../src/api/sql-export-routes.ts"],"sourcesContent":["//#region src/csv.ts\n/**\n* Characters that make a spreadsheet read a cell as a formula rather than text.\n*\n* Quoting is CSV *escaping* and is not enough: Excel, LibreOffice Calc and\n* Sheets strip the CSV quoting at parse time and then evaluate a cell whose\n* first character is one of these — `=HYPERLINK(…)` exfiltrates neighbouring\n* cells on click, `=cmd|'…'!A0` is worse.\n*/\nvar FORMULA_TRIGGERS = [\n\t\"=\",\n\t\"+\",\n\t\"-\",\n\t\"@\",\n\t\"\t\",\n\t\"\\r\"\n];\n/**\n* Neutralise a cell that a spreadsheet would otherwise evaluate, by prefixing a\n* single quote — the standard OWASP mitigation. The apostrophe is consumed by\n* the spreadsheet as \"treat the rest as text\", so the value reads back intact.\n*/\nfunction escapeCsvFormula(value) {\n\tconst first = value.charAt(0);\n\tif (!FORMULA_TRIGGERS.includes(first)) return value;\n\tif ((first === \"-\" || first === \"+\") && value.trim() !== \"\" && Number.isFinite(Number(value))) return value;\n\treturn \"'\" + value;\n}\n/**\n* The inverse of {@link escapeCsvFormula}, for a file read back in: a cell that\n* is an apostrophe followed by a formula trigger loses the apostrophe, as it\n* does when a spreadsheet reads it. Any other apostrophe is text.\n*/\nfunction unescapeCsvFormula(value) {\n\treturn value.charAt(0) === \"'\" && FORMULA_TRIGGERS.includes(value.charAt(1)) ? value.slice(1) : value;\n}\n/**\n* One CSV field (RFC 4180): quoted when it holds a comma, a quote or a line\n* break, with each quote doubled. SQL NULL — `null` or `undefined` — is an\n* empty field, as `COPY … CSV` writes it; an object (a plan, a parsed `jsonb`)\n* is its JSON.\n*\n* Text a spreadsheet would run as a formula (`=…`, `+…`, `-…`, `@…`, a leading\n* tab or carriage return) gets a leading `'` ({@link escapeCsvFormula}), as\n* the CMS export has always done; a signed number is left a number. Every CSV\n* the product writes goes through here, so a file opened in Excel or Sheets\n* never evaluates a cell — at the cost of not being byte-identical to\n* `COPY … CSV` for such cells.\n*/\nfunction csvField(value) {\n\tif (value === null || value === void 0) return \"\";\n\tconst text = escapeCsvFormula(typeof value === \"object\" ? JSON.stringify(value) : String(value));\n\treturn /[\",\\r\\n]/.test(text) ? `\"${text.replace(/\"/g, \"\\\"\\\"\")}\"` : text;\n}\n/** One CSV record: each value through {@link csvField}, separated by commas, with no line break. */\nfunction csvRecord(values) {\n\treturn values.map(csvField).join(\",\");\n}\n//#endregion\nexport { csvField, csvRecord, escapeCsvFormula, unescapeCsvFormula };\n\n//# sourceMappingURL=csv.es.js.map","/**\n * SQL a person ran, as the audit log may keep it: every string literal masked.\n *\n * The SQL console's audit line wrote the statement verbatim, so `ALTER ROLE app\n * PASSWORD 'hunter2'`, `CREATE USER MAPPING … OPTIONS (password 'hunter2')` and\n * `dblink_connect('host=db password=hunter2')` put the password in the\n * production logs, where the logger's redaction — by key name — never looks.\n *\n * A literal is a value the statement carries inline, which is exactly what the\n * line already declines to write when it is bound as a parameter: the\n * statement's shape is the audit signal, the values are whatever the operator\n * was touching. So every literal goes, not only the ones beside a word that\n * looks like `password` — a secret has no reliable neighbour. Identifiers,\n * keywords, numbers and comments stay.\n *\n * Read with Postgres's own lexical rules, not a regular expression over the\n * text: a quote inside a comment, a doubled quote, an `E'…\\'…'` escape or a\n * `$tag$` body must not shift where a literal is thought to end, or the mask\n * covers the statement and leaves the secret.\n */\nexport function redactSqlLiterals(sql: string): string {\n let out = \"\";\n let i = 0;\n while (i < sql.length) {\n const char = sql[i];\n const next = sql[i + 1];\n\n // -- line comment\n if (char === \"-\" && next === \"-\") {\n const end = sql.indexOf(\"\\n\", i);\n const stop = end === -1 ? sql.length : end;\n out += sql.slice(i, stop);\n i = stop;\n continue;\n }\n\n // /* block comment */ — nested, as Postgres reads them\n if (char === \"/\" && next === \"*\") {\n let depth = 1;\n let j = i + 2;\n while (j < sql.length && depth > 0) {\n if (sql[j] === \"/\" && sql[j + 1] === \"*\") { depth++; j += 2; } else if (sql[j] === \"*\" && sql[j + 1] === \"/\") { depth--; j += 2; } else j++;\n }\n out += sql.slice(i, j);\n i = j;\n continue;\n }\n\n // \"quoted identifier\"\n if (char === \"\\\"\") {\n const end = closingQuote(sql, i + 1, \"\\\"\", false);\n out += sql.slice(i, end);\n i = end;\n continue;\n }\n\n // 'string', E'string' with backslash escapes, and the B'', X'', N'',\n // U&'' prefixes — the prefix is kept, the content masked.\n if (char === \"'\") {\n const prefix = /(?:^|[^A-Za-z0-9_$])([EeBbXxNn]|[Uu]&)$/.exec(out)?.[1] ?? \"\";\n out += \"'***'\";\n i = closingQuote(sql, i + 1, \"'\", prefix.toUpperCase() === \"E\");\n continue;\n }\n\n // $tag$ … $tag$ — a dollar-quoted string. A function or DO body is SQL\n // in its own right, and its literals are masked as these are; a\n // password written as `PASSWORD $$hunter2$$` is masked whole.\n if (char === \"$\") {\n const tag = /^\\$([A-Za-z_][A-Za-z0-9_]*)?\\$/.exec(sql.slice(i));\n const precededByIdentifier = /[A-Za-z0-9_]$/.test(out);\n if (tag && !precededByIdentifier) {\n const delimiter = tag[0];\n const bodyStart = i + delimiter.length;\n const bodyEnd = sql.indexOf(delimiter, bodyStart);\n const stop = bodyEnd === -1 ? sql.length : bodyEnd;\n const body = sql.slice(bodyStart, stop);\n const isPassword = /\\bpassword\\s*$/i.test(out);\n out += delimiter + (isPassword ? \"***\" : redactSqlLiterals(body)) + (bodyEnd === -1 ? \"\" : delimiter);\n i = bodyEnd === -1 ? sql.length : bodyEnd + delimiter.length;\n continue;\n }\n }\n\n out += char;\n i++;\n }\n return out;\n}\n\n/**\n * The index just past the quote that closes a literal or identifier opened\n * before `from`. A doubled quote is one quote inside it; with `backslashEscapes`\n * (an `E''` string) so is a backslash-escaped one. Unterminated runs to the end.\n */\nfunction closingQuote(sql: string, from: number, quote: string, backslashEscapes: boolean): number {\n let j = from;\n while (j < sql.length) {\n if (backslashEscapes && sql[j] === \"\\\\\") { j += 2; continue; }\n if (sql[j] === quote) {\n if (sql[j + 1] === quote) { j += 2; continue; }\n return j + 1;\n }\n j++;\n }\n return sql.length;\n}\n","import { Hono } from \"hono\";\nimport { isSQLAdmin, type DatabaseAdmin, type SqlCursor } from \"@rebasepro/types\";\nimport { redactSqlLiterals } from \"@rebasepro/common\";\nimport { csvRecord } from \"@rebasepro/utils\";\nimport { ApiError } from \"./errors\";\nimport type { HonoEnv } from \"./types\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * The SQL console's \"Download full result as CSV\".\n *\n * The console shows at most the first 10,000 rows of a result (see\n * `SQL_CONSOLE_RESULT_LIMITS`), and its own export writes the rows on screen.\n * This route is the way to the rest: it runs ONE query through\n * `SQLAdmin.openSqlCursor` — a server-side cursor in a read-only transaction,\n * as the role the console picked — and streams it as RFC 4180 CSV, one batch\n * at a time. A batch is fetched only when the response has taken the last\n * one, so the server holds one batch however long the result is.\n *\n * Mounted under `/api/admin/sql` behind the admin gate with `database:write` —\n * the scope the socket's `EXECUTE_SQL` asks of the same console, so whoever\n * can run the query can download it and nobody else.\n */\n\n/** RFC 4180's record separator. */\nconst CRLF = \"\\r\\n\";\n\nexport interface SqlExportRoutesOptions {\n /** The default data source's admin capabilities, read per request. */\n getAdmin: () => DatabaseAdmin | undefined;\n}\n\ninterface ExportRequest {\n sql: string;\n database?: string;\n role?: string;\n}\n\nfunction readExportRequest(body: unknown): ExportRequest {\n if (typeof body !== \"object\" || body === null || !(\"sql\" in body) || typeof body.sql !== \"string\" || body.sql.trim() === \"\") {\n throw ApiError.badRequest(\"Send the query to download as `sql`, a non-empty string.\", \"INVALID_INPUT\");\n }\n const optional = (key: \"database\" | \"role\"): string | undefined => {\n const value: unknown = key in body ? Reflect.get(body, key) : undefined;\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value !== \"string\") throw ApiError.badRequest(`\\`${key}\\` must be a string.`, \"INVALID_INPUT\");\n return value;\n };\n return { sql: body.sql, database: optional(\"database\"), role: optional(\"role\") };\n}\n\n/**\n * The cursor's rows as CSV, a header record first. Read one batch per pull:\n * the stream asks for the next only when the response has taken this one.\n *\n * A failure after the first byte cannot change the status any more, so the\n * stream is errored instead — the download fails rather than ending early\n * with a file that looks whole.\n */\nfunction csvStream(cursor: SqlCursor, onFailure: (error: unknown) => void): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n let headerSent = false;\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n if (!headerSent) {\n headerSent = true;\n controller.enqueue(encoder.encode(csvRecord(cursor.columns) + CRLF));\n return;\n }\n const rows = await cursor.read();\n if (!rows) {\n await cursor.close();\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(rows.map(row => csvRecord(row) + CRLF).join(\"\")));\n } catch (error: unknown) {\n onFailure(error);\n await cursor.close();\n controller.error(error);\n }\n },\n async cancel() {\n // The reader went away: end the read and give the session back.\n await cursor.close();\n }\n }, { highWaterMark: 1 });\n}\n\nexport function createSqlExportRoutes(options: SqlExportRoutesOptions): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n\n router.post(\"/csv\", async (c) => {\n const request = readExportRequest(await c.req.json());\n const admin = options.getAdmin();\n if (!isSQLAdmin(admin) || typeof admin.openSqlCursor !== \"function\") {\n throw new ApiError(501, \"SQL_EXPORT_UNSUPPORTED\",\n \"This data source cannot stream a query's result. Add a LIMIT and export the rows on screen.\");\n }\n\n const caller = c.get(\"user\");\n const user = typeof caller === \"object\" && caller !== null ? caller : undefined;\n const audit = {\n // Literals masked, as on the socket: a statement's shape is the\n // audit signal, its values are whatever the operator was reading.\n sql: redactSqlLiterals(request.sql).substring(0, 500),\n database: request.database,\n role: request.role,\n uid: user?.uid ?? \"unknown\",\n roles: user?.roles ?? [],\n ...(c.get(\"apiKey\") ? { apiKey: c.get(\"apiKey\")?.id } : {}),\n requestId: c.get(\"requestId\")\n };\n\n // Opened before the response starts: a query the database refuses — a\n // write, a second statement, a syntax error — is a 400 with its\n // reason, not an empty file.\n const cursor = await admin.openSqlCursor(request.sql, { database: request.database, role: request.role });\n logger.info(\"[SQL Audit] SQL console CSV download\", audit);\n\n const body = csvStream(cursor, (error) => logger.warn(\"[SQL export] The download failed part-way and was cut off\", {\n requestId: audit.requestId,\n error: error instanceof Error ? error.message : String(error)\n }));\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/csv; charset=utf-8\",\n \"Content-Disposition\": \"attachment; filename=\\\"query_results.csv\\\"\",\n \"Cache-Control\": \"no-store\"\n }\n });\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AASA,IAAI,mBAAmB;CACtB;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAMA,SAAS,iBAAiB,OAAO;CAChC,MAAM,QAAQ,MAAM,OAAO,CAAC;CAC5B,IAAI,CAAC,iBAAiB,SAAS,KAAK,GAAG,OAAO;CAC9C,KAAK,UAAU,OAAO,UAAU,QAAQ,MAAM,KAAK,MAAM,MAAM,OAAO,SAAS,OAAO,KAAK,CAAC,GAAG,OAAO;CACtG,OAAO,MAAM;AACd;;;;;;;;;;;;;;AAsBA,SAAS,SAAS,OAAO;CACxB,IAAI,UAAU,QAAQ,UAAU,KAAK,GAAG,OAAO;CAC/C,MAAM,OAAO,iBAAiB,OAAO,UAAU,WAAW,KAAK,UAAU,KAAK,IAAI,OAAO,KAAK,CAAC;CAC/F,OAAO,WAAW,KAAK,IAAI,IAAI,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE,KAAK;AACpE;;AAEA,SAAS,UAAU,QAAQ;CAC1B,OAAO,OAAO,IAAI,QAAQ,CAAC,CAAC,KAAK,GAAG;AACrC;;;;;;;;;;;;;;;;;;;;;;;ACrCA,SAAgB,kBAAkB,KAAqB;CACnD,IAAI,MAAM;CACV,IAAI,IAAI;CACR,OAAO,IAAI,IA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;EAChC;EAKA,MAAM,SAAS,MAAM,MAAM,cAAc,QAAQ,KAAK;GAAE,UAAU,QAAQ;GAAU,MAAM,QAAQ;EAAK,CAAC;EACxG,OAAO,KAAK,wCAAwC,KAAK;EAEzD,MAAM,OAAO,UAAU,SAAS,UAAU,OAAO,KAAK,6DAA6D;GAC/G,WAAW,MAAM;GACjB,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAChE,CAAC,CAAC;EACF,OAAO,IAAI,SAAS,MAAM;GACtB,QAAQ;GACR,SAAS;IACL,gBAAgB;IAChB,uBAAuB;IACvB,iBAAiB;GACrB;EACJ,CAAC;CACL,CAAC;CAED,OAAO;AACX"}
|
|
1
|
+
{"version":3,"file":"sql-export-routes-XkcXbxw5.js","names":[],"sources":["../../utils/dist/csv.es.js","../../common/src/util/sql-redaction.ts","../src/api/sql-export-routes.ts"],"sourcesContent":["//#region src/csv.ts\n/**\n* Characters that make a spreadsheet read a cell as a formula rather than text.\n*\n* Quoting is CSV *escaping* and is not enough: Excel, LibreOffice Calc and\n* Sheets strip the CSV quoting at parse time and then evaluate a cell whose\n* first character is one of these — `=HYPERLINK(…)` exfiltrates neighbouring\n* cells on click, `=cmd|'…'!A0` is worse.\n*/\nvar FORMULA_TRIGGERS = [\n\t\"=\",\n\t\"+\",\n\t\"-\",\n\t\"@\",\n\t\"\t\",\n\t\"\\r\"\n];\n/**\n* Neutralise a cell that a spreadsheet would otherwise evaluate, by prefixing a\n* single quote — the standard OWASP mitigation. The apostrophe is consumed by\n* the spreadsheet as \"treat the rest as text\", so the value reads back intact.\n*/\nfunction escapeCsvFormula(value) {\n\tconst first = value.charAt(0);\n\tif (!FORMULA_TRIGGERS.includes(first)) return value;\n\tif ((first === \"-\" || first === \"+\") && value.trim() !== \"\" && Number.isFinite(Number(value))) return value;\n\treturn \"'\" + value;\n}\n/**\n* The inverse of {@link escapeCsvFormula}, for a file read back in: a cell that\n* is an apostrophe followed by a formula trigger loses the apostrophe, as it\n* does when a spreadsheet reads it. Any other apostrophe is text.\n*/\nfunction unescapeCsvFormula(value) {\n\treturn value.charAt(0) === \"'\" && FORMULA_TRIGGERS.includes(value.charAt(1)) ? value.slice(1) : value;\n}\n/**\n* One CSV field (RFC 4180): quoted when it holds a comma, a quote or a line\n* break, with each quote doubled. SQL NULL — `null` or `undefined` — is an\n* empty field, as `COPY … CSV` writes it; an object (a plan, a parsed `jsonb`)\n* is its JSON.\n*\n* Text a spreadsheet would run as a formula (`=…`, `+…`, `-…`, `@…`, a leading\n* tab or carriage return) gets a leading `'` ({@link escapeCsvFormula}), as\n* the CMS export has always done; a signed number is left a number. Every CSV\n* the product writes goes through here, so a file opened in Excel or Sheets\n* never evaluates a cell — at the cost of not being byte-identical to\n* `COPY … CSV` for such cells.\n*/\nfunction csvField(value) {\n\tif (value === null || value === void 0) return \"\";\n\tconst text = escapeCsvFormula(typeof value === \"object\" ? JSON.stringify(value) : String(value));\n\treturn /[\",\\r\\n]/.test(text) ? `\"${text.replace(/\"/g, \"\\\"\\\"\")}\"` : text;\n}\n/** One CSV record: each value through {@link csvField}, separated by commas, with no line break. */\nfunction csvRecord(values) {\n\treturn values.map(csvField).join(\",\");\n}\n//#endregion\nexport { csvField, csvRecord, escapeCsvFormula, unescapeCsvFormula };\n\n//# sourceMappingURL=csv.es.js.map","/**\n * SQL a person ran, as the audit log may keep it: every string literal masked.\n *\n * The SQL console's audit line wrote the statement verbatim, so `ALTER ROLE app\n * PASSWORD 'hunter2'`, `CREATE USER MAPPING … OPTIONS (password 'hunter2')` and\n * `dblink_connect('host=db password=hunter2')` put the password in the\n * production logs, where the logger's redaction — by key name — never looks.\n *\n * A literal is a value the statement carries inline, which is exactly what the\n * line already declines to write when it is bound as a parameter: the\n * statement's shape is the audit signal, the values are whatever the operator\n * was touching. So every literal goes, not only the ones beside a word that\n * looks like `password` — a secret has no reliable neighbour. Identifiers,\n * keywords, numbers and comments stay.\n *\n * Read with Postgres's own lexical rules, not a regular expression over the\n * text: a quote inside a comment, a doubled quote, an `E'…\\'…'` escape or a\n * `$tag$` body must not shift where a literal is thought to end, or the mask\n * covers the statement and leaves the secret.\n */\nexport function redactSqlLiterals(sql: string): string {\n let out = \"\";\n let i = 0;\n while (i < sql.length) {\n const char = sql[i];\n const next = sql[i + 1];\n\n // -- line comment\n if (char === \"-\" && next === \"-\") {\n const end = sql.indexOf(\"\\n\", i);\n const stop = end === -1 ? sql.length : end;\n out += sql.slice(i, stop);\n i = stop;\n continue;\n }\n\n // /* block comment */ — nested, as Postgres reads them\n if (char === \"/\" && next === \"*\") {\n let depth = 1;\n let j = i + 2;\n while (j < sql.length && depth > 0) {\n if (sql[j] === \"/\" && sql[j + 1] === \"*\") { depth++; j += 2; } else if (sql[j] === \"*\" && sql[j + 1] === \"/\") { depth--; j += 2; } else j++;\n }\n out += sql.slice(i, j);\n i = j;\n continue;\n }\n\n // \"quoted identifier\"\n if (char === \"\\\"\") {\n const end = closingQuote(sql, i + 1, \"\\\"\", false);\n out += sql.slice(i, end);\n i = end;\n continue;\n }\n\n // 'string', E'string' with backslash escapes, and the B'', X'', N'',\n // U&'' prefixes — the prefix is kept, the content masked.\n if (char === \"'\") {\n const prefix = /(?:^|[^A-Za-z0-9_$])([EeBbXxNn]|[Uu]&)$/.exec(out)?.[1] ?? \"\";\n out += \"'***'\";\n i = closingQuote(sql, i + 1, \"'\", prefix.toUpperCase() === \"E\");\n continue;\n }\n\n // $tag$ … $tag$ — a dollar-quoted string. A function or DO body is SQL\n // in its own right, and its literals are masked as these are; a\n // password written as `PASSWORD $$hunter2$$` is masked whole.\n if (char === \"$\") {\n const tag = /^\\$([A-Za-z_][A-Za-z0-9_]*)?\\$/.exec(sql.slice(i));\n const precededByIdentifier = /[A-Za-z0-9_]$/.test(out);\n if (tag && !precededByIdentifier) {\n const delimiter = tag[0];\n const bodyStart = i + delimiter.length;\n const bodyEnd = sql.indexOf(delimiter, bodyStart);\n const stop = bodyEnd === -1 ? sql.length : bodyEnd;\n const body = sql.slice(bodyStart, stop);\n const isPassword = /\\bpassword\\s*$/i.test(out);\n out += delimiter + (isPassword ? \"***\" : redactSqlLiterals(body)) + (bodyEnd === -1 ? \"\" : delimiter);\n i = bodyEnd === -1 ? sql.length : bodyEnd + delimiter.length;\n continue;\n }\n }\n\n out += char;\n i++;\n }\n return out;\n}\n\n/**\n * The index just past the quote that closes a literal or identifier opened\n * before `from`. A doubled quote is one quote inside it; with `backslashEscapes`\n * (an `E''` string) so is a backslash-escaped one. Unterminated runs to the end.\n */\nfunction closingQuote(sql: string, from: number, quote: string, backslashEscapes: boolean): number {\n let j = from;\n while (j < sql.length) {\n if (backslashEscapes && sql[j] === \"\\\\\") { j += 2; continue; }\n if (sql[j] === quote) {\n if (sql[j + 1] === quote) { j += 2; continue; }\n return j + 1;\n }\n j++;\n }\n return sql.length;\n}\n","import { Hono } from \"hono\";\nimport { isSQLAdmin, type DatabaseAdmin, type SqlCursor } from \"@rebasepro/types\";\nimport { redactSqlLiterals } from \"@rebasepro/common\";\nimport { csvRecord } from \"@rebasepro/utils\";\nimport { ApiError } from \"./errors\";\nimport type { HonoEnv } from \"./types\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * The SQL console's \"Download full result as CSV\".\n *\n * The console shows at most the first 10,000 rows of a result (see\n * `SQL_CONSOLE_RESULT_LIMITS`), and its own export writes the rows on screen.\n * This route is the way to the rest: it runs ONE query through\n * `SQLAdmin.openSqlCursor` — a server-side cursor in a read-only transaction,\n * as the role the console picked — and streams it as RFC 4180 CSV, one batch\n * at a time. A batch is fetched only when the response has taken the last\n * one, so the server holds one batch however long the result is.\n *\n * Mounted under `/api/admin/sql` behind the admin gate with `database:write` —\n * the scope the socket's `EXECUTE_SQL` asks of the same console, so whoever\n * can run the query can download it and nobody else.\n */\n\n/** RFC 4180's record separator. */\nconst CRLF = \"\\r\\n\";\n\nexport interface SqlExportRoutesOptions {\n /** The default data source's admin capabilities, read per request. */\n getAdmin: () => DatabaseAdmin | undefined;\n}\n\ninterface ExportRequest {\n sql: string;\n database?: string;\n role?: string;\n}\n\nfunction readExportRequest(body: unknown): ExportRequest {\n if (typeof body !== \"object\" || body === null || !(\"sql\" in body) || typeof body.sql !== \"string\" || body.sql.trim() === \"\") {\n throw ApiError.badRequest(\"Send the query to download as `sql`, a non-empty string.\", \"INVALID_INPUT\");\n }\n const optional = (key: \"database\" | \"role\"): string | undefined => {\n const value: unknown = key in body ? Reflect.get(body, key) : undefined;\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value !== \"string\") throw ApiError.badRequest(`\\`${key}\\` must be a string.`, \"INVALID_INPUT\");\n return value;\n };\n return { sql: body.sql, database: optional(\"database\"), role: optional(\"role\") };\n}\n\n/**\n * The cursor's rows as CSV, a header record first. Read one batch per pull:\n * the stream asks for the next only when the response has taken this one.\n *\n * A failure after the first byte cannot change the status any more, so the\n * stream is errored instead — the download fails rather than ending early\n * with a file that looks whole.\n */\nfunction csvStream(cursor: SqlCursor, onFailure: (error: unknown) => void): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n let headerSent = false;\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n if (!headerSent) {\n headerSent = true;\n controller.enqueue(encoder.encode(csvRecord(cursor.columns) + CRLF));\n return;\n }\n const rows = await cursor.read();\n if (!rows) {\n await cursor.close();\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(rows.map(row => csvRecord(row) + CRLF).join(\"\")));\n } catch (error: unknown) {\n onFailure(error);\n await cursor.close();\n controller.error(error);\n }\n },\n async cancel() {\n // The reader went away: end the read and give the session back.\n await cursor.close();\n }\n }, { highWaterMark: 1 });\n}\n\nexport function createSqlExportRoutes(options: SqlExportRoutesOptions): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n\n router.post(\"/csv\", async (c) => {\n const request = readExportRequest(await c.req.json());\n const admin = options.getAdmin();\n if (!isSQLAdmin(admin) || typeof admin.openSqlCursor !== \"function\") {\n throw new ApiError(501, \"SQL_EXPORT_UNSUPPORTED\",\n \"This data source cannot stream a query's result. Add a LIMIT and export the rows on screen.\");\n }\n\n const caller = c.get(\"user\");\n const user = typeof caller === \"object\" && caller !== null ? caller : undefined;\n const audit = {\n // Literals masked, as on the socket: a statement's shape is the\n // audit signal, its values are whatever the operator was reading.\n sql: redactSqlLiterals(request.sql).substring(0, 500),\n database: request.database,\n role: request.role,\n uid: user?.uid ?? \"unknown\",\n roles: user?.roles ?? [],\n ...(c.get(\"apiKey\") ? { apiKey: c.get(\"apiKey\")?.id } : {}),\n requestId: c.get(\"requestId\")\n };\n\n // Opened before the response starts: a query the database refuses — a\n // write, a second statement, a syntax error — is a 400 with its\n // reason, not an empty file.\n const cursor = await admin.openSqlCursor(request.sql, { database: request.database, role: request.role });\n logger.info(\"[SQL Audit] SQL console CSV download\", audit);\n\n const body = csvStream(cursor, (error) => logger.warn(\"[SQL export] The download failed part-way and was cut off\", {\n requestId: audit.requestId,\n error: error instanceof Error ? error.message : String(error)\n }));\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/csv; charset=utf-8\",\n \"Content-Disposition\": \"attachment; filename=\\\"query_results.csv\\\"\",\n \"Cache-Control\": \"no-store\"\n }\n });\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AASA,IAAI,mBAAmB;CACtB;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAMA,SAAS,iBAAiB,OAAO;CAChC,MAAM,QAAQ,MAAM,OAAO,CAAC;CAC5B,IAAI,CAAC,iBAAiB,SAAS,KAAK,GAAG,OAAO;CAC9C,KAAK,UAAU,OAAO,UAAU,QAAQ,MAAM,KAAK,MAAM,MAAM,OAAO,SAAS,OAAO,KAAK,CAAC,GAAG,OAAO;CACtG,OAAO,MAAM;AACd;;;;;;;;;;;;;;AAsBA,SAAS,SAAS,OAAO;CACxB,IAAI,UAAU,QAAQ,UAAU,KAAK,GAAG,OAAO;CAC/C,MAAM,OAAO,iBAAiB,OAAO,UAAU,WAAW,KAAK,U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OAAO,SAAS,KAAA;EACtE,MAAM,QAAQ;GAGV,KAAK,kBAAkB,QAAQ,GAAG,CAAC,CAAC,UAAU,GAAG,GAAG;GACpD,UAAU,QAAQ;GAClB,MAAM,QAAQ;GACd,KAAK,MAAM,OAAO;GAClB,OAAO,MAAM,SAAS,CAAC;GACvB,GAAI,EAAE,IAAI,QAAQ,IAAI,EAAE,QAAQ,EAAE,IAAI,QAAQ,CAAC,EAAE,GAAG,IAAI,CAAC;GACzD,WAAW,EAAE,IAAI,WAAW;EAChC;EAKA,MAAM,SAAS,MAAM,MAAM,cAAc,QAAQ,KAAK;GAAE,UAAU,QAAQ;GAAU,MAAM,QAAQ;EAAK,CAAC;EACxG,OAAO,KAAK,wCAAwC,KAAK;EAEzD,MAAM,OAAO,UAAU,SAAS,UAAU,OAAO,KAAK,6DAA6D;GAC/G,WAAW,MAAM;GACjB,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAChE,CAAC,CAAC;EACF,OAAO,IAAI,SAAS,MAAM;GACtB,QAAQ;GACR,SAAS;IACL,gBAAgB;IAChB,uBAAuB;IACvB,iBAAiB;GACrB;EACJ,CAAC;CACL,CAAC;CAED,OAAO;AACX"}
|
|
@@ -65,6 +65,8 @@ var CANONICAL_TO_REST = {
|
|
|
65
65
|
"not-in": "nin",
|
|
66
66
|
"array-contains": "cs",
|
|
67
67
|
"array-contains-any": "csa",
|
|
68
|
+
"array-contains-all": "csall",
|
|
69
|
+
"array-contained-by": "cd",
|
|
68
70
|
"like": "like",
|
|
69
71
|
"ilike": "ilike",
|
|
70
72
|
"not-like": "nlike",
|
|
@@ -84,6 +86,8 @@ var REST_TO_CANONICAL = {
|
|
|
84
86
|
"nin": "not-in",
|
|
85
87
|
"cs": "array-contains",
|
|
86
88
|
"csa": "array-contains-any",
|
|
89
|
+
"csall": "array-contains-all",
|
|
90
|
+
"cd": "array-contained-by",
|
|
87
91
|
"like": "like",
|
|
88
92
|
"ilike": "ilike",
|
|
89
93
|
"nlike": "not-like",
|
|
@@ -109,7 +113,9 @@ var NULL_OPS = /* @__PURE__ */ new Set(["is-null", "is-not-null"]);
|
|
|
109
113
|
var LIST_OPS = /* @__PURE__ */ new Set([
|
|
110
114
|
"in",
|
|
111
115
|
"not-in",
|
|
112
|
-
"array-contains-any"
|
|
116
|
+
"array-contains-any",
|
|
117
|
+
"array-contains-all",
|
|
118
|
+
"array-contained-by"
|
|
113
119
|
]);
|
|
114
120
|
/**
|
|
115
121
|
* Every canonical operator, in a stable order. Useful for engine capability
|
|
@@ -128,6 +134,8 @@ var ALL_WHERE_FILTER_OPS = [
|
|
|
128
134
|
"not-in",
|
|
129
135
|
"array-contains",
|
|
130
136
|
"array-contains-any",
|
|
137
|
+
"array-contains-all",
|
|
138
|
+
"array-contained-by",
|
|
131
139
|
"like",
|
|
132
140
|
"ilike",
|
|
133
141
|
"not-like",
|
|
@@ -218,7 +226,7 @@ var FIREBASE_CAPABILITIES = {
|
|
|
218
226
|
supportsColumnTypes: false,
|
|
219
227
|
supportsRealtime: true,
|
|
220
228
|
supportsVectors: false,
|
|
221
|
-
filterOperators: ALL_WHERE_FILTER_OPS.filter((op) => op !== "like" && op !== "ilike" && op !== "not-like" && op !== "not-ilike"),
|
|
229
|
+
filterOperators: ALL_WHERE_FILTER_OPS.filter((op) => op !== "like" && op !== "ilike" && op !== "not-like" && op !== "not-ilike" && op !== "array-contains-all" && op !== "array-contained-by"),
|
|
222
230
|
filterableRelationKinds: [],
|
|
223
231
|
supportsRelationFieldFilters: false,
|
|
224
232
|
relationAggregateSorts: false,
|
|
@@ -435,6 +443,7 @@ var REBASE_SCHEMA = "rebase";
|
|
|
435
443
|
* the trusted server plane and `IS NOT NULL` a tautology.
|
|
436
444
|
*/
|
|
437
445
|
var RLS_UID_SQL = `${REBASE_SCHEMA}.uid()`;
|
|
446
|
+
`${REBASE_SCHEMA}`;
|
|
438
447
|
/** The request's roles as a comma-separated string, for `string_to_array`. */
|
|
439
448
|
var RLS_ROLES_SQL = `${REBASE_SCHEMA}.roles()`;
|
|
440
449
|
`${REBASE_SCHEMA}`;
|
|
@@ -815,17 +824,49 @@ registerResourceKind({
|
|
|
815
824
|
],
|
|
816
825
|
implicitDefault: true
|
|
817
826
|
});
|
|
818
|
-
amendResourceKind("database", {
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
827
|
+
amendResourceKind("database", {
|
|
828
|
+
optionKeys: [
|
|
829
|
+
"databaseId",
|
|
830
|
+
"migrations",
|
|
831
|
+
"extensions",
|
|
832
|
+
"rls"
|
|
833
|
+
],
|
|
834
|
+
envBases: [
|
|
835
|
+
"DATABASE_URL",
|
|
836
|
+
"DATABASE_READ_URL",
|
|
837
|
+
"DATABASE_DIRECT_URL",
|
|
838
|
+
"DATABASE_POOLED",
|
|
839
|
+
"ADMIN_CONNECTION_STRING",
|
|
840
|
+
"REBASE_DRIVER",
|
|
841
|
+
"DB_POOL_MAX",
|
|
842
|
+
"DB_POOL_IDLE_TIMEOUT",
|
|
843
|
+
"DB_POOL_CONNECT_TIMEOUT"
|
|
844
|
+
]
|
|
845
|
+
});
|
|
846
|
+
/** The `rls` options a database declaration gave, `{}` when it gave none or was never declared. */
|
|
847
|
+
function declaredDatabaseRls(key = DEFAULT_DATA_SOURCE_KEY) {
|
|
848
|
+
const rls = declaredResources("database").find((d) => d.key === key)?.options.rls;
|
|
849
|
+
return rls && typeof rls === "object" ? rls : {};
|
|
850
|
+
}
|
|
851
|
+
/**
|
|
852
|
+
* The policy settings every compile path must agree on — the boot's policy
|
|
853
|
+
* ensure, `rebase db generate`, the drift check — read from the one place all
|
|
854
|
+
* of them can see: the database declaration, with `REBASE_RLS_POLICY_TARGET` /
|
|
855
|
+
* `REBASE_RLS_DEFAULT_POLICIES` over it. Defaults are what Rebase compiled
|
|
856
|
+
* before these existed.
|
|
857
|
+
*
|
|
858
|
+
* Browser-safe: where there is no `process`, only the declaration counts.
|
|
859
|
+
*/
|
|
860
|
+
function declaredRlsPolicyShape(dataSource = DEFAULT_DATA_SOURCE_KEY) {
|
|
861
|
+
const declared = declaredDatabaseRls(dataSource);
|
|
862
|
+
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
863
|
+
const envTarget = env?.REBASE_RLS_POLICY_TARGET?.trim();
|
|
864
|
+
const envDefaults = env?.REBASE_RLS_DEFAULT_POLICIES?.trim().toLowerCase();
|
|
865
|
+
return {
|
|
866
|
+
policyTarget: envTarget === "requestRole" || envTarget === "public" ? envTarget : declared.policyTarget === "requestRole" ? "requestRole" : "public",
|
|
867
|
+
defaultPolicies: envDefaults === "false" ? false : envDefaults === "true" ? true : declared.defaultPolicies !== false
|
|
868
|
+
};
|
|
869
|
+
}
|
|
829
870
|
registerResourceKind({
|
|
830
871
|
kind: "bucket",
|
|
831
872
|
engines: [
|
|
@@ -1453,6 +1494,6 @@ function summarizeScopes(model = EMPTY_ACCESS_MODEL) {
|
|
|
1453
1494
|
return [...builtIn, ...app];
|
|
1454
1495
|
}
|
|
1455
1496
|
//#endregion
|
|
1456
|
-
export {
|
|
1497
|
+
export { REST_TO_CANONICAL as $, DEFAULT_STORAGE_SOURCE_KEY as A, RLS_ROLES_SQL as B, declaredQueueConsumers as C, resourceToStorageSource as D, resourceToDataSource as E, resourceEnvSuffix as F, isPostgresCollectionConfig as G, rewriteLegacyRlsFunctions as H, resourceKeyOf as I, getDataSourceCapabilities as J, isRelationalCollectionConfig as K, resourceKind as L, DEFAULT_RESOURCE_KEY as M, buildResourceGraph as N, setQueueRuntime as O, resolveResourceRefs as P, NULL_OPS as Q, resourceKinds as R, declareCron as S, declaredSubscriptions as T, getCollectionDataPath as U, RLS_UID_SQL as V, getDeclaredSubcollections as W, CANONICAL_TO_REST as X, ALL_WHERE_FILTER_OPS as Y, LIST_OPS as Z, scopesBeyond as _, KEY_MANAGEMENT_SCOPES as a, summarizeScopes as b, intersectScopes as c, isDataPlaneScope as d, isRelationAggregateSort as et, knownScopes as f, scopeGrantsAny as g, scopeGrants as h, EMPTY_ACCESS_MODEL as i, storageEnvSuffix as j, setTopicRuntime as k, isAdminScope as l, roleNameProblem as m, ADMIN_SCOPES as n, sortKeyToString as nt, SCOPE_TARGETS as o, parseScope as p, DEFAULT_DATA_SOURCE_KEY as q, BUILT_IN_SCOPES as r, toCanonicalOp as rt, hasAdminRole as s, ADMIN_ROLE as t, parseRelationAggregateSort as tt, isBuiltInScope as u, scopesForRoles as v, declaredRlsPolicyShape as w, validateScopes as x, summarizeRoles as y, RLS_JWT_SQL as z };
|
|
1457
1498
|
|
|
1458
|
-
//# sourceMappingURL=src-
|
|
1499
|
+
//# sourceMappingURL=src-0nCWajy7.js.map
|