diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8bc3419 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +* text=auto eol=lf + +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.webp binary +*.tgz binary diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index c66cc5b..ddda77d 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -27,7 +27,10 @@ jobs: cache: npm - run: npm ci - run: npm run check - - run: npm test + # Keep production Pages deploys on the Node suite. The Workers/D1 pool + # suite stays in CI via `npm test` so workerd/pool flakes cannot block + # an otherwise unrelated site deploy. + - run: npm run test:node - run: npm run build # Migration 0001 is already applied remotely. Keep deployment fail-closed # until a separately least-privileged D1 token exists for future changes. diff --git a/docs/GITHUB_RELEASE_WEBHOOK_PLAN.md b/docs/GITHUB_RELEASE_WEBHOOK_PLAN.md new file mode 100644 index 0000000..e5e64e3 --- /dev/null +++ b/docs/GITHUB_RELEASE_WEBHOOK_PLAN.md @@ -0,0 +1,535 @@ +# GitHub Release Webhook Plan + +## Status + +**Stage:** Phase A complete (2026-07-28). No GitHub organization webhook, +Cloudflare secret, or production release configuration has been activated +yet. Phases B–E remain open. + +**Phase A reconciliation (2026-07-28):** `@pegma/webhooks` is pinned to +`@pegma/storage-core@0.4.0` (commit `1e5ef0732c3595ea82cb80394cf55cd9a0442318`). +pegma.dev vendors that exact `npm pack` artifact under +`vendor/@pegma/webhooks/` with SHA-256 and integrity recorded in +`PROVENANCE.md`. Ledger smoke tests exercise `createMemoryStore()` and the +production D1 composition (`createSchemaIfMissing: false` over the generic +Pegma storage schema). No D1 schema migration is required for new Storage +Core collections. The host still nests `@pegma/storage-core@0.3.0` under +published `@pegma/health`, `@pegma/rate-limit`, and `@pegma/sessions` pins — +pre-existing on `main`, with no newer published releases that declare 0.4.0. +Phase A closes the Webhooks/host Store contract gap; republishing those three +packages is separate host debt, not a webhook-handler prerequisite. The +vendored package README carries only the MIT copyright line for +RetireGolden, LLC — no consumer-migration or commercial planning text. + +**Goal:** Keep the public release version and release date for Pegma +components current on pegma.dev without a content commit, Pages build, or site +deployment for each release. + +**Recommended implementation:** GitHub sends organization-level `release` +webhooks to the existing `pegma-dev-api` Worker. The Worker authenticates the +delivery, records it through `@pegma/webhooks`, projects the small public +release summary into the existing D1-backed `Store`, and exposes that summary +through a same-origin read endpoint. The Pages-hosted site loads the endpoint +at runtime. + +This is deliberately not a GitHub Actions pipeline that asks Pages to rebuild. +Such a pipeline would remove the content commit but still deploy the site and +would not exercise `@pegma/webhooks`. + +## Why this belongs here + +The integration is a real production use case rather than a demonstration: +pegma.dev is the ecosystem's public status surface, GitHub releases are the +authoritative release facts, and those facts should not wait for a second +content lifecycle. + +It also adds useful evidence for two Pegma components: + +- Webhooks runs against a second provider, host, cloud, and storage adapter: + GitHub on Cloudflare/D1 rather than Stripe on Azure Tables. +- Storage Core's D1 adapter carries another independently useful collection + and concurrency path in production. + +It does **not** by itself prove every Webhooks Phase 3 claim: + +- Stripe and GitHub remain in different hosts, so this does not exercise two + provider partitions inside one physical host. +- GitHub does not automatically retry failed webhook deliveries. Manual or + API-driven redelivery can test deduplication and failure counting, but it is + weaker evidence for automatic retry storms and quarantine ergonomics. + +The Webhooks project plan must therefore describe this as a second real +provider and portability result. It must not call the existing same-host +multi-source acceptance criterion complete unless that criterion is +deliberately revised. + +## Current baseline and prerequisites + +pegma.dev already has the pieces this design should reuse: + +- `pegma-dev-api` is routed at `pegma.dev/api/*`. +- The Worker constructs a Storage Core `Store` through + `@pegma/storage-cloudflare-d1`. +- D1 schema creation is deployment-managed and disabled on request paths. +- Cloudflare Workers Logs and the optional Datadog logger are composed through + the Spine `Logger` port. +- A scheduled handler and durable maintenance cursors already exist. +- The static site's CSP permits same-origin scripts, so it can read a + same-origin JSON endpoint without admitting third-party script execution. + +Before implementation: + +1. Align Webhooks with the exact Storage Core version used by pegma.dev. + Webhooks currently pins `@pegma/storage-core@0.3.0`; pegma.dev and its D1 + adapter use `0.4.0`. Do not install parallel Storage Core contracts and + assume structural compatibility. +2. Run the Webhooks memory and real-Azurite suites after the pin change, then + exercise the exact packed artifact against the D1 adapter in pegma.dev. +3. Because `@pegma/webhooks` is unpublished, consume a byte-reproducible + `npm pack` artifact from an identified Webhooks commit. Record its commit, + SHA-256, npm integrity, and reproduction command beside the vendored + artifact. Remove this bridge after the first package release. +4. Confirm that adding new Storage Core collections needs no D1 schema change. + The current adapter uses the generic Pegma storage schema; if that + assumption is false, stop and use the repository's fail-closed migration + process before changing production. +5. Decide whether the first UI is a release section on the Stack page or a + dedicated Releases page. Recommendation: show compact current-version + facts on Stack and link each value to its GitHub release. + +## Architecture + +```text +GitHub organization release event + | + v +POST /api/webhooks/github/releases + - bounded raw body + - HMAC-SHA256 verification + - event, organization, and repository allowlists + | + v +@pegma/webhooks ledger (source: "github") + | + v +Idempotent current-release projection in the existing D1 Store + | + v +GET /api/releases + | + v +Pages-hosted Stack/Releases UI +``` + +The request path never calls the GitHub REST API and never triggers a Pages +deployment. + +## Webhook boundary + +Add one Worker route: + +`POST /api/webhooks/github/releases` + +Processing order is load-bearing: + +1. Require `POST` and `application/json`. +2. Reject a declared or streamed body larger than 1 MiB before JSON parsing. + GitHub's global payload ceiling is much larger, but a release event should + never need it. +3. Read the raw bytes once. +4. Verify `X-Hub-Signature-256` over those exact bytes using a high-entropy + Cloudflare-managed secret and Web Crypto HMAC-SHA256. +5. Require `X-GitHub-Event: release` and a valid + `X-GitHub-Delivery` GUID. +6. Parse JSON only after authenticity, headers, and size checks pass. +7. Require the expected GitHub organization ID and an explicit allowlist of + repository IDs from the parsed payload. Stable numeric IDs are the + authority; names are display data and may change. +8. Pass the delivery GUID to the Webhooks ledger as the event ID and a static + event type such as `github.release.published`. + +`ping` deliveries may receive an authenticated `204` without entering the +release ledger. All other event families receive a non-success response or an +explicit ignored response according to the final endpoint contract; do not +silently broaden the endpoint into an organization-event collector. + +Signature verification remains host code. It does not move into +`@pegma/webhooks`. + +## Release projection + +The Webhooks receipt and public release summary are different records: + +- The receipt proves whether one GitHub delivery completed and contains no + provider payload. +- The release projection supplies the public facts pegma.dev renders. + +Declare a release collection through Storage Core. One current stable release +per repository is sufficient for the first slice. + +Suggested public record: + +```ts +interface ComponentRelease { + readonly repositoryId: string; + readonly repositoryName: string; + readonly releaseId: string; + readonly tagName: string; + readonly publishedAt: string; + readonly releaseUrl: string; + readonly observedAt: string; +} +``` + +Rules: + +- Key the record by stable repository ID. +- Treat `tagName` as the displayed version. Do not silently parse or normalize + it as SemVer. +- Store only the fields above. Do not persist the webhook payload, release + body, actor, assets, commit message, or other provider data. +- Accept only public, non-draft, non-prerelease releases for the initial UI. +- Handle the relevant `published`, `released`, and `edited` actions as + idempotent upserts of the **current** stable release only when the + incoming release is newer than the stored record (compare `publishedAt`, + then `releaseId` as a tie-breaker). An `edited` delivery for an older + release must not displace a newer current record; if it matches the + stored `releaseId`, update the stored fields in place. +- Handle `unpublished` and `deleted` by removing or invalidating the matching + current record **only when** the event's `releaseId` matches the stored + current release, then let reconciliation select the preceding stable + release. +- Ignore draft and prerelease actions after recording an authenticated + delivery outcome. +- Construct or validate GitHub links against `https://github.com/pegma-dev/`; + do not render an arbitrary URL from the payload. + +The release projection write and receipt transition are not cross-collection +atomic. The projection must therefore be idempotent on its own. A crash after +the projection succeeds but before `markProcessed` must make a redelivery +harmless. + +## Webhooks ledger behavior + +Construct one ledger over the Worker's existing Store: + +```ts +createWebhookLedger({ + store, + source: "github", + logger, +}); +``` + +Expected handler flow: + +1. `begin(deliveryId, eventType)`. +2. If the receipt is already `processed` or `quarantined`, acknowledge without + applying the projection again. +3. Apply the idempotent release projection. +4. `markProcessed(deliveryId)`. +5. On a processing failure, call `markFailed(deliveryId)`. +6. Return a failure while the receipt remains retryable; acknowledge only + after the package reports quarantine. + +GitHub does not automatically redeliver failures, so the fifth and sixth steps +mainly govern manual or API-driven redelivery. Quarantine logs remain useful, +but scheduled reconciliation is the real missed-delivery recovery mechanism +for this provider. + +Do not change the package's honest concurrency posture. Two overlapping +deliveries may both project the same release, and the projection must tolerate +that. + +## Read API and site behavior + +Add: + +`GET /api/releases` + +The response contains only allowlisted repositories and their current stable +release summaries, in the component registry's display order. Requirements: + +- return JSON with an explicit schema/version; +- include a server observation timestamp; +- use an ETag or a short public cache lifetime, initially no more than five + minutes; +- set `X-Content-Type-Options: nosniff`; +- never expose receipt rows, delivery IDs, quarantine internals, secrets, or + operator diagnostics; +- return an empty-but-valid result when no release exists for an allowed + repository. + +The static page uses a same-origin external module to fetch this endpoint and +replace a clearly labelled loading state. If the API is unavailable or +JavaScript is disabled, each component still shows its repository link and +the page remains usable. No third-party scripts or analytics are introduced. + +The initial content deployment adds the shell once. Later release events +change D1 data only; they do not change or redeploy site content. + +## Initial backfill and reconciliation + +Webhooks only observe events created after the organization webhook is +enabled. Seed existing releases before exposing the UI. + +Use GitHub's public Releases API to fetch the latest public stable release for +each allowlisted repository and pass it through the same release-projection +function used by webhook ingestion. Reconciliation does not fabricate +Webhooks receipt rows because it is not a webhook delivery. + +Add a separate scheduled cadence, recommended every six hours. Dispatch by the +Cron expression so the existing one-minute Identity maintenance remains +independent. Reconciliation should: + +1. fetch only allowlisted public repositories; +2. use conditional requests where available; +3. bound response sizes and request timeouts; +4. upsert the authoritative latest stable release; +5. remove a local record when the repository has no public stable release; +6. persist a cursor or last-success marker; +7. log counts and classifications without response bodies. + +Public unauthenticated GitHub API access is sufficient at the current +repository count. If its limit becomes operationally inadequate, use a +least-privileged GitHub App installation token; do not introduce a broad +personal token. + +## Operational visibility + +Extend health detail without exposing sensitive state: + +- release ingestion configured; +- last successful release webhook time; +- last successful reconciliation time; +- reconciliation stale/not stale; +- number of current release summaries. + +Use the existing Spine logger composition for: + +- signature rejection classification; +- disallowed event/repository classification; +- processed, duplicate, and quarantined delivery counts; +- reconciliation success/failure and record counts. + +Do not log raw bodies, signatures, release bodies, actors, or secrets. + +An operator can inspect quarantined receipt rows in D1. Do not add a public +replay or acknowledgement endpoint. + +## Security review requirements + +This work adds an unauthenticated Internet-facing Worker route (webhook +ingestion and a public release read endpoint) and therefore requires the +repository's security diff workflow before deployment. +Review at least: + +- raw-body HMAC verification and constant-time comparison; +- missing, malformed, rotated, and incorrect secrets; +- body-length and content-type enforcement; +- organization and stable repository-ID allowlists; +- replay and duplicate delivery behavior; +- out-of-order release actions; +- arbitrary URL injection into rendered links; +- JSON and HTML output encoding; +- log and persistence data boundaries; +- failure behavior before and after quarantine; +- interaction with existing Identity routes and shared D1 resources; +- cross-origin behavior of the public read endpoint and webhook POST route. + +The GitHub webhook secret is installed directly as a managed Worker secret. +It never enters GitHub Actions, the repository, Pages output, health detail, +or logs. Document a coordinated rotation procedure because GitHub +organization webhooks expose one active secret at a time. + +## Implementation phases + +### Phase A - dependency alignment and exact artifact + +Repositories: Webhooks, pegma.dev. + +- Align Webhooks to `@pegma/storage-core@0.4.0`. +- Run its format, type, memory, and real-Azurite gates. +- Pack the exact verified Webhooks commit. +- Vendor and pin the artifact in pegma.dev with provenance and integrity. +- Prove the package runs over `createMemoryStore()` and the D1 adapter. + +Exit: one exact package shape passes both Webhooks' existing backends and +pegma.dev's current Storage Core/D1 composition. + +### Phase B - release catalog and webhook handler + +Repository: pegma.dev. + +- Add the release collection and codec. +- Add the pure action-to-projection logic. +- Add GitHub header/body parsing and HMAC verification. +- Compose the GitHub ledger over the existing production Store. +- Route `POST /api/webhooks/github/releases`. +- Add unit and integration tests. + +Exit: signed fixtures update the release catalog exactly once, duplicates are +harmless, invalid traffic has no storage effect, and no payload field crosses +the codec. + +### Phase C - read surface and UI + +Repository: pegma.dev. + +- Add `GET /api/releases`. +- Add the accessible static shell and same-origin runtime fetch. +- Add loading, empty, stale, and unavailable states. +- Add endpoint and page tests. + +Exit: release facts appear from D1 without a Pages content change and the page +remains useful when the API is unavailable. + +### Phase D - recovery and operations + +Repository: pegma.dev. + +- Add initial backfill. +- Add six-hour reconciliation beside, not inside, minute Identity maintenance. +- Extend health and structured logs. +- Document secret installation, organization webhook configuration, + redelivery, reconciliation, and rollback. + +Exit: a missed or deleted GitHub delivery converges to GitHub's current stable +release state without operator database edits. + +### Phase E - production activation + +External configuration: Cloudflare and GitHub organization. + +1. Run the complete site and Worker gate. +2. Complete the security diff review. +3. Install the Worker secret. +4. Deploy the Worker before configuring GitHub. +5. Backfill and verify `GET /api/releases`. +6. Create one organization webhook subscribed only to release events. +7. Verify the authenticated `ping`. +8. Publish or redeliver a controlled release event. +9. Confirm the page changes without a commit, Pages build, or Pages deploy. +10. Confirm duplicate redelivery is acknowledged without changing the + projection. +11. Observe logs, D1 rows, health, and scheduled reconciliation. + +Exit: a real stable Pegma release updates pegma.dev within the webhook and +cache latency budget, and reconciliation repairs a deliberately missed +delivery. + +## Test matrix + +The mechanized evidence must cover: + +- GitHub's published HMAC fixture; +- absent, malformed, and invalid signatures; +- wrong method, content type, event family, organization, and repository; +- missing/malformed delivery GUID; +- declared and streamed oversized bodies; +- stable release publish and edit; +- draft and prerelease exclusion; +- unpublish/delete followed by reconciliation; +- duplicate and overlapping delivery; +- out-of-order actions; +- catalog success followed by receipt-finalization failure; +- retryable failure and quarantine transition; +- no raw payload or surplus provider fields in D1; +- memory Store and local D1 Store execution; +- read API schema, ordering, caching, and safe URLs; +- UI loading, empty, populated, stale, and unavailable states; +- scheduled reconciliation cursor/freshness behavior; +- no regression to Identity routes or minute maintenance; +- production smoke and manual redelivery. + +Repository gates remain: + +```text +npm run check +npm test +npm run build +``` + +Webhooks additionally keeps: + +```text +npm run format:check +npm run check +npm test +``` + +## Acceptance criteria + +The slice is complete when: + +1. A real GitHub stable release changes the displayed version and publication + date without a pegma.dev commit or deployment. +2. The organization webhook is authenticated from raw bytes and restricted to + explicit repository IDs. +3. `@pegma/webhooks` records delivery identity and outcomes over the production + D1-backed Store. +4. Duplicate, overlapping, and manually redelivered deliveries cannot corrupt + the release projection. +5. No webhook payload is persisted or logged. +6. The public endpoint and page expose only the intended release facts. +7. Initial backfill covers existing releases. +8. Scheduled reconciliation repairs missed, edited, unpublished, and deleted + releases. +9. Quarantine and reconciliation failures are visible to operators without a + public administrative endpoint. +10. The complete site/Worker and Webhooks gates pass, including real Azurite + and local D1 evidence. +11. The Webhooks plan records exactly what the second provider proved and + leaves same-host multi-source evidence open unless deliberately revised. + +## Rollback + +- Disable the GitHub organization webhook first. +- Keep the read endpoint returning the last known public records while the + issue is investigated, unless record integrity is in doubt. +- If integrity is in doubt, disable release rendering and fall back to + repository links. +- Reconciliation can rebuild the projection from GitHub; receipt rows and + release summaries contain no payload data. +- Roll back the Worker version through the existing operator process. +- Do not roll back or rebuild Identity data to remove this feature; the + collections are logically independent even though they share the D1 + database. + +## Clean-up and documentation + +After activation: + +- update this document with the deployed Worker version, webhook activation + date, exact package commit, and verification evidence; +- update `docs/PROJECT_PLAN.md` to record the release-data consumer; +- update the Webhooks project plan with the second-provider verdict and the + remaining same-host evidence; +- update `worker/README.md` with routes, secrets, reconciliation, health, and + operator recovery; +- remove any controlled test release or tag used only for activation; +- remove the vendored artifact and provenance note after + `@pegma/webhooks` is published and the registry artifact is verified; +- do not publish Webhooks, cut a release, or create a tag as an incidental + implementation step. + +## Decisions to confirm before implementation + +1. **Phase 3 accounting:** Treat this as partial Webhooks Phase 3 evidence + unless the owner deliberately changes the same-host requirement. +2. **Display:** Show current stable versions on the Stack page first; add a + separate release-history page only if real demand appears. +3. **Release class:** Stable GitHub releases only; omit drafts and prereleases. +4. **Freshness:** Webhook-driven updates with a five-minute maximum public + cache and six-hour authoritative reconciliation. +5. **History:** Store only the current stable release per repository in the + first slice. + +## Reference documentation + +- [GitHub webhook events and payloads](https://docs.github.com/en/webhooks/webhook-events-and-payloads#release) +- [GitHub webhook signature validation](https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries) +- [GitHub failed-delivery recovery](https://docs.github.com/en/webhooks/using-webhooks/handling-failed-webhook-deliveries) +- [Cloudflare Workers](https://developers.cloudflare.com/workers/) +- [Webhooks project plan](https://github.com/pegma-dev/webhooks/blob/main/docs/PROJECT_PLAN.md) +- [Storage Core repository](https://github.com/pegma-dev/storage-core) diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index bbf38b8..7eb9a89 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -263,3 +263,8 @@ with a source link where not. Decide in Phase 3. 3. Route same-origin `/api/*` traffic to `pegma-dev-api`, deploy, and verify the D1-backed account flow without changing the Pages-hosted static architecture. **Done 2026-07-28, including email activation.** +4. Keep public component release versions current on pegma.dev without a + content commit or Pages deploy per release — see + `docs/GITHUB_RELEASE_WEBHOOK_PLAN.md`. **Phase A (2026-07-28):** vendored + `@pegma/webhooks` artifact aligned to Storage Core `0.4.0` and proven over + memory + D1; handler, read API, UI, reconciliation, and activation remain. diff --git a/package-lock.json b/package-lock.json index 2a0e3bc..bac9349 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,10 +19,12 @@ "@pegma/sessions": "0.1.0", "@pegma/spine": "^0.1.1", "@pegma/storage-cloudflare-d1": "0.4.0", - "@pegma/storage-core": "0.4.0" + "@pegma/storage-core": "0.4.0", + "@pegma/webhooks": "file:vendor/@pegma/webhooks/pegma-webhooks-0.0.0.tgz" }, "devDependencies": { "@astrojs/check": "0.9.10", + "@cloudflare/vitest-pool-workers": "0.18.8", "@types/node": "26.1.1", "astro": "7.1.4", "typescript": "^5.9.2", @@ -703,6 +705,35 @@ } } }, + "node_modules/@cloudflare/vitest-pool-workers": { + "version": "0.18.8", + "resolved": "https://registry.npmjs.org/@cloudflare/vitest-pool-workers/-/vitest-pool-workers-0.18.8.tgz", + "integrity": "sha512-O1kOMZqapidlezNFiBZ7Lbd+8mMEpkGmWwPj+nPLvOngxSL11lmWq7xl7vxyjDxbeD/7l22KqgvRGM7XFaYd9w==", + "dev": true, + "license": "MIT", + "dependencies": { + "cjs-module-lexer": "1.2.3", + "esbuild": "0.28.1", + "miniflare": "4.20260722.0", + "wrangler": "4.114.0", + "zod": "3.25.76" + }, + "peerDependencies": { + "@vitest/runner": "^4.1.0", + "@vitest/snapshot": "^4.1.0", + "vitest": "^4.1.0" + } + }, + "node_modules/@cloudflare/vitest-pool-workers/node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, "node_modules/@cloudflare/workerd-darwin-64": { "version": "1.20260722.1", "resolved": "https://registry.npmjs.org/@cloudflare/workerd-darwin-64/-/workerd-darwin-64-1.20260722.1.tgz", @@ -2417,6 +2448,19 @@ "node": ">=22" } }, + "node_modules/@pegma/webhooks": { + "version": "0.0.0", + "resolved": "file:vendor/@pegma/webhooks/pegma-webhooks-0.0.0.tgz", + "integrity": "sha512-d/SvLJqd7CInzsDKLM6goI8yXh08jMBBzpHlvy3TMYyRmmbthJpkurJda3jZ2aGvrqbW/Rx3nAyxf1ZZhB20Zw==", + "license": "MIT", + "dependencies": { + "@pegma/spine": "0.1.1", + "@pegma/storage-core": "0.4.0" + }, + "engines": { + "node": ">=22" + } + }, "node_modules/@poppinss/colors": { "version": "4.1.6", "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", @@ -3642,6 +3686,13 @@ "node": ">=8" } }, + "node_modules/cjs-module-lexer": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.3.tgz", + "integrity": "sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==", + "dev": true, + "license": "MIT" + }, "node_modules/cliui": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz", diff --git a/package.json b/package.json index a3e493c..cca0f19 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,9 @@ "dev": "astro dev", "build": "astro build", "check": "astro check && tsc -p worker/tsconfig.json --noEmit", - "test": "vitest run", + "test": "vitest run --config vitest.config.ts && vitest run --config vitest.d1.config.ts", + "test:node": "vitest run --config vitest.config.ts", + "test:d1": "vitest run --config vitest.d1.config.ts", "preview": "astro preview", "worker:dev": "wrangler dev -c worker/wrangler.jsonc", "worker:deploy": "wrangler deploy -c worker/wrangler.jsonc", @@ -26,10 +28,12 @@ "@pegma/sessions": "0.1.0", "@pegma/spine": "^0.1.1", "@pegma/storage-cloudflare-d1": "0.4.0", - "@pegma/storage-core": "0.4.0" + "@pegma/storage-core": "0.4.0", + "@pegma/webhooks": "file:vendor/@pegma/webhooks/pegma-webhooks-0.0.0.tgz" }, "devDependencies": { "@astrojs/check": "0.9.10", + "@cloudflare/vitest-pool-workers": "0.18.8", "@types/node": "26.1.1", "astro": "7.1.4", "typescript": "^5.9.2", diff --git a/vendor/@pegma/webhooks/PROVENANCE.md b/vendor/@pegma/webhooks/PROVENANCE.md new file mode 100644 index 0000000..109c17c --- /dev/null +++ b/vendor/@pegma/webhooks/PROVENANCE.md @@ -0,0 +1,31 @@ +# Vendored `@pegma/webhooks` provenance + +`@pegma/webhooks` is unpublished. pegma.dev consumes a byte-reproducible +`npm pack` artifact until the first public package release, then this bridge +is removed. + +| Field | Value | +| --- | --- | +| Package | `@pegma/webhooks@0.0.0` | +| Artifact | `pegma-webhooks-0.0.0.tgz` | +| Source repository | `https://github.com/pegma-dev/webhooks` | +| Exact commit | `1e5ef0732c3595ea82cb80394cf55cd9a0442318` | +| SHA-256 | `2c27d51169c42598b17f95b099cb01b35a8c6cf5bfa42ce1f2c09480746e9521` | +| npm integrity | `sha512-d/SvLJqd7CInzsDKLM6goI8yXh08jMBBzpHlvy3TMYyRmmbthJpkurJda3jZ2aGvrqbW/Rx3nAyxf1ZZhB20Zw==` | +| Storage Core pin inside artifact | `@pegma/storage-core@0.4.0` | + +## Reproduction + +```text +git clone https://github.com/pegma-dev/webhooks.git +cd webhooks +git checkout 1e5ef0732c3595ea82cb80394cf55cd9a0442318 +npm ci +npm pack -w @pegma/webhooks --pack-destination . +Get-FileHash -Algorithm SHA256 .\pegma-webhooks-0.0.0.tgz +# or: shasum -a 256 pegma-webhooks-0.0.0.tgz +``` + +The SHA-256 of the resulting tarball must match the table above. npm records +the sha512 integrity automatically when the dependency is installed from the +local file path. diff --git a/vendor/@pegma/webhooks/pegma-webhooks-0.0.0.tgz b/vendor/@pegma/webhooks/pegma-webhooks-0.0.0.tgz new file mode 100644 index 0000000..a5379a2 Binary files /dev/null and b/vendor/@pegma/webhooks/pegma-webhooks-0.0.0.tgz differ diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000..c085761 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + include: ['worker/src/**/*.test.ts'], + exclude: ['**/node_modules/**', '**/*.d1.test.ts'], + testTimeout: 30_000, + }, +}); diff --git a/vitest.d1.config.ts b/vitest.d1.config.ts new file mode 100644 index 0000000..5e3ae64 --- /dev/null +++ b/vitest.d1.config.ts @@ -0,0 +1,20 @@ +import { cloudflareTest } from '@cloudflare/vitest-pool-workers'; +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + plugins: [ + cloudflareTest({ + wrangler: { configPath: './worker/wrangler.jsonc' }, + miniflare: { + bindings: { + IDENTITY_EMAIL_FROM: 'Pegma ', + IDENTITY_EMAIL_ENABLED: 'false', + }, + }, + }), + ], + test: { + include: ['worker/src/**/*.d1.test.ts'], + testTimeout: 30_000, + }, +}); diff --git a/worker/src/webhooks-ledger.d1.test.ts b/worker/src/webhooks-ledger.d1.test.ts new file mode 100644 index 0000000..9875ea3 --- /dev/null +++ b/worker/src/webhooks-ledger.d1.test.ts @@ -0,0 +1,87 @@ +import { env } from 'cloudflare:workers'; +import { createWebhookLedger } from '@pegma/webhooks'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import type { Logger } from '@pegma/spine'; + +declare global { + namespace Cloudflare { + interface Env { + IDENTITY_DB: D1Database; + } + } +} + +const logger: Logger = { log: vi.fn() }; + +/** Semantically matches worker/migrations/0001_pegma_storage.sql (inlined for the Workers test pool). */ +const SCHEMA_STATEMENTS = [ + `CREATE TABLE IF NOT EXISTS RECORDS ( + partition_key TEXT NOT NULL, + row_key TEXT NOT NULL, + record_json TEXT, + version INTEGER NOT NULL, + deleted INTEGER NOT NULL CHECK (deleted IN (0, 1)), + PRIMARY KEY (partition_key, row_key) +) STRICT`, + `CREATE TABLE IF NOT EXISTS PEGMA_STORAGE_D1_TX_GUARD ( + reason TEXT NOT NULL +) STRICT`, + `CREATE TRIGGER IF NOT EXISTS PEGMA_STORAGE_D1_TX_ABORT_EXISTS +BEFORE INSERT ON PEGMA_STORAGE_D1_TX_GUARD +WHEN NEW.reason = 'exists' +BEGIN + SELECT RAISE(ABORT, 'PEGMA_STORAGE_D1_TX_EXISTS'); +END`, + `CREATE TRIGGER IF NOT EXISTS PEGMA_STORAGE_D1_TX_ABORT_MISSING +BEFORE INSERT ON PEGMA_STORAGE_D1_TX_GUARD +WHEN NEW.reason = 'missing' +BEGIN + SELECT RAISE(ABORT, 'PEGMA_STORAGE_D1_TX_MISSING'); +END`, + `CREATE TRIGGER IF NOT EXISTS PEGMA_STORAGE_D1_TX_ABORT_CHANGED +BEFORE INSERT ON PEGMA_STORAGE_D1_TX_GUARD +WHEN NEW.reason = 'changed' +BEGIN + SELECT RAISE(ABORT, 'PEGMA_STORAGE_D1_TX_CHANGED'); +END`, +] as const; + +beforeAll(async () => { + for (const statement of SCHEMA_STATEMENTS) { + await env.IDENTITY_DB.prepare(statement).run(); + } +}); + +beforeEach(async () => { + await env.IDENTITY_DB.prepare('DELETE FROM RECORDS').run(); + await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run(); +}); + +describe('vendored @pegma/webhooks over Cloudflare D1 composition', () => { + it('uses createSchemaIfMissing: false like production Identity', async () => { + const store = createCloudflareD1Store({ + database: env.IDENTITY_DB, + createSchemaIfMissing: false, + }); + const ledger = createWebhookLedger({ + store, + source: 'github', + logger, + }); + + const first = await ledger.begin( + '22222222-2222-4222-8222-222222222222', + 'github.release.published', + ); + expect(first).toEqual({ status: 'new', attempts: 0 }); + + await ledger.markProcessed('22222222-2222-4222-8222-222222222222'); + + const duplicate = await ledger.begin( + '22222222-2222-4222-8222-222222222222', + 'github.release.published', + ); + expect(duplicate).toEqual({ status: 'processed', attempts: 0 }); + }); +}); diff --git a/worker/src/webhooks-ledger.test.ts b/worker/src/webhooks-ledger.test.ts new file mode 100644 index 0000000..a36f343 --- /dev/null +++ b/worker/src/webhooks-ledger.test.ts @@ -0,0 +1,31 @@ +import { createWebhookLedger } from '@pegma/webhooks'; +import { createMemoryStore } from '@pegma/storage-core'; +import { describe, expect, it, vi } from 'vitest'; +import type { Logger } from '@pegma/spine'; + +const logger: Logger = { log: vi.fn() }; + +describe('vendored @pegma/webhooks over createMemoryStore', () => { + it('records begin, markProcessed, and duplicate begin outcomes', async () => { + const store = createMemoryStore(); + const ledger = createWebhookLedger({ + store, + source: 'github', + logger, + }); + + const first = await ledger.begin( + '11111111-1111-4111-8111-111111111111', + 'github.release.published', + ); + expect(first).toEqual({ status: 'new', attempts: 0 }); + + await ledger.markProcessed('11111111-1111-4111-8111-111111111111'); + + const duplicate = await ledger.begin( + '11111111-1111-4111-8111-111111111111', + 'github.release.published', + ); + expect(duplicate).toEqual({ status: 'processed', attempts: 0 }); + }); +});