# 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.
*   **[Security Profiles & Policies](./docs/profiles.md)**: Using prebuilt profiles (test, session, low, medium, high) and creating custom ones.
*   **[Cryptanalysis & Math](./docs/CRYPTANALYSIS.md)**: Mathematical models and security estimations for Keystone.

## 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:
*   **`id`**: Unique identifier within the keystone
*   **`allowedVerbs`**: Verbs this pool is authorized to sign (e.g., `['revoke']`, `['manage']`)
*   **`algo` / `rounds`**: Hashing algorithm and KDF iteration count
*   **`behavior`**: Rules for capacity (`size`), replenishment (`replenish`), sequential/random consumption (`selectSequentially`/`selectRandomly`), and target binding (`targetBindingCount`).

## Basic Usage

### Genesis (Create Identity)

Using standard pool config factory helpers:

```typescript
import { createStandardPoolConfig, createRevocationPoolConfig } from "./keystone-config-builder.mjs";

const keystone = await keystoneService.genesis({
  masterSecret: "user-password",
  configs: [
    createStandardPoolConfig({ id: 'default', salt: 'default_salt' }),
    createRevocationPoolConfig({ id: 'revoke', salt: 'revoke_salt' })
  ],
  metaspace,
  space
});
```

### Sign a Claim

```typescript
const signedKeystone = await keystoneService.sign({
  latestKeystone: keystone,
  claim: { verb: 'sync', target: 'some_target_addr^gib', timestamp: Date.now() },
  masterSecret: "user-password",
  poolId: 'default', // or omit to 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: [
    createStandardPoolConfig({
      id: 'bob-sso',
      salt: 'bob-sso-salt',
      verbs: ['login']
    })
  ],
  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
