@bevel-software/platform-core-backend 0.23.0 → 0.25.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 (238) hide show
  1. package/dist/core/create-core-server.d.ts.map +1 -1
  2. package/dist/core/create-core-server.js +17 -3
  3. package/dist/core/create-core-server.js.map +1 -1
  4. package/dist/core/create-core-services.d.ts +3 -0
  5. package/dist/core/create-core-services.d.ts.map +1 -1
  6. package/dist/core/create-core-services.js +25 -1
  7. package/dist/core/create-core-services.js.map +1 -1
  8. package/dist/core/lifecycle.d.ts +12 -0
  9. package/dist/core/lifecycle.d.ts.map +1 -1
  10. package/dist/core/lifecycle.js +10 -0
  11. package/dist/core/lifecycle.js.map +1 -1
  12. package/dist/core-config.d.ts +16 -0
  13. package/dist/core-config.d.ts.map +1 -1
  14. package/dist/core-config.js +17 -0
  15. package/dist/core-config.js.map +1 -1
  16. package/dist/index.d.ts +3 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +13 -2
  19. package/dist/index.js.map +1 -1
  20. package/dist/modules/access/access.routes.d.ts.map +1 -1
  21. package/dist/modules/access/access.routes.js +4 -1
  22. package/dist/modules/access/access.routes.js.map +1 -1
  23. package/dist/modules/access/directory-sync-bot.d.ts.map +1 -1
  24. package/dist/modules/access/directory-sync-bot.js +7 -3
  25. package/dist/modules/access/directory-sync-bot.js.map +1 -1
  26. package/dist/modules/agent-instructions/agent-instructions.routes.d.ts +8 -1
  27. package/dist/modules/agent-instructions/agent-instructions.routes.d.ts.map +1 -1
  28. package/dist/modules/agent-instructions/agent-instructions.routes.js +8 -2
  29. package/dist/modules/agent-instructions/agent-instructions.routes.js.map +1 -1
  30. package/dist/modules/agent-instructions/compose.d.ts +38 -6
  31. package/dist/modules/agent-instructions/compose.d.ts.map +1 -1
  32. package/dist/modules/agent-instructions/compose.js +39 -6
  33. package/dist/modules/agent-instructions/compose.js.map +1 -1
  34. package/dist/modules/agent-instructions/index.d.ts +2 -1
  35. package/dist/modules/agent-instructions/index.d.ts.map +1 -1
  36. package/dist/modules/agent-instructions/index.js +2 -1
  37. package/dist/modules/agent-instructions/index.js.map +1 -1
  38. package/dist/modules/agent-instructions/shared-file-rules.d.ts +115 -0
  39. package/dist/modules/agent-instructions/shared-file-rules.d.ts.map +1 -0
  40. package/dist/modules/agent-instructions/shared-file-rules.js +272 -0
  41. package/dist/modules/agent-instructions/shared-file-rules.js.map +1 -0
  42. package/dist/modules/audit/agent-audit.service.d.ts.map +1 -1
  43. package/dist/modules/audit/agent-audit.service.js +4 -2
  44. package/dist/modules/audit/agent-audit.service.js.map +1 -1
  45. package/dist/modules/auth/account-erasure.service.d.ts.map +1 -1
  46. package/dist/modules/auth/account-erasure.service.js +57 -16
  47. package/dist/modules/auth/account-erasure.service.js.map +1 -1
  48. package/dist/modules/auth/auth.service.d.ts.map +1 -1
  49. package/dist/modules/auth/auth.service.js +25 -15
  50. package/dist/modules/auth/auth.service.js.map +1 -1
  51. package/dist/modules/code-mode/code-mode.tool.d.ts +20 -2
  52. package/dist/modules/code-mode/code-mode.tool.d.ts.map +1 -1
  53. package/dist/modules/code-mode/code-mode.tool.js +66 -35
  54. package/dist/modules/code-mode/code-mode.tool.js.map +1 -1
  55. package/dist/modules/database/connection.d.ts +16 -0
  56. package/dist/modules/database/connection.d.ts.map +1 -1
  57. package/dist/modules/database/connection.js +117 -0
  58. package/dist/modules/database/connection.js.map +1 -1
  59. package/dist/modules/database/core-schema.d.ts +296 -96
  60. package/dist/modules/database/core-schema.d.ts.map +1 -1
  61. package/dist/modules/database/core-schema.js +81 -31
  62. package/dist/modules/database/core-schema.js.map +1 -1
  63. package/dist/modules/database/migrate.d.ts +95 -1
  64. package/dist/modules/database/migrate.d.ts.map +1 -1
  65. package/dist/modules/database/migrate.js +390 -2
  66. package/dist/modules/database/migrate.js.map +1 -1
  67. package/dist/modules/kb-fs/locking-filesystem.d.ts +17 -0
  68. package/dist/modules/kb-fs/locking-filesystem.d.ts.map +1 -1
  69. package/dist/modules/kb-fs/locking-filesystem.js +29 -0
  70. package/dist/modules/kb-fs/locking-filesystem.js.map +1 -1
  71. package/dist/modules/mcp/mcp.service.d.ts +8 -0
  72. package/dist/modules/mcp/mcp.service.d.ts.map +1 -1
  73. package/dist/modules/mcp/mcp.service.js +38 -8
  74. package/dist/modules/mcp/mcp.service.js.map +1 -1
  75. package/dist/modules/plugins/join-request-records.store.d.ts.map +1 -1
  76. package/dist/modules/plugins/join-request-records.store.js +7 -4
  77. package/dist/modules/plugins/join-request-records.store.js.map +1 -1
  78. package/dist/modules/tool-auth/external-api-key.service.d.ts.map +1 -1
  79. package/dist/modules/tool-auth/external-api-key.service.js +8 -2
  80. package/dist/modules/tool-auth/external-api-key.service.js.map +1 -1
  81. package/dist/modules/tool-manuals/tool-manuals.service.d.ts.map +1 -1
  82. package/dist/modules/tool-manuals/tool-manuals.service.js +30 -0
  83. package/dist/modules/tool-manuals/tool-manuals.service.js.map +1 -1
  84. package/dist/modules/tool-manuals/tool-manuals.tools.d.ts.map +1 -1
  85. package/dist/modules/tool-manuals/tool-manuals.tools.js +42 -31
  86. package/dist/modules/tool-manuals/tool-manuals.tools.js.map +1 -1
  87. package/dist/modules/tool-registry/description-length.d.ts +80 -0
  88. package/dist/modules/tool-registry/description-length.d.ts.map +1 -0
  89. package/dist/modules/tool-registry/description-length.js +108 -0
  90. package/dist/modules/tool-registry/description-length.js.map +1 -0
  91. package/dist/modules/workflow/git/git.service.d.ts +25 -0
  92. package/dist/modules/workflow/git/git.service.d.ts.map +1 -1
  93. package/dist/modules/workflow/git/git.service.js +40 -1
  94. package/dist/modules/workflow/git/git.service.js.map +1 -1
  95. package/dist/modules/workflow/pending-commits.service.d.ts.map +1 -1
  96. package/dist/modules/workflow/pending-commits.service.js +5 -1
  97. package/dist/modules/workflow/pending-commits.service.js.map +1 -1
  98. package/dist/modules/workflow/recovery-bot.d.ts.map +1 -1
  99. package/dist/modules/workflow/recovery-bot.js +7 -3
  100. package/dist/modules/workflow/recovery-bot.js.map +1 -1
  101. package/dist/modules/workflow/review-workflow/review-workflow.service.d.ts.map +1 -1
  102. package/dist/modules/workflow/review-workflow/review-workflow.service.js +12 -3
  103. package/dist/modules/workflow/review-workflow/review-workflow.service.js.map +1 -1
  104. package/dist/modules/workflow/workflow.service.d.ts.map +1 -1
  105. package/dist/modules/workflow/workflow.service.js +4 -1
  106. package/dist/modules/workflow/workflow.service.js.map +1 -1
  107. package/dist/modules/workspace/agent-upload.routes.d.ts +77 -0
  108. package/dist/modules/workspace/agent-upload.routes.d.ts.map +1 -0
  109. package/dist/modules/workspace/agent-upload.routes.js +210 -0
  110. package/dist/modules/workspace/agent-upload.routes.js.map +1 -0
  111. package/dist/modules/workspace/agent-upload.store.d.ts +284 -0
  112. package/dist/modules/workspace/agent-upload.store.d.ts.map +1 -0
  113. package/dist/modules/workspace/agent-upload.store.js +553 -0
  114. package/dist/modules/workspace/agent-upload.store.js.map +1 -0
  115. package/dist/modules/workspace/startup/steps/seed-tree.d.ts.map +1 -1
  116. package/dist/modules/workspace/startup/steps/seed-tree.js +3 -3
  117. package/dist/modules/workspace/startup/steps/seed-tree.js.map +1 -1
  118. package/dist/modules/workspace/startup/steps/template-source.d.ts +40 -0
  119. package/dist/modules/workspace/startup/steps/template-source.d.ts.map +1 -1
  120. package/dist/modules/workspace/startup/steps/template-source.js +46 -4
  121. package/dist/modules/workspace/startup/steps/template-source.js.map +1 -1
  122. package/dist/modules/workspace/upload-limits.d.ts +13 -0
  123. package/dist/modules/workspace/upload-limits.d.ts.map +1 -0
  124. package/dist/modules/workspace/upload-limits.js +13 -0
  125. package/dist/modules/workspace/upload-limits.js.map +1 -0
  126. package/dist/modules/workspace/workspace.routes.d.ts.map +1 -1
  127. package/dist/modules/workspace/workspace.routes.js +1 -1
  128. package/dist/modules/workspace/workspace.routes.js.map +1 -1
  129. package/dist/modules/workspace/workspace.service.d.ts +13 -0
  130. package/dist/modules/workspace/workspace.service.d.ts.map +1 -1
  131. package/dist/modules/workspace/workspace.service.js +61 -33
  132. package/dist/modules/workspace/workspace.service.js.map +1 -1
  133. package/dist/modules/workspace/workspace.tools.d.ts +11 -9
  134. package/dist/modules/workspace/workspace.tools.d.ts.map +1 -1
  135. package/dist/modules/workspace/workspace.tools.js +570 -134
  136. package/dist/modules/workspace/workspace.tools.js.map +1 -1
  137. package/dist/modules/workspace/write-denial.d.ts +0 -6
  138. package/dist/modules/workspace/write-denial.d.ts.map +1 -1
  139. package/dist/modules/workspace/write-denial.js +0 -6
  140. package/dist/modules/workspace/write-denial.js.map +1 -1
  141. package/dist/modules/workspace/zip-entry-rules.d.ts +114 -0
  142. package/dist/modules/workspace/zip-entry-rules.d.ts.map +1 -0
  143. package/dist/modules/workspace/zip-entry-rules.js +154 -0
  144. package/dist/modules/workspace/zip-entry-rules.js.map +1 -0
  145. package/dist/shared/column-crypto.d.ts +194 -0
  146. package/dist/shared/column-crypto.d.ts.map +1 -0
  147. package/dist/shared/column-crypto.js +144 -0
  148. package/dist/shared/column-crypto.js.map +1 -0
  149. package/dist/shared/token-crypto.d.ts.map +1 -1
  150. package/dist/shared/token-crypto.js +25 -1
  151. package/dist/shared/token-crypto.js.map +1 -1
  152. package/dist/tenancy/static-tenant-source.d.ts.map +1 -1
  153. package/dist/tenancy/static-tenant-source.js +1 -0
  154. package/dist/tenancy/static-tenant-source.js.map +1 -1
  155. package/dist/tenancy/tenant-secrets.d.ts +5 -1
  156. package/dist/tenancy/tenant-secrets.d.ts.map +1 -1
  157. package/dist/tenancy/tenant-secrets.js +4 -0
  158. package/dist/tenancy/tenant-secrets.js.map +1 -1
  159. package/kb-template/AGENTS.md +42 -0
  160. package/migrations/0016_pii_encryption.sql +20 -0
  161. package/migrations/meta/0016_snapshot.json +2327 -0
  162. package/migrations/meta/_journal.json +7 -0
  163. package/package.json +3 -3
  164. package/src/core/__tests__/lifecycle.test.ts +71 -4
  165. package/src/core/create-core-server.ts +21 -3
  166. package/src/core/create-core-services.ts +27 -1
  167. package/src/core/lifecycle.ts +19 -0
  168. package/src/core-config.ts +18 -0
  169. package/src/index.ts +25 -0
  170. package/src/modules/access/__tests__/users-db-double.ts +21 -12
  171. package/src/modules/access/access.routes.ts +4 -1
  172. package/src/modules/access/directory-sync-bot.ts +7 -3
  173. package/src/modules/agent-instructions/__tests__/agent-instructions.route.test.ts +8 -4
  174. package/src/modules/agent-instructions/__tests__/compose.test.ts +19 -10
  175. package/src/modules/agent-instructions/__tests__/shared-file-rules.test.ts +238 -0
  176. package/src/modules/agent-instructions/agent-instructions.routes.ts +12 -2
  177. package/src/modules/agent-instructions/compose.ts +50 -7
  178. package/src/modules/agent-instructions/index.ts +12 -0
  179. package/src/modules/agent-instructions/shared-file-rules.ts +314 -0
  180. package/src/modules/audit/agent-audit.service.ts +4 -2
  181. package/src/modules/auth/__tests__/account-deactivation.test.ts +2 -1
  182. package/src/modules/auth/__tests__/account-erasure.approval-gate.test.ts +6 -2
  183. package/src/modules/auth/__tests__/account.routes.test.ts +6 -3
  184. package/src/modules/auth/__tests__/auth.service.test.ts +3 -1
  185. package/src/modules/auth/account-erasure.service.ts +69 -18
  186. package/src/modules/auth/auth.service.ts +33 -23
  187. package/src/modules/code-mode/__tests__/chain-runtime.e2e.test.ts +335 -0
  188. package/src/modules/code-mode/__tests__/code-mode.tool.test.ts +46 -2
  189. package/src/modules/code-mode/code-mode.tool.ts +80 -34
  190. package/src/modules/database/__tests__/connection.test.ts +12 -0
  191. package/src/modules/database/__tests__/pii-backfill.pg.test.ts +780 -0
  192. package/src/modules/database/connection.ts +117 -0
  193. package/src/modules/database/core-schema.ts +81 -31
  194. package/src/modules/database/migrate.ts +540 -2
  195. package/src/modules/kb-fs/__tests__/locking-filesystem.test.ts +93 -0
  196. package/src/modules/kb-fs/locking-filesystem.ts +37 -0
  197. package/src/modules/mcp/__tests__/mcp.e2e.test.ts +4 -3
  198. package/src/modules/mcp/__tests__/mcp.service.test.ts +47 -7
  199. package/src/modules/mcp/mcp.service.ts +46 -7
  200. package/src/modules/plugins/join-request-records.store.ts +7 -4
  201. package/src/modules/tool-auth/external-api-key.service.ts +8 -2
  202. package/src/modules/tool-manuals/__tests__/tool-manuals.service.test.ts +151 -0
  203. package/src/modules/tool-manuals/tool-manuals.service.ts +37 -0
  204. package/src/modules/tool-manuals/tool-manuals.tools.ts +44 -31
  205. package/src/modules/tool-registry/__tests__/tool-description-length.test.ts +378 -0
  206. package/src/modules/tool-registry/description-length.ts +111 -0
  207. package/src/modules/workflow/git/__tests__/git.service.prFetchFailure.test.ts +170 -0
  208. package/src/modules/workflow/git/git.service.ts +47 -1
  209. package/src/modules/workflow/pending-commits.service.ts +5 -1
  210. package/src/modules/workflow/recovery-bot.ts +7 -3
  211. package/src/modules/workflow/review-workflow/__tests__/carry-approvals-forward.test.ts +4 -0
  212. package/src/modules/workflow/review-workflow/__tests__/erase-approver.test.ts +25 -3
  213. package/src/modules/workflow/review-workflow/review-workflow.service.ts +12 -3
  214. package/src/modules/workflow/workflow.service.ts +4 -1
  215. package/src/modules/workspace/__tests__/agent-uploads.test.ts +1604 -0
  216. package/src/modules/workspace/__tests__/escape-sequences.routes.test.ts +24 -14
  217. package/src/modules/workspace/__tests__/workspace.service.any-workspace-credentials.test.ts +156 -0
  218. package/src/modules/workspace/__tests__/workspace.service.replaced-repository.test.ts +77 -1
  219. package/src/modules/workspace/__tests__/workspace.service.test.ts +57 -0
  220. package/src/modules/workspace/__tests__/workspace.tools.agents-file.test.ts +39 -36
  221. package/src/modules/workspace/__tests__/workspace.tools.test.ts +196 -46
  222. package/src/modules/workspace/agent-upload.routes.ts +214 -0
  223. package/src/modules/workspace/agent-upload.store.ts +668 -0
  224. package/src/modules/workspace/startup/steps/__tests__/steps.test.ts +9 -9
  225. package/src/modules/workspace/startup/steps/seed-tree.ts +3 -6
  226. package/src/modules/workspace/startup/steps/template-source.ts +53 -5
  227. package/src/modules/workspace/upload-limits.ts +12 -0
  228. package/src/modules/workspace/workspace.routes.ts +1 -2
  229. package/src/modules/workspace/workspace.service.ts +63 -37
  230. package/src/modules/workspace/workspace.tools.ts +647 -148
  231. package/src/modules/workspace/write-denial.ts +0 -8
  232. package/src/modules/workspace/zip-entry-rules.ts +173 -0
  233. package/src/shared/__tests__/column-crypto.test.ts +217 -0
  234. package/src/shared/column-crypto.ts +218 -0
  235. package/src/shared/token-crypto.ts +28 -1
  236. package/src/tenancy/__tests__/static-tenant-source.test.ts +4 -0
  237. package/src/tenancy/static-tenant-source.ts +1 -0
  238. package/src/tenancy/tenant-secrets.ts +5 -1
@@ -7,14 +7,6 @@ import { toKbRelative } from '../access-model/kb-read-filter.js';
7
7
  import type { IAccessControl } from '../access/access-control.interface.js';
8
8
  import { workspaceIdForBranch } from '../../shared/workspace-id.js';
9
9
 
10
- /**
11
- * Appended to the description of every workspace tool whose refusal is mapped
12
- * by `writeDenial`, so an agent knows before it is refused that a refusal is
13
- * not necessarily the end of the road.
14
- */
15
- export const PROPOSAL_ROUTE_NOTE =
16
- ' If this is refused for permissions, the `write-denied` error says whether you may propose the change instead (create a branch from this one, repeat this call on it, then `open_change_request` into this branch) and lists those steps.';
17
-
18
10
  /** One step of the proposal route, named by the tool the agent calls. */
19
11
  export interface ProposalStep {
20
12
  tool: string;
@@ -0,0 +1,173 @@
1
+ import { inflateRawSync } from 'node:zlib';
2
+ import { validateFilename } from '@bevel-software/platform-shared';
3
+ import { GitInternalsError } from '../../shared/domain-errors.js';
4
+ import { hasGitInternalsSegment } from '../../shared/git-internals.js';
5
+
6
+ /**
7
+ * What an archive's entry NAMES are allowed to be, as one set of rules two
8
+ * surfaces ask: `unzip` (a .zip already in the workspace) and
9
+ * `apply_file_upload` (a .zip the agent sent to the upload route). Both land
10
+ * bytes an agent never typed at paths the archive chose, so both have to judge
11
+ * the same names the same way — and they did not, for as long as the rules
12
+ * lived inside `WorkspaceService.unzipFile` as three inline blocks.
13
+ *
14
+ * NAMES, and how an entry's BYTES are read ({@link readZipEntry}) — the two
15
+ * things decidable from the archive alone. Whether a target sits behind a
16
+ * symbolic link already on disk, whether the caller may write there, and what
17
+ * is already at the path are facts about a workspace, so each surface asks
18
+ * those where its own writes land.
19
+ */
20
+
21
+ /**
22
+ * The entries an archive from macOS carries that nobody asked for: the
23
+ * resource-fork sidecar tree and the Finder's own index. SILENTLY dropped
24
+ * rather than reported — they are not the caller's content and a list of
25
+ * refusals about them says nothing.
26
+ */
27
+ export function isZipNoiseEntry(rawName: string): boolean {
28
+ return (
29
+ rawName.startsWith('__MACOSX/') ||
30
+ rawName === '__MACOSX' ||
31
+ rawName.endsWith('/.DS_Store') ||
32
+ rawName === '.DS_Store' ||
33
+ /(^|\/)\._/.test(rawName)
34
+ );
35
+ }
36
+
37
+ /**
38
+ * An entry's name with separators in the one spelling the rules read. A zip
39
+ * written on Windows may use `\`, which every check below (and every path
40
+ * built from the result) would otherwise read as part of a single segment.
41
+ */
42
+ export function zipEntryName(entryName: string): string {
43
+ return entryName.replace(/\\/g, '/');
44
+ }
45
+
46
+ /** The path segments `rawName` names, with a trailing slash and empty parts dropped. */
47
+ export function zipEntrySegments(rawName: string): string[] {
48
+ return rawName
49
+ .replace(/\/+$/, '')
50
+ .split('/')
51
+ .filter((s) => s.length > 0);
52
+ }
53
+
54
+ /**
55
+ * Why `rawName` may not be landed at all — the reason a caller reports beside
56
+ * the entry — or null when the name is one a workspace path can be built from.
57
+ *
58
+ * Three rules, in the order that makes each refusal say the most useful thing:
59
+ * a path that climbs out or is anchored at the root is invalid whatever its
60
+ * segments are; the git folder is refused in every spelling, because an
61
+ * archive must not be a way to write what git reads as its own metadata; and
62
+ * then each segment has to be a name a filesystem on any of the three
63
+ * operating systems keeps intact (`validateFilename`).
64
+ */
65
+ export function zipEntryNameRefusal(rawName: string): string | null {
66
+ if (!rawName || rawName.startsWith('/') || /(^|\/)\.\.($|\/)/.test(rawName)) return 'Invalid path';
67
+ if (hasGitInternalsSegment(rawName)) return new GitInternalsError().message;
68
+ for (const segment of zipEntrySegments(rawName)) {
69
+ const reason = validateFilename(segment);
70
+ if (reason) return reason;
71
+ }
72
+ return null;
73
+ }
74
+
75
+ /**
76
+ * Whether a zip entry is a symbolic LINK rather than a file or a folder.
77
+ *
78
+ * A zip stores a link as an ordinary member whose bytes are the link's target
79
+ * text and whose unix mode (the high half of the external attributes) carries
80
+ * `S_IFLNK`. A reader that ignores the mode writes the target text out as a
81
+ * regular file — content nobody sent, under a name that was meant to point
82
+ * somewhere. `apply_file_upload` refuses such an entry outright; the entry is
83
+ * not a file, so there are no bytes of the caller's to land.
84
+ */
85
+ export function isSymlinkZipEntry(entry: {
86
+ header?: { attr?: number };
87
+ attr?: number;
88
+ }): boolean {
89
+ const attr = entry.header?.attr ?? entry.attr ?? 0;
90
+ if (!Number.isFinite(attr) || attr <= 0) return false;
91
+ // The external attributes' high 16 bits are the unix mode when the archive
92
+ // was written on a unix host; `S_IFMT & mode === S_IFLNK` is the link bit.
93
+ return ((attr >>> 16) & 0o170000) === 0o120000;
94
+ }
95
+
96
+ /** A zip's compression method for DEFLATE, the only one that can expand. */
97
+ const ZIP_METHOD_DEFLATED = 8;
98
+
99
+ /** What {@link readZipEntry} needs of an entry — the part of adm-zip's it reads. */
100
+ export interface ReadableZipEntry {
101
+ header: { size: number; compressedSize: number; method: number };
102
+ getData(): Buffer;
103
+ getCompressedData(): Buffer;
104
+ }
105
+
106
+ /** An entry's bytes, or why they were not read. */
107
+ export type ZipEntryRead =
108
+ | { ok: true; data: Buffer }
109
+ /** The entry is, or would expand to, more than the caller's budget allows. */
110
+ | { ok: false; reason: 'too_large' }
111
+ /** The entry cannot be read as what its header says it is. `detail` says how. */
112
+ | { ok: false; reason: 'unreadable'; detail: string };
113
+
114
+ /**
115
+ * Read one entry's bytes, inflating NO MORE than `budget` of them.
116
+ *
117
+ * The one read both surfaces use, because the bound is the whole point and it
118
+ * has a hole when each surface writes it itself. An entry's header DECLARES its
119
+ * uncompressed size, and the reader caps the inflation at that — but only when
120
+ * the size it declares is above zero. An entry that declares zero is inflated
121
+ * with no cap at all, so "check the declared size against the budget, then
122
+ * read" passes a 20 KB archive that expands to 20 MB, and a 50 MB one that
123
+ * expands to tens of gigabytes in a single call, before any check on the bytes
124
+ * that arrived has run. A thousandfold is what deflate does to a run of one
125
+ * byte; the header saying "empty" was the only thing standing in front of it.
126
+ *
127
+ * So the declared size is never the only bound:
128
+ *
129
+ * - an entry declaring more than `budget` is refused unread;
130
+ * - a DEFLATED entry declaring ZERO with a stream of its own is inflated here,
131
+ * capped at a single byte. An empty file compressed with deflate is exactly
132
+ * this shape (a two-byte stream that inflates to nothing) and is read as the
133
+ * empty file it is; anything that inflates to a byte or more contradicts its
134
+ * own header and is refused;
135
+ * - every other entry is read by the archive reader, which caps the inflation
136
+ * at the declared size this function has just held against the budget, and
137
+ * the bytes that arrive are measured again.
138
+ *
139
+ * A read that throws — a failed checksum, a stream longer than it declared, an
140
+ * unknown method — is that entry's refusal, not the whole archive's: one bad
141
+ * member must not cost the caller the others.
142
+ */
143
+ export function readZipEntry(entry: ReadableZipEntry, budget: number): ZipEntryRead {
144
+ const { size: declared, compressedSize, method } = entry.header;
145
+ if (declared > budget) return { ok: false, reason: 'too_large' };
146
+ if (declared === 0 && method === ZIP_METHOD_DEFLATED && compressedSize > 0) {
147
+ let inflated: Buffer;
148
+ try {
149
+ inflated = inflateRawSync(entry.getCompressedData(), { maxOutputLength: 1 });
150
+ } catch (err) {
151
+ // Past the one-byte cap, or not a deflate stream at all: either way it
152
+ // is not the empty file its header says it is.
153
+ return { ok: false, reason: 'unreadable', detail: declaresEmptyButIsNot(err) };
154
+ }
155
+ if (inflated.byteLength > 0) return { ok: false, reason: 'unreadable', detail: declaresEmptyButIsNot() };
156
+ return { ok: true, data: inflated };
157
+ }
158
+ let data: Buffer;
159
+ try {
160
+ data = entry.getData();
161
+ } catch (err) {
162
+ return { ok: false, reason: 'unreadable', detail: err instanceof Error ? err.message : String(err) };
163
+ }
164
+ if (data.byteLength > budget) return { ok: false, reason: 'too_large' };
165
+ return { ok: true, data };
166
+ }
167
+
168
+ function declaresEmptyButIsNot(err?: unknown): string {
169
+ const outputLimit = (err as { code?: string } | undefined)?.code === 'ERR_BUFFER_TOO_LARGE';
170
+ return err === undefined || outputLimit
171
+ ? 'its header declares an empty file, but it holds content'
172
+ : `its header declares an empty file, and its content could not be read (${err instanceof Error ? err.message : String(err)})`;
173
+ }
@@ -0,0 +1,217 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { PgDialect, pgTable, uuid } from 'drizzle-orm/pg-core';
4
+ import { eq, inArray } from 'drizzle-orm';
5
+ import {
6
+ IndexOnWrite,
7
+ PII_CIPHERTEXT_PREFIX,
8
+ PII_SEALED_SHAPE_SQL_REGEX,
9
+ SealOnWrite,
10
+ blindIndexText,
11
+ derivePiiKeys,
12
+ encryptedText,
13
+ isEncryptedBlob,
14
+ } from '../column-crypto.js';
15
+ import { TokenCrypto } from '../token-crypto.js';
16
+
17
+ const KEY = randomBytes(32).toString('base64');
18
+ const keys = derivePiiKeys(KEY);
19
+ const otherKeys = derivePiiKeys(randomBytes(32).toString('base64'));
20
+
21
+ describe('derivePiiKeys: seal / open / read', () => {
22
+ it('round-trips a value through ciphertext', () => {
23
+ const sealed = keys.seal('razvan@bevel.software');
24
+ expect(sealed).not.toContain('razvan');
25
+ expect(sealed.startsWith(PII_CIPHERTEXT_PREFIX)).toBe(true);
26
+ expect(isEncryptedBlob(sealed)).toBe(true);
27
+ expect(keys.read(sealed)).toBe('razvan@bevel.software');
28
+ });
29
+
30
+ it('stores the empty string as itself (no unparseable empty-ciphertext blob)', () => {
31
+ expect(keys.seal('')).toBe('');
32
+ expect(keys.read('')).toBe('');
33
+ expect(isEncryptedBlob('')).toBe(false);
34
+ });
35
+
36
+ it('is randomized — the same plaintext never encrypts to the same blob', () => {
37
+ expect(keys.seal('alice')).not.toBe(keys.seal('alice'));
38
+ });
39
+
40
+ it('passes legacy plaintext through unchanged (pre-backfill rows)', () => {
41
+ expect(keys.read('plain old email@example.com')).toBe('plain old email@example.com');
42
+ });
43
+
44
+ it('passes through plaintext that merely resembles ciphertext', () => {
45
+ // Blob-shaped but unprefixed (the legacy TokenCrypto shape) → plaintext.
46
+ const shapeOnly = new TokenCrypto(KEY).encrypt('not-a-pii-blob');
47
+ expect(isEncryptedBlob(shapeOnly)).toBe(false);
48
+ expect(keys.read(shapeOnly)).toBe(shapeOnly);
49
+ // Prefixed but malformed → still not a blob.
50
+ const impostor = `${PII_CIPHERTEXT_PREFIX}abc:def:ghi`;
51
+ expect(isEncryptedBlob(impostor)).toBe(false);
52
+ expect(keys.read(impostor)).toBe(impostor);
53
+ });
54
+
55
+ it('the SQL shape regex agrees with isEncryptedBlob on what a sealed value is', () => {
56
+ // The backfill trusts rows matching this regex as sealed and skips them;
57
+ // the app-side check is the authority. Pinned together here so a change
58
+ // to the prefix, IV or tag width in one place fails this test.
59
+ const regex = new RegExp(PII_SEALED_SHAPE_SQL_REGEX);
60
+ for (const plain of ['a@b.co', 'razvan@bevel.software', 'x'.repeat(500)]) {
61
+ const sealed = keys.seal(plain);
62
+ expect(isEncryptedBlob(sealed)).toBe(true);
63
+ expect(regex.test(sealed)).toBe(true);
64
+ }
65
+ // The same blob with its padding spelled otherwise decodes to the same
66
+ // bytes, and the two predicates used to disagree about it: the database
67
+ // called it unsealed and selected it, this process called it sealed and
68
+ // skipped it, on every start. One answer, from one pattern.
69
+ const [iv, tag, ct] = keys.seal('a@b.co').slice(PII_CIPHERTEXT_PREFIX.length).split(':') as [string, string, string];
70
+ const respelled = [
71
+ `${PII_CIPHERTEXT_PREFIX}${iv}:${tag.replace(/=+$/, '')}:${ct}`,
72
+ `${PII_CIPHERTEXT_PREFIX}${iv}==:${tag}:${ct}`,
73
+ `${PII_CIPHERTEXT_PREFIX}${iv}:${tag}:${ct}\n`,
74
+ ];
75
+ for (const unsealed of [
76
+ 'a@b.co',
77
+ '',
78
+ `${PII_CIPHERTEXT_PREFIX}abc:def:ghi`,
79
+ new TokenCrypto(KEY).encrypt('x'),
80
+ ...respelled,
81
+ ]) {
82
+ expect(isEncryptedBlob(unsealed), JSON.stringify(unsealed)).toBe(false);
83
+ expect(regex.test(unsealed), JSON.stringify(unsealed)).toBe(false);
84
+ }
85
+ });
86
+
87
+ it("another key cannot open it: the lenient read hands the blob back, open says so", () => {
88
+ const sealed = keys.seal('secret-person@example.com');
89
+ expect(otherKeys.read(sealed)).toBe(sealed);
90
+ expect(otherKeys.open(sealed)).toEqual({ ok: false });
91
+ expect(keys.open(sealed)).toEqual({ ok: true, plain: 'secret-person@example.com' });
92
+ });
93
+
94
+ it('open tells a blob the key does not open from a plaintext shaped like one', () => {
95
+ // A value whose PLAINTEXT is itself a well-formed blob: opened correctly,
96
+ // the result still looks sealed. Only the explicit outcome tells the two
97
+ // apart — the shape of what the lenient read returns cannot.
98
+ const inner = keys.seal('inner@example.com');
99
+ const outer = keys.seal(inner);
100
+ expect(keys.open(outer)).toEqual({ ok: true, plain: inner });
101
+ expect(keys.open('plain@example.com')).toEqual({ ok: true, plain: 'plain@example.com' });
102
+ expect(otherKeys.open(outer)).toEqual({ ok: false });
103
+ });
104
+
105
+ it('domain-separates from the raw secrets key via HKDF', () => {
106
+ // The column key is DERIVED from KEY — a TokenCrypto built from the raw
107
+ // KEY itself must not be able to open a PII blob's body.
108
+ const body = keys.seal('secret-person@example.com').slice(PII_CIPHERTEXT_PREFIX.length);
109
+ expect(() => new TokenCrypto(KEY).decrypt(body)).toThrow();
110
+ });
111
+
112
+ it('refuses a key that is not 32 bytes', () => {
113
+ expect(() => derivePiiKeys('too-short')).toThrow();
114
+ });
115
+
116
+ /**
117
+ * Node's base64 decoder is forgiving in ways a key must not be. Every value
118
+ * below DECODES TO 32 BYTES, so the length check passes each of them, and
119
+ * none of them is a way those 32 bytes are written: a mistyped key that
120
+ * became another key, sealing data the value an operator wrote down will
121
+ * never open. The property is one, whatever the mistake was — what is
122
+ * written must be a spelling of what it decodes to.
123
+ */
124
+ it('refuses whatever decodes to 32 bytes without being a spelling of them', () => {
125
+ const unpadded = KEY.replace(/=+$/, '');
126
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
127
+ // The last character of 32 bytes carries four bits of the key and two
128
+ // that must be zero. Its neighbour in the alphabet sets one of those two.
129
+ const trailingBits = unpadded.slice(0, -1) + alphabet[alphabet.indexOf(unpadded.slice(-1)) + 1];
130
+ const mistakes = {
131
+ 'a character the alphabet does not have': `${KEY.slice(0, 10)}$${KEY.slice(10)}`,
132
+ 'a space in the middle': `${KEY.slice(0, 20)} ${KEY.slice(20)}`,
133
+ 'more padding than its length takes': `${unpadded}==`,
134
+ 'bits its last character should not carry': trailingBits,
135
+ };
136
+ for (const [mistake, written] of Object.entries(mistakes)) {
137
+ // The premise: only the round trip can tell this from a key.
138
+ expect(Buffer.from(written, 'base64'), mistake).toHaveLength(32);
139
+ expect(() => derivePiiKeys(written), mistake).toThrow(/SECRETS_ENC_KEY is not a clean hex or base64 spelling/);
140
+ }
141
+ // Padding in the MIDDLE ends the decoding there, so that one is short and
142
+ // the length check has always refused it.
143
+ expect(() => derivePiiKeys(`${unpadded.slice(0, 20)}=${unpadded.slice(20)}`)).toThrow(/must decode to 32 bytes/);
144
+ });
145
+
146
+ it('takes one key in any of its spellings: hex, base64, url-safe, unpadded, with whitespace around it', () => {
147
+ const raw = Buffer.from(KEY, 'base64');
148
+ const index = keys.index('a@b.co');
149
+ for (const spelled of [
150
+ raw.toString('hex'),
151
+ raw.toString('hex').toUpperCase(),
152
+ raw.toString('base64url'),
153
+ `${raw.toString('base64url')}=`,
154
+ KEY.replace(/=+$/, ''),
155
+ ` ${KEY}\n`,
156
+ ]) {
157
+ expect(derivePiiKeys(spelled).index('a@b.co'), spelled).toBe(index);
158
+ }
159
+ });
160
+ });
161
+
162
+ describe('derivePiiKeys: index', () => {
163
+ it('is deterministic and case/whitespace-insensitive', () => {
164
+ expect(keys.index('Alice@Example.com ')).toBe(keys.index('alice@example.com'));
165
+ expect(keys.index('alice@example.com')).toMatch(/^[0-9a-f]{64}$/);
166
+ });
167
+
168
+ it('differs across values', () => {
169
+ expect(keys.index('a@example.com')).not.toBe(keys.index('b@example.com'));
170
+ });
171
+
172
+ it('differs across keys, so one tenant’s index says nothing about another’s', () => {
173
+ expect(otherKeys.index('a@example.com')).not.toBe(keys.index('a@example.com'));
174
+ });
175
+ });
176
+
177
+ /**
178
+ * The column types hold no key: what they hand the driver is a mark for the
179
+ * database handle's connection to replace. Pinned through drizzle itself —
180
+ * the statement a service writes, rendered — because that is where the mark
181
+ * has to survive to.
182
+ */
183
+ describe('the column types mark values for the handle', () => {
184
+ const people = pgTable('people', {
185
+ id: uuid('id').primaryKey(),
186
+ email: encryptedText('email').notNull(),
187
+ emailBidx: blindIndexText('email_bidx').notNull(),
188
+ });
189
+ const paramsOf = (clause: unknown) => new PgDialect().sqlToQuery(clause as never).params;
190
+
191
+ it('a comparison on an index column binds the address, marked to be indexed', () => {
192
+ const [bound] = paramsOf(eq(people.emailBidx, 'Ada@Example.com'));
193
+ expect(bound).toBeInstanceOf(IndexOnWrite);
194
+ expect((bound as IndexOnWrite).stored(keys)).toBe(keys.index('ada@example.com'));
195
+ expect(paramsOf(inArray(people.emailBidx, ['a@x.co', 'b@x.co'])).every((p) => p instanceof IndexOnWrite)).toBe(true);
196
+ });
197
+
198
+ it('a value for an encrypted column is marked to be sealed; the empty string is stored as it is', () => {
199
+ const [bound] = paramsOf(eq(people.email, 'Ada@Example.com'));
200
+ expect(bound).toBeInstanceOf(SealOnWrite);
201
+ expect(keys.read((bound as SealOnWrite).stored(keys))).toBe('Ada@Example.com');
202
+ expect(paramsOf(eq(people.email, ''))).toEqual(['']);
203
+ });
204
+
205
+ it('a mark that reaches a connection holding no key refuses to be written', () => {
206
+ // `pg` serialises an object parameter through its `toPostgres`. Anything
207
+ // else here — JSON of the object, say — would store the plaintext.
208
+ const [bound] = paramsOf(eq(people.email, 'Ada@Example.com'));
209
+ expect(() => (bound as SealOnWrite).toPostgres()).toThrow(/holds no key/);
210
+ });
211
+
212
+ it('refuses a stored index written back into an index column', () => {
213
+ // Reading the column gives the stored index; writing that back would
214
+ // index the index and the row would answer to no address.
215
+ expect(() => paramsOf(eq(people.emailBidx, keys.index('ada@example.com')))).toThrow(/stored index/);
216
+ });
217
+ });
@@ -0,0 +1,218 @@
1
+ import { createHmac, hkdfSync } from 'node:crypto';
2
+ import { customType } from 'drizzle-orm/pg-core';
3
+ import { TokenCrypto, assertKeyDecodesTo32Bytes } from './token-crypto.js';
4
+
5
+ /**
6
+ * Application-layer encryption for PII columns. Personal data (emails, names,
7
+ * change-request text) is AES-256-GCM ciphertext in Postgres, so a leaked
8
+ * dump, an injected query, or a compromised DB credential yields no personal
9
+ * data — the key lives only in the app's environment. Disk-level encryption
10
+ * still carries the blanket at-rest claim (git refs, WAL, logs); this layer is
11
+ * the DB-specific control on top.
12
+ *
13
+ * THE KEY BELONGS TO THE DATABASE HANDLE, not to the process. A process that
14
+ * serves several knowledge bases holds one handle per tenant, each built with
15
+ * that tenant's own `SECRETS_ENC_KEY` (`createDb(url, { piiKey })`), so a
16
+ * tenant's rows are sealed under the same key as its stored credentials and
17
+ * its dump opens, whole, with that one key.
18
+ *
19
+ * A drizzle column type is a module-level object and is told nothing about
20
+ * the handle a statement runs on, so it cannot hold a key. It only MARKS a
21
+ * value ({@link SealOnWrite}, {@link IndexOnWrite}); the handle's own
22
+ * connection replaces the mark with ciphertext or a blind index on the way
23
+ * in, and opens every sealed value on the way out (see `connection.ts`). A
24
+ * mark that reaches a connection with no key refuses to be written.
25
+ *
26
+ * Both keys are HKDF-derived from the handle's key with distinct info
27
+ * strings, so PII ciphertext and blind indexes are domain-separated from the
28
+ * secrets-vault key without asking operators to provision a second variable.
29
+ */
30
+
31
+ /** What a database handle seals, opens and indexes personal data with. */
32
+ export interface PiiKeys {
33
+ /**
34
+ * Encrypt a value for storage (fresh random IV — NOT equality-comparable).
35
+ *
36
+ * The empty string is stored as itself: it carries no personal data, GCM of
37
+ * an empty plaintext would produce an empty ciphertext segment the blob
38
+ * parser cannot represent, and columns with a DB-level `DEFAULT ''` then
39
+ * hold exactly the same representation as an app-written empty value.
40
+ */
41
+ seal(plain: string): string;
42
+ /**
43
+ * Open a stored value, and SAY whether it opened: a value that is not a
44
+ * blob is its own plaintext; a blob this key does not open is `ok: false`.
45
+ * For the callers that must tell "the key does not open this" from a value
46
+ * — the shape of what {@link read} returns proves nothing, since a
47
+ * plaintext may itself be shaped like a blob.
48
+ */
49
+ open(value: string): { ok: true; plain: string } | { ok: false };
50
+ /**
51
+ * The lenient read every query result goes through: a blob this key does
52
+ * not open is handed back as it is, as is anything that is not a blob —
53
+ * rows written before the encryption release stay readable until the
54
+ * backfill at start rewrites them.
55
+ */
56
+ read(value: string): string;
57
+ /**
58
+ * Blind index for equality on an encrypted column: HMAC-SHA256 of the
59
+ * trimmed, lower-cased value, hex-encoded. Deterministic, so a `*_bidx`
60
+ * column can carry the unique constraints and lookups that randomized
61
+ * ciphertext cannot. Reveals only equality, never content.
62
+ */
63
+ index(value: string): string;
64
+ }
65
+
66
+ /** Derive the personal-data keys from a deployment's (or a tenant's) `SECRETS_ENC_KEY`. */
67
+ export function derivePiiKeys(secretsEncKey: string): PiiKeys {
68
+ const ikm = assertKeyDecodesTo32Bytes(secretsEncKey, 'SECRETS_ENC_KEY');
69
+ const columnKey = Buffer.from(hkdfSync('sha256', ikm, Buffer.alloc(0), 'bevel-pii-column-v1', 32));
70
+ const bidxKey = Buffer.from(hkdfSync('sha256', ikm, Buffer.alloc(0), 'bevel-pii-bidx-v1', 32));
71
+ const crypto = new TokenCrypto(columnKey.toString('base64'));
72
+ const open: PiiKeys['open'] = (value) => {
73
+ if (!isEncryptedBlob(value)) return { ok: true, plain: value };
74
+ try {
75
+ return { ok: true, plain: crypto.decrypt(value.slice(PII_CIPHERTEXT_PREFIX.length)) };
76
+ } catch {
77
+ return { ok: false };
78
+ }
79
+ };
80
+ return {
81
+ seal: (plain) => (plain === '' ? '' : PII_CIPHERTEXT_PREFIX + crypto.encrypt(plain)),
82
+ open,
83
+ read: (value) => {
84
+ const opened = open(value);
85
+ return opened.ok ? opened.plain : value;
86
+ },
87
+ index: (value) => createHmac('sha256', bidxKey).update(value.trim().toLowerCase()).digest('hex'),
88
+ };
89
+ }
90
+
91
+ /**
92
+ * Every PII ciphertext starts with this marker. An explicit prefix — rather
93
+ * than recognising ciphertext by its `iv:tag:ct` shape — means legacy
94
+ * plaintext can never be mistaken for ciphertext (and silently skipped by the
95
+ * backfill), and lets the backfill find unsealed rows with a plain SQL
96
+ * predicate instead of scanning every row in the app. Bump the version
97
+ * segment if the format ever changes.
98
+ */
99
+ export const PII_CIPHERTEXT_PREFIX = 'pii:v1:';
100
+
101
+ /**
102
+ * The shape of a PII ciphertext blob, as ONE pattern both Postgres and this
103
+ * process read: the version prefix followed by base64 segments of the exact
104
+ * widths GCM produces (12-byte IV → 16 chars, 16-byte tag → 22 chars + `==`).
105
+ * Lets the backfill find unsealed rows with a `!~` predicate instead of
106
+ * scanning every row in the app.
107
+ *
108
+ * {@link isEncryptedBlob} is built FROM it rather than written beside it. The
109
+ * two used to be separate spellings of one idea, and they disagreed: the
110
+ * JavaScript one decoded each part and so took an unpadded tag for a 16-byte
111
+ * one, which this pattern does not. A value the two disagreed about was
112
+ * selected by the backfill's SQL as unsealed and then skipped by its
113
+ * JavaScript as sealed, on every start, and stayed in clear for good. The
114
+ * pattern uses nothing POSIX and JavaScript read differently.
115
+ */
116
+ export const PII_SEALED_SHAPE_SQL_REGEX = `^${PII_CIPHERTEXT_PREFIX}[A-Za-z0-9+/]{16}:[A-Za-z0-9+/]{22}==:[A-Za-z0-9+/]+={0,2}$`;
117
+
118
+ const PII_SEALED_SHAPE = new RegExp(PII_SEALED_SHAPE_SQL_REGEX);
119
+
120
+ /**
121
+ * Whether `value` has the shape of a PII ciphertext blob — exactly the values
122
+ * {@link PII_SEALED_SHAPE_SQL_REGEX} matches in the database, no more and no
123
+ * fewer. Shape only: whether the configured key OPENS it is `PiiKeys.open`'s
124
+ * answer, and a plaintext somebody typed in this shape passes here.
125
+ */
126
+ export function isEncryptedBlob(value: string): boolean {
127
+ return PII_SEALED_SHAPE.test(value);
128
+ }
129
+
130
+ /**
131
+ * A value on its way to the database that the handle's connection still has
132
+ * to turn into what is stored. It is never a storable value itself: `pg`
133
+ * asks an object how to serialise itself through `toPostgres`, and this one
134
+ * refuses, so a statement that reaches a connection which did not replace it
135
+ * — a pool built without `createDb`, or a handle built without a key — fails
136
+ * instead of writing the plaintext.
137
+ */
138
+ export abstract class PiiParam {
139
+ constructor(readonly plain: string) {}
140
+
141
+ /** What the handle's keys make of it. */
142
+ abstract stored(keys: PiiKeys): string;
143
+
144
+ toPostgres(): never {
145
+ throw new Error(
146
+ 'A personal-data value reached a database connection that holds no key for it. ' +
147
+ 'Build the handle with createDb/getDb and its piiKey (createCoreServices does).',
148
+ );
149
+ }
150
+ }
151
+
152
+ /** Plaintext of an {@link encryptedText} column: stored as ciphertext. */
153
+ export class SealOnWrite extends PiiParam {
154
+ stored(keys: PiiKeys): string {
155
+ return keys.seal(this.plain);
156
+ }
157
+ }
158
+
159
+ /** The address a {@link blindIndexText} column is written or compared with: stored as its blind index. */
160
+ export class IndexOnWrite extends PiiParam {
161
+ stored(keys: PiiKeys): string {
162
+ return keys.index(this.plain);
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Drizzle column type for encrypted PII text: services read and write
168
+ * plaintext, the database only ever sees ciphertext. NEVER use an
169
+ * `encryptedText` column in a WHERE clause or conflict target — the fresh IV
170
+ * per write means `eq(column, plaintext)` silently matches nothing. Equality
171
+ * goes through the column's `*_bidx` companion ({@link blindIndexText}).
172
+ */
173
+ export const encryptedText = customType<{ data: string; driverData: string }>({
174
+ dataType() {
175
+ return 'text';
176
+ },
177
+ toDriver(value: string): string {
178
+ // The mark, typed as the text it becomes on the handle's connection.
179
+ return (value === '' ? '' : new SealOnWrite(value)) as string;
180
+ },
181
+ fromDriver(value: string): string {
182
+ // Already opened: the handle's connection opens every sealed value of a
183
+ // result before drizzle maps it.
184
+ return value;
185
+ },
186
+ });
187
+
188
+ const STORED_INDEX = /^[0-9a-f]{64}$/;
189
+
190
+ /**
191
+ * Drizzle column type for the blind index beside an encrypted column. WRITE
192
+ * AND COMPARE IT WITH THE VALUE ITSELF — `emailBidx: email`,
193
+ * `eq(users.emailBidx, email)`, `inArray(users.emailBidx, emails)` — and the
194
+ * handle's connection stores or binds its index. Reading the column gives the
195
+ * stored index, which is good for nothing but SQL: writing it back would
196
+ * index the index, so that is refused. A row copied from another carries the
197
+ * value its index was made from, not the index.
198
+ *
199
+ * Only through drizzle's operators, which bind through the column: a value
200
+ * interpolated into a raw `sql` template is compared as it is and matches
201
+ * nothing.
202
+ */
203
+ export const blindIndexText = customType<{ data: string; driverData: string }>({
204
+ dataType() {
205
+ return 'text';
206
+ },
207
+ toDriver(value: string): string {
208
+ if (STORED_INDEX.test(value)) {
209
+ throw new Error(
210
+ 'A blind-index column was written with a stored index. Write it with the value the index is of (the address).',
211
+ );
212
+ }
213
+ return new IndexOnWrite(value) as unknown as string;
214
+ },
215
+ fromDriver(value: string): string {
216
+ return value;
217
+ },
218
+ });
@@ -61,12 +61,39 @@ function decodeKey(raw: string): Buffer {
61
61
  * is then safe, because a bad key never gets that far.
62
62
  */
63
63
  export function assertKeyDecodesTo32Bytes(rawKey: string, envVarName: string): Buffer {
64
- const key = decodeKey(rawKey);
64
+ // Whitespace around it is the environment's, not the key's.
65
+ const written = rawKey.trim();
66
+ const key = decodeKey(written);
65
67
  if (key.length !== 32) {
66
68
  throw new Error(
67
69
  `${envVarName} must decode to 32 bytes (got ${key.length}). ` +
68
70
  'Generate one with: `node -e "console.log(require(\'crypto\').randomBytes(32).toString(\'base64\'))"`.',
69
71
  );
70
72
  }
73
+ // WHAT IS WRITTEN MUST BE A SPELLING OF WHAT IT DECODES TO. Node's decoder is
74
+ // forgiving in ways a key must not be: it skips a character it does not know,
75
+ // it stops at padding wherever padding stands, and it ignores bits a final
76
+ // character should not carry. Each of those turns a mistyped key into 32
77
+ // bytes — a DIFFERENT key, sealing data that the value an operator wrote
78
+ // down will never open. Asking which characters and which padding are
79
+ // acceptable is a list that is always one case short, so the question is put
80
+ // the other way round: encode the bytes again, and accept the value only
81
+ // when it is one of the ways those bytes are written.
82
+ if (!spellingsOf(key).includes(/^[0-9a-fA-F]{64}$/.test(written) ? written.toLowerCase() : written)) {
83
+ throw new Error(
84
+ `${envVarName} is not a clean hex or base64 spelling of a 32-byte key: it holds a character, a padding ` +
85
+ 'or trailing bits the encoding does not have, which the decoder skipped. The key in use so far is what ' +
86
+ 'it decoded to; print that key spelled properly with ' +
87
+ `\`node -e "console.log(Buffer.from(process.env.${envVarName}, 'base64').toString('base64'))"\` and set that.`,
88
+ );
89
+ }
71
90
  return key;
72
91
  }
92
+
93
+ /** Every way 32 bytes are written as a key: hex, and base64 in either alphabet, padded or not. */
94
+ function spellingsOf(key: Buffer): string[] {
95
+ const standard = key.toString('base64');
96
+ const urlSafe = key.toString('base64url');
97
+ const padding = standard.slice(standard.replace(/=+$/, '').length);
98
+ return [key.toString('hex'), standard, standard.replace(/=+$/, ''), urlSafe, urlSafe + padding];
99
+ }
@@ -27,6 +27,10 @@ describe('tenantConfigFrom', () => {
27
27
  expect(config.workspacesRoot).toBe(path.resolve('/srv/hexis/workspaces/acme-2'));
28
28
  expect(config.backupsRoot).toBe(path.resolve('/srv/hexis/backups/acme-2'));
29
29
  expect(config.spillRoot).toBe(path.resolve('/srv/hexis/tool-chain-spills/acme-2'));
30
+ // Per tenant like the rest: a shared staging root would let one tenant's
31
+ // upload sweep delete another's bytes, and both would be writing ids into
32
+ // one directory.
33
+ expect(config.agentUploadsRoot).toBe(path.resolve('/srv/hexis/agent-uploads/acme-2'));
30
34
  expect(config.docExtractCacheRoot).toBe(path.resolve('/srv/hexis/doc-extract-cache/acme-2'));
31
35
  expect(config.loopbackBaseUrl).toBe('http://127.0.0.1:3001/_tenant/acme-2');
32
36
  });