Skip to content

Aegis Phase-0 + Phase-1 rule corpus, GIN-24 token reuse fix - #41

Merged
heybeaux merged 3 commits into
mainfrom
fix/gin-24-token-reuse
Jun 14, 2026
Merged

heybeaux merged 3 commits into
mainfrom
fix/gin-24-token-reuse

Conversation

@heybeaux

@heybeaux heybeaux commented Jun 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Aegis Phase-0 package (@heybeaux/lattice-aegis) — rule-pack + evaluation contract, ReDoS-guarded loader, 3-layer cascade merge with strictness invariant, combinator-aware safe-command allowlist, strictest_of(severity_floor, prediction) combination rule
  • Phase-1 rule corpus — 84-rule AutoHarness corpus ported to JSON rule packs
  • GIN-24 — close token reuse vulnerability with one-time-use TokenStore (prior work on this branch)

Test plan

  • 17/17 aegis tests pass
  • typecheck clean
  • build clean (tsup ESM)
  • CI green

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added Aegis governance harness with rule-based decision evaluation and safe-command assessment.
    • Added token store for authentication token issuance, consumption, rotation, and revocation.
    • Added security rule packs for bash, file access, injection, PII, and secrets detection.
  • Documentation

    • Added specification documents for Aegis system architecture, action-labeling, rule formats, and implementation phases.
    • Updated .gitignore to exclude coverage artifacts.
  • Tests

    • Added comprehensive test coverage for token store and rule evaluation workflows.
    • Added rulepack verification tooling.
  • Chores

    • Added package metadata and TypeScript/Vitest build configuration.

beaux-riel and others added 2 commits May 14, 2026 20:52
…tore

Introduces `packages/core/src/auth/token-store.ts` — a new `TokenStore`
class that enforces one-time-use semantics on every auth token category:

- One-time tokens (magic link, password reset, email verification):
  `consumeToken` atomically marks `usedAt` before returning; any replay
  raises `TokenAlreadyUsedError` with the original consumption timestamp.

- Refresh tokens: `rotateRefreshToken` invalidates the old record before
  issuing a replacement — no window exists between check and use. Replaying
  the rotated-away token raises `TokenAlreadyUsedError`.

- Logout: `revokeToken` marks a token revoked regardless of current status;
  subsequent consume or rotate calls raise `TokenRevokedError`.

Error precedence: used > revoked > expired, so replay detection always
surfaces the most actionable signal even when the token is also past TTL.

Adds 49 tests in `test/token-store.test.ts` covering:
  - Happy-path issue/consume/rotate/revoke
  - Replay attack scenarios for each token category
  - Token theft simulation (attacker replays stolen refresh token)
  - Expiry, revocation, and precedence edge cases
  - Immutability of returned `AuthToken` snapshots

All 359 tests pass (20 test files).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Scaffold @heybeaux/lattice-aegis (Phase 0) and port the AutoHarness
risk-rule corpus to JSON rule packs (Phase 1) for the predictive
governance harness.

- 106 rules across 5 packs (bash/file/injection/pii/secrets), traced
  to AutoHarness source and fidelity-audited; fixed 5 spurious regex
  flags that broadened matching beyond source
- rule loader (validate, flag-restrict, ReDoS budget guard), 3-layer
  merge cascade with strictness invariant, combinator-aware safe-command
  allowlist, strictest-of evaluation contract
- verify-rulepacks.mjs (all green), 17 package tests passing
- design docs: build plan, rulepack spec, action_failed label spec,
  Sonder Phase-3.5 scope

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@heybeaux, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 50 minutes and 56 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 34a551f6-8dfd-4c9d-9549-d6b1101a3fd3

📥 Commits

Reviewing files that changed from the base of the PR and between 026a48b and 4d44e62.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • .gitignore
  • packages/core/src/index.ts
📝 Walkthrough

Walkthrough

Introduces the @heybeaux/lattice-aegis governance harness package (type contracts, fail-closed rule loader, merge engine, evaluator combining deterministic severity with AWM prediction, five built-in JSON rule packs, a verification script, and four design/spec docs) and adds a new in-memory TokenStore to @heybeaux/lattice-core supporting one-time/refresh token lifecycle, revocation, replay-attack rejection, and frozen snapshots.

Changes

Aegis governance harness (packages/aegis)

Layer / File(s) Summary
Type contracts and package scaffold
packages/aegis/src/types.ts, packages/aegis/src/index.ts, packages/aegis/package.json, packages/aegis/tsconfig.json, packages/aegis/vitest.config.ts
Defines all exported Aegis TypeScript types (Severity, GateAction, Rule, RulePack, CompiledRule, ToolCall, Evaluation, Prediction, thresholds/tables) and wires the package entrypoint, build, and test config.
Rule loader and merge engine
packages/aegis/src/rules/loader.ts, packages/aegis/src/rules/merge.ts
loadPack validates flags, compiles regexes, performs load-time ReDoS probing, and detects duplicate IDs (fail-closed); mergeLayers applies builtin→user→project precedence with strictness-downgrade protection and MergeWarning emission.
Evaluation engine and safe-command utility
packages/aegis/src/eval/evaluate.ts, packages/aegis/src/eval/safe-command.ts
evaluate computes a severity-floor action from matched rules and overlays an optional AWM Prediction via configurable probability thresholds, returning the strictest of the two with decidedBy metadata; isSafeCommand gates commands via a combinator denylist and leading-token allowlist.
Built-in rule packs corpus
packages/aegis/rulepacks/bash.json, packages/aegis/rulepacks/file.json, packages/aegis/rulepacks/injection.json, packages/aegis/rulepacks/pii.json, packages/aegis/rulepacks/secrets.json, packages/aegis/scripts/verify-rulepacks.mjs
Adds five built-in JSON rule packs (bash destructive/privesc/obfuscation, file sensitive path write/read, prompt injection phrases and model-token delimiters, PII, and secrets/API keys) plus a standalone verification script that runs loadPack against every pack and exits non-zero on any failure.
Aegis test suite
packages/aegis/test/evaluate.test.ts
Covers loadPack compilation and rejection, evaluate severity-floor and prediction-overlay escalation semantics, mergeLayers strictness invariants, and isSafeCommand combinator/allowlist behavior.
Aegis design and spec docs
docs/autoharness-killer-build-plan-2026-06-14.md, docs/aegis-rulepack-spec-2026-06-14.md, docs/aegis-action-failed-label-spec-2026-06-14.md, docs/aegis-phase35-sonder-scope-2026-06-14.md
Four specification documents: build plan (architecture, phases, AWM predictive layer), rule-pack spec (JSON schema, regex porting, merge/gate-action mapping), action_failed label spec (feature row, outcome window, training loop, open decisions), and Phase 3.5 Sonder scope (typed OUTCOME event, parent_id column, paths envelope field, adapter contribute() path).

Core TokenStore (packages/core)

Layer / File(s) Summary
Token types, interfaces, and error classes
packages/core/src/auth/token-store.ts (lines 1–173)
Defines TokenKind, TokenStatus, AuthToken, RotateResult, TokenStoreOptions, and four typed error classes (TokenNotFoundError, TokenAlreadyUsedError, TokenRevokedError, TokenExpiredError).
TokenStore class implementation
packages/core/src/auth/token-store.ts (lines 179–448)
Implements issueToken (ULID, TTL, frozen record), consumeToken (used→revoked→expired guard), rotateRefreshToken (atomic old-mark + new-issue), revokeToken (idempotent), findToken, clear(), size, and private requireRecord/assertConsumable helpers.
Re-exports and test suite
packages/core/src/auth/index.ts, packages/core/src/index.ts, packages/core/test/token-store.test.ts
Barrel-exports TokenStore, error classes, and types through the core public API; adds Vitest tests covering issuance, lookup, consumption, rotation, revocation, replay-attack rejection across all token states, error precedence ordering, clear(), non-expiring tokens, and AuthToken snapshot immutability.

Sequence Diagram(s)

sequenceDiagram
  participant Hook as aegis-hook (PreToolUse)
  participant Loader as loadPack / mergeLayers
  participant Evaluator as evaluate
  participant SafeCmd as isSafeCommand
  participant Sonder as Sonder checkGate

  Hook->>Loader: load + merge builtin/user/project packs
  Loader-->>Evaluator: CompiledRule[]
  Hook->>SafeCmd: isSafeCommand(command, allowlist)
  SafeCmd-->>Hook: true / false (fast path)
  Hook->>Evaluator: evaluate(ToolCall, CompiledRule[], opts{prediction})
  Evaluator->>Evaluator: iterate rules → RuleHit[], maxSeverity
  Evaluator->>Evaluator: severityFloorAction via SeverityTable
  Evaluator->>Evaluator: predictionAction via PredictionThresholds
  Evaluator->>Evaluator: strictestOf → Evaluation{action, decidedBy}
  Evaluator-->>Hook: Evaluation
  Hook->>Sonder: checkGate(Evaluation.action, signedEvidence)
  Sonder-->>Hook: veto / allow (signed audit entry)
Loading
sequenceDiagram
  participant Client
  participant TokenStore
  participant ErrorHandler

  Client->>TokenStore: issueToken(userId, purpose, {kind, expiresInMs})
  TokenStore-->>Client: AuthToken (frozen, pending)

  Client->>TokenStore: consumeToken(value)
  TokenStore->>TokenStore: requireRecord → assertConsumable
  alt token reused / revoked / expired
    TokenStore-->>ErrorHandler: TokenAlreadyUsedError / TokenRevokedError / TokenExpiredError
  else valid
    TokenStore-->>Client: AuthToken (used, usedAt set)
  end

  Client->>TokenStore: rotateRefreshToken(value)
  TokenStore->>TokenStore: enforce kind=refresh, assertConsumable
  TokenStore->>TokenStore: mark old used, issueToken new refresh
  TokenStore-->>Client: RotateResult {consumed, next}

  Client->>TokenStore: revokeToken(value)
  TokenStore->>TokenStore: idempotent revoke (no-op if missing/already revoked)
  TokenStore-->>Client: void
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 Hop, hop, a rulepack in hand,
RegExp flags checked — no g shall stand!
Token rotates, the old one sleeps,
severity floor the rabbit keeps.
deny > ask > allow, so strict,
AWM predicts before we're tricked! 🔒

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.41% 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 two main components: Aegis Phase-0 and Phase-1 rule corpus work, plus the GIN-24 token reuse fix, matching the substantial changes across both aegis package implementation and core token-store security improvements.
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 fix/gin-24-token-reuse

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.

@heybeaux
heybeaux merged commit 8fb89ef into main Jun 14, 2026
0 of 4 checks passed
@heybeaux
heybeaux deleted the fix/gin-24-token-reuse branch June 14, 2026 22:35
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.

2 participants