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,464 @@
|
|
|
1
|
+
// Opt-in accounts for a local file-backed installation. Account state is a
|
|
2
|
+
// sidecar; board captures, comments and CLI/MCP storage are never migrated.
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { isIP } from 'node:net'
|
|
6
|
+
import express from 'express'
|
|
7
|
+
import { createAuth, AuthError, cleanDisplayName, deviceLabel } from '../hosted/auth.js'
|
|
8
|
+
import { nodeSupportsSqlite, openDatabase, transaction } from '../hosted/db.js'
|
|
9
|
+
import { accounts, accountEvents, auditAccount, lastRecoverySignIn, seenDevice } from '../hosted/tenancy.js'
|
|
10
|
+
import { sha256 } from '../hosted/crypto.js'
|
|
11
|
+
import { createRateLimiter, LIMITS } from '../hosted/ratelimit.js'
|
|
12
|
+
import { settingsRefusal, settingsTokenOk } from '../agent/settings-routes.js'
|
|
13
|
+
import { ownerIdentity } from '../server/pairing-routes.js'
|
|
14
|
+
import { avatarUrl, mountAvatarRoutes } from './avatar.js'
|
|
15
|
+
import { tokenEquals } from '../tokens.js'
|
|
16
|
+
|
|
17
|
+
export function accountOrigin(value) {
|
|
18
|
+
let url
|
|
19
|
+
try {
|
|
20
|
+
url = new URL(value)
|
|
21
|
+
} catch {
|
|
22
|
+
throw new Error('Accounts need a fixed --accounts-origin URL.')
|
|
23
|
+
}
|
|
24
|
+
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
|
|
25
|
+
if (isIP(url.hostname.replace(/^\[|\]$/g, ''))) throw new Error('Passkeys need localhost or an HTTPS hostname, not an IP address.')
|
|
26
|
+
if (
|
|
27
|
+
(url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) ||
|
|
28
|
+
url.pathname !== '/' ||
|
|
29
|
+
url.search ||
|
|
30
|
+
url.hash ||
|
|
31
|
+
url.username ||
|
|
32
|
+
url.password
|
|
33
|
+
)
|
|
34
|
+
throw new Error('Account origin must be HTTPS (or HTTP on localhost), without credentials, path, query or fragment.')
|
|
35
|
+
return url.origin
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function openLocalAccountDatabase(config, origin) {
|
|
39
|
+
if (!nodeSupportsSqlite()) throw new Error('Local accounts require Node 22.13 or newer.')
|
|
40
|
+
accountOrigin(origin)
|
|
41
|
+
const dir = path.join(config.outputDir, '.accounts')
|
|
42
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
43
|
+
if (typeof process.getuid === 'function') {
|
|
44
|
+
// A private leaf is not enough when another user can replace one of its
|
|
45
|
+
// ancestors between validation and SQLite opening its database/WAL.
|
|
46
|
+
let parent = fs.realpathSync(config.outputDir)
|
|
47
|
+
while (true) {
|
|
48
|
+
const stat = fs.statSync(parent)
|
|
49
|
+
if (stat.mode & 0o022 || ![0, process.getuid()].includes(stat.uid))
|
|
50
|
+
throw new Error('Account storage must have trusted parent directories that other users cannot modify.')
|
|
51
|
+
const next = path.dirname(parent)
|
|
52
|
+
if (next === parent) break
|
|
53
|
+
parent = next
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const info = fs.lstatSync(dir)
|
|
57
|
+
if (info.isSymbolicLink() || (typeof process.getuid === 'function' && (info.mode & 0o077 || info.uid !== process.getuid())))
|
|
58
|
+
throw new Error('The local accounts directory must be private and owned by the service user.')
|
|
59
|
+
const file = path.join(dir, 'accounts.sqlite')
|
|
60
|
+
try {
|
|
61
|
+
const fd = fs.openSync(file, 'wx', 0o600)
|
|
62
|
+
fs.closeSync(fd)
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (error.code !== 'EEXIST') throw error
|
|
65
|
+
const stat = fs.lstatSync(file)
|
|
66
|
+
if (
|
|
67
|
+
!stat.isFile() ||
|
|
68
|
+
stat.isSymbolicLink() ||
|
|
69
|
+
(typeof process.getuid === 'function' && (stat.mode & 0o077 || stat.uid !== process.getuid()))
|
|
70
|
+
)
|
|
71
|
+
throw new Error('The account database must be a private regular file owned by the service user.', { cause: error })
|
|
72
|
+
}
|
|
73
|
+
return { db: await openDatabase(file), origin }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function cookie(req, name) {
|
|
77
|
+
const matches = String(req.headers.cookie || '')
|
|
78
|
+
.split(';')
|
|
79
|
+
.map((part) => part.trim())
|
|
80
|
+
.filter((part) => part.startsWith(`${name}=`))
|
|
81
|
+
return matches.length === 1 ? matches[0].slice(name.length + 1) : null
|
|
82
|
+
}
|
|
83
|
+
function setupTokenOk(req, token) {
|
|
84
|
+
return tokenEquals(req.headers['x-shapewall-account-setup-token'], token)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function localOwnerSetupAllowed(req, { settingsToken = null, shared = false, tailscale = null, env = process.env } = {}) {
|
|
88
|
+
return (
|
|
89
|
+
setupTokenOk(req, env.SHAPEWALL_ACCOUNT_SETUP_TOKEN) ||
|
|
90
|
+
ownerIdentity(req, tailscale) ||
|
|
91
|
+
(settingsTokenOk(req, settingsToken) && !settingsRefusal(req, { shared }))
|
|
92
|
+
)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function createLocalAccounts({
|
|
96
|
+
db,
|
|
97
|
+
origin,
|
|
98
|
+
settingsToken = null,
|
|
99
|
+
shared = false,
|
|
100
|
+
tailscale = null,
|
|
101
|
+
env = process.env,
|
|
102
|
+
now = () => new Date(),
|
|
103
|
+
}) {
|
|
104
|
+
origin = accountOrigin(origin)
|
|
105
|
+
const site = new URL(origin)
|
|
106
|
+
const secure = site.protocol === 'https:'
|
|
107
|
+
const sessionCookie = secure ? '__Host-sw_local_session' : 'sw_local_session'
|
|
108
|
+
const ceremonyCookie = secure ? '__Host-sw_local_ceremony' : 'sw_local_ceremony'
|
|
109
|
+
const auth = createAuth({ db, origin, rpId: site.hostname, now, tag: 'local:' })
|
|
110
|
+
const q = accounts(db)
|
|
111
|
+
const rateLimiter = createRateLimiter({ now: () => now().getTime() })
|
|
112
|
+
const router = express.Router()
|
|
113
|
+
const iso = () => now().toISOString()
|
|
114
|
+
const fail = (res, code, name, message) => res.status(code).json({ error: { code: name, message } })
|
|
115
|
+
const publicUser = (user) => ({ id: user.id, handle: user.handle, displayName: user.display_name, avatarUrl: avatarUrl(db, user.id) })
|
|
116
|
+
const read = (req) => {
|
|
117
|
+
if (!req.localAccountChecked) {
|
|
118
|
+
req.localAccountChecked = true
|
|
119
|
+
req.localAccount = auth.readSession(cookie(req, sessionCookie))
|
|
120
|
+
}
|
|
121
|
+
return req.localAccount
|
|
122
|
+
}
|
|
123
|
+
// Tailscale supplies the configured owner's identity through its local
|
|
124
|
+
// proxy. This grants first-owner enrollment only, never agent settings.
|
|
125
|
+
const setupAllowed = (req) => localOwnerSetupAllowed(req, { settingsToken, shared, tailscale, env })
|
|
126
|
+
const needSession = (req, res, next) => {
|
|
127
|
+
const current = read(req)
|
|
128
|
+
if (!current) return fail(res, 401, 'signed_out', 'Sign in with your passkey first.')
|
|
129
|
+
req.user = current.user
|
|
130
|
+
req.auth = current
|
|
131
|
+
next()
|
|
132
|
+
}
|
|
133
|
+
const needFresh = (req, res, next) =>
|
|
134
|
+
auth.isFresh(req.auth.session) ? next() : fail(res, 403, 'reauth_required', 'Confirm with your passkey first.')
|
|
135
|
+
const needFreshOrRecovery = (req, res, next) => (auth.canAddAfterRecovery(req.auth.session) ? next() : needFresh(req, res, next))
|
|
136
|
+
const handle = (fn) => async (req, res) => {
|
|
137
|
+
try {
|
|
138
|
+
await fn(req, res)
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if (error instanceof AuthError) return fail(res, error.statusCode, error.code, error.message)
|
|
141
|
+
fail(res, 500, 'server_error', 'The account request could not finish.')
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const setCookie = (res, name, value, seconds) =>
|
|
145
|
+
res.append('Set-Cookie', `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${seconds}${secure ? '; Secure' : ''}`)
|
|
146
|
+
const audit = (req, action, detail = {}) =>
|
|
147
|
+
auditAccount(db, { userId: req.user?.id || null, action, detail, ip: req.socket.remoteAddress, at: iso() })
|
|
148
|
+
const startSession = (req, res, user, options = {}) => {
|
|
149
|
+
const previous = read(req)
|
|
150
|
+
if (previous) auth.deleteSession(previous.session.hash)
|
|
151
|
+
const token = auth.createSession(user.id, { ...options, device: deviceLabel(req.headers['user-agent']), ip: req.socket.remoteAddress })
|
|
152
|
+
setCookie(res, sessionCookie, token, 30 * 86400)
|
|
153
|
+
setCookie(res, ceremonyCookie, '', 0)
|
|
154
|
+
return sha256(token)
|
|
155
|
+
}
|
|
156
|
+
const limit = (req, res, next) => {
|
|
157
|
+
const result = rateLimiter.hit('ceremony', req.socket.remoteAddress, LIMITS.ceremony)
|
|
158
|
+
if (result.ok) return next()
|
|
159
|
+
res.setHeader('Retry-After', String(result.retryAfter))
|
|
160
|
+
fail(res, 429, 'rate_limited', 'Too many attempts. Wait a moment and try again.')
|
|
161
|
+
}
|
|
162
|
+
router.use((req, res, next) => {
|
|
163
|
+
res.setHeader('Cache-Control', 'no-store')
|
|
164
|
+
if (String(req.headers.host || '').toLowerCase() !== site.host.toLowerCase())
|
|
165
|
+
return fail(res, 421, 'account_host', 'Use the configured account origin.')
|
|
166
|
+
if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method)) {
|
|
167
|
+
if (req.headers.origin !== origin || (req.headers['sec-fetch-site'] && req.headers['sec-fetch-site'] !== 'same-origin'))
|
|
168
|
+
return fail(res, 403, 'bad_origin', 'Use the account page on this installation.')
|
|
169
|
+
if (req.method !== 'DELETE' && !req.is('application/json')) return fail(res, 415, 'json_required', 'Send JSON.')
|
|
170
|
+
}
|
|
171
|
+
next()
|
|
172
|
+
})
|
|
173
|
+
mountAvatarRoutes(router, { db, needSession, handle, now })
|
|
174
|
+
router.use(express.json({ limit: '64kb' }))
|
|
175
|
+
router.get('/me', (req, res) => {
|
|
176
|
+
const current = read(req)
|
|
177
|
+
const base = {
|
|
178
|
+
local: true,
|
|
179
|
+
rpId: site.hostname,
|
|
180
|
+
signup: 'invite',
|
|
181
|
+
setupRequired: auth.userCount() === 0,
|
|
182
|
+
setupAllowed: setupAllowed(req),
|
|
183
|
+
workspaces: [],
|
|
184
|
+
}
|
|
185
|
+
if (!current) return res.json({ ...base, user: null })
|
|
186
|
+
const seen = auth.getUser(current.user.id).security_seen_at
|
|
187
|
+
const recovery = current.session.via === 'recovery' ? null : lastRecoverySignIn(db, current.user.id, seen)
|
|
188
|
+
res.json({
|
|
189
|
+
...base,
|
|
190
|
+
user: publicUser(current.user),
|
|
191
|
+
passkeys: auth.listPasskeys(current.user.id),
|
|
192
|
+
recoveryCodesLeft: auth.recoveryRemaining(current.user.id),
|
|
193
|
+
fresh: auth.isFresh(current.session),
|
|
194
|
+
viaRecovery: current.session.via === 'recovery',
|
|
195
|
+
securityNotice: recovery ? { kind: 'recovery_code_used', at: recovery.at, ip: recovery.ip } : null,
|
|
196
|
+
})
|
|
197
|
+
})
|
|
198
|
+
const bootstrap = (req, res, next) => {
|
|
199
|
+
if (auth.userCount() !== 0) return fail(res, 403, 'registration_closed', 'This installation already has an account. Sign in instead.')
|
|
200
|
+
if (!setupAllowed(req)) return fail(res, 403, 'owner_setup_required', 'Open the installation owner link to create its first account.')
|
|
201
|
+
next()
|
|
202
|
+
}
|
|
203
|
+
router.post(
|
|
204
|
+
'/register/options',
|
|
205
|
+
limit,
|
|
206
|
+
bootstrap,
|
|
207
|
+
handle(async (req, res) => {
|
|
208
|
+
const result = await auth.registrationOptions({ handle: req.body?.handle, displayName: req.body?.displayName })
|
|
209
|
+
setCookie(res, ceremonyCookie, result.ceremony, 300)
|
|
210
|
+
res.json({ options: result.options })
|
|
211
|
+
}),
|
|
212
|
+
)
|
|
213
|
+
router.post(
|
|
214
|
+
'/register/verify',
|
|
215
|
+
limit,
|
|
216
|
+
bootstrap,
|
|
217
|
+
handle(async (req, res) => {
|
|
218
|
+
const { user, extra } = await auth.finishSignUp(cookie(req, ceremonyCookie), req.body?.response, (created) => {
|
|
219
|
+
// Verification awaits outside the transaction, so recheck the first
|
|
220
|
+
// owner condition inside the account engine's write transaction.
|
|
221
|
+
if (auth.userCount() !== 1) throw new AuthError(409, 'registration_closed', 'An owner account was already created.')
|
|
222
|
+
req.user = created
|
|
223
|
+
audit(req, 'account_created', { via: 'local_setup' })
|
|
224
|
+
return { recoveryCodes: auth.newRecoveryCodes(created.id) }
|
|
225
|
+
})
|
|
226
|
+
startSession(req, res, user)
|
|
227
|
+
res.status(201).json({ local: true, user: publicUser(user), recoveryCodes: extra.recoveryCodes })
|
|
228
|
+
}),
|
|
229
|
+
)
|
|
230
|
+
router.post(
|
|
231
|
+
'/login/options',
|
|
232
|
+
limit,
|
|
233
|
+
handle(async (req, res) => {
|
|
234
|
+
const result = await auth.authenticationOptions()
|
|
235
|
+
setCookie(res, ceremonyCookie, result.ceremony, 300)
|
|
236
|
+
res.json({ options: result.options })
|
|
237
|
+
}),
|
|
238
|
+
)
|
|
239
|
+
router.post(
|
|
240
|
+
'/login/verify',
|
|
241
|
+
limit,
|
|
242
|
+
handle(async (req, res) => {
|
|
243
|
+
let user
|
|
244
|
+
try {
|
|
245
|
+
user = await auth.finishAuthentication(cookie(req, ceremonyCookie), req.body?.response)
|
|
246
|
+
} catch (error) {
|
|
247
|
+
audit(req, 'sign_in_failed', { code: error.code || 'error' })
|
|
248
|
+
throw error
|
|
249
|
+
}
|
|
250
|
+
req.user = user
|
|
251
|
+
const device = deviceLabel(req.headers['user-agent'])
|
|
252
|
+
audit(req, 'signed_in', { via: 'passkey', device, ...(seenDevice(db, user.id, device) ? {} : { newDevice: true }) })
|
|
253
|
+
startSession(req, res, user, { verified: user.trusted })
|
|
254
|
+
res.json({ user: publicUser(user) })
|
|
255
|
+
}),
|
|
256
|
+
)
|
|
257
|
+
router.post(
|
|
258
|
+
'/recovery',
|
|
259
|
+
handle(async (req, res) => {
|
|
260
|
+
const ip = req.socket.remoteAddress
|
|
261
|
+
const key = `${String(req.body?.handle || '')
|
|
262
|
+
.toLowerCase()
|
|
263
|
+
.slice(0, 40)}:${ip}`
|
|
264
|
+
const attempt = rateLimiter.attempt([
|
|
265
|
+
['recoveryFail', key, LIMITS.recoveryFail],
|
|
266
|
+
['recoveryFailIp', ip, LIMITS.recoveryFailIp],
|
|
267
|
+
])
|
|
268
|
+
if (!attempt.ok) {
|
|
269
|
+
res.setHeader('Retry-After', String(attempt.retryAfter))
|
|
270
|
+
return fail(res, 429, 'rate_limited', 'Too many attempts. Wait before trying again.')
|
|
271
|
+
}
|
|
272
|
+
const user = auth.useRecoveryCode(req.body?.handle, req.body?.code)
|
|
273
|
+
if (!user) {
|
|
274
|
+
audit(req, 'recovery_failed')
|
|
275
|
+
return fail(res, 401, 'bad_code', 'That handle and recovery code do not match an unused code.')
|
|
276
|
+
}
|
|
277
|
+
attempt.success()
|
|
278
|
+
req.user = user
|
|
279
|
+
const hash = startSession(req, res, user, { via: 'recovery' })
|
|
280
|
+
auth.deleteOtherSessions(user.id, hash)
|
|
281
|
+
audit(req, 'signed_in', { via: 'recovery_code', otherSessionsEnded: true })
|
|
282
|
+
res.json({ user: publicUser(user), recoveryCodesLeft: auth.recoveryRemaining(user.id) })
|
|
283
|
+
}),
|
|
284
|
+
)
|
|
285
|
+
router.post('/logout', (req, res) => {
|
|
286
|
+
const current = read(req)
|
|
287
|
+
if (current) auth.deleteSession(current.session.hash)
|
|
288
|
+
setCookie(res, sessionCookie, '', 0)
|
|
289
|
+
res.json({ ok: true })
|
|
290
|
+
})
|
|
291
|
+
router.patch(
|
|
292
|
+
'/me',
|
|
293
|
+
needSession,
|
|
294
|
+
handle(async (req, res) => {
|
|
295
|
+
const name = cleanDisplayName(req.body?.displayName)
|
|
296
|
+
q.run('UPDATE users SET display_name = :name WHERE id = :id', { name, id: req.user.id })
|
|
297
|
+
res.json({ user: publicUser(auth.getUser(req.user.id)) })
|
|
298
|
+
}),
|
|
299
|
+
)
|
|
300
|
+
router.post(
|
|
301
|
+
'/reauth/options',
|
|
302
|
+
limit,
|
|
303
|
+
needSession,
|
|
304
|
+
handle(async (req, res) => {
|
|
305
|
+
const result = await auth.authenticationOptions({ userId: req.user.id })
|
|
306
|
+
setCookie(res, ceremonyCookie, result.ceremony, 300)
|
|
307
|
+
res.json({ options: result.options })
|
|
308
|
+
}),
|
|
309
|
+
)
|
|
310
|
+
router.post(
|
|
311
|
+
'/reauth/verify',
|
|
312
|
+
limit,
|
|
313
|
+
needSession,
|
|
314
|
+
handle(async (req, res) => {
|
|
315
|
+
const user = await auth.finishAuthentication(cookie(req, ceremonyCookie), req.body?.response, { userId: req.user.id })
|
|
316
|
+
if (!user.trusted)
|
|
317
|
+
throw new AuthError(403, 'passkey_on_hold', 'A passkey added after recovery must wait 24 hours to confirm security changes.')
|
|
318
|
+
q.run("UPDATE sessions SET via = 'passkey' WHERE token_hash = :hash", { hash: req.auth.session.hash })
|
|
319
|
+
auth.markVerified(req.auth.session.hash)
|
|
320
|
+
setCookie(res, ceremonyCookie, '', 0)
|
|
321
|
+
res.json({ ok: true })
|
|
322
|
+
}),
|
|
323
|
+
)
|
|
324
|
+
router.post(
|
|
325
|
+
'/passkeys/options',
|
|
326
|
+
limit,
|
|
327
|
+
needSession,
|
|
328
|
+
needFreshOrRecovery,
|
|
329
|
+
handle(async (req, res) => {
|
|
330
|
+
const result = await auth.registrationOptions({ userId: req.user.id })
|
|
331
|
+
setCookie(res, ceremonyCookie, result.ceremony, 300)
|
|
332
|
+
res.json({ options: result.options })
|
|
333
|
+
}),
|
|
334
|
+
)
|
|
335
|
+
router.post(
|
|
336
|
+
'/passkeys/verify',
|
|
337
|
+
limit,
|
|
338
|
+
needSession,
|
|
339
|
+
needFreshOrRecovery,
|
|
340
|
+
handle(async (req, res) => {
|
|
341
|
+
const viaRecovery = !auth.isFresh(req.auth.session)
|
|
342
|
+
await auth.finishAddPasskey(cookie(req, ceremonyCookie), req.body?.response, req.user.id, req.body?.nickname, { viaRecovery })
|
|
343
|
+
audit(req, 'passkey_added', { viaRecovery })
|
|
344
|
+
setCookie(res, ceremonyCookie, '', 0)
|
|
345
|
+
res.status(201).json({ passkeys: auth.listPasskeys(req.user.id) })
|
|
346
|
+
}),
|
|
347
|
+
)
|
|
348
|
+
router.patch(
|
|
349
|
+
'/passkeys/:id',
|
|
350
|
+
needSession,
|
|
351
|
+
handle(async (req, res) => {
|
|
352
|
+
auth.renamePasskey(req.user.id, req.params.id, req.body?.nickname)
|
|
353
|
+
audit(req, 'passkey_renamed')
|
|
354
|
+
res.json({ passkeys: auth.listPasskeys(req.user.id) })
|
|
355
|
+
}),
|
|
356
|
+
)
|
|
357
|
+
router.delete(
|
|
358
|
+
'/passkeys/:id',
|
|
359
|
+
needSession,
|
|
360
|
+
needFresh,
|
|
361
|
+
handle(async (req, res) => {
|
|
362
|
+
auth.removePasskey(req.user.id, req.params.id)
|
|
363
|
+
auth.deleteOtherSessions(req.user.id, req.auth.session.hash)
|
|
364
|
+
audit(req, 'passkey_removed', { otherSessionsEnded: true })
|
|
365
|
+
res.json({ passkeys: auth.listPasskeys(req.user.id) })
|
|
366
|
+
}),
|
|
367
|
+
)
|
|
368
|
+
router.post(
|
|
369
|
+
'/recovery-codes',
|
|
370
|
+
needSession,
|
|
371
|
+
needFresh,
|
|
372
|
+
handle(async (req, res) => {
|
|
373
|
+
const recoveryCodes = auth.newRecoveryCodes(req.user.id)
|
|
374
|
+
audit(req, 'recovery_codes_created')
|
|
375
|
+
res.json({ recoveryCodes })
|
|
376
|
+
}),
|
|
377
|
+
)
|
|
378
|
+
router.get('/sessions', needSession, (req, res) => res.json({ sessions: auth.listSessions(req.user.id, req.auth.session.hash) }))
|
|
379
|
+
router.post(
|
|
380
|
+
'/sessions/revoke-others',
|
|
381
|
+
needSession,
|
|
382
|
+
needFresh,
|
|
383
|
+
handle(async (req, res) => {
|
|
384
|
+
auth.deleteOtherSessions(req.user.id, req.auth.session.hash)
|
|
385
|
+
audit(req, 'sessions_revoked')
|
|
386
|
+
res.json({ ok: true, sessions: auth.listSessions(req.user.id, req.auth.session.hash) })
|
|
387
|
+
}),
|
|
388
|
+
)
|
|
389
|
+
router.delete(
|
|
390
|
+
'/sessions/:id',
|
|
391
|
+
needSession,
|
|
392
|
+
needFresh,
|
|
393
|
+
handle(async (req, res) => {
|
|
394
|
+
auth.deleteSessionById(req.user.id, req.params.id, req.auth.session.hash)
|
|
395
|
+
audit(req, 'session_revoked')
|
|
396
|
+
res.json({ sessions: auth.listSessions(req.user.id, req.auth.session.hash) })
|
|
397
|
+
}),
|
|
398
|
+
)
|
|
399
|
+
router.get('/security-log', needSession, (req, res) => {
|
|
400
|
+
const before = Number(req.query.before)
|
|
401
|
+
const rows = accountEvents(db, req.user.id, {
|
|
402
|
+
before: Number.isSafeInteger(before) && before > 0 ? before : Number.MAX_SAFE_INTEGER,
|
|
403
|
+
limit: 51,
|
|
404
|
+
})
|
|
405
|
+
res.json({
|
|
406
|
+
events: rows
|
|
407
|
+
.slice(0, 50)
|
|
408
|
+
.map((row) => ({ id: row.id, action: row.action, at: row.at, ip: row.ip, detail: JSON.parse(row.detail || '{}') })),
|
|
409
|
+
next: rows.length > 50 ? rows[49].id : null,
|
|
410
|
+
})
|
|
411
|
+
})
|
|
412
|
+
router.post(
|
|
413
|
+
'/security-notice/seen',
|
|
414
|
+
needSession,
|
|
415
|
+
handle(async (req, res) => {
|
|
416
|
+
q.run('UPDATE users SET security_seen_at = :at WHERE id = :id', { at: iso(), id: req.user.id })
|
|
417
|
+
res.json({ ok: true })
|
|
418
|
+
}),
|
|
419
|
+
)
|
|
420
|
+
router.post('/delete-account/preview', needSession, (req, res) =>
|
|
421
|
+
res.json({
|
|
422
|
+
deleted: [],
|
|
423
|
+
left: [],
|
|
424
|
+
blocked: auth.userCount() <= 1 ? [{ name: 'this installation', reason: 'last_account' }] : [],
|
|
425
|
+
local: true,
|
|
426
|
+
}),
|
|
427
|
+
)
|
|
428
|
+
router.delete(
|
|
429
|
+
'/me',
|
|
430
|
+
needSession,
|
|
431
|
+
needFresh,
|
|
432
|
+
handle(async (req, res) => {
|
|
433
|
+
if (typeof req.body?.confirm !== 'string' || req.body.confirm.replace(/^@/, '').trim().toLowerCase() !== req.user.handle)
|
|
434
|
+
throw new AuthError(400, 'confirm_handle', 'Type your handle exactly to delete your account.')
|
|
435
|
+
transaction(db, () => {
|
|
436
|
+
if (auth.userCount() <= 1) throw new AuthError(409, 'last_account', 'The last local account cannot be deleted.')
|
|
437
|
+
q.run('DELETE FROM users WHERE id = :id', { id: req.user.id })
|
|
438
|
+
})
|
|
439
|
+
setCookie(res, sessionCookie, '', 0)
|
|
440
|
+
res.json({ ok: true, deleted: 0, left: 0 })
|
|
441
|
+
}),
|
|
442
|
+
)
|
|
443
|
+
router.use((req, res) => fail(res, 404, 'not_found', 'No such account route.'))
|
|
444
|
+
|
|
445
|
+
const gate = (req, res, next) => {
|
|
446
|
+
const shellRequest =
|
|
447
|
+
['GET', 'HEAD'].includes(req.method) && /^\/(?:|index\.html|account|signin|signup|console(?:\/.*)?)$/.test(req.path)
|
|
448
|
+
if (shellRequest && String(req.headers.host || '').toLowerCase() !== site.host.toLowerCase())
|
|
449
|
+
return res.redirect(303, `${origin}${req.originalUrl}`)
|
|
450
|
+
if (auth.userCount() === 0) return next()
|
|
451
|
+
const current = read(req)
|
|
452
|
+
if (current) return next()
|
|
453
|
+
// The public shell may explain how to sign in, but no board API,
|
|
454
|
+
// captures, live HTML or installation capabilities pass this boundary.
|
|
455
|
+
const route = req.path.toLowerCase()
|
|
456
|
+
if (['GET', 'HEAD'].includes(req.method) && ['/', '/index.html'].includes(route))
|
|
457
|
+
return res.redirect(303, `/signin?next=${encodeURIComponent(req.originalUrl)}`)
|
|
458
|
+
const shell =
|
|
459
|
+
/^\/(?:|index\.html|console(?:\/.*)?|account|signin|signup|_console\/.*|assets\/.*|icons\/.*|theme-boot\.js|favicon\.svg|sw\.js|manifest\.webmanifest)$/
|
|
460
|
+
if (['GET', 'HEAD'].includes(req.method) && (shell.test(route) || route === '/api/health')) return next()
|
|
461
|
+
return fail(res, 401, 'signed_out', 'Sign in with your passkey first.')
|
|
462
|
+
}
|
|
463
|
+
return { router, gate, read, publicUser, auth, db, origin }
|
|
464
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// The ACP agent command: which program the chat panel starts, and with what
|
|
2
|
+
// environment.
|
|
3
|
+
//
|
|
4
|
+
// The command comes only from the person running Shapewall: the
|
|
5
|
+
// `--agent-acp "<command>"` flag or SHAPEWALL_AGENT_ACP. Never from
|
|
6
|
+
// shapewall.config.json, which is usually committed: a repo that could name a
|
|
7
|
+
// command would run code on the machine of anyone who opens a chat in it.
|
|
8
|
+
//
|
|
9
|
+
// The command is split into argv like `watch --exec` (no shell: no
|
|
10
|
+
// variables, globs, pipes or redirects) and started with a small environment:
|
|
11
|
+
// what a CLI needs to find itself and its login (PATH, HOME, locale, temp and
|
|
12
|
+
// XDG folders), never Shapewall's or other tools' secrets. Extra variables an
|
|
13
|
+
// agent needs (an API key, say) are passed only when named in
|
|
14
|
+
// SHAPEWALL_AGENT_ACP_ENV.
|
|
15
|
+
|
|
16
|
+
import path from 'node:path'
|
|
17
|
+
import { findProgram, splitCommand } from '../../watch.js'
|
|
18
|
+
|
|
19
|
+
export const ACP_COMMAND_VAR = 'SHAPEWALL_AGENT_ACP'
|
|
20
|
+
export const ACP_ENV_VAR = 'SHAPEWALL_AGENT_ACP_ENV'
|
|
21
|
+
export const ACP_FLAG = '--agent-acp'
|
|
22
|
+
|
|
23
|
+
// Always passed when set: where programs, the home folder, the locale, temp
|
|
24
|
+
// files, proxies and per-tool config folders are. None of them is a secret.
|
|
25
|
+
const BASE_VARS = [
|
|
26
|
+
'PATH',
|
|
27
|
+
'HOME',
|
|
28
|
+
'USER',
|
|
29
|
+
'LOGNAME',
|
|
30
|
+
'SHELL',
|
|
31
|
+
'TERM',
|
|
32
|
+
'LANG',
|
|
33
|
+
'LANGUAGE',
|
|
34
|
+
'TZ',
|
|
35
|
+
'TMPDIR',
|
|
36
|
+
'TEMP',
|
|
37
|
+
'TMP',
|
|
38
|
+
'XDG_CONFIG_HOME',
|
|
39
|
+
'XDG_DATA_HOME',
|
|
40
|
+
'XDG_CACHE_HOME',
|
|
41
|
+
'XDG_STATE_HOME',
|
|
42
|
+
'XDG_RUNTIME_DIR',
|
|
43
|
+
// The desktop keyring, where some CLIs keep their login.
|
|
44
|
+
'DBUS_SESSION_BUS_ADDRESS',
|
|
45
|
+
'HTTP_PROXY',
|
|
46
|
+
'HTTPS_PROXY',
|
|
47
|
+
'NO_PROXY',
|
|
48
|
+
'http_proxy',
|
|
49
|
+
'https_proxy',
|
|
50
|
+
'no_proxy',
|
|
51
|
+
'NODE_EXTRA_CA_CERTS',
|
|
52
|
+
'SSL_CERT_FILE',
|
|
53
|
+
'SSL_CERT_DIR',
|
|
54
|
+
// Config folders (not credentials) of the agents in docs/agents.md.
|
|
55
|
+
'CLAUDE_CONFIG_DIR',
|
|
56
|
+
'CODEX_HOME',
|
|
57
|
+
'GOOSE_PROVIDER',
|
|
58
|
+
'GOOSE_MODEL',
|
|
59
|
+
'GOOSE_MODE',
|
|
60
|
+
// A goose profile of its own for Shapewall (docs/agent-hardening.md).
|
|
61
|
+
'GOOSE_PATH_ROOT',
|
|
62
|
+
// Windows: what a program needs to start at all.
|
|
63
|
+
'SystemRoot',
|
|
64
|
+
'SYSTEMROOT',
|
|
65
|
+
'windir',
|
|
66
|
+
'COMSPEC',
|
|
67
|
+
'PATHEXT',
|
|
68
|
+
'APPDATA',
|
|
69
|
+
'LOCALAPPDATA',
|
|
70
|
+
'USERPROFILE',
|
|
71
|
+
'HOMEDRIVE',
|
|
72
|
+
'HOMEPATH',
|
|
73
|
+
'ProgramData',
|
|
74
|
+
'ProgramFiles',
|
|
75
|
+
]
|
|
76
|
+
const BASE_PREFIXES = ['LC_']
|
|
77
|
+
|
|
78
|
+
// Never passed, even when named in SHAPEWALL_AGENT_ACP_ENV: Shapewall's own
|
|
79
|
+
// settings and secrets, and tokens that belong to other tools.
|
|
80
|
+
const DENIED_VARS = new Set(['GITHUB_TOKEN', 'GH_TOKEN', 'RESEND_API_KEY', 'NPM_TOKEN', 'NODE_AUTH_TOKEN'])
|
|
81
|
+
// npm_config_* (any case) too: npm settings such as script-shell or registry
|
|
82
|
+
// would let a variable decide what `npx` runs.
|
|
83
|
+
const DENIED_RE = /^(SHAPEWALL_|npm_config_)|(WEBHOOK_SECRET|_PASSWORD)$/i
|
|
84
|
+
|
|
85
|
+
const ENV_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/
|
|
86
|
+
|
|
87
|
+
export function deniedVar(name) {
|
|
88
|
+
return DENIED_VARS.has(name) || DENIED_RE.test(name)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// A terminal the agent asks for runs with the agent's environment. The
|
|
92
|
+
// agent may add only these harmless names (shown on the approval card); the
|
|
93
|
+
// ones below change what a program loads or runs, so a request naming them
|
|
94
|
+
// is refused outright, and anything else is ignored.
|
|
95
|
+
export const TERMINAL_ENV_ALLOWED = new Set(['TERM', 'COLUMNS', 'LINES', 'NO_COLOR', 'FORCE_COLOR', 'CI', 'TZ', 'LANG', 'LC_ALL'])
|
|
96
|
+
const TERMINAL_ENV_REFUSED_RE =
|
|
97
|
+
/^(LD_|DYLD_|GIT_|npm_config_|PYTHON|RUBY|PERL|JAVA_TOOL|_JAVA)|^(NODE_OPTIONS|NODE_PATH|PATH|PATHEXT|BASH_ENV|ENV|ZDOTDIR|PROMPT_COMMAND|IFS|SHELL|HOME|PAGER|GIT_PAGER|MANPAGER|EDITOR|VISUAL|GIT_EDITOR|SSH_ASKPASS|GIT_ASKPASS|SUDO_ASKPASS|COMSPEC)$/i
|
|
98
|
+
|
|
99
|
+
export function terminalEnvRefused(name) {
|
|
100
|
+
return TERMINAL_ENV_REFUSED_RE.test(name) || deniedVar(name)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// The extra variable names from SHAPEWALL_AGENT_ACP_ENV, and the ones refused.
|
|
104
|
+
export function extraVarNames(env = process.env) {
|
|
105
|
+
const names = String(env[ACP_ENV_VAR] || '')
|
|
106
|
+
.split(',')
|
|
107
|
+
.map((item) => item.trim())
|
|
108
|
+
.filter(Boolean)
|
|
109
|
+
const refused = names.filter((name) => !ENV_NAME_RE.test(name) || deniedVar(name))
|
|
110
|
+
return { names: names.filter((name) => !refused.includes(name)), refused }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// The environment for the agent process: the base variables, any extra ones
|
|
114
|
+
// the person named, and nothing else.
|
|
115
|
+
export function agentEnv(env = process.env, { extra = extraVarNames(env).names } = {}) {
|
|
116
|
+
const out = {}
|
|
117
|
+
for (const [name, value] of Object.entries(env)) {
|
|
118
|
+
if (typeof value !== 'string') continue
|
|
119
|
+
const base = BASE_VARS.includes(name) || BASE_PREFIXES.some((prefix) => name.startsWith(prefix))
|
|
120
|
+
if ((base || extra.includes(name)) && !deniedVar(name)) out[name] = value
|
|
121
|
+
}
|
|
122
|
+
return out
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// A name for the panel, from the command: "Claude Code" for claude-agent-acp,
|
|
126
|
+
// and so on. Never the command line itself, which may hold paths.
|
|
127
|
+
const KNOWN = [
|
|
128
|
+
[/claude-(agent|code)-acp/, 'Claude Code'],
|
|
129
|
+
[/codex-acp/, 'Codex'],
|
|
130
|
+
[/gemini/, 'Gemini CLI'],
|
|
131
|
+
[/goose/, 'goose'],
|
|
132
|
+
[/qwen/, 'Qwen Code'],
|
|
133
|
+
[/opencode/, 'OpenCode'],
|
|
134
|
+
]
|
|
135
|
+
|
|
136
|
+
export function acpLabel(argv) {
|
|
137
|
+
const words = argv.map((arg) => path.basename(String(arg)).toLowerCase())
|
|
138
|
+
for (const [re, label] of KNOWN) if (words.some((word) => re.test(word))) return label
|
|
139
|
+
return path.basename(String(argv[0] || 'agent')).replace(/\.(exe|cmd|bat|m?js)$/i, '') || 'ACP agent'
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Which agent a command starts, from the path segments of its words (so
|
|
143
|
+
// `npx @agentclientprotocol/claude-agent-acp` and
|
|
144
|
+
// `node .../claude-agent-acp/dist/index.js` count too): 'claude', 'codex',
|
|
145
|
+
// 'goose', 'gemini' or null.
|
|
146
|
+
export function acpAgentKind(argv = []) {
|
|
147
|
+
const words = argv.flatMap((arg) =>
|
|
148
|
+
String(arg)
|
|
149
|
+
.toLowerCase()
|
|
150
|
+
.split(/[\\/]/)
|
|
151
|
+
.map((word) => word.replace(/\.(exe|cmd|bat|m?js)$/, '')),
|
|
152
|
+
)
|
|
153
|
+
if (words.some((word) => /^claude-(agent|code)-acp$/.test(word))) return 'claude'
|
|
154
|
+
if (words.some((word) => /^codex-acp$/.test(word))) return 'codex'
|
|
155
|
+
if (words.some((word) => /^goose$/.test(word))) return 'goose'
|
|
156
|
+
if (words.some((word) => /^gemini(-cli)?$/.test(word))) return 'gemini'
|
|
157
|
+
return null
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// How to log the agent in, for the chat error and the server log when it
|
|
161
|
+
// answers "authentication required".
|
|
162
|
+
const LOGIN_HINTS = {
|
|
163
|
+
claude: 'run `claude` in a terminal and use /login, or start the agent with `claude-agent-acp --cli` and use /login there',
|
|
164
|
+
codex: 'run `codex login` in a terminal',
|
|
165
|
+
goose: 'run `goose configure` in a terminal and set up a provider',
|
|
166
|
+
gemini: 'run `gemini` in a terminal and sign in',
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function loginHint(argv) {
|
|
170
|
+
return LOGIN_HINTS[acpAgentKind(argv)] || 'run the agent once in a terminal on this machine and log in'
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// The command the person gave (flag first, then the environment, then the
|
|
174
|
+
// one saved in Settings > Agent: src/agent/user-settings.js), parsed.
|
|
175
|
+
// { source, argv, program, label, problem }; null when there is none.
|
|
176
|
+
export const SETTINGS_SOURCE = 'Settings > Agent'
|
|
177
|
+
|
|
178
|
+
export function acpCommand({ flag = null, env = process.env, saved = null } = {}) {
|
|
179
|
+
const given = (value) => typeof value === 'string' && value.trim() !== ''
|
|
180
|
+
const [raw, source] = given(flag)
|
|
181
|
+
? [flag, ACP_FLAG]
|
|
182
|
+
: given(env[ACP_COMMAND_VAR])
|
|
183
|
+
? [env[ACP_COMMAND_VAR], ACP_COMMAND_VAR]
|
|
184
|
+
: given(saved)
|
|
185
|
+
? [saved, SETTINGS_SOURCE]
|
|
186
|
+
: ['', null]
|
|
187
|
+
if (!source) return null
|
|
188
|
+
let argv
|
|
189
|
+
try {
|
|
190
|
+
argv = splitCommand(raw, source)
|
|
191
|
+
} catch (error) {
|
|
192
|
+
return { source, argv: null, program: null, label: 'ACP agent', problem: error.message }
|
|
193
|
+
}
|
|
194
|
+
const label = acpLabel(argv)
|
|
195
|
+
const program = findProgram(argv[0], env)
|
|
196
|
+
if (!program) return { source, argv, program: null, label, problem: `${source}: "${argv[0]}" is not an executable on PATH` }
|
|
197
|
+
return { source, argv: [program, ...argv.slice(1)], program, label, problem: null }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// The command as shown in the terminal and by `shapewall doctor`: words with
|
|
201
|
+
// spaces quoted. Only ever printed on this machine, never sent to the board.
|
|
202
|
+
export function formatCommand(argv) {
|
|
203
|
+
return argv.map((arg) => (/^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${String(arg).replace(/'/g, `'\\''`)}'`)).join(' ')
|
|
204
|
+
}
|