@otea/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/LICENSE +661 -0
  2. package/README.es.md +151 -0
  3. package/README.md +252 -2
  4. package/THIRD_PARTY_NOTICES.md +114 -0
  5. package/bin/otea.mjs +28 -0
  6. package/dist/app/agent-detail.js +26 -0
  7. package/dist/app/agent-draft.js +429 -0
  8. package/dist/app/agent-prompts.js +52 -0
  9. package/dist/app/agents.js +77 -0
  10. package/dist/app/asking.js +43 -0
  11. package/dist/app/board-archive.js +243 -0
  12. package/dist/app/board-migration.js +272 -0
  13. package/dist/app/boards.js +870 -0
  14. package/dist/app/branch-owner.js +48 -0
  15. package/dist/app/brief.js +53 -0
  16. package/dist/app/choices.js +61 -0
  17. package/dist/app/collections.js +101 -0
  18. package/dist/app/context.js +1 -0
  19. package/dist/app/crop.js +56 -0
  20. package/dist/app/devices.js +62 -0
  21. package/dist/app/draft-request.js +82 -0
  22. package/dist/app/events.js +12 -0
  23. package/dist/app/evidence.js +287 -0
  24. package/dist/app/gates.js +610 -0
  25. package/dist/app/guide.js +37 -0
  26. package/dist/app/home.js +145 -0
  27. package/dist/app/init-boards.js +36 -0
  28. package/dist/app/intake.js +25 -0
  29. package/dist/app/item-search.js +141 -0
  30. package/dist/app/items.js +318 -0
  31. package/dist/app/keep-waiting.js +44 -0
  32. package/dist/app/land-order.js +107 -0
  33. package/dist/app/language.js +52 -0
  34. package/dist/app/launcher.js +56 -0
  35. package/dist/app/lease-take.js +54 -0
  36. package/dist/app/leases.js +86 -0
  37. package/dist/app/machine.js +39 -0
  38. package/dist/app/merged.js +89 -0
  39. package/dist/app/migrate.js +171 -0
  40. package/dist/app/next.js +1637 -0
  41. package/dist/app/notes.js +319 -0
  42. package/dist/app/notify-targets.js +113 -0
  43. package/dist/app/opened.js +25 -0
  44. package/dist/app/owner-only.js +34 -0
  45. package/dist/app/performance.js +28 -0
  46. package/dist/app/phone.js +97 -0
  47. package/dist/app/presence.js +596 -0
  48. package/dist/app/preset-views.js +25 -0
  49. package/dist/app/presets.js +129 -0
  50. package/dist/app/priority.js +156 -0
  51. package/dist/app/profile.js +86 -0
  52. package/dist/app/project.js +247 -0
  53. package/dist/app/proofs.js +179 -0
  54. package/dist/app/questions.js +215 -0
  55. package/dist/app/reader-filter.js +58 -0
  56. package/dist/app/relations.js +164 -0
  57. package/dist/app/relay.js +98 -0
  58. package/dist/app/repos.js +176 -0
  59. package/dist/app/restart.js +92 -0
  60. package/dist/app/set-aside.js +64 -0
  61. package/dist/app/system-locale.js +6 -0
  62. package/dist/app/tailscale-cli.js +77 -0
  63. package/dist/app/tailscale-testing.js +41 -0
  64. package/dist/app/tailscale.js +177 -0
  65. package/dist/app/tips.js +30 -0
  66. package/dist/app/topics-everywhere.js +53 -0
  67. package/dist/app/topics.js +453 -0
  68. package/dist/app/undo.js +52 -0
  69. package/dist/app/validate.js +131 -0
  70. package/dist/app/watch.js +48 -0
  71. package/dist/cli/command.js +44 -0
  72. package/dist/cli/commands.js +3303 -0
  73. package/dist/cli/exit-codes.js +70 -0
  74. package/dist/cli/forge.js +176 -0
  75. package/dist/cli/format.js +340 -0
  76. package/dist/cli/gh.js +17 -0
  77. package/dist/cli/gitrepo.js +489 -0
  78. package/dist/cli/help.js +101 -0
  79. package/dist/cli/hooks.js +232 -0
  80. package/dist/cli/main.js +37 -0
  81. package/dist/cli/merged-outside.js +58 -0
  82. package/dist/cli/names.js +154 -0
  83. package/dist/cli/opener.js +21 -0
  84. package/dist/cli/owner.js +154 -0
  85. package/dist/cli/phone.js +221 -0
  86. package/dist/cli/ports.js +24 -0
  87. package/dist/cli/probe.js +18 -0
  88. package/dist/cli/run.js +246 -0
  89. package/dist/cli/serve-file.js +21 -0
  90. package/dist/cli/stats.js +55 -0
  91. package/dist/cli/version.js +3 -0
  92. package/dist/core/agent-guide.js +31 -0
  93. package/dist/core/agent-prompts.js +139 -0
  94. package/dist/core/authority.js +94 -0
  95. package/dist/core/board/analysis.js +86 -0
  96. package/dist/core/board/choices.js +100 -0
  97. package/dist/core/board/compile.js +362 -0
  98. package/dist/core/board/engine.js +523 -0
  99. package/dist/core/board/hints.js +46 -0
  100. package/dist/core/board/history.js +146 -0
  101. package/dist/core/board/ids.js +87 -0
  102. package/dist/core/board/joins.js +30 -0
  103. package/dist/core/board/mentions.js +68 -0
  104. package/dist/core/board/merged.js +18 -0
  105. package/dist/core/board/model.js +135 -0
  106. package/dist/core/board/next.js +1116 -0
  107. package/dist/core/board/notes.js +298 -0
  108. package/dist/core/board/performance.js +218 -0
  109. package/dist/core/board/plan.js +299 -0
  110. package/dist/core/board/problems.js +232 -0
  111. package/dist/core/board/proofs.js +84 -0
  112. package/dist/core/board/questions.js +114 -0
  113. package/dist/core/board/reading.js +220 -0
  114. package/dist/core/board/readings.js +534 -0
  115. package/dist/core/board/schema.js +335 -0
  116. package/dist/core/board/shape-words.js +179 -0
  117. package/dist/core/board/template-words.js +23 -0
  118. package/dist/core/board/templates-catalogue.js +965 -0
  119. package/dist/core/board/templates-coverage.js +261 -0
  120. package/dist/core/board/templates-flows.js +779 -0
  121. package/dist/core/board/templates.js +586 -0
  122. package/dist/core/brief.js +93 -0
  123. package/dist/core/diagram.js +80 -0
  124. package/dist/core/errors.js +12 -0
  125. package/dist/core/evidence.js +33 -0
  126. package/dist/core/fields.js +129 -0
  127. package/dist/core/hierarchy.js +30 -0
  128. package/dist/core/icons.js +181 -0
  129. package/dist/core/image-crop.js +166 -0
  130. package/dist/core/item.js +49 -0
  131. package/dist/core/lease.js +31 -0
  132. package/dist/core/modules.js +318 -0
  133. package/dist/core/notify/planner.js +117 -0
  134. package/dist/core/notify/signals.js +66 -0
  135. package/dist/core/notify/text.js +60 -0
  136. package/dist/core/path-key.js +22 -0
  137. package/dist/core/placement.js +161 -0
  138. package/dist/core/preset-labels.js +66 -0
  139. package/dist/core/preset-notes.js +109 -0
  140. package/dist/core/preset.js +541 -0
  141. package/dist/core/profile.js +55 -0
  142. package/dist/core/project-id.js +20 -0
  143. package/dist/core/refusal.js +1 -0
  144. package/dist/core/relations.js +208 -0
  145. package/dist/core/repo.js +54 -0
  146. package/dist/core/samples.js +161 -0
  147. package/dist/core/search-words.js +68 -0
  148. package/dist/core/test-report.js +120 -0
  149. package/dist/core/time.js +8 -0
  150. package/dist/core/validation.js +60 -0
  151. package/dist/core/views.js +171 -0
  152. package/dist/core/workflow.js +51 -0
  153. package/dist/mcp/commands.js +101 -0
  154. package/dist/mcp/server.js +239 -0
  155. package/dist/mcp/words.js +95 -0
  156. package/dist/server/boards.js +232 -0
  157. package/dist/server/changes.js +42 -0
  158. package/dist/server/diff-tip.js +83 -0
  159. package/dist/server/drift.js +87 -0
  160. package/dist/server/errors.js +87 -0
  161. package/dist/server/evidence.js +82 -0
  162. package/dist/server/hosts.js +6 -0
  163. package/dist/server/hub.js +98 -0
  164. package/dist/server/lan-access.js +62 -0
  165. package/dist/server/lan.js +164 -0
  166. package/dist/server/listen.js +70 -0
  167. package/dist/server/notifier.js +156 -0
  168. package/dist/server/notify-api.js +151 -0
  169. package/dist/server/pairing.js +124 -0
  170. package/dist/server/projects.js +191 -0
  171. package/dist/server/push.js +199 -0
  172. package/dist/server/server.js +960 -0
  173. package/dist/server/session.js +43 -0
  174. package/dist/server/stream.js +36 -0
  175. package/dist/server/test-push.js +38 -0
  176. package/dist/server/token.js +37 -0
  177. package/dist/server/transports.js +54 -0
  178. package/dist/server/ui.js +44 -0
  179. package/dist/server/writes.js +361 -0
  180. package/dist/server/wrong-address.js +36 -0
  181. package/dist/store/boards.js +111 -0
  182. package/dist/store/database.js +45 -0
  183. package/dist/store/machine.js +77 -0
  184. package/dist/store/migrations.js +493 -0
  185. package/dist/store/queries.js +585 -0
  186. package/dist/store/registry.js +72 -0
  187. package/package.json +73 -4
  188. package/presets/architecture/playbook.md +69 -0
  189. package/presets/architecture/preset.yaml +80 -0
  190. package/presets/architecture/samples.yaml +23 -0
  191. package/presets/bug-triage/playbook.md +129 -0
  192. package/presets/bug-triage/preset.yaml +127 -0
  193. package/presets/bug-triage/samples/wall-slide-after.png +0 -0
  194. package/presets/bug-triage/samples/wall-slide-before.png +0 -0
  195. package/presets/bug-triage/samples.yaml +72 -0
  196. package/presets/change/playbook.md +115 -0
  197. package/presets/change/preset.yaml +141 -0
  198. package/presets/change/samples.yaml +62 -0
  199. package/presets/review/playbook.md +51 -0
  200. package/presets/review/preset.yaml +62 -0
  201. package/presets/review/samples.yaml +27 -0
  202. package/presets/tasks/playbook.md +78 -0
  203. package/presets/tasks/preset.yaml +61 -0
  204. package/presets/tasks/samples.yaml +46 -0
  205. package/schemas/board.schema.json +764 -0
  206. package/ui/dist/THIRD_PARTY_NOTICES.md +114 -0
  207. package/ui/dist/assets/dm-mono-latin-400-normal--0xN8mdc.woff +0 -0
  208. package/ui/dist/assets/dm-mono-latin-400-normal-4GdczIuU.woff2 +0 -0
  209. package/ui/dist/assets/dm-mono-latin-500-normal-CN8Miw6E.woff +0 -0
  210. package/ui/dist/assets/dm-mono-latin-500-normal-DRMDZjhP.woff2 +0 -0
  211. package/ui/dist/assets/dm-mono-latin-ext-400-normal-1aZr6b2b.woff +0 -0
  212. package/ui/dist/assets/dm-mono-latin-ext-400-normal-C2zvOubV.woff2 +0 -0
  213. package/ui/dist/assets/dm-mono-latin-ext-500-normal-BtRyHRi6.woff2 +0 -0
  214. package/ui/dist/assets/dm-mono-latin-ext-500-normal-Dw3M13d8.woff +0 -0
  215. package/ui/dist/assets/index-C3OzJope.js +103 -0
  216. package/ui/dist/assets/index-COdEjckQ.css +1 -0
  217. package/ui/dist/assets/newsreader-latin-ext-opsz-italic-CSPGnFdO.woff2 +0 -0
  218. package/ui/dist/assets/newsreader-latin-ext-opsz-normal-BQn1nviT.woff2 +0 -0
  219. package/ui/dist/assets/newsreader-latin-opsz-italic-kJKFiXvB.woff2 +0 -0
  220. package/ui/dist/assets/newsreader-latin-opsz-normal-s-izfB6B.woff2 +0 -0
  221. package/ui/dist/assets/newsreader-vietnamese-opsz-italic-DTr-ymY4.woff2 +0 -0
  222. package/ui/dist/assets/newsreader-vietnamese-opsz-normal-BjhtXyW2.woff2 +0 -0
  223. package/ui/dist/assets/pdf-YwugTw7Y.js +54 -0
  224. package/ui/dist/assets/pdf-engine-CkBopwck.js +1 -0
  225. package/ui/dist/assets/pdf-rELvHkft.js +56 -0
  226. package/ui/dist/assets/pdf.worker.min-B5Yc7dP4.mjs +27 -0
  227. package/ui/dist/assets/pdf.worker.min-B7U8ptvh.js +1 -0
  228. package/ui/dist/assets/pdf.worker.min-CIqJB0yW.mjs +28 -0
  229. package/ui/dist/assets/pdf.worker.min-UqOn5EDC.js +1 -0
  230. package/ui/dist/assets/schibsted-grotesk-latin-ext-wght-normal-hsMS0n0O.woff2 +0 -0
  231. package/ui/dist/assets/schibsted-grotesk-latin-wght-normal-Bb8VGrTG.woff2 +0 -0
  232. package/ui/dist/icons/apple-touch-icon.png +0 -0
  233. package/ui/dist/icons/otea-192.png +0 -0
  234. package/ui/dist/icons/otea-512.png +0 -0
  235. package/ui/dist/icons/otea-badge.png +0 -0
  236. package/ui/dist/icons/otea-maskable-512.png +0 -0
  237. package/ui/dist/index.html +25 -0
  238. package/ui/dist/manifest.webmanifest +24 -0
  239. package/ui/dist/otea-idle.svg +5 -0
  240. package/ui/dist/otea-working.svg +5 -0
  241. package/ui/dist/otea-yours-working.svg +5 -0
  242. package/ui/dist/otea-yours.svg +5 -0
  243. package/ui/dist/sw.js +1 -0
@@ -0,0 +1,151 @@
1
+ import { Hono } from 'hono';
2
+ import { streamSSE } from 'hono/streaming';
3
+ import { z } from 'zod';
4
+ import { desktopTarget, dropSubscription, loseSubscription, saveDesktopPrefs, savePrefs, saveSubscription, targetOfDevice, } from '../app/notify-targets.js';
5
+ import { DEFAULT_PREFS, TIME_PATTERN } from '../core/notify/planner.js';
6
+ import { isNoticeLang } from '../core/notify/text.js';
7
+ import { RejectedRequest } from './errors.js';
8
+ import { assertCanManageDevices } from './pairing.js';
9
+ import { isPushEndpoint } from './push.js';
10
+ import { clientOf } from './session.js';
11
+ import { sendTestPush } from './test-push.js';
12
+ import { assertSameOrigin, assertWritable } from './writes.js';
13
+ const Time = z.string().regex(TIME_PATTERN);
14
+ const Prefs = z.object({
15
+ turn: z.boolean(),
16
+ ask: z.boolean(),
17
+ replied: z.boolean(),
18
+ stuck: z.boolean(),
19
+ aside: z.boolean(),
20
+ quiet: z.object({ from: Time, to: Time }).nullable(),
21
+ // The projects muted, by id.
22
+ muted: z.array(z.string().min(1).max(200)).max(500),
23
+ });
24
+ const Lang = z.enum(['es', 'en']);
25
+ const SubscribeBody = z.object({
26
+ endpoint: z.string().max(2048),
27
+ keys: z.object({ p256dh: z.string().max(200), auth: z.string().max(100) }),
28
+ lang: Lang,
29
+ });
30
+ const PrefsBody = z.object({ prefs: Prefs, lang: Lang });
31
+ const bytes = (text) => Buffer.from(text, 'base64url').length;
32
+ async function body(c, schema, expected) {
33
+ assertSameOrigin(c);
34
+ const parsed = schema.safeParse(await c.req.json().catch(() => undefined));
35
+ if (!parsed.success)
36
+ throw new RejectedRequest(400, 'invalid_body', `Expected ${expected}`);
37
+ return parsed.data;
38
+ }
39
+ // The paired device asking, over HTTPS: Web Push needs a secure page, so a device on the local
40
+ // network's plain HTTP is told why it cannot.
41
+ function pushDevice(c) {
42
+ const client = clientOf(c);
43
+ if (client.kind !== 'device') {
44
+ throw new RejectedRequest(403, 'forbidden', 'Only a paired device subscribes to push');
45
+ }
46
+ if (!client.secure) {
47
+ throw new RejectedRequest(409, 'push_needs_https', 'Notifications need the phone on HTTPS; connect it through Tailscale (otea phone tailscale)');
48
+ }
49
+ return client.device.id;
50
+ }
51
+ function unsubscribingDevice(c) {
52
+ const client = clientOf(c);
53
+ if (client.kind !== 'device') {
54
+ throw new RejectedRequest(403, 'forbidden', 'Only a paired device unsubscribes from push');
55
+ }
56
+ return client.device.id;
57
+ }
58
+ function view(c, machine, keys) {
59
+ const client = clientOf(c);
60
+ if (client.kind === 'device') {
61
+ const target = targetOfDevice(machine, client.device.id);
62
+ return {
63
+ target: 'device',
64
+ key: client.secure ? keys.publicKey : null,
65
+ subscribed: target?.push != null,
66
+ lost: target !== undefined && target.push === null,
67
+ prefs: target?.prefs ?? DEFAULT_PREFS,
68
+ };
69
+ }
70
+ return {
71
+ target: 'desktop',
72
+ key: null,
73
+ subscribed: true,
74
+ lost: false,
75
+ prefs: desktopTarget(machine).prefs,
76
+ };
77
+ }
78
+ export function notifyApi(machine, notifier, keys, auth, push) {
79
+ return (new Hono()
80
+ .get('/notify', (c) => c.json(view(c, machine, keys)))
81
+ .post('/notify/subscribe', async (c) => {
82
+ assertWritable(c, auth);
83
+ const device = pushDevice(c);
84
+ const { endpoint, keys: subscription, lang, } = await body(c, SubscribeBody, '{"endpoint": string, "keys": {"p256dh": string, "auth": string}, "lang": "es" | "en"}');
85
+ if (!isPushEndpoint(endpoint)) {
86
+ throw new RejectedRequest(400, 'invalid_body', 'The endpoint is not a push service');
87
+ }
88
+ if (bytes(subscription.p256dh) !== 65 || bytes(subscription.auth) !== 16) {
89
+ throw new RejectedRequest(400, 'invalid_body', 'The subscription keys do not read');
90
+ }
91
+ saveSubscription(machine, device, { endpoint, ...subscription }, lang);
92
+ notifier.refresh();
93
+ return c.json(view(c, machine, keys), 201);
94
+ })
95
+ // Preferencias › Avisos › Enviar un aviso de prueba: one push to this device now, past the
96
+ // planner, the quiet hours and the spacing, with what its push service answered.
97
+ .post('/notify/test', async (c) => {
98
+ assertWritable(c, auth);
99
+ assertSameOrigin(c);
100
+ const device = pushDevice(c);
101
+ const answer = await sendTestPush(machine, push.sender, device, push.log);
102
+ if (answer.result === 'gone')
103
+ notifier.refresh();
104
+ return c.json(answer);
105
+ })
106
+ .post('/notify/unsubscribe', (c) => {
107
+ assertWritable(c, auth);
108
+ assertSameOrigin(c);
109
+ dropSubscription(machine, unsubscribingDevice(c));
110
+ notifier.refresh();
111
+ return c.json(view(c, machine, keys));
112
+ })
113
+ // The phone's browser no longer holds the subscription the server pushes to (TS-3).
114
+ .post('/notify/lost', (c) => {
115
+ assertWritable(c, auth);
116
+ assertSameOrigin(c);
117
+ loseSubscription(machine, unsubscribingDevice(c));
118
+ notifier.refresh();
119
+ return c.json(view(c, machine, keys));
120
+ })
121
+ .post('/notify/prefs', async (c) => {
122
+ assertWritable(c, auth);
123
+ const { prefs, lang } = await body(c, PrefsBody, '{"prefs": {"turn", "ask", "replied", "stuck", "aside": boolean, "quiet": {"from": "HH:MM", "to": "HH:MM"} | null, "muted": [project id]}, "lang": "es" | "en"}');
124
+ const client = clientOf(c);
125
+ if (client.kind === 'device')
126
+ savePrefs(machine, client.device.id, prefs, lang);
127
+ else {
128
+ assertCanManageDevices(c, auth);
129
+ saveDesktopPrefs(machine, prefs, lang);
130
+ }
131
+ return c.json(view(c, machine, keys));
132
+ })
133
+ // The desktop app's notices, as server-sent events; for this computer only.
134
+ .get('/notify/stream', (c) => {
135
+ if (clientOf(c).kind !== 'local') {
136
+ throw new RejectedRequest(403, 'forbidden', 'Only the desktop app on this computer listens');
137
+ }
138
+ const asked = c.req.query('lang');
139
+ const lang = isNoticeLang(asked) ? asked : 'en';
140
+ return streamSSE(c, async (stream) => {
141
+ const { promise: ended, resolve } = Promise.withResolvers();
142
+ const stop = notifier.listenDesktop((text) => void stream.writeSSE({ event: 'notice', data: JSON.stringify(text) }), lang, resolve);
143
+ stream.onAbort(() => {
144
+ stop();
145
+ resolve();
146
+ });
147
+ await stream.writeSSE({ event: 'ready', data: '' });
148
+ await ended;
149
+ });
150
+ }));
151
+ }
@@ -0,0 +1,124 @@
1
+ import { setCookie } from 'hono/cookie';
2
+ import { encode } from 'uqr';
3
+ import { z } from 'zod';
4
+ import { deviceName, listDevices, pairDevice, repairDevice, revokeDevice, } from '../app/devices.js';
5
+ import { targetOfDevice } from '../app/notify-targets.js';
6
+ import { RejectedRequest } from './errors.js';
7
+ import { formatCode } from './lan.js';
8
+ import { clientOf, deviceCookie } from './session.js';
9
+ import { assertSameOrigin } from './writes.js';
10
+ // Browsers cap a cookie's lifetime at 400 days.
11
+ const DEVICE_COOKIE_MAX_AGE = 400 * 24 * 60 * 60;
12
+ export function pairingUrl(base, code) {
13
+ // The code rides in the fragment, which the browser never sends, logs or passes on as a referrer.
14
+ return `${base}/pair#code=${formatCode(code.code)}`;
15
+ }
16
+ export function qrCode(text) {
17
+ const { size, data } = encode(text, { ecc: 'M', border: 0 });
18
+ return { size, cells: data };
19
+ }
20
+ const hostnameOf = (url) => new URL(url).hostname.replace(/^\[|\]$/g, '');
21
+ // What the desk shows to pair a phone; `pick` is the host the person chose among several.
22
+ export function pairingView(machine, phone, port, pick) {
23
+ const devices = listDevices(machine).map((device) => {
24
+ // A subscription lost on the way (TS-3) keeps its prefs, but nothing reaches the device.
25
+ const target = targetOfDevice(machine, device.id);
26
+ return { ...device, notify: target?.push ? target.prefs : null };
27
+ });
28
+ const { transport } = phone.settings();
29
+ const door = phone.chosen();
30
+ if (!door)
31
+ return { transport, enabled: false, urls: [], code: null, devices };
32
+ const urls = door.urls(port);
33
+ const base = urls.find((url) => hostnameOf(url) === pick?.toLowerCase()) ?? urls[0];
34
+ const current = phone.codes.current();
35
+ const code = current && base
36
+ ? {
37
+ code: formatCode(current.code),
38
+ expiresAt: new Date(current.expiresAt).toISOString(),
39
+ url: pairingUrl(base, current),
40
+ qr: qrCode(pairingUrl(base, current)),
41
+ }
42
+ : null;
43
+ return { transport, enabled: true, urls, code, devices };
44
+ }
45
+ export function assertCanManageDevices(c, auth) {
46
+ if (!auth.canManageDevices(c)) {
47
+ throw new RejectedRequest(403, 'forbidden', 'Only the browser on this computer, signed in with "otea open", manages paired devices');
48
+ }
49
+ }
50
+ // Some door must be open for a phone to pair: the local network's or the chosen transport's.
51
+ export function assertPhoneOn(phone) {
52
+ if (phone.doors().length === 0) {
53
+ throw new RejectedRequest(409, 'phone_off', 'Phone access is off; open the local network in Settings > Phone (or with "otea phone lan --open"), or set up Tailscale with "otea phone tailscale"');
54
+ }
55
+ return phone;
56
+ }
57
+ const CodeBody = z.object({ code: z.string().min(1).max(64) });
58
+ const PairBody = CodeBody.extend({ name: z.string().max(200) });
59
+ async function body(c, schema, expected) {
60
+ assertSameOrigin(c);
61
+ const parsed = schema.safeParse(await c.req.json().catch(() => undefined));
62
+ if (!parsed.success)
63
+ throw new RejectedRequest(400, 'invalid_body', `Expected ${expected}`);
64
+ return parsed.data;
65
+ }
66
+ function attempt(c, phone) {
67
+ const client = clientOf(c);
68
+ const address = client.kind === 'local' ? 'local' : client.address;
69
+ if (!phone.attempts.allow(address)) {
70
+ c.header('retry-after', '60');
71
+ throw new RejectedRequest(429, 'too_many_attempts', 'Too many pairing attempts; wait a minute');
72
+ }
73
+ }
74
+ function refuse(result) {
75
+ if (result === 'expired') {
76
+ throw new RejectedRequest(410, 'code_expired', 'This pairing code expired; show a new one on the desk');
77
+ }
78
+ throw new RejectedRequest(401, 'invalid_code', 'This pairing code is not valid; check it on the desk');
79
+ }
80
+ // The phone reads what it is about to pair with before it asks for a token, and whether it is
81
+ // paired already; the code stays good.
82
+ export async function peekPairing(c, computer, phone) {
83
+ const on = assertPhoneOn(phone);
84
+ const { code } = await body(c, CodeBody, '{"code": string}');
85
+ attempt(c, on);
86
+ const result = on.codes.check(code);
87
+ if (result !== 'ok')
88
+ refuse(result);
89
+ const expiresAt = new Date(on.codes.current()?.expiresAt ?? 0).toISOString();
90
+ // A phone paired already (its token came along): pairing again gives it a new key.
91
+ return { computer, expiresAt, paired: clientOf(c).kind === 'device' };
92
+ }
93
+ // Only tailscale serve brings a phone over HTTPS; the local network is plain HTTP.
94
+ export const viaOf = (secure) => (secure ? 'tailscale' : 'lan');
95
+ export async function pair(c, machine, computer, phone, port) {
96
+ const on = assertPhoneOn(phone);
97
+ const { code, name } = await body(c, PairBody, '{"code": string, "name": string}');
98
+ const named = deviceName(name);
99
+ attempt(c, on);
100
+ const result = on.codes.redeem(code);
101
+ if (result !== 'ok')
102
+ refuse(result);
103
+ const client = clientOf(c);
104
+ // A phone paired already (its token came with the request) scanning a new code stays one device.
105
+ const { device, token } = client.kind === 'device'
106
+ ? repairDevice(machine, client.device.id, named, new Date(), viaOf(client.secure))
107
+ : pairDevice(machine, named, new Date(), client.kind === 'local' ? null : viaOf(client.secure));
108
+ setCookie(c, deviceCookie(port()), token, {
109
+ path: '/',
110
+ httpOnly: true,
111
+ // Lax: the home-screen shortcut, a notification and a link from another app open Otea as a
112
+ // navigation from outside it, which a Strict cookie never comes with, so each of them landed on
113
+ // the pairing screen. A write still needs the UI's own origin (assertSameOrigin).
114
+ sameSite: 'Lax',
115
+ maxAge: DEVICE_COOKIE_MAX_AGE,
116
+ // Over HTTPS (Tailscale) the token never travels in the clear.
117
+ secure: client.kind !== 'local' && client.secure,
118
+ });
119
+ c.header('cache-control', 'no-store');
120
+ return { computer, device };
121
+ }
122
+ export function revoke(machine, id) {
123
+ return revokeDevice(machine, id);
124
+ }
@@ -0,0 +1,191 @@
1
+ import { existsSync, readdirSync, statSync } from 'node:fs';
2
+ import { basename, join, relative } from 'node:path';
3
+ import { listCollectionViews, typeOfItem } from '../app/collections.js';
4
+ import { evidenceDir } from '../app/evidence.js';
5
+ import { repoOfItem } from '../app/gates.js';
6
+ import { forgetProjectPath, keyOf, kindOf, listProjects, openRegistry, relinkProjectPath, withRegistry, } from '../app/home.js';
7
+ import { listItems } from '../app/items.js';
8
+ import { liveBoards } from '../app/next.js';
9
+ import { addPathToProject, databasePath } from '../app/project.js';
10
+ import { identityAt, listRepos, readReposAtFolder, reposInside } from '../app/repos.js';
11
+ import { listTopics } from '../app/topics.js';
12
+ import { CommandFailure } from '../cli/command.js';
13
+ import { hasOteaGitHook, hasOutdatedGitHook, installGitHook } from '../cli/hooks.js';
14
+ import { OteaError } from '../core/errors.js';
15
+ import { stateLabel } from '../core/workflow.js';
16
+ function withIcon(project, item) {
17
+ const type = typeOfItem(project, item);
18
+ const stateName = stateLabel(type.workflow, item.state);
19
+ return type.icon === undefined ? { ...item, stateName } : { ...item, icon: type.icon, stateName };
20
+ }
21
+ function answeredTopics(project) {
22
+ return listTopics(project)
23
+ .filter((topic) => topic.state === 'answered')
24
+ .sort((a, b) => Date.parse(a.updatedAt) - Date.parse(b.updatedAt))
25
+ .map((topic) => ({
26
+ id: topic.id,
27
+ title: topic.title,
28
+ summary: topic.turns.findLast((turn) => turn.kind === 'answer')?.text ?? '',
29
+ ...(topic.agent === undefined ? {} : { agent: topic.agent }),
30
+ updatedAt: topic.updatedAt,
31
+ }));
32
+ }
33
+ // What waits for you is what Te toca lists: your turn, and the work of an agent that went quiet
34
+ // (its lease ran out), yours to restart or reassign (ONB3-5).
35
+ const yours = (item) => item.turn === 'human' || (item.turn === 'agent' && !!item.expiredLease);
36
+ export function countsOf(project) {
37
+ const open = listItems(project).filter((item) => item.turn !== 'none');
38
+ return {
39
+ waiting: open.filter(yours).map((item) => withIcon(project, item)),
40
+ topics: answeredTopics(project),
41
+ withAgents: open.filter((item) => !yours(item)).length,
42
+ open: open.length,
43
+ };
44
+ }
45
+ const NOTHING = { waiting: [], topics: [], withAgents: 0, open: 0 };
46
+ function overviewOf(served, currentId) {
47
+ const { id, name, storage, paths, project } = served;
48
+ const base = { id, name, storage, paths, current: id === currentId };
49
+ if (!project) {
50
+ return { ...base, ...NOTHING, unavailable: served.unavailable ?? `${name} is not available` };
51
+ }
52
+ try {
53
+ return { ...base, ...countsOf(project) };
54
+ }
55
+ catch (error) {
56
+ const unavailable = error instanceof Error ? error.message : String(error);
57
+ return { ...base, ...NOTHING, unavailable };
58
+ }
59
+ }
60
+ // Every project this server serves, by name; `currentId` is the one the page asking is on.
61
+ export function projectOverviews(served, currentId) {
62
+ return served.map((each) => overviewOf(each, currentId));
63
+ }
64
+ function sizeOf(path) {
65
+ if (!existsSync(path))
66
+ return { bytes: 0, files: 0 };
67
+ const stat = statSync(path);
68
+ if (!stat.isDirectory())
69
+ return { bytes: stat.size, files: 1 };
70
+ return readdirSync(path).reduce((sum, entry) => {
71
+ const inner = sizeOf(join(path, entry));
72
+ return { bytes: sum.bytes + inner.bytes, files: sum.files + inner.files };
73
+ }, { bytes: 0, files: 0 });
74
+ }
75
+ function repoOf(path, parent, { itemRepos, known }) {
76
+ const identity = identityAt(path);
77
+ const name = known.find((repo) => repo.identity === identity)?.name ?? basename(path);
78
+ return {
79
+ name,
80
+ folder: relative(parent, path).replaceAll('\\', '/') || '.',
81
+ gate: hasOteaGitHook(path) ? 'hard' : 'soft',
82
+ items: itemRepos.filter((repo) => repo === name).length,
83
+ remote: identity?.startsWith('remote:') ?? false,
84
+ ...(hasOutdatedGitHook(path) ? { hookOutdated: true } : {}),
85
+ };
86
+ }
87
+ // The repos a path holds: itself when it is a linked repo, the ones inside a linked folder.
88
+ function reposAt(path) {
89
+ if (path.missing)
90
+ return [];
91
+ return path.kind === 'repo' ? [path.path] : reposInside(path.path);
92
+ }
93
+ function pathSettings(path, names) {
94
+ return { ...path, repos: reposAt(path).map((repo) => repoOf(repo, path.path, names)) };
95
+ }
96
+ // Parent folders first, then linked repos, and the missing ones last.
97
+ const byPlace = (a, b) => Number(a.missing) - Number(b.missing) || Number(a.kind === 'repo') - Number(b.kind === 'repo');
98
+ // The paths the project links, as the registry has them; a local project's one folder.
99
+ function projectPaths(project, env) {
100
+ const { identity, root } = project;
101
+ const listed = withRegistry(env, listProjects)?.find((each) => each.id === identity.id);
102
+ return listed?.paths ?? [{ path: root, kind: kindOf(root), missing: false }];
103
+ }
104
+ export function projectSettings(project, env = process.env) {
105
+ const { identity, storage, root, dataDir } = project;
106
+ const listed = withRegistry(env, listProjects)?.find((each) => each.id === identity.id);
107
+ const paths = projectPaths(project, env);
108
+ const items = listItems(project);
109
+ const boards = liveBoards(project);
110
+ const itemRepos = items.map((item) => repoOfItem(project, item, boards));
111
+ const names = { itemRepos, known: listRepos(project, env) };
112
+ const database = databasePath(dataDir);
113
+ const evidence = evidenceDir(dataDir);
114
+ return {
115
+ ...identity,
116
+ storage,
117
+ root,
118
+ dataDir,
119
+ registered: listed !== undefined,
120
+ database: { path: database, bytes: sizeOf(database).bytes + sizeOf(`${database}-wal`).bytes },
121
+ evidence: { path: evidence, ...sizeOf(evidence) },
122
+ items: items.length,
123
+ collections: listCollectionViews(project).map(({ name, preset }) => ({ name, preset })),
124
+ paths: [...paths].sort(byPlace).map((path) => pathSettings(path, names)),
125
+ };
126
+ }
127
+ function inRegistry(env, use) {
128
+ const registry = openRegistry(env);
129
+ try {
130
+ return use(registry);
131
+ }
132
+ finally {
133
+ registry.close();
134
+ }
135
+ }
136
+ // A path this project links, or an error: the settings of one project never touch another's.
137
+ function ownPath(registry, project, path) {
138
+ const key = keyOf(path).pathKey;
139
+ const own = listProjects(registry)
140
+ .find((each) => each.id === project.identity.id)
141
+ ?.paths.some((linked) => keyOf(linked.path).pathKey === key);
142
+ if (!own)
143
+ throw new OteaError('not_found', `${path} is not a path of ${project.identity.name}`);
144
+ }
145
+ // Links another folder to this project; a local project has no registry entry to link it to.
146
+ export function addPath(project, path, env = process.env) {
147
+ if (project.storage === 'local') {
148
+ throw new OteaError('forbidden', 'A local project has one folder; run otea migrate first');
149
+ }
150
+ const linked = addPathToProject(path, project.identity.id, env);
151
+ readReposAtFolder(project, linked.path, env);
152
+ return { path: linked.path, kind: linked.kind, missing: false };
153
+ }
154
+ export function relinkPath(project, from, to, force, env = process.env) {
155
+ return inRegistry(env, (registry) => {
156
+ ownPath(registry, project, from);
157
+ const { link, match } = relinkProjectPath(registry, from, to, force);
158
+ return { path: link.path, kind: link.kind, missing: false, match };
159
+ });
160
+ }
161
+ export function forgetPath(project, path, env = process.env) {
162
+ return inRegistry(env, (registry) => {
163
+ ownPath(registry, project, path);
164
+ const { link, remaining } = forgetProjectPath(registry, path);
165
+ return { path: link.path, remaining };
166
+ });
167
+ }
168
+ // Writes Otea's pre-push hook into every repo of the project that has none, so a push the boards
169
+ // refuse is refused by git too (P2S-R3-1); a repo that has it already is left as it is. `otea` is
170
+ // how the hook runs this Otea again, as otea hook install --git writes it.
171
+ export function installGitHooks(project, otea, env = process.env) {
172
+ const repos = [...new Set(projectPaths(project, env).flatMap(reposAt))];
173
+ const known = listRepos(project, env);
174
+ const nameOf = (path) => {
175
+ const identity = identityAt(path);
176
+ return known.find((repo) => repo.identity === identity)?.name ?? basename(path);
177
+ };
178
+ const result = { installed: [], refused: [] };
179
+ for (const repo of repos.filter((path) => !hasOteaGitHook(path))) {
180
+ try {
181
+ const change = installGitHook(repo, otea);
182
+ result.installed.push({ repo: nameOf(repo), path: change.path });
183
+ }
184
+ catch (error) {
185
+ if (!(error instanceof CommandFailure))
186
+ throw error;
187
+ result.refused.push({ repo: nameOf(repo), message: error.message });
188
+ }
189
+ }
190
+ return result;
191
+ }
@@ -0,0 +1,199 @@
1
+ import { createCipheriv, createECDH, createPrivateKey, hkdfSync, randomBytes, sign, } from 'node:crypto';
2
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { restrictToOwner } from '../app/owner-only.js';
5
+ const DETAIL_MAX = 200;
6
+ // What a push service or the network said, safe to log and show: one line, at most 200 characters,
7
+ // and no URL (an error may name the subscription's endpoint, which opens a push to that browser).
8
+ export function pushDetail(text) {
9
+ const plain = text
10
+ .replace(/https?:\/\/\S+/g, '…')
11
+ .replace(/\s+/g, ' ')
12
+ .trim();
13
+ return plain.length > DETAIL_MAX ? `${plain.slice(0, DETAIL_MAX - 1)}…` : plain;
14
+ }
15
+ function networkDetail(error) {
16
+ if (!(error instanceof Error))
17
+ return 'unknown error';
18
+ const code = error.cause?.code;
19
+ return pushDetail(typeof code === 'string' ? `${error.message} (${code})` : error.message);
20
+ }
21
+ export const PUSH_KEYS_FILE = 'push-keys.json';
22
+ // Who to reach about this sender, which push services ask for: the project's home, never a person.
23
+ const SUBJECT = 'https://github.com/otea-dev/otea';
24
+ // A notice that waits a day at the push service is not news any more.
25
+ const TTL_SECONDS = 24 * 60 * 60;
26
+ const CLAIM_SECONDS = 12 * 60 * 60;
27
+ const RECORD_SIZE = 4096;
28
+ const SEND_TIMEOUT_MS = 10_000;
29
+ const b64 = (text) => Buffer.from(text, 'base64url');
30
+ const SCALAR_BYTES = 32;
31
+ // node's ECDH drops a private scalar's leading zero bytes (about one key in 256 starts with one):
32
+ // the scalar is always written at its full width.
33
+ const fullScalar = (scalar) => Buffer.concat([Buffer.alloc(Math.max(0, SCALAR_BYTES - scalar.length)), scalar]);
34
+ // `privateKey` makes the pair from a known scalar, for tests.
35
+ export function generateVapidKeys(privateKey) {
36
+ const ecdh = createECDH('prime256v1');
37
+ if (privateKey)
38
+ ecdh.setPrivateKey(privateKey);
39
+ else
40
+ ecdh.generateKeys();
41
+ return {
42
+ publicKey: ecdh.getPublicKey().toString('base64url'),
43
+ privateKey: fullScalar(ecdh.getPrivateKey()).toString('base64url'),
44
+ };
45
+ }
46
+ // A kept file whose private key was saved short (before it was padded) still holds a good key:
47
+ // read it padded, so the phones subscribed to it keep working.
48
+ const readKeys = (value) => {
49
+ const keys = value;
50
+ if (typeof keys?.publicKey !== 'string' || typeof keys.privateKey !== 'string')
51
+ return undefined;
52
+ const scalar = b64(keys.privateKey);
53
+ if (b64(keys.publicKey).length !== 65 || scalar.length === 0 || scalar.length > SCALAR_BYTES) {
54
+ return undefined;
55
+ }
56
+ return { publicKey: keys.publicKey, privateKey: fullScalar(scalar).toString('base64url') };
57
+ };
58
+ // `restrict` keeps a new key file to its owner where the mode does not (Windows); `warn` says when
59
+ // it could not.
60
+ export function ensureVapidKeys(dir, { warn, restrict = (path) => restrictToOwner(path, warn ? { warn } : {}), } = {}) {
61
+ const path = join(dir, PUSH_KEYS_FILE);
62
+ if (existsSync(path)) {
63
+ try {
64
+ const kept = readKeys(JSON.parse(readFileSync(path, 'utf8')));
65
+ if (kept)
66
+ return kept;
67
+ }
68
+ catch {
69
+ // unreadable: made again below, and phones subscribe again
70
+ }
71
+ }
72
+ const keys = generateVapidKeys();
73
+ writeFileSync(path, `${JSON.stringify(keys)}\n`, { mode: 0o600 });
74
+ try {
75
+ chmodSync(path, 0o600);
76
+ }
77
+ catch {
78
+ // best effort: some file systems ignore permissions
79
+ }
80
+ restrict(path);
81
+ return keys;
82
+ }
83
+ // The push services of the browsers that run Otea's installed app. A subscription names one of
84
+ // them; the server posts nowhere else, so a paired device cannot point it at the local network.
85
+ const PUSH_HOSTS = [
86
+ 'fcm.googleapis.com',
87
+ 'android.googleapis.com',
88
+ 'updates.push.services.mozilla.com',
89
+ 'push.services.mozilla.com',
90
+ 'push.apple.com',
91
+ 'notify.windows.com',
92
+ ];
93
+ export function isPushEndpoint(text) {
94
+ let url;
95
+ try {
96
+ url = new URL(text);
97
+ }
98
+ catch {
99
+ return false;
100
+ }
101
+ if (url.protocol !== 'https:' || url.port !== '' || url.username || url.password)
102
+ return false;
103
+ const host = url.hostname.toLowerCase();
104
+ return PUSH_HOSTS.some((known) => host === known || host.endsWith(`.${known}`));
105
+ }
106
+ // The aes128gcm body: salt, record size, the sender's one-time public key, then one record.
107
+ export function encryptPayload(plaintext, subscription, fixed = {}) {
108
+ const uaPublic = b64(subscription.p256dh);
109
+ const authSecret = b64(subscription.auth);
110
+ const ecdh = createECDH('prime256v1');
111
+ if (fixed.sender)
112
+ ecdh.setPrivateKey(fixed.sender.privateKey);
113
+ else
114
+ ecdh.generateKeys();
115
+ const asPublic = ecdh.getPublicKey();
116
+ const shared = ecdh.computeSecret(uaPublic);
117
+ const salt = fixed.salt ?? randomBytes(16);
118
+ const keyInfo = Buffer.concat([Buffer.from('WebPush: info\0'), uaPublic, asPublic]);
119
+ const ikm = Buffer.from(hkdfSync('sha256', shared, authSecret, keyInfo, 32));
120
+ const cek = Buffer.from(hkdfSync('sha256', ikm, salt, 'Content-Encoding: aes128gcm\0', 16));
121
+ const nonce = Buffer.from(hkdfSync('sha256', ikm, salt, 'Content-Encoding: nonce\0', 12));
122
+ const cipher = createCipheriv('aes-128-gcm', cek, nonce);
123
+ // One record, the last: the payload and its delimiter (2).
124
+ const record = Buffer.concat([
125
+ cipher.update(Buffer.concat([plaintext, Buffer.from([2])])),
126
+ cipher.final(),
127
+ cipher.getAuthTag(),
128
+ ]);
129
+ const header = Buffer.alloc(21);
130
+ salt.copy(header, 0);
131
+ header.writeUInt32BE(RECORD_SIZE, 16);
132
+ header.writeUInt8(asPublic.length, 20);
133
+ return Buffer.concat([header, asPublic, record]);
134
+ }
135
+ function signingKey(keys) {
136
+ const point = b64(keys.publicKey);
137
+ return createPrivateKey({
138
+ key: {
139
+ kty: 'EC',
140
+ crv: 'P-256',
141
+ d: keys.privateKey,
142
+ x: point.subarray(1, 33).toString('base64url'),
143
+ y: point.subarray(33).toString('base64url'),
144
+ },
145
+ format: 'jwk',
146
+ });
147
+ }
148
+ const json64 = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
149
+ export function vapidAuthorization(endpoint, keys, now) {
150
+ const head = json64({ typ: 'JWT', alg: 'ES256' });
151
+ const claims = json64({
152
+ aud: new URL(endpoint).origin,
153
+ exp: Math.floor(now / 1000) + CLAIM_SECONDS,
154
+ sub: SUBJECT,
155
+ });
156
+ const signature = sign('sha256', Buffer.from(`${head}.${claims}`), {
157
+ key: signingKey(keys),
158
+ dsaEncoding: 'ieee-p1363',
159
+ });
160
+ return `vapid t=${head}.${claims}.${signature.toString('base64url')}, k=${keys.publicKey}`;
161
+ }
162
+ export function webPushSender(keys, options = {}) {
163
+ const post = options.fetch ?? ((url, init) => fetch(url, init));
164
+ const now = options.now ?? Date.now;
165
+ return {
166
+ async send(subscription, payload) {
167
+ // Not a push service: a subscription that can never be delivered to.
168
+ if (!isPushEndpoint(subscription.endpoint)) {
169
+ return { result: 'gone', status: null, detail: 'not a push service' };
170
+ }
171
+ try {
172
+ const body = encryptPayload(Buffer.from(payload, 'utf8'), subscription);
173
+ const response = await post(subscription.endpoint, {
174
+ method: 'POST',
175
+ headers: {
176
+ authorization: vapidAuthorization(subscription.endpoint, keys, now()),
177
+ 'content-encoding': 'aes128gcm',
178
+ 'content-type': 'application/octet-stream',
179
+ ttl: String(TTL_SECONDS),
180
+ urgency: 'normal',
181
+ },
182
+ body: new Uint8Array(body),
183
+ redirect: 'error',
184
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
185
+ });
186
+ const { status } = response;
187
+ if (response.ok)
188
+ return { result: 'sent', status, detail: '' };
189
+ const said = pushDetail(await response.text().catch(() => ''));
190
+ // The browser unsubscribed, or the subscription expired: never again.
191
+ const result = status === 404 || status === 410 ? 'gone' : 'failed';
192
+ return { result, status, detail: said };
193
+ }
194
+ catch (error) {
195
+ return { result: 'failed', status: null, detail: networkDetail(error) };
196
+ }
197
+ },
198
+ };
199
+ }