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,233 @@
|
|
|
1
|
+
// `shapewall login`: a device-style handoff of a project token, so nobody
|
|
2
|
+
// copies one by hand. The CLI starts a login and gets two codes: a long
|
|
3
|
+
// device code it keeps (and polls with), and a short user code it shows.
|
|
4
|
+
// The person opens /device in the console, types the short code, picks the
|
|
5
|
+
// workspace and project, and approves with a fresh passkey check; the
|
|
6
|
+
// server makes a token named after the machine and hands it to the polling
|
|
7
|
+
// CLI once. The token is never shown in the browser or printed by the CLI.
|
|
8
|
+
//
|
|
9
|
+
// Kept in SQLite (table device_logins, migration 5), so a restart does not
|
|
10
|
+
// drop pending or approved logins. Only the SHA-256 of the device code is
|
|
11
|
+
// stored. The approved token is sealed to the device code: at start the
|
|
12
|
+
// server derives an X25519 key pair from the device code and keeps only the
|
|
13
|
+
// public half; approval encrypts the token to it (ephemeral X25519 + HKDF +
|
|
14
|
+
// AES-256-GCM), and only a poll that presents the device code can open it.
|
|
15
|
+
// So a copy of the database (even with secret.key) holds no usable token.
|
|
16
|
+
// Approving and handing over are single-use inside a transaction.
|
|
17
|
+
//
|
|
18
|
+
// The user code is typed, never put in a link, so someone cannot send a
|
|
19
|
+
// victim a ready-made approval URL for their own login (the console also
|
|
20
|
+
// shows the machine name and asks to compare the code with the terminal).
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
createCipheriv,
|
|
24
|
+
createDecipheriv,
|
|
25
|
+
createPrivateKey,
|
|
26
|
+
createPublicKey,
|
|
27
|
+
diffieHellman,
|
|
28
|
+
generateKeyPairSync,
|
|
29
|
+
hkdfSync,
|
|
30
|
+
randomBytes,
|
|
31
|
+
randomInt,
|
|
32
|
+
} from 'node:crypto'
|
|
33
|
+
import { randomToken, sha256 } from './crypto.js'
|
|
34
|
+
import { transaction } from './db.js'
|
|
35
|
+
import { accounts } from './tenancy.js'
|
|
36
|
+
|
|
37
|
+
export const DEVICE_TTL_MS = 10 * 60_000
|
|
38
|
+
export const DEVICE_POLL_SECONDS = 3
|
|
39
|
+
// At most this many pending logins in all, and per client address. A full
|
|
40
|
+
// server makes room by dropping the oldest pending login (expired ones are
|
|
41
|
+
// swept first), so one address cannot lock everyone else out; the per
|
|
42
|
+
// address cap (and the start rate limit in app.js) keeps that from being a
|
|
43
|
+
// way to push other people's logins out quickly.
|
|
44
|
+
const MAX_PENDING = 500
|
|
45
|
+
const MAX_PENDING_PER_IP = 5
|
|
46
|
+
// No vowels (no words), no lookalikes.
|
|
47
|
+
const ALPHABET = 'BCDFGHJKLMNPQRSTVWXZ'
|
|
48
|
+
const USER_CODE_RE = /^[BCDFGHJKLMNPQRSTVWXZ]{8}$/
|
|
49
|
+
const DEVICE_CODE_RE = /^[A-Za-z0-9_-]{40,60}$/
|
|
50
|
+
|
|
51
|
+
export const normalizeUserCode = (value) =>
|
|
52
|
+
typeof value === 'string'
|
|
53
|
+
? value
|
|
54
|
+
.toUpperCase()
|
|
55
|
+
.replace(/[^A-Z]/g, '')
|
|
56
|
+
.slice(0, 8)
|
|
57
|
+
: ''
|
|
58
|
+
export const formatUserCode = (code) => `${code.slice(0, 4)}-${code.slice(4)}`
|
|
59
|
+
|
|
60
|
+
// A machine name as the CLI sends it, cleaned for a token name.
|
|
61
|
+
export function cleanMachineName(value) {
|
|
62
|
+
const name =
|
|
63
|
+
typeof value === 'string'
|
|
64
|
+
? value
|
|
65
|
+
.replace(/[^\w .-]/g, '')
|
|
66
|
+
.replace(/\s+/g, ' ')
|
|
67
|
+
.trim()
|
|
68
|
+
.slice(0, 40)
|
|
69
|
+
: ''
|
|
70
|
+
return name || 'a computer'
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ---- Sealing the token to the device code ----
|
|
74
|
+
|
|
75
|
+
// PKCS#8 header of a raw 32-byte X25519 private key.
|
|
76
|
+
const X25519_PKCS8 = Buffer.from('302e020100300506032b656e04220420', 'hex')
|
|
77
|
+
const INFO = Buffer.from('shapewall device login result')
|
|
78
|
+
|
|
79
|
+
function deviceKey(deviceCode) {
|
|
80
|
+
const raw = Buffer.from(sha256(`shapewall-device-seal:${deviceCode}`), 'hex')
|
|
81
|
+
return createPrivateKey({ key: Buffer.concat([X25519_PKCS8, raw]), format: 'der', type: 'pkcs8' })
|
|
82
|
+
}
|
|
83
|
+
const spki = (key) => key.export({ type: 'spki', format: 'der' }).toString('base64url')
|
|
84
|
+
const fromSpki = (value) => createPublicKey({ key: Buffer.from(value, 'base64url'), format: 'der', type: 'spki' })
|
|
85
|
+
|
|
86
|
+
export function sealFor(publicKeyB64, value) {
|
|
87
|
+
const ephemeral = generateKeyPairSync('x25519')
|
|
88
|
+
const ephemeralPublic = spki(ephemeral.publicKey)
|
|
89
|
+
const shared = diffieHellman({ privateKey: ephemeral.privateKey, publicKey: fromSpki(publicKeyB64) })
|
|
90
|
+
const key = Buffer.from(hkdfSync('sha256', shared, Buffer.from(ephemeralPublic), INFO, 32))
|
|
91
|
+
const nonce = randomBytes(12)
|
|
92
|
+
const cipher = createCipheriv('aes-256-gcm', key, nonce)
|
|
93
|
+
const body = Buffer.concat([cipher.update(JSON.stringify(value), 'utf8'), cipher.final()])
|
|
94
|
+
return JSON.stringify({
|
|
95
|
+
e: ephemeralPublic,
|
|
96
|
+
n: nonce.toString('base64url'),
|
|
97
|
+
c: body.toString('base64url'),
|
|
98
|
+
t: cipher.getAuthTag().toString('base64url'),
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function openSealed(deviceCode, sealed) {
|
|
103
|
+
const { e, n, c, t } = JSON.parse(sealed)
|
|
104
|
+
const shared = diffieHellman({ privateKey: deviceKey(deviceCode), publicKey: fromSpki(e) })
|
|
105
|
+
const key = Buffer.from(hkdfSync('sha256', shared, Buffer.from(e), INFO, 32))
|
|
106
|
+
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(n, 'base64url'))
|
|
107
|
+
decipher.setAuthTag(Buffer.from(t, 'base64url'))
|
|
108
|
+
return JSON.parse(Buffer.concat([decipher.update(Buffer.from(c, 'base64url')), decipher.final()]).toString('utf8'))
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ---- The store ----
|
|
112
|
+
|
|
113
|
+
export function createDeviceLogins({ db, now = () => new Date(), maxPending = MAX_PENDING, maxPerIp = MAX_PENDING_PER_IP } = {}) {
|
|
114
|
+
if (!db) throw new Error('createDeviceLogins needs the database')
|
|
115
|
+
const q = accounts(db)
|
|
116
|
+
const time = () => now().getTime()
|
|
117
|
+
|
|
118
|
+
const sweep = () => q.run('DELETE FROM device_logins WHERE expires_at <= :now', { now: time() })
|
|
119
|
+
const entryOf = (row) =>
|
|
120
|
+
row && {
|
|
121
|
+
userCode: row.user_code,
|
|
122
|
+
name: row.name,
|
|
123
|
+
ip: row.ip,
|
|
124
|
+
createdAt: row.created_at,
|
|
125
|
+
expiresAt: row.expires_at,
|
|
126
|
+
status: row.status,
|
|
127
|
+
purpose: row.purpose || null,
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// A new login, or { refused: 'per_ip' } when this address has too many
|
|
131
|
+
// pending already.
|
|
132
|
+
function start({ name, ip, purpose }) {
|
|
133
|
+
return transaction(db, () => {
|
|
134
|
+
sweep()
|
|
135
|
+
const from = ip || null
|
|
136
|
+
const fromHere = q.get("SELECT COUNT(*) AS n FROM device_logins WHERE status = 'pending' AND ip IS :ip AND expires_at > :now", {
|
|
137
|
+
ip: from,
|
|
138
|
+
now: time(),
|
|
139
|
+
}).n
|
|
140
|
+
if (fromHere >= maxPerIp) return { refused: 'per_ip' }
|
|
141
|
+
// Oldest first; an approved login waiting for its terminal's next poll goes last.
|
|
142
|
+
let size = q.get('SELECT COUNT(*) AS n FROM device_logins').n
|
|
143
|
+
while (size >= maxPending) {
|
|
144
|
+
const oldest =
|
|
145
|
+
q.get("SELECT device_hash FROM device_logins WHERE status != 'approved' ORDER BY created_at, rowid LIMIT 1") ||
|
|
146
|
+
q.get('SELECT device_hash FROM device_logins ORDER BY created_at, rowid LIMIT 1')
|
|
147
|
+
q.run('DELETE FROM device_logins WHERE device_hash = :hash', { hash: oldest.device_hash })
|
|
148
|
+
size -= 1
|
|
149
|
+
}
|
|
150
|
+
let userCode
|
|
151
|
+
do {
|
|
152
|
+
userCode = Array.from({ length: 8 }, () => ALPHABET[randomInt(ALPHABET.length)]).join('')
|
|
153
|
+
} while (q.get('SELECT 1 AS x FROM device_logins WHERE user_code = :code', { code: userCode }))
|
|
154
|
+
const deviceCode = randomToken(32)
|
|
155
|
+
const created = time()
|
|
156
|
+
q.run(
|
|
157
|
+
`INSERT INTO device_logins (device_hash, user_code, name, ip, seal_key, created_at, expires_at, status, purpose)
|
|
158
|
+
VALUES (:hash, :code, :name, :ip, :seal, :created, :expires, 'pending', :purpose)`,
|
|
159
|
+
{
|
|
160
|
+
hash: sha256(deviceCode),
|
|
161
|
+
purpose: purpose === 'import' ? 'import' : null,
|
|
162
|
+
code: userCode,
|
|
163
|
+
name: cleanMachineName(name),
|
|
164
|
+
ip: from,
|
|
165
|
+
seal: spki(createPublicKey(deviceKey(deviceCode))),
|
|
166
|
+
created,
|
|
167
|
+
expires: created + DEVICE_TTL_MS,
|
|
168
|
+
},
|
|
169
|
+
)
|
|
170
|
+
return { deviceCode, userCode, expiresAt: new Date(created + DEVICE_TTL_MS).toISOString() }
|
|
171
|
+
})
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// The CLI's poll. An approved or denied login answers once, then is gone.
|
|
175
|
+
function poll(deviceCode) {
|
|
176
|
+
if (typeof deviceCode !== 'string' || !DEVICE_CODE_RE.test(deviceCode)) return { status: 'expired' }
|
|
177
|
+
return transaction(db, () => {
|
|
178
|
+
sweep()
|
|
179
|
+
const hash = sha256(deviceCode)
|
|
180
|
+
const row = q.get('SELECT * FROM device_logins WHERE device_hash = :hash', { hash })
|
|
181
|
+
if (!row) return { status: 'expired' }
|
|
182
|
+
if (row.status === 'pending') return { status: 'pending' }
|
|
183
|
+
q.run('DELETE FROM device_logins WHERE device_hash = :hash', { hash })
|
|
184
|
+
if (row.status !== 'approved') return { status: 'denied' }
|
|
185
|
+
try {
|
|
186
|
+
return { status: 'approved', result: openSealed(deviceCode, row.result) }
|
|
187
|
+
} catch {
|
|
188
|
+
return { status: 'expired' }
|
|
189
|
+
}
|
|
190
|
+
})
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// A pending login by its user code, for the console.
|
|
194
|
+
function lookup(userCode) {
|
|
195
|
+
const code = normalizeUserCode(userCode)
|
|
196
|
+
if (!USER_CODE_RE.test(code)) return null
|
|
197
|
+
const row = q.get("SELECT * FROM device_logins WHERE user_code = :code AND status = 'pending' AND expires_at > :now", {
|
|
198
|
+
code,
|
|
199
|
+
now: time(),
|
|
200
|
+
})
|
|
201
|
+
return row ? { code, entry: entryOf(row) } : null
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Single use: only a pending, unexpired login changes. Returns whether it did.
|
|
205
|
+
function approve(userCode, result) {
|
|
206
|
+
const code = normalizeUserCode(userCode)
|
|
207
|
+
if (!USER_CODE_RE.test(code)) return false
|
|
208
|
+
return transaction(db, () => {
|
|
209
|
+
const row = q.get("SELECT seal_key FROM device_logins WHERE user_code = :code AND status = 'pending' AND expires_at > :now", {
|
|
210
|
+
code,
|
|
211
|
+
now: time(),
|
|
212
|
+
})
|
|
213
|
+
if (!row) return false
|
|
214
|
+
const changed = q.run(
|
|
215
|
+
"UPDATE device_logins SET status = 'approved', result = :result WHERE user_code = :code AND status = 'pending'",
|
|
216
|
+
{ code, result: sealFor(row.seal_key, result) },
|
|
217
|
+
)
|
|
218
|
+
return changed.changes === 1
|
|
219
|
+
})
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function deny(userCode) {
|
|
223
|
+
const code = normalizeUserCode(userCode)
|
|
224
|
+
if (!USER_CODE_RE.test(code)) return false
|
|
225
|
+
const changed = q.run(
|
|
226
|
+
"UPDATE device_logins SET status = 'denied' WHERE user_code = :code AND status = 'pending' AND expires_at > :now",
|
|
227
|
+
{ code, now: time() },
|
|
228
|
+
)
|
|
229
|
+
return changed.changes === 1
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return { start, poll, lookup, approve, deny, size: () => q.get('SELECT COUNT(*) AS n FROM device_logins').n }
|
|
233
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Process-local notifications carry ids only. Consumers re-authorize and
|
|
2
|
+
// refetch; comment text and account identities are never broadcast here.
|
|
3
|
+
export function createEventBus() {
|
|
4
|
+
const listeners = new Set()
|
|
5
|
+
let sequence = 0
|
|
6
|
+
return {
|
|
7
|
+
publish(event) {
|
|
8
|
+
const item = { ...event, sequence: ++sequence }
|
|
9
|
+
for (const listener of [...listeners]) listener(item)
|
|
10
|
+
},
|
|
11
|
+
subscribe(listener) {
|
|
12
|
+
listeners.add(listener)
|
|
13
|
+
return () => listeners.delete(listener)
|
|
14
|
+
},
|
|
15
|
+
close() {
|
|
16
|
+
for (const listener of [...listeners]) listener({ type: 'close' })
|
|
17
|
+
listeners.clear()
|
|
18
|
+
},
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// The change event a successful write publishes (the SSE stream and board
|
|
23
|
+
// presence refetch on it), or null. Only comment, approval, import, agent
|
|
24
|
+
// policy and push-commit writes change what watchers see; a push's file
|
|
25
|
+
// uploads, token and device approvals publish nothing.
|
|
26
|
+
export function changeEventType(pathname) {
|
|
27
|
+
if (/\/pushes\/[^/]+\/commit$/.test(pathname)) return 'push.committed'
|
|
28
|
+
if (/\/comments\/[1-9][0-9]*\/send-to-agent$/.test(pathname)) return 'comment.vouched'
|
|
29
|
+
if (/\/comments\/[1-9][0-9]*\/resolve$/.test(pathname)) return 'comment.resolved'
|
|
30
|
+
if (/\/boards\/[^/]+\/comments$/.test(pathname)) return 'comment.created'
|
|
31
|
+
if (
|
|
32
|
+
/\/boards\/[^/]+\/(?:comments\/[1-9][0-9]*(?:\/(?:replies|reactions|reopen|agent-status|approvals))?|approvals\/[^/]+|import)$/.test(
|
|
33
|
+
pathname,
|
|
34
|
+
) ||
|
|
35
|
+
/\/projects\/[^/]+\/agent$/.test(pathname)
|
|
36
|
+
)
|
|
37
|
+
return 'comment.updated'
|
|
38
|
+
return null
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Mounted first (src/hosted/app.js): when a write finishes, every event
|
|
42
|
+
// stream rechecks its token and the write's change event (if any) goes out.
|
|
43
|
+
export const publishMutations =
|
|
44
|
+
({ events, streams }) =>
|
|
45
|
+
(req, res, next) => {
|
|
46
|
+
if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method))
|
|
47
|
+
res.once('finish', () => {
|
|
48
|
+
for (const check of [...streams]) check()
|
|
49
|
+
const pathname = req.originalUrl.split('?')[0]
|
|
50
|
+
const type = res.statusCode < 400 && req.t && req.project ? changeEventType(pathname) : null
|
|
51
|
+
if (type) {
|
|
52
|
+
const comment = /\/comments\/([1-9][0-9]*)/.exec(pathname)?.[1]
|
|
53
|
+
events.publish({
|
|
54
|
+
type,
|
|
55
|
+
workspace: req.t.workspaceId,
|
|
56
|
+
project: req.project.id,
|
|
57
|
+
board: req.ctx?.board?.id || /\/boards\/([^/]+)/.exec(pathname)?.[1] || null,
|
|
58
|
+
...(comment ? { comment: Number(comment) } : {}),
|
|
59
|
+
})
|
|
60
|
+
}
|
|
61
|
+
})
|
|
62
|
+
next()
|
|
63
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// Request guards for the hosted app (src/hosted/app.js): cookies, rate
|
|
2
|
+
// limits, sessions, same-origin writes, workspace and project access, error
|
|
3
|
+
// handling and audit entries. createGuards(deps) returns them as one set.
|
|
4
|
+
|
|
5
|
+
import { AuthError, REAUTH_MS } from './auth.js'
|
|
6
|
+
import { AgentPolicyError } from './agent-policy.js'
|
|
7
|
+
import { parseCookies } from './cookies.js'
|
|
8
|
+
import { ID_PATTERNS } from './crypto.js'
|
|
9
|
+
import { HttpError, fail } from './http.js'
|
|
10
|
+
import { suspendedWrite } from './operator.js'
|
|
11
|
+
import { ProjectError, createProjectStore } from './projects.js'
|
|
12
|
+
import { PushError } from './push.js'
|
|
13
|
+
import { LIMITS } from './ratelimit.js'
|
|
14
|
+
import { TenancyError, audit, roleAtLeast, roleIn, tenant } from './tenancy.js'
|
|
15
|
+
import { CommentError } from '../store.js'
|
|
16
|
+
|
|
17
|
+
const ACTIVE_EVERY_MS = 5 * 60_000
|
|
18
|
+
|
|
19
|
+
export function createGuards({ db, dataDir, auth, quotas, secure, trustProxy, rateLimiter, siteOf, SESSION_COOKIE, iso, now, log }) {
|
|
20
|
+
const clientIp = (req) => (trustProxy ? req.ip : req.socket.remoteAddress) || 'unknown'
|
|
21
|
+
const setCookie = (res, name, value, maxAgeSeconds) => {
|
|
22
|
+
res.append('Set-Cookie', `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}${secure ? '; Secure' : ''}`)
|
|
23
|
+
}
|
|
24
|
+
const limit =
|
|
25
|
+
(bucket, keyOf = clientIp) =>
|
|
26
|
+
(req, res, next) => {
|
|
27
|
+
const result = rateLimiter.hit(bucket, keyOf(req), LIMITS[bucket])
|
|
28
|
+
if (result.ok) return next()
|
|
29
|
+
res.setHeader('Retry-After', String(result.retryAfter))
|
|
30
|
+
fail(res, 429, 'rate_limited', 'Too many requests. Wait a moment and try again.')
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// ---- Sessions ----
|
|
34
|
+
function sessionOf(req) {
|
|
35
|
+
if (req.sessionChecked) return req.auth
|
|
36
|
+
req.sessionChecked = true
|
|
37
|
+
req.auth = auth.readSession(parseCookies(req.headers.cookie)[SESSION_COOKIE]) || null
|
|
38
|
+
return req.auth
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Cookie-authenticated writes: JSON only, from this origin.
|
|
42
|
+
function sameOrigin(req) {
|
|
43
|
+
const value = req.headers.origin
|
|
44
|
+
if (value) return value === siteOf(req).origin
|
|
45
|
+
return req.headers['sec-fetch-site'] === 'same-origin'
|
|
46
|
+
}
|
|
47
|
+
const guardWrites = (req, res, next) => {
|
|
48
|
+
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next()
|
|
49
|
+
if (!sameOrigin(req)) return fail(res, 403, 'bad_origin', 'Cross-site request refused.')
|
|
50
|
+
if (req.method !== 'DELETE' && !req.is('application/json'))
|
|
51
|
+
return fail(res, 415, 'json_required', 'Send JSON (Content-Type: application/json).')
|
|
52
|
+
next()
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const needSession = (req, res, next) => {
|
|
56
|
+
if (!sessionOf(req)) return fail(res, 401, 'signed_out', 'Sign in first.')
|
|
57
|
+
req.user = req.auth.user
|
|
58
|
+
next()
|
|
59
|
+
}
|
|
60
|
+
const needFresh = (req, res, next) => {
|
|
61
|
+
if (!auth.isFresh(req.auth.session)) {
|
|
62
|
+
return fail(
|
|
63
|
+
res,
|
|
64
|
+
403,
|
|
65
|
+
'reauth_required',
|
|
66
|
+
`Confirm with your passkey first (needed every ${Math.round(REAUTH_MS / 60000)} minutes for this).`,
|
|
67
|
+
)
|
|
68
|
+
}
|
|
69
|
+
next()
|
|
70
|
+
}
|
|
71
|
+
const needFreshOrRecovery = (req, res, next) => (auth.canAddAfterRecovery(req.auth.session) ? next() : needFresh(req, res, next))
|
|
72
|
+
const freshOrThrow = (req) => {
|
|
73
|
+
if (!auth.isFresh(req.auth.session))
|
|
74
|
+
throw new HttpError(403, 'reauth_required', 'Confirm with your passkey first (needed for owner changes).')
|
|
75
|
+
}
|
|
76
|
+
// :ws must be a workspace the user is in, with at least `role`. Unknown
|
|
77
|
+
// and foreign workspaces answer the same 404.
|
|
78
|
+
const inWorkspace =
|
|
79
|
+
(role = 'viewer') =>
|
|
80
|
+
(req, res, next) => {
|
|
81
|
+
const ws = String(req.params.ws || '')
|
|
82
|
+
const current = ID_PATTERNS.workspace.test(ws) ? roleIn(db, req.user.id, ws) : null
|
|
83
|
+
if (!current) return fail(res, 404, 'unknown_workspace', 'No such workspace.')
|
|
84
|
+
if (!roleAtLeast(current, role)) return fail(res, 403, 'forbidden', `This needs the ${role} role or higher.`)
|
|
85
|
+
// Admin pages idle-expire: 12 hours without one, a passkey check
|
|
86
|
+
// brings them back (the rest of the session keeps working).
|
|
87
|
+
if (roleAtLeast(role, 'admin')) {
|
|
88
|
+
if (auth.adminIdleExpired(req.auth.session))
|
|
89
|
+
return fail(
|
|
90
|
+
res,
|
|
91
|
+
403,
|
|
92
|
+
'reauth_required',
|
|
93
|
+
'You have been away from admin pages for 12 hours. Confirm with your passkey to continue.',
|
|
94
|
+
)
|
|
95
|
+
auth.touchAdmin(req.auth.session)
|
|
96
|
+
}
|
|
97
|
+
req.t = tenant(db, ws)
|
|
98
|
+
// Suspended by the operator: read-only (export still works).
|
|
99
|
+
const suspended = suspendedWrite(req, req.t)
|
|
100
|
+
if (suspended) return fail(res, 403, 'workspace_suspended', suspended)
|
|
101
|
+
req.role = current
|
|
102
|
+
req.projects = createProjectStore(req.t, { db, dataDir, maxProjects: quotas.of(ws).projects })
|
|
103
|
+
touchActive(req.t, req.user.id)
|
|
104
|
+
next()
|
|
105
|
+
}
|
|
106
|
+
const inProject = (req, res, next) => {
|
|
107
|
+
const project = req.projects.get(req.params.pid)
|
|
108
|
+
if (!project) return fail(res, 404, 'unknown_project', 'No such project.')
|
|
109
|
+
req.project = project
|
|
110
|
+
next()
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const handle = (fn) => async (req, res) => {
|
|
114
|
+
try {
|
|
115
|
+
await fn(req, res)
|
|
116
|
+
} catch (error) {
|
|
117
|
+
if (
|
|
118
|
+
error instanceof CommentError ||
|
|
119
|
+
error instanceof AuthError ||
|
|
120
|
+
error instanceof ProjectError ||
|
|
121
|
+
error instanceof PushError ||
|
|
122
|
+
error instanceof HttpError ||
|
|
123
|
+
error instanceof AgentPolicyError
|
|
124
|
+
) {
|
|
125
|
+
return fail(res, error.statusCode, error.code, error.message)
|
|
126
|
+
}
|
|
127
|
+
if (!(error instanceof TenancyError)) log(`error: ${error.name || 'Error'} (request failed; request values omitted)`)
|
|
128
|
+
else log(`tenancy error: ${error.message}`)
|
|
129
|
+
fail(res, 500, 'server_error', 'Something went wrong on the server.')
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const auditOf = (req, action, target = null, detail = {}, t = req.t) =>
|
|
134
|
+
audit(t, {
|
|
135
|
+
userId: req.user?.id || null,
|
|
136
|
+
tokenId: req.token?.id || null,
|
|
137
|
+
shareId: req.guest?.shareId || null,
|
|
138
|
+
action,
|
|
139
|
+
target,
|
|
140
|
+
ip: clientIp(req),
|
|
141
|
+
detail,
|
|
142
|
+
at: iso(),
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
// "Last active" per membership, written at most every few minutes.
|
|
146
|
+
const activeSeen = new Map()
|
|
147
|
+
function touchActive(t, userId) {
|
|
148
|
+
const key = `${t.workspaceId}:${userId}`
|
|
149
|
+
const time = now().getTime()
|
|
150
|
+
if (time - (activeSeen.get(key) || 0) < ACTIVE_EVERY_MS) return
|
|
151
|
+
activeSeen.set(key, time)
|
|
152
|
+
if (activeSeen.size > 10_000) activeSeen.clear()
|
|
153
|
+
t.run('UPDATE memberships SET last_active_at = :at WHERE workspace_id = :ws AND user_id = :user', { at: iso(), user: userId })
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return {
|
|
157
|
+
clientIp,
|
|
158
|
+
setCookie,
|
|
159
|
+
limit,
|
|
160
|
+
sessionOf,
|
|
161
|
+
guardWrites,
|
|
162
|
+
needSession,
|
|
163
|
+
needFresh,
|
|
164
|
+
needFreshOrRecovery,
|
|
165
|
+
freshOrThrow,
|
|
166
|
+
inWorkspace,
|
|
167
|
+
inProject,
|
|
168
|
+
handle,
|
|
169
|
+
auditOf,
|
|
170
|
+
touchActive,
|
|
171
|
+
}
|
|
172
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// What a share link guest sees of a hosted comment. Only import-free
|
|
2
|
+
// modules, so the public demo's in-browser backend (client/src/demo)
|
|
3
|
+
// projects comments the same way the server does.
|
|
4
|
+
|
|
5
|
+
import { countedReactions } from '../reactions.js'
|
|
6
|
+
|
|
7
|
+
// Which share link wrote a guest comment or reply. Kept off the JSON (a
|
|
8
|
+
// symbol key) so members and tokens never see it; guestView uses it.
|
|
9
|
+
export const GUEST_SHARE = Symbol('guestShare')
|
|
10
|
+
|
|
11
|
+
// What a share link guest sees of a comment: the text, place and state, and
|
|
12
|
+
// no workspace detail. Members by display name only (no handles), agents as
|
|
13
|
+
// "Agent", guests of other links as "Another guest"; no agent status,
|
|
14
|
+
// resolution notes, fix references or GitHub links; reactions as counts, not names.
|
|
15
|
+
export function guestView(comment, shareId) {
|
|
16
|
+
const from = comment[GUEST_SHARE] || { comment: null, replies: [] }
|
|
17
|
+
const name = (author, { guest, agent, share }) =>
|
|
18
|
+
guest ? (share && share === shareId ? author : 'Another guest') : agent ? 'Agent' : author
|
|
19
|
+
return {
|
|
20
|
+
id: comment.id,
|
|
21
|
+
pageId: comment.pageId,
|
|
22
|
+
viewport: comment.viewport,
|
|
23
|
+
x: comment.x,
|
|
24
|
+
y: comment.y,
|
|
25
|
+
body: comment.body,
|
|
26
|
+
author: name(comment.author, { guest: comment.authorGuest, agent: comment.authorAgent, share: from.comment }),
|
|
27
|
+
...(comment.authorGuest ? { authorGuest: true } : {}),
|
|
28
|
+
...(comment.authorAgent ? { authorAgent: true } : {}),
|
|
29
|
+
...(comment.anchor ? { anchor: comment.anchor } : {}),
|
|
30
|
+
captureVersion: comment.captureVersion,
|
|
31
|
+
status: comment.status,
|
|
32
|
+
createdAt: comment.createdAt,
|
|
33
|
+
updatedAt: comment.updatedAt,
|
|
34
|
+
resolvedAt: comment.resolvedAt,
|
|
35
|
+
resolution: null,
|
|
36
|
+
replies: comment.replies.map((reply, index) => ({
|
|
37
|
+
id: reply.id,
|
|
38
|
+
author: name(reply.author, { guest: reply.guest, agent: reply.agent, share: from.replies[index] }),
|
|
39
|
+
...(reply.guest ? { guest: true } : {}),
|
|
40
|
+
...(reply.agent ? { agent: true } : {}),
|
|
41
|
+
body: reply.body,
|
|
42
|
+
createdAt: reply.createdAt,
|
|
43
|
+
reactions: countedReactions(reply.reactions),
|
|
44
|
+
})),
|
|
45
|
+
reactions: countedReactions(comment.reactions),
|
|
46
|
+
editedAt: comment.editedAt || null,
|
|
47
|
+
agentStatus: null,
|
|
48
|
+
agentStatusAt: null,
|
|
49
|
+
reopenCount: comment.reopenCount,
|
|
50
|
+
reopenedAt: comment.reopenedAt,
|
|
51
|
+
mentions: [],
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// What a public project's visitor sees: the guest view, with every guest
|
|
56
|
+
// named "Guest" (a visitor belongs to no link).
|
|
57
|
+
export function publicView(comment) {
|
|
58
|
+
const view = guestView(comment, null)
|
|
59
|
+
const anon = (name, guest) => (guest ? 'Guest' : name)
|
|
60
|
+
return {
|
|
61
|
+
...view,
|
|
62
|
+
author: anon(view.author, view.authorGuest),
|
|
63
|
+
replies: view.replies.map((reply) => ({ ...reply, author: anon(reply.author, reply.guest) })),
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Small HTTP and input helpers shared by the hosted app's routes
|
|
2
|
+
// (src/hosted/app.js and the modules it mounts).
|
|
3
|
+
|
|
4
|
+
export class HttpError extends Error {
|
|
5
|
+
constructor(status, code, message) {
|
|
6
|
+
super(message)
|
|
7
|
+
this.statusCode = status
|
|
8
|
+
this.code = code
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function fail(res, status, code, message) {
|
|
13
|
+
res.status(status).json({ error: { code, message } })
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// A share link visitor as the board names them: "Ada (guest)", or just
|
|
17
|
+
// "Guest" for one who gave no name (never "Guest (guest)").
|
|
18
|
+
export const guestLabel = (name) => (!name || name === 'Guest' ? 'Guest' : `${name} (guest)`)
|
|
19
|
+
|
|
20
|
+
// eslint-disable-next-line no-control-regex
|
|
21
|
+
export const CONTROL_RE = /[\u0000-\u001f\u007f]/g
|
|
22
|
+
|
|
23
|
+
// An invite's note: null when empty, false when too long.
|
|
24
|
+
export function cleanInviteNote(value) {
|
|
25
|
+
if (value === undefined || value === null) return null
|
|
26
|
+
if (typeof value !== 'string') return false
|
|
27
|
+
const note = value.replace(CONTROL_RE, '').replace(/\s+/g, ' ').trim()
|
|
28
|
+
if (!note) return null
|
|
29
|
+
return note.length > 80 ? false : note
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Names people type (workspaces, tokens): no control characters, one line.
|
|
33
|
+
export const cleanName = (value, max) =>
|
|
34
|
+
String(value ?? '')
|
|
35
|
+
.replace(/\s+/g, ' ')
|
|
36
|
+
.replace(CONTROL_RE, '')
|
|
37
|
+
.trim()
|
|
38
|
+
.slice(0, max)
|
|
39
|
+
export const cleanWorkspaceName = (value) => cleanName(value, 80)
|