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
package/src/github.js
ADDED
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
// GitHub connect for a self-hosted board: make a GitHub issue from a
|
|
2
|
+
// comment, link pull requests to comments (by hand, or found from a
|
|
3
|
+
// "shapewall:<id>" marker in the PR description), and resolve a comment when
|
|
4
|
+
// its pull request merges. `shapewall github sync` polls; the optional
|
|
5
|
+
// webhook (POST /api/github/webhook) does the same as GitHub sends events.
|
|
6
|
+
//
|
|
7
|
+
// The repository comes from the config (`github.repo`) or
|
|
8
|
+
// $SHAPEWALL_GITHUB_REPO. The token comes only from $SHAPEWALL_GITHUB_TOKEN or
|
|
9
|
+
// $GITHUB_TOKEN, else (for github.com only) from the GitHub CLI's
|
|
10
|
+
// `gh auth token`, and the webhook secret only from
|
|
11
|
+
// $SHAPEWALL_GITHUB_WEBHOOK_SECRET: neither is ever written to a file, an
|
|
12
|
+
// export, a log line or an API response. Calls use the REST API with fetch.
|
|
13
|
+
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import { execFileSync } from 'node:child_process'
|
|
16
|
+
import { createHmac, timingSafeEqual } from 'node:crypto'
|
|
17
|
+
import { GITHUB_REPO_RE, ID_RE } from './config.js'
|
|
18
|
+
import { feedbackContext, feedbackItem, fileKind } from './feedback.js'
|
|
19
|
+
import { aroundRect } from './png.js'
|
|
20
|
+
import { DEFAULT_BOARD_URL, runningBoardUrl } from './serve-state.js'
|
|
21
|
+
import { CommentError, getComment, listComments, readJson, recordGithubPull, setGithubIssue, writeJsonAtomic } from './store.js'
|
|
22
|
+
import { absoluteProgram } from './which.js'
|
|
23
|
+
|
|
24
|
+
// Checked in this order; the first one set wins.
|
|
25
|
+
export const TOKEN_VARS = ['SHAPEWALL_GITHUB_TOKEN', 'GITHUB_TOKEN']
|
|
26
|
+
export const WEBHOOK_SECRET_VAR = 'SHAPEWALL_GITHUB_WEBHOOK_SECRET'
|
|
27
|
+
const DEFAULT_API_URL = 'https://api.github.com'
|
|
28
|
+
const REQUEST_TIMEOUT_MS = 20000
|
|
29
|
+
const SYNC_PAGES_MAX = 5
|
|
30
|
+
const SYNC_PAGE_SIZE = 50
|
|
31
|
+
// PRs updated a little before the last sync are read again, for clock skew.
|
|
32
|
+
const SYNC_OVERLAP_MS = 10 * 60 * 1000
|
|
33
|
+
const REFRESH_MAX = 30
|
|
34
|
+
|
|
35
|
+
const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]', '::1'])
|
|
36
|
+
|
|
37
|
+
// The token, for the request that needs it. Never stored or returned.
|
|
38
|
+
// Without a token variable, a signed-in GitHub CLI lends its token, but only
|
|
39
|
+
// for github.com itself (never for another API URL, which could be anyone's).
|
|
40
|
+
// A token from the environment goes to github.com, or to an API URL the
|
|
41
|
+
// person named themselves ($SHAPEWALL_GITHUB_API_URL). An API URL that only a
|
|
42
|
+
// config file names gets no token: a cloned repository's config could
|
|
43
|
+
// otherwise point it at any host.
|
|
44
|
+
function tokenFrom(env, apiUrl = DEFAULT_API_URL, confirmed = true) {
|
|
45
|
+
if (apiUrl !== DEFAULT_API_URL && !confirmed) return null
|
|
46
|
+
for (const name of TOKEN_VARS) {
|
|
47
|
+
const value = typeof env[name] === 'string' ? env[name].trim() : ''
|
|
48
|
+
if (value) return { name, value }
|
|
49
|
+
}
|
|
50
|
+
if (apiUrl !== DEFAULT_API_URL || env.SHAPEWALL_GITHUB_GH === '0') return null
|
|
51
|
+
const value = ghToken(env)
|
|
52
|
+
return value ? { name: GH_TOKEN_SOURCE, value } : null
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// `gh auth token`, cached for a few minutes per PATH and HOME so the server
|
|
56
|
+
// does not start gh on every request. Any error (no gh, signed out) is null.
|
|
57
|
+
export const GH_TOKEN_SOURCE = 'gh auth token'
|
|
58
|
+
const GH_CACHE_MS = 5 * 60 * 1000
|
|
59
|
+
const ghCache = new Map()
|
|
60
|
+
export function ghToken(env = process.env, { run = execFileSync, now = Date.now() } = {}) {
|
|
61
|
+
// gh keeps its login under HOME (or GH_CONFIG_DIR); without either there is none to lend.
|
|
62
|
+
if (!env.PATH || !(env.HOME || env.GH_CONFIG_DIR || env.GH_TOKEN)) return null
|
|
63
|
+
const key = [env.PATH, env.HOME || '', env.GH_CONFIG_DIR || '', env.GH_TOKEN ? 'gh-token' : ''].join('\n')
|
|
64
|
+
const hit = ghCache.get(key)
|
|
65
|
+
if (hit && run === execFileSync && now - hit.at < GH_CACHE_MS) return hit.value
|
|
66
|
+
let value = null
|
|
67
|
+
try {
|
|
68
|
+
// From absolute PATH entries only: a relative one would let a gh in the project run.
|
|
69
|
+
const gh = absoluteProgram('gh', env)
|
|
70
|
+
if (!gh) throw new Error('gh is not on PATH')
|
|
71
|
+
const output = run(gh, ['auth', 'token', '--hostname', 'github.com'], {
|
|
72
|
+
env,
|
|
73
|
+
encoding: 'utf8',
|
|
74
|
+
timeout: 5000,
|
|
75
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
76
|
+
windowsHide: true,
|
|
77
|
+
})
|
|
78
|
+
const line = String(output || '').trim()
|
|
79
|
+
if (/^[\w-]{10,255}$/.test(line)) value = line
|
|
80
|
+
} catch {
|
|
81
|
+
value = null
|
|
82
|
+
}
|
|
83
|
+
if (run === execFileSync) ghCache.set(key, { at: now, value })
|
|
84
|
+
return value
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// The API must be https; plain http only on this machine (a test stub or a
|
|
88
|
+
// local proxy), so the token never crosses a network in the clear.
|
|
89
|
+
function checkApiUrl(value) {
|
|
90
|
+
try {
|
|
91
|
+
const url = new URL(value)
|
|
92
|
+
if (url.protocol === 'https:') return null
|
|
93
|
+
if (url.protocol === 'http:' && LOOPBACK.has(url.hostname)) return null
|
|
94
|
+
return 'the GitHub API URL must be https (http only on 127.0.0.1 or localhost)'
|
|
95
|
+
} catch {
|
|
96
|
+
return 'the GitHub API URL is not a URL'
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// What GitHub connect is set to, without secrets: safe to print and to send
|
|
101
|
+
// to the board.
|
|
102
|
+
export function githubSettings(config, env = process.env) {
|
|
103
|
+
const base = config.github || {}
|
|
104
|
+
const rawRepo = String(env.SHAPEWALL_GITHUB_REPO || base.repo || '').trim()
|
|
105
|
+
const repoError = rawRepo && !GITHUB_REPO_RE.test(rawRepo) ? `"${rawRepo.slice(0, 80)}" is not owner/name` : null
|
|
106
|
+
const repo = rawRepo && !repoError ? rawRepo : null
|
|
107
|
+
const envApiUrl = String(env.SHAPEWALL_GITHUB_API_URL || '').trim()
|
|
108
|
+
const apiUrl = String(envApiUrl || base.apiUrl || DEFAULT_API_URL).replace(/\/+$/, '')
|
|
109
|
+
const apiError = checkApiUrl(apiUrl)
|
|
110
|
+
// Only the environment can confirm an API URL other than github.com.
|
|
111
|
+
const apiConfirmed = apiUrl === DEFAULT_API_URL || Boolean(envApiUrl)
|
|
112
|
+
// Like notifications: the config, else a running `shapewall serve`, else the default port.
|
|
113
|
+
let boardUrl = String(env.SHAPEWALL_BOARD_URL || base.boardUrl || config.boardUrl || runningBoardUrl(config) || DEFAULT_BOARD_URL)
|
|
114
|
+
if (!boardUrl.endsWith('/')) boardUrl += '/'
|
|
115
|
+
const token = tokenFrom(env, apiUrl, apiConfirmed)
|
|
116
|
+
const board = base.board && config.boards.some((item) => item.id === base.board) ? base.board : config.boards[0]?.id || null
|
|
117
|
+
return {
|
|
118
|
+
repo,
|
|
119
|
+
repoError,
|
|
120
|
+
apiUrl,
|
|
121
|
+
apiError,
|
|
122
|
+
apiConfirmed,
|
|
123
|
+
boardUrl,
|
|
124
|
+
labels: Array.isArray(base.labels) ? base.labels : [],
|
|
125
|
+
board,
|
|
126
|
+
tokenVar: token?.name || null,
|
|
127
|
+
webhook: Boolean(String(env[WEBHOOK_SECRET_VAR] || '').trim()),
|
|
128
|
+
// Issues, links and sync need a repo and a token; the webhook needs a repo and the secret.
|
|
129
|
+
ready: Boolean(repo && token && !apiError),
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function notReady(settings) {
|
|
134
|
+
if (settings.repoError) return `GitHub repo ${settings.repoError}.`
|
|
135
|
+
if (!settings.repo) return 'GitHub is not set up: add "github": { "repo": "owner/name" } to the config.'
|
|
136
|
+
if (!settings.apiConfirmed && !settings.apiError)
|
|
137
|
+
return `The config sets github.apiUrl to ${settings.apiUrl}. To send your GitHub token there, set SHAPEWALL_GITHUB_API_URL to the same URL in your environment.`
|
|
138
|
+
if (!settings.tokenVar) return `No GitHub token: set ${TOKEN_VARS.join(' or ')} in the environment (or sign in with "gh auth login").`
|
|
139
|
+
return `GitHub API URL: ${settings.apiError}.`
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// One REST call. Errors carry GitHub's message, never the token.
|
|
143
|
+
async function githubRequest(settings, env, method, route, { body, fetchImpl = globalThis.fetch } = {}) {
|
|
144
|
+
if (!settings.ready) throw new CommentError(400, 'github_not_configured', notReady(settings))
|
|
145
|
+
const token = tokenFrom(env, settings.apiUrl, settings.apiConfirmed)
|
|
146
|
+
if (!token) throw new CommentError(400, 'github_not_configured', notReady({ ...settings, tokenVar: null }))
|
|
147
|
+
let response
|
|
148
|
+
try {
|
|
149
|
+
response = await fetchImpl(`${settings.apiUrl}${route}`, {
|
|
150
|
+
method,
|
|
151
|
+
headers: {
|
|
152
|
+
Accept: 'application/vnd.github+json',
|
|
153
|
+
Authorization: `Bearer ${token.value}`,
|
|
154
|
+
'X-GitHub-Api-Version': '2022-11-28',
|
|
155
|
+
'User-Agent': 'shapewall',
|
|
156
|
+
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
|
157
|
+
},
|
|
158
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
159
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
160
|
+
redirect: 'error',
|
|
161
|
+
})
|
|
162
|
+
} catch (error) {
|
|
163
|
+
throw new CommentError(502, 'github_unreachable', `Could not reach GitHub at ${settings.apiUrl} (${error.cause?.code || error.name}).`)
|
|
164
|
+
}
|
|
165
|
+
let data = null
|
|
166
|
+
try {
|
|
167
|
+
data = await response.json()
|
|
168
|
+
} catch {
|
|
169
|
+
data = null
|
|
170
|
+
}
|
|
171
|
+
if (response.ok) return data
|
|
172
|
+
const said = typeof data?.message === 'string' ? data.message.slice(0, 200) : `HTTP ${response.status}`
|
|
173
|
+
if (response.status === 401) {
|
|
174
|
+
throw new CommentError(502, 'github_unauthorized', `GitHub refused the token in ${settings.tokenVar} (${said}).`)
|
|
175
|
+
}
|
|
176
|
+
if (response.status === 404) throw new CommentError(404, 'github_not_found', `GitHub: not found in ${settings.repo} (${said}).`)
|
|
177
|
+
throw new CommentError(502, 'github_error', `GitHub answered ${response.status}: ${said}`)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ---- Issue text -------------------------------------------------------------------
|
|
181
|
+
|
|
182
|
+
// GitHub turns "@name" into a mention that notifies that account; reviewers'
|
|
183
|
+
// @mentions are Shapewall handles, so they are kept from pinging strangers.
|
|
184
|
+
function quiet(text) {
|
|
185
|
+
return String(text || '').replace(/@(?=[A-Za-z0-9])/g, '@\u200b')
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Inline code that survives backticks inside the value.
|
|
189
|
+
function code(value) {
|
|
190
|
+
const text = String(value).replace(/\s+/g, ' ')
|
|
191
|
+
const longest = Math.max(0, ...(text.match(/`+/g) || []).map((run) => run.length))
|
|
192
|
+
const fence = '`'.repeat(longest + 1)
|
|
193
|
+
const pad = text.startsWith('`') || text.endsWith('`') ? ' ' : ''
|
|
194
|
+
return `${fence}${pad}${text}${pad}${fence}`
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// A link to the comment on the board: it opens with the comment selected.
|
|
198
|
+
export function boardLink(settings, boardId, commentId) {
|
|
199
|
+
const url = new URL(settings.boardUrl)
|
|
200
|
+
url.searchParams.set('board', boardId)
|
|
201
|
+
url.searchParams.set('filter', 'all')
|
|
202
|
+
url.searchParams.set('c', String(commentId))
|
|
203
|
+
return url.toString()
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function screenshotLink(settings, boardId, item) {
|
|
207
|
+
if (!item.files.screenshot) return null
|
|
208
|
+
// The capture the comment was made on can be an archived version.
|
|
209
|
+
const kind = fileKind(item, item.files.screenshot)
|
|
210
|
+
return new URL(`api/boards/${boardId}/${kind}/${path.basename(item.files.screenshot)}`, settings.boardUrl).toString()
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// The issue made from one comment (the feedback item shape).
|
|
214
|
+
export function issueContent(settings, boardId, item) {
|
|
215
|
+
const where = item.page ? item.page.title : `Variant: ${item.variant?.title || 'removed'}`
|
|
216
|
+
const first = item.body.split('\n')[0].replace(/\s+/g, ' ').trim()
|
|
217
|
+
const title = `${where}: ${first.length > 90 ? `${first.slice(0, 89)}...` : first}`.slice(0, 200)
|
|
218
|
+
const crop = aroundRect(item.position, item.viewport)
|
|
219
|
+
const shot = screenshotLink(settings, boardId, item)
|
|
220
|
+
const lines = [
|
|
221
|
+
...item.body.split('\n').map((line) => `> ${quiet(line)}`),
|
|
222
|
+
'',
|
|
223
|
+
`-- ${quiet(item.author)}, on Shapewall comment #${item.id}`,
|
|
224
|
+
'',
|
|
225
|
+
item.page
|
|
226
|
+
? `**Page:** [${item.page.title}](${item.page.url}) (${code(item.page.path)}), ${item.viewport.name} ${item.viewport.width}x${item.viewport.height}`
|
|
227
|
+
: `**Variant:** ${item.variant?.title || 'removed'} (${item.viewport.name} ${item.viewport.width}x${item.viewport.height})`,
|
|
228
|
+
]
|
|
229
|
+
if (item.element) lines.push(`**Element:** ${code(item.element.selector)}${item.element.text ? ` ("${quiet(item.element.text)}")` : ''}`)
|
|
230
|
+
lines.push(`**Pin:** ${item.position.x}, ${item.position.y} px (${item.position.xPercent}% / ${item.position.yPercent}%)`)
|
|
231
|
+
lines.push(
|
|
232
|
+
`**Screenshot:** ${shot ? `[${item.viewport.name} capture](${shot})` : 'not captured'}; the part around the pin is x ${crop.x}-${crop.x + crop.width}, y ${crop.y}-${crop.y + crop.height}${item.captureVersion ? ` (capture ${item.captureVersion})` : ''}`,
|
|
233
|
+
)
|
|
234
|
+
lines.push(`**On the board:** [comment #${item.id}](${boardLink(settings, boardId, item.id)})`)
|
|
235
|
+
lines.push(
|
|
236
|
+
'',
|
|
237
|
+
`To link a fix, put ${code(`shapewall:${boardId}/${item.id}`)} or ${code(`Fixes shapewall#${item.id}`)} in the pull request description; when it merges, the comment is resolved.`,
|
|
238
|
+
'',
|
|
239
|
+
`<!-- shapewall:${boardId}/${item.id} -->`,
|
|
240
|
+
)
|
|
241
|
+
return { title, body: lines.join('\n') }
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// ---- Issues -------------------------------------------------------------------------
|
|
245
|
+
|
|
246
|
+
// Two clicks on the button make one issue.
|
|
247
|
+
const pendingIssues = new Map()
|
|
248
|
+
|
|
249
|
+
// Creates the GitHub issue for a comment, or returns the one it already has.
|
|
250
|
+
// Returns { comment, issue, created }.
|
|
251
|
+
export async function createIssue(config, { boardId = null, commentId, env = process.env, fetchImpl, now = new Date() }) {
|
|
252
|
+
const settings = githubSettings(config, env)
|
|
253
|
+
const board = boardFor(config, boardId)
|
|
254
|
+
const existing = getComment(config, board.id, commentId)
|
|
255
|
+
if (existing.github.issue) return { comment: existing, issue: existing.github.issue, created: false }
|
|
256
|
+
if (!settings.ready) throw new CommentError(400, 'github_not_configured', notReady(settings))
|
|
257
|
+
const key = `${board.id}/${existing.id}`
|
|
258
|
+
if (pendingIssues.has(key)) return pendingIssues.get(key)
|
|
259
|
+
const run = (async () => {
|
|
260
|
+
const item = feedbackItem(feedbackContext(config, board), existing)
|
|
261
|
+
const { title, body } = issueContent(settings, board.id, item)
|
|
262
|
+
const created = await githubRequest(settings, env, 'POST', `/repos/${settings.repo}/issues`, {
|
|
263
|
+
body: { title, body, ...(settings.labels.length ? { labels: settings.labels } : {}) },
|
|
264
|
+
fetchImpl,
|
|
265
|
+
})
|
|
266
|
+
if (!Number.isSafeInteger(created?.number) || typeof created?.html_url !== 'string') {
|
|
267
|
+
throw new CommentError(502, 'github_error', 'GitHub did not return the new issue.')
|
|
268
|
+
}
|
|
269
|
+
const issue = { number: created.number, url: created.html_url, title: created.title || title, createdAt: now.toISOString() }
|
|
270
|
+
const comment = await setGithubIssue(config, board.id, existing.id, issue, { now })
|
|
271
|
+
return { comment, issue: comment.github.issue, created: true }
|
|
272
|
+
})()
|
|
273
|
+
pendingIssues.set(key, run)
|
|
274
|
+
try {
|
|
275
|
+
return await run
|
|
276
|
+
} finally {
|
|
277
|
+
pendingIssues.delete(key)
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// ---- Pull requests the starter agent opens -------------------------------------------
|
|
282
|
+
|
|
283
|
+
// Opens a pull request from a branch already pushed (the starter agent's).
|
|
284
|
+
// Returns { number, url }. Comment text in the title and body is quieted, so
|
|
285
|
+
// it cannot ping GitHub accounts.
|
|
286
|
+
export async function openPullRequest(config, { head, base, title, body, env = process.env, fetchImpl }) {
|
|
287
|
+
const settings = githubSettings(config, env)
|
|
288
|
+
const created = await githubRequest(settings, env, 'POST', `/repos/${settings.repo}/pulls`, {
|
|
289
|
+
body: { head, base, title: quiet(title).slice(0, 200), body: quiet(body), draft: false },
|
|
290
|
+
fetchImpl,
|
|
291
|
+
})
|
|
292
|
+
if (!Number.isSafeInteger(created?.number) || typeof created?.html_url !== 'string') {
|
|
293
|
+
throw new CommentError(502, 'github_error', 'GitHub did not return the new pull request.')
|
|
294
|
+
}
|
|
295
|
+
return { number: created.number, url: created.html_url }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function boardFor(config, boardId) {
|
|
299
|
+
if (!boardId) return config.boards[0]
|
|
300
|
+
const board = config.boards.find((item) => item.id === boardId)
|
|
301
|
+
if (!board) throw new CommentError(404, 'unknown_board', `No board "${boardId}".`)
|
|
302
|
+
return board
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ---- Pull requests ------------------------------------------------------------------
|
|
306
|
+
|
|
307
|
+
// "12", "#12" or a pull request URL of the configured repo -> 12.
|
|
308
|
+
export function parsePullRef(value, repo) {
|
|
309
|
+
const text = String(value ?? '').trim()
|
|
310
|
+
let match = /^#?([1-9][0-9]{0,9})$/.exec(text)
|
|
311
|
+
if (match) return Number(match[1])
|
|
312
|
+
match = /^https:\/\/[^/]+\/([^/]+\/[^/]+)\/pull\/([1-9][0-9]{0,9})(?:[/?#].*)?$/.exec(text)
|
|
313
|
+
if (match) {
|
|
314
|
+
if (repo && match[1].toLowerCase() !== repo.toLowerCase()) {
|
|
315
|
+
throw new CommentError(400, 'other_repo', `That pull request is in ${match[1]}, not ${repo}.`)
|
|
316
|
+
}
|
|
317
|
+
return Number(match[2])
|
|
318
|
+
}
|
|
319
|
+
throw new CommentError(400, 'invalid_pull', 'Give a pull request number (12 or #12) or its URL.')
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// A pull request as GitHub's API (or a webhook) describes it -> what a comment keeps.
|
|
323
|
+
export function pullFromApi(pr) {
|
|
324
|
+
return {
|
|
325
|
+
number: pr.number,
|
|
326
|
+
url: pr.html_url,
|
|
327
|
+
title: typeof pr.title === 'string' ? pr.title : '',
|
|
328
|
+
state: pr.merged_at || pr.merged === true ? 'merged' : pr.state === 'closed' ? 'closed' : 'open',
|
|
329
|
+
mergedAt: typeof pr.merged_at === 'string' ? pr.merged_at : null,
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const MARKER_RE = /\bshapewall(?::|#)(?:([a-z0-9][a-z0-9-]{0,63})\/)?([1-9][0-9]{0,9})\b/gi
|
|
334
|
+
const CLOSES_ISSUE_RE = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s*:?\s+#([1-9][0-9]{0,9})\b/gi
|
|
335
|
+
|
|
336
|
+
// Comments a pull request names in its title or description:
|
|
337
|
+
// "shapewall:12", "shapewall:<board>/12", "Fixes shapewall#12" (bare ids
|
|
338
|
+
// are on `defaultBoard`), plus issue numbers it closes ("Fixes #45").
|
|
339
|
+
export function refsInText(text, defaultBoard) {
|
|
340
|
+
const value = String(text || '')
|
|
341
|
+
const comments = []
|
|
342
|
+
for (const match of value.matchAll(MARKER_RE)) {
|
|
343
|
+
comments.push({ boardId: match[1] ? match[1].toLowerCase() : defaultBoard, commentId: Number(match[2]) })
|
|
344
|
+
}
|
|
345
|
+
const issues = [...value.matchAll(CLOSES_ISSUE_RE)].map((match) => Number(match[1]))
|
|
346
|
+
return { comments, issues }
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// Which comments link to which issue and pull request numbers, on every board.
|
|
350
|
+
function linkIndex(config) {
|
|
351
|
+
const issues = new Map()
|
|
352
|
+
const pulls = new Map()
|
|
353
|
+
const add = (map, key, value) => map.set(key, [...(map.get(key) || []), value])
|
|
354
|
+
for (const board of config.boards) {
|
|
355
|
+
for (const comment of listComments(config, board.id)) {
|
|
356
|
+
if (comment.github.issue) add(issues, comment.github.issue.number, { boardId: board.id, commentId: comment.id })
|
|
357
|
+
for (const pull of comment.github.pulls) add(pulls, pull.number, { boardId: board.id, commentId: comment.id, state: pull.state })
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return { issues, pulls }
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Links (or updates) one pull request on every comment it concerns. Returns
|
|
364
|
+
// { linked: [...], merged: [...], skipped: [...] } with { board, comment, pull, state }.
|
|
365
|
+
async function applyPull(config, settings, pr, index, now) {
|
|
366
|
+
const pull = pullFromApi(pr)
|
|
367
|
+
const refs = refsInText(`${pr.title || ''}\n${pr.body || ''}`, settings.board)
|
|
368
|
+
const targets = new Map()
|
|
369
|
+
const want = (boardId, commentId, via) => {
|
|
370
|
+
const key = `${boardId}/${commentId}`
|
|
371
|
+
if (!targets.has(key)) targets.set(key, { boardId, commentId, via })
|
|
372
|
+
}
|
|
373
|
+
for (const link of index.pulls.get(pull.number) || []) want(link.boardId, link.commentId, 'manual')
|
|
374
|
+
for (const ref of refs.comments) want(ref.boardId, ref.commentId, 'body')
|
|
375
|
+
for (const number of refs.issues) for (const link of index.issues.get(number) || []) want(link.boardId, link.commentId, 'issue')
|
|
376
|
+
const result = { linked: [], merged: [], skipped: [] }
|
|
377
|
+
for (const target of targets.values()) {
|
|
378
|
+
const entry = { board: target.boardId, comment: target.commentId, pull: pull.number, state: pull.state }
|
|
379
|
+
if (!ID_RE.test(target.boardId) || !config.boards.some((board) => board.id === target.boardId)) {
|
|
380
|
+
result.skipped.push({ ...entry, reason: 'no such board' })
|
|
381
|
+
continue
|
|
382
|
+
}
|
|
383
|
+
try {
|
|
384
|
+
const { changed, merged } = await recordGithubPull(config, target.boardId, target.commentId, pull, { via: target.via, now })
|
|
385
|
+
if (changed) result.linked.push(entry)
|
|
386
|
+
if (merged) result.merged.push(entry)
|
|
387
|
+
} catch (error) {
|
|
388
|
+
if (!(error instanceof CommentError)) throw error
|
|
389
|
+
result.skipped.push({ ...entry, reason: error.code === 'unknown_comment' ? 'no such comment' : error.message })
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return result
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function mergeResults(into, from) {
|
|
396
|
+
into.linked.push(...from.linked)
|
|
397
|
+
into.merged.push(...from.merged)
|
|
398
|
+
into.skipped.push(...from.skipped)
|
|
399
|
+
return into
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// Links a pull request to a comment by hand (`shapewall github link`). Reads
|
|
403
|
+
// the PR from GitHub, so a merged one resolves the comment right away.
|
|
404
|
+
// Returns { comment, pull, merged }.
|
|
405
|
+
export async function linkPull(config, { boardId = null, commentId, pr, env = process.env, fetchImpl, now = new Date() }) {
|
|
406
|
+
const settings = githubSettings(config, env)
|
|
407
|
+
const board = boardFor(config, boardId)
|
|
408
|
+
getComment(config, board.id, commentId)
|
|
409
|
+
if (!settings.ready) throw new CommentError(400, 'github_not_configured', notReady(settings))
|
|
410
|
+
const number = parsePullRef(pr, settings.repo)
|
|
411
|
+
const data = await githubRequest(settings, env, 'GET', `/repos/${settings.repo}/pulls/${number}`, { fetchImpl })
|
|
412
|
+
const pull = pullFromApi(data)
|
|
413
|
+
const { comment, merged } = await recordGithubPull(config, board.id, commentId, pull, { via: 'manual', now })
|
|
414
|
+
return { comment, pull: comment.github.pulls.find((item) => item.number === number), merged }
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// ---- Sync (polling) -----------------------------------------------------------------
|
|
418
|
+
|
|
419
|
+
export function syncStateFile(config) {
|
|
420
|
+
return path.join(config.outputDir, 'github-sync.json')
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// Reads the repo's pull requests updated since the last sync (newest first,
|
|
424
|
+
// a few pages at most), links the ones that name a comment, and refreshes
|
|
425
|
+
// linked ones that were not in the list. Returns { repo, scanned, linked,
|
|
426
|
+
// merged, skipped, since }.
|
|
427
|
+
export async function syncGithub(config, { env = process.env, fetchImpl, now = new Date(), log = () => {} } = {}) {
|
|
428
|
+
const settings = githubSettings(config, env)
|
|
429
|
+
if (!settings.ready) throw new CommentError(400, 'github_not_configured', notReady(settings))
|
|
430
|
+
const stateFile = syncStateFile(config)
|
|
431
|
+
const state = readJson(stateFile)
|
|
432
|
+
const since = state?.repo === settings.repo && typeof state.lastSyncAt === 'string' ? state.lastSyncAt : null
|
|
433
|
+
const cutoff = since ? Date.parse(since) - SYNC_OVERLAP_MS : null
|
|
434
|
+
const index = linkIndex(config)
|
|
435
|
+
const result = { repo: settings.repo, since, scanned: 0, linked: [], merged: [], skipped: [] }
|
|
436
|
+
const seen = new Set()
|
|
437
|
+
let done = false
|
|
438
|
+
for (let page = 1; page <= SYNC_PAGES_MAX && !done; page += 1) {
|
|
439
|
+
const list = await githubRequest(
|
|
440
|
+
settings,
|
|
441
|
+
env,
|
|
442
|
+
'GET',
|
|
443
|
+
`/repos/${settings.repo}/pulls?state=all&sort=updated&direction=desc&per_page=${SYNC_PAGE_SIZE}&page=${page}`,
|
|
444
|
+
{ fetchImpl },
|
|
445
|
+
)
|
|
446
|
+
if (!Array.isArray(list)) throw new CommentError(502, 'github_error', 'GitHub did not return a list of pull requests.')
|
|
447
|
+
for (const pr of list) {
|
|
448
|
+
if (cutoff !== null && Date.parse(pr.updated_at) < cutoff) {
|
|
449
|
+
done = true
|
|
450
|
+
break
|
|
451
|
+
}
|
|
452
|
+
if (!Number.isSafeInteger(pr?.number) || seen.has(pr.number)) continue
|
|
453
|
+
seen.add(pr.number)
|
|
454
|
+
result.scanned += 1
|
|
455
|
+
mergeResults(result, await applyPull(config, settings, pr, index, now))
|
|
456
|
+
}
|
|
457
|
+
if (list.length < SYNC_PAGE_SIZE) done = true
|
|
458
|
+
}
|
|
459
|
+
// Linked pull requests still open that the list did not reach.
|
|
460
|
+
const stale = [...index.pulls.entries()].filter(([number, links]) => !seen.has(number) && links.some((link) => link.state === 'open'))
|
|
461
|
+
for (const [number] of stale.slice(0, REFRESH_MAX)) {
|
|
462
|
+
try {
|
|
463
|
+
const pr = await githubRequest(settings, env, 'GET', `/repos/${settings.repo}/pulls/${number}`, { fetchImpl })
|
|
464
|
+
result.scanned += 1
|
|
465
|
+
mergeResults(result, await applyPull(config, settings, pr, index, now))
|
|
466
|
+
} catch (error) {
|
|
467
|
+
if (!(error instanceof CommentError) || error.code !== 'github_not_found') throw error
|
|
468
|
+
log(`pull request #${number} is gone from ${settings.repo}`)
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
writeJsonAtomic(stateFile, { repo: settings.repo, lastSyncAt: now.toISOString() })
|
|
472
|
+
return result
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// ---- Webhook ------------------------------------------------------------------------
|
|
476
|
+
|
|
477
|
+
// X-Hub-Signature-256 is "sha256=" + HMAC-SHA256(secret, raw body), hex.
|
|
478
|
+
export function verifySignature(secret, raw, header) {
|
|
479
|
+
if (!secret || typeof header !== 'string' || !header.startsWith('sha256=')) return false
|
|
480
|
+
const expected = Buffer.from(`sha256=${createHmac('sha256', secret).update(raw).digest('hex')}`)
|
|
481
|
+
const given = Buffer.from(header)
|
|
482
|
+
return given.length === expected.length && timingSafeEqual(given, expected)
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// Handles one verified delivery. Returns { status, body } for the response.
|
|
486
|
+
// Only pull_request events of the configured repo change anything; a
|
|
487
|
+
// webhook needs no token, the event carries the pull request.
|
|
488
|
+
export async function handleWebhook(config, { event, payload, env = process.env, now = new Date() }) {
|
|
489
|
+
const settings = githubSettings(config, env)
|
|
490
|
+
if (event === 'ping') return { status: 200, body: { ok: true, pong: true } }
|
|
491
|
+
if (event !== 'pull_request') return { status: 202, body: { ok: true, ignored: `event ${String(event).slice(0, 40)}` } }
|
|
492
|
+
const fullName = String(payload?.repository?.full_name || '')
|
|
493
|
+
if (!settings.repo || fullName.toLowerCase() !== settings.repo.toLowerCase()) {
|
|
494
|
+
return { status: 202, body: { ok: true, ignored: 'another repository' } }
|
|
495
|
+
}
|
|
496
|
+
const pr = payload?.pull_request
|
|
497
|
+
if (!pr || !Number.isSafeInteger(pr.number) || typeof pr.html_url !== 'string') {
|
|
498
|
+
return { status: 400, body: { error: { code: 'invalid_payload', message: 'No pull request in the event.' } } }
|
|
499
|
+
}
|
|
500
|
+
const result = await applyPull(config, settings, pr, linkIndex(config), now)
|
|
501
|
+
return { status: 200, body: { ok: true, action: payload.action || null, pull: pr.number, ...result } }
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// ---- Doctor -------------------------------------------------------------------------
|
|
505
|
+
|
|
506
|
+
// The `shapewall doctor` line for GitHub. With a repo and a token it asks
|
|
507
|
+
// GitHub whether the token can see the repo.
|
|
508
|
+
export async function checkGithub(config, { env = process.env, fetchImpl, network = true } = {}) {
|
|
509
|
+
if (!config) return { name: 'github', status: 'skip', message: 'No valid config, so no GitHub settings to check' }
|
|
510
|
+
const settings = githubSettings(config, env)
|
|
511
|
+
const webhook = settings.webhook ? 'webhook secret set' : `no webhook secret (${WEBHOOK_SECRET_VAR}), use "shapewall github sync"`
|
|
512
|
+
if (settings.repoError) return { name: 'github', status: 'fail', message: `GitHub repo ${settings.repoError}`, fix: 'Use "owner/name".' }
|
|
513
|
+
if (!settings.repo) return { name: 'github', status: 'skip', message: 'GitHub connect is off (optional; see docs/github.md)' }
|
|
514
|
+
if (settings.apiError) return { name: 'github', status: 'fail', message: `GitHub: ${settings.apiError}`, fix: 'Fix github.apiUrl.' }
|
|
515
|
+
if (!settings.apiConfirmed) {
|
|
516
|
+
return {
|
|
517
|
+
name: 'github',
|
|
518
|
+
status: 'fail',
|
|
519
|
+
message: `GitHub: the config names the API URL ${settings.apiUrl}, which gets no token until you confirm it`,
|
|
520
|
+
fix: `Set SHAPEWALL_GITHUB_API_URL=${settings.apiUrl} in your environment.`,
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
if (!settings.tokenVar) {
|
|
524
|
+
return {
|
|
525
|
+
name: 'github',
|
|
526
|
+
status: 'warn',
|
|
527
|
+
message: `GitHub repo ${settings.repo}, but no token: issues, links and sync are off`,
|
|
528
|
+
fix: `Set ${TOKEN_VARS.join(' or ')} (a token that can read pull requests and write issues), or sign in with "gh auth login".`,
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
const prefix = `GitHub ${settings.repo}, token from ${settings.tokenVar}, ${webhook}`
|
|
532
|
+
if (!network) return { name: 'github', status: 'ok', message: `${prefix} (not checked)` }
|
|
533
|
+
try {
|
|
534
|
+
const repo = await githubRequest(settings, env, 'GET', `/repos/${settings.repo}`, { fetchImpl })
|
|
535
|
+
if (repo?.has_issues === false) {
|
|
536
|
+
return {
|
|
537
|
+
name: 'github',
|
|
538
|
+
status: 'warn',
|
|
539
|
+
message: `${prefix}; issues are turned off in the repo`,
|
|
540
|
+
fix: 'Turn on Issues in the repo settings.',
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return { name: 'github', status: 'ok', message: `${prefix}; the token can see the repo` }
|
|
544
|
+
} catch (error) {
|
|
545
|
+
// A token GitHub rejects (401 Bad credentials) breaks every GitHub action: a FAIL, not a warning.
|
|
546
|
+
if (error.code === 'github_unauthorized') {
|
|
547
|
+
return { name: 'github', status: 'fail', message: `${prefix}; ${error.message}`, fix: `Replace the token in ${settings.tokenVar}.` }
|
|
548
|
+
}
|
|
549
|
+
return { name: 'github', status: 'warn', message: `${prefix}; ${error.message}`, fix: 'Check the token and its access to the repo.' }
|
|
550
|
+
}
|
|
551
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Functional Source License, Version 1.1, ALv2 Future License
|
|
2
|
+
|
|
3
|
+
## Abbreviation
|
|
4
|
+
|
|
5
|
+
FSL-1.1-ALv2
|
|
6
|
+
|
|
7
|
+
## Notice
|
|
8
|
+
|
|
9
|
+
Copyright 2026 Dan Baruch
|
|
10
|
+
|
|
11
|
+
## Terms and Conditions
|
|
12
|
+
|
|
13
|
+
### Licensor ("We")
|
|
14
|
+
|
|
15
|
+
The party offering the Software under these Terms and Conditions.
|
|
16
|
+
|
|
17
|
+
### The Software
|
|
18
|
+
|
|
19
|
+
The "Software" is each version of the software that we make available under
|
|
20
|
+
these Terms and Conditions, as indicated by our inclusion of these Terms and
|
|
21
|
+
Conditions with the Software.
|
|
22
|
+
|
|
23
|
+
### License Grant
|
|
24
|
+
|
|
25
|
+
Subject to your compliance with this License Grant and the Patents,
|
|
26
|
+
Redistribution and Trademark clauses below, we hereby grant you the right to
|
|
27
|
+
use, copy, modify, create derivative works, publicly perform, publicly display
|
|
28
|
+
and redistribute the Software for any Permitted Purpose identified below.
|
|
29
|
+
|
|
30
|
+
### Permitted Purpose
|
|
31
|
+
|
|
32
|
+
A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
|
|
33
|
+
means making the Software available to others in a commercial product or
|
|
34
|
+
service that:
|
|
35
|
+
|
|
36
|
+
1. substitutes for the Software;
|
|
37
|
+
|
|
38
|
+
2. substitutes for any other product or service we offer using the Software
|
|
39
|
+
that exists as of the date we make the Software available; or
|
|
40
|
+
|
|
41
|
+
3. offers the same or substantially similar functionality as the Software.
|
|
42
|
+
|
|
43
|
+
Permitted Purposes specifically include using the Software:
|
|
44
|
+
|
|
45
|
+
1. for your internal use and access;
|
|
46
|
+
|
|
47
|
+
2. for non-commercial education;
|
|
48
|
+
|
|
49
|
+
3. for non-commercial research; and
|
|
50
|
+
|
|
51
|
+
4. in connection with professional services that you provide to a licensee
|
|
52
|
+
using the Software in accordance with these Terms and Conditions.
|
|
53
|
+
|
|
54
|
+
### Patents
|
|
55
|
+
|
|
56
|
+
To the extent your use for a Permitted Purpose would necessarily infringe our
|
|
57
|
+
patents, the license grant above includes a license under our patents. If you
|
|
58
|
+
make a claim against any party that the Software infringes or contributes to
|
|
59
|
+
the infringement of any patent, then your patent license to the Software ends
|
|
60
|
+
immediately.
|
|
61
|
+
|
|
62
|
+
### Redistribution
|
|
63
|
+
|
|
64
|
+
The Terms and Conditions apply to all copies, modifications and derivatives of
|
|
65
|
+
the Software.
|
|
66
|
+
|
|
67
|
+
If you redistribute any copies, modifications or derivatives of the Software,
|
|
68
|
+
you must include a copy of or a link to these Terms and Conditions and not
|
|
69
|
+
remove any copyright notices provided in or with the Software.
|
|
70
|
+
|
|
71
|
+
### Disclaimer
|
|
72
|
+
|
|
73
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
|
|
74
|
+
IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
|
|
75
|
+
PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
|
|
76
|
+
|
|
77
|
+
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
|
|
78
|
+
SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
|
|
79
|
+
EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
|
|
80
|
+
|
|
81
|
+
### Trademarks
|
|
82
|
+
|
|
83
|
+
Except for displaying the License Details and identifying us as the origin of
|
|
84
|
+
the Software, you have no right under these Terms and Conditions to use our
|
|
85
|
+
trademarks, trade names, service marks or product names.
|
|
86
|
+
|
|
87
|
+
## Grant of Future License
|
|
88
|
+
|
|
89
|
+
We hereby irrevocably grant you an additional license to use the Software under
|
|
90
|
+
the Apache License, Version 2.0 that is effective on the second anniversary of
|
|
91
|
+
the date we make the Software available. On or after that date, you may use the
|
|
92
|
+
Software under the Apache License, Version 2.0, in which case the following
|
|
93
|
+
will apply:
|
|
94
|
+
|
|
95
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
96
|
+
this file except in compliance with the License.
|
|
97
|
+
|
|
98
|
+
You may obtain a copy of the License at
|
|
99
|
+
|
|
100
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
101
|
+
|
|
102
|
+
Unless required by applicable law or agreed to in writing, software distributed
|
|
103
|
+
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
|
104
|
+
CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
|
105
|
+
specific language governing permissions and limitations under the License.
|