npm package: @nextera.one/fabric-seal-sdk
Description: FabricSeal SDK - Cryptographic seal generation and verification with Ed25519 signatures and visual fingerprint encoding
Author: Mohammed Ayesh
Latest version: 1.0.0

# @nextera.one/fabric-seal-sdk

[![npm version](https://img.shields.io/npm/v/@nextera.one/fabric-seal-sdk.svg)](https://www.npmjs.com/package/@nextera.one/fabric-seal-sdk)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

**FabricSeal SDK** — Cryptographic seal generation and verification with Ed25519 signatures and visual fingerprint encoding.

## Features

- 🔐 **Ed25519 Digital Signatures** — State-of-the-art elliptic curve cryptography
- 📜 **FS1 Token Format** — Compact, URL-safe sealed tokens
- 🎨 **Visual Fingerprint Encoding** — 4,608-bit polar grid for physical representation
- ✨ **Zero Dependencies** — Pure TypeScript using Web Crypto API
- 🌐 **Browser & Node.js** — Works in all modern environments
- 🚀 **Type-Safe** — Full TypeScript support with comprehensive types

## Installation

```bash
npm install @nextera.one/fabric-seal-sdk
```

```bash
yarn add @nextera.one/fabric-seal-sdk
```

```bash
pnpm add @nextera.one/fabric-seal-sdk
```

## Quick Start

### Basic Usage

```typescript
import { fabricSealEncode, fabricSealDecode } from '@nextera.one/fabric-seal-sdk';

// Create a sealed contract
const result = await fabricSealEncode(
  '{"title": "Service Agreement", "parties": ["Alice", "Bob"]}',
  'contract',
  'key-alice-2026',
);

console.log('Token:', result.token);
console.log('Public Key:', result.publicKey);
// ⚠️ Store result.privateKey securely!

// Verify and decode the seal
const verification = await fabricSealDecode(result.token, result.publicKey);

if (verification.valid) {
  console.log('✓ Valid signature');
  console.log('Content:', verification.envelope.payloadContent);
  console.log('Type:', verification.envelope.header.type);
} else {
  console.log('✗ Invalid signature');
}
```

## Seal Types

The SDK supports six seal types for different use cases:

- **`contract`** — Legally binding agreements between parties
- **`intent`** — Declarations of intent or consent
- **`ticket`** — Verifiable passes, tickets, or entry tokens
- **`id`** — Identity claims and credentials
- **`asset`** — Digital asset ownership and provenance
- **`writ`** — Authoritative directives, orders, or decrees

## API Reference

### High-Level API

#### `fabricSealEncode(content, sealType, kid?)`

Complete workflow: Generate keys, sign content, and create FS1 token.

**Parameters:**

- `content` (string) — Content to seal
- `sealType` (string) — One of: `contract`, `intent`, `ticket`, `id`, `asset`, `writ`
- `kid?` (string) — Optional key identifier

**Returns:** `Promise<{ token: string; publicKey: string; privateKey: string }>`

```typescript
const result = await fabricSealEncode('Hello World', 'contract', 'my-key-id');
```

#### `fabricSealDecode(token, publicKey)`

Complete workflow: Parse and verify an FS1 token.

**Parameters:**

- `token` (string) — FS1 token to decode
- `publicKey` (string) — Base64url-encoded public key

**Returns:** `Promise<{ envelope: FS1Envelope; valid: boolean; error?: string }>`

```typescript
const result = await fabricSealDecode(token, publicKey);
console.log(result.valid); // true or false
```

---

### Core Cryptographic Functions

#### `fsGenKP()`

Generates an Ed25519 key pair for signing and verification.

**Returns:** `Promise<CryptoKeyPair>`

```typescript
const keyPair = await fsGenKP();
```

#### `fsExportK(key)`

Exports a public key to SPKI format (base64url).

**Parameters:**

- `key` (CryptoKey) — Public key to export

**Returns:** `Promise<string>`

```typescript
const publicKeyB64 = await fsExportK(keyPair.publicKey);
```

#### `fsImportK(b64Key)`

Imports a public key from SPKI format (base64url).

**Parameters:**

- `b64Key` (string) — Base64url-encoded public key

**Returns:** `Promise<CryptoKey>`

```typescript
const publicKey = await fsImportK(publicKeyB64);
```

#### `fsBuild(bytes, header, privateKey)`

Builds and signs an FS1 token.

**Parameters:**

- `bytes` (Uint8Array) — Payload bytes
- `header` (Record<string, string>) — Header metadata (`type`, `alg`, `sig`, `kid`)
- `privateKey` (CryptoKey) — Private key for signing

**Returns:** `Promise<string>` — FS1 token

```typescript
const content = new TextEncoder().encode('{"contract": "Agreement"}');
const header = { type: 'contract', alg: 'sha256', sig: 'ed25519', kid: 'key-123' };
const token = await fsBuild(content, header, keyPair.privateKey);
```

#### `fsParse(token)`

Parses an FS1 token string into its components.

**Parameters:**

- `token` (string) — FS1 token (format: `FS1:header.payload.signature`)

**Returns:** `FS1Envelope`

**Throws:** Error if token is malformed

```typescript
const envelope = fsParse('FS1:eyJ0eXBlIjoi...');
```

#### `fsVerify(envelope, publicKey)`

Verifies the signature of an FS1 token.

**Parameters:**

- `envelope` (FS1Envelope) — Parsed envelope from `fsParse()`
- `publicKey` (CryptoKey) — Public key for verification

**Returns:** `Promise<boolean>`

```typescript
const envelope = fsParse(token);
const pubKey = await fsImportK(publicKeyB64);
const isValid = await fsVerify(envelope, pubKey);
```

---

### Encoding Utilities

#### `fsB64Enc(bytes)`

Encodes a Uint8Array to base64url format (RFC 4648).

**Parameters:**

- `bytes` (Uint8Array) — Data to encode

**Returns:** `string`

#### `fsB64Dec(str)`

Decodes a base64url string to Uint8Array.

**Parameters:**

- `str` (string) — Base64url string

**Returns:** `Uint8Array`

#### `fsJsonB64(obj)`

Encodes a JSON object to base64url.

**Parameters:**

- `obj` (unknown) — Object to encode

**Returns:** `string`

#### `fsB64Json(str)`

Decodes a base64url string to JSON object.

**Parameters:**

- `str` (string) — Base64url-encoded JSON

**Returns:** `unknown`

---

### Hash Functions

#### `fsSha256(buffer)`

Computes SHA-256 hash of the input buffer.

**Parameters:**

- `buffer` (BufferSource) — Data to hash

**Returns:** `Promise<Uint8Array>`

---

### Types

#### `FS1Envelope`

Structure representing a parsed FS1 token.

```typescript
interface FS1Envelope {
  header: { type?: string; alg?: string; sig?: string; kid?: string };
  headerB64Url: string;
  payloadB64Url: string;
  payloadContent: string | null;
  signatureB64Url: string;
  signatureBytes: Uint8Array;
}
```

---

### Constants

- **`RINGS`** — Number of rings in fingerprint polar grid (48)
- **`ANGLES`** — Number of angles in fingerprint polar grid (96)
- **`FINGERPRINT_CAPACITY_BITS`** — Total capacity in bits (4,608)

## Advanced Examples

### Manual Key Management

```typescript
import {
  fsGenKP,
  fsExportK,
  fsBuild,
  fsParse,
  fsVerify,
  fsImportK,
} from '@nextera.one/fabric-seal-sdk';

// Generate and store keys separately
const keyPair = await fsGenKP();
const publicKey = await fsExportK(keyPair.publicKey);

// Create sealed content
const content = new TextEncoder().encode('Sensitive data');
const header = {
  type: 'contract',
  alg: 'sha256',
  sig: 'ed25519',
  kid: 'alice-signing-key-2026',
};

const token = await fsBuild(content, header, keyPair.privateKey);

// Later: verify the seal
const envelope = fsParse(token);
const pubKey = await fsImportK(publicKey);
const isValid = await fsVerify(envelope, pubKey);

console.log('Valid:', isValid);
console.log('Content:', envelope.payloadContent);
```

### Custom Payload Encoding

```typescript
import { fsBuild, fsGenKP } from '@nextera.one/fabric-seal-sdk';

const keyPair = await fsGenKP();

// Seal binary data
const binaryData = new Uint8Array([1, 2, 3, 4, 5]);
const header = { type: 'asset', alg: 'sha256', sig: 'ed25519' };
const token = await fsBuild(binaryData, header, keyPair.privateKey);
```

### Key Identifier Patterns

```typescript
// Domain-based KID
const result1 = await fabricSealEncode(content, 'contract', 'softid:alice@example.com');

// Timestamp-based KID
const result2 = await fabricSealEncode(content, 'intent', `key-${Date.now()}`);

// Hierarchical KID
const result3 = await fabricSealEncode(content, 'writ', 'org:dept:user:2026');
```

## Security Considerations

1. **Private Key Storage**
   - Never expose private keys in client-side code
   - Use secure key management systems (KMS, HSM)
   - Rotate keys periodically

2. **Token Transmission**
   - Always use HTTPS/TLS for token transmission
   - Tokens are not encrypted, only signed
   - Consider additional encryption for sensitive payloads

3. **Verification**
   - Always verify signatures before trusting token content
   - Validate the `kid` against your trusted key registry
   - Check token expiration if implemented in your system

## Browser Compatibility

Requires browsers with Web Crypto API support (Ed25519):

- Chrome 93+
- Firefox 119+
- Safari 16+
- Edge 93+

## Node.js Compatibility

Requires Node.js 18+ with native Web Crypto API support.

## License

MIT © Mohammed Ayesh

## Contributing

Issues and pull requests are welcome at the project repository.

## Links

- [Documentation](https://github.com/nextera-one/fabric-seal)
- [npm Package](https://www.npmjs.com/package/@nextera.one/fabric-seal-sdk)
- [Report Issues](https://github.com/nextera-one/fabric-seal/issues)