@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,22 @@
1
+ import { STDIO_MESSAGES, TERMINAL_SETUP_HINT } from '../../models/auth/message.js';
2
+ import { LOG_PREFIX } from '../../models/package.js';
3
+ import { connectUrl } from './origin.js';
4
+ export const setupBanner = (fields) => [
5
+ '',
6
+ `┌─ ${LOG_PREFIX} first-time setup ─────────────────────────────────────────`,
7
+ '│ This instance has no login yet. Claim it with this one-time setup code:',
8
+ '│',
9
+ `│ ${fields.code}`,
10
+ '│',
11
+ `│ Open ${fields.setupUrl} and enter the code, then choose a username and password,`,
12
+ `│ ${TERMINAL_SETUP_HINT}.`,
13
+ `│ The code expires at ${fields.expiresAt} and is replaced by a new one on every restart.`,
14
+ '└──────────────────────────────────────────────────────────────────────',
15
+ '',
16
+ ].join('\n');
17
+ export const notSignedInMessage = (fields) => {
18
+ const base = fields.origin !== null && fields.userCode !== null
19
+ ? STDIO_MESSAGES.notSignedIn(connectUrl(fields.origin, fields.userCode), fields.userCode)
20
+ : STDIO_MESSAGES.notSignedInWithoutHttp;
21
+ return fields.ownerUnclaimed ? `${base}${STDIO_MESSAGES.ownerUnclaimedHint}` : base;
22
+ };
@@ -0,0 +1,57 @@
1
+ import { HTTP_SCHEME_PREFIX, hostnameOfHostHeader, isLoopbackHost } from '../../common/net.js';
2
+ import { authErrors } from '../../models/auth/errors.js';
3
+ import { CONNECT_CODE_PARAM, CONNECT_PATH, OPAQUE_ORIGIN, SAFE_METHODS, WEB_PROTOCOLS, } from '../../models/auth/origin.js';
4
+ export const isUnsafeMethod = (method) => !SAFE_METHODS.has(method.toUpperCase());
5
+ const parsedUrl = (url) => {
6
+ try {
7
+ return new URL(url);
8
+ }
9
+ catch {
10
+ return null;
11
+ }
12
+ };
13
+ const originOf = (url) => {
14
+ const parsed = parsedUrl(url);
15
+ return parsed === null || parsed.origin === OPAQUE_ORIGIN ? null : parsed.origin;
16
+ };
17
+ export const declaredOrigin = (origin, referer) => origin !== undefined ? originOf(origin) : referer !== undefined ? originOf(referer) : null;
18
+ export const isSameOrigin = (expectedOrigin, declared) => declared !== null && declared === expectedOrigin;
19
+ export const allowedOrigins = (publicUrl, hostHeader) => {
20
+ const hostname = hostHeader === undefined ? null : hostnameOfHostHeader(hostHeader);
21
+ const ownLoopbackOrigin = hostHeader !== undefined && hostname !== null && isLoopbackHost(hostname)
22
+ ? [`${HTTP_SCHEME_PREFIX}${hostHeader}`]
23
+ : [];
24
+ return [...(publicUrl === undefined ? [] : [publicUrl]), ...ownLoopbackOrigin];
25
+ };
26
+ export const csrfVerdict = (request) => {
27
+ if (!isUnsafeMethod(request.method))
28
+ return null;
29
+ const allowed = allowedOrigins(request.publicUrl, request.host);
30
+ if (allowed.length === 0)
31
+ return authErrors.unknownOrigin;
32
+ const declared = declaredOrigin(request.origin, request.referer);
33
+ return allowed.some((origin) => isSameOrigin(origin, declared)) ? null : authErrors.crossOrigin;
34
+ };
35
+ export const preSessionCsrfVerdict = (request) => request.origin === undefined && request.referer === undefined ? null : csrfVerdict(request);
36
+ const isLoopbackOrigin = (origin) => {
37
+ const parsed = parsedUrl(origin);
38
+ return (parsed !== null &&
39
+ parsed.origin !== OPAQUE_ORIGIN &&
40
+ WEB_PROTOCOLS.has(parsed.protocol) &&
41
+ isLoopbackHost(parsed.hostname));
42
+ };
43
+ export const isLoopbackRequest = (request) => {
44
+ const hostname = request.host === undefined ? null : hostnameOfHostHeader(request.host);
45
+ if (hostname === null || !isLoopbackHost(hostname))
46
+ return false;
47
+ return request.origin === undefined || isLoopbackOrigin(request.origin);
48
+ };
49
+ export const signInOrigin = (fields) => {
50
+ if (!fields.httpEnabled)
51
+ return null;
52
+ if (fields.publicUrl !== undefined)
53
+ return fields.publicUrl;
54
+ return isLoopbackHost(fields.host) ? fields.boundOrigin : null;
55
+ };
56
+ export const connectUrl = (origin, userCode) => `${origin}${CONNECT_PATH}?${CONNECT_CODE_PARAM}=${userCode}`;
57
+ export const resourceOrigin = (publicUrl, host) => allowedOrigins(publicUrl, host)[0] ?? null;
@@ -0,0 +1,22 @@
1
+ import { authErrors } from '../../models/auth/errors.js';
2
+ import { AuthMode } from '../../models/auth/mode.js';
3
+ import { NON_ALPHANUMERIC, SETUP_CODE_GROUP_SEPARATOR, SETUP_CODE_GROUP_SIZE, } from '../../models/auth/owner.js';
4
+ import { millis } from './time.js';
5
+ export const normalizeSetupCode = (raw) => raw.replace(NON_ALPHANUMERIC, '').toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1');
6
+ export const formatSetupCode = (raw) => (raw.match(new RegExp(`.{1,${SETUP_CODE_GROUP_SIZE}}`, 'g')) ?? []).join(SETUP_CODE_GROUP_SEPARATOR);
7
+ export const hasCredentials = (user) => user.username !== null && user.passwordHash !== null;
8
+ export const isUnclaimed = (owner) => owner !== null && !hasCredentials(owner);
9
+ export const isNeverClaimed = (owner) => owner !== null && owner.username === null && owner.passwordHash === null;
10
+ export const shouldIssueSetupCode = (mode, owner) => mode === AuthMode.enum.required && isNeverClaimed(owner);
11
+ export const isSetupCodeUsable = (code, now) => code !== null && code.usedAt === null && millis(code.expiresAt) > now.getTime();
12
+ export const claimedOwner = (owner, fields) => ({
13
+ ...owner,
14
+ ...fields,
15
+ });
16
+ export const spentSetupCode = (code, now) => ({
17
+ ...code,
18
+ usedAt: now.toISOString(),
19
+ });
20
+ export const planOwnerClaim = (claimed) => claimed === null ? { kind: 'claim' } : { kind: 'skip', username: claimed.username };
21
+ export const claimRaceWinner = (error, holder) => error.code === authErrors.setupUnavailable.code ? holder : null;
22
+ export const isActiveUser = (user) => user !== null && hasCredentials(user) && user.disabledAt === null;
@@ -0,0 +1,3 @@
1
+ import { isActiveUser } from './owner.js';
2
+ export const withPasswordHash = (user, passwordHash) => ({ ...user, passwordHash });
3
+ export const canLogin = (user, passwordMatches) => passwordMatches && isActiveUser(user);
@@ -0,0 +1,25 @@
1
+ import { SECRET_QUERY_PARAMS, REDACTED, NAME_VALUE_SEPARATOR } from '../../models/auth/redact.js';
2
+ const nameOf = (pair) => {
3
+ const raw = pair.split(NAME_VALUE_SEPARATOR)[0] ?? '';
4
+ try {
5
+ return decodeURIComponent(raw).toLowerCase();
6
+ }
7
+ catch {
8
+ return raw.toLowerCase();
9
+ }
10
+ };
11
+ const isSecretPair = (pair) => pair.includes(NAME_VALUE_SEPARATOR) && SECRET_QUERY_PARAMS.includes(nameOf(pair));
12
+ const redactedPair = (pair) => `${pair.slice(0, pair.indexOf(NAME_VALUE_SEPARATOR))}${NAME_VALUE_SEPARATOR}${REDACTED}`;
13
+ export const redactSecretQuery = (url) => {
14
+ const queryStart = url.indexOf('?');
15
+ if (queryStart === -1)
16
+ return url;
17
+ const fragmentStart = url.indexOf('#', queryStart);
18
+ const queryEnd = fragmentStart === -1 ? url.length : fragmentStart;
19
+ const query = url
20
+ .slice(queryStart + 1, queryEnd)
21
+ .split('&')
22
+ .map((pair) => (isSecretPair(pair) ? redactedPair(pair) : pair))
23
+ .join('&');
24
+ return `${url.slice(0, queryStart + 1)}${query}${url.slice(queryEnd)}`;
25
+ };
@@ -0,0 +1,28 @@
1
+ import * as R from 'remeda';
2
+ import * as persistence from '../persistence.js';
3
+ import { ACCESS_TOKEN_ENTITY_TAG, CLIENT_GRANT_ENTITY_TAG, SESSION_ENTITY_TAG } from '../../models/auth/entity.js';
4
+ import { GrantStatus } from '../../models/auth/grant.js';
5
+ import { expiredGrant } from './grant.js';
6
+ import { isLiveToken, revokedToken } from './token.js';
7
+ export const removeSession = (session) => persistence.remove({ entity: SESSION_ENTITY_TAG, id: session.id, version: session.version });
8
+ export const endedCredentials = (held, now) => {
9
+ const tokens = R.pipe(held.tokens, R.filter(isLiveToken(now)), R.map((token) => revokedToken(token, now)));
10
+ const expiredGrants = R.pipe(held.approvedGrants, R.filter((grant) => grant.status === GrantStatus.enum.approved), R.map(expiredGrant));
11
+ return {
12
+ sessions: [...held.sessions],
13
+ tokens,
14
+ expiredGrants,
15
+ revoked: { sessionsEnded: held.sessions.length, tokensRevoked: tokens.length },
16
+ };
17
+ };
18
+ export const endingCredentials = (held, now) => {
19
+ const ended = endedCredentials(held, now);
20
+ return {
21
+ persist: [
22
+ ...R.map(ended.sessions, removeSession),
23
+ ...R.map(ended.tokens, (token) => persistence.update({ entity: ACCESS_TOKEN_ENTITY_TAG, model: token })),
24
+ ...R.map(ended.expiredGrants, (grant) => persistence.update({ entity: CLIENT_GRANT_ENTITY_TAG, model: grant })),
25
+ ],
26
+ revoked: ended.revoked,
27
+ };
28
+ };
@@ -0,0 +1,17 @@
1
+ import { MCP_TOOLS_CALL_METHOD, READ_METHODS, READ_SCOPE, WRITE_SCOPE, } from '../../models/auth/scope.js';
2
+ export const hasScope = (granted, required) => granted.includes(required) || (required === READ_SCOPE && granted.includes(WRITE_SCOPE));
3
+ export const defaultScopeForMethod = (method) => READ_METHODS.includes(method.toUpperCase()) ? READ_SCOPE : WRITE_SCOPE;
4
+ export const scopeOfTool = (readOnlyHint) => readOnlyHint === true ? READ_SCOPE : WRITE_SCOPE;
5
+ export const requiredMcpScope = (body, toolScope) => {
6
+ const messages = Array.isArray(body) ? body : [body];
7
+ const needsWrite = messages.some((message) => {
8
+ if (typeof message !== 'object' || message === null)
9
+ return false;
10
+ const { method, params } = message;
11
+ if (method !== MCP_TOOLS_CALL_METHOD)
12
+ return false;
13
+ const name = params?.name;
14
+ return typeof name !== 'string' || (toolScope(name) ?? WRITE_SCOPE) === WRITE_SCOPE;
15
+ });
16
+ return needsWrite ? WRITE_SCOPE : READ_SCOPE;
17
+ };
@@ -0,0 +1,30 @@
1
+ import { PrincipalVia } from '../../models/auth/principal.js';
2
+ import { ALL_SCOPES } from '../../models/auth/scope.js';
3
+ import { SESSION_ABSOLUTE_MAX_MS, SESSION_IDLE_TTL_MS, SESSION_TOUCH_INTERVAL_MS, } from '../../models/auth/session.js';
4
+ import { hasCredentials } from './owner.js';
5
+ import { millis, toIso } from './time.js';
6
+ export const slidingExpiry = (createdAt, now) => toIso(Math.min(now.getTime() + SESSION_IDLE_TTL_MS, millis(createdAt) + SESSION_ABSOLUTE_MAX_MS));
7
+ export const newSession = (fields, now) => ({
8
+ ...fields,
9
+ createdAt: now.toISOString(),
10
+ lastSeenAt: now.toISOString(),
11
+ expiresAt: slidingExpiry(now.toISOString(), now),
12
+ });
13
+ export const isSessionExpired = (session, now) => now.getTime() >= millis(session.expiresAt) || now.getTime() >= millis(session.createdAt) + SESSION_ABSOLUTE_MAX_MS;
14
+ export const isStale = (session, now) => now.getTime() - millis(session.lastSeenAt) >= SESSION_TOUCH_INTERVAL_MS;
15
+ export const touched = (session, now) => ({
16
+ ...session,
17
+ lastSeenAt: now.toISOString(),
18
+ expiresAt: slidingExpiry(session.createdAt, now),
19
+ });
20
+ export const sessionPrincipal = (user, session) => ({
21
+ userId: user.id,
22
+ sessionId: session.id,
23
+ role: user.role,
24
+ scopes: [...ALL_SCOPES],
25
+ via: PrincipalVia.enum.session,
26
+ });
27
+ export const liveSessionOf = (sessions, sessionId, now) => sessions.find((s) => s.id === sessionId && !isSessionExpired(s, now)) ?? null;
28
+ export const evaluateSession = (session, user, now) => isSessionExpired(session, now) || user === null || !hasCredentials(user) || user.disabledAt !== null
29
+ ? { kind: 'invalid' }
30
+ : { kind: 'valid', touch: isStale(session, now) };
@@ -0,0 +1,305 @@
1
+ import * as R from 'remeda';
2
+ import { GrantChannel, RedeemKind } from '../../models/auth/grant.js';
3
+ import { STDIO_MESSAGES } from '../../models/auth/message.js';
4
+ import { WRITE_SCOPE } from '../../models/auth/scope.js';
5
+ import { GRANT_POLL_INTERVAL_MS } from '../../models/auth/sign-in.js';
6
+ import { CheckKind, ClearNext, Continuation, CredentialSource, EffectKind, LoadPurpose, ObservationKind, OwnerPurpose, PagePurpose, PresentationKind, REDEEM_ERROR_KIND, RevokeReason, IDLE, SignInStateKind, CLOSE_PAGE, } from '../../models/auth/sign-in-flow.js';
7
+ import { TokenAccess } from '../../models/auth/token.js';
8
+ import { persistsToKeychain } from './grant.js';
9
+ import { connectUrl } from './origin.js';
10
+ import { hasScope } from './scope.js';
11
+ import { isTokenShaped } from './token.js';
12
+ const S = SignInStateKind.enum;
13
+ const O = ObservationKind.enum;
14
+ const E = EffectKind.enum;
15
+ const P = PresentationKind.enum;
16
+ const CHANNEL = GrantChannel.enum;
17
+ export const pendingOf = (state) => {
18
+ switch (state.kind) {
19
+ case S.pending:
20
+ case S.signed_in:
21
+ return state.pending;
22
+ default:
23
+ return null;
24
+ }
25
+ };
26
+ const withPending = (state, pending) => state.kind === S.signed_in ? { ...state, pending } : { kind: S.pending, pending };
27
+ const withoutPending = (state) => {
28
+ if (state.kind === S.pending)
29
+ return IDLE;
30
+ return state.kind === S.signed_in ? { ...state, pending: null } : state;
31
+ };
32
+ const withoutHeld = (state) => {
33
+ const pending = pendingOf(state);
34
+ return pending === null ? IDLE : { kind: S.pending, pending };
35
+ };
36
+ const present = (presentation) => ({ kind: E.present, presentation });
37
+ const step = (state, ...effects) => ({ state, effects });
38
+ const tell = (state, presentation) => step(state, present(presentation));
39
+ const ask = (state, effect) => step(state, effect);
40
+ const ended = (kind, what) => step({ kind }, CLOSE_PAGE, present(what));
41
+ const failedWith = (reason) => ({ kind: P.failed, reason });
42
+ const startInput = (config) => ({
43
+ client: config.client,
44
+ profile: config.profile,
45
+ channel: config.channel,
46
+ ...(config.hint === undefined ? {} : { hint: config.hint }),
47
+ });
48
+ const accessOf = (signedIn) => hasScope(signedIn.scopes, WRITE_SCOPE) ? TokenAccess.enum.write : TokenAccess.enum.read;
49
+ const loadSaved = (purpose) => ({
50
+ kind: E.load_saved,
51
+ purpose,
52
+ tolerateUnreadable: purpose === LoadPurpose.enum.resolve,
53
+ });
54
+ const onRequested = (state, config) => {
55
+ if (config.envToken !== undefined) {
56
+ return isTokenShaped(config.envToken)
57
+ ? ask(state, { kind: E.check_credential, source: CredentialSource.enum.env, token: config.envToken })
58
+ : tell(state, { kind: P.invalid_env_token });
59
+ }
60
+ return state.kind === S.signed_in
61
+ ? ask(state, { kind: E.check_credential, source: CredentialSource.enum.held, token: state.held.token })
62
+ : ask(state, loadSaved(LoadPurpose.enum.resolve));
63
+ };
64
+ const checkedEnv = (state, result) => {
65
+ if (result.kind === CheckKind.enum.ok)
66
+ return tell(state, { kind: P.granted, principal: result.principal });
67
+ return tell(state, { kind: result.kind === CheckKind.enum.invalid ? P.invalid_env_token : P.cannot_verify });
68
+ };
69
+ const checkedHeld = (state, result) => {
70
+ if (state.kind !== S.signed_in)
71
+ return step(state);
72
+ const { held } = state;
73
+ switch (result.kind) {
74
+ case CheckKind.enum.ok:
75
+ return tell({ ...state, held: { ...held, principal: result.principal } }, { kind: P.granted, principal: result.principal });
76
+ case CheckKind.enum.failure:
77
+ return tell(state, { kind: P.cannot_verify });
78
+ case CheckKind.enum.invalid: {
79
+ const dropped = withoutHeld(state);
80
+ return held.ephemeral
81
+ ? ask(dropped, loadSaved(LoadPurpose.enum.resolve))
82
+ : ask(dropped, {
83
+ kind: E.clear_saved_if,
84
+ token: held.token,
85
+ next: ClearNext.enum.load_saved,
86
+ tolerateUnreadable: true,
87
+ });
88
+ }
89
+ }
90
+ };
91
+ const checkedSaved = (state, token, result) => {
92
+ switch (result.kind) {
93
+ case CheckKind.enum.ok:
94
+ return tell({
95
+ kind: S.signed_in,
96
+ held: { token, principal: result.principal, ephemeral: false },
97
+ pending: pendingOf(state),
98
+ }, { kind: P.granted, principal: result.principal });
99
+ case CheckKind.enum.failure:
100
+ return tell(state, { kind: P.cannot_verify });
101
+ case CheckKind.enum.invalid:
102
+ return ask(state, {
103
+ kind: E.clear_saved_if,
104
+ token,
105
+ next: ClearNext.enum.ask,
106
+ tolerateUnreadable: true,
107
+ });
108
+ }
109
+ };
110
+ const onCredentialChecked = (state, observation) => {
111
+ switch (observation.source) {
112
+ case CredentialSource.enum.env:
113
+ return checkedEnv(state, observation.result);
114
+ case CredentialSource.enum.held:
115
+ return checkedHeld(state, observation.result);
116
+ case CredentialSource.enum.saved:
117
+ return checkedSaved(state, observation.token, observation.result);
118
+ }
119
+ };
120
+ const showInstructions = (state) => ask(state, { kind: E.name_page, purpose: PagePurpose.enum.instructions });
121
+ const askToSignIn = (state) => {
122
+ const pending = pendingOf(state);
123
+ return pending === null
124
+ ? ask(state, { kind: E.name_page, purpose: PagePurpose.enum.new_request })
125
+ : ask(state, { kind: E.redeem_grant, deviceCode: pending.deviceCode, then: Continuation.enum.ask });
126
+ };
127
+ const onSavedLoaded = (state, observation, config) => {
128
+ if (observation.purpose === LoadPurpose.enum.logout) {
129
+ return observation.token === null
130
+ ? tell(state, { kind: P.not_signed_in, profile: config.profile })
131
+ : ask(state, { kind: E.revoke_credential, token: observation.token, reason: RevokeReason.enum.logout });
132
+ }
133
+ return observation.token === null
134
+ ? askToSignIn(state)
135
+ : ask(state, { kind: E.check_credential, source: CredentialSource.enum.saved, token: observation.token });
136
+ };
137
+ const onSavedCleared = (state, observation, config) => {
138
+ switch (observation.next) {
139
+ case ClearNext.enum.load_saved:
140
+ return ask(state, loadSaved(LoadPurpose.enum.resolve));
141
+ case ClearNext.enum.ask:
142
+ return askToSignIn(state);
143
+ case ClearNext.enum.signed_out:
144
+ return tell(state, { kind: P.signed_out, profile: config.profile });
145
+ }
146
+ };
147
+ const withoutPage = (state, purpose) => purpose === PagePurpose.enum.login
148
+ ? step({ kind: S.failed }, present(failedWith(STDIO_MESSAGES.notSignedInWithoutHttp)))
149
+ : showInstructions(state);
150
+ const startRequestAt = (state, origin, config) => ask(state, { kind: E.start_grant, input: startInput(config), origin });
151
+ const onPageNamed = (state, observation, config) => {
152
+ const { purpose, origin } = observation;
153
+ if (purpose === PagePurpose.enum.instructions) {
154
+ return ask(state, { kind: E.check_owner, purpose: OwnerPurpose.enum.instructions, origin });
155
+ }
156
+ if (origin !== null)
157
+ return startRequestAt(state, origin, config);
158
+ return observation.canServe ? ask(state, { kind: E.serve_page, purpose }) : withoutPage(state, purpose);
159
+ };
160
+ const onPageServed = (state, observation, config) => observation.origin === null
161
+ ? withoutPage(state, observation.purpose)
162
+ : startRequestAt(state, observation.origin, config);
163
+ const onGrantStarted = (state, observation, config) => {
164
+ const next = withPending(state, { deviceCode: observation.deviceCode, userCode: observation.userCode });
165
+ if (config.channel === CHANNEL.stdio)
166
+ return showInstructions(next);
167
+ return step(next, present({
168
+ kind: P.open,
169
+ url: connectUrl(observation.origin, observation.userCode),
170
+ code: observation.userCode,
171
+ }), present({ kind: P.waiting }));
172
+ };
173
+ const onGrantFailed = (state, observation, config) => config.channel === CHANNEL.stdio
174
+ ? step(state, CLOSE_PAGE, present({ kind: P.cannot_verify }))
175
+ : ended(S.failed, failedWith(observation.error));
176
+ const onOwnerChecked = (state, observation) => {
177
+ if (observation.purpose === OwnerPurpose.enum.login) {
178
+ return observation.unclaimed
179
+ ? step({ kind: S.failed }, present({ kind: P.owner_unclaimed }))
180
+ : ask(state, { kind: E.name_page, purpose: PagePurpose.enum.login });
181
+ }
182
+ const { origin } = observation;
183
+ return tell(state, {
184
+ kind: P.instructions,
185
+ origin,
186
+ userCode: origin === null ? null : (pendingOf(state)?.userCode ?? null),
187
+ ownerUnclaimed: observation.unclaimed,
188
+ });
189
+ };
190
+ const gone = (state, then) => {
191
+ const next = withoutPending(state);
192
+ return then === Continuation.enum.ask
193
+ ? step(next, CLOSE_PAGE, { kind: E.name_page, purpose: PagePurpose.enum.new_request })
194
+ : step(next, CLOSE_PAGE);
195
+ };
196
+ const stillPending = (state, config, then) => {
197
+ if (config.channel === CHANNEL.cli)
198
+ return step(state, { kind: E.wait, ms: GRANT_POLL_INTERVAL_MS });
199
+ return then === Continuation.enum.ask ? showInstructions(state) : step(state);
200
+ };
201
+ const adopted = (signedIn, ephemeral, then, config) => {
202
+ const held = { token: signedIn.token, principal: signedIn.principal, ephemeral };
203
+ const next = { kind: S.signed_in, held, pending: null };
204
+ if (config.channel === CHANNEL.cli) {
205
+ return step(next, CLOSE_PAGE, present({
206
+ kind: P.signed_in,
207
+ profile: config.profile,
208
+ access: accessOf(signedIn),
209
+ expiresAt: signedIn.expiresAt,
210
+ }));
211
+ }
212
+ return then === Continuation.enum.ask
213
+ ? step(next, CLOSE_PAGE, present({ kind: P.granted, principal: signedIn.principal }))
214
+ : step(next, CLOSE_PAGE);
215
+ };
216
+ const keepSignIn = (state, signedIn, then, config) => persistsToKeychain(signedIn.duration)
217
+ ? ask(state, { kind: E.save_credential, signedIn, then })
218
+ : adopted(signedIn, true, then, config);
219
+ const onRedeemed = (state, observation, config) => {
220
+ const { result, then } = observation;
221
+ switch (result.kind) {
222
+ case RedeemKind.enum.signed_in:
223
+ return keepSignIn(state, R.omit(result, ['kind']), then, config);
224
+ case REDEEM_ERROR_KIND:
225
+ return config.channel === CHANNEL.cli
226
+ ? ended(S.failed, failedWith(result.error))
227
+ : stillPending(state, config, then);
228
+ case RedeemKind.enum.pending:
229
+ return stillPending(state, config, then);
230
+ case RedeemKind.enum.denied:
231
+ return config.channel === CHANNEL.cli ? ended(S.denied, { kind: P.denied }) : gone(state, then);
232
+ case RedeemKind.enum.expired:
233
+ case RedeemKind.enum.invalid:
234
+ return config.channel === CHANNEL.cli ? ended(S.expired, { kind: P.expired }) : gone(state, then);
235
+ }
236
+ };
237
+ const onSaved = (state, observation, config) => {
238
+ const { signedIn, then } = observation;
239
+ if (observation.ok)
240
+ return adopted(signedIn, false, then, config);
241
+ return config.channel === CHANNEL.cli
242
+ ? ask(state, { kind: E.revoke_credential, token: signedIn.token, reason: RevokeReason.enum.keychain_refused })
243
+ : adopted(signedIn, true, then, config);
244
+ };
245
+ const onRevoked = (state, observation) => {
246
+ switch (observation.reason) {
247
+ case RevokeReason.enum.keychain_refused:
248
+ return ended(S.failed, { kind: observation.ok ? P.keychain_refused : P.keychain_refused_still_active });
249
+ case RevokeReason.enum.logout:
250
+ return observation.ok
251
+ ? ask(state, {
252
+ kind: E.clear_saved_if,
253
+ token: observation.token,
254
+ next: ClearNext.enum.signed_out,
255
+ tolerateUnreadable: false,
256
+ })
257
+ : step({ kind: S.failed }, present({ kind: P.logout_failed, reason: observation.error ?? '' }));
258
+ case RevokeReason.enum.close:
259
+ return step(state);
260
+ }
261
+ };
262
+ const onTicked = (state) => {
263
+ const pending = pendingOf(state);
264
+ return pending === null
265
+ ? step(state)
266
+ : ask(state, { kind: E.redeem_grant, deviceCode: pending.deviceCode, then: Continuation.enum.poll });
267
+ };
268
+ const onLoginRequested = (config) => config.authRequired
269
+ ? ask(IDLE, { kind: E.check_owner, purpose: OwnerPurpose.enum.login, origin: null })
270
+ : step({ kind: S.failed }, present({ kind: P.auth_disabled }));
271
+ const onLogoutRequested = () => ask(IDLE, loadSaved(LoadPurpose.enum.logout));
272
+ const onInterrupted = (state) => state.kind === S.pending ? ended(S.cancelled, { kind: P.cancelled }) : step(state);
273
+ const onClosed = (state) => {
274
+ const base = withoutPending(state);
275
+ if (base.kind === S.signed_in && base.held.ephemeral) {
276
+ return step(IDLE, CLOSE_PAGE, {
277
+ kind: E.revoke_credential,
278
+ token: base.held.token,
279
+ reason: RevokeReason.enum.close,
280
+ });
281
+ }
282
+ return step(base, CLOSE_PAGE);
283
+ };
284
+ const OBSERVATION_HANDLERS = {
285
+ [O.requested]: (state, _observation, config) => onRequested(state, config),
286
+ [O.ticked]: onTicked,
287
+ [O.login_requested]: (_state, _observation, config) => onLoginRequested(config),
288
+ [O.logout_requested]: onLogoutRequested,
289
+ [O.interrupted]: onInterrupted,
290
+ [O.closed]: onClosed,
291
+ [O.errored]: (state) => tell(state, { kind: P.cannot_verify }),
292
+ [O.credential_checked]: onCredentialChecked,
293
+ [O.saved_loaded]: onSavedLoaded,
294
+ [O.saved_unreadable]: () => step({ kind: S.failed }, present({ kind: P.keychain_unreadable })),
295
+ [O.saved_cleared]: onSavedCleared,
296
+ [O.owner_checked]: onOwnerChecked,
297
+ [O.page_named]: onPageNamed,
298
+ [O.page_served]: onPageServed,
299
+ [O.grant_started]: onGrantStarted,
300
+ [O.grant_failed]: onGrantFailed,
301
+ [O.redeemed]: onRedeemed,
302
+ [O.saved]: onSaved,
303
+ [O.revoked]: onRevoked,
304
+ };
305
+ export const nextStep = (state, observation, config) => OBSERVATION_HANDLERS[observation.kind](state, observation, config);
@@ -0,0 +1,2 @@
1
+ export const millis = (iso) => Date.parse(iso);
2
+ export const toIso = (millisSinceEpoch) => new Date(millisSinceEpoch).toISOString();
@@ -0,0 +1,74 @@
1
+ import { PrincipalVia } from '../../models/auth/principal.js';
2
+ import { SESSION_TOUCH_INTERVAL_MS } from '../../models/auth/session.js';
3
+ import { DAY_MS } from '../../models/auth/time.js';
4
+ import { AccessTokenKind, MAX_TOKEN_LENGTH, TOKEN_ACCESS_SCOPES, TOKEN_DISPLAY_PREFIX_RANDOM_CHARS, TOKEN_EXPIRY_DAYS, TOKEN_PREFIX, TokenStatus, } from '../../models/auth/token.js';
5
+ import { hasCredentials } from './owner.js';
6
+ import { millis, toIso } from './time.js';
7
+ export const tokenDisplayPrefix = (token) => token.slice(0, TOKEN_PREFIX.length + TOKEN_DISPLAY_PREFIX_RANDOM_CHARS);
8
+ export const newAccessToken = (fields, now) => {
9
+ const days = TOKEN_EXPIRY_DAYS[fields.input.expiry];
10
+ return {
11
+ id: fields.id,
12
+ userId: fields.userId,
13
+ name: fields.input.name,
14
+ tokenHash: fields.tokenHash,
15
+ prefix: fields.prefix,
16
+ scopes: [...TOKEN_ACCESS_SCOPES[fields.input.access]],
17
+ kind: AccessTokenKind.enum.pat,
18
+ clientName: null,
19
+ profile: null,
20
+ createdAt: now.toISOString(),
21
+ lastUsedAt: null,
22
+ expiresAt: toIso(now.getTime() + days * DAY_MS),
23
+ revokedAt: null,
24
+ };
25
+ };
26
+ export const tokenStatus = (token, now) => token.revokedAt !== null
27
+ ? TokenStatus.enum.revoked
28
+ : token.expiresAt !== null && now.getTime() >= millis(token.expiresAt)
29
+ ? TokenStatus.enum.expired
30
+ : TokenStatus.enum.active;
31
+ export const isLiveToken = (now) => (token) => tokenStatus(token, now) === TokenStatus.enum.active;
32
+ export const summarizeToken = (token, now) => ({
33
+ id: token.id,
34
+ userId: token.userId,
35
+ name: token.name,
36
+ prefix: token.prefix,
37
+ scopes: token.scopes,
38
+ kind: token.kind,
39
+ clientName: token.clientName,
40
+ profile: token.profile,
41
+ createdAt: token.createdAt,
42
+ lastUsedAt: token.lastUsedAt,
43
+ expiresAt: token.expiresAt,
44
+ revokedAt: token.revokedAt,
45
+ status: tokenStatus(token, now),
46
+ });
47
+ export const tokenAdmitsVia = (token, via) => token.kind === AccessTokenKind.enum.pat || via === PrincipalVia.enum.stdio;
48
+ export const evaluateToken = (token, user, now, via = PrincipalVia.enum.token) => token === null ||
49
+ !tokenAdmitsVia(token, via) ||
50
+ tokenStatus(token, now) !== TokenStatus.enum.active ||
51
+ user === null ||
52
+ !hasCredentials(user) ||
53
+ user.disabledAt !== null
54
+ ? { kind: 'invalid' }
55
+ : {
56
+ kind: 'valid',
57
+ touch: token.lastUsedAt === null || now.getTime() - millis(token.lastUsedAt) >= SESSION_TOUCH_INTERVAL_MS,
58
+ };
59
+ export const usedToken = (token, now) => ({
60
+ ...token,
61
+ lastUsedAt: now.toISOString(),
62
+ });
63
+ export const revokedToken = (token, now) => ({
64
+ ...token,
65
+ revokedAt: now.toISOString(),
66
+ });
67
+ export const tokenPrincipal = (token, user, via = PrincipalVia.enum.token) => ({
68
+ userId: user.id,
69
+ role: user.role,
70
+ scopes: token.scopes,
71
+ via,
72
+ tokenId: token.id,
73
+ });
74
+ export const isTokenShaped = (raw) => raw.startsWith(TOKEN_PREFIX) && raw.length <= MAX_TOKEN_LENGTH;