Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,28 @@ Objects now declare `namespace: 'sys'` and a short `name` (e.g., `name: 'user'`)
- [x] Metadata-driven deploy pipeline — `system/deploy-bundle.zod.ts`: `DeployBundleSchema`, `MigrationPlanSchema`, `DeployDiffSchema`; `contracts/deploy-pipeline-service.ts`: `IDeployPipelineService`
- [x] App marketplace installation protocol — `system/app-install.zod.ts`: `AppManifestSchema`, `AppInstallResultSchema`, `AppCompatibilityCheckSchema`; `contracts/app-lifecycle-service.ts`: `IAppLifecycleService`
- [ ] Cross-tenant data sharing policies
- [x] **Phase 1: Multi-Tenant Protocol & Minimal Prototype (v3.4)** — ✅ Complete (2026-04-17)
- [x] UUID-based tenant database naming (not org-slug, for immutability)
- [x] Tenant registry schema — `cloud/tenant.zod.ts`: `TenantDatabaseSchema`, `PackageInstallationSchema`, `TenantContextSchema`, `TenantRoutingConfigSchema`, `ProvisionTenantRequestSchema`, `ProvisionTenantResponseSchema`
- [x] `@objectstack/service-tenant` package — Tenant context service, multi-tenant router integration, UUID-based naming enforcement
- [x] Tenant identification strategies — Subdomain, custom domain, HTTP header, JWT claim, session
- [x] TenantContextService — Tenant context resolution with caching and multiple identification sources
- [x] TenantProvisioningService skeleton — Minimal prototype for tenant database provisioning (Turso Platform API integration pending)
- [x] Multi-tenant router documentation updates — UUID naming conventions and examples
- [x] Test coverage — TenantContextService identification and caching tests
- [x] **Phase 2: Turso Platform API Integration (v3.5)** — ✅ Complete (2026-04-17)
- [x] Turso Platform API client implementation
- [x] Automated tenant database creation
- [x] Tenant-specific auth token generation
- [x] Global control plane database setup (sys_tenant_registry, sys_package_installation)
- [x] Tenant database schema initialization
- [x] Package installation per tenant
- [ ] **Phase 3: Production Hardening (v4.0)** — 🟡 Partially Complete
- [x] Tenant lifecycle management (suspend, archive, restore)
- [ ] Multi-region tenant migration
- [ ] Tenant usage tracking and quota enforcement
- [ ] Cross-tenant data sharing policies
- [ ] Tenant-specific RBAC and permissions

### 6.3 Observability

Expand Down
29 changes: 23 additions & 6 deletions packages/plugins/driver-turso/src/multi-tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,14 @@
*
* Manages per-tenant TursoDriver instances with TTL-based caching.
* Uses a URL template with `{tenant}` placeholder that is replaced
* with the tenantId at runtime.
* with the tenantId (UUID) at runtime.
*
* Serverless-safe: no global intervals, no leaked state. Expired
* **UUID-Based Tenant Naming:**
* - Tenant IDs are UUIDs, not organization slugs
* - Ensures database URLs remain stable even if organization names change
* - Example: `550e8400-e29b-41d4-a716-446655440000.turso.io`
*
* **Serverless-safe:** no global intervals, no leaked state. Expired
* entries are evicted lazily on next access.
*/

Expand All @@ -18,20 +23,32 @@ import { TursoDriver, type TursoDriverConfig } from './turso-driver.js';
/**
* Configuration for the multi-tenant router.
*
* **UUID-Based Tenant Naming:**
* The `{tenant}` placeholder is replaced with a UUID, not an organization slug.
* This ensures database URLs remain stable even if organization names change.
*
* @example
* ```typescript
* const router = createMultiTenantRouter({
* urlTemplate: 'file:./data/{tenant}.db',
* // UUID-based URL template
* urlTemplate: 'libsql://{tenant}.turso.io',
* groupAuthToken: process.env.TURSO_GROUP_TOKEN,
* clientCacheTTL: 300_000, // 5 minutes
* });
*
* const driver = await router.getDriverForTenant('acme');
* // Tenant ID is a UUID
* const driver = await router.getDriverForTenant('550e8400-e29b-41d4-a716-446655440000');
* ```
*/
export interface MultiTenantConfig {
/**
* URL template with `{tenant}` placeholder.
* Example: `'file:./data/{tenant}.db'`
* URL template with `{tenant}` placeholder (replaced with UUID at runtime).
*
* Examples:
* - Remote: `'libsql://{tenant}.turso.io'`
* - Local: `'file:./data/{tenant}.db'`
*
* **Important:** Use UUID for tenant ID, not organization slug.
*/
urlTemplate: string;

Expand Down
232 changes: 232 additions & 0 deletions packages/services/service-tenant/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
# @objectstack/service-tenant

Multi-tenant context management and routing service for ObjectStack.

## Overview

This service provides comprehensive multi-tenant infrastructure for ObjectStack deployments, including:

- Tenant identification and context resolution
- Turso Platform API integration for automated database provisioning
- Tenant database schema initialization
- Global control plane management
- Package installation per tenant

## Features

### Phase 1 (Complete)
- **Multiple Identification Sources**: Subdomain, custom domain, HTTP headers, JWT claims, session
- **UUID-Based Tenant Naming**: Immutable tenant identifiers (not organization slugs)
- **Tenant Context Caching**: Performance optimization for frequently accessed tenants
- **Flexible Configuration**: Priority-based identification source ordering

### Phase 2 (Complete)
- **Turso Platform API Integration**: Automated database creation via Turso Platform API
- **Tenant-Specific Auth Tokens**: Secure, database-specific authentication
- **Global Control Plane**: System objects for tenant registry and package installations
- **Schema Initialization**: Automated tenant database schema setup
- **Package Management**: Per-tenant package installation and schema migration

## Installation

```bash
pnpm add @objectstack/service-tenant
```

## Usage

### Basic Setup (Tenant Routing)

```typescript
import { createTenantPlugin } from '@objectstack/service-tenant';
import { ObjectKernel } from '@objectstack/core';

const kernel = new ObjectKernel();

// Create tenant plugin with routing configuration
const tenantPlugin = createTenantPlugin({
routing: {
enabled: true,
identificationSources: ['header', 'custom_domain', 'jwt_claim'],
tenantHeaderName: 'X-Tenant-ID',
customDomainMapping: {
'app.acme.com': '550e8400-e29b-41d4-a716-446655440000',
},
},
registerSystemObjects: true, // Register control plane objects
});

await kernel.use(tenantPlugin);
await kernel.bootstrap();
```

### Tenant Provisioning

```typescript
import {
TenantProvisioningService,
TursoPlatformClient,
} from '@objectstack/service-tenant';

// Production mode: with Turso Platform API
const provisioningService = new TenantProvisioningService({
turso: {
apiToken: process.env.TURSO_API_TOKEN!,
organization: 'my-org',
},
controlPlaneDriver: globalDriver, // Global control plane driver
defaultRegion: 'us-east-1',
databaseGroup: 'production-tenants',
});

// Provision a new tenant
const result = await provisioningService.provisionTenant({
organizationId: 'org-123',
plan: 'pro',
region: 'us-west-2',
storageLimitMb: 5120,
});

console.log('Tenant provisioned:', result.tenant);
// {
// id: '550e8400-e29b-41d4-a716-446655440000',
// databaseUrl: 'libsql://550e8400-e29b-41d4-a716-446655440000.turso.io',
// authToken: '<encrypted-token>',
// status: 'active',
// ...
// }
```

### Development Mode (No Turso API)

```typescript
// Development/Mock mode: no Turso Platform API required
const devService = new TenantProvisioningService({
defaultRegion: 'us-east-1',
});

const result = await devService.provisionTenant({
organizationId: 'org-123',
plan: 'free',
});

// Returns mock tenant with warnings
console.log(result.warnings);
// ['Running in mock mode - Turso Platform API credentials not configured']
```

### Schema Initialization

```typescript
import { TenantSchemaInitializer } from '@objectstack/service-tenant';

const initializer = new TenantSchemaInitializer();

// Initialize tenant database with base schema
await initializer.initializeTenantSchema(
tenant.databaseUrl,
tenant.authToken,
baseObjects, // Optional: base objects to create
);

// Install package schema
await initializer.installPackageSchema(
tenant.databaseUrl,
tenant.authToken,
packageObjects,
);
```

### Resolving Tenant Context

```typescript
import { TenantContextService } from '@objectstack/service-tenant';

const service = kernel.getService<TenantContextService>('tenant');

const context = await service.resolveTenantContext({
hostname: 'app.acme.com',
headers: {
'X-Tenant-ID': '550e8400-e29b-41d4-a716-446655440000',
},
jwt: {
organizationId: 'org-123',
},
});

console.log(context);
// {
// tenantId: '550e8400-e29b-41d4-a716-446655440000',
// organizationId: 'org-123',
// databaseUrl: 'libsql://550e8400-e29b-41d4-a716-446655440000.turso.io',
// plan: 'pro'
// }
```

## Architecture

### Tenant Identification Flow

```
Request → TenantContextService → Identification Sources (in order)
1. Subdomain
2. Custom Domain
3. HTTP Header
4. JWT Claim
5. Session
6. Default Tenant
Tenant Context
```

### UUID-Based Naming

Tenant databases use UUID naming instead of organization slugs:

- **Why**: Organization slugs can be modified, UUIDs are immutable
- **Format**: `{uuid}.turso.io` (e.g., `550e8400-e29b-41d4-a716-446655440000.turso.io`)
- **Benefit**: Stable database URLs regardless of organization name changes

## Configuration

### TenantRoutingConfig

```typescript
interface TenantRoutingConfig {
// Enable multi-tenant mode
enabled: boolean;

// Identification strategy (in order of precedence)
identificationSources: TenantIdentificationSource[];

// Default tenant ID (for single-tenant or fallback)
defaultTenantId?: string;

// Subdomain pattern for tenant extraction
subdomainPattern?: string;

// Custom domain to tenant ID mapping
customDomainMapping?: Record<string, string>;

// Header name for tenant ID
tenantHeaderName: string; // Default: 'X-Tenant-ID'

// JWT claim name for organization ID
jwtOrganizationClaim: string; // Default: 'organizationId'
}
```

## Testing

```bash
# Run tests
pnpm test

# Run tests in watch mode
pnpm test:watch
```

## License

Apache-2.0
51 changes: 51 additions & 0 deletions packages/services/service-tenant/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"name": "@objectstack/service-tenant",
"version": "0.1.0",
"description": "ObjectStack Multi-Tenant Service - Tenant context management and routing",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"files": [
"dist",
"README.md"
],
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@objectstack/spec": "workspace:^",
"@objectstack/core": "workspace:^"
},
"devDependencies": {
"@types/node": "^22.10.5",
"tsup": "^8.3.5",
"typescript": "^5.7.3",
"vitest": "^2.1.8"
Comment on lines +31 to +34

Copilot AI Apr 17, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This package pins significantly older toolchain versions (vitest@^2, typescript@^5, @types/node@^22) than the rest of packages/services/* (which use vitest@^4, typescript@^6, @types/node@^25). This introduces duplicate transitive deps in the lockfile (e.g. extra vite/esbuild trees) and increases maintenance burden. Align devDependencies and build scripts with the existing service package conventions (see service-storage / service-package).

Suggested change
"@types/node": "^22.10.5",
"tsup": "^8.3.5",
"typescript": "^5.7.3",
"vitest": "^2.1.8"
"@types/node": "^25",
"tsup": "^8.3.5",
"typescript": "^6",
"vitest": "^4"

Copilot uses AI. Check for mistakes.
},
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/objectstack-ai/framework.git",
"directory": "packages/services/service-tenant"
},
"keywords": [
"objectstack",
"multi-tenant",
"saas",
"tenant-routing"
],
"author": "ObjectStack Team",
"license": "Apache-2.0"
}
8 changes: 8 additions & 0 deletions packages/services/service-tenant/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

export * from './tenant-context';
export * from './tenant-plugin';
export * from './tenant-provisioning';
export * from './turso-platform-client';
export * from './tenant-schema-initializer';
export * from './objects';
4 changes: 4 additions & 0 deletions packages/services/service-tenant/src/objects/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

export * from './sys-tenant-database.object';
export * from './sys-package-installation.object';
Loading
Loading