@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,51 @@
1
+ import * as R from 'remeda';
2
+ import { SignInDuration } from '../../models/auth/grant.js';
3
+ import { CONNECT_PASSWORD_PARAM } from '../../models/auth/origin.js';
4
+ import { PASSWORD_MAX_LENGTH } from '../../models/auth/password.js';
5
+ import { TokenAccess } from '../../models/auth/token.js';
6
+ import { sessionOnlyLabel } from '../../logic/auth/grant.js';
7
+ import { ACCESS_LABEL, errorBlock, escapeHtml, fillTemplate, formatMinute } from './auth-pages.js';
8
+ import { CONNECT_PATH, UI_APP_CSS_PATH, UI_ROOT_PATH } from './auth-paths.js';
9
+ import { readCached, UI_ROOT } from './ui-files.js';
10
+ const CONNECT_TEMPLATE_PATH = `${UI_ROOT}/connect.html`;
11
+ const CONNECT_RESULT_TEMPLATE_PATH = `${UI_ROOT}/connect-result.html`;
12
+ // Typed by the enum, so a new duration cannot exist without a label here — and the radio values the form posts are the
13
+ // very values `ConnectFormSchema` accepts.
14
+ const SAVED_DURATION_LABEL = {
15
+ '24h': '24 hours',
16
+ '7d': '7 days',
17
+ '30d': '30 days',
18
+ };
19
+ const durationLabel = (duration, clientName) => duration === SignInDuration.enum.session ? sessionOnlyLabel(clientName) : SAVED_DURATION_LABEL[duration];
20
+ const radio = (name, value, label, checked) => `<label><input type="radio" name="${name}" value="${escapeHtml(value)}"${checked ? ' checked' : ''} required />` +
21
+ `${escapeHtml(label)}</label>`;
22
+ const accessOptions = (selected) => TokenAccess.options.map((access) => radio('access', access, ACCESS_LABEL[access], access === selected)).join('');
23
+ // Only what the asker may have (`logic/auth/grant.ts`'s `offeredDurations`): "this session only" is for a stdio
24
+ // process, which has a session to tie the sign-in to, and nothing is above the instance's cap.
25
+ const durationOptions = (request, offered, selected) => R.map(offered, (duration) => radio('duration', duration, durationLabel(duration, request.clientName), duration === selected)).join('');
26
+ export const renderConnectPage = async (fields) => fillTemplate(await readCached(CONNECT_TEMPLATE_PATH), {
27
+ stylesheet: UI_APP_CSS_PATH,
28
+ action: CONNECT_PATH,
29
+ // Everything the client reported is escaped: it is whatever the spawning program chose to call itself.
30
+ clientName: escapeHtml(fields.request.clientName),
31
+ clientVersion: escapeHtml(fields.request.clientVersion),
32
+ profile: escapeHtml(fields.request.profile),
33
+ requestedAt: formatMinute(fields.request.createdAt),
34
+ userCode: escapeHtml(fields.request.userCode),
35
+ passwordName: CONNECT_PASSWORD_PARAM,
36
+ passwordMaxLength: String(PASSWORD_MAX_LENGTH),
37
+ accessOptions: accessOptions(fields.choice.access),
38
+ durationOptions: durationOptions(fields.request, fields.durations, fields.choice.duration),
39
+ error: errorBlock(fields.error),
40
+ });
41
+ const CLOSE_TAB_HINT = 'You can close this tab.';
42
+ // Once a request is answered the page has nothing left to offer: a temporary server (`patty login`, or a stdio
43
+ // process whose own dashboard could not start) closes as soon as the sign-in is picked up, so a link back to its
44
+ // dashboards would be dead moments later. A page that is only an error keeps the way out while the server still lives.
45
+ const nextStep = (answered) => answered ? `<p>${CLOSE_TAB_HINT}</p>` : `<p><a href="${UI_ROOT_PATH}">Back to the dashboards</a></p>`;
46
+ export const renderConnectResultPage = async (fields) => fillTemplate(await readCached(CONNECT_RESULT_TEMPLATE_PATH), {
47
+ stylesheet: UI_APP_CSS_PATH,
48
+ heading: escapeHtml(fields.heading),
49
+ message: escapeHtml(fields.message),
50
+ next: nextStep(fields.answered ?? false),
51
+ });
@@ -0,0 +1,17 @@
1
+ import { AuthMode } from '../../models/auth/mode.js';
2
+ import { LOG_PREFIX } from '../../models/package.js';
3
+ const DOCUMENTATION_ONLY = () => {
4
+ throw new Error(`${LOG_PREFIX} this HTTP context only documents the routes (OpenAPI) — it serves none`);
5
+ };
6
+ /** Builds the route list for documentation only (no request, no principal); handlers must never run. */
7
+ export const documentationContext = (version) => ({
8
+ version,
9
+ publicDeps: { health: { reachable: DOCUMENTATION_ONLY } },
10
+ instanceKind: DOCUMENTATION_ONLY,
11
+ instanceLocale: DOCUMENTATION_ONLY,
12
+ depsFor: DOCUMENTATION_ONLY,
13
+ runEffectsFor: DOCUMENTATION_ONLY,
14
+ runEffectsSequenceFor: DOCUMENTATION_ONLY,
15
+ resetLocaleFor: DOCUMENTATION_ONLY,
16
+ });
17
+ export const DISABLED_AUTH = { mode: AuthMode.enum.disabled };
@@ -0,0 +1,27 @@
1
+ import { SESSION_ABSOLUTE_MAX_MS } from '../../models/auth/session.js';
2
+ /** The browser session cookie (ADR-033 §2). One name, used by the hook that reads it and the routes that
3
+ * set and clear it. */
4
+ export const SESSION_COOKIE_NAME = 'patty_session';
5
+ const COOKIE_PAIR_SEPARATOR = ';';
6
+ const COOKIE_VALUE_SEPARATOR = '=';
7
+ const SECOND_MS = 1000;
8
+ /** The value of cookie `name` in a `Cookie` request header, or `undefined`. Session tokens are base64url,
9
+ * so no percent-decoding is needed — and none is done, so an encoded lookalike never matches. */
10
+ export const readCookie = (header, name) => header
11
+ ?.split(COOKIE_PAIR_SEPARATOR)
12
+ .map((pair) => pair.trim())
13
+ .find((pair) => pair.startsWith(`${name}${COOKIE_VALUE_SEPARATOR}`))
14
+ ?.slice(name.length + COOKIE_VALUE_SEPARATOR.length);
15
+ // HttpOnly: no script can read it. SameSite=Lax: not sent on cross-site POSTs (CSRF layer one — the
16
+ // Origin check is layer two). Secure only over https: a Secure cookie is dropped by browsers on plain
17
+ // http, which would break login on loopback.
18
+ const serialize = (value, { secure, maxAgeMs }) => [
19
+ `${SESSION_COOKIE_NAME}${COOKIE_VALUE_SEPARATOR}${value}`,
20
+ 'Path=/',
21
+ 'HttpOnly',
22
+ 'SameSite=Lax',
23
+ `Max-Age=${Math.max(0, Math.floor(maxAgeMs / SECOND_MS))}`,
24
+ ...(secure ? ['Secure'] : []),
25
+ ].join(`${COOKIE_PAIR_SEPARATOR} `);
26
+ export const sessionCookie = (token, secure) => serialize(token, { secure, maxAgeMs: SESSION_ABSOLUTE_MAX_MS });
27
+ export const clearedSessionCookie = (secure) => serialize('', { secure, maxAgeMs: 0 });
@@ -0,0 +1,38 @@
1
+ import { httpStatus } from '../../common/errors.js';
2
+ import { authErrors } from '../../models/auth/errors.js';
3
+ import { HTML_CONTENT_TYPE } from './ui-files.js';
4
+ /** Server-rendered, form-posting pages (the sign-in pages and the token pages): one set of headers and one
5
+ * urlencoded parser, so no page can be a little less locked down than its neighbour. */
6
+ export const FORM_BODY_LIMIT_BYTES = 8 * 1024;
7
+ // A wrong step-up password is a refused action inside a valid session, not a missing credential.
8
+ export const STEP_UP_REFUSED_STATUS = httpStatus(authErrors.sessionRequired);
9
+ const FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded';
10
+ // These pages are tiny, self-contained and framed by nobody: lock everything down (no scripts, no
11
+ // third-party loads, no embedding) and never let a proxy or the back button keep a copy.
12
+ const PAGE_HEADERS = {
13
+ 'cache-control': 'no-store',
14
+ 'content-security-policy': "default-src 'none'; style-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
15
+ 'x-frame-options': 'DENY',
16
+ // A dashboard script runs in this same origin; without this it could `window.open` one of these pages, keep the
17
+ // handle, and read the form or the one-time token. Same-origin COOP puts the page in its own browsing context group.
18
+ 'cross-origin-opener-policy': 'same-origin',
19
+ 'x-content-type-options': 'nosniff',
20
+ 'referrer-policy': 'same-origin',
21
+ };
22
+ /**
23
+ * A page whose URL carries a secret (an invite code) must not leak it through `Referer`: `strict-origin` sends
24
+ * the origin and never the path or query. Deliberately not `no-referrer` — with that policy a browser sends
25
+ * `Origin: null` on the page's own form POST, which the CSRF origin check (rightly) cannot accept.
26
+ */
27
+ export const SECRET_URL_HEADERS = { 'referrer-policy': 'strict-origin' };
28
+ export const page = (reply, status, html, overrides = {}) => reply
29
+ .status(status)
30
+ .headers({ ...PAGE_HEADERS, ...overrides })
31
+ .type(HTML_CONTENT_TYPE)
32
+ .send(html);
33
+ // An urlencoded body is only parsed in the scopes that call `addFormParser` — never app-wide, so `/api` keeps
34
+ // rejecting it.
35
+ const parseFormBody = (_req, body, done) => {
36
+ done(null, Object.fromEntries(new URLSearchParams(body)));
37
+ };
38
+ export const addFormParser = (scope) => scope.addContentTypeParser(FORM_CONTENT_TYPE, { parseAs: 'string', bodyLimit: FORM_BODY_LIMIT_BYTES }, parseFormBody);
@@ -0,0 +1,106 @@
1
+ import { startsAtSetup } from '../../../controllers/auth/owner.js';
2
+ import { acceptsBearer, credentialOf } from '../../../logic/auth/bearer.js';
3
+ import { csrfVerdict, isLoopbackRequest, preSessionCsrfVerdict } from '../../../logic/auth/origin.js';
4
+ import { defaultScopeForMethod, hasScope } from '../../../logic/auth/scope.js';
5
+ import { authErrors } from '../../../models/auth/errors.js';
6
+ import { AuthMode } from '../../../models/auth/mode.js';
7
+ import { isUiPath } from '../../../models/auth/origin.js';
8
+ import { OWNER_PRINCIPAL } from '../../../models/auth/principal.js';
9
+ import { safeNextPath } from '../../../wire/in/auth.js';
10
+ import { isPublicRoute, LOGIN_PATH, SEE_OTHER, SETUP_PATH } from '../auth-paths.js';
11
+ import { rejectWithChallenge } from '../bearer.js';
12
+ import { replyError as reject } from '../respond.js';
13
+ import { resolveBearerPrincipal, resolvePrincipal } from '../session.js';
14
+ /**
15
+ * The auth hook (ADR-033 §1, §2, §6): an inbound-edge request interceptor — read the headers, route pattern and
16
+ * session cookie, ask `logic/auth/` and `controllers/auth/owner.ts` for the decision, translate it to 401 / 403 /
17
+ * redirect / `req.principal`. No policy lives here; `composition/http.ts` registers it on the root instance BEFORE any
18
+ * route (ordering is wiring), so it also guards a request no route matches.
19
+ * - auth `disabled` (loopback) → the owner — but only for a request that names a loopback `Host` (and
20
+ * `Origin`, if sent): anything else is a DNS-rebound or cross-site page and gets 403 on every route;
21
+ * - auth `required` → on `/api` and `/mcp` an `Authorization` header is AUTHORITATIVE: it must be
22
+ * `Bearer ptk_…` and valid, and the cookie is then ignored — a bad bearer never falls back to a session, and a
23
+ * bearer request carries no ambient credential, so it skips the CSRF check. Otherwise (no header, or a `/ui`
24
+ * path, where a bearer is never accepted) the session cookie's user. No credential → 401 + a Bearer challenge
25
+ * (anything not under `/ui`) or a redirect to setup/login (`/ui`). The principal's scopes are then checked
26
+ * against the matched route's declared scope. Only `PUBLIC_ROUTES` skip all of this.
27
+ * stdio never reaches this hook: it is trusted and acts as the owner too (`OWNER_PRINCIPAL`).
28
+ */
29
+ const NEXT_PARAM = 'next';
30
+ const pathOf = (url) => url.split('?')[0] ?? url;
31
+ const isLoginOrSetup = (path) => path === LOGIN_PATH || path === SETUP_PATH;
32
+ const csrfInput = (req, publicUrl) => ({
33
+ method: req.method,
34
+ publicUrl,
35
+ host: req.headers.host,
36
+ origin: req.headers.origin,
37
+ referer: req.headers.referer,
38
+ });
39
+ const loginRedirectTarget = (req) => {
40
+ const next = safeNextPath(req.url);
41
+ return next === req.url && !isLoginOrSetup(pathOf(next))
42
+ ? `${LOGIN_PATH}?${NEXT_PARAM}=${encodeURIComponent(next)}`
43
+ : LOGIN_PATH;
44
+ };
45
+ const admitOwnerOnLoopback = async (req, reply) => {
46
+ // Never echo the offending header back: the hint is a constant.
47
+ if (!isLoopbackRequest({ host: req.headers.host, origin: req.headers.origin })) {
48
+ return reject(reply, authErrors.nonLoopbackRequest);
49
+ }
50
+ req.principal = OWNER_PRINCIPAL;
51
+ return undefined;
52
+ };
53
+ const rejectUnauthenticated = async (auth, req, reply) => {
54
+ if (!isUiPath(pathOf(req.url)))
55
+ return rejectWithChallenge(req, reply, auth.publicUrl, authErrors.unauthenticated);
56
+ const target = (await startsAtSetup(auth.deps)) ? SETUP_PATH : loginRedirectTarget(req);
57
+ return reply.redirect(target, SEE_OTHER);
58
+ };
59
+ // A route's declared scope (RouteDefinition.scope); a route that declares none falls back to the method rule.
60
+ const requiredScope = (req) => req.routeOptions.config?.scope ?? defaultScopeForMethod(req.method);
61
+ const admit = (auth, req, reply, principal) => {
62
+ const required = requiredScope(req);
63
+ if (!hasScope(principal.scopes, required)) {
64
+ return rejectWithChallenge(req, reply, auth.publicUrl, authErrors.insufficientScope(required));
65
+ }
66
+ req.principal = principal;
67
+ return undefined;
68
+ };
69
+ const authenticateBearer = async (auth, req, reply, token) => {
70
+ if (token === null)
71
+ return rejectWithChallenge(req, reply, auth.publicUrl, authErrors.invalidToken);
72
+ const resolved = await resolveBearerPrincipal(auth, token);
73
+ if ('failure' in resolved)
74
+ return reject(reply, resolved.failure);
75
+ if (resolved.principal === null)
76
+ return rejectWithChallenge(req, reply, auth.publicUrl, authErrors.invalidToken);
77
+ return admit(auth, req, reply, resolved.principal);
78
+ };
79
+ // Decide from the route the router actually matched (it decodes `/%61pi/…` to `/api/…`); the raw path only
80
+ // for a request no route matched, where the answer is a 404 or a 401 anyway.
81
+ const bearerCredentialOf = (req) => acceptsBearer(req.routeOptions.url ?? pathOf(req.url)) ? credentialOf(req.headers.authorization) : null;
82
+ const authenticateSession = async (auth, req, reply) => {
83
+ const resolved = await resolvePrincipal(auth, req);
84
+ if ('failure' in resolved)
85
+ return reject(reply, resolved.failure);
86
+ if (resolved.principal === null)
87
+ return rejectUnauthenticated(auth, req, reply);
88
+ // Cookie-authenticated, so unsafe methods (including POST /mcp) must come from our own origin.
89
+ const verdict = csrfVerdict(csrfInput(req, auth.publicUrl));
90
+ return verdict ? reject(reply, verdict) : admit(auth, req, reply, resolved.principal);
91
+ };
92
+ const guardRequest = (auth) => async (req, reply) => {
93
+ if (isPublicRoute(req.routeOptions.url, req.method)) {
94
+ const verdict = preSessionCsrfVerdict(csrfInput(req, auth.publicUrl));
95
+ return verdict ? reject(reply, verdict) : undefined;
96
+ }
97
+ const credential = bearerCredentialOf(req);
98
+ if (credential !== null && credential.kind !== 'none') {
99
+ return authenticateBearer(auth, req, reply, credential.kind === 'bearer' ? credential.token : null);
100
+ }
101
+ return authenticateSession(auth, req, reply);
102
+ };
103
+ export const registerAuthHook = (app, auth) => {
104
+ app.decorateRequest('principal', undefined);
105
+ app.addHook('onRequest', auth.mode === AuthMode.enum.disabled ? admitOwnerOnLoopback : guardRequest(auth));
106
+ };
@@ -0,0 +1,59 @@
1
+ import { instanceFactsOf } from '../../../controllers/instance.js';
2
+ import { InstanceKind, isDemoInstance } from '../../../models/instance.js';
3
+ import { Locale } from '../../../models/locale.js';
4
+ import { PRODUCT_NAME, REPOSITORY_URL } from '../../../models/package.js';
5
+ import { escapeHtml } from '../auth-pages.js';
6
+ import { HTML_CONTENT_TYPE } from '../ui-files.js';
7
+ /** The attribute `ui/app.js` reads to keep `[Demo]` in the titles it sets after load. */
8
+ export const INSTANCE_KIND_ATTRIBUTE = 'data-instance-kind';
9
+ export const DEMO_TITLE_PREFIX = '[Demo] ';
10
+ /** The banner in the demo's language (`user_settings.locale`, set by the seeder). */
11
+ export const DEMO_BANNER_COPY = {
12
+ [Locale.enum.en]: {
13
+ label: 'Demo',
14
+ message: 'sample data, not your finances.',
15
+ linkText: `Install ${PRODUCT_NAME} for your own data`,
16
+ },
17
+ [Locale.enum.pt]: {
18
+ label: 'Demo',
19
+ message: 'dados de exemplo, não as suas finanças.',
20
+ linkText: `Instale o ${PRODUCT_NAME} para usar seus próprios dados`,
21
+ },
22
+ [Locale.enum.es]: {
23
+ label: 'Demo',
24
+ message: 'datos de ejemplo, no tus finanzas.',
25
+ linkText: `Instala ${PRODUCT_NAME} para usar tus propios datos`,
26
+ },
27
+ };
28
+ const BANNER_LINK_URL = `${REPOSITORY_URL}#readme`;
29
+ // Classes live in ui/app.css: the auth pages' CSP allows `style-src 'self'` only, so no inline style can carry this.
30
+ const bannerHtml = (locale) => {
31
+ const { label, message, linkText } = DEMO_BANNER_COPY[locale];
32
+ return (`<div class="demo-banner" role="note" lang="${locale}">` +
33
+ `<strong>${escapeHtml(label)}</strong> — ${escapeHtml(message)} ` +
34
+ `<a href="${BANNER_LINK_URL}" target="_blank" rel="noopener noreferrer">${escapeHtml(linkText)}</a>` +
35
+ '</div>');
36
+ };
37
+ const TITLE_OPEN = /<title>/;
38
+ const BODY_OPEN = /<body([^>]*)>/;
39
+ /** A full HTML document gets the banner as the first thing in `<body>` and `[Demo]` at the start of its title. A
40
+ * fragment (no `<body>`) is returned as is: the page that embeds it already carries both. */
41
+ export const markDemoPage = (html, locale) => BODY_OPEN.test(html)
42
+ ? html
43
+ .replace(TITLE_OPEN, `<title>${DEMO_TITLE_PREFIX}`)
44
+ .replace(BODY_OPEN, `<body$1 ${INSTANCE_KIND_ATTRIBUTE}="${InstanceKind.enum.demo}">${bannerHtml(locale)}`)
45
+ : html;
46
+ const isHtmlDocument = (contentType, payload) => typeof payload === 'string' && String(contentType ?? '').startsWith(HTML_CONTENT_TYPE.split(';')[0] ?? '');
47
+ /**
48
+ * Marks every HTML page — the shell and the auth pages alike — when the database says it is a demo, in the language
49
+ * the demo speaks. The marker is read from the database on each page, not from a path or an env var, so a demo
50
+ * database cannot be served without it.
51
+ */
52
+ export const registerDemoMarkerHook = (app, tenancy) => {
53
+ app.addHook('onSend', async (_req, reply, payload) => {
54
+ if (!isHtmlDocument(reply.getHeader('content-type'), payload))
55
+ return payload;
56
+ const { kind, locale } = await instanceFactsOf(tenancy);
57
+ return isDemoInstance(kind) ? markDemoPage(payload, locale) : payload;
58
+ });
59
+ };
@@ -0,0 +1,73 @@
1
+ import { extendZodWithOpenApi, OpenAPIRegistry, OpenApiGeneratorV3, } from '@asteasolutions/zod-to-openapi';
2
+ import './principal.js';
3
+ import { z } from 'zod';
4
+ import { scopedFor } from '../../controllers/deps.js';
5
+ import { LOG_PREFIX, PRODUCT_NAME } from '../../models/package.js';
6
+ /**
7
+ * OpenAPI machinery shared by every REST route. routes.ts builds ONE array of route
8
+ * definitions (method/path/schemas/handler) — the single source of truth. `mountRoutes`
9
+ * registers it on Fastify; `buildOpenApiDocument` documents it. Neither needs the other, so
10
+ * the MCP resource (which has no Fastify instance under stdio transport) can call
11
+ * `buildOpenApiDocument` directly on the same array with nothing to keep in sync (ADR-013 Phase A).
12
+ *
13
+ * This module holds only routing/doc-generation mechanics — no wire schemas. Response and
14
+ * request shapes are domain wire contracts and live in `wire/out/*` and `wire/in/*`, same as
15
+ * everywhere else in the app; routes.ts imports them from there.
16
+ */
17
+ extendZodWithOpenApi(z);
18
+ // Route definitions write paths in Fastify's `:param` syntax (the only form Fastify accepts);
19
+ // this is the sole conversion to OpenAPI's `{param}` syntax, applied when documenting.
20
+ const toOpenApiPath = (fastifyPath) => fastifyPath.replace(/:([A-Za-z]+)/g, '{$1}');
21
+ export const MISSING_PRINCIPAL_MESSAGE = `${LOG_PREFIX} a route reached user data without an authenticated principal`;
22
+ const withScope = (tenancy, handler) => (req, reply) => handler(req, reply, () => {
23
+ if (!req.principal)
24
+ throw new Error(MISSING_PRINCIPAL_MESSAGE);
25
+ return scopedFor(tenancy, req.principal);
26
+ });
27
+ export const mountRoutes = (app, definitions, tenancy) => {
28
+ for (const { method, path, scope, handler } of definitions) {
29
+ const options = { config: { scope } };
30
+ const scoped = withScope(tenancy, handler);
31
+ switch (method) {
32
+ case 'get':
33
+ app.get(path, options, scoped);
34
+ break;
35
+ case 'post':
36
+ app.post(path, options, scoped);
37
+ break;
38
+ case 'patch':
39
+ app.patch(path, options, scoped);
40
+ break;
41
+ case 'delete':
42
+ app.delete(path, options, scoped);
43
+ break;
44
+ default: {
45
+ const _exhaustive = method;
46
+ throw new Error(`unmapped HTTP method: ${JSON.stringify(_exhaustive)}`);
47
+ }
48
+ }
49
+ }
50
+ };
51
+ export const buildOpenApiDocument = (definitions, version) => {
52
+ const registry = new OpenAPIRegistry();
53
+ for (const { handler: _handler, scope: _scope, ...meta } of definitions) {
54
+ registry.registerPath({ ...meta, path: toOpenApiPath(meta.path) });
55
+ }
56
+ const generator = new OpenApiGeneratorV3(registry.definitions);
57
+ return generator.generateDocument({
58
+ openapi: '3.0.3',
59
+ info: {
60
+ title: `${PRODUCT_NAME} API`,
61
+ version,
62
+ description: `REST contract for the ${PRODUCT_NAME} HTTP API (ADR-013). MCP (POST /mcp) is the primary surface; ` +
63
+ 'this document exists so agent-generated dashboards can call /api with correct request/response shapes.',
64
+ },
65
+ });
66
+ };
67
+ // ─── OpenAPI response-config formatting — presentation glue, not domain/wire shapes ───
68
+ const jsonContent = (schema) => ({ 'application/json': { schema } });
69
+ export const jsonBody = (schema) => ({ content: jsonContent(schema) });
70
+ export const okResponse = (description, schema) => ({
71
+ description,
72
+ content: jsonContent(schema),
73
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,78 @@
1
+ // A cap on tracked keys: an attacker spraying random usernames must not be able to grow this without bound.
2
+ const MAX_TRACKED_KEYS = 10_000;
3
+ export const createRateLimiter = (options) => {
4
+ const failures = new Map();
5
+ const recent = (key) => {
6
+ const cutoff = options.now() - options.windowMs;
7
+ const kept = (failures.get(key) ?? []).filter((at) => at > cutoff);
8
+ if (kept.length === 0)
9
+ failures.delete(key);
10
+ else
11
+ failures.set(key, kept);
12
+ return kept;
13
+ };
14
+ return {
15
+ isLimited: (key) => recent(key).length >= options.maxFailures,
16
+ recordFailure: (key) => {
17
+ const kept = recent(key);
18
+ if (kept.length === 0 && failures.size >= MAX_TRACKED_KEYS) {
19
+ const oldest = failures.keys().next().value;
20
+ if (oldest !== undefined)
21
+ failures.delete(oldest);
22
+ }
23
+ failures.set(key, [...kept, options.now()]);
24
+ },
25
+ reset: (key) => {
26
+ failures.delete(key);
27
+ },
28
+ forgive: (key) => {
29
+ const kept = recent(key).slice(0, -1);
30
+ if (kept.length === 0)
31
+ failures.delete(key);
32
+ else
33
+ failures.set(key, kept);
34
+ },
35
+ };
36
+ };
37
+ const MINUTE_MS = 60_000;
38
+ export const LOGIN_ATTEMPT_WINDOW_MS = 15 * MINUTE_MS;
39
+ export const MAX_FAILURES_PER_IP = 20;
40
+ export const MAX_FAILURES_PER_USERNAME = 5;
41
+ /** Failed `/ui/connect` code lookups (unknown, expired or already-answered codes) per client IP in that window. */
42
+ export const MAX_CODE_LOOKUP_FAILURES_PER_IP = 10;
43
+ const ipKey = (ip) => `ip:${ip}`;
44
+ const usernameKey = (username) => `username:${username}`;
45
+ export const createAttemptLimiter = (now = Date.now) => {
46
+ const perIp = createRateLimiter({ windowMs: LOGIN_ATTEMPT_WINDOW_MS, maxFailures: MAX_FAILURES_PER_IP, now });
47
+ const perUsername = createRateLimiter({
48
+ windowMs: LOGIN_ATTEMPT_WINDOW_MS,
49
+ maxFailures: MAX_FAILURES_PER_USERNAME,
50
+ now,
51
+ });
52
+ const limiter = {
53
+ isLimited: (ip, username) => perIp.isLimited(ipKey(ip)) || perUsername.isLimited(usernameKey(username)),
54
+ recordFailure: (ip, username) => {
55
+ perIp.recordFailure(ipKey(ip));
56
+ perUsername.recordFailure(usernameKey(username));
57
+ },
58
+ recordSuccess: (ip, username) => {
59
+ perUsername.reset(usernameKey(username));
60
+ perIp.forgive(ipKey(ip));
61
+ },
62
+ forgive: (ip, username) => {
63
+ perIp.forgive(ipKey(ip));
64
+ perUsername.forgive(usernameKey(username));
65
+ },
66
+ attempt: async (ip, username, run) => {
67
+ limiter.recordFailure(ip, username);
68
+ try {
69
+ return await run();
70
+ }
71
+ catch (cause) {
72
+ limiter.forgive(ip, username);
73
+ throw cause;
74
+ }
75
+ },
76
+ };
77
+ return limiter;
78
+ };
@@ -0,0 +1,26 @@
1
+ import { withRemedyHint } from '../../common/errors.js';
2
+ /**
3
+ * The route that performs each domain operation a rejected call is told to use instead. The route definitions take
4
+ * their method and path from here (`...REMEDY_ROUTE.pay_bill`), so each path is typed once and a hint can never drift
5
+ * from the route it names. A leaf module (type imports only): `respond.ts` needs it, and the route modules need
6
+ * `respond.ts`.
7
+ */
8
+ export const REMEDY_ROUTE = {
9
+ pay_bill: { method: 'post', path: '/api/bills/pay' },
10
+ revert_bill_payment: { method: 'post', path: '/api/bills/revert' },
11
+ create_credit_card: { method: 'post', path: '/api/credit-cards' },
12
+ update_credit_card: { method: 'patch', path: '/api/credit-cards/:name' },
13
+ delete_credit_card: { method: 'delete', path: '/api/credit-cards/:name' },
14
+ update_account_transaction: { method: 'patch', path: '/api/accounts/transactions/:id' },
15
+ update_card_transaction: { method: 'patch', path: '/api/credit-cards/transactions/:id' },
16
+ delete_account_transaction: { method: 'delete', path: '/api/accounts/transactions/:id' },
17
+ delete_card_transaction: { method: 'delete', path: '/api/credit-cards/transactions/:id' },
18
+ };
19
+ /** `"METHOD /path"` of the route that performs the remedy. */
20
+ export const remedyRoute = (remedy) => {
21
+ const { method, path } = REMEDY_ROUTE[remedy];
22
+ return `${method.toUpperCase()} ${path}`;
23
+ };
24
+ export const remedyHint = (remedy) => `use ${remedyRoute(remedy)}`;
25
+ /** The error as a REST reply shows it: a `remedy` becomes `hint: "use <METHOD /route>"`. */
26
+ export const withRouteHint = (error) => withRemedyHint(error, remedyHint);
@@ -0,0 +1,50 @@
1
+ import { httpStatus } from '../../common/errors.js';
2
+ import { ConfirmQuerySchema, IdParamSchema, NameParamSchema } from '../../wire/in/common.js';
3
+ import { ConflictErrorOut, NotFoundErrorOut, ValidationErrorOut } from '../../wire/out/errors.js';
4
+ import { okResponse } from './openapi.js';
5
+ import { withRouteHint } from './remedy.js';
6
+ /** Shared HTTP response helpers (ADR-025) — one implementation for every route module. */
7
+ /** The one error reply shape: the error's HTTP status and `{ error }`. */
8
+ export const replyError = (reply, error) => reply.status(httpStatus(error)).send({ error: withRouteHint(error) });
9
+ export const send = (reply, result, okStatus = 200) => result.match((value) => reply.status(okStatus).send(value), (e) => replyError(reply, e));
10
+ /** The one 422 reply shape: `{ error: { code: 'validation', issues } }`. */
11
+ export const unprocessable = (reply, issues) => reply.status(422).send({ error: { code: 'validation', issues } });
12
+ export const parse = (schema, body, reply) => {
13
+ const r = schema.safeParse(body);
14
+ if (!r.success) {
15
+ unprocessable(reply, r.error.issues.map((i) => i.message));
16
+ return null;
17
+ }
18
+ return r.data;
19
+ };
20
+ // Some handlers report one fixed message on a failed safeParse rather than `parse`'s per-field zod issues, since a
21
+ // query string (or an optional body) is already loosely typed at that point.
22
+ const INVALID_QUERY_ISSUE = 'invalid query';
23
+ export const invalidQueryResponse = (reply, issue = INVALID_QUERY_ISSUE) => unprocessable(reply, [issue]);
24
+ /** `parse`, but a failure answers with one fixed `issue` instead of the per-field zod messages. */
25
+ export const parseOrIssue = (schema, input, reply, issue) => {
26
+ const r = schema.safeParse(input);
27
+ if (!r.success) {
28
+ invalidQueryResponse(reply, issue);
29
+ return null;
30
+ }
31
+ return r.data;
32
+ };
33
+ /** 201 when the write created something, 200 on an idempotent replay. */
34
+ export const sendUpsert = (reply, result) => result.match((value) => reply.status(value.created ? 201 : 200).send(value), (e) => replyError(reply, e));
35
+ /** A route's `:name` / `:id` path parameter. */
36
+ export const pathParam = (req, key) => req.params[key];
37
+ /** `?confirm=true` — the opt-in that turns a destructive route's dry-run preview into the real thing. */
38
+ export const isConfirmed = (req) => req.query.confirm === 'true';
39
+ // OpenAPI response-config shorthands, reused across route modules — composed here (not in
40
+ // openapi.ts) because they're built from wire/out/errors.js schemas, and openapi.ts stays
41
+ // domain/wire-agnostic (routing + doc-generation mechanics only).
42
+ export const validation422 = okResponse('Validation error', ValidationErrorOut);
43
+ export const notFound404 = okResponse('Not found', NotFoundErrorOut);
44
+ export const conflict409 = okResponse('Conflict', ConflictErrorOut);
45
+ export const nameParam = NameParamSchema;
46
+ export const idParam = IdParamSchema;
47
+ export const confirmQuery = ConfirmQuerySchema;
48
+ // Shared by /ui/:name (routes/dashboard.ts) and /api/openapi.json (routes.ts) — both must never
49
+ // be masked by a stale browser copy.
50
+ export const CACHE_CONTROL_NO_CACHE = 'no-cache';