From a081f75341f0982bfedf249ec29210b39504f21b Mon Sep 17 00:00:00 2001 From: Erik Goins Date: Tue, 10 Nov 2026 08:56:42 -0500 Subject: [PATCH 1/3] =?UTF-8?q?feat:=20self-host=20release=20=E2=80=94=20D?= =?UTF-8?q?ocker=20image,=20config=20check,=20health=20page,=20backups,=20?= =?UTF-8?q?releases?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Dockerfile (standalone Next, node:22-slim, non-root), docker-compose.yml with an optional Caddy TLS profile, migrations at start, refuse to start on a config error. - checkConfig()/instanceHealth() in packages/server; /setup/health for instance admins. - scripts/backup.mjs (VACUUM INTO), scripts/selfhost-check.sh, pnpm deploy:cf. - CI: docker job runs the self-host exit check; release.yml publishes to GHCR on tags; dco.yml checks sign-offs (decision 024). smoke fails above 10 MiB gzipped. - README, CONTRIBUTING, SECURITY, CODE_OF_CONDUCT, CHANGELOG, templates, guide. - E2E outbox helper waits for a newer email, so a second sign-in never reads an old code. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T7sHybpLbFAyRXzPFkfWun Signed-off-by: Erik Goins --- .dockerignore | 17 +++ .env.example | 12 ++ .github/ISSUE_TEMPLATE/bug.yml | 37 +++++ .github/ISSUE_TEMPLATE/config.yml | 5 + .github/ISSUE_TEMPLATE/feature.yml | 19 +++ .github/pull_request_template.md | 9 ++ .github/workflows/ci.yml | 24 ++++ .github/workflows/dco.yml | 13 ++ .github/workflows/release.yml | 44 ++++++ CHANGELOG.md | 17 +++ CODE_OF_CONDUCT.md | 10 ++ CONTRIBUTING.md | 50 +++++++ Dockerfile | 36 +++++ README.md | 51 ++++--- SECURITY.md | 22 +++ apps/web/e2e/outbox.ts | 32 +++-- apps/web/e2e/setup.spec.ts | 27 +++- apps/web/next.config.ts | 6 + apps/web/package.json | 1 + apps/web/public/.gitkeep | 0 apps/web/public/file.svg | 1 - apps/web/public/globe.svg | 1 - apps/web/public/next.svg | 1 - apps/web/public/vercel.svg | 1 - apps/web/public/window.svg | 1 - apps/web/src/app/api/v1/health/route.ts | 2 +- apps/web/src/app/setup/health/page.tsx | 102 ++++++++++++++ apps/web/src/app/setup/page.tsx | 8 +- apps/web/src/instrumentation.ts | 6 +- apps/web/src/server/runtime/index.ts | 10 +- apps/web/src/server/runtime/runtime.node.ts | 27 +++- .../web/src/server/runtime/runtime.workerd.ts | 7 +- deploy/Caddyfile | 7 + docker-compose.yml | 35 +++++ docs/INDEX.md | 2 + docs/STATE.md | 21 +-- docs/features/self-host.md | 67 +++++++++ docs/self-host/README.md | 119 ++++++++++++++++ package.json | 3 +- packages/server/src/config-check.ts | 128 ++++++++++++++++++ packages/server/src/index.ts | 1 + packages/server/test/config-check.test.ts | 110 +++++++++++++++ scripts/backup.mjs | 29 ++++ scripts/check-dco.sh | 14 ++ scripts/selfhost-check.sh | 33 +++++ scripts/smoke.sh | 7 +- 46 files changed, 1122 insertions(+), 53 deletions(-) create mode 100644 .dockerignore create mode 100644 .github/ISSUE_TEMPLATE/bug.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature.yml create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/dco.yml create mode 100644 .github/workflows/release.yml create mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 Dockerfile create mode 100644 SECURITY.md create mode 100644 apps/web/public/.gitkeep delete mode 100644 apps/web/public/file.svg delete mode 100644 apps/web/public/globe.svg delete mode 100644 apps/web/public/next.svg delete mode 100644 apps/web/public/vercel.svg delete mode 100644 apps/web/public/window.svg create mode 100644 apps/web/src/app/setup/health/page.tsx create mode 100644 deploy/Caddyfile create mode 100644 docker-compose.yml create mode 100644 docs/features/self-host.md create mode 100644 docs/self-host/README.md create mode 100644 packages/server/src/config-check.ts create mode 100644 packages/server/test/config-check.test.ts create mode 100644 scripts/backup.mjs create mode 100755 scripts/check-dco.sh create mode 100755 scripts/selfhost-check.sh diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..95d5ae0 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,17 @@ +**/node_modules +**/.next +**/.open-next +**/.wrangler +**/.data +**/test-results +**/playwright-report +**/*.tsbuildinfo +**/* [0-9]* +.git +.env* +!.env.example +**/.dev.vars* +apps/mac +CLAUDE.local.md +.claude +.agents diff --git a/.env.example b/.env.example index 126a6c0..a7dc36d 100644 --- a/.env.example +++ b/.env.example @@ -41,3 +41,15 @@ GITWORK_SCHEDULER= # Free plan, which allows 50 subrequests per invocation. RECONCILE_MAX_TARGETS= RECONCILE_MAX_PAGES= + +# ---- Docker and other self-hosted Node servers (docs/self-host/) ---------------------------- +# The Docker image sets these three itself; set them only on a plain Node host. +# DATABASE_URL=file:/data/gitwork.sqlite +# GITWORK_MIGRATIONS_DIR=/app/migrations # apply pending migrations at start +# GITWORK_FAIL_ON_CONFIG_ERROR=1 # refuse to start on a configuration error +# docker-compose.yml: image tag, host port, and the domain for the optional Caddy profile. +GITWORK_TAG=latest +GITWORK_PORT=3000 +GITWORK_DOMAIN= +# Tests only: write emails to a file instead of sending them (EMAIL_TRANSPORT=outbox). +EMAIL_OUTBOX_PATH= diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml new file mode 100644 index 0000000..2b72a18 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -0,0 +1,37 @@ +name: Bug +description: Something does not work as documented. +labels: [bug] +body: + - type: textarea + id: what + attributes: + label: What happened, and what did you expect? + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce + placeholder: "1. …\n2. …" + validations: + required: true + - type: input + id: version + attributes: + label: Version + description: From /setup/health, or the Docker tag. + validations: + required: true + - type: dropdown + id: host + attributes: + label: Host + options: [Docker, Cloudflare Workers, Other Node host, Local development] + validations: + required: true + - type: textarea + id: logs + attributes: + label: Logs + description: Remove secrets, emails, and tokens first. + render: text diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..2344917 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Security vulnerability + url: https://github.com/FlywheelStudio/gitwork/security/advisories/new + about: Report it privately, not as an issue. diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml new file mode 100644 index 0000000..92192f1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature.yml @@ -0,0 +1,19 @@ +name: Feature request +description: Suggest a change or a new feature. +labels: [enhancement] +body: + - type: textarea + id: problem + attributes: + label: What problem does this solve? + validations: + required: true + - type: textarea + id: proposal + attributes: + label: What do you propose? + - type: textarea + id: github + attributes: + label: Where does the data live in GitHub? + description: GitHub is the source of truth. Name the GitHub field, label, or file, if you know it. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..aeda336 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,9 @@ +## What and why + +## How I tested it + +## Checklist +- [ ] Every commit is signed off (`git commit -s`) +- [ ] `pnpm lint && pnpm typecheck && pnpm test` pass +- [ ] Tests cover the change (API routes: success, 401, 403, 400; DB code on both drivers) +- [ ] Docs updated (decision record if needed, `docs/INDEX.md`) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c5562c9..d6a2836 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,3 +24,27 @@ jobs: - run: pnpm test:e2e # Builds and serves both runtimes; fails if libsql reaches the Worker bundle. - run: pnpm smoke + + # The Phase 7 exit check, minus GitHub: build the Docker image, start it on an empty volume, and + # sign in as the instance admin. + docker: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - run: docker build -t gitwork:ci . + - name: Start a fresh instance + run: | + mkdir -p /tmp/gw && chmod 777 /tmp/gw + docker run -d --name gw -p 3000:3000 -v /tmp/gw:/data \ + -e BETTER_AUTH_SECRET="$(openssl rand -base64 32)" -e BETTER_AUTH_URL=http://localhost:3000 \ + -e INSTANCE_ADMIN_EMAILS=admin@example.com -e EMAIL_TRANSPORT=outbox -e EMAIL_OUTBOX_PATH=/data/outbox.jsonl \ + gitwork:ci + - run: ./scripts/selfhost-check.sh http://localhost:3000 /tmp/gw/outbox.jsonl admin@example.com + - name: Online backup + run: docker exec gw node backup.mjs /data/backup.sqlite && test -s /tmp/gw/backup.sqlite + - name: Refuses to start without configuration + run: | + if docker run --rm gitwork:ci; then echo "FAIL: started without configuration"; exit 1; fi + - if: always() + run: docker logs gw || true diff --git a/.github/workflows/dco.yml b/.github/workflows/dco.yml new file mode 100644 index 0000000..237ad56 --- /dev/null +++ b/.github/workflows/dco.yml @@ -0,0 +1,13 @@ +name: DCO + +# Contributions are accepted under the Developer Certificate of Origin (decision 024). +on: pull_request + +jobs: + signoff: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - run: ./scripts/check-dco.sh "${{ github.event.pull_request.base.sha }}" "${{ github.event.pull_request.head.sha }}" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..6b5fb00 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,44 @@ +name: Release + +# Push a tag like v0.1.0 to publish ghcr.io/flywheelstudio/gitwork: and :latest +# (linux/amd64 and linux/arm64) and a GitHub Release with generated notes. +on: + push: + tags: ["v*.*.*"] + +permissions: + contents: write + packages: write + +jobs: + image: + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-qemu-action@v3 + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - id: meta + uses: docker/metadata-action@v5 + with: + images: ghcr.io/${{ github.repository }} + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=raw,value=latest + - uses: docker/build-push-action@v6 + with: + context: . + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + build-args: GITWORK_VERSION=${{ github.ref_name }} + - run: gh release create "$GITHUB_REF_NAME" --generate-notes --verify-tag + env: + GH_TOKEN: ${{ github.token }} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..8222882 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,17 @@ +# Changelog + +All notable changes. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and versions follow [Semantic Versioning](https://semver.org/). Before 1.0.0, a minor version may +break things; the notes say how to upgrade. + +## Unreleased + +### Added +- Self-hosting: Docker image (`ghcr.io/flywheelstudio/gitwork`), `docker-compose.yml` with an + optional Caddy TLS profile, migrations on start, a configuration check that stops a bad deploy at + boot, an online backup script, and a self-host guide. +- `/setup/health` for instance admins: configuration, GitHub App, last webhook, last reconcile. +- `pnpm deploy:cf`: build, migrate D1, and deploy to Cloudflare Workers. +- Tasks on web: list, kanban, and timeline views of a GitHub Projects v2 board; task edits. +- Identity: email-code sign-in, accounts, workspaces, four roles, invites, GitHub account link. +- GitHub App: setup wizard, webhooks, cache, 15-minute reconcile. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..6485d16 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,10 @@ +# Code of conduct + +Gitwork adopts the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/). + +In short: be respectful, assume good intent, and criticize ideas, not people. Harassment is not +tolerated in issues, pull requests, or any other project space. + +Report a problem privately to the maintainers through GitHub's **Report content** feature or a +private security report (see SECURITY.md). Maintainers review every report and keep the reporter's +identity private. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..c0e3e81 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,50 @@ +# Contributing to Gitwork + +Thank you for helping. This file covers how to set up, what a pull request needs, and the rules that +keep Gitwork safe. + +## Set up + +```bash +corepack enable +pnpm install +pnpm dev +``` + +`CLAUDE.md` lists every command and the codebase map. `docs/INDEX.md` lists every design decision. + +## Sign off every commit (DCO) + +Gitwork accepts contributions under the [Developer Certificate of Origin](https://developercertificate.org/) +(decision 024). Sign off each commit to certify that you wrote it or may submit it under the +project's license: + +```bash +git commit -s -m "fix: …" +``` + +This adds `Signed-off-by: Your Name `, matching the commit author. A CI check +fails a pull request with an unsigned commit. To fix one: `git rebase --signoff origin/main`, then +push. + +## A pull request needs + +- `pnpm lint && pnpm typecheck && pnpm test` passing. CI also runs `pnpm test:e2e`, `pnpm smoke`, + and a Docker self-host check. +- Tests for the change. API routes: success, 401, 403, 400. Database code runs on both drivers + (`describe.each(await allTestDrivers())`). +- Docs in the same pull request: a decision record in `docs/decisions/` for a decision of lasting + consequence, and `docs/INDEX.md` updated. +- Commit messages as `: ` (feat, fix, docs, test, refactor, chore). + +## Rules that must not break + +- Every read and write goes through the permission and visibility checks in `packages/core`. +- Read Only users never receive a hidden item, by any path. +- Every write adds an `audit_log` row in the same batch. +- The markdown editors leave untouched lines byte-identical. +- Never call real GitHub from tests. Use `packages/server/test/fake-github.ts`. + +## Licensing + +By contributing, you license your work under [AGPL-3.0-only](LICENSE). diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..863079d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,36 @@ +# syntax=docker/dockerfile:1 +# Gitwork on any Node host: Next.js standalone server + a SQLite file on the /data volume. +# Build: docker build -t gitwork . +# Run: docker compose up -d (see docker-compose.yml and docs/self-host/) + +FROM node:22-slim AS build +WORKDIR /src +ENV NEXT_TELEMETRY_DISABLED=1 GITWORK_STANDALONE=1 COREPACK_ENABLE_DOWNLOAD_PROMPT=0 +RUN corepack enable +COPY . . +RUN pnpm install --frozen-lockfile +RUN pnpm --filter @gitwork/web build + +FROM node:22-slim +ARG GITWORK_VERSION=dev +LABEL org.opencontainers.image.source="https://github.com/FlywheelStudio/gitwork" \ + org.opencontainers.image.licenses="AGPL-3.0-only" \ + org.opencontainers.image.version="${GITWORK_VERSION}" +WORKDIR /app +ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 PORT=3000 HOSTNAME=0.0.0.0 \ + GITWORK_VERSION=${GITWORK_VERSION} \ + DATABASE_URL=file:/data/gitwork.sqlite \ + GITWORK_MIGRATIONS_DIR=/app/migrations \ + GITWORK_FAIL_ON_CONFIG_ERROR=1 +COPY --from=build --chown=node:node /src/apps/web/.next/standalone ./ +COPY --from=build --chown=node:node /src/apps/web/.next/static ./apps/web/.next/static +COPY --from=build --chown=node:node /src/apps/web/public ./apps/web/public +COPY --from=build --chown=node:node /src/packages/db/migrations ./migrations +COPY --from=build --chown=node:node /src/scripts/backup.mjs ./backup.mjs +RUN mkdir -p /data && chown node:node /data +USER node +VOLUME /data +EXPOSE 3000 +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s \ + CMD node -e "fetch('http://127.0.0.1:3000/api/v1/health').then(r=>process.exit(r.ok?0:1),()=>process.exit(1))" +CMD ["node", "apps/web/server.js"] diff --git a/README.md b/README.md index 9e89c8e..5d0bb6b 100644 --- a/README.md +++ b/README.md @@ -1,42 +1,61 @@ # Gitwork -Project management on top of GitHub. GitHub stays the source of truth for tasks and docs; Gitwork -gives your clients and stakeholders a fast, permissioned view of it — list, kanban, and timeline -views of a GitHub Projects v2 board, plus editable markdown from each repo's `docs/` folder. +Project management on top of GitHub. GitHub stays the source of truth for tasks and docs. Gitwork +gives your team, clients, and stakeholders a fast, permissioned view of it: list, kanban, and +timeline views of a GitHub Projects v2 board, with edits that go back to GitHub. -> **Status:** early development (Phase 0 of 7). Not usable yet. See [docs/STATE.md](docs/STATE.md). +People without a GitHub account can take part. Four roles (Owner, Admin, Member, Read Only) decide +what each person sees and changes. Read Only users never receive hidden items. -## Run it locally +> **Status: pre-release.** Tasks work end to end against a simulated GitHub. Docs editing, the +> activity inbox, and the Mac app are still in progress. See [docs/STATE.md](docs/STATE.md) and the +> [roadmap](docs/roadmap.md). -Requires Node 22+ and corepack (ships with Node 22–24). +## Self-host + +Gitwork is open source under the [AGPL-3.0](LICENSE). Run it on any Docker host or on Cloudflare +Workers. + +```bash +git clone https://github.com/FlywheelStudio/gitwork && cd gitwork +cp .env.example .env # fill in the URL, secret, admin email, and SMTP +docker compose up -d +``` + +The full guide, with Cloudflare, backups, and upgrades: [docs/self-host/](docs/self-host/README.md). + +## Develop + +Requires Node 22+ and corepack. ```bash -corepack enable # provides the pinned pnpm +corepack enable pnpm install pnpm dev # Node + SQLite file at apps/web/.data/ → http://localhost:3000 pnpm preview # Cloudflare Workers (workerd) + local D1 → http://localhost:8787 ``` -## Checks +Checks, as CI runs them: ```bash pnpm lint && pnpm typecheck -pnpm test # unit tests; the DB suite runs on both libsql and D1 +pnpm test # unit and integration; the DB suite runs on both libsql and D1 pnpm test:e2e # Playwright against the Node runtime pnpm smoke # builds and serves both runtimes end to end ``` -## Self-hosting - -Gitwork runs on Cloudflare Workers (D1) or any Node host (SQLite file). Deploy guides arrive in -Phase 7. For Cloudflare today: `wrangler d1 create gitwork`, put the ID in -`apps/web/wrangler.jsonc`, then `wrangler d1 migrations apply DB --remote` and -`pnpm --filter @gitwork/web exec opennextjs-cloudflare deploy`. +Read [CONTRIBUTING.md](CONTRIBUTING.md) before a pull request. Every commit needs a DCO sign-off +(`git commit -s`). ## Docs Start at [docs/INDEX.md](docs/INDEX.md). The product spec is [docs/spec.md](docs/spec.md). +## Security + +Report vulnerabilities privately. See [SECURITY.md](SECURITY.md). + ## License -[AGPL-3.0](LICENSE). +[AGPL-3.0-only](LICENSE). If you run a modified Gitwork for other people, you must offer them your +source code. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..726a5a7 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,22 @@ +# Security policy + +## Report a vulnerability + +Do not open a public issue. Report it privately through GitHub: +**Security → Report a vulnerability** on this repository. + +Include the affected version or commit, the steps to reproduce, and the impact. We answer within +five working days and tell you when a fix ships. We credit reporters who want credit. + +## Scope + +In scope: this repository, the Docker image `ghcr.io/flywheelstudio/gitwork`, and the default +configuration. Especially: a Read Only user receiving a hidden item, any bypass of the role checks, +webhook signature bypass, and leaks of stored secrets. + +Out of scope: problems that need a compromised instance admin or host, and self-hosted instances +running outdated versions. + +## Supported versions + +The latest release gets security fixes. Upgrade to it before you report. diff --git a/apps/web/e2e/outbox.ts b/apps/web/e2e/outbox.ts index 55f436a..2cd8199 100644 --- a/apps/web/e2e/outbox.ts +++ b/apps/web/e2e/outbox.ts @@ -8,20 +8,28 @@ interface Message { text: string; } -/** The newest email to `to` whose text matches `pattern`. Polls: sending is async. */ -export async function lastEmail(to: string, pattern: RegExp): Promise { +function readMessages(): Message[] { + try { + return readFileSync(E2E_OUTBOX, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l) as Message); + } catch { + return []; + } +} + +/** How many emails `to` has received so far. Pass it to `signInCode` to wait for a newer one. */ +export const emailCount = (to: string) => readMessages().filter((m) => m.to === to).length; + +/** + * The newest email to `to` whose text matches `pattern`. Polls: sending is async. With `after`, + * waits until `to` has more than `after` emails, so a second sign-in never reads the first code. + */ +export async function lastEmail(to: string, pattern: RegExp, after = 0): Promise { let found: RegExpExecArray | null = null; await expect .poll(() => { - let lines: string[] = []; - try { - lines = readFileSync(E2E_OUTBOX, "utf8").trim().split("\n"); - } catch { - return false; - } - const messages = lines.filter(Boolean).map((l) => JSON.parse(l) as Message); - const match = messages - .filter((m) => m.to === to) + const mine = readMessages().filter((m) => m.to === to); + if (mine.length <= after) return false; + const match = mine .map((m) => pattern.exec(m.text)) .filter((m): m is RegExpExecArray => m !== null) .at(-1); @@ -32,4 +40,4 @@ export async function lastEmail(to: string, pattern: RegExp): Promise (await lastEmail(email, /sign-in code is (\d{6})/))[1]!; +export const signInCode = async (email: string, after = 0) => (await lastEmail(email, /sign-in code is (\d{6})/, after))[1]!; diff --git a/apps/web/e2e/setup.spec.ts b/apps/web/e2e/setup.spec.ts index c8bbe05..666cb81 100644 --- a/apps/web/e2e/setup.spec.ts +++ b/apps/web/e2e/setup.spec.ts @@ -1,11 +1,12 @@ import { type Page, expect, test } from "@playwright/test"; -import { signInCode } from "./outbox"; +import { emailCount, signInCode } from "./outbox"; async function signIn(page: Page, email: string) { + const before = emailCount(email); await page.goto("/sign-in"); await page.getByLabel("Email").fill(email); await page.getByRole("button", { name: "Email me a sign-in code" }).click(); - await page.getByLabel("Code").fill(await signInCode(email)); + await page.getByLabel("Code").fill(await signInCode(email, before)); await page.getByRole("button", { name: "Sign in" }).click(); await expect(page.getByRole("button", { name: "Sign out" })).toBeVisible(); } @@ -45,3 +46,25 @@ test("an instance admin finishes setup; everyone else gets a 404", async ({ brow await adminCtx.close(); await userCtx.close(); }); + +test("an instance admin sees instance health without secret values; everyone else gets a 404", async ({ browser }) => { + const adminCtx = await browser.newContext(); + const admin = await adminCtx.newPage(); + await signIn(admin, "admin@example.com"); + await admin.goto("/setup"); + await admin.getByRole("link", { name: "Instance health" }).click(); + await expect(admin.getByRole("heading", { name: "Instance health" })).toBeVisible(); + await expect(admin.getByTestId("health-row")).toHaveCount(6); + await expect(admin.getByTestId("health-row").filter({ hasText: "GitHub App" })).toContainText("Not set up yet."); + // The E2E server sends email to a file: a warning, named by variable. + await expect(admin.getByTestId("config-issues")).toContainText("EMAIL_TRANSPORT"); + await expect(admin.locator("body")).not.toContainText("e2e-secret-e2e-secret"); + + const userCtx = await browser.newContext(); + const user = await userCtx.newPage(); + await signIn(user, "plain-health@example.com"); + expect((await user.goto("/setup/health"))?.status()).toBe(404); + + await adminCtx.close(); + await userCtx.close(); +}); diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 26476a1..5137c52 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -1,3 +1,4 @@ +import { fileURLToPath } from "node:url"; import type { NextConfig } from "next"; // Build-time driver split (decision 004). `pnpm cf:build` sets GITWORK_TARGET=cloudflare, so the @@ -8,7 +9,12 @@ const runtime = ? "./src/server/runtime/runtime.workerd.ts" : "./src/server/runtime/runtime.node.ts"; +// The Docker image sets GITWORK_STANDALONE=1: a self-contained server in .next/standalone, traced +// from the repo root so the workspace packages come along. +const standalone = process.env.GITWORK_STANDALONE === "1"; + const nextConfig: NextConfig = { + ...(standalone && { output: "standalone", outputFileTracingRoot: fileURLToPath(new URL("../..", import.meta.url)) }), // cacheComponents stays off: under workerd its setTimeout dependency hangs every request. reactCompiler: true, transpilePackages: ["@gitwork/core", "@gitwork/db", "@gitwork/server"], diff --git a/apps/web/package.json b/apps/web/package.json index 3b064d0..d953b46 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -13,6 +13,7 @@ "predev": "pnpm db:migrate", "db:migrate": "tsx ../../packages/db/src/migrate-cli.ts", "cf:migrate:local": "wrangler d1 migrations apply DB --local", + "cf:deploy": "pnpm cf:build && wrangler d1 migrations apply DB --remote && opennextjs-cloudflare deploy", "cf:typegen": "wrangler types --env-interface CloudflareEnv cloudflare-env.d.ts", "test:e2e": "playwright test" }, diff --git a/apps/web/public/.gitkeep b/apps/web/public/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/apps/web/public/file.svg b/apps/web/public/file.svg deleted file mode 100644 index 004145c..0000000 --- a/apps/web/public/file.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/apps/web/public/globe.svg b/apps/web/public/globe.svg deleted file mode 100644 index 567f17b..0000000 --- a/apps/web/public/globe.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/apps/web/public/next.svg b/apps/web/public/next.svg deleted file mode 100644 index 5174b28..0000000 --- a/apps/web/public/next.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/apps/web/public/vercel.svg b/apps/web/public/vercel.svg deleted file mode 100644 index 7705396..0000000 --- a/apps/web/public/vercel.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/apps/web/public/window.svg b/apps/web/public/window.svg deleted file mode 100644 index b2b2a44..0000000 --- a/apps/web/public/window.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/apps/web/src/app/api/v1/health/route.ts b/apps/web/src/app/api/v1/health/route.ts index eab3271..1633293 100644 --- a/apps/web/src/app/api/v1/health/route.ts +++ b/apps/web/src/app/api/v1/health/route.ts @@ -7,5 +7,5 @@ import { getDatabase } from "@/server/runtime"; export async function GET() { const { driver, db } = getDatabase(); const [row] = await db.select({ settings: count() }).from(instanceSettings); - return Response.json({ ok: true, app: APP_NAME, driver, settings: row?.settings ?? 0 }); + return Response.json({ ok: true, app: APP_NAME, version: process.env.GITWORK_VERSION || "dev", driver, settings: row?.settings ?? 0 }); } diff --git a/apps/web/src/app/setup/health/page.tsx b/apps/web/src/app/setup/health/page.tsx new file mode 100644 index 0000000..39cdf06 --- /dev/null +++ b/apps/web/src/app/setup/health/page.tsx @@ -0,0 +1,102 @@ +import { instanceHealth } from "@gitwork/server"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import type { ReactNode } from "react"; +import { Header } from "@/components/header"; +import { Card } from "@/components/kit"; +import { getDeps, getConfig, isAdmin } from "@/server/context"; +import { requireUser } from "@/server/pages"; +import { RUNTIME } from "@/server/runtime"; + +function Row({ ok, label, children }: { ok: boolean | null; label: string; children: ReactNode }) { + const mark = ok === null ? "–" : ok ? "✓" : "✗"; + const color = ok === null ? "text-muted-foreground" : ok ? "text-green-600" : "text-red-600"; + return ( +
  • + + {mark} + + {label} + {children} +
  • + ); +} + +const ago = (date: Date) => { + const minutes = Math.round((Date.now() - date.getTime()) / 60_000); + return minutes < 1 ? "just now" : minutes < 120 ? `${minutes} min ago` : `${Math.round(minutes / 60)} h ago`; +}; + +/** Reconcile runs every 15 minutes; three missed runs is a problem. */ +const isRecent = (date: Date, minutes: number) => Date.now() - date.getTime() < minutes * 60_000; + +/** Instance admins only: one line per check, from the database and the environment. No GitHub calls. */ +export default async function HealthPage() { + const user = await requireUser("/setup/health"); + if (!isAdmin(user.email)) notFound(); + const deps = await getDeps(); + const health = await instanceHealth(deps.database, getConfig().env, RUNTIME); + const errors = health.issues.filter((i) => i.level === "error"); + const reconcile = health.lastReconcile; + const reconcileAt = reconcile ? new Date(reconcile.at) : null; + const reconcileFresh = reconcileAt ? isRecent(reconcileAt, 45) : false; + + return ( + <> +
    +
    +
    +

    Instance health

    + + Setup + +
    + +
      + + {process.env.GITWORK_VERSION || "dev"} · {RUNTIME === "node" ? "Node" : "Cloudflare Workers"} · database{" "} + {health.driver} + + + {health.issues.length === 0 ? "No problems." : `${errors.length} errors, ${health.issues.length - errors.length} warnings (below).`} + + + {deps.github + ? `${deps.github.app.slug || deps.github.app.appId} (${deps.github.app.source === "env" ? "environment" : "created in setup"})` + : deps.githubError + ? "Stored credentials cannot be decrypted. Re-run setup." + : "Not set up yet."} + + 0 ? true : null} label="Installations"> + {health.installations === 0 ? "None yet." : `${health.installations} organization(s).`} + + + {health.lastWebhookAt ? ago(health.lastWebhookAt) : "None received yet. GitHub must reach this instance's URL."} + + + {reconcile && reconcileAt + ? `${ago(reconcileAt)}: ${reconcile.status}${reconcile.message ? ` (${reconcile.message})` : ""}` + : "Not run yet. It runs every 15 minutes."} + +
    +
    + {health.issues.length > 0 && ( + +

    Configuration problems

    +
      + {health.issues.map((issue) => ( +
    • + + {issue.level === "error" ? "Error" : "Warning"} + {" "} + {issue.key}: {issue.message} +
    • + ))} +
    +

    Change the environment variables, then restart. See .env.example.

    +
    + )} +
    + + ); +} diff --git a/apps/web/src/app/setup/page.tsx b/apps/web/src/app/setup/page.tsx index 87bb3d7..f1b4bff 100644 --- a/apps/web/src/app/setup/page.tsx +++ b/apps/web/src/app/setup/page.tsx @@ -1,4 +1,5 @@ import { getSignupPolicy } from "@gitwork/server"; +import Link from "next/link"; import { notFound } from "next/navigation"; import { Header } from "@/components/header"; import { Card } from "@/components/kit"; @@ -26,7 +27,12 @@ export default async function SetupPage({ searchParams }: PageProps<"/setup">) { <>
    -

    Instance setup

    +
    +

    Instance setup

    + + Instance health + +
    {typeof error === "string" &&

    {ERRORS[error] ?? "Setup failed."}

    } diff --git a/apps/web/src/instrumentation.ts b/apps/web/src/instrumentation.ts index 19ae7dd..d6e1693 100644 --- a/apps/web/src/instrumentation.ts +++ b/apps/web/src/instrumentation.ts @@ -1,6 +1,8 @@ -// Runs once per server start. Starts the Node reconcile timer; a no-op in the Worker build. +// Runs once per server start, before requests. Node: config check, migrations (Docker), the +// reconcile timer. A no-op in the Worker build. export async function register() { if (process.env.NEXT_RUNTIME !== "nodejs") return; - const { startScheduler } = await import("@/server/runtime"); + const { bootNode, startScheduler } = await import("@/server/runtime"); + await bootNode(); startScheduler(); } diff --git a/apps/web/src/server/runtime/index.ts b/apps/web/src/server/runtime/index.ts index eb788ad..6a230ea 100644 --- a/apps/web/src/server/runtime/index.ts +++ b/apps/web/src/server/runtime/index.ts @@ -1,2 +1,10 @@ // Resolves to runtime.node.ts or runtime.workerd.ts at build time (see next.config.ts). -export { DEFAULT_TRUSTED_IP_HEADER, getDatabase, getEmailSender, getEnv, startScheduler } from "@gitwork/runtime"; +export { + bootNode, + DEFAULT_TRUSTED_IP_HEADER, + getDatabase, + getEmailSender, + getEnv, + RUNTIME, + startScheduler, +} from "@gitwork/runtime"; diff --git a/apps/web/src/server/runtime/runtime.node.ts b/apps/web/src/server/runtime/runtime.node.ts index 62c5e39..e8b1fff 100644 --- a/apps/web/src/server/runtime/runtime.node.ts +++ b/apps/web/src/server/runtime/runtime.node.ts @@ -1,7 +1,8 @@ import "server-only"; import type { Database } from "@gitwork/db"; import { openSqlite } from "@gitwork/db/node"; -import { type EmailSender, consoleSender, unconfiguredSender } from "@gitwork/server"; +import { migrate } from "drizzle-orm/libsql/migrator"; +import { type EmailSender, type RuntimeName, checkConfig, consoleSender, unconfiguredSender } from "@gitwork/server"; import { outboxSender, smtpSender } from "@gitwork/server/email-node"; import { runScheduledReconcile } from "@gitwork/server/sync"; @@ -49,3 +50,27 @@ export function startScheduler(): void { scheduler.__gitworkScheduler = setInterval(tick, RECONCILE_EVERY_MS); setTimeout(tick, 30_000); } + +export const RUNTIME: RuntimeName = "node"; + +/** + * Runs once before the server takes requests (src/instrumentation.ts). Production only: + * 1. Logs every configuration problem by variable name. With GITWORK_FAIL_ON_CONFIG_ERROR=1 (the + * Docker image sets it) an error stops the process, so a bad deploy fails loudly at boot. + * 2. With GITWORK_MIGRATIONS_DIR set (the Docker image sets it), applies pending migrations. + */ +export async function bootNode(): Promise { + if (process.env.NODE_ENV !== "production") return; + const issues = checkConfig(process.env, RUNTIME); + for (const issue of issues) console[issue.level === "error" ? "error" : "warn"](`[config] ${issue.level}: ${issue.key}: ${issue.message}`); + if (process.env.GITWORK_FAIL_ON_CONFIG_ERROR === "1" && issues.some((i) => i.level === "error")) { + console.error("[config] Fix the errors above, then restart. See .env.example."); + process.exit(1); + } + const dir = process.env.GITWORK_MIGRATIONS_DIR; + if (dir) { + // The runtime object is a LibSQLDatabase; `Db` hides only `transaction`. + await migrate(getDatabase().db as unknown as Parameters[0], { migrationsFolder: dir }); + console.info(`[db] migrations applied from ${dir}`); + } +} diff --git a/apps/web/src/server/runtime/runtime.workerd.ts b/apps/web/src/server/runtime/runtime.workerd.ts index b589e5f..7bf7b8c 100644 --- a/apps/web/src/server/runtime/runtime.workerd.ts +++ b/apps/web/src/server/runtime/runtime.workerd.ts @@ -1,7 +1,7 @@ import "server-only"; import type { Database } from "@gitwork/db"; import { openD1 } from "@gitwork/db/d1"; -import { type EmailSender, cloudflareSender, parseFrom, unconfiguredSender } from "@gitwork/server"; +import { type EmailSender, type RuntimeName, cloudflareSender, parseFrom, unconfiguredSender } from "@gitwork/server"; import { getCloudflareContext } from "@opennextjs/cloudflare"; /** Cloudflare Workers: the D1 binding named DB. Bindings are per request, so no caching here. */ @@ -27,3 +27,8 @@ export function getEmailSender(): EmailSender { /** Workers: the Cron Trigger in worker.ts runs reconcile. Nothing to start here. */ export function startScheduler(): void {} + +export const RUNTIME: RuntimeName = "workerd"; + +/** Workers: migrations run with `wrangler d1 migrations apply`; nothing runs at boot. */ +export async function bootNode(): Promise {} diff --git a/deploy/Caddyfile b/deploy/Caddyfile new file mode 100644 index 0000000..5851ac2 --- /dev/null +++ b/deploy/Caddyfile @@ -0,0 +1,7 @@ +# Used by `docker compose --profile caddy up -d`. Caddy gets and renews the TLS certificate. +# It overwrites X-Real-IP with the real client address, so set TRUSTED_IP_HEADER=x-real-ip in .env. +{$GITWORK_DOMAIN} { + reverse_proxy gitwork:3000 { + header_up X-Real-IP {remote_host} + } +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..0e38f86 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,35 @@ +# Gitwork with a SQLite file on a named volume. +# 1. cp .env.example .env and fill it in (BETTER_AUTH_URL = your public https URL). +# 2. docker compose up -d # Gitwork on port 3000, behind your own proxy +# docker compose --profile caddy up -d # or let Caddy get a TLS certificate (set GITWORK_DOMAIN) +# Full guide: docs/self-host/README.md +services: + gitwork: + image: ghcr.io/flywheelstudio/gitwork:${GITWORK_TAG:-latest} + build: . + restart: unless-stopped + env_file: .env + environment: + DATABASE_URL: file:/data/gitwork.sqlite + volumes: + - gitwork-data:/data + ports: + - "${GITWORK_PORT:-3000}:3000" + + caddy: + image: caddy:2 + profiles: [caddy] + restart: unless-stopped + depends_on: [gitwork] + environment: + GITWORK_DOMAIN: ${GITWORK_DOMAIN:-localhost} + ports: + - "80:80" + - "443:443" + volumes: + - ./deploy/Caddyfile:/etc/caddy/Caddyfile:ro + - caddy-data:/data + +volumes: + gitwork-data: + caddy-data: diff --git a/docs/INDEX.md b/docs/INDEX.md index 780e065..42e6212 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -39,3 +39,5 @@ | [features/identity.md](features/identity.md) | Email-code sign-in, accounts, workspaces, roles, invites, GitHub link, `/api/v1`. | | [features/github-app.md](features/github-app.md) | Setup wizard, GitHub App, installations, webhooks, cache, reconcile. | | [features/tasks.md](features/tasks.md) | Board and repo link, list / kanban / timeline, task edits, visibility filter, audit log. | +| [features/self-host.md](features/self-host.md) | Docker image, config check, /setup/health, backup, release pipeline, DCO. | +| [self-host/README.md](self-host/README.md) | Self-host guide: Docker, Cloudflare, upgrades, backups, troubleshooting. | diff --git a/docs/STATE.md b/docs/STATE.md index bd9bdc3..789fc46 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -1,20 +1,22 @@ # State -Last updated: 2026-10-15 +Last updated: 2026-11-10 ## Resume here -- **Phase 3 (tasks on web) is in review** on branch `feature/tasks` (PR pending owner merge). - PRs #1–#3 (Phases 0–2) are merged. -- **Live GitHub check: still not done.** It needs a person (or a connected browser) to click - "Create GitHub App" on github.com, and a public webhook URL. See Chores. +- Plan: `docs/roadmap.md` (PR #6), accepted 2026-11-10 with decisions 023–032. Order: live GitHub + check → self-host v0.1 → speed / keyboard / layout → Linear parity tier 1 → Phase 4 Docs. +- Open PRs: #5 (decisions 020–022, iCloud copies removed), #6 (roadmap), #7 (self-host, Track A). +- **Live GitHub check: still not done.** The session's permission rules block a `cloudflared` + tunnel. The owner must start the tunnel or allow it. See Chores. +- **Move the repo out of `~/Documents`.** iCloud copies files, including inside `.git`. - **Before any work:** `git fetch origin && git status -sb`. -- **Toolchain:** pnpm comes from corepack (`corepack enable` was run on this machine). Run checks - from the repo root: `pnpm lint && pnpm typecheck && pnpm test && pnpm test:e2e && pnpm smoke`. +- **Toolchain:** pnpm comes from corepack. Run checks from the repo root: + `pnpm lint && pnpm typecheck && pnpm test && pnpm test:e2e && pnpm smoke`. ## In Progress -None. Next step: Phase 4 — Docs on web. +Track B + C + D (speed, keyboard, layout) — next after PR #7. ## Completed @@ -24,7 +26,8 @@ None. Next step: Phase 4 — Docs on web. | Phase 0 — Scaffold | 2026-10-15 | [features/scaffold.md](features/scaffold.md) | | Phase 1 — Identity | 2026-10-15 | [features/identity.md](features/identity.md) | | Phase 2 — GitHub App (PR #3) | 2026-10-15 | [features/github-app.md](features/github-app.md) | -| Phase 3 — Tasks on web (in review) | 2026-10-15 | [features/tasks.md](features/tasks.md) | +| Phase 3 — Tasks on web (PR #4) | 2026-10-16 | [features/tasks.md](features/tasks.md) | +| Track A — Self-host release (PR #7) | 2026-11-10 | [features/self-host.md](features/self-host.md) | ## Backlog diff --git a/docs/features/self-host.md b/docs/features/self-host.md new file mode 100644 index 0000000..e072ae9 --- /dev/null +++ b/docs/features/self-host.md @@ -0,0 +1,67 @@ +# Self-host release — Docker, config check, health page, release pipeline + +Shipped 2026-11-10 (roadmap Track A). Branch `feature/self-host`. Decisions 001, 019, 022, 023, 024. + +## What it does +- **Docker:** `docker compose up -d` runs Gitwork with a SQLite file on a named volume. An optional + `caddy` profile gets a TLS certificate. The image applies migrations at start and refuses to start + on a configuration error. +- **Config check:** every production start on Node logs each problem by variable name. The page + `/setup/health` shows the same list to instance admins. +- **Health page:** `/setup/health` (instance admins): version, runtime, database driver, + configuration, GitHub App, installations, last webhook, last reconcile. Database reads only. +- **Backup:** `node backup.mjs ` inside the container: SQLite `VACUUM INTO`, safe while running. +- **Cloudflare:** `pnpm deploy:cf` builds, applies D1 migrations, and deploys. +- **Release:** a `v*.*.*` tag publishes `ghcr.io/flywheelstudio/gitwork` (amd64 + arm64) and a + GitHub Release with generated notes. +- **Repo:** README, CONTRIBUTING (DCO), SECURITY, CODE_OF_CONDUCT, CHANGELOG, issue and PR + templates, a DCO check on pull requests, and the self-host guide (`docs/self-host/`). + +## How it works + +| File | Role | +|---|---| +| `Dockerfile` | Two stages: `pnpm install` + standalone `next build`, then `node:22-slim` as user `node`. Sets `DATABASE_URL`, `GITWORK_MIGRATIONS_DIR`, `GITWORK_FAIL_ON_CONFIG_ERROR`. | +| `apps/web/next.config.ts` | `GITWORK_STANDALONE=1` turns on `output: "standalone"`, traced from the repo root. Off by default, so `pnpm start` and OpenNext are unchanged. | +| `packages/server/src/config-check.ts` | `checkConfig(env, runtime)`: pure, names variables only. `instanceHealth()`: the health page's data. | +| `apps/web/src/server/runtime/runtime.node.ts` | `bootNode()`: config check, optional exit, migrations. The Worker runtime's `bootNode()` is a no-op. | +| `apps/web/src/instrumentation.ts` | Awaits `bootNode()` before the server takes requests, then starts the reconcile timer. | +| `apps/web/src/app/setup/health/page.tsx` | The health page. | +| `scripts/backup.mjs` | Finds `@libsql/client` under the standalone `node_modules/.pnpm` and runs `VACUUM INTO`. | +| `scripts/selfhost-check.sh` | The exit check minus GitHub: health on sqlite, email-code sign-in, `/setup` and `/setup/health` as admin. | +| `scripts/check-dco.sh` | Every non-merge commit in the PR carries `Signed-off-by:` matching its author. | +| `.github/workflows/ci.yml` (`docker` job) | Builds the image, runs the self-host check and a backup, and proves the image refuses to start unconfigured. | +| `.github/workflows/release.yml` | Tag → multi-arch image on GHCR + GitHub Release. | + +**Config rules.** Errors: missing or short (< 32) `BETTER_AUTH_SECRET`; missing or non-http(s) +`BETTER_AUTH_URL`; empty `INSTANCE_ADMIN_EMAILS`; an email transport that cannot send in production +(`smtp` without `SMTP_URL`, `console`, nothing; anything but `cloudflare` on Workers); a partial set +of the five GitHub App variables. Warnings: plain http on a public host, `outbox`, no `EMAIL_FROM`, +no `DATABASE_URL`, an unknown `GITWORK_SCHEDULER`. + +## Testing +- `config-check.test.ts`: every rule, both runtimes, values never in messages; `instanceHealth` on + both drivers (fresh database; installations without deleted ones; newest webhook; last run). +- E2E `setup.spec.ts`: an admin opens `/setup/health`, sees six rows and the outbox warning, and no + secret value; a non-admin gets 404. +- Local run of the standalone server laid out like the image: unconfigured start exits 1 and names + three variables; configured start migrates a fresh database and passes `selfhost-check.sh`; + `backup.mjs` writes a copy and refuses to overwrite it. +- `scripts/check-dco.sh` fails on the unsigned Phase 3 commits (proven red). +- `pnpm smoke` now fails above 10 MiB gzipped; today 3,496 KiB. +- **Not run locally:** `docker build` (no Docker on the dev machine). The CI `docker` job is the + first real build of the image. + +## Gotchas +- **iCloud Drive copies files** (`name 2.ext`) in a repo under `~/Documents`, including inside + `.next` and `.git`. A copied migration runs twice on D1. `scripts/check-repo.sh` (PR #5) guards + tracked files; keep the repo out of iCloud. +- **Standalone hides `@libsql/client`** under `node_modules/.pnpm/`. `backup.mjs` searches for it; + a one-line `require('@libsql/client')` fails. +- **E2E outbox race:** a second sign-in for the same email can read the first code. `signInCode(email, + emailCount(email))` waits for a newer email. +- **Deploy to Cloudflare button: not shipped.** Cloudflare's button wants the app isolated in one + folder; Gitwork's Worker depends on workspace packages. Proving it needs a real deploy to a + Cloudflare account (owner approval). `pnpm deploy:cf` is the documented path. +- **Private vulnerability reporting** must be turned on in the repo settings for SECURITY.md's link + to work (owner action). diff --git a/docs/self-host/README.md b/docs/self-host/README.md new file mode 100644 index 0000000..d6eafad --- /dev/null +++ b/docs/self-host/README.md @@ -0,0 +1,119 @@ +# Self-host Gitwork + +Gitwork runs on any Docker host (a SQLite file on a volume) or on Cloudflare Workers (D1). Pick one. +Either way you need four things: + +1. **A public https URL.** GitHub sends webhooks to it, and sign-in emails link to it. +2. **Email for sign-in codes.** SMTP on Docker; Cloudflare Email Service on Workers. +3. **Your admin email** in `INSTANCE_ADMIN_EMAILS`. That person opens `/setup`. +4. **A GitHub organization** where an owner can install the GitHub App that `/setup` creates. + +## Docker + +```bash +git clone https://github.com/FlywheelStudio/gitwork && cd gitwork +cp .env.example .env +``` + +Edit `.env`: + +| Variable | Value | +|---|---| +| `BETTER_AUTH_SECRET` | `openssl rand -base64 32`. Keep it: changing it locks out the stored GitHub App and linked accounts. | +| `BETTER_AUTH_URL` | Your public URL, for example `https://gitwork.example.com`. | +| `INSTANCE_ADMIN_EMAILS` | Your email. Commas separate several. | +| `EMAIL_TRANSPORT` | `smtp` | +| `SMTP_URL` | `smtp://user:password@smtp.example.com:587` (or `smtps://…:465`). | +| `EMAIL_FROM` | `Gitwork `. Use a domain your SMTP provider may send from. | + +Start it. Pick one: + +```bash +docker compose up -d # port 3000, behind your own proxy +GITWORK_DOMAIN=gitwork.example.com docker compose --profile caddy up -d # Caddy gets a TLS certificate +``` + +With the Caddy profile, also set `TRUSTED_IP_HEADER=x-real-ip` in `.env` (Caddy overwrites that +header). Behind another proxy, set it only if that proxy always overwrites the header. + +The container applies database migrations on every start, and **refuses to start** on a +configuration error. `docker compose logs gitwork` names the variable. + +Then open your URL, sign in with your admin email, and go to **/setup**. + +### Upgrade + +```bash +docker compose pull && docker compose up -d +``` + +Migrations run on start. Read the [release notes](https://github.com/FlywheelStudio/gitwork/releases) +first. Pin a version with `GITWORK_TAG=0.1.0` in `.env`. + +### Back up + +The database is one SQLite file on the `gitwork-data` volume. `backup.mjs` copies it with SQLite's +`VACUUM INTO`, which is safe while Gitwork runs: + +```bash +docker compose exec gitwork node backup.mjs /data/backup-$(date +%F).sqlite +docker compose cp gitwork:/data/backup-$(date +%F).sqlite . +``` + +Run it daily from cron. To restore, stop Gitwork, replace `gitwork.sqlite` with the backup, and +start it. Also keep `BETTER_AUTH_SECRET`: a backup without it cannot decrypt the stored GitHub App. + +## Cloudflare Workers + +Needs the **Workers Paid plan** (decision 022): the Worker is over the Free plan's 3 MiB. + +```bash +git clone https://github.com/FlywheelStudio/gitwork && cd gitwork +corepack enable && pnpm install +cd apps/web +pnpm exec wrangler d1 create gitwork # paste the database_id into wrangler.jsonc +``` + +In `apps/web/wrangler.jsonc`, set `EMAIL_FROM` to an address on a domain you onboarded to +[Cloudflare Email Service](https://developers.cloudflare.com/email-service/). Then set the secrets +and deploy: + +```bash +pnpm exec wrangler secret put BETTER_AUTH_SECRET # openssl rand -base64 32 +pnpm exec wrangler secret put BETTER_AUTH_URL # https://gitwork..workers.dev or your domain +pnpm exec wrangler secret put INSTANCE_ADMIN_EMAILS +cd ../.. && pnpm deploy:cf # build, migrate D1, deploy +``` + +`pnpm deploy:cf` runs D1 migrations before each deploy, so upgrades are `git pull` and +`pnpm deploy:cf`. D1 keeps 30 days of point-in-time history (Time Travel) for restores. Reconcile +runs from the Cron Trigger in `wrangler.jsonc`. + +If you rename the Worker, change `services[0].service` in `wrangler.jsonc` to the new name too. + +## Any other Node host + +Build with `GITWORK_STANDALONE=1 pnpm --filter @gitwork/web build`, or run the Docker image. Set the +same variables as for Docker, plus `DATABASE_URL=file:/path/to/gitwork.sqlite` on a persistent disk +and `GITWORK_MIGRATIONS_DIR` pointing at `packages/db/migrations`. One instance per SQLite file. + +## After the first start + +1. Sign in with your admin email. The code arrives by email. +2. **/setup → Create GitHub App.** GitHub asks you to confirm, then returns you to Gitwork. The App + is private to your organization. Its webhook URL is `BETTER_AUTH_URL/api/github/webhook`. +3. Install the App on your organization (an org owner must approve). Choose the repos. +4. Choose who may create accounts (setup step 3). Invites always work. +5. Create a workspace, link your GitHub account (Settings), then link a board and repos. +6. **/setup/health** shows the configuration, the GitHub App, the last webhook, and the last + reconcile. + +## Troubleshooting + +| Symptom | Cause | +|---|---| +| Container exits at start | A configuration error. `docker compose logs gitwork` names it. | +| No sign-in email | `SMTP_URL` or `EMAIL_FROM` is wrong. Check the SMTP provider's log. | +| "Last webhook: none" on /setup/health | GitHub cannot reach `BETTER_AUTH_URL`. Check the App's "Recent deliveries" on GitHub. | +| "Stored credentials cannot be decrypted" | `BETTER_AUTH_SECRET` changed. Restore it, or replace the App in /setup. | +| Tasks are stale | Check "Last reconcile" on /setup/health. Rate limits show there. | diff --git a/package.json b/package.json index 2cad5cb..db44113 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,8 @@ "smoke": "./scripts/smoke.sh", "db:migrate": "pnpm --filter @gitwork/web db:migrate", "db:generate": "pnpm --filter @gitwork/db generate", - "preview": "pnpm --filter @gitwork/web preview" + "preview": "pnpm --filter @gitwork/web preview", + "deploy:cf": "pnpm --filter @gitwork/web cf:deploy" }, "devDependencies": { "eslint": "9.39.5", diff --git a/packages/server/src/config-check.ts b/packages/server/src/config-check.ts new file mode 100644 index 0000000..3435cc3 --- /dev/null +++ b/packages/server/src/config-check.ts @@ -0,0 +1,128 @@ +import { githubInstallations, githubWebhookDeliveries, instanceSettings, type Database } from "@gitwork/db"; +import { count, desc, eq, isNull } from "drizzle-orm"; + +/** One problem with the instance configuration. Names the variable, never its value. */ +export interface ConfigIssue { + level: "error" | "warn"; + key: string; + message: string; +} + +export type RuntimeName = "node" | "workerd"; + +const GITHUB_KEYS = [ + "GITHUB_APP_ID", + "GITHUB_APP_PRIVATE_KEY", + "GITHUB_WEBHOOK_SECRET", + "GITHUB_CLIENT_ID", + "GITHUB_CLIENT_SECRET", +] as const; + +/** + * Checks the production configuration. An "error" stops sign-in or setup from working; a "warn" + * works but is probably a mistake. Messages name variables only, so the result is safe to log and + * to show an instance admin. + */ +export function checkConfig(env: Record, runtime: RuntimeName): ConfigIssue[] { + const issues: ConfigIssue[] = []; + const error = (key: string, message: string) => issues.push({ level: "error", key, message }); + const warn = (key: string, message: string) => issues.push({ level: "warn", key, message }); + + const secret = env.BETTER_AUTH_SECRET ?? ""; + if (!secret) error("BETTER_AUTH_SECRET", "Not set. Generate one with: openssl rand -base64 32"); + else if (secret.length < 32) error("BETTER_AUTH_SECRET", "Shorter than 32 characters."); + + const url = parseUrl(env.BETTER_AUTH_URL); + if (!env.BETTER_AUTH_URL) error("BETTER_AUTH_URL", "Not set. Use the public URL of this instance."); + else if (!url) error("BETTER_AUTH_URL", "Not an http(s) URL."); + else if (url.protocol === "http:" && !isLocal(url.hostname)) { + warn("BETTER_AUTH_URL", "Uses http. Sign-in cookies and GitHub webhooks need https in production."); + } + + if (!env.INSTANCE_ADMIN_EMAILS?.trim()) { + error("INSTANCE_ADMIN_EMAILS", "Not set. Nobody can open /setup or create the first account."); + } + + const transport = env.EMAIL_TRANSPORT ?? ""; + if (runtime === "workerd") { + if (transport !== "cloudflare") error("EMAIL_TRANSPORT", 'Must be "cloudflare" on Workers.'); + } else if (transport === "smtp") { + if (!env.SMTP_URL) error("SMTP_URL", 'Not set, but EMAIL_TRANSPORT is "smtp".'); + } else if (transport === "outbox") { + warn("EMAIL_TRANSPORT", '"outbox" writes sign-in codes to a file. Use it for tests only.'); + } else { + error("EMAIL_TRANSPORT", 'Must be "smtp" on Node hosts. Nobody can sign in without email.'); + } + if (!env.EMAIL_FROM) warn("EMAIL_FROM", "Not set. Sign-in emails come from no-reply@localhost."); + + const set = GITHUB_KEYS.filter((key) => env[key]); + if (set.length > 0 && set.length < GITHUB_KEYS.length) { + const missing = GITHUB_KEYS.filter((key) => !env[key]); + error(missing.join(", "), "Set all five GitHub App variables, or none and use /setup."); + } + + if (runtime === "node") { + if (!env.DATABASE_URL) warn("DATABASE_URL", "Not set. Using file:.data/gitwork.sqlite in the working directory."); + const scheduler = env.GITWORK_SCHEDULER; + if (scheduler && scheduler !== "off") warn("GITWORK_SCHEDULER", 'Only "off" has a meaning. Leave it empty to reconcile.'); + } + return issues; +} + +function parseUrl(value: string | undefined): URL | null { + if (!value) return null; + try { + const url = new URL(value); + return url.protocol === "http:" || url.protocol === "https:" ? url : null; + } catch { + return null; + } +} + +function isLocal(hostname: string): boolean { + return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname.endsWith(".localhost"); +} + +export interface InstanceHealth { + issues: ConfigIssue[]; + driver: string; + installations: number; + lastWebhookAt: Date | null; + lastReconcile: { at: string; status: string; message?: string } | null; +} + +/** What the admin health page shows. Reads the database only; no GitHub calls. */ +export async function instanceHealth( + database: Database, + env: Record, + runtime: RuntimeName, +): Promise { + const { db } = database; + const [installs] = await db.select({ n: count() }).from(githubInstallations).where(isNull(githubInstallations.deletedAt)); + const [hook] = await db + .select({ at: githubWebhookDeliveries.receivedAt }) + .from(githubWebhookDeliveries) + .orderBy(desc(githubWebhookDeliveries.receivedAt)) + .limit(1); + const [run] = await db + .select({ value: instanceSettings.value }) + .from(instanceSettings) + .where(eq(instanceSettings.key, "reconcile_last_run")); + return { + issues: checkConfig(env, runtime), + driver: database.driver, + installations: installs?.n ?? 0, + lastWebhookAt: hook?.at ?? null, + lastReconcile: run ? parseRun(run.value) : null, + }; +} + +function parseRun(value: string): InstanceHealth["lastReconcile"] { + try { + const run = JSON.parse(value) as { at?: unknown; status?: unknown; message?: unknown }; + if (typeof run.at !== "string" || typeof run.status !== "string") return null; + return { at: run.at, status: run.status, ...(typeof run.message === "string" ? { message: run.message } : {}) }; + } catch { + return null; + } +} diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index 3058a59..2e413c2 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -10,6 +10,7 @@ export { } from "./email"; export { getSignupPolicy, setSignupPolicy, type SignupPolicy } from "./instance-settings"; export { signInEmail } from "./sign-in-email"; +export { type ConfigIssue, type InstanceHealth, type RuntimeName, checkConfig, instanceHealth } from "./config-check"; export { mayCreateUser } from "./signup"; export { ServiceError } from "./errors"; export { diff --git a/packages/server/test/config-check.test.ts b/packages/server/test/config-check.test.ts new file mode 100644 index 0000000..c2c6272 --- /dev/null +++ b/packages/server/test/config-check.test.ts @@ -0,0 +1,110 @@ +import { githubInstallations, githubWebhookDeliveries, instanceSettings } from "@gitwork/db"; +import { allTestDrivers } from "@gitwork/db/testing"; +import { afterAll, describe, expect, it } from "vitest"; +import { checkConfig, instanceHealth } from "../src/config-check"; + +const GOOD_NODE = { + BETTER_AUTH_SECRET: "a".repeat(44), + BETTER_AUTH_URL: "https://gitwork.example", + INSTANCE_ADMIN_EMAILS: "admin@example.com", + EMAIL_TRANSPORT: "smtp", + SMTP_URL: "smtp://user:pass@mail.example:587", + EMAIL_FROM: "Gitwork ", + DATABASE_URL: "file:/data/gitwork.sqlite", +}; +const GOOD_WORKER = { ...GOOD_NODE, EMAIL_TRANSPORT: "cloudflare", SMTP_URL: undefined, DATABASE_URL: undefined }; + +const keys = (env: Record, runtime: "node" | "workerd" = "node", level = "error") => + checkConfig(env, runtime) + .filter((i) => i.level === level) + .map((i) => i.key); + +describe("checkConfig", () => { + it("passes a complete Node configuration", () => { + expect(checkConfig(GOOD_NODE, "node")).toEqual([]); + }); + + it("passes a complete Worker configuration", () => { + expect(checkConfig(GOOD_WORKER, "workerd")).toEqual([]); + }); + + it("fails an empty configuration on every required variable", () => { + expect(keys({})).toEqual(["BETTER_AUTH_SECRET", "BETTER_AUTH_URL", "INSTANCE_ADMIN_EMAILS", "EMAIL_TRANSPORT"]); + }); + + it("fails a short secret", () => { + expect(keys({ ...GOOD_NODE, BETTER_AUTH_SECRET: "short" })).toEqual(["BETTER_AUTH_SECRET"]); + }); + + it("fails a URL that is not http(s), and warns on plain http for a public host", () => { + expect(keys({ ...GOOD_NODE, BETTER_AUTH_URL: "ftp://x.example" })).toEqual(["BETTER_AUTH_URL"]); + expect(keys({ ...GOOD_NODE, BETTER_AUTH_URL: "not a url" })).toEqual(["BETTER_AUTH_URL"]); + expect(keys({ ...GOOD_NODE, BETTER_AUTH_URL: "http://gitwork.example" }, "node", "warn")).toEqual(["BETTER_AUTH_URL"]); + expect(checkConfig({ ...GOOD_NODE, BETTER_AUTH_URL: "http://localhost:3000" }, "node")).toEqual([]); + }); + + it("fails smtp without SMTP_URL, console in production, and anything but cloudflare on Workers", () => { + expect(keys({ ...GOOD_NODE, SMTP_URL: undefined })).toEqual(["SMTP_URL"]); + expect(keys({ ...GOOD_NODE, EMAIL_TRANSPORT: "console" })).toEqual(["EMAIL_TRANSPORT"]); + expect(keys({ ...GOOD_WORKER, EMAIL_TRANSPORT: "smtp" }, "workerd")).toEqual(["EMAIL_TRANSPORT"]); + expect(keys({ ...GOOD_NODE, EMAIL_TRANSPORT: "outbox" }, "node", "warn")).toEqual(["EMAIL_TRANSPORT"]); + }); + + it("fails a partial set of GitHub App variables and names the missing ones", () => { + const issues = checkConfig({ ...GOOD_NODE, GITHUB_APP_ID: "1", GITHUB_CLIENT_ID: "Iv1.x" }, "node"); + expect(issues).toEqual([ + expect.objectContaining({ level: "error", key: "GITHUB_APP_PRIVATE_KEY, GITHUB_WEBHOOK_SECRET, GITHUB_CLIENT_SECRET" }), + ]); + }); + + it("accepts all five GitHub App variables", () => { + const all = { + GITHUB_APP_ID: "1", + GITHUB_APP_PRIVATE_KEY: "k", + GITHUB_WEBHOOK_SECRET: "w", + GITHUB_CLIENT_ID: "c", + GITHUB_CLIENT_SECRET: "s", + }; + expect(checkConfig({ ...GOOD_NODE, ...all }, "node")).toEqual([]); + }); + + it("never puts a value in a message", () => { + const env = { ...GOOD_NODE, BETTER_AUTH_SECRET: "tiny-secret-value", SMTP_URL: undefined, GITHUB_APP_ID: "12345" }; + const text = JSON.stringify(checkConfig(env, "node")); + expect(text).not.toContain("tiny-secret-value"); + expect(text).not.toContain("12345"); + }); +}); + +const drivers = await allTestDrivers(); +afterAll(() => Promise.all(drivers.map((d) => d.dispose()))); + +describe.each(drivers)("instanceHealth on $name", (driver) => { + it("reports nothing on a fresh database", async () => { + const database = await driver.fresh(); + const health = await instanceHealth(database, GOOD_NODE, "node"); + expect(health).toEqual({ issues: [], driver: driver.name, installations: 0, lastWebhookAt: null, lastReconcile: null }); + }); + + it("reports installations, the newest webhook, and the last reconcile run", async () => { + const database = await driver.fresh(); + const { db } = database; + await db.insert(githubInstallations).values([ + { id: 9, accountLogin: "acme", accountId: 1, accountType: "Organization" }, + { id: 10, accountLogin: "gone", accountId: 2, accountType: "Organization", deletedAt: new Date(2_000) }, + ]); + await db.insert(githubWebhookDeliveries).values([ + { deliveryId: "a", event: "ping", receivedAt: new Date(1_000) }, + { deliveryId: "b", event: "issues", receivedAt: new Date(5_000) }, + ]); + await db.insert(instanceSettings).values({ + key: "reconcile_last_run", + value: JSON.stringify({ at: "2026-11-10T00:00:00.000Z", status: "error", message: "rate limited" }), + }); + const health = await instanceHealth(database, {}, "node"); + expect(health.installations).toBe(1); + expect(health.lastWebhookAt?.getTime()).toBe(5_000); + expect(health.lastReconcile).toEqual({ at: "2026-11-10T00:00:00.000Z", status: "error", message: "rate limited" }); + expect(health.issues.length).toBeGreaterThan(0); + }); +}); diff --git a/scripts/backup.mjs b/scripts/backup.mjs new file mode 100644 index 0000000..fcad7c7 --- /dev/null +++ b/scripts/backup.mjs @@ -0,0 +1,29 @@ +// Online backup of the SQLite database, safe while Gitwork runs (VACUUM INTO). +// The Docker image ships this as /app/backup.mjs: +// docker compose exec gitwork node backup.mjs /data/backup.sqlite +// Reads DATABASE_URL (file:...). Refuses to overwrite an existing file. +import { existsSync, readdirSync } from "node:fs"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; + +const target = process.argv[2]; +if (!target) { + console.error("usage: node backup.mjs "); + process.exit(2); +} +if (existsSync(target)) { + console.error(`${target} exists; choose a new name`); + process.exit(1); +} +const url = process.env.DATABASE_URL ?? "file:/data/gitwork.sqlite"; +// The standalone server keeps the libsql client under node_modules/.pnpm. +const store = fileURLToPath(new URL("./node_modules/.pnpm/", import.meta.url)); +const dir = readdirSync(store).find((name) => name.startsWith("@libsql+client@")); +if (!dir) { + console.error(`no @libsql/client under ${store}`); + process.exit(1); +} +const require = createRequire(import.meta.url); +const { createClient } = require(`${store}${dir}/node_modules/@libsql/client`); +await createClient({ url }).execute({ sql: "VACUUM INTO ?", args: [target] }); +console.log(`backed up ${url} to ${target}`); diff --git a/scripts/check-dco.sh b/scripts/check-dco.sh new file mode 100755 index 0000000..1aab6ef --- /dev/null +++ b/scripts/check-dco.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# Every non-merge commit in .. must carry a DCO sign-off by its author (decision 024). +# usage: check-dco.sh +set -euo pipefail +base="${1:?base}"; head="${2:?head}"; fail=0 +for sha in $(git rev-list --no-merges "$base..$head"); do + author=$(git log -1 --format='%an <%ae>' "$sha") + if ! git log -1 --format='%B' "$sha" | grep -qiF "Signed-off-by: $author"; then + echo "FAIL: $(git log -1 --format='%h %s' "$sha") has no 'Signed-off-by: $author'"; fail=1 + fi +done +[ "$fail" -eq 0 ] && echo "dco: every commit is signed off" +[ "$fail" -eq 0 ] || echo "Fix: git rebase --signoff $base, then push. See CONTRIBUTING.md." +exit "$fail" diff --git a/scripts/selfhost-check.sh b/scripts/selfhost-check.sh new file mode 100755 index 0000000..31adce2 --- /dev/null +++ b/scripts/selfhost-check.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# The Phase 7 exit check, minus GitHub: a fresh self-host answers health on the SQLite driver and +# completes an email-code sign-in for an instance admin, which can then open /setup. +# usage: selfhost-check.sh +# The instance must run with EMAIL_TRANSPORT=outbox and EMAIL_OUTBOX_PATH=. +set -euo pipefail +B="${1:?base url}"; OUTBOX="${2:?outbox file}"; EMAIL="${3:?admin email}" + +health=$(curl -sf --retry-connrefused --retry 90 --retry-delay 1 --retry-max-time 120 "$B/api/v1/health") +echo " health -> $health" +[[ "$health" == *'"driver":"sqlite"'* ]] || { echo "FAIL: health did not report the sqlite driver"; exit 1; } + +post() { curl -sf -X POST "$B$1" -H "origin: $B" -H "content-type: application/json" "${@:2}"; } +post /api/auth/email-otp/send-verification-otp -d "{\"email\":\"$EMAIL\",\"type\":\"sign-in\"}" >/dev/null +code="" +for _ in $(seq 1 50); do + code=$(grep -F "\"$EMAIL\"" "$OUTBOX" 2>/dev/null | tail -1 | grep -oE 'sign-in code is [0-9]{6}' | grep -oE '[0-9]{6}$' || true) + [ -n "$code" ] && break + sleep 0.2 +done +[ -n "$code" ] || { echo "FAIL: no sign-in code in $OUTBOX"; exit 1; } +cookie=$(post /api/auth/sign-in/email-otp -D - -o /dev/null -d "{\"email\":\"$EMAIL\",\"otp\":\"$code\"}" \ + | grep -i '^set-cookie:' | cut -d' ' -f2 | cut -d';' -f1 | paste -sd';' -) +me=$(curl -sf "$B/api/v1/me" -H "cookie: $cookie") +echo " me -> $me" +[[ "$me" == *"\"email\":\"$EMAIL\""* ]] || { echo "FAIL: sign-in did not produce a session"; exit 1; } +setup=$(curl -s -o /dev/null -w '%{http_code}' "$B/setup" -H "cookie: $cookie") +echo " /setup -> $setup" +[ "$setup" = 200 ] || { echo "FAIL: the instance admin cannot open /setup"; exit 1; } +health_page=$(curl -s -o /dev/null -w '%{http_code}' "$B/setup/health" -H "cookie: $cookie") +echo " /setup/health -> $health_page" +[ "$health_page" = 200 ] || { echo "FAIL: the instance admin cannot open /setup/health"; exit 1; } +echo "selfhost-check: OK" diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 2f3cd02..09df724 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -40,7 +40,12 @@ echo "== worker" pnpm cf:build ../../scripts/scan-worker-bundle.sh .open-next # The deployable bundle is worker.ts wrapped around .open-next: scan what wrangler would upload. -rm -rf .wrangler/dry && pnpm exec wrangler deploy --dry-run --outdir .wrangler/dry >/dev/null +rm -rf .wrangler/dry && dry=$(pnpm exec wrangler deploy --dry-run --outdir .wrangler/dry 2>&1) +# The Workers Paid plan allows 10 MiB gzipped per Worker (decision 022). Fail before a deploy would. +gzip_kib=$(echo "$dry" | grep -oE 'gzip: [0-9.]+ KiB' | tail -1 | grep -oE '[0-9.]+') +[ -n "$gzip_kib" ] || { echo "FAIL: wrangler did not report the bundle size"; echo "$dry" | tail -20; exit 1; } +echo " worker bundle: ${gzip_kib} KiB gzipped (limit 10240)" +awk -v k="$gzip_kib" 'BEGIN { exit !(k <= 10240) }' || { echo "FAIL: worker bundle over 10 MiB gzipped"; exit 1; } ../../scripts/scan-worker-bundle.sh .wrangler/dry pnpm cf:migrate:local rm -rf .wrangler/tmp/email From dfbd86681c5a711d03683db239154dc71c5dfaf3 Mon Sep 17 00:00:00 2001 From: Erik Goins Date: Tue, 10 Nov 2026 08:58:48 -0500 Subject: [PATCH 2/3] fix: self-host check retries on any error while the container starts Docker's port proxy resets the connection (curl exit 56) before the server listens. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T7sHybpLbFAyRXzPFkfWun Signed-off-by: Erik Goins --- scripts/selfhost-check.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/selfhost-check.sh b/scripts/selfhost-check.sh index 31adce2..83dadb3 100755 --- a/scripts/selfhost-check.sh +++ b/scripts/selfhost-check.sh @@ -6,7 +6,7 @@ set -euo pipefail B="${1:?base url}"; OUTBOX="${2:?outbox file}"; EMAIL="${3:?admin email}" -health=$(curl -sf --retry-connrefused --retry 90 --retry-delay 1 --retry-max-time 120 "$B/api/v1/health") +health=$(curl -sf --retry-all-errors --retry 90 --retry-delay 1 --retry-max-time 120 "$B/api/v1/health") echo " health -> $health" [[ "$health" == *'"driver":"sqlite"'* ]] || { echo "FAIL: health did not report the sqlite driver"; exit 1; } From fa5188a66427e9e41cd229bc015cb388e930d87a Mon Sep 17 00:00:00 2001 From: Erik Goins Date: Tue, 10 Nov 2026 09:00:42 -0500 Subject: [PATCH 3/3] =?UTF-8?q?docs:=20correct=20the=20iCloud=20fix=20?= =?UTF-8?q?=E2=80=94=20move=20the=20whole=20Flywheel=20tree=20or=20stop=20?= =?UTF-8?q?sync?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01T7sHybpLbFAyRXzPFkfWun Signed-off-by: Erik Goins --- docs/STATE.md | 6 ++++-- docs/features/self-host.md | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/STATE.md b/docs/STATE.md index 789fc46..835df1b 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -9,7 +9,9 @@ Last updated: 2026-11-10 - Open PRs: #5 (decisions 020–022, iCloud copies removed), #6 (roadmap), #7 (self-host, Track A). - **Live GitHub check: still not done.** The session's permission rules block a `cloudflared` tunnel. The owner must start the tunnel or allow it. See Chores. -- **Move the repo out of `~/Documents`.** iCloud copies files, including inside `.git`. +- **iCloud copies files in this repo**, even inside `.git`. Fix: turn off iCloud Desktop & Documents + sync, or move the whole `~/Documents/Flywheel` tree (not only `gitwork`: CLAUDE.md discovery and + the `../../conventions` import depend on it) and copy the Claude memory folder to the new path key. - **Before any work:** `git fetch origin && git status -sb`. - **Toolchain:** pnpm comes from corepack. Run checks from the repo root: `pnpm lint && pnpm typecheck && pnpm test && pnpm test:e2e && pnpm smoke`. @@ -27,7 +29,7 @@ Track B + C + D (speed, keyboard, layout) — next after PR #7. | Phase 1 — Identity | 2026-10-15 | [features/identity.md](features/identity.md) | | Phase 2 — GitHub App (PR #3) | 2026-10-15 | [features/github-app.md](features/github-app.md) | | Phase 3 — Tasks on web (PR #4) | 2026-10-16 | [features/tasks.md](features/tasks.md) | -| Track A — Self-host release (PR #7) | 2026-11-10 | [features/self-host.md](features/self-host.md) | +| Track A — Self-host release (PR #7, in review; GitHub half of the exit check waits on the live check) | 2026-11-10 | [features/self-host.md](features/self-host.md) | ## Backlog diff --git a/docs/features/self-host.md b/docs/features/self-host.md index e072ae9..bfd4aa4 100644 --- a/docs/features/self-host.md +++ b/docs/features/self-host.md @@ -55,7 +55,8 @@ no `DATABASE_URL`, an unknown `GITWORK_SCHEDULER`. ## Gotchas - **iCloud Drive copies files** (`name 2.ext`) in a repo under `~/Documents`, including inside `.next` and `.git`. A copied migration runs twice on D1. `scripts/check-repo.sh` (PR #5) guards - tracked files; keep the repo out of iCloud. + tracked files. Turn off iCloud Desktop & Documents sync, or move the whole `~/Documents/Flywheel` + tree (moving only this repo breaks CLAUDE.md discovery and the `../../conventions` import). - **Standalone hides `@libsql/client`** under `node_modules/.pnpm/`. `backup.mjs` searches for it; a one-line `require('@libsql/client')` fails. - **E2E outbox race:** a second sign-in for the same email can read the first code. `signInCode(email,