@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,40 @@
1
+ import { ok, safeTry } from 'neverthrow';
2
+ import { guard } from '../common/result.js';
3
+ import { shapeAggregateResult, wantsDisplayConversion } from '../logic/aggregate.js';
4
+ import { consolidateInCurrency } from '../logic/currency-rate.js';
5
+ import { decimalsLookup } from '../logic/money.js';
6
+ import { assertHasPeriodOrRange, resolveDateRange } from '../logic/period.js';
7
+ import { aggregateErrors, } from '../models/aggregate.js';
8
+ import { resolveAccountRef, resolveCategoryRef } from './resolve.js';
9
+ const resolveAggregateRefs = (deps, input) => safeTry(async function* () {
10
+ const account = input.account ? yield* resolveAccountRef(deps, input.account) : null;
11
+ const category = input.category ? yield* resolveCategoryRef(deps, input.category) : null;
12
+ return ok({ accountId: account?.id ?? null, categoryId: category?.id ?? null });
13
+ });
14
+ const convertBlockTotals = async (deps, displayCurrency, currencies, decimalsFor) => {
15
+ const amounts = currencies.map((c) => ({ currency: c.currency, amount: c.total }));
16
+ const converted = consolidateInCurrency(amounts, displayCurrency, await deps.currencyRates.list(), deps.clock(), deps.rateStaleness, decimalsFor(displayCurrency));
17
+ return { displayCurrency, ...converted };
18
+ };
19
+ export const aggregateSpending = (deps, input) => safeTry(async function* () {
20
+ yield* guard(assertHasPeriodOrRange(input), aggregateErrors.missingPeriod);
21
+ const { from, to } = resolveDateRange(input);
22
+ const { accountId, categoryId } = yield* resolveAggregateRefs(deps, input);
23
+ const [locale, currencyList] = await Promise.all([deps.locale(), deps.currencies.list()]);
24
+ const decimalsFor = decimalsLookup(currencyList);
25
+ const rows = await deps.transactions.aggregate({
26
+ groupBy: input.groupBy,
27
+ metric: input.metric,
28
+ from,
29
+ to,
30
+ type: input.type ?? null,
31
+ accountId,
32
+ categoryId,
33
+ tagNames: input.tags ?? [],
34
+ });
35
+ const currencies = shapeAggregateResult(rows, input.groupBy, input.sort, locale, decimalsFor, input.limit);
36
+ const result = { groupBy: input.groupBy, metric: input.metric, currencies };
37
+ return ok(wantsDisplayConversion(input)
38
+ ? { ...result, converted: await convertBlockTotals(deps, input.displayCurrency, currencies, decimalsFor) }
39
+ : result);
40
+ });
@@ -0,0 +1,61 @@
1
+ import { ok, safeTry } from 'neverthrow';
2
+ import * as R from 'remeda';
3
+ import { guard, okOr } from '../../common/result.js';
4
+ import { liveSessionOf } from '../../logic/auth/session.js';
5
+ import { withCredentialsChanged } from '../../logic/auth/users.js';
6
+ import { evaluateToken, newAccessToken, revokedToken, summarizeToken, tokenDisplayPrefix, tokenPrincipal, usedToken, } from '../../logic/auth/token.js';
7
+ import * as persistence from '../../logic/persistence.js';
8
+ import { ACCESS_TOKEN_ENTITY_TAG, SESSION_ENTITY_TAG, USER_ENTITY_TAG } from '../../models/auth/entity.js';
9
+ import { authErrors } from '../../models/auth/errors.js';
10
+ import { PrincipalVia } from '../../models/auth/principal.js';
11
+ import { AccessTokenKind, } from '../../models/auth/token.js';
12
+ import { confirmedUser } from './step-up.js';
13
+ export const createToken = (deps, principal, input) => safeTry(async function* () {
14
+ const userId = principal.userId;
15
+ const user = await deps.users.findById(userId);
16
+ const account = yield* okOr(await confirmedUser(deps, user, input.password), authErrors.invalidCredentials);
17
+ yield* guard(principal.via === PrincipalVia.enum.session, authErrors.sessionRequired);
18
+ const now = deps.clock();
19
+ const session = yield* okOr(liveSessionOf(await deps.sessions.listByUser(userId), principal.sessionId, now), authErrors.unauthenticated);
20
+ const token = deps.secrets.randomAccessToken();
21
+ const entity = newAccessToken({ id: deps.newId(), userId, tokenHash: deps.secrets.hashSecret(token), prefix: tokenDisplayPrefix(token), input }, now);
22
+ const persist = [
23
+ persistence.check({ entity: SESSION_ENTITY_TAG, id: session.id, version: session.version }),
24
+ persistence.update({ entity: USER_ENTITY_TAG, model: withCredentialsChanged(account, now) }),
25
+ persistence.insert({ entity: ACCESS_TOKEN_ENTITY_TAG, model: entity }),
26
+ ];
27
+ return ok({ persist, response: { token, summary: summarizeToken(entity, now) } });
28
+ });
29
+ export const listTokens = async (deps, userId) => {
30
+ const now = deps.clock();
31
+ return R.map(await deps.accessTokens.listByUser(userId), (token) => summarizeToken(token, now));
32
+ };
33
+ export const revokeToken = (deps, userId, id) => safeTry(async function* () {
34
+ const token = yield* okOr(await deps.accessTokens.findById(userId, id), authErrors.unknownToken(id));
35
+ const persist = token.revokedAt === null
36
+ ? [persistence.update({ entity: ACCESS_TOKEN_ENTITY_TAG, model: revokedToken(token, deps.clock()) })]
37
+ : [];
38
+ return ok({ persist, response: undefined });
39
+ });
40
+ export const authenticateToken = (deps, tokenHash, via = PrincipalVia.enum.token) => safeTry(async function* () {
41
+ const token = await deps.accessTokens.findByTokenHash(tokenHash);
42
+ const user = token ? await deps.users.findById(token.userId) : null;
43
+ const now = deps.clock();
44
+ const verdict = evaluateToken(token, user, now, via);
45
+ if (verdict.kind === 'invalid' || token === null || user === null)
46
+ return ok({ persist: [], response: null });
47
+ const persist = verdict.touch
48
+ ? [persistence.update({ entity: ACCESS_TOKEN_ENTITY_TAG, model: usedToken(token, now) })]
49
+ : [];
50
+ return ok({ persist, response: tokenPrincipal(token, user, via) });
51
+ });
52
+ export const revokeSignInByHash = (deps, tokenHash) => safeTry(async function* () {
53
+ const found = await deps.accessTokens.findByTokenHash(tokenHash);
54
+ const live = found?.kind === AccessTokenKind.enum.stdio && found.revokedAt === null ? found : null;
55
+ return ok({
56
+ persist: live
57
+ ? [persistence.update({ entity: ACCESS_TOKEN_ENTITY_TAG, model: revokedToken(live, deps.clock()) })]
58
+ : [],
59
+ response: live !== null,
60
+ });
61
+ });
@@ -0,0 +1,136 @@
1
+ import { ok, safeTry } from 'neverthrow';
2
+ import * as R from 'remeda';
3
+ import { guard, okOr } from '../../common/result.js';
4
+ import { approvedGrant, clampToCap, consentChoice, deniedGrant, durationAllowedFor, formatUserCode, grantRequestOf, isAnswerable, newGrant, newStdioSignIn, normalizeUserCode, offeredDurations, redeemPlan, redeemedGrant, signedIn, signInCapOf, supersededGrants, } from '../../logic/auth/grant.js';
5
+ import { isActiveUser } from '../../logic/auth/owner.js';
6
+ import { liveSessionOf } from '../../logic/auth/session.js';
7
+ import { withCredentialsChanged } from '../../logic/auth/users.js';
8
+ import { tokenDisplayPrefix, tokenPrincipal } from '../../logic/auth/token.js';
9
+ import * as persistence from '../../logic/persistence.js';
10
+ import { ACCESS_TOKEN_ENTITY_TAG, CLIENT_GRANT_ENTITY_TAG, INSTANCE_SETTINGS_ENTITY_TAG, SESSION_ENTITY_TAG, USER_ENTITY_TAG, } from '../../models/auth/entity.js';
11
+ import { authErrors } from '../../models/auth/errors.js';
12
+ import { RedeemKind, RedeemPlanKind, USER_CODE_ATTEMPTS, } from '../../models/auth/grant.js';
13
+ import { PrincipalVia } from '../../models/auth/principal.js';
14
+ import { TOKEN_ACCESS_SCOPES } from '../../models/auth/token.js';
15
+ import { conflict } from '../../models/error.js';
16
+ import { confirmedUser } from './step-up.js';
17
+ const plainResult = (kind) => ({ kind });
18
+ const requireSession = (principal) => guard(principal.via === PrincipalVia.enum.session, authErrors.sessionRequired);
19
+ const freshUserCode = async (deps, attemptsLeft = USER_CODE_ATTEMPTS) => {
20
+ const code = normalizeUserCode(deps.secrets.randomUserCode());
21
+ if ((await deps.clientGrants.findPendingByUserCode(code)) === null)
22
+ return code;
23
+ return attemptsLeft > 1 ? freshUserCode(deps, attemptsLeft - 1) : null;
24
+ };
25
+ export const startGrant = (deps, input) => safeTry(async function* () {
26
+ const userCode = yield* okOr(await freshUserCode(deps), conflict);
27
+ const deviceCode = deps.secrets.randomDeviceCode();
28
+ const grant = newGrant({ id: deps.newId(), deviceCodeHash: deps.secrets.hashSecret(deviceCode), userCode, input }, deps.clock());
29
+ return ok({
30
+ persist: [persistence.insert({ entity: CLIENT_GRANT_ENTITY_TAG, model: grant })],
31
+ response: { deviceCode, userCode: formatUserCode(userCode), expiresAt: grant.expiresAt },
32
+ });
33
+ });
34
+ const instanceCap = async (deps) => signInCapOf(await deps.instanceSettings.get());
35
+ const settingsCheck = (current) => persistence.check({ entity: INSTANCE_SETTINGS_ENTITY_TAG, id: current.id, version: current.version });
36
+ export const findConsent = async (deps, userId, rawUserCode) => {
37
+ const grant = await deps.clientGrants.findPendingByUserCode(normalizeUserCode(rawUserCode));
38
+ if (!isAnswerable(grant, deps.clock()))
39
+ return null;
40
+ const last = await deps.clientGrants.lastRedeemed(userId, grant.profile, grant.clientName);
41
+ const cap = await instanceCap(deps);
42
+ return {
43
+ request: grantRequestOf(grant),
44
+ choice: consentChoice(grant, last, cap),
45
+ durations: offeredDurations(grant.channel, cap),
46
+ };
47
+ };
48
+ const answerableGrant = (deps, rawUserCode) => safeTry(async function* () {
49
+ const grant = await deps.clientGrants.findPendingByUserCode(normalizeUserCode(rawUserCode));
50
+ return ok(yield* okOr(isAnswerable(grant, deps.clock()) ? grant : null, authErrors.invalidGrant));
51
+ });
52
+ export const approveGrant = (deps, principal, input) => safeTry(async function* () {
53
+ yield* requireSession(principal);
54
+ const row = await deps.users.findById(principal.userId);
55
+ const approver = yield* okOr(isActiveUser(row) ? row : null, authErrors.unauthenticated);
56
+ const now = deps.clock();
57
+ const sessions = await deps.sessions.listByUser(approver.id);
58
+ const session = yield* okOr(liveSessionOf(sessions, principal.sessionId, now), authErrors.unauthenticated);
59
+ yield* okOr(await confirmedUser(deps, approver, input.password), authErrors.invalidCredentials);
60
+ const grant = yield* answerableGrant(deps, input.userCode);
61
+ yield* guard(durationAllowedFor(grant.channel, input.duration), authErrors.sessionDurationRefused);
62
+ const duration = clampToCap(input.duration, await instanceCap(deps));
63
+ const approved = approvedGrant(grant, { userId: principal.userId, scopes: TOKEN_ACCESS_SCOPES[input.access], duration }, now);
64
+ return ok({
65
+ persist: [
66
+ persistence.check({ entity: SESSION_ENTITY_TAG, id: session.id, version: session.version }),
67
+ persistence.update({ entity: USER_ENTITY_TAG, model: withCredentialsChanged(approver, now) }),
68
+ persistence.update({ entity: CLIENT_GRANT_ENTITY_TAG, model: approved }),
69
+ ],
70
+ response: undefined,
71
+ });
72
+ });
73
+ export const denyGrant = (deps, principal, rawUserCode) => safeTry(async function* () {
74
+ yield* requireSession(principal);
75
+ const grant = yield* answerableGrant(deps, rawUserCode);
76
+ return ok({
77
+ persist: [persistence.update({ entity: CLIENT_GRANT_ENTITY_TAG, model: deniedGrant(grant) })],
78
+ response: undefined,
79
+ });
80
+ });
81
+ const unchanged = (kind) => ({
82
+ persist: [],
83
+ response: plainResult(kind),
84
+ });
85
+ const settledExpiry = (settle) => ({
86
+ persist: settle ? [persistence.update({ entity: CLIENT_GRANT_ENTITY_TAG, model: settle })] : [],
87
+ response: plainResult(RedeemKind.enum.expired),
88
+ });
89
+ const mintSignIn = async (deps, approved, now) => {
90
+ const user = await deps.users.findById(approved.userId);
91
+ if (!isActiveUser(user))
92
+ return unchanged(RedeemKind.enum.invalid);
93
+ const token = deps.secrets.randomAccessToken();
94
+ const settings = await deps.instanceSettings.get();
95
+ const grant = { ...approved, duration: clampToCap(approved.duration, signInCapOf(settings)) };
96
+ const entity = newStdioSignIn({ id: deps.newId(), tokenHash: deps.secrets.hashSecret(token), prefix: tokenDisplayPrefix(token), grant }, now);
97
+ // Writing the approver's row makes a racing disable or reset conflict and retry.
98
+ const persist = [
99
+ persistence.update({ entity: USER_ENTITY_TAG, model: withCredentialsChanged(user, now) }),
100
+ settingsCheck(settings),
101
+ persistence.insert({ entity: ACCESS_TOKEN_ENTITY_TAG, model: entity }),
102
+ persistence.update({ entity: CLIENT_GRANT_ENTITY_TAG, model: redeemedGrant(approved) }),
103
+ ];
104
+ return {
105
+ persist,
106
+ response: signedIn(token, entity, tokenPrincipal(entity, user, PrincipalVia.enum.stdio), grant.duration),
107
+ };
108
+ };
109
+ export const redeemGrant = (deps, deviceCode) => safeTry(async function* () {
110
+ const now = deps.clock();
111
+ const grant = await deps.clientGrants.findByDeviceCodeHash(deps.secrets.hashSecret(deviceCode));
112
+ const plan = redeemPlan(grant, now);
113
+ switch (plan.kind) {
114
+ case RedeemPlanKind.enum.invalid:
115
+ case RedeemPlanKind.enum.pending:
116
+ case RedeemPlanKind.enum.denied:
117
+ return ok(unchanged(plan.kind));
118
+ case RedeemPlanKind.enum.expired:
119
+ return ok(settledExpiry(plan.settle));
120
+ case RedeemPlanKind.enum.mint:
121
+ return ok(await mintSignIn(deps, plan.grant, now));
122
+ default: {
123
+ const _exhaustive = plan;
124
+ throw new Error(`unmapped redeem plan: ${JSON.stringify(_exhaustive)}`);
125
+ }
126
+ }
127
+ });
128
+ export const pruneExpiredGrants = (deps) => safeTry(async function* () {
129
+ const expired = await deps.clientGrants.listExpired(deps.clock().toISOString());
130
+ const superseded = supersededGrants(await deps.clientGrants.listRedeemed());
131
+ const doomed = [...expired, ...superseded];
132
+ return ok({
133
+ persist: R.map(doomed, (grant) => persistence.remove({ entity: CLIENT_GRANT_ENTITY_TAG, id: grant.id, version: grant.version })),
134
+ response: doomed.length,
135
+ });
136
+ });
@@ -0,0 +1,20 @@
1
+ import { err, ok, safeTry, ResultAsync } from 'neverthrow';
2
+ import { findUserNamed, hasClaimedAdmin, mayExportKey } from '../../logic/auth/key-export.js';
3
+ import { authErrors } from '../../models/auth/errors.js';
4
+ import { usersUnreadable } from '../../models/auth/key-export.js';
5
+ import { confirmedUser } from './step-up.js';
6
+ const readUsers = (deps) => new ResultAsync(deps.users()).mapErr(usersUnreadable);
7
+ /** Before anything is asked: an administrator with a login must exist, or there is no password to check. */
8
+ export const guardClaimedAdminExists = (deps) => safeTry(async function* () {
9
+ const users = yield* readUsers(deps);
10
+ return hasClaimedAdmin(users) ? ok(undefined) : err(authErrors.ownerUnclaimed);
11
+ });
12
+ /**
13
+ * Step-up for the key export: the administrator whose password this is. Unknown user, wrong password, a member and a
14
+ * disabled user are the same refusal, and each costs one full password check.
15
+ */
16
+ export const confirmKeyExportAdmin = (deps, credentials) => safeTry(async function* () {
17
+ const users = yield* readUsers(deps);
18
+ const confirmed = await confirmedUser(deps, findUserNamed(users, credentials.username), credentials.password);
19
+ return mayExportKey(confirmed) ? ok(confirmed) : err(authErrors.invalidCredentials);
20
+ });
@@ -0,0 +1,80 @@
1
+ import { ok, safeTry } from 'neverthrow';
2
+ import { guard, okOr } from '../../common/result.js';
3
+ import { claimedOwner, claimRaceWinner, formatSetupCode, hasCredentials, isActiveUser, isNeverClaimed, isSetupCodeUsable, isUnclaimed, normalizeSetupCode, planOwnerClaim, shouldIssueSetupCode, spentSetupCode, } from '../../logic/auth/owner.js';
4
+ import { loggedIn, withCredentialsChanged } from '../../logic/auth/users.js';
5
+ import * as persistence from '../../logic/persistence.js';
6
+ import { SETUP_CODE_ENTITY_TAG, USER_ENTITY_TAG } from '../../models/auth/entity.js';
7
+ import { authErrors } from '../../models/auth/errors.js';
8
+ import { OWNER_USER_ID, SETUP_CODE_ID, SETUP_CODE_TTL_MS, } from '../../models/auth/owner.js';
9
+ import { startSession } from './session.js';
10
+ export const issueSetupCode = (deps, mode) => safeTry(async function* () {
11
+ const owner = await deps.users.findById(OWNER_USER_ID);
12
+ if (!shouldIssueSetupCode(mode, owner))
13
+ return ok({ persist: [], response: null });
14
+ const now = deps.clock();
15
+ const code = formatSetupCode(deps.secrets.randomSetupCode());
16
+ const expiresAt = new Date(now.getTime() + SETUP_CODE_TTL_MS).toISOString();
17
+ const fresh = {
18
+ id: SETUP_CODE_ID,
19
+ codeHash: deps.secrets.hashSecret(normalizeSetupCode(code)),
20
+ createdAt: now.toISOString(),
21
+ expiresAt,
22
+ usedAt: null,
23
+ };
24
+ const current = await deps.setupCodes.current();
25
+ const persist = [
26
+ current
27
+ ? persistence.update({ entity: SETUP_CODE_ENTITY_TAG, model: { ...fresh, version: current.version } })
28
+ : persistence.insert({ entity: SETUP_CODE_ENTITY_TAG, model: fresh }),
29
+ ];
30
+ return ok({ persist, response: { code, expiresAt } });
31
+ });
32
+ const unclaimedOwner = (deps) => safeTry(async function* () {
33
+ const owner = yield* okOr(await deps.users.findById(OWNER_USER_ID), authErrors.setupUnavailable);
34
+ yield* guard(isUnclaimed(owner), authErrors.setupUnavailable);
35
+ return ok(owner);
36
+ });
37
+ const nameAvailableTo = async (deps, owner, username) => {
38
+ const holder = await deps.users.findByUsername(username);
39
+ return guard(holder === null || holder.id === owner.id, authErrors.usernameTaken(username));
40
+ };
41
+ const claimOwnerUpdate = (owner, input, passwordHash, now) => persistence.update({
42
+ entity: USER_ENTITY_TAG,
43
+ model: withCredentialsChanged(claimedOwner(owner, { username: input.username, passwordHash }), now),
44
+ });
45
+ export const claimOwner = (deps, input) => safeTry(async function* () {
46
+ const owner = yield* unclaimedOwner(deps);
47
+ yield* guard(isNeverClaimed(owner), authErrors.setupUnavailable);
48
+ const now = deps.clock();
49
+ const stored = await deps.setupCodes.findByHash(deps.secrets.hashSecret(normalizeSetupCode(input.code)));
50
+ const code = yield* okOr(isSetupCodeUsable(stored, now) ? stored : null, authErrors.invalidSetupCode);
51
+ yield* await nameAvailableTo(deps, owner, input.username);
52
+ const passwordHash = await deps.secrets.hashPassword(input.password);
53
+ const { persistable: sessionInsert, started } = startSession(deps, owner.id, now);
54
+ const persist = [
55
+ claimOwnerUpdate(loggedIn(owner, now), input, passwordHash, now),
56
+ persistence.update({ entity: SETUP_CODE_ENTITY_TAG, model: spentSetupCode(code, now) }),
57
+ sessionInsert,
58
+ ];
59
+ return ok({ persist, response: started });
60
+ });
61
+ export const claimOwnerLocally = (deps, input) => safeTry(async function* () {
62
+ const owner = yield* unclaimedOwner(deps);
63
+ yield* await nameAvailableTo(deps, owner, input.username);
64
+ const now = deps.clock();
65
+ const outstanding = await deps.setupCodes.current();
66
+ const spent = outstanding !== null && outstanding.usedAt === null ? [spentSetupCode(outstanding, now)] : [];
67
+ const persist = [
68
+ claimOwnerUpdate(owner, input, await deps.secrets.hashPassword(input.password), now),
69
+ ...spent.map((code) => persistence.update({ entity: SETUP_CODE_ENTITY_TAG, model: code })),
70
+ ];
71
+ return ok({ persist, response: { username: input.username } });
72
+ });
73
+ export const claimedOwnerOf = async (deps) => {
74
+ const owner = await deps.users.findById(OWNER_USER_ID);
75
+ return owner !== null && hasCredentials(owner) ? { username: owner.username } : null;
76
+ };
77
+ export const ownerClaimPlan = async (deps) => planOwnerClaim(await claimedOwnerOf(deps));
78
+ export const claimRaceWinnerOf = async (deps, refusal) => claimRaceWinner(refusal, await claimedOwnerOf(deps));
79
+ export const startsAtSetup = async (deps) => (await ownerNeedsSetup(deps)) && !(await deps.users.listAll()).some(isActiveUser);
80
+ export const ownerNeedsSetup = async (deps) => isNeverClaimed(await deps.users.findById(OWNER_USER_ID));
@@ -0,0 +1,35 @@
1
+ import { ok, safeTry } from 'neverthrow';
2
+ import { okOr } from '../../common/result.js';
3
+ import { hasCredentials } from '../../logic/auth/owner.js';
4
+ import { withPasswordHash } from '../../logic/auth/password.js';
5
+ import { endingCredentials } from '../../logic/auth/revoke.js';
6
+ import { withCredentialsChanged } from '../../logic/auth/users.js';
7
+ import * as persistence from '../../logic/persistence.js';
8
+ import { USER_ENTITY_TAG } from '../../models/auth/entity.js';
9
+ import { authErrors } from '../../models/auth/errors.js';
10
+ import { OWNER_USER_ID } from '../../models/auth/owner.js';
11
+ export const findResetTarget = (deps, username) => safeTry(async function* () {
12
+ if (username !== undefined) {
13
+ const named = await deps.users.findByUsername(username);
14
+ return ok(yield* okOr(named !== null && hasCredentials(named) ? named : null, authErrors.unknownUser(username)));
15
+ }
16
+ const owner = await deps.users.findById(OWNER_USER_ID);
17
+ return ok(yield* okOr(owner !== null && hasCredentials(owner) ? owner : null, authErrors.ownerUnclaimed));
18
+ });
19
+ export const resetPassword = (deps, input) => safeTry(async function* () {
20
+ const user = yield* findResetTarget(deps, input.username);
21
+ const now = deps.clock();
22
+ const ended = endingCredentials({
23
+ sessions: await deps.sessions.listByUser(user.id),
24
+ tokens: await deps.accessTokens.listByUser(user.id),
25
+ approvedGrants: await deps.clientGrants.listApprovedByUser(user.id),
26
+ }, now);
27
+ const persist = [
28
+ persistence.update({
29
+ entity: USER_ENTITY_TAG,
30
+ model: withCredentialsChanged(withPasswordHash(user, await deps.secrets.hashPassword(input.password)), now),
31
+ }),
32
+ ...ended.persist,
33
+ ];
34
+ return ok({ persist, response: { username: user.username, ...ended.revoked } });
35
+ });
@@ -0,0 +1,50 @@
1
+ import { ok, safeTry } from 'neverthrow';
2
+ import * as R from 'remeda';
3
+ import { okOr } from '../../common/result.js';
4
+ import { canLogin } from '../../logic/auth/password.js';
5
+ import { evaluateSession, newSession, sessionPrincipal, touched } from '../../logic/auth/session.js';
6
+ import { removeSession } from '../../logic/auth/revoke.js';
7
+ import { loggedIn } from '../../logic/auth/users.js';
8
+ import * as persistence from '../../logic/persistence.js';
9
+ import { SESSION_ENTITY_TAG, USER_ENTITY_TAG } from '../../models/auth/entity.js';
10
+ import { authErrors } from '../../models/auth/errors.js';
11
+ export const startSession = (deps, userId, now) => {
12
+ const token = deps.secrets.randomToken();
13
+ const session = newSession({ id: deps.newId(), userId, tokenHash: deps.secrets.hashSecret(token) }, now);
14
+ const persistable = persistence.insert({ entity: SESSION_ENTITY_TAG, model: session });
15
+ const started = { token, expiresAt: session.expiresAt };
16
+ return { persistable, started };
17
+ };
18
+ export const login = (deps, input) => safeTry(async function* () {
19
+ const user = await deps.users.findByUsername(input.username);
20
+ const passwordMatches = await deps.secrets.verifyPassword(user?.passwordHash ?? deps.secrets.dummyPasswordHash, input.password);
21
+ const account = yield* okOr(canLogin(user, passwordMatches) ? user : null, authErrors.invalidCredentials);
22
+ const now = deps.clock();
23
+ const { persistable: sessionInsert, started } = startSession(deps, account.id, now);
24
+ const expired = R.map(await deps.sessions.listExpired(now.toISOString()), removeSession);
25
+ const seen = persistence.update({ entity: USER_ENTITY_TAG, model: loggedIn(account, now) });
26
+ return ok({ persist: [...expired, seen, sessionInsert], response: started });
27
+ });
28
+ export const logout = (deps, tokenHash) => safeTry(async function* () {
29
+ const session = await deps.sessions.findByTokenHash(tokenHash);
30
+ return ok({ persist: session ? [removeSession(session)] : [], response: undefined });
31
+ });
32
+ export const authenticate = (deps, tokenHash) => safeTry(async function* () {
33
+ const session = await deps.sessions.findByTokenHash(tokenHash);
34
+ if (!session)
35
+ return ok({ persist: [], response: null });
36
+ const user = await deps.users.findById(session.userId);
37
+ const now = deps.clock();
38
+ const verdict = evaluateSession(session, user, now);
39
+ if (verdict.kind === 'invalid' || user === null) {
40
+ return ok({ persist: [removeSession(session)], response: null });
41
+ }
42
+ const persist = verdict.touch
43
+ ? [persistence.update({ entity: SESSION_ENTITY_TAG, model: touched(session, now) })]
44
+ : [];
45
+ return ok({ persist, response: sessionPrincipal(user, session) });
46
+ });
47
+ export const pruneExpiredSessions = (deps) => safeTry(async function* () {
48
+ const expired = await deps.sessions.listExpired(deps.clock().toISOString());
49
+ return ok({ persist: R.map(expired, removeSession), response: expired.length });
50
+ });
@@ -0,0 +1,8 @@
1
+ import { canLogin } from '../../logic/auth/password.js';
2
+ /**
3
+ * Step-up: the user, when `password` is theirs and they can sign in, else null. An absent or unclaimed user is verified
4
+ * against a dummy hash, so every refusal costs the same as a wrong password.
5
+ */
6
+ export const confirmedUser = async (deps, user, password) => canLogin(user, await deps.secrets.verifyPassword(user?.passwordHash ?? deps.secrets.dummyPasswordHash, password ?? ''))
7
+ ? user
8
+ : null;
@@ -0,0 +1,183 @@
1
+ import { INITIAL_VERSION } from '@rfc0/effect-runner';
2
+ import { ok, safeTry } from 'neverthrow';
3
+ import * as R from 'remeda';
4
+ import { guard, okOr, orRefuse } from '../../common/result.js';
5
+ import { signInCapOf } from '../../logic/auth/grant.js';
6
+ import { hasCredentials } from '../../logic/auth/owner.js';
7
+ import { removeSession } from '../../logic/auth/revoke.js';
8
+ import { planDisable, planReissue, planRole } from '../../logic/auth/user-plans.js';
9
+ import { authorizeActor, claimedByInvite, enabledUser, formatInviteCode, isInviteUsable, newInvite, newInvitedUser, normalizeInviteCode, spentInvite, summarizeUser, checkUser, } from '../../logic/auth/users.js';
10
+ import { liveSessionOf } from '../../logic/auth/session.js';
11
+ import * as persistence from '../../logic/persistence.js';
12
+ import { ACCESS_TOKEN_ENTITY_TAG, CLIENT_GRANT_ENTITY_TAG, INSTANCE_SETTINGS_ENTITY_TAG, INVITE_ENTITY_TAG, SESSION_ENTITY_TAG, USER_ENTITY_TAG, } from '../../models/auth/entity.js';
13
+ import { authErrors } from '../../models/auth/errors.js';
14
+ import { ActorKind, NO_REVOCATIONS, } from '../../models/auth/users.js';
15
+ import { startSession } from './session.js';
16
+ import { confirmedUser } from './step-up.js';
17
+ const updateUser = (user) => persistence.update({ entity: USER_ENTITY_TAG, model: user });
18
+ const removeInvite = (invite) => persistence.remove({ entity: INVITE_ENTITY_TAG, id: invite.id, version: invite.version });
19
+ const persistOf = (plan) => [
20
+ ...R.map(plan.checks, checkUser),
21
+ ...R.map(plan.removedInvites, removeInvite),
22
+ ...R.map(plan.newInvites, (invite) => persistence.insert({ entity: INVITE_ENTITY_TAG, model: invite })),
23
+ ...R.map(plan.userWrites, updateUser),
24
+ ...R.map(plan.expiredGrants, (grant) => persistence.update({ entity: CLIENT_GRANT_ENTITY_TAG, model: grant })),
25
+ ...R.map(plan.sessions, removeSession),
26
+ ...R.map(plan.tokens, (token) => persistence.update({ entity: ACCESS_TOKEN_ENTITY_TAG, model: token })),
27
+ ];
28
+ const admit = (deps, actor, options) => safeTry(async function* () {
29
+ const acting = actor.kind === ActorKind.enum.session ? await deps.users.findById(actor.principal.userId) : null;
30
+ yield* orRefuse(authorizeActor(actor, acting));
31
+ if (actor.kind !== ActorKind.enum.session)
32
+ return ok({ actingUserId: null, acting: null, session: null });
33
+ const sessions = await deps.sessions.listByUser(actor.principal.userId);
34
+ const session = yield* okOr(liveSessionOf(sessions, actor.principal.sessionId, deps.clock()), authErrors.unauthenticated);
35
+ if (options.stepUp) {
36
+ yield* okOr(await confirmedUser(deps, acting, actor.password), authErrors.invalidCredentials);
37
+ }
38
+ return ok({ actingUserId: acting?.id ?? null, acting, session });
39
+ });
40
+ const sessionCheck = ({ session }) => session === null ? [] : [persistence.check({ entity: SESSION_ENTITY_TAG, id: session.id, version: session.version })];
41
+ const batchOf = (admitted, plan) => {
42
+ const writes = persistOf(plan);
43
+ return writes.length === 0 ? [] : [...sessionCheck(admitted), ...writes];
44
+ };
45
+ const actorCheck = (admitted) => [
46
+ ...(admitted.acting === null ? [] : [checkUser(admitted.acting)]),
47
+ ...sessionCheck(admitted),
48
+ ];
49
+ const targetOf = ({ acting }, deps, userId) => safeTry(async function* () {
50
+ if (acting !== null && acting.id === userId)
51
+ return ok(acting);
52
+ return ok(yield* okOr(await deps.users.findById(userId), authErrors.unknownUser(userId)));
53
+ });
54
+ export const resolveUserId = (deps, username) => safeTry(async function* () {
55
+ const user = yield* okOr(await deps.users.findByUsername(username), authErrors.unknownUser(username));
56
+ return ok(user.id);
57
+ });
58
+ const heldCredentials = async (deps, userId) => ({
59
+ sessions: await deps.sessions.listByUser(userId),
60
+ tokens: await deps.accessTokens.listByUser(userId),
61
+ approvedGrants: await deps.clientGrants.listApprovedByUser(userId),
62
+ });
63
+ export const listUsers = (deps, actor) => safeTry(async function* () {
64
+ yield* admit(deps, actor, { stepUp: false });
65
+ const [users, invites] = [await deps.users.listAll(), await deps.invites.listUnclaimed()];
66
+ return ok(R.map(users, (user) => summarizeUser(user, invites, deps.clock())));
67
+ });
68
+ const freshInvite = (deps, fields, now) => {
69
+ const code = formatInviteCode(deps.secrets.randomInviteCode());
70
+ const invite = newInvite({ id: deps.newId(), ...fields, codeHash: deps.secrets.hashSecret(normalizeInviteCode(code)) }, now);
71
+ return { code, invite, insert: persistence.insert({ entity: INVITE_ENTITY_TAG, model: invite }) };
72
+ };
73
+ export const inviteUser = (deps, actor, input) => safeTry(async function* () {
74
+ const admitted = yield* admit(deps, actor, { stepUp: true });
75
+ yield* guard((await deps.users.findByUsername(input.username)) === null, authErrors.usernameTaken(input.username));
76
+ const now = deps.clock();
77
+ const user = newInvitedUser({ id: deps.newId(), ...input }, now);
78
+ const invite = freshInvite(deps, { userId: user.id, createdBy: admitted.actingUserId }, now);
79
+ const summary = {
80
+ ...summarizeUser({ ...user, version: INITIAL_VERSION }, [], now),
81
+ inviteExpiresAt: invite.invite.expiresAt,
82
+ };
83
+ return ok({
84
+ persist: [...actorCheck(admitted), persistence.insert({ entity: USER_ENTITY_TAG, model: user }), invite.insert],
85
+ response: { user: summary, code: invite.code, expiresAt: invite.invite.expiresAt, revoked: NO_REVOCATIONS },
86
+ });
87
+ });
88
+ export const reissueInvite = (deps, actor, userId) => safeTry(async function* () {
89
+ const admitted = yield* admit(deps, actor, { stepUp: true });
90
+ const target = yield* targetOf(admitted, deps, userId);
91
+ const now = deps.clock();
92
+ const invite = freshInvite(deps, { userId: target.id, createdBy: admitted.actingUserId }, now);
93
+ const plan = yield* planReissue({
94
+ ...admitted,
95
+ target,
96
+ users: await deps.users.listAll(),
97
+ held: await heldCredentials(deps, target.id),
98
+ openInvites: await deps.invites.listUnclaimedByUser(target.id),
99
+ invite: invite.invite,
100
+ now,
101
+ });
102
+ const user = { ...summarizeUser(plan.after, [], now), inviteExpiresAt: invite.invite.expiresAt };
103
+ const response = { user, code: invite.code, expiresAt: invite.invite.expiresAt, revoked: plan.revoked };
104
+ return ok({ persist: batchOf(admitted, plan), response });
105
+ });
106
+ const isClaimable = (user) => user !== null && user.disabledAt === null && !hasCredentials(user);
107
+ export const claimInvite = (deps, input) => safeTry(async function* () {
108
+ const now = deps.clock();
109
+ const stored = await deps.invites.findByHash(deps.secrets.hashSecret(normalizeInviteCode(input.code)));
110
+ const invite = yield* okOr(isInviteUsable(stored, now) ? stored : null, authErrors.invalidInvite);
111
+ const user = yield* okOr(await claimableUser(deps, invite), authErrors.invalidInvite);
112
+ const passwordHash = await deps.secrets.hashPassword(input.password);
113
+ const { persistable: sessionInsert, started } = startSession(deps, user.id, now);
114
+ const persist = [
115
+ updateUser(claimedByInvite(user, passwordHash, now)),
116
+ persistence.update({ entity: INVITE_ENTITY_TAG, model: spentInvite(invite, now) }),
117
+ sessionInsert,
118
+ ];
119
+ return ok({ persist, response: started });
120
+ });
121
+ const claimableUser = async (deps, invite) => {
122
+ const user = await deps.users.findById(invite.userId);
123
+ return isClaimable(user) ? user : null;
124
+ };
125
+ const reportOf = (user, revoked, now) => ({
126
+ user: summarizeUser(user, [], now),
127
+ revoked,
128
+ });
129
+ export const disableUser = (deps, actor, userId) => safeTry(async function* () {
130
+ const admitted = yield* admit(deps, actor, { stepUp: true });
131
+ const target = yield* targetOf(admitted, deps, userId);
132
+ const now = deps.clock();
133
+ const plan = yield* planDisable({
134
+ ...admitted,
135
+ target,
136
+ users: await deps.users.listAll(),
137
+ held: await heldCredentials(deps, target.id),
138
+ openInvites: await deps.invites.listUnclaimedByUser(target.id),
139
+ now,
140
+ });
141
+ return ok({
142
+ persist: batchOf(admitted, plan),
143
+ response: reportOf(plan.after, plan.revoked, now),
144
+ });
145
+ });
146
+ export const enableUser = (deps, actor, userId) => safeTry(async function* () {
147
+ const admitted = yield* admit(deps, actor, { stepUp: true });
148
+ const target = yield* targetOf(admitted, deps, userId);
149
+ const now = deps.clock();
150
+ if (target.disabledAt === null)
151
+ return ok({ persist: [], response: reportOf(target, NO_REVOCATIONS, now) });
152
+ const enabled = enabledUser(target);
153
+ return ok({
154
+ persist: [...actorCheck(admitted), updateUser(enabled)],
155
+ response: reportOf(enabled, NO_REVOCATIONS, now),
156
+ });
157
+ });
158
+ export const setRole = (deps, actor, input) => safeTry(async function* () {
159
+ const admitted = yield* admit(deps, actor, { stepUp: true });
160
+ const target = yield* targetOf(admitted, deps, input.userId);
161
+ const now = deps.clock();
162
+ const plan = yield* planRole({ ...admitted, target, users: await deps.users.listAll(), role: input.role, now });
163
+ return ok({
164
+ persist: batchOf(admitted, plan),
165
+ response: reportOf(plan.after, plan.revoked, now),
166
+ });
167
+ });
168
+ export const setSignInCap = (deps, actor, input) => safeTry(async function* () {
169
+ const admitted = yield* admit(deps, actor, { stepUp: true });
170
+ const current = await deps.instanceSettings.get();
171
+ if (signInCapOf(current) === input.maxSignInDuration)
172
+ return ok({ persist: [], response: input.maxSignInDuration });
173
+ const write = persistence.update({
174
+ entity: INSTANCE_SETTINGS_ENTITY_TAG,
175
+ model: { ...current, maxSignInDuration: input.maxSignInDuration },
176
+ });
177
+ return ok({ persist: [...actorCheck(admitted), write], response: input.maxSignInDuration });
178
+ });
179
+ export const pruneExpiredInvites = (deps) => safeTry(async function* () {
180
+ const expired = await deps.invites.listExpiredUnclaimed(deps.clock().toISOString());
181
+ return ok({ persist: R.map(expired, removeInvite), response: expired.length });
182
+ });
183
+ export const currentSignInCap = async (deps) => signInCapOf(await deps.instanceSettings.get());