create-pmos 0.382.0 → 0.383.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-pmos",
3
- "version": "0.382.0",
3
+ "version": "0.383.0",
4
4
  "description": "Scaffold the PMOS portable kit — run the PMOS product-management workflow (initiative → lane-fit spec → contract → build → three gates, with work-type lanes for features, research, maintenance, incidents, and content) entirely inside your own repo, with all state as git-versioned files. Includes `workflow-sweep`, which audits the state every board derives from and separates real defects from work you simply have not done. `create-pmos workspace` also installs + launches the local Terminal Workspace GUI. No database, no network, no telemetry.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -32,6 +32,18 @@
32
32
  "audit"
33
33
  ],
34
34
  "pmosChanges": [
35
+ {
36
+ "v": "0.383.0",
37
+ "at": "2026-10-21T13:13:17.082Z",
38
+ "f": 2,
39
+ "prs": [
40
+ {
41
+ "n": 994,
42
+ "t": "Share a viewer file as a password link that needs no Cloudflare login",
43
+ "s": "Share a viewer file as a password link that needs no Cloudflare login"
44
+ }
45
+ ]
46
+ },
35
47
  {
36
48
  "v": "0.382.0",
37
49
  "at": "2026-10-21T12:58:18.296Z",
@@ -299,23 +311,6 @@
299
311
  "s": "Each tool the Briefing uses gets a stored read (briefing-source-flow, slice 1)"
300
312
  }
301
313
  ]
302
- },
303
- {
304
- "v": "0.363.0",
305
- "at": "2026-10-21T00:46:24.704Z",
306
- "f": 2,
307
- "prs": [
308
- {
309
- "n": 965,
310
- "t": "Chat is the big middle place in the premium rail",
311
- "s": "Chat is the big middle place in the premium rail"
312
- },
313
- {
314
- "n": 966,
315
- "t": "The meeting detail is one scroll with a short head on a phone",
316
- "s": "The meeting detail is one scroll with a short head on a phone"
317
- }
318
- ]
319
314
  }
320
315
  ]
321
316
  }
@@ -1,3 +1,3 @@
1
- kernel-source: pmos@55f5fd88
1
+ kernel-source: pmos@36fe68a0
2
2
  assembled: 2026-10-21
3
3
  mode: vendor
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Eval calibration log"
4
4
  description: "Append-only record of every PM override of an evaluator verdict."
5
- generated: {by: process:create-pmos, at: "2026-10-21T12:58:15Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-21T13:13:14Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Health budgets"
4
4
  description: "Closed registry of health-budget anchors (D59), edited only by the PM."
5
- generated: {by: process:create-pmos, at: "2026-10-21T12:58:15Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-21T13:13:14Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -2,7 +2,7 @@
2
2
  type: Reference
3
3
  title: "Discoveries and friction log"
4
4
  description: "Append-only record of what runs discovered and where the process rubbed."
5
- generated: {by: process:create-pmos, at: "2026-10-21T12:58:15Z"}
5
+ generated: {by: process:create-pmos, at: "2026-10-21T13:13:14Z"}
6
6
  status: stable
7
7
  ---
8
8
 
@@ -212,6 +212,45 @@ Run these from a machine that is **not** signed in to Access:
212
212
  | `PMOS_PUBLIC_HOST=<hostname>` | Opt in. Add this one bare hostname to the Host allowlist, and require the token and the Access header for requests to it. The server still binds loopback only (plus the tailnet when `PMOS_REMOTE=tailnet` is also set). A scheme, port, path, IP address or `localhost` is refused, and the server does not start. |
213
213
  | `PMOS_TOKEN=<t>` | The workspace token. Recommended in this mode. Never printed. |
214
214
 
215
+ ## Share links (a second hostname, without Access)
216
+
217
+ A share link lets someone with no PMOS and no Cloudflare login read a copy of one file. You make it from the share icon of a file in the viewer (D97). The link names a second hostname, by default `share.` followed by your Online hostname's domain: with Online at `pmos.pm-os.app`, links read `https://share.pm-os.app/s/<id>`. To name another hostname, set `PMOS_SHARE_HOST`.
218
+
219
+ A separate server answers that hostname. It is not the workspace server. It listens on `127.0.0.1` only, on the workspace port plus one (7434 by default; `PMOS_SHARE_PORT` changes it). It can read only the shared copies and has no terminals, no API and no settings. The workspace starts it when you make your first link and stops it with itself. Your workspace hostname keeps its Access sign-in.
220
+
221
+ Do these steps one time, on the computer that runs the workspace:
222
+
223
+ 1. **Route the hostname to the tunnel:**
224
+
225
+ ```sh
226
+ cloudflared tunnel route dns pmos share.pm-os.app
227
+ ```
228
+
229
+ 2. **Add one ingress rule** to `~/.cloudflared/config.yml`, above the last rule:
230
+
231
+ ```yaml
232
+ ingress:
233
+ - hostname: pmos.pm-os.app
234
+ service: http://127.0.0.1:7433
235
+ - hostname: share.pm-os.app
236
+ service: http://127.0.0.1:7434
237
+ - service: http_status:404
238
+ ```
239
+
240
+ 3. **Do not add an Access application for `share.pm-os.app`.** If a wildcard application (`*.pm-os.app`) covers it, add a second application for `share.pm-os.app` with one policy: **Bypass**, **Everyone**. The share server has its own password check.
241
+
242
+ 4. Turn Online off and on again in **Settings › Online**, so the tunnel reads the new rule.
243
+
244
+ Check it: open `https://share.pm-os.app/robots.txt` in a private window. It shows `Disallow: /` with no sign-in. Any other path shows "Not found". A link opens only while this computer is on and Online runs.
245
+
246
+ What a link does:
247
+
248
+ - **A copy, not the file.** The link serves the file as it was when you pressed Create link. Later edits are not shared.
249
+ - **Password.** On by default, with a generated password you can change or turn off. It is stored as a hash. Five wrong tries lock the link for 15 minutes.
250
+ - **End date.** 1, 7 or 30 days, 7 by default. There is no "never". When a link ends, or you press **Turn off**, its copy is deleted at once.
251
+ - **Secrets.** PMOS scans the file first. A key or token in the file stops the link, and the message names what it found.
252
+ - **No indexing, no caching, no log.** Every answer tells search engines not to index it and Cloudflare not to cache it. No IP address or header is kept, only a view count and the last view time.
253
+
215
254
  ## Troubleshooting
216
255
 
217
256
  - **`403` "the public host is only reachable through Cloudflare Access"** — the request reached the workspace without passing Access. Create the Access application for the hostname (Setup step 3).
@@ -1,4 +1,16 @@
1
1
  [
2
+ {
3
+ "v": "0.383.0",
4
+ "at": "2026-10-21T13:13:17.082Z",
5
+ "f": 2,
6
+ "prs": [
7
+ {
8
+ "n": 994,
9
+ "t": "Share a viewer file as a password link that needs no Cloudflare login",
10
+ "s": "Share a viewer file as a password link that needs no Cloudflare login"
11
+ }
12
+ ]
13
+ },
2
14
  {
3
15
  "v": "0.382.0",
4
16
  "at": "2026-10-21T12:58:18.296Z",
@@ -424,6 +424,7 @@ Every popup has this chat, including the ones that have no row of their own: a t
424
424
  - **While a session runs**, the panel reads it again every 2 seconds and changes only when there is something new. The messages already on screen stay still, so nothing blinks beside the viewer.
425
425
  - **A file Claude names** (a path such as `briefs/drafts/plan.md`, or a link to one) is underlined. Press it to read the file beside the conversation, as a tab in the viewer; on a phone, the Detail side shows it (on the Chat page, the viewer opens over the conversation). Markdown shows as a page, an HTML file shows as the page it draws (press **Source** for its code), and other text files show as code. An HTML page runs its own scripts, so its toggles and charts work, but it cannot reach PMOS or the internet: a web font falls back to the system font. It is read-only. While the tab is open it shows the newest version, so a file Claude is still writing stays current. A file outside the workspaces PMOS serves says "Not in a workspace" and is not read.
426
426
  - **Download a file** with the download icon at the right of its name in the viewer. An HTML file saves as **HTML** (as it is) or **PDF**. A markdown file saves as **Markdown**, **Word .docx** or **PDF**. Other text files save at once as they are, with no menu. PDF opens your browser's print window: choose **Save as PDF** there. An HTML page prints with no access to PMOS or the internet, as in the viewer. Word holds the note's headings, paragraphs, lists and tables.
427
+ - **Share a file** with the share icon beside download. On a phone, **Send a copy** comes first: it opens the phone's share sheet with the file, and no link is made. **Public link** makes a link to a copy of the file as it is now, for someone with no PMOS or Cloudflare login. The password is on, with a generated one you can change or turn off. The link ends after 7 days; press **1 day** or **30 days** to change it. Press **Create link**, then **Copy link and password**, and send the password in a different message. The same popover lists your **open links** with their end date and views; **Turn off** (pressed twice) deletes the copy at once. A file with a key or token in it is not shared. Links need Online and one more tunnel rule: see REMOTE.md, "Share links".
427
428
  - **What an answer worked with** shows as buttons under it: the files Claude wrote, changed or read, the Jira tickets and Slack channels it used, and the links it named. The first one is the main one: a file Claude wrote comes first, then what it named in its words, then what it only read. When an answer finishes while the chat is open, its main one opens in the viewer by itself, once; answers that were there when you opened the chat open nothing. On a phone a bar over the message box offers it instead (**View**), so the conversation stays in view. A Jira ticket shows what PMOS last read from Jira for a board or initiative it syncs, with **Open in Jira**; a ticket PMOS has not read says so. A Slack channel or message opens with **Open in Slack**, as PMOS keeps no copy of Slack messages.
428
429
  - **A link to a Google Doc or a Confluence page** opens beside the conversation too, as the viewer shows a copy: the text PMOS has read, or **Read it now**. **A Claude artifact link** opens a tab with **Open in Claude**: claude.ai does not let another site show an artifact inside it. Other links open in a new browser tab.
429
430
  - **The session** is also listed in **Sessions** and in the console, where you can open its terminal.
@@ -0,0 +1,150 @@
1
+ 'use strict';
2
+ /* share-store.js — the copies a share link serves (premium-viewer-share slice 2, D97). The workspace server writes them on the PM's press; the share
3
+ * server (share-server.js) reads them and counts views and wrong passwords. Nothing else reads or writes this folder.
4
+ *
5
+ * THE FOLDER. `<runtime state>/shares/<id>/`, in the per-user runtime directory outside every repository, mode 0700:
6
+ * meta.json { id, name, kind, made, ends, pw: 'scrypt$<salt>$<hash>' | null, key, views, last, fails, lockedUntil } mode 0600
7
+ * page.html the copy as a page: an .html file as it is, markdown rendered by the caller, other text in a <pre> mode 0600
8
+ * file the file's own text, for the guest's Download mode 0600
9
+ * id is 128 random bits (base64url, 22 characters). `key` is a random secret per link that signs the guest's cookie. No IP address,
10
+ * header or user agent is stored (D08): a view is a count and a time.
11
+ *
12
+ * create(dir, { name, kind, page, file, days, password, now }) -> { ok, id, ends } | { ok: false, error }
13
+ * list(dir, now) -> [{ id, name, ends, made, views, last, pw }] the newest first; ended links are deleted on the way
14
+ * get(dir, id, now) -> meta | null null for an unknown, malformed or ended id (an ended one is deleted)
15
+ * remove(dir, id) -> boolean
16
+ * checkPassword(dir, id, given, now) -> { ok } | { ok: false, locked, left, until } five wrong tries lock the link for 15 minutes
17
+ * sign(meta, until) · verifyCookie(meta, value, now) the guest's cookie for one link
18
+ * view(dir, id, now) count one view
19
+ * newPassword() three words and two digits, from crypto.randomInt
20
+ */
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+ const crypto = require('crypto');
24
+
25
+ const DAYS = [1, 7, 30];
26
+ const MAX_TRIES = 5;
27
+ const LOCK_MS = 15 * 60 * 1000;
28
+ const COOKIE_MS = 12 * 60 * 60 * 1000;
29
+ const ID_RX = /^[A-Za-z0-9_-]{22}$/;
30
+ const WORDS = ('amber anchor apple arrow aspen atlas basil beacon birch bison blossom border breeze brook cabin cactus canyon cedar chalk cherry cliff clover '
31
+ + 'cobalt comet coral cotton crane crystal dawn delta desert dune eagle ember falcon fern field flint forest fossil garden ginger glacier granite '
32
+ + 'harbor hazel heron hollow honey island ivory jasmine juniper kettle lagoon lantern lemon lily linen lotus maple marble meadow mesa mint '
33
+ + 'moss nectar oak ocean olive onyx orbit orchid otter pebble pepper pine planet plum pond poppy prairie quartz quill rain raven reef '
34
+ + 'ridge river robin saffron sage salt sand shore silver slate spruce stone summit sun swan thistle thunder tide timber topaz tulip '
35
+ + 'valley velvet violet walnut willow winter wren yarrow zephyr').split(' ');
36
+
37
+ const root = (dir) => path.join(dir, 'shares');
38
+ const at = (dir, id) => path.join(root(dir), id);
39
+ function writeFile(p, data) {
40
+ const tmp = p + '.' + process.pid + '.' + crypto.randomBytes(4).toString('hex') + '.tmp';
41
+ fs.writeFileSync(tmp, data, { mode: 0o600 });
42
+ fs.renameSync(tmp, p);
43
+ }
44
+ function readMeta(dir, id) {
45
+ if (!ID_RX.test(String(id || ''))) return null;
46
+ try { const st = fs.lstatSync(at(dir, id)); if (!st.isDirectory()) return null; return JSON.parse(fs.readFileSync(path.join(at(dir, id), 'meta.json'), 'utf8')); }
47
+ catch { return null; }
48
+ }
49
+ function writeMeta(dir, m) { writeFile(path.join(at(dir, m.id), 'meta.json'), JSON.stringify(m)); }
50
+
51
+ function hashPassword(pw, salt = crypto.randomBytes(16)) {
52
+ const h = crypto.scryptSync(String(pw), salt, 32, { N: 16384, r: 8, p: 1 });
53
+ return 'scrypt$' + salt.toString('base64') + '$' + h.toString('base64');
54
+ }
55
+ function samePassword(stored, given) {
56
+ const [kind, s, h] = String(stored || '').split('$');
57
+ if (kind !== 'scrypt' || !s || !h) return false;
58
+ const want = Buffer.from(h, 'base64');
59
+ const got = crypto.scryptSync(String(given), Buffer.from(s, 'base64'), want.length, { N: 16384, r: 8, p: 1 });
60
+ return got.length === want.length && crypto.timingSafeEqual(got, want);
61
+ }
62
+ function newPassword() {
63
+ const w = () => WORDS[crypto.randomInt(WORDS.length)];
64
+ return `${w()}-${w()}-${w()}-${String(crypto.randomInt(100)).padStart(2, '0')}`;
65
+ }
66
+
67
+ function create(dir, o = {}) {
68
+ const days = Number(o.days);
69
+ if (!DAYS.includes(days)) return { ok: false, error: 'days must be 1, 7 or 30' };
70
+ if (!['html', 'markdown', 'text'].includes(o.kind)) return { ok: false, error: 'kind must be html, markdown or text' };
71
+ if (typeof o.page !== 'string' || typeof o.file !== 'string') return { ok: false, error: 'there is nothing to share' };
72
+ if (o.password != null) {
73
+ const p = String(o.password);
74
+ if (p.length < 8 || p.length > 128) return { ok: false, error: 'the password needs 8 to 128 characters' };
75
+ }
76
+ const now = o.now || Date.now();
77
+ const id = crypto.randomBytes(16).toString('base64url');
78
+ const name = String(o.name || 'file').replace(/[\\/\r\n\0]/g, '-').slice(0, 160);
79
+ const meta = { id, name, kind: o.kind, made: new Date(now).toISOString(), ends: new Date(now + days * 86400000).toISOString(),
80
+ pw: o.password == null ? null : hashPassword(o.password), key: crypto.randomBytes(32).toString('base64'), views: 0, last: null, fails: 0, lockedUntil: null };
81
+ try {
82
+ fs.mkdirSync(root(dir), { recursive: true, mode: 0o700 });
83
+ fs.mkdirSync(at(dir, id), { mode: 0o700 });
84
+ writeFile(path.join(at(dir, id), 'page.html'), o.page);
85
+ writeFile(path.join(at(dir, id), 'file'), o.file);
86
+ writeMeta(dir, meta);
87
+ } catch (e) {
88
+ remove(dir, id);
89
+ return { ok: false, error: 'the copy could not be saved (' + String((e && e.code) || 'write failed') + ')' };
90
+ }
91
+ return { ok: true, id, ends: meta.ends };
92
+ }
93
+ function remove(dir, id) {
94
+ if (!ID_RX.test(String(id || ''))) return false;
95
+ try { fs.rmSync(at(dir, id), { recursive: true, force: true }); return true; } catch { return false; }
96
+ }
97
+ const ended = (m, now) => !m || !m.ends || Date.parse(m.ends) <= now;
98
+ function get(dir, id, now = Date.now()) {
99
+ const m = readMeta(dir, id);
100
+ if (!m) return null;
101
+ if (ended(m, now)) { remove(dir, id); return null; }
102
+ return m;
103
+ }
104
+ function list(dir, now = Date.now()) {
105
+ let ids = [];
106
+ try { ids = fs.readdirSync(root(dir)).filter((x) => ID_RX.test(x)); } catch { return []; }
107
+ const out = [];
108
+ for (const id of ids) {
109
+ const m = get(dir, id, now);
110
+ if (m) out.push({ id: m.id, name: m.name, kind: m.kind, made: m.made, ends: m.ends, views: m.views || 0, last: m.last || null, pw: !!m.pw });
111
+ }
112
+ return out.sort((a, b) => String(b.made).localeCompare(String(a.made)));
113
+ }
114
+ function readPart(dir, id, part) {
115
+ if (!['page.html', 'file'].includes(part) || !ID_RX.test(String(id || ''))) return null;
116
+ try { return fs.readFileSync(path.join(at(dir, id), part), 'utf8'); } catch { return null; }
117
+ }
118
+ function checkPassword(dir, id, given, now = Date.now()) {
119
+ const m = get(dir, id, now);
120
+ if (!m || !m.pw) return { ok: false, locked: false, left: 0 };
121
+ if (m.lockedUntil && Date.parse(m.lockedUntil) > now) return { ok: false, locked: true, left: 0, until: m.lockedUntil };
122
+ if (samePassword(m.pw, String(given || '').slice(0, 256))) {
123
+ if (m.fails || m.lockedUntil) { m.fails = 0; m.lockedUntil = null; writeMeta(dir, m); }
124
+ return { ok: true };
125
+ }
126
+ m.fails = (m.lockedUntil && Date.parse(m.lockedUntil) <= now ? 0 : m.fails || 0) + 1;
127
+ m.lockedUntil = null;
128
+ if (m.fails >= MAX_TRIES) { m.fails = 0; m.lockedUntil = new Date(now + LOCK_MS).toISOString(); }
129
+ writeMeta(dir, m);
130
+ return m.lockedUntil ? { ok: false, locked: true, left: 0, until: m.lockedUntil } : { ok: false, locked: false, left: MAX_TRIES - m.fails };
131
+ }
132
+ function sign(m, until) {
133
+ const exp = String(Math.floor(until));
134
+ return exp + '.' + crypto.createHmac('sha256', Buffer.from(m.key, 'base64')).update(m.id + '.' + exp).digest('base64url');
135
+ }
136
+ function verifyCookie(m, value, now = Date.now()) {
137
+ const [exp, sig] = String(value || '').split('.');
138
+ if (!/^\d{10,16}$/.test(exp || '') || !sig || Number(exp) <= now) return false;
139
+ const want = Buffer.from(sign(m, Number(exp)).split('.')[1]), got = Buffer.from(sig);
140
+ return want.length === got.length && crypto.timingSafeEqual(want, got);
141
+ }
142
+ function view(dir, id, now = Date.now()) {
143
+ const m = get(dir, id, now);
144
+ if (!m) return;
145
+ m.views = (m.views || 0) + 1; m.last = new Date(now).toISOString();
146
+ try { writeMeta(dir, m); } catch { /* a missed count is not worth a failed page */ }
147
+ }
148
+
149
+ module.exports = { create, list, get, remove, readPart, checkPassword, sign, verifyCookie, view, newPassword, hashPassword, samePassword,
150
+ DAYS, MAX_TRIES, LOCK_MS, COOKIE_MS, ID_RX };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.382.0",
3
+ "version": "0.383.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.382.0",
9
+ "version": "0.383.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.382.0",
3
+ "version": "0.383.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
@@ -0,0 +1,208 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* premium-viewer-share-test.js — share links from the viewer (premium-viewer-share slice 2, D97; PM 2026-10-21: "share (no need login to cloudflare,
4
+ * but I can set password)"). lib/share-store.js keeps the copies, POST /api/shares makes one on a page press, share-server.js serves them.
5
+ * K1 the store: 22-character ids, a scrypt hash and never the password, five wrong tries lock for 15 minutes, a link past its end is deleted,
6
+ * the cookie is signed per link and a changed one fails
7
+ * K2 the routes: an agent session and a request without the page's press headers are refused; a file with a secret is refused and the answer
8
+ * names the rule only; 1, 7 or 30 days only; a made link is listed with its password flag and no hash
9
+ * K3 the share server: the password page names neither the file nor PMOS; a wrong password counts down, five lock, the right one opens; the copy
10
+ * is under a sandbox CSP; Download gives the file's own text; every answer is noindex, no-store, no-referrer; any other path is 404
11
+ * K4 Turn off deletes the copy and the link answers "no longer active"; the workspace server refuses the share hostname
12
+ * K5 the page: the share icon opens the popover with a generated password and 7 days; Create link shows the link; a guest opens it with the
13
+ * password in a browser; Turn off asks once more, then removes it; at 390 the popover is a sheet that fits
14
+ * PMOS_SHOTS=<dir> also saves the popover at 1280 and 390, light and dark, and the guest's pages. */
15
+ const fs = require('fs');
16
+ const os = require('os');
17
+ const path = require('path');
18
+ const http = require('http');
19
+ const { spawn } = require('child_process');
20
+ const { findBrowser } = require('./lib/find-browser');
21
+ const T = require('./test-run').configure({ name: 'premium-viewer-share' });
22
+ const store = require('./lib/share-store');
23
+
24
+ const BASE = T.BASE;
25
+ const SHARE_PORT = T.port();
26
+ const SBASE = `http://127.0.0.1:${SHARE_PORT}`;
27
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
28
+ const until = async (fn, ms = 10000, step = 100) => { const t0 = Date.now(); for (;;) { const v = await fn(); if (v) return v; if (Date.now() - t0 > ms) return v; await sleep(step); } };
29
+ const results = [];
30
+ const ok = (name, cond, extra = '') => { results.push({ name, cond: !!cond }); console.log(`${cond ? '✓' : '✗'} ${name}${!cond && extra !== '' ? ' — ' + String(extra).slice(0, 600) : ''}`); };
31
+ let srv = null; let browser = null;
32
+ const REPO = path.resolve(__dirname, '..');
33
+ const SECRET_REL = `workspace/.share-test-${process.pid}.md`;
34
+ const finish = async (code) => {
35
+ if (browser) await browser.close().catch(() => {});
36
+ if (srv) { try { srv.kill('SIGTERM'); } catch { /* gone */ } }
37
+ try { fs.unlinkSync(path.join(REPO, SECRET_REL)); } catch { /* not made */ }
38
+ T.killTmux();
39
+ const bad = results.filter((x) => !x.cond).length;
40
+ console.log(`\n${results.length - bad}/${results.length} premium-viewer-share assertions passed`);
41
+ process.exit(code !== undefined ? code : (bad ? 1 : 0));
42
+ };
43
+ process.on('unhandledRejection', (e) => { console.error(e); finish(1); });
44
+ const req = (url, { method = 'GET', headers = {}, body } = {}) => new Promise((resolve) => {
45
+ const u = new URL(url);
46
+ const r = http.request({ host: u.hostname, port: u.port, path: u.pathname + u.search, method, headers }, (res) => {
47
+ const parts = []; res.on('data', (c) => parts.push(c)); res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, text: Buffer.concat(parts).toString('utf8') }));
48
+ });
49
+ r.on('error', (e) => resolve({ status: 0, headers: {}, text: String(e) }));
50
+ if (body) r.write(body);
51
+ r.end();
52
+ });
53
+ const PRD = 'planning/prd/premium-viewer-share-prd.md';
54
+ const SHOTS = process.env.PMOS_SHOTS || '';
55
+
56
+ (async () => {
57
+ // K1 the store, on its own folder
58
+ {
59
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'share-store-'));
60
+ const now = Date.parse('2026-10-21T10:00:00Z');
61
+ const a = store.create(dir, { name: 'n.md', kind: 'markdown', page: '<p>x</p>', file: '# x', days: 7, password: 'cedar-river-tulip-07', now });
62
+ const meta = JSON.parse(fs.readFileSync(path.join(dir, 'shares', a.id, 'meta.json'), 'utf8'));
63
+ ok('K1 a link has a 22-character id and ends 7 days on', a.ok && store.ID_RX.test(a.id) && a.ends === '2026-10-28T10:00:00.000Z', JSON.stringify(a));
64
+ ok('K1 the password is kept as a scrypt hash, never as itself', /^scrypt\$/.test(meta.pw) && !fs.readFileSync(path.join(dir, 'shares', a.id, 'meta.json'), 'utf8').includes('cedar-river'));
65
+ ok('K1 only 1, 7 or 30 days, and a password of 8 or more', !store.create(dir, { name: 'n', kind: 'text', page: '', file: '', days: 365 }).ok && !store.create(dir, { name: 'n', kind: 'text', page: '', file: '', days: 7, password: 'short' }).ok);
66
+ const tries = [1, 2, 3, 4, 5].map(() => store.checkPassword(dir, a.id, 'wrong', now));
67
+ ok('K1 wrong tries count down and the fifth locks the link', tries.slice(0, 4).map((t) => t.left).join() === '4,3,2,1' && tries[4].locked, JSON.stringify(tries));
68
+ ok('K1 while locked even the right password is refused', store.checkPassword(dir, a.id, 'cedar-river-tulip-07', now + 60000).locked);
69
+ ok('K1 after 15 minutes the right password opens', store.checkPassword(dir, a.id, 'cedar-river-tulip-07', now + store.LOCK_MS + 1000).ok);
70
+ const m = store.get(dir, a.id, now), c = store.sign(m, now + 1000);
71
+ ok('K1 the cookie is signed for this link, and a changed or late one fails', store.verifyCookie(m, c, now) && !store.verifyCookie(m, c.slice(0, -2) + 'xx', now) && !store.verifyCookie(m, c, now + 2000));
72
+ ok('K1 a link past its end is gone from the list and the disk', store.list(dir, now + 8 * 86400000).length === 0 && !fs.existsSync(path.join(dir, 'shares', a.id)));
73
+ ok('K1 a password is three words and two digits', /^[a-z]+-[a-z]+-[a-z]+-\d{2}$/.test(store.newPassword()));
74
+ fs.rmSync(dir, { recursive: true, force: true });
75
+ }
76
+
77
+ srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore',
78
+ env: T.env({ PMOS_WS_PORT: String(T.PORT), PMOS_SHARE_PORT: String(SHARE_PORT), PMOS_SHARE_HOST: 'share.example.test' }) });
79
+ await T.waitForServer(BASE);
80
+ const H = await T.pressHeaders(BASE);
81
+ const post = (p, body, extra = {}) => req(BASE + p, { method: 'POST', headers: { ...H, ...extra }, body: JSON.stringify(body) });
82
+
83
+ // K2 the routes
84
+ {
85
+ ok('K2 a POST without the page\'s press headers is refused', (await req(BASE + '/api/shares', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: PRD, days: 7 }) })).status === 403);
86
+ ok('K2 an agent session cannot make a link', (await post('/api/shares', { path: PRD, days: 7 }, { 'x-pmos-session': 'sess-1' })).status === 403);
87
+ fs.writeFileSync(path.join(REPO, SECRET_REL), '# Keys\n\naws ' + 'AKIA' + 'ABCDEFGHIJKLMNOP' + ' here\n');
88
+ const sec = await post('/api/shares', { path: SECRET_REL, days: 7, password: null });
89
+ ok('K2 a file with a secret is refused, naming the rule and not the text', sec.status === 422 && /aws-access-key/.test(sec.text) && !/AKIAABCD/.test(sec.text), sec.status + ' ' + sec.text);
90
+ ok('K2 only 1, 7 or 30 days', (await post('/api/shares', { path: PRD, days: 3, password: null })).status === 400);
91
+ ok('K2 a path outside the workspace is not shared', (await post('/api/shares', { path: '../../../etc/hosts', days: 7 })).status === 404);
92
+ }
93
+ const PASS = 'harbor-maple-quartz-42';
94
+ const mk = await post('/api/shares', { path: PRD, days: 7, password: PASS });
95
+ const made = JSON.parse(mk.text || '{}');
96
+ ok('K2 a link is made, on the share hostname', mk.status === 200 && made.ok && /^https:\/\/share\.example\.test\/s\/[A-Za-z0-9_-]{22}$/.test(made.url), mk.text);
97
+ const listed = JSON.parse((await req(BASE + '/api/shares')).text || '{}');
98
+ const row = (listed.shares || []).find((x) => x.id === made.id);
99
+ ok('K2 the list shows it with its password flag and no hash or key', row && row.pw === true && row.views === 0 && !('key' in row) && !/scrypt/.test(JSON.stringify(listed)) && listed.host === 'share.example.test', JSON.stringify(listed));
100
+ const pw = JSON.parse((await req(BASE + '/api/shares/password')).text || '{}');
101
+ ok('K2 the page can ask for a generated password', pw.ok && /^[a-z]+-[a-z]+-[a-z]+-\d{2}$/.test(pw.password));
102
+
103
+ // K3 the share server
104
+ const up = await until(async () => (await req(SBASE + '/robots.txt')).status === 200, 10000, 200);
105
+ ok('K3 the share server starts on its own loopback port once a link exists', !!up);
106
+ const S = '/s/' + made.id;
107
+ const lock = await req(SBASE + S);
108
+ const hdr = (r) => r.headers['x-robots-tag'] === 'noindex, nofollow, noarchive' && /no-store/.test(r.headers['cache-control'] || '') && r.headers['referrer-policy'] === 'no-referrer';
109
+ ok('K3 the password page names neither the file nor PMOS', lock.status === 200 && /This page is protected/.test(lock.text) && !/premium-viewer-share|PMOS|Download and share/.test(lock.text), lock.text.slice(0, 200));
110
+ ok('K3 every answer is noindex, no-store and no-referrer', hdr(lock) && hdr(await req(SBASE + '/nope')) && hdr(await req(SBASE + '/robots.txt')));
111
+ ok('K3 robots.txt disallows everything', (await req(SBASE + '/robots.txt')).text === 'User-agent: *\nDisallow: /\n');
112
+ ok('K3 the copy and the file stay closed without the password', (await req(SBASE + S + '/view')).status === 404 && (await req(SBASE + S + '/file')).status === 404);
113
+ const form = (p) => req(SBASE + S, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'pw=' + encodeURIComponent(p) });
114
+ const w1 = await form('nope');
115
+ ok('K3 a wrong password says how many tries are left', w1.status === 401 && /4 tries left/.test(w1.text), w1.status + ' ' + w1.text.slice(0, 300));
116
+ const right = await form(PASS);
117
+ const cookie = String((right.headers['set-cookie'] || [])[0] || '');
118
+ ok('K3 the right password sets a cookie for this link only', right.status === 303 && new RegExp(`Path=/s/${made.id}`).test(cookie) && /HttpOnly/.test(cookie) && /Secure/.test(cookie) && /Max-Age=43200/.test(cookie), cookie);
119
+ const C = { Cookie: cookie.split(';')[0] };
120
+ const page = await req(SBASE + S, { headers: C });
121
+ ok('K3 with the cookie the page frames the copy, with Download and the end date', page.status === 200 && /<iframe src="\/s\/[^"]+\/view"/.test(page.text) && /Download/.test(page.text) && /The link ends/.test(page.text), page.text.slice(0, 300));
122
+ const view = await req(SBASE + S + '/view', { headers: C });
123
+ ok('K3 the copy is under a sandbox CSP and holds the document\'s words', view.status === 200 && /^sandbox[;\s]/.test(view.headers['content-security-policy'] || '') && /default-src 'none'/.test(view.headers['content-security-policy']) && /Download and share a file from the viewer/.test(view.text), view.headers['content-security-policy']);
124
+ const file = await req(SBASE + S + '/file', { headers: C });
125
+ ok('K3 Download gives the file\'s own text as an attachment', file.status === 200 && /attachment; filename="premium-viewer-share-prd\.md"/.test(file.headers['content-disposition'] || '') && file.text === fs.readFileSync(path.join(REPO, PRD), 'utf8'));
126
+ ok('K3 any other path is 404, including the workspace API', (await req(SBASE + '/')).status === 404 && (await req(SBASE + '/api/shares')).status === 404 && (await req(SBASE + '/s/short')).status === 404 && (await req(SBASE + '/premium.html')).status === 404);
127
+ for (let i = 0; i < 5; i++) await form('wrong-' + i);
128
+ const locked = await form(PASS);
129
+ ok('K3 five wrong tries lock the link, even for the right password', locked.status === 429 && /15 minutes/.test(locked.text), locked.status);
130
+ const views = (JSON.parse((await req(BASE + '/api/shares')).text).shares || []).find((x) => x.id === made.id);
131
+ ok('K3 a view is counted, with no address kept', views && views.views === 1 && !/127\.0\.0\.1/.test(fs.readFileSync(path.join(T.STATE_DIR, 'shares', made.id, 'meta.json'), 'utf8')), JSON.stringify(views));
132
+
133
+ // K4 Turn off, and the workspace refuses the share hostname
134
+ const off = await post('/api/shares/off', { id: made.id });
135
+ ok('K4 Turn off deletes the copy and the link says it is no longer active', off.status === 200 && !fs.existsSync(path.join(T.STATE_DIR, 'shares', made.id)) && /no longer active/.test((await req(SBASE + S)).text));
136
+ const wsHost = await req(BASE + '/api/shares', { headers: { Host: 'share.example.test' } });
137
+ ok('K4 the workspace server refuses a request for the share hostname', wsHost.status === 403, wsHost.status);
138
+
139
+ // K5 the page
140
+ const exe = findBrowser();
141
+ if (!exe) { console.log('✗ no Chrome/Chromium on this machine — the browser part cannot run'); return finish(1); }
142
+ let chromium;
143
+ try { ({ chromium } = require('playwright-core')); } catch { console.log('✗ playwright-core is not installed'); return finish(1); }
144
+ browser = await chromium.launch({ executablePath: exe });
145
+ const open = async ({ w = 1280, h = 900, theme = 'light' } = {}) => {
146
+ const ctx = await browser.newContext({ viewport: { width: w, height: h }, colorScheme: theme });
147
+ const page = await ctx.newPage();
148
+ const errors = [];
149
+ page.on('pageerror', (e) => errors.push(String((e && e.message) || e)));
150
+ await page.route('**/api/brief-page*', (r) => r.fulfill({ contentType: 'application/json', body: '{"ok":false,"error":"off in this suite"}' }));
151
+ await page.goto(BASE + '/premium.html?theme=' + theme);
152
+ await until(() => page.evaluate(() => !!document.querySelector('#dlg')), 15000);
153
+ await page.evaluate(async () => {
154
+ const Sh = await import('/pm/premium-shell.js');
155
+ Sh.openDlg({ eye: 'Your item', title: 'Share plan', say: 'The PRD is in the repo.', noteKey: null, pane: '<article class="paper doc"><p>Item record</p></article>', label: 'Item record' });
156
+ });
157
+ await page.evaluate((f) => { const b = document.createElement('button'); b.type = 'button'; b.className = 'fpath'; b.dataset.file = f; b.textContent = f; document.querySelector('#dBody .stream').append(b); b.click(); }, PRD);
158
+ await until(() => page.$('#dOut .obody.vw:not([hidden]) [data-fsh]'), 10000);
159
+ return { ctx, page, errors };
160
+ };
161
+ const ICON = '#dOut .obody.vw:not([hidden]) [data-fsh]';
162
+ {
163
+ const { page, errors, ctx } = await open();
164
+ await page.click(ICON);
165
+ const st = await until(() => page.evaluate(() => { const m = document.querySelector('.vwshp'), i = m && m.querySelector('#vwsPass'); return i && i.value ? { pass: i.value, days: (m.querySelector('[data-days][aria-pressed="true"]') || {}).textContent, sw: m.querySelector('[data-sh="pw"]').getAttribute('aria-checked') } : null; }), 5000);
166
+ ok('K5 the share icon opens the popover: password on and filled, 7 days', st && /^[a-z]+-[a-z]+-[a-z]+-\d{2}$/.test(st.pass) && st.days === '7 days' && st.sw === 'true', JSON.stringify(st));
167
+ if (SHOTS) { fs.mkdirSync(SHOTS, { recursive: true }); await page.screenshot({ path: path.join(SHOTS, 'popover-1280-light.png') }); }
168
+ await page.click('.vwshp [data-sh="make"]');
169
+ const link = await until(() => page.evaluate(() => { const u = document.querySelector('.vwshp .vwsu'); return u ? u.textContent : null; }), 8000);
170
+ const pass = st && st.pass;
171
+ ok('K5 Create link shows the link on the share hostname', /^https:\/\/share\.example\.test\/s\/[A-Za-z0-9_-]{22}$/.test(link || ''), link);
172
+ const n = await page.evaluate(() => (document.querySelector('.vwshp .vwsh:last-of-type') || {}).textContent);
173
+ ok('K5 the open links list shows it', /Open links \(1\)/.test(await page.evaluate(() => document.querySelector('.vwshp').textContent)), n);
174
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, 'made-1280-light.png') });
175
+ // a guest, in another browser context, with no PMOS session
176
+ const g = await browser.newContext({ viewport: { width: 1000, height: 760 } });
177
+ const gp = await g.newPage();
178
+ await gp.goto(SBASE + new URL(link).pathname);
179
+ ok('K5 the guest sees the password page', /This page is protected/.test(await gp.textContent('body')));
180
+ if (SHOTS) await gp.screenshot({ path: path.join(SHOTS, 'guest-lock.png') });
181
+ await gp.fill('input[name="pw"]', pass);
182
+ await gp.click('button[type="submit"]');
183
+ const fr = await until(async () => { const h = await gp.$('iframe'); const f = h && await h.contentFrame(); return f && /Download and share a file from the viewer/.test(await f.textContent('body').catch(() => '')) ? f : null; }, 8000);
184
+ ok('K5 with the password the guest reads the copy', !!fr);
185
+ if (SHOTS) await gp.screenshot({ path: path.join(SHOTS, 'guest-page.png') });
186
+ await g.close();
187
+ const id = new URL(link).pathname.split('/').pop();
188
+ await page.click(`.vwshp [data-off="${id}"]`);
189
+ const sure = await page.textContent(`.vwshp [data-off="${id}"]`);
190
+ await page.click(`.vwshp [data-off="${id}"]`);
191
+ const gone = await until(() => page.evaluate((x) => !document.querySelector(`.vwshp [data-off="${x}"]`), id), 5000);
192
+ ok('K5 Turn off asks once more, then removes the link', sure === 'Sure? Turn off' && gone && !fs.existsSync(path.join(T.STATE_DIR, 'shares', id)), sure);
193
+ await page.keyboard.press('Escape');
194
+ ok('K5 Escape closes the popover', !(await page.$('.vwshp')));
195
+ ok('K5 no page errors', errors.length === 0, errors.join(' | '));
196
+ await ctx.close();
197
+ }
198
+ for (const [w, h] of [[1280, 900], [390, 844]]) for (const theme of ['light', 'dark']) {
199
+ const { page, ctx } = await open({ w, h, theme });
200
+ await page.click(ICON);
201
+ await until(() => page.evaluate(() => { const i = document.querySelector('.vwshp #vwsPass'); return i && i.value; }), 5000);
202
+ const geo = await page.evaluate(() => { const r = document.querySelector('.vwshp').getBoundingClientRect(); const b = document.querySelector('.vwshp [data-sh="make"]').getBoundingClientRect(); return { l: Math.round(r.left), r: Math.round(r.right), t: Math.round(r.top), b: Math.round(r.bottom), vw: innerWidth, vh: innerHeight, bh: Math.round(b.height), sx: document.documentElement.scrollWidth - innerWidth }; });
203
+ ok(`K5 at ${w} ${theme} the popover fits on screen${w < 700 ? ' as a sheet with 44 px targets' : ''}`, geo.l >= 0 && geo.r <= geo.vw && geo.t >= 0 && geo.b <= geo.vh && geo.sx <= 0 && (w >= 700 || (geo.bh >= 44 && geo.vh - geo.b < 40)), JSON.stringify(geo));
204
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, `popover-${w}-${theme}.png`) });
205
+ await ctx.close();
206
+ }
207
+ return finish();
208
+ })();
@@ -197,3 +197,33 @@
197
197
  iframe.vwprint{position:fixed;right:0;bottom:0;width:1px;height:1px;border:0;opacity:0;pointer-events:none}
198
198
  @media (hover:hover){.vwib:hover{background:var(--well);color:var(--ink)}}
199
199
  @media (max-width:640px){.vwib{width:44px;height:44px}.vwdlm button{min-height:44px}}
200
+ /* the share popover (premium-viewer-share S1, S8, P1): under the icons on a desktop, a sheet at the bottom on a phone */
201
+ .vwshp{position:absolute;right:0;top:calc(100% + 4px);z-index:6;width:340px;max-width:min(340px,calc(100vw - 32px));padding:8px;border-radius:8px;background:var(--card-solid);border:1px solid var(--hair);box-shadow:var(--card-shadow);display:grid;gap:4px;font-size:var(--fs-2);color:var(--ink)}
202
+ .vwshp .i{width:16px;height:16px;flex:none;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round;color:var(--ink-3)}
203
+ .vwsh{font:500 var(--fs-1) var(--mono);letter-spacing:.08em;text-transform:uppercase;color:var(--ink-3);padding:6px 8px 2px}
204
+ .vwsm{display:flex;align-items:center;gap:10px;min-height:40px;padding:6px 8px;border:0;border-radius:6px;background:transparent;color:var(--ink);font:inherit;text-align:left;cursor:pointer}
205
+ .vwsm small{margin-left:auto;font:500 var(--fs-1) var(--mono);color:var(--ink-3)}
206
+ .vwsrow2{display:flex;align-items:center;gap:10px;min-height:40px;padding:2px 8px}.vwsrow2>span{flex:1}
207
+ .vwsw{position:relative;width:40px;height:24px;flex:none;border-radius:6px;border:1px solid var(--hair);background:var(--well);cursor:pointer;padding:0}
208
+ .vwsw::after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:6px;background:var(--ink-3);transition:left .15s}
209
+ .vwsw[aria-checked="true"]{background:var(--ok);border-color:transparent}.vwsw[aria-checked="true"]::after{left:19px;background:var(--card-solid)}
210
+ .vwspwi{display:flex;gap:6px;padding:0 8px}.vwspwi input{flex:1;min-width:0;min-height:34px;padding:0 10px;border-radius:8px;border:1px solid var(--hair);background:var(--well);color:var(--ink);font:500 var(--fs-2) var(--mono)}
211
+ .vwsn{margin:2px 8px;color:var(--ink-3);font-size:var(--fs-1);line-height:1.45}
212
+ .vwserr{margin:2px 8px;color:var(--bad);font-size:var(--fs-1);line-height:1.45}
213
+ .vwsgo{margin:4px 8px 4px;justify-content:center}
214
+ .vwssep{height:1px;background:var(--hair);margin:4px 4px}
215
+ .vwsrow{display:flex;align-items:center;gap:10px;padding:6px 8px}.vwsrow>span{flex:1;min-width:0}
216
+ .vwsrow b{display:block;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.vwsrow em{font-style:normal;color:var(--ink-3);font-size:var(--fs-1)}
217
+ .vwsoff{flex:none;min-height:30px;padding:0 10px;border-radius:6px;border:1px solid var(--hair);background:transparent;color:var(--bad);font:500 var(--fs-1) var(--sans);cursor:pointer}
218
+ .vwslnk{margin:2px 8px 6px;padding:10px;border:1px solid var(--hair);border-radius:8px;display:grid;gap:8px}
219
+ .vwslnk code{font:500 var(--fs-1) var(--mono);overflow-wrap:anywhere;user-select:all}
220
+ .vwspw{display:flex;align-items:center;gap:8px}
221
+ .vwsr{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.vwsok{color:var(--ok);font-size:var(--fs-1)}
222
+ .vwslnk .vwsn{margin:0}
223
+ .vwshp :focus-visible{outline:2px solid var(--ember);outline-offset:2px}
224
+ @media (hover:hover){.vwsm:hover{background:var(--well)}}
225
+ @media (max-width:640px){
226
+ .vwshp{position:fixed;left:8px;right:8px;top:auto;bottom:calc(8px + env(safe-area-inset-bottom,0px));width:auto;max-width:none;max-height:80dvh;overflow:auto;border-radius:8px;z-index:60}
227
+ .vwsm,.vwsrow2,.vwsoff,.vwshp .vwseg,.vwsgo{min-height:44px}.vwsw{width:48px;height:30px}.vwsw::after{width:22px;height:22px}.vwsw[aria-checked="true"]::after{left:23px}
228
+ }
229
+ @media (prefers-reduced-motion:reduce){.vwsw::after{transition:none}}
@@ -5,6 +5,7 @@
5
5
  * changed, so a file Claude is still writing stays current. Nothing here writes.
6
6
  * A download icon sits at the right of the file's title (premium-viewer-share D1-D5): one format saves at once, more open a small menu with the original
7
7
  * first. The original is saved from the text already read; Word comes from GET /api/doc/export; PDF is the browser's print of the page, in a sandboxed frame.
8
+ * A share icon beside it opens the share popover (premium-vw-share.js: Send a copy on a phone, a public link with a password and an end date, open links).
8
9
  * openChatFile(path, { session, ws }) -> the tab's pane */
9
10
  import { vwOpen, vwStyle } from './premium-viewer.js';
10
11
  import { bodyHtml, pageHead, splitDoc, readMinutes } from './premium-vw-doc-model.js';
@@ -41,27 +42,35 @@ export function downloadsOf(f) {
41
42
  return [orig];
42
43
  }
43
44
  const DL_ICON = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v11M7 10l5 5 5-5M5 20h14"/></svg>';
45
+ const SH_ICON = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 15V4M8 8l4-4 4 4M6 12v7h12v-7"/></svg>';
44
46
  /** The title row: the name, and the download icon when the file was read. */
45
47
  function headHtml(f, title) {
46
48
  const n = downloadsOf(f).length;
47
- const dl = n ? `<div class="vwacts"><button type="button" class="vwib" data-fdl aria-label="Download${n > 1 ? '…' : ''}" title="Download"${n > 1 ? ' aria-haspopup="menu" aria-expanded="false"' : ''}>${DL_ICON}</button></div>` : '';
49
+ const dl = n ? `<div class="vwacts"><button type="button" class="vwib" data-fdl aria-label="Download${n > 1 ? '…' : ''}" title="Download"${n > 1 ? ' aria-haspopup="menu" aria-expanded="false"' : ''}>${DL_ICON}</button>`
50
+ + `<button type="button" class="vwib" data-fsh aria-label="Share…" title="Share" aria-haspopup="dialog" aria-expanded="false">${SH_ICON}</button></div>` : '';
48
51
  return `<header class="cfh vwfh"><h1 class="cft">${esc(title)}</h1>${dl}</header>`;
49
52
  }
50
53
  /** The MIME type the original is saved with. */
51
54
  export function mimeOf(f) { return isHtml(f) ? 'text/html' : f.kind === 'markdown' ? 'text/markdown' : 'text/plain'; }
52
- /** The page a PDF is printed from, as the srcdoc of a sandboxed frame: an .html file as it is, markdown as a clean page of its words.
53
- * It prints itself once it has loaded; the frame's CSP still blocks every network fetch. Pure. */
54
- export function printSrc(f) {
55
- const go = '<script>addEventListener("load",function(){setTimeout(function(){print()},150)})<\/script>';
55
+ /** A file as one standalone page, for the print frame and for a share link's copy (premium-viewer-share D3, S2): an .html file as it is, markdown as a
56
+ * clean page of its words, other text in a <pre>. With print, the page prints itself once it has loaded. The viewer's CSP always comes first. Pure. */
57
+ export function pageSrc(f, print = false) {
58
+ const go = print ? '<script>addEventListener("load",function(){setTimeout(function(){print()},150)})<\/script>' : '';
56
59
  if (isHtml(f)) return framedSrc(String(f.text || '') + go);
57
- const h = pageHead(f.text), sd = splitDoc(f.text);
58
- const body = bodyHtml([sd.pre, ...sd.sections.map((x, n) => (n === 0 && h.h1 ? x.body : x.head + '\n' + x.body))].join('\n')).html;
59
- // a plain document for the printer: the browser's own heading sizes and black text, no app colours (the frame cannot load the app's stylesheets)
60
- const css = 'body{font:15px/1.6 -apple-system,"Segoe UI",system-ui,sans-serif;max-width:720px;margin:32px auto;padding:0 24px}'
60
+ const title = f.kind === 'markdown' ? pageHead(f.text).title || f.name : f.name;
61
+ let body;
62
+ if (f.kind === 'markdown') {
63
+ const h = pageHead(f.text), sd = splitDoc(f.text);
64
+ body = `<h1>${esc(title)}</h1>` + bodyHtml([sd.pre, ...sd.sections.map((x, n) => (n === 0 && h.h1 ? x.body : x.head + '\n' + x.body))].join('\n')).html;
65
+ } else body = `<h1>${esc(title)}</h1><pre>${esc(f.text)}</pre>`;
66
+ // a plain document: the browser's own heading sizes and black on white, no app colours (the frame cannot load the app's stylesheets)
67
+ const css = ':root{color-scheme:light}body{font:15px/1.6 -apple-system,"Segoe UI",system-ui,sans-serif;max-width:720px;margin:32px auto;padding:0 24px}'
61
68
  + 'table{border-collapse:collapse;width:100%}th,td{border:1px solid;padding:5px 9px;text-align:left;vertical-align:top}'
62
69
  + 'pre,code{font:13px ui-monospace,Menlo,monospace;white-space:pre-wrap}img{max-width:100%}@page{margin:18mm}';
63
- return framedSrc(`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${esc((h.title || f.name || 'Document').replace(/\.[A-Za-z0-9]+$/, ''))}</title><style>${css}</style></head><body><h1>${esc(h.title || f.name)}</h1>${body}${go}</body></html>`);
70
+ return framedSrc(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(String(title || 'Document').replace(/\.[A-Za-z0-9]+$/, ''))}</title><style>${css}</style></head><body>${body}${go}</body></html>`);
64
71
  }
72
+ /** The page a PDF is printed from, as the srcdoc of a sandboxed frame. Pure. */
73
+ export const printSrc = (f) => pageSrc(f, true);
65
74
  function saveBlob(text, name, type) {
66
75
  const url = URL.createObjectURL(new Blob([text], { type: type + ';charset=utf-8' }));
67
76
  const a = document.createElement('a'); a.href = url; a.download = name; a.hidden = true; document.body.append(a); a.click(); a.remove();
@@ -129,11 +138,14 @@ export function openChatFile(p, ctx = {}) {
129
138
  el.onclick = (e) => {
130
139
  const d = e.target.closest('[data-fdl]');
131
140
  if (d) { const opts = downloadsOf(st.f); if (opts.length === 1) download(st.f, opts[0].fmt); else dlMenu(d, opts); return; }
141
+ const sh = e.target.closest('[data-fsh]');
142
+ if (sh) { const k = sh.parentElement.querySelector('.vmenu'); if (k) k.remove(); import('./premium-vw-share.js').then((M) => M.shareMenu(sh, st.f)); return; }
132
143
  const b = e.target.closest('[data-fv]'); if (!b || b.dataset.fv === st.view) return; st.view = b.dataset.fv; draw();
133
144
  };
134
145
  };
135
146
  const dlMenu = (btn, opts) => {
136
147
  const box = btn.parentElement; let m = box.querySelector('.vmenu');
148
+ const sp = box.querySelector('.vwshp'); if (sp) { sp.remove(); const sb = box.querySelector('[data-fsh]'); if (sb) sb.setAttribute('aria-expanded', 'false'); }
137
149
  const close = (focus) => { const k = box.querySelector('.vmenu'); if (k) k.remove(); btn.setAttribute('aria-expanded', 'false'); if (focus) btn.focus(); };
138
150
  if (m) return close();
139
151
  m = document.createElement('div'); m.className = 'vmenu vwdlm'; m.setAttribute('role', 'menu'); m.setAttribute('aria-label', 'Download as'); m.dataset.escLayer = '1';
@@ -0,0 +1,112 @@
1
+ /* pm/premium-vw-share.js — the share icon's popover on a file in the viewer (premium-viewer-share S1-S9, P1; PM 2026-10-21: "I should be able to download
2
+ * or share (no need login to cloudflare, but I can set password)"). It opens under the icon (a sheet at the bottom on a phone) and holds:
3
+ * Send a copy on a device that can share files (a phone), the system share sheet with the file attached. No link is made.
4
+ * Public link Password (on, a generated one the PM can change), Ends (1, 7 or 30 days; 7), Create link. A copy of the file as it is now goes to
5
+ * the share copies folder through POST /api/shares; the share server (share-server.js, D97) serves it. Nothing is public before the press.
6
+ * Open links every open link with its end date and views, and Turn off (a second press confirms). Turn off deletes the copy at once.
7
+ * Reads GET /api/shares and GET /api/shares/password; writes only through the two page-press routes.
8
+ * shareMenu(btn, f) f is the file tab's record: { name, ws, rel, kind, text } */
9
+ import { pmGet, pmPost } from './http.js';
10
+
11
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
12
+ const day = (iso) => { try { return new Date(iso).toLocaleDateString(undefined, { day: 'numeric', month: 'short' }); } catch { return ''; } };
13
+ const LOCK = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>';
14
+ const LINK = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/></svg>';
15
+ const SEND = '<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 12l16-8-6 16-2-7z"/></svg>';
16
+
17
+ /** Whether this device can hand a file to the system share sheet (a phone, mostly). */
18
+ export function canSendFile(f) {
19
+ try { return typeof navigator !== 'undefined' && !!navigator.share && !!navigator.canShare && navigator.canShare({ files: [new File([f.text || ''], f.name || 'file.txt', { type: 'text/plain' })] }); }
20
+ catch { return false; }
21
+ }
22
+
23
+ /** The popover's inside as HTML. Pure. S = { pw, pass, days, made, err, busy, list, host, off, send } */
24
+ export function shareHtml(S) {
25
+ const send = S.send ? `<button type="button" class="vwsm" data-sh="send">${SEND}<span>Send a copy</span><small>share sheet</small></button><div class="vwssep"></div>` : '';
26
+ const list = S.list && S.list.length
27
+ ? `<div class="vwsh">Open links (${S.list.length})</div>` + S.list.map((x) => `<div class="vwsrow">${x.pw ? LOCK : LINK}<span><b>${esc(x.name)}</b><em>Ends ${esc(day(x.ends))} · ${x.views ? x.views + (x.views === 1 ? ' view' : ' views') : 'not opened yet'}</em></span>`
28
+ + `<button type="button" class="vwsoff" data-off="${esc(x.id)}">${S.off === x.id ? 'Sure? Turn off' : 'Turn off'}</button></div>`).join('')
29
+ : '';
30
+ if (S.made) {
31
+ return send + `<div class="vwsh">Link ready</div><div class="vwslnk"><code class="vwsu">${esc(S.made.url)}</code>`
32
+ + (S.made.pass ? `<div class="vwspw">${LOCK}<code>${esc(S.made.pass)}</code></div>` : '')
33
+ + `<div class="vwsr"><button type="button" class="vwbtn pri" data-sh="copy">${S.made.pass ? 'Copy link and password' : 'Copy link'}</button><span class="vwsok" role="status">${esc(S.copied || '')}</span></div>`
34
+ + `<p class="vwsn">Ends ${esc(day(S.made.ends))}.${S.made.pass ? ' Send the password in a different message.' : ''}</p></div>`
35
+ + (list ? '<div class="vwssep"></div>' + list : '');
36
+ }
37
+ return send + `<div class="vwsh">Public link</div>`
38
+ + `<div class="vwsrow2">${LOCK}<span>Password</span><button type="button" class="vwsw" role="switch" aria-checked="${S.pw}" aria-label="Password" data-sh="pw"></button></div>`
39
+ + (S.pw ? `<div class="vwspwi"><input id="vwsPass" type="text" spellcheck="false" autocomplete="off" aria-label="Password" value="${esc(S.pass)}"><button type="button" class="vwbtn" data-sh="new">New</button></div>` : '')
40
+ + `<div class="vwsrow2"><span>Ends</span><div class="vwsg" role="group" aria-label="Link ends after">${[1, 7, 30].map((d) => `<button type="button" class="vwseg" data-days="${d}" aria-pressed="${S.days === d}">${d === 1 ? '1 day' : d + ' days'}</button>`).join('')}</div></div>`
41
+ + `<p class="vwsn">Anyone with the link${S.pw ? ' and the password' : ''} can read a copy of this file as it is now. Later edits are not shared.</p>`
42
+ + (S.err ? `<p class="vwserr" role="alert">${esc(S.err)}</p>` : '')
43
+ + `<button type="button" class="vwbtn pri vwsgo" data-sh="make"${S.busy ? ' disabled' : ''}>${S.busy ? 'Making the link…' : 'Create link'}</button>`
44
+ + (list ? '<div class="vwssep"></div>' + list : '');
45
+ }
46
+
47
+ export function shareMenu(btn, f) {
48
+ const box = btn.parentElement;
49
+ const old = box.querySelector('.vwshp');
50
+ const close = (focus) => { const k = box.querySelector('.vwshp'); if (k) k.remove(); btn.setAttribute('aria-expanded', 'false'); if (focus) btn.focus(); };
51
+ if (old) return close();
52
+ // Escape closes the popover wherever the focus is (a press redraws it), before the dialog under it sees the key
53
+ const onKey = (e) => { if (e.key !== 'Escape') return; document.removeEventListener('keydown', onKey, true); if (!m.isConnected) return; e.stopPropagation(); close(true); };
54
+ box.querySelectorAll('.vmenu').forEach((m) => m.remove());
55
+ const S = { pw: true, pass: '', days: 7, made: null, err: '', busy: false, list: [], host: null, off: null, send: canSendFile(f), copied: '' };
56
+ const m = document.createElement('div');
57
+ m.className = 'vwshp'; m.setAttribute('role', 'dialog'); m.setAttribute('aria-label', 'Share ' + (f.name || 'this file')); m.dataset.escLayer = '1';
58
+ const draw = (focus) => {
59
+ m.innerHTML = shareHtml(S);
60
+ const f2 = focus && m.querySelector(focus); if (f2) f2.focus();
61
+ };
62
+ const load = async () => {
63
+ const [l, p] = await Promise.all([pmGet('/api/shares'), S.pass ? null : pmGet('/api/shares/password')]);
64
+ if (l && l.ok) { S.list = l.shares || []; S.host = l.host; }
65
+ const typed = m.querySelector('#vwsPass');
66
+ if (typed && typed.value) S.pass = typed.value; // the PM typed before the generated one arrived
67
+ else if (p && p.ok && !S.pass) S.pass = p.password;
68
+ if (m.isConnected) draw(document.activeElement && m.contains(document.activeElement) && document.activeElement.dataset.sh ? `[data-sh="${document.activeElement.dataset.sh}"]` : null);
69
+ };
70
+ m.onclick = async (e) => {
71
+ e.stopPropagation();
72
+ const b = e.target.closest('button'); if (!b) return;
73
+ const pass = m.querySelector('#vwsPass'); if (pass) S.pass = pass.value;
74
+ if (b.dataset.days) { S.days = Number(b.dataset.days); return draw(`[data-days="${S.days}"]`); }
75
+ if (b.dataset.off) {
76
+ if (S.off !== b.dataset.off) { S.off = b.dataset.off; return draw(`[data-off="${S.off}"]`); }
77
+ const r = await pmPost('/api/shares/off', { id: b.dataset.off });
78
+ S.off = null; if (r && r.ok) S.list = S.list.filter((x) => x.id !== b.dataset.off); else S.err = (r && r.error) || 'The link could not be turned off.';
79
+ return draw();
80
+ }
81
+ const k = b.dataset.sh;
82
+ if (k === 'pw') { S.pw = !S.pw; return draw('[data-sh="pw"]'); }
83
+ if (k === 'new') { const p = await pmGet('/api/shares/password'); if (p && p.ok) S.pass = p.password; return draw('[data-sh="new"]'); }
84
+ if (k === 'send') {
85
+ try { await navigator.share({ files: [new File([f.text || ''], f.name || 'file.txt', { type: 'text/plain' })], title: f.name }); close(true); }
86
+ catch { /* the PM closed the share sheet */ }
87
+ return;
88
+ }
89
+ if (k === 'make') {
90
+ if (S.pw && String(S.pass || '').trim().length < 8) { S.err = 'The password needs at least 8 characters.'; return draw(); }
91
+ S.busy = true; S.err = ''; draw();
92
+ const r = await pmPost('/api/shares', { ws: f.ws, path: f.rel, days: S.days, password: S.pw ? String(S.pass).trim() : null });
93
+ S.busy = false;
94
+ if (!r || !r.ok) { S.err = (r && r.error) || 'The link could not be made.'; return draw(); }
95
+ S.made = { url: r.url, ends: r.ends, pass: S.pw ? String(S.pass).trim() : '' };
96
+ const l = await pmGet('/api/shares'); if (l && l.ok) S.list = l.shares || [];
97
+ return draw('[data-sh="copy"]');
98
+ }
99
+ if (k === 'copy') {
100
+ const t = S.made.url + (S.made.pass ? '\nPassword: ' + S.made.pass : '');
101
+ try { await navigator.clipboard.writeText(t); S.copied = 'Copied'; }
102
+ catch { const c = m.querySelector('.vwsu'); if (c) { const r = document.createRange(); r.selectNodeContents(c); getSelection().removeAllRanges(); getSelection().addRange(r); } S.copied = 'Press Copy on your keyboard'; }
103
+ return draw('[data-sh="copy"]');
104
+ }
105
+ };
106
+ document.addEventListener('keydown', onKey, true);
107
+ draw();
108
+ box.append(m); btn.setAttribute('aria-expanded', 'true');
109
+ const first = m.querySelector('button'); if (first) first.focus();
110
+ setTimeout(() => document.addEventListener('click', function off(e) { if (!e.target.closest('.vwshp,[data-fsh]')) close(); if (!box.querySelector('.vwshp')) document.removeEventListener('click', off, true); }, true), 0);
111
+ load();
112
+ }
@@ -342,6 +342,32 @@ const accessKeys = require('./lib/access-keys');
342
342
  const ONLINE = { settings: onlineMode.read(STATE), keys: null, keysTeam: null, fetchKeys: accessKeys.fetchCerts, find: onlineMode.findCloudflared,
343
343
  lastRefusal: null }; // { reason, at } of the last refused sign-in: a fixed reason word only, never the assertion or a claim (D08)
344
344
  const tunnel = onlineMode.createTunnel({ stateDir: STATE, find: () => ONLINE.find() });
345
+ // premium-viewer-share (D97): share links are served by share-server.js, a separate process on its own loopback port that reads only the
346
+ // share copies folder. This server starts it, restarts it when it exits, and stops it with itself. It answers the internet only when the PM's
347
+ // tunnel sends the share hostname to SHARE_PORT; the workspace's own hostname and its Access check are unchanged.
348
+ const shareStore = require('./lib/share-store');
349
+ const SHARE_PORT = Number(process.env.PMOS_SHARE_PORT) || (PORT + 1);
350
+ const SHARE = { child: null, stopped: false, timer: null };
351
+ function startShareServer() {
352
+ if (SHARE.child || SHARE.stopped || process.env.PMOS_SHARE_SERVER === 'off') return;
353
+ try {
354
+ SHARE.child = require('child_process').spawn(process.execPath, [path.join(__dirname, 'share-server.js')],
355
+ { stdio: 'ignore', env: { PATH: process.env.PATH || '', PMOS_STATE_DIR: STATE, PMOS_SHARE_PORT: String(SHARE_PORT), PMOS_SHARE_PARENT: String(process.pid) } });
356
+ } catch { SHARE.child = null; return; }
357
+ const mine = SHARE.child;
358
+ mine.on('error', () => {});
359
+ mine.on('exit', () => { if (SHARE.child !== mine) return; SHARE.child = null; if (!SHARE.stopped && !SHARE.timer) { SHARE.timer = setTimeout(() => { SHARE.timer = null; startShareServer(); }, 5000); if (SHARE.timer.unref) SHARE.timer.unref(); } });
360
+ }
361
+ function stopShareServer() { SHARE.stopped = true; if (SHARE.timer) clearTimeout(SHARE.timer); const c = SHARE.child; SHARE.child = null; if (c) { try { c.kill('SIGTERM'); } catch { /* gone */ } } }
362
+ /** The hostname a share link names: PMOS_SHARE_HOST, else share.<the Online hostname's domain>, else null (Online is not set up). */
363
+ function shareHost() {
364
+ const env = String(process.env.PMOS_SHARE_HOST || '').trim().toLowerCase();
365
+ if (env) return remoteAccess.parsePublicHost(env).refused ? null : env;
366
+ const h = ONLINE.settings.host;
367
+ if (!h) return null;
368
+ const parts = h.split('.');
369
+ return 'share.' + (parts.length > 2 ? parts.slice(1).join('.') : h);
370
+ }
345
371
  /** The public hostname the guards admit right now: the environment's, else the Online switch's while it is on. */
346
372
  function publicHost() { return BIND.publicHost || (ONLINE.settings.on ? ONLINE.settings.host : null); }
347
373
  /** True when this request is addressed to the Online switch's hostname, so the Access assertion decides it (D89). */
@@ -7527,6 +7553,43 @@ async function handleRequest(req, res) {
7527
7553
  const r = chatFileLocate.locate({ path: url.searchParams.get('path') || '', roots: [...workspaces.values()].map((w) => ({ id: w.id, root: w.root })), base: base ? base.id : null, home: os.homedir() });
7528
7554
  return json(res, r);
7529
7555
  }
7556
+ /* ── premium-viewer-share (D97): share links. Listing is a read; making and turning off a link is a page press, never an agent session. ── */
7557
+ if (p === '/api/shares' && req.method === 'GET') {
7558
+ const host = shareHost();
7559
+ return json(res, { ok: true, host, days: shareStore.DAYS, shares: shareStore.list(STATE).map((x) => ({ ...x, url: host ? `https://${host}/s/${x.id}` : null })) });
7560
+ }
7561
+ if (p === '/api/shares/password' && req.method === 'GET') return json(res, { ok: true, password: shareStore.newPassword() });
7562
+ if ((p === '/api/shares' || p === '/api/shares/off') && req.method === 'POST') {
7563
+ if (req.headers['x-pmos-session']) return json(res, { ok: false, error: 'An agent session cannot make or turn off a share link. Only a press on the page does.' }, 403);
7564
+ let body = {};
7565
+ try { body = JSON.parse((await readBody(req)) || '{}'); } catch { return json(res, { ok: false, error: 'invalid JSON body' }, 400); }
7566
+ const g = pmGuard.requirePagePress(req, body);
7567
+ if (!g.ok) return json(res, { ok: false, error: g.error }, g.status);
7568
+ if (p === '/api/shares/off') {
7569
+ const id = String(body.id || '');
7570
+ if (!shareStore.ID_RX.test(id)) return json(res, { ok: false, error: 'no such link' }, 404);
7571
+ shareStore.remove(STATE, id);
7572
+ return json(res, { ok: true });
7573
+ }
7574
+ const host = shareHost();
7575
+ if (!host) return json(res, { ok: false, error: 'Share links use your Online hostname. Set up Online in Settings first, or set PMOS_SHARE_HOST.' }, 409);
7576
+ const w = getWs(body.ws);
7577
+ const rel = String(body.path || '');
7578
+ const got = w ? readTextDocWhy(w.root, rel) : { ok: false, reason: 'no such workspace' };
7579
+ if (!got.ok) return json(res, { ok: false, error: got.reason }, 404);
7580
+ // the local secret scan first: a key or token in the file blocks the link, and the answer names the rule, never the text (D08)
7581
+ const hits = require('./lib/secret-scan').scan(got.text);
7582
+ if (hits.length) return json(res, { ok: false, error: 'This file holds what looks like a secret (' + hits.join(', ') + '). Remove it, then share again.', secrets: hits }, 422);
7583
+ const name = path.basename(rel);
7584
+ const kind = got.kind === 'html' ? 'html' : got.kind === 'markdown' ? 'markdown' : 'text';
7585
+ let page;
7586
+ try { const F = await import('./public/pm/premium-vw-file.js'); page = kind === 'html' ? got.text : F.pageSrc({ name, kind, text: got.text }); }
7587
+ catch { return json(res, { ok: false, error: 'The copy could not be made.' }, 500); }
7588
+ const r = shareStore.create(STATE, { name, kind, page, file: got.text, days: Number(body.days), password: body.password == null || body.password === '' ? null : String(body.password) });
7589
+ if (!r.ok) return json(res, { ok: false, error: r.error }, 400);
7590
+ startShareServer();
7591
+ return json(res, { ok: true, id: r.id, ends: r.ends, url: `https://${host}/s/${r.id}` });
7592
+ }
7530
7593
  if (p === '/api/doc/export') {
7531
7594
  // A markdown file from the viewer's download menu as Word (premium-viewer-share D4). The same guard as GET /api/doc
7532
7595
  // (readTextDocWhy: inside the workspace, text only), built in memory by lib/report-export.js. It writes nothing and is never cached.
@@ -10124,6 +10187,7 @@ if (require.main === module) {
10124
10187
  for (const s of sessions.values()) if (s.pty) { try { persist(s); } catch {} }
10125
10188
  for (const l of listeners) { try { l.close(); } catch {} }
10126
10189
  try { tunnel.stop(); } catch {} // workspace-online-mode: the tunnel is this server's child and ends with it
10190
+ try { stopShareServer(); } catch {} // premium-viewer-share: so is the share server
10127
10191
  try { fs.unlinkSync(PID_FILE); } catch {} // stop being discoverable the moment we stop serving
10128
10192
  try { scheduleOwner.release(); } catch {} // another server can run the schedules at once
10129
10193
  process.exit(0);
@@ -10159,6 +10223,7 @@ if (require.main === module) {
10159
10223
  for (const line of remoteAccess.startupLines(BIND, PORT, { ansi: !!process.stdout.isTTY && !process.env.NO_COLOR })) console.log(line);
10160
10224
  // workspace-online-mode: a workspace that stopped while Online was on comes back online (PRD O2)
10161
10225
  applyOnline();
10226
+ if (shareStore.list(STATE).length) startShareServer(); // premium-viewer-share (D97): the share links' own server, on loopback, only while a link is open
10162
10227
  if (ONLINE.settings.on && !BIND.publicHost) console.log(` online: https://${ONLINE.settings.host}/ (Cloudflare Access sign-in, tunnel ${ONLINE.settings.tunnel})`);
10163
10228
  // bring in what another machine pushed while this one was off (D70 as amended); never on the request path
10164
10229
  { const t = setTimeout(() => { autoSync.startup().catch(() => {}); }, 3000); if (t.unref) t.unref(); }
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* share-server.js — the one PMOS server that answers someone with no PMOS login (premium-viewer-share slice 2, D97).
4
+ *
5
+ * It is a separate process from the workspace server, on its own loopback port, and it knows nothing of the workspace: no terminal, no
6
+ * API, no WebSocket, no repository, no token, no settings. It reads only the share copies folder (lib/share-store.js) and writes only a
7
+ * link's view count and wrong-password count there. The workspace server starts it and stops it. The PM's Cloudflare tunnel sends the
8
+ * share hostname (share.pm-os.app) here, with no Access application in front; the workspace hostname keeps its Access check.
9
+ *
10
+ * GET /robots.txt Disallow: /
11
+ * GET /s/<id> the password page, or the copy in a sandboxed frame with Download
12
+ * POST /s/<id> the password form (pw=…): a right password sets a cookie for this link only, for 12 hours
13
+ * GET /s/<id>/view the copy itself, under a sandbox CSP (only with a valid cookie when the link has a password)
14
+ * GET /s/<id>/file the file's own text as an attachment (the same rule)
15
+ * anything else 404
16
+ *
17
+ * Every answer: X-Robots-Tag noindex, Cache-Control no-store, Referrer-Policy no-referrer, nosniff, frame-ancestors limited. An unknown,
18
+ * ended or turned-off link reads "This link is no longer active" and names nothing. Nothing is logged (D08).
19
+ *
20
+ * PMOS_SHARE_PORT the port (required) PMOS_STATE_DIR the runtime state folder that holds shares/
21
+ * PMOS_SHARE_PARENT the workspace server's pid: the share server exits when that process is gone
22
+ */
23
+ const http = require('http');
24
+ const store = require('./lib/share-store');
25
+
26
+ const DIR = process.env.PMOS_STATE_DIR;
27
+ const PORT = Number(process.env.PMOS_SHARE_PORT);
28
+ const HOST = '127.0.0.1';
29
+
30
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
31
+ const BASE_HEADERS = {
32
+ 'X-Robots-Tag': 'noindex, nofollow, noarchive', 'Cache-Control': 'no-store, private', 'Referrer-Policy': 'no-referrer',
33
+ 'X-Content-Type-Options': 'nosniff', 'Cross-Origin-Opener-Policy': 'same-origin', 'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',
34
+ };
35
+ const PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; frame-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'";
36
+ // the copy itself: the viewer's own sandbox (premium-vw-file.js FRAME_CSP), shown only inside its own page
37
+ const VIEW_CSP = (scripts) => `sandbox${scripts ? ' allow-scripts' : ''}; default-src 'none'; img-src data:; style-src 'unsafe-inline'; font-src data:; script-src ${scripts ? "'unsafe-inline'" : "'none'"}; frame-ancestors 'self'; base-uri 'none'; form-action 'none'`;
38
+
39
+ function send(res, status, body, headers = {}) {
40
+ res.writeHead(status, { ...BASE_HEADERS, 'Content-Type': 'text/html; charset=utf-8', 'Content-Security-Policy': PAGE_CSP, 'X-Frame-Options': 'DENY', ...headers });
41
+ res.end(body);
42
+ }
43
+ const STYLE = `<style>:root{color-scheme:light dark;--bg:#f6f6f4;--card:#fff;--ink:#14161f;--mut:#6e7486;--hair:rgba(20,24,40,.12);--solid:#14161f;--on:#fff;--bad:#be3434}
44
+ @media (prefers-color-scheme:dark){:root{--bg:#0e1016;--card:#171a23;--ink:#f3f4f8;--mut:#9aa0b4;--hair:rgba(255,255,255,.12);--solid:#f3f4f8;--on:#14161f;--bad:#f06e6e}}
45
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 -apple-system,"Segoe UI",system-ui,sans-serif}
46
+ .box{max-width:340px;margin:18vh auto 0;padding:0 16px;text-align:center}h1{font-size:20px;margin:0 0 6px}p{color:var(--mut);margin:0 0 16px}
47
+ input{width:100%;font:inherit;padding:11px 12px;border-radius:12px;border:1px solid var(--hair);background:var(--card);color:var(--ink);margin:0 0 10px}
48
+ button,.btn{display:inline-block;width:100%;font:600 15px/1 inherit;padding:12px;border:0;border-radius:99px;background:var(--solid);color:var(--on);cursor:pointer;text-decoration:none}
49
+ .bad{color:var(--bad)}.wrap{display:flex;flex-direction:column;height:100vh;height:100dvh}iframe{flex:1;width:100%;border:0;background:#fff}
50
+ .bar{display:flex;gap:12px;align-items:center;padding:10px max(16px,env(safe-area-inset-left));border-top:1px solid var(--hair);font-size:13px;color:var(--mut);background:var(--card)}
51
+ .bar span{flex:1;min-width:0}.bar .btn{width:auto;padding:9px 16px;font-size:13px}</style>`;
52
+ const doc = (title, body) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow,noarchive"><title>${esc(title)}</title>${STYLE}</head><body>${body}</body></html>`;
53
+ const gone = (res) => send(res, 404, doc('Link not active', '<div class="box"><h1>This link is no longer active</h1><p>Ask the person who sent it for a new one.</p></div>'));
54
+ const day = (iso) => new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' });
55
+ function lockPage(res, id, note, status = 200) {
56
+ // the password page names neither PMOS nor the file, so a link preview or a stranger learns nothing from it
57
+ send(res, status, doc('Protected page', `<div class="box"><h1>This page is protected</h1><p${note ? ' class="bad"' : ''}>${esc(note || 'Enter the password you were given.')}</p>`
58
+ + `<form method="post" action="/s/${esc(id)}"><input type="password" name="pw" autocomplete="current-password" aria-label="Password" placeholder="Password" required autofocus><button type="submit">Open</button></form></div>`));
59
+ }
60
+ function cookieOf(req) {
61
+ const m = /(?:^|;\s*)s=([^;]+)/.exec(String(req.headers.cookie || ''));
62
+ return m ? decodeURIComponent(m[1]) : '';
63
+ }
64
+ function readForm(req) {
65
+ return new Promise((resolve) => {
66
+ let n = 0; const parts = [];
67
+ req.on('data', (c) => { n += c.length; if (n > 2048) { req.destroy(); resolve(null); } else parts.push(c); });
68
+ req.on('end', () => { try { resolve(new URLSearchParams(Buffer.concat(parts).toString('utf8'))); } catch { resolve(null); } });
69
+ req.on('error', () => resolve(null));
70
+ });
71
+ }
72
+
73
+ async function handle(req, res) {
74
+ let url;
75
+ try { url = new URL(req.url, 'http://share.invalid'); } catch { return send(res, 400, doc('Bad request', '')); }
76
+ const p = url.pathname;
77
+ if (req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'POST') return send(res, 405, doc('Not allowed', ''), { Allow: 'GET, POST' });
78
+ if (p === '/robots.txt' && req.method !== 'POST') { res.writeHead(200, { ...BASE_HEADERS, 'Content-Type': 'text/plain; charset=utf-8' }); return res.end('User-agent: *\nDisallow: /\n'); }
79
+ const m = /^\/s\/([A-Za-z0-9_-]{22})(\/view|\/file)?$/.exec(p);
80
+ if (!m) return send(res, 404, doc('Not found', '<div class="box"><h1>Not found</h1></div>'));
81
+ const id = m[1], part = m[2] || '';
82
+ const now = Date.now();
83
+ const meta = store.get(DIR, id, now);
84
+ if (!meta) return gone(res);
85
+ const open = !meta.pw || store.verifyCookie(meta, cookieOf(req), now);
86
+
87
+ if (req.method === 'POST') {
88
+ if (part) return send(res, 405, doc('Not allowed', ''));
89
+ if (!meta.pw) { res.writeHead(303, { ...BASE_HEADERS, Location: '/s/' + id }); return res.end(); }
90
+ const form = await readForm(req);
91
+ const r = store.checkPassword(DIR, id, form ? form.get('pw') : '', now);
92
+ if (r.ok) {
93
+ const until = now + store.COOKIE_MS;
94
+ res.writeHead(303, { ...BASE_HEADERS, Location: '/s/' + id,
95
+ 'Set-Cookie': `s=${encodeURIComponent(store.sign(meta, until))}; Path=/s/${id}; Max-Age=${store.COOKIE_MS / 1000}; HttpOnly; Secure; SameSite=Lax` });
96
+ return res.end();
97
+ }
98
+ if (r.locked) return lockPage(res, id, 'Too many wrong tries. Try again in 15 minutes.', 429);
99
+ return lockPage(res, id, `That password is not right. ${r.left} ${r.left === 1 ? 'try' : 'tries'} left before a 15-minute wait.`, 401);
100
+ }
101
+ if (!open) return part ? gone(res) : lockPage(res, id);
102
+ if (part === '/view') {
103
+ const page = store.readPart(DIR, id, 'page.html');
104
+ if (page == null) return gone(res);
105
+ res.writeHead(200, { ...BASE_HEADERS, 'Content-Type': 'text/html; charset=utf-8', 'Content-Security-Policy': VIEW_CSP(meta.kind === 'html'), 'X-Frame-Options': 'SAMEORIGIN' });
106
+ return res.end(req.method === 'HEAD' ? undefined : page);
107
+ }
108
+ if (part === '/file') {
109
+ const text = store.readPart(DIR, id, 'file');
110
+ if (text == null) return gone(res);
111
+ const name = meta.name.replace(/[^A-Za-z0-9._-]+/g, '-').slice(0, 120) || 'file.txt';
112
+ res.writeHead(200, { ...BASE_HEADERS, 'Content-Type': 'application/octet-stream', 'Content-Disposition': `attachment; filename="${name}"`, 'Content-Security-Policy': "default-src 'none'; sandbox" });
113
+ return res.end(req.method === 'HEAD' ? undefined : text);
114
+ }
115
+ if (req.method === 'GET') store.view(DIR, id, now);
116
+ return send(res, 200, doc(meta.name, `<div class="wrap"><iframe src="/s/${esc(id)}/view" title="${esc(meta.name)}" sandbox="${meta.kind === 'html' ? 'allow-scripts' : ''}" referrerpolicy="no-referrer"></iframe>`
117
+ + `<div class="bar"><span>A shared copy, made ${esc(day(meta.made))}. The link ends ${esc(day(meta.ends))}.</span><a class="btn" href="/s/${esc(id)}/file" download>Download</a></div></div>`));
118
+ }
119
+
120
+ function start({ port = PORT, host = HOST } = {}) {
121
+ const server = http.createServer((req, res) => { handle(req, res).catch(() => { try { send(res, 500, doc('Error', '')); } catch { /* the socket is gone */ } }); });
122
+ server.listen(port, host);
123
+ return server;
124
+ }
125
+
126
+ if (require.main === module) {
127
+ if (!DIR || !(PORT > 0)) { console.error('share-server: PMOS_STATE_DIR and PMOS_SHARE_PORT are required'); process.exit(2); }
128
+ const s = start();
129
+ s.on('error', (e) => { console.error('share-server: ' + (e.code === 'EADDRINUSE' ? `port ${PORT} is in use` : 'could not listen')); process.exit(1); });
130
+ process.on('SIGTERM', () => { s.close(); process.exit(0); });
131
+ // it lives only as long as the workspace server that started it: a parent killed without a goodbye leaves no share server behind
132
+ const parent = Number(process.env.PMOS_SHARE_PARENT);
133
+ if (parent > 0) setInterval(() => { try { process.kill(parent, 0); } catch { process.exit(0); } }, 5000).unref();
134
+ }
135
+ module.exports = { start, handle, VIEW_CSP, PAGE_CSP };
@@ -1,9 +1,11 @@
1
1
  {
2
- "_comment": "A file in the viewer has a download icon (premium-viewer-share slice 1): HTML or PDF for an .html file, Markdown, Word or PDF for a note, the original for other text; GET /api/doc/export builds Word. Real server, 390 and 1280 wide.",
2
+ "_comment": "Download and share a file from the viewer (premium-viewer-share): the download icon and GET /api/doc/export; share links through lib/share-store.js, POST /api/shares and share-server.js (D97), with the guest's password page. Real server, 390 and 1280 wide.",
3
3
  "seconds": {
4
- "premium-viewer-download-test.js": 30
4
+ "premium-viewer-download-test.js": 30,
5
+ "premium-viewer-share-test.js": 40
5
6
  },
6
7
  "panels": [
7
- "premium-viewer-download-test.js"
8
+ "premium-viewer-download-test.js",
9
+ "premium-viewer-share-test.js"
8
10
  ]
9
11
  }