@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,51 @@
1
+ import { z } from 'zod';
2
+ import * as tagAdapters from '../../../adapters/tags.js';
3
+ import { createTag, deleteTag, listTags } from '../../../controllers/tags.js';
4
+ import { TagSchema } from '../../../models/tag.js';
5
+ import { CreateTagSchema } from '../../../wire/in/tags.js';
6
+ import { DeletedOut } from '../../../wire/out/common.js';
7
+ import { jsonBody, okResponse } from '../openapi.js';
8
+ import { conflict409, idParam, parse, pathParam, send, validation422 } from '../respond.js';
9
+ import { READ_SCOPE, WRITE_SCOPE } from '../../../models/auth/scope.js';
10
+ const TAGS_TAG = 'Tags';
11
+ const listTagsRoute = {
12
+ method: 'get',
13
+ scope: READ_SCOPE,
14
+ path: '/api/tags',
15
+ tags: [TAGS_TAG],
16
+ summary: 'List tags',
17
+ responses: { 200: okResponse('Tags', z.array(TagSchema)) },
18
+ handler: async (_req, _reply, scope) => listTags(scope().deps),
19
+ };
20
+ const createTagRoute = {
21
+ method: 'post',
22
+ scope: WRITE_SCOPE,
23
+ path: '/api/tags',
24
+ tags: [TAGS_TAG],
25
+ summary: 'Create tag',
26
+ request: { body: jsonBody(CreateTagSchema) },
27
+ responses: { 201: okResponse('Tag created', TagSchema), 409: conflict409, 422: validation422 },
28
+ handler: async (req, reply, scope) => {
29
+ const { deps, runEffects } = scope();
30
+ const input = parse(CreateTagSchema, req.body, reply);
31
+ if (!input)
32
+ return reply;
33
+ const flow = () => createTag(deps, input.name).map(tagAdapters.outcomeToDb);
34
+ return send(reply, await runEffects(flow), 201);
35
+ },
36
+ };
37
+ const deleteTagRoute = {
38
+ method: 'delete',
39
+ scope: WRITE_SCOPE,
40
+ path: '/api/tags/:id',
41
+ tags: [TAGS_TAG],
42
+ summary: 'Delete tag',
43
+ request: { params: idParam },
44
+ responses: { 200: okResponse('Tag deleted', DeletedOut) },
45
+ handler: async (req, reply, scope) => {
46
+ const { deps, runEffects } = scope();
47
+ const flow = () => deleteTag(deps, pathParam(req, 'id')).map(tagAdapters.outcomeToDb);
48
+ return send(reply, await runEffects(flow));
49
+ },
50
+ };
51
+ export const tagRoutes = [listTagsRoute, createTagRoute, deleteTagRoute];
@@ -0,0 +1,72 @@
1
+ import { createToken, listTokens, revokeToken } from '../../../controllers/auth/access-tokens.js';
2
+ import { httpStatus } from '../../../common/errors.js';
3
+ import { authErrors } from '../../../models/auth/errors.js';
4
+ import { UserRole } from '../../../models/auth/owner.js';
5
+ import { AUTH_MESSAGES } from '../../../models/auth/message.js';
6
+ import { validation } from '../../../models/error.js';
7
+ import { CreateTokenFormSchema } from '../../../wire/in/auth.js';
8
+ import { SEE_OTHER, TOKEN_REVOKE_PATH, TOKENS_PATH } from '../auth-paths.js';
9
+ import { addFormParser, FORM_BODY_LIMIT_BYTES, page, STEP_UP_REFUSED_STATUS } from '../form-pages.js';
10
+ import { createAttemptLimiter } from '../rate-limiter.js';
11
+ import { requireSession } from '../session.js';
12
+ import { renderTokenCreatedPage, renderTokensPage } from '../token-pages.js';
13
+ const INVALID_FORM_STATUS = httpStatus(validation([]));
14
+ const RATE_LIMITED_STATUS = httpStatus(authErrors.rateLimited);
15
+ const firstIssue = (error) => error.issues[0]?.message ?? AUTH_MESSAGES.tryAgain;
16
+ const showTokens = async (ctx, reply, principal, status, error) => page(reply, status, await renderTokensPage({
17
+ tokens: await listTokens(ctx.deps, principal.userId),
18
+ // Only an administrator is shown the way to user management; to anyone else the page does not exist.
19
+ showUsersLink: principal.role === UserRole.enum.admin,
20
+ error,
21
+ }));
22
+ const listPage = (ctx) => (req, reply) => showTokens(ctx, reply, req.principal, 200);
23
+ // A wrong step-up password is a refused action inside a valid session; anything else is a generic failure.
24
+ const refusalOf = (error) => error.code === authErrors.invalidCredentials.code
25
+ ? { status: STEP_UP_REFUSED_STATUS, message: AUTH_MESSAGES.invalidPassword }
26
+ : { status: httpStatus(error), message: AUTH_MESSAGES.tryAgain };
27
+ const createPage = (ctx, limiter) => async (req, reply) => {
28
+ const principal = req.principal;
29
+ const { userId } = principal;
30
+ const parsed = CreateTokenFormSchema.safeParse(req.body);
31
+ if (!parsed.success)
32
+ return showTokens(ctx, reply, principal, INVALID_FORM_STATUS, firstIssue(parsed.error));
33
+ if (limiter.isLimited(req.ip, userId)) {
34
+ return showTokens(ctx, reply, principal, RATE_LIMITED_STATUS, AUTH_MESSAGES.rateLimited);
35
+ }
36
+ const created = await limiter.attempt(req.ip, userId, () => ctx.runEffects(() => createToken(ctx.deps, principal, parsed.data)));
37
+ if (created.isErr()) {
38
+ if (created.error.code !== authErrors.invalidCredentials.code)
39
+ limiter.forgive(req.ip, userId);
40
+ const { status, message } = refusalOf(created.error);
41
+ return showTokens(ctx, reply, principal, status, message);
42
+ }
43
+ limiter.recordSuccess(req.ip, userId);
44
+ return page(reply, 200, await renderTokenCreatedPage(created.value));
45
+ };
46
+ const revokePage = (ctx) => async (req, reply) => {
47
+ const principal = req.principal;
48
+ const { userId } = principal;
49
+ const { id } = req.params;
50
+ const revoked = await ctx.runEffects(() => revokeToken(ctx.deps, userId, id));
51
+ return revoked.isErr()
52
+ ? showTokens(ctx, reply, principal, httpStatus(revoked.error), AUTH_MESSAGES.unknownToken)
53
+ : reply.redirect(TOKENS_PATH, SEE_OTHER);
54
+ };
55
+ /**
56
+ * `/ui/access/tokens` (ADR-033 §3): the personal-access-token pages. Browser HTML behind the session cookie and the
57
+ * hook's CSRF check — a bearer token is never accepted on `/ui`, so a token can never mint, widen or revoke
58
+ * another. Thin: parse the form, run the `controllers/auth/access-tokens.ts` flow, render a page. The plaintext token
59
+ * is rendered once, by the response to the create POST, and nowhere else.
60
+ */
61
+ export const registerTokenRoutes = (app, ctx) => {
62
+ // Guessing the step-up password costs the same strikes as guessing it at /ui/login.
63
+ const passwordLimiter = createAttemptLimiter();
64
+ const formRoute = { bodyLimit: FORM_BODY_LIMIT_BYTES };
65
+ void app.register(async (scope) => {
66
+ addFormParser(scope);
67
+ scope.addHook('preHandler', requireSession);
68
+ scope.get(TOKENS_PATH, listPage(ctx));
69
+ scope.post(TOKENS_PATH, formRoute, createPage(ctx, passwordLimiter));
70
+ scope.post(TOKEN_REVOKE_PATH, formRoute, revokePage(ctx));
71
+ });
72
+ };
@@ -0,0 +1,55 @@
1
+ import * as transactionAdapters from '../../../adapters/transactions.js';
2
+ import { confirmTransaction } from '../../../controllers/transaction/core.js';
3
+ import { searchTransactions } from '../../../controllers/transaction/read.js';
4
+ import { pageSchema } from '../../../models/page.js';
5
+ import { TransactionViewSchema } from '../../../models/transaction.js';
6
+ import * as wireInTransactions from '../../../wire/in/transactions.js';
7
+ import { jsonBody, okResponse } from '../openapi.js';
8
+ import { conflict409, idParam, notFound404, parse, pathParam, send, validation422 } from '../respond.js';
9
+ import { READ_SCOPE, WRITE_SCOPE } from '../../../models/auth/scope.js';
10
+ const TRANSACTIONS_TAG = 'Transactions';
11
+ const confirmTransactionRoute = {
12
+ method: 'post',
13
+ scope: WRITE_SCOPE,
14
+ path: '/api/transactions/:id/confirm',
15
+ tags: [TRANSACTIONS_TAG],
16
+ summary: 'Confirm (clear) a pending transaction',
17
+ request: { params: idParam, body: jsonBody(wireInTransactions.ConfirmTransactionSchema.omit({ id: true })) },
18
+ responses: {
19
+ 200: okResponse('Transaction confirmed', TransactionViewSchema),
20
+ 404: notFound404,
21
+ 409: conflict409,
22
+ 422: validation422,
23
+ },
24
+ handler: async (req, reply, scope) => {
25
+ const { deps, runEffects } = scope();
26
+ const id = pathParam(req, 'id');
27
+ const wireIn = parse(wireInTransactions.ConfirmTransactionSchema, { ...(req.body ?? {}), id }, reply);
28
+ if (!wireIn)
29
+ return reply;
30
+ const model = transactionAdapters.confirmWireInToModel(wireIn);
31
+ const flow = () => confirmTransaction(deps, model).map(transactionAdapters.outcomeToDb);
32
+ return send(reply, await runEffects(flow));
33
+ },
34
+ };
35
+ const searchTransactionsRoute = {
36
+ method: 'get',
37
+ scope: READ_SCOPE,
38
+ path: '/api/transactions',
39
+ tags: [TRANSACTIONS_TAG],
40
+ summary: 'Search transactions',
41
+ request: { query: wireInTransactions.SearchTransactionsQuerySchema },
42
+ responses: {
43
+ 200: okResponse('A page of matching transactions', pageSchema(TransactionViewSchema)),
44
+ 404: notFound404,
45
+ 409: conflict409,
46
+ 422: validation422,
47
+ },
48
+ handler: async (req, reply, scope) => {
49
+ const wireIn = parse(wireInTransactions.SearchTransactionsInputSchema, req.query, reply);
50
+ if (!wireIn)
51
+ return reply;
52
+ return send(reply, await searchTransactions(scope().deps, transactionAdapters.searchWireInToModel(wireIn)));
53
+ },
54
+ };
55
+ export const transactionRoutes = [confirmTransactionRoute, searchTransactionsRoute];
@@ -0,0 +1,35 @@
1
+ import * as accountAdapters from '../../../adapters/accounts.js';
2
+ import * as transactionAdapters from '../../../adapters/transactions.js';
3
+ import { createTransfer } from '../../../controllers/account/transfer.js';
4
+ import { TransactionSource } from '../../../models/transaction.js';
5
+ import * as wireInAccounts from '../../../wire/in/accounts.js';
6
+ import { TransferResultOut } from '../../../wire/out/transactions.js';
7
+ import { jsonBody, okResponse } from '../openapi.js';
8
+ import { conflict409, notFound404, parse, sendUpsert, validation422 } from '../respond.js';
9
+ import { WRITE_SCOPE } from '../../../models/auth/scope.js';
10
+ const TRANSFERS_TAG = 'Transfers';
11
+ const createTransferRoute = {
12
+ method: 'post',
13
+ scope: WRITE_SCOPE,
14
+ path: '/api/transfers',
15
+ tags: [TRANSFERS_TAG],
16
+ summary: 'Transfer between accounts',
17
+ request: { body: jsonBody(wireInAccounts.CreateTransferSchema) },
18
+ responses: {
19
+ 200: okResponse('Existing transfer returned (idempotent replay)', TransferResultOut),
20
+ 201: okResponse('Transfer created', TransferResultOut),
21
+ 404: notFound404,
22
+ 409: conflict409,
23
+ 422: validation422,
24
+ },
25
+ handler: async (req, reply, scope) => {
26
+ const { deps, runEffects } = scope();
27
+ const wireIn = parse(wireInAccounts.CreateTransferSchema, req.body, reply);
28
+ if (!wireIn)
29
+ return reply;
30
+ const model = accountAdapters.transferWireInToModel(wireIn);
31
+ const flow = () => createTransfer(deps, model, TransactionSource.enum.rest).map(transactionAdapters.outcomeToDb);
32
+ return sendUpsert(reply, await runEffects(flow));
33
+ },
34
+ };
35
+ export const transferRoutes = [createTransferRoute];
@@ -0,0 +1,110 @@
1
+ import { SHARED_ENTITY_TAGS } from '../../../models/tenancy.js';
2
+ import { LOGOUT_PATH, TOKENS_PATH, UI_APP_CSS_PATH, UI_ROOT_PATH } from '../auth-paths.js';
3
+ import { authErrors } from '../../../models/auth/errors.js';
4
+ import { CACHE_CONTROL_NO_CACHE, replyError } from '../respond.js';
5
+ import { HTML_CONTENT_TYPE, readCached, UI_ROOT } from '../ui-files.js';
6
+ const SHELL_PATH = `${UI_ROOT}/shell.html`;
7
+ const APP_CSS_PATH = `${UI_ROOT}/app.css`;
8
+ const APP_JS_PATH = `${UI_ROOT}/app.js`;
9
+ const MONEY_JS_PATH = `${UI_ROOT}/money.js`;
10
+ const CSS_CONTENT_TYPE = 'text/css; charset=utf-8';
11
+ const JS_CONTENT_TYPE = 'text/javascript; charset=utf-8';
12
+ const SSE_CONTENT_TYPE = 'text/event-stream; charset=utf-8';
13
+ const SSE_SESSION_RECHECK_MS = 30_000;
14
+ // Where ui/shell.html reserves room for controls that only exist when sessions do (ADR-033).
15
+ const AUTH_CONTROLS_MARKER = '<!--patty:auth-controls-->';
16
+ const TOKENS_CONTROL = `<a href="${TOKENS_PATH}" class="sidebar-more-btn sidebar-tokens" aria-label="Access tokens" title="Access tokens">` +
17
+ '<i class="fa-solid fa-key"></i></a>';
18
+ const LOGOUT_CONTROL = `<form method="post" action="${LOGOUT_PATH}" class="sidebar-logout">` +
19
+ '<button type="submit" class="sidebar-more-btn" aria-label="Log out" title="Log out">' +
20
+ '<i class="fa-solid fa-right-from-bracket"></i></button></form>';
21
+ const serveUiFile = async (reply, path, contentType) => {
22
+ const content = await readCached(path);
23
+ return reply.header('cache-control', CACHE_CONTROL_NO_CACHE).type(contentType).send(content);
24
+ };
25
+ // Own changes in full; another user's only where they are shared (userId null = bookkeeping, heard by no one).
26
+ const entitiesFor = (event, userId) => {
27
+ if (event.userId === userId)
28
+ return event.entities;
29
+ return event.userId === null ? [] : event.entities.filter((tag) => SHARED_ENTITY_TAGS.includes(tag));
30
+ };
31
+ const openEventStream = (reply) => {
32
+ reply.hijack();
33
+ reply.raw.writeHead(200, {
34
+ 'content-type': SSE_CONTENT_TYPE,
35
+ 'cache-control': CACHE_CONTROL_NO_CACHE,
36
+ connection: 'keep-alive',
37
+ });
38
+ // writeHead() alone only sets internal state — Node doesn't put headers on the wire until the
39
+ // first write()/end() or an explicit flush, and a client with nothing yet to publish would
40
+ // otherwise hang waiting for a response that was never actually sent.
41
+ reply.raw.flushHeaders();
42
+ };
43
+ const forwardChanges = (reply, subscribe, userId) => {
44
+ const unsubscribe = subscribe((event) => {
45
+ const entities = entitiesFor(event, userId);
46
+ if (entities.length === 0)
47
+ return;
48
+ // A publish can race a client disconnect that hasn't reached the 'close' handler below yet
49
+ // — skip the write rather than push data onto a response that's already torn down.
50
+ if (reply.raw.destroyed)
51
+ return;
52
+ reply.raw.write(`data: ${JSON.stringify({ entities })}\n\n`);
53
+ });
54
+ // reply.raw (not req.raw), matching the other hijacked route in this codebase
55
+ // (diplomat/mcp/route.ts) — this handler owns the response after hijack(), and it's the
56
+ // response's own lifecycle this cleanup is guarding.
57
+ reply.raw.on('close', unsubscribe);
58
+ };
59
+ // With sessions on, the cookie was checked only when this stream opened. Logout, expiry or a disabled
60
+ // user must end it too, or it would keep delivering change notifications to someone no longer signed in.
61
+ const endWhenSessionLapses = (req, reply, session) => {
62
+ const recheck = setInterval(() => {
63
+ // Fail closed: a check that cannot be completed ends the stream rather than leaving it authorized.
64
+ void session
65
+ .isActive(req)
66
+ .catch(() => false)
67
+ .then((active) => {
68
+ if (!active)
69
+ reply.raw.end();
70
+ });
71
+ }, session.everyMs ?? SSE_SESSION_RECHECK_MS);
72
+ recheck.unref();
73
+ reply.raw.on('close', () => clearInterval(recheck));
74
+ };
75
+ /**
76
+ * Live update (ADR-027 Phase 3): the shell (`ui/app.js`) opens one long-lived `EventSource` here
77
+ * for the life of the page; every message is `{"entities": [...]}` — the entity tags of a batch
78
+ * that just committed, straight from the change bus's `subscribe` (`@rfc0/effect-runner`'s
79
+ * post-commit publish hook). `reply.hijack()` opts out of Fastify's own response lifecycle (its
80
+ * automatic `send()`/timeout/hook handling assumes a response that ends promptly, which an SSE
81
+ * stream deliberately never does) so this handler owns `reply.raw` until the client disconnects.
82
+ * Not a `RouteDefinition` — same reasoning as the rest of this file: a browser-facing stream, not
83
+ * part of the `/api` JSON contract.
84
+ */
85
+ const registerUiEventsRoute = (app, subscribe, session) => {
86
+ app.get(`${UI_ROOT_PATH}/events`, (req, reply) => {
87
+ // Without a principal, open no stream rather than everyone's events.
88
+ const userId = req.principal?.userId;
89
+ if (userId === undefined)
90
+ return replyError(reply, authErrors.unauthenticated);
91
+ openEventStream(reply);
92
+ forwardChanges(reply, subscribe, userId);
93
+ if (session)
94
+ endWhenSessionLapses(req, reply, session);
95
+ return undefined;
96
+ });
97
+ };
98
+ export const registerUiRoutes = (app, subscribeToChanges, options = { authControls: false }) => {
99
+ const serveShell = async (_req, reply) => {
100
+ const shell = await readCached(SHELL_PATH);
101
+ const html = shell.replace(AUTH_CONTROLS_MARKER, options.authControls ? `${TOKENS_CONTROL}${LOGOUT_CONTROL}` : '');
102
+ return reply.header('cache-control', CACHE_CONTROL_NO_CACHE).type(HTML_CONTENT_TYPE).send(html);
103
+ };
104
+ app.get(UI_ROOT_PATH, serveShell);
105
+ app.get(`${UI_ROOT_PATH}/:name`, serveShell);
106
+ app.get(UI_APP_CSS_PATH, async (_req, reply) => serveUiFile(reply, APP_CSS_PATH, CSS_CONTENT_TYPE));
107
+ app.get(`${UI_ROOT_PATH}/assets/app.js`, async (_req, reply) => serveUiFile(reply, APP_JS_PATH, JS_CONTENT_TYPE));
108
+ app.get(`${UI_ROOT_PATH}/assets/money.js`, async (_req, reply) => serveUiFile(reply, MONEY_JS_PATH, JS_CONTENT_TYPE));
109
+ registerUiEventsRoute(app, subscribeToChanges, options.session);
110
+ };
@@ -0,0 +1,156 @@
1
+ import { err } from 'neverthrow';
2
+ import { z } from 'zod';
3
+ import { httpStatus } from '../../../common/errors.js';
4
+ import { currentSignInCap, disableUser, enableUser, inviteUser, listUsers, reissueInvite, setRole, setSignInCap, } from '../../../controllers/auth/users.js';
5
+ import { inviteLink } from '../../../logic/auth/users.js';
6
+ import { resourceOrigin } from '../../../logic/auth/origin.js';
7
+ import { authErrors } from '../../../models/auth/errors.js';
8
+ import { AUTH_MESSAGES, USER_PAGE_HEADINGS } from '../../../models/auth/message.js';
9
+ import { ActorKind } from '../../../models/auth/users.js';
10
+ import { validation } from '../../../models/error.js';
11
+ import { InviteUserFormSchema, SetRoleFormSchema, SignInCapFormSchema, StepUpFormSchema, UserParamsSchema, } from '../../../wire/in/auth.js';
12
+ import { SEE_OTHER, USER_DISABLE_PATH, USER_ENABLE_PATH, USER_REISSUE_PATH, USER_ROLE_PATH, USERS_CAP_PATH, USERS_PATH, } from '../auth-paths.js';
13
+ import { addFormParser, FORM_BODY_LIMIT_BYTES, page, STEP_UP_REFUSED_STATUS } from '../form-pages.js';
14
+ import { createAttemptLimiter } from '../rate-limiter.js';
15
+ import { requireAdmin, requireSession } from '../session.js';
16
+ import { renderInvitedPage, renderUsersPage } from '../user-pages.js';
17
+ const INVALID_FORM_STATUS = httpStatus(validation([]));
18
+ // What each refusal says on this edge. The domain's messages are neutral; the next step is worded here, in the page's
19
+ // own vocabulary (a button on a row), never in the domain's.
20
+ const REFUSAL_MESSAGE = {
21
+ invalid_credentials: AUTH_MESSAGES.invalidPassword,
22
+ username_taken: AUTH_MESSAGES.usernameTaken,
23
+ cannot_change_self: AUTH_MESSAGES.cannotChangeSelf,
24
+ last_admin: `${AUTH_MESSAGES.lastAdmin} Make another user an administrator first.`,
25
+ user_disabled: `${AUTH_MESSAGES.userDisabled} Use the Enable button on that row.`,
26
+ unknown_user: AUTH_MESSAGES.unknownUser,
27
+ owner_unclaimed: AUTH_MESSAGES.ownerUnclaimed,
28
+ rate_limited: AUTH_MESSAGES.rateLimited,
29
+ };
30
+ const refusalOf = (error) => ({
31
+ status: error.code === authErrors.invalidCredentials.code ? STEP_UP_REFUSED_STATUS : httpStatus(error),
32
+ message: REFUSAL_MESSAGE[error.code] ?? AUTH_MESSAGES.tryAgain,
33
+ });
34
+ const firstIssue = (error) => error.issues[0]?.message ?? AUTH_MESSAGES.tryAgain;
35
+ const sessionActor = (req, password) => ({
36
+ kind: ActorKind.enum.session,
37
+ principal: req.principal,
38
+ password,
39
+ });
40
+ const showUsers = async (pages, req, reply, status = 200, error) => {
41
+ const { ctx } = pages;
42
+ const [users, cap] = [await listUsers(ctx.deps, sessionActor(req)), await currentSignInCap(ctx.deps)];
43
+ if (users.isErr())
44
+ return reply.status(httpStatus(users.error)).send({ error: users.error });
45
+ return page(reply, status, await renderUsersPage({ users: users.value, cap, error }));
46
+ };
47
+ const refused = (pages, req, reply, error) => {
48
+ const { status, message } = refusalOf(error);
49
+ return showUsers(pages, req, reply, status, message);
50
+ };
51
+ /**
52
+ * Runs one step-up action: guessing the admin's password costs the same strikes as guessing it at `/ui/login`, a
53
+ * wrong one counts and a right one clears them. The strike is taken before the slow verification.
54
+ */
55
+ const attemptAs = async (pages, req, password, run) => {
56
+ const key = req.principal.userId;
57
+ if (pages.passwords.isLimited(req.ip, key))
58
+ return err(authErrors.rateLimited);
59
+ const result = await pages.passwords.attempt(req.ip, key, () => run(sessionActor(req, password)));
60
+ if (result.isOk())
61
+ pages.passwords.recordSuccess(req.ip, key);
62
+ else if (result.error.code !== authErrors.invalidCredentials.code)
63
+ pages.passwords.forgive(req.ip, key);
64
+ return result;
65
+ };
66
+ const showInvited = (pages, heading) => async (issued, req, reply) => {
67
+ const origin = resourceOrigin(pages.ctx.publicUrl, req.headers.host);
68
+ const link = origin === null ? null : inviteLink(origin, issued.code);
69
+ return page(reply, 200, await renderInvitedPage({ heading, issued, link }));
70
+ };
71
+ const redirectToUsers = (_value, _req, reply) => reply.redirect(USERS_PATH, SEE_OTHER);
72
+ const NO_PARAMS = z
73
+ .object({})
74
+ .strip()
75
+ .transform(() => ({}));
76
+ /**
77
+ * One state-changing admin action: decode the path parameters and the form, run the flow as the typed-password actor
78
+ * through the throttled `attemptAs`, then render the success or the refusal on the users page. Every action that
79
+ * changes who can sign in or what they can do goes through here, so none can skip the password.
80
+ */
81
+ const stepUpAction = (pages, params, action) => async (req, reply) => {
82
+ const decodedParams = params.safeParse(req.params);
83
+ const form = action.form.safeParse(req.body);
84
+ if (!decodedParams.success)
85
+ return showUsers(pages, req, reply, INVALID_FORM_STATUS, AUTH_MESSAGES.tryAgain);
86
+ if (!form.success)
87
+ return showUsers(pages, req, reply, INVALID_FORM_STATUS, firstIssue(form.error));
88
+ const { password, ...input } = form.data;
89
+ const result = await attemptAs(pages, req, password, (actor) => action.run(actor, decodedParams.data, input));
90
+ return result.isErr() ? refused(pages, req, reply, result.error) : action.onSuccess(result.value, req, reply);
91
+ };
92
+ /** An action on the instance (the invite form, the cap), not on one user: it has no path parameters. */
93
+ const instanceAction = (pages, action) => stepUpAction(pages, NO_PARAMS, action);
94
+ /** An action on one user, named by the `:id` of the path. */
95
+ const userAction = (pages, action) => stepUpAction(pages, UserParamsSchema, action);
96
+ const runIn = (pages, flow) => pages.ctx.runEffects(flow);
97
+ const listPage = (pages) => (req, reply) => showUsers(pages, req, reply);
98
+ const userRoutes = (pages) => {
99
+ const { deps } = pages.ctx;
100
+ return {
101
+ invite: instanceAction(pages, {
102
+ form: InviteUserFormSchema,
103
+ run: (actor, _params, input) => runIn(pages, () => inviteUser(deps, actor, input)),
104
+ onSuccess: showInvited(pages, USER_PAGE_HEADINGS.inviteCreated),
105
+ }),
106
+ reissue: userAction(pages, {
107
+ form: StepUpFormSchema,
108
+ run: (actor, params) => runIn(pages, () => reissueInvite(deps, actor, params.id)),
109
+ onSuccess: showInvited(pages, USER_PAGE_HEADINGS.newInvite),
110
+ }),
111
+ disable: userAction(pages, {
112
+ form: StepUpFormSchema,
113
+ run: (actor, params) => runIn(pages, () => disableUser(deps, actor, params.id)),
114
+ onSuccess: redirectToUsers,
115
+ }),
116
+ enable: userAction(pages, {
117
+ form: StepUpFormSchema,
118
+ run: (actor, params) => runIn(pages, () => enableUser(deps, actor, params.id)),
119
+ onSuccess: redirectToUsers,
120
+ }),
121
+ role: userAction(pages, {
122
+ form: SetRoleFormSchema,
123
+ run: (actor, params, input) => runIn(pages, () => setRole(deps, actor, { userId: params.id, role: input.role })),
124
+ onSuccess: redirectToUsers,
125
+ }),
126
+ cap: instanceAction(pages, {
127
+ form: SignInCapFormSchema,
128
+ run: (actor, _params, input) => runIn(pages, () => setSignInCap(deps, actor, input)),
129
+ onSuccess: redirectToUsers,
130
+ }),
131
+ };
132
+ };
133
+ /**
134
+ * `/ui/access/users`: user management. Browser HTML behind the session cookie, the hook's CSRF check
135
+ * AND an admin: a member's request to any of these routes — page or form post — is answered as if the route did not
136
+ * exist. Never an `/api` route or an MCP tool, and a bearer token is never accepted on `/ui`. Thin: parse the form,
137
+ * throttle the step-up password, run the `controllers/auth/users.ts` flow, render a page or redirect. An invite's code
138
+ * and link are rendered once, by the response to the POST that issued them.
139
+ */
140
+ export const registerUserRoutes = (app, ctx) => {
141
+ const pages = { ctx, passwords: createAttemptLimiter() };
142
+ const formRoute = { bodyLimit: FORM_BODY_LIMIT_BYTES };
143
+ void app.register(async (scope) => {
144
+ addFormParser(scope);
145
+ scope.addHook('preHandler', requireSession);
146
+ scope.addHook('preHandler', requireAdmin);
147
+ const routes = userRoutes(pages);
148
+ scope.get(USERS_PATH, listPage(pages));
149
+ scope.post(USERS_PATH, formRoute, routes.invite);
150
+ scope.post(USER_REISSUE_PATH, formRoute, routes.reissue);
151
+ scope.post(USER_DISABLE_PATH, formRoute, routes.disable);
152
+ scope.post(USER_ENABLE_PATH, formRoute, routes.enable);
153
+ scope.post(USER_ROLE_PATH, formRoute, routes.role);
154
+ scope.post(USERS_CAP_PATH, formRoute, routes.cap);
155
+ });
156
+ };
@@ -0,0 +1,26 @@
1
+ import { protectedResourceMetadata } from '../../../logic/auth/bearer.js';
2
+ import { resourceOrigin } from '../../../logic/auth/origin.js';
3
+ import { MCP_PRM_PATH, PRM_WELL_KNOWN_PATH } from '../../../models/auth/bearer.js';
4
+ import { authErrors } from '../../../models/auth/errors.js';
5
+ import { READ_SCOPE } from '../../../models/auth/scope.js';
6
+ import { CACHE_CONTROL_NO_CACHE, replyError } from '../respond.js';
7
+ /**
8
+ * Protected Resource Metadata (RFC 9728 §3, MCP authorization): the document an unauthenticated client finds
9
+ * through the 401 challenge's `resource_metadata`. Served at the path-inserted URI for resource `<origin>/mcp`
10
+ * and at the bare well-known URI (same document); both are in `PUBLIC_ROUTES`. Only mounted when auth is
11
+ * `required` — with auth disabled there is no authorization to describe. The origin is `PUBLIC_URL`, else the
12
+ * request's own loopback origin; if neither is known the document would name a resource we cannot vouch for, so
13
+ * it is a 404 with a hint.
14
+ */
15
+ export const registerProtectedResourceMetadataRoutes = (app, publicUrl) => {
16
+ const serve = async (req, reply) => {
17
+ const origin = resourceOrigin(publicUrl, req.headers.host);
18
+ if (origin === null) {
19
+ return replyError(reply, authErrors.metadataUnavailable);
20
+ }
21
+ return reply.header('cache-control', CACHE_CONTROL_NO_CACHE).send(protectedResourceMetadata(origin));
22
+ };
23
+ const options = { config: { scope: READ_SCOPE } };
24
+ app.get(PRM_WELL_KNOWN_PATH, options, serve);
25
+ app.get(MCP_PRM_PATH, options, serve);
26
+ };
@@ -0,0 +1,85 @@
1
+ import { AuthMode } from '../../models/auth/mode.js';
2
+ import { READ_SCOPE } from '../../models/auth/scope.js';
3
+ import { DISABLED_AUTH } from './context.js';
4
+ import { buildOpenApiDocument, mountRoutes } from './openapi.js';
5
+ import { CACHE_CONTROL_NO_CACHE } from './respond.js';
6
+ import { accountRoutes } from './routes/account.js';
7
+ import { aggregateRoutes } from './routes/aggregate.js';
8
+ import { budgetRoutes } from './routes/budget.js';
9
+ import { categoryRoutes } from './routes/category.js';
10
+ import { creditCardRoutes } from './routes/credit-card.js';
11
+ import { currencyRoutes } from './routes/currency.js';
12
+ import { currencyRateRoutes } from './routes/currency-rates.js';
13
+ import { dashboardRoutes } from './routes/dashboard.js';
14
+ import { recurringRoutes } from './routes/recurring.js';
15
+ import { settingsRoutes } from './routes/settings.js';
16
+ import { summaryRoutes } from './routes/summary.js';
17
+ import { systemRoutes } from './routes/system.js';
18
+ import { tagRoutes } from './routes/tag.js';
19
+ import { transactionRoutes } from './routes/transaction.js';
20
+ import { transferRoutes } from './routes/transfer.js';
21
+ import { registerAuthRoutes } from './routes/auth.js';
22
+ import { registerConnectRoutes } from './routes/connect.js';
23
+ import { registerInviteRoutes } from './routes/invite.js';
24
+ import { registerTokenRoutes } from './routes/tokens.js';
25
+ import { registerUserRoutes } from './routes/users.js';
26
+ import { registerProtectedResourceMetadataRoutes } from './routes/well-known.js';
27
+ import { registerUiRoutes } from './routes/ui.js';
28
+ import { resolvePrincipal } from './session.js';
29
+ /**
30
+ * Thin diplomat: zod-parse (wire/in) → wireInToModel → controller → map Result to HTTP.
31
+ * Aggregation only (ADR-025) — each domain's routes are declared by its own module in
32
+ * `routes/<domain>.ts`, mirroring `controllers/`. A new route lives in the domain module
33
+ * matching its controller; this file never inlines a new registration.
34
+ *
35
+ * `buildRouteDefinitions` concatenates every domain's routes into ONE array — method, path,
36
+ * OpenAPI docs, and the real handler together for each entry, still the single source of truth.
37
+ * `registerRoutes` mounts this list on Fastify and documents it at `/api/openapi.json`; the MCP
38
+ * resource `patty://openapi` documents the same list without ever mounting it — so there is
39
+ * nowhere for the two surfaces to drift apart (ADR-013 Phase A).
40
+ */
41
+ export const buildRouteDefinitions = (ctx) => [
42
+ ...systemRoutes(ctx),
43
+ ...accountRoutes,
44
+ ...categoryRoutes,
45
+ ...creditCardRoutes,
46
+ ...currencyRoutes,
47
+ ...currencyRateRoutes,
48
+ ...settingsRoutes,
49
+ ...transferRoutes,
50
+ ...recurringRoutes,
51
+ ...transactionRoutes,
52
+ ...tagRoutes,
53
+ ...dashboardRoutes,
54
+ ...aggregateRoutes,
55
+ ...summaryRoutes,
56
+ ...budgetRoutes,
57
+ ];
58
+ // A long-lived stream is authenticated once, when it opens — so it asks again on this schedule.
59
+ const sessionRecheck = (auth) => ({
60
+ isActive: async (req) => {
61
+ const resolution = await resolvePrincipal(auth, req);
62
+ return 'principal' in resolution && resolution.principal !== null;
63
+ },
64
+ everyMs: auth.sessionRecheckMs,
65
+ });
66
+ export const registerRoutes = (app, ctx, subscribeToChanges, auth = DISABLED_AUTH) => {
67
+ const definitions = buildRouteDefinitions(ctx);
68
+ mountRoutes(app, definitions, ctx);
69
+ const authRequired = auth.mode === AuthMode.enum.required;
70
+ registerUiRoutes(app, subscribeToChanges, {
71
+ authControls: authRequired,
72
+ session: authRequired ? sessionRecheck(auth) : undefined,
73
+ });
74
+ if (authRequired) {
75
+ registerAuthRoutes(app, auth);
76
+ registerTokenRoutes(app, auth);
77
+ registerConnectRoutes(app, auth);
78
+ registerUserRoutes(app, auth);
79
+ registerInviteRoutes(app, auth);
80
+ registerProtectedResourceMetadataRoutes(app, auth.publicUrl);
81
+ }
82
+ // Built from the same list just mounted; excluded from its own document by design.
83
+ const openApiDocument = buildOpenApiDocument(definitions, ctx.version);
84
+ app.get('/api/openapi.json', { config: { scope: READ_SCOPE } }, async (_req, reply) => reply.header('cache-control', CACHE_CONTROL_NO_CACHE).send(openApiDocument));
85
+ };
@@ -0,0 +1,34 @@
1
+ import { authenticate } from '../../controllers/auth/session.js';
2
+ import { authenticateToken } from '../../controllers/auth/access-tokens.js';
3
+ import { authErrors } from '../../models/auth/errors.js';
4
+ import { UserRole } from '../../models/auth/owner.js';
5
+ import { PrincipalVia } from '../../models/auth/principal.js';
6
+ import { readCookie, SESSION_COOKIE_NAME } from './cookies.js';
7
+ import { replyError } from './respond.js';
8
+ /** Who does this request's session cookie belong to? Slides, or deletes, the session as a side effect
9
+ * (`controllers/auth/session.ts`'s `authenticate`). Shared by the auth hook and long-lived streams that re-check. */
10
+ export const resolvePrincipal = async (auth, req) => {
11
+ const token = readCookie(req.headers.cookie, SESSION_COOKIE_NAME);
12
+ if (!token)
13
+ return { principal: null };
14
+ const result = await auth.runEffects(() => authenticate(auth.deps, auth.deps.secrets.hashSecret(token)));
15
+ return result.isOk() ? { principal: result.value } : { failure: result.error };
16
+ };
17
+ /** Whose personal access token is this? `null` for an unknown, revoked or expired one
18
+ * (`controllers/auth/access-tokens.ts`'s `authenticateToken`; `last_used_at` is touched at most every few minutes). */
19
+ export const resolveBearerPrincipal = async (auth, token) => {
20
+ const result = await auth.runEffects(() => authenticateToken(auth.deps, auth.deps.secrets.hashSecret(token)));
21
+ return result.isOk() ? { principal: result.value } : { failure: result.error };
22
+ };
23
+ /** The hook only authenticates a bearer on /api and /mcp, so a token should never reach a browser page — but "a token
24
+ * can never mint, widen or approve anything" is too important to rest on path routing alone, so each page that
25
+ * grants access also insists on a browser session. */
26
+ export const requireSession = async (req, reply) => req.principal?.via === PrincipalVia.enum.session ? undefined : replyError(reply, authErrors.sessionRequired);
27
+ /** User management is for administrators. Anyone else — a member — gets the answer for a page that does not exist
28
+ * (Fastify's own not-found reply), not a 403 that would reveal it is there. */
29
+ export const requireAdmin = async (req, reply) => {
30
+ if (req.principal?.role === UserRole.enum.admin)
31
+ return undefined;
32
+ reply.callNotFound();
33
+ return reply;
34
+ };