# credorix — complete library (all audiences)

_Generated whole-library download. See `agent-manifest.json` → `library` for discovery._

## Table of contents

- **Platform Overview** (`00-platform-overview`, developers)
- **Platform Overview** (`00-platform-overview`, builders)
- **Architecture** (`01-architecture`, developers)
- **HTTP API** (`02-http-api`, developers)
- **Providers and Secrets** (`03-providers-and-secrets`, developers)
- **Security Model** (`04-security`, developers)
- **Security Model** (`04-security`, builders)
- **Production Hardening** (`05-production`, developers)
- **Production Hardening** (`05-production`, builders)
- **Memorix Integration** (`06-memorix-integration`, developers)
- **Connector Framework** (`07-connector-framework`, developers)

---

# Platform Overview — developers

# Platform Overview — Developers

**Audience:** Engineers wiring Credorix into callers, workers, and BFFs.  
**Related:** [Architecture](../../01-architecture/developers/BOOK.md) · [HTTP API](../../02-http-api/developers/BOOK.md)

---

## The central idea

**Credorix** is an isolated credential and authentication runtime for outbound service and API calls.

Applications reference a logical profile such as `authRef: "explorer-api"`. Credorix authenticates the caller, verifies that it may use the profile, resolves the underlying secret or identity, obtains or renews authentication, and either returns a short-lived credential lease or performs the request through a protected broker.

Business envelopes carry **refs**, never raw secrets.

---

## 1. What Credorix is

Credorix manages two different authentication relationships:

```text
1. Caller ──authenticates──▶ Credorix
2. Credorix/SDK ──authenticates──▶ destination
```

The first step is never skipped. Knowing an `authRef` does not grant access to it.

Credorix is not tied to Memorix. Memorix workers, Explorer, vendor integrations, pipeline systems, UIs and other products are ordinary consumers.

**Supported production shape:** one active Credorix process on a private network / VPN (not public internet, not multi-replica HA).

---

## 2. Packages

| Package | Purpose |
|---|---|
| `@x12i/credorix` | Convenience facade (`client` + `./core` + `./fastify`) |
| `@x12i/credorix-core` | Profiles, schemas, errors, redaction |
| `@x12i/credorix-client` | Lease client, auth injection, broker, 401 retry |
| `@x12i/credorix-providers` | Credential sources and built-in auth providers |
| `@x12i/credorix-fastify` | Inbound JWT/JWKS and static-Bearer guards |
| `@x12i/credorix-service` | Central registry, policy, lifecycle, broker (this repo) |
| `@x12i/credorix-docs` | Knowledge SDK for agents (devDependency only) |

```bash
npm install @x12i/credorix
npm i -D @x12i/credorix-docs   # agents / tooling
```

---

## 3. Where to go next

| Goal | Book |
|---|---|
| Runtime shape | Architecture (`01-architecture`) |
| Lease / broker / admin | HTTP API (`02-http-api`) |
| Schemes and secrets | Providers and Secrets (`03-providers-and-secrets`) |
| Invariants | Security Model (`04-security`) |
| Deploy | Production Hardening (`05-production`) |
| MPS / pipelines | Memorix Integration (`06-memorix-integration`) |

---

# Platform Overview — builders

# Platform Overview — Builders

**Audience:** Operators and platform builders deploying Credorix.  
**Related:** [Production Hardening](../../05-production/developers/BOOK.md) · [Security Model](../../04-security/developers/BOOK.md)

---

## The central idea

Credorix owns credentials and outbound auth for internal callers. Deploy one active owner on a private network; keep secrets out of product envelopes and browsers.

---

## 1. What Credorix is

Callers authenticate to Credorix, then request a lease or a brokered fetch against an `authRef`. Profiles hold **references** to secrets — not raw material.

---

## 2. Packages

Operators run `@x12i/credorix-service` from this monorepo (`npm start`). Downstream apps install `@x12i/credorix` / `@x12i/credorix-client`. Agents use `@x12i/credorix-docs` as a **devDependency**.

---

## 3. Where to go next

| Goal | Book |
|---|---|
| Deploy boundary + SERVICE_MODE | Production Hardening |
| Encryption, SSRF, rotation | Security Model |
| Admin API | HTTP API |

---

# Architecture — developers

# Architecture — Developers

**Audience:** Engineers extending or integrating the Credorix runtime.  
**Related:** [HTTP API](../../02-http-api/developers/BOOK.md) · [Security](../../04-security/developers/BOOK.md)

---

## Components

```text
Caller
  │ caller authentication
  ▼
Credorix HTTP service
  ├── CallerAuthenticator
  ├── ProfileRepository
  ├── CallerRepository
  ├── AuthEngine
  │    ├── authorization policy
  │    ├── provider registry
  │    ├── renewal coordination
  │    └── lease index
  ├── CredentialSource
  ├── TokenStateStore
  └── Broker network policy
```

---

## Profile resolution

An auth profile combines:

- provider scheme and provider configuration
- named credential references
- allowed callers
- single-tenant or multi-tenant policy
- delivery mode
- destination allowlist
- security and audit metadata

The profile never contains raw secret material.

---

## Cache identity

Authentication state is keyed by:

```text
authRef + audience + normalized scopes + tenant + delegated subject
```

This permits safe reuse when callers intentionally share one service identity, while separating tokens that differ in audience, scope, tenant or subject.

---

## Delivery modes

### Token lease

The authorized internal caller receives only the short-lived material needed for the request. Long-lived client credentials and refresh tokens stay in Credorix.

### Request broker

Credorix performs the target request. This is required for HMAC signing and recommended for high-impact credentials that must never enter application memory.

---

## Renewal coordination

One process-level single-flight promise prevents duplicate renewals for the same cache key inside a single active Credorix process. Multi-replica / distributed locking is unsupported; run only one active owner for mutating work.

---

## Extension interfaces

- `AuthProvider`
- `CredentialSource`
- `CallerAuthenticator`
- `TokenStateStore`

These are the stable seams for cloud, IdP, vault and persistence adapters.

---

# HTTP API — developers

# HTTP API — Developers

**Audience:** Engineers calling Credorix over HTTP or via `@x12i/credorix-client`.  
**Related:** [Architecture](../../01-architecture/developers/BOOK.md) · [Memorix Integration](../../06-memorix-integration/developers/BOOK.md)

---

## Public endpoints

### Health, readiness, and live view

- `GET /health` — liveness (`{ ok, service, package }`)
- `GET /ready` — readiness (persistence available)
- `GET /_live` — embeddable status + live request UI (`@x12i/api-live-view`)

### Metadata

`GET /metadata` returns sanitized capabilities for discovery (including the status UI):

- `service`, `package`, `version`, `persistence`
- `capabilities` — feature flags and supported schemes
- `endpoints[]` — `{ method, path, description, access }` (`public` \| `caller` \| `admin`)
- `operations[]` — tryable caller flows with examples

---

## Caller authentication

All caller routes require:

```http
Authorization: Bearer <caller-token>
X-Credorix-Caller: <caller-id>
```

`CallerAuthenticator` is injectable so production can replace bootstrap tokens with workload identity, JWT, SPIFFE or mTLS.

---

## Leases

### Obtain a lease

`POST /v1/leases`

```json
{
  "authRef": "vendor-api",
  "audience": "vendor",
  "scopes": ["read"],
  "tenantId": "org-123",
  "subject": "user-456",
  "forceRefresh": false
}
```

### Invalidate

`POST /v1/leases/:id/invalidate` with `{ "reason": "target_unauthorized" }` — idempotent.

### Profile metadata

`GET /v1/profiles/:id` returns sanitized metadata when the caller may use the profile. May include non-secret `consent` hints. Never includes credentials.

### Token-state ingest

`POST /v1/profiles/:id/token-state` binds consent-exchanged tokens into encrypted runtime state for an `oauth2-refresh-token` profile. Response never echoes tokens.

---

## Broker fetch

`POST /v1/broker/fetch`

```json
{
  "authRef": "vendor-api",
  "url": "https://vendor.example/v1/items",
  "method": "POST",
  "headers": { "x-correlation-id": "abc" },
  "body": { "query": "example" },
  "timeoutMs": 30000
}
```

Broker destinations are allowlisted. Prefer the broker for HMAC and high-impact credentials.

SDK helpers: `createCredorixClient`, lease APIs, and `brokerFetch` / Memorix pipeline helpers in `@x12i/credorix-client`.

---

## Administration API

Admin routes require:

```http
Authorization: Bearer <admin-token>
```

Mutating routes also require `Idempotency-Key`. Same key + same body → cached response; same key + different body → `409`.

---

## Profiles and callers

### Profiles

- `GET /admin/profiles`, `GET /admin/profiles/:id`
- `POST /admin/profiles`, `PUT /admin/profiles/:id`, `DELETE /admin/profiles/:id`
- `POST /admin/profiles/:id/token-state` — ops bootstrap of encrypted token state

### Callers

- `GET /admin/callers`
- `POST /admin/callers`, `PUT /admin/callers/:id`
- `POST /admin/callers/:id/rotate-token`

Raw token hashes and credential values are never returned.

---

# Providers and Secrets — developers

# Providers and Secrets — Developers

**Audience:** Engineers choosing schemes and wiring credential sources.  
**Related:** [Security](../../04-security/developers/BOOK.md) · [HTTP API](../../02-http-api/developers/BOOK.md)

---

## Built-in providers

| Scheme | Lease | Broker | Notes |
|---|---:|---:|---|
| Static Bearer | Yes | Yes | Re-read secret after invalidation/rotation |
| Projected token file | Yes | Yes | Re-read token file |
| API key | Yes | Yes | Header preferred; query only when enabled |
| Basic authentication | Yes | Yes | Username/password resolved separately |
| OAuth 2 client credentials | Yes | Yes | App-only; proactive renewal |
| OAuth 2 refresh token | Yes | Yes | Rotated refresh state encrypted; optional ingest seeding |
| HMAC-SHA256 request signing | No | Yes | Sign every request |
| Custom provider | Provider-defined | Provider-defined | Via `AuthProvider` |

OAuth client-credentials supports `client_secret_basic`, `client_secret_post`, public-client `none`, audience, resource, scopes, and extra form fields.

---

## Credential sources

Profiles reference secrets via URI schemes such as:

- `env://VAR_NAME`
- `file://relative/path`
- `memory://name` for tests

`CredentialSource` is pluggable for Vault, Azure Key Vault, AWS Secrets Manager, Google Secret Manager, Kubernetes CSI, HSM/KMS or another secure store.

Persisted profiles, callers, and token state are always AES-256-GCM encrypted with `CREDORIX_MASTER_KEY` (Mongo or on-disk) — independent of where source secrets live.

---

## Choosing a scheme

| Destination need | Prefer |
|---|---|
| Fixed service token | Static Bearer or API key |
| K8s / projected workload token | Token file |
| App-only OAuth (client id/secret) | OAuth 2 client credentials |
| User-delegated OAuth after BFF consent | OAuth 2 refresh token + token-state ingest |
| HMAC signed requests | HMAC (broker only) |
| Secret must never enter app memory | Broker delivery |

Workers and pipelines should emit `credentialRef` / `tokenRef` values that match Credorix profile ids — never materialize secrets into envelopes.

---

# Security Model — developers

# Security Model — Developers

**Audience:** Engineers and operators enforcing Credorix security invariants.  
**Related:** [Production](../../05-production/developers/BOOK.md) · [Providers](../../03-providers-and-secrets/developers/BOOK.md)

---

## Invariants

1. Business payloads never contain credentials.
2. Profile records contain references, not raw secrets.
3. Refresh tokens never leave the service (including after consent ingest — GET profiles never returns token state).
4. A caller must be authenticated and independently authorized for the requested profile.
5. Multi-tenant values participate in authorization and cache identity.
6. Broker destinations are allowlisted.
7. Sensitive keys are redacted from logs and errors.
8. Authentication failures retry at most once at the SDK boundary.
9. A `403` is not treated as an expired token.
10. Missing authentication never silently downgrades a protected call.
11. BFF and worker callers use distinct registrations with least-privilege `allowedAuthRefs`.
12. Consent redirects stay in the product BFF; Credorix does not host OAuth UIs or exchange authorization codes.

---

## Secret storage

The default service supports environment and file credential references (`env://`, `file://`).

Persisted service state is always encrypted with AES-256-GCM using `CREDORIX_MASTER_KEY`. Backend selection (first match wins):

1. `CREDORIX_MONGODB_URI`
2. `MONGODB_URI`
3. Encrypted files under `CREDORIX_DATA_DIR`

The master key must come from a deployment secret mechanism and must not be committed alongside encrypted state.

---

## Caller bootstrap

The included bootstrap token is generated at high entropy, returned once and stored only as an HMAC hash. It is a compatibility method, not a requirement of the protocol. Use `CallerAuthenticator` to adopt workload identity, mTLS or JWT.

---

## Broker SSRF controls

The broker requires an exact origin allowlist. It blocks private-network destinations by default, removes caller-controlled credential headers, disables redirects and checks DNS results before dispatch. When `SERVICE_MODE=prod` (the default), `CREDORIX_ALLOW_PRIVATE_NETWORK=true` is rejected.

A network egress proxy remains a strong deployment control.

---

## Rotation

- rotate caller bootstrap tokens through the admin API
- rotate source secrets in the underlying secret store
- invalidate leases after target rejection
- use broker-only delivery for high-impact credentials
- use separate profiles for materially different privilege levels

---

## Audit and logging

When `profile.security.audit` is not `false`, Credorix emits structured audit events (no secrets) through the Fastify/pino logger. Do not add raw provider responses to application logs; Credorix redacts common token, secret, cookie and password fields.

---

# Security Model — builders

# Security Model — Builders

**Audience:** Operators owning Credorix security posture.  
**Related:** [Production Hardening](../../05-production/builders/BOOK.md)

---

## Invariants

Never put secrets in business payloads or browsers. Profiles hold refs. Callers are authenticated and authorized per profile. Broker destinations are allowlisted. BFF and worker callers stay least-privilege and separate.

---

## Secret storage

Inject `CREDORIX_MASTER_KEY` from a deployment secret mechanism. Persistence (disk or Mongo) stores AES-256-GCM envelopes only.

---

## Caller bootstrap

Prefer replacing demo/bootstrap bearer tokens with platform identity via `CallerAuthenticator` in production.

---

## Broker SSRF controls

Keep Credorix off the public internet. Do not enable private-network broker access in `SERVICE_MODE=prod`.

---

## Rotation

Own caller token rotation, secret-store rotation, and emergency disable (`enabled: false` on profiles).

---

## Audit and logging

Rely on structured audit fields on the service logger; never log raw provider token material.

---

# Production Hardening — developers

# Production Hardening — Developers

**Audience:** Engineers deploying Credorix.  
**Related:** [Security](../../04-security/developers/BOOK.md) · [Platform Overview](../../00-platform-overview/developers/BOOK.md)

---

## Supported deployment boundary

Credorix is an **internal** credential service for:

- A single machine, or multiple machines on a **private network / VPN**
- **One active owner** for scheduled and mutating work (token renewal, admin mutations)
- **No direct public internet exposure**

**Unsupported:** multi-replica active-active coordination, horizontal scaling of mutating work, multi-region, public-internet edge controls, distributed locks.

---

## Runtime mode

| `SERVICE_MODE` | Behavior |
|---|---|
| missing / empty | **prod** |
| `prod` | production-safe gates |
| `dev` | soft defaults allowed |
| anything else | startup failure |

Development behavior is never entered because configuration is missing.

---

## Implemented in this repository

1. AES-256-GCM encrypted persistence for profiles, callers, and token state.
2. In-process single-flight for token renewal (one active process only).
3. Caller/admin authentication, bootstrap token hashing, log redaction, broker SSRF allowlist + private-network block.
4. Structured audit fields when `profile.security.audit` is not `false`.
5. Production gates when `SERVICE_MODE=prod`: require non-placeholder `CREDORIX_ADMIN_TOKEN` and `CREDORIX_MASTER_KEY`; reject private-network broker and demo caller token.
6. Admin mutating routes require `Idempotency-Key`.
7. `/health`, `/ready`, and `/_live`.

---

## Deployment-owned

1. Keep Credorix off the public internet.
2. Inject `CREDORIX_MASTER_KEY`; do not commit it.
3. Prefer platform identity over bootstrap bearer tokens when needed.
4. Define profile owners, expiration reviews, and emergency disable procedures.
5. Back up profile and caller policy data.

---

# Production Hardening — builders

# Production Hardening — Builders

**Audience:** Operators owning Credorix deployment.  
**Related:** [Security Model](../../04-security/builders/BOOK.md)

---

## Supported deployment boundary

One active Credorix process on a private network / VPN. Not a public edge service; not multi-replica HA.

---

## Runtime mode

Default is **prod**. Use `SERVICE_MODE=dev` only for local soft defaults. Missing/empty is prod — not dev.

---

## Implemented in this repository

Encrypted persistence, single-flight renewal, SSRF allowlist, admin idempotency, health/ready/`/_live`, and prod gates on admin token + master key.

---

## Deployment-owned

Network isolation, secret injection, identity strategy, profile ownership, and backups remain yours.

---

# Memorix Integration — developers

# Memorix Integration — Developers

**Audience:** Engineers connecting Memorix / pipeline-services to Credorix.  
**Pinned:** `@x12i/memorix-pipeline-services@1.4.0`  
**Related:** [HTTP API](../../02-http-api/developers/BOOK.md) · [Providers](../../03-providers-and-secrets/developers/BOOK.md)

---

## Pinned contract

Memorix / pipeline-services is a **consumer** of Credorix, not part of Credorix.

Pipeline envelope `contractVersion: "1.0"` from MPS **1.4.0**. Credorix maps:

| Memorix (MPS 1.4.0) | Credorix |
|---|---|
| `auth.mode: "credential-ref"` + `auth.credentialRef` | profile `authRef` |
| `auth.mode: "token-ref"` + `auth.tokenRef` | profile `authRef` |
| `scope.orgId` (else `run.orgId`) | `tenantId` |
| `execution.timeoutMs` | broker `timeoutMs` |
| Raw secrets in envelopes | **forbidden** — use refs only |

Helpers (no runtime dependency on MPS; types tested against 1.4.0):

```ts
import {
  leaseRequestFromPipelineAuth,
  brokerRequestFromPipelineAuth,
  brokerFetchForPipeline,
} from "@x12i/credorix-client";
```

---

## Credential profiles

Register Credorix profiles whose **ids match** the `credentialRef` / `tokenRef` values workers and orchestrators emit, for example:

- `customer-a:paloalto-prod-readonly`
- `memorix-skill-workers`
- `explorer-api`

Use multi-tenant profiles when `orgId` must participate in cache identity and authorization.

---

## Worker to vendor

```ts
import { createCredorixClient, brokerFetchForPipeline } from "@x12i/credorix";

const credorix = createCredorixClient({
  serviceUrl: process.env.CREDORIX_BASE_URL!,
  callerId: process.env.CREDORIX_CALLER_ID!,
  callerToken: process.env.CREDORIX_CALLER_TOKEN!,
});

export async function handleLive(request) {
  const brokered = await brokerFetchForPipeline(credorix, request, {
    url: "https://vendor.example/api/v1/resources",
    method: "GET",
    timeoutMs: request.execution?.timeoutMs ?? 30_000,
  });
  return {
    status: "success",
    result: brokered.body,
    metrics: { apiCalls: 1 },
  };
}
```

Status UI / BFF → worker `/pipeline` should hold the Credorix **caller** token server-side and broker the worker call. No vendor secret or Credorix admin token in the browser.

---

## Consent custody

Browser redirect and PKCE stay in the product BFF. Credorix stores and renews tokens.

```text
Browser → BFF (authorize + code exchange)
       → Credorix POST /v1/profiles/{tokenRef}/token-state
Worker → Credorix POST /v1/leases { authRef: tokenRef }
       → vendor API (or broker)
```

Use **separate callers** for BFF and workers with distinct `allowedAuthRefs`. Credorix does **not** implement the MPS registry, Catalox store, stub fixture packs, or invoke router.

---

# Connector Framework — developers

# Connector Framework — Developers

**Audience:** Engineers wiring Memorix connector hosts to Credorix.  
**Protocol:** `memorix-connector/1`  
**Package:** `@x12i/credorix-client@1.3.0`  
**Related:** [HTTP API](../../02-http-api/developers/BOOK.md) · [Memorix Integration](../../06-memorix-integration/developers/BOOK.md) · [Security](../../04-security/developers/BOOK.md)

---

## Product decision

Connectors receive **purpose-bound provider capabilities**, never unbounded secret bags. Credorix is the sole authority for credential material, provider-target policy, auth adapters, lease lifecycle, and shared redaction for connector invocations.

Memorix local stubs are **not** the design — replace them with Credorix ports when this package is published.

---

## Compatibility matrix

| Memorix protocol | Credorix client | Notes |
|---|---|---|
| `memorix-connector/1` | `@x12i/credorix-client@1.3.0` | Required for connector production certification |

Docs-only pins (`@x12i/credorix-docs`) are insufficient for runtime certification.

**Semver:** breaking capability kinds require a **major** bump of `@x12i/credorix-client`.

---

## Host ports

```ts
import {
  createGovernedCredentialProvider,
  createGovernedHttpPort,
} from "@x12i/credorix-client";

const credentials = createGovernedCredentialProvider({ /* caller auth */ });
const delegation = await credentials.mintDelegation({ /* bindings + correlation */ });
const capability = await credentials.resolve(delegation.delegationId, {
  purpose: "provider-http",
});
const http = createGovernedHttpPort({ /* … */, delegationId: delegation.delegationId });
```

---

## Capability kinds

| Kind | When |
|---|---|
| `brokered-fetch` | Default for `request-broker` / mtls / hmac profiles |
| `injectable-auth` | Short-lived leaseable material with `expiresAt` |
| `per-request-signing` | HMAC sign without exposing the key |
| `material-lease` | Only if `security.allowMaterialLease: true` (deny by default) |

---

## Delegation HTTP API

- `POST /v1/connector/delegations` — mint
- `POST /v1/connector/delegations/:id/resolve` — purpose-bound capability
- `POST /v1/connector/delegations/:id/broker/fetch` — governed egress
- `POST /v1/connector/delegations/:id/broker/stream` — streaming egress
- `POST /v1/connector/delegations/:id/sign` — per-request signing
- `POST /v1/connector/delegations/:id/invalidate` — run teardown

Bindings (org, source, connector, profile, purposes, tenant) are immutable for the run. Cross-* attempts return sanitized errors.

---

## Shared canary redaction

```ts
import { createCanaryRedactor } from "@x12i/credorix-core";
```

Seed the same canaries in Memorix and Credorix evidence tests.
