Skip to content

feat(worker): Phase 1 Hono skeleton + canonical Phase 0 remediation#33

Open
chitcommit wants to merge 2 commits into
mainfrom
feat/hono-migration-phase-1
Open

feat(worker): Phase 1 Hono skeleton + canonical Phase 0 remediation#33
chitcommit wants to merge 2 commits into
mainfrom
feat/hono-migration-phase-1

Conversation

@chitcommit
Copy link
Copy Markdown
Contributor

@chitcommit chitcommit commented May 11, 2026

Summary

  • Phase 0 — Canonical compliance artifacts (CHARTER, CHITTY, AGENTS, SECURITY, register.json), wrangler.jsonc replaces stale wrangler.toml, .github/CODEOWNERS, P/L/T/E/A entity types declared, repository slug + compat date fixed
  • Phase 1 — Hono Worker skeleton at worker/src/ with JWKS-validated ChittyAuth, /health, /api/v1/status, /api/auth/user. Defer-by-501 stub for unmigrated routes. Express server still serves dev — no breaking change to existing dev flow

Multi-agent review applied

Findings from chittyos-core:chittycanon-code-cardinal, pr-review-toolkit:code-reviewer, pr-review-toolkit:silent-failure-hunter, pr-review-toolkit:type-design-analyzer, chittyos-governance:chittyagent-neon, chittyos-proxy-agents:chittyagent-cloudflare, chittyos-core:chittyschema-overlord consolidated:

  • ✅ Audience claim check (CHITTYAUTH_AUDIENCE=chittyassets-api)
  • ✅ JWKS infra failures (503) distinguished from validation failures (401)
  • ✅ Auth rejection logging to chittytrack tail consumer with reason codes
  • ✅ JWKS timeoutDuration + cooldownDuration configured
  • ✅ Zod schema replaces unchecked cast — trust_level bounded 0..5, sub === chitty_id invariant, exp > iat
  • ENTITY_TYPES const tuple — single source of truth (was triplicated)
  • ✅ 501 stub no longer behind requireChittyAuth (closes auth-oracle leak)
  • ✅ CORS allowlist (no reflect-any-with-credentials)
  • err.message scrubbed from 500 responses, replaced with correlation_id
  • ✅ Cookie regex no longer decodeURIComponents JWTs
  • ✅ CHARTER entity-type corrected (warranties/insurance reclassified T, legal cases reclassified E per chittyschema-overlord)

Validation

  • tsc --noEmit clean
  • wrangler deploy --dry-run --env production succeeds (250 KiB / 50 KiB gzip)
  • Tail consumer chittytrack bound
  • No existing chittyassets-api* worker, R2 bucket, or assets.chitty.cc DNS record (per chittyagent-cloudflare audit) — clean first-deploy state

Phase 2 prerequisites (next PR)

  1. Enable Neon GitHub integration → preview branch per PR on project steep-cloud-28172078
  2. Provision Hyperdrive chittyassets-db (binding CHITTYASSETS_DB)
  3. Add proxied AAAA assets 100:: for assets.chitty.cc
  4. Decide Pages strategy (Worker [assets] binding vs new Pages project — chittyassets Pages project does not exist in account)
  5. Schema work via chittyschema-overlord: add chitty_id UNIQUE, entity_type discriminator, r2_object_acl table, drop sessions, plan users.chitty_id migration

Test plan

  • Deploy preview env, verify curl preview-url/health returns canonical envelope
  • Verify curl preview-url/api/v1/status shows migration_status: MIGRATING_EXPRESS_TO_HONO
  • Verify curl preview-url/api/auth/user returns 401 without bearer
  • Verify curl -H 'Authorization: Bearer <valid-ChittyAuth-JWT>' preview-url/api/auth/user returns claims
  • Verify curl preview-url/api/assets returns 501 anonymously (no auth oracle)
  • Verify tail consumer receives auth_reject events with reason codes

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Sign-in/sign-up/sign-out helpers and redirects
    • Health/status endpoints and authenticated user endpoint
  • Documentation

    • Added governance (charter), security policy, agent/operational guidance, and service registry
    • Documented architecture, API surface, lifecycle, compliance and deployment guidance
  • Chores

    • Cloudflare Workers deployment config and service registration updates
    • Added auth/validation runtime dependencies
    • Added CODEOWNERS entry assigning ownership for the repo

Review Change Stack

Phase 0 — canonical artifacts and config:
- CHARTER.md, CHITTY.md, AGENTS.md, SECURITY.md, register.json (canonical
  frontmatter, P/L/T/E/A entity-type declarations, repo slug fix, MIGRATING
  status flag)
- wrangler.jsonc replaces wrangler.toml (compat 2026-03-28, observability,
  tail_consumers: chittytrack, assets.chitty.cc route in env.production)
- .github/CODEOWNERS
- sovereignty.cert deleted (non-canonical)

Phase 1 — Hono Worker skeleton:
- worker/src/env.ts — ENTITY_TYPES const tuple, ChittyAuthClaimsSchema (zod),
  CHITTY_ID_PATTERN
- worker/src/auth.ts — JWKS verify with audience claim, distinguishes
  validation errors (401) from JWKS infra failures (503), logs every reject
  with reason code to tail consumer, configured JWKS timeout+cooldown,
  Person-only principal enforcement
- worker/src/index.ts — /health, /api/v1/status, /api/auth/user, anonymous
  501 stub (no auth oracle), CORS allowlist, correlation-id error handler
  that scrubs err.message from client response
- client/src/lib/chittyAuthUrls.ts — ChittyAuth issuer URLs

Validated: typecheck clean, wrangler deploy --dry-run --env production
succeeds (250 KiB / 50 KiB gzip), tail consumer chittytrack bound.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 11, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f1196b4a-1f07-4caf-af05-d8596e06a36e

📥 Commits

Reviewing files that changed from the base of the PR and between 806c8a5 and a28523b.

📒 Files selected for processing (1)
  • wrangler.jsonc

📝 Walkthrough

Walkthrough

This PR bootstraps the ChittyAssets Cloudflare Workers API service with JWT-protected endpoints, client-side authentication URL helpers, service registration metadata, and comprehensive governance documentation defining tier, certification, security policy, and operational constraints.

Changes

ChittyAssets Worker Service Initialization

Layer / File(s) Summary
Environment & Type Definitions
worker/src/env.ts
Exports ENTITY_TYPES enum, CHITTY_ID_PATTERN regex, Env interface for worker bindings, ChittyAuthClaimsSchema Zod schema, and ChittyAuthClaims inferred type.
JWT Authentication Middleware
worker/src/auth.ts
Implements JWKS caching with configurable timeout, bearer token extraction from Authorization header or chitty_jwt cookie, JWT verification via issuer/audience, and requireChittyAuth middleware enforcing person-entity claims.
Client Authentication URL Helpers
client/src/lib/chittyAuthUrls.ts
Provides getChittyAuthOrigin(), getReturnToUrl(), and builders for sign-in/sign-up/sign-out URLs with return_to query parameter, plus redirect functions.
Worker Application Setup
worker/src/index.ts
Hono app with allowlist CORS, request logging, GET /health and GET /api/v1/status public endpoints, GET /api/auth/user protected by requireChittyAuth, catch-all 501 for unimplemented /api/* routes, and error/404 handlers with correlation IDs.
Runtime Dependencies
package.json
Adds hono, jose, and @hono/zod-validator to support Hono framework, JWT operations, and Zod validation.
Service Registration & Schema
register.json
Declares chittyassets service metadata including endpoints, entity schema (users, assets, evidence, etc.), security model (JWT + TLS + encryption), and dependencies (auth, storage, database, AI).
Deployment Configuration
wrangler.jsonc, wrangler.toml
New wrangler.jsonc configures Cloudflare Workers entrypoint, compatibility date 2026-03-28 with nodejs_compat, observability, tail consumers, auth/service environment variables, and production route for assets.chitty.cc/*. Legacy wrangler.toml removed.
Governance & Documentation
.github/CODEOWNERS, CHARTER.md, CHITTY.md, AGENTS.md, SECURITY.md
Establishes service governance: CODEOWNERS assigns all files to @chittyos/assets; CHARTER.md defines mission, scope, API routes, schema, and security controls; CHITTY.md documents tier-4 position, architecture, lifecycle state machine, and BRONZE certification; AGENTS.md provides operational guidance (commands, integration patterns, testing, security rules, compliance flags); SECURITY.md specifies vulnerability reporting, SLA, threat model, and known issues.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant HonoApp as Hono App
  participant CORS as CORS Middleware
  participant Auth as requireChittyAuth
  participant JWKS as JWKS Cache
  participant Handler as Route Handler

  Client->>HonoApp: HTTP Request
  HonoApp->>CORS: Check origin allowlist
  CORS->>HonoApp: Allowed/Rejected
  alt Public Route
    HonoApp->>Handler: GET /health or /api/v1/status
    Handler->>Client: JSON metadata + timestamp
  else Protected Route
    HonoApp->>Auth: Extract bearer token or cookie
    Auth->>JWKS: Verify JWT signature
    JWKS->>Auth: Remote JWKS key set
    alt Valid JWT
      Auth->>Auth: Validate claims schema
      alt Person entity
        Auth->>Handler: Proceed with claims in context
        Handler->>Client: Response with user data
      else Non-person
        Auth->>Client: 403 Forbidden
      end
    else Invalid/Expired
      Auth->>Client: 401 Unauthorized
    end
  else Unimplemented
    HonoApp->>Client: 501 Not Yet Migrated
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Behold the assets worker, now initialized,
With JWKS-verified claims and CORS-sanctified,
From env types to routes, each layer aligned,
Health checks and sign-outs, a service refined.
Guard well your JWTs and ACLs tight— the ChittyAssets takes flight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main changes: introduction of a Hono worker skeleton for Phase 1 migration and addition of canonical Phase 0 compliance artifacts (CHARTER, CHITTY, AGENTS, SECURITY, register.json, codeowners).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/hono-migration-phase-1

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
client/src/lib/chittyAuthUrls.ts (1)

16-22: 💤 Low value

Consider simplifying URL base construction.

The buildAuthUrl function adds a trailing slash to the origin when creating the base URL (${getChittyAuthOrigin()}/), but normalizeOrigin already strips trailing slashes. While the URL constructor handles this correctly, it creates inconsistency. Consider passing the origin directly:

 function buildAuthUrl(path: string, params: Record<string, string>): string {
-  const url = new URL(path, `${getChittyAuthOrigin()}/`);
+  const url = new URL(path, getChittyAuthOrigin());
   for (const [k, v] of Object.entries(params)) {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/src/lib/chittyAuthUrls.ts` around lines 16 - 22, The buildAuthUrl
function constructs the base URL using `${getChittyAuthOrigin()}/` which is
redundant because normalizeOrigin already strips trailing slashes; update
buildAuthUrl to pass getChittyAuthOrigin() directly into the URL constructor
(i.e., new URL(path, getChittyAuthOrigin())) while keeping the existing loop
that sets url.searchParams from params; reference the buildAuthUrl function and
ensure no other behavior changes around path handling or query param population.
worker/src/index.ts (1)

36-66: ⚡ Quick win

Consider centralizing service metadata constants.

The metadata fields version, tier, and canonical_uri are hardcoded and duplicated across both /health and /api/v1/status endpoints. Consider extracting these into constants at the top of the file or in worker/src/env.ts to ensure consistency and ease of maintenance.

♻️ Proposed refactor
+const SERVICE_METADATA = {
+  name: "chittyassets",
+  tier: 4,
+  canonical_uri: "chittycanon://core/services/chittyassets",
+  version: "1.0.0",
+} as const;
+
 const app = new Hono<{ Bindings: Env; Variables: Variables }>();

 app.get("/health", (c) =>
   c.json({
     status: "ok",
-    service: "chittyassets",
-    tier: 4,
-    canonical_uri: "chittycanon://core/services/chittyassets",
-    version: "1.0.0",
+    ...SERVICE_METADATA,
     environment: c.env.ENVIRONMENT,
     timestamp: new Date().toISOString(),
   }),
 );

 app.get("/api/v1/status", (c) =>
   c.json({
     status: "ok",
-    service: "chittyassets",
-    tier: 4,
-    canonical_uri: "chittycanon://core/services/chittyassets",
-    version: "1.0.0",
+    ...SERVICE_METADATA,
     environment: c.env.ENVIRONMENT,
     migration_status: "MIGRATING_EXPRESS_TO_HONO",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@worker/src/index.ts` around lines 36 - 66, Extract duplicated service
metadata (version, tier, canonical_uri and any other repeated literals like
service name) into shared constants (e.g., SERVICE_NAME, SERVICE_VERSION,
SERVICE_TIER, SERVICE_CANONICAL_URI) defined at the top of this file or exported
from worker/src/env.ts, then replace the hardcoded values in the handlers for
app.get("/health", ...) and app.get("/api/v1/status", ...) to reference those
constants (also reuse for the "service" field). Ensure timestamp and environment
still come from c.env and that entity_types_handled and dependencies remain
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@package.json`:
- Line 46: Change the invalid dependency version for `@hono/zod-validator` in
package.json from "^0.8.0" to the valid latest stable version "^0.7.6"; update
the dependency entry ("@hono/zod-validator") accordingly and run your package
manager (npm/yarn/pnpm) to reinstall and verify no dependency conflicts.

In `@register.json`:
- Around line 254-258: The repo metadata lists "cloudflare-r2" in register.json
but docs mention Google Cloud Storage; decide which storage is authoritative and
make consistent: if Cloudflare R2 is correct, update CHITTY.md (references
around the stack table and architecture diagram) and SECURITY.md (the "Evidence
File ACL" threat surface) to replace "Google Cloud Storage" and GCS-specific
terminology with "Cloudflare R2" and R2-specific details; if Google Cloud
Storage is correct, change the register.json external entry from "cloudflare-r2"
to "google-cloud-storage" and update the storage endpoint descriptions (the
endpoint text referenced in CHITTY.md lines ~194 and ~200) to GCS
endpoints/terminology so all docs and register.json match. Ensure you update all
occurrences of GCS/R2 in CHITTY.md and SECURITY.md to avoid mixed references.

---

Nitpick comments:
In `@client/src/lib/chittyAuthUrls.ts`:
- Around line 16-22: The buildAuthUrl function constructs the base URL using
`${getChittyAuthOrigin()}/` which is redundant because normalizeOrigin already
strips trailing slashes; update buildAuthUrl to pass getChittyAuthOrigin()
directly into the URL constructor (i.e., new URL(path, getChittyAuthOrigin()))
while keeping the existing loop that sets url.searchParams from params;
reference the buildAuthUrl function and ensure no other behavior changes around
path handling or query param population.

In `@worker/src/index.ts`:
- Around line 36-66: Extract duplicated service metadata (version, tier,
canonical_uri and any other repeated literals like service name) into shared
constants (e.g., SERVICE_NAME, SERVICE_VERSION, SERVICE_TIER,
SERVICE_CANONICAL_URI) defined at the top of this file or exported from
worker/src/env.ts, then replace the hardcoded values in the handlers for
app.get("/health", ...) and app.get("/api/v1/status", ...) to reference those
constants (also reuse for the "service" field). Ensure timestamp and environment
still come from c.env and that entity_types_handled and dependencies remain
unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 40a6c92c-4e8d-4e11-915b-a0fb8ff15d77

📥 Commits

Reviewing files that changed from the base of the PR and between 4c8d603 and 806c8a5.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (13)
  • .github/CODEOWNERS
  • AGENTS.md
  • CHARTER.md
  • CHITTY.md
  • SECURITY.md
  • client/src/lib/chittyAuthUrls.ts
  • package.json
  • register.json
  • worker/src/auth.ts
  • worker/src/env.ts
  • worker/src/index.ts
  • wrangler.jsonc
  • wrangler.toml
💤 Files with no reviewable changes (1)
  • wrangler.toml

Comment thread package.json
"@clerk/express": "^2.0.1",
"@clerk/types": "^4.0.0",
"@google-cloud/storage": "^7.16.0",
"@hono/zod-validator": "^0.8.0",
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🌐 Web query:

What is the latest stable version of @hono/zod-validator npm package?

💡 Result:

The latest stable version of the @hono/zod-validator npm package is 0.7.6 [1][2]. Evidence: the npm package page lists “0.7.6” as the current version [1], and JSR also shows @hono/zod-validator at version 0.7.6 (released as the latest in the 0.7.x series) [2].

Citations:


Update @hono/zod-validator to a valid version. The specified version ^0.8.0 does not exist; the latest stable release is 0.7.6. Update to ^0.7.6 to resolve dependency conflicts during installation.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@package.json` at line 46, Change the invalid dependency version for
`@hono/zod-validator` in package.json from "^0.8.0" to the valid latest stable
version "^0.7.6"; update the dependency entry ("@hono/zod-validator")
accordingly and run your package manager (npm/yarn/pnpm) to reinstall and verify
no dependency conflicts.

Comment thread register.json
Comment on lines +254 to +258
"external": [
"openai-gpt4o",
"cloudflare-r2",
"neon-postgresql"
]
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Resolve object storage platform inconsistency across documentation.

This file declares cloudflare-r2 as the external storage dependency, but CHITTY.md specifies "Google Cloud Storage" in the stack table and architecture diagram, and SECURITY.md describes "Evidence File ACL (Google Cloud Storage)" as a threat surface.

Please clarify which platform is actually deployed:

  • If Cloudflare R2 is correct: update CHITTY.md lines 34, 58-59 and SECURITY.md lines 89-95 to replace GCS references with R2
  • If Google Cloud Storage is correct: change line 256 to "google-cloud-storage" and update endpoint descriptions at lines 194, 200
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@register.json` around lines 254 - 258, The repo metadata lists
"cloudflare-r2" in register.json but docs mention Google Cloud Storage; decide
which storage is authoritative and make consistent: if Cloudflare R2 is correct,
update CHITTY.md (references around the stack table and architecture diagram)
and SECURITY.md (the "Evidence File ACL" threat surface) to replace "Google
Cloud Storage" and GCS-specific terminology with "Cloudflare R2" and R2-specific
details; if Google Cloud Storage is correct, change the register.json external
entry from "cloudflare-r2" to "google-cloud-storage" and update the storage
endpoint descriptions (the endpoint text referenced in CHITTY.md lines ~194 and
~200) to GCS endpoints/terminology so all docs and register.json match. Ensure
you update all occurrences of GCS/R2 in CHITTY.md and SECURITY.md to avoid mixed
references.

- Provisioned Hyperdrive 'chittyassets-db' (id: 4bd7964c46dd42be86e8a5e3dd0d7376)
  pointing at Neon project steep-cloud-28172078 pooled endpoint
- Added Worker [assets] static binding (Option B per chittyagent-cloudflare):
  serves dist/public as SPA fallback, single deploy artifact for UI + API
- DNS AAAA assets.chitty.cc → 100:: proxied (record 8f5080ce71da05449312b1b1bc7c22a1)
- Verified: wrangler deploy --dry-run --env production binds
  CHITTYASSETS_DB Hyperdrive + ASSETS static + chittytrack tail consumer

Phase 2 prerequisites: complete. Ready for read-route migration.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant