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,164 @@
|
|
|
1
|
+
// Broken links: links on captured pages that lead to an error.
|
|
2
|
+
//
|
|
3
|
+
// A capture already reads every page's links (links.js). Links to the same
|
|
4
|
+
// site are checked: one that points at a page on the board takes that page's
|
|
5
|
+
// capture result (no second request), any other is requested once. With
|
|
6
|
+
// `external`, links to other sites are requested too. A link is broken when
|
|
7
|
+
// it answers 4xx/5xx or does not answer at all.
|
|
8
|
+
//
|
|
9
|
+
// The hrefs come from the captured site, so they are untrusted: only http(s)
|
|
10
|
+
// URLs are kept, without credentials or hash, cut to a sane length, and they
|
|
11
|
+
// are stored and shown as plain text, never followed by the board.
|
|
12
|
+
|
|
13
|
+
import { createLinkMatcher } from './links.js'
|
|
14
|
+
|
|
15
|
+
const URL_MAX = 2048
|
|
16
|
+
export const SITE_CHECK_MAX = 300
|
|
17
|
+
export const EXTERNAL_CHECK_MAX = 100
|
|
18
|
+
const CHECK_CONCURRENCY = 4
|
|
19
|
+
|
|
20
|
+
function normalize(href) {
|
|
21
|
+
if (typeof href !== 'string' || !href || href.length > URL_MAX) return null
|
|
22
|
+
let url
|
|
23
|
+
try {
|
|
24
|
+
url = new URL(href)
|
|
25
|
+
} catch {
|
|
26
|
+
return null
|
|
27
|
+
}
|
|
28
|
+
if (!/^https?:$/.test(url.protocol) || url.username || url.password) return null
|
|
29
|
+
url.hash = ''
|
|
30
|
+
return url
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Adds a page's hrefs to `found` (Map url -> { kind, from: Set }). Same-site
|
|
34
|
+
// links are inside the base URL's origin and base path.
|
|
35
|
+
export function collectLinks(found, hrefs, { baseUrl, pageId, external = false }) {
|
|
36
|
+
if (!Array.isArray(hrefs)) return found
|
|
37
|
+
const base = new URL(baseUrl)
|
|
38
|
+
const prefix = base.pathname.replace(/\/+$/, '')
|
|
39
|
+
for (const href of hrefs) {
|
|
40
|
+
const url = normalize(href)
|
|
41
|
+
if (!url) continue
|
|
42
|
+
const site = url.origin === base.origin && (!prefix || url.pathname === prefix || url.pathname.startsWith(`${prefix}/`))
|
|
43
|
+
if (!site && !external) continue
|
|
44
|
+
const key = url.toString()
|
|
45
|
+
if (!found.has(key)) found.set(key, { kind: site ? 'site' : 'external', from: new Set() })
|
|
46
|
+
found.get(key).from.add(pageId)
|
|
47
|
+
}
|
|
48
|
+
return found
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// What a board page's capture says about a link to it: { status } (the HTTP
|
|
52
|
+
// status), { error } (it never answered), or null (not captured).
|
|
53
|
+
function fromCapture(shots) {
|
|
54
|
+
const list = Object.values(shots || {}).filter((shot) => shot && typeof shot === 'object')
|
|
55
|
+
if (!list.length) return null
|
|
56
|
+
const answered = list.find((shot) => Number.isInteger(shot.httpStatus))
|
|
57
|
+
if (answered) return { status: answered.httpStatus }
|
|
58
|
+
const failed = list.find((shot) => shot.status === 'failed')
|
|
59
|
+
return failed ? { error: String(failed.error || 'failed').slice(0, 200) } : null
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function pool(items, size, worker) {
|
|
63
|
+
let next = 0
|
|
64
|
+
await Promise.all(
|
|
65
|
+
Array.from({ length: Math.min(size, items.length) }, async () => {
|
|
66
|
+
while (next < items.length) {
|
|
67
|
+
const index = next
|
|
68
|
+
next += 1
|
|
69
|
+
await worker(items[index])
|
|
70
|
+
}
|
|
71
|
+
}),
|
|
72
|
+
)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Checks the collected links. `request(url)` resolves { status } or
|
|
76
|
+
// { error }. Returns { broken, checked, skipped }: broken is a sorted list of
|
|
77
|
+
// { url, path, kind, status, error, from }.
|
|
78
|
+
export async function checkLinks(found, { board, baseUrl, manifestPages = {}, request }) {
|
|
79
|
+
const match = createLinkMatcher(board, baseUrl)
|
|
80
|
+
const broken = []
|
|
81
|
+
const toRequest = []
|
|
82
|
+
let skipped = 0
|
|
83
|
+
let checked = 0
|
|
84
|
+
const counts = { site: 0, external: 0 }
|
|
85
|
+
for (const [url, info] of found) {
|
|
86
|
+
const pageId = info.kind === 'site' ? match(url) : null
|
|
87
|
+
if (pageId) {
|
|
88
|
+
const result = fromCapture(manifestPages[pageId])
|
|
89
|
+
if (!result) continue
|
|
90
|
+
checked += 1
|
|
91
|
+
if (result.error || result.status >= 400) broken.push(entry(url, info, result, baseUrl))
|
|
92
|
+
continue
|
|
93
|
+
}
|
|
94
|
+
counts[info.kind] += 1
|
|
95
|
+
if (counts[info.kind] > (info.kind === 'site' ? SITE_CHECK_MAX : EXTERNAL_CHECK_MAX)) {
|
|
96
|
+
skipped += 1
|
|
97
|
+
continue
|
|
98
|
+
}
|
|
99
|
+
toRequest.push([url, info])
|
|
100
|
+
}
|
|
101
|
+
await pool(toRequest, CHECK_CONCURRENCY, async ([url, info]) => {
|
|
102
|
+
let result
|
|
103
|
+
try {
|
|
104
|
+
result = await request(url)
|
|
105
|
+
} catch (error) {
|
|
106
|
+
result = { error: String(error?.message || error).split('\n')[0] }
|
|
107
|
+
}
|
|
108
|
+
checked += 1
|
|
109
|
+
if (result.error || result.status >= 400) broken.push(entry(url, info, result, baseUrl))
|
|
110
|
+
})
|
|
111
|
+
broken.sort((a, b) => (a.kind === b.kind ? a.url.localeCompare(b.url) : a.kind === 'site' ? -1 : 1))
|
|
112
|
+
return { broken, checked, skipped }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function entry(url, info, result, baseUrl) {
|
|
116
|
+
const parsed = new URL(url)
|
|
117
|
+
const base = new URL(baseUrl)
|
|
118
|
+
const prefix = base.pathname.replace(/\/+$/, '')
|
|
119
|
+
const sitePath = `${parsed.pathname.slice(prefix.length) || '/'}${parsed.search}`
|
|
120
|
+
return {
|
|
121
|
+
url,
|
|
122
|
+
path: info.kind === 'site' ? sitePath : null,
|
|
123
|
+
kind: info.kind,
|
|
124
|
+
status: Number.isInteger(result.status) ? result.status : null,
|
|
125
|
+
error: result.error ? String(result.error).slice(0, 200) : null,
|
|
126
|
+
from: [...info.from].sort(),
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// A partial capture (--only) re-reads the links of some pages: their old
|
|
131
|
+
// entries go, the rest stay, and a link to one of those pages that now
|
|
132
|
+
// captured fine is no longer broken.
|
|
133
|
+
export function mergeBroken(previous, fresh, { recaptured, board, baseUrl, manifestPages = {} }) {
|
|
134
|
+
const again = new Set(recaptured)
|
|
135
|
+
const match = createLinkMatcher(board, baseUrl)
|
|
136
|
+
const byUrl = new Map()
|
|
137
|
+
for (const item of Array.isArray(previous) ? previous : []) {
|
|
138
|
+
if (!item || typeof item.url !== 'string') continue
|
|
139
|
+
const from = (item.from || []).filter((id) => !again.has(id))
|
|
140
|
+
if (!from.length) continue
|
|
141
|
+
const pageId = item.kind === 'site' ? match(item.url) : null
|
|
142
|
+
if (pageId && again.has(pageId)) {
|
|
143
|
+
const result = fromCapture(manifestPages[pageId])
|
|
144
|
+
if (result && !result.error && result.status < 400) continue
|
|
145
|
+
}
|
|
146
|
+
byUrl.set(item.url, { ...item, from })
|
|
147
|
+
}
|
|
148
|
+
for (const item of fresh) {
|
|
149
|
+
const old = byUrl.get(item.url)
|
|
150
|
+
byUrl.set(item.url, old ? { ...item, from: [...new Set([...old.from, ...item.from])].sort() } : item)
|
|
151
|
+
}
|
|
152
|
+
return [...byUrl.values()].sort((a, b) => (a.kind === b.kind ? a.url.localeCompare(b.url) : a.kind === 'site' ? -1 : 1))
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// " 404 /missing (from home, about)" lines.
|
|
156
|
+
export function formatBroken(broken, { max = 20 } = {}) {
|
|
157
|
+
const lines = broken.slice(0, max).map((item) => {
|
|
158
|
+
const what = item.status ? String(item.status) : 'fail'
|
|
159
|
+
const where = item.path ?? item.url
|
|
160
|
+
return ` ${what.padEnd(4)} ${where} (from ${item.from.join(', ')})${item.error ? `: ${item.error}` : ''}`
|
|
161
|
+
})
|
|
162
|
+
if (broken.length > max) lines.push(` ... and ${broken.length - max} more`)
|
|
163
|
+
return lines
|
|
164
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import http from 'node:http'
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import { BridgeError, loadBridgeConfig, privatePath, projectFor, within } from './config.js'
|
|
4
|
+
|
|
5
|
+
export function createBuzzClient(file, config) {
|
|
6
|
+
const bridge = loadBridgeConfig(file)
|
|
7
|
+
const root = fs.realpathSync(config.dir)
|
|
8
|
+
// None of this private state may be served as captures, shell assets or a
|
|
9
|
+
// source project's files, including a custom outputDir outside the root.
|
|
10
|
+
if ([bridge.file, bridge.socketPath, bridge.stateDir].some((p) => within(p, config.outputDir)))
|
|
11
|
+
throw new Error('Buzz private state must be outside capture/export data.')
|
|
12
|
+
const available = (board) => {
|
|
13
|
+
try {
|
|
14
|
+
projectFor(bridge, root, board)
|
|
15
|
+
return true
|
|
16
|
+
} catch {
|
|
17
|
+
return false
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return {
|
|
21
|
+
available,
|
|
22
|
+
request(action, board, body = {}) {
|
|
23
|
+
projectFor(bridge, root, board)
|
|
24
|
+
privatePath(bridge.socketPath, 'socket')
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const request = http.request(
|
|
27
|
+
{ socketPath: bridge.socketPath, path: `/${action}`, method: 'POST', headers: { 'Content-Type': 'application/json' } },
|
|
28
|
+
(response) => {
|
|
29
|
+
let output = ''
|
|
30
|
+
response.on('data', (part) => {
|
|
31
|
+
output += part
|
|
32
|
+
if (Buffer.byteLength(output) > 8 * 1024 * 1024) request.destroy(new Error('Bridge response too large.'))
|
|
33
|
+
})
|
|
34
|
+
response.on('end', () => {
|
|
35
|
+
try {
|
|
36
|
+
const data = JSON.parse(output)
|
|
37
|
+
if (response.statusCode !== 200)
|
|
38
|
+
return reject(
|
|
39
|
+
new BridgeError(
|
|
40
|
+
data.error?.code || 'bridge_unavailable',
|
|
41
|
+
data.error?.message || 'Buzz gateway unavailable.',
|
|
42
|
+
response.statusCode,
|
|
43
|
+
),
|
|
44
|
+
)
|
|
45
|
+
resolve(data)
|
|
46
|
+
} catch {
|
|
47
|
+
reject(new BridgeError('bridge_unavailable', 'Buzz gateway returned an invalid response.', 503))
|
|
48
|
+
}
|
|
49
|
+
})
|
|
50
|
+
response.on('error', () =>
|
|
51
|
+
reject(
|
|
52
|
+
new BridgeError(
|
|
53
|
+
'bridge_unavailable',
|
|
54
|
+
'Buzz gateway disconnected. Delivery may be unknown; refresh receipts before sending again.',
|
|
55
|
+
503,
|
|
56
|
+
),
|
|
57
|
+
),
|
|
58
|
+
)
|
|
59
|
+
},
|
|
60
|
+
)
|
|
61
|
+
request.setTimeout(100000, () => request.destroy())
|
|
62
|
+
request.on('error', () =>
|
|
63
|
+
reject(
|
|
64
|
+
new BridgeError(
|
|
65
|
+
'bridge_unavailable',
|
|
66
|
+
'Start the private Buzz gateway on this computer. Check receipts before retrying a send.',
|
|
67
|
+
503,
|
|
68
|
+
),
|
|
69
|
+
),
|
|
70
|
+
)
|
|
71
|
+
request.end(JSON.stringify({ ...body, root, board }))
|
|
72
|
+
})
|
|
73
|
+
},
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// Operator-only configuration. This file contains public identities and paths,
|
|
2
|
+
// never credentials. The browser cannot supply any of these values.
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import os from 'node:os'
|
|
6
|
+
|
|
7
|
+
export const HEX64 = /^[0-9a-f]{64}$/
|
|
8
|
+
export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
|
9
|
+
export const CLI = path.join(os.homedir(), '.local/bin/buzz')
|
|
10
|
+
// Where each transport signer's private EnvironmentFile is. There is no
|
|
11
|
+
// default: the bridge is off until the operator names both files, in the
|
|
12
|
+
// operator map (`signerFiles`) or in these variables (the map wins).
|
|
13
|
+
export const SIGNER_FILE_VARS = Object.freeze({ codex: 'SHAPEWALL_BUZZ_SIGNER_CODEX', claude: 'SHAPEWALL_BUZZ_SIGNER_CLAUDE' })
|
|
14
|
+
export function signerFiles(config, env = process.env) {
|
|
15
|
+
if (
|
|
16
|
+
config.signerFiles !== undefined &&
|
|
17
|
+
(!config.signerFiles || typeof config.signerFiles !== 'object' || Array.isArray(config.signerFiles))
|
|
18
|
+
)
|
|
19
|
+
throw new Error('signerFiles must map codex and claude to absolute file paths.')
|
|
20
|
+
const out = {}
|
|
21
|
+
for (const [id, name] of Object.entries(SIGNER_FILE_VARS)) {
|
|
22
|
+
const value = config.signerFiles?.[id] ?? env[name]
|
|
23
|
+
if (value === undefined || value === '')
|
|
24
|
+
throw new Error(
|
|
25
|
+
`The Buzz bridge is off: no signer file for ${id}. Set signerFiles.${id} in the bridge configuration, or ${name}, to its private EnvironmentFile.`,
|
|
26
|
+
)
|
|
27
|
+
if (typeof value !== 'string' || !path.isAbsolute(value)) throw new Error('Signer file paths must be absolute.')
|
|
28
|
+
out[id] = path.resolve(value)
|
|
29
|
+
}
|
|
30
|
+
return Object.freeze(out)
|
|
31
|
+
}
|
|
32
|
+
export const SIGNERS = Object.freeze({ codex: 'claude', claude: 'codex', goose: 'codex' })
|
|
33
|
+
export const within = (file, dir) => {
|
|
34
|
+
const relative = path.relative(dir, file)
|
|
35
|
+
return !relative || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export class BridgeError extends Error {
|
|
39
|
+
constructor(code, message, status = 400) {
|
|
40
|
+
super(message)
|
|
41
|
+
this.code = code
|
|
42
|
+
this.status = status
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function noSymlinks(file) {
|
|
47
|
+
const absolute = path.resolve(file)
|
|
48
|
+
let current = path.parse(absolute).root
|
|
49
|
+
for (const part of absolute.slice(current.length).split(path.sep).filter(Boolean)) {
|
|
50
|
+
current = path.join(current, part)
|
|
51
|
+
if (fs.lstatSync(current).isSymbolicLink()) throw new Error('Bridge paths must not contain symlinks.')
|
|
52
|
+
}
|
|
53
|
+
return absolute
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function privatePath(file, kind = 'file') {
|
|
57
|
+
noSymlinks(file)
|
|
58
|
+
const stat = fs.lstatSync(file)
|
|
59
|
+
if (
|
|
60
|
+
stat.uid !== process.getuid() ||
|
|
61
|
+
stat.mode & 0o077 ||
|
|
62
|
+
(kind === 'dir' ? !stat.isDirectory() : kind === 'socket' ? !stat.isSocket() : !stat.isFile())
|
|
63
|
+
)
|
|
64
|
+
throw new Error('Bridge paths must be owned by this user and private to this user.')
|
|
65
|
+
return file
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function loadBridgeConfig(file, env = process.env) {
|
|
69
|
+
file = path.resolve(file)
|
|
70
|
+
privatePath(path.dirname(file), 'dir')
|
|
71
|
+
privatePath(file)
|
|
72
|
+
if (fs.statSync(file).size > 65536) throw new Error('Bridge configuration is too large.')
|
|
73
|
+
const config = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
74
|
+
if (
|
|
75
|
+
config.version !== 1 ||
|
|
76
|
+
!UUID.test(config.channel?.id) ||
|
|
77
|
+
typeof config.channel?.name !== 'string' ||
|
|
78
|
+
config.channel.name.length > 80 ||
|
|
79
|
+
!HEX64.test(config.ownerPubkey)
|
|
80
|
+
)
|
|
81
|
+
throw new Error('Invalid bridge identity or channel configuration.')
|
|
82
|
+
if (!Array.isArray(config.agents) || config.agents.length !== 3 || new Set(config.agents.map((a) => a.id)).size !== 3)
|
|
83
|
+
throw new Error('Configure exactly codex, claude and goose.')
|
|
84
|
+
for (const agent of config.agents) {
|
|
85
|
+
if (!Object.hasOwn(SIGNERS, agent.id) || !HEX64.test(agent.pubkey) || typeof agent.name !== 'string' || agent.name.length > 80)
|
|
86
|
+
throw new Error('Invalid bridge agent configuration.')
|
|
87
|
+
}
|
|
88
|
+
if (new Set([config.ownerPubkey, ...config.agents.map((a) => a.pubkey)]).size !== 4)
|
|
89
|
+
throw new Error('Bridge identities must be distinct.')
|
|
90
|
+
if (!Array.isArray(config.projects) || !config.projects.length || config.projects.length > 16)
|
|
91
|
+
throw new Error('Configure the allowed source projects.')
|
|
92
|
+
for (const project of config.projects) {
|
|
93
|
+
if (
|
|
94
|
+
typeof project.root !== 'string' ||
|
|
95
|
+
!path.isAbsolute(project.root) ||
|
|
96
|
+
fs.realpathSync(project.root) !== project.root ||
|
|
97
|
+
typeof project.name !== 'string' ||
|
|
98
|
+
project.name.length > 100 ||
|
|
99
|
+
!Array.isArray(project.boards) ||
|
|
100
|
+
!project.boards.length ||
|
|
101
|
+
project.boards.length > 32 ||
|
|
102
|
+
project.boards.some((id) => !/^[a-z0-9][a-z0-9-]{0,63}$/.test(id))
|
|
103
|
+
)
|
|
104
|
+
throw new Error('Invalid fixed project mapping.')
|
|
105
|
+
}
|
|
106
|
+
if (new Set(config.projects.map((p) => p.root)).size !== config.projects.length) throw new Error('Duplicate project mapping.')
|
|
107
|
+
const relay = new URL(config.relayUrl)
|
|
108
|
+
if (
|
|
109
|
+
!['https:', 'wss:'].includes(relay.protocol) ||
|
|
110
|
+
relay.username ||
|
|
111
|
+
relay.password ||
|
|
112
|
+
relay.pathname !== '/' ||
|
|
113
|
+
relay.search ||
|
|
114
|
+
relay.hash
|
|
115
|
+
)
|
|
116
|
+
throw new Error('Use the fixed authenticated HTTPS/WSS Buzz relay origin.')
|
|
117
|
+
for (const key of ['socketPath', 'stateDir']) {
|
|
118
|
+
if (typeof config[key] !== 'string' || !path.isAbsolute(config[key])) throw new Error('Bridge paths must be absolute.')
|
|
119
|
+
privatePath(path.dirname(config[key]), 'dir')
|
|
120
|
+
}
|
|
121
|
+
if (
|
|
122
|
+
Buffer.byteLength(config.socketPath) > 100 ||
|
|
123
|
+
config.socketPath === config.stateDir ||
|
|
124
|
+
path.dirname(config.socketPath) === config.stateDir
|
|
125
|
+
)
|
|
126
|
+
throw new Error('Use a short socket path outside the journal directory.')
|
|
127
|
+
const signers = signerFiles(config, env)
|
|
128
|
+
if (
|
|
129
|
+
config.projects.some((project) =>
|
|
130
|
+
[file, config.socketPath, config.stateDir, ...Object.values(signers)].some((p) => within(p, project.root)),
|
|
131
|
+
)
|
|
132
|
+
)
|
|
133
|
+
throw new Error('Keep bridge configuration, socket, journal and signer files outside source projects and capture/export data.')
|
|
134
|
+
return Object.freeze({ ...config, signerFiles: signers, file })
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function projectFor(config, root, board) {
|
|
138
|
+
const project = config.projects.find((p) => p.root === root && p.boards.includes(board))
|
|
139
|
+
if (!project) throw new BridgeError('project_denied', 'This source project and board are not mapped to Buzz.', 403)
|
|
140
|
+
return project
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function publicBridge(config, root, board) {
|
|
144
|
+
projectFor(config, root, board)
|
|
145
|
+
return {
|
|
146
|
+
channel: config.channel,
|
|
147
|
+
sourceRoot: root,
|
|
148
|
+
agents: config.agents.map((agent) => ({ ...agent, signer: config.agents.find((a) => a.id === SIGNERS[agent.id]) })),
|
|
149
|
+
semantics: 'shared-channel',
|
|
150
|
+
}
|
|
151
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export const BUZZ_CREDENTIAL_NAMES = ['BUZZ_PRIVATE_KEY', 'BUZZ_AUTH_TAG', 'BUZZ_RELAY_URL']
|
|
2
|
+
|
|
3
|
+
export function withoutBuzzCredentials(env) {
|
|
4
|
+
return Object.fromEntries(Object.entries(env).filter(([name]) => !BUZZ_CREDENTIAL_NAMES.includes(name)))
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function requireCleanBuzzEnvironment(env = process.env) {
|
|
8
|
+
if (BUZZ_CREDENTIAL_NAMES.some((name) => env[name] !== undefined))
|
|
9
|
+
throw new Error('Launch Shapewall without inherited Buzz credential variables. Use the shapewall CLI clean launcher.')
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const signerBaseEnvironment = () => ({ HOME: os.homedir(), PATH: '/usr/bin:/bin', LANG: 'C.UTF-8' })
|
|
13
|
+
import os from 'node:os'
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import http from 'node:http'
|
|
3
|
+
import net from 'node:net'
|
|
4
|
+
import express from 'express'
|
|
5
|
+
import { BridgeError, UUID, loadBridgeConfig, privatePath, projectFor, publicBridge, SIGNERS } from './config.js'
|
|
6
|
+
import { dispatchMatches, envelope, hash, MAX_TEXT_BYTES, verifiedFeed } from './verify.js'
|
|
7
|
+
import { openJournal } from './store.js'
|
|
8
|
+
import { runSigner } from './transport.js'
|
|
9
|
+
import { requireCleanBuzzEnvironment } from './environment.js'
|
|
10
|
+
|
|
11
|
+
const cleanReceipt = (r) => ({
|
|
12
|
+
requestId: r.requestId,
|
|
13
|
+
status: r.status,
|
|
14
|
+
eventId: r.eventId || null,
|
|
15
|
+
createdAt: r.createdAt,
|
|
16
|
+
target: r.target,
|
|
17
|
+
signer: r.signer,
|
|
18
|
+
envelope: r.envelope,
|
|
19
|
+
message:
|
|
20
|
+
r.status === 'sent'
|
|
21
|
+
? 'Sent to Buzz. Recapture and review changes manually.'
|
|
22
|
+
: r.status === 'not_sent'
|
|
23
|
+
? 'Not sent: host identity, attestation, membership or configuration preflight failed.'
|
|
24
|
+
: 'Delivery is unknown. Check the shared Buzz conversation before creating a new request. This request will not resend.',
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
export function createGateway(config, { run = runSigner, journal = openJournal(config.stateDir) } = {}) {
|
|
28
|
+
const app = express()
|
|
29
|
+
app.disable('x-powered-by')
|
|
30
|
+
app.use(express.json({ limit: '24kb' }))
|
|
31
|
+
let working = false
|
|
32
|
+
const handle =
|
|
33
|
+
(fn, busy = false) =>
|
|
34
|
+
async (req, res) => {
|
|
35
|
+
res.setHeader('Cache-Control', 'no-store')
|
|
36
|
+
if (working && busy)
|
|
37
|
+
return res.status(409).json({ error: { code: 'bridge_busy', message: 'Another Buzz operation is in progress. Refresh shortly.' } })
|
|
38
|
+
if (busy) working = true
|
|
39
|
+
try {
|
|
40
|
+
await fn(req, res)
|
|
41
|
+
} catch (error) {
|
|
42
|
+
res.status(error instanceof BridgeError ? error.status : 503).json({
|
|
43
|
+
error: {
|
|
44
|
+
code: error instanceof BridgeError ? error.code : 'bridge_unavailable',
|
|
45
|
+
message:
|
|
46
|
+
error instanceof BridgeError ? error.message : 'The private Buzz gateway could not finish. No automatic resend will occur.',
|
|
47
|
+
},
|
|
48
|
+
})
|
|
49
|
+
} finally {
|
|
50
|
+
if (busy) working = false
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const context = (body) => {
|
|
54
|
+
if (!body || typeof body.root !== 'string' || typeof body.board !== 'string')
|
|
55
|
+
throw new BridgeError('invalid_request', 'Select a mapped source board.')
|
|
56
|
+
return projectFor(config, body.root, body.board)
|
|
57
|
+
}
|
|
58
|
+
const receiptsFor = (body) => journal.list(body.root, body.board).map(cleanReceipt)
|
|
59
|
+
app.post(
|
|
60
|
+
'/view',
|
|
61
|
+
handle(async (req, res) => {
|
|
62
|
+
context(req.body)
|
|
63
|
+
res.json({ ...publicBridge(config, req.body.root, req.body.board), receipts: receiptsFor(req.body) })
|
|
64
|
+
}),
|
|
65
|
+
)
|
|
66
|
+
app.post(
|
|
67
|
+
'/feed',
|
|
68
|
+
handle(async (req, res) => {
|
|
69
|
+
context(req.body)
|
|
70
|
+
const result = await run(config.file, { action: 'feed' })
|
|
71
|
+
const events = verifiedFeed(result.events, config)
|
|
72
|
+
// Only the exact outgoing signed envelope can reconcile an ambiguous
|
|
73
|
+
// dispatch. Agent responses never complete or resolve a Shapewall item.
|
|
74
|
+
for (const receipt of journal.list(req.body.root, req.body.board)) {
|
|
75
|
+
if (!['unknown', 'publishing'].includes(receipt.status)) continue
|
|
76
|
+
const event = events.find((e) => dispatchMatches(e, receipt))
|
|
77
|
+
if (event) journal.update(receipt.requestId, { status: 'sent', eventId: event.id })
|
|
78
|
+
}
|
|
79
|
+
// Keep raw signature/tag material inside the gateway. In particular,
|
|
80
|
+
// owner attestations carried by signed events are not browser state.
|
|
81
|
+
res.json({
|
|
82
|
+
events: events.map((e) => ({ id: e.id, pubkey: e.pubkey, createdAt: e.created_at, content: e.content, verified: true })),
|
|
83
|
+
receipts: receiptsFor(req.body),
|
|
84
|
+
completeHistory: false,
|
|
85
|
+
})
|
|
86
|
+
}, true),
|
|
87
|
+
)
|
|
88
|
+
app.post(
|
|
89
|
+
'/dispatch',
|
|
90
|
+
handle(async (req, res) => {
|
|
91
|
+
const body = req.body
|
|
92
|
+
const project = context(body)
|
|
93
|
+
if (
|
|
94
|
+
Object.keys(body).some((k) => !['root', 'board', 'target', 'text', 'requestId'].includes(k)) ||
|
|
95
|
+
!UUID.test(body.requestId) ||
|
|
96
|
+
typeof body.text !== 'string' ||
|
|
97
|
+
!body.text.trim() ||
|
|
98
|
+
Buffer.byteLength(body.text) > MAX_TEXT_BYTES
|
|
99
|
+
)
|
|
100
|
+
throw new BridgeError('invalid_request', 'Supply a request id, configured target and up to 12,000 bytes of text.')
|
|
101
|
+
const target = config.agents.find((a) => a.id === body.target)
|
|
102
|
+
if (!target) throw new BridgeError('target_denied', 'Choose a configured Buzz agent.')
|
|
103
|
+
const signer = config.agents.find((a) => a.id === SIGNERS[target.id])
|
|
104
|
+
const content = envelope({ ...body, project, signer, target })
|
|
105
|
+
const requestHash = hash(JSON.stringify([body.root, body.board, target.pubkey, signer.pubkey, config.channel.id, content]))
|
|
106
|
+
const previous = journal.get(body.requestId)
|
|
107
|
+
if (previous) {
|
|
108
|
+
if (previous.requestHash !== requestHash)
|
|
109
|
+
throw new BridgeError('request_conflict', 'This request id already belongs to different content.', 409)
|
|
110
|
+
return res.json({ receipt: cleanReceipt(previous) })
|
|
111
|
+
}
|
|
112
|
+
const receipt = journal.add({
|
|
113
|
+
requestId: body.requestId,
|
|
114
|
+
root: body.root,
|
|
115
|
+
board: body.board,
|
|
116
|
+
requestHash,
|
|
117
|
+
target,
|
|
118
|
+
signer,
|
|
119
|
+
envelope: content,
|
|
120
|
+
envelopeHash: hash(content),
|
|
121
|
+
createdAt: new Date().toISOString(),
|
|
122
|
+
status: 'publishing',
|
|
123
|
+
})
|
|
124
|
+
let result
|
|
125
|
+
try {
|
|
126
|
+
result = await run(config.file, { ...body, action: 'dispatch' })
|
|
127
|
+
} catch {
|
|
128
|
+
result = { outcome: 'unknown' }
|
|
129
|
+
}
|
|
130
|
+
journal.update(body.requestId, { status: result.outcome === 'not_sent' ? 'not_sent' : 'unknown' })
|
|
131
|
+
if (result.outcome === 'accepted') {
|
|
132
|
+
try {
|
|
133
|
+
const signed = await run(config.file, { action: 'event', eventId: result.eventId })
|
|
134
|
+
const event = verifiedFeed(signed.events, config).find((e) => e.id === result.eventId && dispatchMatches(e, receipt))
|
|
135
|
+
if (event) journal.update(body.requestId, { status: 'sent', eventId: event.id })
|
|
136
|
+
} catch {
|
|
137
|
+
/* accepted but not yet independently verified: unknown */
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
res.json({ receipt: cleanReceipt(receipt) })
|
|
141
|
+
}, true),
|
|
142
|
+
)
|
|
143
|
+
app.use((error, req, res, _next) =>
|
|
144
|
+
res.status(error.status || 400).json({ error: { code: 'invalid_request', message: 'Invalid bounded JSON request.' } }),
|
|
145
|
+
)
|
|
146
|
+
return { app, close: () => journal.close(), busy: () => working }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function staleSocket(file) {
|
|
150
|
+
if (!fs.existsSync(file)) return
|
|
151
|
+
privatePath(file, 'socket')
|
|
152
|
+
await new Promise((resolve, reject) => {
|
|
153
|
+
const probe = net.createConnection(file)
|
|
154
|
+
probe.once('connect', () => {
|
|
155
|
+
probe.destroy()
|
|
156
|
+
reject(new Error('A gateway already owns this socket.'))
|
|
157
|
+
})
|
|
158
|
+
probe.once('error', (error) => {
|
|
159
|
+
if (error.code !== 'ECONNREFUSED') return reject(error)
|
|
160
|
+
fs.unlinkSync(file)
|
|
161
|
+
resolve()
|
|
162
|
+
})
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export async function startGateway(file, options = {}) {
|
|
167
|
+
requireCleanBuzzEnvironment()
|
|
168
|
+
const config = loadBridgeConfig(file)
|
|
169
|
+
const gateway = createGateway(config, options)
|
|
170
|
+
let server
|
|
171
|
+
try {
|
|
172
|
+
await staleSocket(config.socketPath)
|
|
173
|
+
server = http.createServer(gateway.app)
|
|
174
|
+
await new Promise((resolve, reject) => {
|
|
175
|
+
server.once('error', reject)
|
|
176
|
+
server.listen(config.socketPath, resolve)
|
|
177
|
+
})
|
|
178
|
+
fs.chmodSync(config.socketPath, 0o600)
|
|
179
|
+
} catch (error) {
|
|
180
|
+
gateway.close()
|
|
181
|
+
throw error
|
|
182
|
+
}
|
|
183
|
+
return {
|
|
184
|
+
...gateway,
|
|
185
|
+
server,
|
|
186
|
+
config,
|
|
187
|
+
async stop() {
|
|
188
|
+
await new Promise((resolve) => server.close(resolve))
|
|
189
|
+
gateway.close()
|
|
190
|
+
},
|
|
191
|
+
}
|
|
192
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import express from 'express'
|
|
2
|
+
import { localRequest, settingsTokenOk, sameOriginWrite } from '../agent/settings-routes.js'
|
|
3
|
+
import { BridgeError } from './config.js'
|
|
4
|
+
|
|
5
|
+
// A paired viewer or an ordinary account session is insufficient. Remote
|
|
6
|
+
// access requires the server's existing verified Tailscale owner identity;
|
|
7
|
+
// direct host access requires the current process's private owner capability.
|
|
8
|
+
export function buzzOwner(req, { settingsToken, shared, readOnly }) {
|
|
9
|
+
return !shared && !readOnly && (req.shapewallAccess?.kind === 'identity' || (localRequest(req) && settingsTokenOk(req, settingsToken)))
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function buzzRouter({ client, settingsToken, shared, readOnly, config, expectedOrigin = null }) {
|
|
13
|
+
const router = express.Router()
|
|
14
|
+
const owner = (req) => buzzOwner(req, { settingsToken, shared, readOnly })
|
|
15
|
+
router.use((req, res, next) => {
|
|
16
|
+
res.setHeader('Cache-Control', 'no-store')
|
|
17
|
+
if (!client || !owner(req)) return res.status(404).json({ error: { code: 'not_found', message: 'No such API route.' } })
|
|
18
|
+
let originOk = sameOriginWrite(req)
|
|
19
|
+
if (originOk) {
|
|
20
|
+
const origin = new URL(req.headers.origin)
|
|
21
|
+
originOk = expectedOrigin
|
|
22
|
+
? origin.origin === new URL(expectedOrigin).origin
|
|
23
|
+
: origin.protocol === (req.socket.encrypted ? 'https:' : 'http:')
|
|
24
|
+
}
|
|
25
|
+
if (req.method !== 'GET' && (!req.is('application/json') || !originOk))
|
|
26
|
+
return res.status(403).json({ error: { code: 'bad_origin', message: 'Use the owner page on this Shapewall installation.' } })
|
|
27
|
+
next()
|
|
28
|
+
})
|
|
29
|
+
const counts = new Map()
|
|
30
|
+
for (const action of ['view', 'feed', 'dispatch'])
|
|
31
|
+
router.post(`/boards/:board/${action}`, async (req, res) => {
|
|
32
|
+
if (!config.boards.some((b) => b.id === req.params.board) || !client.available(req.params.board))
|
|
33
|
+
return res.status(404).json({ error: { code: 'not_found', message: 'This board is not mapped to Buzz.' } })
|
|
34
|
+
if (
|
|
35
|
+
!req.body ||
|
|
36
|
+
typeof req.body !== 'object' ||
|
|
37
|
+
Array.isArray(req.body) ||
|
|
38
|
+
Object.keys(req.body).some((k) => !['target', 'text', 'requestId'].includes(k)) ||
|
|
39
|
+
(action !== 'dispatch' && Object.keys(req.body).length)
|
|
40
|
+
)
|
|
41
|
+
return res.status(400).json({ error: { code: 'invalid_request', message: 'Use only the configured target, text and request id.' } })
|
|
42
|
+
const minute = Math.floor(Date.now() / 60000)
|
|
43
|
+
const previous = counts.get(action)
|
|
44
|
+
const rate = previous?.minute === minute ? previous : { minute, n: 0 }
|
|
45
|
+
counts.set(action, rate)
|
|
46
|
+
if (++rate.n > (action === 'dispatch' ? 10 : 30))
|
|
47
|
+
return res.status(429).json({ error: { code: 'rate_limited', message: 'Wait a minute before making more Buzz requests.' } })
|
|
48
|
+
try {
|
|
49
|
+
res.json(await client.request(action, req.params.board, req.body))
|
|
50
|
+
} catch (error) {
|
|
51
|
+
res.status(error instanceof BridgeError ? error.status : 503).json({
|
|
52
|
+
error: {
|
|
53
|
+
code: error instanceof BridgeError ? error.code : 'bridge_unavailable',
|
|
54
|
+
message:
|
|
55
|
+
error instanceof BridgeError ? error.message : 'The private Buzz gateway is unavailable. Check receipts before retrying.',
|
|
56
|
+
},
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
})
|
|
60
|
+
return { router, owner }
|
|
61
|
+
}
|