townmouse 0.0.0-stage → 0.2.1

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 (103) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/DESIGN.md +169 -0
  3. package/LICENSE +661 -0
  4. package/README.md +368 -2
  5. package/SECURITY.md +57 -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 +275 -0
  13. package/docs/browser-workspace.md +184 -0
  14. package/docs/panes.md +252 -0
  15. package/native/TownmouseApp.swift +108 -0
  16. package/package.json +89 -4
  17. package/public/apple-touch-icon.png +0 -0
  18. package/public/brand/floydslabs-credit.png +0 -0
  19. package/public/brand/floydslabs-credit.webp +0 -0
  20. package/public/brand/townmouse-aristocrat.webp +0 -0
  21. package/public/brand/townmouse-monocled.webp +0 -0
  22. package/public/clipboard-text.mjs +5 -0
  23. package/public/favicon-16x16.png +0 -0
  24. package/public/favicon-32x32.png +0 -0
  25. package/public/favicon.ico +0 -0
  26. package/public/favicon.svg +1 -0
  27. package/public/features/autosave.mjs +76 -0
  28. package/public/features/clipboard.mjs +69 -0
  29. package/public/features/command-palette.mjs +181 -0
  30. package/public/features/desktop-palette.mjs +19 -0
  31. package/public/features/export.mjs +37 -0
  32. package/public/features/file-drop.mjs +77 -0
  33. package/public/features/floating-palette.mjs +113 -0
  34. package/public/features/fontsize.mjs +72 -0
  35. package/public/features/haptic-keys.mjs +42 -0
  36. package/public/features/history-undo.mjs +102 -0
  37. package/public/features/keepalive.mjs +36 -0
  38. package/public/features/keybar-config.mjs +70 -0
  39. package/public/features/keyboard-shortcuts.mjs +74 -0
  40. package/public/features/links.mjs +139 -0
  41. package/public/features/multi-window-sync.mjs +74 -0
  42. package/public/features/osc-bridge.mjs +59 -0
  43. package/public/features/phone-landscape-focus.mjs +157 -0
  44. package/public/features/recent-commands.mjs +100 -0
  45. package/public/features/search.mjs +134 -0
  46. package/public/features/session-lock.mjs +96 -0
  47. package/public/features/session-manager.mjs +149 -0
  48. package/public/features/settings-sync.mjs +77 -0
  49. package/public/features/shortcut-help.mjs +85 -0
  50. package/public/features/smart-completions.mjs +101 -0
  51. package/public/features/smart-suggest.mjs +124 -0
  52. package/public/features/snippets.mjs +85 -0
  53. package/public/features/split-view.mjs +102 -0
  54. package/public/features/status-metrics.mjs +114 -0
  55. package/public/features/stylus-support.mjs +124 -0
  56. package/public/features/swipe-history.mjs +141 -0
  57. package/public/features/swipe-sessions.mjs +85 -0
  58. package/public/features/tab-reorder.mjs +62 -0
  59. package/public/features/theme-system.mjs +51 -0
  60. package/public/features/toast-status.mjs +118 -0
  61. package/public/features/two-finger-menu.mjs +87 -0
  62. package/public/features/voice-input.mjs +244 -0
  63. package/public/features/wake-fullscreen.mjs +67 -0
  64. package/public/features/window-title.mjs +40 -0
  65. package/public/features/zoom.mjs +80 -0
  66. package/public/icon-128.png +0 -0
  67. package/public/icon-180.png +0 -0
  68. package/public/icon-192.png +0 -0
  69. package/public/icon-48.png +0 -0
  70. package/public/icon-512-maskable.png +0 -0
  71. package/public/icon-512.png +0 -0
  72. package/public/icon.svg +1 -0
  73. package/public/index.html +1765 -0
  74. package/public/input-chunks.mjs +22 -0
  75. package/public/input-guard.mjs +210 -0
  76. package/public/manifest.json +56 -0
  77. package/public/panes.css +1257 -0
  78. package/public/panes.html +208 -0
  79. package/public/panes.mjs +2625 -0
  80. package/public/service-worker.js +67 -0
  81. package/public/workspace.css +1447 -0
  82. package/public/workspace.mjs +1475 -0
  83. package/scripts/install-service.sh +269 -0
  84. package/scripts/node-runtime.sh +138 -0
  85. package/scripts/panes +439 -0
  86. package/scripts/prepare-native.sh +35 -0
  87. package/scripts/run-hooks +69 -0
  88. package/scripts/t1.sh +113 -0
  89. package/scripts/uninstall-service.sh +49 -0
  90. package/src/agent-guide.js +260 -0
  91. package/src/attachments.js +128 -0
  92. package/src/browser-dom.js +545 -0
  93. package/src/browser-workspace.js +1246 -0
  94. package/src/chrome-resolve.js +80 -0
  95. package/src/pty-permissions.js +99 -0
  96. package/src/regex-worker.js +13 -0
  97. package/src/replay-text.js +189 -0
  98. package/src/request-boundary.js +58 -0
  99. package/src/safe-regex.js +87 -0
  100. package/src/server.js +1122 -0
  101. package/src/shell-resolve.js +42 -0
  102. package/src/static-deps.js +61 -0
  103. package/src/workspace-panes.js +1099 -0
@@ -0,0 +1,49 @@
1
+ #!/bin/bash
2
+ #
3
+ # Townmouse — remove the always-on LaunchAgent. Full reversal of install-service.sh.
4
+ # Stops the running service and deletes the plist. Does not touch app code or ports
5
+ # beyond releasing 11001 when the process stops.
6
+ #
7
+ set -euo pipefail
8
+
9
+ LABEL="com.floyd.terminalone"
10
+ DOMAIN="gui/$(id -u)"
11
+ PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
12
+
13
+ launchctl bootout "$DOMAIN/$LABEL" 2>/dev/null || true
14
+ if [ -f "$PLIST" ]; then
15
+ rm -f "$PLIST"
16
+ echo "Removed $PLIST"
17
+ else
18
+ echo "No plist found at $PLIST (nothing to remove)"
19
+ fi
20
+
21
+ # Remove the `t1` launcher(s) created by install-service.sh — symlink (legacy) or
22
+ # the generated binary (current). Guarded: only delete if it's ours (marker match)
23
+ # so we never clobber an unrelated `t1` on the user's PATH.
24
+ for d in /usr/local/bin "$HOME/.local/bin" "$HOME/bin"; do
25
+ f="$d/t1"
26
+ if [ -L "$f" ]; then
27
+ case "$(readlink "$f")" in *Townmouse*|*TerminalOne*) rm -f "$f" && echo "Removed $f (symlink)";; esac
28
+ elif [ -f "$f" ] && grep -Eq 'Townmouse launcher|TerminalOne launcher' "$f" 2>/dev/null; then
29
+ rm -f "$f" && echo "Removed $f (binary)"
30
+ fi
31
+ done
32
+
33
+ # Remove the no-terminal app launcher from both possible install locations.
34
+ for APP_BUNDLE in "/Applications/Townmouse.app" "$HOME/Applications/Townmouse.app" "/Applications/TerminalOne.app" "$HOME/Applications/TerminalOne.app"; do
35
+ if [ -d "$APP_BUNDLE" ]; then rm -rf "$APP_BUNDLE" && echo "Removed $APP_BUNDLE"; fi
36
+ done
37
+
38
+ # Remove the PATH line added to shell rc files by install-service.sh.
39
+ # Use ';' not '&&' for mv: grep -vF exits 1 when the marked line is the last
40
+ # remaining content (no output lines), but we must still write the (empty) result.
41
+ MARK="# added by Townmouse install-service.sh"
42
+ for rc in "$HOME/.zshrc" "$HOME/.bash_profile"; do
43
+ if [ -f "$rc" ] && grep -qF "$MARK" "$rc" 2>/dev/null; then
44
+ tmp="$(mktemp)"
45
+ grep -vF "$MARK" "$rc" > "$tmp"; mv "$tmp" "$rc" && echo "Cleaned PATH line from $rc"
46
+ fi
47
+ done
48
+
49
+ echo "Townmouse service uninstalled."
@@ -0,0 +1,260 @@
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: 'browser.observe',
89
+ cli: 'panes pane browser observe <pane-id> [--elements] [--max N]',
90
+ purpose: 'Take a fresh screenshot with an observation label, and optionally a catalog of the controls on the page.',
91
+ needs: 'browser pane id',
92
+ returns: 'Observation id, capture time, viewport size, scroll offset, address, title, and (with --elements) controls with refs.'
93
+ },
94
+ {
95
+ name: 'browser.elements',
96
+ cli: 'panes pane browser elements <pane-id> [--max N]',
97
+ 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.',
98
+ needs: 'browser pane id'
99
+ },
100
+ {
101
+ name: 'browser.click',
102
+ cli: 'panes pane browser click <pane-id> (--ref e12 | --x N --y N [--observation N])',
103
+ purpose: 'Click a control by ref (preferred) or by coordinate from a named observation. A coordinate from a stale observation is refused.',
104
+ needs: 'browser pane id and ref, or x/y with the observation they came from'
105
+ },
106
+ {
107
+ name: 'browser.type',
108
+ cli: 'panes pane browser type <pane-id> <text...> [--ref e12] [--replace]',
109
+ purpose: 'Type text, optionally into a specific control. --replace selects the existing content first instead of appending.',
110
+ needs: 'browser pane id, text; optional ref'
111
+ },
112
+ {
113
+ name: 'browser.key',
114
+ cli: 'panes pane browser key <pane-id> <key...>',
115
+ purpose: 'Press browser keys, including combinations such as Alt+M, Control+Shift+Tab.',
116
+ needs: 'browser pane id, key names'
117
+ },
118
+ {
119
+ name: 'browser.hover',
120
+ cli: 'panes pane browser hover <pane-id> (--ref e12 | --x N --y N)',
121
+ purpose: 'Move the pointer over a target without clicking.',
122
+ needs: 'browser pane id and ref or coordinates'
123
+ },
124
+ {
125
+ name: 'browser.drag',
126
+ cli: 'panes pane browser drag <pane-id> --from-ref e12 --to-ref e15',
127
+ purpose: 'Drag from one target to another inside the agent browser.',
128
+ needs: 'browser pane id and two targets'
129
+ },
130
+ {
131
+ name: 'browser.scroll',
132
+ cli: 'panes pane browser scroll <pane-id> [--ref e12 | --selector CSS] [--dy N] [--dx N]',
133
+ purpose: 'Scroll a named area. Without a target it scrolls the page; with one it scrolls that element\'s own scroll box.',
134
+ needs: 'browser pane id; optional target and deltas'
135
+ },
136
+ {
137
+ name: 'browser.select',
138
+ cli: 'panes pane browser select <pane-id> --ref e12 --value V',
139
+ purpose: 'Set the value of a select or input by ref.',
140
+ needs: 'browser pane id, ref, value'
141
+ },
142
+ {
143
+ name: 'browser.navigate',
144
+ cli: 'panes pane browser navigate <pane-id> <url>',
145
+ purpose: 'Open an http(s) address. The reply carries the new address and the new title.',
146
+ needs: 'browser pane id, URL'
147
+ },
148
+ {
149
+ name: 'browser.wait',
150
+ cli: 'panes pane browser wait <pane-id> [--url URL | --text TEXT | --selector CSS | --value TEXT --ref e12] [--timeout MS]',
151
+ purpose: 'Wait until the page reaches a condition, bounded by a timeout. Prefer this over sleeping.',
152
+ needs: 'browser pane id, one condition, optional timeout'
153
+ },
154
+ {
155
+ name: 'browser.text',
156
+ cli: 'panes pane browser text <pane-id>',
157
+ purpose: 'Read the page text, with an explicit flag when it was cut short.',
158
+ needs: 'browser pane id'
159
+ },
160
+ {
161
+ name: 'browser.dialog',
162
+ cli: 'panes pane dialog <pane-id> --accept|--dismiss [--text VALUE]',
163
+ purpose: 'Answer a page dialog that is waiting.',
164
+ needs: 'browser pane id and an action'
165
+ },
166
+ {
167
+ name: 'browser.sizing',
168
+ cli: 'panes pane browser sizing <pane-id> fit|fixed [--width N] [--height N]',
169
+ 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.',
170
+ needs: 'browser pane id and mode'
171
+ },
172
+ {
173
+ name: 'attach',
174
+ cli: 'panes attach <file> [--pane <pane-id>] [--type MIME]',
175
+ purpose: 'Upload a file to the workspace and optionally insert its path into a terminal pane.',
176
+ needs: 'file path'
177
+ }
178
+ ];
179
+
180
+ const CAPABILITIES = [
181
+ {
182
+ id: 'workspace',
183
+ granted: true,
184
+ summary: 'Create, read, and close workspace tabs and panes through the scoped pane token you already hold.'
185
+ },
186
+ {
187
+ id: 'browser.control',
188
+ granted: true,
189
+ summary: 'Drive browser panes you create or that the owner has shared with control permission.'
190
+ },
191
+ {
192
+ id: 'browser.sharing',
193
+ granted: false,
194
+ summary: 'Change a browser\'s sharing permission or reveal its access token. Only the owner page can do this; an agent token is refused.'
195
+ },
196
+ {
197
+ id: 'owner.page',
198
+ granted: false,
199
+ summary: 'Read or bootstrap the owner workspace token. An Authorization header is refused at the bootstrap routes.'
200
+ },
201
+ {
202
+ id: 'workspace.limits',
203
+ granted: true,
204
+ summary: 'Limits are enforced and unchanged: at most four panes per tab, 24 tabs, 24 terminal panes, 32 browser tabs.'
205
+ }
206
+ ];
207
+
208
+ function buildGuide(options = {}) {
209
+ const cli = options.cli || { available: false };
210
+ const lines = [];
211
+ lines.push('TownMouse agent guide');
212
+ lines.push('');
213
+ lines.push('You are connected to a TownMouse workspace through a scoped agent token.');
214
+ lines.push('This sheet tells you what you may do. It does not add permissions you were not granted.');
215
+ lines.push('');
216
+ lines.push('## Two ways to work');
217
+ lines.push('');
218
+ if (cli.available) {
219
+ lines.push(`The native command-line tool is available in your terminal panes: ${cli.path || 'panes'}`);
220
+ lines.push('It already holds the workspace token, so never copy or paste a token yourself.');
221
+ lines.push('You can also call the HTTP API directly with the TOWNMOUSE_TOKEN environment variable.');
222
+ } else {
223
+ 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.');
224
+ }
225
+ lines.push('');
226
+ lines.push('## Ground rules');
227
+ lines.push('- Never activate or switch the owner\'s visible tab unless they asked you to.');
228
+ lines.push('- Prefer element refs from a fresh observation over coordinates.');
229
+ lines.push('- A coordinate is only valid for the observation it came from; a stale one is refused.');
230
+ lines.push('- Use a bounded wait instead of guessing that a page is ready after a pause.');
231
+ lines.push('- "job completed" is the only proof a command finished. A typed line returning output is not proof.');
232
+ lines.push('- Tokens go in the X-Townmouse-Token header, never in a URL, page text, or screenshot.');
233
+ lines.push('');
234
+ lines.push('## Tools');
235
+ lines.push('');
236
+ for (const tool of TOOLS) {
237
+ lines.push(`### ${tool.name}`);
238
+ lines.push(tool.purpose);
239
+ lines.push(`CLI: ${tool.cli}`);
240
+ lines.push(`Needs: ${tool.needs}`);
241
+ if (tool.returns) lines.push(`Returns: ${tool.returns}`);
242
+ lines.push('');
243
+ }
244
+ lines.push('## What this connection may do');
245
+ lines.push('');
246
+ for (const capability of CAPABILITIES) {
247
+ lines.push(`- ${capability.granted ? 'ALLOWED' : 'NOT ALLOWED'}: ${capability.summary}`);
248
+ }
249
+ lines.push('');
250
+ return {
251
+ version: 1,
252
+ generatedAt: new Date().toISOString(),
253
+ cli,
254
+ capabilities: CAPABILITIES,
255
+ tools: TOOLS,
256
+ text: lines.join('\n')
257
+ };
258
+ }
259
+
260
+ 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 || 11001}`;
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 || 11001}${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 };