townmouse 0.0.0-stage → 0.4.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 (108) hide show
  1. package/CHANGELOG.md +196 -0
  2. package/DESIGN.md +153 -0
  3. package/LICENSE +661 -0
  4. package/README.md +600 -2
  5. package/SECURITY.md +60 -0
  6. package/TOWNMOUSE.md +91 -0
  7. package/assets/brand/mascot/README.md +23 -0
  8. package/assets/brand/mascot/townmouse-aristocrat.png +0 -0
  9. package/assets/brand/mascot/townmouse-icon.svg +1 -0
  10. package/assets/brand/mascot/townmouse-monocled.png +0 -0
  11. package/bin/townmouse +68 -0
  12. package/docs/PACKAGING.md +371 -0
  13. package/docs/browser-workspace.md +237 -0
  14. package/docs/panes.md +442 -0
  15. package/native/TownmouseApp.swift +108 -0
  16. package/npm-shrinkwrap.json +1282 -0
  17. package/package.json +93 -4
  18. package/public/apple-touch-icon.png +0 -0
  19. package/public/brand/floydslabs-credit.png +0 -0
  20. package/public/brand/floydslabs-credit.webp +0 -0
  21. package/public/brand/townmouse-aristocrat.webp +0 -0
  22. package/public/brand/townmouse-monocled.webp +0 -0
  23. package/public/browser-picture.mjs +159 -0
  24. package/public/clipboard-text.mjs +5 -0
  25. package/public/favicon-16x16.png +0 -0
  26. package/public/favicon-32x32.png +0 -0
  27. package/public/favicon.ico +0 -0
  28. package/public/favicon.svg +1 -0
  29. package/public/features/app-version.mjs +35 -0
  30. package/public/features/autosave.mjs +80 -0
  31. package/public/features/clipboard.mjs +69 -0
  32. package/public/features/command-palette.mjs +181 -0
  33. package/public/features/desktop-palette.mjs +19 -0
  34. package/public/features/export.mjs +37 -0
  35. package/public/features/file-drop.mjs +77 -0
  36. package/public/features/floating-palette.mjs +113 -0
  37. package/public/features/fontsize.mjs +72 -0
  38. package/public/features/haptic-keys.mjs +42 -0
  39. package/public/features/history-undo.mjs +102 -0
  40. package/public/features/keepalive.mjs +36 -0
  41. package/public/features/keybar-config.mjs +70 -0
  42. package/public/features/keyboard-shortcuts.mjs +74 -0
  43. package/public/features/links.mjs +139 -0
  44. package/public/features/multi-window-sync.mjs +76 -0
  45. package/public/features/osc-bridge.mjs +64 -0
  46. package/public/features/phone-landscape-focus.mjs +157 -0
  47. package/public/features/recent-commands.mjs +100 -0
  48. package/public/features/search.mjs +134 -0
  49. package/public/features/session-lock.mjs +96 -0
  50. package/public/features/session-manager.mjs +251 -0
  51. package/public/features/settings-sync.mjs +77 -0
  52. package/public/features/shortcut-help.mjs +85 -0
  53. package/public/features/smart-completions.mjs +101 -0
  54. package/public/features/smart-suggest.mjs +124 -0
  55. package/public/features/snippets.mjs +85 -0
  56. package/public/features/split-view.mjs +102 -0
  57. package/public/features/status-metrics.mjs +137 -0
  58. package/public/features/stylus-support.mjs +124 -0
  59. package/public/features/swipe-history.mjs +141 -0
  60. package/public/features/swipe-sessions.mjs +85 -0
  61. package/public/features/tab-reorder.mjs +70 -0
  62. package/public/features/theme-system.mjs +51 -0
  63. package/public/features/toast-status.mjs +118 -0
  64. package/public/features/two-finger-menu.mjs +87 -0
  65. package/public/features/voice-input.mjs +244 -0
  66. package/public/features/wake-fullscreen.mjs +67 -0
  67. package/public/features/window-title.mjs +47 -0
  68. package/public/features/zoom.mjs +80 -0
  69. package/public/icon-128.png +0 -0
  70. package/public/icon-180.png +0 -0
  71. package/public/icon-192.png +0 -0
  72. package/public/icon-48.png +0 -0
  73. package/public/icon-512-maskable.png +0 -0
  74. package/public/icon-512.png +0 -0
  75. package/public/icon.svg +1 -0
  76. package/public/index.html +2304 -0
  77. package/public/input-chunks.mjs +22 -0
  78. package/public/input-guard.mjs +218 -0
  79. package/public/manifest.json +56 -0
  80. package/public/panes.css +1433 -0
  81. package/public/panes.html +211 -0
  82. package/public/panes.mjs +3183 -0
  83. package/public/service-worker.js +67 -0
  84. package/public/workspace.css +1621 -0
  85. package/public/workspace.mjs +1715 -0
  86. package/scripts/install-service.sh +303 -0
  87. package/scripts/node-runtime.sh +138 -0
  88. package/scripts/panes +568 -0
  89. package/scripts/prepare-native.sh +35 -0
  90. package/scripts/retire-legacy-service.sh +76 -0
  91. package/scripts/run-hooks +69 -0
  92. package/scripts/townmouse.sh +152 -0
  93. package/scripts/uninstall-service.sh +65 -0
  94. package/src/agent-guide.js +329 -0
  95. package/src/attachments.js +128 -0
  96. package/src/browser-dom.js +548 -0
  97. package/src/browser-workspace.js +1733 -0
  98. package/src/chrome-resolve.js +80 -0
  99. package/src/owner-page.js +43 -0
  100. package/src/pty-permissions.js +99 -0
  101. package/src/regex-worker.js +13 -0
  102. package/src/replay-text.js +189 -0
  103. package/src/request-boundary.js +58 -0
  104. package/src/safe-regex.js +87 -0
  105. package/src/server.js +1582 -0
  106. package/src/shell-resolve.js +42 -0
  107. package/src/static-deps.js +61 -0
  108. package/src/workspace-panes.js +1431 -0
@@ -0,0 +1,329 @@
1
+ 'use strict';
2
+
3
+ // The instruction sheet an agent receives when it connects to TownMouse.
4
+ //
5
+ // It describes the tools that exist and the permissions of the specific token
6
+ // that is asking. It never grants a capability: the caller already holds one,
7
+ // and the same endpoint is served to any holder of a pane token. Every claim
8
+ // here is checked against the routes in src/workspace-panes.js and
9
+ // scripts/panes — the guide is documentation, not an authorization layer.
10
+
11
+ const TOOLS = [
12
+ {
13
+ name: 'state',
14
+ cli: 'panes state',
15
+ purpose: 'Read the workspace: tabs, panes, limits, and each pane\'s program status, agent-reported status, and recent command jobs.',
16
+ needs: 'nothing',
17
+ returns: 'Host name, tabs with panes, active tab/pane, limits.'
18
+ },
19
+ {
20
+ name: 'tab.create',
21
+ cli: 'panes tab create --title TEXT [--activate]',
22
+ purpose: 'Create a background workspace tab. It is not activated unless you ask, so the owner\'s view does not move.',
23
+ needs: 'optional title; optional --activate',
24
+ returns: 'The new tab.'
25
+ },
26
+ {
27
+ name: 'tab.close',
28
+ cli: 'panes tab close <tab-id>',
29
+ purpose: 'Close a tab and every pane in it.',
30
+ needs: 'tab id'
31
+ },
32
+ {
33
+ name: 'pane.create',
34
+ cli: 'panes pane create --tab <tab-id> --kind terminal|browser [--url URL] [--cwd PATH] [--title TEXT]',
35
+ purpose: 'Add a terminal or browser pane to a tab. A tab holds at most four panes; a fifth is refused with an explanation.',
36
+ needs: 'tab id, kind; optional url/cwd/title'
37
+ },
38
+ {
39
+ name: 'pane.exec',
40
+ cli: 'panes pane exec <pane-id> -- <command> [--wait-ms N]',
41
+ purpose: 'Run one non-interactive command in the pane\'s working directory as a tracked job. Returns a job id, exit code, stdout and stderr. Use this when you need to know whether a command finished.',
42
+ needs: 'pane id, command',
43
+ returns: 'Job id, status (running|completed|failed), exitCode, stdout, stderr, truncation flags.'
44
+ },
45
+ {
46
+ name: 'pane.job',
47
+ cli: 'panes pane job <pane-id> <job-id>',
48
+ purpose: 'Re-read a tracked job: still running, finished, its exit code, and its output so far.',
49
+ needs: 'pane id and job id'
50
+ },
51
+ {
52
+ name: 'pane.run',
53
+ cli: 'panes pane run <pane-id> <command...>',
54
+ purpose: 'Type a line into the interactive terminal and return recent output. This does not prove the command finished; use pane.exec for that.',
55
+ needs: 'pane id, command text'
56
+ },
57
+ {
58
+ name: 'pane.input',
59
+ cli: 'panes pane input <pane-id> <text...>',
60
+ purpose: 'Send raw text to the interactive terminal without a trailing newline.',
61
+ needs: 'pane id, text'
62
+ },
63
+ {
64
+ name: 'pane.keys',
65
+ cli: 'panes pane keys <pane-id> <key...>',
66
+ purpose: 'Press terminal keys, including modifiers: enter, esc, tab, ctrl+c, alt+x, up/down/left/right.',
67
+ needs: 'pane id, one or more key names'
68
+ },
69
+ {
70
+ name: 'pane.read',
71
+ cli: 'panes pane read <pane-id> [--lines N] [--raw]',
72
+ purpose: 'Read terminal output. Default is clean screen text; --raw returns the original escape sequences.',
73
+ needs: 'pane id; optional line count'
74
+ },
75
+ {
76
+ name: 'pane.wait',
77
+ cli: 'panes pane wait <pane-id> [--match TEXT | --regex PATTERN | --idle MS | --state STATE] [--timeout MS]',
78
+ purpose: 'Wait for a specific terminal condition, bounded by a timeout. Returns matched:true/false and why it stopped.',
79
+ needs: 'pane id and at least one of match/regex/idle/state'
80
+ },
81
+ {
82
+ name: 'pane.status',
83
+ cli: 'panes pane status <pane-id> --state working|blocked|idle|done|unknown [--message TEXT]',
84
+ purpose: 'Report your own status for a terminal pane. This is the agent-reported status, separate from whether the program is running.',
85
+ needs: 'pane id, state'
86
+ },
87
+ {
88
+ name: 'pane.request',
89
+ cli: 'panes pane request <pane-id> --level view|control [--message TEXT] [--timeout MS] [--no-wait]',
90
+ purpose: 'Ask the owner for access to one of the owner\'s panes. The ask appears on that pane, with your message, and the command waits for the answer. Use it when a refusal says the pane is Private or View only.',
91
+ needs: 'pane id, and the level you need',
92
+ returns: 'granted, declined, withdrawn, or still waiting when the timeout passes'
93
+ },
94
+ {
95
+ name: 'browser.observe',
96
+ cli: 'panes pane browser observe <pane-id> [--elements] [--max N]',
97
+ purpose: 'Take a fresh screenshot with an observation label, and optionally a catalog of the controls on the page.',
98
+ needs: 'browser pane id',
99
+ returns: 'Observation id, capture time, viewport size, scroll offset, address, title, and (with --elements) controls with refs.'
100
+ },
101
+ {
102
+ name: 'browser.elements',
103
+ cli: 'panes pane browser elements <pane-id> [--max N]',
104
+ purpose: 'Catalog controls by identity: role, name, value, state, box, and a ref you can act on. Works inside nested frames and open shadow roots.',
105
+ needs: 'browser pane id'
106
+ },
107
+ {
108
+ name: 'browser.click',
109
+ cli: 'panes pane browser click <pane-id> (--ref e12 | --x N --y N [--observation N])',
110
+ purpose: 'Click a control by ref (preferred) or by coordinate from a named observation. A coordinate from a stale observation is refused.',
111
+ needs: 'browser pane id and ref, or x/y with the observation they came from'
112
+ },
113
+ {
114
+ name: 'browser.type',
115
+ cli: 'panes pane browser type <pane-id> <text...> [--ref e12] [--replace]',
116
+ purpose: 'Type text, optionally into a specific control. --replace selects the existing content first instead of appending.',
117
+ needs: 'browser pane id, text; optional ref'
118
+ },
119
+ {
120
+ name: 'browser.key',
121
+ cli: 'panes pane browser key <pane-id> <key...>',
122
+ purpose: 'Press browser keys, including combinations such as Alt+M, Control+Shift+Tab.',
123
+ needs: 'browser pane id, key names'
124
+ },
125
+ {
126
+ name: 'browser.hover',
127
+ cli: 'panes pane browser hover <pane-id> (--ref e12 | --x N --y N)',
128
+ purpose: 'Move the pointer over a target without clicking.',
129
+ needs: 'browser pane id and ref or coordinates'
130
+ },
131
+ {
132
+ name: 'browser.drag',
133
+ cli: 'panes pane browser drag <pane-id> --from-ref e12 --to-ref e15',
134
+ purpose: 'Drag from one target to another inside the agent browser.',
135
+ needs: 'browser pane id and two targets'
136
+ },
137
+ {
138
+ name: 'browser.scroll',
139
+ cli: 'panes pane browser scroll <pane-id> [--ref e12 | --selector CSS] [--dy N] [--dx N]',
140
+ purpose: 'Scroll a named area. Without a target it scrolls the page; with one it scrolls that element\'s own scroll box.',
141
+ needs: 'browser pane id; optional target and deltas'
142
+ },
143
+ {
144
+ name: 'browser.select',
145
+ cli: 'panes pane browser select <pane-id> --ref e12 --value V',
146
+ purpose: 'Set the value of a select or input by ref.',
147
+ needs: 'browser pane id, ref, value'
148
+ },
149
+ {
150
+ name: 'browser.navigate',
151
+ cli: 'panes pane browser navigate <pane-id> <url>',
152
+ purpose: 'Open an http(s) address. The reply carries the new address and the new title.',
153
+ needs: 'browser pane id, URL'
154
+ },
155
+ {
156
+ name: 'browser.wait',
157
+ cli: 'panes pane browser wait <pane-id> [--url URL | --text TEXT | --selector CSS | --value TEXT --ref e12] [--timeout MS]',
158
+ purpose: 'Wait until the page reaches a condition, bounded by a timeout. Prefer this over sleeping.',
159
+ needs: 'browser pane id, one condition, optional timeout'
160
+ },
161
+ {
162
+ name: 'browser.text',
163
+ cli: 'panes pane browser text <pane-id>',
164
+ purpose: 'Read the page text, with an explicit flag when it was cut short.',
165
+ needs: 'browser pane id'
166
+ },
167
+ {
168
+ name: 'browser.dialog',
169
+ cli: 'panes pane dialog <pane-id> --accept|--dismiss [--text VALUE]',
170
+ purpose: 'Answer a page dialog that is waiting.',
171
+ needs: 'browser pane id and an action'
172
+ },
173
+ {
174
+ name: 'browser.sizing',
175
+ cli: 'panes pane browser sizing <pane-id> fit|fixed [--width N] [--height N]',
176
+ purpose: 'Choose whether the page resizes with the human viewer (fit) or keeps a fixed size (fixed), so the owner\'s window never rearranges it.',
177
+ needs: 'browser pane id and mode'
178
+ },
179
+ {
180
+ name: 'attach',
181
+ cli: 'panes attach <file> [--pane <pane-id>] [--type MIME]',
182
+ purpose: 'Upload a file to the workspace and optionally insert its path into a terminal pane.',
183
+ needs: 'file path'
184
+ },
185
+ {
186
+ name: 'session.list',
187
+ cli: 'panes session list',
188
+ purpose: 'List the shells agents started, as they stand in the owner\'s terminal row: each one\'s id, name, folder, how many windows are viewing it, and whether the owner is viewing it. The owner\'s own shells are not listed; ownerStarted says how many there are, and max is the limit. A session is named by its name, its id, or the start of its id.',
189
+ needs: 'nothing',
190
+ returns: 'The agent-started sessions, ownerStarted, the limit, and which session the owner is viewing when it is one of them.'
191
+ },
192
+ {
193
+ name: 'session.create',
194
+ cli: 'panes session create [--name TEXT] [--cwd PATH] [--activate]',
195
+ purpose: 'Start a shell nobody is viewing yet. It is an agent\'s shell from the moment it starts, whatever the request says. It appears in the owner\'s row and does not change which shell the owner is looking at unless you pass --activate. At most ten shells run at once; a refused create says so, and says when none of them is one an agent may close.',
196
+ needs: 'optional name, folder; optional --activate',
197
+ returns: 'The new session.'
198
+ },
199
+ {
200
+ name: 'session.rename',
201
+ cli: 'panes session rename <session> --name TEXT',
202
+ purpose: 'Give a shell an agent started a name the owner can read. On a shell the owner started it is refused with OWNER_ONLY. Names are unique and at most 40 characters.',
203
+ needs: 'one of the agent-started sessions, new name'
204
+ },
205
+ {
206
+ name: 'session.activate',
207
+ cli: 'panes session activate <session>',
208
+ purpose: 'Ask the owner\'s open Townmouse windows to show a shell an agent started. This moves the owner\'s view; use it only when they asked to see it. On a shell the owner started it is refused with OWNER_ONLY.',
209
+ needs: 'one of the agent-started sessions'
210
+ },
211
+ {
212
+ name: 'session.close',
213
+ cli: 'panes session close <session>',
214
+ purpose: 'End a shell an agent started, and anything still running in it. It cannot be undone. A window that was viewing it moves to another shell and says so. On a shell the owner started it is refused with OWNER_ONLY.',
215
+ needs: 'one of the agent-started sessions'
216
+ }
217
+ ];
218
+
219
+ const CAPABILITIES = [
220
+ {
221
+ id: 'workspace',
222
+ granted: true,
223
+ summary: 'Use the workspace through the scoped pane token you already hold: create tabs, and open panes of your own. A pane an agent opened is every agent\'s to read and drive, including the Orchestrator pane.'
224
+ },
225
+ {
226
+ id: 'owner.panes',
227
+ granted: false,
228
+ summary: 'See, read or drive a pane the owner opened. Each is Private until the owner gives View only (read) or Allow control (read and drive); a Private pane appears in state as an empty shape. Every pane\'s state says what you have on it under agentAccess, and a refusal names the level and the pane.request command to ask for more.'
229
+ },
230
+ {
231
+ id: 'owner.surface',
232
+ granted: false,
233
+ summary: 'Close, resize, move or bring forward one of the owner\'s panes, or close a tab that holds one. These are the owner\'s whatever you were given on the pane.'
234
+ },
235
+ {
236
+ id: 'browser.control',
237
+ granted: true,
238
+ summary: 'Drive browser panes you create or that the owner has given Allow control on.'
239
+ },
240
+ {
241
+ id: 'browser.sharing',
242
+ granted: false,
243
+ summary: 'Change a pane\'s agent access, or answer an ask. Only the owner page can do this; an agent token is refused.'
244
+ },
245
+ {
246
+ id: 'page.passwords',
247
+ granted: false,
248
+ summary: 'Read a password field\'s value. A catalog, an action\'s result and its focused-element report all return null with redacted: true for one, and it cannot be waited on. Typing into the field still works.'
249
+ },
250
+ {
251
+ id: 'owner.page',
252
+ granted: false,
253
+ summary: 'Read or bootstrap the owner workspace token. An Authorization header is refused at the bootstrap routes.'
254
+ },
255
+ {
256
+ id: 'shell-sessions',
257
+ granted: true,
258
+ summary: 'Start shells in the owner\'s terminal row, and list, name, show and close the shells agents started. A shell keeps running, with or without a viewer, until it is closed or the app stops; at most ten run at once.'
259
+ },
260
+ {
261
+ id: 'owner.shells',
262
+ granted: false,
263
+ summary: 'Rename, show or close a shell the owner started, or see the owner\'s shells. session list holds the shells agents started and counts the rest as ownerStarted; a rename, show or close of one of the owner\'s is refused with OWNER_ONLY.'
264
+ },
265
+ {
266
+ id: 'workspace.limits',
267
+ granted: true,
268
+ summary: 'Limits are enforced and unchanged: at most four panes per tab, 24 tabs, 24 terminal panes, 32 browser tabs.'
269
+ }
270
+ ];
271
+
272
+ function buildGuide(options = {}) {
273
+ const cli = options.cli || { available: false };
274
+ const lines = [];
275
+ lines.push('TownMouse agent guide');
276
+ lines.push('');
277
+ lines.push('You are connected to a TownMouse workspace through a scoped agent token.');
278
+ lines.push('This sheet tells you what you may do. It does not add permissions you were not granted.');
279
+ lines.push('');
280
+ lines.push('## Two ways to work');
281
+ lines.push('');
282
+ if (cli.available) {
283
+ lines.push(`The native command-line tool is available in your terminal panes: ${cli.path || 'panes'}`);
284
+ lines.push('It already holds the workspace token, so never copy or paste a token yourself.');
285
+ lines.push('You can also call the HTTP API directly with the TOWNMOUSE_TOKEN environment variable.');
286
+ } else {
287
+ lines.push('The native command-line tool is not on PATH here. Call the HTTP API with TOWNMOUSE_API and TOWNMOUSE_TOKEN from the environment.');
288
+ }
289
+ lines.push('');
290
+ lines.push('## Ground rules');
291
+ lines.push('- Never activate or switch the owner\'s visible tab unless they asked you to.');
292
+ lines.push('- A pane the owner opened is the owner\'s. `panes state` says what you have on every pane (agentAccess); when it is not enough, ask with pane.request instead of working around it.');
293
+ lines.push('- To show the owner one of your own panes, report it with pane status and bring that pane forward with panes active.');
294
+ lines.push('- A password field takes your typing and never gives a value back. Do not look for one; wait on a selector or on page text.');
295
+ lines.push('- A shell you start keeps running after you stop looking. Close the shells you start when the owner is done with them.');
296
+ lines.push('- A shell the owner started is the owner\'s: an agent cannot rename, show or close it, whatever else it has been given.');
297
+ lines.push('- Prefer element refs from a fresh observation over coordinates.');
298
+ lines.push('- A coordinate is only valid for the observation it came from; a stale one is refused.');
299
+ lines.push('- Use a bounded wait instead of guessing that a page is ready after a pause.');
300
+ lines.push('- "job completed" is the only proof a command finished. A typed line returning output is not proof.');
301
+ lines.push('- Tokens go in the X-Townmouse-Token header, never in a URL, page text, or screenshot.');
302
+ lines.push('');
303
+ lines.push('## Tools');
304
+ lines.push('');
305
+ for (const tool of TOOLS) {
306
+ lines.push(`### ${tool.name}`);
307
+ lines.push(tool.purpose);
308
+ lines.push(`CLI: ${tool.cli}`);
309
+ lines.push(`Needs: ${tool.needs}`);
310
+ if (tool.returns) lines.push(`Returns: ${tool.returns}`);
311
+ lines.push('');
312
+ }
313
+ lines.push('## What this connection may do');
314
+ lines.push('');
315
+ for (const capability of CAPABILITIES) {
316
+ lines.push(`- ${capability.granted ? 'ALLOWED' : 'NOT ALLOWED'}: ${capability.summary}`);
317
+ }
318
+ lines.push('');
319
+ return {
320
+ version: 1,
321
+ generatedAt: new Date().toISOString(),
322
+ cli,
323
+ capabilities: CAPABILITIES,
324
+ tools: TOOLS,
325
+ text: lines.join('\n')
326
+ };
327
+ }
328
+
329
+ module.exports = { buildGuide, TOOLS, CAPABILITIES };
@@ -0,0 +1,128 @@
1
+ 'use strict';
2
+ const crypto = require('crypto');
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const express = require('express');
7
+
8
+ // Move old day buckets out of the active upload tree. They are archived, not
9
+ // deleted: the owner can inspect or remove them without losing a file the
10
+ // workspace still references.
11
+ function pruneAttachments(stateDir, options = {}) {
12
+ const root = path.join(stateDir, 'attachments');
13
+ const archive = path.join(stateDir, 'attachments-archive');
14
+ const retentionDays = Math.max(1, Number(options.retentionDays ?? process.env.TOWNMOUSE_ATTACHMENT_RETENTION_DAYS ?? 30) || 30);
15
+ const now = Number(options.now) || Date.now();
16
+ const cutoff = now - retentionDays * 24 * 60 * 60 * 1000;
17
+ let moved = 0;
18
+ let entries;
19
+ try { entries = fs.readdirSync(root, { withFileTypes: true }); }
20
+ catch (_) { return { moved }; }
21
+ for (const entry of entries) {
22
+ if (!entry.isDirectory() || !/^\d{8}$/.test(entry.name)) continue;
23
+ const year = Number(entry.name.slice(0, 4));
24
+ const month = Number(entry.name.slice(4, 6));
25
+ const day = Number(entry.name.slice(6, 8));
26
+ const stamp = Date.UTC(year, month - 1, day);
27
+ if (!Number.isFinite(stamp) || stamp >= cutoff) continue;
28
+ const from = path.join(root, entry.name);
29
+ const to = path.join(archive, entry.name);
30
+ if (fs.existsSync(to)) continue;
31
+ try {
32
+ fs.mkdirSync(archive, { recursive: true, mode: 0o700 });
33
+ fs.renameSync(from, to);
34
+ moved += 1;
35
+ } catch (_) { /* leave the bucket in place if it cannot move */ }
36
+ }
37
+ return { moved };
38
+ }
39
+
40
+ function installAttachments(app) {
41
+ const stateDir = process.env.TOWNMOUSE_STATE_DIR || path.join(os.homedir(), '.townmouse');
42
+ const root = path.join(stateDir, 'attachments');
43
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
44
+ try { pruneAttachments(stateDir); } catch (_) { /* retention is best effort */ }
45
+
46
+ app.use('/attachments', express.static(root, {
47
+ fallthrough: false,
48
+ setHeaders: (res) => {
49
+ res.setHeader('Cache-Control', 'no-store');
50
+ res.setHeader('X-Content-Type-Options', 'nosniff');
51
+ // Attachments are untrusted URL-backed documents. Sandbox them into an
52
+ // opaque origin so HTML/SVG cannot read the workspace token or call the
53
+ // pane-control API from the Townmouse origin.
54
+ res.setHeader('Content-Security-Policy', "sandbox; default-src 'none'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'unsafe-inline'");
55
+ res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
56
+ // Never render an uploaded HTML/SVG/XML document as active content on
57
+ // the workspace origin. Downloads keep even a CSP bypass from reaching
58
+ // the bootstrap endpoints or the pane-control API.
59
+ const extension = path.extname(String(res.req?.path || '')).toLowerCase();
60
+ if (['.html', '.htm', '.xhtml', '.svg', '.xml'].includes(extension)) {
61
+ res.setHeader('Content-Disposition', 'attachment');
62
+ }
63
+ }
64
+ }));
65
+
66
+ app.post('/api/attachments', express.raw({ type: '*/*', limit: '25mb' }), async (req, res) => {
67
+ try {
68
+ const paneToken = req.get('X-Townmouse-Token') || (req.get('Authorization') || '').replace(/^Bearer\s+/i, '');
69
+ const agentUpload = Boolean(paneToken && app.locals.townmousePaneToken && paneToken === app.locals.townmousePaneToken);
70
+ if (!req.isOwner && !agentUpload) {
71
+ res.status(403).json({ error: 'Owner page or workspace token required.' });
72
+ return;
73
+ }
74
+ const data = req.body;
75
+ if (!Buffer.isBuffer(data) || data.length === 0) {
76
+ res.status(400).json({ error: 'No file body was received.' });
77
+ return;
78
+ }
79
+ let original = 'attachment';
80
+ try { original = decodeURIComponent(String(req.get('X-Filename') || 'attachment')); } catch (_) { /* keep fallback */ }
81
+ const base = path.basename(original).replace(/[^A-Za-z0-9._ -]/g, '_').replace(/^\.+/, '').slice(-120) || 'attachment';
82
+ const day = new Date().toISOString().slice(0, 10).replace(/-/g, '');
83
+ const dir = path.join(root, day);
84
+ await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });
85
+ // Bound one day's uploads so a runaway agent cannot fill the disk a
86
+ // request at a time. Older day directories are left for the owner to
87
+ // inspect or remove; nothing is silently deleted.
88
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
89
+ const files = entries.filter((entry) => entry.isFile());
90
+ if (files.length >= 2000) {
91
+ res.status(413).json({ error: 'Daily attachment count limit reached.' });
92
+ return;
93
+ }
94
+ let dayBytes = 0;
95
+ for (const entry of files) {
96
+ try { dayBytes += (await fs.promises.stat(path.join(dir, entry.name))).size; } catch (_) { /* vanished */ }
97
+ }
98
+ if (dayBytes + data.length > 512 * 1024 * 1024) {
99
+ res.status(413).json({ error: 'Daily attachment storage limit reached.' });
100
+ return;
101
+ }
102
+ const stored = `${Date.now()}-${crypto.randomBytes(4).toString('hex')}-${base}`;
103
+ const target = path.join(dir, stored);
104
+ await fs.promises.writeFile(target, data, { mode: 0o600 });
105
+ const relative = `/attachments/${day}/${encodeURIComponent(stored)}`;
106
+ const forwardedHost = String(req.get('X-Forwarded-Host') || '').split(',')[0].trim();
107
+ const forwardedProto = String(req.get('X-Forwarded-Proto') || '').split(',')[0].trim();
108
+ const host = forwardedHost || req.get('host') || `127.0.0.1:${process.env.PORT || 11002}`;
109
+ const protocol = forwardedProto === 'https' ? 'https' : req.protocol;
110
+ res.set('Cache-Control', 'no-store');
111
+ res.json({
112
+ name: original,
113
+ path: target,
114
+ url: `${protocol}://${host}${relative}`,
115
+ localUrl: `http://127.0.0.1:${process.env.PORT || 11002}${relative}`,
116
+ relativeUrl: relative,
117
+ mime: String(req.get('Content-Type') || 'application/octet-stream'),
118
+ bytes: data.length
119
+ });
120
+ } catch (error) {
121
+ res.status(error.status || 500).json({ error: error.message });
122
+ }
123
+ });
124
+
125
+ return { root };
126
+ }
127
+
128
+ module.exports = { installAttachments, pruneAttachments };