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,300 @@
|
|
|
1
|
+
// One-way local comment imports. All fields are untrusted; paths and local
|
|
2
|
+
// identities never enter the hosted store. Every batch and its retry result
|
|
3
|
+
// commit together. A completed session can only be replayed by its own token.
|
|
4
|
+
import { createHash } from 'node:crypto'
|
|
5
|
+
import { AGENT_STATUSES, AUTHOR_MAX, COMMENT_BODY_MAX, CommentError, cleanFixRef, validateAnchor, VERSION_RE } from '../store.js'
|
|
6
|
+
import { ID_RE, VIEWPORT_NAME_RE } from '../config.js'
|
|
7
|
+
import { REACTIONS } from '../reactions.js'
|
|
8
|
+
import { findApiToken } from './tenancy.js'
|
|
9
|
+
import { transaction, hasCommentPolicy } from './db.js'
|
|
10
|
+
|
|
11
|
+
const hex = /^[a-f0-9]{64}$/
|
|
12
|
+
const SCOPE = 'workspace_id = :ws AND project_id = :project AND board_id = :board'
|
|
13
|
+
const digest = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex')
|
|
14
|
+
const bad = (message) => {
|
|
15
|
+
throw new CommentError(400, 'invalid_import', message)
|
|
16
|
+
}
|
|
17
|
+
const text = (value, max, fallback = '') => {
|
|
18
|
+
if (value === null || value === undefined) return fallback
|
|
19
|
+
if (typeof value !== 'string' || value.length > max) bad(`Text must be at most ${max} characters.`)
|
|
20
|
+
return value.replace(/\r\n/g, '\n').trim()
|
|
21
|
+
}
|
|
22
|
+
const date = (value, optional = false) => {
|
|
23
|
+
if ((value === null || value === undefined) && optional) return null
|
|
24
|
+
if (typeof value !== 'string' || value.length > 40 || !Number.isFinite(Date.parse(value))) bad('An import timestamp is invalid.')
|
|
25
|
+
return new Date(value).toISOString()
|
|
26
|
+
}
|
|
27
|
+
const author = (value) => `${text(value, AUTHOR_MAX, 'anonymous').slice(0, AUTHOR_MAX - 11) || 'anonymous'} (imported)`
|
|
28
|
+
const reactions = (value) => {
|
|
29
|
+
if (value === undefined || value === null) return []
|
|
30
|
+
if (!Array.isArray(value) || value.length > REACTIONS.length) bad('Invalid reaction counts.')
|
|
31
|
+
const seen = new Set()
|
|
32
|
+
return value.map((item) => {
|
|
33
|
+
if (!REACTIONS.includes(item?.emoji) || seen.has(item.emoji) || !Number.isInteger(item.count) || item.count < 1 || item.count > 200)
|
|
34
|
+
bad('Invalid reaction count.')
|
|
35
|
+
seen.add(item.emoji)
|
|
36
|
+
return { emoji: item.emoji, count: item.count }
|
|
37
|
+
})
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function cleanImportedComment(raw) {
|
|
41
|
+
if (!raw || typeof raw !== 'object' || typeof raw.importKey !== 'string' || !hex.test(raw.importKey))
|
|
42
|
+
bad('An import needs a SHA-256 importKey.')
|
|
43
|
+
if (!Number.isSafeInteger(raw.localId) || raw.localId < 1) bad('An import needs a positive local id.')
|
|
44
|
+
if (typeof raw.pageId !== 'string' || (!ID_RE.test(raw.pageId) && !/^variant:[a-z0-9][a-z0-9-]{0,63}$/.test(raw.pageId)))
|
|
45
|
+
bad('Invalid page id.')
|
|
46
|
+
if (typeof raw.viewport !== 'string' || !VIEWPORT_NAME_RE.test(raw.viewport)) bad('Invalid viewport.')
|
|
47
|
+
if (![raw.x, raw.y].every((n) => typeof n === 'number' && Number.isFinite(n) && n >= 0 && n <= 100)) bad('Invalid pin position.')
|
|
48
|
+
if (raw.authorKind !== undefined && !['local', 'agent', 'guest'].includes(raw.authorKind)) bad('Invalid imported author kind.')
|
|
49
|
+
const body = text(raw.body, COMMENT_BODY_MAX)
|
|
50
|
+
if (!body) bad('A comment needs text.')
|
|
51
|
+
if (!['open', 'resolved'].includes(raw.status)) bad('Invalid comment state.')
|
|
52
|
+
if (raw.agentStatus != null && !AGENT_STATUSES.includes(raw.agentStatus)) bad('Invalid agent status.')
|
|
53
|
+
if (!Number.isInteger(raw.reopenCount ?? 0) || (raw.reopenCount ?? 0) < 0 || (raw.reopenCount ?? 0) > 100000) bad('Invalid reopen count.')
|
|
54
|
+
if (raw.captureVersion != null && !VERSION_RE.test(raw.captureVersion)) bad('Invalid capture version.')
|
|
55
|
+
if (!Array.isArray(raw.replies) || raw.replies.length > 200) bad('At most 200 replies per comment.')
|
|
56
|
+
return {
|
|
57
|
+
importKey: raw.importKey,
|
|
58
|
+
authorKind: raw.authorKind || 'local',
|
|
59
|
+
localId: raw.localId,
|
|
60
|
+
pageId: raw.pageId,
|
|
61
|
+
viewport: raw.viewport,
|
|
62
|
+
x: raw.x,
|
|
63
|
+
y: raw.y,
|
|
64
|
+
body,
|
|
65
|
+
author: author(raw.author),
|
|
66
|
+
anchor: validateAnchor(raw.anchor),
|
|
67
|
+
captureVersion: raw.captureVersion || null,
|
|
68
|
+
status: raw.status,
|
|
69
|
+
createdAt: date(raw.createdAt),
|
|
70
|
+
updatedAt: date(raw.updatedAt),
|
|
71
|
+
resolvedAt: date(raw.resolvedAt, true),
|
|
72
|
+
resolution: text(raw.resolution, COMMENT_BODY_MAX, null),
|
|
73
|
+
agentStatus: raw.agentStatus || null,
|
|
74
|
+
agentStatusAt: date(raw.agentStatusAt, true),
|
|
75
|
+
reopenCount: raw.reopenCount || 0,
|
|
76
|
+
reopenedAt: date(raw.reopenedAt, true),
|
|
77
|
+
fixRef: raw.fixRef == null ? null : cleanFixRef(raw.fixRef),
|
|
78
|
+
editedAt: date(raw.editedAt, true),
|
|
79
|
+
reactions: reactions(raw.reactions),
|
|
80
|
+
replies: raw.replies.map((reply, i) => {
|
|
81
|
+
const body = text(reply?.body, COMMENT_BODY_MAX)
|
|
82
|
+
if (!body) bad('A reply needs text.')
|
|
83
|
+
return {
|
|
84
|
+
id: i + 1,
|
|
85
|
+
author: author(reply.author),
|
|
86
|
+
body,
|
|
87
|
+
createdAt: date(reply.createdAt),
|
|
88
|
+
...(reply.agent === true ? { agent: true } : {}),
|
|
89
|
+
...(reply.guest === true ? { guest: true } : {}),
|
|
90
|
+
imported: true,
|
|
91
|
+
...(reply.editedAt ? { editedAt: date(reply.editedAt) } : {}),
|
|
92
|
+
importedReactions: reactions(reply.reactions),
|
|
93
|
+
}
|
|
94
|
+
}),
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Includes reactions as well as text: a remote reaction must not be silently
|
|
99
|
+
// overwritten by a later local snapshot. Identities remain server-side here.
|
|
100
|
+
const fingerprint = (row) => digest(row)
|
|
101
|
+
|
|
102
|
+
export function importBatch({ db, t, projectId, board, token, tokenHash, input, now = new Date() }) {
|
|
103
|
+
if (
|
|
104
|
+
typeof input?.sessionId !== 'string' ||
|
|
105
|
+
typeof input?.batchKey !== 'string' ||
|
|
106
|
+
!hex.test(input.sessionId) ||
|
|
107
|
+
!hex.test(input.batchKey)
|
|
108
|
+
)
|
|
109
|
+
bad('An import needs session and batch idempotency keys.')
|
|
110
|
+
const commit = input.commit === true
|
|
111
|
+
if (!Array.isArray(input.comments) || input.comments.length > 200 || (commit && input.comments.length))
|
|
112
|
+
bad('An import batch holds at most 200 comments; commit has no comments.')
|
|
113
|
+
const clean = input.comments.map(cleanImportedComment)
|
|
114
|
+
if (new Set(clean.map((item) => item.importKey)).size !== clean.length) bad('Duplicate import keys in a batch.')
|
|
115
|
+
const key = { project: projectId, board: board.id }
|
|
116
|
+
const session = { project: projectId, session: input.sessionId }
|
|
117
|
+
const hash = digest({ board: board.id, commit, comments: clean })
|
|
118
|
+
return transaction(db, () => {
|
|
119
|
+
// Authentication before the JSON parser is only admission. A body may be
|
|
120
|
+
// held open while another request consumes/revokes the grant. Recheck the
|
|
121
|
+
// exact admitted credential inside the write transaction, including all
|
|
122
|
+
// live creator, expiry and suspension rules, before replay or mutation.
|
|
123
|
+
const live = typeof tokenHash === 'string' ? findApiToken(db, tokenHash, now.toISOString()) : null
|
|
124
|
+
if (!live || live.id !== token.id || live.workspace_id !== t.workspaceId || live.project_id !== projectId)
|
|
125
|
+
throw new CommentError(401, 'bad_token', 'This token is no longer valid for this project.')
|
|
126
|
+
const scopes = JSON.parse(live.scopes)
|
|
127
|
+
const userId = live.created_by
|
|
128
|
+
const old = t.get(
|
|
129
|
+
'SELECT * FROM import_batches WHERE workspace_id = :ws AND project_id = :project AND session_id = :session AND batch_key = :batch',
|
|
130
|
+
{ ...session, batch: input.batchKey },
|
|
131
|
+
)
|
|
132
|
+
if (old) {
|
|
133
|
+
if (old.token_id !== token.id || old.payload_hash !== hash)
|
|
134
|
+
throw new CommentError(409, 'import_key_reused', 'That batch key was already used for different content.')
|
|
135
|
+
return JSON.parse(old.result)
|
|
136
|
+
}
|
|
137
|
+
if (!scopes.includes('import'))
|
|
138
|
+
throw new CommentError(
|
|
139
|
+
403,
|
|
140
|
+
'missing_scope',
|
|
141
|
+
'This token needs the one-time import scope. Run shapewall share again and approve the move.',
|
|
142
|
+
)
|
|
143
|
+
const prior = t.get(
|
|
144
|
+
'SELECT * FROM import_sessions WHERE workspace_id = :ws AND project_id = :project AND session_id = :session',
|
|
145
|
+
session,
|
|
146
|
+
)
|
|
147
|
+
if (prior && (prior.token_id !== token.id || prior.committed_at))
|
|
148
|
+
throw new CommentError(409, 'import_finished', 'This import session has finished or belongs to another token.')
|
|
149
|
+
if (
|
|
150
|
+
!prior &&
|
|
151
|
+
t.get('SELECT COUNT(*) AS n FROM import_sessions WHERE workspace_id = :ws AND project_id=:project AND token_id=:token', {
|
|
152
|
+
project: projectId,
|
|
153
|
+
token: token.id,
|
|
154
|
+
}).n >= 20
|
|
155
|
+
)
|
|
156
|
+
throw new CommentError(409, 'too_many_imports', 'Too many import sessions for this token. Finish a pending move.')
|
|
157
|
+
if (
|
|
158
|
+
t.get('SELECT COUNT(*) AS n FROM import_batches WHERE workspace_id = :ws AND project_id=:project AND session_id=:session', session)
|
|
159
|
+
.n >= 100
|
|
160
|
+
)
|
|
161
|
+
throw new CommentError(409, 'too_many_batches', 'This move exceeded 100 batches; commit it before starting another.')
|
|
162
|
+
if (!prior)
|
|
163
|
+
t.run(
|
|
164
|
+
'INSERT INTO import_sessions (workspace_id, project_id, session_id, token_id, created_at) VALUES (:ws, :project, :session, :token, :at)',
|
|
165
|
+
{ ...session, token: token.id, at: now.toISOString() },
|
|
166
|
+
)
|
|
167
|
+
const result = { imported: 0, updated: 0, skipped: 0, conflicts: [], mappings: [], committed: commit }
|
|
168
|
+
const hasPolicy = hasCommentPolicy(db)
|
|
169
|
+
for (const item of clean) {
|
|
170
|
+
const params = { ...key, importKey: item.importKey }
|
|
171
|
+
const mapped = t.get(`SELECT * FROM comment_imports WHERE ${SCOPE} AND import_key = :importKey`, params)
|
|
172
|
+
const row = mapped && t.get(`SELECT * FROM comments WHERE ${SCOPE} AND number = :number`, { ...key, number: mapped.comment_number })
|
|
173
|
+
const sourceHash = digest(item)
|
|
174
|
+
if (mapped && mapped.source_hash === sourceHash) {
|
|
175
|
+
result.skipped += 1
|
|
176
|
+
} else if (mapped && (!row || fingerprint(row) !== mapped.remote_hash)) {
|
|
177
|
+
result.conflicts.push(item.localId)
|
|
178
|
+
continue
|
|
179
|
+
} else {
|
|
180
|
+
let number = mapped?.comment_number
|
|
181
|
+
if (!mapped) {
|
|
182
|
+
const count = t.get(`SELECT COUNT(*) AS n FROM comments WHERE ${SCOPE}`, key).n
|
|
183
|
+
if (count >= 5000) throw new CommentError(409, 'too_many_comments', 'A board holds at most 5000 comments.')
|
|
184
|
+
number = t.get(`SELECT next_comment FROM boards WHERE ${SCOPE}`, key).next_comment
|
|
185
|
+
t.run(`UPDATE boards SET next_comment = :next WHERE ${SCOPE}`, { ...key, next: number + 1 })
|
|
186
|
+
t.run(
|
|
187
|
+
`INSERT INTO comments (workspace_id, project_id, board_id, number, page_id, viewport, x, y, body, author, status, created_at, updated_at) VALUES (:ws, :project, :board, :number, :page, :viewport, :x, :y, :body, :author, :status, :created, :updated)`,
|
|
188
|
+
{
|
|
189
|
+
...key,
|
|
190
|
+
number,
|
|
191
|
+
page: item.pageId,
|
|
192
|
+
viewport: item.viewport,
|
|
193
|
+
x: item.x,
|
|
194
|
+
y: item.y,
|
|
195
|
+
body: item.body,
|
|
196
|
+
author: item.author,
|
|
197
|
+
status: item.status,
|
|
198
|
+
created: item.createdAt,
|
|
199
|
+
updated: item.updatedAt,
|
|
200
|
+
},
|
|
201
|
+
)
|
|
202
|
+
}
|
|
203
|
+
t.run(
|
|
204
|
+
`UPDATE comments SET page_id=:page, viewport=:viewport, x=:x, y=:y, body=:body, author=:author, author_handle=NULL, author_user_id=NULL, author_token_id=NULL, author_share_id=NULL, anchor=:anchor, capture_version=:version, status=:status, created_at=:created, updated_at=:updated, resolved_at=:resolved, resolution=:resolution, replies=:replies, agent_status=:agent, agent_status_at=:agentAt, reopen_count=:reopens, reopened_at=:reopened, fix_ref=:fix, edited_at=:edited, reactions='[]', imported_by=:user, import_author_kind=:kind, imported_at=:at, import_orphan=:orphan, imported_reactions=:reactions ${hasPolicy ? ', imported=1, dispatch_hash=NULL, dispatch_by=NULL, dispatch_at=NULL, run_approved=0' : ''} WHERE ${SCOPE} AND number = :number`,
|
|
205
|
+
{
|
|
206
|
+
...key,
|
|
207
|
+
number,
|
|
208
|
+
page: item.pageId,
|
|
209
|
+
viewport: item.viewport,
|
|
210
|
+
x: item.x,
|
|
211
|
+
y: item.y,
|
|
212
|
+
body: item.body,
|
|
213
|
+
author: item.author,
|
|
214
|
+
anchor: item.anchor ? JSON.stringify(item.anchor) : null,
|
|
215
|
+
version: item.captureVersion,
|
|
216
|
+
status: item.status,
|
|
217
|
+
created: item.createdAt,
|
|
218
|
+
updated: item.updatedAt,
|
|
219
|
+
resolved: item.resolvedAt,
|
|
220
|
+
resolution: item.resolution,
|
|
221
|
+
replies: JSON.stringify(item.replies),
|
|
222
|
+
agent: item.agentStatus,
|
|
223
|
+
agentAt: item.agentStatusAt,
|
|
224
|
+
reopens: item.reopenCount,
|
|
225
|
+
reopened: item.reopenedAt,
|
|
226
|
+
fix: item.fixRef,
|
|
227
|
+
edited: item.editedAt,
|
|
228
|
+
user: userId,
|
|
229
|
+
kind: item.authorKind,
|
|
230
|
+
at: now.toISOString(),
|
|
231
|
+
orphan: board.pages.some((page) => page.id === item.pageId) || item.pageId.startsWith('variant:') ? 0 : 1,
|
|
232
|
+
reactions: JSON.stringify(item.reactions),
|
|
233
|
+
},
|
|
234
|
+
)
|
|
235
|
+
const saved = t.get(`SELECT * FROM comments WHERE ${SCOPE} AND number = :number`, { ...key, number })
|
|
236
|
+
if (mapped) {
|
|
237
|
+
t.run(
|
|
238
|
+
`UPDATE comment_imports SET source_hash=:source, remote_hash=:remote, imported_at=:at WHERE ${SCOPE} AND import_key=:importKey`,
|
|
239
|
+
{ ...params, source: sourceHash, remote: fingerprint(saved), at: now.toISOString() },
|
|
240
|
+
)
|
|
241
|
+
result.updated += 1
|
|
242
|
+
} else {
|
|
243
|
+
t.run(
|
|
244
|
+
'INSERT INTO comment_imports (workspace_id, project_id, board_id, import_key, comment_number, source_hash, remote_hash, imported_at) VALUES (:ws, :project, :board, :importKey, :number, :source, :remote, :at)',
|
|
245
|
+
{ ...params, number, source: sourceHash, remote: fingerprint(saved), at: now.toISOString() },
|
|
246
|
+
)
|
|
247
|
+
result.imported += 1
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
result.mappings.push({
|
|
251
|
+
localId: item.localId,
|
|
252
|
+
remoteId:
|
|
253
|
+
mapped?.comment_number ||
|
|
254
|
+
t.get(`SELECT comment_number FROM comment_imports WHERE ${SCOPE} AND import_key=:importKey`, params).comment_number,
|
|
255
|
+
importedAt: now.toISOString(),
|
|
256
|
+
sourceHash,
|
|
257
|
+
})
|
|
258
|
+
}
|
|
259
|
+
if (commit) {
|
|
260
|
+
t.run('UPDATE import_sessions SET committed_at=:at WHERE workspace_id = :ws AND project_id = :project AND session_id=:session', {
|
|
261
|
+
...session,
|
|
262
|
+
at: now.toISOString(),
|
|
263
|
+
})
|
|
264
|
+
t.run('UPDATE api_tokens SET scopes=:scopes WHERE workspace_id = :ws AND project_id = :project AND id=:token', {
|
|
265
|
+
project: projectId,
|
|
266
|
+
token: token.id,
|
|
267
|
+
scopes: JSON.stringify(scopes.filter((scope) => scope !== 'import')),
|
|
268
|
+
})
|
|
269
|
+
}
|
|
270
|
+
t.run(
|
|
271
|
+
'INSERT INTO import_batches (workspace_id, project_id, session_id, batch_key, token_id, payload_hash, result) VALUES (:ws, :project, :session, :batch, :token, :hash, :result)',
|
|
272
|
+
{ ...session, batch: input.batchKey, token: token.id, hash, result: JSON.stringify(result) },
|
|
273
|
+
)
|
|
274
|
+
return result
|
|
275
|
+
})
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function mountImports(v1, { db, boardContext, handle, now }) {
|
|
279
|
+
v1.post(
|
|
280
|
+
'/boards/:bid/import',
|
|
281
|
+
(req, res, next) => {
|
|
282
|
+
if (!req.is('application/json')) return res.status(415).json({ error: { code: 'json_required', message: 'Send JSON.' } })
|
|
283
|
+
next()
|
|
284
|
+
},
|
|
285
|
+
handle(async (req, res) => {
|
|
286
|
+
const ctx = boardContext(req.t, req.project, req.params.bid)
|
|
287
|
+
const result = importBatch({
|
|
288
|
+
db,
|
|
289
|
+
t: req.t,
|
|
290
|
+
projectId: req.project.id,
|
|
291
|
+
board: ctx.board,
|
|
292
|
+
token: req.token,
|
|
293
|
+
tokenHash: req.authTokenHash,
|
|
294
|
+
input: req.body,
|
|
295
|
+
now: now(),
|
|
296
|
+
})
|
|
297
|
+
res.json(result)
|
|
298
|
+
}),
|
|
299
|
+
)
|
|
300
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Invite emails for the hosted server, through Resend like the local
|
|
2
|
+
// notifications (src/notify). Off unless RESEND_API_KEY and
|
|
3
|
+
// SHAPEWALL_EMAIL_FROM are set. The key is read from the environment when a
|
|
4
|
+
// message is sent and never logged; log lines name the outcome only.
|
|
5
|
+
//
|
|
6
|
+
// The message carries the invite link (its token is in the fragment, as on
|
|
7
|
+
// the console). Everything else in it is plain text the server wrote; the
|
|
8
|
+
// workspace name and the inviter's name are escaped for the HTML part.
|
|
9
|
+
|
|
10
|
+
import { RESEND_URL } from '../notify/index.js'
|
|
11
|
+
|
|
12
|
+
const EMAIL_RE = /^[^\s@<>"]{1,64}@[^\s@<>"]{1,190}\.[^\s@<>"]{2,}$/
|
|
13
|
+
const TIMEOUT_MS = 10_000
|
|
14
|
+
|
|
15
|
+
export function cleanEmail(value) {
|
|
16
|
+
const email = typeof value === 'string' ? value.trim() : ''
|
|
17
|
+
return EMAIL_RE.test(email) && email.length <= 254 ? email : null
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const htmlEscape = (value) =>
|
|
21
|
+
String(value).replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char])
|
|
22
|
+
const oneLine = (value) => String(value).replace(/[\r\n]+/g, ' ')
|
|
23
|
+
|
|
24
|
+
export function inviteMessage({ from, to, workspaceName, role, url, inviterName, expiresAt }) {
|
|
25
|
+
const expires = new Date(expiresAt).toUTCString().replace(/ GMT$/, ' UTC')
|
|
26
|
+
// Names are free text that anyone with an account chooses, so they stay out
|
|
27
|
+
// of the subject (where they would read as the sender's own words) and are
|
|
28
|
+
// quoted as names in the body.
|
|
29
|
+
const subject = 'You have an invite to a Shapewall workspace'
|
|
30
|
+
const text = [
|
|
31
|
+
`${oneLine(inviterName)} (a name they chose) invited you to the workspace "${oneLine(workspaceName)}" on Shapewall as ${role === 'admin' ? 'an' : 'a'} ${role}.`,
|
|
32
|
+
'',
|
|
33
|
+
`Open this link to join (it works once and expires ${expires}):`,
|
|
34
|
+
url,
|
|
35
|
+
'',
|
|
36
|
+
'Shapewall uses passkeys, so there is no password to set. If you did not expect this, ignore it.',
|
|
37
|
+
].join('\n')
|
|
38
|
+
const html = [
|
|
39
|
+
`<p>${htmlEscape(oneLine(inviterName))} (a name they chose) invited you to the workspace “${htmlEscape(oneLine(workspaceName))}” on Shapewall as ${role === 'admin' ? 'an' : 'a'} ${htmlEscape(role)}.</p>`,
|
|
40
|
+
`<p><a href="${htmlEscape(url)}">Open the invite</a> (${htmlEscape(new URL(url).host)})</p>`,
|
|
41
|
+
`<p style="color:#666">The link works once and expires ${htmlEscape(expires)}. Shapewall uses passkeys, so there is no password to set. If you did not expect this, ignore it.</p>`,
|
|
42
|
+
].join('')
|
|
43
|
+
return { from, to: [to], subject, text, html }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// createMailer({ env, fetch, log }) -> { configured, sendInvite(details) }.
|
|
47
|
+
// sendInvite resolves { ok, error }; it never throws.
|
|
48
|
+
export function createMailer({ env = process.env, fetch = globalThis.fetch, log = () => {} } = {}) {
|
|
49
|
+
const configured = Boolean(env.RESEND_API_KEY && env.SHAPEWALL_EMAIL_FROM)
|
|
50
|
+
async function sendInvite(details) {
|
|
51
|
+
if (!configured) return { ok: false, error: 'email is not configured' }
|
|
52
|
+
const message = inviteMessage({ ...details, from: env.SHAPEWALL_EMAIL_FROM })
|
|
53
|
+
try {
|
|
54
|
+
const response = await fetch(env.SHAPEWALL_RESEND_URL || RESEND_URL, {
|
|
55
|
+
method: 'POST',
|
|
56
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${env.RESEND_API_KEY}`, 'User-Agent': 'Shapewall-Hosted' },
|
|
57
|
+
body: JSON.stringify(message),
|
|
58
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
59
|
+
redirect: 'error',
|
|
60
|
+
})
|
|
61
|
+
await response.arrayBuffer().catch(() => null)
|
|
62
|
+
if (!response.ok) {
|
|
63
|
+
log(`mail: invite email failed (HTTP ${response.status})`)
|
|
64
|
+
return { ok: false, error: `the email service answered ${response.status}` }
|
|
65
|
+
}
|
|
66
|
+
return { ok: true }
|
|
67
|
+
} catch (error) {
|
|
68
|
+
log(`mail: invite email failed (${error?.name === 'TimeoutError' ? 'timed out' : 'network error'})`)
|
|
69
|
+
return { ok: false, error: 'the email service could not be reached' }
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return { configured, sendInvite }
|
|
73
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Stateless Streamable HTTP: one fresh MCP server per request. No session
|
|
2
|
+
// cookie, shared MCP session, project selector, or ambient account authority.
|
|
3
|
+
import { isIPv6 } from 'node:net'
|
|
4
|
+
import express from 'express'
|
|
5
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'
|
|
6
|
+
import { createRemoteMcpServer } from '../remote/remote-mcp.js'
|
|
7
|
+
import { createRemote } from '../remote/remote.js'
|
|
8
|
+
|
|
9
|
+
export function mountMcpHttp(app, { tokenAuth, origin }) {
|
|
10
|
+
const router = express.Router()
|
|
11
|
+
router.use((req, res, next) => {
|
|
12
|
+
res.setHeader('Cache-Control', 'no-store')
|
|
13
|
+
if (req.headers.cookie)
|
|
14
|
+
return res.status(403).json({ error: { code: 'cookies_refused', message: 'MCP accepts project bearer tokens only; remove Cookie.' } })
|
|
15
|
+
if (req.headers.origin && req.headers.origin !== origin)
|
|
16
|
+
return res.status(403).json({ error: { code: 'bad_origin', message: 'Wrong origin.' } })
|
|
17
|
+
next()
|
|
18
|
+
})
|
|
19
|
+
router.use(tokenAuth)
|
|
20
|
+
router.use(express.json({ limit: '64kb' }))
|
|
21
|
+
router.post('/', async (req, res, next) => {
|
|
22
|
+
// Tokens bind a single project. Even a redundant conflicting selector
|
|
23
|
+
// is refused rather than silently widening or changing the scope.
|
|
24
|
+
const project = req.query.project || req.body?.params?.arguments?.project
|
|
25
|
+
if (project && project !== req.project.id)
|
|
26
|
+
return res.status(403).json({ error: { code: 'wrong_project', message: 'This token belongs to another project.' } })
|
|
27
|
+
if (!req.token.scopes.includes('read'))
|
|
28
|
+
return res.status(403).json({ error: { code: 'missing_scope', message: 'MCP needs the read scope.' } })
|
|
29
|
+
const local = req.socket.localAddress
|
|
30
|
+
const loopback = isIPv6(local) ? `[${local.replace('%', '%25')}]` : local
|
|
31
|
+
const remote = createRemote({
|
|
32
|
+
origin,
|
|
33
|
+
token: String(req.headers.authorization).slice(7),
|
|
34
|
+
fetchImpl: (url, options) => {
|
|
35
|
+
const target = new URL(url)
|
|
36
|
+
// Loop back into the same token API, on the address this request
|
|
37
|
+
// arrived at (the server may listen on ::1, a LAN or a tailnet
|
|
38
|
+
// address only). Never send this token to an operator-configured
|
|
39
|
+
// public hostname or a proxy's redirect.
|
|
40
|
+
return fetch(`http://${loopback}:${req.socket.localPort}${target.pathname}${target.search}`, {
|
|
41
|
+
...options,
|
|
42
|
+
headers: { ...options.headers, Host: new URL(origin).host },
|
|
43
|
+
redirect: 'error',
|
|
44
|
+
})
|
|
45
|
+
},
|
|
46
|
+
})
|
|
47
|
+
let server
|
|
48
|
+
let transport
|
|
49
|
+
try {
|
|
50
|
+
server = await createRemoteMcpServer({ remote })
|
|
51
|
+
transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true })
|
|
52
|
+
await server.connect(transport)
|
|
53
|
+
res.once('close', () => {
|
|
54
|
+
void transport.close()
|
|
55
|
+
void server.close()
|
|
56
|
+
})
|
|
57
|
+
await transport.handleRequest(req, res, req.body)
|
|
58
|
+
} catch (error) {
|
|
59
|
+
await transport?.close()
|
|
60
|
+
await server?.close()
|
|
61
|
+
next(error)
|
|
62
|
+
}
|
|
63
|
+
})
|
|
64
|
+
router.all('/', (req, res) =>
|
|
65
|
+
res
|
|
66
|
+
.status(405)
|
|
67
|
+
.set('Allow', 'POST')
|
|
68
|
+
.json({ error: { code: 'method_not_allowed', message: 'Use stateless Streamable HTTP POST.' } }),
|
|
69
|
+
)
|
|
70
|
+
app.use('/mcp', router)
|
|
71
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Accounts in workspaces (src/hosted/app.js): a user as the API shows
|
|
2
|
+
// them, new workspaces, accepting an invite, what someone handed out going
|
|
3
|
+
// with them when they leave or lose a role, and counting owners.
|
|
4
|
+
|
|
5
|
+
import { avatarUrl } from '../accounts/avatar.js'
|
|
6
|
+
import { AuthError } from './auth.js'
|
|
7
|
+
import { newId } from './crypto.js'
|
|
8
|
+
import { transaction } from './db.js'
|
|
9
|
+
import { HttpError, cleanWorkspaceName } from './http.js'
|
|
10
|
+
import { workspaceSuspended } from './operator.js'
|
|
11
|
+
import { grantsToRevoke } from './permissions.js'
|
|
12
|
+
import { audit, inviteUsable, tenant, workspacesForUser } from './tenancy.js'
|
|
13
|
+
|
|
14
|
+
const WORKSPACES_PER_USER = 10
|
|
15
|
+
|
|
16
|
+
export function createMembership({ db, quotas, iso, auditOf }) {
|
|
17
|
+
function publicUser(user) {
|
|
18
|
+
return { id: user.id, handle: user.handle, displayName: user.display_name, avatarUrl: avatarUrl(db, user.id) }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function createWorkspace(user, name, ip) {
|
|
22
|
+
const owned = workspacesForUser(db, user.id).filter((item) => item.role === 'owner').length
|
|
23
|
+
if (owned >= WORKSPACES_PER_USER) throw new HttpError(409, 'too_many_workspaces', `You own at most ${WORKSPACES_PER_USER} workspaces.`)
|
|
24
|
+
const id = newId('ws')
|
|
25
|
+
const t = tenant(db, id)
|
|
26
|
+
const clean = cleanWorkspaceName(name)
|
|
27
|
+
if (!clean) throw new HttpError(400, 'invalid_name', 'Workspace name: 1 to 80 characters.')
|
|
28
|
+
transaction(db, () => {
|
|
29
|
+
t.run('INSERT INTO workspaces (workspace_id, id, name, created_by, created_at) VALUES (:ws, :ws, :name, :user, :at)', {
|
|
30
|
+
name: clean,
|
|
31
|
+
user: user.id,
|
|
32
|
+
at: iso(),
|
|
33
|
+
})
|
|
34
|
+
t.run("INSERT INTO memberships (workspace_id, user_id, role, created_at) VALUES (:ws, :user, 'owner', :at)", {
|
|
35
|
+
user: user.id,
|
|
36
|
+
at: iso(),
|
|
37
|
+
})
|
|
38
|
+
audit(t, { userId: user.id, action: 'workspace_created', target: id, ip, at: iso() })
|
|
39
|
+
})
|
|
40
|
+
return id
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function acceptInvite(t, invite, userId, ip) {
|
|
44
|
+
return transaction(db, () => {
|
|
45
|
+
if (t.get('SELECT role FROM memberships WHERE workspace_id = :ws AND user_id = :user', { user: userId })) {
|
|
46
|
+
throw new HttpError(409, 'already_member', 'You are already in this workspace.')
|
|
47
|
+
}
|
|
48
|
+
// The creator must still be able to invite to this role, checked in the
|
|
49
|
+
// same transaction as the accept.
|
|
50
|
+
const creator = invite.created_by
|
|
51
|
+
? t.get('SELECT role FROM memberships WHERE workspace_id = :ws AND user_id = :user', { user: invite.created_by })
|
|
52
|
+
: null
|
|
53
|
+
if (!inviteUsable({ ...invite, creator_role: creator?.role }, iso()))
|
|
54
|
+
throw new AuthError(403, 'invalid_invite', 'This invite link is used, expired or revoked.')
|
|
55
|
+
const used = t.run(
|
|
56
|
+
'UPDATE invites SET used_at = :at, used_by = :user WHERE workspace_id = :ws AND id = :id AND used_at IS NULL AND revoked_at IS NULL AND expires_at > :at',
|
|
57
|
+
{ at: iso(), user: userId, id: invite.id },
|
|
58
|
+
)
|
|
59
|
+
if (!used.changes) throw new AuthError(403, 'invalid_invite', 'This invite link is used, expired or revoked.')
|
|
60
|
+
if (workspaceSuspended(t)) throw new AuthError(403, 'workspace_suspended', 'This workspace is suspended by the server operator.')
|
|
61
|
+
const most = quotas.of(t.workspaceId).members
|
|
62
|
+
if (t.get('SELECT COUNT(*) AS n FROM memberships WHERE workspace_id = :ws').n >= most)
|
|
63
|
+
throw new AuthError(409, 'workspace_full', `This workspace has reached its limit of ${most} people. Ask its admin.`)
|
|
64
|
+
t.run('INSERT INTO memberships (workspace_id, user_id, role, created_at) VALUES (:ws, :user, :role, :at)', {
|
|
65
|
+
user: userId,
|
|
66
|
+
role: invite.role,
|
|
67
|
+
at: iso(),
|
|
68
|
+
})
|
|
69
|
+
audit(t, { userId, action: 'invite_accepted', target: invite.id, ip, at: iso(), detail: { role: invite.role } })
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// When someone leaves, is removed or loses admin, what they handed out
|
|
74
|
+
// goes with them: pending invites they can no longer make (all of them
|
|
75
|
+
// below admin, owner invites below owner) and, below admin, their share
|
|
76
|
+
// links. Runs inside the caller's transaction. `role` is the new role, or
|
|
77
|
+
// null when they leave the workspace.
|
|
78
|
+
//
|
|
79
|
+
// API tokens are not revoked by the role rules (CI keeps working when its
|
|
80
|
+
// maker leaves), but whoever removes someone is asked, and `revokeTokens`
|
|
81
|
+
// revokes every live token that person made in this workspace.
|
|
82
|
+
function revokeGrantsOf(req, userId, role, { revokeTokens = null, t = req.t } = {}) {
|
|
83
|
+
const plan = grantsToRevoke(role)
|
|
84
|
+
if (revokeTokens === null) revokeTokens = plan.tokens
|
|
85
|
+
const at = iso()
|
|
86
|
+
const pending =
|
|
87
|
+
'UPDATE invites SET revoked_at = :at WHERE workspace_id = :ws AND created_by = :user AND used_at IS NULL AND revoked_at IS NULL'
|
|
88
|
+
const invites =
|
|
89
|
+
plan.invites === 'none'
|
|
90
|
+
? 0
|
|
91
|
+
: t.run(plan.invites === 'owner' ? `${pending} AND role = 'owner'` : pending, { at, user: userId }).changes
|
|
92
|
+
const shares = !plan.shares
|
|
93
|
+
? 0
|
|
94
|
+
: t.run('UPDATE shares SET revoked_at = :at WHERE workspace_id = :ws AND created_by = :user AND revoked_at IS NULL', {
|
|
95
|
+
at,
|
|
96
|
+
user: userId,
|
|
97
|
+
}).changes
|
|
98
|
+
const tokens = revokeTokens
|
|
99
|
+
? t.run('UPDATE api_tokens SET revoked_at = :at WHERE workspace_id = :ws AND created_by = :user AND revoked_at IS NULL', {
|
|
100
|
+
at,
|
|
101
|
+
user: userId,
|
|
102
|
+
}).changes
|
|
103
|
+
: 0
|
|
104
|
+
if (invites || shares || tokens) auditOf(req, 'member_grants_revoked', userId, { invites, shares, tokens }, t)
|
|
105
|
+
return { invites, shares, tokens }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Roles: admins manage members and viewers (and may make admins); only
|
|
109
|
+
// owners change owners or admins (canManage in permissions.js). A
|
|
110
|
+
// workspace keeps at least one owner.
|
|
111
|
+
const ownerCount = (t) => t.get("SELECT COUNT(*) AS n FROM memberships WHERE workspace_id = :ws AND role = 'owner'").n
|
|
112
|
+
|
|
113
|
+
return { publicUser, createWorkspace, acceptInvite, revokeGrantsOf, ownerCount }
|
|
114
|
+
}
|