# Keystone Identity Policies & Fluent Builder

This module manages Keystone Identity Policies, including security preset profiles (`high`, `medium`, `low`), modular schema composition, and the fluent configuration builder.

---

## 📖 Documentation Index

*   **[Policy Architecture](../../../../../docs/identity/ARCHITECTURE.md)**: Conceptual design of separate pool behaviors, verbs, and composed schemas.
*   **[Implementation Roadmap](./IMPLEMENTATION.md)**: Current development checklist and tasks.

---

## 🛠️ Usage: Fluent Builder API

The `KeystoneProfileBuilder` provides a fluid interface to construct, enrich, and customize Keystone configurations before genesis.

### Basic Identity Creation

```typescript
import { KeystoneProfileBuilder } from "@ibgib/core-gib/dist/keystone/policy/keystone-profile-builder.mjs";

// Build a medium-security identity config salted for a specific user
const configs = KeystoneProfileBuilder
    .buildKeystone('medium')
    .withUsername('alice')
    .withEmail('alice@example.com')
    .withDescription('Main user identity for Space-Gib')
    .compileConfigs();

// Pass these configurations directly to genesis
const identity = await keystoneService.genesis({
    masterSecret,
    configs,
    metaspace,
    space
});
```

### Unifying Identity Details

The metadata provided to `withUsername`, `withEmail`, `withDescription`, and `withDetails` are automatically consolidated into the unified `frameDetails` field of the genesis frame:

```typescript
const configs = KeystoneProfileBuilder
    .buildKeystone('low')
    .withUsername('bob')
    .withDetails({
        device: 'Pixel 8 Pro',
        os: 'Android 14'
    })
    .compileConfigs();
```

### Runtime Customizations

If an application needs to customize a specific pool's parameters dynamically (for example, raising KDF hash rounds on the sync pool for higher-security environments), use `customizePool`:

```typescript
const configs = KeystoneProfileBuilder
    .buildKeystone('primary-profile.dev')
    .withUsername('charlie')
    .customizePool('sync', {
        template: {
            config: {
                options: { saltRounds: 5 } // Override default salt rounds
            }
        }
    })
    .compileConfigs();
```

---

## 🧩 Custom Profiles for Downstream Applications

Downstream applications, enterprise consumers, and test suites can define and consume bespoke keystone policies without modifying `core-gib` source files.

### 1. In-Memory Custom Profile Registration (`registerCustomProfile`)

Register custom policy templates in memory by name (e.g. at application startup):

```typescript
import { KeystoneProfileBuilder } from "@ibgib/core-gib/dist/keystone/policy/keystone-profile-builder.mjs";
import enterpriseSyncProfile from "./enterprise-sync.json" with { type: "json" };

// Register the custom profile once at boot
KeystoneProfileBuilder.registerCustomProfile({
    name: 'sync-profile.enterprise',
    template: enterpriseSyncProfile
});

// Consume anywhere in the application by name
const configs = KeystoneProfileBuilder
    .buildKeystone('sync-profile.enterprise')
    .withUsername('enterprise-node')
    .compileConfigs();
```

### 2. Direct Template Consumption (`fromTemplate`)

Construct a builder instance directly from any JSON template object or inline policy definition:

```typescript
import { KeystoneProfileBuilder } from "@ibgib/core-gib/dist/keystone/policy/keystone-profile-builder.mjs";

const customPolicy = {
    metadata: {
        name: 'custom-sync-policy',
        defaultTtlSeconds: 86400
    },
    pools: [ /* ... */ ]
};

const builder = KeystoneProfileBuilder
    .fromTemplate(customPolicy)
    .withUsername('bot-user');

const configs = await builder.compileConfigs();
```

### 3. Short-TTL Test Profile (`sync-profile.test-short-ttl`)

For automated and manual testing of session expiration and the "Sign Back In" renewal flow, `core-gib` includes a built-in testing profile with a 10-second TTL:

```typescript
import { createSyncDelegateKeystone } from "@ibgib/core-gib/dist/keystone/delegate/delegate-helpers.mjs";

const shortLivedDelegate = await createSyncDelegateKeystone({
    profileName: 'sync-profile.test-short-ttl', // Expires in 10s
    username: 'alice',
    primaryTjpAddr,
    delegateSecret,
    metaspace,
    space
});
```

---

## ⚠️ TypeScript & JSON Config Integration

If downstream projects import or load their own JSON configurations (e.g., custom `.json` files representing schemas or behavior configurations) rather than relying solely on the built-in profiles, TypeScript requires explicit path tracking in projects using `"composite": true`.

To prevent compiler errors like `TS6307: File '...' is not listed within the file list...`, ensure your project's `tsconfig.json` contains:

1. `"resolveJsonModule": true` under `compilerOptions` to allow static importing of JSON files as ES modules.
2. The folder/wildcard path of the JSON files added to the `"include"` array. For example:

```json
{
  "compilerOptions": {
    "composite": true,
    "resolveJsonModule": true,
    "module": "ESNext"
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.mts",
    "src/custom-policies/*.json"
  ]
}
```

