Skip to content

AI-native design editor. Open-source Figma alternative.

feat(cloud): sign AI service tokens and accept versioned entitlement writes (#1341)

Danila Poyarkov413c3aa4d178
diff --git a/packages/cloud/deploy/openpencil-cloud.example.toml b/packages/cloud/deploy/openpencil-cloud.example.toml
index f3489151c..a2cf82cf5 100644
--- a/packages/cloud/deploy/openpencil-cloud.example.toml
+++ b/packages/cloud/deploy/openpencil-cloud.example.toml
@@ -79,6 +79,23 @@ checksum_verification = "metadata"
[email]
transport = "none"
+# Add this table to offer an AI service to editors. Cloud never proxies models: it advertises the
+# endpoint and signs short-lived ES256 tokens the service verifies against /.well-known/jwks.json.
+# The PKCS #8 signing key defaults to OPENPENCIL_CLOUD_AI_SIGNING_KEY. Workspaces also need the
+# [entitlements.ai] enabled entitlement.
+# [ai]
+# endpoint = "https://ai.example.com"
+# token_lifetime_minutes = 10
+
+# Where people manage their plan; editors link to it. Leave it out when the deployment does not bill.
+# [billing]
+# portal_url = "https://billing.example.com"
+
+# Add this table to let services such as billing set workspace entitlements over HTTP at
+# PUT /api/internal/workspaces/<id>/entitlements. The bearer token defaults to
+# OPENPENCIL_CLOUD_SERVICE_TOKEN; requires entitlements from the database.
+# [internal_api]
+
[workers.email]
batch_size = 50
interval_ms = 30000
@@ -113,6 +130,12 @@ guest_presence = true
enabled = true
maximum_participants = 100
+# The AI service [ai] advertises. The allowance is credits per month, passed to the service in
+# every token; leave it out for no allowance.
+[entitlements.ai]
+enabled = false
+# monthly_credit_allowance = 10000
+
[technical_limits]
maximum_upload_bytes = 1073741824
maximum_collaboration_message_bytes = 1048576
diff --git a/packages/cloud/src/contract/ai.ts b/packages/cloud/src/contract/ai.ts
new file mode 100644
index 000000000..a2084285b
--- /dev/null
+++ b/packages/cloud/src/contract/ai.ts
@@ -0,0 +1,119 @@
+import * as v from 'valibot'
+
+/**
+ * The contract between editors, Cloud, and an AI service. Cloud only advertises the service and
+ * signs short-lived tokens for it; the service, official or self-hosted, proxies models and keeps
+ * the credit wallet. It is versioned apart from the Cloud protocol so a service can change without
+ * a Cloud release.
+ */
+export const CLOUD_AI_CONTRACT_VERSION = '1' as const
+/** The `aud` of every token Cloud signs for an AI service. */
+export const CLOUD_AI_TOKEN_AUDIENCE = 'openpencil-ai' as const
+/** Where Cloud publishes the public keys an AI service verifies its tokens with. */
+export const CLOUD_AI_JWKS_PATH = '/.well-known/jwks.json' as const
+
+const url = v.pipe(v.string(), v.url())
+const credits = v.pipe(v.number(), v.integer(), v.minValue(0))
+
+export const cloudAIDiscoverySchema = v.object({
+ endpoint: url,
+ contractVersion: v.literal(CLOUD_AI_CONTRACT_VERSION)
+})
+export type CloudAIDiscovery = v.InferOutput<typeof cloudAIDiscoverySchema>
+
+export const cloudBillingDiscoverySchema = v.object({ portalURL: url })
+export type CloudBillingDiscovery = v.InferOutput<typeof cloudBillingDiscoverySchema>
+
+export const createAITokenSchema = v.object({ workspaceId: v.pipe(v.string(), v.uuid()) })
+export type CreateAITokenInput = v.InferOutput<typeof createAITokenSchema>
+
+export function parseCreateAIToken(input: unknown): CreateAITokenInput {
+ return v.parse(createAITokenSchema, input)
+}
+
+export const aiTokenSchema = v.object({
+ token: v.pipe(v.string(), v.minLength(1)),
+ expiresAt: v.pipe(v.string(), v.isoTimestamp())
+})
+export type AIToken = v.InferOutput<typeof aiTokenSchema>
+
+/** What an AI service may rely on once a token's signature, issuer, audience, and expiry check. */
+export const aiTokenClaimsSchema = v.object({
+ iss: url,
+ aud: v.literal(CLOUD_AI_TOKEN_AUDIENCE),
+ sub: v.pipe(v.string(), v.minLength(1)),
+ workspaceId: v.pipe(v.string(), v.uuid()),
+ /** Credits the workspace's plan grants each month; `null` when Cloud sets no allowance. */
+ monthlyCreditAllowance: v.nullable(credits),
+ iat: v.pipe(v.number(), v.integer()),
+ exp: v.pipe(v.number(), v.integer())
+})
+export type AITokenClaims = v.InferOutput<typeof aiTokenClaimsSchema>
+
+export const aiModelSchema = v.object({
+ id: v.pipe(v.string(), v.minLength(1)),
+ label: v.pipe(v.string(), v.minLength(1)),
+ /** Credits per million input and output tokens. */
+ creditsPerMillionInputTokens: credits,
+ creditsPerMillionOutputTokens: credits,
+ contextTokens: v.pipe(v.number(), v.integer(), v.minValue(1)),
+ capabilities: v.object({ reasoning: v.boolean(), vision: v.boolean(), tools: v.boolean() })
+})
+export type AIModel = v.InferOutput<typeof aiModelSchema>
+
+export const aiCatalogSchema = v.object({
+ models: v.array(aiModelSchema),
+ defaultModelID: v.pipe(v.string(), v.minLength(1))
+})
+export type AICatalog = v.InferOutput<typeof aiCatalogSchema>
+
+export const aiCreditBucketSchema = v.object({
+ kind: v.picklist(['allowance', 'purchased', 'grant']),
+ remaining: credits,
+ expiresAt: v.nullable(v.pipe(v.string(), v.isoTimestamp()))
+})
+export type AICreditBucket = v.InferOutput<typeof aiCreditBucketSchema>
+
+export const aiWalletSchema = v.object({
+ balance: credits,
+ /** Spent first to last. */
+ buckets: v.array(aiCreditBucketSchema)
+})
+export type AIWallet = v.InferOutput<typeof aiWalletSchema>
+
+export const aiUsageEntrySchema = v.object({
+ id: v.pipe(v.string(), v.minLength(1)),
+ createdAt: v.pipe(v.string(), v.isoTimestamp()),
+ kind: v.picklist(['model', 'image', 'search']),
+ modelID: v.nullable(v.string()),
+ userId: v.pipe(v.string(), v.minLength(1)),
+ credits
+})
+export type AIUsageEntry = v.InferOutput<typeof aiUsageEntrySchema>
+
+export const aiUsagePageSchema = v.object({
+ entries: v.array(aiUsageEntrySchema),
+ next: v.nullable(v.string())
+})
+export type AIUsagePage = v.InferOutput<typeof aiUsagePageSchema>
+
+/** Errors an AI service answers with, beside the upstream model's own. */
+export const aiErrorCodeSchema = v.picklist([
+ 'unauthorized',
+ 'insufficient_credits',
+ 'model_not_allowed',
+ 'rate_limited'
+])
+export type AIErrorCode = v.InferOutput<typeof aiErrorCodeSchema>
+
+export const aiErrorSchema = v.object({
+ error: v.object({ code: aiErrorCodeSchema, message: v.optional(v.string()) })
+})
+export type AIError = v.InferOutput<typeof aiErrorSchema>
+
+export const AI_ERROR_STATUS = {
+ unauthorized: 401,
+ insufficient_credits: 402,
+ model_not_allowed: 403,
+ rate_limited: 429
+} as const satisfies Record<AIErrorCode, number>
diff --git a/packages/cloud/src/contract/discovery.ts b/packages/cloud/src/contract/discovery.ts
index 171298f69..721ec3a32 100644
--- a/packages/cloud/src/contract/discovery.ts
+++ b/packages/cloud/src/contract/discovery.ts
@@ -1,5 +1,7 @@
import * as v from 'valibot'
+import { cloudAIDiscoverySchema, cloudBillingDiscoverySchema } from './ai'
+
export const CLOUD_PROTOCOL_VERSION = '1' as const
export const CLOUD_DISCOVERY_PATH = '/.well-known/openpencil' as const
@@ -60,7 +62,11 @@ export const cloudDiscoverySchema = v.object({
appURL: v.optional(v.pipe(v.string(), v.url())),
authentication: cloudAuthenticationSchema,
capabilities: cloudCapabilitiesSchema,
- listing: v.optional(cloudListingSchema)
+ listing: v.optional(cloudListingSchema),
+ /** The AI service editors reach with Cloud-signed tokens; absent when the deployment has none. */
+ ai: v.optional(cloudAIDiscoverySchema),
+ /** Where people manage their plan and buy credits; absent when the deployment does not bill. */
+ billing: v.optional(cloudBillingDiscoverySchema)
})
export type CloudDiscovery = v.InferOutput<typeof cloudDiscoverySchema>
diff --git a/packages/cloud/src/contract/entitlements.ts b/packages/cloud/src/contract/entitlements.ts
index 74d4bcdd8..cbcf3bbd8 100644
--- a/packages/cloud/src/contract/entitlements.ts
+++ b/packages/cloud/src/contract/entitlements.ts
@@ -7,12 +7,18 @@ export const workspaceEntitlementsSchema = v.object({
anonymousEdit: v.boolean(),
guestPresence: v.boolean(),
collaboration: v.boolean(),
- revisionHistory: v.boolean()
+ revisionHistory: v.boolean(),
+ // Optional so editors keep reading servers released before the AI service.
+ cloudAI: v.optional(v.boolean(), false)
}),
limits: v.object({
maximumFileBytes: v.pipe(v.number(), v.integer(), v.minValue(1)),
maximumStorageBytes: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1))),
- maximumParticipants: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1)))
+ maximumParticipants: v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1))),
+ monthlyCreditAllowance: v.optional(
+ v.nullable(v.pipe(v.number(), v.integer(), v.minValue(0))),
+ null
+ )
}),
usage: v.object({
committedStorageBytes: v.pipe(v.number(), v.integer(), v.minValue(0)),
diff --git a/packages/cloud/src/contract/index.ts b/packages/cloud/src/contract/index.ts
index 4376771c6..3435df0e0 100644
--- a/packages/cloud/src/contract/index.ts
+++ b/packages/cloud/src/contract/index.ts
@@ -1,4 +1,37 @@
export * from './account'
+export {
+ AI_ERROR_STATUS,
+ aiCatalogSchema,
+ aiCreditBucketSchema,
+ aiErrorCodeSchema,
+ aiErrorSchema,
+ aiModelSchema,
+ aiTokenClaimsSchema,
+ aiTokenSchema,
+ aiUsageEntrySchema,
+ aiUsagePageSchema,
+ aiWalletSchema,
+ CLOUD_AI_CONTRACT_VERSION,
+ CLOUD_AI_JWKS_PATH,
+ CLOUD_AI_TOKEN_AUDIENCE,
+ cloudAIDiscoverySchema,
+ cloudBillingDiscoverySchema,
+ createAITokenSchema,
+ parseCreateAIToken,
+ type AICatalog,
+ type AICreditBucket,
+ type AIError,
+ type AIErrorCode,
+ type AIModel,
+ type AIToken,
+ type AITokenClaims,
+ type AIUsageEntry,
+ type AIUsagePage,
+ type AIWallet,
+ type CloudAIDiscovery,
+ type CloudBillingDiscovery,
+ type CreateAITokenInput
+} from './ai'
export * from './admin'
export {
collaborationPrincipalSchema,
diff --git a/packages/cloud/src/runtime/node/application.ts b/packages/cloud/src/runtime/node/application.ts
index 3c7d68bdc..10278a422 100644
--- a/packages/cloud/src/runtime/node/application.ts
+++ b/packages/cloud/src/runtime/node/application.ts
@@ -2,6 +2,7 @@ import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
import {
createCloudAuthenticationRuntime,
createCloudApp,
+ loadAISigningKey,
type CloudApp,
type CloudEnvironment,
type CloudServerConfig,
@@ -28,6 +29,7 @@ export async function createNodeCloudApplication(
}> {
const environment = options.environment ?? process.env
const config = await loadNodeCloudServerConfig(environment)
+ const aiSigningKey = await loadAISigningKey(config)
const database = createNodeCloudDatabase({
connectionString: options.databaseURL ?? config.databaseURL
})
@@ -41,7 +43,8 @@ export async function createNodeCloudApplication(
objects,
invitationOutbox,
transactionalEmail: email,
- enrollment
+ enrollment,
+ aiSigningKey
})
return { app, config, database, objects, email }
}
diff --git a/packages/cloud/src/runtime/node/server.ts b/packages/cloud/src/runtime/node/server.ts
index 74e8fc462..061efc0d8 100644
--- a/packages/cloud/src/runtime/node/server.ts
+++ b/packages/cloud/src/runtime/node/server.ts
@@ -4,6 +4,7 @@ import { createS3ObjectStore } from '#cloud/runtime/s3/objects'
import {
CLOUD_FEATURE_KEYS,
createCloudApp,
+ loadAISigningKey,
createCloudAuthenticationRuntime,
createCollaborationRelay,
createCollaborationStateStore,
@@ -35,6 +36,11 @@ export type NodeCloudServerOptions = {
export async function startNodeCloudServer(options: NodeCloudServerOptions = {}) {
const environment = options.environment ?? process.env
const { config, database } = await createMigratedNodeCloudDatabase(environment)
+ // Before any worker starts, so a key that cannot sign leaves nothing running.
+ const aiSigningKey = await loadAISigningKey(config).catch(async (error: unknown) => {
+ await database.destroy()
+ throw error
+ })
const objects = createS3ObjectStore(config)
const {
email,
@@ -106,6 +112,7 @@ export async function startNodeCloudServer(options: NodeCloudServerOptions = {})
invitationOutbox,
transactionalEmail: email,
enrollment,
+ aiSigningKey,
relayURL: config.relayURL ?? defaultRelayURL(config.publicURL),
onDocumentRestored: (documentId) => relay.startOver(documentId),
onDocumentVersionsChanged: (documentId) => relay.announceVersions(documentId)
diff --git a/packages/cloud/src/server/ai/errors.ts b/packages/cloud/src/server/ai/errors.ts
new file mode 100644
index 000000000..0030818ef
--- /dev/null
+++ b/packages/cloud/src/server/ai/errors.ts
@@ -0,0 +1,7 @@
+/** The workspace's plan does not include the AI service. */
+export class AINotEntitledError extends Error {
+ constructor() {
+ super('The workspace is not entitled to the AI service')
+ this.name = 'AINotEntitledError'
+ }
+}
diff --git a/packages/cloud/src/server/ai/index.ts b/packages/cloud/src/server/ai/index.ts
new file mode 100644
index 000000000..be66eb10d
--- /dev/null
+++ b/packages/cloud/src/server/ai/index.ts
@@ -0,0 +1,4 @@
+export { AINotEntitledError } from './errors'
+export { importAISigningKey, loadAISigningKey, type AISigningKey } from './keys'
+export { createAIRoutes, type AIRouteEnvironment } from './routes'
+export { createAITokenService, type AITokenService, type AITokenServiceOptions } from './service'
diff --git a/packages/cloud/src/server/ai/keys.ts b/packages/cloud/src/server/ai/keys.ts
new file mode 100644
index 000000000..1aca2d94d
--- /dev/null
+++ b/packages/cloud/src/server/ai/keys.ts
@@ -0,0 +1,43 @@
+import { CloudConfigError, type CloudServerConfig } from '#cloud/server/config/schema'
+import { calculateJwkThumbprint, exportJWK, importPKCS8, type JWK } from 'jose'
+
+const ALGORITHM = 'ES256'
+
+export type AISigningKey = {
+ privateKey: CryptoKey
+ /** The public half, as published in the JWKS. */
+ publicJWK: JWK & { kid: string }
+}
+
+/**
+ * Imports the P-256 key that signs AI service tokens. Its `kid` is the public key's thumbprint,
+ * so replacing the key changes the `kid`, and a service that caches the JWKS refetches it on the
+ * first token it cannot match. Tokens the old key signed fail once and are re-requested.
+ */
+export async function importAISigningKey(pem: string): Promise<AISigningKey> {
+ const privateKey = await importPKCS8(pem, ALGORITHM, { extractable: true })
+ const { kty, crv, x, y } = await exportJWK(privateKey)
+ const publicJWK = { kty, crv, x, y }
+ const kid = await calculateJwkThumbprint(publicJWK)
+ return {
+ privateKey: await importPKCS8(pem, ALGORITHM),
+ publicJWK: { ...publicJWK, kid, alg: ALGORITHM, use: 'sig' }
+ }
+}
+
+/**
+ * Imports the configured signing key at startup, so a key that cannot sign stops the runtime
+ * instead of failing every token request after discovery has advertised the AI service.
+ */
+export async function loadAISigningKey(
+ config: Pick<CloudServerConfig, 'aiSigningKey'>
+): Promise<AISigningKey | undefined> {
+ if (!config.aiSigningKey) return undefined
+ try {
+ return await importAISigningKey(config.aiSigningKey)
+ } catch {
+ throw new CloudConfigError('AI signing key must be a PKCS #8 P-256 private key')
+ }
+}
+
+export const AI_SIGNING_ALGORITHM = ALGORITHM
diff --git a/packages/cloud/src/server/ai/routes.ts b/packages/cloud/src/server/ai/routes.ts
new file mode 100644
index 000000000..04f26e22c
--- /dev/null
+++ b/packages/cloud/src/server/ai/routes.ts
@@ -0,0 +1,43 @@
+import { parseCreateAIToken } from '#cloud/contract'
+import type { CloudActor } from '#cloud/server/auth'
+import type { CloudDatabase } from '#cloud/server/db'
+import { DocumentNotFoundError } from '#cloud/server/documents'
+import { CLOUD_RATE_LIMITS, createActorRateLimiter } from '#cloud/server/rate-limit'
+import { validatedJSON } from '#cloud/server/validation'
+import { Hono } from 'hono'
+import type { Kysely } from 'kysely'
+
+import { AINotEntitledError } from './errors'
+import type { AITokenService } from './service'
+
+export type AIRouteEnvironment = { Variables: { actor: CloudActor } }
+
+/** Without a service, the deployment has no AI service and the token route is not found. */
+export function createAIRoutes(
+ service: AITokenService | undefined,
+ rateLimit?: { database: Kysely<CloudDatabase>; secret: string }
+) {
+ const router = new Hono<AIRouteEnvironment>()
+ if (!service) return router
+ if (rateLimit) {
+ router.use(
+ '/ai/token',
+ createActorRateLimiter(rateLimit.database, rateLimit.secret, CLOUD_RATE_LIMITS.aiToken)
+ )
+ }
+ return router.post('/ai/token', validatedJSON(parseCreateAIToken), async (context) => {
+ try {
+ return context.json(
+ await service.issue(context.get('actor'), context.req.valid('json').workspaceId)
+ )
+ } catch (error) {
+ if (error instanceof DocumentNotFoundError) {
+ return context.json({ error: { code: 'not_found' as const } }, 404)
+ }
+ if (error instanceof AINotEntitledError) {
+ return context.json({ error: { code: 'forbidden' as const } }, 403)
+ }
+ throw error
+ }
+ })
+}
diff --git a/packages/cloud/src/server/ai/service.ts b/packages/cloud/src/server/ai/service.ts
new file mode 100644
index 000000000..56224d0ed
--- /dev/null
+++ b/packages/cloud/src/server/ai/service.ts
@@ -0,0 +1,70 @@
+import { CLOUD_AI_TOKEN_AUDIENCE, type AIToken } from '#cloud/contract'
+import type { CloudActor } from '#cloud/server/auth'
+import type { CloudDatabase } from '#cloud/server/db'
+import { workspaceRole } from '#cloud/server/documents/repository'
+import { DocumentNotFoundError } from '#cloud/server/documents/service'
+import { CLOUD_FEATURE_KEYS } from '#cloud/server/policy/keys'
+import type { CloudPolicy } from '#cloud/server/policy/policy'
+import { SignJWT } from 'jose'
+import type { Kysely } from 'kysely'
+
+import { AINotEntitledError } from './errors'
+import { AI_SIGNING_ALGORITHM, type AISigningKey } from './keys'
+
+export type AITokenServiceOptions = {
+ database: Kysely<CloudDatabase>
+ policy: CloudPolicy
+ deploymentMode: 'official' | 'self-hosted'
+ /** The Cloud public URL, which services check as the token's `iss`. */
+ issuer: string
+ signingKey: AISigningKey
+ lifetimeSeconds: number
+}
+
+export function createAITokenService(options: AITokenServiceOptions) {
+ const { privateKey, publicJWK } = options.signingKey
+
+ return {
+ /**
+ * Signs a token that lets a workspace member reach the AI service on the workspace's behalf.
+ * Entitlements are read for every token, so a plan change reaches the service within one
+ * token lifetime.
+ */
+ async issue(actor: CloudActor, workspaceId: string): Promise<AIToken> {
+ if (!(await workspaceRole(options.database, actor.userId, workspaceId))) {
+ throw new DocumentNotFoundError()
+ }
+ const context = {
+ targetingKey: workspaceId,
+ actorId: actor.userId,
+ workspaceId,
+ deploymentMode: options.deploymentMode
+ }
+ const [enabled, allowance] = await Promise.all([
+ options.policy.boolean(CLOUD_FEATURE_KEYS.cloudAI, false, context),
+ options.policy.number(CLOUD_FEATURE_KEYS.monthlyCreditAllowance, -1, context)
+ ])
+ if (!enabled) throw new AINotEntitledError()
+ const issuedAt = Math.floor(Date.now() / 1000)
+ const expiresAt = issuedAt + options.lifetimeSeconds
+ const token = await new SignJWT({
+ workspaceId,
+ monthlyCreditAllowance: allowance < 0 ? null : allowance
+ })
+ .setProtectedHeader({ alg: AI_SIGNING_ALGORITHM, kid: publicJWK.kid, typ: 'JWT' })
+ .setIssuer(options.issuer)
+ .setAudience(CLOUD_AI_TOKEN_AUDIENCE)
+ .setSubject(actor.userId)
+ .setIssuedAt(issuedAt)
+ .setExpirationTime(expiresAt)
+ .sign(privateKey)
+ return { token, expiresAt: new Date(expiresAt * 1000).toISOString() }
+ },
+
+ jwks() {
+ return { keys: [publicJWK] }
+ }
+ }
+}
+
+export type AITokenService = ReturnType<typeof createAITokenService>
diff --git a/packages/cloud/src/server/app.ts b/packages/cloud/src/server/app.ts
index 0aaadb213..d54e2aaed 100644
--- a/packages/cloud/src/server/app.ts
+++ b/packages/cloud/src/server/app.ts
@@ -7,8 +7,14 @@ import {
createEnrollmentService,
type EnrollmentService
} from '#cloud/admin'
-import { CLOUD_DISCOVERY_PATH, CLOUD_PROTOCOL_VERSION, type CloudDiscovery } from '#cloud/contract'
+import {
+ CLOUD_AI_JWKS_PATH,
+ CLOUD_DISCOVERY_PATH,
+ CLOUD_PROTOCOL_VERSION,
+ type CloudDiscovery
+} from '#cloud/contract'
import { createAccountRoutes } from '#cloud/server/account/routes'
+import { createAIRoutes, createAITokenService, type AISigningKey } from '#cloud/server/ai'
import {
createCloudAPIRouter,
createPublicCloudAPIRouter,
@@ -22,11 +28,16 @@ import {
type CloudSessionResolver
} from '#cloud/server/auth'
import { createCollaborationTicketService } from '#cloud/server/collaboration'
-import { cloudDiscoveryFromConfig, type CloudServerConfig } from '#cloud/server/config'
+import {
+ CloudConfigError,
+ cloudDiscoveryFromConfig,
+ type CloudServerConfig
+} from '#cloud/server/config'
import type { CloudDatabase } from '#cloud/server/db'
import { createDocumentService } from '#cloud/server/documents'
import { createDocumentVersionService } from '#cloud/server/documents/versions'
import type { TransactionalEmailService } from '#cloud/server/email'
+import { createInternalRoutes, createInternalService } from '#cloud/server/internal'
import type { InvitationDelivery, InvitationOutbox } from '#cloud/server/invitations'
import type { ObjectStore } from '#cloud/server/objects'
import {
@@ -63,6 +74,8 @@ export type CloudServices = {
enrollment?: EnrollmentService
entitlementSource?: EntitlementSource
policy?: CloudPolicy
+ /** The imported `aiSigningKey`, required when the config names one. See `loadAISigningKey`. */
+ aiSigningKey?: AISigningKey
/**
* Where clients reach this runtime's collaboration relay. Without one, Cloud rooms fall back to
* peer-to-peer and writes are not enforced by the server.
@@ -234,6 +247,19 @@ export function createCloudApp(services: CloudServices) {
policy,
deploymentMode: services.config.deployment
})
+ if (services.config.aiSigningKey && !services.aiSigningKey) {
+ throw new CloudConfigError('The AI service needs the signing key imported by loadAISigningKey')
+ }
+ const aiTokens = services.aiSigningKey
+ ? createAITokenService({
+ database: services.database,
+ policy,
+ deploymentMode: services.config.deployment,
+ issuer: new URL(services.config.publicURL).origin,
+ signingKey: services.aiSigningKey,
+ lifetimeSeconds: services.config.aiTokenLifetimeSeconds
+ })
+ : undefined
const requireActiveSession = async (context: Context, next: () => Promise<void>) => {
const actor = await resolveSession(context.req.raw)
@@ -268,6 +294,7 @@ export function createCloudApp(services: CloudServices) {
(context) =>
context.req.method === 'GET' ||
context.req.path.endsWith('/collaboration-ticket') ||
+ context.req.path === '/api/ai/token' ||
context.req.path.endsWith('/invitations') ||
context.req.path.endsWith('/uploads') ||
/^\/api\/workspaces(?:\/[^/]+\/documents)?$/.test(context.req.path)
@@ -306,6 +333,14 @@ export function createCloudApp(services: CloudServices) {
resolveSession
})
+ // Services such as billing authenticate with their own token, not a session.
+ const internalAPI = services.config.internalServiceToken
+ ? createInternalRoutes(
+ createInternalService(services.database),
+ services.config.internalServiceToken
+ )
+ : new Hono()
+
return new Hono<CloudEnvironment>()
.use(CLOUD_DISCOVERY_PATH, cloudCORS)
.use('/api/*', cloudCORS)
@@ -351,6 +386,9 @@ export function createCloudApp(services: CloudServices) {
}
})
.get(CLOUD_DISCOVERY_PATH, (context) => context.json(discovery))
+ .get(CLOUD_AI_JWKS_PATH, async (context) =>
+ aiTokens ? context.json(aiTokens.jwks()) : context.notFound()
+ )
.on(['GET', 'POST'], '/api/auth/*', async (context) => {
if (POLICY_MANAGED_AUTH_PATHS.has(context.req.path)) {
return context.json({ error: { code: 'forbidden' as const } }, 403)
@@ -369,9 +407,14 @@ export function createCloudApp(services: CloudServices) {
.use('/api/shares/*', publicRateLimiter)
.use('/api/invitations/*', publicRateLimiter)
.route('/api', publicCloudAPI)
+ .route('/api/internal', internalAPI)
.use('/api/*', requireActiveSession)
.route('/api/admin', admin)
.use('/api/*', authenticatedMutationLimiter)
+ .route(
+ '/api',
+ createAIRoutes(aiTokens, { database: services.database, secret: services.config.authSecret })
+ )
.route('/api', cloudAPI)
}
diff --git a/packages/cloud/src/server/config/deployment.ts b/packages/cloud/src/server/config/deployment.ts
index c3ddc2889..483257308 100644
--- a/packages/cloud/src/server/config/deployment.ts
+++ b/packages/cloud/src/server/config/deployment.ts
@@ -1,5 +1,8 @@
import { cloudEditorVersionSchema } from '#cloud/contract'
-import { staticEntitlementsTOMLSchema } from '#cloud/server/policy/static'
+import {
+ staticEntitlementsFromTOML,
+ staticEntitlementsTOMLSchema
+} from '#cloud/server/policy/static'
import { parse as parseTOML } from 'smol-toml'
import * as v from 'valibot'
@@ -18,7 +21,9 @@ const DEFAULT_SECRET_NAMES = {
s3SessionToken: 'S3_SESSION_TOKEN',
smtpUser: 'OPENPENCIL_CLOUD_SMTP_USER',
smtpPassword: 'OPENPENCIL_CLOUD_SMTP_PASSWORD',
- turnstileSecretKey: 'TURNSTILE_SECRET_KEY'
+ turnstileSecretKey: 'TURNSTILE_SECRET_KEY',
+ aiSigningKey: 'OPENPENCIL_CLOUD_AI_SIGNING_KEY',
+ internalServiceToken: 'OPENPENCIL_CLOUD_SERVICE_TOKEN'
} as const
const url = v.pipe(v.string(), v.url())
@@ -214,6 +219,20 @@ export const cloudDeploymentConfigSchema = v.object({
v.object({ source: v.literal('database') })
])
),
+ ai: v.optional(
+ v.object({
+ endpoint: url,
+ signing_key: defaultReference(DEFAULT_SECRET_NAMES.aiSigningKey),
+ token_lifetime_minutes: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(60)),
+ 10
+ )
+ })
+ ),
+ billing: v.optional(v.object({ portal_url: url })),
+ internal_api: v.optional(
+ v.object({ service_token: defaultReference(DEFAULT_SECRET_NAMES.internalServiceToken) })
+ ),
technical_limits: v.optional(
v.object({
maximum_upload_bytes: v.optional(positiveInteger),
@@ -254,23 +273,7 @@ function optionalSecret(
function staticEntitlements(config: CloudDeploymentConfig) {
if (config.entitlements?.source !== 'static') return undefined
- return {
- documents: {
- maximumFileBytes: config.entitlements.documents?.maximum_file_bytes,
- revisionHistory: config.entitlements.documents?.revision_history
- },
- storage: { maximumBytes: config.entitlements.storage?.maximum_bytes },
- sharing: {
- capabilityLinks: config.entitlements.sharing?.capability_links,
- anonymousView: config.entitlements.sharing?.anonymous_view,
- anonymousEdit: config.entitlements.sharing?.anonymous_edit,
- guestPresence: config.entitlements.sharing?.guest_presence
- },
- collaboration: {
- enabled: config.entitlements.collaboration?.enabled,
- maximumParticipants: config.entitlements.collaboration?.maximum_participants
- }
- }
+ return staticEntitlementsFromTOML(config.entitlements)
}
function emailConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {
@@ -319,6 +322,18 @@ function workerConfig(config: CloudDeploymentConfig) {
}
}
+function serviceConfig(config: CloudDeploymentConfig, environment: CloudEnvironment) {
+ return {
+ aiEndpoint: config.ai?.endpoint,
+ aiSigningKey: config.ai ? requiredSecret(environment, config.ai.signing_key) : undefined,
+ aiTokenLifetimeSeconds: config.ai ? config.ai.token_lifetime_minutes * 60 : undefined,
+ billingPortalURL: config.billing?.portal_url,
+ internalServiceToken: config.internal_api
+ ? requiredSecret(environment, config.internal_api.service_token)
+ : undefined
+ }
+}
+
function technicalLimits(config: CloudDeploymentConfig) {
const limits = config.technical_limits
if (!limits) return undefined
@@ -389,6 +404,7 @@ export function parseCloudDeploymentConfig(
staticEntitlements: staticEntitlements(config),
...emailConfig(config, environment),
...workerConfig(config),
+ ...serviceConfig(config, environment),
technicalLimits: technicalLimits(config)
})
}
diff --git a/packages/cloud/src/server/config/public.ts b/packages/cloud/src/server/config/public.ts
index 7cd95ffe7..81f88bb00 100644
--- a/packages/cloud/src/server/config/public.ts
+++ b/packages/cloud/src/server/config/public.ts
@@ -1,4 +1,9 @@
-import { CLOUD_PROTOCOL_VERSION, parseCloudDiscovery, type CloudDiscovery } from '#cloud/contract'
+import {
+ CLOUD_AI_CONTRACT_VERSION,
+ CLOUD_PROTOCOL_VERSION,
+ parseCloudDiscovery,
+ type CloudDiscovery
+} from '#cloud/contract'
import { withoutTrailingSlash } from 'ufo'
import type { CloudServerConfig } from './schema'
@@ -52,6 +57,10 @@ export function cloudDiscoveryFromConfig(config: CloudServerConfig): CloudDiscov
},
listing: config.listingMinimumEditorVersion
? { minimumEditorVersion: config.listingMinimumEditorVersion }
- : undefined
+ : undefined,
+ ai: config.aiEndpoint
+ ? { endpoint: config.aiEndpoint, contractVersion: CLOUD_AI_CONTRACT_VERSION }
+ : undefined,
+ billing: config.billingPortalURL ? { portalURL: config.billingPortalURL } : undefined
})
}
diff --git a/packages/cloud/src/server/config/schema.ts b/packages/cloud/src/server/config/schema.ts
index fcb3a4481..ab87a9e43 100644
--- a/packages/cloud/src/server/config/schema.ts
+++ b/packages/cloud/src/server/config/schema.ts
@@ -133,7 +133,18 @@ const rawCloudServerConfigSchema = v.object({
documentRetentionMs: v.optional(
v.pipe(v.number(), v.integer(), v.minValue(0)),
30 * 24 * 60 * 60_000
- )
+ ),
+ /** The AI service editors reach with tokens this server signs; see `src/contract/ai.ts`. */
+ aiEndpoint: v.optional(httpURLSchema),
+ /** The PKCS #8 PEM of the P-256 key that signs AI service tokens. */
+ aiSigningKey: optionalTextSchema,
+ aiTokenLifetimeSeconds: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(60), v.maxValue(60 * 60)),
+ 10 * 60
+ ),
+ billingPortalURL: v.optional(httpURLSchema),
+ /** The bearer token services such as billing present to the internal API. */
+ internalServiceToken: v.optional(v.pipe(v.string(), v.minLength(32)))
})
export type CloudServerConfig = v.InferOutput<typeof rawCloudServerConfigSchema>
@@ -217,6 +228,22 @@ function validateEmailConfig(config: CloudServerConfig): void {
}
}
+function validateServiceConfig(config: CloudServerConfig): void {
+ requireTogether(config, 'AI service', ['aiEndpoint', 'aiSigningKey'])
+ if (config.internalServiceToken && config.staticEntitlements) {
+ throw new CloudConfigError(
+ 'The internal API writes database entitlements, which static entitlements would hide'
+ )
+ }
+ if (
+ config.deployment === 'official' &&
+ config.aiEndpoint &&
+ new URL(config.aiEndpoint).protocol !== 'https:'
+ ) {
+ throw new CloudConfigError('Official AI service endpoint must use HTTPS')
+ }
+}
+
function validateObjectStorageConfig(config: CloudServerConfig): void {
if (config.s3KmsKeyId && config.s3ServerSideEncryption !== 'aws:kms') {
throw new CloudConfigError('S3 KMS key ID requires aws:kms server-side encryption')
@@ -246,6 +273,7 @@ export function parseCloudServerConfig(input: unknown): CloudServerConfig {
}
validateAuthenticationConfig(config)
validateEmailConfig(config)
+ validateServiceConfig(config)
validateObjectStorageConfig(config)
return config
}
diff --git a/packages/cloud/src/server/db/migrate.ts b/packages/cloud/src/server/db/migrate.ts
index 4c9e68e5f..97695f59c 100644
--- a/packages/cloud/src/server/db/migrate.ts
+++ b/packages/cloud/src/server/db/migrate.ts
@@ -22,6 +22,7 @@ import * as authenticationMFA from './migrations/018_authentication_mfa'
import * as betterAuthAccountIssuer from './migrations/019_better_auth_account_issuer'
import * as workspaceInvitations from './migrations/020_workspace_invitations'
import * as documentVersions from './migrations/021_document_versions'
+import * as entitlementExternalVersion from './migrations/022_entitlement_external_version'
import type { CloudDatabase } from './schema'
const migrations: Record<string, Migration> = {
@@ -45,7 +46,8 @@ const migrations: Record<string, Migration> = {
'018_authentication_mfa': authenticationMFA,
'019_better_auth_account_issuer': betterAuthAccountIssuer,
'020_workspace_invitations': workspaceInvitations,
- '021_document_versions': documentVersions
+ '021_document_versions': documentVersions,
+ '022_entitlement_external_version': entitlementExternalVersion
}
class CloudMigrationProvider implements MigrationProvider {
diff --git a/packages/cloud/src/server/db/migrations/022_entitlement_external_version.ts b/packages/cloud/src/server/db/migrations/022_entitlement_external_version.ts
new file mode 100644
index 000000000..1d67c7abf
--- /dev/null
+++ b/packages/cloud/src/server/db/migrations/022_entitlement_external_version.ts
@@ -0,0 +1,17 @@
+import type { CloudDatabase } from '#cloud/server/db/schema'
+import type { Kysely } from 'kysely'
+
+/**
+ * The version an external writer, such as a billing service, attached to a workspace's
+ * entitlements. Writers deliver out of order, so a write older than the stored one is refused.
+ */
+export async function up(database: Kysely<CloudDatabase>): Promise<void> {
+ await database.schema
+ .alterTable('workspaceEntitlement')
+ .addColumn('externalVersion', 'bigint')
+ .execute()
+}
+
+export async function down(database: Kysely<CloudDatabase>): Promise<void> {
+ await database.schema.alterTable('workspaceEntitlement').dropColumn('externalVersion').execute()
+}
diff --git a/packages/cloud/src/server/db/schema.ts b/packages/cloud/src/server/db/schema.ts
index c31ce7e92..d1adb4e9a 100644
--- a/packages/cloud/src/server/db/schema.ts
+++ b/packages/cloud/src/server/db/schema.ts
@@ -208,6 +208,8 @@ export interface WorkspaceEntitlementTable {
values: unknown
source: string
revision: Generated<number>
+ /** Set only by versioned writes; see `setVersioned`. */
+ externalVersion: number | null
updatedAt: TimestampColumn
}
diff --git a/packages/cloud/src/server/index.ts b/packages/cloud/src/server/index.ts
index 6c7bce807..3c11098f2 100644
--- a/packages/cloud/src/server/index.ts
+++ b/packages/cloud/src/server/index.ts
@@ -19,6 +19,17 @@ export {
type EnrollmentService,
type EnrollmentStatus
} from '#cloud/admin'
+export {
+ AINotEntitledError,
+ createAIRoutes,
+ createAITokenService,
+ importAISigningKey,
+ loadAISigningKey,
+ type AIRouteEnvironment,
+ type AISigningKey,
+ type AITokenService,
+ type AITokenServiceOptions
+} from './ai'
export {
createAuthenticationEmailService,
createAccountAuthenticationService,
@@ -167,6 +178,14 @@ export {
type TransactionalEmailWorker,
type TransactionalEmailWorkerOptions
} from './email'
+export {
+ createInternalRoutes,
+ createInternalService,
+ parseSetWorkspaceEntitlements,
+ setWorkspaceEntitlementsSchema,
+ type InternalService,
+ type SetWorkspaceEntitlementsInput
+} from './internal'
export {
noOpInvitationDelivery,
type DocumentInvitationMessage,
@@ -221,7 +240,8 @@ export {
type EntitlementSource,
type EntitlementService,
type EntitlementSubject,
- type StaticEntitlements
+ type StaticEntitlements,
+ type StaticEntitlementsInput
} from './policy'
export {
createStorageQuotaService,
diff --git a/packages/cloud/src/server/internal/index.ts b/packages/cloud/src/server/internal/index.ts
new file mode 100644
index 000000000..137f5d983
--- /dev/null
+++ b/packages/cloud/src/server/internal/index.ts
@@ -0,0 +1,8 @@
+export { createInternalRoutes } from './routes'
+export {
+ createInternalService,
+ parseSetWorkspaceEntitlements,
+ setWorkspaceEntitlementsSchema,
+ type InternalService,
+ type SetWorkspaceEntitlementsInput
+} from './service'
diff --git a/packages/cloud/src/server/internal/routes.ts b/packages/cloud/src/server/internal/routes.ts
new file mode 100644
index 000000000..0d4d177d5
--- /dev/null
+++ b/packages/cloud/src/server/internal/routes.ts
@@ -0,0 +1,41 @@
+import { capabilityHashMatches, hashCapability } from '#cloud/server/sharing/crypto'
+import { validatedJSON } from '#cloud/server/validation'
+import { Hono } from 'hono'
+import { bearerAuth } from 'hono/bearer-auth'
+import * as v from 'valibot'
+
+import { parseSetWorkspaceEntitlements, type InternalService } from './service'
+
+const uuid = v.pipe(v.string(), v.uuid())
+
+/** The internal API on HTTP, for runtimes without a private transport to their services. */
+export function createInternalRoutes(service: InternalService, serviceToken: string) {
+ const digest = hashCapability(serviceToken)
+ const unauthorized = { error: { code: 'unauthorized' as const } }
+ return new Hono()
+ .use(
+ '*',
+ bearerAuth({
+ verifyToken: (token) => capabilityHashMatches(digest, token),
+ noAuthenticationHeader: { message: unauthorized },
+ invalidAuthenticationHeader: { message: unauthorized },
+ invalidToken: { message: unauthorized }
+ })
+ )
+ .put(
+ '/workspaces/:workspaceId/entitlements',
+ validatedJSON(parseSetWorkspaceEntitlements),
+ async (context) => {
+ const workspaceId = context.req.param('workspaceId')
+ if (!v.is(uuid, workspaceId)) {
+ return context.json({ error: { code: 'not_found' as const } }, 404)
+ }
+ const result = await service.setWorkspaceEntitlements(
+ workspaceId,
+ context.req.valid('json')
+ )
+ if (!result.found) return context.json({ error: { code: 'not_found' as const } }, 404)
+ return context.json({ applied: result.applied })
+ }
+ )
+}
diff --git a/packages/cloud/src/server/internal/service.ts b/packages/cloud/src/server/internal/service.ts
new file mode 100644
index 000000000..e1ee83648
--- /dev/null
+++ b/packages/cloud/src/server/internal/service.ts
@@ -0,0 +1,52 @@
+import type { CloudDatabase } from '#cloud/server/db'
+import {
+ createWorkspaceEntitlementRepository,
+ staticEntitlementsSchema
+} from '#cloud/server/policy'
+import type { Kysely } from 'kysely'
+import * as v from 'valibot'
+
+export const setWorkspaceEntitlementsSchema = v.object({
+ values: staticEntitlementsSchema,
+ /** Who decided these values, such as `billing`; stored as the row's source. */
+ source: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(64)),
+ /** Increases with every decision the writer makes, such as a billing event's timestamp. */
+ externalVersion: v.pipe(v.number(), v.safeInteger(), v.minValue(0))
+})
+export type SetWorkspaceEntitlementsInput = v.InferInput<typeof setWorkspaceEntitlementsSchema>
+
+export function parseSetWorkspaceEntitlements(input: unknown) {
+ return v.parse(setWorkspaceEntitlementsSchema, input)
+}
+
+/**
+ * What services beside Cloud, such as billing, may change. Runtimes expose it to them through
+ * their own transport: an authenticated HTTP route on Node, a service binding on Workers.
+ */
+export function createInternalService(database: Kysely<CloudDatabase>) {
+ const entitlements = createWorkspaceEntitlementRepository(database)
+ return {
+ /** `found` is false for an unknown workspace; `applied` is false for an outdated version. */
+ async setWorkspaceEntitlements(
+ workspaceId: string,
+ input: SetWorkspaceEntitlementsInput
+ ): Promise<{ found: boolean; applied: boolean }> {
+ const { values, source, externalVersion } = parseSetWorkspaceEntitlements(input)
+ const workspace = await database
+ .selectFrom('workspace')
+ .select('id')
+ .where('id', '=', workspaceId)
+ .executeTakeFirst()
+ if (!workspace) return { found: false, applied: false }
+ const { applied } = await entitlements.setVersioned(
+ workspaceId,
+ values,
+ source,
+ externalVersion
+ )
+ return { found: true, applied }
+ }
+ }
+}
+
+export type InternalService = ReturnType<typeof createInternalService>
diff --git a/packages/cloud/src/server/policy/database.ts b/packages/cloud/src/server/policy/database.ts
index d3f50f202..704687a9f 100644
--- a/packages/cloud/src/server/policy/database.ts
+++ b/packages/cloud/src/server/policy/database.ts
@@ -6,7 +6,7 @@ import type { EntitlementSource, EntitlementSubject } from './entitlements'
import {
staticEntitlementValues,
staticEntitlementsSchema,
- type StaticEntitlements
+ type StaticEntitlementsInput
} from './static'
export class DatabaseEntitlementSource implements EntitlementSource {
@@ -47,7 +47,7 @@ export function createWorkspaceEntitlementRepository(database: Kysely<CloudDatab
.executeTakeFirst()
},
- async set(workspaceId: string, values: StaticEntitlements, source: string) {
+ async set(workspaceId: string, values: StaticEntitlementsInput, source: string) {
const validated = v.parse(staticEntitlementsSchema, values)
return database
.insertInto('workspaceEntitlement')
@@ -64,6 +64,43 @@ export function createWorkspaceEntitlementRepository(database: Kysely<CloudDatab
.executeTakeFirstOrThrow()
},
+ /**
+ * Stores entitlements an external writer versioned, unless the stored row carries a newer
+ * version: billing events arrive out of order, and a late one must not undo a newer plan.
+ * An unversioned row, such as one an operator set, is replaced.
+ */
+ async setVersioned(
+ workspaceId: string,
+ values: StaticEntitlementsInput,
+ source: string,
+ externalVersion: number
+ ): Promise<{ applied: boolean }> {
+ const validated = v.parse(staticEntitlementsSchema, values)
+ const row = await database
+ .insertInto('workspaceEntitlement')
+ .values({ workspaceId, values: validated, source, externalVersion })
+ .onConflict((conflict) =>
+ conflict
+ .column('workspaceId')
+ .doUpdateSet({
+ values: validated,
+ source,
+ externalVersion,
+ revision: (expression) => expression('workspaceEntitlement.revision', '+', 1),
+ updatedAt: new Date()
+ })
+ .where((expression) =>
+ expression.or([
+ expression('workspaceEntitlement.externalVersion', 'is', null),
+ expression('workspaceEntitlement.externalVersion', '<', externalVersion)
+ ])
+ )
+ )
+ .returning('workspaceId')
+ .executeTakeFirst()
+ return { applied: row !== undefined }
+ },
+
async clear(workspaceId: string): Promise<void> {
await database
.deleteFrom('workspaceEntitlement')
diff --git a/packages/cloud/src/server/policy/index.ts b/packages/cloud/src/server/policy/index.ts
index fc48ed47c..0976c164b 100644
--- a/packages/cloud/src/server/policy/index.ts
+++ b/packages/cloud/src/server/policy/index.ts
@@ -10,7 +10,8 @@ export {
parseStaticEntitlementsTOML,
staticEntitlementValues,
staticEntitlementsSchema,
- type StaticEntitlements
+ type StaticEntitlements,
+ type StaticEntitlementsInput
} from './static'
export { CloudPolicy, createDefaultCloudPolicy } from './policy'
export { createEntitlementService, type EntitlementService } from './service'
diff --git a/packages/cloud/src/server/policy/keys.ts b/packages/cloud/src/server/policy/keys.ts
index bea971d04..60f413bf6 100644
--- a/packages/cloud/src/server/policy/keys.ts
+++ b/packages/cloud/src/server/policy/keys.ts
@@ -8,7 +8,9 @@ export const CLOUD_FEATURE_KEYS = {
revisionHistory: 'cloud.documents.revision-history',
maximumFileBytes: 'cloud.documents.maximum-file-bytes',
maximumStorageBytes: 'cloud.storage.maximum-bytes',
- maximumParticipants: 'cloud.collaboration.maximum-participants'
+ maximumParticipants: 'cloud.collaboration.maximum-participants',
+ cloudAI: 'cloud.ai.enabled',
+ monthlyCreditAllowance: 'cloud.ai.monthly-credit-allowance'
} as const
export type CloudPolicyContext = {
diff --git a/packages/cloud/src/server/policy/service.ts b/packages/cloud/src/server/policy/service.ts
index e44f807d3..adc8908cc 100644
--- a/packages/cloud/src/server/policy/service.ts
+++ b/packages/cloud/src/server/policy/service.ts
@@ -31,9 +31,11 @@ export function createEntitlementService(
guestPresence,
collaboration,
revisionHistory,
+ cloudAI,
maximumFileBytes,
maximumStorage,
maximumParticipants,
+ monthlyCreditAllowance,
usage
] = await Promise.all([
policy.boolean(CLOUD_FEATURE_KEYS.capabilityLinks, false, context),
@@ -42,6 +44,7 @@ export function createEntitlementService(
policy.boolean(CLOUD_FEATURE_KEYS.guestPresence, false, context),
policy.boolean(CLOUD_FEATURE_KEYS.collaboration, false, context),
policy.boolean(CLOUD_FEATURE_KEYS.revisionHistory, false, context),
+ policy.boolean(CLOUD_FEATURE_KEYS.cloudAI, false, context),
policy.number(CLOUD_FEATURE_KEYS.maximumFileBytes, technicalMaximumFileBytes, context),
policy.number(CLOUD_FEATURE_KEYS.maximumStorageBytes, Number.MAX_SAFE_INTEGER, context),
policy.number(
@@ -49,6 +52,7 @@ export function createEntitlementService(
technicalMaximumParticipants,
context
),
+ policy.number(CLOUD_FEATURE_KEYS.monthlyCreditAllowance, -1, context),
quota.snapshot(workspaceId)
])
// Technical limits are ceilings: an entitlement can lower them but never raise them.
@@ -60,12 +64,14 @@ export function createEntitlementService(
anonymousEdit,
guestPresence,
collaboration,
- revisionHistory
+ revisionHistory,
+ cloudAI
},
limits: {
maximumFileBytes: Math.min(technicalMaximumFileBytes, maximumFileBytes),
maximumStorageBytes: maximumStorage === Number.MAX_SAFE_INTEGER ? null : maximumStorage,
- maximumParticipants: participants === Number.MAX_SAFE_INTEGER ? null : participants
+ maximumParticipants: participants === Number.MAX_SAFE_INTEGER ? null : participants,
+ monthlyCreditAllowance: monthlyCreditAllowance < 0 ? null : monthlyCreditAllowance
},
usage: {
committedStorageBytes: usage.committedBytes,
diff --git a/packages/cloud/src/server/policy/static.ts b/packages/cloud/src/server/policy/static.ts
index 458b5796a..137fea0de 100644
--- a/packages/cloud/src/server/policy/static.ts
+++ b/packages/cloud/src/server/policy/static.ts
@@ -5,6 +5,7 @@ import * as v from 'valibot'
import { CLOUD_FEATURE_KEYS } from './keys'
const positiveInteger = v.pipe(v.number(), v.integer(), v.minValue(1))
+const nonNegativeInteger = v.pipe(v.number(), v.integer(), v.minValue(0))
export const staticEntitlementsSchema = v.object({
documents: v.optional(
@@ -30,10 +31,19 @@ export const staticEntitlementsSchema = v.object({
maximumParticipants: v.optional(positiveInteger)
}),
{}
+ ),
+ ai: v.optional(
+ v.object({
+ enabled: v.optional(v.boolean()),
+ monthlyCreditAllowance: v.optional(nonNegativeInteger)
+ }),
+ {}
)
})
export type StaticEntitlements = v.InferOutput<typeof staticEntitlementsSchema>
+/** Entitlements as a writer sends them, with any group left out. */
+export type StaticEntitlementsInput = v.InferInput<typeof staticEntitlementsSchema>
export const staticEntitlementsTOMLSchema = v.object({
documents: v.optional(
@@ -56,11 +66,19 @@ export const staticEntitlementsTOMLSchema = v.object({
enabled: v.optional(v.boolean()),
maximum_participants: v.optional(positiveInteger)
})
+ ),
+ ai: v.optional(
+ v.object({
+ enabled: v.optional(v.boolean()),
+ monthly_credit_allowance: v.optional(nonNegativeInteger)
+ })
)
})
-export function parseStaticEntitlementsTOML(input: unknown): StaticEntitlements {
- const value = v.parse(staticEntitlementsTOMLSchema, input)
+/** Entitlements as the deployment TOML spells them, renamed to their structured form. */
+export function staticEntitlementsFromTOML(
+ value: v.InferOutput<typeof staticEntitlementsTOMLSchema>
+): StaticEntitlements {
return v.parse(staticEntitlementsSchema, {
documents: {
maximumFileBytes: value.documents?.maximum_file_bytes,
@@ -76,10 +94,18 @@ export function parseStaticEntitlementsTOML(input: unknown): StaticEntitlements
collaboration: {
enabled: value.collaboration?.enabled,
maximumParticipants: value.collaboration?.maximum_participants
+ },
+ ai: {
+ enabled: value.ai?.enabled,
+ monthlyCreditAllowance: value.ai?.monthly_credit_allowance
}
})
}
+export function parseStaticEntitlementsTOML(input: unknown): StaticEntitlements {
+ return staticEntitlementsFromTOML(v.parse(staticEntitlementsTOMLSchema, input))
+}
+
export function staticEntitlementValues(input: unknown): Record<string, boolean | number> {
const entitlements = v.parse(staticEntitlementsSchema, input)
const values: Record<string, boolean | number | undefined> = {
@@ -91,7 +117,9 @@ export function staticEntitlementValues(input: unknown): Record<string, boolean
[CLOUD_FEATURE_KEYS.anonymousEdit]: entitlements.sharing.anonymousEdit,
[CLOUD_FEATURE_KEYS.guestPresence]: entitlements.sharing.guestPresence,
[CLOUD_FEATURE_KEYS.collaboration]: entitlements.collaboration.enabled,
- [CLOUD_FEATURE_KEYS.maximumParticipants]: entitlements.collaboration.maximumParticipants
+ [CLOUD_FEATURE_KEYS.maximumParticipants]: entitlements.collaboration.maximumParticipants,
+ [CLOUD_FEATURE_KEYS.cloudAI]: entitlements.ai.enabled,
+ [CLOUD_FEATURE_KEYS.monthlyCreditAllowance]: entitlements.ai.monthlyCreditAllowance
}
return pickBy(values, isNotNil) as Record<string, boolean | number>
}
diff --git a/packages/cloud/src/server/rate-limit/middleware.ts b/packages/cloud/src/server/rate-limit/middleware.ts
index 63f9663cf..0635dec5f 100644
--- a/packages/cloud/src/server/rate-limit/middleware.ts
+++ b/packages/cloud/src/server/rate-limit/middleware.ts
@@ -21,6 +21,7 @@ export const CLOUD_RATE_LIMITS = {
documentCreation: { namespace: 'document-creation', windowMs: 60_000, limit: 60 },
uploadCreation: { namespace: 'upload-creation', windowMs: 60_000, limit: 120 },
authenticatedMutation: { namespace: 'authenticated-mutation', windowMs: 60_000, limit: 120 },
+ aiToken: { namespace: 'ai-token', windowMs: 60_000, limit: 30 },
adminRead: { namespace: 'admin-read', windowMs: 60_000, limit: 300 },
adminMutation: { namespace: 'admin-mutation', windowMs: 60_000, limit: 30 }
} as const satisfies Record<string, RateLimitPolicy>
diff --git a/packages/cloud/tests/contract/ai.test.ts b/packages/cloud/tests/contract/ai.test.ts
new file mode 100644
index 000000000..39a77e40e
--- /dev/null
+++ b/packages/cloud/tests/contract/ai.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ aiTokenClaimsSchema,
+ CLOUD_AI_TOKEN_AUDIENCE,
+ CLOUD_PROTOCOL_VERSION,
+ parseCloudDiscovery,
+ parseCreateAIToken,
+ workspaceEntitlementsSchema
+} from '#cloud/contract'
+import * as v from 'valibot'
+
+const discovery = {
+ protocolVersion: CLOUD_PROTOCOL_VERSION,
+ deployment: 'official' as const,
+ apiURL: 'https://cloud.example.com/api',
+ authURL: 'https://cloud.example.com/api/auth',
+ authentication: { socialProviders: [], enterpriseSSO: false },
+ capabilities: { documents: true, workspaces: true, collaboration: true }
+}
+
+describe('Cloud AI contract', () => {
+ test('discovery stays valid without an AI service, so older servers still parse', () => {
+ expect(parseCloudDiscovery(discovery).ai).toBeUndefined()
+ })
+
+ test('discovery advertises an AI service only for a contract version editors speak', () => {
+ const ai = { endpoint: 'https://ai.example.com', contractVersion: '1' as const }
+ expect(parseCloudDiscovery({ ...discovery, ai }).ai).toEqual(ai)
+ expect(() =>
+ parseCloudDiscovery({ ...discovery, ai: { ...ai, contractVersion: '2' } })
+ ).toThrow()
+ })
+
+ test('token requests name a workspace by its ID', () => {
+ const workspaceId = crypto.randomUUID()
+ expect(parseCreateAIToken({ workspaceId })).toEqual({ workspaceId })
+ expect(() => parseCreateAIToken({ workspaceId: 'personal' })).toThrow()
+ })
+
+ test('token claims carry the workspace and its allowance for the AI service', () => {
+ const claims = {
+ iss: 'https://cloud.example.com',
+ aud: CLOUD_AI_TOKEN_AUDIENCE,
+ sub: 'user-1',
+ workspaceId: crypto.randomUUID(),
+ monthlyCreditAllowance: null,
+ iat: 1,
+ exp: 2
+ }
+ expect(v.parse(aiTokenClaimsSchema, claims)).toEqual(claims)
+ expect(v.is(aiTokenClaimsSchema, { ...claims, aud: 'other' })).toBe(false)
+ })
+})
+
+describe('workspace entitlements contract', () => {
+ test('reads entitlements from servers released before the AI service', () => {
+ const entitlements = v.parse(workspaceEntitlementsSchema, {
+ features: {
+ capabilityLinks: true,
+ anonymousView: true,
+ anonymousEdit: false,
+ guestPresence: true,
+ collaboration: true,
+ revisionHistory: true
+ },
+ limits: { maximumFileBytes: 1, maximumStorageBytes: null, maximumParticipants: null },
+ usage: { committedStorageBytes: 0, reservedStorageBytes: 0 }
+ })
+ expect(entitlements.features.cloudAI).toBe(false)
+ expect(entitlements.limits.monthlyCreditAllowance).toBeNull()
+ })
+})
diff --git a/packages/cloud/tests/helpers/auth.ts b/packages/cloud/tests/helpers/auth.ts
new file mode 100644
index 000000000..f5f9e6349
--- /dev/null
+++ b/packages/cloud/tests/helpers/auth.ts
@@ -0,0 +1,25 @@
+import { createBetterAuthAdapter, type CloudDatabase, type CloudServerConfig } from '#cloud/server'
+import {
+ DummyDriver,
+ Kysely,
+ PostgresAdapter,
+ PostgresIntrospector,
+ PostgresQueryCompiler
+} from 'kysely'
+
+/**
+ * An auth adapter for apps whose tests resolve sessions themselves. Better Auth checks its schema
+ * in the background once created, so an adapter on the test database can still be querying it
+ * when a short test closes it; this one queries a database that answers nothing.
+ */
+export function unusedAuthAdapter(config: CloudServerConfig) {
+ const database = new Kysely<CloudDatabase>({
+ dialect: {
+ createAdapter: () => new PostgresAdapter(),
+ createDriver: () => new DummyDriver(),
+ createIntrospector: (kysely) => new PostgresIntrospector(kysely),
+ createQueryCompiler: () => new PostgresQueryCompiler()
+ }
+ })
+ return createBetterAuthAdapter(config, database)
+}
diff --git a/packages/cloud/tests/integration/server/ai/token.test.ts b/packages/cloud/tests/integration/server/ai/token.test.ts
new file mode 100644
index 000000000..fecbb7832
--- /dev/null
+++ b/packages/cloud/tests/integration/server/ai/token.test.ts
@@ -0,0 +1,192 @@
+import { describe, expect, test } from 'bun:test'
+
+import { unusedAuthAdapter } from '#cloud-tests/helpers/auth'
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createMemoryObjectStore } from '#cloud-tests/helpers/objects'
+import { responseJSON } from '#cloud-tests/helpers/response'
+import {
+ aiTokenClaimsSchema,
+ aiTokenSchema,
+ CLOUD_AI_JWKS_PATH,
+ CLOUD_AI_TOKEN_AUDIENCE
+} from '#cloud/contract'
+import {
+ CLOUD_FEATURE_KEYS,
+ CloudConfigError,
+ createCloudApp,
+ loadAISigningKey,
+ parseCloudServerConfig,
+ StaticEntitlementSource,
+ type CloudActor
+} from '#cloud/server'
+import {
+ createLocalJWKSet,
+ exportPKCS8,
+ generateKeyPair,
+ jwtVerify,
+ type JSONWebKeySet
+} from 'jose'
+import * as v from 'valibot'
+
+const baseConfig = {
+ deployment: 'self-hosted' as const,
+ publicURL: 'http://localhost:8787',
+ databaseURL: 'postgresql://test:test@localhost/test',
+ authSecret: 'integration-test-secret-at-least-32-characters',
+ s3Endpoint: 'http://localhost:9000',
+ s3Region: 'us-east-1',
+ s3Bucket: 'openpencil',
+ s3AccessKeyId: 'openpencil',
+ s3SecretAccessKey: 'openpencil-secret'
+}
+
+const member: CloudActor = { userId: 'member', email: '[email protected]', name: 'Member' }
+const stranger: CloudActor = { userId: 'stranger', email: '[email protected]', name: 'S' }
+
+const jwksSchema = v.custom<JSONWebKeySet>(
+ (value) => v.is(v.object({ keys: v.array(v.object({ kid: v.string() })) }), value),
+ 'Expected a JWKS'
+)
+
+async function signingKeyPEM() {
+ const { privateKey } = await generateKeyPair('ES256', { extractable: true })
+ return exportPKCS8(privateKey)
+}
+
+async function testApp(options: {
+ actor: CloudActor
+ entitlements?: Record<string, boolean | number>
+ ai?: boolean
+}) {
+ const runtime = await createCloudTestDatabase()
+ const config = parseCloudServerConfig(
+ options.ai === false
+ ? baseConfig
+ : { ...baseConfig, aiEndpoint: 'https://ai.example.com', aiSigningKey: await signingKeyPEM() }
+ )
+ const workspaceId = crypto.randomUUID()
+ await runtime.database
+ .insertInto('workspace')
+ .values({ id: workspaceId, name: 'W', slug: `w-${workspaceId}`, createdBy: member.userId })
+ .execute()
+ await runtime.database
+ .insertInto('workspaceMember')
+ .values({ workspaceId, userId: member.userId, role: 'editor' })
+ .execute()
+ const app = createCloudApp({
+ config,
+ database: runtime.database,
+ auth: unusedAuthAdapter(config),
+ objects: createMemoryObjectStore().store,
+ resolveSession: async () => options.actor,
+ entitlementSource: new StaticEntitlementSource(options.entitlements ?? {}),
+ aiSigningKey: await loadAISigningKey(config)
+ })
+ const requestToken = () =>
+ app.request('/api/ai/token', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ workspaceId })
+ })
+ return { runtime, app, workspaceId, requestToken }
+}
+
+describe('AI service tokens', () => {
+ test('a member of an entitled workspace gets a token the published keys verify', async () => {
+ const context = await testApp({
+ actor: member,
+ entitlements: {
+ [CLOUD_FEATURE_KEYS.cloudAI]: true,
+ [CLOUD_FEATURE_KEYS.monthlyCreditAllowance]: 5000
+ }
+ })
+ try {
+ const response = await context.requestToken()
+ expect(response.status).toBe(200)
+ const { token, expiresAt } = await responseJSON(response, aiTokenSchema)
+
+ const keys = await responseJSON(await context.app.request(CLOUD_AI_JWKS_PATH), jwksSchema)
+ const { payload, protectedHeader } = await jwtVerify(token, createLocalJWKSet(keys), {
+ issuer: 'http://localhost:8787',
+ audience: CLOUD_AI_TOKEN_AUDIENCE
+ })
+ expect(protectedHeader.kid).toBe(keys.keys[0]?.kid)
+ expect(v.parse(aiTokenClaimsSchema, payload)).toMatchObject({
+ sub: member.userId,
+ workspaceId: context.workspaceId,
+ monthlyCreditAllowance: 5000
+ })
+ expect(new Date(expiresAt).getTime()).toBe((payload.exp ?? 0) * 1000)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('a workspace without the entitlement is refused, and one with no allowance gets null', async () => {
+ const refused = await testApp({ actor: member })
+ try {
+ expect((await refused.requestToken()).status).toBe(403)
+ } finally {
+ await refused.runtime.close()
+ }
+ const unlimited = await testApp({
+ actor: member,
+ entitlements: { [CLOUD_FEATURE_KEYS.cloudAI]: true }
+ })
+ try {
+ const { token } = await responseJSON(await unlimited.requestToken(), aiTokenSchema)
+ const keys = await responseJSON(await unlimited.app.request(CLOUD_AI_JWKS_PATH), jwksSchema)
+ const { payload } = await jwtVerify(token, createLocalJWKSet(keys))
+ expect(payload.monthlyCreditAllowance).toBeNull()
+ } finally {
+ await unlimited.runtime.close()
+ }
+ })
+
+ test('someone outside the workspace cannot tell it exists', async () => {
+ const context = await testApp({
+ actor: stranger,
+ entitlements: { [CLOUD_FEATURE_KEYS.cloudAI]: true }
+ })
+ try {
+ expect((await context.requestToken()).status).toBe(404)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('a deployment without an AI service publishes no keys and signs no tokens', async () => {
+ const context = await testApp({
+ actor: member,
+ ai: false,
+ entitlements: { [CLOUD_FEATURE_KEYS.cloudAI]: true }
+ })
+ try {
+ expect((await context.app.request(CLOUD_AI_JWKS_PATH)).status).toBe(404)
+ expect((await context.requestToken()).status).toBe(404)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('an app configured with a key it was not given refuses to start', async () => {
+ const runtime = await createCloudTestDatabase()
+ try {
+ const config = parseCloudServerConfig({
+ ...baseConfig,
+ aiEndpoint: 'https://ai.example.com',
+ aiSigningKey: await signingKeyPEM()
+ })
+ expect(() =>
+ createCloudApp({
+ config,
+ database: runtime.database,
+ auth: unusedAuthAdapter(config),
+ objects: createMemoryObjectStore().store
+ })
+ ).toThrow(CloudConfigError)
+ } finally {
+ await runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/integration/server/internal/routes.test.ts b/packages/cloud/tests/integration/server/internal/routes.test.ts
new file mode 100644
index 000000000..0fb91bf99
--- /dev/null
+++ b/packages/cloud/tests/integration/server/internal/routes.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, test } from 'bun:test'
+
+import { unusedAuthAdapter } from '#cloud-tests/helpers/auth'
+import { createCloudTestDatabase } from '#cloud-tests/helpers/database'
+import { createMemoryObjectStore } from '#cloud-tests/helpers/objects'
+import { responseJSON } from '#cloud-tests/helpers/response'
+import {
+ CLOUD_FEATURE_KEYS,
+ createCloudApp,
+ DatabaseEntitlementSource,
+ parseCloudServerConfig
+} from '#cloud/server'
+import * as v from 'valibot'
+
+const SERVICE_TOKEN = 'billing-service-token-with-at-least-32-characters'
+
+const config = parseCloudServerConfig({
+ deployment: 'self-hosted',
+ publicURL: 'http://localhost:8787',
+ databaseURL: 'postgresql://test:test@localhost/test',
+ authSecret: 'integration-test-secret-at-least-32-characters',
+ s3Endpoint: 'http://localhost:9000',
+ s3Region: 'us-east-1',
+ s3Bucket: 'openpencil',
+ s3AccessKeyId: 'openpencil',
+ s3SecretAccessKey: 'openpencil-secret',
+ internalServiceToken: SERVICE_TOKEN
+})
+
+async function testApp() {
+ const runtime = await createCloudTestDatabase()
+ const workspaceId = crypto.randomUUID()
+ await runtime.database
+ .insertInto('workspace')
+ .values({ id: workspaceId, name: 'W', slug: `w-${workspaceId}`, createdBy: 'owner' })
+ .execute()
+ const app = createCloudApp({
+ config,
+ database: runtime.database,
+ auth: unusedAuthAdapter(config),
+ objects: createMemoryObjectStore().store,
+ resolveSession: async () => null
+ })
+ const put = (id: string, body: unknown, token = SERVICE_TOKEN) =>
+ app.request(`/api/internal/workspaces/${id}/entitlements`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
+ body: JSON.stringify(body)
+ })
+ const enabled = () =>
+ new DatabaseEntitlementSource(runtime.database).boolean(
+ { type: 'workspace', id: workspaceId },
+ CLOUD_FEATURE_KEYS.cloudAI
+ )
+ return { runtime, workspaceId, put, enabled }
+}
+
+const appliedSchema = v.object({ applied: v.boolean() })
+
+describe('internal entitlements API', () => {
+ test('keeps the newest decision when billing events arrive out of order', async () => {
+ const context = await testApp()
+ try {
+ const plan = (enabled: boolean, externalVersion: number) => ({
+ values: { ai: { enabled } },
+ source: 'billing',
+ externalVersion
+ })
+ const newer = await context.put(context.workspaceId, plan(true, 20))
+ expect(await responseJSON(newer, appliedSchema)).toEqual({ applied: true })
+
+ const late = await context.put(context.workspaceId, plan(false, 10))
+ expect(await responseJSON(late, appliedSchema)).toEqual({ applied: false })
+ const redelivered = await context.put(context.workspaceId, plan(true, 20))
+ expect(await responseJSON(redelivered, appliedSchema)).toEqual({ applied: false })
+ expect(await context.enabled()).toBe(true)
+
+ const canceled = await context.put(context.workspaceId, plan(false, 30))
+ expect(await responseJSON(canceled, appliedSchema)).toEqual({ applied: true })
+ expect(await context.enabled()).toBe(false)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('refuses callers without the service token', async () => {
+ const context = await testApp()
+ try {
+ const body = { values: { ai: { enabled: true } }, source: 'billing', externalVersion: 1 }
+ expect((await context.put(context.workspaceId, body, 'x'.repeat(48))).status).toBe(401)
+ expect(await context.enabled()).toBeNull()
+ } finally {
+ await context.runtime.close()
+ }
+ })
+
+ test('answers not found for unknown workspaces and invalid bodies with 400', async () => {
+ const context = await testApp()
+ try {
+ const body = { values: {}, source: 'billing', externalVersion: 1 }
+ expect((await context.put(crypto.randomUUID(), body)).status).toBe(404)
+ expect((await context.put('not-a-uuid', body)).status).toBe(404)
+ expect(
+ (await context.put(context.workspaceId, { ...body, externalVersion: -1 })).status
+ ).toBe(400)
+ } finally {
+ await context.runtime.close()
+ }
+ })
+})
diff --git a/packages/cloud/tests/runtime/node/entitlements/refusal.test.ts b/packages/cloud/tests/runtime/node/entitlements/refusal.test.ts
index 815de5f7e..ea7d2a459 100644
--- a/packages/cloud/tests/runtime/node/entitlements/refusal.test.ts
+++ b/packages/cloud/tests/runtime/node/entitlements/refusal.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, test } from 'bun:test'
import { entitlementWriteRefusal } from '#cloud/runtime/node/entitlements/refusal'
const staticConfig = {
- staticEntitlements: { documents: {}, sharing: {}, storage: {}, collaboration: {} }
+ staticEntitlements: { documents: {}, sharing: {}, storage: {}, collaboration: {}, ai: {} }
}
describe('entitlements command', () => {
diff --git a/packages/cloud/tests/server/ai/keys.test.ts b/packages/cloud/tests/server/ai/keys.test.ts
new file mode 100644
index 000000000..ba9a4e6f1
--- /dev/null
+++ b/packages/cloud/tests/server/ai/keys.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, test } from 'bun:test'
+
+import { CloudConfigError, loadAISigningKey } from '#cloud/server'
+import { exportPKCS8, generateKeyPair } from 'jose'
+
+async function pkcs8(algorithm: 'ES256' | 'ES384') {
+ const { privateKey } = await generateKeyPair(algorithm, { extractable: true })
+ return exportPKCS8(privateKey)
+}
+
+describe('AI signing key', () => {
+ test('a P-256 key loads with a thumbprint kid', async () => {
+ const key = await loadAISigningKey({ aiSigningKey: await pkcs8('ES256') })
+ expect(key?.publicJWK).toMatchObject({ kty: 'EC', crv: 'P-256', alg: 'ES256', use: 'sig' })
+ expect(key?.publicJWK.kid).toBeString()
+ expect(key?.publicJWK).not.toHaveProperty('d')
+ })
+
+ test('a deployment without a key loads none', async () => {
+ expect(await loadAISigningKey({})).toBeUndefined()
+ })
+
+ test('text that is not a P-256 key stops startup', async () => {
+ for (const aiSigningKey of ['signing-key-pem', await pkcs8('ES384')]) {
+ const loading = loadAISigningKey({ aiSigningKey })
+ expect(loading).rejects.toBeInstanceOf(CloudConfigError)
+ await expect(loading).rejects.toThrow('PKCS #8 P-256')
+ }
+ })
+})
diff --git a/packages/cloud/tests/server/config/deployment.test.ts b/packages/cloud/tests/server/config/deployment.test.ts
index 9d6f6a42b..80118741e 100644
--- a/packages/cloud/tests/server/config/deployment.test.ts
+++ b/packages/cloud/tests/server/config/deployment.test.ts
@@ -183,6 +183,46 @@ describe('Cloud TOML deployment configuration', () => {
).toThrow()
})
+ test('advertises an AI service and billing portal only when configured', () => {
+ const plain = cloudDiscoveryFromConfig(parseCloudDeploymentTOML(minimalSource, environment))
+ expect(plain.ai).toBeUndefined()
+ expect(plain.billing).toBeUndefined()
+
+ const source = `${minimalSource}
+[ai]
+endpoint = "https://ai.example.com"
+token_lifetime_minutes = 5
+
+[billing]
+portal_url = "https://billing.example.com"
+
+[internal_api]
+`
+ const withSecrets = {
+ ...environment,
+ OPENPENCIL_CLOUD_AI_SIGNING_KEY: 'signing-key-pem',
+ OPENPENCIL_CLOUD_SERVICE_TOKEN: 'service-token-with-at-least-32-characters'
+ }
+ const config = parseCloudDeploymentTOML(source, withSecrets)
+ expect(config).toMatchObject({
+ aiEndpoint: 'https://ai.example.com',
+ aiSigningKey: 'signing-key-pem',
+ aiTokenLifetimeSeconds: 300,
+ billingPortalURL: 'https://billing.example.com',
+ internalServiceToken: 'service-token-with-at-least-32-characters'
+ })
+ const discovery = cloudDiscoveryFromConfig(config)
+ expect(discovery.ai).toEqual({ endpoint: 'https://ai.example.com', contractVersion: '1' })
+ expect(discovery.billing).toEqual({ portalURL: 'https://billing.example.com' })
+
+ expect(() => parseCloudDeploymentTOML(source, environment)).toThrow(
+ 'OPENPENCIL_CLOUD_AI_SIGNING_KEY'
+ )
+ expect(() =>
+ parseCloudDeploymentTOML(`${source}\n[entitlements]\nsource = "static"\n`, withSecrets)
+ ).toThrow('static entitlements')
+ })
+
test('reads a relay URL override and requires a WebSocket scheme', () => {
const relay = (url: string) =>
parseCloudDeploymentTOML(
diff --git a/packages/cloud/tests/server/config/schema.test.ts b/packages/cloud/tests/server/config/schema.test.ts
index 8c967003a..df69aa567 100644
--- a/packages/cloud/tests/server/config/schema.test.ts
+++ b/packages/cloud/tests/server/config/schema.test.ts
@@ -123,6 +123,22 @@ describe('Cloud server configuration', () => {
)
})
+ test('requires HTTPS for the official AI service endpoint, whatever the scheme case', () => {
+ const official = {
+ ...baseConfig,
+ deployment: 'official',
+ aiSigningKey: 'signing-key-pem'
+ }
+ for (const aiEndpoint of ['http://ai.example.com', 'HTTP://ai.example.com']) {
+ expect(() => parseCloudServerConfig({ ...official, aiEndpoint })).toThrow(
+ 'Official AI service endpoint must use HTTPS'
+ )
+ }
+ expect(
+ parseCloudServerConfig({ ...official, aiEndpoint: 'HTTPS://ai.example.com' }).aiEndpoint
+ ).toBe('HTTPS://ai.example.com')
+ })
+
test('rejects short auth secrets', () => {
expect(() => parseCloudServerConfig({ ...baseConfig, authSecret: 'short' })).toThrow()
})
diff --git a/packages/cloud/tests/server/policy/static.test.ts b/packages/cloud/tests/server/policy/static.test.ts
index 419982828..f2997dd42 100644
--- a/packages/cloud/tests/server/policy/static.test.ts
+++ b/packages/cloud/tests/server/policy/static.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { staticEntitlementValues } from '#cloud/server'
+import { parseStaticEntitlementsTOML, staticEntitlementValues } from '#cloud/server'
describe('structured static entitlements', () => {
test('maps product-domain configuration to internal feature keys', () => {
@@ -22,4 +22,13 @@ describe('structured static entitlements', () => {
'cloud.collaboration.maximum-participants': 5
})
})
+
+ test('maps AI service entitlements, including a zero allowance', () => {
+ expect(
+ staticEntitlementValues(
+ parseStaticEntitlementsTOML({ ai: { enabled: true, monthly_credit_allowance: 0 } })
+ )
+ ).toEqual({ 'cloud.ai.enabled': true, 'cloud.ai.monthly-credit-allowance': 0 })
+ expect(() => parseStaticEntitlementsTOML({ ai: { monthly_credit_allowance: -1 } })).toThrow()
+ })
})
diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.md
index 61ac0815d..a8191978f 100644
--- a/packages/docs/development/cloud.md
+++ b/packages/docs/development/cloud.md
@@ -211,6 +211,24 @@ Storage quota uses reservations: the upload locks the workspace's quota row, cou
plus active reservations, reserves the requested bytes, and commits the verified size when the
upload finishes. Cleanup releases reservations from abandoned uploads.
+## AI service and billing
+
+Cloud does not proxy models or keep credit balances. An `[ai]` table advertises a separate AI
+service in discovery, and `POST /api/ai/token` signs a short-lived ES256 token for a workspace
+member when the workspace has the `ai.enabled` entitlement. The token names the user, the
+workspace, and its `ai.monthly_credit_allowance`; the service verifies it against the keys at
+`/.well-known/jwks.json`, so it never reads Cloud's database. The contract editors and services
+share, including the service's catalog, wallet, and error codes, is `src/contract/ai.ts`; it has its
+own version so a service can change without a Cloud release. A `[billing]` table only advertises
+where people manage their plan.
+
+Services that decide entitlements, such as billing, write them through the internal API rather than
+the database: `setWorkspaceEntitlements` in `src/server/internal`, which runtimes expose over HTTP
+with a bearer token (`[internal_api]`) or a private transport of their own. Every write carries an
+increasing `externalVersion`, and a write older than the stored one is refused, because billing
+events arrive out of order. Cloud keeps answering from the last entitlements it received while the
+writer is down.
+
## Rate limiting
OpenPencil routes use `hono-rate-limiter` with one PostgreSQL store that atomically increments
@@ -334,3 +352,10 @@ and named versions, and saves between them are compacted after a day. Checkpoint
save lands rather than on a timer, so they need no client clock and cover every writer. History stores
`.fig` revisions rather than Yjs snapshots: snapshots would need garbage collection off in every room
and a version would still have to become a file to open, restore, or duplicate.
+
+**2026-10 · AI services verify Cloud-signed tokens instead of calling Cloud.** A service checks a
+token against a published key on every model request, with no round-trip to Cloud or its database,
+and the same check serves the official service and self-hosted ones. Entitlements are read when a
+token is signed, so a plan change reaches the service within one token lifetime; asking Cloud on
+every request would have made model calls depend on Cloud's database. Entitlements are pushed to
+Cloud rather than read from billing, so documents keep opening when billing is down.