Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 0 additions & 12 deletions .dockerignore

This file was deleted.

17 changes: 11 additions & 6 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
# The ID of your GitHub App
# Existing GitHub App registration credentials. Never put these in a repository.
APP_ID=
WEBHOOK_SECRET=development
# PEM text (quoted multiline in .env), escaped-newline PEM, or base64-encoded PEM.
PRIVATE_KEY=
# At least 32 bytes. Generate a random secret; use the same value in GitHub settings.
WEBHOOK_SECRET=

# Use `trace` to get verbose logging or `info` to show less
LOG_LEVEL=debug
# Optional: disabled when blank. No Stately user/project key is needed.
# Production target: https://stately.ai/registry/api/github/documentation
STATELY_DOCUMENTATION_WEBHOOK_URL=

# Go to https://smee.io/new set this to the URL that you are redirected to.
WEBHOOK_PROXY_URL=
# Standalone HTTP listener; terminate TLS at a trusted reverse proxy.
HOST=127.0.0.1
PORT=3000
12 changes: 12 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
open-pull-requests-limit: 5
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
open-pull-requests-limit: 5
25 changes: 25 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: CodeQL
on:
pull_request:
push:
branches: [main]
schedule:
- cron: "41 7 * * 1"
permissions:
contents: read
jobs:
analyze:
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
security-events: write
steps:
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
with:
persist-credentials: false
- uses: github/codeql-action/init@5895b2c9be147bc7f1c75ce72c5cb577febb1907 # v4
with:
languages: javascript-typescript
build-mode: none
- uses: github/codeql-action/analyze@5895b2c9be147bc7f1c75ce72c5cb577febb1907 # v4
24 changes: 24 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: GitHub App tests
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
with:
persist-credentials: false
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
with:
node-version: 24
- run: corepack enable
- run: corepack pnpm install --frozen-lockfile
- run: corepack pnpm typecheck
- run: corepack pnpm test
- run: corepack pnpm build:vercel
- run: corepack pnpm audit --audit-level=moderate
12 changes: 7 additions & 5 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
node_modules
npm-debug.log
dist
.scratch
.env
.env.*
!.env.example
*.pem
!mock-cert.pem
.env
coverage
dist
.next

.vercel
*.tsbuildinfo
.next
50 changes: 15 additions & 35 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,39 +1,19 @@
## Contributing
# Contributing

[fork]: /fork
[pr]: /compare
[code-of-conduct]: CODE_OF_CONDUCT.md
Use Node 24 and Corepack's pinned pnpm version. See [README](README.md) for setup
and [security boundaries](SECURITY.md) before changing webhook/authentication code.

Hi there! We're thrilled that you'd like to contribute to this project. Your help is essential for keeping it great.
<!-- contributor verification commands from package.json -->

Please note that this project is released with a [Contributor Code of Conduct][code-of-conduct]. By participating in this project you agree to abide by its terms.
```sh
corepack pnpm install --frozen-lockfile
corepack pnpm typecheck
corepack pnpm test
corepack pnpm audit
corepack pnpm build:vercel
```

## Issues and PRs

If you have suggestions for how this project could be improved, or want to report a bug, open an issue! We'd love all and any contributions. If you have questions, too, we'd love to hear them.

We'd also love PRs. If you're thinking of a large PR, we advise opening up an issue first to talk about it, though! Look at the links below if you're not sure how to open a PR.

## Submitting a pull request

1. [Fork][fork] and clone the repository.
1. Configure and install the dependencies: `npm install`.
1. Make sure the tests pass on your machine: `npm test`, note: these tests also apply the linter, so there's no need to lint separately.
1. Create a new branch: `git checkout -b my-branch-name`.
1. Make your change, add tests, and make sure the tests still pass.
1. Push to your fork and [submit a pull request][pr].
1. Pat your self on the back and wait for your pull request to be reviewed and merged.

Here are a few things you can do that will increase the likelihood of your pull request being accepted:

- Write and update tests.
- Keep your changes as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests.
- Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).

Work in Progress pull requests are also welcome to get feedback early on, or if there is something blocked you.

## Resources

- [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
- [Using Pull Requests](https://help.github.com/articles/about-pull-requests/)
- [GitHub Help](https://help.github.com)
Work on a feature branch. Keep documentation aligned with behavior and add tests
for affected security boundaries. Tests must use synthetic credentials and mock
external GitHub/Registry transport; never exercise production registrations.
Open pull requests ready for review. Follow the [Code of Conduct](CODE_OF_CONDUCT.md).
139 changes: 121 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,33 +1,136 @@
# stately-github-app
# Stately GitHub App

> A GitHub App built with [Probot](https://github.com/probot/probot) that An app for visualising XState machines in GitHub
Private XState diagrams in pull requests, plus authenticated event forwarding for
Stately's managed documentation drafts. This is an API service; it has no web UI.

## Setup
## Development

```sh
# Install dependencies
npm install
<!-- runtime and commands from package.json, .env.example and lib/config.ts -->

Use Node 24 and the pinned pnpm version through Corepack.

# Run the bot
npm start
```sh
corepack pnpm install --frozen-lockfile
cp .env.example .env
# Configure a development GitHub App and fill in its credentials locally.
corepack pnpm dev
```

## Docker
`POST /api/webhook` is the only route. Supply `APP_ID`, `PRIVATE_KEY` (RSA PEM,
escaped-newline PEM, or base64 PEM) and a random `WEBHOOK_SECRET` of at least 32
bytes. Empty/weak credentials fail closed. Probot's registration UI, Smee proxy,
`LOG_LEVEL` and `PRIVATE_KEY_PATH` are no longer supported. Use a separate
development app and a trusted HTTPS tunnel when testing real deliveries.

```sh
# 1. Build container
docker build -t stately-github-app .

# 2. Start container
docker run -e APP_ID=<app-id> -e PRIVATE_KEY=<pem-value> stately-github-app
corepack pnpm typecheck
corepack pnpm test
corepack pnpm audit
corepack pnpm build:vercel
```

## Contributing
Tests run real local HTTP handlers and the production parser worker. Only external
GitHub/Registry transport is mocked; they need no live credentials or AI calls.
CI also builds the deployable function, audits dependencies, and runs CodeQL.
Dependabot checks npm packages and pinned GitHub Actions weekly.

## Pull request diagrams

<!-- PR actions, source/comment budgets and preview semantics from lib/app.ts, lib/pull-requests.ts, lib/parser.ts and lib/diagrams.ts -->

On `opened`, `reopened` and `synchronize`, the app reads the current open PR and
requests a token restricted to that repository: `contents: read` and
`pull_requests: write`. It reads JavaScript/TypeScript at the immutable head SHA,
extracts static XState topology, and posts up to ten inline Mermaid diagrams in
one review. Existing comments and replies are never deleted or rewritten. Bot
identity and persisted markers prevent ordinary redelivery duplicates.

The app no longer puts machine definitions in external image/editor URLs. Context,
action implementations and service code are excluded from previews. Labels are
encoded, not interpolated as Mermaid instructions. GitHub renders the diagram
within the repository's existing access controls.

Previews cover extracted states and state-level static transitions. Root-level transitions, dynamic
expressions, guards, actions, services, history and parallel execution semantics
are not modeled. The extractor retains the XState 4 dependency it requires;
this is not a runtime validator or complete XState 5 conversion tool.

Work is bounded to 300 listed files, 20 candidate source files, 100 KiB per source,
80 states/160 edges per diagram and ten comment pages. Machines outside the
right-side diff, unsupported/oversized machines and files are skipped. Each parser
runs in a thread with an empty environment, no inherited CLI flags, a three-second
deadline and V8 heap/stack limits. Repository code is parsed, never executed.
Threads share OS filesystem/network permissions; this is not an OS sandbox.

PR processing has an eight-second abort budget. A failed/timed-out delivery can be
redelivered from GitHub; no partial pending review is created before the final
head check. Distributed simultaneous deliveries can still race to post a review;
GitHub's review API has no idempotency key. See [security boundaries](SECURITY.md).

If you have suggestions for how stately-github-app could be improved, or want to report a bug, open an issue! We'd love all and any contributions.
## Managed documentation

For more, check out the [Contributing Guide](CONTRIBUTING.md).
<!-- forwarded payloads and configuration from lib/app.ts and lib/documentation.ts -->

When enabled, authenticated non-deletion pushes on the default branch and
installation deletion/suspension/repository-removal events are forwarded to
Registry. Only branch/commit and installation/repository identity fields leave
this host. Commit messages, source files and installation credentials do not.
The compact payload is signed again with the shared webhook secret.

Registry owns repository/project pairing, source-reading consent, token creation,
queueing, AI allowance enforcement and separate reviewable documentation drafts.
This host holds no Stately project key and writes no Stately models. End users
install the app on selected repositories, pair it in Stately and commit the
one-time challenge. They do not create CI secrets.

Deploy the coordinated Studio and Viz changes before activation. An unset
`STATELY_DOCUMENTATION_WEBHOOK_URL` disables forwarding. Enabling this host alone
does not enable generation or authorize source processing.

## License

[ISC](LICENSE) © 2021 Matt Pocock <mattpocockvoice@gmail.com>
[ISC](LICENSE), original copyright retained.

## Self-hosting

<!-- listener/build/manifest/ingress settings from lib/server.ts, lib/webhook.ts, scripts/build-vercel.mjs, vercel.json and app.yml -->

Run `corepack pnpm build && corepack pnpm start` from this repository's root.
`HOST` defaults to loopback and `PORT` to 3000. Use TLS at the reverse proxy and
keep GitHub SSL verification enabled. Apply deployment-level rate/concurrency
limits; the application's four-request bound is per process, not a global quota.

On Vercel, `vercel.json` uses the Build Output API. `pnpm build:vercel` packages
only the bundled Node 24 handler and parser worker. `.vc-config.json` explicitly
disables body-parsing helpers so the handler receives the original signed bytes.
The existing `/api/webhook` URL is preserved. Builds need no credentials.

The handler bounds actual ingress bytes to 25 MiB, including chunked requests,
with a ten-second absolute body deadline. It requires SHA-256 HMAC over the exact
bytes before UTF-8/JSON parsing, rejects compression and validates event shapes.
Forwarding accepts only operator-configured HTTPS destinations with no URL
credentials/query/fragment, rejects redirects and has a ten-second total deadline.
SDK requests reject redirects and destinations outside `api.github.com`.

**Hosting limits apply first:** Vercel Functions cap request bodies at 4.5 MB;
this host cannot receive larger GitHub deliveries there. Large commit _lists_ are
compacted only after ingress. Check missed deliveries, redeliver failures, and use
a compatible ingress/host if full 25 MiB delivery support is required. GitHub
expects acknowledgement within ten seconds; slow body transfer or a timeout can
exceed that deadline. This service acknowledges completed work synchronously;
it is not a durable ingress queue.

Keep the existing `stately-github` registration, ID, private key and webhook URL.
Before rollout, check the secret satisfies the new minimum; coordinate rotation
across GitHub, this host and Registry if needed. Subscribe to `push` and
`pull_request`. Installation lifecycle/access changes arrive automatically.
`app.yml` supplies new-registration defaults only. Its permissions omit the unused
`issues: write` grant and its events omit `pull_request_review_comment`. Remove
those legacy grants/subscriptions in the live registration as a separate
operational change; this PR does not alter installed app settings.

Set `STATELY_DOCUMENTATION_WEBHOOK_URL` to
`https://stately.ai/registry/api/github/documentation` after Registry is deployed,
migrated and enabled. Registry's `STATELY_GITHUB_WEBHOOK_SECRET` must match this
host's `WEBHOOK_SECRET`. Registry separately needs the existing app ID/private key
for its own repository-scoped reads. No repository or Stately user key is needed.
42 changes: 42 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Security boundaries

The app is a webhook processor, not an agent that executes repository code.

- Trust starts with TLS and a SHA-256 HMAC over bounded, original request bytes.
Event/delivery headers are not part of GitHub's signature. Runtime schemas
select the supported actions and project only necessary forwarding fields.
- The GitHub App private key stays in the host. PR installation tokens are minted
explicitly for one repository with contents read and pull request write; issue
writes, repository writes, workflow access and Stately project edits are absent.
- Static AST extraction runs in bounded, credential-free worker threads. These
threads are resource/heap boundaries, not filesystem/network sandboxes. Do not
add evaluation, dynamic imports of source, or execution of repository scripts.
- Mermaid uses generated IDs and encoded labels. No source-derived URLs, context
values, action bodies, external thumbnails or rendering-service requests appear
in comments. Static previews do not establish application correctness.
- The app never deletes comments or modifies existing discussions. Before posting
it rechecks the current open PR head. Markers are trusted only on this app's bot
comments. A bounded warm-instance cache suppresses identical signed bodies,
including replays with changed delivery IDs; it is not distributed storage.
- Cross-instance races, replay beyond the cache window, and delivery/response loss
are possible. Registry must retain its own durable delivery/SHA deduplication,
pairing/installation checks, source consent and job lease/revocation controls.
- Neither logs nor HTTP failures serialize SDK errors, request objects, source
payloads, credentials or validation inputs. Failed processing logs a delivery ID
for correlation. Disable outbound body/header logging in hosting integrations.
- Dependency scripts are disabled except esbuild's binary installer. CI uses
read-only repository permissions for tests, pinned actions, a frozen lockfile,
dependency audit and CodeQL. Dependency/update scanners are evidence, not a
guarantee that the app or all transitive dependencies are vulnerability-free.

## Operational controls

Keep production forwarding disabled until coordinated backend/UI rollout. Store
keys in the host's secret store, install on selected repositories, rotate keys and
webhook secrets together, and remove unused live app grants/subscriptions. Rate
limits/WAF rules, GitHub IP allow lists, deployment access, secret rotation and
missed-delivery recovery remain operator responsibilities. No live settings,
permissions or secrets are changed by this code update.

Use Stately's private support channel for suspected credential exposure or
vulnerabilities. Do not include real keys or private source in public issues.
24 changes: 24 additions & 0 deletions api/webhook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { createApp } from "../lib/app.js";
import { readConfig } from "../lib/config.js";
import { createWebhookHandler } from "../lib/webhook.js";

let handler: ReturnType<typeof createWebhookHandler> | undefined;
export default async function webhook(
request: IncomingMessage,
response: ServerResponse,
) {
try {
handler ??= createWebhookHandler(createApp(readConfig()));
} catch {
console.error(JSON.stringify({ event: "invalid_app_configuration" }));
response.writeHead(503, {
"Content-Type": "text/plain",
"Cache-Control": "no-store",
Connection: "close",
});
response.end("Webhook unavailable");
return;
}
await handler(request, response);
}
Loading
Loading