@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,154 @@
1
+ import { ok } from 'neverthrow';
2
+ import { formatAppError } from '../../common/errors.js';
3
+ import { authenticateToken, revokeSignInByHash } from '../../controllers/auth/access-tokens.js';
4
+ import { ownerNeedsSetup } from '../../controllers/auth/owner.js';
5
+ import { redeemGrant, startGrant } from '../../controllers/auth/grants.js';
6
+ import { CheckKind, EffectKind, ObservationKind, REDEEM_ERROR_KIND, } from '../../models/auth/sign-in-flow.js';
7
+ import { nextStep } from '../../logic/auth/sign-in-flow.js';
8
+ import { PrincipalVia } from '../../models/auth/principal.js';
9
+ const E = EffectKind.enum;
10
+ const O = ObservationKind.enum;
11
+ const temporaryPage = (options) => {
12
+ let temporary = null;
13
+ return {
14
+ namedOrigin: () => temporary?.origin ?? options.origin(),
15
+ serve: async () => {
16
+ temporary = (await options.startPage?.()) ?? null;
17
+ return temporary?.origin ?? null;
18
+ },
19
+ close: async () => {
20
+ const server = temporary;
21
+ temporary = null;
22
+ await server?.close().catch(() => undefined);
23
+ },
24
+ canServe: options.startPage !== undefined,
25
+ };
26
+ };
27
+ const loadSavedToken = async (store, tolerateUnreadable) => {
28
+ const loaded = await store.load();
29
+ return loaded.isErr() && tolerateUnreadable ? ok(null) : loaded;
30
+ };
31
+ const checkResult = async ({ deps, run }, token) => {
32
+ const result = await run(() => authenticateToken(deps, deps.secrets.hashSecret(token), PrincipalVia.enum.stdio));
33
+ if (result.isErr())
34
+ return { kind: CheckKind.enum.failure };
35
+ return result.value === null
36
+ ? { kind: CheckKind.enum.invalid }
37
+ : { kind: CheckKind.enum.ok, principal: result.value };
38
+ };
39
+ const performCheckCredential = (ctx) => async (effect) => ({
40
+ kind: O.credential_checked,
41
+ source: effect.source,
42
+ token: effect.token,
43
+ result: await checkResult(ctx, effect.token),
44
+ });
45
+ const performLoadSaved = ({ store }) => async (effect) => (await loadSavedToken(store, effect.tolerateUnreadable)).match((token) => ({ kind: O.saved_loaded, purpose: effect.purpose, token }), () => ({ kind: O.saved_unreadable }));
46
+ const performClearSavedIf = ({ store }) => async (effect) => {
47
+ const loaded = await loadSavedToken(store, effect.tolerateUnreadable);
48
+ if (loaded.isErr())
49
+ return { kind: O.saved_unreadable };
50
+ if (loaded.value === effect.token)
51
+ await store.clear();
52
+ return { kind: O.saved_cleared, next: effect.next };
53
+ };
54
+ const performSaveCredential = ({ store }) => async (effect) => ({
55
+ kind: O.saved,
56
+ then: effect.then,
57
+ signedIn: effect.signedIn,
58
+ ok: await store.save(effect.signedIn.token),
59
+ });
60
+ const performRevokeCredential = ({ deps, run }) => async (effect) => {
61
+ const revoked = await run(() => revokeSignInByHash(deps, deps.secrets.hashSecret(effect.token)));
62
+ return {
63
+ kind: O.revoked,
64
+ reason: effect.reason,
65
+ token: effect.token,
66
+ ok: revoked.isOk(),
67
+ error: revoked.isErr() ? formatAppError(revoked.error) : null,
68
+ };
69
+ };
70
+ const performNamePage = ({ page }) => async (effect) => ({
71
+ kind: O.page_named,
72
+ purpose: effect.purpose,
73
+ origin: page.namedOrigin(),
74
+ canServe: page.canServe,
75
+ });
76
+ const performServePage = ({ page }) => async (effect) => ({
77
+ kind: O.page_served,
78
+ purpose: effect.purpose,
79
+ origin: await page.serve(),
80
+ });
81
+ const performStartGrant = ({ deps, run, page }) => async (effect) => {
82
+ const started = await run(() => startGrant(deps, effect.input)).then((result) => result, async (cause) => {
83
+ await page.close();
84
+ throw cause;
85
+ });
86
+ return started.isErr()
87
+ ? { kind: O.grant_failed, error: formatAppError(started.error) }
88
+ : {
89
+ kind: O.grant_started,
90
+ deviceCode: started.value.deviceCode,
91
+ userCode: started.value.userCode,
92
+ origin: effect.origin,
93
+ };
94
+ };
95
+ const performRedeemGrant = ({ deps, run }) => async (effect) => {
96
+ const redeemed = await run(() => redeemGrant(deps, effect.deviceCode));
97
+ return {
98
+ kind: O.redeemed,
99
+ then: effect.then,
100
+ result: redeemed.isErr() ? { kind: REDEEM_ERROR_KIND, error: formatAppError(redeemed.error) } : redeemed.value,
101
+ };
102
+ };
103
+ const performCheckOwner = ({ deps }) => async (effect) => ({
104
+ kind: O.owner_checked,
105
+ purpose: effect.purpose,
106
+ unclaimed: await ownerNeedsSetup(deps),
107
+ origin: effect.origin,
108
+ });
109
+ const performClosePage = ({ page }) => async () => {
110
+ await page.close();
111
+ return undefined;
112
+ };
113
+ const performWait = async (effect, hooks) => {
114
+ await hooks.wait(effect.ms);
115
+ return undefined;
116
+ };
117
+ const performPresent = async (effect, hooks) => {
118
+ hooks.present(effect.presentation);
119
+ return undefined;
120
+ };
121
+ const performersFor = (ctx) => ({
122
+ [E.check_credential]: performCheckCredential(ctx),
123
+ [E.load_saved]: performLoadSaved(ctx),
124
+ [E.clear_saved_if]: performClearSavedIf(ctx),
125
+ [E.save_credential]: performSaveCredential(ctx),
126
+ [E.revoke_credential]: performRevokeCredential(ctx),
127
+ [E.name_page]: performNamePage(ctx),
128
+ [E.serve_page]: performServePage(ctx),
129
+ [E.start_grant]: performStartGrant(ctx),
130
+ [E.redeem_grant]: performRedeemGrant(ctx),
131
+ [E.check_owner]: performCheckOwner(ctx),
132
+ [E.close_page]: performClosePage(ctx),
133
+ [E.wait]: performWait,
134
+ [E.present]: performPresent,
135
+ });
136
+ export const createSignInInterpreter = (options) => {
137
+ const page = temporaryPage(options);
138
+ const performers = performersFor({ deps: options.deps, run: options.run, store: options.store, page });
139
+ const perform = (effect, hooks) => performers[effect.kind](effect, hooks);
140
+ const performAll = async (effects, hooks) => {
141
+ const [effect, ...rest] = effects;
142
+ if (effect === undefined)
143
+ return undefined;
144
+ const answer = await perform(effect, hooks);
145
+ return (await performAll(rest, hooks)) ?? answer;
146
+ };
147
+ const drive = async (state, observation, config, hooks) => {
148
+ const step = nextStep(state, observation, config);
149
+ hooks.progress(step.state);
150
+ const answer = await performAll(step.effects, hooks);
151
+ return answer === undefined ? step.state : drive(step.state, answer, config, hooks);
152
+ };
153
+ return { drive, release: page.close };
154
+ };
@@ -0,0 +1,36 @@
1
+ import { prepareAuth } from '../auth.js';
2
+ import { version } from '../../common/build-version.js';
3
+ import { httpOrigin, LOCALHOST_NAME } from '../../common/net.js';
4
+ import { McpTransport } from '../../config.js';
5
+ import { AuthMode } from '../../models/auth/mode.js';
6
+ import { createRuntime } from '../runtime.js';
7
+ /** Lazy: Fastify and the whole route table load only when a login actually needs to serve the consent page. */
8
+ const loadServerModule = () => import('../http.js');
9
+ /**
10
+ * Where the browser goes when a sign-in has no honest page of its own to name — `patty login` (ADR-034 §6), and a
11
+ * stdio session whose sidecar is not serving a valid link: always a temporary app of THIS process — authentication
12
+ * required, no `PUBLIC_URL` — on a free loopback port, closed when the login ends. A server already running on
13
+ * `HOST:PORT` is deliberately not reused: a healthy `/api/health` proves it is PATTY, not that it opened this
14
+ * database, and a grant written here would never validate there.
15
+ */
16
+ export const startSignInServer = async (config, db) => {
17
+ const runtime = createRuntime(db, config);
18
+ const { auth } = await prepareAuth({
19
+ ...config,
20
+ PATTY_AUTH: AuthMode.enum.required,
21
+ PUBLIC_URL: undefined,
22
+ MCP_TRANSPORT: McpTransport.enum.http,
23
+ PATTY_HTTP: true,
24
+ }, db, runtime.authRunEffects);
25
+ const { buildHttpApp } = await loadServerModule();
26
+ const app = buildHttpApp(runtime, version, { logger: false, auth, trustProxy: config.TRUST_PROXY });
27
+ // Loopback only, but under the NAME `localhost`: the session cookie is keyed by host, not port, so on `127.0.0.1`
28
+ // this login would overwrite the cookie of any PATTY already open there and sign its dashboard out.
29
+ // Fastify binds `localhost` to both its IPv4 and IPv6 loopback addresses.
30
+ await app.listen({ port: 0, host: LOCALHOST_NAME }).catch(async (cause) => {
31
+ await app.close();
32
+ throw cause;
33
+ });
34
+ const { port } = app.server.address();
35
+ return { origin: httpOrigin(LOCALHOST_NAME, port), close: () => app.close() };
36
+ };
@@ -0,0 +1,23 @@
1
+ import { keychainSignInStore } from '../../diplomat/auth/sign-in-store.js';
2
+ import { dbIdOf, keychainAccount } from '../../logic/auth/keychain.js';
3
+ import { createSignInInterpreter } from './interpreter.js';
4
+ /** Lazy: Fastify and the route table load only when a sign-in actually has to serve the consent page. */
5
+ const loadSignInServerModule = () => import('./server.js');
6
+ /**
7
+ * Composition root: the sign-in interpreter for one profile of this database. The one place that derives the keychain
8
+ * account (profile + the database it belongs to), opens the keychain store and knows how to serve a temporary
9
+ * `/ui/connect` page — `composition/auth.ts` (stdio) and `composition/cli.ts` (`login`/`logout`) differ only in
10
+ * what they pass.
11
+ */
12
+ export const createSignInFor = (world, options) => {
13
+ const { config, db, deps, run } = world;
14
+ return createSignInInterpreter({
15
+ deps,
16
+ run,
17
+ store: keychainSignInStore(keychainAccount(options.profile, dbIdOf(deps.secrets.hashSecret(config.DB_PATH)))),
18
+ origin: options.origin,
19
+ startPage: options.canServePage
20
+ ? async () => (await loadSignInServerModule()).startSignInServer(config, db)
21
+ : undefined,
22
+ });
23
+ };
@@ -0,0 +1,69 @@
1
+ import { ok, safeTry } from 'neverthrow';
2
+ import { version } from '../common/build-version.js';
3
+ import { httpOrigin } from '../common/net.js';
4
+ import { connectStdio } from '../diplomat/mcp/stdio.js';
5
+ import { signInOrigin } from '../logic/auth/origin.js';
6
+ import { AuthMode } from '../models/auth/mode.js';
7
+ import { boot } from './boot.js';
8
+ import { loadHttpModule } from './lazy-modules.js';
9
+ const maybeStartSidecar = async (config, runtime, auth) => {
10
+ if (!config.PATTY_HTTP)
11
+ return null;
12
+ const { startHttpSidecar } = await loadHttpModule();
13
+ return startHttpSidecar(runtime, version, config.PORT, config.HOST, { auth, trustProxy: config.TRUST_PROXY });
14
+ };
15
+ const signInLink = (config) => {
16
+ let boundOrigin = null;
17
+ return {
18
+ origin: () => signInOrigin({
19
+ httpEnabled: config.PATTY_HTTP,
20
+ publicUrl: config.PUBLIC_URL,
21
+ boundOrigin,
22
+ host: config.HOST,
23
+ }),
24
+ bind: (origin) => {
25
+ boundOrigin = origin;
26
+ },
27
+ };
28
+ };
29
+ const stdioAuthFor = (config, stdio, linkOrigin) => stdio
30
+ ? {
31
+ mode: AuthMode.enum.required,
32
+ profile: config.PATTY_PROFILE,
33
+ envToken: config.PATTY_TOKEN,
34
+ signIn: (profile) => stdio.signIn(profile, linkOrigin),
35
+ }
36
+ : { mode: AuthMode.enum.disabled };
37
+ const closeLogged = (closing) => closing.catch((err) => console.error(err));
38
+ const shutdownOf = ({ server, session }, sidecar) => {
39
+ let shuttingDown = false;
40
+ return () => {
41
+ if (shuttingDown)
42
+ return;
43
+ shuttingDown = true;
44
+ void Promise.allSettled([
45
+ closeLogged(server.close()),
46
+ sidecar?.listening ? closeLogged(sidecar.app.close()) : Promise.resolve(),
47
+ session?.close(),
48
+ ]).finally(() => process.exit(0));
49
+ };
50
+ };
51
+ const shutDownOnDisconnect = (shutdown) => {
52
+ process.once('SIGINT', shutdown);
53
+ process.once('SIGTERM', shutdown);
54
+ process.stdin.once('end', shutdown);
55
+ process.stdin.once('close', shutdown);
56
+ };
57
+ export const runStdio = (config) => safeTry(async function* () {
58
+ const { runtime, prepared } = yield* boot(config);
59
+ const link = signInLink(config);
60
+ const connection = await connectStdio(runtime, version, stdioAuthFor(config, prepared.stdio, link.origin));
61
+ const sidecar = await maybeStartSidecar(config, runtime, prepared.auth);
62
+ if (sidecar?.listening) {
63
+ const boundOrigin = httpOrigin(config.HOST, sidecar.app.server.address().port);
64
+ link.bind(boundOrigin);
65
+ await prepared.issueAndAnnounceSetup(boundOrigin);
66
+ }
67
+ shutDownOnDisconnect(shutdownOf(connection, sidecar));
68
+ return ok(undefined);
69
+ });
package/dist/config.js ADDED
@@ -0,0 +1,136 @@
1
+ import { homedir } from 'node:os';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { z } from 'zod';
4
+ import { isLoopbackHost, LOOPBACK_HOST } from './common/net.js';
5
+ import { AuthMode, DEFAULT_AUTH_MODE } from './models/auth/mode.js';
6
+ import { DEFAULT_PROFILE, ProfileSchema } from './models/auth/sign-in.js';
7
+ import { DEMO_DB_KEY, DEMO_ENV_ON, DEMO_ENV_VAR, DEMO_PORT } from './models/demo/core.js';
8
+ import { EncryptionKey } from './models/encryption-key.js';
9
+ import { Locale } from './models/locale.js';
10
+ export const McpTransport = z.enum(['stdio', 'http']);
11
+ // Absolute default so the DB is always created in a stable, writable location
12
+ // regardless of the cwd when spawned by an MCP client (e.g. Claude Desktop).
13
+ const DATA_DIRECTORY = join(homedir(), '.patty');
14
+ const DEFAULT_DB_PATH = join(DATA_DIRECTORY, 'patty.db');
15
+ const OS_LOCALE_VARIABLES = ['LC_ALL', 'LC_MESSAGES', 'LANG'];
16
+ export const osLocale = (env = process.env) => OS_LOCALE_VARIABLES.map((name) => env[name]).find((value) => value) ?? Intl.DateTimeFormat().resolvedOptions().locale;
17
+ export const DEMO_DB_PATH = join(DATA_DIRECTORY, 'demo.db');
18
+ // One lock per OS user: the keychain entry it guards is per user, not per DB_PATH.
19
+ const DEFAULT_KEY_LOCK_PATH = join(DATA_DIRECTORY, 'db-key.lock');
20
+ // Deliberately NOT 3000/3001/8000/8080/etc — those are the most commonly used ports across
21
+ // Node/Fastify/React dev-server defaults, so picking one of them maximizes collision risk with
22
+ // other software on a typical dev machine. This value sits in IANA's dynamic/private range
23
+ // (49152-65535), which is never assigned to a registered service. This is the default for the
24
+ // published package; `npm run dev` overrides PORT back to the familiar 3001 (package.json), so
25
+ // a contributor's local dev instance never collides with an already-running installed instance.
26
+ const DEFAULT_PORT = 51737;
27
+ // `TRUST_PROXY=0` trusts zero proxy hops: no proxy.
28
+ const NO_PROXY_HOPS = 0;
29
+ /** Whether anything besides this machine can reach the instance: a non-loopback bind, or a reverse proxy
30
+ * configured in front of it (`PUBLIC_URL` names its external origin; `TRUST_PROXY` says to believe it). A
31
+ * proxy typically connects to a loopback bind, so `HOST` alone would call that instance private. Only used to
32
+ * refuse `PATTY_AUTH=disabled` on such an instance. */
33
+ export const isExposed = (env) => !isLoopbackHost(env.HOST) ||
34
+ env.PUBLIC_URL !== undefined ||
35
+ (env.TRUST_PROXY !== undefined && env.TRUST_PROXY !== false && env.TRUST_PROXY !== NO_PROXY_HOPS);
36
+ // An empty string (`PUBLIC_URL=` from a compose file or shell) means "unset", not "invalid".
37
+ const unsetWhenEmpty = (value) => (value === '' ? undefined : value);
38
+ const optionalEnv = (schema) => z.preprocess(unsetWhenEmpty, schema.optional());
39
+ // The external origin only — it is compared verbatim against the browser's `Origin` header (CSRF) and
40
+ // decides the cookie `Secure` flag, so a path or trailing slash would make both silently wrong.
41
+ const PublicUrl = z
42
+ .string()
43
+ .url()
44
+ .refine((value) => /^https?:\/\//.test(value) && new URL(value).origin === value, {
45
+ message: 'PUBLIC_URL must be an http(s) origin with no path or trailing slash, e.g. https://patty.example.com',
46
+ });
47
+ // Fastify's `trustProxy`: `true`/`false`, a hop count, or a comma-separated list of trusted
48
+ // addresses/CIDRs. Anything else is passed through for Fastify (proxy-addr) to interpret.
49
+ const HOP_COUNT = /^\d+$/;
50
+ const TrustProxy = z
51
+ .string()
52
+ .min(1)
53
+ .transform((value) => {
54
+ if (value === 'true')
55
+ return true;
56
+ if (value === 'false')
57
+ return false;
58
+ return HOP_COUNT.test(value) ? Number(value) : value;
59
+ });
60
+ const Env = z
61
+ .object({
62
+ // Unset: the demo's under PATTY_DEMO, so the demo never defaults to the real database.
63
+ DB_PATH: z
64
+ .string()
65
+ .refine(isAbsolute, {
66
+ message: `DB_PATH must be an absolute path — "~" is not expanded by Node. Use a full path, e.g. ${DEFAULT_DB_PATH}`,
67
+ })
68
+ .optional(),
69
+ PATTY_DB_KEY: EncryptionKey.optional(),
70
+ // File holding the key (e.g. a Docker secret at /run/secrets/patty_db_key) — keeps it out of
71
+ // `docker inspect`, unlike the env var (ADR-032).
72
+ PATTY_DB_KEY_FILE: z
73
+ .string()
74
+ .refine(isAbsolute, { message: 'PATTY_DB_KEY_FILE must be an absolute path' })
75
+ .optional(),
76
+ PATTY_LOCALE: Locale.optional(),
77
+ PORT: z.coerce.number().default(DEFAULT_PORT),
78
+ // Loopback by default: a wildcard bind is an explicit opt-in (a container needs it; ADR-032).
79
+ HOST: z.string().min(1).default(LOOPBACK_HOST),
80
+ // `required` everywhere, loopback included; `disabled` is an explicit, loopback-only opt-out.
81
+ PATTY_AUTH: z.preprocess(unsetWhenEmpty, AuthMode.default(DEFAULT_AUTH_MODE)),
82
+ // Which saved sign-in a stdio process uses, so two client configs on one machine can sign in as two users
83
+ // (ADR-034 §2); and the headless alternative to the browser sign-in — a personal access token in the env.
84
+ PATTY_PROFILE: z.preprocess(unsetWhenEmpty, ProfileSchema.default(DEFAULT_PROFILE)),
85
+ PATTY_TOKEN: optionalEnv(z.string()),
86
+ // External origin of this instance behind a reverse proxy — the CSRF expected origin, and https
87
+ // turns on the cookie `Secure` flag. Optional in Phase 1 (OAuth makes it mandatory in Phase 3).
88
+ PUBLIC_URL: optionalEnv(PublicUrl),
89
+ // Passed to Fastify so rate limiting sees the real client IP behind a reverse proxy.
90
+ TRUST_PROXY: optionalEnv(TrustProxy),
91
+ [DEMO_ENV_VAR]: z
92
+ .string()
93
+ .optional()
94
+ .transform((v) => v === DEMO_ENV_ON),
95
+ MCP_TRANSPORT: McpTransport.default(McpTransport.enum.stdio),
96
+ // HTTP sidecar alongside stdio MCP (ADR-013 Decision 7) — on by default: the dashboard/REST
97
+ // surface is a core feature, not an add-on. A bind failure is caught and non-fatal (stdio
98
+ // keeps working regardless) — that's a resilience fallback, not the normal state. Set
99
+ // PATTY_HTTP=false to opt out and skip starting it entirely.
100
+ PATTY_HTTP: z
101
+ .string()
102
+ .optional()
103
+ .transform((v) => v !== 'false'),
104
+ // Per-class staleness windows for currency_rates (ADR-026 Phase 2) — crypto moves fast enough to
105
+ // need a much tighter window than fiat; both configurable rather than hardcoded in logic/.
106
+ FIAT_RATE_STALE_HOURS: z.coerce.number().positive().default(24),
107
+ CRYPTO_RATE_STALE_HOURS: z.coerce.number().positive().default(1),
108
+ })
109
+ .refine((env) => !(env.PATTY_DB_KEY && env.PATTY_DB_KEY_FILE), {
110
+ path: ['PATTY_DB_KEY_FILE'],
111
+ message: 'PATTY_DB_KEY and PATTY_DB_KEY_FILE are both set — the key source is ambiguous; set only one',
112
+ })
113
+ .refine((env) => !(env.PATTY_DEMO && (env.PATTY_DB_KEY || env.PATTY_DB_KEY_FILE)), {
114
+ path: [DEMO_ENV_VAR],
115
+ message: `${DEMO_ENV_VAR} fixes the database key — do not also set PATTY_DB_KEY or PATTY_DB_KEY_FILE`,
116
+ })
117
+ .transform((env) => ({
118
+ ...env,
119
+ DB_PATH: env.DB_PATH ?? (env.PATTY_DEMO ? DEMO_DB_PATH : DEFAULT_DB_PATH),
120
+ KEY_LOCK_PATH: DEFAULT_KEY_LOCK_PATH,
121
+ }))
122
+ .transform((env) => env.PATTY_DEMO ? { ...env, PATTY_DB_KEY: DEMO_DB_KEY, PATTY_AUTH: AuthMode.enum.disabled } : env)
123
+ .refine((env) => !(env.PATTY_AUTH === AuthMode.enum.disabled && isExposed(env)), {
124
+ path: ['PATTY_AUTH'],
125
+ message: 'PATTY_AUTH=disabled is only allowed on a loopback HOST (127.0.0.0/8, ::1, localhost) with no PUBLIC_URL ' +
126
+ 'or TRUST_PROXY — the API would be unauthenticated to everyone who can reach it (directly or through a ' +
127
+ 'reverse proxy). Remove PATTY_AUTH (it defaults to required) or drop the exposure.',
128
+ });
129
+ export const loadConfig = (env = process.env) => Env.parse(env);
130
+ /** Built from scratch, never from the process environment. */
131
+ export const demoConfig = (dbPath) => loadConfig({
132
+ DB_PATH: dbPath,
133
+ PORT: String(DEMO_PORT),
134
+ MCP_TRANSPORT: McpTransport.enum.http,
135
+ [DEMO_ENV_VAR]: DEMO_ENV_ON,
136
+ });
@@ -0,0 +1,88 @@
1
+ import { ok, safeTry } from 'neverthrow';
2
+ import * as R from 'remeda';
3
+ import { guard, okOr } from '../../common/result.js';
4
+ import { assertNonCreditType, changesPinnedField, filterByType, guardPinnedFields, isRename, isUnreferenced, mergeAccountPatch, withTypeLabel, } from '../../logic/account.js';
5
+ import { computeBalance, computeProjectedBalance } from '../../logic/balance.js';
6
+ import { consolidateNetWorth, valueAccount } from '../../logic/currency-rate.js';
7
+ import { resolveBaseCurrency } from '../../logic/locale.js';
8
+ import { decimalsLookup } from '../../logic/money.js';
9
+ import * as persistence from '../../logic/persistence.js';
10
+ import { resolveByName } from '../../logic/resolve.js';
11
+ import { accountErrors, ACCOUNT_ENTITY_TAG, } from '../../models/account.js';
12
+ import { notFound } from '../../models/error.js';
13
+ import { Locale } from '../../models/locale.js';
14
+ import { Remedy } from '../../models/remedy.js';
15
+ import { resolveAccountRef, resolutionToResult } from '../resolve.js';
16
+ const assertNameAvailable = async (deps, name) => !(await deps.accounts.findByName(name));
17
+ export const listAccounts = async (deps, type) => {
18
+ const [locale, all] = await Promise.all([deps.locale(), deps.accounts.list()]);
19
+ return R.pipe(all, R.filter(filterByType(type)), R.map(withTypeLabel(locale)));
20
+ };
21
+ export const createAccount = (deps, input) => safeTry(async function* () {
22
+ yield* guard(assertNonCreditType(input.type), accountErrors.creditRejected(Remedy.enum.create_credit_card));
23
+ yield* guard(await assertNameAvailable(deps, input.name), accountErrors.duplicateName(input.name));
24
+ const account = { id: deps.newId(), ...input };
25
+ const persist = [persistence.insert({ entity: ACCOUNT_ENTITY_TAG, model: account })];
26
+ return ok({ persist, response: account });
27
+ });
28
+ export const getAccountBalances = (deps, filter) => safeTry(async function* () {
29
+ const candidates = await listAccounts(deps, filter?.type);
30
+ const accounts = filter?.account
31
+ ? [yield* resolutionToResult(resolveByName(candidates, filter.account), 'account')]
32
+ : candidates;
33
+ const balances = await Promise.all(accounts.map(async (account) => {
34
+ const parts = await deps.accounts.balanceParts(account.id);
35
+ const balance = computeBalance({ initialBalance: account.initialBalance, ...parts });
36
+ const projectedBalance = filter?.projectedAsOf
37
+ ? computeProjectedBalance(balance, await deps.transactions.pendingBalanceParts(account.id, filter.projectedAsOf))
38
+ : undefined;
39
+ return { ...account, ...parts, balance, projectedBalance };
40
+ }));
41
+ const [settingsRow, currencies, rates] = await Promise.all([
42
+ deps.settings.getLocale(),
43
+ deps.currencies.list(),
44
+ deps.currencyRates.list(),
45
+ ]);
46
+ const baseCurrency = resolveBaseCurrency(settingsRow?.baseCurrency, settingsRow?.locale ?? Locale.enum.en);
47
+ const baseDecimals = decimalsLookup(currencies)(baseCurrency);
48
+ const now = deps.clock();
49
+ const valued = balances.map((b) => valueAccount(b, baseCurrency, rates, now, baseDecimals, deps.rateStaleness));
50
+ const consolidatedNetWorth = consolidateNetWorth(valued, baseCurrency, baseDecimals);
51
+ return ok({ balances: valued, consolidatedNetWorth });
52
+ });
53
+ export const deleteAccount = (deps, name) => safeTry(async function* () {
54
+ const account = yield* resolveAccountRef(deps, name);
55
+ yield* guard(assertNonCreditType(account.type), accountErrors.creditRejected(Remedy.enum.delete_credit_card));
56
+ const refs = await deps.accounts.countReferences(account.id);
57
+ yield* guard(isUnreferenced(refs), accountErrors.inUse(account.name, refs));
58
+ const raw = yield* okOr(await deps.accounts.findRawById(account.id), notFound('account', account.id, []));
59
+ const persist = [persistence.remove({ entity: ACCOUNT_ENTITY_TAG, id: raw.id, version: raw.version })];
60
+ return ok({ persist, response: { deleted: true } });
61
+ });
62
+ const guardRenameAvailable = (deps, account, newName) => safeTry(async function* () {
63
+ if (isRename(account.name, newName)) {
64
+ yield* guard(await assertNameAvailable(deps, newName), accountErrors.duplicateName(newName));
65
+ }
66
+ return ok(undefined);
67
+ });
68
+ const guardPinnedFieldChange = (deps, accountId, input) => safeTry(async function* () {
69
+ if (changesPinnedField(input)) {
70
+ yield* guardPinnedFields(await deps.accounts.countReferences(accountId), input);
71
+ }
72
+ return ok(undefined);
73
+ });
74
+ export const updateAccount = (deps, input) => safeTry(async function* () {
75
+ const account = yield* resolveAccountRef(deps, input.name);
76
+ yield* guard(assertNonCreditType(account.type), accountErrors.creditRejected(Remedy.enum.update_credit_card));
77
+ yield* guard(assertNonCreditType(input.type), accountErrors.creditRejected(Remedy.enum.create_credit_card));
78
+ yield* guardRenameAvailable(deps, account, input.newName);
79
+ yield* guardPinnedFieldChange(deps, account.id, input);
80
+ const raw = yield* okOr(await deps.accounts.findRawById(account.id), notFound('account', account.id, []));
81
+ const entity = mergeAccountPatch(raw, input);
82
+ const locale = await deps.locale();
83
+ const persist = R.isDeepEqual(entity, raw)
84
+ ? []
85
+ : [persistence.update({ entity: ACCOUNT_ENTITY_TAG, model: entity })];
86
+ const response = withTypeLabel(R.omit(entity, ['version']), locale);
87
+ return ok({ persist, response });
88
+ });
@@ -0,0 +1,119 @@
1
+ import { ok, safeTry } from 'neverthrow';
2
+ import * as R from 'remeda';
3
+ import { guard, okOr } from '../../common/result.js';
4
+ import { assertNonCreditType, guardTransferMutability, isAccountOwnedType } from '../../logic/account.js';
5
+ import { resolveCurrency } from '../../logic/money.js';
6
+ import { resolveMerchantCorrection, withMerchant, withMerchantLearning } from '../../logic/merchant.js';
7
+ import * as persistence from '../../logic/persistence.js';
8
+ import { toIsoDate } from '../../logic/period.js';
9
+ import { overlayResolvedTags } from '../../logic/tag.js';
10
+ import { addLocalizedLabels, assertExclusiveCategorySubCategory, buildTransactionView, buildUpsertResult, defaultStatementLines, mergePatch, planNewTransaction, } from '../../logic/transaction.js';
11
+ import { accountErrors, } from '../../models/account.js';
12
+ import { DELETE_TRANSACTION_CONFIRM_HINT, TRANSACTION_ENTITY_TAG, transactionErrors, MovementType, } from '../../models/transaction.js';
13
+ import { Remedy } from '../../models/remedy.js';
14
+ import { matchCandidatesFor, resolveAccountRef, resolveDecimals, resolveLegAccounts, resolveTagLinks, } from '../resolve.js';
15
+ import { decideTransactionUpdate, resolveCategorySelection } from '../transaction/core.js';
16
+ const assertAccountOwnedLegs = (deps, tx) => resolveLegAccounts(deps, tx).map((legs) => legs.every((account) => isAccountOwnedType(account.type)));
17
+ const resolveFundingAccount = (deps, ref) => safeTry(async function* () {
18
+ if (!R.isNonNullish(ref))
19
+ return ok(null);
20
+ const account = yield* resolveAccountRef(deps, ref);
21
+ yield* guard(assertNonCreditType(account.type), accountErrors.creditPostRejected);
22
+ return ok(account);
23
+ });
24
+ const planAccountMovement = (deps, input, type, source) => safeTry(async function* () {
25
+ yield* guard(assertExclusiveCategorySubCategory(input), transactionErrors.exclusiveCategorySubCategory);
26
+ const account = yield* resolveFundingAccount(deps, input.account);
27
+ const currency = resolveCurrency(account, input);
28
+ const categorySelection = yield* resolveCategorySelection(deps, input, type);
29
+ return ok(planNewTransaction({
30
+ id: deps.newId(),
31
+ today: toIsoDate(deps.clock()),
32
+ input,
33
+ type,
34
+ source,
35
+ currency,
36
+ decimals: await resolveDecimals(deps, currency),
37
+ funding: { refs: { accountId: account?.id }, sourceId: account?.id },
38
+ categorySelection,
39
+ candidates: await matchCandidatesFor(deps, input.description, categorySelection),
40
+ keepsUnmatchedMerchant: true,
41
+ }));
42
+ });
43
+ const addAccountMovement = (deps, input, type, source) => safeTry(async function* () {
44
+ const { entity, classification, idempotencyKey } = yield* planAccountMovement(deps, input, type, source);
45
+ const locale = await deps.locale();
46
+ const tagLinks = await resolveTagLinks(deps, entity.id, input.tags);
47
+ const persist = [
48
+ ...withMerchant([persistence.insert({ entity: TRANSACTION_ENTITY_TAG, model: entity, idempotencyKey })], entity.refs.merchantKey),
49
+ ...(tagLinks ? [tagLinks.persistable] : []),
50
+ ];
51
+ const response = (outcomes) => {
52
+ const result = buildUpsertResult(outcomes, classification, locale);
53
+ return tagLinks
54
+ ? { ...result, transaction: overlayResolvedTags(result.transaction, tagLinks.tags, outcomes) }
55
+ : result;
56
+ };
57
+ return ok({ persist, response });
58
+ });
59
+ export const addAccountExpense = (deps, input, source) => addAccountMovement(deps, input, MovementType.enum.expense, source);
60
+ export const addAccountIncome = (deps, input, source) => addAccountMovement(deps, input, MovementType.enum.income, source);
61
+ export const importAccountStatement = async (deps, input, source) => {
62
+ const lines = defaultStatementLines(toIsoDate(deps.clock()), input.items, input.rawInput);
63
+ const localePromise = deps.locale();
64
+ const currenciesPromise = deps.currencies.list();
65
+ const cachedDeps = {
66
+ ...deps,
67
+ locale: () => localePromise,
68
+ currencies: { ...deps.currencies, list: () => currenciesPromise },
69
+ };
70
+ const flowFor = (line) => () => {
71
+ const movement = { ...R.omit(line, ['type']), account: input.account };
72
+ return line.type === MovementType.enum.expense
73
+ ? addAccountExpense(cachedDeps, movement, source)
74
+ : addAccountIncome(cachedDeps, movement, source);
75
+ };
76
+ return { lines, flowFor };
77
+ };
78
+ export const updateAccountTransaction = (deps, input) => safeTry(async function* () {
79
+ const existing = yield* okOr(await deps.transactions.getById(input.id), transactionErrors.notFound(input.id));
80
+ const isAccountOwned = yield* assertAccountOwnedLegs(deps, existing);
81
+ yield* guard(isAccountOwned, transactionErrors.wrongOperation(Remedy.enum.update_card_transaction));
82
+ yield* guardTransferMutability(existing, input);
83
+ const { account, categorySelection } = yield* decideTransactionUpdate(deps, input, existing);
84
+ const entity = mergePatch(existing, input, categorySelection, { account });
85
+ const locale = await deps.locale();
86
+ const merchantCorrection = resolveMerchantCorrection(existing, entity.refs.categoryId);
87
+ const tagLinks = await resolveTagLinks(deps, entity.id, input.tags);
88
+ const persist = [
89
+ ...withMerchantLearning([persistence.update({ entity: TRANSACTION_ENTITY_TAG, model: { ...entity, version: existing.version } })], merchantCorrection),
90
+ ...(tagLinks ? [tagLinks.persistable] : []),
91
+ ];
92
+ const response = (outcomes) => {
93
+ const result = buildTransactionView(outcomes, locale);
94
+ return tagLinks ? overlayResolvedTags(result, tagLinks.tags, outcomes) : result;
95
+ };
96
+ return ok({ persist, response });
97
+ });
98
+ export const deleteAccountTransaction = (deps, input) => safeTry(async function* () {
99
+ const existing = yield* okOr(await deps.transactions.getById(input.id), transactionErrors.notFound(input.id));
100
+ const isAccountOwned = yield* assertAccountOwnedLegs(deps, existing);
101
+ yield* guard(isAccountOwned, transactionErrors.wrongOperation(Remedy.enum.delete_card_transaction));
102
+ const locale = await deps.locale();
103
+ const labeled = addLocalizedLabels(existing, locale);
104
+ if (!input.confirm) {
105
+ return ok({
106
+ persist: [],
107
+ response: {
108
+ deleted: false,
109
+ dryRun: true,
110
+ wouldDelete: labeled,
111
+ hint: DELETE_TRANSACTION_CONFIRM_HINT,
112
+ },
113
+ });
114
+ }
115
+ const persist = [
116
+ persistence.remove({ entity: TRANSACTION_ENTITY_TAG, id: existing.id, version: existing.version }),
117
+ ];
118
+ return ok({ persist, response: { deleted: true, transaction: labeled } });
119
+ });
@@ -0,0 +1,34 @@
1
+ import { ok, safeTry } from 'neverthrow';
2
+ import { guard } from '../../common/result.js';
3
+ import { areDifferentAccounts, assertCurrencyMatch, assertNonCreditType, planTransfer } from '../../logic/account.js';
4
+ import * as persistence from '../../logic/persistence.js';
5
+ import { toIsoDate } from '../../logic/period.js';
6
+ import { buildUpsertResult } from '../../logic/transaction.js';
7
+ import { accountErrors } from '../../models/account.js';
8
+ import { TRANSACTION_ENTITY_TAG, } from '../../models/transaction.js';
9
+ import { resolveAccountRef, resolveDecimals } from '../resolve.js';
10
+ const validateTransferAccounts = (from, to) => safeTry(function* () {
11
+ yield* guard(assertNonCreditType(from.type), accountErrors.creditTransferFromRejected(from.name));
12
+ yield* guard(assertNonCreditType(to.type), accountErrors.creditTransferToRejected(to.name));
13
+ yield* guard(areDifferentAccounts(from, to), accountErrors.sameAccount);
14
+ yield* guard(assertCurrencyMatch(from, to), accountErrors.crossCurrencyTransfer(from, to));
15
+ return ok(undefined);
16
+ });
17
+ export const createTransfer = (deps, input, source) => safeTry(async function* () {
18
+ const from = yield* resolveAccountRef(deps, input.from);
19
+ const to = yield* resolveAccountRef(deps, input.to);
20
+ yield* validateTransferAccounts(from, to);
21
+ const { entity, idempotencyKey } = planTransfer({
22
+ id: deps.newId(),
23
+ today: toIsoDate(deps.clock()),
24
+ input,
25
+ from,
26
+ to,
27
+ source,
28
+ decimals: await resolveDecimals(deps, from.currency),
29
+ });
30
+ const locale = await deps.locale();
31
+ const persist = [persistence.insert({ entity: TRANSACTION_ENTITY_TAG, model: entity, idempotencyKey })];
32
+ const response = buildUpsertResult(undefined, locale);
33
+ return ok({ persist, response });
34
+ });