npm package: @mafate/sdk
Description: MAFATE Encryption as a Service — Node.js SDK
Author: UNIVILE SAS
Latest version: 0.1.0

# MAFATE Node.js SDK

**MAFATE** — Encryption as a Service. Sovereign, compliant, effortless.

The official Node.js SDK for the [MAFATE](https://mafate.io) platform — AES-256 key management and envelope encryption, built for European compliance (RGPD, NIS2, DORA).

---

## Install

```bash
npm install @mafate/sdk
```

Requires Node.js >= 18.

---

## Quick Start

```typescript
import { Mafate } from '@mafate/sdk'

const client = new Mafate({ apiKey: 'mft_live_...' })

const encrypted = await client.crypto.encrypt('my secret data', 'key_abc123')
const plaintext = await client.crypto.decrypt(encrypted)
// => 'my secret data'
```

---

## Configuration

```typescript
const client = new Mafate({
  apiKey: 'mft_live_...',      // required — your MAFATE API key
  baseUrl: 'https://api.mafate.io', // optional — default shown
  timeout: 30000,              // optional — ms, default 30 000
})
```

| Option    | Type     | Required | Default                    | Description             |
|-----------|----------|----------|----------------------------|-------------------------|
| `apiKey`  | `string` | yes      | —                          | Your MAFATE API key     |
| `baseUrl` | `string` | no       | `https://api.mafate.io`    | API base URL            |
| `timeout` | `number` | no       | `30000`                    | Request timeout (ms)    |

---

## API Reference

### `client.keys` — Encryption Key Management

#### `list(): Promise<Key[]>`

Returns all encryption keys for your tenant.

```typescript
const keys = await client.keys.list()
// [{ id, name, algorithm, status, current_version, created_at }, ...]
```

#### `get(id: string): Promise<KeyDetail>`

Returns full detail for a single key, including its version history.

```typescript
const key = await client.keys.get('key_abc123')
// { id, name, algorithm, status, current_version, created_at, updated_at, versions: [...] }
```

#### `create(options: CreateKeyOptions): Promise<Key>`

Creates a new encryption key.

```typescript
const key = await client.keys.create({
  name: 'user-data-key',
  algorithm: 'AES_256', // optional, default used if omitted
})
```

#### `rotate(id: string): Promise<Key>`

Rotates a key — creates a new version. Existing ciphertext remains decryptable with the previous version.

```typescript
const updated = await client.keys.rotate('key_abc123')
```

#### `disable(id: string): Promise<void>`

Disables a key. The key can no longer be used for encryption.

```typescript
await client.keys.disable('key_abc123')
```

---

### `client.crypto` — Encrypt and Decrypt

#### `encrypt(plaintext: string | Buffer, keyId: string): Promise<EncryptedData>`

Encrypts data using envelope encryption. Accepts a plain string or a `Buffer`. The SDK handles base64 encoding automatically.

```typescript
const encrypted = await client.crypto.encrypt('confidential payload', 'key_abc123')
// {
//   ciphertext: '...',
//   wrapped_key: '...',
//   iv: '...',
//   key_id: 'key_abc123',
//   key_version: 3
// }
```

You can also pass a `Buffer`:

```typescript
const buf = Buffer.from(JSON.stringify({ ssn: '123-45-6789' }))
const encrypted = await client.crypto.encrypt(buf, 'key_abc123')
```

#### `decrypt(data: EncryptedData): Promise<string>`

Decrypts an `EncryptedData` object. Returns the original UTF-8 string. The SDK handles base64 decoding automatically.

```typescript
const plaintext = await client.crypto.decrypt(encrypted)
```

Store the full `EncryptedData` object — all fields are required for decryption.

---

### `client.apiKeys` — API Key Management

#### `list(): Promise<ApiKey[]>`

Returns all API keys for your tenant (secrets are not returned after creation).

```typescript
const apiKeys = await client.apiKeys.list()
```

#### `create(options: CreateApiKeyOptions): Promise<ApiKeyWithSecret>`

Creates a new API key. The `secret` field is only returned once — store it securely.

```typescript
const { secret, ...key } = await client.apiKeys.create({
  name: 'production-service',
  permissions: ['encrypt', 'decrypt'],
  expires_at: '2027-01-01T00:00:00Z', // optional
})
// Store `secret` immediately — it will not be shown again
```

#### `update(id: string, options: UpdateApiKeyOptions): Promise<ApiKey>`

Updates permissions or expiry for an existing API key.

```typescript
const updated = await client.apiKeys.update('apk_xyz', {
  permissions: ['encrypt', 'decrypt', 'keys:read'],
  expires_at: '2028-01-01T00:00:00Z',
})
```

Set `expires_at: null` to remove the expiry.

#### `revoke(id: string): Promise<void>`

Permanently revokes an API key. This cannot be undone.

```typescript
await client.apiKeys.revoke('apk_xyz')
```

---

### `client.audit` — Audit Logs

#### `list(filters?: AuditFilters): Promise<ListAuditResponse>`

Returns audit log entries with optional filters. Results are paginated.

```typescript
const logs = await client.audit.list()
// { logs: [...], count, total, limit, offset }
```

With filters:

```typescript
const logs = await client.audit.list({
  action: 'encrypt',
  key_id: 'key_abc123',
  date_from: '2026-01-01T00:00:00Z',
  date_to: '2026-03-31T23:59:59Z',
  limit: 50,
  offset: 0,
})
```

| Filter      | Type     | Description                        |
|-------------|----------|------------------------------------|
| `action`    | `string` | Filter by action (e.g. `encrypt`)  |
| `key_id`    | `string` | Filter by encryption key ID        |
| `date_from` | `string` | ISO 8601 start date                |
| `date_to`   | `string` | ISO 8601 end date                  |
| `limit`     | `number` | Page size (default set by API)     |
| `offset`    | `number` | Pagination offset                  |

---

## Error Handling

All methods throw `ApiError` on non-2xx responses and `MafateError` for SDK-level errors.

```typescript
import { Mafate, ApiError, MafateError } from '@mafate/sdk'

const client = new Mafate({ apiKey: 'mft_live_...' })

try {
  const encrypted = await client.crypto.encrypt('secret', 'key_abc123')
} catch (err) {
  if (err instanceof ApiError) {
    console.error(`API error ${err.status}: ${err.title} — ${err.detail}`)
    // e.g. "API error 404: Not Found — key key_abc123 does not exist"
  } else if (err instanceof MafateError) {
    console.error('SDK error:', err.message)
  } else {
    throw err
  }
}
```

`ApiError` properties:

| Property | Type     | Description                |
|----------|----------|----------------------------|
| `status` | `number` | HTTP status code           |
| `title`  | `string` | Short error title          |
| `detail` | `string` | Detailed error description |

---

## TypeScript

The SDK is written in TypeScript and ships with full type declarations. No `@types/` package required.

```typescript
import type { Key, EncryptedData, AuditFilters } from '@mafate/sdk'
```

All request and response types are exported from the top-level package entry point.

---

## Documentation

Full API documentation: [https://docs.mafate.io](https://docs.mafate.io)

---

## License

MIT — UNIVILE SAS