Skip to content

fix(auth): correct entity type T→P for context ChittyIDs#49

Open
chitcommit wants to merge 1 commit intomainfrom
fix/entity-type-correction
Open

fix(auth): correct entity type T→P for context ChittyIDs#49
chitcommit wants to merge 1 commit intomainfrom
fix/entity-type-correction

Conversation

@chitcommit
Copy link
Contributor

@chitcommit chitcommit commented Mar 17, 2026

Summary

  • ChittyMint ignores entity_type=P param, always returns T (Thing) for context mints
  • Client-side correction: detects mismatch, swaps T→P, recalculates mod-97 checksum
  • Fixes createLocalContext to persist minted ChittyID when DB is unavailable (was hardcoded to "UNBOUND")

Test plan

  • can chitty authenticate-context produces ChittyID with P entity type
  • session_binding.json persists corrected ChittyID (not "UNBOUND")
  • Checksum recalculation is valid
  • Upstream ChittyMint fix still needed (tracked separately)

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Authentication identifiers are now automatically validated and corrected with recalculated checksums when formatting issues are detected, ensuring consistent format compliance throughout the authentication process.
    • Context binding propagation has been enhanced for offline and disconnected scenarios with improved fallback mechanisms to maintain proper session connectivity when database operations fail.

ChittyMint ignores the entity_type=P parameter and always returns T (Thing).
Contexts are Person (P) per canonical governance (chittycanon://gov/governance#core-types).

This client-side correction:
- Detects entity type mismatch after minting
- Replaces T with P in the ChittyID segment
- Recalculates mod-97 checksum for the corrected ID
- Persists the minted ChittyID even when ChittyCanon DB is unavailable
  (previously fell back to "UNBOUND" losing the minted ID)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@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.

@chitcommit chitcommit enabled auto-merge (squash) March 17, 2026 00:10
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2026

📝 Walkthrough

Walkthrough

The pull request modifies ChittyID minting and context binding logic to validate and correct entity type segments to "P" during authentication, recalculate checksums when corrections are made, and propagate the corrected ChittyID through both database and local context creation paths, including fallback scenarios.

Changes

Cohort / File(s) Summary
ChittyID Validation & Correction
src/commands/hook-handlers.ts
Added validation logic to detect when entity type segment is not "P" during ChittyID minting, corrects it, recalculates checksum, and uses the corrected ID for context creation and logging. Includes infrastructure comment documenting entity type canonicalization on client side.
Context Binding Propagation
src/commands/hook-handlers.ts
Extended createLocalContext flow to accept optional mintedChittyId parameter and propagate it into ContextBinding. Updated database insertion fallback to pass mintedChittyId to local context creation, ensuring correct ChittyID binding in offline scenarios (defaults to "UNBOUND" when absent).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

🐰 A ChittyID hops along so true,
Entity type now checks: is it "P"? If not, we'll fix the view!
Checksums dance, contexts bind tight,
From database to offline, the ID flows just right! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides a clear summary and test plan, but omits several required template sections including type of change, motivation/context, testing methodology, and the standard checklist items. Complete the description by adding the Type of Change checkbox, Motivation and Context section, testing details with configuration, and the required checklist items per the repository template.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: correcting entity type from T to P for context ChittyIDs during authentication.
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 (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/entity-type-correction
📝 Coding Plan
  • Generate coding plan for human review comments

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
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: 1

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

Inline comments:
In `@src/commands/hook-handlers.ts`:
- Around line 564-573: The checksum recompute can throw when numericStr contains
unexpected chars; update the correction path that manipulates chittyId/segments
(the block using variables chittyId, segments, numericStr, checksum) to: strip
known prefixes like "did:chitty:" and any colons, convert to upper case, then
build numericStr by removing any non-alphanumeric characters and mapping A–Z to
10–35 (use /[A-Z]/g and /[0-9]/), e.g. replace letters with (charCodeAt-55) and
keep digits as-is; validate numericStr is non-empty and wrap the BigInt(...)
conversion and mod-97 logic in a try/catch to handle failures (log an error and
skip correction or mark as invalid) so the code never throws on malformed IDs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e0ef5fc6-d191-4f0c-81be-5d6575ac9423

📥 Commits

Reviewing files that changed from the base of the PR and between 95473d5 and 64ce4b6.

📒 Files selected for processing (1)
  • src/commands/hook-handlers.ts

Comment on lines +564 to +573
const segments = chittyId.split("-");
let correctedId = chittyId;
if (segments[4] && segments[4] !== "P") {
console.log(` \x1b[33m⚠ Entity type mismatch: got '${segments[4]}', expected 'P' (Person) — correcting\x1b[0m`);
segments[4] = "P";
// Recalculate checksum (mod-97 of all segments except last)
const baseSegments = segments.slice(0, -1);
const numericStr = baseSegments.join("").replace(/[A-Z]/g, (c) => String(c.charCodeAt(0) - 55));
const checksum = String(98n - (BigInt(numericStr) % 97n)).padStart(2, "0");
segments[segments.length - 1] = checksum;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Potential runtime failure in checksum recompute path.

At Line 571–572, BigInt(numericStr) can throw when the minted ID includes non-numeric chars (e.g., did:chitty: prefix/lowercase/:), because only [A-Z] is normalized. This can break context auth even after a successful mint.

Suggested hardening
-          const baseSegments = segments.slice(0, -1);
-          const numericStr = baseSegments.join("").replace(/[A-Z]/g, (c) => String(c.charCodeAt(0) - 55));
-          const checksum = String(98n - (BigInt(numericStr) % 97n)).padStart(2, "0");
+          const baseSegments = segments.slice(0, -1);
+          // Normalize DID prefix + separators before numeric conversion
+          const normalized = baseSegments
+            .join("")
+            .replace(/^did:chitty:/i, "")
+            .replace(/[^a-zA-Z0-9]/g, "")
+            .toUpperCase();
+          const numericStr = normalized.replace(/[A-Z]/g, (c) => String(c.charCodeAt(0) - 55));
+          const checksum = String(98n - (BigInt(numericStr) % 97n)).padStart(2, "0");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/commands/hook-handlers.ts` around lines 564 - 573, The checksum recompute
can throw when numericStr contains unexpected chars; update the correction path
that manipulates chittyId/segments (the block using variables chittyId,
segments, numericStr, checksum) to: strip known prefixes like "did:chitty:" and
any colons, convert to upper case, then build numericStr by removing any
non-alphanumeric characters and mapping A–Z to 10–35 (use /[A-Z]/g and /[0-9]/),
e.g. replace letters with (charCodeAt-55) and keep digits as-is; validate
numericStr is non-empty and wrap the BigInt(...) conversion and mod-97 logic in
a try/catch to handle failures (log an error and skip correction or mark as
invalid) so the code never throws on malformed IDs.

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