@rfc0/patty 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +493 -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 +1716 -0
  449. package/ui/dashboards/cards.html +4032 -0
  450. package/ui/dashboards/categories.html +4694 -0
  451. package/ui/dashboards/comparative.html +2464 -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 +2517 -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,226 @@
1
+ import { z } from 'zod';
2
+ import * as accountAdapters from '../../../adapters/accounts.js';
3
+ import * as transactionAdapters from '../../../adapters/transactions.js';
4
+ import { createAccount, deleteAccount, getAccountBalances, listAccounts, updateAccount, } from '../../../controllers/account/account.js';
5
+ import { addAccountExpense, addAccountIncome, deleteAccountTransaction, importAccountStatement, updateAccountTransaction, } from '../../../controllers/account/transaction.js';
6
+ import { buildBulkResult } from '../../../controllers/transaction/bulk.js';
7
+ import { AccountBalancesResultSchema, AccountSchema } from '../../../models/account.js';
8
+ import { TransactionSource, TransactionViewSchema } from '../../../models/transaction.js';
9
+ import * as wireInAccounts from '../../../wire/in/accounts.js';
10
+ import { DeletedOut } from '../../../wire/out/common.js';
11
+ import { BulkResultOut, CreateTransactionOut, DeleteTransactionOut } from '../../../wire/out/transactions.js';
12
+ import { REMEDY_ROUTE } from '../remedy.js';
13
+ import { jsonBody, okResponse } from '../openapi.js';
14
+ import { conflict409, confirmQuery, idParam, invalidQueryResponse, isConfirmed, nameParam, notFound404, parse, parseOrIssue, pathParam, send, sendUpsert, validation422, } from '../respond.js';
15
+ import { READ_SCOPE, WRITE_SCOPE } from '../../../models/auth/scope.js';
16
+ const ACCOUNTS_TAG = 'Accounts';
17
+ const INVALID_ACCOUNT_TYPE_ISSUE = 'invalid type';
18
+ const listAccountsRoute = {
19
+ method: 'get',
20
+ scope: READ_SCOPE,
21
+ path: '/api/accounts',
22
+ tags: [ACCOUNTS_TAG],
23
+ summary: 'List accounts',
24
+ request: { query: wireInAccounts.AccountsQuerySchema },
25
+ responses: { 200: okResponse('Accounts', z.array(AccountSchema)), 422: validation422 },
26
+ handler: async (req, reply, scope) => {
27
+ const { deps } = scope();
28
+ const query = parseOrIssue(wireInAccounts.AccountsQuerySchema, req.query, reply, INVALID_ACCOUNT_TYPE_ISSUE);
29
+ if (!query)
30
+ return reply;
31
+ return reply.send(await listAccounts(deps, query.type));
32
+ },
33
+ };
34
+ const getAccountBalancesRoute = {
35
+ method: 'get',
36
+ scope: READ_SCOPE,
37
+ path: '/api/accounts/balances',
38
+ tags: [ACCOUNTS_TAG],
39
+ summary: 'Get account balances',
40
+ request: { query: wireInAccounts.AccountBalancesQuerySchema },
41
+ responses: {
42
+ 200: okResponse('Account balances + consolidated net worth', AccountBalancesResultSchema),
43
+ 404: notFound404,
44
+ 409: conflict409,
45
+ 422: validation422,
46
+ },
47
+ handler: async (req, reply, scope) => {
48
+ const { deps } = scope();
49
+ const query = wireInAccounts.AccountBalancesQuerySchema.safeParse(req.query);
50
+ if (!query.success)
51
+ return invalidQueryResponse(reply);
52
+ return send(reply, await getAccountBalances(deps, query.data));
53
+ },
54
+ };
55
+ const createAccountRoute = {
56
+ method: 'post',
57
+ scope: WRITE_SCOPE,
58
+ path: '/api/accounts',
59
+ tags: [ACCOUNTS_TAG],
60
+ summary: 'Create account',
61
+ request: { body: jsonBody(wireInAccounts.CreateAccountSchema) },
62
+ responses: { 201: okResponse('Account created', AccountSchema), 409: conflict409, 422: validation422 },
63
+ handler: async (req, reply, scope) => {
64
+ const { deps, runEffects } = scope();
65
+ const wireIn = parse(wireInAccounts.CreateAccountSchema, req.body, reply);
66
+ if (!wireIn)
67
+ return reply;
68
+ const flow = () => createAccount(deps, accountAdapters.createWireInToModel(wireIn)).map(accountAdapters.outcomeToDb);
69
+ return send(reply, await runEffects(flow), 201);
70
+ },
71
+ };
72
+ const updateAccountRoute = {
73
+ method: 'patch',
74
+ scope: WRITE_SCOPE,
75
+ path: '/api/accounts/:name',
76
+ tags: [ACCOUNTS_TAG],
77
+ summary: 'Update account',
78
+ request: { params: nameParam, body: jsonBody(wireInAccounts.UpdateAccountSchema.omit({ name: true })) },
79
+ responses: {
80
+ 200: okResponse('Account updated', AccountSchema),
81
+ 404: notFound404,
82
+ 409: conflict409,
83
+ 422: validation422,
84
+ },
85
+ handler: async (req, reply, scope) => {
86
+ const { deps, runEffects } = scope();
87
+ const name = pathParam(req, 'name');
88
+ const wireIn = parse(wireInAccounts.UpdateAccountSchema, { ...(req.body ?? {}), name }, reply);
89
+ if (!wireIn)
90
+ return reply;
91
+ const flow = () => updateAccount(deps, accountAdapters.updateWireInToModel(wireIn)).map(accountAdapters.outcomeToDb);
92
+ return send(reply, await runEffects(flow));
93
+ },
94
+ };
95
+ const deleteAccountRoute = {
96
+ method: 'delete',
97
+ scope: WRITE_SCOPE,
98
+ path: '/api/accounts/:name',
99
+ tags: [ACCOUNTS_TAG],
100
+ summary: 'Delete account',
101
+ request: { params: nameParam },
102
+ responses: {
103
+ 200: okResponse('Account deleted', DeletedOut),
104
+ 404: notFound404,
105
+ 409: conflict409,
106
+ 422: validation422,
107
+ },
108
+ handler: async (req, reply, scope) => {
109
+ const { deps, runEffects } = scope();
110
+ const flow = () => deleteAccount(deps, pathParam(req, 'name')).map(accountAdapters.outcomeToDb);
111
+ return send(reply, await runEffects(flow));
112
+ },
113
+ };
114
+ const movementResponses = (replay, created) => ({
115
+ 200: okResponse(replay, CreateTransactionOut),
116
+ 201: okResponse(created, CreateTransactionOut),
117
+ 404: notFound404,
118
+ 409: conflict409,
119
+ 422: validation422,
120
+ });
121
+ /** Shared by the expense and income routes — identical aside from which movement the controller records. */
122
+ const recordMovement = (record) => async (req, reply, scope) => {
123
+ const { deps, runEffects } = scope();
124
+ const wireIn = parse(wireInAccounts.AddAccountMovementSchema, req.body, reply);
125
+ if (!wireIn)
126
+ return reply;
127
+ const model = accountAdapters.addAccountMovementWireInToModel(wireIn);
128
+ const flow = () => record(deps, model, TransactionSource.enum.rest).map(transactionAdapters.outcomeToDb);
129
+ return sendUpsert(reply, (await runEffects(flow)).map(transactionAdapters.createResultToWireOut));
130
+ };
131
+ const addAccountExpenseRoute = {
132
+ method: 'post',
133
+ scope: WRITE_SCOPE,
134
+ path: '/api/accounts/expenses',
135
+ tags: [ACCOUNTS_TAG],
136
+ summary: 'Add an account expense',
137
+ request: { body: jsonBody(wireInAccounts.AddAccountMovementSchema) },
138
+ responses: movementResponses('Existing expense returned (idempotent replay)', 'Expense recorded'),
139
+ handler: recordMovement(addAccountExpense),
140
+ };
141
+ const addAccountIncomeRoute = {
142
+ method: 'post',
143
+ scope: WRITE_SCOPE,
144
+ path: '/api/accounts/income',
145
+ tags: [ACCOUNTS_TAG],
146
+ summary: 'Add account income',
147
+ request: { body: jsonBody(wireInAccounts.AddAccountMovementSchema) },
148
+ responses: movementResponses('Existing income returned (idempotent replay)', 'Income recorded'),
149
+ handler: recordMovement(addAccountIncome),
150
+ };
151
+ const importAccountStatementRoute = {
152
+ method: 'post',
153
+ scope: WRITE_SCOPE,
154
+ path: '/api/accounts/statement',
155
+ tags: [ACCOUNTS_TAG],
156
+ summary: 'Import an account statement',
157
+ request: { body: jsonBody(wireInAccounts.ImportAccountStatementSchema) },
158
+ responses: { 201: okResponse('Import result', BulkResultOut), 422: validation422 },
159
+ // Orchestration (plan → run each line → bulk result) that belongs in a controller; kept as one named step here
160
+ // until the controllers can hand back the adapted flow (the adapters are the edge's).
161
+ handler: async (req, reply, scope) => {
162
+ const { deps, runEffectsSequence } = scope();
163
+ const wireIn = parse(wireInAccounts.ImportAccountStatementSchema, req.body, reply);
164
+ if (!wireIn)
165
+ return reply;
166
+ const plan = await importAccountStatement(deps, accountAdapters.importAccountStatementWireInToModel(wireIn), TransactionSource.enum.import);
167
+ const outcomes = await runEffectsSequence(plan.lines, (line) => () => plan.flowFor(line)().map(transactionAdapters.outcomeToDb));
168
+ return reply.status(201).send(transactionAdapters.bulkResultToWireOut(buildBulkResult(outcomes, plan.lines)));
169
+ },
170
+ };
171
+ const updateAccountTransactionRoute = {
172
+ ...REMEDY_ROUTE.update_account_transaction,
173
+ scope: WRITE_SCOPE,
174
+ tags: [ACCOUNTS_TAG],
175
+ summary: 'Update an account transaction',
176
+ request: {
177
+ params: idParam,
178
+ body: jsonBody(wireInAccounts.UpdateAccountTransactionSchema.omit({ id: true })),
179
+ },
180
+ responses: {
181
+ 200: okResponse('Transaction updated', TransactionViewSchema),
182
+ 404: notFound404,
183
+ 409: conflict409,
184
+ 422: validation422,
185
+ },
186
+ handler: async (req, reply, scope) => {
187
+ const { deps, runEffects } = scope();
188
+ const id = pathParam(req, 'id');
189
+ const wireIn = parse(wireInAccounts.UpdateAccountTransactionSchema, { ...req.body, id }, reply);
190
+ if (!wireIn)
191
+ return reply;
192
+ const model = accountAdapters.updateAccountTransactionWireInToModel(wireIn);
193
+ const flow = () => updateAccountTransaction(deps, model).map(transactionAdapters.outcomeToDb);
194
+ return send(reply, await runEffects(flow));
195
+ },
196
+ };
197
+ const deleteAccountTransactionRoute = {
198
+ ...REMEDY_ROUTE.delete_account_transaction,
199
+ scope: WRITE_SCOPE,
200
+ tags: [ACCOUNTS_TAG],
201
+ summary: 'Delete an account transaction',
202
+ request: { params: idParam, query: confirmQuery },
203
+ responses: {
204
+ 200: okResponse('Deleted, or dry-run preview when confirm is omitted', DeleteTransactionOut),
205
+ 404: notFound404,
206
+ 422: validation422,
207
+ },
208
+ handler: async (req, reply, scope) => {
209
+ const { deps, runEffects } = scope();
210
+ const input = { id: pathParam(req, 'id'), confirm: isConfirmed(req) };
211
+ const flow = () => deleteAccountTransaction(deps, input).map(transactionAdapters.outcomeToDb);
212
+ return send(reply, (await runEffects(flow)).map(transactionAdapters.deleteResultToWireOut));
213
+ },
214
+ };
215
+ export const accountRoutes = [
216
+ listAccountsRoute,
217
+ getAccountBalancesRoute,
218
+ createAccountRoute,
219
+ updateAccountRoute,
220
+ deleteAccountRoute,
221
+ addAccountExpenseRoute,
222
+ addAccountIncomeRoute,
223
+ importAccountStatementRoute,
224
+ updateAccountTransactionRoute,
225
+ deleteAccountTransactionRoute,
226
+ ];
@@ -0,0 +1,28 @@
1
+ import { aggregateSpending } from '../../../controllers/aggregate.js';
2
+ import { AggregateResultSchema } from '../../../models/aggregate.js';
3
+ import { AggregateSpendingInputSchema } from '../../../wire/in/aggregate.js';
4
+ import { okResponse } from '../openapi.js';
5
+ import { conflict409, notFound404, parse, send, validation422 } from '../respond.js';
6
+ import { READ_SCOPE } from '../../../models/auth/scope.js';
7
+ const AGGREGATE_TAG = 'Aggregate';
8
+ const aggregateSpendingRoute = {
9
+ method: 'get',
10
+ scope: READ_SCOPE,
11
+ path: '/api/aggregate',
12
+ tags: [AGGREGATE_TAG],
13
+ summary: 'Aggregate spending',
14
+ request: { query: AggregateSpendingInputSchema },
15
+ responses: {
16
+ 200: okResponse('Aggregated spending', AggregateResultSchema),
17
+ 404: notFound404,
18
+ 409: conflict409,
19
+ 422: validation422,
20
+ },
21
+ handler: async (req, reply, scope) => {
22
+ const wireIn = parse(AggregateSpendingInputSchema, req.query, reply);
23
+ if (!wireIn)
24
+ return reply;
25
+ return send(reply, await aggregateSpending(scope().deps, wireIn));
26
+ },
27
+ };
28
+ export const aggregateRoutes = [aggregateSpendingRoute];
@@ -0,0 +1,105 @@
1
+ import { claimOwner, ownerNeedsSetup, startsAtSetup } from '../../../controllers/auth/owner.js';
2
+ import { login, logout } from '../../../controllers/auth/session.js';
3
+ import { httpStatus } from '../../../common/errors.js';
4
+ import { authErrors } from '../../../models/auth/errors.js';
5
+ import { AUTH_MESSAGES } from '../../../models/auth/message.js';
6
+ import { DEFAULT_LANDING_PATH } from '../../../models/auth/origin.js';
7
+ import { validation } from '../../../models/error.js';
8
+ import { LoginFormSchema, NextQuerySchema, SetupFormSchema } from '../../../wire/in/auth.js';
9
+ import { replyError } from '../respond.js';
10
+ import { renderLoginPage, renderSetupPage } from '../auth-pages.js';
11
+ import { LOGIN_PATH, LOGOUT_PATH, SEE_OTHER, SETUP_PATH } from '../auth-paths.js';
12
+ import { addFormParser, FORM_BODY_LIMIT_BYTES, page } from '../form-pages.js';
13
+ import { clearedSessionCookie, readCookie, SESSION_COOKIE_NAME, sessionCookie } from '../cookies.js';
14
+ import { createAttemptLimiter } from '../rate-limiter.js';
15
+ const statusOf = (error) => httpStatus(error);
16
+ const RATE_LIMITED_STATUS = statusOf(authErrors.rateLimited);
17
+ // An unparsable form is the same "validation" failure every other boundary reports.
18
+ const INVALID_FORM_STATUS = statusOf(validation([]));
19
+ const messageFor = (e) => {
20
+ switch (e.code) {
21
+ case 'invalid_credentials':
22
+ return AUTH_MESSAGES.invalidCredentials;
23
+ case 'invalid_setup_code':
24
+ return AUTH_MESSAGES.invalidSetupCode;
25
+ case 'setup_unavailable':
26
+ return AUTH_MESSAGES.setupUnavailable;
27
+ case 'username_taken':
28
+ return AUTH_MESSAGES.usernameTaken;
29
+ case 'rate_limited':
30
+ return AUTH_MESSAGES.rateLimited;
31
+ default:
32
+ return AUTH_MESSAGES.tryAgain;
33
+ }
34
+ };
35
+ const nextFrom = (query) => NextQuerySchema.safeParse(query).data?.next ?? DEFAULT_LANDING_PATH;
36
+ const firstIssue = (error) => error.issues[0]?.message ?? AUTH_MESSAGES.tryAgain;
37
+ const startSession = (ctx, reply, started, next) => reply.header('set-cookie', sessionCookie(started.token, ctx.secureCookie)).redirect(next, SEE_OTHER);
38
+ const loginPage = (ctx) => async (req, reply) => (await startsAtSetup(ctx.deps))
39
+ ? reply.redirect(SETUP_PATH)
40
+ : page(reply, 200, await renderLoginPage({ next: nextFrom(req.query) }));
41
+ const submitLogin = (ctx, limiter) => async (req, reply) => {
42
+ const parsed = LoginFormSchema.safeParse(req.body);
43
+ const next = parsed.success ? parsed.data.next : DEFAULT_LANDING_PATH;
44
+ const failLogin = async (status, error) => page(reply, status, await renderLoginPage({ next, error }));
45
+ if (!parsed.success)
46
+ return failLogin(INVALID_FORM_STATUS, AUTH_MESSAGES.invalidCredentials);
47
+ const { username } = parsed.data;
48
+ if (limiter.isLimited(req.ip, username))
49
+ return failLogin(RATE_LIMITED_STATUS, AUTH_MESSAGES.rateLimited);
50
+ // Reserve the strike before the slow verification: the check above and this take no await between
51
+ // them, so N concurrent guesses are counted as they arrive rather than all slipping past `isLimited`.
52
+ const result = await limiter.attempt(req.ip, username, () => ctx.runEffects(() => login(ctx.deps, parsed.data)));
53
+ if (result.isOk()) {
54
+ limiter.recordSuccess(req.ip, username);
55
+ return startSession(ctx, reply, result.value, next);
56
+ }
57
+ if (result.error.code !== authErrors.invalidCredentials.code)
58
+ limiter.forgive(req.ip, username);
59
+ return failLogin(statusOf(result.error), messageFor(result.error));
60
+ };
61
+ const setupPage = (ctx) => async (_req, reply) => (await ownerNeedsSetup(ctx.deps)) ? page(reply, 200, await renderSetupPage({})) : reply.redirect(LOGIN_PATH);
62
+ const submitSetup = (ctx, limiter) => async (req, reply) => {
63
+ const failSetup = async (status, error) => page(reply, status, await renderSetupPage({ error }));
64
+ const parsed = SetupFormSchema.safeParse(req.body);
65
+ if (!parsed.success)
66
+ return failSetup(INVALID_FORM_STATUS, firstIssue(parsed.error));
67
+ const { username } = parsed.data;
68
+ if (limiter.isLimited(req.ip, username))
69
+ return failSetup(RATE_LIMITED_STATUS, AUTH_MESSAGES.rateLimited);
70
+ const result = await limiter.attempt(req.ip, username, () => ctx.runEffects(() => claimOwner(ctx.deps, parsed.data)));
71
+ if (result.isOk()) {
72
+ limiter.recordSuccess(req.ip, username);
73
+ return startSession(ctx, reply, result.value, DEFAULT_LANDING_PATH);
74
+ }
75
+ if (result.error.code !== authErrors.invalidSetupCode.code)
76
+ limiter.forgive(req.ip, username);
77
+ return failSetup(statusOf(result.error), messageFor(result.error));
78
+ };
79
+ const submitLogout = (ctx) => async (req, reply) => {
80
+ const token = readCookie(req.headers.cookie, SESSION_COOKIE_NAME);
81
+ const revoked = token ? await ctx.runEffects(() => logout(ctx.deps, ctx.deps.secrets.hashSecret(token))) : undefined;
82
+ // The cookie is only cleared once the session row is really gone: reporting a logout that did not
83
+ // commit would leave a still-valid token (possibly copied elsewhere) behind a "logged out" screen.
84
+ if (revoked?.isErr())
85
+ return replyError(reply, revoked.error);
86
+ return reply.header('set-cookie', clearedSessionCookie(ctx.secureCookie)).redirect(LOGIN_PATH, SEE_OTHER);
87
+ };
88
+ /**
89
+ * `/ui/login`, `/ui/setup`, `/ui/logout` (ADR-033 §2). Browser-facing HTML, not part of the `/api` JSON
90
+ * contract, so — like `routes/ui.ts` — these are not `RouteDefinition`s. Thin: parse the form, throttle,
91
+ * run the `controllers/auth/{owner,session}.ts` flow, translate to a cookie + redirect or a page.
92
+ */
93
+ export const registerAuthRoutes = (app, ctx) => {
94
+ const loginLimiter = createAttemptLimiter();
95
+ const setupLimiter = createAttemptLimiter();
96
+ const formRoute = { bodyLimit: FORM_BODY_LIMIT_BYTES };
97
+ void app.register(async (scope) => {
98
+ addFormParser(scope);
99
+ scope.get(LOGIN_PATH, loginPage(ctx));
100
+ scope.post(LOGIN_PATH, formRoute, submitLogin(ctx, loginLimiter));
101
+ scope.get(SETUP_PATH, setupPage(ctx));
102
+ scope.post(SETUP_PATH, formRoute, submitSetup(ctx, setupLimiter));
103
+ scope.post(LOGOUT_PATH, submitLogout(ctx));
104
+ });
105
+ };
@@ -0,0 +1,34 @@
1
+ import { z } from 'zod';
2
+ import { getBudgetStatus, listBudgets } from '../../../controllers/budgets.js';
3
+ import { BudgetViewSchema } from '../../../models/budget.js';
4
+ import { BudgetStatusQuerySchema } from '../../../wire/in/budgets.js';
5
+ import { BudgetStatusOutSchema } from '../../../wire/out/budgets.js';
6
+ import { okResponse } from '../openapi.js';
7
+ import { parse, validation422 } from '../respond.js';
8
+ import { READ_SCOPE } from '../../../models/auth/scope.js';
9
+ const BUDGETS_TAG = 'Budgets';
10
+ const listBudgetsRoute = {
11
+ method: 'get',
12
+ scope: READ_SCOPE,
13
+ path: '/api/budgets',
14
+ tags: [BUDGETS_TAG],
15
+ summary: 'List budgets',
16
+ responses: { 200: okResponse('Budgets', z.array(BudgetViewSchema)) },
17
+ handler: async (_req, _reply, scope) => listBudgets(scope().deps),
18
+ };
19
+ const getBudgetStatusRoute = {
20
+ method: 'get',
21
+ scope: READ_SCOPE,
22
+ path: '/api/budgets/status',
23
+ tags: [BUDGETS_TAG],
24
+ summary: 'Get budget status',
25
+ request: { query: BudgetStatusQuerySchema },
26
+ responses: { 200: okResponse('Budget status', BudgetStatusOutSchema), 422: validation422 },
27
+ handler: async (req, reply, scope) => {
28
+ const input = parse(BudgetStatusQuerySchema, req.query, reply);
29
+ if (!input)
30
+ return reply;
31
+ return reply.send(await getBudgetStatus(scope().deps, input, input.displayCurrency));
32
+ },
33
+ };
34
+ export const budgetRoutes = [listBudgetsRoute, getBudgetStatusRoute];
@@ -0,0 +1,109 @@
1
+ import { z } from 'zod';
2
+ import * as categoryAdapters from '../../../adapters/categories.js';
3
+ import { createCategory, createSubCategory, deleteCategory, deleteSubCategory, listCategories, listSubCategories, } from '../../../controllers/categories.js';
4
+ import { CategorySchema, SubCategorySchema } from '../../../models/category.js';
5
+ import * as wireInCategories from '../../../wire/in/categories.js';
6
+ import { DeletedOut } from '../../../wire/out/common.js';
7
+ import { jsonBody, okResponse } from '../openapi.js';
8
+ import { conflict409, invalidQueryResponse, nameParam, notFound404, parse, pathParam, send, validation422, } from '../respond.js';
9
+ import { READ_SCOPE, WRITE_SCOPE } from '../../../models/auth/scope.js';
10
+ const CATEGORIES_TAG = 'Categories';
11
+ const listCategoriesRoute = {
12
+ method: 'get',
13
+ scope: READ_SCOPE,
14
+ path: '/api/categories',
15
+ tags: [CATEGORIES_TAG],
16
+ summary: 'List categories',
17
+ responses: { 200: okResponse('Categories', z.array(CategorySchema)) },
18
+ handler: async (_req, _reply, scope) => listCategories(scope().deps),
19
+ };
20
+ const createCategoryRoute = {
21
+ method: 'post',
22
+ scope: WRITE_SCOPE,
23
+ path: '/api/categories',
24
+ tags: [CATEGORIES_TAG],
25
+ summary: 'Create category',
26
+ request: { body: jsonBody(wireInCategories.CreateCategorySchema) },
27
+ responses: { 201: okResponse('Category created', CategorySchema), 409: conflict409, 422: validation422 },
28
+ handler: async (req, reply, scope) => {
29
+ const { deps, runEffects } = scope();
30
+ const wireIn = parse(wireInCategories.CreateCategorySchema, req.body, reply);
31
+ if (!wireIn)
32
+ return reply;
33
+ const flow = () => createCategory(deps, categoryAdapters.wireInToModel(wireIn)).map(categoryAdapters.outcomeToDb);
34
+ return send(reply, await runEffects(flow), 201);
35
+ },
36
+ };
37
+ const listSubCategoriesRoute = {
38
+ method: 'get',
39
+ scope: READ_SCOPE,
40
+ path: '/api/sub-categories',
41
+ tags: [CATEGORIES_TAG],
42
+ summary: 'List sub-categories',
43
+ request: { query: wireInCategories.SubCategoriesQuerySchema },
44
+ responses: { 200: okResponse('Sub-categories', z.array(SubCategorySchema)), 422: validation422 },
45
+ handler: async (req, reply, scope) => {
46
+ const query = wireInCategories.SubCategoriesQuerySchema.safeParse(req.query);
47
+ if (!query.success)
48
+ return invalidQueryResponse(reply);
49
+ return reply.send(await listSubCategories(scope().deps, query.data.parentId));
50
+ },
51
+ };
52
+ const createSubCategoryRoute = {
53
+ method: 'post',
54
+ scope: WRITE_SCOPE,
55
+ path: '/api/sub-categories',
56
+ tags: [CATEGORIES_TAG],
57
+ summary: 'Create sub-category',
58
+ request: { body: jsonBody(wireInCategories.CreateSubCategorySchema) },
59
+ responses: {
60
+ 201: okResponse('Sub-category created', SubCategorySchema),
61
+ 404: notFound404,
62
+ 409: conflict409,
63
+ 422: validation422,
64
+ },
65
+ handler: async (req, reply, scope) => {
66
+ const { deps, runEffects } = scope();
67
+ const wireIn = parse(wireInCategories.CreateSubCategorySchema, req.body, reply);
68
+ if (!wireIn)
69
+ return reply;
70
+ const flow = () => createSubCategory(deps, wireIn).map(categoryAdapters.outcomeToDb);
71
+ return send(reply, await runEffects(flow), 201);
72
+ },
73
+ };
74
+ const deleteCategoryRoute = {
75
+ method: 'delete',
76
+ scope: WRITE_SCOPE,
77
+ path: '/api/categories/:name',
78
+ tags: [CATEGORIES_TAG],
79
+ summary: 'Delete category',
80
+ request: { params: nameParam },
81
+ responses: { 200: okResponse('Category deleted', DeletedOut), 404: notFound404, 409: conflict409 },
82
+ handler: async (req, reply, scope) => {
83
+ const { deps, runEffects } = scope();
84
+ const flow = () => deleteCategory(deps, pathParam(req, 'name')).map(categoryAdapters.outcomeToDb);
85
+ return send(reply, await runEffects(flow));
86
+ },
87
+ };
88
+ const deleteSubCategoryRoute = {
89
+ method: 'delete',
90
+ scope: WRITE_SCOPE,
91
+ path: '/api/sub-categories/:name',
92
+ tags: [CATEGORIES_TAG],
93
+ summary: 'Delete sub-category',
94
+ request: { params: nameParam },
95
+ responses: { 200: okResponse('Sub-category deleted', DeletedOut), 404: notFound404, 409: conflict409 },
96
+ handler: async (req, reply, scope) => {
97
+ const { deps, runEffects } = scope();
98
+ const flow = () => deleteSubCategory(deps, pathParam(req, 'name')).map(categoryAdapters.outcomeToDb);
99
+ return send(reply, await runEffects(flow));
100
+ },
101
+ };
102
+ export const categoryRoutes = [
103
+ listCategoriesRoute,
104
+ createCategoryRoute,
105
+ listSubCategoriesRoute,
106
+ createSubCategoryRoute,
107
+ deleteCategoryRoute,
108
+ deleteSubCategoryRoute,
109
+ ];
@@ -0,0 +1,124 @@
1
+ import { err } from 'neverthrow';
2
+ import { httpStatus } from '../../../common/errors.js';
3
+ import { approveGrant, denyGrant, findConsent } from '../../../controllers/auth/grants.js';
4
+ import { authErrors } from '../../../models/auth/errors.js';
5
+ import { AUTH_MESSAGES } from '../../../models/auth/message.js';
6
+ import { CONNECT_CODE_PARAM } from '../../../models/auth/origin.js';
7
+ import { validation } from '../../../models/error.js';
8
+ import { ConnectDecision, ConnectFormSchema, ConnectQuerySchema } from '../../../wire/in/auth.js';
9
+ import { CONNECT_PATH } from '../auth-paths.js';
10
+ import { renderConnectPage, renderConnectResultPage } from '../connect-pages.js';
11
+ import { addFormParser, FORM_BODY_LIMIT_BYTES, page, STEP_UP_REFUSED_STATUS } from '../form-pages.js';
12
+ import { createAttemptLimiter, createRateLimiter, LOGIN_ATTEMPT_WINDOW_MS, MAX_CODE_LOOKUP_FAILURES_PER_IP, } from '../rate-limiter.js';
13
+ import { requireSession } from '../session.js';
14
+ const OK_STATUS = 200;
15
+ const INVALID_STATUS = httpStatus(authErrors.invalidGrant);
16
+ const INVALID_FORM_STATUS = httpStatus(validation([]));
17
+ const RATE_LIMITED_STATUS = httpStatus(authErrors.rateLimited);
18
+ const HEADINGS = {
19
+ approved: 'Approved',
20
+ denied: 'Request denied',
21
+ invalid: 'Not valid',
22
+ limited: 'Slow down',
23
+ };
24
+ const MESSAGES = {
25
+ approved: 'Approved. You can go back to your Claude session — it will pick the sign-in up in a moment.',
26
+ denied: 'Denied. The client was not signed in.',
27
+ };
28
+ const result = async (reply, status, heading, message, options = {}) => page(reply, status, await renderConnectResultPage({ heading, message, answered: options.answered }));
29
+ const invalid = (reply) => result(reply, INVALID_STATUS, HEADINGS.invalid, AUTH_MESSAGES.invalidGrant);
30
+ const limited = (reply) => result(reply, RATE_LIMITED_STATUS, HEADINGS.limited, AUTH_MESSAGES.rateLimited);
31
+ const failed = ({ lookups }, reply, ip, error) => {
32
+ if (error.code === authErrors.invalidGrant.code) {
33
+ lookups.recordFailure(ip); // answered by someone else between the lookup and the decision: a miss after all
34
+ return invalid(reply);
35
+ }
36
+ const status = error.code === validation([]).code ? INVALID_FORM_STATUS : httpStatus(error);
37
+ return result(reply, status, HEADINGS.invalid, AUTH_MESSAGES.tryAgain);
38
+ };
39
+ // The strike is taken BEFORE the awaited lookup and given back for a valid code: recording the miss only afterwards
40
+ // would let a burst of concurrent guesses all see an empty limiter (the login pages reserve the same way).
41
+ const lookUp = async ({ ctx, lookups }, ip, userId, code) => {
42
+ lookups.recordFailure(ip);
43
+ const consent = await findConsent(ctx.deps, userId, code);
44
+ if (consent !== null)
45
+ lookups.forgive(ip);
46
+ return consent;
47
+ };
48
+ const showConsent = (pages) => async (req, reply) => {
49
+ const code = ConnectQuerySchema.safeParse(req.query).data?.[CONNECT_CODE_PARAM];
50
+ if (pages.lookups.isLimited(req.ip))
51
+ return limited(reply);
52
+ const consent = code === undefined ? null : await lookUp(pages, req.ip, req.principal.userId, code);
53
+ if (consent === null)
54
+ return invalid(reply);
55
+ return page(reply, OK_STATUS, await renderConnectPage(consent));
56
+ };
57
+ const isWrongPassword = (error) => error.code === authErrors.invalidCredentials.code;
58
+ // Only an approval re-asks the password; denying grants nothing. The strike is taken before the slow verification.
59
+ const approve = async ({ ctx, passwords }, req, input) => {
60
+ const { userId } = req.principal;
61
+ if (passwords.isLimited(req.ip, userId))
62
+ return err(authErrors.rateLimited);
63
+ const approved = await passwords.attempt(req.ip, userId, () => ctx.runEffects(() => approveGrant(ctx.deps, req.principal, input)));
64
+ if (approved.isOk())
65
+ passwords.recordSuccess(req.ip, userId);
66
+ else if (!isWrongPassword(approved.error))
67
+ passwords.forgive(req.ip, userId);
68
+ return approved;
69
+ };
70
+ const answerGrant = (pages, req, decision, input) => decision === ConnectDecision.enum.approve
71
+ ? approve(pages, req, input)
72
+ : pages.ctx.runEffects(() => denyGrant(pages.ctx.deps, req.principal, input.userCode));
73
+ const answeredPage = (reply, decision) => decision === ConnectDecision.enum.approve
74
+ ? result(reply, OK_STATUS, HEADINGS.approved, MESSAGES.approved, { answered: true })
75
+ : result(reply, OK_STATUS, HEADINGS.denied, MESSAGES.denied, { answered: true });
76
+ // The request stays pending: the same consent page again, with the person's choices kept and the password field empty.
77
+ const retryConsent = async (reply, consent, input) => page(reply, STEP_UP_REFUSED_STATUS, await renderConnectPage({
78
+ ...consent,
79
+ choice: { access: input.access, duration: input.duration },
80
+ error: AUTH_MESSAGES.invalidPassword,
81
+ }));
82
+ const submitDecision = (pages) => async (req, reply) => {
83
+ const parsed = ConnectFormSchema.safeParse(req.body);
84
+ if (!parsed.success)
85
+ return result(reply, INVALID_FORM_STATUS, HEADINGS.invalid, AUTH_MESSAGES.tryAgain);
86
+ if (pages.lookups.isLimited(req.ip))
87
+ return limited(reply);
88
+ const { decision, code, access, duration, password } = parsed.data;
89
+ const consent = await lookUp(pages, req.ip, req.principal.userId, code);
90
+ if (consent === null)
91
+ return invalid(reply);
92
+ const input = { userCode: code, access, duration, password };
93
+ const answered = await answerGrant(pages, req, decision, input);
94
+ if (answered.isOk())
95
+ return answeredPage(reply, decision);
96
+ if (isWrongPassword(answered.error))
97
+ return retryConsent(reply, consent, input);
98
+ return answered.error.code === authErrors.rateLimited.code
99
+ ? limited(reply)
100
+ : failed(pages, reply, req.ip, answered.error);
101
+ };
102
+ /**
103
+ * `/ui/connect` (ADR-034 §3): the consent page for a stdio (or `patty login`) sign-in. Browser HTML behind the
104
+ * session cookie and the hook's CSRF check — a link that merely carries a code grants nothing, and a bearer token can
105
+ * never approve one. Thin: parse, throttle, run the `controllers/auth/grants.ts` flow, render a page. An unknown,
106
+ * expired or already-answered code all read the same, and a run of them from one address is throttled.
107
+ */
108
+ export const registerConnectRoutes = (app, ctx) => {
109
+ const pages = {
110
+ ctx,
111
+ passwords: createAttemptLimiter(),
112
+ lookups: createRateLimiter({
113
+ windowMs: LOGIN_ATTEMPT_WINDOW_MS,
114
+ maxFailures: MAX_CODE_LOOKUP_FAILURES_PER_IP,
115
+ now: Date.now,
116
+ }),
117
+ };
118
+ void app.register(async (scope) => {
119
+ addFormParser(scope);
120
+ scope.addHook('preHandler', requireSession);
121
+ scope.get(CONNECT_PATH, showConsent(pages));
122
+ scope.post(CONNECT_PATH, { bodyLimit: FORM_BODY_LIMIT_BYTES }, submitDecision(pages));
123
+ });
124
+ };