@tsok.org/global-id
v1.0.0
Published
Type-safe versionable global identifiers with encryption support
Downloads
4
Readme
@tsok.org/global-id
Type-safe, versionable global identifiers with encryption support for TypeScript/JavaScript applications.
Overview
GlobalID is a high-performance library for creating type-safe, versionable identifiers with built-in encryption support. It combines the benefits of compile-time type safety, runtime validation, and efficient binary encoding to provide a robust solution for distributed systems.
Key Benefits:
- 🔒 Type-Safe: Phantom types and branded types ensure compile-time safety
- 📦 Compact: CBOR encoding provides 10-40% size reduction vs JSON
- ⚡ Fast: 500k+ ops/sec encoding, 600k+ ops/sec decoding
- 🔐 Secure: AES-256-GCM encryption with PBKDF2 key derivation
- 🧩 Extensible: Plugin architecture for custom transformations
- ✅ Validated: Optional Zod integration for runtime schema validation
- 🌍 Universal: Works in Node.js and modern browsers
- 📝 Immutable: All instances are deeply frozen
Installation
```bash npm install @tsok.org/global-id ```
Optional peer dependencies:
```bash
For runtime validation
npm install zod ```
Quick Start
```typescript import { GlobalId, Encoder, Decoder, TypeRegistry, ParserRegistry, StringParser, } from '@tsok.org/global-id';
// 1. Set up registries const typeRegistry = new TypeRegistry(); typeRegistry.register('User', 'usr');
const parserRegistry = new ParserRegistry(); parserRegistry.register('User', '1.0', new StringParser());
// 2. Create encoder/decoder const encoder = new Encoder({ typeRegistry, parserRegistry }); const decoder = new Decoder({ typeRegistry, parserRegistry });
// 3. Create and encode GlobalId const userId = GlobalId.create('User', '1.0', 'user-12345'); const encoded = encoder.encode(userId);
// 4. Decode const decoded = decoder.decode<'User', '1.0', string>(encoded); console.log(decoded.value); // => "user-12345" ```
Documentation
Features
Type-Safe Identifiers
```typescript type UserId = GlobalId<'User', '1.0', string>; type OrderId = GlobalId<'Order', '1.0', { orderId: string }>;
// Compile-time type checking const user: UserId = GlobalId.create('User', '1.0', 'user-123'); // ✅ const order: UserId = GlobalId.create('Order', '1.0', { orderId: '789' }); // ❌ Error ```
Compact Binary Encoding
Uses CBOR + Base64URL for 10-40% size reduction compared to JSON.
Encryption Support
```typescript import { WebCryptoEncryptor, EncryptedGlobalId } from '@tsok.org/global-id';
const encryptor = new WebCryptoEncryptor(); const sensitive = GlobalId.create('User', '1.0', { ssn: '123-45-6789' });
const encrypted = await EncryptedGlobalId.create(sensitive, encryptor, { password: 'strong-password', salt: crypto.getRandomValues(new Uint8Array(16)), });
const decrypted = await encrypted.decrypt(encryptor, { password: 'strong-password', }); ```
Runtime Validation with Zod
```typescript import { z } from 'zod'; import { ZodParser } from '@tsok.org/global-id';
const schema = z.object({ id: z.string().uuid(), email: z.string().email(), });
const parser = new ZodParser(schema); parserRegistry.register('User', '2.0', parser);
// Validation happens automatically during encoding ```
Plugin System
```typescript import { GlobalIdBuilder } from '@tsok.org/global-id';
const encoded = await GlobalIdBuilder .create('User', '1.0', 'data') .withEncoderPlugin(new LoggingPlugin()) .withEncoderPlugin(new ValidationPlugin()) .buildAndEncode(encoder); ```
Performance
Measured on Node.js 20, Apple M1 Pro:
- Encoding: ~950k ops/sec (simple strings), ~520k ops/sec (complex objects)
- Decoding: ~1.2M ops/sec (simple strings), ~680k ops/sec (complex objects)
- Encryption: ~15k ops/sec (AES-256-GCM)
- Size: 10-40% smaller than JSON
See benchmarks for detailed metrics.
Security
- Algorithm: AES-256-GCM (Authenticated Encryption)
- Key Derivation: PBKDF2-SHA256, 100,000 iterations
- IV: 12 bytes, randomly generated
- Authentication: 128-bit authentication tag
Best Practices:
- Use strong passwords (12+ characters)
- Generate random salts per encryption
- Store keys in secure vaults (AWS KMS, Google Secret Manager)
- Rotate keys periodically
Examples
REST API
```typescript app.get('/api/users/:id', async (req, res) => { const userId = decoder.decode<'User', '1.0', string>(req.params.id); const user = await db.findUser(userId.value); res.json({ id: req.params.id, ...user }); }); ```
Database Storage
```typescript const userId = GlobalId.create('User', '1.0', crypto.randomUUID()); const encoded = encoder.encode(userId);
await prisma.user.create({ data: { globalId: encoded, name: 'John' }, }); ```
Kafka Messages
```typescript const key = encoder.encode(GlobalId.create('User', '1.0', 'user-123')); await producer.send({ topic: 'events', messages: [{ key, value: JSON.stringify(event) }], }); ```
Contributing
Contributions welcome! Please see CONTRIBUTING.md.
```bash
Setup
npm install
Tests
npm test
Benchmarks
npm test -- --testPathPattern=bench
Build
npm run build ```
License
MIT License - see LICENSE for details.
