@rebasepro/server 0.16.1-canary.ge71347e → 0.17.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.
Files changed (50) hide show
  1. package/dist/{admin_block-BeypnEfb.js → admin_block-BX6YULvJ.js} +8 -8
  2. package/dist/admin_block-BX6YULvJ.js.map +1 -0
  3. package/dist/api/ast-schema-editor.d.ts +1 -1
  4. package/dist/api/rest/idempotency.d.ts +1 -1
  5. package/dist/{ast-schema-editor-BrarYZCq.js → ast-schema-editor-BLADP9O2.js} +3 -3
  6. package/dist/ast-schema-editor-BLADP9O2.js.map +1 -0
  7. package/dist/auth/crypto-utils.d.ts +4 -0
  8. package/dist/auth/jwt-crypto.d.ts +91 -0
  9. package/dist/auth/jwt.d.ts +10 -9
  10. package/dist/auth/middleware.d.ts +1 -1
  11. package/dist/auth/rate-limiter.d.ts +10 -3
  12. package/dist/{auth-Cd6qQw_0.js → auth-BVPx33qB.js} +51 -77
  13. package/dist/auth-BVPx33qB.js.map +1 -0
  14. package/dist/boot/fetch-bundle.d.ts +18 -1
  15. package/dist/collections/validate-config.d.ts +14 -1
  16. package/dist/{cron-store-BFmnkJ2s.js → cron-store-CbFfQhbg.js} +3 -2
  17. package/dist/{cron-store-BFmnkJ2s.js.map → cron-store-CbFfQhbg.js.map} +1 -1
  18. package/dist/{ddl-bootstrap-euwN8FOy.js → ddl-bootstrap-5YZCZ8qk.js} +2 -92
  19. package/dist/ddl-bootstrap-5YZCZ8qk.js.map +1 -0
  20. package/dist/history-recorder-B67maiTi.js +76 -0
  21. package/dist/history-recorder-B67maiTi.js.map +1 -0
  22. package/dist/history-store-oiqhb3HU.js +210 -0
  23. package/dist/history-store-oiqhb3HU.js.map +1 -0
  24. package/dist/index.d.ts +1 -1
  25. package/dist/index.es.js +302 -77
  26. package/dist/index.es.js.map +1 -1
  27. package/dist/init.d.ts +8 -0
  28. package/dist/internal-tables-DpxfPaEB.js +97 -0
  29. package/dist/internal-tables-DpxfPaEB.js.map +1 -0
  30. package/dist/{jobs-DE0KUNT0.js → jobs-B2ELModo.js} +3 -2
  31. package/dist/{jobs-DE0KUNT0.js.map → jobs-B2ELModo.js.map} +1 -1
  32. package/dist/{jwt-DoHkMMWF.js → jwt-5VN4C6ln.js} +230 -38
  33. package/dist/jwt-5VN4C6ln.js.map +1 -0
  34. package/dist/metrics/history-recorder.d.ts +18 -0
  35. package/dist/metrics/history-store.d.ts +123 -0
  36. package/dist/metrics/index.d.ts +9 -1
  37. package/dist/{schema-editor-routes-Bf5h5Emf.js → schema-editor-routes-BWCIqZoT.js} +2 -2
  38. package/dist/{schema-editor-routes-Bf5h5Emf.js.map → schema-editor-routes-BWCIqZoT.js.map} +1 -1
  39. package/dist/src-B-CmIFMr.js.map +1 -1
  40. package/dist/src-Cdsw7DqV.js.map +1 -1
  41. package/dist/storage/keys.d.ts +21 -0
  42. package/dist/utils/ip-address.d.ts +30 -0
  43. package/dist/utils/portable-crypto.d.ts +71 -0
  44. package/dist/utils/request-id.d.ts +20 -0
  45. package/package.json +5 -5
  46. package/dist/admin_block-BeypnEfb.js.map +0 -1
  47. package/dist/ast-schema-editor-BrarYZCq.js.map +0 -1
  48. package/dist/auth-Cd6qQw_0.js.map +0 -1
  49. package/dist/ddl-bootstrap-euwN8FOy.js.map +0 -1
  50. package/dist/jwt-DoHkMMWF.js.map +0 -1
@@ -8,7 +8,7 @@ __rebaseCreateRequire(import.meta.url);
8
8
  *
9
9
  * There is no *type* for the block in this package any more, and that is the point:
10
10
  * `admin` is not declared on `BaseCollectionConfig` or on any property here, so a
11
- * BaaS install cannot even write one. `@rebasepro/admin-types` adds the field back by
11
+ * BaaS install cannot even write one. `@rebasepro/cms-types` adds the field back by
12
12
  * declaration merging, which is why installing it is what makes the admin surface
13
13
  * appear.
14
14
  *
@@ -19,7 +19,7 @@ __rebaseCreateRequire(import.meta.url);
19
19
  * Every key that belongs inside a collection's `admin` block, as data.
20
20
  *
21
21
  * The type that describes these fields is `AdminCollectionOptions` in
22
- * `@rebasepro/admin-types`, and it is erased at build time — but three runtime
22
+ * `@rebasepro/cms-types`, and it is erased at build time — but three runtime
23
23
  * consumers need the list, and two of them are core:
24
24
  *
25
25
  * - `serializeCollections`, to drop the block from the contract
@@ -29,7 +29,7 @@ __rebaseCreateRequire(import.meta.url);
29
29
  * backend ignores it and the panel never finds it again.
30
30
  * - the `collections-admin-block` codemod
31
31
  *
32
- * `@rebasepro/admin-types` re-exports this and asserts it names only real option
32
+ * `@rebasepro/cms-types` re-exports this and asserts it names only real option
33
33
  * keys; the count is pinned by a test there.
34
34
  *
35
35
  * @group Models
@@ -81,15 +81,15 @@ var ADMIN_COLLECTION_KEYS = [
81
81
  * Every key that belongs inside a *property's* `admin` block, as data.
82
82
  *
83
83
  * The union of `AdminPropertyOptions` and its per-type extensions
84
- * (`AdminStringOptions`, `AdminArrayOptions`, …) in `@rebasepro/admin-types`.
84
+ * (`AdminStringOptions`, `AdminArrayOptions`, …) in `@rebasepro/cms-types`.
85
85
  * It lives here for the same reason {@link ADMIN_COLLECTION_KEYS} does: the
86
86
  * runtime consumers are core packages that the BaaS guard forbids from
87
- * importing `@rebasepro/admin-types`. Here it is the boot-time collection
87
+ * importing `@rebasepro/cms-types`. Here it is the boot-time collection
88
88
  * validator in `@rebasepro/server`, which has to tell "you left `readOnly` at
89
89
  * the top of the property, where nothing reads it" apart from "you invented a
90
90
  * key we have never heard of".
91
91
  *
92
- * `@rebasepro/admin-types` re-exports this and asserts it names only real
92
+ * `@rebasepro/cms-types` re-exports this and asserts it names only real
93
93
  * option keys.
94
94
  *
95
95
  * @group Models
@@ -134,7 +134,7 @@ var ADMIN_PROPERTY_KEYS = [
134
134
  * in favour of the value the user changed away from.
135
135
  *
136
136
  * This lives here, next to the key lists, because it had two implementations —
137
- * `toAdminCollectionConfig` in `@rebasepro/admin-types` and `nestAdminKeys` in
137
+ * `toAdminCollectionConfig` in `@rebasepro/cms-types` and `nestAdminKeys` in
138
138
  * `@rebasepro/server`'s schema editor — that agreed on everything except that
139
139
  * precedence, which is the only part that decides whether a save is visible.
140
140
  *
@@ -182,4 +182,4 @@ function nestAdminPropertyKeys(property) {
182
182
  //#endregion
183
183
  export { nestAdminPropertyKeys as i, ADMIN_PROPERTY_KEYS as n, nestAdminCollectionKeys as r, ADMIN_COLLECTION_KEYS as t };
184
184
 
185
- //# sourceMappingURL=admin_block-BeypnEfb.js.map
185
+ //# sourceMappingURL=admin_block-BX6YULvJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"admin_block-BX6YULvJ.js","names":[],"sources":["../../types/src/types/admin_block.ts"],"sourcesContent":["/**\n * The keys of a collection's admin block, as data.\n *\n * There is no *type* for the block in this package any more, and that is the point:\n * `admin` is not declared on `BaseCollectionConfig` or on any property here, so a\n * BaaS install cannot even write one. `@rebasepro/cms-types` adds the field back by\n * declaration merging, which is why installing it is what makes the admin surface\n * appear.\n *\n * The *list* still has to live here, because three runtime consumers need it and two\n * of them are core — see below.\n */\n\n/**\n * Every key that belongs inside a collection's `admin` block, as data.\n *\n * The type that describes these fields is `AdminCollectionOptions` in\n * `@rebasepro/cms-types`, and it is erased at build time — but three runtime\n * consumers need the list, and two of them are core:\n *\n * - `serializeCollections`, to drop the block from the contract\n * - the ts-morph schema editor in `@rebasepro/server`, which rewrites collection\n * files on disk from the admin panel and has to know where each key goes. A key\n * missing from this list gets written to the *top level* of the file, where the\n * backend ignores it and the panel never finds it again.\n * - the `collections-admin-block` codemod\n *\n * `@rebasepro/cms-types` re-exports this and asserts it names only real option\n * keys; the count is pinned by a test there.\n *\n * @group Models\n */\nexport const ADMIN_COLLECTION_KEYS = [\n \"Actions\",\n \"additionalFields\",\n \"alwaysApplyDefaultValues\",\n \"components\",\n \"customViews\",\n \"defaultEntityAction\",\n \"defaultFilter\",\n \"defaultSelectedView\",\n \"defaultSize\",\n \"defaultViewMode\",\n \"disableDefaultActions\",\n \"display\",\n \"enabledViews\",\n \"entityActions\",\n \"entityViews\",\n \"exportable\",\n \"filterPresets\",\n \"fixedFilter\",\n \"form\",\n \"formAutoSave\",\n \"formView\",\n \"group\",\n \"hideFromEntityViews\",\n \"hideFromNavigation\",\n \"hideIdFromCollection\",\n \"hideIdFromForm\",\n \"icon\",\n \"includeJsonView\",\n \"inlineEditing\",\n \"kanban\",\n \"listProperties\",\n \"localChangesBackup\",\n \"openEntityMode\",\n \"orderProperty\",\n \"pagination\",\n \"previewProperties\",\n \"propertiesOrder\",\n \"selectionController\",\n \"selectionEnabled\",\n \"sideDialogWidth\",\n \"sort\"\n] as const;\n\n/** A key of a collection's `admin` block. @group Models */\nexport type AdminCollectionKey = typeof ADMIN_COLLECTION_KEYS[number];\n\n/**\n * Every key that belongs inside a *property's* `admin` block, as data.\n *\n * The union of `AdminPropertyOptions` and its per-type extensions\n * (`AdminStringOptions`, `AdminArrayOptions`, …) in `@rebasepro/cms-types`.\n * It lives here for the same reason {@link ADMIN_COLLECTION_KEYS} does: the\n * runtime consumers are core packages that the BaaS guard forbids from\n * importing `@rebasepro/cms-types`. Here it is the boot-time collection\n * validator in `@rebasepro/server`, which has to tell \"you left `readOnly` at\n * the top of the property, where nothing reads it\" apart from \"you invented a\n * key we have never heard of\".\n *\n * `@rebasepro/cms-types` re-exports this and asserts it names only real\n * option keys.\n *\n * @group Models\n */\nexport const ADMIN_PROPERTY_KEYS = [\n \"canAddElements\",\n \"clearable\",\n \"columnWidth\",\n \"customProps\",\n \"disabled\",\n \"expanded\",\n \"Field\",\n \"Filter\",\n \"filterOperators\",\n \"fixedFilter\",\n \"hideFromCollection\",\n \"includeEntityLink\",\n \"includeId\",\n \"markdown\",\n \"minimalistView\",\n \"multiline\",\n \"Preview\",\n \"previewAsTag\",\n \"previewProperties\",\n \"readOnly\",\n \"sortable\",\n \"span\",\n \"spreadChildren\",\n \"urlPreview\",\n \"widget\",\n] as const;\n\n/** A key of a property's `admin` block. @group Models */\nexport type AdminPropertyKey = typeof ADMIN_PROPERTY_KEYS[number];\n\n/**\n * Move flattened admin keys back down into the `admin` block.\n *\n * The admin panel works with a *flat* view model — the block merged onto the\n * collection — so what comes back from a form has `icon` and `defaultViewMode`\n * at the top level while `admin` still holds whatever the file was loaded with.\n * This is the way back.\n *\n * **The top-level value wins.** It is the one the form just wrote; the block is\n * the copy the collection was loaded with, and preferring it resolves every edit\n * in favour of the value the user changed away from.\n *\n * This lives here, next to the key lists, because it had two implementations —\n * `toAdminCollectionConfig` in `@rebasepro/cms-types` and `nestAdminKeys` in\n * `@rebasepro/server`'s schema editor — that agreed on everything except that\n * precedence, which is the only part that decides whether a save is visible.\n *\n * @group Models\n */\nexport function nestAdminKeysOf(\n source: Record<string, unknown>,\n adminKeys: readonly string[]\n): Record<string, unknown> {\n const keys = new Set<string>(adminKeys);\n const top: Record<string, unknown> = {};\n const block: Record<string, unknown> = { ...((source.admin as Record<string, unknown> | undefined) ?? {}) };\n\n for (const [key, value] of Object.entries(source)) {\n if (key === \"admin\") continue;\n if (keys.has(key)) block[key] = value;\n else top[key] = value;\n }\n\n if (Object.keys(block).length > 0) top.admin = block;\n return top;\n}\n\n/**\n * {@link nestAdminKeysOf} for a collection.\n *\n * @group Models\n */\nexport function nestAdminCollectionKeys(collection: Record<string, unknown>): Record<string, unknown> {\n return nestAdminKeysOf(collection, ADMIN_COLLECTION_KEYS);\n}\n\n/**\n * {@link nestAdminKeysOf} for a property, applied to its children too.\n *\n * A map property carries `properties`, an array property carries `of`, and both\n * hold properties with `admin` blocks of their own. A flat `readOnly` left on a\n * child is as dead — and as fatal at the next boot — as one left on the parent,\n * so the walk goes all the way down.\n *\n * @group Models\n */\nexport function nestAdminPropertyKeys(property: Record<string, unknown>): Record<string, unknown> {\n const nested = nestAdminKeysOf(property, ADMIN_PROPERTY_KEYS);\n\n const children = nested.properties;\n if (children && typeof children === \"object\" && !Array.isArray(children)) {\n nested.properties = Object.fromEntries(\n Object.entries(children as Record<string, unknown>).map(([key, child]) => [\n key,\n child && typeof child === \"object\" && !Array.isArray(child)\n ? nestAdminPropertyKeys(child as Record<string, unknown>)\n : child\n ])\n );\n }\n\n const of = nested.of;\n if (Array.isArray(of)) {\n nested.of = of.map(entry => entry && typeof entry === \"object\" && !Array.isArray(entry)\n ? nestAdminPropertyKeys(entry as Record<string, unknown>)\n : entry);\n } else if (of && typeof of === \"object\") {\n nested.of = nestAdminPropertyKeys(of as Record<string, unknown>);\n }\n\n return nested;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAa,wBAAwB;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;;;;;;;;;;;;;;;;;AAsBA,IAAa,sBAAsB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,gBACZ,QACA,WACuB;CACvB,MAAM,OAAO,IAAI,IAAY,SAAS;CACtC,MAAM,MAA+B,CAAC;CACtC,MAAM,QAAiC,EAAE,GAAK,OAAO,SAAiD,CAAC,EAAG;CAE1G,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG;EAC/C,IAAI,QAAQ,SAAS;EACrB,IAAI,KAAK,IAAI,GAAG,GAAG,MAAM,OAAO;OAC3B,IAAI,OAAO;CACpB;CAEA,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,GAAG,IAAI,QAAQ;CAC/C,OAAO;AACX;;;;;;AAOA,SAAgB,wBAAwB,YAA8D;CAClG,OAAO,gBAAgB,YAAY,qBAAqB;AAC5D;;;;;;;;;;;AAYA,SAAgB,sBAAsB,UAA4D;CAC9F,MAAM,SAAS,gBAAgB,UAAU,mBAAmB;CAE5D,MAAM,WAAW,OAAO;CACxB,IAAI,YAAY,OAAO,aAAa,YAAY,CAAC,MAAM,QAAQ,QAAQ,GACnE,OAAO,aAAa,OAAO,YACvB,OAAO,QAAQ,QAAmC,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CACtE,KACA,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IACpD,sBAAsB,KAAgC,IACtD,KACV,CAAC,CACL;CAGJ,MAAM,KAAK,OAAO;CAClB,IAAI,MAAM,QAAQ,EAAE,GAChB,OAAO,KAAK,GAAG,KAAI,UAAS,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAChF,sBAAsB,KAAgC,IACtD,KAAK;MACR,IAAI,MAAM,OAAO,OAAO,UAC3B,OAAO,KAAK,sBAAsB,EAA6B;CAGnE,OAAO;AACX"}
@@ -2,7 +2,7 @@
2
2
  * Move presentation keys into the `admin` block.
3
3
  *
4
4
  * The rule itself lives in `@rebasepro/types`, next to `ADMIN_COLLECTION_KEYS`,
5
- * because `@rebasepro/admin-types` has to apply the identical one on the panel's
5
+ * because `@rebasepro/cms-types` has to apply the identical one on the panel's
6
6
  * side and this package cannot import that one. Two copies used to exist and
7
7
  * they disagreed about precedence, which decided whether a presentation edit was
8
8
  * saved or silently reverted to the value the user had just changed away from.
@@ -11,7 +11,7 @@ import { DataDriver } from "@rebasepro/types";
11
11
  * difference between "here is your earlier answer" and silently discarding a
12
12
  * correction.
13
13
  */
14
- export declare function requestFingerprint(method: string, path: string, body: unknown): string;
14
+ export declare function requestFingerprint(method: string, path: string, body: unknown): Promise<string>;
15
15
  /**
16
16
  * What a caller may do with a key.
17
17
  *
@@ -3,7 +3,7 @@ import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
5
  import "./src-Cdsw7DqV.js";
6
- import { i as nestAdminPropertyKeys, r as nestAdminCollectionKeys } from "./admin_block-BeypnEfb.js";
6
+ import { i as nestAdminPropertyKeys, r as nestAdminCollectionKeys } from "./admin_block-BX6YULvJ.js";
7
7
  import * as fs$1 from "fs";
8
8
  import * as path$1 from "path";
9
9
  import { IndentationText, Node, Project, SyntaxKind } from "ts-morph";
@@ -36,7 +36,7 @@ var RawExpression = class {
36
36
  * Move presentation keys into the `admin` block.
37
37
  *
38
38
  * The rule itself lives in `@rebasepro/types`, next to `ADMIN_COLLECTION_KEYS`,
39
- * because `@rebasepro/admin-types` has to apply the identical one on the panel's
39
+ * because `@rebasepro/cms-types` has to apply the identical one on the panel's
40
40
  * side and this package cannot import that one. Two copies used to exist and
41
41
  * they disagreed about precedence, which decided whether a presentation edit was
42
42
  * saved or silently reverted to the value the user had just changed away from.
@@ -426,4 +426,4 @@ var AstSchemaEditor = class AstSchemaEditor {
426
426
  //#endregion
427
427
  export { AstSchemaEditor };
428
428
 
429
- //# sourceMappingURL=ast-schema-editor-BrarYZCq.js.map
429
+ //# sourceMappingURL=ast-schema-editor-BLADP9O2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ast-schema-editor-BLADP9O2.js","names":[],"sources":["../src/api/ast-schema-editor.ts"],"sourcesContent":["import { Project, SyntaxKind, Node, ObjectLiteralExpression, ObjectLiteralElementLike, PropertyAssignment, SourceFile, IndentationText } from \"ts-morph\";\nimport { nestAdminCollectionKeys, nestAdminPropertyKeys } from \"@rebasepro/types\";\nimport * as path from \"path\";\nimport * as fs from \"fs\";\n\n/**\n * The helpers a collection file may be wrapped in.\n *\n * `rebase init` scaffolds every collection as\n * `const postsCollection = defineCollection({ … })` — a call expression, not the\n * bare object literal `rebase introspect` emits. An editor that only understood\n * the bare form found nothing to patch in any stock project, and then rewrote the\n * file from the panel's JSON: no wrapper, no imports, no relation thunks.\n */\nconst COLLECTION_FACTORIES = new Set([\"defineCollection\"]);\n\n/**\n * A value that must be emitted as source code rather than as JSON.\n *\n * Everything reaching the writer has been through `JSON.stringify` on the wire,\n * so a function-valued key arrives either missing or as a string. A relation's\n * `target` is a thunk in the file and a slug in the payload; this is how the\n * thunk gets written back.\n */\nclass RawExpression {\n constructor(public readonly text: string) {\n }\n}\n\n/**\n * Move presentation keys into the `admin` block.\n *\n * The rule itself lives in `@rebasepro/types`, next to `ADMIN_COLLECTION_KEYS`,\n * because `@rebasepro/cms-types` has to apply the identical one on the panel's\n * side and this package cannot import that one. Two copies used to exist and\n * they disagreed about precedence, which decided whether a presentation edit was\n * saved or silently reverted to the value the user had just changed away from.\n */\nexport function nestAdminKeys(collectionData: Record<string, unknown>): Record<string, unknown> {\n return nestAdminCollectionKeys(collectionData);\n}\n\nexport class AstSchemaEditor {\n private project: Project;\n private collectionsDir: string;\n\n constructor(collectionsDir: string) {\n this.project = new Project({\n manipulationSettings: {\n indentationText: IndentationText.FourSpaces\n }\n });\n if (fs.existsSync(collectionsDir)) {\n this.project.addSourceFilesAtPaths(`${collectionsDir}/**/*.ts`);\n }\n this.collectionsDir = path.resolve(collectionsDir);\n }\n\n /**\n * Sanitize collectionId to prevent path traversal attacks.\n * Only allows alphanumeric characters, underscores, and hyphens.\n */\n /**\n * The variable name the generated file binds the collection to.\n *\n * `sanitizeCollectionId` guards the FILENAME, and permits hyphens and a\n * leading digit — both legal in a filename and neither legal in a\n * JavaScript identifier. So a collection created from the admin panel as\n * `my-notes` (the documented slug shape) or `2024 Archive` (auto-slugged to\n * `2024_archive`) wrote:\n *\n * const my-notesCollection: CollectionConfig = … \"',' expected\"\n * const 2024_archiveCollection: CollectionConfig = … \"Numeric separators\n * are not allowed here\"\n *\n * The panel reported success, and the next boot failed for EVERY collection\n * in the directory — the loader imports all of them — while the editor could\n * no longer parse the file it had just written, so it could not fix itself.\n *\n * Separators camel-case rather than vanish, so `my-notes` and `my_notes`\n * stay distinct; a leading digit is prefixed rather than stripped, so\n * `2024_archive` stays distinct from `archive`. Byte-identical for every\n * slug that already produced a valid identifier.\n */\n private static collectionVarName(safeId: string): string {\n const camel = safeId.replace(/[-_]+([a-zA-Z0-9])/g, (_, char: string) => char.toUpperCase());\n const identifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(camel) ? camel : `c${camel.replace(/^[0-9]/, (d) => d)}`;\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(identifier) ? identifier : `c${identifier.replace(/[^A-Za-z0-9_$]/g, \"\")}`;\n }\n\n private sanitizeCollectionId(collectionId: string): string {\n const sanitized = collectionId.replace(/[^a-zA-Z0-9_-]/g, \"\");\n if (!sanitized || sanitized !== collectionId) {\n throw new Error(`Invalid collection ID: \"${collectionId}\". Only alphanumeric characters, underscores, and hyphens are allowed.`);\n }\n return sanitized;\n }\n\n /**\n * Resolve a file path and ensure it falls within the collectionsDir.\n */\n private safePath(filename: string): string {\n const resolved = path.resolve(this.collectionsDir, filename);\n if (!resolved.startsWith(this.collectionsDir + path.sep) && resolved !== this.collectionsDir) {\n throw new Error(\"Path traversal detected: resolved path is outside the collections directory.\");\n }\n return resolved;\n }\n\n private getCollectionFile(collectionId: string) {\n const safeId = this.sanitizeCollectionId(collectionId);\n const filePath = this.safePath(`${safeId}.ts`);\n let file = this.project.getSourceFile(filePath);\n if (!file && fs.existsSync(filePath)) {\n this.project.addSourceFilesAtPaths(`${this.collectionsDir}/**/*.ts`);\n file = this.project.getSourceFile(filePath);\n }\n return file;\n }\n\n /**\n * Find the object literal a collection is declared with, through whatever\n * wraps it.\n *\n * `defineCollection({ … })` is the shape `rebase init` writes and the one the\n * docs recommend; `satisfies` / `as` / parentheses are the other ways an\n * author can dress the same literal. Returning `null` for any of them meant\n * the three callers below each failed differently, and the worst of them\n * overwrote the file.\n */\n private unwrapCollectionObject(node: Node | undefined): ObjectLiteralExpression | null {\n if (!node) return null;\n if (Node.isObjectLiteralExpression(node)) return node;\n if (Node.isParenthesizedExpression(node) ||\n Node.isAsExpression(node) ||\n Node.isSatisfiesExpression(node) ||\n Node.isTypeAssertion(node) ||\n Node.isNonNullExpression(node)) {\n return this.unwrapCollectionObject(node.getExpression());\n }\n if (Node.isCallExpression(node)) {\n // `defineCollection`, `admin.defineCollection`, `defineCollection<Post>`\n const callee = node.getExpression().getText().split(\".\").pop();\n if (callee && COLLECTION_FACTORIES.has(callee)) {\n return this.unwrapCollectionObject(node.getArguments()[0]);\n }\n }\n return null;\n }\n\n private getCollectionObject(collectionId: string): ObjectLiteralExpression | null {\n const file = this.getCollectionFile(collectionId);\n if (!file) return null;\n\n const defaultExport = file.getDefaultExportSymbol();\n if (defaultExport) {\n const declaration = defaultExport.getDeclarations()[0];\n if (declaration && declaration.getKind() === SyntaxKind.ExportAssignment) {\n const expr = declaration.asKind(SyntaxKind.ExportAssignment)?.getExpression();\n if (expr && expr.getKind() === SyntaxKind.Identifier) {\n const varName = expr.getText();\n const varDecl = file.getVariableDeclaration(varName);\n const unwrapped = this.unwrapCollectionObject(varDecl?.getInitializer());\n if (unwrapped) return unwrapped;\n } else {\n // `export default defineCollection({ … })`\n const unwrapped = this.unwrapCollectionObject(expr);\n if (unwrapped) return unwrapped;\n }\n }\n }\n // Fallback: the first VariableDeclaration that holds a collection literal\n for (const varDecl of file.getVariableDeclarations()) {\n const init = this.unwrapCollectionObject(varDecl.getInitializer());\n if (init) return init;\n }\n return null;\n }\n\n /**\n * The collection's object literal, or a refusal that says what to do.\n *\n * Every caller needs this to be all-or-nothing: a missing object literal used\n * to mean \"throw\", \"report success and do nothing\" and \"recreate the file\n * from scratch\" depending on which method you called.\n */\n private requireCollectionObject(collectionId: string): ObjectLiteralExpression {\n const file = this.getCollectionFile(collectionId);\n if (!file) {\n throw new Error(`Collection \"${collectionId}\" has no file at ${path.join(this.collectionsDir, `${collectionId}.ts`)}.`);\n }\n const collectionObj = this.getCollectionObject(collectionId);\n if (!collectionObj) {\n throw new Error(this.unreadableFileMessage(collectionId, file));\n }\n return collectionObj;\n }\n\n private unreadableFileMessage(collectionId: string, file: SourceFile): string {\n return `Could not find the collection object in ${file.getFilePath()}. ` +\n \"The schema editor can only edit a collection declared as `const x = defineCollection({ … })` \" +\n \"or `const x: CollectionConfig = { … }` and exported as the file's default. \" +\n `Edit \"${collectionId}\" in code instead.`;\n }\n\n /** Look a key up on an object literal, quoted or not. */\n private findProperty(obj: ObjectLiteralExpression, name: string): ObjectLiteralElementLike | undefined {\n return obj.getProperty((p: ObjectLiteralElementLike) =>\n \"getName\" in p &&\n typeof (p as PropertyAssignment).getName === \"function\" &&\n ((p as PropertyAssignment).getName() === name ||\n (p as PropertyAssignment).getName() === `\"${name}\"` ||\n (p as PropertyAssignment).getName() === `'${name}'`));\n }\n\n private static quoteKey(key: string): string {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key);\n }\n\n private static isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value) && !(value instanceof RawExpression);\n }\n\n private convertJsonToAstString(obj: unknown, indentLevel = 0, oldAstNode?: ObjectLiteralExpression): string {\n // Base TS-morph parses arrays as 2 levels deep from the property key:\n // PropertiesObject = level 1, PropertyConfig = level 2.\n // We calibrate the spacing multiples to keep the items flush with standard TS format.\n const indentStr = \" \";\n const indent = indentStr.repeat(indentLevel);\n const innerIndent = indentStr.repeat(indentLevel + 1);\n\n if (obj instanceof RawExpression) {\n return obj.text;\n }\n if (obj === null || obj === undefined) {\n return \"undefined\";\n }\n if (typeof obj === \"string\") {\n return JSON.stringify(obj);\n }\n if (typeof obj === \"number\" || typeof obj === \"boolean\") {\n return String(obj);\n }\n if (Array.isArray(obj)) {\n if (obj.length === 0) return \"[]\";\n const items = obj.map(item => this.convertJsonToAstString(item, indentLevel + 1));\n return `[\\n${innerIndent}${items.join(`,\\n${innerIndent}`)}\\n${indent}]`;\n }\n if (typeof obj === \"object\") {\n const record = obj as Record<string, unknown>;\n const keys = Object.keys(record);\n\n // Collect preserved AST properties\n const preservedProps: string[] = [];\n if (oldAstNode) {\n const oldProps = oldAstNode.getProperties();\n for (const oldProp of oldProps) {\n if (oldProp.isKind(SyntaxKind.PropertyAssignment)) {\n const nameNode = oldProp.getNameNode();\n let name = nameNode.getText();\n if (name.startsWith('\"') && name.endsWith('\"')) name = name.slice(1, -1);\n if (name.startsWith(\"'\") && name.endsWith(\"'\")) name = name.slice(1, -1);\n\n // If the JSON object doesn't have this key, check if we should preserve it\n if (!(name in record)) {\n const init = oldProp.getInitializer();\n if (init) {\n const kind = init.getKind();\n const isCode = kind === SyntaxKind.ArrowFunction ||\n kind === SyntaxKind.FunctionExpression ||\n kind === SyntaxKind.Identifier ||\n kind === SyntaxKind.CallExpression ||\n kind === SyntaxKind.JsxElement;\n\n if (isCode || name === \"target\" || name === \"callbacks\" || name === \"permissions\" || name === \"securityRules\") {\n // Preserve this property exactly as it was\n preservedProps.push(`${AstSchemaEditor.quoteKey(name)}: ${init.getText()}`);\n }\n }\n }\n }\n }\n }\n\n if (keys.length === 0 && preservedProps.length === 0) return \"{}\";\n\n const props = keys.map(key => {\n const keyStr = AstSchemaEditor.quoteKey(key);\n\n // If the value is an object, pass the old AST node to recurse\n let childAstNode: ObjectLiteralExpression | undefined;\n if (oldAstNode && AstSchemaEditor.isPlainObject(record[key])) {\n const oldProp = this.findProperty(oldAstNode, key);\n if (oldProp && oldProp.isKind(SyntaxKind.PropertyAssignment)) {\n childAstNode = oldProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);\n }\n }\n\n return `${keyStr}: ${this.convertJsonToAstString(record[key], indentLevel + 1, childAstNode)}`;\n });\n\n const allProps = [...props, ...preservedProps];\n return `{\\n${innerIndent}${allProps.join(`,\\n${innerIndent}`)}\\n${indent}}`;\n }\n return \"undefined\";\n }\n\n /**\n * Write only the keys the patch names, leaving every sibling alone.\n *\n * A patch says what changed, not what the collection is. The panel sends one\n * — `{ propertiesOrder }` is what adding a column posts — and rewriting the\n * `admin` block from it deleted the collection's icon, group, list columns\n * and kanban config in the same write.\n */\n private mergeIntoObjectLiteral(target: ObjectLiteralExpression, data: Record<string, unknown>, indentLevel: number): void {\n for (const [key, value] of Object.entries(data)) {\n const existing = this.findProperty(target, key);\n const existingObj = existing && existing.isKind(SyntaxKind.PropertyAssignment)\n ? existing.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression)\n : undefined;\n\n if (existingObj && AstSchemaEditor.isPlainObject(value)) {\n this.mergeIntoObjectLiteral(existingObj, value, indentLevel + 1);\n continue;\n }\n\n const initializer = this.convertJsonToAstString(value, indentLevel, existingObj);\n if (existing && existing.isKind(SyntaxKind.PropertyAssignment)) {\n existing.setInitializer(initializer);\n } else {\n target.addPropertyAssignment({\n name: AstSchemaEditor.quoteKey(key),\n initializer\n });\n }\n }\n }\n\n public async saveProperty(collectionId: string, propertyKey: string, propertyConfig: Record<string, unknown>) {\n const collectionObj = this.requireCollectionObject(collectionId);\n\n // The panel's property forms bind to the flat names — `readOnly`,\n // `hideFromCollection` — while on disk they belong inside the property's\n // own `admin` block. Written flat they are not merely ignored: the boot\n // validator treats a moved key as fatal.\n const nestedConfig = nestAdminPropertyKeys(propertyConfig);\n\n let propertiesProp = collectionObj.getProperty(\"properties\") as PropertyAssignment;\n if (!propertiesProp) {\n propertiesProp = collectionObj.addPropertyAssignment({\n name: \"properties\",\n initializer: \"{}\"\n });\n }\n\n const propsObj = propertiesProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);\n if (propsObj) {\n const existingProp = this.findProperty(propsObj, propertyKey);\n\n let oldPropAstNode: ObjectLiteralExpression | undefined;\n if (existingProp && existingProp.isKind(SyntaxKind.PropertyAssignment)) {\n oldPropAstNode = existingProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);\n }\n\n const newInitializer = this.convertJsonToAstString(nestedConfig, 2, oldPropAstNode);\n\n if (existingProp) {\n if (existingProp.isKind(SyntaxKind.PropertyAssignment)) {\n existingProp.setInitializer(newInitializer);\n }\n } else {\n propsObj.addPropertyAssignment({\n name: AstSchemaEditor.quoteKey(propertyKey),\n initializer: newInitializer\n });\n }\n\n const file = this.getCollectionFile(collectionId);\n if (file) {\n file.formatText();\n }\n await this.project.save();\n }\n }\n\n public async deleteProperty(collectionId: string, propertyKey: string) {\n const collectionObj = this.requireCollectionObject(collectionId);\n\n const propertiesProp = collectionObj.getProperty(\"properties\") as PropertyAssignment;\n if (propertiesProp) {\n const propsObj = propertiesProp.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);\n if (propsObj) {\n const existingProp = this.findProperty(propsObj, propertyKey);\n if (existingProp) {\n existingProp.remove();\n const file = this.getCollectionFile(collectionId);\n if (file) {\n file.formatText();\n }\n await this.project.save();\n }\n }\n }\n }\n\n /**\n * Write a collection back to its file.\n *\n * `partial` is the difference between \"this is the collection\" and \"this is\n * what changed about it\". The panel sends both — a full save from the editor\n * dialog, and a one-key patch whenever a property is added, deleted or\n * reordered — and they cannot be told apart by looking at the payload. Read\n * as a full save, a patch deletes everything it does not mention, including\n * `securityRules`; the loader then hands the collection the directory\n * default, which in the scaffold is `access: \"public\"`.\n */\n public async saveCollection(collectionId: string, collectionData: Record<string, unknown>, options: { partial?: boolean } = {}) {\n const partial = options.partial === true;\n let file = this.getCollectionFile(collectionId);\n const collectionObj = file ? this.getCollectionObject(collectionId) : null;\n\n if (file && !collectionObj) {\n // The file is there and we could not read it. Recreating it from the\n // panel's JSON would drop the imports, the callbacks and the relation\n // thunks that JSON cannot carry.\n throw new Error(this.unreadableFileMessage(collectionId, file));\n }\n\n if (!file || !collectionObj) {\n if (partial) {\n throw new Error(`Cannot apply a partial update to \"${collectionId}\": it has no collection file yet.`);\n }\n // Create a new file\n const safeId = this.sanitizeCollectionId(collectionId);\n const newFilePath = this.safePath(`${safeId}.ts`);\n if (fs.existsSync(newFilePath)) {\n throw new Error(`Refusing to overwrite ${newFilePath}: a file for \"${collectionId}\" already exists but could not be parsed.`);\n }\n const varName = `${AstSchemaEditor.collectionVarName(safeId)}Collection`;\n file = this.project.createSourceFile(newFilePath, `import { CollectionConfig } from \"@rebasepro/types\";\\n\\nconst ${varName}: CollectionConfig = ${this.convertJsonToAstString(nestAdminKeys(collectionData))};\\n\\nexport default ${varName};\\n`);\n } else {\n // Update root level properties gracefully\n\n if (!partial) {\n // Force delete securityRules if empty or undefined to handle Formex / serialization stripping\n if (!(\"securityRules\" in collectionData) || collectionData.securityRules === undefined || (Array.isArray(collectionData.securityRules) && collectionData.securityRules.length === 0)) {\n const srProp = collectionObj.getProperty(\"securityRules\");\n if (srProp) {\n srProp.remove();\n }\n\n // If it was in collectionData as an empty array, delete it so the loop below doesn't add it back as \"[]\"\n // Actually, if it's \"[]\", omitting it entirely from the TS file achieves the same logical effect (no RLS rules)\n // and correctly triggers \"unmapped policies\" if the DB still has them.\n delete collectionData[\"securityRules\"];\n }\n }\n\n // The panel works with a flat view model — presentation merged onto the\n // collection — so what arrives here has `icon` and `listProperties` at\n // the top level. On disk they belong inside `admin`. Writing them flat\n // would produce a file the backend loads and ignores and the panel\n // never reads back, which looks exactly like the edit not saving.\n collectionData = nestAdminKeys(collectionData);\n\n for (const key of Object.keys(collectionData)) {\n if (key === \"relations\") {\n this.writeRelations(collectionId, file, collectionObj, collectionData[key]);\n continue;\n }\n\n const prop = collectionObj.getProperty(key) as PropertyAssignment;\n\n let oldAstNode: ObjectLiteralExpression | undefined;\n if (prop && prop.isKind(SyntaxKind.PropertyAssignment)) {\n oldAstNode = prop.getInitializerIfKind(SyntaxKind.ObjectLiteralExpression);\n }\n\n if (partial && oldAstNode && AstSchemaEditor.isPlainObject(collectionData[key])) {\n this.mergeIntoObjectLiteral(oldAstNode, collectionData[key] as Record<string, unknown>, 2);\n continue;\n }\n\n const newInit = this.convertJsonToAstString(collectionData[key], 1, oldAstNode);\n if (prop) {\n prop.setInitializer(newInit);\n } else {\n collectionObj.addPropertyAssignment({\n name: key,\n initializer: newInit\n });\n }\n }\n }\n if (file) {\n file.formatText();\n }\n await this.project.save();\n }\n\n /**\n * Write the collection-level `relations` array.\n *\n * Relations are the one key whose values are not all data: `target` is a\n * thunk in the file, and the panel sends the target collection's slug (or,\n * for a relation it did not touch, nothing at all — `JSON.stringify` drops\n * the function). So each entry's target is resolved in that order: a slug\n * becomes `() => xCollection` plus the import it needs, and anything else\n * falls back to the thunk already in the file.\n *\n * This used to be a `continue` with a comment saying relations were handled\n * elsewhere. Nothing handled them; every edit in the Relations tab was\n * dropped without a word.\n */\n private writeRelations(collectionId: string, file: SourceFile, collectionObj: ObjectLiteralExpression, value: unknown): void {\n if (!Array.isArray(value)) return;\n\n const existing = this.findProperty(collectionObj, \"relations\");\n const oldArray = existing && existing.isKind(SyntaxKind.PropertyAssignment)\n ? existing.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression)\n : undefined;\n\n const oldElements = oldArray?.getElements() ?? [];\n const oldTargetsByName = new Map<string, string>();\n // Only for entries the file left unnamed — `relationName` is optional, and\n // those cannot be matched any other way. Positional matching is off the\n // moment the array's length changes, because then a position no longer\n // means the same relation.\n const anonymousTargetsByIndex: (string | undefined)[] = [];\n oldElements.forEach((element, index) => {\n const elementObj = element.asKind(SyntaxKind.ObjectLiteralExpression);\n if (!elementObj) return;\n const targetProp = this.findProperty(elementObj, \"target\");\n const targetInit = targetProp && targetProp.isKind(SyntaxKind.PropertyAssignment)\n ? targetProp.getInitializer()\n : undefined;\n if (!targetInit) return;\n\n const nameProp = this.findProperty(elementObj, \"relationName\");\n const nameInit = nameProp && nameProp.isKind(SyntaxKind.PropertyAssignment)\n ? nameProp.getInitializerIfKind(SyntaxKind.StringLiteral)\n : undefined;\n if (nameInit) oldTargetsByName.set(nameInit.getLiteralValue(), targetInit.getText());\n else anonymousTargetsByIndex[index] = targetInit.getText();\n });\n\n const items = value.map((entry, index) => {\n if (!AstSchemaEditor.isPlainObject(entry)) return entry;\n const relation: Record<string, unknown> = { ...entry };\n const relationName = typeof relation.relationName === \"string\" ? relation.relationName : undefined;\n const rawTarget = relation.target;\n\n let targetText: string | undefined;\n if (typeof rawTarget === \"string\" && rawTarget.trim().length > 0) {\n targetText = rawTarget.includes(\"=>\")\n ? rawTarget.trim()\n : this.targetThunk(file, rawTarget.trim());\n } else if (relationName && oldTargetsByName.has(relationName)) {\n targetText = oldTargetsByName.get(relationName);\n } else if (value.length === oldElements.length) {\n targetText = anonymousTargetsByIndex[index];\n }\n\n if (!targetText) {\n throw new Error(`Relation \"${relationName ?? `#${index}`}\" on collection \"${collectionId}\" has no target collection. Pick one before saving.`);\n }\n\n relation.target = new RawExpression(targetText);\n return relation;\n });\n\n const initializer = this.convertJsonToAstString(items, 1);\n if (existing && existing.isKind(SyntaxKind.PropertyAssignment)) {\n existing.setInitializer(initializer);\n } else {\n collectionObj.addPropertyAssignment({ name: \"relations\", initializer });\n }\n }\n\n /**\n * `() => targetCollection` for a target named by its slug, importing it if\n * the file does not already.\n */\n private targetThunk(file: SourceFile, targetSlug: string): string {\n const targetFile = this.getCollectionFile(targetSlug);\n if (!targetFile) {\n throw new Error(`Cannot link to collection \"${targetSlug}\": no file for it in ${this.collectionsDir}.`);\n }\n\n const identifier = this.getDefaultExportName(targetFile);\n if (!identifier) {\n throw new Error(`Cannot link to collection \"${targetSlug}\": ${targetFile.getFilePath()} has no default export to import.`);\n }\n\n if (targetFile.getFilePath() !== file.getFilePath() && !this.hasDefaultImport(file, identifier)) {\n const relative = path.relative(path.dirname(file.getFilePath()), targetFile.getFilePath())\n .split(path.sep)\n .join(\"/\")\n .replace(/\\.tsx?$/, \".js\");\n file.addImportDeclaration({\n defaultImport: identifier,\n moduleSpecifier: relative.startsWith(\".\") ? relative : `./${relative}`\n });\n }\n\n return `() => ${identifier}`;\n }\n\n private hasDefaultImport(file: SourceFile, identifier: string): boolean {\n return file.getImportDeclarations().some(decl => decl.getDefaultImport()?.getText() === identifier);\n }\n\n private getDefaultExportName(file: SourceFile): string | undefined {\n const declaration = file.getDefaultExportSymbol()?.getDeclarations()[0];\n const expr = declaration?.asKind(SyntaxKind.ExportAssignment)?.getExpression();\n if (expr && expr.getKind() === SyntaxKind.Identifier) return expr.getText();\n\n for (const varDecl of file.getVariableDeclarations()) {\n if (this.unwrapCollectionObject(varDecl.getInitializer())) return varDecl.getName();\n }\n return undefined;\n }\n\n public async deleteCollection(collectionId: string) {\n const file = this.getCollectionFile(collectionId);\n if (file) {\n file.deleteImmediatelySync();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAcA,IAAM,uCAAuB,IAAI,IAAI,CAAC,kBAAkB,CAAC;;;;;;;;;AAUzD,IAAM,gBAAN,MAAoB;CACY;CAA5B,YAAY,MAA8B;EAAd,KAAA,OAAA;CAC5B;AACJ;;;;;;;;;;AAWA,SAAgB,cAAc,gBAAkE;CAC5F,OAAO,wBAAwB,cAAc;AACjD;AAEA,IAAa,kBAAb,MAAa,gBAAgB;CACzB;CACA;CAEA,YAAY,gBAAwB;EAChC,KAAK,UAAU,IAAI,QAAQ,EACvB,sBAAsB,EAClB,iBAAiB,gBAAgB,WACrC,EACJ,CAAC;EACD,IAAI,KAAG,WAAW,cAAc,GAC5B,KAAK,QAAQ,sBAAsB,GAAG,eAAe,SAAS;EAElE,KAAK,iBAAiB,OAAK,QAAQ,cAAc;CACrD;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BA,OAAe,kBAAkB,QAAwB;EACrD,MAAM,QAAQ,OAAO,QAAQ,wBAAwB,GAAG,SAAiB,KAAK,YAAY,CAAC;EAC3F,MAAM,aAAa,6BAA6B,KAAK,KAAK,IAAI,QAAQ,IAAI,MAAM,QAAQ,WAAW,MAAM,CAAC;EAC1G,OAAO,6BAA6B,KAAK,UAAU,IAAI,aAAa,IAAI,WAAW,QAAQ,mBAAmB,EAAE;CACpH;CAEA,qBAA6B,cAA8B;EACvD,MAAM,YAAY,aAAa,QAAQ,mBAAmB,EAAE;EAC5D,IAAI,CAAC,aAAa,cAAc,cAC5B,MAAM,IAAI,MAAM,2BAA2B,aAAa,uEAAuE;EAEnI,OAAO;CACX;;;;CAKA,SAAiB,UAA0B;EACvC,MAAM,WAAW,OAAK,QAAQ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AAM,UAAU,GAAG;GAC7F,MAAM,WAAW,OAAK,SAAS,OAAK,QAAQ,KAAK,YAAY,CAAC,GAAG,WAAW,YAAY,CAAC,CAAC,CACrF,MAAM,OAAK,GAAG,CAAC,CACf,KAAK,GAAG,CAAC,CACT,QAAQ,WAAW,KAAK;GAC7B,KAAK,qBAAqB;IACtB,eAAe;IACf,iBAAiB,SAAS,WAAW,GAAG,IAAI,WAAW,KAAK;GAChE,CAAC;EACL;EAEA,OAAO,SAAS;CACpB;CAEA,iBAAyB,MAAkB,YAA6B;EACpE,OAAO,KAAK,sBAAsB,CAAC,CAAC,MAAK,SAAQ,KAAK,iBAAiB,CAAC,EAAE,QAAQ,MAAM,UAAU;CACtG;CAEA,qBAA6B,MAAsC;EAE/D,MAAM,QADc,KAAK,uBAAuB,CAAC,EAAE,gBAAgB,CAAC,CAAC,GAAA,EAC3C,OAAO,WAAW,gBAAgB,CAAC,EAAE,cAAc;EAC7E,IAAI,QAAQ,KAAK,QAAQ,MAAM,WAAW,YAAY,OAAO,KAAK,QAAQ;EAE1E,KAAK,MAAM,WAAW,KAAK,wBAAwB,GAC/C,IAAI,KAAK,uBAAuB,QAAQ,eAAe,CAAC,GAAG,OAAO,QAAQ,QAAQ;CAG1F;CAEA,MAAa,iBAAiB,cAAsB;EAChD,MAAM,OAAO,KAAK,kBAAkB,YAAY;EAChD,IAAI,MACA,KAAK,sBAAsB;CAEnC;AACJ"}
@@ -9,6 +9,10 @@
9
9
  * Used for comparing service keys, tokens, and other secrets where
10
10
  * timing side-channels could leak information about the expected value.
11
11
  *
12
+ * The implementation lives in `utils/portable-crypto.ts`, which does this over
13
+ * UTF-8 bytes without `node:crypto` — this function is on the request path, and
14
+ * the byte-level reasoning it depends on is documented there.
15
+ *
12
16
  * @param a - First string to compare.
13
17
  * @param b - Second string to compare.
14
18
  * @returns `true` if the strings are identical, `false` otherwise.
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The one module in the request path that knows what signs a JWT.
3
+ *
4
+ * `jsonwebtoken` is built on `node:crypto` and is synchronous. Every portable
5
+ * JWT implementation — WebCrypto directly, or `jose` on top of it — is
6
+ * asynchronous, because `crypto.subtle` is. So the shape of the boundary
7
+ * matters more than what is behind it right now: **these functions are async
8
+ * and `jsonwebtoken` is confined to this file.**
9
+ *
10
+ * That is the expensive half of the change, and it is why it was made before
11
+ * anything actually needed it. Swapping the implementation touches one file.
12
+ * Going from synchronous to asynchronous verification touches every caller of
13
+ * every function that verifies a token — which, at the time of writing, is
14
+ * eleven call sites in `src` and about a hundred and eighty in the suite. Doing
15
+ * that as a line item inside a runtime port, on top of everything else moving
16
+ * at once, is how a port stalls.
17
+ *
18
+ * What is **not** here: key parsing. `jwt-keys.ts` turns PEM into
19
+ * `node:crypto` `KeyObject`s, and the portable replacement for that is
20
+ * `jose`'s `importSPKI`/`importPKCS8` — a dependency this package does not
21
+ * carry yet. It stays recorded in `contracts/portable-core.txt` rather than
22
+ * wrapped in something that would imply it had moved.
23
+ *
24
+ * ## Replacing this with jose
25
+ *
26
+ * Add `jose` (a lockfile change, so it happens in the primary checkout), then:
27
+ * `signJwt` becomes `new SignJWT(payload).setProtectedHeader({ alg, kid })
28
+ * .setExpirationTime(...).sign(key)`, `verifyJwt` becomes `jwtVerify(token,
29
+ * key, { algorithms })`, and `decodeProtectedHeader` is already what jose's
30
+ * function of that name does. Nothing outside this file changes — with one
31
+ * exception worth writing down, because nothing would fail loudly:
32
+ * **`jsonwebtoken` stamps `iat` on every token it signs and jose does not**
33
+ * (it wants an explicit `.setIssuedAt()`). `iat` is what the revocation
34
+ * watermark compares against — `logout`, `change-password`, `reset-password`
35
+ * and `DELETE /auth/sessions` all stamp `tokensValidAfter` on the user, and
36
+ * every access token issued before that mark is void. Tokens minted without
37
+ * `iat` would verify perfectly well and simply stop being revocable.
38
+ *
39
+ * @module
40
+ */
41
+ import jwt from "jsonwebtoken";
42
+ /**
43
+ * Key material, as whatever the current implementation accepts.
44
+ *
45
+ * Deliberately expressed in terms of `jsonwebtoken`'s own parameter types
46
+ * rather than spelled out: naming `KeyObject` here would put `node:crypto` in
47
+ * the signature and leak the thing this module exists to contain.
48
+ */
49
+ export type JwtSigningKey = jwt.Secret | jwt.PrivateKey;
50
+ export type JwtVerificationKey = jwt.Secret | jwt.PublicKey;
51
+ export interface JwtSignOptions {
52
+ algorithm: string;
53
+ /** Seconds, or a duration string such as `"1h"`. */
54
+ expiresIn?: number | string;
55
+ /** The `kid` header, so a verifier can pick the right key out of a JWKS. */
56
+ keyid?: string;
57
+ }
58
+ /** The claims of a verified token. Callers narrow; nothing here interprets. */
59
+ export type JwtClaims = Record<string, unknown>;
60
+ /** Sign a set of claims. Rejects if the key and algorithm disagree. */
61
+ export declare function signJwt(payload: JwtClaims, key: JwtSigningKey, options: JwtSignOptions): Promise<string>;
62
+ /**
63
+ * Verify a token against one key and an explicit algorithm list, and return its
64
+ * claims. Rejects — never returns null — when the token is not valid.
65
+ *
66
+ * `algorithms` has no default and must not acquire one. Letting the verifier
67
+ * read `alg` out of the token's own header is the canonical JWT vulnerability:
68
+ * an attacker takes a published RSA public key, HMACs a payload of their
69
+ * choosing with it, sets `alg: HS256`, and a verifier holding that same public
70
+ * key as "the secret" agrees. The caller decides the algorithm from the key it
71
+ * chose, and {@link decodeProtectedHeader} exists so it can choose that key
72
+ * without trusting anything the token asserts.
73
+ */
74
+ export declare function verifyJwt(token: string, key: JwtVerificationKey, options: {
75
+ algorithms: string[];
76
+ }): Promise<JwtClaims>;
77
+ /**
78
+ * The token's unverified header — `kid` and `alg` — or an empty object.
79
+ *
80
+ * Unverified is the point: this is read *in order to* pick the key that will
81
+ * verify it, so it cannot itself be verified first. Nothing but key selection
82
+ * may depend on it, and key selection then pins the algorithm.
83
+ *
84
+ * Implemented here rather than via the JWT library because it is plain
85
+ * base64url and JSON, needs no cryptography, and there is no reason for the
86
+ * portable half of this module to wait on the non-portable half.
87
+ */
88
+ export declare function decodeProtectedHeader(token: string): {
89
+ kid?: string;
90
+ alg?: string;
91
+ };
@@ -35,7 +35,8 @@ export interface AccessTokenPayload {
35
35
  aal?: "aal1" | "aal2";
36
36
  /**
37
37
  * When the token was issued, in seconds since the epoch — the standard JWT
38
- * `iat` claim, which `jsonwebtoken` sets on every token it signs.
38
+ * `iat` claim, which the signer behind `jwt-crypto.ts` sets on every token
39
+ * it mints — see the note there before replacing that implementation.
39
40
  *
40
41
  * Carried through verification because revocation needs it: `logout`,
41
42
  * `change-password`, `reset-password` and `DELETE /auth/sessions` all stamp
@@ -89,7 +90,7 @@ export declare function isJwtConfigured(): boolean;
89
90
  /**
90
91
  * Generate an access token (short-lived, 1 hour by default)
91
92
  */
92
- export declare function generateAccessToken(uid: string, roles: string[], aal?: "aal1" | "aal2", customClaims?: Record<string, unknown>): string;
93
+ export declare function generateAccessToken(uid: string, roles: string[], aal?: "aal1" | "aal2", customClaims?: Record<string, unknown>): Promise<string>;
93
94
  /**
94
95
  * Get the expiration time of an access token in milliseconds from now
95
96
  */
@@ -112,7 +113,7 @@ export declare function getAccessTokenExpiry(): number;
112
113
  * checked explicitly: a token minted for reading a file is not a token for
113
114
  * being a user.
114
115
  */
115
- export declare function verifyAccessToken(token: string): AccessTokenPayload | null;
116
+ export declare function verifyAccessToken(token: string): Promise<AccessTokenPayload | null>;
116
117
  /**
117
118
  * Generate a random refresh token (long-lived, 30 days by default)
118
119
  */
@@ -120,7 +121,7 @@ export declare function generateRefreshToken(): string;
120
121
  /**
121
122
  * Hash a refresh token for database storage (don't store raw tokens)
122
123
  */
123
- export declare function hashRefreshToken(token: string): string;
124
+ export declare function hashRefreshToken(token: string): Promise<string>;
124
125
  /**
125
126
  * The longest a cookie can live. Chrome (since 104) and RFC 6265bis silently
126
127
  * rewrite any `Max-Age` beyond 400 days down to 400 days, so promising a
@@ -160,16 +161,16 @@ export declare const MFA_PENDING_PURPOSE = "mfa-pending";
160
161
  * first factor may present the second, not a session to be carried around. Five
161
162
  * minutes matches the challenge TTL.
162
163
  */
163
- export declare function generateMfaPendingToken(uid: string, expiresInSeconds?: number): string;
164
+ export declare function generateMfaPendingToken(uid: string, expiresInSeconds?: number): Promise<string>;
164
165
  /**
165
166
  * Verify a pre-auth token and return the user it was minted for.
166
167
  *
167
168
  * Returns `null` for anything else — including a perfectly valid *access*
168
169
  * token, which must not be interchangeable with this one in either direction.
169
170
  */
170
- export declare function verifyMfaPendingToken(token: string): {
171
+ export declare function verifyMfaPendingToken(token: string): Promise<{
171
172
  uid: string;
172
- } | null;
173
+ } | null>;
173
174
  export interface DownloadTokenPayload {
174
175
  purpose: "file-read";
175
176
  path: string;
@@ -198,7 +199,7 @@ export interface DownloadTokenPayload {
198
199
  * site that forgets to pass a named source produces a default-scoped token,
199
200
  * which fails closed at `/file/*` rather than over-granting.
200
201
  */
201
- export declare function generateDownloadToken(path: string, expiresInSeconds?: number, storageId?: string | null): string;
202
+ export declare function generateDownloadToken(path: string, expiresInSeconds?: number, storageId?: string | null): Promise<string>;
202
203
  /**
203
204
  * Verify and decode a download token.
204
205
  *
@@ -209,4 +210,4 @@ export declare function generateDownloadToken(path: string, expiresInSeconds?: n
209
210
  * five-minute TTL — for at most that long after a deploy, an in-flight token
210
211
  * for a *named* source is refused and the client re-fetches `/metadata`.
211
212
  */
212
- export declare function verifyDownloadToken(token: string): DownloadTokenPayload | null;
213
+ export declare function verifyDownloadToken(token: string): Promise<DownloadTokenPayload | null>;
@@ -127,7 +127,7 @@ export declare const optionalAuth: MiddlewareHandler<HonoEnv>;
127
127
  /**
128
128
  * Extract user from token - for WebSocket authentication
129
129
  */
130
- export declare function extractUserFromToken(token: string): AccessTokenPayload | null;
130
+ export declare function extractUserFromToken(token: string): Promise<AccessTokenPayload | null>;
131
131
  /**
132
132
  * Create a configurable auth middleware that handles:
133
133
  * 1. Token extraction (via custom validator or JWT Bearer token)
@@ -12,8 +12,15 @@ interface RateLimiterOptions {
12
12
  windowMs?: number;
13
13
  /** Maximum requests per window (default: 100) */
14
14
  limit?: number;
15
- /** Key generator function. Defaults to IP-based keying. */
16
- keyGenerator?: (c: Parameters<MiddlewareHandler<HonoEnv>>[0]) => string;
15
+ /**
16
+ * Key generator function. Defaults to IP-based keying.
17
+ *
18
+ * May return a promise: a generator that buckets by the *user* has to
19
+ * verify a token to find one, and verification is asynchronous (see
20
+ * `jwt-crypto.ts`). Returning a plain string is still fine, and is what
21
+ * every IP-keyed generator does.
22
+ */
23
+ keyGenerator?: (c: Parameters<MiddlewareHandler<HonoEnv>>[0]) => string | Promise<string>;
17
24
  /** Custom message for rate limit responses */
18
25
  message?: string;
19
26
  /**
@@ -26,7 +33,7 @@ interface RateLimiterOptions {
26
33
  * than config (an API key's own `rate_limit`). Returning `undefined` uses
27
34
  * `limit`; returning `null` skips the limiter for this request.
28
35
  */
29
- resolveLimit?: (c: Parameters<MiddlewareHandler<HonoEnv>>[0]) => number | null | undefined;
36
+ resolveLimit?: (c: Parameters<MiddlewareHandler<HonoEnv>>[0]) => number | null | undefined | Promise<number | null | undefined>;
30
37
  /**
31
38
  * Number of trusted reverse-proxy hops in front of this server. Each hop
32
39
  * appends the address it saw to `X-Forwarded-For`, so the real client IP is