# Security API reference

> Current emitted signatures and options for @db3.ai/app/security.

- Package: `@db3.ai/app/security`
- Canonical page: [https://db3.ai/docs/security-api](https://db3.ai/docs/security-api)
- Markdown: [https://db3.ai/docs/security-api.md](https://db3.ai/docs/security-api.md)
- Framework source of truth: `packages/app/src/security/README.md`

<a id="start"></a>

## Imports and examples

Import supported APIs from `@db3.ai/app/security`. These signatures come from the staged package used by consumers. Relative filenames in declarations describe type dependencies; they are not extra supported deep imports.

Use the guide for setup, executable examples, failure handling and ownership. A signature is not proof that every deployment or provider has been exercised.

- [Guide, examples and testing](https://db3.ai/docs/security.md)

<a id="security"></a>

## Encryption and JSON methods

### Encryption and JSON methods

```typescript
import { Buffer } from 'node:buffer';
import type * as security from './contracts/index.js';
/**
 * Central application service for versioned authenticated encryption.
 *
 * The service owns key resolution, cipher policy, payload framing, and JSON
 * serialization so fields and application services do not implement their own
 * cryptographic formats.
 *
 * @example
 * const encrypted = app().security.encryptJson({
 * 	token: 'provider-secret',
 * });
 * const decrypted = app().security.decryptJson<{ token: string }>(encrypted);
 */
export declare class Security {
    #private;
    /**
     * Creates the application security service from the active app config.
     */
    constructor();
    /**
     * Generates a new base64-formatted 256-bit application key.
     *
     * @returns Value suitable for an `APP_KEY` environment variable.
     */
    static generateKey(): string;
    /**
     * Encrypts bytes or text with authenticated encryption.
     *
     * @param value - Plaintext bytes or UTF-8 text.
     * @param options - Optional additional authenticated ownership context.
     * @returns Versioned encrypted payload safe for text storage.
     */
    encrypt(value: string | Buffer, options?: security.SecurityPayloadOptions): string;
    /**
     * Decrypts and authenticates a versioned security payload.
     *
     * @param payload - Encrypted payload created by {@link encrypt}.
     * @param options - Additional authenticated data supplied during encryption.
     * @returns Decrypted plaintext bytes.
     */
    decrypt(payload: string, options?: security.SecurityPayloadOptions): Buffer;
    /**
     * Serializes and encrypts a JSON-compatible value.
     *
     * @param value - JSON-compatible value to protect.
     * @param options - Optional additional authenticated ownership context.
     * @returns Versioned encrypted payload safe for text storage.
     */
    encryptJson<TValue>(value: TValue, options?: security.SecurityPayloadOptions): string;
    /**
     * Decrypts and parses a JSON-compatible value.
     *
     * @param payload - Encrypted JSON payload created by {@link encryptJson}.
     * @param options - Additional authenticated data supplied during encryption.
     * @returns Decrypted and parsed JSON value.
     */
    decryptJson<TValue>(payload: string, options?: security.SecurityPayloadOptions): TValue;
}
```

<a id="options"></a>

## App security options

### App security options

```typescript
import type { Buffer } from 'node:buffer';
/**
 * Authenticated encryption ciphers supported by the framework security service.
 */
export type SecurityCipher = 'aes-256-gcm';
/**
 * Central application security configuration.
 */
export interface SecurityOptions {
    /**
     * Application encryption key as 32 raw bytes, a 32-byte UTF-8 string, or a
     * `base64:`-prefixed value.
     */
    key?: string | Buffer;
    /** Authenticated encryption cipher used for new payloads. */
    cipher?: SecurityCipher;
}
```

<a id="payload"></a>

## Authenticated context

### Authenticated context

```typescript
import type { Buffer } from 'node:buffer';
/**
 * Per-operation options for authenticated encryption and decryption.
 */
export interface SecurityPayloadOptions {
    /**
     * Optional context authenticated with the payload but not stored inside it.
     *
     * Callers can use this to bind ciphertext to a model field, tenant, or other
     * stable ownership boundary.
     */
    additionalAuthenticatedData?: string | Buffer;
}
```

<a id="key"></a>

## Local key provisioning

### Local key provisioning

```typescript
/**
 * Returns the conventional `APP_KEY`, generating it in `.env` when missing.
 *
 * Applications should normally call this from their security config after
 * checking the environment. Existing non-empty values are preserved so invalid
 * keys fail normal security validation instead of being silently replaced.
 *
 * @returns Existing or newly generated application key.
 * @throws {SecurityError} When `.env` cannot be read or updated.
 *
 * @example
 * export default defineConfig({
 * 	key: env.string('APP_KEY') || ensureAppKey(),
 * });
 */
export declare function ensureAppKey(): string;
```

<a id="errors"></a>

## SecurityError

### SecurityError

```typescript
/**
 * Error raised when the application security service cannot safely complete an
 * encryption, decryption, or key operation.
 */
export declare class SecurityError extends Error {
    /**
     * Creates a security error with a message that must not contain protected data.
     *
     * @param message - User-safe explanation of the security failure.
     * @param options - Optional error cause retained for server-side diagnostics.
     */
    constructor(message: string, options?: ErrorOptions);
}
```

## Related documentation
- [Encrypt a secret you need to read later](https://db3.ai/docs/security.md): Keep reversible secrets encrypted with an application-owned key and explicit ownership context.

## Guidance for AI tools
Use the documented public import `@db3.ai/app/security` and its exported types. Prefer the source-backed examples and behavioural outcomes above over invented APIs or source-relative internal imports.
