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,205 @@
|
|
|
1
|
+
// The only bridge process that reads existing Buzz credentials. Its parent
|
|
2
|
+
// starts it with a minimal environment. Never log inputs, CLI stderr or keys.
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import { spawn } from 'node:child_process'
|
|
5
|
+
import { fileURLToPath } from 'node:url'
|
|
6
|
+
import { schnorr } from '@noble/curves/secp256k1.js'
|
|
7
|
+
import { bech32 } from '@scure/base'
|
|
8
|
+
import { CLI, SIGNERS, HEX64, loadBridgeConfig, privatePath, projectFor } from './config.js'
|
|
9
|
+
import { envelope, MAX_TEXT_BYTES, ownerAttested } from './verify.js'
|
|
10
|
+
import { signerBaseEnvironment } from './environment.js'
|
|
11
|
+
|
|
12
|
+
const PERMITTED = new Set(['BUZZ_PRIVATE_KEY', 'BUZZ_AUTH_TAG', 'BUZZ_RELAY_URL'])
|
|
13
|
+
|
|
14
|
+
// Deliberately a strict subset of EnvironmentFile syntax, never a shell.
|
|
15
|
+
// Unsupported quoting fails closed. Unrelated lines are never interpreted.
|
|
16
|
+
export function parseSignerEnv(text) {
|
|
17
|
+
if (Buffer.byteLength(text) > 131072) throw new Error('Invalid signer environment.')
|
|
18
|
+
const result = {}
|
|
19
|
+
for (const line of text.split(/\r?\n/)) {
|
|
20
|
+
const match = /^\s*([A-Z_][A-Z0-9_]*)=(.*)$/.exec(line)
|
|
21
|
+
if (!match || !PERMITTED.has(match[1])) continue
|
|
22
|
+
if (Object.hasOwn(result, match[1])) throw new Error('Duplicate signer environment variable.')
|
|
23
|
+
let value = match[2].trim()
|
|
24
|
+
if (value.startsWith("'")) {
|
|
25
|
+
if (!value.endsWith("'") || value.slice(1, -1).includes("'")) throw new Error('Unsupported signer quoting.')
|
|
26
|
+
value = value.slice(1, -1)
|
|
27
|
+
} else if (value.startsWith('"')) {
|
|
28
|
+
if (!value.endsWith('"') || /(?<!\\)"/.test(value.slice(1, -1))) throw new Error('Unsupported signer quoting.')
|
|
29
|
+
value = value.slice(1, -1).replace(/\\([\\"`$])/g, '$1')
|
|
30
|
+
if (/\\/.test(value)) throw new Error('Unsupported signer escaping.')
|
|
31
|
+
} else if (/[\\'"\s]/.test(value)) throw new Error('Unsupported signer quoting.')
|
|
32
|
+
if (!value || /[\r\n\0]/.test(value)) throw new Error('Invalid signer environment value.')
|
|
33
|
+
result[match[1]] = value
|
|
34
|
+
}
|
|
35
|
+
if ([...PERMITTED].some((key) => !result[key])) throw new Error('Missing signer environment variable.')
|
|
36
|
+
return result
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function checkSigner(env, signer, config) {
|
|
40
|
+
let secret
|
|
41
|
+
if (HEX64.test(env.BUZZ_PRIVATE_KEY)) secret = Buffer.from(env.BUZZ_PRIVATE_KEY, 'hex')
|
|
42
|
+
else {
|
|
43
|
+
const decoded = bech32.decode(env.BUZZ_PRIVATE_KEY, 100)
|
|
44
|
+
if (decoded.prefix !== 'nsec') throw new Error('Invalid signer identity.')
|
|
45
|
+
secret = Uint8Array.from(bech32.fromWords(decoded.words))
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
const pubkey = Buffer.from(schnorr.getPublicKey(secret)).toString('hex')
|
|
49
|
+
if (
|
|
50
|
+
pubkey !== signer.pubkey ||
|
|
51
|
+
!ownerAttested(env.BUZZ_AUTH_TAG, pubkey, config.ownerPubkey) ||
|
|
52
|
+
new URL(env.BUZZ_RELAY_URL).href !== new URL(config.relayUrl).href
|
|
53
|
+
)
|
|
54
|
+
throw new Error('Signer identity, owner attestation or relay does not match.')
|
|
55
|
+
} finally {
|
|
56
|
+
secret?.fill(0)
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// `buzz channels members` emits objects, not public-key strings. Do not
|
|
61
|
+
// coerce unknown/malformed records or accept an ambiguous duplicate identity.
|
|
62
|
+
export function memberPubkeys(members) {
|
|
63
|
+
if (!Array.isArray(members) || !members.length || members.length > 256) throw new Error('Invalid channel membership response.')
|
|
64
|
+
const seen = new Set()
|
|
65
|
+
for (const member of members) {
|
|
66
|
+
if (
|
|
67
|
+
!member ||
|
|
68
|
+
typeof member !== 'object' ||
|
|
69
|
+
Array.isArray(member) ||
|
|
70
|
+
Object.keys(member).some((key) => !['pubkey', 'role'].includes(key)) ||
|
|
71
|
+
typeof member.pubkey !== 'string' ||
|
|
72
|
+
!HEX64.test(member.pubkey) ||
|
|
73
|
+
typeof member.role !== 'string' ||
|
|
74
|
+
!/^[a-z][a-z-]{0,31}$/.test(member.role) ||
|
|
75
|
+
seen.has(member.pubkey)
|
|
76
|
+
)
|
|
77
|
+
throw new Error('Invalid or duplicate channel membership record.')
|
|
78
|
+
seen.add(member.pubkey)
|
|
79
|
+
}
|
|
80
|
+
return seen
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function cli(args, env, input = '') {
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
const child = spawn(CLI, ['--format', 'json', ...args], {
|
|
86
|
+
env: {
|
|
87
|
+
...signerBaseEnvironment(),
|
|
88
|
+
BUZZ_PRIVATE_KEY: env.BUZZ_PRIVATE_KEY,
|
|
89
|
+
BUZZ_AUTH_TAG: env.BUZZ_AUTH_TAG,
|
|
90
|
+
BUZZ_RELAY_URL: env.BUZZ_RELAY_URL,
|
|
91
|
+
},
|
|
92
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
93
|
+
})
|
|
94
|
+
let output = ''
|
|
95
|
+
let overflow = false
|
|
96
|
+
child.stdout.on('data', (part) => {
|
|
97
|
+
output += part
|
|
98
|
+
if (Buffer.byteLength(output) > 1024 * 1024) {
|
|
99
|
+
overflow = true
|
|
100
|
+
child.kill('SIGKILL')
|
|
101
|
+
}
|
|
102
|
+
})
|
|
103
|
+
child.stdin.on('error', () => {})
|
|
104
|
+
child.stdin.end(input)
|
|
105
|
+
child.on('error', () => reject(new Error('Buzz CLI failed.')))
|
|
106
|
+
child.on('close', (code) => {
|
|
107
|
+
if (code || overflow) return reject(new Error('Buzz CLI failed.'))
|
|
108
|
+
try {
|
|
109
|
+
resolve(JSON.parse(output))
|
|
110
|
+
} catch {
|
|
111
|
+
reject(new Error('Invalid Buzz CLI response.'))
|
|
112
|
+
}
|
|
113
|
+
})
|
|
114
|
+
})
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export async function signerOperation(file, request) {
|
|
118
|
+
const config = loadBridgeConfig(file)
|
|
119
|
+
if (!['feed', 'dispatch', 'event'].includes(request.action)) throw new Error('Unsupported bridge operation.')
|
|
120
|
+
const target = config.agents.find((a) => a.id === request.target)
|
|
121
|
+
const signerId = request.action === 'dispatch' ? SIGNERS[target?.id] : 'codex'
|
|
122
|
+
if (!signerId) throw new Error('Unmapped target.')
|
|
123
|
+
privatePath(config.signerFiles[signerId])
|
|
124
|
+
const env = parseSignerEnv(fs.readFileSync(config.signerFiles[signerId], 'utf8'))
|
|
125
|
+
return performSignerOperation(config, request, env)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Pure fixture seam: production obtains env only from the operator's signer files.
|
|
129
|
+
// Neither operator JSON nor browser input can replace the publisher.
|
|
130
|
+
export async function performSignerOperation(config, request, env, execute = cli) {
|
|
131
|
+
if (!['feed', 'dispatch', 'event'].includes(request.action)) throw new Error('Unsupported bridge operation.')
|
|
132
|
+
const target = config.agents.find((a) => a.id === request.target)
|
|
133
|
+
const signerId = request.action === 'dispatch' ? SIGNERS[target?.id] : 'codex'
|
|
134
|
+
const signer = config.agents.find((a) => a.id === signerId)
|
|
135
|
+
if (!signer) throw new Error('Unmapped target.')
|
|
136
|
+
checkSigner(env, signer, config)
|
|
137
|
+
if (request.action === 'feed')
|
|
138
|
+
return { events: await execute(['messages', 'get', '--channel', config.channel.id, '--limit', '100', '--kinds', '9'], env) }
|
|
139
|
+
if (request.action === 'event') {
|
|
140
|
+
if (!HEX64.test(request.eventId)) throw new Error('Invalid event id.')
|
|
141
|
+
return { events: await execute(['social', 'event', '--event', request.eventId], env) }
|
|
142
|
+
}
|
|
143
|
+
const project = projectFor(config, request.root, request.board)
|
|
144
|
+
if (
|
|
145
|
+
typeof request.text !== 'string' ||
|
|
146
|
+
!request.text.trim() ||
|
|
147
|
+
Buffer.byteLength(request.text) > MAX_TEXT_BYTES ||
|
|
148
|
+
!/^[0-9a-f-]{36}$/.test(request.requestId)
|
|
149
|
+
)
|
|
150
|
+
throw new Error('Invalid owner request.')
|
|
151
|
+
const content = envelope({ ...request, project, signer, target })
|
|
152
|
+
// These guards precede the only publishing call. Visible/URI mentions in
|
|
153
|
+
// every envelope field have been JSON escaped, preserving decoded text.
|
|
154
|
+
if (content.includes('@') || /nostr:/i.test(content)) throw new Error('Unsafe mention content.')
|
|
155
|
+
const members = memberPubkeys(await execute(['channels', 'members', '--channel', config.channel.id], env))
|
|
156
|
+
if (![config.ownerPubkey, signer.pubkey, target.pubkey].every((key) => members.has(key)))
|
|
157
|
+
throw new Error('The configured identities must already belong to the channel.')
|
|
158
|
+
let response
|
|
159
|
+
try {
|
|
160
|
+
response = await execute(
|
|
161
|
+
['messages', 'send', '--channel', config.channel.id, '--kind', '9', '--mention', target.pubkey, '--content', '-'],
|
|
162
|
+
env,
|
|
163
|
+
content,
|
|
164
|
+
)
|
|
165
|
+
} catch {
|
|
166
|
+
return { outcome: 'unknown' }
|
|
167
|
+
}
|
|
168
|
+
// From this point a publish may already have happened. No response shape
|
|
169
|
+
// or classification exception may escape to main's preflight/not_sent path.
|
|
170
|
+
try {
|
|
171
|
+
if (
|
|
172
|
+
response &&
|
|
173
|
+
typeof response === 'object' &&
|
|
174
|
+
!Array.isArray(response) &&
|
|
175
|
+
response.accepted === true &&
|
|
176
|
+
typeof response.event_id === 'string' &&
|
|
177
|
+
HEX64.test(response.event_id) &&
|
|
178
|
+
Array.isArray(response.mention_pubkeys) &&
|
|
179
|
+
response.mention_pubkeys.length === 1 &&
|
|
180
|
+
response.mention_pubkeys[0] === target.pubkey
|
|
181
|
+
)
|
|
182
|
+
return { outcome: 'accepted', eventId: response.event_id }
|
|
183
|
+
} catch {
|
|
184
|
+
/* published but unclassifiable: unknown, never not_sent */
|
|
185
|
+
}
|
|
186
|
+
return { outcome: 'unknown' }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async function main() {
|
|
190
|
+
let input = ''
|
|
191
|
+
for await (const part of process.stdin) {
|
|
192
|
+
input += part
|
|
193
|
+
if (Buffer.byteLength(input) > 32768) throw new Error('Request too large.')
|
|
194
|
+
}
|
|
195
|
+
// Failure before the publishing call is safely not sent; ambiguous send
|
|
196
|
+
// outcomes are caught above and explicitly returned as unknown.
|
|
197
|
+
const result = await signerOperation(process.argv[2], JSON.parse(input))
|
|
198
|
+
process.stdout.write(JSON.stringify(result))
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (process.argv[1] === fileURLToPath(import.meta.url))
|
|
202
|
+
main().catch(() => {
|
|
203
|
+
process.stdout.write(JSON.stringify({ outcome: 'not_sent', code: 'preflight_failed' }))
|
|
204
|
+
process.exitCode = 1
|
|
205
|
+
})
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
4
|
+
import { BridgeError, privatePath } from './config.js'
|
|
5
|
+
|
|
6
|
+
// One foreground gateway owns this private journal. Persist the intent before
|
|
7
|
+
// any publish. Interrupted/ambiguous requests stay unknown and never resend.
|
|
8
|
+
export function openJournal(dir) {
|
|
9
|
+
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { mode: 0o700 })
|
|
10
|
+
privatePath(dir, 'dir')
|
|
11
|
+
const lock = path.join(dir, 'gateway.lock')
|
|
12
|
+
let lockFd
|
|
13
|
+
const acquire = () => fs.openSync(lock, 'wx', 0o600)
|
|
14
|
+
try {
|
|
15
|
+
lockFd = acquire()
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (error.code !== 'EEXIST') throw error
|
|
18
|
+
privatePath(lock)
|
|
19
|
+
const owner = JSON.parse(fs.readFileSync(lock, 'utf8'))
|
|
20
|
+
if (!Number.isInteger(owner.pid) || owner.pid < 1)
|
|
21
|
+
throw new Error('Invalid gateway lock. Inspect it before starting another gateway.', { cause: error })
|
|
22
|
+
try {
|
|
23
|
+
process.kill(owner.pid, 0)
|
|
24
|
+
} catch (probe) {
|
|
25
|
+
if (probe.code === 'ESRCH') {
|
|
26
|
+
fs.unlinkSync(lock)
|
|
27
|
+
lockFd = acquire()
|
|
28
|
+
} else throw probe
|
|
29
|
+
}
|
|
30
|
+
if (lockFd === undefined) throw new Error('A gateway already owns this journal.', { cause: error })
|
|
31
|
+
}
|
|
32
|
+
fs.writeFileSync(lockFd, JSON.stringify({ pid: process.pid }))
|
|
33
|
+
fs.fsyncSync(lockFd)
|
|
34
|
+
const file = path.join(dir, 'receipts.json')
|
|
35
|
+
let receipts = []
|
|
36
|
+
const save = () => {
|
|
37
|
+
const tmp = path.join(dir, `.receipts-${randomUUID()}`)
|
|
38
|
+
const fd = fs.openSync(tmp, 'wx', 0o600)
|
|
39
|
+
try {
|
|
40
|
+
fs.writeFileSync(fd, JSON.stringify(receipts))
|
|
41
|
+
fs.fsyncSync(fd)
|
|
42
|
+
} finally {
|
|
43
|
+
fs.closeSync(fd)
|
|
44
|
+
}
|
|
45
|
+
fs.renameSync(tmp, file)
|
|
46
|
+
const parent = fs.openSync(dir, 'r')
|
|
47
|
+
try {
|
|
48
|
+
fs.fsyncSync(parent)
|
|
49
|
+
} finally {
|
|
50
|
+
fs.closeSync(parent)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
if (fs.existsSync(file)) {
|
|
55
|
+
privatePath(file)
|
|
56
|
+
if (fs.statSync(file).size > 20 * 1024 * 1024) throw new Error('The bridge journal is too large.')
|
|
57
|
+
receipts = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
58
|
+
if (!Array.isArray(receipts) || receipts.length > 500) throw new Error('Invalid bridge journal.')
|
|
59
|
+
for (const receipt of receipts) if (receipt.status === 'publishing') receipt.status = 'unknown'
|
|
60
|
+
save()
|
|
61
|
+
}
|
|
62
|
+
} catch (error) {
|
|
63
|
+
fs.closeSync(lockFd)
|
|
64
|
+
fs.unlinkSync(lock)
|
|
65
|
+
throw error
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
get: (id) => receipts.find((r) => r.requestId === id),
|
|
69
|
+
list: (root, board) => receipts.filter((r) => r.root === root && r.board === board).slice(-50),
|
|
70
|
+
add(receipt) {
|
|
71
|
+
if (receipts.length >= 500)
|
|
72
|
+
throw new BridgeError('journal_full', 'The private receipt journal is full. Archive it on the host before sending more.', 409)
|
|
73
|
+
receipts.push(receipt)
|
|
74
|
+
save()
|
|
75
|
+
return receipt
|
|
76
|
+
},
|
|
77
|
+
update(id, patch) {
|
|
78
|
+
Object.assign(
|
|
79
|
+
receipts.find((r) => r.requestId === id),
|
|
80
|
+
patch,
|
|
81
|
+
)
|
|
82
|
+
save()
|
|
83
|
+
},
|
|
84
|
+
close() {
|
|
85
|
+
fs.closeSync(lockFd)
|
|
86
|
+
fs.unlinkSync(lock)
|
|
87
|
+
},
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
import { SIGNER_FILE_VARS } from './config.js'
|
|
4
|
+
import { signerBaseEnvironment } from './environment.js'
|
|
5
|
+
|
|
6
|
+
const CHILD = fileURLToPath(new URL('./signer-child.js', import.meta.url))
|
|
7
|
+
|
|
8
|
+
export function runSigner(configFile, request) {
|
|
9
|
+
return new Promise((resolve) => {
|
|
10
|
+
const child = spawn(process.execPath, [CHILD, configFile], {
|
|
11
|
+
detached: true,
|
|
12
|
+
// No Buzz, model/provider, SSH or other inherited credentials.
|
|
13
|
+
// Only the two signer file paths (not secrets) pass through.
|
|
14
|
+
env: {
|
|
15
|
+
...signerBaseEnvironment(),
|
|
16
|
+
...Object.fromEntries(
|
|
17
|
+
Object.values(SIGNER_FILE_VARS)
|
|
18
|
+
.filter((name) => typeof process.env[name] === 'string')
|
|
19
|
+
.map((name) => [name, process.env[name]]),
|
|
20
|
+
),
|
|
21
|
+
},
|
|
22
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
23
|
+
})
|
|
24
|
+
let output = ''
|
|
25
|
+
let invalid = false
|
|
26
|
+
const kill = () => {
|
|
27
|
+
try {
|
|
28
|
+
process.kill(-child.pid, 'SIGKILL')
|
|
29
|
+
} catch {
|
|
30
|
+
/* only this owned child group */
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const timer = setTimeout(() => {
|
|
34
|
+
invalid = true
|
|
35
|
+
kill()
|
|
36
|
+
}, 45000)
|
|
37
|
+
child.stdout.on('data', (part) => {
|
|
38
|
+
output += part
|
|
39
|
+
if (Buffer.byteLength(output) > 1024 * 1024) {
|
|
40
|
+
invalid = true
|
|
41
|
+
kill()
|
|
42
|
+
}
|
|
43
|
+
})
|
|
44
|
+
child.stdin.on('error', () => {})
|
|
45
|
+
child.stdin.end(JSON.stringify(request))
|
|
46
|
+
child.on('error', () => {
|
|
47
|
+
clearTimeout(timer)
|
|
48
|
+
resolve({ outcome: 'unknown' })
|
|
49
|
+
})
|
|
50
|
+
child.on('close', () => {
|
|
51
|
+
clearTimeout(timer)
|
|
52
|
+
if (invalid) return resolve({ outcome: 'unknown' })
|
|
53
|
+
try {
|
|
54
|
+
resolve(JSON.parse(output))
|
|
55
|
+
} catch {
|
|
56
|
+
resolve({ outcome: 'unknown' })
|
|
57
|
+
}
|
|
58
|
+
})
|
|
59
|
+
})
|
|
60
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { schnorr } from '@noble/curves/secp256k1.js'
|
|
3
|
+
import { HEX64 } from './config.js'
|
|
4
|
+
|
|
5
|
+
export const MAX_TEXT_BYTES = 12000
|
|
6
|
+
export const hash = (text) => createHash('sha256').update(text).digest('hex')
|
|
7
|
+
export const eventHash = (event) => hash(JSON.stringify([0, event.pubkey, event.created_at, event.kind, event.tags, event.content]))
|
|
8
|
+
|
|
9
|
+
// Relay transport authentication is not event authentication. Verify the whole
|
|
10
|
+
// signed Nostr event before accepting any content, identity or receipt.
|
|
11
|
+
export function verifiedEvent(event, config, now = Date.now()) {
|
|
12
|
+
try {
|
|
13
|
+
if (
|
|
14
|
+
!event ||
|
|
15
|
+
!HEX64.test(event.id) ||
|
|
16
|
+
!HEX64.test(event.pubkey) ||
|
|
17
|
+
!/^[0-9a-f]{128}$/.test(event.sig) ||
|
|
18
|
+
event.kind !== 9 ||
|
|
19
|
+
!Number.isSafeInteger(event.created_at) ||
|
|
20
|
+
event.created_at < 0 ||
|
|
21
|
+
event.created_at > Math.floor(now / 1000) + 300 ||
|
|
22
|
+
typeof event.content !== 'string' ||
|
|
23
|
+
Buffer.byteLength(event.content) > 65536 ||
|
|
24
|
+
!Array.isArray(event.tags) ||
|
|
25
|
+
event.tags.length > 128 ||
|
|
26
|
+
event.tags.some(
|
|
27
|
+
(tag) =>
|
|
28
|
+
!Array.isArray(tag) || !tag.length || tag.length > 16 || tag.some((v) => typeof v !== 'string' || Buffer.byteLength(v) > 8192),
|
|
29
|
+
)
|
|
30
|
+
)
|
|
31
|
+
return null
|
|
32
|
+
if (![config.ownerPubkey, ...config.agents.map((a) => a.pubkey)].includes(event.pubkey)) return null
|
|
33
|
+
const channels = event.tags.filter((tag) => tag[0] === 'h')
|
|
34
|
+
if (channels.length !== 1 || channels[0][1] !== config.channel.id) return null
|
|
35
|
+
const digest = eventHash(event)
|
|
36
|
+
if (digest !== event.id || !schnorr.verify(Buffer.from(event.sig, 'hex'), Buffer.from(digest, 'hex'), Buffer.from(event.pubkey, 'hex')))
|
|
37
|
+
return null
|
|
38
|
+
return {
|
|
39
|
+
id: event.id,
|
|
40
|
+
pubkey: event.pubkey,
|
|
41
|
+
created_at: event.created_at,
|
|
42
|
+
kind: event.kind,
|
|
43
|
+
tags: event.tags,
|
|
44
|
+
content: event.content,
|
|
45
|
+
sig: event.sig,
|
|
46
|
+
}
|
|
47
|
+
} catch {
|
|
48
|
+
return null
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function verifiedFeed(events, config) {
|
|
53
|
+
if (!Array.isArray(events) || events.length > 200) throw new Error('Invalid bounded Buzz feed.')
|
|
54
|
+
const unique = new Map()
|
|
55
|
+
for (const candidate of events) {
|
|
56
|
+
const event = verifiedEvent(candidate, config)
|
|
57
|
+
if (event) unique.set(event.id, event)
|
|
58
|
+
}
|
|
59
|
+
return [...unique.values()].sort((a, b) => a.created_at - b.created_at || a.id.localeCompare(b.id))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Apply only to serialized JSON. These JSON escapes preserve the exact text
|
|
63
|
+
// after parsing, while Buzz CLI's raw-text mention scanner sees no recipient.
|
|
64
|
+
export function inertMentions(text) {
|
|
65
|
+
return text.replaceAll('@', '\\u0040').replace(/nostr:/gi, (match) => `${match.slice(0, -1)}\\u003a`)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function envelope({ requestId, text, board, root, project, target, signer }) {
|
|
69
|
+
return inertMentions(
|
|
70
|
+
JSON.stringify(
|
|
71
|
+
{
|
|
72
|
+
type: 'shapewall-owner-request',
|
|
73
|
+
requestId,
|
|
74
|
+
origin: 'Authenticated Shapewall owner; request text supplied in Shapewall.',
|
|
75
|
+
transportSigner: {
|
|
76
|
+
name: signer.name,
|
|
77
|
+
pubkey: signer.pubkey,
|
|
78
|
+
role: 'Existing Buzz transport identity; did not compose this request.',
|
|
79
|
+
},
|
|
80
|
+
target: { name: target.name, pubkey: target.pubkey },
|
|
81
|
+
context: { project: project.name, sourceRoot: root, board },
|
|
82
|
+
instructions: [
|
|
83
|
+
'Existing shared Buzz conversation, not a separate Shapewall thread or sandbox.',
|
|
84
|
+
'Reply in the channel without mentioning the transport signer. Do not automatically notify another agent.',
|
|
85
|
+
'Shapewall does not infer completion from replies. The owner will recapture and review manually.',
|
|
86
|
+
'Decode JSON escapes in request text. Text mentions are inert; only the configured target is notified.',
|
|
87
|
+
],
|
|
88
|
+
request: text,
|
|
89
|
+
},
|
|
90
|
+
null,
|
|
91
|
+
2,
|
|
92
|
+
),
|
|
93
|
+
)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Matches Buzz SDK nip_oa.rs: owner-signed agent binding plus canonical
|
|
97
|
+
// conditions. Evaluate all time clauses now, and kind clauses for the send.
|
|
98
|
+
export function ownerAttested(authTag, signer, owner, now = Math.floor(Date.now() / 1000)) {
|
|
99
|
+
try {
|
|
100
|
+
const tag = JSON.parse(authTag)
|
|
101
|
+
if (
|
|
102
|
+
!Array.isArray(tag) ||
|
|
103
|
+
tag.length !== 4 ||
|
|
104
|
+
tag[0] !== 'auth' ||
|
|
105
|
+
tag[1] !== owner ||
|
|
106
|
+
owner === signer ||
|
|
107
|
+
!HEX64.test(owner) ||
|
|
108
|
+
!HEX64.test(signer) ||
|
|
109
|
+
typeof tag[2] !== 'string' ||
|
|
110
|
+
!/^[0-9a-f]{128}$/.test(tag[3])
|
|
111
|
+
)
|
|
112
|
+
return false
|
|
113
|
+
if (
|
|
114
|
+
tag[2] &&
|
|
115
|
+
!tag[2].split('&').every((clause) => {
|
|
116
|
+
const match = /^(kind=|created_at<|created_at>)(0|[1-9][0-9]*)$/.exec(clause)
|
|
117
|
+
if (!match) return false
|
|
118
|
+
const n = Number(match[2])
|
|
119
|
+
if (!Number.isSafeInteger(n)) return false
|
|
120
|
+
return match[1] === 'kind=' ? n <= 65535 && n === 9 : n <= 4294967295 && (match[1] === 'created_at<' ? now < n : now > n)
|
|
121
|
+
})
|
|
122
|
+
)
|
|
123
|
+
return false
|
|
124
|
+
const digest = hash(`nostr:agent-auth:${signer}:${tag[2]}`)
|
|
125
|
+
return schnorr.verify(Buffer.from(tag[3], 'hex'), Buffer.from(digest, 'hex'), Buffer.from(owner, 'hex'))
|
|
126
|
+
} catch {
|
|
127
|
+
return false
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function dispatchMatches(event, receipt) {
|
|
132
|
+
const mentions = event.tags.filter((tag) => tag[0] === 'p')
|
|
133
|
+
return (
|
|
134
|
+
event.pubkey === receipt.signer.pubkey &&
|
|
135
|
+
hash(event.content) === receipt.envelopeHash &&
|
|
136
|
+
mentions.length === 1 &&
|
|
137
|
+
mentions[0][1] === receipt.target.pubkey &&
|
|
138
|
+
!event.tags.some((tag) => ['e', 'broadcast'].includes(tag[0]))
|
|
139
|
+
)
|
|
140
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// Runs a page's configured actions (src/config.js validates them) in a
|
|
2
|
+
// Playwright page, for captures, setup and page checks alike.
|
|
3
|
+
//
|
|
4
|
+
// A failure names the step: `action 3 (click "button:has-text('Play')") timed
|
|
5
|
+
// out after 45 s`. Messages are built from the config only: page text,
|
|
6
|
+
// Playwright's call log (which quotes page markup) and exceptions thrown by a
|
|
7
|
+
// waitForFunction expression never reach the manifest or the board.
|
|
8
|
+
|
|
9
|
+
// An optional action that is not there gives up after this long (unless it
|
|
10
|
+
// sets its own `timeout`).
|
|
11
|
+
export const OPTIONAL_TIMEOUT_MS = 5000
|
|
12
|
+
|
|
13
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
14
|
+
const quote = (value, max = 80) => JSON.stringify(String(value).length > max ? `${String(value).slice(0, max - 1)}…` : String(value))
|
|
15
|
+
export const seconds = (ms) => `${Math.round(ms / 100) / 10} s`
|
|
16
|
+
|
|
17
|
+
// One line per action, for logs and errors.
|
|
18
|
+
export function describeAction(action) {
|
|
19
|
+
switch (action.type) {
|
|
20
|
+
case 'wait':
|
|
21
|
+
return `wait ${action.ms} ms`
|
|
22
|
+
case 'scrollTo':
|
|
23
|
+
return `scrollTo ${action.y}`
|
|
24
|
+
case 'mouse':
|
|
25
|
+
return `mouse ${action.x}, ${action.y}`
|
|
26
|
+
case 'hold':
|
|
27
|
+
return `hold ${quote(action.key)} ${action.ms} ms`
|
|
28
|
+
case 'press':
|
|
29
|
+
case 'keyDown':
|
|
30
|
+
case 'keyUp':
|
|
31
|
+
return `${action.type} ${quote(action.key)}`
|
|
32
|
+
case 'waitForFunction':
|
|
33
|
+
return `waitForFunction ${quote(action.expression, 60)}`
|
|
34
|
+
default:
|
|
35
|
+
return `${action.type} ${quote(action.selector)}`
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// How long an action may take: its own timeout, else a short one when it
|
|
40
|
+
// is optional, else the page's.
|
|
41
|
+
export const actionTimeout = (action, timeout) => action.timeout ?? (action.optional ? Math.min(OPTIONAL_TIMEOUT_MS, timeout) : timeout)
|
|
42
|
+
|
|
43
|
+
export const isTimeout = (error) => error?.name === 'TimeoutError' || /Timeout \d+ms exceeded/.test(String(error?.message || ''))
|
|
44
|
+
|
|
45
|
+
// A short, config-only reason for a failed step.
|
|
46
|
+
export function stepFailure(label, error, timeout, { pageCode = false } = {}) {
|
|
47
|
+
const message = String(error?.message || error || '')
|
|
48
|
+
if (isTimeout(error)) {
|
|
49
|
+
// Playwright retries a click on a covered element until the timeout.
|
|
50
|
+
const covered = /intercepts pointer events/.test(message)
|
|
51
|
+
? '; another element covers it (a canvas or overlay): try "force": true, or a "mouse" click at its position'
|
|
52
|
+
: ''
|
|
53
|
+
return new StepError(`${label} timed out after ${seconds(timeout)}${covered}`)
|
|
54
|
+
}
|
|
55
|
+
if (/has been closed|Target closed/i.test(message)) return new StepError(`${label} stopped: the page was closed`)
|
|
56
|
+
if (/does not support tap/i.test(message)) return new StepError(`${label} failed: tap needs a touch viewport`)
|
|
57
|
+
// An expression's own exception is page output: keep it out.
|
|
58
|
+
if (pageCode) return new StepError(`${label} failed: the expression threw in the page`)
|
|
59
|
+
const first = message
|
|
60
|
+
.split('\n')[0]
|
|
61
|
+
.replace(/^\w+\.\w+:\s*/, '')
|
|
62
|
+
.slice(0, 160)
|
|
63
|
+
return new StepError(`${label} failed${first ? `: ${first}` : ''}`)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export class StepError extends Error {
|
|
67
|
+
constructor(message) {
|
|
68
|
+
super(message)
|
|
69
|
+
this.name = 'StepError'
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// A forced click goes to the element itself: pointer, mouse and click events
|
|
74
|
+
// dispatched on it, so a canvas or overlay on top (a game's render surface)
|
|
75
|
+
// cannot swallow it. A coordinate click ("mouse") hits whatever is on top.
|
|
76
|
+
const FORCED_EVENTS = ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']
|
|
77
|
+
async function forceClick(page, selector, timeout) {
|
|
78
|
+
const target = page.locator(selector).first()
|
|
79
|
+
await target.waitFor({ state: 'attached', timeout })
|
|
80
|
+
const box = await target.boundingBox().catch(() => null)
|
|
81
|
+
const point = box ? { clientX: box.x + box.width / 2, clientY: box.y + box.height / 2 } : {}
|
|
82
|
+
for (const type of FORCED_EVENTS) {
|
|
83
|
+
await target.dispatchEvent(type, { button: 0, isPrimary: true, pointerType: 'mouse', ...point }, { timeout })
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function runOne(page, action, timeout) {
|
|
88
|
+
const force = action.force ? { force: true } : {}
|
|
89
|
+
switch (action.type) {
|
|
90
|
+
case 'click':
|
|
91
|
+
return action.force ? forceClick(page, action.selector, timeout) : page.click(action.selector, { timeout })
|
|
92
|
+
case 'tap':
|
|
93
|
+
return page.tap(action.selector, { timeout, ...force })
|
|
94
|
+
case 'fill':
|
|
95
|
+
return page.fill(action.selector, action.value, { timeout, ...force })
|
|
96
|
+
case 'hover':
|
|
97
|
+
return page.hover(action.selector, { timeout, ...force })
|
|
98
|
+
case 'press':
|
|
99
|
+
return page.keyboard.press(action.key)
|
|
100
|
+
case 'keyDown':
|
|
101
|
+
return page.keyboard.down(action.key)
|
|
102
|
+
case 'keyUp':
|
|
103
|
+
return page.keyboard.up(action.key)
|
|
104
|
+
case 'hold':
|
|
105
|
+
await page.keyboard.down(action.key)
|
|
106
|
+
try {
|
|
107
|
+
await sleep(action.ms)
|
|
108
|
+
} finally {
|
|
109
|
+
await page.keyboard.up(action.key).catch(() => {})
|
|
110
|
+
}
|
|
111
|
+
return undefined
|
|
112
|
+
case 'mouse':
|
|
113
|
+
return page.mouse.click(action.x, action.y)
|
|
114
|
+
case 'wait':
|
|
115
|
+
return sleep(action.ms)
|
|
116
|
+
case 'waitFor':
|
|
117
|
+
return page.waitForSelector(action.selector, { timeout, state: 'visible' })
|
|
118
|
+
case 'waitForFunction': {
|
|
119
|
+
// Only "it became truthy" comes back; the value itself is dropped in the page.
|
|
120
|
+
const handle = await page.waitForFunction(action.expression, undefined, { timeout, polling: 100 })
|
|
121
|
+
await handle.dispose().catch(() => {})
|
|
122
|
+
return undefined
|
|
123
|
+
}
|
|
124
|
+
case 'scrollTo':
|
|
125
|
+
// A function, not a string: a string is evaluated as an expression and never called.
|
|
126
|
+
return page.evaluate((y) => globalThis.scrollTo(0, y), action.y)
|
|
127
|
+
default:
|
|
128
|
+
throw new Error(`unknown action ${action.type}`)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Runs `actions` in order. `viewport` skips actions guarded to other
|
|
133
|
+
// viewports; optional actions that fail are skipped. `label` prefixes errors
|
|
134
|
+
// ("action", "setup action"); `onStep(text)` hears each step as it starts.
|
|
135
|
+
// Returns { skipped: [1-based numbers of optional actions that were skipped] }.
|
|
136
|
+
export async function runActions(page, actions, { timeout, viewport = null, label = 'action', onStep = () => {} } = {}) {
|
|
137
|
+
const skipped = []
|
|
138
|
+
for (const [index, action] of (actions || []).entries()) {
|
|
139
|
+
const result = await runAction(page, action, index, { timeout, viewport, label, onStep })
|
|
140
|
+
if (result === 'skipped') skipped.push(index + 1)
|
|
141
|
+
}
|
|
142
|
+
return { skipped }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// One action (index from 0). Returns 'ran', 'not-here' (guarded to other
|
|
146
|
+
// viewports) or 'skipped' (optional and absent); throws a StepError otherwise.
|
|
147
|
+
export async function runAction(page, action, index, { timeout, viewport = null, label = 'action', onStep = () => {} } = {}) {
|
|
148
|
+
if (viewport && action.viewports && !action.viewports.includes(viewport)) return 'not-here'
|
|
149
|
+
const step = `${label} ${index + 1} (${describeAction(action)})`
|
|
150
|
+
onStep(step)
|
|
151
|
+
const limit = actionTimeout(action, timeout)
|
|
152
|
+
try {
|
|
153
|
+
await runOne(page, action, limit)
|
|
154
|
+
return 'ran'
|
|
155
|
+
} catch (error) {
|
|
156
|
+
if (action.optional) return 'skipped'
|
|
157
|
+
throw stepFailure(step, error, limit, { pageCode: action.type === 'waitForFunction' })
|
|
158
|
+
}
|
|
159
|
+
}
|