@rfc0/patty 0.0.0-stage → 1.0.2

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 (465) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +214 -2
  3. package/dist/adapters/access-tokens.js +7 -0
  4. package/dist/adapters/accounts.js +37 -0
  5. package/dist/adapters/auth.js +11 -0
  6. package/dist/adapters/bills.js +32 -0
  7. package/dist/adapters/budgets.js +29 -0
  8. package/dist/adapters/categories.js +32 -0
  9. package/dist/adapters/client-grants.js +7 -0
  10. package/dist/adapters/credit-cards.js +33 -0
  11. package/dist/adapters/currencies.js +2 -0
  12. package/dist/adapters/currency-rates.js +18 -0
  13. package/dist/adapters/dashboards.js +43 -0
  14. package/dist/adapters/demo.js +13 -0
  15. package/dist/adapters/instance-settings.js +7 -0
  16. package/dist/adapters/invites.js +7 -0
  17. package/dist/adapters/recurring.js +55 -0
  18. package/dist/adapters/sessions.js +7 -0
  19. package/dist/adapters/settings.js +4 -0
  20. package/dist/adapters/setup-codes.js +7 -0
  21. package/dist/adapters/tags.js +9 -0
  22. package/dist/adapters/transactions.js +95 -0
  23. package/dist/adapters/users.js +7 -0
  24. package/dist/common/build-version.js +5 -0
  25. package/dist/common/errors.js +118 -0
  26. package/dist/common/net.js +71 -0
  27. package/dist/common/result.js +7 -0
  28. package/dist/composition/auth.js +106 -0
  29. package/dist/composition/boot.js +27 -0
  30. package/dist/composition/cli.js +86 -0
  31. package/dist/composition/demo/seed.js +92 -0
  32. package/dist/composition/demo/shell.js +107 -0
  33. package/dist/composition/export.js +89 -0
  34. package/dist/composition/http.js +110 -0
  35. package/dist/composition/import.js +55 -0
  36. package/dist/composition/lazy-modules.js +2 -0
  37. package/dist/composition/runtime.js +115 -0
  38. package/dist/composition/sign-in/interpreter.js +154 -0
  39. package/dist/composition/sign-in/server.js +36 -0
  40. package/dist/composition/sign-in/wiring.js +23 -0
  41. package/dist/composition/stdio.js +69 -0
  42. package/dist/config.js +136 -0
  43. package/dist/controllers/account/account.js +88 -0
  44. package/dist/controllers/account/transaction.js +119 -0
  45. package/dist/controllers/account/transfer.js +34 -0
  46. package/dist/controllers/aggregate.js +40 -0
  47. package/dist/controllers/auth/access-tokens.js +61 -0
  48. package/dist/controllers/auth/grants.js +136 -0
  49. package/dist/controllers/auth/key-export.js +20 -0
  50. package/dist/controllers/auth/owner.js +80 -0
  51. package/dist/controllers/auth/password.js +35 -0
  52. package/dist/controllers/auth/session.js +50 -0
  53. package/dist/controllers/auth/step-up.js +8 -0
  54. package/dist/controllers/auth/users.js +183 -0
  55. package/dist/controllers/budgets.js +87 -0
  56. package/dist/controllers/categories.js +67 -0
  57. package/dist/controllers/correlations.js +112 -0
  58. package/dist/controllers/credit-card/bill.js +105 -0
  59. package/dist/controllers/credit-card/credit-card.js +129 -0
  60. package/dist/controllers/credit-card/transaction.js +181 -0
  61. package/dist/controllers/currencies.js +1 -0
  62. package/dist/controllers/currency-rates.js +40 -0
  63. package/dist/controllers/dashboards.js +68 -0
  64. package/dist/controllers/demo/seed.js +31 -0
  65. package/dist/controllers/demo/tour.js +12 -0
  66. package/dist/controllers/deps.js +6 -0
  67. package/dist/controllers/instance.js +6 -0
  68. package/dist/controllers/merchants.js +12 -0
  69. package/dist/controllers/recurring.js +70 -0
  70. package/dist/controllers/resolve.js +37 -0
  71. package/dist/controllers/settings.js +47 -0
  72. package/dist/controllers/status.js +19 -0
  73. package/dist/controllers/summary.js +21 -0
  74. package/dist/controllers/tags.js +19 -0
  75. package/dist/controllers/transaction/bulk.js +6 -0
  76. package/dist/controllers/transaction/core.js +49 -0
  77. package/dist/controllers/transaction/read.js +28 -0
  78. package/dist/diplomat/auth/credentials.js +58 -0
  79. package/dist/diplomat/auth/sign-in-store.js +18 -0
  80. package/dist/diplomat/cli/commands/auth.js +100 -0
  81. package/dist/diplomat/cli/commands/db.js +72 -0
  82. package/dist/diplomat/cli/commands/demo.js +68 -0
  83. package/dist/diplomat/cli/commands/key.js +119 -0
  84. package/dist/diplomat/cli/commands/login.js +151 -0
  85. package/dist/diplomat/cli/commands/setup.js +132 -0
  86. package/dist/diplomat/cli/commands/users.js +123 -0
  87. package/dist/diplomat/cli/commands.js +61 -0
  88. package/dist/diplomat/cli/export-file.js +37 -0
  89. package/dist/diplomat/cli/import-file.js +44 -0
  90. package/dist/diplomat/cli/io.js +61 -0
  91. package/dist/diplomat/cli/key-export-approval.js +37 -0
  92. package/dist/diplomat/cli/messages.js +96 -0
  93. package/dist/diplomat/cli/prompt.js +74 -0
  94. package/dist/diplomat/cli/terminal.js +81 -0
  95. package/dist/diplomat/client-config/clients.js +150 -0
  96. package/dist/diplomat/client-config/merge.js +41 -0
  97. package/dist/diplomat/db/bootstrap.js +98 -0
  98. package/dist/diplomat/db/database-files.js +147 -0
  99. package/dist/diplomat/db/driver.js +167 -0
  100. package/dist/diplomat/db/effects.js +101 -0
  101. package/dist/diplomat/db/engine.js +9 -0
  102. package/dist/diplomat/db/export.js +22 -0
  103. package/dist/diplomat/db/file-lock.js +82 -0
  104. package/dist/diplomat/db/key-lock.js +14 -0
  105. package/dist/diplomat/db/locale-cache.js +23 -0
  106. package/dist/diplomat/db/migration-barrier.js +57 -0
  107. package/dist/diplomat/db/migration-journal.js +18 -0
  108. package/dist/diplomat/db/migration-lock.js +15 -0
  109. package/dist/diplomat/db/migrations.js +11 -0
  110. package/dist/diplomat/db/present.js +17 -0
  111. package/dist/diplomat/db/queries/aggregate-whitelist.js +35 -0
  112. package/dist/diplomat/db/queries/filters.js +59 -0
  113. package/dist/diplomat/db/queries/fts.js +18 -0
  114. package/dist/diplomat/db/queries/scope.js +8 -0
  115. package/dist/diplomat/db/queries/transaction-select.js +26 -0
  116. package/dist/diplomat/db/queries/tx-predicates.js +13 -0
  117. package/dist/diplomat/db/repos/access-tokens.js +27 -0
  118. package/dist/diplomat/db/repos/accounts.js +91 -0
  119. package/dist/diplomat/db/repos/bills.js +93 -0
  120. package/dist/diplomat/db/repos/budgets.js +72 -0
  121. package/dist/diplomat/db/repos/categories.js +53 -0
  122. package/dist/diplomat/db/repos/client-grants.js +67 -0
  123. package/dist/diplomat/db/repos/correlations.js +66 -0
  124. package/dist/diplomat/db/repos/credit-cards.js +67 -0
  125. package/dist/diplomat/db/repos/currencies.js +8 -0
  126. package/dist/diplomat/db/repos/currency-rates.js +40 -0
  127. package/dist/diplomat/db/repos/dashboards.js +123 -0
  128. package/dist/diplomat/db/repos/health.js +12 -0
  129. package/dist/diplomat/db/repos/instance-settings.js +14 -0
  130. package/dist/diplomat/db/repos/instance.js +58 -0
  131. package/dist/diplomat/db/repos/invites.js +43 -0
  132. package/dist/diplomat/db/repos/merchants.js +121 -0
  133. package/dist/diplomat/db/repos/recurring.js +29 -0
  134. package/dist/diplomat/db/repos/sessions.js +19 -0
  135. package/dist/diplomat/db/repos/settings.js +41 -0
  136. package/dist/diplomat/db/repos/setup-codes.js +28 -0
  137. package/dist/diplomat/db/repos/sub-categories.js +67 -0
  138. package/dist/diplomat/db/repos/tags.js +51 -0
  139. package/dist/diplomat/db/repos/transaction-tags.js +57 -0
  140. package/dist/diplomat/db/repos/transactions.js +163 -0
  141. package/dist/diplomat/db/repos/users.js +47 -0
  142. package/dist/diplomat/db/safety-copy.js +87 -0
  143. package/dist/diplomat/db/schema.js +348 -0
  144. package/dist/diplomat/db/seed/categories.js +112 -0
  145. package/dist/diplomat/db/seed/currencies.js +9 -0
  146. package/dist/diplomat/db/seed/demo/br.js +98 -0
  147. package/dist/diplomat/db/seed/demo/co.js +89 -0
  148. package/dist/diplomat/db/seed/demo/index.js +12 -0
  149. package/dist/diplomat/db/seed/demo/mx.js +90 -0
  150. package/dist/diplomat/db/seed/demo/shared.js +39 -0
  151. package/dist/diplomat/db/seed/demo/us.js +90 -0
  152. package/dist/diplomat/db/seed/merchant-rules.js +188 -0
  153. package/dist/diplomat/db/sqlite-errors.js +40 -0
  154. package/dist/diplomat/db/tenancy-integrity.js +45 -0
  155. package/dist/diplomat/db/version-guard.js +16 -0
  156. package/dist/diplomat/http/auth-pages.js +41 -0
  157. package/dist/diplomat/http/auth-paths.js +46 -0
  158. package/dist/diplomat/http/bearer.js +15 -0
  159. package/dist/diplomat/http/connect-pages.js +51 -0
  160. package/dist/diplomat/http/context.js +17 -0
  161. package/dist/diplomat/http/cookies.js +27 -0
  162. package/dist/diplomat/http/form-pages.js +38 -0
  163. package/dist/diplomat/http/hooks/auth.js +106 -0
  164. package/dist/diplomat/http/hooks/demo-marker.js +59 -0
  165. package/dist/diplomat/http/openapi.js +73 -0
  166. package/dist/diplomat/http/principal.js +1 -0
  167. package/dist/diplomat/http/rate-limiter.js +78 -0
  168. package/dist/diplomat/http/remedy.js +26 -0
  169. package/dist/diplomat/http/respond.js +50 -0
  170. package/dist/diplomat/http/routes/account.js +226 -0
  171. package/dist/diplomat/http/routes/aggregate.js +28 -0
  172. package/dist/diplomat/http/routes/auth.js +105 -0
  173. package/dist/diplomat/http/routes/budget.js +34 -0
  174. package/dist/diplomat/http/routes/category.js +109 -0
  175. package/dist/diplomat/http/routes/connect.js +124 -0
  176. package/dist/diplomat/http/routes/credit-card.js +263 -0
  177. package/dist/diplomat/http/routes/currency-rates.js +60 -0
  178. package/dist/diplomat/http/routes/currency.js +16 -0
  179. package/dist/diplomat/http/routes/dashboard.js +93 -0
  180. package/dist/diplomat/http/routes/invite.js +63 -0
  181. package/dist/diplomat/http/routes/recurring.js +65 -0
  182. package/dist/diplomat/http/routes/settings.js +38 -0
  183. package/dist/diplomat/http/routes/summary.js +23 -0
  184. package/dist/diplomat/http/routes/system.js +29 -0
  185. package/dist/diplomat/http/routes/tag.js +51 -0
  186. package/dist/diplomat/http/routes/tokens.js +72 -0
  187. package/dist/diplomat/http/routes/transaction.js +55 -0
  188. package/dist/diplomat/http/routes/transfer.js +35 -0
  189. package/dist/diplomat/http/routes/ui.js +110 -0
  190. package/dist/diplomat/http/routes/users.js +156 -0
  191. package/dist/diplomat/http/routes/well-known.js +26 -0
  192. package/dist/diplomat/http/routes.js +85 -0
  193. package/dist/diplomat/http/session.js +34 -0
  194. package/dist/diplomat/http/token-pages.js +75 -0
  195. package/dist/diplomat/http/ui-files.js +21 -0
  196. package/dist/diplomat/http/user-pages.js +93 -0
  197. package/dist/diplomat/mcp/annotations.js +8 -0
  198. package/dist/diplomat/mcp/auth-info.js +20 -0
  199. package/dist/diplomat/mcp/context.js +14 -0
  200. package/dist/diplomat/mcp/definition.js +3 -0
  201. package/dist/diplomat/mcp/gate.js +15 -0
  202. package/dist/diplomat/mcp/instructions.js +19 -0
  203. package/dist/diplomat/mcp/prompts.js +125 -0
  204. package/dist/diplomat/mcp/register.js +12 -0
  205. package/dist/diplomat/mcp/remedy.js +17 -0
  206. package/dist/diplomat/mcp/resources.js +93 -0
  207. package/dist/diplomat/mcp/respond.js +20 -0
  208. package/dist/diplomat/mcp/route.js +62 -0
  209. package/dist/diplomat/mcp/scopes.js +53 -0
  210. package/dist/diplomat/mcp/server.js +26 -0
  211. package/dist/diplomat/mcp/shared.js +5 -0
  212. package/dist/diplomat/mcp/stdio-session.js +94 -0
  213. package/dist/diplomat/mcp/stdio.js +23 -0
  214. package/dist/diplomat/mcp/tool-name.js +59 -0
  215. package/dist/diplomat/mcp/tools/account.js +218 -0
  216. package/dist/diplomat/mcp/tools/aggregate.js +32 -0
  217. package/dist/diplomat/mcp/tools/budget.js +99 -0
  218. package/dist/diplomat/mcp/tools/category.js +103 -0
  219. package/dist/diplomat/mcp/tools/correlations.js +70 -0
  220. package/dist/diplomat/mcp/tools/credit-card.js +239 -0
  221. package/dist/diplomat/mcp/tools/currency-rates.js +62 -0
  222. package/dist/diplomat/mcp/tools/dashboard.js +75 -0
  223. package/dist/diplomat/mcp/tools/index.js +31 -0
  224. package/dist/diplomat/mcp/tools/recurring.js +62 -0
  225. package/dist/diplomat/mcp/tools/summary.js +30 -0
  226. package/dist/diplomat/mcp/tools/system.js +83 -0
  227. package/dist/diplomat/mcp/tools/tag.js +48 -0
  228. package/dist/diplomat/mcp/tools/transaction.js +53 -0
  229. package/dist/diplomat/mcp/tools/transfer.js +28 -0
  230. package/dist/diplomat/mcp/tour.js +87 -0
  231. package/dist/logic/account.js +79 -0
  232. package/dist/logic/aggregate.js +37 -0
  233. package/dist/logic/auth/bearer.js +35 -0
  234. package/dist/logic/auth/grant.js +126 -0
  235. package/dist/logic/auth/key-export.js +10 -0
  236. package/dist/logic/auth/keychain.js +3 -0
  237. package/dist/logic/auth/message.js +22 -0
  238. package/dist/logic/auth/origin.js +57 -0
  239. package/dist/logic/auth/owner.js +22 -0
  240. package/dist/logic/auth/password.js +3 -0
  241. package/dist/logic/auth/redact.js +25 -0
  242. package/dist/logic/auth/revoke.js +28 -0
  243. package/dist/logic/auth/scope.js +17 -0
  244. package/dist/logic/auth/session.js +30 -0
  245. package/dist/logic/auth/sign-in-flow.js +305 -0
  246. package/dist/logic/auth/time.js +2 -0
  247. package/dist/logic/auth/token.js +74 -0
  248. package/dist/logic/auth/user-plans.js +84 -0
  249. package/dist/logic/auth/users.js +78 -0
  250. package/dist/logic/balance.js +2 -0
  251. package/dist/logic/bill.js +74 -0
  252. package/dist/logic/budget.js +78 -0
  253. package/dist/logic/category.js +37 -0
  254. package/dist/logic/classify.js +21 -0
  255. package/dist/logic/correlations.js +147 -0
  256. package/dist/logic/credit-card.js +2 -0
  257. package/dist/logic/currency-rate.js +69 -0
  258. package/dist/logic/dashboard.js +40 -0
  259. package/dist/logic/demo/database.js +30 -0
  260. package/dist/logic/demo/plan.js +308 -0
  261. package/dist/logic/demo/tour.js +33 -0
  262. package/dist/logic/export-destination.js +12 -0
  263. package/dist/logic/key-import.js +15 -0
  264. package/dist/logic/locale.js +5 -0
  265. package/dist/logic/localize.js +12 -0
  266. package/dist/logic/merchant.js +31 -0
  267. package/dist/logic/migration.js +1 -0
  268. package/dist/logic/money.js +12 -0
  269. package/dist/logic/period.js +45 -0
  270. package/dist/logic/persistence.js +48 -0
  271. package/dist/logic/recurring.js +51 -0
  272. package/dist/logic/resolve.js +44 -0
  273. package/dist/logic/summary.js +29 -0
  274. package/dist/logic/tag.js +13 -0
  275. package/dist/logic/transaction.js +197 -0
  276. package/dist/main.js +42 -0
  277. package/dist/models/account.js +197 -0
  278. package/dist/models/aggregate.js +61 -0
  279. package/dist/models/auth/bearer.js +11 -0
  280. package/dist/models/auth/entity.js +17 -0
  281. package/dist/models/auth/errors.js +42 -0
  282. package/dist/models/auth/grant.js +58 -0
  283. package/dist/models/auth/key-export.js +11 -0
  284. package/dist/models/auth/message.js +50 -0
  285. package/dist/models/auth/mode.js +7 -0
  286. package/dist/models/auth/origin.js +16 -0
  287. package/dist/models/auth/owner.js +36 -0
  288. package/dist/models/auth/password.js +24 -0
  289. package/dist/models/auth/principal.js +26 -0
  290. package/dist/models/auth/redact.js +4 -0
  291. package/dist/models/auth/scope.js +9 -0
  292. package/dist/models/auth/session.js +19 -0
  293. package/dist/models/auth/sign-in-flow.js +102 -0
  294. package/dist/models/auth/sign-in.js +41 -0
  295. package/dist/models/auth/time.js +5 -0
  296. package/dist/models/auth/token.js +50 -0
  297. package/dist/models/auth/users.js +52 -0
  298. package/dist/models/bill.js +55 -0
  299. package/dist/models/budget.js +106 -0
  300. package/dist/models/category.js +52 -0
  301. package/dist/models/client-config.js +18 -0
  302. package/dist/models/correlations.js +215 -0
  303. package/dist/models/credit-card.js +156 -0
  304. package/dist/models/currency-rate.js +83 -0
  305. package/dist/models/dashboard.js +54 -0
  306. package/dist/models/database.js +16 -0
  307. package/dist/models/date.js +8 -0
  308. package/dist/models/demo/core.js +58 -0
  309. package/dist/models/demo/tour.js +41 -0
  310. package/dist/models/encryption-key.js +2 -0
  311. package/dist/models/error.js +13 -0
  312. package/dist/models/export.js +9 -0
  313. package/dist/models/id.js +2 -0
  314. package/dist/models/instance.js +7 -0
  315. package/dist/models/key-import.js +6 -0
  316. package/dist/models/locale.js +25 -0
  317. package/dist/models/merchant.js +12 -0
  318. package/dist/models/money.js +14 -0
  319. package/dist/models/package.js +12 -0
  320. package/dist/models/page.js +56 -0
  321. package/dist/models/persistence.js +1 -0
  322. package/dist/models/prompts.js +5 -0
  323. package/dist/models/recurring.js +54 -0
  324. package/dist/models/remedy.js +17 -0
  325. package/dist/models/resolution.js +1 -0
  326. package/dist/models/startup.js +7 -0
  327. package/dist/models/summary.js +24 -0
  328. package/dist/models/tag.js +14 -0
  329. package/dist/models/tenancy.js +10 -0
  330. package/dist/models/transaction-tag.js +6 -0
  331. package/dist/models/transaction.js +275 -0
  332. package/dist/wire/db/access-tokens.js +1 -0
  333. package/dist/wire/db/accounts.js +7 -0
  334. package/dist/wire/db/aggregate.js +16 -0
  335. package/dist/wire/db/bills.js +14 -0
  336. package/dist/wire/db/budgets.js +33 -0
  337. package/dist/wire/db/categories.js +14 -0
  338. package/dist/wire/db/client-grants.js +1 -0
  339. package/dist/wire/db/correlations.js +49 -0
  340. package/dist/wire/db/credit-cards.js +1 -0
  341. package/dist/wire/db/currencies.js +1 -0
  342. package/dist/wire/db/currency-rates.js +1 -0
  343. package/dist/wire/db/dashboards.js +1 -0
  344. package/dist/wire/db/instance-settings.js +1 -0
  345. package/dist/wire/db/invites.js +1 -0
  346. package/dist/wire/db/merchants.js +18 -0
  347. package/dist/wire/db/recurring.js +19 -0
  348. package/dist/wire/db/sessions.js +1 -0
  349. package/dist/wire/db/settings.js +1 -0
  350. package/dist/wire/db/setup-codes.js +1 -0
  351. package/dist/wire/db/tags.js +1 -0
  352. package/dist/wire/db/tenancy.js +1 -0
  353. package/dist/wire/db/transactions.js +89 -0
  354. package/dist/wire/db/users.js +1 -0
  355. package/dist/wire/in/accounts.js +26 -0
  356. package/dist/wire/in/aggregate.js +10 -0
  357. package/dist/wire/in/auth.js +107 -0
  358. package/dist/wire/in/bills.js +11 -0
  359. package/dist/wire/in/budgets.js +11 -0
  360. package/dist/wire/in/categories.js +9 -0
  361. package/dist/wire/in/cli.js +106 -0
  362. package/dist/wire/in/coerce.js +6 -0
  363. package/dist/wire/in/common.js +17 -0
  364. package/dist/wire/in/credit-cards.js +16 -0
  365. package/dist/wire/in/currency-rates.js +8 -0
  366. package/dist/wire/in/period.js +7 -0
  367. package/dist/wire/in/recurring.js +6 -0
  368. package/dist/wire/in/settings.js +5 -0
  369. package/dist/wire/in/summary.js +5 -0
  370. package/dist/wire/in/tags.js +2 -0
  371. package/dist/wire/in/transactions.js +31 -0
  372. package/dist/wire/out/bills.js +9 -0
  373. package/dist/wire/out/budgets.js +10 -0
  374. package/dist/wire/out/client-config.js +2 -0
  375. package/dist/wire/out/common.js +4 -0
  376. package/dist/wire/out/credit-cards.js +15 -0
  377. package/dist/wire/out/currency-rates.js +11 -0
  378. package/dist/wire/out/errors.js +58 -0
  379. package/dist/wire/out/recurring.js +6 -0
  380. package/dist/wire/out/status.js +10 -0
  381. package/dist/wire/out/summary.js +9 -0
  382. package/dist/wire/out/transactions.js +52 -0
  383. package/drizzle/0000_futuristic_umar.sql +124 -0
  384. package/drizzle/0001_fts5_search.sql +23 -0
  385. package/drizzle/0002_rename_graph_to_history.sql +7 -0
  386. package/drizzle/0003_lyrical_hairball.sql +2 -0
  387. package/drizzle/0004_misty_ikaris.sql +7 -0
  388. package/drizzle/0005_credit-liability-accounts.sql +14 -0
  389. package/drizzle/0006_smart_aqueduct.sql +1 -0
  390. package/drizzle/0007_add_dashboards.sql +5 -0
  391. package/drizzle/0008_yummy_madripoor.sql +1 -0
  392. package/drizzle/0009_version_groundwork.sql +9 -0
  393. package/drizzle/0010_category_merchant_association_cascade.sql +16 -0
  394. package/drizzle/0011_dashboard_id_normalization.sql +16 -0
  395. package/drizzle/0012_hot_the_spike.sql +12 -0
  396. package/drizzle/0013_recurring_rules_merchant.sql +1 -0
  397. package/drizzle/0014_dashboard_source_discriminator.sql +17 -0
  398. package/drizzle/0015_currencies_decimals.sql +1 -0
  399. package/drizzle/0016_unusual_zaran.sql +13 -0
  400. package/drizzle/0017_premium_blur.sql +1 -0
  401. package/drizzle/0018_auth_identity.sql +39 -0
  402. package/drizzle/0019_access_tokens.sql +16 -0
  403. package/drizzle/0020_stdio_sign_in.sql +27 -0
  404. package/drizzle/0021_tenancy_data.sql +289 -0
  405. package/drizzle/0022_user_management.sql +17 -0
  406. package/drizzle/0023_instance_settings_row.sql +2 -0
  407. package/drizzle/0024_credentials_changed_at.sql +2 -0
  408. package/drizzle/0025_instance_kind.sql +2 -0
  409. package/drizzle/0026_demo_seeded_at.sql +2 -0
  410. package/drizzle/0027_demo_country.sql +2 -0
  411. package/drizzle/0028_reset_sign_ins.sql +2 -0
  412. package/drizzle/meta/0000_snapshot.json +894 -0
  413. package/drizzle/meta/0003_snapshot.json +910 -0
  414. package/drizzle/meta/0004_snapshot.json +951 -0
  415. package/drizzle/meta/0005_snapshot.json +991 -0
  416. package/drizzle/meta/0006_snapshot.json +998 -0
  417. package/drizzle/meta/0007_snapshot.json +1029 -0
  418. package/drizzle/meta/0008_snapshot.json +1049 -0
  419. package/drizzle/meta/0009_snapshot.json +1121 -0
  420. package/drizzle/meta/0010_snapshot.json +1121 -0
  421. package/drizzle/meta/0011_snapshot.json +1136 -0
  422. package/drizzle/meta/0012_snapshot.json +1227 -0
  423. package/drizzle/meta/0013_snapshot.json +1247 -0
  424. package/drizzle/meta/0014_snapshot.json +1267 -0
  425. package/drizzle/meta/0015_snapshot.json +1275 -0
  426. package/drizzle/meta/0016_snapshot.json +1371 -0
  427. package/drizzle/meta/0017_snapshot.json +1392 -0
  428. package/drizzle/meta/0018_snapshot.json +1603 -0
  429. package/drizzle/meta/0019_snapshot.json +1713 -0
  430. package/drizzle/meta/0020_snapshot.json +1904 -0
  431. package/drizzle/meta/0021_snapshot.json +2186 -0
  432. package/drizzle/meta/0022_snapshot.json +2311 -0
  433. package/drizzle/meta/0023_snapshot.json +2311 -0
  434. package/drizzle/meta/0024_snapshot.json +2318 -0
  435. package/drizzle/meta/0025_snapshot.json +2326 -0
  436. package/drizzle/meta/0026_snapshot.json +2333 -0
  437. package/drizzle/meta/0027_snapshot.json +2340 -0
  438. package/drizzle/meta/0028_snapshot.json +2340 -0
  439. package/drizzle/meta/_journal.json +209 -0
  440. package/package.json +106 -4
  441. package/skills/dashboard-building/SKILL.md +201 -0
  442. package/skills/patty-tour/SKILL.md +34 -0
  443. package/ui/app.css +758 -0
  444. package/ui/app.js +543 -0
  445. package/ui/connect-result.html +16 -0
  446. package/ui/connect.html +53 -0
  447. package/ui/dashboards/accounts.html +3189 -0
  448. package/ui/dashboards/budget.html +1734 -0
  449. package/ui/dashboards/cards.html +4032 -0
  450. package/ui/dashboards/categories.html +4694 -0
  451. package/ui/dashboards/comparative.html +2475 -0
  452. package/ui/dashboards/dashboards.html +839 -0
  453. package/ui/dashboards/overview.html +2405 -0
  454. package/ui/dashboards/pending.html +2973 -0
  455. package/ui/dashboards/projections.html +2528 -0
  456. package/ui/dashboards/tags.html +1365 -0
  457. package/ui/invite.html +44 -0
  458. package/ui/login.html +26 -0
  459. package/ui/money.js +175 -0
  460. package/ui/setup.html +29 -0
  461. package/ui/shell.html +96 -0
  462. package/ui/token-created.html +24 -0
  463. package/ui/tokens.html +58 -0
  464. package/ui/user-invited.html +27 -0
  465. package/ui/users.html +60 -0
@@ -0,0 +1,167 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { mkdirSync, readFileSync } from 'node:fs';
3
+ import { dirname } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { createClient } from '@libsql/client';
6
+ import { drizzle } from 'drizzle-orm/libsql';
7
+ import { EncryptionKey } from '../../models/encryption-key.js';
8
+ import { PRIVATE_DIRECTORY_MODE } from '../../models/export.js';
9
+ import { DB_KEY_KEYCHAIN_ACCOUNT, KEYCHAIN_SERVICE } from '../../models/auth/sign-in.js';
10
+ import { withKeyLock } from './key-lock.js';
11
+ import * as schema from './schema.js';
12
+ import { LOG_PREFIX } from '../../models/package.js';
13
+ // ADR-024: WAL lets readers (the HTTP sidecar) proceed without blocking the single writer, instead
14
+ // of rollback-journal's mutual blocking. busy_timeout makes a contended writer wait for the lock
15
+ // instead of throwing SQLITE_BUSY immediately — the common case for stdio spawned per client
16
+ // (ADR-007) when more than one is connected to the same file at once.
17
+ const JOURNAL_MODE_WAL = 'WAL';
18
+ export const BUSY_TIMEOUT_MS = 5000;
19
+ /** `busy_timeout` is per connection (ADR-024) and libsql opens a fresh connection after every transaction, so
20
+ * anything that has just run one re-asserts it on the connection that follows. */
21
+ export const assertBusyTimeout = (client) => client.execute(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
22
+ const KEY_GENERATION_HINT = 'Generate one with `openssl rand -hex 32` and provide it via PATTY_DB_KEY_FILE ' +
23
+ '(e.g. a Docker secret mounted at /run/secrets/patty_db_key) or the PATTY_DB_KEY environment variable.';
24
+ const readKeyFile = (path) => {
25
+ let contents;
26
+ try {
27
+ contents = readFileSync(path, 'utf8');
28
+ }
29
+ catch (cause) {
30
+ throw new Error(`${LOG_PREFIX} cannot read the encryption key file PATTY_DB_KEY_FILE (${path}). ${KEY_GENERATION_HINT}`, { cause });
31
+ }
32
+ const parsed = EncryptionKey.safeParse(contents.trim());
33
+ if (!parsed.success) {
34
+ throw new Error(`${LOG_PREFIX} PATTY_DB_KEY_FILE (${path}) must contain a 64-character hex key (a trailing newline is fine). ${KEY_GENERATION_HINT}`);
35
+ }
36
+ return parsed.data;
37
+ };
38
+ // The only place the native keychain module is loaded, so the file/env key paths never load it (ADR-032).
39
+ const importKeyring = () => import('@napi-rs/keyring');
40
+ let keyring;
41
+ const loadKeyring = () => (keyring ??= importKeyring());
42
+ // A hand-edited or corrupted keychain entry must fail here with a clear message, not reach libSQL.
43
+ const validateStoredKey = (stored) => {
44
+ const parsed = EncryptionKey.safeParse(stored);
45
+ if (!parsed.success) {
46
+ throw new Error(`${LOG_PREFIX} the encryption key stored in the OS keychain is not a 64-character hex key. ` +
47
+ `Remove the "${KEYCHAIN_SERVICE}" / "${DB_KEY_KEYCHAIN_ACCOUNT}" keychain entry (this loses access to an existing database ` +
48
+ `encrypted with it), or supply the correct key. ${KEY_GENERATION_HINT}`);
49
+ }
50
+ return parsed.data;
51
+ };
52
+ const keychainEntry = async () => {
53
+ const { Entry } = await loadKeyring();
54
+ return new Entry(KEYCHAIN_SERVICE, DB_KEY_KEYCHAIN_ACCOUNT);
55
+ };
56
+ const inKeychain = async (work) => {
57
+ try {
58
+ return await work();
59
+ }
60
+ catch (cause) {
61
+ throw new Error(`${LOG_PREFIX} cannot read or write the database encryption key in the OS keychain, and no key source was configured. ${KEY_GENERATION_HINT}`, { cause });
62
+ }
63
+ };
64
+ const generateKeychainKey = (entry, keyLockPath) => {
65
+ return withKeyLock(() => inKeychain(() => {
66
+ const existing = entry.getPassword();
67
+ if (existing)
68
+ return existing;
69
+ const key = randomBytes(32).toString('hex');
70
+ entry.setPassword(key);
71
+ return key;
72
+ }), keyLockPath);
73
+ };
74
+ const resolveKeychainKey = async (keyLockPath) => {
75
+ const entry = await inKeychain(keychainEntry);
76
+ const existing = await inKeychain(() => entry.getPassword());
77
+ return existing || generateKeychainKey(entry, keyLockPath);
78
+ };
79
+ const configuredKey = (config) => {
80
+ if (config.PATTY_DB_KEY_FILE) {
81
+ console.warn(`${LOG_PREFIX} using the encryption key from PATTY_DB_KEY_FILE; OS keychain bypassed.`);
82
+ return readKeyFile(config.PATTY_DB_KEY_FILE);
83
+ }
84
+ // Env-var override: CI, headless, or manual recovery (ADR-005). We log that we are in
85
+ // env-var mode (never the key value itself) so the weaker posture is visible.
86
+ if (config.PATTY_DB_KEY) {
87
+ console.warn(`${LOG_PREFIX} using PATTY_DB_KEY from the environment; OS keychain bypassed.`);
88
+ return config.PATTY_DB_KEY;
89
+ }
90
+ return null;
91
+ };
92
+ // Order: key file -> env var -> OS keychain. The key is never written next to the data: the
93
+ // keychain generates on first run for local use only, and every other path fails fast.
94
+ export const resolveEncryptionKey = async (config) => configuredKey(config) ?? validateStoredKey(await resolveKeychainKey(config.KEY_LOCK_PATH));
95
+ export const keychainHoldsKey = async () => Boolean((await keychainEntry()).getPassword());
96
+ export const storeKeychainKeyIfAbsent = async (key, keyLockPath) => {
97
+ const entry = await keychainEntry();
98
+ return withKeyLock(async () => {
99
+ if (entry.getPassword())
100
+ return false;
101
+ entry.setPassword(key);
102
+ return true;
103
+ }, keyLockPath);
104
+ };
105
+ export const findEncryptionKey = async (config) => {
106
+ const configured = configuredKey(config);
107
+ if (configured !== null)
108
+ return configured;
109
+ const stored = (await keychainEntry()).getPassword();
110
+ return stored ? validateStoredKey(stored) : null;
111
+ };
112
+ /** Best-effort: WAL is verified to work with libSQL's encryption-at-rest in this project's target
113
+ * environments, but a build lacking WAL support degrades to busy_timeout + retry alone (ADR-024
114
+ * Consequences) rather than failing the whole DB open. `PRAGMA journal_mode = WAL` does not throw
115
+ * when WAL can't be applied — SQLite silently keeps the prior mode and reports it back in the
116
+ * result row — so the applied mode is checked explicitly, not just the thrown-exception path.
117
+ * Exported so the silent-fallback path (unreachable through `openDatabase`'s always-file-backed
118
+ * `DB_PATH`) has direct unit coverage against a real in-memory client. */
119
+ export const enableWal = async (client) => {
120
+ try {
121
+ const result = await client.execute(`PRAGMA journal_mode = ${JOURNAL_MODE_WAL}`);
122
+ const appliedMode = result.rows[0]?.journal_mode;
123
+ if (typeof appliedMode !== 'string' || appliedMode.toUpperCase() !== JOURNAL_MODE_WAL) {
124
+ console.warn(`${LOG_PREFIX} WAL journal mode was not applied (sqlite reports "${String(appliedMode)}"); ` +
125
+ 'continuing with busy_timeout + retry only.');
126
+ }
127
+ }
128
+ catch (cause) {
129
+ // Not necessarily a WAL-support gap — could equally be a wrong key or a corrupt file, both of
130
+ // which still surface their own real error on the next query. Worded neutrally rather than
131
+ // diagnosing a cause this catch can't actually distinguish.
132
+ console.warn(`${LOG_PREFIX} could not enable WAL journal mode; continuing with busy_timeout + retry only.`, cause);
133
+ }
134
+ };
135
+ /**
136
+ * Open the encrypted libSQL database and return a Drizzle client.
137
+ * The encryption key comes from PATTY_DB_KEY_FILE, PATTY_DB_KEY or the OS keychain (generated
138
+ * on first run); throws if none is available so the DB is never opened unencrypted.
139
+ */
140
+ export const openDatabase = async (config) => openDatabaseWithKey(config, await resolveEncryptionKey(config));
141
+ /** Opens the database with a key already in hand — what `openDatabase` does after resolving one, and what the key
142
+ * export does after proving it. Neither migrates nor seeds: that is `bootstrap`'s. */
143
+ export const openDatabaseWithKey = async (config, encryptionKey, { initializeJournal = true } = {}) => {
144
+ // mode 0o700 applies only when the directory is first created; pre-existing directories
145
+ // keep their current permissions (Node does not retroactively tighten them).
146
+ mkdirSync(dirname(config.DB_PATH), { recursive: true, mode: PRIVATE_DIRECTORY_MODE });
147
+ const client = createClient({ url: pathToFileURL(config.DB_PATH).href, encryptionKey });
148
+ if (initializeJournal)
149
+ await enableWal(client);
150
+ // busy_timeout is per-connection (ADR-024), so it is asserted unconditionally on every open.
151
+ await assertBusyTimeout(client);
152
+ return drizzle(client, { schema });
153
+ };
154
+ /** Releases the libSQL connection a short-lived process (the CLI) opened, so it can end by itself. Drizzle keeps
155
+ * the client on `$client` at runtime without typing it on `LibSQLDatabase`. */
156
+ export const closeDatabase = (db) => {
157
+ db.$client?.close();
158
+ };
159
+ /** Adapts libSQL Drizzle's `Db.transaction` to the effect engine's `TransactionRunner` port
160
+ * (ADR-030 Phase 1) — `diplomat/db/effects.ts`'s `runEffects`/`runEffectsSequence` call
161
+ * `runInTransaction` and never name `Db.transaction` directly; this is the one place, at the
162
+ * composition root's binding, that still does. No explicit return-type annotation: the object
163
+ * literal structurally satisfies `TransactionRunner<Tx>` without this adapter-side file importing
164
+ * that port type from the engine. */
165
+ export const createTransactionRunner = (db) => ({
166
+ runInTransaction: (work) => db.transaction(work),
167
+ });
@@ -0,0 +1,101 @@
1
+ import { and, eq } from 'drizzle-orm';
2
+ import * as R from 'remeda';
3
+ import { VersionConflict, } from '@rfc0/effect-runner';
4
+ import { isForeignKeyConstraintViolation } from './sqlite-errors.js';
5
+ export { VersionConflict };
6
+ const IDEMPOTENCY_KEY_COLUMN = 'idempotencyKey';
7
+ export const missingIdempotencyKeyMessage = () => `runEffects: table has an "${IDEMPOTENCY_KEY_COLUMN}" column but the insert carries no idempotencyKey`;
8
+ export const unexpectedIdempotencyKeyMessage = () => `runEffects: insert carries an idempotencyKey but its table has no "${IDEMPOTENCY_KEY_COLUMN}" column`;
9
+ const tableContextFor = (table, owner, readBack) => {
10
+ const columns = table;
11
+ const ownerColumn = owner ? columns['userId'] : undefined;
12
+ if (owner && !ownerColumn)
13
+ throw new Error('versionedTableApplier: an owner scope needs a "userId" column');
14
+ return {
15
+ table,
16
+ keyColumn: columns[IDEMPOTENCY_KEY_COLUMN],
17
+ ownerColumn,
18
+ ownedBy: () => (owner && ownerColumn ? [eq(ownerColumn, owner.userId)] : []),
19
+ readBack,
20
+ owner,
21
+ };
22
+ };
23
+ const findSurvivingRowId = async ({ table, ownedBy }, tx, column, key) => {
24
+ const [row] = await tx
25
+ .select({ id: table.id })
26
+ .from(table)
27
+ .where(and(eq(column, key), ...ownedBy()));
28
+ if (!row)
29
+ throw new Error(`runEffects: no surviving row holds idempotency key "${key}" after a duplicate insert`);
30
+ return row.id;
31
+ };
32
+ const assertKeyMatchesTable = ({ keyColumn }, idempotencyKey) => {
33
+ if (keyColumn && idempotencyKey === undefined) {
34
+ throw new Error(missingIdempotencyKeyMessage());
35
+ }
36
+ if (!keyColumn && idempotencyKey !== undefined) {
37
+ throw new Error(unexpectedIdempotencyKeyMessage());
38
+ }
39
+ };
40
+ const rowToInsert = ({ owner, keyColumn }, model, idempotencyKey) => {
41
+ const given = model;
42
+ const row = owner ? R.omit(given, ['userId']) : given;
43
+ const stamped = owner ? { ...row, userId: owner.userId } : row;
44
+ return keyColumn && idempotencyKey !== undefined ? { ...stamped, [IDEMPOTENCY_KEY_COLUMN]: idempotencyKey } : stamped;
45
+ };
46
+ const conflictTarget = ({ table, keyColumn, ownerColumn }, idempotencyKey) => {
47
+ const keyTarget = ownerColumn && keyColumn ? [ownerColumn, keyColumn] : keyColumn;
48
+ return idempotencyKey !== undefined && keyTarget ? keyTarget : table.id;
49
+ };
50
+ const persistedIdAfter = async (ctx, tx, applied, row, idempotencyKey) => applied || idempotencyKey === undefined || !ctx.keyColumn
51
+ ? row.id
52
+ : await findSurvivingRowId(ctx, tx, ctx.keyColumn, idempotencyKey);
53
+ const insertRow = (ctx) => async (tx, model, idempotencyKey) => {
54
+ assertKeyMatchesTable(ctx, idempotencyKey);
55
+ const row = rowToInsert(ctx, model, idempotencyKey);
56
+ const result = await tx
57
+ .insert(ctx.table)
58
+ .values(row)
59
+ .onConflictDoNothing({ target: conflictTarget(ctx, idempotencyKey) });
60
+ const applied = (result.rowsAffected ?? 0) > 0;
61
+ if (!ctx.readBack)
62
+ return { applied };
63
+ return { applied, read: await ctx.readBack(tx, await persistedIdAfter(ctx, tx, applied, row, idempotencyKey)) };
64
+ };
65
+ const updateRow = ({ table, owner, ownedBy, readBack }) => async (tx, model) => {
66
+ const row = model;
67
+ const values = R.omit(row, owner ? ['id', 'version', 'userId'] : ['id', 'version']);
68
+ const result = await tx
69
+ .update(table)
70
+ .set({ ...values, version: row.version + 1 })
71
+ .where(and(eq(table.id, row.id), eq(table.version, row.version), ...ownedBy()));
72
+ const applied = (result.rowsAffected ?? 0) > 0;
73
+ if (!applied || !readBack)
74
+ return { applied };
75
+ return { applied, read: await readBack(tx, row.id) };
76
+ };
77
+ const deleteRow = ({ table, ownedBy }) => async (tx, id, version) => {
78
+ try {
79
+ const result = await tx.delete(table).where(and(eq(table.id, id), eq(table.version, version), ...ownedBy()));
80
+ return { applied: (result.rowsAffected ?? 0) > 0 };
81
+ }
82
+ catch (cause) {
83
+ if (isForeignKeyConstraintViolation(cause))
84
+ throw new VersionConflict();
85
+ throw cause;
86
+ }
87
+ };
88
+ const checkRow = ({ table, ownedBy }) => async (tx, id, version) => {
89
+ const [row] = await tx
90
+ .select({ id: table.id })
91
+ .from(table)
92
+ .where(and(eq(table.id, id), eq(table.version, version), ...ownedBy()))
93
+ .limit(1);
94
+ return { applied: row !== undefined };
95
+ };
96
+ const applierFor = (table, owner, { readBack }) => {
97
+ const ctx = tableContextFor(table, owner, readBack);
98
+ return { insert: insertRow(ctx), update: updateRow(ctx), delete: deleteRow(ctx), check: checkRow(ctx) };
99
+ };
100
+ export const versionedTableApplier = (table, config = {}) => applierFor(table, undefined, config);
101
+ export const ownedTableApplier = (table, userId, config = {}) => applierFor(table, { userId }, config);
@@ -0,0 +1,9 @@
1
+ import { conflict } from '../../models/error.js';
2
+ import { createTransactionRunner } from './driver.js';
3
+ import { isSqliteBusy } from './sqlite-errors.js';
4
+ export const createEngineContext = (db, onPublishError) => ({
5
+ runner: createTransactionRunner(db),
6
+ isTransientContention: isSqliteBusy,
7
+ conflictError: () => conflict,
8
+ onPublishError,
9
+ });
@@ -0,0 +1,22 @@
1
+ import { createClient } from '@libsql/client';
2
+ import { count, getTableName } from 'drizzle-orm';
3
+ import { drizzle } from 'drizzle-orm/libsql';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { accounts, transactions } from './schema.js';
6
+ const COUNTED_TABLES = [accounts, transactions];
7
+ const countOf = async (db, table) => {
8
+ const [row] = await db.select({ rows: count() }).from(table);
9
+ return [getTableName(table), row?.rows ?? 0];
10
+ };
11
+ /** Reads the row counts of a snapshot with its key, on a connection of its own: no WAL switch, no migration, so the
12
+ * file stays exactly what `VACUUM INTO` wrote. Doubles as proof that the snapshot opens with the key. */
13
+ export const countSnapshotRows = async (file, encryptionKey) => {
14
+ const client = createClient({ url: pathToFileURL(file).href, encryptionKey });
15
+ try {
16
+ const db = drizzle(client);
17
+ return Object.fromEntries(await Promise.all(COUNTED_TABLES.map((table) => countOf(db, table))));
18
+ }
19
+ finally {
20
+ client.close();
21
+ }
22
+ };
@@ -0,0 +1,82 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ import { createClient } from '@libsql/client';
3
+ import { isSqliteBusy } from './sqlite-errors.js';
4
+ export const NEVER_BLOCK_IN_SQLITE_MS = 0;
5
+ export const openLockFile = async (lockPath) => {
6
+ const client = createClient({ url: pathToFileURL(lockPath).href });
7
+ try {
8
+ await client.execute(`PRAGMA busy_timeout = ${NEVER_BLOCK_IN_SQLITE_MS}`);
9
+ return client;
10
+ }
11
+ catch (cause) {
12
+ client.close();
13
+ throw cause;
14
+ }
15
+ };
16
+ /** One attempt at the exclusive transaction: `cause` is the busy error when another holder has it; any other failure
17
+ * is thrown. */
18
+ export const tryBeginExclusive = async (client) => {
19
+ try {
20
+ await client.execute('BEGIN EXCLUSIVE');
21
+ return { acquired: true };
22
+ }
23
+ catch (cause) {
24
+ if (isSqliteBusy(cause))
25
+ return { acquired: false, cause };
26
+ throw cause;
27
+ }
28
+ };
29
+ /** A failed rollback must never hide the error the caller is already throwing. */
30
+ export const rollbackQuietly = async (client) => {
31
+ try {
32
+ await client.execute('ROLLBACK');
33
+ }
34
+ catch {
35
+ // closing the client ends the transaction and frees the lock either way
36
+ }
37
+ };
38
+ // A client that failed to begin must be closed, not retried: its later begin succeeds but its release leaves the OS
39
+ // lock held until the process exits.
40
+ const attemptExclusiveLock = async (lockPath) => {
41
+ const client = await openLockFile(lockPath);
42
+ try {
43
+ const attempt = await tryBeginExclusive(client);
44
+ if (!attempt.acquired) {
45
+ client.close();
46
+ return { lock: null, cause: attempt.cause };
47
+ }
48
+ }
49
+ catch (cause) {
50
+ client.close();
51
+ throw cause;
52
+ }
53
+ return {
54
+ lock: {
55
+ release: async () => {
56
+ await rollbackQuietly(client);
57
+ client.close();
58
+ },
59
+ },
60
+ };
61
+ };
62
+ export const tryExclusiveLock = async (lockPath) => (await attemptExclusiveLock(lockPath)).lock;
63
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
64
+ const acquireWithin = async (lockPath, deadline, wait) => {
65
+ const attempt = await attemptExclusiveLock(lockPath);
66
+ if (attempt.lock !== null)
67
+ return attempt.lock;
68
+ if (Date.now() >= deadline)
69
+ throw new Error(wait.timeoutMessage, { cause: attempt.cause });
70
+ await sleep(wait.retryMs);
71
+ return acquireWithin(lockPath, deadline, wait);
72
+ };
73
+ export const waitForExclusiveLock = (lockPath, wait) => acquireWithin(lockPath, Date.now() + wait.waitMs, wait);
74
+ export const withExclusiveLock = async (lockPath, wait, work) => {
75
+ const lock = await waitForExclusiveLock(lockPath, wait);
76
+ try {
77
+ return await work();
78
+ }
79
+ finally {
80
+ await lock.release();
81
+ }
82
+ };
@@ -0,0 +1,14 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { PRIVATE_DIRECTORY_MODE } from '../../models/export.js';
4
+ import { KEY_LOCK_RETRY_MS, KEY_LOCK_WAIT_MS } from '../../models/key-import.js';
5
+ import { withExclusiveLock } from './file-lock.js';
6
+ import { LOG_PREFIX } from '../../models/package.js';
7
+ export const withKeyLock = (work, lockPath, waitMs = KEY_LOCK_WAIT_MS) => {
8
+ mkdirSync(dirname(lockPath), { recursive: true, mode: PRIVATE_DIRECTORY_MODE });
9
+ return withExclusiveLock(lockPath, {
10
+ waitMs,
11
+ retryMs: KEY_LOCK_RETRY_MS,
12
+ timeoutMessage: `${LOG_PREFIX} another patty process is writing the database key (lock ${lockPath}); try again in a moment.`,
13
+ }, work);
14
+ };
@@ -0,0 +1,23 @@
1
+ import { Locale } from '../../models/locale.js';
2
+ // resetLocale is shell-only — never a Deps field; a diplomat handler calls it after its own
3
+ // setLocale write commits. configLocale (PATTY_LOCALE) always wins, for every user, and is never cached.
4
+ // Keyed by user, so one person's language never becomes another's.
5
+ export const createLocaleResolver = (configLocale) => {
6
+ const cachedByUser = new Map();
7
+ return {
8
+ locale: async (userId, settings) => {
9
+ if (configLocale)
10
+ return configLocale;
11
+ const cached = cachedByUser.get(userId);
12
+ if (cached)
13
+ return cached;
14
+ const row = await settings.getLocale();
15
+ const locale = row?.locale ?? Locale.enum.en;
16
+ cachedByUser.set(userId, locale);
17
+ return locale;
18
+ },
19
+ resetLocale: (userId) => {
20
+ cachedByUser.delete(userId);
21
+ },
22
+ };
23
+ };
@@ -0,0 +1,57 @@
1
+ import { readMigrationFiles } from 'drizzle-orm/migrator';
2
+ import { assertBusyTimeout } from './driver.js';
3
+ import { isSqliteBusy } from './sqlite-errors.js';
4
+ import { LOG_PREFIX, PRODUCT_NAME } from '../../models/package.js';
5
+ export const MIGRATIONS_TABLE = '__drizzle_migrations';
6
+ const lastApplied = async (barrier) => {
7
+ const [last] = (await barrier.execute(`SELECT created_at FROM ${MIGRATIONS_TABLE} ORDER BY created_at DESC LIMIT 1`))
8
+ .rows;
9
+ return last;
10
+ };
11
+ const applyMigration = async (barrier, migration) => {
12
+ for (const statement of migration.sql)
13
+ await barrier.execute(statement);
14
+ await barrier.execute({
15
+ sql: `INSERT INTO ${MIGRATIONS_TABLE} ("hash", "created_at") VALUES (?, ?)`,
16
+ args: [migration.hash, migration.folderMillis],
17
+ });
18
+ };
19
+ const applyPending = async (barrier, migrations, last) => {
20
+ for (const migration of migrations) {
21
+ const isPending = last === undefined || Number(last.created_at) < migration.folderMillis;
22
+ if (isPending)
23
+ await applyMigration(barrier, migration);
24
+ }
25
+ };
26
+ export const applyPendingMigrationsHolding = async (db, migrationsFolder, whileHeld, verify = async () => undefined) => {
27
+ const { $client: client } = db;
28
+ const migrations = readMigrationFiles({ migrationsFolder });
29
+ await client.execute('PRAGMA foreign_keys=off');
30
+ const barrier = await openWriteBarrier(client);
31
+ try {
32
+ const last = await lastApplied(barrier);
33
+ await whileHeld();
34
+ await applyPending(barrier, migrations, last);
35
+ await verify(barrier);
36
+ await barrier.commit();
37
+ }
38
+ catch (cause) {
39
+ await barrier.rollback().catch(() => undefined);
40
+ throw cause;
41
+ }
42
+ finally {
43
+ barrier.close();
44
+ await assertBusyTimeout(client);
45
+ }
46
+ };
47
+ const openWriteBarrier = async (client) => {
48
+ try {
49
+ return await client.transaction('write');
50
+ }
51
+ catch (cause) {
52
+ if (!isSqliteBusy(cause))
53
+ throw cause;
54
+ throw new Error(`${LOG_PREFIX} cannot start the database upgrade — another ${PRODUCT_NAME} process is writing to the database. ` +
55
+ 'Stop it (or wait for it to finish) and start again.', { cause });
56
+ }
57
+ };
@@ -0,0 +1,18 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { sql } from 'drizzle-orm';
4
+ import { z } from 'zod';
5
+ import { MIGRATIONS_TABLE } from './migration-barrier.js';
6
+ /** Both halves of "where do migrations stand": what this build ships (its journal) and what a database has applied
7
+ * (drizzle's bookkeeping table). The safety copy and the version guard each compare the two. */
8
+ const JournalSchema = z.object({ entries: z.array(z.object({ tag: z.string(), when: z.number() })) });
9
+ /** The migrations this build ships, in journal order. */
10
+ export const readJournal = (migrationsFolder) => JournalSchema.parse(JSON.parse(readFileSync(join(migrationsFolder, 'meta', '_journal.json'), 'utf8'))).entries;
11
+ // `undefined` = the migrator has never run here (nothing in the file worth protecting).
12
+ export const lastAppliedMillis = async (db) => {
13
+ const [table] = await db.all(sql `SELECT name FROM sqlite_master WHERE type = 'table' AND name = ${MIGRATIONS_TABLE}`);
14
+ if (!table)
15
+ return undefined;
16
+ const [last] = await db.all(sql `SELECT created_at FROM ${sql.identifier(MIGRATIONS_TABLE)} ORDER BY created_at DESC LIMIT 1`);
17
+ return last?.created_at;
18
+ };
@@ -0,0 +1,15 @@
1
+ import { withExclusiveLock } from './file-lock.js';
2
+ import { LOG_PREFIX, PRODUCT_NAME } from '../../models/package.js';
3
+ const LOCK_SUFFIX = '.migrate.lock';
4
+ const POLL_INTERVAL_MS = 100;
5
+ const WAIT_LIMIT_MS = 60_000;
6
+ export const lockPath = (dbFile) => `${dbFile}${LOCK_SUFFIX}`;
7
+ export const withMigrationLock = (dbFile, work) => {
8
+ const path = lockPath(dbFile);
9
+ return withExclusiveLock(path, {
10
+ waitMs: WAIT_LIMIT_MS,
11
+ retryMs: POLL_INTERVAL_MS,
12
+ timeoutMessage: `${LOG_PREFIX} another ${PRODUCT_NAME} process has held the migration lock (${path}) for over ` +
13
+ `${WAIT_LIMIT_MS / 1000}s. Stop it and retry.`,
14
+ }, work);
15
+ };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Migrations that rewrite or add rows to data that already exists (ADR-033 §7), as opposed to ones
3
+ * that only add empty structure. Startup copies the database file aside before applying any of these
4
+ * to a database that already holds applied migrations. The one place this list lives — add a tag here
5
+ * in the same change as the migration that needs it.
6
+ */
7
+ export const DATA_REWRITING_MIGRATIONS = [
8
+ '0018_auth_identity', // inserts the owner user (ADR-033 Phase 1)
9
+ '0021_tenancy_data', // rebuilds every user-owned table with user_id, backfilled to the owner
10
+ '0028_reset_sign_ins', // empties access_tokens and client_grants: every sign-in is reissued once (ADR-035)
11
+ ];
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Assert a value the code path guarantees is present — e.g. a row read back
3
+ * immediately after the INSERT/UPDATE that created it. Throws (→ unexpected error,
4
+ * surfaced as a 500) with a traceable message instead of a silent `value!`
5
+ * non-null assertion, so an invariant violation fails loudly rather than
6
+ * propagating `undefined` into the domain.
7
+ *
8
+ * Lives under `diplomat/db` (not `common/`): every caller is a repo asserting a row it
9
+ * just wrote is readable back, a `diplomat/db`-internal invariant, not cross-layer plumbing.
10
+ */
11
+ export const expectPresent = (value, message) => {
12
+ if (value == null)
13
+ throw new Error(message);
14
+ return value;
15
+ };
16
+ /** Shared `expectPresent` message shape for a row re-read immediately after the write that created it. */
17
+ export const rowNotFoundAfterWrite = (table, verb) => `${table}: row not found after ${verb}`;
@@ -0,0 +1,35 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { AggregateGroupBy, AggregateMetric } from '../../../models/aggregate.js';
3
+ export const GROUP_BY_MAP = {
4
+ [AggregateGroupBy.enum.category]: {
5
+ expr: sql `t.category_id`,
6
+ join: sql `LEFT JOIN categories c ON c.id = t.category_id`,
7
+ label: sql `c.name`,
8
+ labelNames: sql `c.names`,
9
+ },
10
+ [AggregateGroupBy.enum.account]: {
11
+ expr: sql `t.from_account_id`,
12
+ join: sql `LEFT JOIN accounts a ON a.id = t.from_account_id`,
13
+ label: sql `a.name`,
14
+ },
15
+ [AggregateGroupBy.enum.tag]: {
16
+ expr: sql `tg.name`,
17
+ join: sql `JOIN transaction_tags tt ON tt.transaction_id = t.id JOIN tags tg ON tg.id = tt.tag_id`,
18
+ label: sql `tg.name`,
19
+ },
20
+ [AggregateGroupBy.enum.month]: {
21
+ expr: sql `substr(t.date, 1, 7)`,
22
+ join: sql ``,
23
+ label: sql `substr(t.date, 1, 7)`,
24
+ },
25
+ [AggregateGroupBy.enum.merchant]: {
26
+ expr: sql `t.merchant_key`,
27
+ join: sql ``,
28
+ label: sql `t.merchant_key`,
29
+ },
30
+ };
31
+ export const METRIC_MAP = {
32
+ [AggregateMetric.enum.sum]: sql `SUM(t.amount)`,
33
+ [AggregateMetric.enum.count]: sql `COUNT(*)`,
34
+ [AggregateMetric.enum.avg]: sql `AVG(t.amount)`,
35
+ };
@@ -0,0 +1,59 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { toMatchQuery } from './fts.js';
3
+ import { ownedBy } from './scope.js';
4
+ /** The one model→SQL-filter shaping step for search_transactions — owned here (diplomat/db), not
5
+ * by the controller, which hands the repo the model plus `ResolvedSearchRefs` and never builds
6
+ * this flat shape itself (mirrors `transactionsRepo.create` calling `modelToDb` internally). */
7
+ export const toSearchFilters = (input, refs) => ({
8
+ from: refs.from ?? input.from ?? null,
9
+ to: refs.to ?? input.to ?? null,
10
+ type: input.type ?? null,
11
+ status: input.status ?? null,
12
+ text: input.text ?? null,
13
+ accountId: refs.accountId,
14
+ categoryId: refs.categoryId,
15
+ subCategoryId: refs.subCategoryId,
16
+ tagNames: input.tags ?? [],
17
+ limit: input.limit,
18
+ sort: input.sort,
19
+ dir: input.dir,
20
+ cursorKey: refs.cursorKey,
21
+ });
22
+ export const buildCommonWhere = (filters, userId) => {
23
+ const conditions = [ownedBy(userId, 't')];
24
+ if (filters.from)
25
+ conditions.push(sql `t.date >= ${filters.from}`);
26
+ if (filters.to)
27
+ conditions.push(sql `t.date < ${filters.to}`);
28
+ if (filters.type)
29
+ conditions.push(sql `t.type = ${filters.type}`);
30
+ if (filters.accountId)
31
+ conditions.push(sql `(t.from_account_id = ${filters.accountId} OR t.to_account_id = ${filters.accountId})`);
32
+ if (filters.categoryId)
33
+ conditions.push(sql `t.category_id = ${filters.categoryId}`);
34
+ if (filters.tagNames.length > 0) {
35
+ const placeholders = sql.join(filters.tagNames.map((n) => sql `${n}`), sql `, `);
36
+ conditions.push(sql `EXISTS (
37
+ SELECT 1 FROM transaction_tags tt2
38
+ JOIN tags tg2 ON tg2.id = tt2.tag_id
39
+ WHERE tt2.transaction_id = t.id AND tg2.name IN (${placeholders})
40
+ )`);
41
+ }
42
+ return conditions;
43
+ };
44
+ /** search_transactions' full WHERE — shared by the paged row query and its opt-in `count`
45
+ * (ADR-011 § shared filter WHERE-builder); only the projection/keyset/ORDER-BY tail differs. */
46
+ export const buildSearchWhere = (filters, userId) => {
47
+ const conditions = buildCommonWhere(filters, userId);
48
+ if (filters.status)
49
+ conditions.push(sql `t.status = ${filters.status}`);
50
+ if (filters.subCategoryId)
51
+ conditions.push(sql `t.subcategory_id = ${filters.subCategoryId}`);
52
+ if (filters.text) {
53
+ const matchQuery = toMatchQuery(filters.text);
54
+ if (matchQuery !== null) {
55
+ conditions.push(sql `t.rowid IN (SELECT rowid FROM transactions_fts WHERE transactions_fts MATCH ${matchQuery})`);
56
+ }
57
+ }
58
+ return conditions;
59
+ };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Convert free user text into a safe FTS5 MATCH query.
3
+ *
4
+ * User input must never reach `MATCH` verbatim: FTS5 interprets its argument as a
5
+ * query expression, so characters like `" - * : ( )` and bareword operators
6
+ * (`AND`, `OR`, `NOT`, `NEAR`) cause `fts5: syntax error` at runtime. We tokenise on
7
+ * whitespace and emit each token as a quoted string literal (internal quotes doubled),
8
+ * combined with implicit AND. The value is still passed as a bound parameter — this
9
+ * only neutralises FTS5 *expression* syntax, it is not about SQL injection.
10
+ *
11
+ * Returns `null` when there is no searchable token (caller skips the FTS filter).
12
+ */
13
+ export const toMatchQuery = (text) => {
14
+ const tokens = text.split(/\s+/).filter((token) => token.length > 0);
15
+ if (tokens.length === 0)
16
+ return null;
17
+ return tokens.map((token) => `"${token.replaceAll('"', '""')}"`).join(' ');
18
+ };