# Keystone Security Profiles & Policies

Keystone configurations are standardized using JSON-based Policy Profiles. These profiles allow downstream applications to select predefined security levels (from `test` to `high`) or define custom ones that validate against a strict JSON Schema.

---

## 1. Predefined Security Profiles

The repository provides five prebuilt profiles in `@ibgib/core-gib/dist/keystone/profiles/`:

| Profile | Target Size | Hash Algo | Rounds | Selection (Seq+Rand) | Binding Count | Use Case |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| **`test`** | 12 | SHA-256 | 1 | 1 + 1 | 3 | Fast development / unit tests. |
| **`session`** | 50 | SHA-256 | 1 | 2 + 2 | 6 | Short-lived WS sync sagas (connect). |
| **`low`** | 100 | SHA-256 | 1 | 3 + 3 | 8 | Medium lifespan, low-overhead client keys. |
| **`medium`** | 500 | SHA-256 | 2 | 5 + 5 | 10 | Standard production identity keys. |
| **`high`** | 2000 | SHA-512 | 4 | 10 + 10 | 16 | High-security cold/warm root keys. |

---

## 2. Consuming Profile Policies in Code

To apply a profile to a Keystone identity at genesis, import the JSON file and use the `createPoolConfigFromJson` factory helper:

### Example: Initializing Genesis with the Medium Profile

```typescript
import { KeystoneService_V1 } from "@ibgib/core-gib/dist/keystone/keystone-service-v1.mjs";
import { createPoolConfigFromJson } from "@ibgib/core-gib/dist/keystone/keystone-config-builder.mjs";

// Import the prebuilt profile JSON
import profileMedium from "@ibgib/core-gib/dist/keystone/profiles/profile-medium.json" assert { type: 'json' };

async function createIdentity(masterSecret: string, metaspace: any, space: any) {
    // 1. Map the JSON templates to concrete KeystonePoolConfig objects
    const configs = Object.values(profileMedium.pools).map(template => {
        return createPoolConfigFromJson({
            template: template as any,
            behaviorProfiles: profileMedium.behaviorProfiles as any,
            salt: `${template.id}_pool_salt` // Unique salt per pool
        });
    });

    // 2. Perform genesis
    const keystoneService = new KeystoneService_V1();
    const keystoneIbGib = await keystoneService.genesis({
        masterSecret,
        configs,
        metaspace,
        space,
        frameDetails: { client: 'my-app', timestamp: Date.now() }
    });

    return keystoneIbGib;
}
```

---

## 3. Creating Custom Profiles

Custom policy profiles must match the JSON Schema at [keystone-policy.schema.json](../keystone-policy.schema.json). 

### Structure of a Profile JSON File

```json
{
  "$schema": "../keystone-policy.schema.json",
  "behaviorProfiles": {
    "my-custom-behavior": {
      "size": 300,
      "replenish": "top-up",
      "selectSequentially": 3,
      "selectRandomly": 3,
      "targetBindingCount": 8
    }
  },
  "pools": {
    "sync": {
      "id": "sync",
      "allowedVerbs": ["sync"],
      "behaviorProfile": "my-custom-behavior",
      "algo": "SHA-256",
      "rounds": 2
    },
    "manage": {
      "id": "manage",
      "allowedVerbs": ["manage"],
      "behaviorInline": {
        "size": 1000,
        "replenish": "replace-all",
        "selectSequentially": 5,
        "selectRandomly": 5,
        "targetBindingCount": 12
      },
      "algo": "SHA-512",
      "rounds": 5
    }
  }
}
```

### Property Reference

#### behaviorProfiles
A dictionary of shared behavior templates. Each template contains:
*   **`size`**: `number`. The capacity of the challenge pool.
*   **`replenish`**: `string`. The strategy for refilling the pool when challenges are consumed:
    *   `"top-up"`: Generates new challenges to replace only those used. Recommended for normal, reusable signing keys.
    *   `"replace-all"`: Discards the remaining pool and generates a completely fresh set of challenges when any are used. Recommended for high-security pools to prevent long-term grinding.
    *   `"consume"`: Consumes challenges without replenishing them (limiting the total amount of evolutions possible).
    *   `"delete-all"`: Clears all challenges permanently (used for Scorched-Earth revocation).
*   **`selectSequentially`**: `number`. Number of challenges solved in FIFO order from the front of the pool.
*   **`selectRandomly`**: `number`. Number of challenges solved stochastically.
*   **`targetBindingCount`**: `number`. Number of challenges selected deterministically via the hash-based selection algorithm bound to the `targetAddr` of the claim.

#### pools
Defines the individual challenge pools for the keystone:
*   **`id`**: `string`. A unique identifier within the keystone frame.
*   **`allowedVerbs`**: `string[]`. List of verbs (operations) this pool is authorized to sign.
*   **`algo`**: `"SHA-256" | "SHA-512"`. Cryptographic hash algorithm used for challenges.
*   **`rounds`**: `number`. Number of iterations for the key derivation function (KDF) challenge loop.
*   **`behaviorProfile`**: `string`. (Optional) References a key in `behaviorProfiles`.
*   **`behaviorInline`**: `object`. (Optional) An inline declaration of behavior properties if not using a shared profile.
