# 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`) or managing delegates
*   **Foreign Pools**: Inward delegation to external identities (SSO co-signing 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`).

## Delegation (Inward vs. Outward)

Keystones support both **Inward Delegation** (bringing external keys inside this identity) and **Outward Delegation** (externalizing keystone responsibilities to other keystones).

### 1. Inward Delegation (Foreign Pools)
Alice can delegate co-signing rights to Bob (e.g., for Single Sign-On) by embedding Bob's challenge pool in her Keystone. Bob can then sign claims on Alice's behalf without ever exposing Alice's master secret, sharing Bob's master secret, or requiring co-located servers.

### 2. Outward Delegation (Delegate Keystones)
Alice can authorize entire external keystones to act on her behalf (e.g., authorizing a specific client keystone to sync data or sign messages) by adding them to her keystone's `delegates` map:
*   **Manage Verb Authorized**: Adding or removing a delegate modifies the keystone's metadata. This transition is strictly rejected during validation unless authorized by a signature proof using the parent's `manage` pool (`KEYSTONE_VERB_MANAGE`).
*   **Ancestry Linkage**: The delegate registration records the exact frame (`thisAddr`) in the parent timeline where the delegation is active. The validator enforces that `thisAddr` is a valid historical or current frame in the parent's timeline ancestry, preventing delegate replay or hijack attacks.
*   **Soft-Linking**: Keeps delegate keystones "pure" and independent (with their own pools/lifecycle) while maintaining secure, verifiable delegation on the parent.

## 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
