# keystone-gib

"Keystones" are a new ibgib-specific identity mechanism that leverages ibgib's unique Merkle-based DLT structure.

## 📚 Documentation
*   **[Architecture](./docs/architecture.md)**: Detailed design of the Policy Engine, Hash-Based Cryptography, and Lifecycle.

## Overview
A **Keystone** is a "Stone" (ibgib without `dna`) used for Identity. It is a graph of ibgib frames that evolves over time but maintains a strict, verifiable lineage.

Validation in this system is **Auditability**: to verify an identity (e.g., "Is this Alice?"), one "replays" the Keystone timeline from its Genesis to the current Frame, verifying the cryptographic proofs at every step.

## Principles
1.  **DRY**: Leverages the ubiquity of ibgib's existing crypto hypergraph.
2.  **Non-Evil Root**: Prioritizes security/correctness over pre-optimization (signing speed).
3.  **Hash-based**: Uses hash pre-imaging for quantum resistance (`hash-reveal-v1`).
4.  **Merkle Graphs**: Efficient communication by only transmitting missing graph nodes.

## Challenge Pools

Keystones organize challenges into **pools** with specific purposes:

*   **Default Pool**: General-purpose signing operations
*   **Revoke Pool**: Permanent identity termination (one-time use, `verb: revoke`)
*   **Manage Pool**: Structural changes like adding pools (`verb: manage`)
*   **Foreign Pools**: Delegation to external identities (SSO-like workflows)

Each pool configuration specifies:
*   **`poolId`**: Unique identifier within the keystone
*   **`verb`**: Auto-routes operations (e.g., `revoke`, `manage`, `login`)
*   **`replenishStrategy`**: What to do after using challenges in a pool, e.g.
    `'top-up'`, `'replace-all'`, `'delete-all'`, etc.
*   **`challengeCount`**: Number of hash challenges in the pool

## Basic Usage

### Genesis (Create Identity)

```typescript
const keystone = await keystoneService.genesis({
  masterSecret: "user-password",
  configs: [
    { poolId: 'default', challengeCount: 100, replenishStrategy: KeystoneReplenishStrategy.topUp },
    { poolId: 'revoke', verb: 'revoke', challengeCount: 10, replenishStrategy: KeystoneReplenishStrategy.deleteAll }
  ],
  metaspace,
  space
});
```

### Sign a Claim

```typescript
const signedKeystone = await keystoneService.sign({
  latestKeystone: keystone,
  claim: { action: 'login', timestamp: Date.now() },
  masterSecret: "user-password",
  poolId: 'default', // or use verb-based auto-routing
  metaspace,
  space
});
```

### Revoke Identity

```typescript
await keystoneService.revoke({
  latestKeystone: keystone,
  reason: "Device compromised",
  masterSecret: "user-password",
  metaspace,
  space
});
```

## Delegation via Foreign Pools

> [!IMPORTANT]
> **🔑 Foreign pools enable delegation** - Alice can grant Bob signing authority for specific operations.

Alice can delegate signing authority to Bob by adding his challenge pool:

```typescript
const aliceWithBobPool = await keystoneService.addPools({
  latestKeystone: aliceKeystone,
  newPoolConfigs: [
    {
      poolId: 'bob-sso',
      verb: 'login',
      foreignServerUrl: 'https://bob-server.com',
      challengeCount: 50
    }
  ],
  masterSecret: aliceSecret,
  metaspace,
  space
});
```

Now Bob can sign login claims on Alice's behalf, but only for operations using the `login` verb.

**Trust Model**:
- Alice validates Bob's pool **shape** when adding (via `validateChallengePool`)
- Bob never transmits his secrets
- Communication secured via TLS
- Bob can validate his pool section when Alice evolves keystone

## Validation

To verify a keystone timeline:

1. **Replay** from genesis to current frame
2. **Verify** each proof's hash pre-images match challenges
3. **Validate** challenge selection matches policy engine rules
4. **Check** revocation status (if revoked, identity cannot evolve)

Validation helpers:
*   `validateEvolution()`: Verifies transition from previous to current frame
*   `validateKeystoneTimeline()`: Replays entire timeline from genesis

## Integration with Sync

Keystones integrate with the sync protocol to provide **session identity**:

*   **Session Keystones**: Ephemeral identities created per sync saga
*   **Saga Binding**: Session keystone salted with `sagaId`
*   **Signature Frames**: Each saga frame can be signed with session identity

> [!CAUTION]
> **🚧 Session identity integration is NOT yet functional.** See [sync README](file:../sync/README.md#session-identity-usesessionidentity) for current status.

## Implementation

The v1 implementation creates a pure TypeScript, isomorphic, hash-based identity system. It is designed to be "Non-Evil" and "Graph-Native".

**Key Files**:
*   [keystone-service-v1.mts](file:./keystone-service-v1.mts): Core service implementation
*   [keystone-types.mts](file:./keystone-types.mts): TypeScript type definitions
*   [keystone-helpers.mts](file:./keystone-helpers.mts): Utility functions
