shapewall 0.0.0-stage → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +139 -0
- package/Dockerfile.agent +45 -0
- package/LICENSE +202 -0
- package/NOTICE +12 -0
- package/README.md +651 -2
- package/THIRD_PARTY.md +165 -0
- package/bin/shapewall.js +29 -0
- package/dist/agent/package-lock.json +8384 -0
- package/dist/client/assets/BoardChat-D5SFd8HE.js +28 -0
- package/dist/client/assets/BuzzDialog-HWXBy52W.js +1 -0
- package/dist/client/assets/ChecksPanel-DTdImWoD.js +1 -0
- package/dist/client/assets/History-CEv6b-av.js +1 -0
- package/dist/client/assets/LocalSettings-C4vriEVQ.js +1 -0
- package/dist/client/assets/Management-DCfhcEUY.js +1 -0
- package/dist/client/assets/QuickConnect-DQGgUsl1.js +1 -0
- package/dist/client/assets/ShareDialog-C_plIto0.js +2 -0
- package/dist/client/assets/app-update-dialog-2hPz_N9G.js +1 -0
- package/dist/client/assets/circle-x-BZMPi8Zf.js +1 -0
- package/dist/client/assets/index-ByQRKVit.css +2 -0
- package/dist/client/assets/index-DweQ8Qtu.js +29 -0
- package/dist/client/assets/refresh-cw-CRow0Nbq.js +1 -0
- package/dist/client/assets/runtime-Bft6x_6E.js +4 -0
- package/dist/client/assets/square-A8EnIYLR.js +1 -0
- package/dist/client/assets/tts-dist-DYlBQmwG.js +18 -0
- package/dist/client/assets/tts-en-g2p-BPUtBFGG.js +1 -0
- package/dist/client/assets/tts-ort-wasm-simd-threaded-qh98TCA_.wasm +0 -0
- package/dist/client/assets/tts-ort.wasm.bundle.min-rEkcs_ow.js +12 -0
- package/dist/client/assets/tts-rolldown-runtime-D8NudN84.js +1 -0
- package/dist/client/assets/tts-spacy-en-tokenizer-6SNMl--A.json +1 -0
- package/dist/client/assets/tts-tts.worker-Bzm6aWbv.js +1 -0
- package/dist/client/assets/tts-us_gold-DcjeNMH1.json +92589 -0
- package/dist/client/assets/tts-us_silver-C964mEB5.json +93363 -0
- package/dist/client/assets/ui-CLbws0rx.js +41 -0
- package/dist/client/build-info.json +1 -0
- package/dist/client/favicon.svg +7 -0
- package/dist/client/icons/apple-touch-icon.png +0 -0
- package/dist/client/icons/icon-192.png +0 -0
- package/dist/client/icons/icon-512.png +0 -0
- package/dist/client/icons/maskable-512.png +0 -0
- package/dist/client/index.html +25 -0
- package/dist/client/manifest.webmanifest +15 -0
- package/dist/client/sw.js +53 -0
- package/dist/client/theme-boot.js +27 -0
- package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +1 -0
- package/dist/console/assets/LocalConsole-Bb2FUDs7.js +1 -0
- package/dist/console/assets/app-update-dialog-DIeYepLZ.js +1 -0
- package/dist/console/assets/console-C7uJLLOn.js +51 -0
- package/dist/console/assets/console-R8IBY3Am.css +2 -0
- package/dist/console/build-info.json +1 -0
- package/dist/console/console.html +21 -0
- package/dist/console/favicon.svg +7 -0
- package/dist/console/icons/apple-touch-icon.png +0 -0
- package/dist/console/icons/icon-192.png +0 -0
- package/dist/console/icons/icon-512.png +0 -0
- package/dist/console/icons/maskable-512.png +0 -0
- package/dist/console/manifest.webmanifest +15 -0
- package/dist/console/theme-boot.js +27 -0
- package/docs/agent-hardening.md +342 -0
- package/docs/agent-recipes.md +187 -0
- package/docs/agent-workflow.md +320 -0
- package/docs/agents.md +894 -0
- package/docs/architecture.md +242 -0
- package/docs/buzz.md +140 -0
- package/docs/capture-warnings.md +57 -0
- package/docs/config.md +489 -0
- package/docs/deployment.md +289 -0
- package/docs/design-system.md +162 -0
- package/docs/github.md +107 -0
- package/docs/hosted.md +764 -0
- package/docs/images/board-overview.png +0 -0
- package/docs/images/journeys.png +0 -0
- package/docs/images/live-comment.png +0 -0
- package/docs/images/phone-comment.png +0 -0
- package/docs/images/phone-overview.png +0 -0
- package/docs/images/variant.png +0 -0
- package/docs/interaction-audits.md +40 -0
- package/docs/journeys.md +137 -0
- package/docs/local-accounts.md +80 -0
- package/docs/notifications.md +237 -0
- package/docs/page-checks.md +69 -0
- package/docs/performance.md +174 -0
- package/docs/starter-agent.md +325 -0
- package/docs/updates.md +87 -0
- package/examples/audits/interaction.audit.json +17 -0
- package/package.json +132 -4
- package/src/accounts/avatar.js +121 -0
- package/src/accounts/local.js +464 -0
- package/src/agent/acp/command.js +204 -0
- package/src/agent/acp/detect.js +75 -0
- package/src/agent/acp/sandbox.js +160 -0
- package/src/agent/agent-health.js +75 -0
- package/src/agent/backends/acp.js +1297 -0
- package/src/agent/backends/index.js +61 -0
- package/src/agent/backends/openai.js +308 -0
- package/src/agent/composer.js +221 -0
- package/src/agent/config.js +338 -0
- package/src/agent/context.js +191 -0
- package/src/agent/control.js +122 -0
- package/src/agent/errors.js +17 -0
- package/src/agent/feedback-loop.js +137 -0
- package/src/agent/manage.js +94 -0
- package/src/agent/next-steps.js +51 -0
- package/src/agent/owner-mcp.js +38 -0
- package/src/agent/plain-text.js +52 -0
- package/src/agent/ratings-core.js +213 -0
- package/src/agent/ratings.js +100 -0
- package/src/agent/reply-text.js +67 -0
- package/src/agent/routes.js +1065 -0
- package/src/agent/run.js +326 -0
- package/src/agent/settings-routes.js +704 -0
- package/src/agent/showable.js +23 -0
- package/src/agent/starter/approvals.js +181 -0
- package/src/agent/starter/build-image.js +90 -0
- package/src/agent/starter/cli.js +163 -0
- package/src/agent/starter/disk.js +53 -0
- package/src/agent/starter/doctor.js +180 -0
- package/src/agent/starter/egress-proxy.js +351 -0
- package/src/agent/starter/gate.js +90 -0
- package/src/agent/starter/loop.js +114 -0
- package/src/agent/starter/model-relay.js +289 -0
- package/src/agent/starter/pause.js +14 -0
- package/src/agent/starter/probe.js +272 -0
- package/src/agent/starter/prompt.js +41 -0
- package/src/agent/starter/push-guard.js +146 -0
- package/src/agent/starter/rpc.js +164 -0
- package/src/agent/starter/runtime.js +287 -0
- package/src/agent/starter/sandbox-main.js +121 -0
- package/src/agent/starter/settings.js +290 -0
- package/src/agent/starter/source.js +69 -0
- package/src/agent/starter/supervisor.js +755 -0
- package/src/agent/starter/sweep.js +46 -0
- package/src/agent/starter/tools.js +524 -0
- package/src/agent/starter/watch.js +84 -0
- package/src/agent/starter/worktree.js +409 -0
- package/src/agent/text-diff.js +210 -0
- package/src/agent/thread-history.js +223 -0
- package/src/agent/threads.js +399 -0
- package/src/agent/tools.js +200 -0
- package/src/agent/turn-changes.js +424 -0
- package/src/agent/undo-state.js +26 -0
- package/src/agent/user-settings.js +308 -0
- package/src/auth/record.js +375 -0
- package/src/broken-links.js +164 -0
- package/src/buzz/client.js +75 -0
- package/src/buzz/config.js +151 -0
- package/src/buzz/environment.js +13 -0
- package/src/buzz/gateway.js +192 -0
- package/src/buzz/routes.js +61 -0
- package/src/buzz/signer-child.js +205 -0
- package/src/buzz/store.js +89 -0
- package/src/buzz/transport.js +60 -0
- package/src/buzz/verify.js +140 -0
- package/src/capture/actions.js +159 -0
- package/src/capture/capture.js +776 -0
- package/src/capture/dom-names.js +189 -0
- package/src/capture/element-map.js +509 -0
- package/src/capture/live.js +827 -0
- package/src/capture/media-scheme.js +317 -0
- package/src/capture/network-summary.js +86 -0
- package/src/capture/pacing.js +34 -0
- package/src/capture/requests.js +167 -0
- package/src/capture/sanitize.js +752 -0
- package/src/checks/accessibility.js +134 -0
- package/src/checks/budgets.js +58 -0
- package/src/checks/cli.js +55 -0
- package/src/checks/comparison.js +113 -0
- package/src/checks/environments.js +32 -0
- package/src/checks/flow-config.js +82 -0
- package/src/checks/flow-origin.js +53 -0
- package/src/checks/flows.js +398 -0
- package/src/checks/lighthouse-auth.js +145 -0
- package/src/checks/lighthouse-findings.js +130 -0
- package/src/checks/lighthouse.js +395 -0
- package/src/checks/robots.js +85 -0
- package/src/checks/routes.js +52 -0
- package/src/checks/run-control.js +259 -0
- package/src/checks/runner.js +724 -0
- package/src/checks/schema.js +133 -0
- package/src/checks/seo-analysis.js +443 -0
- package/src/checks/seo-probe.js +190 -0
- package/src/checks/seo-snapshot.js +99 -0
- package/src/checks/store.js +214 -0
- package/src/checks/transport.js +47 -0
- package/src/cli/args.js +319 -0
- package/src/cli/capture.js +79 -0
- package/src/cli/commands.js +92 -0
- package/src/cli/comments.js +84 -0
- package/src/cli/help.js +243 -0
- package/src/cli/init.js +214 -0
- package/src/cli/misc.js +64 -0
- package/src/cli/notify.js +87 -0
- package/src/cli/open.js +22 -0
- package/src/cli/serve.js +274 -0
- package/src/cli/variant.js +82 -0
- package/src/cli/watch.js +70 -0
- package/src/cli.js +130 -0
- package/src/comment-fields.js +76 -0
- package/src/comments-cli.js +208 -0
- package/src/config-reload.js +100 -0
- package/src/config.js +1061 -0
- package/src/devices-cli.js +21 -0
- package/src/diff.js +95 -0
- package/src/discover.js +284 -0
- package/src/doctor.js +295 -0
- package/src/event-log.js +268 -0
- package/src/events-cli.js +102 -0
- package/src/events.js +113 -0
- package/src/export.js +119 -0
- package/src/feedback.js +246 -0
- package/src/github.js +551 -0
- package/src/hosted/LICENSE.md +105 -0
- package/src/hosted/access-cli.js +78 -0
- package/src/hosted/admin.js +682 -0
- package/src/hosted/agent-approvals.js +163 -0
- package/src/hosted/agent-policy.js +189 -0
- package/src/hosted/app.js +510 -0
- package/src/hosted/auth-routes.js +540 -0
- package/src/hosted/auth.js +536 -0
- package/src/hosted/backup.js +483 -0
- package/src/hosted/board-context.js +35 -0
- package/src/hosted/board-routes.js +486 -0
- package/src/hosted/board-view.js +94 -0
- package/src/hosted/clean-worker.js +24 -0
- package/src/hosted/cleaner.js +89 -0
- package/src/hosted/comments.js +355 -0
- package/src/hosted/console-routes.js +401 -0
- package/src/hosted/cookies.js +18 -0
- package/src/hosted/crypto.js +80 -0
- package/src/hosted/db.js +496 -0
- package/src/hosted/device-routes.js +175 -0
- package/src/hosted/device.js +233 -0
- package/src/hosted/events.js +63 -0
- package/src/hosted/guards.js +172 -0
- package/src/hosted/guest-view.js +65 -0
- package/src/hosted/http.js +39 -0
- package/src/hosted/import.js +300 -0
- package/src/hosted/mail.js +73 -0
- package/src/hosted/mcp-http.js +71 -0
- package/src/hosted/membership.js +114 -0
- package/src/hosted/operator.js +478 -0
- package/src/hosted/ops-cli.js +345 -0
- package/src/hosted/pages.js +146 -0
- package/src/hosted/permissions.js +113 -0
- package/src/hosted/presence.js +372 -0
- package/src/hosted/projects.js +124 -0
- package/src/hosted/public.js +109 -0
- package/src/hosted/push.js +622 -0
- package/src/hosted/quotas.js +115 -0
- package/src/hosted/ratelimit.js +96 -0
- package/src/hosted/rebind.js +316 -0
- package/src/hosted/retention.js +128 -0
- package/src/hosted/server.js +260 -0
- package/src/hosted/setup-link.js +64 -0
- package/src/hosted/setup.js +323 -0
- package/src/hosted/shares.js +444 -0
- package/src/hosted/tailscale.js +204 -0
- package/src/hosted/tenancy.js +301 -0
- package/src/hosted/token-api.js +455 -0
- package/src/hosted/token-events.js +60 -0
- package/src/hosted/tokens.js +57 -0
- package/src/hosted/turnstile.js +49 -0
- package/src/hosted/usercontent.js +154 -0
- package/src/hosted/zip.js +155 -0
- package/src/invocation.js +58 -0
- package/src/journey-paths.js +282 -0
- package/src/journeys.js +189 -0
- package/src/links.js +106 -0
- package/src/local-projects.js +182 -0
- package/src/lock.js +193 -0
- package/src/mcp.js +417 -0
- package/src/mentions.js +151 -0
- package/src/net.js +15 -0
- package/src/notify/config.js +275 -0
- package/src/notify/index.js +301 -0
- package/src/notify/lease.js +73 -0
- package/src/notify/messages.js +212 -0
- package/src/notify/run.js +174 -0
- package/src/pixeldiff.js +49 -0
- package/src/png.js +143 -0
- package/src/reactions.js +111 -0
- package/src/remote/cli.js +133 -0
- package/src/remote/credentials.js +62 -0
- package/src/remote/ids.js +12 -0
- package/src/remote/login.js +155 -0
- package/src/remote/remote-mcp.js +237 -0
- package/src/remote/remote-watch.js +291 -0
- package/src/remote/remote.js +313 -0
- package/src/remote/share-state.js +78 -0
- package/src/remote/share.js +369 -0
- package/src/remote/terminal.js +13 -0
- package/src/serve-state.js +64 -0
- package/src/server/app.js +824 -0
- package/src/server/devices.js +186 -0
- package/src/server/local-console.js +28 -0
- package/src/server/local-user.js +59 -0
- package/src/server/pairing-routes.js +159 -0
- package/src/server/share-routes.js +89 -0
- package/src/server/tailscale.js +97 -0
- package/src/sitemap.js +431 -0
- package/src/store.js +983 -0
- package/src/tokens.js +11 -0
- package/src/update/routes.js +245 -0
- package/src/watch.js +403 -0
- package/src/which.js +58 -0
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
// Share links: a view-only or guest-comment link to one project's boards, for
|
|
2
|
+
// people outside the workspace. Off in every workspace until an admin turns
|
|
3
|
+
// them on (Settings); turning them off stops every link at once.
|
|
4
|
+
//
|
|
5
|
+
// Security model:
|
|
6
|
+
// - The link is /share#<token>: 32 random bytes in the fragment, which
|
|
7
|
+
// browsers never send, so it stays out of logs and Referer headers. Only
|
|
8
|
+
// its SHA-256 is stored. Optional passcode (scrypt, salted), checked with
|
|
9
|
+
// its own rate limits (only failures count).
|
|
10
|
+
// - Opening it (POST /api/shares/open) sets a guest cookie: HttpOnly,
|
|
11
|
+
// SameSite=Strict, Path=/s/<share id>/, signed with the server secret and
|
|
12
|
+
// bound to that link's token hash, at most 12 hours and never past the
|
|
13
|
+
// link's expiry. The cookie is a random 32-byte guest session token
|
|
14
|
+
// (stored as SHA-256 in guest_sessions, migration 5), one row per opened
|
|
15
|
+
// link, so an admin can see each guest (name, opened, last seen, address
|
|
16
|
+
// prefix) and end one guest without revoking the link. The guest API
|
|
17
|
+
// (/s/<id>/api) reads only that cookie, never the account session, and
|
|
18
|
+
// checks the link and the guest session on every request: revoked,
|
|
19
|
+
// expired, switched off, its project deleted or the guest ended, it stops
|
|
20
|
+
// at once.
|
|
21
|
+
// - A guest reaches one project: its boards, captures, live HTML (through
|
|
22
|
+
// the same signed /uc/ URLs) and comments. No workspace data, members,
|
|
23
|
+
// other projects or tokens. On a comment link a guest adds comments and
|
|
24
|
+
// replies, named "<name> (guest)" and flagged as guest content
|
|
25
|
+
// (authorGuest). Their @mentions are dropped, the token API leaves guest
|
|
26
|
+
// comments out unless asked (`guests=1`), and `watch --remote` and MCP
|
|
27
|
+
// skip them unless --include-guests / includeGuests, so a guest cannot
|
|
28
|
+
// wake an agent. They cannot resolve, edit or delete anything.
|
|
29
|
+
// - Every link created, revoked, opened and every guest comment is audited.
|
|
30
|
+
|
|
31
|
+
import { checkPasscode, hashPasscode, newId, randomToken, sha256, SHARE_ID_RE } from './crypto.js'
|
|
32
|
+
import { guestCookieName, parseCookies } from './cookies.js'
|
|
33
|
+
import { deviceLabel } from './auth.js'
|
|
34
|
+
import { LIMITS } from './ratelimit.js'
|
|
35
|
+
import { audit, findShareByHash, findShareById, shareUsable, tenant } from './tenancy.js'
|
|
36
|
+
import { NEEDS } from './permissions.js'
|
|
37
|
+
import { transaction } from './db.js'
|
|
38
|
+
|
|
39
|
+
export const SHARE_DAYS = [1, 7, 30, 90]
|
|
40
|
+
export const SHARE_MODES = ['view', 'comment']
|
|
41
|
+
const SHARES_PER_PROJECT = 20
|
|
42
|
+
const GUEST_SESSION_MS = 12 * 3_600_000
|
|
43
|
+
// Guest sessions kept per link (oldest go first), and how long ended or
|
|
44
|
+
// expired ones stay listed.
|
|
45
|
+
const GUESTS_PER_SHARE = 500
|
|
46
|
+
const GUEST_KEEP_MS = 7 * 86_400_000
|
|
47
|
+
export const GUEST_ID_RE = /^gs_[a-f0-9]{24}$/
|
|
48
|
+
const TOKEN_RE = /^[A-Za-z0-9_-]{20,100}$/
|
|
49
|
+
const GUEST_TOKEN_RE = /^[A-Za-z0-9_-]{43}$/
|
|
50
|
+
// eslint-disable-next-line no-control-regex
|
|
51
|
+
const CONTROL_RE = /[\u0000-\u001f\u007f]/g
|
|
52
|
+
|
|
53
|
+
function cleanText(value, max) {
|
|
54
|
+
return typeof value === 'string' ? value.replace(CONTROL_RE, '').replace(/\s+/g, ' ').trim().slice(0, max) : ''
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function cleanGuestName(value) {
|
|
58
|
+
const name = cleanText(value, 41)
|
|
59
|
+
if (!name || name.length > 40) return null
|
|
60
|
+
return name
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// An address with its last part hidden, for the guest list: 203.0.113.x for
|
|
64
|
+
// IPv4, the first three groups for IPv6.
|
|
65
|
+
export function ipPrefix(ip) {
|
|
66
|
+
const value = String(ip || '').replace(/^::ffff:/, '')
|
|
67
|
+
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(value)) return `${value.split('.').slice(0, 3).join('.')}.x`
|
|
68
|
+
if (value.includes(':')) return `${value.split(':').slice(0, 3).join(':')}::/48`
|
|
69
|
+
return null
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// The guest session row of a request's cookie for link `row` (any state), or null.
|
|
73
|
+
function guestSessionRow(req, { db, secure }, row) {
|
|
74
|
+
const raw = parseCookies(req.headers.cookie)[guestCookieName(secure)]
|
|
75
|
+
if (!raw || !GUEST_TOKEN_RE.test(raw)) return null
|
|
76
|
+
return (
|
|
77
|
+
tenant(db, row.workspace_id).get('SELECT * FROM guest_sessions WHERE workspace_id = :ws AND token_hash = :hash AND share_id = :share', {
|
|
78
|
+
hash: sha256(raw),
|
|
79
|
+
share: row.id,
|
|
80
|
+
}) || null
|
|
81
|
+
)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// The guest of the request (for /s/:sid/...), or null. The cookie must be a
|
|
85
|
+
// live guest session of this path's link (not ended, not expired), and the
|
|
86
|
+
// link must still work.
|
|
87
|
+
export function readGuest(req, { db, secure, iso, now }) {
|
|
88
|
+
const sid = String(req.params?.sid || '')
|
|
89
|
+
if (!SHARE_ID_RE.test(sid)) return null
|
|
90
|
+
const row = findShareById(db, sid)
|
|
91
|
+
if (!shareUsable(row, iso())) return null
|
|
92
|
+
const session = guestSessionRow(req, { db, secure }, row)
|
|
93
|
+
if (!session || session.ended_at || session.expires_at <= iso()) return null
|
|
94
|
+
// Last seen, written at most once a minute.
|
|
95
|
+
if (now().getTime() - Date.parse(session.last_seen_at) > 60_000) {
|
|
96
|
+
tenant(db, row.workspace_id).run('UPDATE guest_sessions SET last_seen_at = :at WHERE workspace_id = :ws AND id = :id', {
|
|
97
|
+
at: iso(),
|
|
98
|
+
id: session.id,
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
shareId: row.id,
|
|
103
|
+
guestId: session.id,
|
|
104
|
+
workspaceId: row.workspace_id,
|
|
105
|
+
projectId: row.project_id,
|
|
106
|
+
mode: row.mode,
|
|
107
|
+
includeChecks: row.include_checks === 1,
|
|
108
|
+
name: cleanGuestName(session.name) || 'Guest',
|
|
109
|
+
expiresAt: row.expires_at,
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function publicGuest(row, at) {
|
|
114
|
+
return {
|
|
115
|
+
id: row.id,
|
|
116
|
+
name: row.name,
|
|
117
|
+
createdAt: row.created_at,
|
|
118
|
+
lastSeenAt: row.last_seen_at,
|
|
119
|
+
expiresAt: row.expires_at,
|
|
120
|
+
endedAt: row.ended_at,
|
|
121
|
+
ipPrefix: row.ip_prefix,
|
|
122
|
+
device: row.device,
|
|
123
|
+
status: row.ended_at ? 'ended' : row.expires_at <= at ? 'expired' : 'active',
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function publicShare(row, at) {
|
|
128
|
+
return {
|
|
129
|
+
id: row.id,
|
|
130
|
+
name: row.name,
|
|
131
|
+
projectId: row.project_id,
|
|
132
|
+
projectName: row.project_name || null,
|
|
133
|
+
mode: row.mode,
|
|
134
|
+
includeChecks: row.include_checks === 1,
|
|
135
|
+
passcode: Boolean(row.passcode_hash),
|
|
136
|
+
createdAt: row.created_at,
|
|
137
|
+
expiresAt: row.expires_at,
|
|
138
|
+
revokedAt: row.revoked_at,
|
|
139
|
+
lastUsedAt: row.last_used_at,
|
|
140
|
+
opens: row.opens,
|
|
141
|
+
status: row.revoked_at ? 'revoked' : row.expires_at <= at ? 'expired' : 'active',
|
|
142
|
+
createdBy: row.creator_handle ? { handle: row.creator_handle, displayName: row.creator_name } : null,
|
|
143
|
+
url: `/s/${row.id}/`,
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const SHARE_SELECT = `SELECT s.*, p.name AS project_name, c.handle AS creator_handle, c.display_name AS creator_name
|
|
148
|
+
FROM shares s JOIN projects p ON p.id = s.project_id AND p.workspace_id = s.workspace_id LEFT JOIN users c ON c.id = s.created_by`
|
|
149
|
+
|
|
150
|
+
// Console routes for admins: list, create and revoke a project's links.
|
|
151
|
+
export function mountShareAdmin(router, deps) {
|
|
152
|
+
const { iso, handle, inWorkspace, inProject, needFresh, auditOf, HttpError, publicOrigin } = deps
|
|
153
|
+
|
|
154
|
+
router.get(
|
|
155
|
+
'/workspaces/:ws/shares',
|
|
156
|
+
inWorkspace(NEEDS.shares),
|
|
157
|
+
handle(async (req, res) => {
|
|
158
|
+
const at = iso()
|
|
159
|
+
const rows = req.t.all(`${SHARE_SELECT} WHERE s.workspace_id = :ws ORDER BY s.created_at DESC LIMIT 500`)
|
|
160
|
+
res.json({ shares: rows.map((row) => publicShare(row, at)) })
|
|
161
|
+
}),
|
|
162
|
+
)
|
|
163
|
+
router.get(
|
|
164
|
+
'/workspaces/:ws/projects/:pid/shares',
|
|
165
|
+
inWorkspace(NEEDS.shares),
|
|
166
|
+
inProject,
|
|
167
|
+
handle(async (req, res) => {
|
|
168
|
+
const at = iso()
|
|
169
|
+
const rows = req.t.all(
|
|
170
|
+
`${SHARE_SELECT} WHERE s.workspace_id = :ws AND s.project_id = :project ORDER BY s.created_at DESC LIMIT 200`,
|
|
171
|
+
{
|
|
172
|
+
project: req.project.id,
|
|
173
|
+
},
|
|
174
|
+
)
|
|
175
|
+
res.json({ shares: rows.map((row) => publicShare(row, at)) })
|
|
176
|
+
}),
|
|
177
|
+
)
|
|
178
|
+
router.post(
|
|
179
|
+
'/workspaces/:ws/projects/:pid/shares',
|
|
180
|
+
inWorkspace(NEEDS.shares),
|
|
181
|
+
needFresh,
|
|
182
|
+
inProject,
|
|
183
|
+
handle(async (req, res) => {
|
|
184
|
+
const workspace = req.t.get('SELECT share_links FROM workspaces WHERE workspace_id = :ws')
|
|
185
|
+
if (!workspace.share_links)
|
|
186
|
+
throw new HttpError(409, 'shares_off', 'Share links are off in this workspace. An admin turns them on in Settings.')
|
|
187
|
+
const body = req.body || {}
|
|
188
|
+
const mode = body.mode ?? 'view'
|
|
189
|
+
if (!SHARE_MODES.includes(mode)) throw new HttpError(400, 'invalid_mode', 'mode: view or comment.')
|
|
190
|
+
if (body.includeChecks !== undefined && typeof body.includeChecks !== 'boolean')
|
|
191
|
+
throw new HttpError(400, 'invalid_checks_policy', 'includeChecks must be true or false.')
|
|
192
|
+
const includeChecks = body.includeChecks === true
|
|
193
|
+
const days = body.expiresInDays ?? 7
|
|
194
|
+
if (!SHARE_DAYS.includes(days)) throw new HttpError(400, 'invalid_expiry', `expiresInDays: one of ${SHARE_DAYS.join(', ')}.`)
|
|
195
|
+
const name = cleanText(body.name, 61) || (mode === 'comment' ? 'Comment link' : 'View link')
|
|
196
|
+
if (name.length > 60) throw new HttpError(400, 'invalid_name', 'Link name: up to 60 characters.')
|
|
197
|
+
let passcodeHash = null
|
|
198
|
+
if (body.passcode !== undefined && body.passcode !== null && body.passcode !== '') {
|
|
199
|
+
if (typeof body.passcode !== 'string' || body.passcode.length < 4 || body.passcode.length > 64)
|
|
200
|
+
throw new HttpError(400, 'invalid_passcode', 'Passcode: 4 to 64 characters, or none.')
|
|
201
|
+
passcodeHash = await hashPasscode(body.passcode)
|
|
202
|
+
}
|
|
203
|
+
const at = iso()
|
|
204
|
+
const active = req.t.get(
|
|
205
|
+
'SELECT COUNT(*) AS n FROM shares WHERE workspace_id = :ws AND project_id = :project AND revoked_at IS NULL AND expires_at > :now',
|
|
206
|
+
{ project: req.project.id, now: at },
|
|
207
|
+
).n
|
|
208
|
+
const most = deps.quotas ? deps.quotas.of(req.t.workspaceId).shareLinksPerProject : SHARES_PER_PROJECT
|
|
209
|
+
if (active >= most) throw new HttpError(409, 'too_many_shares', `Revoke an old link first (${most} per project).`)
|
|
210
|
+
const token = randomToken(32)
|
|
211
|
+
const id = newId('sh')
|
|
212
|
+
req.t.run(
|
|
213
|
+
`INSERT INTO shares (workspace_id, id, project_id, token_hash, name, mode, include_checks, passcode_hash, created_by, created_at, expires_at)
|
|
214
|
+
VALUES (:ws, :id, :project, :hash, :name, :mode, :checks, :passcode, :user, :at, :expires)`,
|
|
215
|
+
{
|
|
216
|
+
id,
|
|
217
|
+
project: req.project.id,
|
|
218
|
+
hash: sha256(token),
|
|
219
|
+
name,
|
|
220
|
+
mode,
|
|
221
|
+
checks: includeChecks ? 1 : 0,
|
|
222
|
+
passcode: passcodeHash,
|
|
223
|
+
user: req.user.id,
|
|
224
|
+
at,
|
|
225
|
+
expires: new Date(Date.parse(at) + days * 86_400_000).toISOString(),
|
|
226
|
+
},
|
|
227
|
+
)
|
|
228
|
+
auditOf(req, 'share_created', id, { project: req.project.id, mode, days, includeChecks, passcode: Boolean(passcodeHash) })
|
|
229
|
+
const row = req.t.get(`${SHARE_SELECT} WHERE s.workspace_id = :ws AND s.id = :id`, { id })
|
|
230
|
+
res.status(201).json({ share: publicShare(row, iso()), url: `${deps.shareOrigin || publicOrigin}/share#${token}` })
|
|
231
|
+
}),
|
|
232
|
+
)
|
|
233
|
+
// The guests of one link: who opened it, and ending one of them.
|
|
234
|
+
const shareOf = (req) => {
|
|
235
|
+
const sid = String(req.params.sid)
|
|
236
|
+
const row = SHARE_ID_RE.test(sid)
|
|
237
|
+
? req.t.get('SELECT id FROM shares WHERE workspace_id = :ws AND project_id = :project AND id = :id', {
|
|
238
|
+
project: req.project.id,
|
|
239
|
+
id: sid,
|
|
240
|
+
})
|
|
241
|
+
: null
|
|
242
|
+
if (!row) throw new HttpError(404, 'unknown_share', 'No such share link.')
|
|
243
|
+
return row
|
|
244
|
+
}
|
|
245
|
+
router.get(
|
|
246
|
+
'/workspaces/:ws/projects/:pid/shares/:sid/guests',
|
|
247
|
+
inWorkspace(NEEDS.shares),
|
|
248
|
+
inProject,
|
|
249
|
+
handle(async (req, res) => {
|
|
250
|
+
const share = shareOf(req)
|
|
251
|
+
const at = iso()
|
|
252
|
+
const rows = req.t.all(
|
|
253
|
+
'SELECT * FROM guest_sessions WHERE workspace_id = :ws AND share_id = :share ORDER BY last_seen_at DESC LIMIT 200',
|
|
254
|
+
{ share: share.id },
|
|
255
|
+
)
|
|
256
|
+
res.json({ guests: rows.map((row) => publicGuest(row, at)) })
|
|
257
|
+
}),
|
|
258
|
+
)
|
|
259
|
+
router.delete(
|
|
260
|
+
'/workspaces/:ws/projects/:pid/shares/:sid/guests/:gid',
|
|
261
|
+
inWorkspace(NEEDS.shares),
|
|
262
|
+
inProject,
|
|
263
|
+
handle(async (req, res) => {
|
|
264
|
+
const share = shareOf(req)
|
|
265
|
+
const gid = String(req.params.gid)
|
|
266
|
+
const guest = GUEST_ID_RE.test(gid)
|
|
267
|
+
? req.t.get('SELECT * FROM guest_sessions WHERE workspace_id = :ws AND share_id = :share AND id = :id', {
|
|
268
|
+
share: share.id,
|
|
269
|
+
id: gid,
|
|
270
|
+
})
|
|
271
|
+
: null
|
|
272
|
+
if (!guest) throw new HttpError(404, 'unknown_guest', 'No such guest.')
|
|
273
|
+
if (!guest.ended_at) {
|
|
274
|
+
req.t.run('UPDATE guest_sessions SET ended_at = :at, ended_by = :user WHERE workspace_id = :ws AND id = :id AND ended_at IS NULL', {
|
|
275
|
+
at: iso(),
|
|
276
|
+
user: req.user.id,
|
|
277
|
+
id: guest.id,
|
|
278
|
+
})
|
|
279
|
+
auditOf(req, 'guest_ended', share.id, { project: req.project.id, guest: guest.name, guestSession: guest.id })
|
|
280
|
+
}
|
|
281
|
+
const row = req.t.get('SELECT * FROM guest_sessions WHERE workspace_id = :ws AND id = :id', { id: guest.id })
|
|
282
|
+
res.json({ guest: publicGuest(row, iso()) })
|
|
283
|
+
}),
|
|
284
|
+
)
|
|
285
|
+
router.delete(
|
|
286
|
+
'/workspaces/:ws/projects/:pid/shares/:sid',
|
|
287
|
+
inWorkspace(NEEDS.shares),
|
|
288
|
+
inProject,
|
|
289
|
+
handle(async (req, res) => {
|
|
290
|
+
const result = req.t.run(
|
|
291
|
+
'UPDATE shares SET revoked_at = :at WHERE workspace_id = :ws AND project_id = :project AND id = :id AND revoked_at IS NULL',
|
|
292
|
+
{ at: iso(), project: req.project.id, id: String(req.params.sid) },
|
|
293
|
+
)
|
|
294
|
+
if (!result.changes) throw new HttpError(404, 'unknown_share', 'No such share link.')
|
|
295
|
+
auditOf(req, 'share_revoked', String(req.params.sid), { project: req.project.id })
|
|
296
|
+
res.json({ ok: true })
|
|
297
|
+
}),
|
|
298
|
+
)
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// Public routes (no session): preview a link and open it.
|
|
302
|
+
export function mountSharePublic(router, deps) {
|
|
303
|
+
const { db, iso, now, handle, limit, clientIp, HttpError, rateLimiter, secure, turnstile = null, turnstileHosts } = deps
|
|
304
|
+
const ended = () => new HttpError(404, 'invalid_share', 'This share link was revoked, has expired or is turned off.')
|
|
305
|
+
const lookup = (token) => {
|
|
306
|
+
const row = typeof token === 'string' && TOKEN_RE.test(token) ? findShareByHash(db, sha256(token)) : null
|
|
307
|
+
if (!shareUsable(row, iso())) throw ended()
|
|
308
|
+
return row
|
|
309
|
+
}
|
|
310
|
+
// Opens and wrong passcodes repeat: one audit row per link, action and
|
|
311
|
+
// hour, with a count (and up to 10 guest names), instead of one per try.
|
|
312
|
+
const auditCollapsed = (t, { shareId, action, target, ip, guest = null }) => {
|
|
313
|
+
const since = new Date(now().getTime() - 3_600_000).toISOString()
|
|
314
|
+
const last = t.get(
|
|
315
|
+
'SELECT id, detail FROM audit_log WHERE workspace_id = :ws AND share_id = :share AND action = :action AND at > :since ORDER BY id DESC LIMIT 1',
|
|
316
|
+
{ share: shareId, action, since },
|
|
317
|
+
)
|
|
318
|
+
if (!last) {
|
|
319
|
+
audit(t, { shareId, action, target, ip, at: iso(), detail: { count: 1, ...(guest ? { guests: [guest] } : {}) } })
|
|
320
|
+
return
|
|
321
|
+
}
|
|
322
|
+
let detail = {}
|
|
323
|
+
try {
|
|
324
|
+
detail = JSON.parse(last.detail) || {}
|
|
325
|
+
} catch {
|
|
326
|
+
detail = {}
|
|
327
|
+
}
|
|
328
|
+
const guests = Array.isArray(detail.guests) ? detail.guests : []
|
|
329
|
+
if (guest && !guests.includes(guest) && guests.length < 10) guests.push(guest)
|
|
330
|
+
const next = { ...detail, count: (Number(detail.count) || 1) + 1, lastAt: iso(), lastIp: ip, ...(guests.length ? { guests } : {}) }
|
|
331
|
+
t.run('UPDATE audit_log SET detail = :detail WHERE workspace_id = :ws AND id = :id', { detail: JSON.stringify(next), id: last.id })
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// What the link opens. Behind a passcode, nothing about the workspace or
|
|
335
|
+
// project shows before the passcode is right.
|
|
336
|
+
router.post(
|
|
337
|
+
'/shares/preview',
|
|
338
|
+
limit('share'),
|
|
339
|
+
handle(async (req, res) => {
|
|
340
|
+
const row = lookup(req.body?.token)
|
|
341
|
+
const locked = Boolean(row.passcode_hash)
|
|
342
|
+
res.json({
|
|
343
|
+
id: row.id,
|
|
344
|
+
mode: row.mode,
|
|
345
|
+
needsPasscode: locked,
|
|
346
|
+
expiresAt: row.expires_at,
|
|
347
|
+
project: locked ? null : { name: row.project_name },
|
|
348
|
+
workspace: locked ? null : { name: row.workspace_name },
|
|
349
|
+
// A comment link asks for the bot check when the operator set one up.
|
|
350
|
+
...(turnstile && row.mode === 'comment' ? { turnstile: turnstile.siteKey } : {}),
|
|
351
|
+
})
|
|
352
|
+
}),
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
const openHandlers = [
|
|
356
|
+
limit('share'),
|
|
357
|
+
handle(async (req, res) => {
|
|
358
|
+
const row = lookup(req.body?.token)
|
|
359
|
+
if (req.params.sid && req.params.sid !== row.id) throw ended()
|
|
360
|
+
const ip = clientIp(req)
|
|
361
|
+
const t = tenant(db, row.workspace_id)
|
|
362
|
+
if (row.passcode_hash) {
|
|
363
|
+
const passcode = typeof req.body?.passcode === 'string' ? req.body.passcode.slice(0, 64) : ''
|
|
364
|
+
if (!passcode) throw new HttpError(401, 'passcode_required', 'This link needs its passcode.')
|
|
365
|
+
// Counted before the (slow) check, given back when right: parallel
|
|
366
|
+
// guesses cannot slip past the limit.
|
|
367
|
+
const tries = rateLimiter.attempt([
|
|
368
|
+
['shareFail', `${row.id}\u0000${ip}`, LIMITS.shareFail],
|
|
369
|
+
['shareFailIp', ip, LIMITS.shareFailIp],
|
|
370
|
+
['shareFailLink', row.id, LIMITS.shareFailLink],
|
|
371
|
+
])
|
|
372
|
+
if (!tries.ok) {
|
|
373
|
+
res.setHeader('Retry-After', String(tries.retryAfter))
|
|
374
|
+
throw new HttpError(429, 'rate_limited', 'Too many wrong passcodes. Wait a while and try again.')
|
|
375
|
+
}
|
|
376
|
+
if (!(await checkPasscode(passcode, row.passcode_hash))) {
|
|
377
|
+
auditCollapsed(t, { shareId: row.id, action: 'share_passcode_failed', target: row.id, ip })
|
|
378
|
+
throw new HttpError(401, 'bad_passcode', 'That passcode is not right.')
|
|
379
|
+
}
|
|
380
|
+
tries.success()
|
|
381
|
+
}
|
|
382
|
+
let name = cleanGuestName(req.body?.name)
|
|
383
|
+
if (req.body?.name !== undefined && req.body?.name !== '' && !name)
|
|
384
|
+
throw new HttpError(400, 'invalid_name', 'Your name: 1 to 40 characters.')
|
|
385
|
+
if (row.mode === 'comment' && !name) throw new HttpError(400, 'name_required', 'Add your name: it is shown with your comments.')
|
|
386
|
+
name = name || 'Guest'
|
|
387
|
+
// Guests who can comment pass the bot check first (when configured).
|
|
388
|
+
if (turnstile && row.mode === 'comment' && !(await turnstile.verify(req.body?.turnstileToken, ip, { hostnames: turnstileHosts })))
|
|
389
|
+
throw new HttpError(403, 'turnstile_failed', 'The bot check did not pass. Try again.')
|
|
390
|
+
let expires
|
|
391
|
+
const token = randomToken(32)
|
|
392
|
+
const at = iso()
|
|
393
|
+
transaction(db, () => {
|
|
394
|
+
// Looked up again: the link may have been revoked, expired or turned
|
|
395
|
+
// off during the passcode and bot checks above.
|
|
396
|
+
const current = findShareById(db, row.id)
|
|
397
|
+
if (!shareUsable(current, iso())) throw ended()
|
|
398
|
+
expires = Math.min(now().getTime() + GUEST_SESSION_MS, Date.parse(current.expires_at))
|
|
399
|
+
// Opening again in the same browser replaces that browser's guest.
|
|
400
|
+
const previous = guestSessionRow(req, { db, secure }, row)
|
|
401
|
+
if (previous && !previous.ended_at)
|
|
402
|
+
t.run("UPDATE guest_sessions SET ended_at = :at, ended_by = 'reopened' WHERE workspace_id = :ws AND id = :id", {
|
|
403
|
+
at,
|
|
404
|
+
id: previous.id,
|
|
405
|
+
})
|
|
406
|
+
// Old rows go, and a link keeps at most GUESTS_PER_SHARE (oldest first).
|
|
407
|
+
t.run('DELETE FROM guest_sessions WHERE workspace_id = :ws AND share_id = :share AND expires_at < :cutoff', {
|
|
408
|
+
share: row.id,
|
|
409
|
+
cutoff: new Date(now().getTime() - GUEST_KEEP_MS).toISOString(),
|
|
410
|
+
})
|
|
411
|
+
const count = t.get('SELECT COUNT(*) AS n FROM guest_sessions WHERE workspace_id = :ws AND share_id = :share', { share: row.id }).n
|
|
412
|
+
for (const old of t.all(
|
|
413
|
+
'SELECT id FROM guest_sessions WHERE workspace_id = :ws AND share_id = :share ORDER BY created_at LIMIT :n',
|
|
414
|
+
{ share: row.id, n: Math.max(0, count - GUESTS_PER_SHARE + 1) },
|
|
415
|
+
))
|
|
416
|
+
t.run('DELETE FROM guest_sessions WHERE workspace_id = :ws AND id = :id', { id: old.id })
|
|
417
|
+
t.run(
|
|
418
|
+
`INSERT INTO guest_sessions (workspace_id, id, share_id, token_hash, name, ip_prefix, device, created_at, last_seen_at, expires_at)
|
|
419
|
+
VALUES (:ws, :id, :share, :hash, :name, :ip, :device, :at, :at, :expires)`,
|
|
420
|
+
{
|
|
421
|
+
id: newId('gs'),
|
|
422
|
+
share: row.id,
|
|
423
|
+
hash: sha256(token),
|
|
424
|
+
name,
|
|
425
|
+
ip: ipPrefix(ip),
|
|
426
|
+
device: deviceLabel(req.headers['user-agent']),
|
|
427
|
+
at,
|
|
428
|
+
expires: new Date(expires).toISOString(),
|
|
429
|
+
},
|
|
430
|
+
)
|
|
431
|
+
})
|
|
432
|
+
const maxAge = Math.max(1, Math.floor((expires - now().getTime()) / 1000))
|
|
433
|
+
res.append(
|
|
434
|
+
'Set-Cookie',
|
|
435
|
+
`${guestCookieName(secure)}=${token}; Path=/s/${row.id}/; HttpOnly; SameSite=Strict; Max-Age=${maxAge}${secure ? '; Secure' : ''}`,
|
|
436
|
+
)
|
|
437
|
+
t.run('UPDATE shares SET opens = opens + 1, last_used_at = :at WHERE workspace_id = :ws AND id = :id', { at: iso(), id: row.id })
|
|
438
|
+
auditCollapsed(t, { shareId: row.id, action: 'share_opened', target: row.id, ip, guest: name })
|
|
439
|
+
res.json({ url: `/s/${row.id}/`, mode: row.mode, name, expiresAt: new Date(expires).toISOString() })
|
|
440
|
+
}),
|
|
441
|
+
]
|
|
442
|
+
router.post('/shares/open', ...openHandlers)
|
|
443
|
+
return openHandlers
|
|
444
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// Mode 1: `shapewall hosted --tailscale`. The server listens on loopback and
|
|
2
|
+
// `tailscale serve` puts it on the tailnet at https://<machine>.<tailnet>.ts.net
|
|
3
|
+
// with a real certificate, so passkeys work and nothing is public.
|
|
4
|
+
//
|
|
5
|
+
// Optional, `--funnel`: a second listener that serves only what a share link
|
|
6
|
+
// guest needs (the share landing page, the guest board and its API, live
|
|
7
|
+
// HTML, the report form), published to the internet through Tailscale Funnel
|
|
8
|
+
// on its own port. The console, sign-in, sign-up, invites, the token API and
|
|
9
|
+
// member boards are never on it: those paths answer 404 there, and it never
|
|
10
|
+
// reads the session cookie.
|
|
11
|
+
//
|
|
12
|
+
// Both use `tailscale serve|funnel --bg`, which Tailscale keeps across
|
|
13
|
+
// restarts; the server removes what it added when it stops (SIGINT/SIGTERM).
|
|
14
|
+
// A config left behind by a crash must be removed explicitly before retrying.
|
|
15
|
+
// An occupied port is never taken over, even if its target happens to match.
|
|
16
|
+
|
|
17
|
+
import { execFile } from 'node:child_process'
|
|
18
|
+
|
|
19
|
+
export class TailscaleError extends Error {}
|
|
20
|
+
|
|
21
|
+
// Funnel only publishes these HTTPS ports.
|
|
22
|
+
export const FUNNEL_PORTS = [443, 8443, 10000]
|
|
23
|
+
|
|
24
|
+
const INSTALL_HELP = `Tailscale is not installed on this machine (no "tailscale" command on PATH).
|
|
25
|
+
To run hosted Shapewall on your tailnet:
|
|
26
|
+
1. Install Tailscale: https://tailscale.com/download
|
|
27
|
+
2. Sign in: sudo tailscale up
|
|
28
|
+
3. In the admin console (DNS page) turn on MagicDNS and HTTPS certificates.
|
|
29
|
+
4. Let your user configure serve: sudo tailscale set --operator=$USER
|
|
30
|
+
Then run shapewall hosted --tailscale again. Without Tailscale, run the server
|
|
31
|
+
behind your own reverse proxy instead (docs/hosted.md, "Own domain").`
|
|
32
|
+
|
|
33
|
+
export function runCommand(command, args, { timeoutMs = 20_000 } = {}) {
|
|
34
|
+
return new Promise((resolve) => {
|
|
35
|
+
execFile(command, args, { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => {
|
|
36
|
+
if (error && error.code === 'ENOENT') return resolve({ missing: true, code: null, stdout: '', stderr: '' })
|
|
37
|
+
resolve({ missing: false, code: error ? (typeof error.code === 'number' ? error.code : 1) : 0, stdout, stderr })
|
|
38
|
+
})
|
|
39
|
+
})
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function explain(result, what) {
|
|
43
|
+
const text = `${result.stderr || ''}${result.stdout || ''}`.trim()
|
|
44
|
+
if (/access denied|permission denied|must be root|operator/i.test(text))
|
|
45
|
+
return new TailscaleError(
|
|
46
|
+
`${what} was refused by tailscaled: ${firstLine(text)}\nLet your user configure it once: sudo tailscale set --operator=$USER. Run Shapewall as an unprivileged user.`,
|
|
47
|
+
)
|
|
48
|
+
if (/funnel.*(not enabled|not available|disabled)|nodeAttr|funnel is not/i.test(text))
|
|
49
|
+
return new TailscaleError(
|
|
50
|
+
`${what} failed: Funnel is not allowed for this machine (${firstLine(text)}). Turn it on in the tailnet policy (nodeAttrs "funnel"), or run without --funnel.`,
|
|
51
|
+
)
|
|
52
|
+
if (/https.*(not enabled|disabled)|certificate|cert domains/i.test(text))
|
|
53
|
+
return new TailscaleError(
|
|
54
|
+
`${what} failed: HTTPS certificates are off for this tailnet (${firstLine(text)}). Turn them on in the admin console, DNS page.`,
|
|
55
|
+
)
|
|
56
|
+
return new TailscaleError(`${what} failed (exit ${result.code}): ${firstLine(text) || 'no output'}`)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const firstLine = (text) =>
|
|
60
|
+
String(text || '')
|
|
61
|
+
.split('\n')
|
|
62
|
+
.find(Boolean)
|
|
63
|
+
?.slice(0, 300) || ''
|
|
64
|
+
|
|
65
|
+
// This machine on the tailnet: its MagicDNS name and whether it can serve.
|
|
66
|
+
export async function tailscaleStatus({ run = runCommand } = {}) {
|
|
67
|
+
const result = await run('tailscale', ['status', '--json'])
|
|
68
|
+
if (result.missing) throw new TailscaleError(INSTALL_HELP)
|
|
69
|
+
if (result.code !== 0) throw explain(result, 'tailscale status')
|
|
70
|
+
let status
|
|
71
|
+
try {
|
|
72
|
+
status = JSON.parse(result.stdout)
|
|
73
|
+
} catch {
|
|
74
|
+
throw new TailscaleError('tailscale status --json did not answer JSON; is tailscaled running?')
|
|
75
|
+
}
|
|
76
|
+
if (status.BackendState !== 'Running')
|
|
77
|
+
throw new TailscaleError(`Tailscale is not connected (state: ${status.BackendState || 'unknown'}). Run: sudo tailscale up`)
|
|
78
|
+
const dnsName = String(status.Self?.DNSName || '').replace(/\.$/, '')
|
|
79
|
+
if (!dnsName || !/\.ts\.net$/i.test(dnsName))
|
|
80
|
+
throw new TailscaleError('This machine has no MagicDNS name (*.ts.net). Turn on MagicDNS in the Tailscale admin console, DNS page.')
|
|
81
|
+
const certDomains = (status.CertDomains || []).map((name) => String(name).replace(/\.$/, ''))
|
|
82
|
+
if (!certDomains.includes(dnsName))
|
|
83
|
+
throw new TailscaleError(
|
|
84
|
+
`HTTPS certificates are off for this tailnet, so ${dnsName} cannot serve https. Turn on "HTTPS Certificates" in the admin console, DNS page.`,
|
|
85
|
+
)
|
|
86
|
+
return { dnsName: dnsName.toLowerCase(), version: status.Version || null }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// What `tailscale serve` already does on `port`: null (free), or the local
|
|
90
|
+
// target(s) it proxies to and whether Funnel is on there.
|
|
91
|
+
export async function servedOn(port, { run = runCommand, dnsName } = {}) {
|
|
92
|
+
const result = await run('tailscale', ['serve', 'status', '--json'])
|
|
93
|
+
if (result.missing) throw new TailscaleError(INSTALL_HELP)
|
|
94
|
+
if (result.code !== 0) throw explain(result, 'tailscale serve status')
|
|
95
|
+
let config = {}
|
|
96
|
+
try {
|
|
97
|
+
config = JSON.parse(result.stdout || '{}') || {}
|
|
98
|
+
} catch (error) {
|
|
99
|
+
throw new TailscaleError('tailscale serve status returned invalid JSON; refusing to change its configuration', { cause: error })
|
|
100
|
+
}
|
|
101
|
+
const tcp = config.TCP?.[String(port)]
|
|
102
|
+
if (!tcp) return null
|
|
103
|
+
const web = config.Web?.[`${dnsName}:${port}`] || Object.entries(config.Web || {}).find(([key]) => key.endsWith(`:${port}`))?.[1]
|
|
104
|
+
const targets = Object.values(web?.Handlers || {}).map((handler) => handler.Proxy || handler.Path || handler.Text || 'something')
|
|
105
|
+
if (tcp.TCPForward) targets.push(`tcp ${tcp.TCPForward}`)
|
|
106
|
+
const funnel = Object.entries(config.AllowFunnel || {}).some(([key, on]) => on && key.endsWith(`:${port}`))
|
|
107
|
+
return { targets, funnel }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const localTarget = (port) => `http://127.0.0.1:${port}`
|
|
111
|
+
|
|
112
|
+
async function claim(kind, httpsPort, localPort, { run, dnsName }) {
|
|
113
|
+
const current = await servedOn(httpsPort, { run, dnsName })
|
|
114
|
+
const target = localTarget(localPort)
|
|
115
|
+
if (current) {
|
|
116
|
+
throw new TailscaleError(
|
|
117
|
+
`Tailscale already serves port ${httpsPort} on this machine (${current.targets.join(', ') || 'another service'}${current.funnel ? ', public through Funnel' : ''}). ` +
|
|
118
|
+
`Pick another port (${kind === 'funnel' ? `--funnel-port, one of ${FUNNEL_PORTS.join(', ')}` : '--tailscale-port 8443'}) or remove it first: tailscale ${kind} --https=${httpsPort} off`,
|
|
119
|
+
)
|
|
120
|
+
}
|
|
121
|
+
const result = await run('tailscale', [kind, '--bg', `--https=${httpsPort}`, target])
|
|
122
|
+
if (result.code !== 0) throw explain(result, `tailscale ${kind} --https=${httpsPort}`)
|
|
123
|
+
return async () => {
|
|
124
|
+
const active = await servedOn(httpsPort, { run, dnsName })
|
|
125
|
+
if (!active) return true
|
|
126
|
+
if (active.targets.length !== 1 || active.targets[0] !== target || active.funnel !== (kind === 'funnel')) return false
|
|
127
|
+
const off = await run('tailscale', [kind, `--https=${httpsPort}`, 'off'])
|
|
128
|
+
return off.code === 0
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Puts the server on the tailnet. Returns { origin, shareOrigin, stop }:
|
|
133
|
+
// `stop()` removes what was added.
|
|
134
|
+
export async function startTailscale({ localPort, httpsPort = 443, funnel = null, run = runCommand }) {
|
|
135
|
+
const { dnsName } = await tailscaleStatus({ run })
|
|
136
|
+
if (!Number.isInteger(httpsPort) || httpsPort < 1 || httpsPort > 65535) throw new TailscaleError('--tailscale-port: a port number')
|
|
137
|
+
if (funnel) {
|
|
138
|
+
if (!FUNNEL_PORTS.includes(funnel.httpsPort))
|
|
139
|
+
throw new TailscaleError(`--funnel-port: Funnel publishes only ports ${FUNNEL_PORTS.join(', ')}`)
|
|
140
|
+
if (funnel.httpsPort === httpsPort) throw new TailscaleError('--funnel-port must differ from --tailscale-port')
|
|
141
|
+
}
|
|
142
|
+
const undo = []
|
|
143
|
+
const stop = async () => {
|
|
144
|
+
const results = []
|
|
145
|
+
for (const step of undo.reverse()) results.push(await step().catch(() => false))
|
|
146
|
+
undo.length = 0
|
|
147
|
+
return results.every(Boolean)
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
undo.push(await claim('serve', httpsPort, localPort, { run, dnsName }))
|
|
151
|
+
let shareOrigin = null
|
|
152
|
+
if (funnel) {
|
|
153
|
+
undo.push(await claim('funnel', funnel.httpsPort, funnel.localPort, { run, dnsName }))
|
|
154
|
+
shareOrigin = originFor(dnsName, funnel.httpsPort)
|
|
155
|
+
}
|
|
156
|
+
return { origin: originFor(dnsName, httpsPort), shareOrigin, dnsName, stop }
|
|
157
|
+
} catch (error) {
|
|
158
|
+
await stop()
|
|
159
|
+
throw error
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export const originFor = (dnsName, port) => `https://${dnsName}${port === 443 ? '' : `:${port}`}`
|
|
164
|
+
|
|
165
|
+
// ---- The share-only listener ----------------------------------------------------
|
|
166
|
+
|
|
167
|
+
// What the Funnel listener answers. Everything else is a plain 404, so the
|
|
168
|
+
// console, sign-in and member APIs do not exist on the public port.
|
|
169
|
+
export function shareOnlyAllowed(method, pathname) {
|
|
170
|
+
const read = method === 'GET' || method === 'HEAD'
|
|
171
|
+
if (read && (pathname === '/share' || pathname === '/share/')) return true
|
|
172
|
+
if (read && pathname.startsWith('/_console/')) return true
|
|
173
|
+
if (method === 'POST' && (pathname === '/api/shares/preview' || pathname === '/api/shares/open')) return true
|
|
174
|
+
if (/^\/s\/sh_[a-f0-9]{24}(?:\/|$)/.test(pathname)) return true
|
|
175
|
+
if (read && pathname.startsWith('/uc/')) return true
|
|
176
|
+
if ((read || method === 'POST') && pathname === '/report') return true
|
|
177
|
+
if (read && (pathname === '/api/legal' || pathname === '/api/health')) return true
|
|
178
|
+
return false
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Wraps a hosted app (made with the Funnel origin) for the public listener.
|
|
182
|
+
// The console asks /auth/me on every page; here it is always signed out.
|
|
183
|
+
export function shareOnly(app) {
|
|
184
|
+
return (req, res) => {
|
|
185
|
+
const pathname = (req.url || '/').split('?')[0]
|
|
186
|
+
if (req.method === 'GET' && pathname === '/auth/me') {
|
|
187
|
+
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' })
|
|
188
|
+
return res.end(JSON.stringify({ user: null, signup: 'invite' }))
|
|
189
|
+
}
|
|
190
|
+
if (!shareOnlyAllowed(req.method, pathname)) {
|
|
191
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'X-Content-Type-Options': 'nosniff', 'X-Robots-Tag': 'noindex' })
|
|
192
|
+
return res.end('Not found')
|
|
193
|
+
}
|
|
194
|
+
// Browsers may send same-host cookies across ports. Never pass the member
|
|
195
|
+
// session or ceremony cookie to hosted authentication on this listener.
|
|
196
|
+
if (req.headers.cookie) {
|
|
197
|
+
req.headers.cookie = req.headers.cookie
|
|
198
|
+
.split(';')
|
|
199
|
+
.filter((part) => !/^\s*(__Host-)?sw_(session|ceremony)=/.test(part))
|
|
200
|
+
.join(';')
|
|
201
|
+
}
|
|
202
|
+
return app(req, res)
|
|
203
|
+
}
|
|
204
|
+
}
|