Skip to content

refactor: standardize legacy token naming aliases#113

Open
chitcommit wants to merge 1 commit intomainfrom
refactor/standardize-token-naming
Open

refactor: standardize legacy token naming aliases#113
chitcommit wants to merge 1 commit intomainfrom
refactor/standardize-token-naming

Conversation

@chitcommit
Copy link
Contributor

@chitcommit chitcommit commented Mar 26, 2026

Summary

  • Consolidate CHITTY_ID_SERVICE_TOKEN / CHITTY_SERVICE_TOKENCHITTY_ID_TOKEN across all source, tests, mocks, migrations, deploy scripts, secret catalog, and CI config
  • Remove dead CHITTY_API_KEY references
  • Replace internal CLOUDFLARE_ACCOUNT_ID / CF_ACCOUNT_ID fallbacks with direct CHITTYOS_ACCOUNT_ID usage
  • Update wrangler.jsonc manifest to document retired aliases
  • Guard Ollama CF Access headers against missing secret binding
  • Preserve external-facing GitHub Actions secret names (consumer contract)

19 files changed, 45 insertions, 48 deletions

Test plan

  • npm test passes (test mocks updated to use canonical names)
  • Verify cloudflare-api-helper.test.js no longer tests removed fallback
  • Confirm deploy script no longer deploys CHITTY_ID_SERVICE_TOKEN or CLOUDFLARE_ACCOUNT_ID as secrets
  • Verify GitHub Actions workflows still reference secrets.CLOUDFLARE_ACCOUNT_ID (external contract unchanged)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Fixed Ollama Access authentication to require both client credentials before sending headers, preventing partial credential injection.
  • Chores

    • Standardized service token naming conventions across the platform.
    • Updated credential configuration references for improved consistency.
    • Reorganized deployment secret list with new service tokens for task and trust operations, plus emergency and integration secrets.

Consolidate scattered token/env aliases to canonical names across 19 files:
- CHITTY_ID_SERVICE_TOKEN / CHITTY_SERVICE_TOKEN → CHITTY_ID_TOKEN
- CHITTY_API_KEY → removed (dead code)
- CLOUDFLARE_ACCOUNT_ID / CF_ACCOUNT_ID → CHITTYOS_ACCOUNT_ID (internal only)

External-facing contract names (GitHub Actions secrets, CLI scripts) preserved.
Tests, mocks, migrations, deploy scripts, secret catalog, and wrangler manifest
all updated to match.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings March 26, 2026 04:20
@chatgpt-codex-connector
Copy link

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

@cloudflare-workers-and-pages
Copy link
Contributor

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
chittyconnect d6031c9 Mar 26 2026, 04:20 AM

@coderabbitai
Copy link

coderabbitai bot commented Mar 26, 2026

📝 Walkthrough

Walkthrough

This pull request systematically renames authentication secrets and environment variables across the codebase: CHITTY_ID_SERVICE_TOKEN becomes CHITTY_ID_TOKEN, CF_ACCOUNT_ID becomes CHITTYOS_ACCOUNT_ID, and removes fallback references to the old names. Additionally, a conditional check is added to require both Ollama Cloudflare credentials before injecting headers.

Changes

Cohort / File(s) Summary
Secret Configuration & Catalog
.github/secret-catalog.json, .github/workflows/sync-secrets.yml, wrangler.jsonc
Renames CHITTY_ID_SERVICE_TOKEN to CHITTY_ID_TOKEN and CF_ACCOUNT_ID to CHITTYOS_ACCOUNT_ID in secret definitions, workflow environment, and documentation.
ChittyID Intelligence Services
src/intelligence/context-intelligence.js, src/intelligence/experience-anchor.js, src/intelligence/__tests__/...
Updates Authorization headers and test mocks to use CHITTY_ID_TOKEN instead of CHITTY_ID_SERVICE_TOKEN.
Credential Library & Mocking
src/lib/chittyid-client.js, tests/helpers/mocks.js
Modifies credential initialization to read from CHITTY_ID_TOKEN env var and updates mock environment setup accordingly.
Cloudflare Account ID Migration
src/api/routes/credentials.js, src/lib/cloudflare-api-helper.js, src/mcp/tool-dispatcher.js, src/services/credential-provisioner.js, tests/lib/cloudflare-api-helper.test.js
Removes fallback to CLOUDFLARE_ACCOUNT_ID; uses only CHITTYOS_ACCOUNT_ID for account identification. Error messages narrowed to reference only the new env var name.
Ollama Integration Security
src/api/routes/thirdparty.js
Adds conditional check to require both OLLAMA_CF_CLIENT_ID and OLLAMA_CF_CLIENT_SECRET before injecting Cloudflare Access headers.
Deployment & Migration
scripts/deploy-missing-secrets.sh, migrations/013_connections.sql, CLAUDE.md
Updates deployment scripts to reflect new secret names (CHITTY_ID_TOKEN), adds new tokens (CHITTY_TASK_TOKEN, CHITTY_TRUST_TOKEN), removes old CLOUDFLARE_ACCOUNT_ID references, and refactors shell counter increment syntax.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

security-approved, docs-approved, access-reviewed

Poem

🐰 Secrets renamed with careful grace,
Old tokens vanish without trace,
CHITTYOS leads the auth parade,
Fallbacks fade where names once played,
Security blooms as defaults fade! 🌸

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor: standardize legacy token naming aliases' clearly and specifically describes the main change—consolidating and standardizing token naming conventions across the codebase.
Description check ✅ Passed The description is well-structured and covers the core intent (token/alias consolidation, fallback removal, manifest updates), but the template's required Security & Access and Docs sections are incomplete or omitted.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/standardize-token-naming

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

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Refactors environment/secret naming to standardize on canonical token/ID variables (notably CHITTY_ID_TOKEN and CHITTYOS_ACCOUNT_ID), removing legacy aliases and tightening header injection behavior.

Changes:

  • Consolidates ChittyID auth token usage to CHITTY_ID_TOKEN across runtime code and tests/mocks, and updates connection seed data accordingly.
  • Removes Cloudflare account ID fallbacks (CLOUDFLARE_ACCOUNT_ID / CF_ACCOUNT_ID) in runtime paths in favor of CHITTYOS_ACCOUNT_ID.
  • Updates secret/deploy documentation & tooling and adds a safety guard to only send Ollama CF Access headers when both values are present.

Reviewed changes

Copilot reviewed 19 out of 19 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
wrangler.jsonc Documents canonical secrets/vars and marks legacy aliases as retired.
tests/lib/cloudflare-api-helper.test.js Updates Cloudflare credential tests for CHITTYOS_ACCOUNT_ID.
tests/intelligence/experience-anchor.test.js Updates mock env to use CHITTY_ID_TOKEN.
tests/helpers/mocks.js Updates shared test env mock to use CHITTY_ID_TOKEN.
src/services/credential-provisioner.js Removes CLOUDFLARE_ACCOUNT_ID fallback; uses CHITTYOS_ACCOUNT_ID only.
src/mcp/tool-dispatcher.js Removes CLOUDFLARE_ACCOUNT_ID fallback for Evidence AI tools.
src/lib/cloudflare-api-helper.js Uses CHITTYOS_ACCOUNT_ID as the env fallback key for account ID retrieval.
src/lib/chittyid-client.js Removes legacy token/api-key env aliases; uses CHITTY_ID_TOKEN.
src/intelligence/experience-anchor.js Switches Authorization header to CHITTY_ID_TOKEN.
src/intelligence/context-intelligence.js Switches mint auth header to CHITTY_ID_TOKEN.
src/intelligence/tests/experience-anchor.test.js Updates test env token name to CHITTY_ID_TOKEN.
src/intelligence/tests/context-intelligence.test.js Updates test env token name to CHITTY_ID_TOKEN.
src/api/routes/thirdparty.js Only injects CF Access headers when both client id + secret are present.
src/api/routes/credentials.js Health output now checks only CHITTYOS_ACCOUNT_ID.
scripts/deploy-missing-secrets.sh Drops legacy ChittyID token secret; adds a few additional secrets; fixes arithmetic with set -e.
migrations/013_connections.sql Updates ChittyID connection seed token pattern to CHITTY_ID_TOKEN.
CLAUDE.md Updates setup docs to use wrangler secret put CHITTY_ID_TOKEN.
.github/workflows/sync-secrets.yml Renames env var from CF_ACCOUNT_ID to CHITTYOS_ACCOUNT_ID.
.github/secret-catalog.json Renames secret entry from CHITTY_ID_SERVICE_TOKEN to CHITTY_ID_TOKEN.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +77 to 80
const env = { CHITTYOS_ACCOUNT_ID: "acct-456" };

const { accountId } = await getCloudflareApiCredentials(env);
expect(accountId).toBe("acct-456");
Copy link

Copilot AI Mar 26, 2026

Choose a reason for hiding this comment

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

This test name and setup don’t match the current implementation: getCloudflareApiCredentials returns env.CHITTYOS_ACCOUNT_ID directly when present, so it won’t call getCredential for the account ID. As written, the second .mockResolvedValueOnce("acct-456") is unused and the test isn’t exercising the broker/env-fallback path. Consider either (a) renaming the test to reflect “accountId from env”, or (b) setting env without CHITTYOS_ACCOUNT_ID and asserting the accountId comes from the second getCredential call (and optionally asserting call count/args).

Suggested change
const env = { CHITTYOS_ACCOUNT_ID: "acct-456" };
const { accountId } = await getCloudflareApiCredentials(env);
expect(accountId).toBe("acct-456");
const env = {};
const { accountId } = await getCloudflareApiCredentials(env);
expect(accountId).toBe("acct-456");
expect(getCredential).toHaveBeenCalledTimes(2);

Copilot uses AI. Check for mistakes.
Comment on lines +356 to +362
// │ RETIRED ALIASES (removed from codeDO NOT re-add)
// ├─────────────────────────────────────────────────────────────────┤
// │ CF_ACCOUNT_ID → CHITTYOS_ACCOUNT_ID (var) │
// │ CHITTY_SERVICE_TOKEN → CHITTY_ID_SERVICE_TOKEN (secret) │
// │ CHITTY_API_KEY → API_KEYS KV lookup (binding) │
// │ CF_ACCOUNT_ID → removed, use CHITTYOS_ACCOUNT_ID │
// │ CLOUDFLARE_ACCOUNT_ID → removed, use CHITTYOS_ACCOUNT_ID │
// │ CHITTY_SERVICE_TOKEN → removed, use CHITTY_ID_TOKEN │
// │ CHITTY_ID_SERVICE_TOKEN → removed, use CHITTY_ID_TOKEN │
// │ CHITTY_API_KEY → removed (dead code) │
Copy link

Copilot AI Mar 26, 2026

Choose a reason for hiding this comment

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

The header says these aliases are “removed from code — DO NOT re-add”, but there are still active references to CLOUDFLARE_ACCOUNT_ID in the repo (e.g. GitHub workflows and scripts). Either update the remaining references as part of this refactor, or clarify the comment scope (e.g. “removed from Worker runtime code” / “still used as external GitHub secret contract”).

Copilot uses AI. Check for mistakes.
Comment on lines +75 to +83
# Credential Provisioning & Emergency
# Note: CHITTYOS_ACCOUNT_ID is a wrangler var, not a secret — no deployment needed
"ENCRYPTION_KEY|$VAULT_EMERGENCY|encryption|key"
"INTERNAL_WEBHOOK_SECRET|$VAULT_EMERGENCY|internal-webhook|secret"
"OP_EVENTS_API_TOKEN|$VAULT_EMERGENCY|1password-events|api_token"
"EMERGENCY_REVOKE_TOKEN|$VAULT_EMERGENCY|emergency-revoke|token"

# Google Integration
"GOOGLE_ACCESS_TOKEN|$VAULT_INTEGRATIONS|google-drive|access_token"
Copy link

Copilot AI Mar 26, 2026

Choose a reason for hiding this comment

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

deploy-missing-secrets.sh says this list is “in the manifest AND used in code”, but EMERGENCY_REVOKE_TOKEN doesn’t appear to be referenced anywhere in src/ (searching the repo only finds it in docs/manifest comments). If this token is intentionally pre-provisioned for future use, consider moving it into a separate “not yet used” section or updating the comment so the script output isn’t interpreted as an actionable runtime requirement.

Copilot uses AI. Check for mistakes.
Copy link

@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: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@migrations/013_connections.sql`:
- Line 52: The migration currently uses an INSERT OR IGNORE for the
conn-chittyid row which will not change existing records; add an UPDATE after
the INSERT to set the new service_token_pattern ('CHITTY_ID_TOKEN') and any
other changed columns for rows where id = 'conn-chittyid' so existing
deployments are migrated; target the same table and the same unique id
'conn-chittyid' (the row inserted in migrations/013_connections.sql) and ensure
the UPDATE runs unconditionally after the INSERT OR IGNORE to overwrite the old
CHITTY_ID_SERVICE_TOKEN pattern.

In `@tests/lib/cloudflare-api-helper.test.js`:
- Around line 73-78: The test currently sets env.CHITTYOS_ACCOUNT_ID which
prevents exercising the getCredential fallback; update the test so
CHITTYOS_ACCOUNT_ID is not present (e.g., set env = {} or delete
CHITTYOS_ACCOUNT_ID) and keep the getCredential mocks
(.mockResolvedValueOnce("op-api-token") then .mockResolvedValueOnce("acct-456"))
so the code path in the function that reads CHITTYOS_ACCOUNT_ID falls back to
getCredential is actually executed and validated.

In `@wrangler.jsonc`:
- Line 313: Remove the duplicate secret entry for CHITTY_ID_TOKEN: locate the
second occurrence of "CHITTY_ID_TOKEN" (the entry with description "ChittyID
service auth token") and delete that entire line so only the original entry
(description "ChittyID service auth") remains in the secrets manifest; ensure no
other duplicate CHITTY_ID_TOKEN entries remain.
🪄 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: a2d2d920-681e-4674-9dd9-d70a8173f7bb

📥 Commits

Reviewing files that changed from the base of the PR and between 89cf77c and d6031c9.

📒 Files selected for processing (19)
  • .github/secret-catalog.json
  • .github/workflows/sync-secrets.yml
  • CLAUDE.md
  • migrations/013_connections.sql
  • scripts/deploy-missing-secrets.sh
  • src/api/routes/credentials.js
  • src/api/routes/thirdparty.js
  • src/intelligence/__tests__/context-intelligence.test.js
  • src/intelligence/__tests__/experience-anchor.test.js
  • src/intelligence/context-intelligence.js
  • src/intelligence/experience-anchor.js
  • src/lib/chittyid-client.js
  • src/lib/cloudflare-api-helper.js
  • src/mcp/tool-dispatcher.js
  • src/services/credential-provisioner.js
  • tests/helpers/mocks.js
  • tests/intelligence/experience-anchor.test.js
  • tests/lib/cloudflare-api-helper.test.js
  • wrangler.jsonc

-- Seed: ChittyOS Services (Tier 0-5)
INSERT OR IGNORE INTO connections (id, name, slug, category, provider, base_url, health_endpoint, tier, credential_source, service_token_pattern, status, description, icon, depends_on) VALUES
('conn-chittyid', 'ChittyID', 'chittyid', 'chittyos_service', 'chittyos', 'https://id.chitty.cc', '/health', 0, 'env', 'CHITTY_ID_SERVICE_TOKEN', 'active', 'Identity minting and validation', 'ID', '[]'),
('conn-chittyid', 'ChittyID', 'chittyid', 'chittyos_service', 'chittyos', 'https://id.chitty.cc', '/health', 0, 'env', 'CHITTY_ID_TOKEN', 'active', 'Identity minting and validation', 'ID', '[]'),
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Migration will not update existing database rows.

The INSERT OR IGNORE statement only inserts new rows—it won't update the service_token_pattern for the conn-chittyid row if it already exists in production. Since src/api/routes/connections.js dynamically looks up credentials via c.env[conn.service_token_pattern] (line 752), existing deployments will continue using the old CHITTY_ID_SERVICE_TOKEN pattern and fail silently when that env var no longer exists.

Add an UPDATE statement to fix existing rows:

Proposed fix: Add UPDATE for existing rows
 INSERT OR IGNORE INTO connections (id, name, slug, category, provider, base_url, health_endpoint, tier, credential_source, service_token_pattern, status, description, icon, depends_on) VALUES
   ('conn-chittyid', 'ChittyID', 'chittyid', 'chittyos_service', 'chittyos', 'https://id.chitty.cc', '/health', 0, 'env', 'CHITTY_ID_TOKEN', 'active', 'Identity minting and validation', 'ID', '[]'),
   ...

+-- Update existing row if it has the old token pattern
+UPDATE connections SET service_token_pattern = 'CHITTY_ID_TOKEN' WHERE id = 'conn-chittyid' AND service_token_pattern = 'CHITTY_ID_SERVICE_TOKEN';

Based on learnings: "All database changes must be coordinated with other ChittyOS services."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@migrations/013_connections.sql` at line 52, The migration currently uses an
INSERT OR IGNORE for the conn-chittyid row which will not change existing
records; add an UPDATE after the INSERT to set the new service_token_pattern
('CHITTY_ID_TOKEN') and any other changed columns for rows where id =
'conn-chittyid' so existing deployments are migrated; target the same table and
the same unique id 'conn-chittyid' (the row inserted in
migrations/013_connections.sql) and ensure the UPDATE runs unconditionally after
the INSERT OR IGNORE to overwrite the old CHITTY_ID_SERVICE_TOKEN pattern.

Comment on lines +73 to 78
it("falls back to CHITTYOS_ACCOUNT_ID via getCredential", async () => {
getCredential
.mockResolvedValueOnce("op-api-token") // apiToken
.mockResolvedValueOnce("acct-456"); // accountId via env fallback
const env = { CLOUDFLARE_ACCOUNT_ID: "acct-456" };
.mockResolvedValueOnce("acct-456"); // accountId via getCredential
const env = { CHITTYOS_ACCOUNT_ID: "acct-456" };

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fix the fallback test so it actually exercises credential fallback.

The test title says fallback is via getCredential, but env.CHITTYOS_ACCOUNT_ID is pre-populated, so it validates env resolution instead. This can hide fallback regressions.

✅ Suggested test adjustment
 it("falls back to CHITTYOS_ACCOUNT_ID via getCredential", async () => {
   getCredential
     .mockResolvedValueOnce("op-api-token") // apiToken
     .mockResolvedValueOnce("acct-456"); // accountId via getCredential
-  const env = { CHITTYOS_ACCOUNT_ID: "acct-456" };
+  const env = {};

   const { accountId } = await getCloudflareApiCredentials(env);
   expect(accountId).toBe("acct-456");
+  expect(getCredential).toHaveBeenCalledTimes(2);
 });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/lib/cloudflare-api-helper.test.js` around lines 73 - 78, The test
currently sets env.CHITTYOS_ACCOUNT_ID which prevents exercising the
getCredential fallback; update the test so CHITTYOS_ACCOUNT_ID is not present
(e.g., set env = {} or delete CHITTYOS_ACCOUNT_ID) and keep the getCredential
mocks (.mockResolvedValueOnce("op-api-token") then
.mockResolvedValueOnce("acct-456")) so the code path in the function that reads
CHITTYOS_ACCOUNT_ID falls back to getCredential is actually executed and
validated.

// │ CHITTY_DISPUTES_TOKEN ChittyDisputes service auth │
// │ CHITTY_LEDGER_TOKEN ChittyLedger service auth │
// │ CHITTY_ID_SERVICE_TOKEN ChittyID generic service token │
// │ CHITTY_ID_TOKEN ChittyID service auth token
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Duplicate entry in secrets manifest.

CHITTY_ID_TOKEN is already listed at line 294 with description "ChittyID service auth". Line 313 adds a second entry "ChittyID service auth token". Remove the duplicate to keep the manifest clean.

Proposed fix

Remove line 313 entirely since line 294 already documents this secret:

 // │ CHITTY_LEDGER_TOKEN        ChittyLedger service auth          │
-// │ CHITTY_ID_TOKEN            ChittyID service auth token          │
 // │ CHITTYCONNECT_SERVICE_TOKEN ChittyConnect self-service token   │
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
//CHITTY_ID_TOKEN ChittyID service auth token
//CHITTY_LEDGER_TOKEN ChittyLedger service auth │
// │ CHITTYCONNECT_SERVICE_TOKEN ChittyConnect self-service token │
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@wrangler.jsonc` at line 313, Remove the duplicate secret entry for
CHITTY_ID_TOKEN: locate the second occurrence of "CHITTY_ID_TOKEN" (the entry
with description "ChittyID service auth token") and delete that entire line so
only the original entry (description "ChittyID service auth") remains in the
secrets manifest; ensure no other duplicate CHITTY_ID_TOKEN entries remain.

@chitcommit chitcommit added security-approved Security review approved docs-approved Documentation review approved access-reviewed Access control review approved labels Mar 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

access-reviewed Access control review approved docs-approved Documentation review approved security-approved Security review approved

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants