@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,28 @@
1
+ import { ok, okAsync, safeTry } from 'neverthrow';
2
+ import * as R from 'remeda';
3
+ import { guard } from '../../common/result.js';
4
+ import { assertExclusivePeriodOrRange, periodBounds } from '../../logic/period.js';
5
+ import { addLocalizedLabels, nextCursorAfter, resolveCursorKey } from '../../logic/transaction.js';
6
+ import { transactionErrors, } from '../../models/transaction.js';
7
+ import { resolveAccountRef, resolveCategoryRef, resolveSubCategoryRef } from '../resolve.js';
8
+ const optionalId = (name, resolve) => (name ? resolve(name).map((entity) => entity.id) : okAsync(null));
9
+ const resolveSearchRefs = (deps, input) => safeTry(async function* () {
10
+ const accountId = yield* optionalId(input.account, (name) => resolveAccountRef(deps, name));
11
+ const categoryId = yield* optionalId(input.category, (name) => resolveCategoryRef(deps, name));
12
+ const subCategoryId = yield* optionalId(input.subCategory, (name) => resolveSubCategoryRef(deps, name));
13
+ const cursorKey = yield* resolveCursorKey(input);
14
+ return ok({ accountId, categoryId, subCategoryId, ...periodBounds(input), cursorKey });
15
+ });
16
+ export const searchTransactions = (deps, input) => safeTry(async function* () {
17
+ yield* guard(assertExclusivePeriodOrRange(input), transactionErrors.exclusivePeriodRange);
18
+ const refs = yield* resolveSearchRefs(deps, input);
19
+ const [locale, page, total] = await Promise.all([
20
+ deps.locale(),
21
+ deps.transactions.search(input, refs),
22
+ input.includeTotal ? deps.transactions.count(input, refs) : Promise.resolve(undefined),
23
+ ]);
24
+ const items = page.items.map(addLocalizedLabels(locale));
25
+ const lastItem = R.last(items);
26
+ const nextCursor = page.hasMore && lastItem ? nextCursorAfter(lastItem, input.sort, input.dir) : undefined;
27
+ return ok({ items, nextCursor, total });
28
+ });
@@ -0,0 +1,58 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { hash, verify } from '@node-rs/argon2';
3
+ import { USER_CODE_LENGTH } from '../../models/auth/grant.js';
4
+ import { TOKEN_PREFIX } from '../../models/auth/token.js';
5
+ // OWASP Password Storage Cheat Sheet, first-choice argon2id parameters. `@node-rs/argon2` defaults to
6
+ // argon2id when no algorithm is given (its `Algorithm` enum is not available at runtime to import).
7
+ const ARGON2_MEMORY_COST_KIB = 47_104;
8
+ const ARGON2_TIME_COST = 1;
9
+ const ARGON2_PARALLELISM = 1;
10
+ const ARGON2_OPTIONS = {
11
+ memoryCost: ARGON2_MEMORY_COST_KIB,
12
+ timeCost: ARGON2_TIME_COST,
13
+ parallelism: ARGON2_PARALLELISM,
14
+ };
15
+ const TOKEN_BYTES = 32; // 256 bits — session tokens and access tokens alike
16
+ const TOKEN_ENCODING = 'base64url';
17
+ const HASH_ALGORITHM = 'sha256';
18
+ const HASH_ENCODING = 'hex';
19
+ // Crockford base32: 32 symbols with no I, L, O or U, so a code survives being read aloud or retyped.
20
+ // A setup code is 20 symbols (100 bits), a sign-in user code 8 (40 bits). 32 divides 256, so `byte & 31` is unbiased.
21
+ const SETUP_CODE_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
22
+ const SETUP_CODE_LENGTH = 20;
23
+ const SETUP_CODE_SYMBOL_MASK = SETUP_CODE_ALPHABET.length - 1;
24
+ export const hashPassword = (password) => hash(password, ARGON2_OPTIONS);
25
+ /** Constant-time compare inside argon2; an unparseable stored hash is a mismatch, never an exception. */
26
+ export const verifyPassword = async (storedHash, password) => {
27
+ try {
28
+ return await verify(storedHash, password);
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ };
34
+ export const randomToken = () => randomBytes(TOKEN_BYTES).toString(TOKEN_ENCODING);
35
+ /** `ptk_` + 32 random bytes, base64url — the prefix keeps a leaked token greppable (ADR-033 §3). */
36
+ export const randomAccessToken = () => `${TOKEN_PREFIX}${randomBytes(TOKEN_BYTES).toString(TOKEN_ENCODING)}`;
37
+ const randomCode = (length) => Array.from(randomBytes(length), (byte) => SETUP_CODE_ALPHABET[byte & SETUP_CODE_SYMBOL_MASK]).join('');
38
+ export const randomSetupCode = () => randomCode(SETUP_CODE_LENGTH);
39
+ /** An invite code is as strong as a setup code (100 bits): it is a bearer secret for up to 72 hours. */
40
+ export const randomInviteCode = () => randomCode(SETUP_CODE_LENGTH);
41
+ /** Short enough to type, valid only while pending (10 min) and single-use — the device code is the real secret. */
42
+ export const randomUserCode = () => randomCode(USER_CODE_LENGTH);
43
+ export const randomDeviceCode = () => randomBytes(TOKEN_BYTES).toString(TOKEN_ENCODING);
44
+ export const hashSecret = (secret) => createHash(HASH_ALGORITHM).update(secret).digest(HASH_ENCODING);
45
+ /** The real `AuthSecrets`. Built once at startup: it hashes a throwaway password so unknown-user logins
46
+ * have a genuine argon2id hash to verify against. */
47
+ export const createSecrets = async () => ({
48
+ hashPassword,
49
+ verifyPassword,
50
+ randomToken,
51
+ randomAccessToken,
52
+ randomSetupCode,
53
+ randomInviteCode,
54
+ randomUserCode,
55
+ randomDeviceCode,
56
+ hashSecret,
57
+ dummyPasswordHash: await hashPassword(randomToken()),
58
+ });
@@ -0,0 +1,18 @@
1
+ import { ResultAsync } from 'neverthrow';
2
+ import { KEYCHAIN_SERVICE, keychainFailures } from '../../models/auth/sign-in.js';
3
+ import { LOG_PREFIX } from '../../models/package.js';
4
+ /** The OS keychain, one entry per profile and database (ADR-034 §2). */
5
+ // The only other place besides the database key's that loads the native keychain module, and lazily, so a
6
+ // run that never signs in never loads it.
7
+ const loadKeyring = () => import('@napi-rs/keyring');
8
+ /** The one place the throwing native module is called: whatever it does with an entry becomes a `Result`. */
9
+ const useEntry = (account, action) => ResultAsync.fromPromise(loadKeyring().then(({ Entry }) => action(new Entry(KEYCHAIN_SERVICE, account))), keychainFailures.unavailable);
10
+ export const keychainSignInStore = (account, report = console.error) => ({
11
+ load: () => useEntry(account, (entry) => entry.getPassword() ?? null),
12
+ save: (token) => useEntry(account, (entry) => entry.setPassword(token)).match(() => true, () => {
13
+ report(`${LOG_PREFIX} could not save the sign-in to the OS keychain; it will last only until this process exits.`);
14
+ return false;
15
+ }),
16
+ // Nothing saved, or the keychain is unavailable: either way there is nothing left to remove.
17
+ clear: () => useEntry(account, (entry) => entry.deletePassword()).match(() => undefined, () => undefined),
18
+ });
@@ -0,0 +1,100 @@
1
+ import { formatAppError } from '../../../common/errors.js';
2
+ import { claimOwnerLocally, claimRaceWinnerOf, ownerClaimPlan } from '../../../controllers/auth/owner.js';
3
+ import { findResetTarget, resetPassword } from '../../../controllers/auth/password.js';
4
+ import { NPX_COMMAND } from '../../../models/package.js';
5
+ import { AUTH_POSITIONALS, AuthSubcommand, ClaimOptionsSchema, PASSWORD_STDIN_FLAG, ResetOptionsSchema, } from '../../../wire/in/cli.js';
6
+ import { EXIT_FAILURE, EXIT_OK, exitCodeOf, exitCodeOfPrompt, fail, failed, parseFlags, withShell, } from '../io.js';
7
+ import { CLI_MESSAGES } from '../messages.js';
8
+ import { collectNewCredentials, collectNewPassword } from '../prompt.js';
9
+ export const AUTH_HELP = `
10
+ Usage: ${NPX_COMMAND} auth <command>
11
+
12
+ Commands:
13
+ setup Choose the owner's username and password (once; claims the existing owner, never creates a user)
14
+ reset-password Choose a new password and end every session and access token of that user
15
+
16
+ Options:
17
+ --username <name> (setup) the owner's username — required with --${PASSWORD_STDIN_FLAG}
18
+ --user <name> (reset-password) whose password; default: the owner
19
+ --${PASSWORD_STDIN_FLAG} read the password from stdin instead of asking (scripted installs; stdin must not be a terminal)
20
+ `.trimStart();
21
+ const withPromptIo = async (io, options, work) => {
22
+ const terminal = options.passwordStdin ? null : io.openTerminal();
23
+ try {
24
+ return await work({ terminal, readPasswordFromStdin: io.readPasswordFromStdin });
25
+ }
26
+ finally {
27
+ terminal?.close();
28
+ }
29
+ };
30
+ export const ensureOwnerClaimed = (io, options) => withShell(io, async (shell) => {
31
+ const plan = await ownerClaimPlan(shell.deps);
32
+ if (plan.kind === 'skip') {
33
+ io.out(CLI_MESSAGES.alreadyClaimed(plan.username));
34
+ return EXIT_OK;
35
+ }
36
+ const credentials = await withPromptIo(io, options, (promptIo) => collectNewCredentials(promptIo, options));
37
+ if (credentials.isErr())
38
+ return exitCodeOfPrompt(io, credentials.error);
39
+ const claimed = await shell.run(() => claimOwnerLocally(shell.deps, credentials.value));
40
+ if (claimed.isOk()) {
41
+ io.out(CLI_MESSAGES.ownerClaimed(claimed.value.username));
42
+ return EXIT_OK;
43
+ }
44
+ const winner = await claimRaceWinnerOf(shell.deps, claimed.error);
45
+ if (winner) {
46
+ io.out(CLI_MESSAGES.alreadyClaimed(winner.username));
47
+ return EXIT_OK;
48
+ }
49
+ return failed(io, formatAppError(claimed.error));
50
+ }, EXIT_FAILURE);
51
+ const reportReset = (io, reset) => {
52
+ io.out(CLI_MESSAGES.passwordReset(reset));
53
+ io.out(CLI_MESSAGES.sessionsEnded(reset.sessionsEnded));
54
+ io.out(CLI_MESSAGES.tokensRevoked(reset.tokensRevoked));
55
+ };
56
+ const resetUserPassword = (io, options) => withShell(io, async (shell) => {
57
+ const target = await findResetTarget(shell.deps, options.user);
58
+ if (target.isErr())
59
+ return failed(io, formatAppError(target.error));
60
+ const password = await withPromptIo(io, options, (promptIo) => {
61
+ promptIo.terminal?.tell(CLI_MESSAGES.resetting(target.value.username));
62
+ return collectNewPassword(promptIo, options);
63
+ });
64
+ if (password.isErr())
65
+ return exitCodeOfPrompt(io, password.error);
66
+ const reset = await shell.run(() => resetPassword(shell.deps, { username: options.user, password: password.value }));
67
+ if (reset.isErr())
68
+ return failed(io, formatAppError(reset.error));
69
+ reportReset(io, reset.value);
70
+ return EXIT_OK;
71
+ }, EXIT_FAILURE);
72
+ const CLAIM_FLAGS = { [PASSWORD_STDIN_FLAG]: { type: 'boolean' }, username: { type: 'string' } };
73
+ const RESET_FLAGS = { [PASSWORD_STDIN_FLAG]: { type: 'boolean' }, user: { type: 'string' } };
74
+ export const parseClaimArgs = (args, maxPositionals) => parseFlags(args, CLAIM_FLAGS, ClaimOptionsSchema, maxPositionals);
75
+ const setupFromArgs = async (args, io) => {
76
+ const parsed = parseClaimArgs(args, AUTH_POSITIONALS);
77
+ if ('error' in parsed)
78
+ return exitCodeOf(fail(io, parsed.error));
79
+ return ensureOwnerClaimed(io, parsed.options);
80
+ };
81
+ const resetFromArgs = async (args, io) => {
82
+ const parsed = parseFlags(args, RESET_FLAGS, ResetOptionsSchema, AUTH_POSITIONALS);
83
+ if ('error' in parsed)
84
+ return exitCodeOf(fail(io, parsed.error));
85
+ return resetUserPassword(io, parsed.options);
86
+ };
87
+ export const runAuthCommand = async (args, io) => {
88
+ const [name, ...rest] = args;
89
+ if (name === undefined) {
90
+ io.out(AUTH_HELP);
91
+ return EXIT_OK;
92
+ }
93
+ const subcommand = AuthSubcommand.safeParse(name);
94
+ if (!subcommand.success) {
95
+ io.err(CLI_MESSAGES.failure(`unknown auth command "${name}"`));
96
+ io.err(AUTH_HELP);
97
+ return EXIT_FAILURE;
98
+ }
99
+ return subcommand.data === AuthSubcommand.enum.setup ? setupFromArgs(rest, io) : resetFromArgs(rest, io);
100
+ };
@@ -0,0 +1,72 @@
1
+ import { errAsync, ResultAsync } from 'neverthrow';
2
+ import { NPX_COMMAND, PRODUCT_NAME } from '../../../models/package.js';
3
+ import { DbSubcommand, EXPORT_FLAGS, EXPORT_POSITIONALS, ExportOptionsSchema, IMPORT_FLAGS, IMPORT_POSITIONALS, ImportOptionsSchema, } from '../../../wire/in/cli.js';
4
+ import { snapshotDestination } from '../export-file.js';
5
+ import { snapshotSource } from '../import-file.js';
6
+ import { EXIT_OK, exitCodeOf, fail, failed, parseFlags, refuseUnknownSubcommand, } from '../io.js';
7
+ import { CLI_MESSAGES } from '../messages.js';
8
+ export const DB_HELP = `
9
+ Usage: ${NPX_COMMAND} db <command>
10
+
11
+ Commands:
12
+ export --to <file> Write a consistent, still-encrypted snapshot of the database to a new file
13
+ import --from <file> Put a snapshot written by \`export\` in place as this install's database
14
+
15
+ Export: the snapshot is created owner-only and never overwritten, is complete on its own (no -wal file) and opens with
16
+ the same key. It is safe to take while ${PRODUCT_NAME} is running, but stop every client first so nothing is written after
17
+ it. The database is opened as it is: nothing is migrated. Prints row counts (no data) to compare after a move.
18
+
19
+ Import: refused when a database already exists here, and when the snapshot does not open with this install's key (file,
20
+ env var or keychain; one is never generated). The copy is created owner-only and never overwrites; nothing is
21
+ migrated, the next start does that after its usual safety copy. Prints the same row counts as export.
22
+ To move to this machine: key import first, then db import, then setup <client>.
23
+ `.trimStart();
24
+ const exportSnapshot = async (args, io) => {
25
+ const parsed = parseFlags(args, EXPORT_FLAGS, ExportOptionsSchema, EXPORT_POSITIONALS);
26
+ if ('error' in parsed)
27
+ return exitCodeOf(fail(io, parsed.error));
28
+ const destination = snapshotDestination(io.exporter, parsed.options.to);
29
+ if (destination.isErr())
30
+ return failed(io, destination.error);
31
+ const counts = await io.exporter.writeSnapshot(destination.value);
32
+ if (counts.isErr())
33
+ return failed(io, counts.error);
34
+ io.out(CLI_MESSAGES.snapshotExported(destination.value, counts.value));
35
+ return EXIT_OK;
36
+ };
37
+ const publishChecked = (importer, staged, key) => new ResultAsync(importer.inspectSnapshot(staged, key))
38
+ .andThen((counts) => new ResultAsync(importer.publishSnapshot(staged)).map(() => counts))
39
+ .orElse((failure) => {
40
+ importer.discardSnapshot(staged);
41
+ return errAsync(failure);
42
+ });
43
+ const importSnapshot = async (args, io) => {
44
+ const parsed = parseFlags(args, IMPORT_FLAGS, ImportOptionsSchema, IMPORT_POSITIONALS);
45
+ if ('error' in parsed)
46
+ return exitCodeOf(fail(io, parsed.error));
47
+ const { importer } = io;
48
+ const source = snapshotSource(importer, parsed.options.from);
49
+ if (source.isErr())
50
+ return failed(io, source.error);
51
+ const { file, target } = source.value;
52
+ const imported = await new ResultAsync(importer.resolveKey()).andThen((key) => new ResultAsync(importer.stageSnapshot(file)).andThen((staged) => publishChecked(importer, staged, key)));
53
+ if (imported.isErr())
54
+ return failed(io, imported.error);
55
+ io.out(CLI_MESSAGES.snapshotImported(target, imported.value));
56
+ return EXIT_OK;
57
+ };
58
+ const DB_RUNNERS = {
59
+ export: exportSnapshot,
60
+ import: importSnapshot,
61
+ };
62
+ export const runDbCommand = async (args, io) => {
63
+ const [name, ...rest] = args;
64
+ if (name === undefined) {
65
+ io.out(DB_HELP);
66
+ return EXIT_OK;
67
+ }
68
+ const known = DbSubcommand.safeParse(name);
69
+ if (!known.success)
70
+ return refuseUnknownSubcommand(io, 'db', name, DB_HELP);
71
+ return DB_RUNNERS[known.data](rest, io);
72
+ };
@@ -0,0 +1,68 @@
1
+ import { DASHBOARD_PATH, httpOrigin, LOOPBACK_HOST } from '../../../common/net.js';
2
+ import { DEMO_PORT, DemoCountry, DemoFailureCode, DemoSeedStatus, } from '../../../models/demo/core.js';
3
+ import { NPX_COMMAND, PRODUCT_NAME } from '../../../models/package.js';
4
+ import { DEMO_FLAG, DEMO_POSITIONALS, DemoOptionsSchema } from '../../../wire/in/cli.js';
5
+ import { EXIT_OK, exitCodeOf, fail, parseFlags } from '../io.js';
6
+ const RESET_FLAG = 'reset';
7
+ const COUNTRY_FLAG = 'country';
8
+ const DEMO_FLAGS = { [COUNTRY_FLAG]: { type: 'string' }, [RESET_FLAG]: { type: 'boolean' } };
9
+ const dashboardUrl = () => `${httpOrigin(LOOPBACK_HOST, DEMO_PORT)}${DASHBOARD_PATH}`;
10
+ const RESET_HINT = `${NPX_COMMAND} demo --${RESET_FLAG}`;
11
+ export const DEMO_HELP = `
12
+ Usage: ${NPX_COMMAND} demo [--${COUNTRY_FLAG} ${DemoCountry.options.join('|')}] [--${RESET_FLAG}]
13
+
14
+ Seeds a throwaway demo database — sample data, never your finances — and serves its dashboards on port ${DEMO_PORT}
15
+ (your real ${PRODUCT_NAME} keeps its own database and port). No login: the demo is loopback-only and its key is public.
16
+
17
+ Options:
18
+ --${COUNTRY_FLAG} <code> the data set, and with it the language and currency: ${DemoCountry.options.join(', ')}
19
+ (default: your OS locale's country, else us)
20
+ --${RESET_FLAG} delete the demo database and seed it again; refuses any file that is not a demo database
21
+
22
+ To use it from an AI client: ${NPX_COMMAND} setup <client> --${DEMO_FLAG}
23
+ `.trimStart();
24
+ const FAILURE_MESSAGES = {
25
+ [DemoFailureCode.enum.real_database]: () => 'the demo database path is the real database (DB_PATH), or cannot be resolved to a file — the demo never touches it',
26
+ [DemoFailureCode.enum.not_demo]: () => 'the file at the demo database path is not a demo database (or does not open with the demo key), so it is left ' +
27
+ `alone. If a ${PRODUCT_NAME} demo is running (an AI client's patty-demo server), stop it and retry. ` +
28
+ 'Move the file away if it is yours to remove',
29
+ [DemoFailureCode.enum.interrupted]: () => `the demo was not fully seeded (an earlier run stopped partway). Start it over with: ${RESET_HINT}`,
30
+ [DemoFailureCode.enum.seed_failed]: ({ reason }) => `seeding the demo failed: ${reason}. A demo created by this run was removed; try again, or use --${RESET_FLAG}`,
31
+ [DemoFailureCode.enum.start_failed]: ({ reason }) => `the demo could not start: ${reason}`,
32
+ [DemoFailureCode.enum.busy]: () => 'another demo run is preparing the same database right now (or died holding its lock file, which is cleared once ' +
33
+ 'that process is gone). Wait for it, then run this again',
34
+ [DemoFailureCode.enum.port_in_use]: () => `port ${DEMO_PORT} is already in use. If the demo is already running (an AI client's patty-demo server, or ` +
35
+ `another "demo"), open ${dashboardUrl()}`,
36
+ };
37
+ const failureMessage = (failure) => FAILURE_MESSAGES[failure.code](failure);
38
+ const seededNote = (prepared) => prepared.status === DemoSeedStatus.enum.seeded
39
+ ? `Seeded a new demo (${prepared.country}).`
40
+ : `The demo is already seeded (add --${RESET_FLAG} to start over, with --${COUNTRY_FLAG} to pick another data set).`;
41
+ export const DEMO_MESSAGES = {
42
+ ready: (prepared) => [
43
+ `${PRODUCT_NAME} demo — sample data, not your finances. Do not enter real data here.`,
44
+ seededNote(prepared),
45
+ ` Database: ${prepared.databasePath} (encrypted with the published demo key)`,
46
+ ` Dashboards: ${dashboardUrl()} (Ctrl-C to stop)`,
47
+ `Use it from an AI client: ${NPX_COMMAND} setup <client> --${DEMO_FLAG}`,
48
+ `Ready for your own data? ${NPX_COMMAND} setup <client>`,
49
+ ].join('\n'),
50
+ };
51
+ const HELP_FLAGS = ['--help', '-h'];
52
+ export const runDemoCommand = async (args, io) => {
53
+ if (args.some((argument) => HELP_FLAGS.includes(argument))) {
54
+ io.out(DEMO_HELP);
55
+ return EXIT_OK;
56
+ }
57
+ const parsed = parseFlags(args, DEMO_FLAGS, DemoOptionsSchema, DEMO_POSITIONALS);
58
+ if ('error' in parsed)
59
+ return exitCodeOf(fail(io, parsed.error));
60
+ const prepared = await io.demo.prepare(parsed.options);
61
+ if (prepared.isErr())
62
+ return exitCodeOf(fail(io, failureMessage(prepared.error)));
63
+ io.out(DEMO_MESSAGES.ready(prepared.value));
64
+ const serving = await io.demo.serve();
65
+ if (serving.isErr())
66
+ return exitCodeOf(fail(io, failureMessage(serving.error)));
67
+ return EXIT_OK;
68
+ };
@@ -0,0 +1,119 @@
1
+ import { closeSync, openSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { errAsync, okAsync, Result, ResultAsync } from 'neverthrow';
3
+ import { reasonOf } from '../../../models/error.js';
4
+ import { EXCLUSIVE_CREATE_FLAG, PRIVATE_FILE_MODE } from '../../../models/export.js';
5
+ import { NPX_COMMAND } from '../../../models/package.js';
6
+ import { keyImportRefusal } from '../../../logic/key-import.js';
7
+ import { STEP_UP_RETRY_DELAY_MS } from '../../../models/auth/key-export.js';
8
+ import { EXPORT_FLAGS, EXPORT_POSITIONALS, ExportOptionsSchema, IMPORT_FLAGS, IMPORT_POSITIONALS, ImportOptionsSchema, KeySubcommand, } from '../../../wire/in/cli.js';
9
+ import { keyDestination } from '../export-file.js';
10
+ import { keyFromFile } from '../import-file.js';
11
+ import { EXIT_OK, exitCodeOf, fail, failed, parseFlags, refuseUnknownSubcommand, } from '../io.js';
12
+ import { CLI_MESSAGES } from '../messages.js';
13
+ import { approveKeyExport, exitCodeOfStop } from '../key-export-approval.js';
14
+ export const KEY_HELP = `
15
+ Usage: ${NPX_COMMAND} key <command>
16
+
17
+ Commands:
18
+ export --to <file> Write the database encryption key to a new file, usable as PATTY_DB_KEY_FILE
19
+ import --from <file> Store a key written by \`export\` in the OS keychain, where this install reads it
20
+
21
+ Export: asks for an administrator's username and password (typed, never echoed), then for a confirmation, before
22
+ anything is written. It needs a terminal and cannot be scripted. The file is created owner-only and never overwritten,
23
+ and must not be in the database's directory. The key is written only there: it is never printed. Run it from the
24
+ terminal that holds the key, before moving the database.
25
+
26
+ Import: refused when the keychain already holds a key (remove that entry yourself first) and when PATTY_DB_KEY_FILE
27
+ or PATTY_DB_KEY is set (those installs read the key from there). When a database already exists here, the key must
28
+ open it. To move to this machine: key import first, then db import, then setup <client>.
29
+ `.trimStart();
30
+ /** One line, the key and a newline: what `PATTY_DB_KEY_FILE` reads back exactly. A half-written file is removed. */
31
+ const writeKeyFile = Result.fromThrowable((path, key) => {
32
+ const file = openSync(path, EXCLUSIVE_CREATE_FLAG, PRIVATE_FILE_MODE);
33
+ try {
34
+ writeFileSync(file, `${key}\n`); // writes it all or throws; writeSync may stop short
35
+ }
36
+ catch (cause) {
37
+ rmSync(path, { force: true });
38
+ throw cause;
39
+ }
40
+ finally {
41
+ closeSync(file);
42
+ }
43
+ }, reasonOf);
44
+ /** An administrator's password and a confirmation come before anything is written; what stopped it is said once. */
45
+ const approveExport = async (io, terminal, destination) => {
46
+ const { exporter } = io;
47
+ const signal = io.interruptSignal();
48
+ const approved = await approveKeyExport({
49
+ terminal,
50
+ destination,
51
+ users: exporter.users,
52
+ secrets: exporter.stepUpSecrets,
53
+ pause: () => io.wait(STEP_UP_RETRY_DELAY_MS, signal),
54
+ });
55
+ return approved.isOk() ? null : exitCodeOfStop(io, approved.error);
56
+ };
57
+ const exportKeyTo = async (io, terminal, to) => {
58
+ const destination = keyDestination(io.exporter, to);
59
+ if (destination.isErr())
60
+ return failed(io, destination.error);
61
+ const refused = await approveExport(io, terminal, destination.value);
62
+ if (refused !== null)
63
+ return refused;
64
+ const key = await io.exporter.provenKey();
65
+ if (key.isErr())
66
+ return failed(io, key.error);
67
+ const written = writeKeyFile(destination.value, key.value);
68
+ if (written.isErr())
69
+ return failed(io, written.error);
70
+ io.out(CLI_MESSAGES.keyExported(destination.value));
71
+ return EXIT_OK;
72
+ };
73
+ /** Interactive only: with no terminal nothing is opened and nothing is asked (there is no `--password-stdin` here). */
74
+ const exportKey = async (args, io) => {
75
+ const parsed = parseFlags(args, EXPORT_FLAGS, ExportOptionsSchema, EXPORT_POSITIONALS);
76
+ if ('error' in parsed)
77
+ return exitCodeOf(fail(io, parsed.error));
78
+ const terminal = io.openTerminal();
79
+ if (terminal === null)
80
+ return failed(io, CLI_MESSAGES.keyExportNeedsTerminal);
81
+ try {
82
+ return await exportKeyTo(io, terminal, parsed.options.to);
83
+ }
84
+ finally {
85
+ terminal.close();
86
+ }
87
+ };
88
+ const checkKeySources = (importer) => new ResultAsync(importer.keySources()).andThen((sources) => {
89
+ const refusal = keyImportRefusal(sources);
90
+ return refusal === null ? okAsync(undefined) : errAsync(CLI_MESSAGES.keyImportRefused(refusal));
91
+ });
92
+ const importKey = async (args, io) => {
93
+ const parsed = parseFlags(args, IMPORT_FLAGS, ImportOptionsSchema, IMPORT_POSITIONALS);
94
+ if ('error' in parsed)
95
+ return exitCodeOf(fail(io, parsed.error));
96
+ const { importer } = io;
97
+ const stored = await keyFromFile(parsed.options.from).asyncAndThen((key) => checkKeySources(importer)
98
+ .andThen(() => new ResultAsync(importer.proveAgainstDatabase(key)))
99
+ .andThen(() => new ResultAsync(importer.storeKey(key))));
100
+ if (stored.isErr())
101
+ return failed(io, stored.error);
102
+ io.out(CLI_MESSAGES.keyImported());
103
+ return EXIT_OK;
104
+ };
105
+ const KEY_RUNNERS = {
106
+ export: exportKey,
107
+ import: importKey,
108
+ };
109
+ export const runKeyCommand = async (args, io) => {
110
+ const [name, ...rest] = args;
111
+ if (name === undefined) {
112
+ io.out(KEY_HELP);
113
+ return EXIT_OK;
114
+ }
115
+ const known = KeySubcommand.safeParse(name);
116
+ if (!known.success)
117
+ return refuseUnknownSubcommand(io, 'key', name, KEY_HELP);
118
+ return KEY_RUNNERS[known.data](rest, io);
119
+ };
@@ -0,0 +1,151 @@
1
+ import { GrantChannel } from '../../../models/auth/grant.js';
2
+ import { AUTH_MESSAGES } from '../../../models/auth/message.js';
3
+ import { AUTH_ENV_VAR } from '../../../models/auth/mode.js';
4
+ import { CLI_CLIENT_NAME, TOKEN_ENV_VAR } from '../../../models/auth/sign-in.js';
5
+ import { ObservationKind, PresentationKind, SignInStateKind, IDLE, } from '../../../models/auth/sign-in-flow.js';
6
+ import { NPX_COMMAND } from '../../../models/package.js';
7
+ import { LoginOptionsSchema, LogoutOptionsSchema, SIGN_IN_POSITIONALS, } from '../../../wire/in/cli.js';
8
+ import { EXIT_FAILURE, EXIT_INTERRUPTED, EXIT_OK, exitCodeOf, fail, parseFlags, withShell, } from '../io.js';
9
+ import { CLI_MESSAGES } from '../messages.js';
10
+ import { PromptEnd } from '../terminal.js';
11
+ export const LOGIN_MESSAGES = {
12
+ authDisabled: `${AUTH_ENV_VAR}=disabled: stdio acts as the owner, so there is nothing to sign in to. Remove it to use sign-ins.`,
13
+ open: (url, code) => `Open ${url} and confirm the code ${code}.`,
14
+ waiting: 'Waiting for you to approve it in the browser… (Ctrl-C to cancel)',
15
+ signedIn: (profile, access, expiresAt) => `Signed in on profile "${profile}" (${access}) until ${expiresAt}.`,
16
+ denied: 'The sign-in was denied.',
17
+ expired: 'The sign-in request expired before it was approved. Run the command again.',
18
+ cancelled: 'Cancelled.',
19
+ keychainRefused: 'The OS keychain would not keep the sign-in, so it was revoked again. Fix keychain access, or set ' +
20
+ `${TOKEN_ENV_VAR} in the client instead.`,
21
+ keychainRefusedAndStillActive: 'The OS keychain would not keep the sign-in, and it could not be revoked either: revoke it now on the Access ' +
22
+ 'page of the dashboard (/ui/access/tokens), or it stays valid until it expires.',
23
+ keychainUnavailable: 'the OS keychain is unavailable, so whether this profile is signed in could not be checked — unlock it and try again',
24
+ signedOut: (profile) => `Signed out of profile "${profile}".`,
25
+ notSignedIn: (profile) => `Not signed in on profile "${profile}".`,
26
+ skippedNoTerminal: (profile) => `Not signing in now (no terminal). Run \`${NPX_COMMAND} login --profile ${profile}\` when you are ready, or ` +
27
+ 'let the first tool call show a sign-in link.',
28
+ skippedByChoice: (profile) => `Skipped. The first tool call will show a sign-in link, or run \`${NPX_COMMAND} login --profile ${profile}\`.`,
29
+ offer: 'Sign in this client now? [Y/n] ',
30
+ };
31
+ const ANSWERED_NO = /^\s*n/i;
32
+ const O = ObservationKind.enum;
33
+ const P = PresentationKind.enum;
34
+ const S = SignInStateKind.enum;
35
+ /** Where the protocol ended up decides the exit code. */
36
+ const EXIT_CODE_OF_STATE = {
37
+ [S.idle]: EXIT_OK,
38
+ [S.signed_in]: EXIT_OK,
39
+ [S.pending]: EXIT_FAILURE,
40
+ [S.denied]: EXIT_FAILURE,
41
+ [S.expired]: EXIT_FAILURE,
42
+ [S.failed]: EXIT_FAILURE,
43
+ [S.cancelled]: EXIT_INTERRUPTED,
44
+ };
45
+ const renderNothing = () => undefined;
46
+ const RENDERERS = {
47
+ [P.auth_disabled]: (io) => io.err(LOGIN_MESSAGES.authDisabled),
48
+ [P.owner_unclaimed]: (io) => io.err(AUTH_MESSAGES.ownerUnclaimed),
49
+ [P.open]: (io, presentation) => io.out(LOGIN_MESSAGES.open(presentation.url, presentation.code)),
50
+ [P.waiting]: (io) => io.out(LOGIN_MESSAGES.waiting),
51
+ [P.signed_in]: (io, presentation) => io.out(LOGIN_MESSAGES.signedIn(presentation.profile, presentation.access, presentation.expiresAt)),
52
+ [P.denied]: (io) => io.err(LOGIN_MESSAGES.denied),
53
+ [P.expired]: (io) => io.err(LOGIN_MESSAGES.expired),
54
+ [P.cancelled]: (io) => io.err(LOGIN_MESSAGES.cancelled),
55
+ [P.failed]: (io, presentation) => io.err(presentation.reason),
56
+ [P.keychain_refused]: (io) => io.err(LOGIN_MESSAGES.keychainRefused),
57
+ [P.keychain_refused_still_active]: (io) => io.err(LOGIN_MESSAGES.keychainRefusedAndStillActive),
58
+ [P.signed_out]: (io, presentation) => io.out(LOGIN_MESSAGES.signedOut(presentation.profile)),
59
+ [P.not_signed_in]: (io, presentation) => io.out(LOGIN_MESSAGES.notSignedIn(presentation.profile)),
60
+ [P.keychain_unreadable]: (io) => io.err(CLI_MESSAGES.failure(LOGIN_MESSAGES.keychainUnavailable)),
61
+ [P.logout_failed]: (io, presentation) => io.err(CLI_MESSAGES.failure(presentation.reason)),
62
+ [P.granted]: renderNothing,
63
+ [P.invalid_env_token]: renderNothing,
64
+ [P.cannot_verify]: renderNothing,
65
+ [P.instructions]: renderNothing,
66
+ };
67
+ /** The terminal lines for what the protocol said. A stdio-only presentation never reaches a terminal. */
68
+ const render = (io, presentation) => RENDERERS[presentation.kind](io, presentation);
69
+ const hooksFor = (io, wait) => ({
70
+ present: (presentation) => render(io, presentation),
71
+ wait,
72
+ progress: () => undefined,
73
+ });
74
+ const configFor = (io, shell, profile, hint) => ({
75
+ channel: GrantChannel.enum.cli,
76
+ profile,
77
+ client: { name: CLI_CLIENT_NAME, version: io.version },
78
+ authRequired: shell.authRequired,
79
+ hint,
80
+ });
81
+ /**
82
+ * The browser sign-in from a shell (ADR-034 §3, §6): feed the protocol until it ends, printing what it says. The
83
+ * protocol starts a grant, names the link and code, polls until it is approved, then keeps the result in the keychain
84
+ * profile; the interpreter serves `/ui/connect` itself when no PATTY server does. The device code and token never
85
+ * reach the output.
86
+ */
87
+ const signIn = async (io, shell, request) => {
88
+ const interrupted = io.interruptSignal();
89
+ const interpreter = shell.signIn(request.profile);
90
+ const config = configFor(io, shell, request.profile, { access: request.scope, duration: request.duration });
91
+ const hooks = hooksFor(io, (ms) => io.wait(ms, interrupted));
92
+ const feed = (state, observation) => interpreter.drive(state, observation, config, hooks);
93
+ // While a request is open the protocol is fed again each time it has finished waiting — unless Ctrl-C came.
94
+ const untilEnded = async (state) => state.kind === S.pending
95
+ ? untilEnded(await feed(state, { kind: interrupted.aborted ? O.interrupted : O.ticked }))
96
+ : state;
97
+ try {
98
+ return await untilEnded(await feed(IDLE, { kind: O.login_requested }));
99
+ }
100
+ finally {
101
+ await interpreter.release();
102
+ }
103
+ };
104
+ const LOGIN_FLAGS = {
105
+ profile: { type: 'string' },
106
+ duration: { type: 'string' },
107
+ scope: { type: 'string' },
108
+ };
109
+ const LOGOUT_FLAGS = { profile: { type: 'string' } };
110
+ export const runLogin = async (args, io) => {
111
+ const parsed = parseFlags(args, LOGIN_FLAGS, LoginOptionsSchema, SIGN_IN_POSITIONALS);
112
+ if ('error' in parsed)
113
+ return exitCodeOf(fail(io, parsed.error));
114
+ const { profile, duration, scope } = parsed.options;
115
+ return withShell(io, async (shell) => EXIT_CODE_OF_STATE[(await signIn(io, shell, { profile: profile ?? shell.defaultProfile, duration, scope })).kind], EXIT_FAILURE);
116
+ };
117
+ /** Revoke the profile's saved sign-in and forget it. Idempotent: with nothing saved it says so and succeeds. */
118
+ export const runLogout = async (args, io) => {
119
+ const parsed = parseFlags(args, LOGOUT_FLAGS, LogoutOptionsSchema, SIGN_IN_POSITIONALS);
120
+ if ('error' in parsed)
121
+ return exitCodeOf(fail(io, parsed.error));
122
+ return withShell(io, async (shell) => {
123
+ const profile = parsed.options.profile ?? shell.defaultProfile;
124
+ const state = await shell.signIn(profile).drive(IDLE, { kind: O.logout_requested }, configFor(io, shell, profile, undefined), hooksFor(io, async () => undefined));
125
+ return EXIT_CODE_OF_STATE[state.kind];
126
+ }, EXIT_FAILURE);
127
+ };
128
+ /** `setup`'s last step (ADR-034 §5.3): offer to sign the client in now. Never fails the setup that wrote the config —
129
+ * a declined, denied or cancelled sign-in just leaves the first tool call to ask. Answers `EXIT_INTERRUPTED` after
130
+ * Ctrl-C at the question. */
131
+ export const offerSignIn = async (io, profile) => {
132
+ const terminal = io.openTerminal();
133
+ if (terminal === null) {
134
+ io.out(LOGIN_MESSAGES.skippedNoTerminal(profile));
135
+ return EXIT_OK;
136
+ }
137
+ const answer = await terminal.ask(LOGIN_MESSAGES.offer);
138
+ terminal.close();
139
+ // Ctrl-D at the question is "not now"; Ctrl-C ends the command.
140
+ if (answer.isErr() && answer.error.how === PromptEnd.enum.interrupted)
141
+ return EXIT_INTERRUPTED;
142
+ if (answer.isErr() || ANSWERED_NO.test(answer.value)) {
143
+ io.out(LOGIN_MESSAGES.skippedByChoice(profile));
144
+ return EXIT_OK;
145
+ }
146
+ const signedIn = await withShell(io, async (shell) => {
147
+ await signIn(io, shell, { profile });
148
+ return true;
149
+ }, false);
150
+ return signedIn ? EXIT_OK : EXIT_FAILURE;
151
+ };